@mago-foundation/mago-ski 0.4.0 → 0.5.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +5 -3
  2. package/action.yml +21 -2
  3. package/dist/hosts/github/check.d.ts +21 -0
  4. package/dist/hosts/github/check.js +124 -0
  5. package/dist/hosts/github/publish.d.ts +7 -0
  6. package/dist/hosts/github/publish.js +52 -0
  7. package/dist/hosts/github/run.d.ts +12 -0
  8. package/dist/hosts/github/run.js +32 -18
  9. package/dist/hosts/pi/index.js +40 -18
  10. package/dist/src/admin.d.ts +2 -1
  11. package/dist/src/admin.js +3 -2
  12. package/dist/src/admission-evidence.d.ts +15 -0
  13. package/dist/src/admission-evidence.js +48 -0
  14. package/dist/src/admission.d.ts +102 -0
  15. package/dist/src/admission.js +316 -0
  16. package/dist/src/canonical-json.d.ts +6 -0
  17. package/dist/src/canonical-json.js +11 -0
  18. package/dist/src/cli.d.ts +2 -0
  19. package/dist/src/cli.js +229 -5
  20. package/dist/src/diff.d.ts +9 -0
  21. package/dist/src/diff.js +3 -2
  22. package/dist/src/dsse.js +2 -2
  23. package/dist/src/experimental/sigstore.d.ts +30 -0
  24. package/dist/src/experimental/sigstore.js +35 -5
  25. package/dist/src/fs-safe.d.ts +15 -2
  26. package/dist/src/fs-safe.js +68 -50
  27. package/dist/src/gate/adapters/claude-code.js +8 -5
  28. package/dist/src/gate/adapters/codex.js +5 -6
  29. package/dist/src/gate/generations.js +2 -0
  30. package/dist/src/gate/instance.js +7 -7
  31. package/dist/src/gate/proc.d.ts +6 -0
  32. package/dist/src/gate/proc.js +14 -3
  33. package/dist/src/gate/service.js +3 -0
  34. package/dist/src/gate/setup.d.ts +5 -5
  35. package/dist/src/gate/setup.js +128 -88
  36. package/dist/src/policy.d.ts +7 -0
  37. package/dist/src/policy.js +19 -2
  38. package/dist/src/profile.d.ts +34 -0
  39. package/dist/src/profile.js +182 -0
  40. package/dist/src/published-by.d.ts +64 -0
  41. package/dist/src/published-by.js +227 -0
  42. package/dist/src/recovery-admin.js +7 -4
  43. package/dist/src/root-events.d.ts +2 -0
  44. package/dist/src/root-events.js +61 -4
  45. package/dist/src/tree-digest.d.ts +6 -0
  46. package/dist/src/tree-digest.js +8 -0
  47. package/dist/src/usf-check.d.ts +28 -0
  48. package/dist/src/usf-check.js +128 -0
  49. package/dist/src/usf.d.ts +48 -0
  50. package/dist/src/usf.js +238 -0
  51. package/docs/hosts/publish.md +65 -0
  52. package/docs/hosts/skill-check.md +91 -0
  53. package/docs/spec/admission-v0.md +84 -0
  54. package/docs/spec/gui-admin-rack-v1.md +1 -1
  55. package/docs/spec/observed-profile-v1.md +51 -0
  56. package/docs/spec/root-recovery-v1.md +3 -2
  57. package/docs/spec/trust-documents-v1.md +1 -1
  58. package/docs/threat-model.md +12 -0
  59. package/package.json +5 -1
@@ -4,12 +4,12 @@
4
4
  // parameters (`base`, `rootUid`, `platform`, ...) so tests can run them against a temporary tree and the current user.
5
5
  import { createHash } from 'node:crypto';
6
6
  import { execFile } from 'node:child_process';
7
- import { chmod, chown, link, lstat, mkdir, open, opendir, readdir, readFile, readlink, realpath, rename, stat, unlink } from 'node:fs/promises';
7
+ import { link, lstat, mkdir, open, opendir, readdir, readFile, readlink, realpath, rename, stat, unlink } from 'node:fs/promises';
8
8
  import { constants as fsConstants, existsSync } from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import { fileURLToPath } from 'node:url';
11
11
  import { isRecord, parseCanonicalJsonBytes, serializeCanonicalJson } from "../canonical-json.js";
12
- import { readRegularFile, writeFileAtomic } from "../fs-safe.js";
12
+ import { readOwnedRegularFile, readRegularFile, writeFileAtomic } from "../fs-safe.js";
13
13
  import { validateKeyId } from "../keys.js";
14
14
  import { claudeCodeManagedSettings } from "./adapters/claude-code-settings.js";
15
15
  import { codexManagedConfigToml, codexRequirementsToml } from "./adapters/codex-requirements.js";
@@ -75,10 +75,16 @@ const message = (e) => (e instanceof Error ? e.message : String(e));
75
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
76
  */
