@mago-foundation/mago-ski 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +30 -3
  2. package/dist/hosts/github/run.d.ts +3 -1
  3. package/dist/hosts/github/run.js +29 -9
  4. package/dist/hosts/pi/index.js +48 -5
  5. package/dist/src/admin.d.ts +136 -1
  6. package/dist/src/admin.js +221 -84
  7. package/dist/src/cli.js +335 -10
  8. package/dist/src/fs-safe.d.ts +15 -2
  9. package/dist/src/fs-safe.js +32 -3
  10. package/dist/src/gate/adapters/claude-code-hook.d.ts +1 -0
  11. package/dist/src/gate/adapters/claude-code-hook.js +4 -0
  12. package/dist/src/gate/adapters/claude-code-settings.d.ts +13 -0
  13. package/dist/src/gate/adapters/claude-code-settings.js +49 -0
  14. package/dist/src/gate/adapters/claude-code.d.ts +33 -0
  15. package/dist/src/gate/adapters/claude-code.js +193 -0
  16. package/dist/src/gate/adapters/client.d.ts +13 -0
  17. package/dist/src/gate/adapters/client.js +57 -0
  18. package/dist/src/gate/adapters/codex-hook.d.ts +1 -0
  19. package/dist/src/gate/adapters/codex-hook.js +5 -0
  20. package/dist/src/gate/adapters/codex-requirements.d.ts +19 -0
  21. package/dist/src/gate/adapters/codex-requirements.js +56 -0
  22. package/dist/src/gate/adapters/codex.d.ts +16 -0
  23. package/dist/src/gate/adapters/codex.js +574 -0
  24. package/dist/src/gate/adapters/hook-main.d.ts +7 -0
  25. package/dist/src/gate/adapters/hook-main.js +35 -0
  26. package/dist/src/gate/adapters/host-pid.d.ts +1 -0
  27. package/dist/src/gate/adapters/host-pid.js +20 -0
  28. package/dist/src/gate/admission.d.ts +54 -0
  29. package/dist/src/gate/admission.js +490 -0
  30. package/dist/src/gate/contract.d.ts +51 -0
  31. package/dist/src/gate/contract.js +94 -0
  32. package/dist/src/gate/decision-log.d.ts +38 -0
  33. package/dist/src/gate/decision-log.js +251 -0
  34. package/dist/src/gate/generations.d.ts +67 -0
  35. package/dist/src/gate/generations.js +518 -0
  36. package/dist/src/gate/proc.d.ts +31 -0
  37. package/dist/src/gate/proc.js +79 -0
  38. package/dist/src/gate/refresh.d.ts +11 -0
  39. package/dist/src/gate/refresh.js +30 -0
  40. package/dist/src/gate/run-verifier.d.ts +23 -0
  41. package/dist/src/gate/run-verifier.js +89 -0
  42. package/dist/src/gate/service.d.ts +80 -0
  43. package/dist/src/gate/service.js +722 -0
  44. package/dist/src/gate/strict-json.d.ts +11 -0
  45. package/dist/src/gate/strict-json.js +190 -0
  46. package/dist/src/gate/trust-store.d.ts +36 -0
  47. package/dist/src/gate/trust-store.js +251 -0
  48. package/dist/src/gate/verifier-worker.d.ts +8 -0
  49. package/dist/src/gate/verifier-worker.js +66 -0
  50. package/dist/src/index.d.ts +2 -0
  51. package/dist/src/index.js +2 -0
  52. package/dist/src/keys.d.ts +4 -0
  53. package/dist/src/keys.js +23 -14
  54. package/dist/src/policy.d.ts +145 -0
  55. package/dist/src/policy.js +554 -35
  56. package/dist/src/recovery-admin.d.ts +173 -0
  57. package/dist/src/recovery-admin.js +400 -0
  58. package/dist/src/root-events.d.ts +107 -0
  59. package/dist/src/root-events.js +376 -0
  60. package/dist/src/timestamp.d.ts +61 -0
  61. package/dist/src/timestamp.js +107 -0
  62. package/dist/src/tree-digest.d.ts +1 -0
  63. package/dist/src/tree-digest.js +1 -1
  64. package/dist/src/verify.d.ts +33 -0
  65. package/dist/src/verify.js +4 -2
  66. package/docs/hosts/adapter-interface.md +8 -2
  67. package/docs/hosts/github-action.md +1 -1
  68. package/docs/hosts/pi.md +2 -0
  69. package/docs/spec/gui-admin-rack-v1.md +289 -0
  70. package/docs/spec/root-recovery-v1.md +33 -12
  71. package/docs/spec/trust-documents-v1.md +8 -2
  72. package/docs/spec/verification.md +9 -2
  73. package/docs/threat-model.md +4 -2
  74. package/package.json +3 -1
@@ -1,19 +1,30 @@
1
1
  import { lstat, opendir, stat } from 'node:fs/promises';
2
2
  import { homedir, hostname } from 'node:os';
3
3
  import path from 'node:path';
4
+ import { StaleDocumentError } from "./admin.js";
4
5
  import { canonicalBytes, exactKeys, isRecord, parseCanonicalJsonBytes, requireArray, requireString } from "./canonical-json.js";
5
- import { appendToRegularFile, isInside, readRegularFile, realpathAllowingMissing, resolveInsideDirectory, writeFileAtomic } from "./fs-safe.js";
6
+ import { FileChangedError, appendToRegularFile, isInside, readRegularFile, realpathAllowingMissing, resolveInsideDirectory, writeFileAtomic } from "./fs-safe.js";
6
7
  import { validateKeyId } from "./keys.js";
