@mago-foundation/mago-ski 0.4.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.
@@ -161,6 +161,7 @@ async function listen(server, file, mode) {
161
161
  await unlink(file);
162
162
  }
163
163
  await new Promise((resolve, reject) => { server.once('error', reject); server.listen(file, 4096, () => { server.off('error', reject); resolve(); }); });
164
+ // nosemgrep: mago-no-path-chown-chmod -- the service's own socket, just made by listen() in a root-owned socket folder
164
165
  await chmod(file, mode);
165
166
  }
166
167
  /** One request line per connection: read to the first newline (bounded, idle deadline), reply with one line, close. Anything else just closes. */
@@ -653,9 +654,11 @@ export function createGateService(config) {
653
654
  /** Removes a generation this install just created (sealed read-only folders need their mode back first). */
654
655
  async function removeGeneration(name, digest) {
655
656
  const gen = path.join(generationsDir, name, hex(digest));
657
+ // nosemgrep: mago-no-path-chown-chmod -- a generation inside the root-owned generation store, being removed
656
658
  for (const e of await readdir(gen, { recursive: true, withFileTypes: true }).catch(() => []))
657
659
  if (e.isDirectory())
658
660
  await chmod(path.join(e.parentPath, e.name), 0o755).catch(() => { });
661
+ // nosemgrep: mago-no-path-chown-chmod -- a generation inside the root-owned generation store, being removed
659
662
  await chmod(gen, 0o755).catch(() => { });
660
663
  await rm(gen, { recursive: true, force: true });
661
664
  await rm(`${gen}.manifest.json`, { force: true });
@@ -67,9 +67,9 @@ export interface InitOptions extends Seams {
67
67
  /** `--new-root`: the installed instance pins a different root and the administrator means to replace it (design gate-new-root.md N2). */
68
68
  newRoot?: boolean;
69
69
  /** Tests: sets the immutable attribute on a path (default `chattr +i`). A failure stops the command. */
70
- chattr?: (target: string) => Promise<void>;
70
+ chattr?: (target: string, via?: string) => Promise<void>;
71
71
  /** Tests: reads the immutable attribute (default `lsattr -d`). */
72
- isImmutable?: (target: string) => Promise<boolean>;
72
+ isImmutable?: (target: string, via?: string) => Promise<boolean>;
73
73
  now?: () => Date;
74
74
  }
75
75
  export type FileRole = 'instance' | 'hook' | 'unit' | 'dropin' | 'host' | 'managed-config' | 'manifest' | 'shared-manifest';
@@ -149,8 +149,8 @@ export interface ApplyOptions {
149
149
  base?: string;
150
150
  rootUid?: number;
151
151
  now?: () => Date;
152
- chattr?: (target: string) => Promise<void>;
153
- isImmutable?: (target: string) => Promise<boolean>;
152
+ chattr?: (target: string, via?: string) => Promise<void>;
153
+ isImmutable?: (target: string, via?: string) => Promise<boolean>;
154
154
  }
155
155
  export interface ApplyResult {
156
156
  written: string[];
@@ -190,7 +190,7 @@ export interface DoctorOptions extends Seams {
190
190
  /** Codex: the output of `codex --version` for a host binary (default: runs it). */
191
191
  codexVersion?: (exe: string) => Promise<string>;
192
192
  /** Codex: the immutable attribute of a path (default `lsattr -d`). */
193
- isImmutable?: (target: string) => Promise<boolean>;
193
+ isImmutable?: (target: string, via?: string) => Promise<boolean>;
194
194
  /** Tests: smaller bounds for the scan of the listed homes. */
195
195
  skillScanLimits?: SkillScanLimits;
196
196
  }
@@ -4,7 +4,7 @@
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';
@@ -170,6 +170,7 @@ async function chooseHomes(opts, problems) {
170
170
  if (opts.userHomes && opts.userHomes.length > 0)
171
171
  return [...new Set(opts.userHomes.map((h) => cleanDir(h, '--user-home', problems)).filter((h) => h !== undefined))];
172
172
  const out = [];
173
+ // nosemgrep: mago-no-raw-read-of-signed-input -- the system user list, read as root to choose the homes
173
174
  const text = await readFile(path.join(opts.base ?? '/', 'etc', 'passwd'), 'utf8').catch(() => '');
174
175
  for (const line of text.split('\n')) {
175
176
  const f = line.split(':');
@@ -184,12 +185,38 @@ async function chooseHomes(opts, problems) {
184
185
  }
185
186
  return out;
186
187
  }
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()));
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()));
189
192
  });
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))));
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))));
192
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
+ }
193
220
  /** `.system` moves (F5, F7.6) and, with `--lock-user-skill-folders`, the lock of each listed home (E1). Refusals go to `problems`. */