77
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);
78
+ let handle;
79
+ try {
80
+ handle = await open(exe, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
81
+ }
82
+ catch (e) {
83
+ const code = errnoCode(e);
84
+ if (code === 'ELOOP' || code === 'EISDIR' || code === 'ENXIO' || code === 'EOPNOTSUPP')
85
+ throw new Error(`${exe} is not a regular file`);
86
+ throw e;
87
+ }
82
88
  try {
83
89
  const fd = await handle.stat();
84
90
  if (!fd.isFile())
@@ -170,6 +176,7 @@ async function chooseHomes(opts, problems) {
170
176
  if (opts.userHomes && opts.userHomes.length > 0)
171
177
  return [...new Set(opts.userHomes.map((h) => cleanDir(h, '--user-home', problems)).filter((h) => h !== undefined))];
172
178
  const out = [];
179
+ // nosemgrep: mago-no-raw-read-of-signed-input -- the system user list, read as root to choose the homes
173
180
  const text = await readFile(path.join(opts.base ?? '/', 'etc', 'passwd'), 'utf8').catch(() => '');
174
181
  for (const line of text.split('\n')) {
175
182
  const f = line.split(':');
@@ -184,12 +191,38 @@ async function chooseHomes(opts, problems) {
184
191
  }
185
192
  return out;
186
193
  }
187
- const defaultChattr = (target) => new Promise((resolve, reject) => {
188
- execFile('chattr', ['+i', target], { timeout: 10_000 }, (e, _o, stderr) => (e ? reject(new Error(`chattr +i ${target} failed: ${String(stderr).trim() || e.message}`)) : resolve()));
194
+ // `via` is the same folder named through an open handle of this process (`/proc/<pid>/fd/N`): the tool then works on the
195
+ // folder that was opened and checked, whatever the path points to by now. `target` is the path, for messages.
196
+ const defaultChattr = (target, via = target) => new Promise((resolve, reject) => {
197
+ execFile('chattr', ['+i', via], { timeout: 10_000 }, (e, _o, stderr) => (e ? reject(new Error(`chattr +i ${target} failed: ${String(stderr).trim() || e.message}`)) : resolve()));
189
198
  });
190
- const defaultIsImmutable = (target) => new Promise((resolve) => {
191
- execFile('lsattr', ['-d', target], { timeout: 10_000 }, (e, out) => resolve(!e && /^\S*i\S*\s/u.test(String(out))));
199
+ const defaultIsImmutable = (target, via = target) => new Promise((resolve) => {
200
+ execFile('lsattr', ['-d', via], { timeout: 10_000 }, (e, out) => resolve(!e && /^\S*i\S*\s/u.test(String(out))));
192
201
  });
202
+ const REAL_DIR = fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW;
203
+ /** A folder named through an open handle, also for a child process (`/proc/self` would be the child's own). */
204
+ const viaHandle = (handle, name) => `/proc/${process.pid}/fd/${handle.fd}${name === undefined ? '' : `/${name}`}`;
205
+ /**
206
+ * Opens `dir` without following a link in its last part and requires the kernel's name for the open folder to be exactly
207
+ * `dir`, so no part of the path is a link. What is done through the handle afterwards cannot be redirected by its owner.
208
+ */
209
+ async function pinFolder(dir, refusal) {
210
+ 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}`); });
211
+ const real = await readlink(viaHandle(handle)).catch(() => undefined);
212
+ if (real !== dir) {
213
+ await handle.close();
214
+ throw new Error(`${dir} is not a real path (it resolves to ${real ?? 'an unknown folder'}); ${refusal}`);
215
+ }
216
+ return handle;
217
+ }
218
+ /** Opens the folder `name` inside an open folder, creating it when missing; a link or a file there is refused. */
219
+ async function pinChild(parent, name, mode, label) {
220
+ let created = true;
221
+ await mkdir(viaHandle(parent, name), { mode }).catch((e) => { if (errnoCode(e) !== 'EEXIST')
222
+ throw e; created = false; });
223
+ 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)})`); });
224
+ return { handle, created };
225
+ }
193
226
  /** `.system` moves (F5, F7.6) and, with `--lock-user-skill-folders`, the lock of each listed home (E1). Refusals go to `problems`. */
194
227
  async function planHomeActions(homes, opts, problems) {
195
228
  const out = [];
@@ -216,6 +249,12 @@ async function planHomeActions(homes, opts, problems) {
216
249
  problems.push(`${home} is not a folder; cannot lock its Skill folders`);
217
250
  continue;
218
251
  }
252
+ // Root works inside a folder its owner controls: the path must be the real one (the lock checks it again, on open handles).
253
+ const real = await realpath(home).catch(() => undefined);
254
+ if (real !== home) {
255
+ problems.push(`${home} is not a real path (it resolves to ${real ?? 'nothing'}); list the real home to lock its Skill folders`);
256
+ continue;
257
+ }
219
258
  for (const dir of [`${home}/.agents/skills`, `${home}/.codex/skills`]) {
220
259
  const entries = await readdir(dir).catch(() => []);
221
260
  const left = entries.filter((e) => !(dir.endsWith('/.codex/skills') && e === '.system'));
@@ -234,27 +273,17 @@ async function planHomeActions(homes, opts, problems) {
234
273
  * folder swapped for a link after the check changes nothing. `.system` itself must be a real folder inside the open handle.
235
274
  */
236
275
  async function moveSystemFolder(from, to) {
237
- const flags = fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW;
238
- const pinned = async (dir) => {
239
- const handle = await open(dir, flags).catch((e) => { throw new Error(`${dir} cannot be opened as a real folder (${errnoCode(e) ?? message(e)}); .system was not moved`); });
240
- const real = await readlink(`/proc/self/fd/${handle.fd}`).catch(() => undefined);
241
- if (real !== dir) {
242
- await handle.close();
243
- throw new Error(`${dir} is not a real path (it resolves to ${real ?? 'an unknown folder'}); .system was not moved`);
244
- }
245
- return handle;
246
- };
247
- const skills = await pinned(path.dirname(from));
276
+ const skills = await pinFolder(path.dirname(from), '.system was not moved');
248
277
  try {
249
278
  const backupDir = path.dirname(to);
250
279
  await mkdir(backupDir, { mode: 0o755 }).catch((e) => { if (errnoCode(e) !== 'EEXIST')
251
280
  throw e; });
252
- const backup = await pinned(backupDir);
281
+ const backup = await pinFolder(backupDir, '.system was not moved');
253
282
  try {
254
- const source = `/proc/self/fd/${skills.fd}/${path.basename(from)}`;
283
+ const source = viaHandle(skills, path.basename(from));
255
284
  if (!(await lstat(source)).isDirectory())
256
285
  throw new Error(`${from} is no longer a real folder; .system was not moved`);
257
- await rename(source, `/proc/self/fd/${backup.fd}/${path.basename(to)}`); // rename never follows a link in the last part
286
+ await rename(source, viaHandle(backup, path.basename(to))); // rename never follows a link in the last part
258
287
  }
259
288
  finally {
260
289
  await backup.close();
@@ -264,6 +293,53 @@ async function moveSystemFolder(from, to) {
264
293
  await skills.close();
265
294
  }
266
295
  }
296
+ /**
297
+ * Locks one home's Skill folders (E1): `~/.agents`, `~/.agents/skills` and `~/.codex/skills` become root-owned, 0755 and
298
+ * immutable. Root works here inside a folder its owner controls, so nothing is done by path: the home and each folder are
299
+ * opened without following links, and ownership, mode and the immutable attribute are set on the open handles. A folder
300
+ * swapped for a link at any moment is either refused or changes nothing. `~/.codex` stays the user's own folder (Codex
301
+ * writes there), which is also the limit of the lock: its owner can still rename `~/.codex` and make a new one, and
302
+ * `gate doctor` then reports the Skill folder as not locked.
303
+ */
304
+ async function lockHome(a, rootUid, gid, chattr, isImmutable) {
305
+ const handles = [];
306
+ const child = async (parent, name, mode, label) => { const c = await pinChild(parent, name, mode, label); handles.push(c.handle); return c; };
307
+ try {
308
+ const home = await pinFolder(a.home, 'its Skill folders were not locked');
309
+ handles.push(home);
310
+ const codex = await child(home, '.codex', 0o700, `${a.home}/.codex`);
311
+ if (codex.created && a.owner)
312
+ await codex.handle.chown(a.owner.uid, a.owner.gid).catch(() => { }); // Codex writes here: the user's own folder
313
+ const agents = await child(home, '.agents', 0o755, `${a.home}/.agents`);
314
+ const agentsSkills = await child(agents.handle, 'skills', 0o755, `${a.home}/.agents/skills`);
315
+ const codexSkills = await child(codex.handle, 'skills', 0o755, `${a.home}/.codex/skills`);
316
+ const dirs = [
317
+ { dir: `${a.home}/.agents/skills`, handle: agentsSkills.handle, empty: true },
318
+ { dir: `${a.home}/.codex/skills`, handle: codexSkills.handle, empty: true },
319
+ { dir: `${a.home}/.agents`, handle: agents.handle, empty: false }, // children first: the order of the plan
320
+ ];
321
+ const locked = [];
322
+ for (const d of dirs) {
323
+ if (await isImmutable(d.dir, viaHandle(d.handle))) {
324
+ locked.push(d.dir);
325
+ continue;
326
+ } // a re-run
327
+ // The plan saw these folders empty; a Skill added since then must not be locked in.
328
+ const left = d.empty ? await readdir(viaHandle(d.handle)) : [];
329
+ if (left.length > 0)
330
+ 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`);
331
+ await d.handle.chown(rootUid, gid);
332
+ await d.handle.chmod(0o755);
333
+ await chattr(d.dir, viaHandle(d.handle)); // a failure (an unsupported file system) stops the command
334
+ locked.push(d.dir);
335
+ }
336
+ return locked;
337
+ }
338
+ finally {
339
+ for (const h of handles.reverse())
340
+ await h.close().catch(() => { });
341
+ }
342
+ }
267
343
  /** Plan: moves first, then locks. Each move needs the target folder free. */
268
344
  async function runHomeActions(actions, opts, rootUid) {
269
345
  const moved = [];
@@ -277,36 +353,9 @@ async function runHomeActions(actions, opts, rootUid) {
277
353
  const chattr = opts.chattr ?? defaultChattr;
278
354
  const isImmutable = opts.isImmutable ?? defaultIsImmutable;
279
355
  const gid = rootUid === 0 ? 0 : (process.getgid?.() ?? 0);
280
- for (const a of actions) {
281
- if (a.kind !== 'lock')
282
- continue;
283
- const codex = `${a.home}/.codex`;
284
- if (!(await lstat(codex).catch(() => undefined))) { // Codex writes here, so it stays the user's own folder
285
- await mkdir(codex, { mode: 0o700 });
286
- if (a.owner)
287
- await chown(codex, a.owner.uid, a.owner.gid).catch(() => { });
288
- }
289
- const agents = `${a.home}/.agents`;
290
- for (const dir of [agents, `${agents}/skills`, `${codex}/skills`]) {
291
- if (await isImmutable(dir))
292
- continue; // a re-run
293
- await mkdir(dir, { mode: 0o755 }).catch((e) => { if (errnoCode(e) !== 'EEXIST')
294
- throw e; });
295
- const info = await lstat(dir);
296
- if (info.isSymbolicLink() || !info.isDirectory())
297
- throw new Error(`${dir} must be a real folder to be locked`);
298
- await chown(dir, rootUid, gid);
299
- await chmod(dir, 0o755);
300
- }
301
- for (const dir of [`${agents}/skills`, `${codex}/skills`, agents]) { // children first: an immutable parent would still allow it, but the order is the plan's
302
- if (await isImmutable(dir)) {
303
- locked.push(dir);
304
- continue;
305
- }
306
- await chattr(dir); // a failure (an unsupported file system) stops the command
307
- locked.push(dir);
308
- }
309
- }
356
+ for (const a of actions)
357
+ if (a.kind === 'lock')
358
+ locked.push(...await lockHome(a, rootUid, gid, chattr, isImmutable));
310
359
  return { moved, locked };
311
360
  }
312
361
  export function unitText(tc) {
@@ -361,10 +410,7 @@ function manifestText(files, previous) {
361
410
  async function readManifest(file, uid) {
362
411
  let raw;
363
412
  try {
364
- const info = await lstat(file);
365
- if (!info.isFile() || info.uid !== uid || (info.mode & 0o022) !== 0)
366
- return undefined;
367
- raw = parseCanonicalJsonBytes(await readRegularFile(file, 'manifest', 1024 * 1024), 'manifest');
413
+ raw = parseCanonicalJsonBytes(await readOwnedRegularFile(file, 'manifest', { uid, maxBytes: 1024 * 1024 }), 'manifest');
368
414
  }
369
415
  catch {
370
416
  return undefined;
@@ -458,15 +504,19 @@ export async function planInit(opts) {
458
504
  const sharedOwn = await readManifest(p.sharedManifest, uid);
459
505
  const foreign = [];
460
506
  for (const f of files) {
461
- const info = await lstat(f.path).catch((e) => { if (errnoCode(e) === 'ENOENT' || errnoCode(e) === 'ENOTDIR')
462
- return undefined; throw e; });
463
- if (!info)
464
- continue;
465
- let ours = false;
466
- if (info.isFile()) {
467
- const h = sha256(await readFile(f.path));
468
- ours = own?.get(f.path) === h || sharedOwn?.get(f.path) === h;
507
+ let bytes;
508
+ try {
509
+ bytes = await readRegularFile(f.path, f.path);
469
510
  }
511
+ catch (e) {
512
+ const code = errnoCode(e);
513
+ if (code === 'ENOENT' || code === 'ENOTDIR')
514
+ continue;
515
+ if (code !== undefined)
516
+ throw e;
517
+ }
518
+ const h = bytes ? sha256(bytes) : undefined;
519
+ const ours = h !== undefined && (own?.get(f.path) === h || sharedOwn?.get(f.path) === h);
470
520
  if (!ours)
471
521
  foreign.push(f.path);
472
522
  }
@@ -617,14 +667,6 @@ export async function applyInit(plan, opts = {}) {
617
667
  }
618
668
  return result;
619
669
  }
620
- /** lstat: a regular file (not a symlink) owned by `uid` and not writable by group or others. */
621
- async function trustedRegularFile(file, uid) {
622
- const info = await lstat(file);
623
- if (info.isSymbolicLink() || !info.isFile())
624
- throw new Error(`${file} must be a regular file, not a symlink`);
625
- if (info.uid !== uid || (info.mode & 0o022) !== 0)
626
- throw new Error(NOT_ROOT(file));
627
- }
628
670
  /** Read-only checks, in the order of the design (v1 section 6, G6, G12). Never throws. */
629
671
  export async function doctor(host, opts = {}) {
630
672
  const out = [];
@@ -697,15 +739,14 @@ export async function doctor(host, opts = {}) {
697
739
  // Host config and hook config: exact content of what `gate init` would write now.
698
740
  // Codex: the listed homes live in the hook config (the instance config does not know them); deny_read is present or not as written.
699
741
  const homes = (host === 'codex' ? await readHookHomes(p.hook) : undefined) ?? { userHomes: [], codexHomes: [] };
700
- const denyRoots = host === 'codex' && /^deny_read = /mu.test(await readFile(p.hostConfig, 'utf8').catch(() => '')) ? codexDenyRoots(homes) : [];
701
742
  const hookExpected = hookConfigText(host, c, homes);
702
743
  let hostFileMode;
703
744
  try {
745
+ const msg = `${p.hostConfig} must be a regular file owned by root and not writable by others`;
746
+ const hostBytes = await readOwnedRegularFile(p.hostConfig, p.hostConfig, { uid, notRegularMessage: msg, ownershipMessage: msg });
747
+ const denyRoots = host === 'codex' && /^deny_read = /mu.test(hostBytes.toString('utf8')) ? codexDenyRoots(homes) : [];
704
748
  const expected = hostConfigText(host, c.mode, tc, p.hook, denyRoots);
705
- const info = await lstat(p.hostConfig);
706
- if (!info.isFile() || info.uid !== uid || (info.mode & 0o022) !== 0)
707
- throw new Error(`${p.hostConfig} must be a regular file owned by root and not writable by others`);
708
- const have = sha256(await readFile(p.hostConfig));
749
+ const have = sha256(hostBytes);
709
750
  if (have === sha256(expected)) {
710
751
  hostFileMode = c.mode;
711
752
  add('host config', 'PASS', `${p.hostConfig} matches what gate init writes`);
@@ -728,8 +769,8 @@ export async function doctor(host, opts = {}) {
728
769
  // The unit and the drop-in: root-owned regular files with the content the plan would write.
729
770
  for (const [label, file, expected] of [['unit', p.unit, unitText(tc)], ['drop-in', p.dropin, dropinText(c, p.stateRoot)]]) {
730
771
  try {
731
- await trustedRegularFile(file, uid);
732
- if (sha256(await readFile(file)) !== sha256(expected))
772
+ const bytes = await readOwnedRegularFile(file, file, { uid, notRegularMessage: `${file} must be a regular file, not a symlink`, ownershipMessage: NOT_ROOT(file) });
773
+ if (sha256(bytes) !== sha256(expected))
733
774
  throw new Error(`${file} differs from what gate init would write now; run gate init again`);
734
775
  add(label, 'PASS', `${file} matches what gate init writes`);
735
776
  }
@@ -738,8 +779,8 @@ export async function doctor(host, opts = {}) {
738
779
  }
739
780
  }
740
781
  try {
741
- await trustedRegularFile(p.hook, uid);
742
- if (sha256(await readFile(p.hook)) !== sha256(hookExpected))
782
+ const bytes = await readOwnedRegularFile(p.hook, p.hook, { uid, notRegularMessage: `${p.hook} must be a regular file, not a symlink`, ownershipMessage: NOT_ROOT(p.hook) });
783
+ if (sha256(bytes) !== sha256(hookExpected))
743
784
  throw new Error(`${p.hook} differs from what gate init would write now; run gate init again`);
744
785
  add('hook config', 'PASS', `${p.hook} matches what gate init writes`);
745
786
  }
@@ -851,7 +892,7 @@ export async function doctor(host, opts = {}) {
851
892
  /* ---------------------------------------------------------------------------------------------- Codex doctor checks */
852
893
  async function readHookHomes(file) {
853
894
  try {
854
- const raw = parseStrictJson(await readFile(file));
895
+ const raw = parseStrictJson(await readRegularFile(file, 'hook config'));
855
896
  if (!isRecord(raw))
856
897
  return undefined;
857
898
  const list = (v) => (Array.isArray(v) && v.every((x) => typeof x === 'string') ? v : undefined);
@@ -909,10 +950,9 @@ async function codexDoctor(c, p, homes, uid, opts, add) {
909
950
  // managed_config.toml: exact content, root-owned.
910
951
  try {
911
952
  const file = p.managedConfig;
912
- const info = await lstat(file);
913
- if (!info.isFile() || info.uid !== uid || (info.mode & 0o022) !== 0)
914
- throw new Error(`${file} must be a regular file owned by root and not writable by others`);
915
- if (sha256(await readFile(file)) !== sha256(codexManagedConfigToml()))
953
+ const msg = `${file} must be a regular file owned by root and not writable by others`;
954
+ const bytes = await readOwnedRegularFile(file, file, { uid, notRegularMessage: msg, ownershipMessage: msg });
955
+ if (sha256(bytes) !== sha256(codexManagedConfigToml()))
916
956
  throw new Error(`${file} differs from what gate init would write now; run gate init again`);
917
957
  add('managed config', 'PASS', `${file} matches what gate init writes`);
918
958
  }
@@ -59,6 +59,11 @@ export interface Policy {
59
59
  }
60
60
  /** Policy files are hand-edited JSON; paths are relative to the policy file's directory. */
61
61
  export declare function loadPolicy(policyPath: string): Promise<Policy>;
62
+ /**
63
+ * Two canonical paths that name the same file. On macOS the default file system ignores case, and a path whose last part
64
+ * does not exist yet keeps the case it was written in, so `state.json` and `STATE.JSON` must count as the same file there.
65
+ */
66
+ export declare function samePath(a: string, b: string, platform?: NodeJS.Platform): boolean;
62
67
  /** The host state file exists and was read, but its content or kind is wrong. Every other read error is not this. */
63
68
  export declare class HostStateFormatError extends Error {
64
69
  constructor(message: string);
@@ -170,6 +175,8 @@ export interface DiscoveryLimits {
170
175
  maxSkills?: number;
171
176
  /** Maximum directory entries visited across all roots. */
172
177
  maxEntries?: number;
178
+ /** Directories (absolute) that are not entered and not reported: another checkout that sits inside a root. */
179
+ exclude?: readonly string[];
173
180
  }
174
181
  /** Discovery stopped because the tree is larger than the budget. It never returns a partial list: callers must fail closed. */
175
182
  export declare class DiscoveryBudgetError extends Error {
@@ -127,6 +127,13 @@ async function canonicalOrLexical(target) {
127
127
  return path.resolve(target);
128
128
  }
129
129
  }
130
+ /**
131
+ * Two canonical paths that name the same file. On macOS the default file system ignores case, and a path whose last part
132
+ * does not exist yet keeps the case it was written in, so `state.json` and `STATE.JSON` must count as the same file there.
133
+ */
134
+ export function samePath(a, b, platform = process.platform) {
135
+ return platform === 'darwin' || platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
136
+ }
130
137
  /** decision_log and state_file are overwritten or appended to, so they must not be a file the policy reads. */
131
138
  async function rejectWriteTargetsThatOverlapInputs(policy) {
132
139
  const inputs = [
@@ -142,13 +149,13 @@ async function rejectWriteTargetsThatOverlapInputs(policy) {
142
149
  continue;
143
150
  const canonical = await canonicalOrLexical(target);
144
151
  for (const [name, input] of inputs) {
145
- if (canonical === await canonicalOrLexical(input))
152
+ if (samePath(canonical, await canonicalOrLexical(input)))
146
153
  throw new Error(`Policy ${label} must not be ${name}`);
147
154
  }
148
155
  if (directories.some((directory) => isInside(directory, canonical)))
149
156
  throw new Error(`Policy ${label} must not be inside a certificate_dirs directory`);
150
157
  for (const [other, otherPath] of seen)
151
- if (canonical === otherPath)
158
+ if (samePath(canonical, otherPath))
152
159
  throw new Error(`Policy ${label} must not be the same file as ${other}`);
153
160
  seen.push([label, canonical]);
154
161
  }
@@ -644,6 +651,13 @@ async function loadTrustBody(policy, now, o) {
644
651
  const problem = await saveState();
645
652
  if (problem)
646
653
  return problem;
654
+ // Another load on this host may have accepted newer documents meanwhile (the merge kept the higher versions): then the
655
+ // documents this load read are older than what the host has already accepted, which is a rollback like any other.
656
+ const accepted = state.roots[activeRootKeyId];
657
+ if (accepted && (accepted.trust_root_version > next.trust_root_version || accepted.revocations_version > next.revocations_version))
658
+ return failure(`this host has already accepted trust root ${accepted.trust_root_version} and revocation list ${accepted.revocations_version}; the documents read are older (rollback)`, { rollback: true });
659
+ if (timestamp && walk?.timestampKeyId && (state.timestamps[walk.timestampKeyId]?.version ?? 0) > timestamp.version)
660
+ return failure(`this host has already accepted timestamp ${state.timestamps[walk.timestampKeyId].version}; the timestamp read is older (rollback)`, { rollback: true });
647
661
  if (walk) {
648
662
  result.context.root = {
649
663
  pinnedRootKeyId: policy.rootKeyId,
@@ -734,12 +748,15 @@ export async function findSkillDirs(roots, maxDepth = MAX_DISCOVERY_DEPTH, limit
734
748
  const maxEntries = limits.maxEntries ?? MAX_DISCOVERY_ENTRIES;
735
749
  const found = new Set();
736
750
  const tooDeep = new Set();
751
+ const excluded = new Set((limits.exclude ?? []).map((dir) => path.resolve(dir)));
737
752
  let entries = 0;
738
753
  const checkSkills = () => {
739
754
  if (found.size + tooDeep.size > maxSkills)
740
755
  throw new DiscoveryBudgetError(`more than ${maxSkills} Skills found under skill_dirs; narrow skill_dirs or split the repository`);
741
756
  };
742
757
  async function walk(directory, depth) {
758
+ if (excluded.has(directory))
759
+ return;
743
760
  try {
744
761
  await lstat(path.join(directory, 'SKILL.md'));
745
762
  found.add(directory);
@@ -0,0 +1,34 @@
1
+ import { type SkillTree } from './tree-digest.ts';
2
+ export declare const PROFILE_FORMAT = "mago.observed-profile/v1";
3
+ /** Same limit as the origin scan in diff.ts: larger files are not searched. */
4
+ export declare const MAX_SEARCHED_BYTES: number;
5
+ export interface ScriptEvidence {
6
+ path: string;
7
+ reason: string;
8
+ }
9
+ export interface ObservedProfile {
10
+ profile: typeof PROFILE_FORMAT;
11
+ /** Tree digest (mago.skill-tree/v2) of the bytes this profile describes. */
12
+ digest: string;
13
+ /** Host names of http and https addresses found in any searched file. */
14
+ web_hosts: string[];
15
+ /** Files that are code: executable bit, `#!`, a script extension or a build-file name, or Markdown with shell code blocks. */
16
+ scripts: ScriptEvidence[];
17
+ /** Commands named first on a line inside shell code blocks in Markdown files (not a complete list). */
18
+ programs: string[];
19
+ not_searched: {
20
+ /** Images, fonts, audio and video: not searched, not a gap. */
21
+ media: string[];
22
+ /** Binary, not UTF-8, or larger than 2 MiB. */
23
+ unreadable: string[];
24
+ /** Left out by `.skilldigestignore`. */
25
+ ignored: string[];
26
+ };
27
+ /** False when anything above may be missing: an unreadable or ignored file, or a scan limit. */
28
+ complete: boolean;
29
+ }
30
+ /** The profile of a tree read with `collectSkillTree(dir, { includeContents: true })`. */
31
+ export declare function profileTree(tree: SkillTree & {
32
+ contents?: Map<string, Buffer>;
33
+ }): ObservedProfile;
34
+ export declare function observeSkill(skillDir: string): Promise<ObservedProfile>;
@@ -0,0 +1,182 @@
1
+ // Observed profile (mago.observed-profile/v1): what a Skill's own bytes show, computed deterministically and offline.
2
+ // It works on every Skill and never reads the frontmatter, so it cannot be steered by what a Skill says about itself.
3
+ // Spec: docs/spec/observed-profile-v1.md. Changing what it extracts needs a new profile version.
4
+ import { isUtf8 } from 'node:buffer';
5
+ import path from 'node:path';
6
+ import { collectOrigins } from "./diff.js";
7
+ import { collectSkillTree, pathsNotCovered } from "./tree-digest.js";
8
+ export const PROFILE_FORMAT = 'mago.observed-profile/v1';
9
+ /** Same limit as the origin scan in diff.ts: larger files are not searched. */
10
+ export const MAX_SEARCHED_BYTES = 2 * 1024 * 1024;
11
+ const MAX_PROGRAMS = 200;
12
+ const SCRIPT_EXTENSIONS = new Set(['.sh', '.bash', '.zsh', '.fish', '.ksh', '.py', '.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.rb', '.pl', '.php', '.lua', '.ps1', '.psm1', '.bat', '.cmd',
13
+ '.go', '.rs', '.java', '.kt', '.kts', '.swift', '.c', '.cc', '.cpp', '.cs', '.vbs', '.awk', '.tcl', '.r', '.jl', '.ex', '.exs', '.groovy', '.scala', '.applescript', '.scpt', '.jar', '.wasm', '.exe', '.dll', '.so', '.dylib']);
14
+ const SCRIPT_NAMES = new Set(['makefile', 'gnumakefile', 'justfile', 'rakefile', 'dockerfile', 'containerfile']);
15
+ const MARKDOWN_EXTENSIONS = new Set(['.md', '.markdown', '.mdx']);
16
+ /** Binary formats that hold no instructions or code for an agent; they are not searched and are not a gap. */
17
+ const MEDIA_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.bmp', '.ico', '.tif', '.tiff', '.heic', '.woff', '.woff2', '.ttf', '.otf', '.eot', '.mp3', '.wav', '.ogg', '.flac', '.m4a', '.mp4', '.webm', '.mov']);
18
+ /** Shell languages, compared on the info string's first part: `bash-session`, `zsh_session`, `sh+x` count as their shell. */
19
+ const SHELL_LANGUAGES = new Set(['sh', 'bash', 'shell', 'zsh', 'fish', 'ksh', 'csh', 'tcsh', 'dash', 'ash', 'console', 'shellsession', 'shellscript', 'terminal', 'powershell', 'ps1', 'pwsh', 'cmd', 'bat', 'batch', 'nushell', 'nu']);
20
+ const isShellLanguage = (info) => SHELL_LANGUAGES.has(info.toLowerCase().split(/[-_+.:]/u)[0]);
21
+ // Indentation, blockquote markers and list markers (`-`, `*`, `+`, `1.`, `1)`), then the fence, then `bash`, `{bash}` or `{.bash ...}`.
22
+ // The three prefix alternatives start with different characters, so the pattern stays linear.
23
+ const fenceOpenPattern = /^(?:[ \t>]|[-*+][ \t]|[0-9]{1,9}[.)][ \t])*(`{3,}|~{3,})[ \t]*\{?\.?([A-Za-z0-9_+.:-]*)/u;
24
+ /** Bracketed IPv6 hosts, which the shared origin scan in diff.ts does not match. */
25
+ const ipv6UrlPattern = /https?:\/\/\[[0-9A-Fa-f:.]{2,45}\](?::[0-9]{1,5})?/gu;
26
+ const MAX_IPV6_HOSTS = 128;
27
+ // Brackets kept, so a bracketed IPv6 host after a backslash stays in the candidate.
28
+ const urlCandidatePattern = /https?:\/\/[^\s"'`<>(){}]+/giu;
29
+ const plainHostPattern = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/u;
30
+ /**
31
+ * The host another URL parser reads from an address with a backslash. WHATWG (used above) treats `\` like `/`, so
32
+ * `https://api.github.com\@evil.example/` is api.github.com there; Python's urlparse and others read evil.example.
33
+ * Both are listed.
34
+ */
35
+ function backslashHost(candidate) {
36
+ if (!candidate.includes('\\'))
37
+ return null;
38
+ const rest = candidate.slice(candidate.indexOf('://') + 3);
39
+ const end = rest.search(/[/?#]/u);
40
+ const authority = end < 0 ? rest : rest.slice(0, end);
41
+ let host = authority.slice(authority.lastIndexOf('@') + 1).replace(/:[0-9]*$/u, '');
42
+ try {
43
+ host = decodeURIComponent(host);
44
+ }
45
+ catch {
46
+ // Not valid percent-encoding: keep the text as it is.
47
+ }
48
+ host = host.toLowerCase().replace(/\.$/u, '');
49
+ if (/^\[[0-9a-f:.]+\]$/u.test(host)) {
50
+ try {
51
+ return new URL(`http://${host}/`).hostname;
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ }
57
+ return plainHostPattern.test(host) ? host : null;
58
+ }
59
+ const programPattern = /^[A-Za-z0-9._+-]{1,64}$/u;
60
+ const PREFIX_WORDS = new Set(['sudo', 'doas', 'env', 'exec', 'time', 'nohup', 'command', 'builtin', 'then', 'do', 'else', '!']);
61
+ const extension = (file) => path.posix.extname(file).toLowerCase();
62
+ /** Counts lines that open a shell code block. No open/close tracking: a crafted pairing can never hide a block. */
63
+ function shellFenceCount(text) {
64
+ let count = 0;
65
+ for (const line of text.split(/\r?\n|\r/u)) {
66
+ const match = fenceOpenPattern.exec(line);
67
+ if (match && isShellLanguage(match[2]))
68
+ count += 1;
69
+ }
70
+ return count;
71
+ }
72
+ /** Programs named first on each command line of shell code blocks. Report-only, so open/close tracking is fine here. */
73
+ function shellPrograms(text, into) {
74
+ let open = null;
75
+ for (const line of text.split(/\r?\n|\r/u)) {
76
+ const fence = fenceOpenPattern.exec(line);
77
+ if (open) {
78
+ if (fence && fence[1][0] === open.char && fence[1].length >= open.length && fence[2] === '') {
79
+ open = null;
80
+ continue;
81
+ }
82
+ if (!open.shell)
83
+ continue;
84
+ let words = line.replace(/^(?:[ \t>]|[-*+][ \t]|[0-9]{1,9}[.)][ \t])*/u, '').replace(/^(?:\$|PS>|>|%)[ \t]+/u, '').split(/[ \t]+/u).filter(Boolean);
85
+ while (words.length > 0 && (PREFIX_WORDS.has(words[0]) || /^[A-Za-z_][A-Za-z0-9_]*=/u.test(words[0])))
86
+ words = words.slice(1);
87
+ const first = words[0];
88
+ if (first === undefined || first.startsWith('#'))
89
+ continue;
90
+ const name = path.posix.basename(first);
91
+ if (programPattern.test(name) && into.size < MAX_PROGRAMS)
92
+ into.add(name);
93
+ continue;
94
+ }
95
+ if (fence)
96
+ open = { char: fence[1][0], length: fence[1].length, shell: isShellLanguage(fence[2]) };
97
+ }
98
+ }
99
+ function scriptReason(file, exec, content, text) {
100
+ if (exec)
101
+ return 'executable file';
102
+ if (content.subarray(0, 2).toString('latin1') === '#!')
103
+ return 'starts with #!';
104
+ if (SCRIPT_EXTENSIONS.has(extension(file)))
105
+ return `${extension(file)} file`;
106
+ if (SCRIPT_NAMES.has(path.posix.basename(file).toLowerCase()))
107
+ return 'build or task file';
108
+ if (text !== null && MARKDOWN_EXTENSIONS.has(extension(file))) {
109
+ const fences = shellFenceCount(text);
110
+ if (fences > 0)
111
+ return `${fences} shell code block${fences === 1 ? '' : 's'}`;
112
+ }
113
+ return null;
114
+ }
115
+ /** The profile of a tree read with `collectSkillTree(dir, { includeContents: true })`. */
116
+ export function profileTree(tree) {
117
+ const contents = tree.contents;
118
+ const searched = new Map();
119
+ const media = [];
120
+ const unreadable = [];
121
+ const scripts = [];
122
+ const programs = new Set();
123
+ for (const file of tree.files) {
124
+ const content = contents.get(file.path);
125
+ const searchable = content.length <= MAX_SEARCHED_BYTES && !content.includes(0) && isUtf8(content);
126
+ if (!searchable)
127
+ (MEDIA_EXTENSIONS.has(extension(file.path)) ? media : unreadable).push(file.path);
128
+ if (searchable)
129
+ searched.set(file.path, content);
130
+ const text = searchable ? content.toString('utf8') : null;
131
+ const reason = scriptReason(file.path, file.exec, content, text);
132
+ if (reason)
133
+ scripts.push({ path: file.path, reason });
134
+ if (text !== null && MARKDOWN_EXTENSIONS.has(extension(file.path)))
135
+ shellPrograms(text, programs);
136
+ }
137
+ const ignored = pathsNotCovered(tree.excluded);
138
+ // Only searchable files go in, so an incomplete scan means a limit was hit (sites or addresses).
139
+ const origins = collectOrigins(searched);
140
+ const hosts = new Set(origins.origins.map((origin) => new URL(origin).hostname));
141
+ let limitHit = !origins.complete;
142
+ scan: for (const content of searched.values()) {
143
+ const text = content.toString('utf8');
144
+ if (text.includes('\\')) {
145
+ for (const match of text.matchAll(urlCandidatePattern)) {
146
+ const host = backslashHost(match[0]);
147
+ if (host)
148
+ hosts.add(host);
149
+ if (hosts.size > origins.origins.length + MAX_IPV6_HOSTS) {
150
+ limitHit = true;
151
+ break scan;
152
+ }
153
+ }
154
+ }
155
+ for (const match of text.matchAll(ipv6UrlPattern)) {
156
+ let host;
157
+ try {
158
+ host = new URL(match[0]).hostname;
159
+ }
160
+ catch {
161
+ continue;
162
+ }
163
+ hosts.add(host);
164
+ if (hosts.size > origins.origins.length + MAX_IPV6_HOSTS) {
165
+ limitHit = true;
166
+ break scan;
167
+ }
168
+ }
169
+ }
170
+ return {
171
+ profile: PROFILE_FORMAT,
172
+ digest: tree.digest,
173
+ web_hosts: [...hosts].sort(),
174
+ scripts,
175
+ programs: [...programs].sort(),
176
+ not_searched: { media, unreadable, ignored },
177
+ complete: !limitHit && unreadable.length === 0 && ignored.length === 0,
178
+ };
179
+ }
180
+ export async function observeSkill(skillDir) {
181
+ return profileTree(await collectSkillTree(skillDir, { includeContents: true }));
182
+ }