7
- import { CERTIFICATE_FILENAME } from "./tree-digest.js";
8
+ import { readRevocationsForUpdate } from "./revocations.js";
9
+ import { readTrustRootForUpdate } from "./trust-root.js";
10
+ import { MAX_ROOT_EVENTS_BYTES, parseRecoverySet, walkRootEventsCached, } from "./root-events.js";
11
+ import { formatTimestamp, parseDuration } from "./time.js";
12
+ import { DEFAULT_MAX_TIMESTAMP_LIFETIME, MAX_TIMESTAMP_BYTES, MAX_TIMESTAMP_LIFETIME_MS, TimestampBindingError, TimestampRollbackError, verifyTimestamp } from "./timestamp.js";
13
+ import { CERTIFICATE_FILENAME, sha256Hex } from "./tree-digest.js";
8
14
  import { loadTrustContext, unverifiable, verifySkill, } from "./verify.js";
9
15
  export const POLICY_VERSION = 'mago.policy/v1';
16
+ /** Adds root recovery and freshness; a v2 host reads v1 policies unchanged. */
17
+ export const POLICY_VERSION_V2 = 'mago.policy/v2';
10
18
  export const STATE_TYPE = 'mago.host-state/v1';
19
+ export const STATE_TYPE_V2 = 'mago.host-state/v2';
11
20
  const MAX_CERTIFICATE_BYTES = 8 * 1024 * 1024;
12
21
  /** Per-Skill budget across all certificate candidates (explicit file, policy directories, in-Skill file). */
13
22
  export const MAX_CERTIFICATE_CANDIDATES = 64;
14
23
  export const MAX_CERTIFICATE_TOTAL_BYTES = 32 * 1024 * 1024;
15
24
  const POLICY_KEYS = ['policy_version', 'mode', 'root_fingerprint', 'trust_root', 'revocations', 'certificate_dirs', 'skill_dirs', 'state_file', 'decision_log'];
25
+ const POLICY_V2_KEYS = ['recovery', 'root_events', 'root_events_after', 'freshness'];
16
26
  const REQUIRED_POLICY_KEYS = ['policy_version', 'mode', 'root_fingerprint', 'trust_root', 'revocations'];
27
+ const FRESHNESS_KEYS = ['timestamp', 'key_id', 'max_lifetime'];
17
28
  /*
18
29
  * Where hosts and the CLI read policy when none is given: $MAGO_SKI_POLICY (absolute, or "~/..."), else ~/.mago-ski/policy.json.
19
30
  * Never a path in the current directory, because the project being checked may be controlled by the code under review.
@@ -41,14 +52,15 @@ export async function loadPolicy(policyPath) {
41
52
  }
42
53
  if (!isRecord(value))
43
54
  throw new Error('Policy file must contain a JSON object');
55
+ if (value.policy_version !== POLICY_VERSION && value.policy_version !== POLICY_VERSION_V2)
56
+ throw new Error(`Policy file must declare policy_version "${POLICY_VERSION}" or "${POLICY_VERSION_V2}"`);
57
+ const v2 = value.policy_version === POLICY_VERSION_V2;
44
58
  for (const key of Object.keys(value))
45
- if (!POLICY_KEYS.includes(key))
46
- throw new Error(`Policy file has unsupported field "${key}"`);
59
+ if (!POLICY_KEYS.includes(key) && !(v2 && POLICY_V2_KEYS.includes(key)))
60
+ throw new Error(`Policy file has unsupported field "${key}"${POLICY_V2_KEYS.includes(key) ? ` (it needs policy_version "${POLICY_VERSION_V2}")` : ''}`);
47
61
  for (const key of REQUIRED_POLICY_KEYS)
48
62
  if (!(key in value))
49
63
  throw new Error(`Policy file is missing "${key}"`);
50
- if (value.policy_version !== POLICY_VERSION)
51
- throw new Error(`Policy file must declare policy_version "${POLICY_VERSION}"`);
52
64
  if (value.mode !== 'shadow' && value.mode !== 'enforce')
53
65
  throw new Error('Policy mode must be "shadow" or "enforce"');
54
66
  const base = path.dirname(absolute);
@@ -56,20 +68,56 @@ export async function loadPolicy(policyPath) {
56
68
  // decision_log and state_file are files this tool writes, so the policy may only place them in its own directory.
57
69
  const writablePath = async (item, label) => item === undefined || item === null ? null : await resolveInsideDirectory(base, requireString(item, `Policy ${label}`, 4096), `Policy ${label}`);
58
70
  const optionalList = (item, label) => item === undefined ? [] : requireArray(item, `Policy ${label}`, 256).map((entry, index) => resolvePath(entry, `${label}[${index}]`));
71
+ const rootKeyId = validateKeyId(value.root_fingerprint, 'Policy root_fingerprint');
59
72
  const policy = {
60
73
  path: absolute,
61
74
  mode: value.mode,
62
- rootKeyId: validateKeyId(value.root_fingerprint, 'Policy root_fingerprint'),
75
+ rootKeyId,
63
76
  trustRootPath: resolvePath(value.trust_root, 'trust_root'),
64
77
  revocationsPath: resolvePath(value.revocations, 'revocations'),
65
78
  certificateDirs: optionalList(value.certificate_dirs, 'certificate_dirs'),
66
79
  skillDirs: optionalList(value.skill_dirs, 'skill_dirs'),
67
80
  statePath: await writablePath(value.state_file, 'state_file'),
68
81
  decisionLogPath: await writablePath(value.decision_log, 'decision_log'),
82
+ recovery: parseRecoveryPolicy(value, rootKeyId, resolvePath),
69
83
  };
70
84
  await rejectWriteTargetsThatOverlapInputs(policy);
71
85
  return policy;
72
86
  }
87
+ /** The v2 fields. A policy without "recovery" must not use the other recovery fields: it behaves as v1. */
88
+ function parseRecoveryPolicy(value, rootKeyId, resolvePath) {
89
+ if (value.recovery === undefined) {
90
+ for (const key of ['root_events', 'root_events_after', 'freshness'])
91
+ if (value[key] !== undefined)
92
+ throw new Error(`Policy "${key}" requires "recovery"`);
93
+ return null;
94
+ }
95
+ const set = parseRecoverySet(value.recovery, 'Policy recovery');
96
+ if (set.keyIds.includes(rootKeyId))
97
+ throw new Error('Policy recovery key_ids must not include root_fingerprint');
98
+ if (value.root_events === undefined)
99
+ throw new Error('Policy "recovery" requires "root_events" (publish an empty log with "mago-ski root-events init")');
100
+ const eventsAfter = value.root_events_after === undefined ? 0 : value.root_events_after;
101
+ if (typeof eventsAfter !== 'number' || !Number.isSafeInteger(eventsAfter) || eventsAfter < 0)
102
+ throw new Error('Policy root_events_after must be a non-negative integer');
103
+ let freshness = null;
104
+ if (value.freshness !== undefined) {
105
+ if (!isRecord(value.freshness))
106
+ throw new Error('Policy freshness must be a JSON object');
107
+ for (const key of Object.keys(value.freshness))
108
+ if (!FRESHNESS_KEYS.includes(key))
109
+ throw new Error(`Policy freshness has unsupported field "${key}"`);
110
+ const keyId = validateKeyId(value.freshness.key_id, 'Policy freshness key_id');
111
+ if (keyId === rootKeyId || set.keyIds.includes(keyId))
112
+ throw new Error('Policy freshness key_id must not be root_fingerprint or a recovery key');
113
+ const lifetime = value.freshness.max_lifetime === undefined ? DEFAULT_MAX_TIMESTAMP_LIFETIME : requireString(value.freshness.max_lifetime, 'Policy freshness max_lifetime', 16);
114
+ const maxLifetimeMs = parseDuration(lifetime, 'Policy freshness max_lifetime');
115
+ if (maxLifetimeMs > MAX_TIMESTAMP_LIFETIME_MS)
116
+ throw new Error('Policy freshness max_lifetime must be at most 7d');
117
+ freshness = { timestampPath: resolvePath(value.freshness.timestamp, 'freshness timestamp'), keyId, maxLifetimeMs };
118
+ }
119
+ return { set, rootEventsPath: resolvePath(value.root_events, 'root_events'), eventsAfter, freshness };
120
+ }
73
121
  /** A path with symlinks resolved where possible; falls back to the lexical path (the read itself will fail later). */