194
221
  async function planHomeActions(homes, opts, problems) {
195
222
  const out = [];
@@ -216,6 +243,12 @@ async function planHomeActions(homes, opts, problems) {
216
243
  problems.push(`${home} is not a folder; cannot lock its Skill folders`);
217
244
  continue;
218
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
+ }
219
252
  for (const dir of [`${home}/.agents/skills`, `${home}/.codex/skills`]) {
220
253
  const entries = await readdir(dir).catch(() => []);
221
254
  const left = entries.filter((e) => !(dir.endsWith('/.codex/skills') && e === '.system'));
@@ -234,27 +267,17 @@ async function planHomeActions(homes, opts, problems) {
234
267
  * folder swapped for a link after the check changes nothing. `.system` itself must be a real folder inside the open handle.
235
268
  */
236
269
  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));
270
+ const skills = await pinFolder(path.dirname(from), '.system was not moved');
248
271
  try {
249
272
  const backupDir = path.dirname(to);
250
273
  await mkdir(backupDir, { mode: 0o755 }).catch((e) => { if (errnoCode(e) !== 'EEXIST')
251
274
  throw e; });
252
- const backup = await pinned(backupDir);
275
+ const backup = await pinFolder(backupDir, '.system was not moved');
253
276
  try {
254
- const source = `/proc/self/fd/${skills.fd}/${path.basename(from)}`;
277
+ const source = viaHandle(skills, path.basename(from));
255
278
  if (!(await lstat(source)).isDirectory())
256
279
  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
280
+ await rename(source, viaHandle(backup, path.basename(to))); // rename never follows a link in the last part
258
281
  }
259
282
  finally {
260
283
  await backup.close();
@@ -264,6 +287,53 @@ async function moveSystemFolder(from, to) {
264
287
  await skills.close();
265
288
  }
266
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
+ }
267
337
  /** Plan: moves first, then locks. Each move needs the target folder free. */
268
338
  async function runHomeActions(actions, opts, rootUid) {
269
339
  const moved = [];
@@ -277,36 +347,9 @@ async function runHomeActions(actions, opts, rootUid) {
277
347
  const chattr = opts.chattr ?? defaultChattr;
278
348
  const isImmutable = opts.isImmutable ?? defaultIsImmutable;
279
349
  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
- }
350
+ for (const a of actions)
351
+ if (a.kind === 'lock')
352
+ locked.push(...await lockHome(a, rootUid, gid, chattr, isImmutable));
310
353
  return { moved, locked };
311
354
  }
312
355
  export function unitText(tc) {
@@ -464,6 +507,7 @@ export async function planInit(opts) {
464
507
  continue;
465
508
  let ours = false;
466
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
467
511
  const h = sha256(await readFile(f.path));
468
512
  ours = own?.get(f.path) === h || sharedOwn?.get(f.path) === h;
469
513
  }
@@ -697,6 +741,7 @@ export async function doctor(host, opts = {}) {
697
741
  // Host config and hook config: exact content of what `gate init` would write now.
698
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.
699
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
700
745
  const denyRoots = host === 'codex' && /^deny_read = /mu.test(await readFile(p.hostConfig, 'utf8').catch(() => '')) ? codexDenyRoots(homes) : [];
701
746
  const hookExpected = hookConfigText(host, c, homes);
702
747
  let hostFileMode;
@@ -705,6 +750,7 @@ export async function doctor(host, opts = {}) {
705
750
  const info = await lstat(p.hostConfig);
706
751
  if (!info.isFile() || info.uid !== uid || (info.mode & 0o022) !== 0)
707
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
708
754
  const have = sha256(await readFile(p.hostConfig));
709
755
  if (have === sha256(expected)) {
710
756
  hostFileMode = c.mode;
@@ -729,6 +775,7 @@ export async function doctor(host, opts = {}) {
729
775
  for (const [label, file, expected] of [['unit', p.unit, unitText(tc)], ['drop-in', p.dropin, dropinText(c, p.stateRoot)]]) {
730
776
  try {
731
777
  await trustedRegularFile(file, uid);
778
+ // nosemgrep: mago-no-raw-read-of-signed-input -- doctor: checked just above by trustedRegularFile
732
779
  if (sha256(await readFile(file)) !== sha256(expected))
733
780
  throw new Error(`${file} differs from what gate init would write now; run gate init again`);
734
781
  add(label, 'PASS', `${file} matches what gate init writes`);
@@ -739,6 +786,7 @@ export async function doctor(host, opts = {}) {
739
786
  }
740
787
  try {
741
788
  await trustedRegularFile(p.hook, uid);
789
+ // nosemgrep: mago-no-raw-read-of-signed-input -- doctor: checked just above by trustedRegularFile
742
790
  if (sha256(await readFile(p.hook)) !== sha256(hookExpected))
743
791
  throw new Error(`${p.hook} differs from what gate init would write now; run gate init again`);
744
792
  add('hook config', 'PASS', `${p.hook} matches what gate init writes`);
@@ -851,6 +899,7 @@ export async function doctor(host, opts = {}) {
851
899
  /* ---------------------------------------------------------------------------------------------- Codex doctor checks */
852
900
  async function readHookHomes(file) {
853
901
  try {
902
+ // nosemgrep: mago-no-raw-read-of-signed-input -- the root-owned hook config; doctor checks its ownership and content separately
854
903
  const raw = parseStrictJson(await readFile(file));
855
904
  if (!isRecord(raw))
856
905
  return undefined;
@@ -912,6 +961,7 @@ async function codexDoctor(c, p, homes, uid, opts, add) {
912
961
  const info = await lstat(file);
913
962
  if (!info.isFile() || info.uid !== uid || (info.mode & 0o022) !== 0)
914
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
915
965
  if (sha256(await readFile(file)) !== sha256(codexManagedConfigToml()))
916
966
  throw new Error(`${file} differs from what gate init would write now; run gate init again`);
917
967
  add('managed config', 'PASS', `${file} matches what gate init writes`);
@@ -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);
@@ -372,8 +372,10 @@ export async function adoptTrustDocuments(options) {
372
372
  const root = await loadPrivateKey(options.rootKeyPath);
373
373
  if (root.keyId === options.fromRootKeyId)
374
374
  throw new Error('The new root key is the same as the current one; nothing to adopt');
375
- const currentTrust = readTrustRootForUpdate(await readRegularFile(options.trustRootPath, 'Trust root', 4 * 1024 * 1024), options.fromRootKeyId);
376
- const currentList = readRevocationsForUpdate(await readRegularFile(options.revocationsPath, 'Revocation list', 8 * 1024 * 1024), options.fromRootKeyId, currentTrust.root.publicKey);
375
+ const trustRead = await readRegularFile(options.trustRootPath, 'Trust root', 4 * 1024 * 1024);
376
+ const listRead = await readRegularFile(options.revocationsPath, 'Revocation list', 8 * 1024 * 1024);
377
+ const currentTrust = readTrustRootForUpdate(trustRead, options.fromRootKeyId);
378
+ const currentList = readRevocationsForUpdate(listRead, options.fromRootKeyId, currentTrust.root.publicKey);
377
379
  if (currentTrust.approvers.some((approver) => approver.keyId === root.keyId))
378
380
  throw new Error('The new root key is listed as an approver; remove it first');
379
381
  const issuedAt = truncateToSecond(options.now);
@@ -393,8 +395,9 @@ export async function adoptTrustDocuments(options) {
393
395
  };
394
396
  const trustBytes = signTrustRoot(trustRoot, root.privateKey);
395
397
  const listBytes = signRevocations(revocations, root.privateKey);
396
- await writeFileAtomic(options.trustRootPath, trustBytes);
397
- await writeFileAtomic(options.revocationsPath, listBytes);
398
+ // Each file is replaced only if it is still the one that was read and re-signed (like every other root write).
399
+ await writeFileAtomic(options.trustRootPath, trustBytes, undefined, { expectSha256: `sha256:${sha256Hex(trustRead)}` });
400
+ await writeFileAtomic(options.revocationsPath, listBytes, undefined, { expectSha256: `sha256:${sha256Hex(listRead)}` });
398
401
  return { trustRoot, trustRootVersion: trustRoot.version, revocationsVersion: revocations.version };
399
402
  }
400
403
  export { recoverySetJson };
@@ -95,6 +95,8 @@ export declare function parseRootEventLog(bytes: Uint8Array): Array<MultiEnvelop
95
95
  /**
96
96
  * Walks the root event log from the policy's starting point. Throws (the log is UNVERIFIABLE) if any event after
97
97
  * `eventsAfter` breaks a rule; events are never skipped. Hashes every event so rollback and fork checks can use them.
98
+ * Keys that left a role in the events before `eventsAfter` are read without checking signatures and used only to refuse
99
+ * (see keysLeftBeforeStart).
98
100
  */
99
101
  export declare function walkRootEvents(bytes: Uint8Array, start: RootStart, now: Date): RootWalk;
100
102
  /**
@@ -2,7 +2,7 @@
2
2
  // policy, signs numbered root events that revoke or replace the root key. Hosts walk the log from the policy's
3
3
  // starting point at every trust check; one event that breaks a rule makes the whole log UNVERIFIABLE.
4
4
  import { sign, verify } from 'node:crypto';
5
- import { canonicalBytes, exactKeys, isRecord, parseCanonicalJsonBytes, requireArray, requirePositiveInteger, requireString } from "./canonical-json.js";
5
+ import { canonicalBytes, exactKeys, isRecord, readableCanonicalBytes, parseCanonicalJsonBytes, requireArray, requirePositiveInteger, requireString } from "./canonical-json.js";
6
6
  import { preAuthEncoding } from "./dsse.js";
7
7
  import { parseSpki, validateKeyId } from "./keys.js";
8
8
  import { CLOCK_SKEW_MS, formatTimestamp, parseTimestamp, requireValidDate } from "./time.js";
@@ -177,7 +177,7 @@ export function emptyRootEventLog() {
177
177
  return canonicalBytes({ events: [], type: ROOT_EVENTS_TYPE });
178
178
  }
179
179
  export function rootEventLogBytes(envelopes) {
180
- return canonicalBytes({ events: envelopes, type: ROOT_EVENTS_TYPE });
180
+ return readableCanonicalBytes({ events: envelopes, type: ROOT_EVENTS_TYPE }, 'The root event log');
181
181
  }
182
182
  /** `sha256:` + the SHA-256 of the envelope as canonical JSON with its trailing LF (the host state's event_digest). */
183
183
  export function eventDigest(envelope) {
@@ -307,9 +307,65 @@ function applyEvent(state, envelope, sequence, now) {
307
307
  }
308
308
  return next;
309
309
  }
310
+ /**
311
+ * Keys that left a role in the events before `root_events_after`. Those events are not checked (the policy pins the
312
+ * state after them, not the keys that signed them), so what they say is used only to refuse: a key named here can never
313
+ * be an approver or take a role in a walked event, and nothing is ever accepted because of them. Someone who can change
314
+ * the log can make a host refuse more, which they can already do by deleting the log; with freshness, the timestamp
315
+ * covers the whole file anyway. An event here that retires a key the policy pins contradicts the policy and throws.
316
+ */
317
+ function keysLeftBeforeStart(envelopes, start) {
318
+ const retired = new Set();
319
+ const formerRecovery = new Set();
320
+ let recovery = null;
321
+ let timestampKeyId = null;
322
+ for (let index = 0; index < start.eventsAfter; index += 1) {
323
+ const label = `root event ${index + 1} (before root_events_after)`;
324
+ const envelope = envelopes[index];
325
+ if (envelope.payloadType !== ROOT_EVENT_PAYLOAD_TYPE)
326
+ throw new Error(`${label} has the wrong payload type`);
327
+ let event;
328
+ try {
329
+ event = parseRootEventPayload(envelope.payloadBytes);
330
+ }
331
+ catch (error) {
332
+ throw new Error(`${label}: ${error.message}`);
333
+ }
334
+ if (event.sequence !== index + 1)
335
+ throw new Error(`${label} carries sequence ${event.sequence}`);
336
+ if (event.action === 'revoke') {
337
+ retired.add(event.rootKeyId);
338
+ continue;
339
+ }
340
+ const newRecovery = event.newRecovery.keyIds;
341
+ if (event.newRoot.keyId !== event.rootKeyId)
342
+ retired.add(event.rootKeyId);
343
+ if (event.newTimestamp) {
344
+ if (timestampKeyId !== null && timestampKeyId !== event.newTimestamp.keyId)
345
+ retired.add(timestampKeyId);
346
+ timestampKeyId = event.newTimestamp.keyId;
347
+ }
348
+ // Signers not in the new set come from the set this event replaces, as does every key of an earlier new set.
349
+ for (const keyId of [...event.signers.map((key) => key.keyId), ...(recovery ?? [])])
350
+ if (!newRecovery.includes(keyId))
351
+ formerRecovery.add(keyId);
352
+ recovery = newRecovery;
353
+ }
354
+ for (const keyId of recovery ?? [])
355
+ if (!start.recovery.keyIds.includes(keyId))
356
+ formerRecovery.add(keyId);
357
+ for (const keyId of retired) {
358
+ const pinned = keyId === start.rootKeyId ? 'root' : keyId === start.timestampKeyId ? 'timestamp' : start.recovery.keyIds.includes(keyId) ? 'recovery' : null;
359
+ if (pinned)
360
+ throw new Error(`the events before root_events_after show key ${keyId} leaving the root or timestamp role, but the policy pins it as the ${pinned} key`);
361
+ }
362
+ return { retired, formerRecovery };
363
+ }
310
364
  /**
311
365
  * Walks the root event log from the policy's starting point. Throws (the log is UNVERIFIABLE) if any event after
312
366
  * `eventsAfter` breaks a rule; events are never skipped. Hashes every event so rollback and fork checks can use them.
367
+ * Keys that left a role in the events before `eventsAfter` are read without checking signatures and used only to refuse
368
+ * (see keysLeftBeforeStart).
313
369
  */
314
370
  export function walkRootEvents(bytes, start, now) {
315
371
  requireValidDate(now, 'Verification time');
@@ -317,13 +373,14 @@ export function walkRootEvents(bytes, start, now) {
317
373
  const envelopes = parseRootEventLog(bytes);
318
374
  if (envelopes.length < start.eventsAfter)
319
375
  throw new Error(`root event log has ${envelopes.length} event(s), fewer than root_events_after (${start.eventsAfter})`);
376
+ const before = keysLeftBeforeStart(envelopes, start);
320
377
  let state = {
321
378
  activeRootKeyId: start.rootKeyId,
322
379
  recovery: start.recovery,
323
380
  timestampKeyId: start.timestampKeyId,
324
381
  revoked: null,
325
- retired: new Set(),
326
- formerRecovery: new Set(),
382
+ retired: before.retired,
383
+ formerRecovery: before.formerRecovery,
327
384
  lastIssuedAt: null,
328
385
  };
329
386
  for (let index = start.eventsAfter; index < envelopes.length; index += 1)
@@ -2,6 +2,12 @@ import { type BigIntStats } from 'node:fs';
2
2
  export declare const TREE_PROFILE = "mago.skill-tree/v2";
3
3
  export declare const CERTIFICATE_FILENAME = ".mago-ski-cert.json";
4
4
  export declare const IGNORE_FILENAME = ".skilldigestignore";
5
+ /**
6
+ * The paths a `.skilldigestignore` keeps out of the digest (the built-in exclusions, `.git/` and the certificate file, are
7
+ * left out). A certificate says nothing about these: they can change, or be added, without invalidating it. Every command
8
+ * that tells a person "approved" or "unchanged" must show them.
9
+ */
10
+ export declare function pathsNotCovered(excluded: readonly string[]): string[];
5
11
  /** Always covered: it holds the instructions and the description hosts show the model. */
6
12
  export declare const SKILL_FILENAME = "SKILL.md";
7
13
  export declare const MAX_TREE_FILES = 20000;
@@ -6,6 +6,14 @@ import { canonicalBytes } from "./canonical-json.js";
6
6
  export const TREE_PROFILE = 'mago.skill-tree/v2';
7
7
  export const CERTIFICATE_FILENAME = '.mago-ski-cert.json';
8
8
  export const IGNORE_FILENAME = '.skilldigestignore';
9
+ /**
10
+ * The paths a `.skilldigestignore` keeps out of the digest (the built-in exclusions, `.git/` and the certificate file, are
11
+ * left out). A certificate says nothing about these: they can change, or be added, without invalidating it. Every command
12
+ * that tells a person "approved" or "unchanged" must show them.
13
+ */
14
+ export function pathsNotCovered(excluded) {
15
+ return excluded.filter((item) => item !== '.git/' && item !== CERTIFICATE_FILENAME);
16
+ }
9
17
  /** Always covered: it holds the instructions and the description hosts show the model. */
10
18
  export const SKILL_FILENAME = 'SKILL.md';
11
19
  export const MAX_TREE_FILES = 20_000;
@@ -274,7 +274,7 @@ The renderer cannot name a file, a key or a directory in any of them. A compromi
274
274
  - **The user-namespace check is a hurdle**, not a boundary (see [Organisation pin](#organisation-pin)); Flatpak, rootless containers and user-namespace CI runners are unsupported.
275
275
  - **A copy or hard link of the key inside a Skill is not detected.** A moved key fails the stored-path check at signing. The private-key scan at signing covers the files the digest covers, as in the CLI.
276
276
  - **The memory does not protect against the user** (see above).
277
- - **Retired keys are known only from walked events.** A key retired before `root_events_after` is not known to a host or to the GUI. The host check refuses a trust root that lists a key retired in the events the host walked (`trust root lists approver <id>, which has held the root or timestamp role; a key that left those roles never takes another`); the gate's trust store (`src/gate/trust-store.ts`) calls `loadTrustContext` directly and does not check this.
277
+ - **Retired keys come from the whole log.** A key retired in a walked event, or shown leaving a role in an event before `root_events_after` (read without checking its signatures, and used only to refuse), is retired. The host check refuses a trust root that lists such a key (`trust root lists approver <id>, which has held the root or timestamp role; a key that left those roles never takes another`); the gate's trust store (`src/gate/trust-store.ts`) calls `loadTrustContext` directly and does not check this.
278
278
  - **Former recovery keys.** The GUI and `root add-approver --policy` refuse a key that left a recovery set in the walked events as an approver; hosts do not check this. For former recovery keys, no host refuses a document it accepted before. While a former recovery key is listed as an approver, the GUI marks it and allows only removing it, hosts keep accepting the trust root, and `root renew` and `root remove-approver` in the CLI do not check it.
279
279
  - **Upgrade note for retired keys.** The host check for retired root and timestamp keys is the one deliberate exception to "no host refuses a document it accepted before":
280
280
 
@@ -171,7 +171,7 @@ Let *current set* be the recovery set in force just before the event.
171
171
  - `new_root.key_id` must not be any key that an earlier event revoked or replaced. A key that has left the root role never returns.
172
172
  - `new_root.key_id` may equal `root_key_id` only if that key is not revoked. This changes the recovery set or the timestamp key without changing the root (for example, when a trustee leaves or the timestamp key leaks).
173
173
  - `new_timestamp.key_id` must not be the current or new root key, must not be in the current or new recovery set, and must not be a timestamp key that an earlier event replaced.
174
- - `new_root.key_id` must not be the current or new timestamp key, and `new_recovery` must not contain the current root key, the current timestamp key, or any key that an earlier event revoked or replaced. **A key that has left the root or timestamp role never takes any role again**, so a leaked key cannot come back as a recovery key. Hosts only know the keys replaced by events they walk (after `root_events_after`).
174
+ - `new_root.key_id` must not be the current or new timestamp key, and `new_recovery` must not contain the current root key, the current timestamp key, or any key that an earlier event revoked or replaced. **A key that has left the root or timestamp role never takes any role again**, so a leaked key cannot come back as a recovery key. Events before `root_events_after` are not checked, but hosts still read which keys they show leaving a role and treat those keys as retired (see [Host processing](#host-processing)).
175
175
 
176
176
  ### Rules for a revoke
177
177
 
@@ -245,6 +245,7 @@ At every trust check, before reading the trust root, a host with a v2 recovery p
245
245
 
246
246
  1. Starts from the policy: *active root* = `root_fingerprint`, *recovery set* = `recovery`, *timestamp key* = `freshness.key_id`, *revoked* = false.
247
247
  2. Reads `root_events`. A missing, malformed or oversized log is `UNVERIFIABLE`.
248
+ - **Events before `root_events_after` are read, not checked.** The policy pins the state after them, not the keys that signed them, so their signatures and rules are not checked and nothing is ever accepted because of them. The host reads only which keys they show leaving a role, and uses that only to refuse: the root key a revoke names, the root key a rotate replaces with another key, a timestamp key that a later event replaces, and a recovery key that a rotate leaves out of `new_recovery` count as retired or former recovery keys for the rest of the walk and for the trust root check. Someone who can change these events can only make a host refuse more, which they can already do by deleting the log; with `freshness`, the timestamp covers the whole file. An event there with the wrong payload type, a payload that does not parse, or the wrong `sequence`, and an event there that retires a key the policy pins (`the events before root_events_after show key <id> leaving the root or timestamp role, but the policy pins it as the <role> key`), make the log `UNVERIFIABLE`.
248
249
  3. For each event after the first `root_events_after`, in order, checks every rule above against the current state, then applies it:
249
250
  - revoke: *revoked* = true.
250
251
  - rotate: *active root* = `new_root.key_id`, *recovery set* = `new_recovery`, *timestamp key* = `new_timestamp.key_id` if present, *revoked* = false.
@@ -258,7 +259,7 @@ Walking the full log keeps hosts without state correct, but hosts load trust doc
258
259
  2. Check rollback and forks against the host state. Otherwise `UNVERIFIABLE`.
259
260
  3. If the active root is revoked, every Skill is blocked: see [Revoked root](#revoked-root-blocked-in-every-mode). Nothing else is read.
260
261
  4. With `freshness`, check the timestamp against the files. Otherwise `UNVERIFIABLE`.
261
- 5. Check the trust root and the revocation list as in v1, except that they must be signed by the **active root** instead of `root_fingerprint`. The trust root is also `UNVERIFIABLE` if any approver's key is in the active recovery set, is the active timestamp key, or is a key that has held the root or timestamp role in the walked events (`trust root lists approver <id>, which has held the root or timestamp role; a key that left those roles never takes another`). Only events after `root_events_after` are walked, so only keys retired in them are known. Hosts do not refuse a former recovery key listed as an approver; the GUI and `root add-approver --policy` refuse it as a new approver. The gate trust store (`src/gate/trust-store.ts`) does not run this check.
262
+ 5. Check the trust root and the revocation list as in v1, except that they must be signed by the **active root** instead of `root_fingerprint`. The trust root is also `UNVERIFIABLE` if any approver's key is in the active recovery set, is the active timestamp key, or is a key that has held the root or timestamp role in the walked events (`trust root lists approver <id>, which has held the root or timestamp role; a key that left those roles never takes another`). Keys shown leaving a role in the events before `root_events_after` count too (see [Walking the log](#walking-the-log)). Hosts do not refuse a former recovery key listed as an approver; the GUI and `root add-approver --policy` refuse it as a new approver. The gate trust store (`src/gate/trust-store.ts`) does not run this check.
262
263
 
263
264
  Before upgrading hosts, an organisation removes such approvers; see the upgrade note in the CHANGELOG.
264
265
  6. Record the new state.
@@ -24,7 +24,7 @@ An organization's trust is anchored in one **root key**, kept offline. Hosts pin
24
24
 
25
25
  - `version`: positive integer, increased on every change. Hosts with a configured state file reject versions lower than those recorded there.
26
26
  - `root.public_key` must hash to `root.key_id`, which must equal the pinned fingerprint and the envelope's `keyid`.
27
- - `approvers`: sorted by `key_id`, unique, at most 256. The root key may not also be an approver. With root recovery, a host also refuses (`UNVERIFIABLE`) a trust root that lists an approver whose key has held the root or timestamp role in the root events the host walked: `trust root lists approver <id>, which has held the root or timestamp role; a key that left those roles never takes another`. Only keys retired in events after `root_events_after` are known, and the gate trust store does not check it. Before upgrading, remove such approvers (see the CHANGELOG).
27
+ - `approvers`: sorted by `key_id`, unique, at most 256. The root key may not also be an approver. With root recovery, a host also refuses (`UNVERIFIABLE`) a trust root that lists an approver whose key has held the root or timestamp role in the root events the host walked: `trust root lists approver <id>, which has held the root or timestamp role; a key that left those roles never takes another`. Keys shown leaving a role in events before `root_events_after` count too; the gate trust store does not check it. Before upgrading, remove such approvers (see the CHANGELOG).
28
28
  - `scopes`: sorted, unique, 1–64 per approver. `*` matches every Skill name; `prefix*` matches names starting with `prefix`; anything else matches one exact name.
29
29
 
30
30
  ## Revocation list