@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.
- package/README.md +34 -10
- package/action.yml +21 -2
- package/dist/hosts/github/run.d.ts +9 -0
- package/dist/hosts/github/run.js +30 -16
- package/dist/hosts/pi/index.js +40 -18
- package/dist/src/admin.d.ts +2 -1
- package/dist/src/admin.js +3 -2
- package/dist/src/canonical-json.d.ts +6 -0
- package/dist/src/canonical-json.js +11 -0
- package/dist/src/cli.d.ts +13 -1
- package/dist/src/cli.js +426 -8
- package/dist/src/diff.d.ts +5 -0
- package/dist/src/diff.js +2 -1
- package/dist/src/dsse.js +2 -2
- package/dist/src/experimental/sigstore.d.ts +6 -0
- package/dist/src/experimental/sigstore.js +13 -5
- package/dist/src/gate/adapters/claude-code-settings.js +1 -1
- package/dist/src/gate/adapters/claude-code.js +1 -0
- package/dist/src/gate/adapters/codex-names.d.ts +1 -0
- package/dist/src/gate/adapters/codex-names.js +56 -0
- package/dist/src/gate/adapters/codex-requirements.d.ts +11 -0
- package/dist/src/gate/adapters/codex-requirements.js +56 -29
- package/dist/src/gate/adapters/codex.d.ts +3 -0
- package/dist/src/gate/adapters/codex.js +147 -20
- package/dist/src/gate/admin-client.d.ts +19 -0
- package/dist/src/gate/admin-client.js +62 -0
- package/dist/src/gate/generations.js +2 -0
- package/dist/src/gate/instance.d.ts +57 -0
- package/dist/src/gate/instance.js +97 -0
- package/dist/src/gate/proc.d.ts +6 -0
- package/dist/src/gate/proc.js +14 -3
- package/dist/src/gate/service.d.ts +13 -0
- package/dist/src/gate/service.js +344 -37
- package/dist/src/gate/setup.d.ts +210 -0
- package/dist/src/gate/setup.js +1038 -0
- package/dist/src/gate/trust-store.d.ts +14 -0
- package/dist/src/gate/trust-store.js +66 -0
- package/dist/src/index.d.ts +2 -1
- package/dist/src/index.js +3 -1
- package/dist/src/policy.d.ts +7 -0
- package/dist/src/policy.js +19 -2
- package/dist/src/recovery-admin.js +7 -4
- package/dist/src/root-events.d.ts +2 -0
- package/dist/src/root-events.js +61 -4
- package/dist/src/tree-digest.d.ts +6 -0
- package/dist/src/tree-digest.js +8 -0
- package/docs/hosts/adapter-interface.md +1 -1
- package/docs/hosts/claude-code.md +108 -0
- package/docs/hosts/codex.md +181 -0
- package/docs/spec/gui-admin-rack-v1.md +1 -1
- package/docs/spec/root-recovery-v1.md +3 -2
- package/docs/spec/trust-documents-v1.md +1 -1
- package/docs/threat-model.md +13 -1
- package/package.json +3 -1
|
@@ -0,0 +1,1038 @@
|
|
|
1
|
+
// `mago-ski gate init` and `gate doctor` (design docs/design/gate-cli.md: v1 sections 3-6, G2-G7, G9-G10, v3 decisions).
|
|
2
|
+
// planInit computes everything an installation writes without touching the disk; applyInit writes it in a fixed order and
|
|
3
|
+
// puts a moved-aside file back if a write fails; doctor reads and reports. All functions take their environment as
|
|
4
|
+
// parameters (`base`, `rootUid`, `platform`, ...) so tests can run them against a temporary tree and the current user.
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { execFile } from 'node:child_process';
|
|
7
|
+
import { link, lstat, mkdir, open, opendir, readdir, readFile, readlink, realpath, rename, stat, unlink } from 'node:fs/promises';
|
|
8
|
+
import { constants as fsConstants, existsSync } from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
import { isRecord, parseCanonicalJsonBytes, serializeCanonicalJson } from "../canonical-json.js";
|
|
12
|
+
import { readRegularFile, writeFileAtomic } from "../fs-safe.js";
|
|
13
|
+
import { validateKeyId } from "../keys.js";
|
|
14
|
+
import { claudeCodeManagedSettings } from "./adapters/claude-code-settings.js";
|
|
15
|
+
import { codexManagedConfigToml, codexRequirementsToml } from "./adapters/codex-requirements.js";
|
|
16
|
+
import { askAdmin, checkAdminSocket } from "./admin-client.js";
|
|
17
|
+
import { MODES } from "./contract.js";
|
|
18
|
+
import { buildId, HOSTS, instancePaths, isHost, missingInstanceMessage, readInstanceConfig } from "./instance.js";
|
|
19
|
+
import { assertGatePlatform } from "./proc.js";
|
|
20
|
+
import { parseStrictJson } from "./strict-json.js";
|
|
21
|
+
/** What the hook may and the service must do within these limits (the values the live tests ran with). */
|
|
22
|
+
export const HOOK_TIMEOUT_SEC = 5;
|
|
23
|
+
export const SELF_DEADLINE_MS = 3000;
|
|
24
|
+
export const CLIENT_DEADLINE_MS = 1500;
|
|
25
|
+
export const CODEX_ENFORCE_NOTE = 'Codex enforcement depends on organisation controls; read docs/hosts/codex.md before enabling enforce';
|
|
26
|
+
/** Same set as the two generators' SAFE_PATH: these paths go unquoted into a shell command, a TOML string and a unit file. */
|
|
27
|
+
const SAFE_PATH = /^\/[A-Za-z0-9._/@-]+$/u;
|
|
28
|
+
const sha256 = (data) => `sha256:${createHash('sha256').update(data).digest('hex')}`;
|
|
29
|
+
const errnoCode = (e) => e?.code;
|
|
30
|
+
/* ---------------------------------------------------------------------------------------------- trust of files */
|
|
31
|
+
const BYPASS = 'an editable hook file would let a user bypass the gate';
|
|
32
|
+
const NOT_ROOT = (p) => `${p} must be owned by root and not writable by others: ${BYPASS}`;
|
|
33
|
+
/**
|
|
34
|
+
* `target` itself and every parent folder up to and including `stopAt` must be owned by `uid`, a real folder (a parent) and
|
|
35
|
+
* not writable by group or others. Not recursive: use it for folders whose contents are checked elsewhere (the managed
|
|
36
|
+
* folder holds symlinks by design). Throws with the first bad path.
|
|
37
|
+
*/
|
|
38
|
+
export async function checkRootOwnedChain(target, uid, stopAt = '/') {
|
|
39
|
+
const stop = path.resolve(stopAt);
|
|
40
|
+
let p = path.resolve(target);
|
|
41
|
+
for (;;) {
|
|
42
|
+
const info = await lstat(p);
|
|
43
|
+
if (info.isSymbolicLink())
|
|
44
|
+
throw new Error(`${p} is a symlink; ${NOT_ROOT(p)}`);
|
|
45
|
+
if (info.uid !== uid || (info.mode & 0o022) !== 0)
|
|
46
|
+
throw new Error(NOT_ROOT(p));
|
|
47
|
+
if (p === stop || p === path.dirname(p))
|
|
48
|
+
return;
|
|
49
|
+
p = path.dirname(p);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Whole-tree check (G4): every entry under `target` (a folder or a file), and every parent up to `stopAt`, is owned by `uid`
|
|
54
|
+
* and not writable by group or others. A symlink inside the tree is refused. Throws with the first bad path.
|
|
55
|
+
*/
|
|
56
|
+
export async function checkRootOwnedTree(target, uid, stopAt = '/') {
|
|
57
|
+
const walk = async (p) => {
|
|
58
|
+
const info = await lstat(p);
|
|
59
|
+
if (info.isSymbolicLink())
|
|
60
|
+
throw new Error(`${p} is a symlink; ${NOT_ROOT(p)}`);
|
|
61
|
+
if (info.uid !== uid || (info.mode & 0o022) !== 0)
|
|
62
|
+
throw new Error(NOT_ROOT(p));
|
|
63
|
+
if (info.isDirectory())
|
|
64
|
+
for (const name of (await readdir(p)).sort())
|
|
65
|
+
await walk(path.join(p, name));
|
|
66
|
+
};
|
|
67
|
+
const top = path.resolve(target);
|
|
68
|
+
await walk(top);
|
|
69
|
+
if (top !== path.resolve(stopAt) && top !== path.dirname(top))
|
|
70
|
+
await checkRootOwnedChain(path.dirname(top), uid, stopAt);
|
|
71
|
+
}
|
|
72
|
+
const message = (e) => (e instanceof Error ? e.message : String(e));
|
|
73
|
+
/**
|
|
74
|
+
* A host binary: a regular ELF executable (a script would allowlist its interpreter), root-owned along its whole chain.
|
|
75
|
+
* It is opened without following a link; the type and owner are checked on the descriptor, and only then are its first 4 bytes read.
|
|
76
|
+
*/
|
|
77
|
+
export async function checkHostExe(exe, uid, stopAt = '/') {
|
|
78
|
+
const info = await lstat(exe);
|
|
79
|
+
if (!info.isFile())
|
|
80
|
+
throw new Error(`${exe} is not a regular file`);
|
|
81
|
+
const handle = await open(exe, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
|
|
82
|
+
try {
|
|
83
|
+
const fd = await handle.stat();
|
|
84
|
+
if (!fd.isFile())
|
|
85
|
+
throw new Error(`${exe} is not a regular file`);
|
|
86
|
+
if (fd.uid !== uid || (fd.mode & 0o022) !== 0)
|
|
87
|
+
throw new Error(NOT_ROOT(exe));
|
|
88
|
+
const head = Buffer.alloc(4);
|
|
89
|
+
const { bytesRead } = await handle.read(head, 0, 4, 0);
|
|
90
|
+
if (bytesRead !== 4 || !head.equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])))
|
|
91
|
+
throw new Error(`${exe} is not an ELF executable (a script would allowlist its interpreter)`);
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
await handle.close();
|
|
95
|
+
}
|
|
96
|
+
await checkRootOwnedChain(exe, uid, stopAt);
|
|
97
|
+
}
|
|
98
|
+
function findInstallRoot() {
|
|
99
|
+
let dir = path.dirname(fileURLToPath(import.meta.url));
|
|
100
|
+
while (!existsSync(path.join(dir, 'package.json'))) {
|
|
101
|
+
const up = path.dirname(dir);
|
|
102
|
+
if (up === dir)
|
|
103
|
+
throw new Error('cannot find the mago-ski package root');
|
|
104
|
+
dir = up;
|
|
105
|
+
}
|
|
106
|
+
return dir;
|
|
107
|
+
}
|
|
108
|
+
async function realOr(p) {
|
|
109
|
+
return await realpath(p).catch(() => p);
|
|
110
|
+
}
|
|
111
|
+
export async function resolveToolchain(host, seams) {
|
|
112
|
+
const installRoot = await realOr(seams.installRoot ?? findInstallRoot());
|
|
113
|
+
const dist = path.join(installRoot, 'dist', 'src');
|
|
114
|
+
return {
|
|
115
|
+
installRoot,
|
|
116
|
+
hookEntry: path.join(dist, 'gate', 'adapters', `${host}-hook.js`),
|
|
117
|
+
cliPath: await realOr(path.join(dist, 'cli.js')),
|
|
118
|
+
nodePath: await realOr(seams.nodePath ?? process.execPath),
|
|
119
|
+
envPath: seams.envPath ?? '/usr/bin/env',
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/** Every check of the install itself (G4, G12). Returns the failures as messages. */
|
|
123
|
+
async function toolchainProblems(host, tc, seams) {
|
|
124
|
+
const uid = seams.rootUid ?? 0;
|
|
125
|
+
const stop = seams.base ?? '/';
|
|
126
|
+
const out = [];
|
|
127
|
+
const run = async (fn, what) => {
|
|
128
|
+
try {
|
|
129
|
+
await fn();
|
|
130
|
+
}
|
|
131
|
+
catch (e) {
|
|
132
|
+
out.push(errnoCode(e) === 'ENOENT' ? `${what} not found (${message(e)}); run from a built, installed package` : message(e));
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
await run(() => checkRootOwnedTree(path.join(tc.installRoot, 'dist'), uid, stop), `${path.join(tc.installRoot, 'dist')}`);
|
|
136
|
+
if (!existsSync(tc.hookEntry))
|
|
137
|
+
out.push(`${tc.hookEntry} not found for host ${host}`);
|
|
138
|
+
if (seams.checkExec !== false) {
|
|
139
|
+
await run(() => checkRootOwnedTree(tc.nodePath, uid, stop), tc.nodePath);
|
|
140
|
+
await run(() => checkRootOwnedChain(path.join(tc.installRoot, 'package.json'), uid, stop), path.join(tc.installRoot, 'package.json'));
|
|
141
|
+
await run(() => checkRootOwnedChain(tc.envPath, uid, stop), tc.envPath);
|
|
142
|
+
}
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
145
|
+
/* --------------------------------------------------------------------------------------------- host binaries */
|
|
146
|
+
/** The host's default binary: its name on root's own PATH (the invoking user's PATH is never consulted). */
|
|
147
|
+
export function defaultHostExe(host) {
|
|
148
|
+
const name = hostBinaryName(host);
|
|
149
|
+
for (const dir of (process.env['PATH'] ?? '').split(':')) {
|
|
150
|
+
if (dir === '' || !path.isAbsolute(dir))
|
|
151
|
+
continue;
|
|
152
|
+
const candidate = path.join(dir, name);
|
|
153
|
+
if (existsSync(candidate))
|
|
154
|
+
return candidate;
|
|
155
|
+
}
|
|
156
|
+
throw new Error(`${name} was not found on root's PATH; pass --host-exe PATH`);
|
|
157
|
+
}
|
|
158
|
+
const hostBinaryName = (host) => (host === 'claude-code' ? 'claude' : 'codex');
|
|
159
|
+
/* ------------------------------------------------------------------------------------------ Codex homes (C5, D3, E1) */
|
|
160
|
+
function cleanDir(value, flag, problems) {
|
|
161
|
+
const v = value.replace(/(?<=.)\/+$/u, '');
|
|
162
|
+
if (!path.isAbsolute(v) || !SAFE_PATH.test(v) || v === '/') {
|
|
163
|
+
problems.push(`${flag} ${value} must be an absolute folder (letters, digits and . _ / @ - only)`);
|
|
164
|
+
return undefined;
|
|
165
|
+
}
|
|
166
|
+
return v;
|
|
167
|
+
}
|
|
168
|
+
/** `--user-home` (repeatable) or else every passwd home with uid 1000 or above and a login shell. */
|
|
169
|
+
async function chooseHomes(opts, problems) {
|
|
170
|
+
if (opts.userHomes && opts.userHomes.length > 0)
|
|
171
|
+
return [...new Set(opts.userHomes.map((h) => cleanDir(h, '--user-home', problems)).filter((h) => h !== undefined))];
|
|
172
|
+
const out = [];
|
|
173
|
+
// nosemgrep: mago-no-raw-read-of-signed-input -- the system user list, read as root to choose the homes
|
|
174
|
+
const text = await readFile(path.join(opts.base ?? '/', 'etc', 'passwd'), 'utf8').catch(() => '');
|
|
175
|
+
for (const line of text.split('\n')) {
|
|
176
|
+
const f = line.split(':');
|
|
177
|
+
const uid = Number(f[2]);
|
|
178
|
+
if (f.length < 7 || !Number.isInteger(uid) || uid < 1000 || uid === 65534)
|
|
179
|
+
continue;
|
|
180
|
+
if (/(^|\/)(nologin|false|sync|halt|shutdown)$/u.test(f[6]) || f[6] === '')
|
|
181
|
+
continue;
|
|
182
|
+
const home = cleanDir(f[5], `the home of ${f[0]}`, problems);
|
|
183
|
+
if (home && !out.includes(home))
|
|
184
|
+
out.push(home);
|
|
185
|
+
}
|
|
186
|
+
return out;
|
|
187
|
+
}
|
|
188
|
+
// `via` is the same folder named through an open handle of this process (`/proc/<pid>/fd/N`): the tool then works on the
|
|
189
|
+
// folder that was opened and checked, whatever the path points to by now. `target` is the path, for messages.
|
|
190
|
+
const defaultChattr = (target, via = target) => new Promise((resolve, reject) => {
|
|
191
|
+
execFile('chattr', ['+i', via], { timeout: 10_000 }, (e, _o, stderr) => (e ? reject(new Error(`chattr +i ${target} failed: ${String(stderr).trim() || e.message}`)) : resolve()));
|
|
192
|
+
});
|
|
193
|
+
const defaultIsImmutable = (target, via = target) => new Promise((resolve) => {
|
|
194
|
+
execFile('lsattr', ['-d', via], { timeout: 10_000 }, (e, out) => resolve(!e && /^\S*i\S*\s/u.test(String(out))));
|
|
195
|
+
});
|
|
196
|
+
const REAL_DIR = fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW;
|
|
197
|
+
/** A folder named through an open handle, also for a child process (`/proc/self` would be the child's own). */
|
|
198
|
+
const viaHandle = (handle, name) => `/proc/${process.pid}/fd/${handle.fd}${name === undefined ? '' : `/${name}`}`;
|
|
199
|
+
/**
|
|
200
|
+
* Opens `dir` without following a link in its last part and requires the kernel's name for the open folder to be exactly
|
|
201
|
+
* `dir`, so no part of the path is a link. What is done through the handle afterwards cannot be redirected by its owner.
|
|
202
|
+
*/
|
|
203
|
+
async function pinFolder(dir, refusal) {
|
|
204
|
+
const handle = await open(dir, REAL_DIR).catch((e) => { throw new Error(`${dir} cannot be opened as a real folder (${errnoCode(e) ?? message(e)}); ${refusal}`); });
|
|
205
|
+
const real = await readlink(viaHandle(handle)).catch(() => undefined);
|
|
206
|
+
if (real !== dir) {
|
|
207
|
+
await handle.close();
|
|
208
|
+
throw new Error(`${dir} is not a real path (it resolves to ${real ?? 'an unknown folder'}); ${refusal}`);
|
|
209
|
+
}
|
|
210
|
+
return handle;
|
|
211
|
+
}
|
|
212
|
+
/** Opens the folder `name` inside an open folder, creating it when missing; a link or a file there is refused. */
|
|
213
|
+
async function pinChild(parent, name, mode, label) {
|
|
214
|
+
let created = true;
|
|
215
|
+
await mkdir(viaHandle(parent, name), { mode }).catch((e) => { if (errnoCode(e) !== 'EEXIST')
|
|
216
|
+
throw e; created = false; });
|
|
217
|
+
const handle = await open(viaHandle(parent, name), REAL_DIR).catch((e) => { throw new Error(`${label} must be a real folder to be locked (${errnoCode(e) ?? message(e)})`); });
|
|
218
|
+
return { handle, created };
|
|
219
|
+
}
|
|
220
|
+
/** `.system` moves (F5, F7.6) and, with `--lock-user-skill-folders`, the lock of each listed home (E1). Refusals go to `problems`. */
|
|
221
|
+
async function planHomeActions(homes, opts, problems) {
|
|
222
|
+
const out = [];
|
|
223
|
+
const stampNow = stamp((opts.now ?? (() => new Date()))());
|
|
224
|
+
const isDir = async (d) => (await lstat(d).catch(() => undefined))?.isDirectory() === true;
|
|
225
|
+
for (const [root, backupParent] of [...homes.userHomes.map((h) => [`${h}/.codex`, `${h}/.codex`]), ...homes.codexHomes.map((h) => [h, h])])
|
|
226
|
+
if (await isDir(`${root}/skills/.system`)) {
|
|
227
|
+
// The home's owner controls these folders: a link in the path (`~/.codex/skills` -> another account's Skill folder) would
|
|
228
|
+
// make root move a folder that is not this home's. The path must be the real one; the move checks it again (moveSystemFolder).
|
|
229
|
+
const skills = `${root}/skills`;
|
|
230
|
+
const real = await realpath(skills).catch(() => undefined);
|
|
231
|
+
if (real !== skills) {
|
|
232
|
+
problems.push(`${skills} is not a real path (it resolves to ${real ?? 'nothing'}); gate init does not move .system through a link. Remove the link, or list the real home`);
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
out.push({ kind: 'move-system', from: `${skills}/.system`, to: `${backupParent}/mago-ski-backup/system-${stampNow}` });
|
|
236
|
+
}
|
|
237
|
+
if (opts.lockUserSkillFolders) {
|
|
238
|
+
if (homes.userHomes.length === 0)
|
|
239
|
+
problems.push('--lock-user-skill-folders needs at least one home (--user-home DIR)');
|
|
240
|
+
for (const home of homes.userHomes) {
|
|
241
|
+
const info = await lstat(home).catch(() => undefined);
|
|
242
|
+
if (!info?.isDirectory()) {
|
|
243
|
+
problems.push(`${home} is not a folder; cannot lock its Skill folders`);
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
// Root works inside a folder its owner controls: the path must be the real one (the lock checks it again, on open handles).
|
|
247
|
+
const real = await realpath(home).catch(() => undefined);
|
|
248
|
+
if (real !== home) {
|
|
249
|
+
problems.push(`${home} is not a real path (it resolves to ${real ?? 'nothing'}); list the real home to lock its Skill folders`);
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
for (const dir of [`${home}/.agents/skills`, `${home}/.codex/skills`]) {
|
|
253
|
+
const entries = await readdir(dir).catch(() => []);
|
|
254
|
+
const left = entries.filter((e) => !(dir.endsWith('/.codex/skills') && e === '.system'));
|
|
255
|
+
if (left.length > 0)
|
|
256
|
+
problems.push(`${dir} already holds ${left.slice(0, 3).join(', ')}${left.length > 3 ? ', ...' : ''}; move or remove it before locking (a locked folder is created empty)`);
|
|
257
|
+
}
|
|
258
|
+
out.push({ kind: 'lock', home, owner: { uid: info.uid, gid: info.gid } });
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
return out;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Moves `<root>/skills/.system` to `<root>/mago-ski-backup/<leaf>` as root without following a link the home's owner can make.
|
|
265
|
+
* Both parent folders are opened with O_NOFOLLOW and must be exactly the planned paths (the kernel's name for the open folder
|
|
266
|
+
* equals the path, so no part of it is a link); the rename then goes through the open handles (`/proc/self/fd/N/...`), so a
|
|
267
|
+
* folder swapped for a link after the check changes nothing. `.system` itself must be a real folder inside the open handle.
|
|
268
|
+
*/
|
|
269
|
+
async function moveSystemFolder(from, to) {
|
|
270
|
+
const skills = await pinFolder(path.dirname(from), '.system was not moved');
|
|
271
|
+
try {
|
|
272
|
+
const backupDir = path.dirname(to);
|
|
273
|
+
await mkdir(backupDir, { mode: 0o755 }).catch((e) => { if (errnoCode(e) !== 'EEXIST')
|
|
274
|
+
throw e; });
|
|
275
|
+
const backup = await pinFolder(backupDir, '.system was not moved');
|
|
276
|
+
try {
|
|
277
|
+
const source = viaHandle(skills, path.basename(from));
|
|
278
|
+
if (!(await lstat(source)).isDirectory())
|
|
279
|
+
throw new Error(`${from} is no longer a real folder; .system was not moved`);
|
|
280
|
+
await rename(source, viaHandle(backup, path.basename(to))); // rename never follows a link in the last part
|
|
281
|
+
}
|
|
282
|
+
finally {
|
|
283
|
+
await backup.close();
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
finally {
|
|
287
|
+
await skills.close();
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Locks one home's Skill folders (E1): `~/.agents`, `~/.agents/skills` and `~/.codex/skills` become root-owned, 0755 and
|
|
292
|
+
* immutable. Root works here inside a folder its owner controls, so nothing is done by path: the home and each folder are
|
|
293
|
+
* opened without following links, and ownership, mode and the immutable attribute are set on the open handles. A folder
|
|
294
|
+
* swapped for a link at any moment is either refused or changes nothing. `~/.codex` stays the user's own folder (Codex
|
|
295
|
+
* writes there), which is also the limit of the lock: its owner can still rename `~/.codex` and make a new one, and
|
|
296
|
+
* `gate doctor` then reports the Skill folder as not locked.
|
|
297
|
+
*/
|
|
298
|
+
async function lockHome(a, rootUid, gid, chattr, isImmutable) {
|
|
299
|
+
const handles = [];
|
|
300
|
+
const child = async (parent, name, mode, label) => { const c = await pinChild(parent, name, mode, label); handles.push(c.handle); return c; };
|
|
301
|
+
try {
|
|
302
|
+
const home = await pinFolder(a.home, 'its Skill folders were not locked');
|
|
303
|
+
handles.push(home);
|
|
304
|
+
const codex = await child(home, '.codex', 0o700, `${a.home}/.codex`);
|
|
305
|
+
if (codex.created && a.owner)
|
|
306
|
+
await codex.handle.chown(a.owner.uid, a.owner.gid).catch(() => { }); // Codex writes here: the user's own folder
|
|
307
|
+
const agents = await child(home, '.agents', 0o755, `${a.home}/.agents`);
|
|
308
|
+
const agentsSkills = await child(agents.handle, 'skills', 0o755, `${a.home}/.agents/skills`);
|
|
309
|
+
const codexSkills = await child(codex.handle, 'skills', 0o755, `${a.home}/.codex/skills`);
|
|
310
|
+
const dirs = [
|
|
311
|
+
{ dir: `${a.home}/.agents/skills`, handle: agentsSkills.handle, empty: true },
|
|
312
|
+
{ dir: `${a.home}/.codex/skills`, handle: codexSkills.handle, empty: true },
|
|
313
|
+
{ dir: `${a.home}/.agents`, handle: agents.handle, empty: false }, // children first: the order of the plan
|
|
314
|
+
];
|
|
315
|
+
const locked = [];
|
|
316
|
+
for (const d of dirs) {
|
|
317
|
+
if (await isImmutable(d.dir, viaHandle(d.handle))) {
|
|
318
|
+
locked.push(d.dir);
|
|
319
|
+
continue;
|
|
320
|
+
} // a re-run
|
|
321
|
+
// The plan saw these folders empty; a Skill added since then must not be locked in.
|
|
322
|
+
const left = d.empty ? await readdir(viaHandle(d.handle)) : [];
|
|
323
|
+
if (left.length > 0)
|
|
324
|
+
throw new Error(`${d.dir} now holds ${left.slice(0, 3).join(', ')}; it was empty when the lock was planned. Remove it and run gate init again`);
|
|
325
|
+
await d.handle.chown(rootUid, gid);
|
|
326
|
+
await d.handle.chmod(0o755);
|
|
327
|
+
await chattr(d.dir, viaHandle(d.handle)); // a failure (an unsupported file system) stops the command
|
|
328
|
+
locked.push(d.dir);
|
|
329
|
+
}
|
|
330
|
+
return locked;
|
|
331
|
+
}
|
|
332
|
+
finally {
|
|
333
|
+
for (const h of handles.reverse())
|
|
334
|
+
await h.close().catch(() => { });
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
/** Plan: moves first, then locks. Each move needs the target folder free. */
|
|
338
|
+
async function runHomeActions(actions, opts, rootUid) {
|
|
339
|
+
const moved = [];
|
|
340
|
+
const locked = [];
|
|
341
|
+
for (const a of actions) {
|
|
342
|
+
if (a.kind !== 'move-system')
|
|
343
|
+
continue;
|
|
344
|
+
await moveSystemFolder(a.from, a.to);
|
|
345
|
+
moved.push({ from: a.from, to: a.to });
|
|
346
|
+
}
|
|
347
|
+
const chattr = opts.chattr ?? defaultChattr;
|
|
348
|
+
const isImmutable = opts.isImmutable ?? defaultIsImmutable;
|
|
349
|
+
const gid = rootUid === 0 ? 0 : (process.getgid?.() ?? 0);
|
|
350
|
+
for (const a of actions)
|
|
351
|
+
if (a.kind === 'lock')
|
|
352
|
+
locked.push(...await lockHome(a, rootUid, gid, chattr, isImmutable));
|
|
353
|
+
return { moved, locked };
|
|
354
|
+
}
|
|
355
|
+
export function unitText(tc) {
|
|
356
|
+
return [
|
|
357
|
+
'[Unit]', 'Description=mago-ski gate for %i', 'After=local-fs.target', '',
|
|
358
|
+
'[Service]', 'Type=simple', `ExecStart=${tc.nodePath} ${tc.cliPath} gate run --host %i`, 'Restart=on-failure',
|
|
359
|
+
'RuntimeDirectory=mago-ski/gate/%i', 'RuntimeDirectoryMode=0755', 'LimitNOFILE=4096', 'ProtectSystem=strict', 'NoNewPrivileges=yes', '',
|
|
360
|
+
'[Install]', 'WantedBy=multi-user.target', '',
|
|
361
|
+
].join('\n');
|
|
362
|
+
}
|
|
363
|
+
export function dropinText(cfg, stateRoot) {
|
|
364
|
+
return ['[Service]', `ReadWritePaths=${stateRoot} ${cfg.managed_dir}`, 'ReadOnlyPaths=/etc/mago-ski', ''].join('\n');
|
|
365
|
+
}
|
|
366
|
+
export function hookConfigText(host, cfg, homes = { userHomes: [], codexHomes: [] }) {
|
|
367
|
+
return serializeCanonicalJson({
|
|
368
|
+
v: 1, socket: path.join(cfg.decision_socket_dir, 'decision.sock'), mode: cfg.mode, host_exes: cfg.host_exes,
|
|
369
|
+
client_deadline_ms: CLIENT_DEADLINE_MS, self_deadline_ms: SELF_DEADLINE_MS,
|
|
370
|
+
...(host === 'codex' ? { admin_root: cfg.managed_dir, skill_roots: [], user_homes: homes.userHomes, codex_homes: homes.codexHomes } : {}),
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
/** The fixed user Skill roots the requirements file denies reads of (D3: the roots of every listed home and CODEX_HOME). */
|
|
374
|
+
export function codexDenyRoots(homes) {
|
|
375
|
+
return [
|
|
376
|
+
...homes.userHomes.flatMap((h) => [`${h}/.codex/skills`, `${h}/.codex/skills/.system`, `${h}/.agents/skills`]),
|
|
377
|
+
...homes.codexHomes.flatMap((h) => [`${h}/skills`, `${h}/skills/.system`]),
|
|
378
|
+
];
|
|
379
|
+
}
|
|
380
|
+
/** The host's own configuration file for this instance. */
|
|
381
|
+
export function hostConfigText(host, mode, tc, hookConfigPath, denyRoots = []) {
|
|
382
|
+
const common = { mode, nodePath: tc.nodePath, hookEntry: tc.hookEntry, configPath: hookConfigPath, hookTimeoutSec: HOOK_TIMEOUT_SEC, selfDeadlineMs: SELF_DEADLINE_MS, envPath: tc.envPath };
|
|
383
|
+
if (host === 'claude-code')
|
|
384
|
+
return `${JSON.stringify(claudeCodeManagedSettings(common), null, 2)}\n`;
|
|
385
|
+
return codexRequirementsToml({ ...common, userSkillRoots: denyRoots });
|
|
386
|
+
}
|
|
387
|
+
export function instanceFromOptions(o) {
|
|
388
|
+
const p = instancePaths(o.host, o.base ?? '/');
|
|
389
|
+
return {
|
|
390
|
+
v: 1, host: o.host, mode: o.mode, root_fingerprint: o.rootFingerprint, host_exes: o.hostExes,
|
|
391
|
+
state_dir: p.stateDir, generations_dir: p.generationsDir, managed_dir: p.managedDir,
|
|
392
|
+
decision_socket_dir: p.decisionSocketDir, admin_socket_dir: p.adminSocketDir,
|
|
393
|
+
inbox_dir: o.inbox ?? null, build_id: buildId(),
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
/** `previous` entries stay unless a planned file has the same path (the shared manifest is written by both hosts). */
|
|
397
|
+
function manifestText(files, previous) {
|
|
398
|
+
const entries = new Map(previous ?? []);
|
|
399
|
+
for (const f of files)
|
|
400
|
+
entries.set(f.path, sha256(f.content));
|
|
401
|
+
return serializeCanonicalJson({ v: 1, files: [...entries].map(([p, h]) => ({ path: p, sha256: h })).sort((a, b) => (a.path < b.path ? -1 : 1)) });
|
|
402
|
+
}
|
|
403
|
+
/** A manifest is read only if it is a root-owned regular file that others cannot write. */
|
|
404
|
+
async function readManifest(file, uid) {
|
|
405
|
+
let raw;
|
|
406
|
+
try {
|
|
407
|
+
const info = await lstat(file);
|
|
408
|
+
if (!info.isFile() || info.uid !== uid || (info.mode & 0o022) !== 0)
|
|
409
|
+
return undefined;
|
|
410
|
+
raw = parseCanonicalJsonBytes(await readRegularFile(file, 'manifest', 1024 * 1024), 'manifest');
|
|
411
|
+
}
|
|
412
|
+
catch {
|
|
413
|
+
return undefined;
|
|
414
|
+
}
|
|
415
|
+
if (!isRecord(raw) || raw['v'] !== 1 || !Array.isArray(raw['files']))
|
|
416
|
+
return undefined;
|
|
417
|
+
const out = new Map();
|
|
418
|
+
for (const f of raw['files'])
|
|
419
|
+
if (isRecord(f) && typeof f['path'] === 'string' && typeof f['sha256'] === 'string')
|
|
420
|
+
out.set(f['path'], f['sha256']);
|
|
421
|
+
return out;
|
|
422
|
+
}
|
|
423
|
+
/** Everything `gate init` would write and create. Reads the disk (existing files, manifests, the install's ownership); writes nothing. */
|
|
424
|
+
export async function planInit(opts) {
|
|
425
|
+
assertGatePlatform(opts.platform ?? process.platform);
|
|
426
|
+
const { host } = opts;
|
|
427
|
+
if (!isHost(host))
|
|
428
|
+
throw new Error(`--host must be one of ${HOSTS.join(', ')}`);
|
|
429
|
+
validateKeyId(opts.rootFingerprint, '--root-fingerprint');
|
|
430
|
+
const mode = opts.mode ?? 'shadow';
|
|
431
|
+
if (!MODES.includes(mode))
|
|
432
|
+
throw new Error('--mode must be shadow or enforce');
|
|
433
|
+
if (opts.inbox !== undefined && (!path.isAbsolute(opts.inbox) || !SAFE_PATH.test(opts.inbox)))
|
|
434
|
+
throw new Error('--inbox must be an absolute path');
|
|
435
|
+
const uid = opts.rootUid ?? 0;
|
|
436
|
+
const stop = opts.base ?? '/';
|
|
437
|
+
const p = instancePaths(host, opts.base ?? '/');
|
|
438
|
+
const tc = await resolveToolchain(host, opts);
|
|
439
|
+
const problems = await toolchainProblems(host, tc, opts);
|
|
440
|
+
// Host binaries: resolved to their real path (that is what /proc/<pid>/exe shows), then required to be trusted ELF files.
|
|
441
|
+
const requested = opts.hostExes && opts.hostExes.length > 0 ? opts.hostExes : [undefined];
|
|
442
|
+
const hostExes = [];
|
|
443
|
+
for (const given of requested) {
|
|
444
|
+
let exe;
|
|
445
|
+
try {
|
|
446
|
+
exe = given ?? (opts.resolveHostExe ?? defaultHostExe)(host);
|
|
447
|
+
if (!path.isAbsolute(exe))
|
|
448
|
+
throw new Error(`${exe} must be an absolute path`);
|
|
449
|
+
exe = await realpath(exe);
|
|
450
|
+
// A binary found by itself must look like the host's (a `claude` symlink to python3 is refused); an explicit --host-exe may be named anything.
|
|
451
|
+
if (given === undefined && !path.basename(exe).startsWith(hostBinaryName(host)))
|
|
452
|
+
throw new Error(`${exe} (the real path of the ${hostBinaryName(host)} found on PATH) is not named ${hostBinaryName(host)}*; check it, then pass it with --host-exe`);
|
|
453
|
+
await checkHostExe(exe, uid, stop);
|
|
454
|
+
}
|
|
455
|
+
catch (e) {
|
|
456
|
+
const fallback = given ?? `/usr/bin/${hostBinaryName(host)}`;
|
|
457
|
+
problems.push(`${message(e)}; host binaries must be root-owned (not in a user's home): pass --host-exe PATH`);
|
|
458
|
+
exe = fallback;
|
|
459
|
+
}
|
|
460
|
+
if (!hostExes.includes(exe))
|
|
461
|
+
hostExes.push(exe);
|
|
462
|
+
}
|
|
463
|
+
for (const q of [tc.nodePath, tc.hookEntry, tc.cliPath, tc.envPath, p.hook, p.managedDir, p.stateRoot, ...hostExes])
|
|
464
|
+
if (!SAFE_PATH.test(q))
|
|
465
|
+
throw new Error(`${q} contains characters that are not allowed in a unit or hook command (only letters, digits and . _ / @ - are accepted)`);
|
|
466
|
+
const cfg = instanceFromOptions({ host, mode, rootFingerprint: opts.rootFingerprint, hostExes, inbox: opts.inbox, base: opts.base });
|
|
467
|
+
// A changed root is never silent (design gate-new-root.md N2). An instance config that cannot be read gives no root to
|
|
468
|
+
// compare with, so the run is treated like a first one.
|
|
469
|
+
const installed = await readInstanceConfig(p.instance, uid).catch(() => undefined);
|
|
470
|
+
let rootChange;
|
|
471
|
+
if (installed && installed.root_fingerprint !== cfg.root_fingerprint) {
|
|
472
|
+
if (opts.newRoot)
|
|
473
|
+
rootChange = { from: installed.root_fingerprint, to: cfg.root_fingerprint };
|
|
474
|
+
else
|
|
475
|
+
problems.push(`this gate is set up for root ${installed.root_fingerprint}, not ${cfg.root_fingerprint}; check the fingerprint, or pass --new-root to move the gate to the new root (after a root rotation). Until the new root's documents are sent with gate trust, enforce mode blocks every Skill`);
|
|
476
|
+
}
|
|
477
|
+
else if (opts.newRoot)
|
|
478
|
+
problems.push(installed ? `--new-root was given, but this gate already uses root ${cfg.root_fingerprint}` : `--new-root was given, but no ${host} gate is set up on this machine yet`);
|
|
479
|
+
const homes = { userHomes: [], codexHomes: [] };
|
|
480
|
+
const actions = [];
|
|
481
|
+
if (host === 'codex') {
|
|
482
|
+
homes.userHomes = await chooseHomes(opts, problems);
|
|
483
|
+
homes.codexHomes = (opts.codexHomes ?? []).map((h) => cleanDir(h, '--codex-home', problems)).filter((h) => h !== undefined);
|
|
484
|
+
actions.push(...await planHomeActions(homes, opts, problems));
|
|
485
|
+
}
|
|
486
|
+
else if (opts.userHomes?.length || opts.codexHomes?.length || opts.noDenyRead || opts.lockUserSkillFolders)
|
|
487
|
+
throw new Error('--user-home, --codex-home, --no-deny-read and --lock-user-skill-folders are for --host codex');
|
|
488
|
+
const denyRoots = host === 'codex' && !opts.noDenyRead ? codexDenyRoots(homes) : [];
|
|
489
|
+
const files = [
|
|
490
|
+
{ path: p.instance, content: serializeCanonicalJson(cfg), mode: 0o644, role: 'instance' },
|
|
491
|
+
{ path: p.hook, content: hookConfigText(host, cfg, homes), mode: 0o644, role: 'hook' },
|
|
492
|
+
{ path: p.unit, content: unitText(tc), mode: 0o644, role: 'unit' },
|
|
493
|
+
{ path: p.dropin, content: dropinText(cfg, p.stateRoot), mode: 0o644, role: 'dropin' },
|
|
494
|
+
{ path: p.hostConfig, content: hostConfigText(host, mode, tc, p.hook, denyRoots), mode: 0o644, role: 'host' }, // last of the configs
|
|
495
|
+
...(p.managedConfig ? [{ path: p.managedConfig, content: codexManagedConfigToml(), mode: 0o644, role: 'managed-config' }] : []),
|
|
496
|
+
];
|
|
497
|
+
const hostOwn = files.filter((f) => f.role !== 'unit');
|
|
498
|
+
const shared = files.filter((f) => f.role === 'unit');
|
|
499
|
+
// Ownership by manifest (G5, N1): a file is ours when its hash equals its entry in this host's or the shared manifest.
|
|
500
|
+
const own = await readManifest(p.manifest, uid);
|
|
501
|
+
const sharedOwn = await readManifest(p.sharedManifest, uid);
|
|
502
|
+
const foreign = [];
|
|
503
|
+
for (const f of files) {
|
|
504
|
+
const info = await lstat(f.path).catch((e) => { if (errnoCode(e) === 'ENOENT' || errnoCode(e) === 'ENOTDIR')
|
|
505
|
+
return undefined; throw e; });
|
|
506
|
+
if (!info)
|
|
507
|
+
continue;
|
|
508
|
+
let ours = false;
|
|
509
|
+
if (info.isFile()) {
|
|
510
|
+
// nosemgrep: mago-no-raw-read-of-signed-input -- a system host file gate init would replace, hashed to see whether mago-ski wrote it
|
|
511
|
+
const h = sha256(await readFile(f.path));
|
|
512
|
+
ours = own?.get(f.path) === h || sharedOwn?.get(f.path) === h;
|
|
513
|
+
}
|
|
514
|
+
if (!ours)
|
|
515
|
+
foreign.push(f.path);
|
|
516
|
+
}
|
|
517
|
+
// The manifests themselves: an existing one that is not a root-owned regular manifest is foreign too.
|
|
518
|
+
for (const [m, read] of [[p.manifest, own], [p.sharedManifest, sharedOwn]])
|
|
519
|
+
if (read === undefined && await lstat(m).then(() => true, (e) => { if (errnoCode(e) === 'ENOENT' || errnoCode(e) === 'ENOTDIR')
|
|
520
|
+
return false; throw e; }))
|
|
521
|
+
foreign.push(m);
|
|
522
|
+
files.push({ path: p.manifest, content: manifestText(hostOwn), mode: 0o644, role: 'manifest' }, { path: p.sharedManifest, content: manifestText(shared, sharedOwn), mode: 0o644, role: 'shared-manifest' });
|
|
523
|
+
const dirs = [
|
|
524
|
+
{ path: p.configDir, mode: 0o755 }, { path: p.stateRoot, mode: 0o755 }, { path: p.stateDir, mode: 0o700 },
|
|
525
|
+
{ path: p.generationsDir, mode: 0o755 }, { path: p.managedDir, mode: 0o755 }, { path: p.dropinDir, mode: 0o755 },
|
|
526
|
+
];
|
|
527
|
+
const rerun = own !== undefined;
|
|
528
|
+
const next = [
|
|
529
|
+
rerun ? `systemctl daemon-reload && systemctl restart mago-ski-gate@${host}` : `systemctl daemon-reload && systemctl enable --now mago-ski-gate@${host}`,
|
|
530
|
+
rootChange ? `mago-ski gate trust --host ${host} --trust-root FILE --revocations FILE (the documents signed by the new root)` : `mago-ski gate trust --host ${host} --trust-root FILE --revocations FILE`,
|
|
531
|
+
`mago-ski gate doctor --host ${host}`,
|
|
532
|
+
];
|
|
533
|
+
return { host, mode, homes, denyRoots, actions, hostExes, files, dirs, foreign, problems, rerun, next, ...(rootChange ? { rootChange } : {}) };
|
|
534
|
+
}
|
|
535
|
+
const stamp = (d) => d.toISOString().replace(/[-:]/gu, '').replace(/\.\d+Z$/u, 'Z');
|
|
536
|
+
/** Sets the mode through an open descriptor (no path race), after checking that the descriptor is a folder owned by `uid`. */
|
|
537
|
+
async function fchmodDir(dir, mode, uid) {
|
|
538
|
+
const handle = await open(dir, fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW);
|
|
539
|
+
try {
|
|
540
|
+
const info = await handle.stat();
|
|
541
|
+
if (!info.isDirectory() || info.uid !== uid)
|
|
542
|
+
throw new Error(`${dir} must be a real folder owned by root`);
|
|
543
|
+
await handle.chmod(mode);
|
|
544
|
+
}
|
|
545
|
+
finally {
|
|
546
|
+
await handle.close();
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
async function ensureDir(dir, mode, uid) {
|
|
550
|
+
const missing = [];
|
|
551
|
+
for (let d = dir;; d = path.dirname(d)) {
|
|
552
|
+
const info = await lstat(d).catch((e) => { if (errnoCode(e) === 'ENOENT')
|
|
553
|
+
return undefined; throw e; });
|
|
554
|
+
if (info) {
|
|
555
|
+
if (!info.isDirectory())
|
|
556
|
+
throw new Error(`${d} must be a real directory`);
|
|
557
|
+
break;
|
|
558
|
+
}
|
|
559
|
+
missing.unshift(d);
|
|
560
|
+
if (d === path.dirname(d))
|
|
561
|
+
break;
|
|
562
|
+
}
|
|
563
|
+
for (const m of missing) {
|
|
564
|
+
const want = m === dir ? mode : 0o755; // parents are root-owned 0755, the leaf has its stated mode (umask must not change it)
|
|
565
|
+
await mkdir(m, { mode: want });
|
|
566
|
+
await fchmodDir(m, want, uid);
|
|
567
|
+
}
|
|
568
|
+
if (missing.length === 0)
|
|
569
|
+
await fchmodDir(dir, mode, uid);
|
|
570
|
+
return missing.length > 0;
|
|
571
|
+
}
|
|
572
|
+
/** Every planned folder that exists, or else its nearest existing ancestor, up to `stop`: root-owned, not writable by others. */
|
|
573
|
+
async function checkPlannedFolders(plan, uid, stop) {
|
|
574
|
+
for (const d of plan.dirs) {
|
|
575
|
+
let existing = path.resolve(d.path);
|
|
576
|
+
while (!(await lstat(existing).then(() => true, (e) => { if (errnoCode(e) === 'ENOENT')
|
|
577
|
+
return false; throw e; }))) {
|
|
578
|
+
const up = path.dirname(existing);
|
|
579
|
+
if (up === existing)
|
|
580
|
+
break;
|
|
581
|
+
existing = up;
|
|
582
|
+
}
|
|
583
|
+
await checkRootOwnedChain(existing, uid, stop);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
const sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino;
|
|
587
|
+
/**
|
|
588
|
+
* Writes the plan (G5, v3 decision 3, v4 items 2-3). First it refuses (problems, foreign files without `force`, any planned
|
|
589
|
+
* folder or ancestor not owned by root or writable by others), before any rename or write. Then each foreign file is hard-linked
|
|
590
|
+
* to `<path>.mago-ski-bak-<stamp>` (the original stays in place), the folders are made, and each file is written with an atomic
|
|
591
|
+
* rename that replaces the original in one step: the host never lacks a config file. After a failure, a backup is put back
|
|
592
|
+
* only over a path this run did not write, and the message lists what is new, what was restored and what stays as a backup.
|
|
593
|
+
*/
|
|
594
|
+
export async function applyInit(plan, opts = {}) {
|
|
595
|
+
if (plan.problems.length > 0)
|
|
596
|
+
throw new Error(plan.problems.join('\n'));
|
|
597
|
+
if (plan.foreign.length > 0 && !opts.force)
|
|
598
|
+
throw new Error(plan.foreign.map((f) => `${f} exists and was not written by mago-ski; merge it by hand (mago-ski gate init --print) or pass --force`).join('\n'));
|
|
599
|
+
const uid = opts.rootUid ?? 0;
|
|
600
|
+
await checkPlannedFolders(plan, uid, opts.base ?? '/');
|
|
601
|
+
const result = { written: [], backups: [], dirs: [], movedSystem: [], locked: [] };
|
|
602
|
+
const suffix = `.mago-ski-bak-${stamp((opts.now ?? (() => new Date()))())}`;
|
|
603
|
+
try {
|
|
604
|
+
for (const f of plan.foreign) { // a failed link stops the command before anything is written
|
|
605
|
+
const to = `${f}${suffix}`;
|
|
606
|
+
await link(f, to);
|
|
607
|
+
result.backups.push({ from: f, to });
|
|
608
|
+
}
|
|
609
|
+
for (const d of plan.dirs)
|
|
610
|
+
if (await ensureDir(d.path, d.mode, uid))
|
|
611
|
+
result.dirs.push(d.path);
|
|
612
|
+
for (const f of plan.files) {
|
|
613
|
+
await writeFileAtomic(f.path, Buffer.from(f.content, 'utf8'), f.mode);
|
|
614
|
+
const handle = await open(f.path, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
|
|
615
|
+
try {
|
|
616
|
+
await handle.chmod(f.mode);
|
|
617
|
+
}
|
|
618
|
+
finally {
|
|
619
|
+
await handle.close();
|
|
620
|
+
}
|
|
621
|
+
result.written.push(f.path);
|
|
622
|
+
}
|
|
623
|
+
const home = await runHomeActions(plan.actions, opts, uid); // after every file: a refused plan or a failed write never moves user data
|
|
624
|
+
result.movedSystem = home.moved;
|
|
625
|
+
result.locked = home.locked;
|
|
626
|
+
}
|
|
627
|
+
catch (e) {
|
|
628
|
+
const written = new Set(result.written);
|
|
629
|
+
const restored = [];
|
|
630
|
+
const kept = [];
|
|
631
|
+
for (const b of result.backups) {
|
|
632
|
+
if (written.has(b.from)) {
|
|
633
|
+
kept.push(`${b.from} (original kept as ${b.to})`);
|
|
634
|
+
continue;
|
|
635
|
+
}
|
|
636
|
+
try {
|
|
637
|
+
const [now, bak] = await Promise.all([lstat(b.from).catch(() => undefined), lstat(b.to)]);
|
|
638
|
+
if (now && sameFile(now, bak))
|
|
639
|
+
await unlink(b.to); // untouched: the original is still in place, the extra link goes
|
|
640
|
+
else if (!now)
|
|
641
|
+
await rename(b.to, b.from);
|
|
642
|
+
else {
|
|
643
|
+
kept.push(`${b.from} (original kept as ${b.to})`);
|
|
644
|
+
continue;
|
|
645
|
+
}
|
|
646
|
+
restored.push(b.from);
|
|
647
|
+
}
|
|
648
|
+
catch {
|
|
649
|
+
kept.push(`${b.from} (original kept as ${b.to})`);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
const fresh = result.written.filter((w) => !result.backups.some((b) => b.from === w));
|
|
653
|
+
const lines = [`gate init failed: ${message(e)}.`];
|
|
654
|
+
if (fresh.length > 0)
|
|
655
|
+
lines.push(`New files written (not in the manifest, so the next run treats them as foreign; check them and use --force): ${fresh.join(', ')}.`);
|
|
656
|
+
if (restored.length > 0)
|
|
657
|
+
lines.push(`Original put back, not changed: ${restored.join(', ')}.`);
|
|
658
|
+
if (kept.length > 0)
|
|
659
|
+
lines.push(`Replaced by new content; the original stays as a backup: ${kept.join(', ')}.`);
|
|
660
|
+
throw new Error(lines.join(' '));
|
|
661
|
+
}
|
|
662
|
+
return result;
|
|
663
|
+
}
|
|
664
|
+
/** lstat: a regular file (not a symlink) owned by `uid` and not writable by group or others. */
|
|
665
|
+
async function trustedRegularFile(file, uid) {
|
|
666
|
+
const info = await lstat(file);
|
|
667
|
+
if (info.isSymbolicLink() || !info.isFile())
|
|
668
|
+
throw new Error(`${file} must be a regular file, not a symlink`);
|
|
669
|
+
if (info.uid !== uid || (info.mode & 0o022) !== 0)
|
|
670
|
+
throw new Error(NOT_ROOT(file));
|
|
671
|
+
}
|
|
672
|
+
/** Read-only checks, in the order of the design (v1 section 6, G6, G12). Never throws. */
|
|
673
|
+
export async function doctor(host, opts = {}) {
|
|
674
|
+
const out = [];
|
|
675
|
+
const add = (check, result, detail) => { out.push({ check, result, detail }); };
|
|
676
|
+
const attempt = async (check, ok, fn) => {
|
|
677
|
+
try {
|
|
678
|
+
add(check, 'PASS', (await fn()) || ok);
|
|
679
|
+
return true;
|
|
680
|
+
}
|
|
681
|
+
catch (e) {
|
|
682
|
+
add(check, 'FAIL', message(e));
|
|
683
|
+
return false;
|
|
684
|
+
}
|
|
685
|
+
};
|
|
686
|
+
const uid = opts.rootUid ?? 0;
|
|
687
|
+
const stop = opts.base ?? '/';
|
|
688
|
+
try {
|
|
689
|
+
assertGatePlatform(opts.platform ?? process.platform);
|
|
690
|
+
add('platform', 'PASS', 'Linux');
|
|
691
|
+
}
|
|
692
|
+
catch (e) {
|
|
693
|
+
add('platform', 'FAIL', message(e));
|
|
694
|
+
return out;
|
|
695
|
+
}
|
|
696
|
+
const p = instancePaths(host, opts.base ?? '/');
|
|
697
|
+
let cfg;
|
|
698
|
+
await attempt('instance config', p.instance, async () => {
|
|
699
|
+
try {
|
|
700
|
+
cfg = await readInstanceConfig(p.instance, uid);
|
|
701
|
+
}
|
|
702
|
+
catch (e) {
|
|
703
|
+
throw errnoCode(e) === 'ENOENT' ? new Error(missingInstanceMessage(host)) : e;
|
|
704
|
+
} // lstat: a root-owned regular file, not a symlink
|
|
705
|
+
if (cfg.host !== host)
|
|
706
|
+
throw new Error(`${p.instance} is for host ${cfg.host}`);
|
|
707
|
+
return `${p.instance} (mode ${cfg.mode})`;
|
|
708
|
+
});
|
|
709
|
+
if (!cfg) {
|
|
710
|
+
for (const c of ['host binaries', 'hook entry', 'node', 'managed folder', 'host config', 'unit', 'drop-in', 'service', 'trust', 'mode'])
|
|
711
|
+
add(c, 'SKIP', 'no usable instance config');
|
|
712
|
+
return out;
|
|
713
|
+
}
|
|
714
|
+
const c = cfg;
|
|
715
|
+
for (const exe of c.host_exes)
|
|
716
|
+
await attempt('host binaries', exe, async () => { await checkHostExe(exe, uid, stop); return exe; });
|
|
717
|
+
const tc = await resolveToolchain(host, opts);
|
|
718
|
+
await attempt('hook entry', tc.hookEntry, async () => {
|
|
719
|
+
if (!existsSync(tc.hookEntry))
|
|
720
|
+
throw new Error(`${tc.hookEntry} not found`);
|
|
721
|
+
await checkRootOwnedTree(path.join(tc.installRoot, 'dist'), uid, stop);
|
|
722
|
+
return `${path.join(tc.installRoot, 'dist')} is root-owned`;
|
|
723
|
+
});
|
|
724
|
+
if (opts.checkExec === false)
|
|
725
|
+
add('node', 'SKIP', 'not checked in this environment');
|
|
726
|
+
else
|
|
727
|
+
await attempt('node', tc.nodePath, async () => {
|
|
728
|
+
await checkRootOwnedTree(tc.nodePath, uid, stop);
|
|
729
|
+
await checkRootOwnedChain(path.join(tc.installRoot, 'package.json'), uid, stop);
|
|
730
|
+
await checkRootOwnedChain(tc.envPath, uid, stop);
|
|
731
|
+
return `${tc.nodePath}, package.json and ${tc.envPath} are root-owned`;
|
|
732
|
+
});
|
|
733
|
+
for (const [label, dir, must] of [['config folder', p.configDir, true], ['managed folder', c.managed_dir, true], ['state folder', c.state_dir, true],
|
|
734
|
+
['generations folder', c.generations_dir, true], ['decision socket folder', c.decision_socket_dir, false], ['admin socket folder', c.admin_socket_dir, false]]) {
|
|
735
|
+
if (!must && !existsSync(dir)) {
|
|
736
|
+
add(label, 'SKIP', `${dir} does not exist yet (the service creates it)`);
|
|
737
|
+
continue;
|
|
738
|
+
}
|
|
739
|
+
await attempt(label, dir, async () => { await checkRootOwnedChain(dir, uid, stop); return `${dir} is root-owned`; });
|
|
740
|
+
}
|
|
741
|
+
// Host config and hook config: exact content of what `gate init` would write now.
|
|
742
|
+
// Codex: the listed homes live in the hook config (the instance config does not know them); deny_read is present or not as written.
|
|
743
|
+
const homes = (host === 'codex' ? await readHookHomes(p.hook) : undefined) ?? { userHomes: [], codexHomes: [] };
|
|
744
|
+
// nosemgrep: mago-no-raw-read-of-signed-input -- doctor: the root-owned host config, only searched for one line
|
|
745
|
+
const denyRoots = host === 'codex' && /^deny_read = /mu.test(await readFile(p.hostConfig, 'utf8').catch(() => '')) ? codexDenyRoots(homes) : [];
|
|
746
|
+
const hookExpected = hookConfigText(host, c, homes);
|
|
747
|
+
let hostFileMode;
|
|
748
|
+
try {
|
|
749
|
+
const expected = hostConfigText(host, c.mode, tc, p.hook, denyRoots);
|
|
750
|
+
const info = await lstat(p.hostConfig);
|
|
751
|
+
if (!info.isFile() || info.uid !== uid || (info.mode & 0o022) !== 0)
|
|
752
|
+
throw new Error(`${p.hostConfig} must be a regular file owned by root and not writable by others`);
|
|
753
|
+
// nosemgrep: mago-no-raw-read-of-signed-input -- doctor: checked just above as a root-owned regular file not writable by others
|
|
754
|
+
const have = sha256(await readFile(p.hostConfig));
|
|
755
|
+
if (have === sha256(expected)) {
|
|
756
|
+
hostFileMode = c.mode;
|
|
757
|
+
add('host config', 'PASS', `${p.hostConfig} matches what gate init writes`);
|
|
758
|
+
}
|
|
759
|
+
else {
|
|
760
|
+
const other = c.mode === 'shadow' ? 'enforce' : 'shadow';
|
|
761
|
+
let otherMatches = false;
|
|
762
|
+
try {
|
|
763
|
+
otherMatches = have === sha256(hostConfigText(host, other, tc, p.hook, denyRoots));
|
|
764
|
+
}
|
|
765
|
+
catch { /* not generated */ }
|
|
766
|
+
if (otherMatches)
|
|
767
|
+
hostFileMode = other;
|
|
768
|
+
throw new Error(otherMatches ? `${p.hostConfig} is the ${other} configuration but the instance is ${c.mode}; run gate init again` : `${p.hostConfig} differs from what gate init would write now; run gate init again (it keeps a backup with --force)`);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
catch (e) {
|
|
772
|
+
add('host config', 'FAIL', message(e));
|
|
773
|
+
}
|
|
774
|
+
// The unit and the drop-in: root-owned regular files with the content the plan would write.
|
|
775
|
+
for (const [label, file, expected] of [['unit', p.unit, unitText(tc)], ['drop-in', p.dropin, dropinText(c, p.stateRoot)]]) {
|
|
776
|
+
try {
|
|
777
|
+
await trustedRegularFile(file, uid);
|
|
778
|
+
// nosemgrep: mago-no-raw-read-of-signed-input -- doctor: checked just above by trustedRegularFile
|
|
779
|
+
if (sha256(await readFile(file)) !== sha256(expected))
|
|
780
|
+
throw new Error(`${file} differs from what gate init would write now; run gate init again`);
|
|
781
|
+
add(label, 'PASS', `${file} matches what gate init writes`);
|
|
782
|
+
}
|
|
783
|
+
catch (e) {
|
|
784
|
+
add(label, 'FAIL', message(e));
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
try {
|
|
788
|
+
await trustedRegularFile(p.hook, uid);
|
|
789
|
+
// nosemgrep: mago-no-raw-read-of-signed-input -- doctor: checked just above by trustedRegularFile
|
|
790
|
+
if (sha256(await readFile(p.hook)) !== sha256(hookExpected))
|
|
791
|
+
throw new Error(`${p.hook} differs from what gate init would write now; run gate init again`);
|
|
792
|
+
add('hook config', 'PASS', `${p.hook} matches what gate init writes`);
|
|
793
|
+
}
|
|
794
|
+
catch (e) {
|
|
795
|
+
add('hook config', 'FAIL', message(e));
|
|
796
|
+
}
|
|
797
|
+
if (host === 'codex')
|
|
798
|
+
await codexDoctor(c, p, homes, uid, opts, add);
|
|
799
|
+
// Service, trust, mode: need the admin socket (root).
|
|
800
|
+
const callerUid = opts.uid ?? process.getuid?.() ?? -1;
|
|
801
|
+
let status;
|
|
802
|
+
if (callerUid !== uid) {
|
|
803
|
+
for (const k of ['service', 'trust'])
|
|
804
|
+
add(k, 'SKIP', 'needs root');
|
|
805
|
+
}
|
|
806
|
+
else {
|
|
807
|
+
const decision = path.join(c.decision_socket_dir, 'decision.sock');
|
|
808
|
+
const sock = await lstat(decision).then((s) => s.isSocket(), () => false);
|
|
809
|
+
let adminTrusted = true;
|
|
810
|
+
if (sock && existsSync(c.admin_socket_dir)) {
|
|
811
|
+
try {
|
|
812
|
+
await checkAdminSocket(c.admin_socket_dir, uid);
|
|
813
|
+
}
|
|
814
|
+
catch (e) {
|
|
815
|
+
adminTrusted = false;
|
|
816
|
+
add('admin socket', 'FAIL', message(e));
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
if (!sock)
|
|
820
|
+
add('service', 'FAIL', `${decision} does not exist; is the service running? (systemctl status mago-ski-gate@${host})`);
|
|
821
|
+
else if (!adminTrusted)
|
|
822
|
+
add('service', 'SKIP', 'the admin socket is not trusted (see the admin socket check)');
|
|
823
|
+
else {
|
|
824
|
+
try {
|
|
825
|
+
const r = await (opts.ask ?? askAdmin)(path.join(c.admin_socket_dir, 'admin.sock'), { cmd: 'status' }, 10_000);
|
|
826
|
+
if (!r.ok)
|
|
827
|
+
add('service', 'FAIL', r.error);
|
|
828
|
+
else {
|
|
829
|
+
status = r;
|
|
830
|
+
const log = isRecord(r['log']) ? r['log'] : {};
|
|
831
|
+
if (r['ready'] === true && log['state'] === 'ready')
|
|
832
|
+
add('service', 'PASS', 'answers status; ready; decision log ready');
|
|
833
|
+
else
|
|
834
|
+
add('service', 'FAIL', `answers status but is not fully ready (ready=${String(r['ready'])}, admission=${String(r['admission'])}, log=${String(log['state'])})`);
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
catch (e) {
|
|
838
|
+
add('service', 'FAIL', message(e));
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
if (!status)
|
|
842
|
+
add('trust', 'SKIP', 'no status from the service');
|
|
843
|
+
else if (status['trust'] === 'ready')
|
|
844
|
+
add('trust', 'PASS', `trust accepted; revocation list valid until ${String(status['revocationsExpiresAt'])}`);
|
|
845
|
+
else
|
|
846
|
+
add('trust', 'FAIL', `trust is not accepted: ${String(status['trust'])}; run mago-ski gate trust --host ${host}${status['trust'] === 'no-state' ? ' (after gate init --new-root: with the documents signed by the new root)' : ''}`);
|
|
847
|
+
}
|
|
848
|
+
if (status) {
|
|
849
|
+
if (status['root_fingerprint'] === c.root_fingerprint)
|
|
850
|
+
add('root fingerprint', 'PASS', `the service uses ${c.root_fingerprint}`);
|
|
851
|
+
else
|
|
852
|
+
add('root fingerprint', 'FAIL', `the service uses ${String(status['root_fingerprint'])} but the instance config says ${c.root_fingerprint}; restart the service`);
|
|
853
|
+
}
|
|
854
|
+
if (status) { // only when something is wrong: what hosts can see must match the install records
|
|
855
|
+
const unrecorded = Array.isArray(status['unrecorded']) ? status['unrecorded'] : [];
|
|
856
|
+
if (unrecorded.length > 0)
|
|
857
|
+
add('unrecorded Skills', 'FAIL', `the managed Skill folder holds entries with no install record that hosts can load: ${unrecorded.join(', ')}; remove them (in enforce the service removes links itself, never folders)`);
|
|
858
|
+
if (typeof status['reconcileError'] === 'string')
|
|
859
|
+
add('reconcile', 'FAIL', `the last reconcile did not finish cleanly, so a Skill that should be hidden may still be visible: ${status['reconcileError']}`);
|
|
860
|
+
}
|
|
861
|
+
if (host === 'codex' && status) {
|
|
862
|
+
const mism = Array.isArray(status['nameMismatch']) ? status['nameMismatch'] : [];
|
|
863
|
+
if (mism.length > 0)
|
|
864
|
+
add('name mismatch', 'FAIL', `installed Skills whose SKILL.md does not start with one plain "name:" line equal to the install name (hidden in enforce): ${mism.join(', ')}`);
|
|
865
|
+
else
|
|
866
|
+
add('name mismatch', 'PASS', 'every installed Skill has a plain name line equal to its install name');
|
|
867
|
+
const removed = isRecord(status['removedNames']) ? status['removedNames'] : {};
|
|
868
|
+
if (removed['full'] === true)
|
|
869
|
+
add('removed names', 'WARN', `the removed-names file is full (${String(removed['evicted'])} oldest entries evicted); run: mago-ski gate prune-removed --host codex --older-than-days 90`);
|
|
870
|
+
else if (typeof removed['error'] === 'string')
|
|
871
|
+
add('removed names', 'WARN', `the removed-names file could not be written: ${removed['error']}`);
|
|
872
|
+
}
|
|
873
|
+
const mismatches = [];
|
|
874
|
+
if (status && status['mode'] !== c.mode)
|
|
875
|
+
mismatches.push(`the service runs in ${String(status['mode'])} but the instance config says ${c.mode}; restart the service`);
|
|
876
|
+
if (hostFileMode && hostFileMode !== c.mode)
|
|
877
|
+
mismatches.push(`the host config is for ${hostFileMode}`);
|
|
878
|
+
if (mismatches.length > 0)
|
|
879
|
+
add('mode', 'FAIL', mismatches.join('; '));
|
|
880
|
+
else if (c.mode === 'shadow')
|
|
881
|
+
add('mode', 'WARN', 'shadow: decisions are logged, nothing is blocked (a trial mode; use gate init --mode enforce to enforce)');
|
|
882
|
+
else
|
|
883
|
+
add('mode', 'PASS', 'enforce');
|
|
884
|
+
// Kernel settings the service header names as deployment requirements.
|
|
885
|
+
try {
|
|
886
|
+
const n = await (opts.somaxconn ?? (async () => Number((await readFile('/proc/sys/net/core/somaxconn', 'utf8')).trim())))();
|
|
887
|
+
if (Number.isFinite(n) && n < 1024)
|
|
888
|
+
add('somaxconn', 'WARN', `net.core.somaxconn is ${n}; at least 1024 is advised (the service lowers its connection cap to it)`);
|
|
889
|
+
}
|
|
890
|
+
catch { /* unreadable: no warning */ }
|
|
891
|
+
try {
|
|
892
|
+
const mounts = await (opts.procMounts ?? (() => readFile('/proc/mounts', 'utf8')))();
|
|
893
|
+
if (mounts.split('\n').some((l) => /^\S+ \/proc /u.test(l) && /hidepid=(?!0|off)/u.test(l)))
|
|
894
|
+
add('proc mount', 'WARN', '/proc is mounted with hidepid: other users\' sessions stay open longer before they are reaped');
|
|
895
|
+
}
|
|
896
|
+
catch { /* unreadable: no warning */ }
|
|
897
|
+
return out;
|
|
898
|
+
}
|
|
899
|
+
/* ---------------------------------------------------------------------------------------------- Codex doctor checks */
|
|
900
|
+
async function readHookHomes(file) {
|
|
901
|
+
try {
|
|
902
|
+
// nosemgrep: mago-no-raw-read-of-signed-input -- the root-owned hook config; doctor checks its ownership and content separately
|
|
903
|
+
const raw = parseStrictJson(await readFile(file));
|
|
904
|
+
if (!isRecord(raw))
|
|
905
|
+
return undefined;
|
|
906
|
+
const list = (v) => (Array.isArray(v) && v.every((x) => typeof x === 'string') ? v : undefined);
|
|
907
|
+
const userHomes = list(raw['user_homes']);
|
|
908
|
+
const codexHomes = list(raw['codex_homes']);
|
|
909
|
+
return userHomes && codexHomes ? { userHomes, codexHomes } : undefined;
|
|
910
|
+
}
|
|
911
|
+
catch {
|
|
912
|
+
return undefined;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
const SKILL_SCAN_LIMITS = { dirs: 5000, entries: 200_000, depth: 8 };
|
|
916
|
+
/**
|
|
917
|
+
* Looks for a SKILL.md (any case) under `root`, entering dot folders and following links. Bounded in folders, in entries (read
|
|
918
|
+
* one at a time: a folder is never loaded whole, and the queue never holds more than `dirs` folders) and in depth. `none` means
|
|
919
|
+
* every folder was read. When a bound is reached with folders left, or a folder cannot be read, the answer is `incomplete`:
|
|
920
|
+
* a SKILL.md may exist where the scan did not look, so the caller must not report a clean home.
|
|
921
|
+
*/
|
|
922
|
+
export async function scanForSkillFile(root, skip = () => false, limits = SKILL_SCAN_LIMITS) {
|
|
923
|
+
const queue = [{ dir: root, depth: 0 }];
|
|
924
|
+
let entries = 0;
|
|
925
|
+
let complete = true;
|
|
926
|
+
for (let i = 0; i < queue.length; i++) {
|
|
927
|
+
const { dir, depth } = queue[i];
|
|
928
|
+
try {
|
|
929
|
+
for await (const e of await opendir(dir)) { // closed by the loop, also on return
|
|
930
|
+
if (++entries > limits.entries)
|
|
931
|
+
return 'incomplete';
|
|
932
|
+
const full = path.join(dir, e.name);
|
|
933
|
+
if (skip(path.relative(root, full)))
|
|
934
|
+
continue;
|
|
935
|
+
if (/^skill\.md$/iu.test(e.name))
|
|
936
|
+
return 'found';
|
|
937
|
+
const isDir = e.isDirectory() || (e.isSymbolicLink() && (await stat(full).catch(() => undefined))?.isDirectory() === true);
|
|
938
|
+
if (!isDir)
|
|
939
|
+
continue;
|
|
940
|
+
if (depth >= limits.depth || queue.length >= limits.dirs) {
|
|
941
|
+
complete = false;
|
|
942
|
+
continue;
|
|
943
|
+
} // not entered: keep looking in what is queued
|
|
944
|
+
queue.push({ dir: full, depth: depth + 1 });
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
catch (e) {
|
|
948
|
+
if (!['ENOENT', 'ENOTDIR'].includes(errnoCode(e) ?? ''))
|
|
949
|
+
complete = false; // absent is empty; unreadable is unknown
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
return complete ? 'none' : 'incomplete';
|
|
953
|
+
}
|
|
954
|
+
const defaultCodexVersion = (exe) => new Promise((resolve, reject) => {
|
|
955
|
+
execFile(exe, ['--version'], { timeout: 5000, env: {} }, (e, out) => (e ? reject(e) : resolve(String(out))));
|
|
956
|
+
});
|
|
957
|
+
async function codexDoctor(c, p, homes, uid, opts, add) {
|
|
958
|
+
// managed_config.toml: exact content, root-owned.
|
|
959
|
+
try {
|
|
960
|
+
const file = p.managedConfig;
|
|
961
|
+
const info = await lstat(file);
|
|
962
|
+
if (!info.isFile() || info.uid !== uid || (info.mode & 0o022) !== 0)
|
|
963
|
+
throw new Error(`${file} must be a regular file owned by root and not writable by others`);
|
|
964
|
+
// nosemgrep: mago-no-raw-read-of-signed-input -- doctor: checked just above as a root-owned regular file not writable by others
|
|
965
|
+
if (sha256(await readFile(file)) !== sha256(codexManagedConfigToml()))
|
|
966
|
+
throw new Error(`${file} differs from what gate init would write now; run gate init again`);
|
|
967
|
+
add('managed config', 'PASS', `${file} matches what gate init writes`);
|
|
968
|
+
}
|
|
969
|
+
catch (e) {
|
|
970
|
+
add('managed config', 'FAIL', errnoCode(e) === 'ENOENT' ? `${p.managedConfig} does not exist; run gate init again` : message(e));
|
|
971
|
+
}
|
|
972
|
+
// The hook config must list the homes (an unlisted HOME blocks bare mentions).
|
|
973
|
+
const listed = homes.userHomes.length > 0 || homes.codexHomes.length > 0;
|
|
974
|
+
if (!listed)
|
|
975
|
+
add('user homes', 'WARN', 'no home is listed (gate init --user-home DIR): the hook cannot recognise any HOME, so bare mentions are blocked');
|
|
976
|
+
// Non-admin Skills in a listed home (the menu route, D1): FAIL.
|
|
977
|
+
const withSkills = [];
|
|
978
|
+
const notScanned = [];
|
|
979
|
+
const withSystem = [];
|
|
980
|
+
const notSystem = (rel) => rel === '.system' || rel.startsWith('.system/');
|
|
981
|
+
const scan = async (d) => {
|
|
982
|
+
const r = await scanForSkillFile(d, notSystem, opts.skillScanLimits);
|
|
983
|
+
if (r === 'found')
|
|
984
|
+
withSkills.push(d);
|
|
985
|
+
else if (r === 'incomplete')
|
|
986
|
+
notScanned.push(d);
|
|
987
|
+
};
|
|
988
|
+
for (const h of homes.userHomes) {
|
|
989
|
+
for (const d of [`${h}/.agents/skills`, `${h}/.codex/skills`])
|
|
990
|
+
await scan(d);
|
|
991
|
+
if (await lstat(`${h}/.codex/skills/.system`).then(() => true, () => false))
|
|
992
|
+
withSystem.push(`${h}/.codex/skills/.system`);
|
|
993
|
+
}
|
|
994
|
+
for (const h of homes.codexHomes) {
|
|
995
|
+
await scan(`${h}/skills`);
|
|
996
|
+
if (await lstat(`${h}/skills/.system`).then(() => true, () => false))
|
|
997
|
+
withSystem.push(`${h}/skills/.system`);
|
|
998
|
+
}
|
|
999
|
+
// An incomplete scan is a FAIL, never a PASS: a SKILL.md may exist where the scan did not look.
|
|
1000
|
+
const findings = [];
|
|
1001
|
+
if (withSkills.length > 0)
|
|
1002
|
+
findings.push(`a listed home has Skills that Codex would list (a menu pick reaches the model with no hook): ${withSkills.join(', ')}`);
|
|
1003
|
+
if (notScanned.length > 0)
|
|
1004
|
+
findings.push(`the scan could not read all of ${notScanned.join(', ')} (too many folders or entries, deeper than the scan goes, or unreadable), so a SKILL.md there cannot be ruled out; empty or lock these folders`);
|
|
1005
|
+
if (findings.length > 0)
|
|
1006
|
+
add('user Skills', 'FAIL', findings.join('; '));
|
|
1007
|
+
else
|
|
1008
|
+
add('user Skills', 'PASS', 'no SKILL.md under the listed homes');
|
|
1009
|
+
if (withSystem.length > 0)
|
|
1010
|
+
add('.system folder', 'FAIL', `${withSystem.join(', ')} exists; the profile turns bundled Skills off, so move it away (gate init does, into <home>/.codex/mago-ski-backup/)`);
|
|
1011
|
+
else
|
|
1012
|
+
add('.system folder', 'PASS', 'no .system folder under the listed homes');
|
|
1013
|
+
// The optional lock (E1).
|
|
1014
|
+
if (homes.userHomes.length > 0) {
|
|
1015
|
+
const isImmutable = opts.isImmutable ?? defaultIsImmutable;
|
|
1016
|
+
const open = [];
|
|
1017
|
+
for (const h of homes.userHomes)
|
|
1018
|
+
for (const d of [`${h}/.agents/skills`, `${h}/.codex/skills`])
|
|
1019
|
+
if (!(await isImmutable(d)))
|
|
1020
|
+
open.push(d);
|
|
1021
|
+
if (open.length > 0)
|
|
1022
|
+
add('Skill folder lock', 'WARN', `not locked (gate init --lock-user-skill-folders): ${open.join(', ')}`);
|
|
1023
|
+
else
|
|
1024
|
+
add('Skill folder lock', 'PASS', 'the user Skill folders are locked (immutable)');
|
|
1025
|
+
}
|
|
1026
|
+
// The Codex version the profile was verified on.
|
|
1027
|
+
try {
|
|
1028
|
+
const out = await (opts.codexVersion ?? defaultCodexVersion)(c.host_exes[0]);
|
|
1029
|
+
const m = /(\d+)\.(\d+)\.(\d+)/u.exec(out);
|
|
1030
|
+
if (m && m[1] === '0' && m[2] === '166')
|
|
1031
|
+
add('codex version', 'PASS', `codex ${m[0]}`);
|
|
1032
|
+
else
|
|
1033
|
+
add('codex version', 'WARN', `untested Codex version${m ? ` ${m[0]}` : ''}: the profile was verified on 0.166.x`);
|
|
1034
|
+
}
|
|
1035
|
+
catch {
|
|
1036
|
+
add('codex version', 'WARN', 'untested Codex version: codex --version could not be run');
|
|
1037
|
+
}
|
|
1038
|
+
}
|