74
122
  async function canonicalOrLexical(target) {
75
123
  try {
@@ -83,6 +131,8 @@ async function canonicalOrLexical(target) {
83
131
  async function rejectWriteTargetsThatOverlapInputs(policy) {
84
132
  const inputs = [
85
133
  ['the policy file', policy.path], ['trust_root', policy.trustRootPath], ['revocations', policy.revocationsPath],
134
+ ...(policy.recovery ? [['root_events', policy.recovery.rootEventsPath]] : []),
135
+ ...(policy.recovery?.freshness ? [['freshness timestamp', policy.recovery.freshness.timestampPath]] : []),
86
136
  ];
87
137
  const directories = await Promise.all(policy.certificateDirs.map(canonicalOrLexical));
88
138
  const targets = [['state_file', policy.statePath], ['decision_log', policy.decisionLogPath]];
@@ -103,6 +153,23 @@ async function rejectWriteTargetsThatOverlapInputs(policy) {
103
153
  seen.push([label, canonical]);
104
154
  }
105
155
  }
156
+ function stateCount(value, label) {
157
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1)
158
+ throw new Error(`${label} must be a positive integer`);
159
+ return value;
160
+ }
161
+ /** The host state file exists and was read, but its content or kind is wrong. Every other read error is not this. */
162
+ export class HostStateFormatError extends Error {
163
+ constructor(message) {
164
+ super(message);
165
+ this.name = 'HostStateFormatError';
166
+ }
167
+ }
168
+ const FORMAT_READ_ERROR = /(must be a regular, non-symlink file|exceeds the \d+-byte limit)$/;
169
+ /** The host state file as it is now (a missing file is an empty state). The GUI memory uses this format too. */
170
+ export async function readHostState(statePath) {
171
+ return await readState(statePath);
172
+ }
106
173
  async function readState(statePath) {
107
174
  let bytes;
108
175
  try {
@@ -110,57 +177,483 @@ async function readState(statePath) {
110
177
  }
111
178
  catch (error) {
112
179
  if (error?.code === 'ENOENT')
113
- return {};
180
+ return { roots: {}, rootEvents: {}, timestamps: {}, v2: false };
181
+ if (error instanceof Error && FORMAT_READ_ERROR.test(error.message))
182
+ throw new HostStateFormatError(error.message);
114
183
  throw error;
115
184
  }
116
- const value = exactKeys(parseCanonicalJsonBytes(bytes, 'host state'), ['type', 'roots'], 'host state');
117
- if (value.type !== STATE_TYPE || !isRecord(value.roots))
185
+ try {
186
+ return parseState(bytes);
187
+ }
188
+ catch (error) {
189
+ throw new HostStateFormatError(error.message);
190
+ }
191
+ }
192
+ function parseState(bytes) {
193
+ const parsed = parseCanonicalJsonBytes(bytes, 'host state');
194
+ const v2 = isRecord(parsed) && parsed.type === STATE_TYPE_V2;
195
+ const value = exactKeys(parsed, v2 ? ['type', 'roots', 'root_events', 'timestamps'] : ['type', 'roots'], 'host state');
196
+ if ((value.type !== STATE_TYPE && !v2) || !isRecord(value.roots))
118
197
  throw new Error('host state file has an unsupported format');
119
- const roots = {};
198
+ const state = { roots: {}, rootEvents: {}, timestamps: {}, v2 };
120
199
  for (const [rootKeyId, entry] of Object.entries(value.roots)) {
121
200
  const fields = exactKeys(entry, ['trust_root_version', 'revocations_version'], 'host state root');
122
- roots[validateKeyId(rootKeyId, 'host state root key')] = {
123
- trust_root_version: Number(fields.trust_root_version), revocations_version: Number(fields.revocations_version),
201
+ state.roots[validateKeyId(rootKeyId, 'host state root key')] = {
202
+ trust_root_version: stateCount(fields.trust_root_version, 'host state trust_root_version'),
203
+ revocations_version: stateCount(fields.revocations_version, 'host state revocations_version'),
124
204
  };
125
205
  }
126
- return roots;
206
+ if (v2) {
207
+ if (!isRecord(value.root_events) || !isRecord(value.timestamps))
208
+ throw new Error('host state file has an unsupported format');
209
+ for (const [rootKeyId, entry] of Object.entries(value.root_events)) {
210
+ const withRevoked = isRecord(entry) && 'revoked' in entry;
211
+ const fields = exactKeys(entry, withRevoked ? ['sequence', 'event_digest', 'revoked'] : ['sequence', 'event_digest'], 'host state root_events');
212
+ if (withRevoked && fields.revoked !== true)
213
+ throw new Error('host state root_events revoked must be true when present');
214
+ state.rootEvents[validateKeyId(rootKeyId, 'host state root_events key')] = {
215
+ sequence: stateCount(fields.sequence, 'host state root_events sequence'),
216
+ event_digest: validateKeyId(fields.event_digest, 'host state root_events event_digest'),
217
+ ...(withRevoked ? { revoked: true } : {}),
218
+ };
219
+ }
220
+ for (const [keyId, entry] of Object.entries(value.timestamps)) {
221
+ const fields = exactKeys(entry, ['version'], 'host state timestamps');
222
+ state.timestamps[validateKeyId(keyId, 'host state timestamps key')] = { version: stateCount(fields.version, 'host state timestamp version') };
223
+ }
224
+ }
225
+ return state;
226
+ }
227
+ /**
228
+ * Combines this load's state with the state file as it is now, so two hosts sharing one state file (two Pi sessions,
229
+ * Pi and the CLI) cannot erase each other's progress: every counter keeps its highest value, the root event entry
230
+ * with the higher sequence wins (on a tie with different digests, the one already on disk stays, so the fork is
231
+ * reported on the next load), and v2 is never written back as v1.
232
+ */
233
+ export function mergeHostState(ours, disk) {
234
+ const merged = { roots: { ...disk.roots }, rootEvents: { ...disk.rootEvents }, timestamps: { ...disk.timestamps }, v2: ours.v2 || disk.v2 };
235
+ for (const [keyId, entry] of Object.entries(ours.roots)) {
236
+ const other = merged.roots[keyId];
237
+ merged.roots[keyId] = other ? {
238
+ trust_root_version: Math.max(entry.trust_root_version, other.trust_root_version),
239
+ revocations_version: Math.max(entry.revocations_version, other.revocations_version),
240
+ } : entry;
241
+ }
242
+ for (const [keyId, entry] of Object.entries(ours.rootEvents)) {
243
+ const other = merged.rootEvents[keyId];
244
+ if (!other || entry.sequence > other.sequence)
245
+ merged.rootEvents[keyId] = entry;
246
+ }
247
+ for (const [keyId, entry] of Object.entries(ours.timestamps)) {
248
+ const other = merged.timestamps[keyId];
249
+ if (!other || entry.version > other.version)
250
+ merged.timestamps[keyId] = entry;
251
+ }
252
+ return merged;
253
+ }
254
+ function stateBytes(state) {
255
+ if (!state.v2)
256
+ return canonicalBytes({ type: STATE_TYPE, roots: state.roots });
257
+ return canonicalBytes({ type: STATE_TYPE_V2, roots: state.roots, root_events: state.rootEvents, timestamps: state.timestamps });
258
+ }
259
+ /** Reads a file once, so the bytes that are hashed for freshness are the bytes that are parsed. */
260
+ async function readTrustFile(filePath, label, maxBytes) {
261
+ try {
262
+ return await readRegularFile(filePath, label, maxBytes);
263
+ }
264
+ catch (error) {
265
+ if (error?.code === 'ENOENT' && (label === 'Root event log' || label === 'Timestamp'))
266
+ throw new Error(`${label} not found: ${filePath}`);
267
+ throw error;
268
+ }
269
+ }
270
+ /*
271
+ * A revoke this host has applied stays in force while the log cannot be checked: making the log missing, malformed,
272
+ * shorter or forked must not turn root-revoked into trust-unavailable, which shadow mode would let through.
273
+ */
274
+ function rootBlocked(problem, entry) {
275
+ return entry?.revoked
276
+ ? { reason: `root key was revoked by root event ${entry.sequence}, and the root event log cannot be checked now (${problem}); waiting for a valid log with a rotation`, rootRevoked: true }
277
+ : { reason: problem, rootRevoked: false };
278
+ }
279
+ /**
280
+ * The root-event part of a load, without I/O: walks the log, compares it with what this host has applied (rollback,
281
+ * fork), and says which progress to record. `loadPolicyTrust` and `loadPolicyRoot` both apply `progress` to their state.
282
+ * Only a revoke result carries a walk on failure; a log that is old, forked or unreadable yields no walk and so no roles.
283
+ */
284
+ function checkRootEvents(policy, state, log, now) {
285
+ const recovery = policy.recovery;
286
+ const pinned = policy.rootKeyId;
287
+ if (!recovery || log === null)
288
+ return { ok: true, walk: null, activeRootKeyId: pinned, progress: null };
289
+ const seen = state.rootEvents[pinned];
290
+ const stop = (problem, rollback) => ({ ok: false, ...rootBlocked(problem, seen), ...(rollback ? { rollback } : {}), walk: null, progress: null });
291
+ if ('error' in log)
292
+ return stop(`root event log: ${log.error}`);
293
+ let walk;
294
+ try {
295
+ walk = walkRootEventsCached(log.bytes, {
296
+ rootKeyId: pinned, recovery: recovery.set, timestampKeyId: recovery.freshness?.keyId ?? null, eventsAfter: recovery.eventsAfter,
297
+ }, now);
298
+ }
299
+ catch (error) {
300
+ return stop(`root event log: ${error.message}`);
301
+ }
302
+ if (seen) {
303
+ if (walk.count < seen.sequence)
304
+ return stop(`root event log has ${walk.count} event(s), but this host has already applied ${seen.sequence} (rollback)`, true);
305
+ if (walk.eventDigests[seen.sequence - 1] !== seen.event_digest)
306
+ return stop(`root event ${seen.sequence} differs from the one this host already applied (fork); the organization must resolve it`);
307
+ }
308
+ // Only events this host checked are recorded: those before root_events_after were never verified here.
309
+ const progress = walk.count > recovery.eventsAfter && (!seen || walk.count > seen.sequence)
310
+ ? { sequence: walk.count, event_digest: walk.eventDigests[walk.count - 1], ...(walk.revoked ? { revoked: true } : {}) }
311
+ : null;
312
+ if (walk.revoked) {
313
+ return {
314
+ ok: false, rootRevoked: true, walk, progress,
315
+ reason: `root key ${walk.activeRootKeyId} was revoked by root event ${walk.revoked.sequence} (${walk.revoked.reason}); waiting for a rotation`,
316
+ };
317
+ }
318
+ return { ok: true, walk, activeRootKeyId: walk.activeRootKeyId, progress };
319
+ }
320
+ async function readRootEventLog(policy) {
321
+ if (!policy.recovery)
322
+ return null;
323
+ try {
324
+ return { bytes: await readTrustFile(policy.recovery.rootEventsPath, 'Root event log', MAX_ROOT_EVENTS_BYTES) };
325
+ }
326
+ catch (error) {
327
+ return { error: error.message };
328
+ }
329
+ }
330
+ /** Applies a progress entry to a state, as the loads record it. */
331
+ function applyProgress(state, pinned, progress) {
332
+ state.v2 = true;
333
+ state.rootEvents[pinned] = progress;
334
+ }
335
+ /**
336
+ * Merges `state` with the state file as it is now and writes the result, as a compare-and-swap: the raw bytes are read
337
+ * once, the merge is written only if the file still has those bytes, and a change in between (another process) means
338
+ * re-read, merge and retry, up to 5 times with 10 to 80 ms jittered waits. A counter is never lowered within that
339
+ * budget; when it runs out the write fails closed. A file that cannot be read or parsed fails the write.
340
+ * Returns the merged state, or the reason the write failed.
341
+ */
342
+ const persistChains = new Map();
343
+ async function persistState(statePath, state) {
344
+ const key = await canonicalOrLexical(statePath);
345
+ const previous = persistChains.get(key) ?? Promise.resolve();
346
+ const run = previous.then(() => persistStateNow(statePath, state));
347
+ const tail = run.catch(() => undefined);
348
+ persistChains.set(key, tail);
349
+ try {
350
+ return await run;
351
+ }
352
+ finally {
353
+ if (persistChains.get(key) === tail)
354
+ persistChains.delete(key);
355
+ }
356
+ }
357
+ const PERSIST_ATTEMPTS = 5;
358
+ async function persistStateNow(statePath, state) {
359
+ try {
360
+ for (let attempt = 0; attempt < PERSIST_ATTEMPTS; attempt += 1) {
361
+ let raw = null;
362
+ try {
363
+ raw = await readRegularFile(statePath, 'Host state file', 1024 * 1024);
364
+ }
365
+ catch (error) {
366
+ if (error?.code !== 'ENOENT')
367
+ throw error;
368
+ }
369
+ const disk = raw === null ? null : parseState(raw);
370
+ const merged = disk ? mergeHostState(state, disk) : state;
371
+ try {
372
+ await writeFileAtomic(statePath, stateBytes(merged), 0o600, { expectSha256: raw === null ? null : `sha256:${sha256Hex(raw)}` });
373
+ return { state: merged };
374
+ }
375
+ catch (error) {
376
+ if (!(error instanceof FileChangedError))
377
+ throw error;
378
+ }
379
+ if (attempt < PERSIST_ATTEMPTS - 1)
380
+ await new Promise((resolve) => setTimeout(resolve, 10 + Math.random() * 70));
381
+ }
382
+ throw new Error('the file kept changing');
383
+ }
384
+ catch (error) {
385
+ return { error: `cannot record trust versions in ${statePath}: ${error.message}` };
386
+ }
387
+ }
388
+ /**
389
+ * Records document versions in a host state file (the GUI memory), merging with what is on disk: every counter keeps
390
+ * its highest value, so this never lowers anything within the retry budget of `persistState` (it fails closed otherwise). A root entry takes each given half and `1` (the lowest valid
391
+ * value) for a missing one. Throws when the file cannot be read or written.
392
+ */
393
+ export async function recordDocumentVersions(statePath, v) {
394
+ if ((v.trustRoot !== undefined || v.revocations !== undefined) && v.rootKeyId === undefined)
395
+ throw new Error('rootKeyId is required to record a trust root or revocation list version');
396
+ await readState(statePath);
397
+ const ours = { roots: {}, rootEvents: {}, timestamps: {}, v2: false };
398
+ if (v.rootKeyId !== undefined && (v.trustRoot !== undefined || v.revocations !== undefined))
399
+ ours.roots[v.rootKeyId] = { trust_root_version: v.trustRoot ?? 1, revocations_version: v.revocations ?? 1 };
400
+ if (v.timestamp) {
401
+ ours.timestamps[v.timestamp.keyId] = { version: v.timestamp.version };
402
+ ours.v2 = true;
403
+ }
404
+ const saved = await persistState(statePath, ours);
405
+ if ('error' in saved)
406
+ throw new Error(saved.error);
407
+ }
408
+ /** The lowest versions this computer's memory allows for each document; 0 where nothing is recorded. */
409
+ export function memoryMinimums(state, rootKeyId, timestampKeyId) {
410
+ const root = state.roots[rootKeyId];
411
+ return {
412
+ trustRoot: root?.trust_root_version ?? 0,
413
+ revocations: root?.revocations_version ?? 0,
414
+ timestamp: timestampKeyId === null ? 0 : (state.timestamps[timestampKeyId]?.version ?? 0),
415
+ };
416
+ }
417
+ /**
418
+ * Keys that must not be approvers in this organisation: the root, the recovery set, the timestamp key, keys that left
419
+ * the root or timestamp role, keys that left a recovery set, and every revoked key. Neither reads nor writes host state.
420
+ * Throws when the root event log or the revocation list cannot be checked, and `StaleDocumentError` when the revocation
421
+ * list is older than `minimumRevocations` (the caller's memory; the CLI passes none).
422
+ */
423
+ export async function forbiddenApproverKeys(policy, now, o = {}) {
424
+ const rootResult = await loadPolicyRoot(policy, now, { recordVersions: false });
425
+ if (!rootResult.ok)
426
+ throw new Error(`Cannot check the root event log, so no approver is added: ${rootResult.reason}`);
427
+ const found = new Map();
428
+ const add = (keyId, why) => {
429
+ if (keyId && !found.has(keyId))
430
+ found.set(keyId, why);
431
+ };
432
+ const { walk, activeRootKeyId } = rootResult;
433
+ add(activeRootKeyId, 'root');
434
+ add(policy.rootKeyId, 'retired');
435
+ if (walk) {
436
+ for (const keyId of walk.recovery.keyIds)
437
+ add(keyId, 'recovery');
438
+ add(walk.timestampKeyId, 'timestamp');
439
+ for (const keyId of walk.retired)
440
+ add(keyId, 'retired');
441
+ for (const keyId of walk.formerRecovery)
442
+ add(keyId, 'formerRecovery');
443
+ }
444
+ else if (policy.recovery) {
445
+ for (const keyId of policy.recovery.set.keyIds)
446
+ add(keyId, 'recovery');
447
+ add(policy.recovery.freshness?.keyId, 'timestamp');
448
+ }
449
+ let stale = null;
450
+ try {
451
+ const trust = readTrustRootForUpdate(await readRegularFile(policy.trustRootPath, 'Trust root', 4 * 1024 * 1024), activeRootKeyId);
452
+ const list = readRevocationsForUpdate(await readRegularFile(policy.revocationsPath, 'Revocation list', 8 * 1024 * 1024), activeRootKeyId, trust.root.publicKey);
453
+ if (o.minimumRevocations !== undefined && list.version < o.minimumRevocations)
454
+ stale = new StaleDocumentError('Revocation list', list.version, o.minimumRevocations);
455
+ for (const entry of list.keys)
456
+ add(entry.keyId, 'revoked');
457
+ }
458
+ catch (error) {
459
+ throw new Error(`Cannot read the revocation list, so no approver is added: ${error.message}`);
460
+ }
461
+ if (stale)
462
+ throw stale;
463
+ return [...found].map(([keyId, why]) => ({ keyId, why }));
464
+ }
465
+ const stateErrorKind = (error) => error instanceof HostStateFormatError ? 'corrupt' : 'unreadable';
466
+ const failure = (reason, extra = {}) => ({ ok: false, verdict: 'UNVERIFIABLE', reason, ...extra });
467
+ /**
468
+ * Only the root-event part of `loadPolicyTrust`: which root key is active, whether it is revoked, and the walk. It
469
+ * reads the state and the log, checks rollback and forks the same way, and with `recordVersions` (the default) and a
470
+ * state file records the progress with the same merge-before-write. A policy without `recovery` reads nothing.
471
+ */
472
+ export async function loadPolicyRoot(policy, now, options = {}) {
473
+ if (!policy.recovery)
474
+ return { ok: true, walk: null, activeRootKeyId: policy.rootKeyId };
475
+ const pinned = policy.rootKeyId;
476
+ let state = { roots: {}, rootEvents: {}, timestamps: {}, v2: false };
477
+ try {
478
+ if (policy.statePath)
479
+ state = await readState(policy.statePath);
480
+ }
481
+ catch (error) {
482
+ return { ok: false, reason: error.message, rootRevoked: false, walk: null, stateError: stateErrorKind(error) };
483
+ }
484
+ const checked = checkRootEvents(policy, state, await readRootEventLog(policy), now);
485
+ if (checked.progress)
486
+ applyProgress(state, pinned, checked.progress);
487
+ if (checked.progress && options.recordVersions !== false && policy.statePath !== null) {
488
+ const saved = await persistState(policy.statePath, state);
489
+ if ('error' in saved) {
490
+ // A revoke stays reported as a revoke even when it could not be recorded.
491
+ if (!checked.ok)
492
+ return { ok: false, reason: checked.reason, rootRevoked: checked.rootRevoked, walk: checked.walk, ...(checked.rollback ? { rollback: true } : {}) };
493
+ return { ok: false, reason: saved.error, rootRevoked: false, walk: null, stateError: 'write' };
494
+ }
495
+ const merged = saved.state.rootEvents[pinned];
496
+ if (checked.ok && checked.walk && merged && merged.sequence > checked.walk.count)
497
+ return { ok: false, ...rootBlocked(`root event log has ${checked.walk.count} event(s), but this host has already applied ${merged.sequence} (rollback)`, merged), walk: null, rollback: true };
498
+ }
499
+ if (!checked.ok)
500
+ return { ok: false, reason: checked.reason, rootRevoked: checked.rootRevoked, walk: checked.walk, ...(checked.rollback ? { rollback: true } : {}) };
501
+ return { ok: true, walk: checked.walk, activeRootKeyId: checked.activeRootKeyId };
127
502
  }
128
503
  /**
129
504
  * Loads trust documents for a policy, enforcing rollback protection through the state file.
130
505
  * With `recordVersions: false` the state file is still read (the same rollback minimums apply) but never written:
131
506
  * for observers such as the GUI, which must not move a host's rollback memory.
507
+ *
508
+ * With root recovery (policy v2), the order is: walk the root event log, check rollback and forks, stop if the active
509
+ * root is revoked (`rootRevoked`, which blocks in every mode), check the timestamp, then the trust root and revocation
510
+ * list against the active root, then record the new state.
132
511
  */
133
512
  export async function loadPolicyTrust(policy, now, options = {}) {
513
+ return await loadTrustBody(policy, now, { record: options.recordVersions !== false });
514
+ }
515
+ /**
516
+ * The host's own trust load, for a preview: never records versions, may replace the documents read from disk with
517
+ * in-memory bytes (`override`, subject to the same size limits), and with `skipFreshness` skips reading and checking
518
+ * the timestamp and its binding to the documents (`context.root.timestamp` is then null). Only the GUI service uses it.
519
+ */
520
+ export async function loadTrustForPreview(policy, now, o = {}) {
521
+ return await loadTrustBody(policy, now, { record: false, ...(o.override ? { override: o.override } : {}), ...(o.skipFreshness ? { skipFreshness: true } : {}) });
522
+ }
523
+ function overridden(bytes, label, maxBytes) {
524
+ if (bytes.byteLength > maxBytes)
525
+ throw new Error(`${label} exceeds the ${maxBytes}-byte limit`);
526
+ return bytes;
527
+ }
528
+ async function loadTrustBody(policy, now, o) {
529
+ const record = o.record && policy.statePath !== null;
530
+ const freshness = o.skipFreshness ? undefined : policy.recovery?.freshness;
531
+ let state = { roots: {}, rootEvents: {}, timestamps: {}, v2: false };
532
+ try {
533
+ if (policy.statePath)
534
+ state = await readState(policy.statePath);
535
+ }
536
+ catch (error) {
537
+ return failure(error.message, { stateError: stateErrorKind(error) });
538
+ }
539
+ const recovery = policy.recovery;
540
+ const pinned = policy.rootKeyId;
541
+ let activeRootKeyId = pinned;
542
+ let walk = null;
543
+ let logBytes = null;
544
+ // Root event progress is recorded as soon as the log is accepted, even if a later step fails: the events are signed
545
+ // by recovery keys, and remembering them is what stops a host being moved back to a log without a revoke.
546
+ let stateChanged = false;
547
+ const saveState = async () => {
548
+ if (!record || !stateChanged)
549
+ return null;
550
+ const saved = await persistState(policy.statePath, state);
551
+ if ('error' in saved)
552
+ return failure(saved.error, { stateError: 'write' });
553
+ state = saved.state;
554
+ stateChanged = false;
555
+ // Another load on this host may have applied later root events meanwhile; this load's log is then a rollback.
556
+ const merged = state.rootEvents[pinned];
557
+ if (walk && merged && merged.sequence > walk.count) {
558
+ const { reason, rootRevoked } = rootBlocked(`root event log has ${walk.count} event(s), but this host has already applied ${merged.sequence} (rollback)`, merged);
559
+ return failure(reason, { ...(rootRevoked ? { rootRevoked } : {}), rollback: true });
560
+ }
561
+ return null;
562
+ };
563
+ if (recovery) {
564
+ const log = await readRootEventLog(policy);
565
+ const checked = checkRootEvents(policy, state, log, now);
566
+ if (checked.progress) {
567
+ applyProgress(state, pinned, checked.progress);
568
+ stateChanged = true;
569
+ }
570
+ walk = checked.walk;
571
+ if (!checked.ok) {
572
+ if (checked.progress)
573
+ await saveState();
574
+ return failure(checked.reason, { ...(checked.rootRevoked ? { rootRevoked: true } : {}), ...(checked.rollback ? { rollback: true } : {}) });
575
+ }
576
+ logBytes = log !== null && 'bytes' in log ? log.bytes : null;
577
+ activeRootKeyId = checked.activeRootKeyId;
578
+ }
134
579
  let trustRootBytes;
135
580
  let revocationsBytes;
136
- let roots = {};
581
+ let timestampBytes = null;
137
582
  try {
138
- trustRootBytes = await readRegularFile(policy.trustRootPath, 'Trust root', 4 * 1024 * 1024);
139
- revocationsBytes = await readRegularFile(policy.revocationsPath, 'Revocation list', 8 * 1024 * 1024);
140
- if (policy.statePath)
141
- roots = await readState(policy.statePath);
583
+ trustRootBytes = o.override?.trustRoot ? overridden(o.override.trustRoot, 'Trust root', 4 * 1024 * 1024) : await readTrustFile(policy.trustRootPath, 'Trust root', 4 * 1024 * 1024);
584
+ revocationsBytes = o.override?.revocations ? overridden(o.override.revocations, 'Revocation list', 8 * 1024 * 1024) : await readTrustFile(policy.revocationsPath, 'Revocation list', 8 * 1024 * 1024);
585
+ if (freshness)
586
+ timestampBytes = o.override?.timestamp ? overridden(o.override.timestamp, 'Timestamp', MAX_TIMESTAMP_BYTES) : await readTrustFile(freshness.timestampPath, 'Timestamp', MAX_TIMESTAMP_BYTES);
142
587
  }
143
588
  catch (error) {
144
- return { ok: false, verdict: 'UNVERIFIABLE', reason: error.message };
589
+ return await saveState() ?? failure(error.message);
590
+ }
591
+ let timestamp = null;
592
+ if (freshness) {
593
+ // Freshness is configured, so a missing input fails closed instead of skipping the check.
594
+ if (!walk || !logBytes || !timestampBytes || walk.timestampKeyId === null)
595
+ return await saveState() ?? failure('freshness: the timestamp could not be checked');
596
+ const timestampKeyId = walk.timestampKeyId;
597
+ try {
598
+ timestamp = verifyTimestamp(timestampBytes, {
599
+ keyId: timestampKeyId, now, maxLifetimeMs: freshness.maxLifetimeMs,
600
+ minimumVersion: state.timestamps[timestampKeyId]?.version,
601
+ inputs: {
602
+ rootEvents: { sha256: walk.logSha256, count: walk.count },
603
+ trustRoot: { sha256: sha256Hex(trustRootBytes) },
604
+ revocations: { sha256: sha256Hex(revocationsBytes) },
605
+ },
606
+ });
607
+ }
608
+ catch (error) {
609
+ return await saveState() ?? failure(`freshness: ${error.message}`, error instanceof TimestampRollbackError ? { rollback: true } : error instanceof TimestampBindingError ? { bindingMismatch: true } : {});
610
+ }
145
611
  }
146
- const seen = roots[policy.rootKeyId];
612
+ const seen = state.roots[activeRootKeyId];
147
613
  const minimum = seen ? { trustRootVersion: seen.trust_root_version, revocationsVersion: seen.revocations_version } : undefined;
148
- const result = loadTrustContext({ trustRootBytes, revocationsBytes, rootKeyId: policy.rootKeyId, now, minimum });
149
- if (result.ok && policy.statePath && options.recordVersions !== false) {
150
- const next = { trust_root_version: result.context.trustRoot.version, revocations_version: result.context.revocations.version };
151
- if (!seen || next.trust_root_version > seen.trust_root_version || next.revocations_version > seen.revocations_version) {
152
- roots[policy.rootKeyId] = {
153
- trust_root_version: Math.max(next.trust_root_version, seen?.trust_root_version ?? 0),
154
- revocations_version: Math.max(next.revocations_version, seen?.revocations_version ?? 0),
155
- };
156
- try {
157
- await writeFileAtomic(policy.statePath, canonicalBytes({ type: STATE_TYPE, roots }), 0o600);
158
- }
159
- catch (error) {
160
- return { ok: false, verdict: 'UNVERIFIABLE', reason: `cannot record trust versions in ${policy.statePath}: ${error.message}` };
161
- }
614
+ const result = loadTrustContext({ trustRootBytes, revocationsBytes, rootKeyId: activeRootKeyId, now, minimum });
615
+ if (!result.ok)
616
+ return await saveState() ?? result;
617
+ const { trustRoot, revocations } = result.context;
618
+ if (walk) {
619
+ const collision = trustRoot.approvers.find((approver) => walk.recovery.keyIds.includes(approver.keyId) || approver.keyId === walk.timestampKeyId);
620
+ if (collision)
621
+ return await saveState() ?? failure(`trust root lists approver ${collision.keyId}, which is a recovery or timestamp key; no key may hold two roles`);
622
+ const retiredApprover = trustRoot.approvers.find((approver) => walk.retired.includes(approver.keyId));
623
+ if (retiredApprover)
624
+ return await saveState() ?? failure(`trust root lists approver ${retiredApprover.keyId}, which has held the root or timestamp role; a key that left those roles never takes another`);
625
+ }
626
+ if (timestamp && (timestamp.trustRoot.version !== trustRoot.version || timestamp.revocations.version !== revocations.version))
627
+ return await saveState() ?? failure('freshness: the trust root or revocation list version does not match the timestamp', { bindingMismatch: true });
628
+ const next = { trust_root_version: trustRoot.version, revocations_version: revocations.version };
629
+ if (!seen || next.trust_root_version > seen.trust_root_version || next.revocations_version > seen.revocations_version) {
630
+ state.roots[activeRootKeyId] = {
631
+ trust_root_version: Math.max(next.trust_root_version, seen?.trust_root_version ?? 0),
632
+ revocations_version: Math.max(next.revocations_version, seen?.revocations_version ?? 0),
633
+ };
634
+ stateChanged = true;
635
+ }
636
+ if (timestamp && walk?.timestampKeyId) {
637
+ const previous = state.timestamps[walk.timestampKeyId]?.version ?? 0;
638
+ if (timestamp.version > previous) {
639
+ state.v2 = true;
640
+ state.timestamps[walk.timestampKeyId] = { version: timestamp.version };
641
+ stateChanged = true;
162
642
  }
163
643
  }
644
+ const problem = await saveState();
645
+ if (problem)
646
+ return problem;
647
+ if (walk) {
648
+ result.context.root = {
649
+ pinnedRootKeyId: policy.rootKeyId,
650
+ activeRootKeyId,
651
+ sequence: walk.count,
652
+ recovery: walk.recovery,
653
+ timestampKeyId: walk.timestampKeyId,
654
+ timestamp: timestamp ? { version: timestamp.version, expiresAt: timestamp.expiresAt } : null,
655
+ };
656
+ }
164
657
  return result;
165
658
  }
166
659
  async function readOptional(filePath, label) {
@@ -301,6 +794,32 @@ export async function findSkillDirs(roots, maxDepth = MAX_DISCOVERY_DEPTH, limit
301
794
  export function tooDeepResult(directory, now) {
302
795
  return unverifiable(directory, path.basename(directory), `directory is deeper than the discovery limit (${MAX_DISCOVERY_DEPTH} levels below skill_dirs); Skills below it were not checked. Point skill_dirs closer to the Skills`, now);
303
796
  }
797
+ export function trustFailureEvent(failure) {
798
+ return failure.rootRevoked ? 'root-revoked' : 'trust-unavailable';
799
+ }
800
+ /**
801
+ * The mode a host acts in for this trust state. A revoked root is a signed statement that the trust anchor is not
802
+ * sound, so it blocks in shadow mode too; no policy setting changes that. Every other failure follows the policy.
803
+ */
804
+ export function effectiveMode(mode, trust) {
805
+ return trust && !trust.ok && trust.rootRevoked ? 'enforce' : mode;
806
+ }
807
+ /** The single decision-log record for a trust failure: empty skill and skill_dir, null digest and certificate_id. */
808
+ export function trustFailureRecord(failure, mode, now, host = `${hostname()}`) {
809
+ return {
810
+ timestamp: formatTimestamp(now),
811
+ host,
812
+ mode,
813
+ action: failure.rootRevoked ? 'block' : actionFor(mode, false),
814
+ event: trustFailureEvent(failure),
815
+ skill: '',
816
+ skill_dir: '',
817
+ digest: null,
818
+ certificate_id: null,
819
+ verdict: 'UNVERIFIABLE',
820
+ reason: failure.reason,
821
+ };
822
+ }
304
823
  export function actionFor(mode, verified) {
305
824
  if (verified)
306
825
  return 'allow';