@mago-foundation/mago-ski 0.1.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 (91) hide show
  1. package/README.md +54 -9
  2. package/action.yml +2 -2
  3. package/dist/hosts/github/run.d.ts +9 -1
  4. package/dist/hosts/github/run.js +64 -11
  5. package/dist/hosts/pi/index.d.ts +5 -3
  6. package/dist/hosts/pi/index.js +219 -14
  7. package/dist/src/admin.d.ts +140 -1
  8. package/dist/src/admin.js +328 -63
  9. package/dist/src/canonical-json.js +73 -28
  10. package/dist/src/certificate.js +23 -15
  11. package/dist/src/cli.js +590 -89
  12. package/dist/src/diff.d.ts +0 -4
  13. package/dist/src/diff.js +326 -70
  14. package/dist/src/dsse.d.ts +6 -4
  15. package/dist/src/dsse.js +22 -6
  16. package/dist/src/fs-safe.d.ts +32 -3
  17. package/dist/src/fs-safe.js +193 -31
  18. package/dist/src/gate/adapters/claude-code-hook.d.ts +1 -0
  19. package/dist/src/gate/adapters/claude-code-hook.js +4 -0
  20. package/dist/src/gate/adapters/claude-code-settings.d.ts +13 -0
  21. package/dist/src/gate/adapters/claude-code-settings.js +49 -0
  22. package/dist/src/gate/adapters/claude-code.d.ts +33 -0
  23. package/dist/src/gate/adapters/claude-code.js +193 -0
  24. package/dist/src/gate/adapters/client.d.ts +13 -0
  25. package/dist/src/gate/adapters/client.js +57 -0
  26. package/dist/src/gate/adapters/codex-hook.d.ts +1 -0
  27. package/dist/src/gate/adapters/codex-hook.js +5 -0
  28. package/dist/src/gate/adapters/codex-requirements.d.ts +19 -0
  29. package/dist/src/gate/adapters/codex-requirements.js +56 -0
  30. package/dist/src/gate/adapters/codex.d.ts +16 -0
  31. package/dist/src/gate/adapters/codex.js +574 -0
  32. package/dist/src/gate/adapters/hook-main.d.ts +7 -0
  33. package/dist/src/gate/adapters/hook-main.js +35 -0
  34. package/dist/src/gate/adapters/host-pid.d.ts +1 -0
  35. package/dist/src/gate/adapters/host-pid.js +20 -0
  36. package/dist/src/gate/admission.d.ts +54 -0
  37. package/dist/src/gate/admission.js +490 -0
  38. package/dist/src/gate/contract.d.ts +51 -0
  39. package/dist/src/gate/contract.js +94 -0
  40. package/dist/src/gate/decision-log.d.ts +38 -0
  41. package/dist/src/gate/decision-log.js +251 -0
  42. package/dist/src/gate/generations.d.ts +67 -0
  43. package/dist/src/gate/generations.js +518 -0
  44. package/dist/src/gate/proc.d.ts +31 -0
  45. package/dist/src/gate/proc.js +79 -0
  46. package/dist/src/gate/refresh.d.ts +11 -0
  47. package/dist/src/gate/refresh.js +30 -0
  48. package/dist/src/gate/run-verifier.d.ts +23 -0
  49. package/dist/src/gate/run-verifier.js +89 -0
  50. package/dist/src/gate/service.d.ts +80 -0
  51. package/dist/src/gate/service.js +722 -0
  52. package/dist/src/gate/strict-json.d.ts +11 -0
  53. package/dist/src/gate/strict-json.js +190 -0
  54. package/dist/src/gate/trust-store.d.ts +36 -0
  55. package/dist/src/gate/trust-store.js +251 -0
  56. package/dist/src/gate/verifier-worker.d.ts +8 -0
  57. package/dist/src/gate/verifier-worker.js +66 -0
  58. package/dist/src/index.d.ts +2 -0
  59. package/dist/src/index.js +2 -0
  60. package/dist/src/keys.d.ts +4 -0
  61. package/dist/src/keys.js +85 -30
  62. package/dist/src/main-module.js +1 -1
  63. package/dist/src/names.js +2 -4
  64. package/dist/src/policy.d.ts +173 -6
  65. package/dist/src/policy.js +685 -54
  66. package/dist/src/recovery-admin.d.ts +173 -0
  67. package/dist/src/recovery-admin.js +400 -0
  68. package/dist/src/revocations.js +3 -1
  69. package/dist/src/root-events.d.ts +107 -0
  70. package/dist/src/root-events.js +376 -0
  71. package/dist/src/time.d.ts +19 -3
  72. package/dist/src/time.js +50 -8
  73. package/dist/src/timestamp.d.ts +61 -0
  74. package/dist/src/timestamp.js +107 -0
  75. package/dist/src/tree-digest.d.ts +4 -0
  76. package/dist/src/tree-digest.js +41 -16
  77. package/dist/src/trust-root.d.ts +5 -0
  78. package/dist/src/trust-root.js +34 -13
  79. package/dist/src/verify.d.ts +69 -13
  80. package/dist/src/verify.js +309 -61
  81. package/docs/hosts/adapter-interface.md +8 -2
  82. package/docs/hosts/github-action.md +3 -3
  83. package/docs/hosts/pi.md +10 -3
  84. package/docs/spec/gui-admin-rack-v1.md +289 -0
  85. package/docs/spec/root-recovery-v1.md +451 -0
  86. package/docs/spec/skill-certificate-v1.md +1 -1
  87. package/docs/spec/skill-tree-v2.md +2 -2
  88. package/docs/spec/trust-documents-v1.md +12 -6
  89. package/docs/spec/verification.md +20 -3
  90. package/docs/threat-model.md +9 -6
  91. package/package.json +49 -44
@@ -0,0 +1,11 @@
1
+ export interface StrictJsonLimits {
2
+ maxBytes: number;
3
+ maxDepth: number;
4
+ maxMembers: number;
5
+ maxStringLength: number;
6
+ }
7
+ export declare const DEFAULT_STRICT_JSON_LIMITS: StrictJsonLimits;
8
+ export declare class StrictJsonError extends Error {
9
+ constructor(reason: string, offset?: number);
10
+ }
11
+ export declare function parseStrictJson(bytes: Uint8Array, limits?: StrictJsonLimits): unknown;
@@ -0,0 +1,190 @@
1
+ // Strict parser for untrusted, non-canonical JSON (host hook input, gate IPC).
2
+ // JSON.parse silently keeps the last duplicate member, so this is a small
3
+ // recursive-descent parser. Objects are built with a null prototype AFTER the
4
+ // forbidden-name check (`__proto__`, `constructor`, `prototype` are rejected
5
+ // outright), so no prototype pollution is possible. Errors carry a reason and
6
+ // a character offset only, never input content.
7
+ export const DEFAULT_STRICT_JSON_LIMITS = {
8
+ maxBytes: 64 * 1024,
9
+ maxDepth: 16,
10
+ maxMembers: 256,
11
+ maxStringLength: 16 * 1024,
12
+ };
13
+ export class StrictJsonError extends Error {
14
+ constructor(reason, offset) {
15
+ super(offset === undefined ? reason : `${reason} at offset ${offset}`);
16
+ this.name = 'StrictJsonError';
17
+ }
18
+ }
19
+ const FORBIDDEN_NAMES = new Set(['__proto__', 'constructor', 'prototype']);
20
+ const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
21
+ const NUMBER_PATTERN = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/u;
22
+ const SIMPLE_ESCAPES = {
23
+ '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t',
24
+ };
25
+ export function parseStrictJson(bytes, limits = DEFAULT_STRICT_JSON_LIMITS) {
26
+ if (bytes.length > limits.maxBytes)
27
+ throw new StrictJsonError('input exceeds byte limit');
28
+ let text;
29
+ try {
30
+ text = decoder.decode(bytes);
31
+ }
32
+ catch {
33
+ throw new StrictJsonError('input is not valid UTF-8');
34
+ }
35
+ if (text.charCodeAt(0) === 0xfeff)
36
+ throw new StrictJsonError('byte order mark not allowed', 0);
37
+ let pos = 0;
38
+ const fail = (reason) => { throw new StrictJsonError(reason, pos); };
39
+ const skipWhitespace = () => {
40
+ while (pos < text.length && ' \t\n\r'.includes(text[pos]))
41
+ pos += 1;
42
+ };
43
+ const parseString = () => {
44
+ pos += 1; // opening quote
45
+ let out = '';
46
+ for (;;) {
47
+ if (pos >= text.length)
48
+ fail('unterminated string');
49
+ const ch = text[pos];
50
+ if (ch === '"') {
51
+ pos += 1;
52
+ return out;
53
+ }
54
+ if (ch.charCodeAt(0) < 0x20)
55
+ fail('control character in string');
56
+ if (ch === '\\') {
57
+ pos += 1;
58
+ const esc = text[pos];
59
+ if (esc === 'u') {
60
+ const unit = readHex4();
61
+ if (unit >= 0xdc00 && unit <= 0xdfff)
62
+ fail('lone low surrogate');
63
+ if (unit >= 0xd800 && unit <= 0xdbff) {
64
+ if (text[pos] !== '\\' || text[pos + 1] !== 'u')
65
+ fail('lone high surrogate');
66
+ pos += 1;
67
+ const low = readHex4();
68
+ if (low < 0xdc00 || low > 0xdfff)
69
+ fail('lone high surrogate');
70
+ out += String.fromCharCode(unit, low);
71
+ }
72
+ else {
73
+ out += String.fromCharCode(unit);
74
+ }
75
+ }
76
+ else if (esc !== undefined && esc in SIMPLE_ESCAPES) {
77
+ out += SIMPLE_ESCAPES[esc];
78
+ pos += 1;
79
+ }
80
+ else {
81
+ fail('invalid escape');
82
+ }
83
+ }
84
+ else {
85
+ out += ch;
86
+ pos += 1;
87
+ }
88
+ if (out.length > limits.maxStringLength)
89
+ fail('string exceeds length limit');
90
+ }
91
+ };
92
+ // pos is on the 'u'; leaves pos after the four hex digits.
93
+ const readHex4 = () => {
94
+ const hex = text.slice(pos + 1, pos + 5);
95
+ if (!/^[0-9A-Fa-f]{4}$/u.test(hex))
96
+ fail('invalid unicode escape');
97
+ pos += 5;
98
+ return Number.parseInt(hex, 16);
99
+ };
100
+ const parseValue = (depth) => {
101
+ skipWhitespace();
102
+ const ch = text[pos];
103
+ if (ch === '{' || ch === '[') {
104
+ if (depth >= limits.maxDepth)
105
+ fail('nesting exceeds depth limit');
106
+ return ch === '{' ? parseObject(depth + 1) : parseArray(depth + 1);
107
+ }
108
+ if (ch === '"')
109
+ return parseString();
110
+ for (const [word, value] of [['true', true], ['false', false], ['null', null]]) {
111
+ if (text.startsWith(word, pos)) {
112
+ pos += word.length;
113
+ return value;
114
+ }
115
+ }
116
+ const match = NUMBER_PATTERN.exec(text.slice(pos, pos + 400));
117
+ if (!match)
118
+ return fail('unexpected token');
119
+ const number = Number(match[0]);
120
+ if (!Number.isFinite(number))
121
+ fail('number out of range');
122
+ pos += match[0].length;
123
+ return number;
124
+ };
125
+ const parseArray = (depth) => {
126
+ pos += 1;
127
+ const out = [];
128
+ skipWhitespace();
129
+ if (text[pos] === ']') {
130
+ pos += 1;
131
+ return out;
132
+ }
133
+ for (;;) {
134
+ if (out.length >= limits.maxMembers)
135
+ fail('array exceeds member limit');
136
+ out.push(parseValue(depth));
137
+ skipWhitespace();
138
+ if (text[pos] === ',') {
139
+ pos += 1;
140
+ continue;
141
+ }
142
+ if (text[pos] === ']') {
143
+ pos += 1;
144
+ return out;
145
+ }
146
+ fail('expected "," or "]"');
147
+ }
148
+ };
149
+ const parseObject = (depth) => {
150
+ pos += 1;
151
+ const out = Object.create(null);
152
+ skipWhitespace();
153
+ if (text[pos] === '}') {
154
+ pos += 1;
155
+ return out;
156
+ }
157
+ for (;;) {
158
+ skipWhitespace();
159
+ if (text[pos] !== '"')
160
+ fail('expected member name');
161
+ const name = parseString();
162
+ if (FORBIDDEN_NAMES.has(name))
163
+ fail('forbidden member name');
164
+ if (Object.hasOwn(out, name))
165
+ fail('duplicate member name');
166
+ if (Object.keys(out).length >= limits.maxMembers)
167
+ fail('object exceeds member limit');
168
+ skipWhitespace();
169
+ if (text[pos] !== ':')
170
+ fail('expected ":"');
171
+ pos += 1;
172
+ out[name] = parseValue(depth);
173
+ skipWhitespace();
174
+ if (text[pos] === ',') {
175
+ pos += 1;
176
+ continue;
177
+ }
178
+ if (text[pos] === '}') {
179
+ pos += 1;
180
+ return out;
181
+ }
182
+ fail('expected "," or "}"');
183
+ }
184
+ };
185
+ const value = parseValue(0);
186
+ skipWhitespace();
187
+ if (pos !== text.length)
188
+ fail('trailing data');
189
+ return value;
190
+ }
@@ -0,0 +1,36 @@
1
+ import { type MinimumVersions, type TrustContext } from '../verify.ts';
2
+ export type NotReadyReason = 'no-state' | 'state-corrupt' | 'list-expired' | 'trust-root-expired' | 'clock-moved-backwards';
3
+ export type CurrentTrust = {
4
+ ready: true;
5
+ context: TrustContext;
6
+ versions: MinimumVersions;
7
+ } | {
8
+ ready: false;
9
+ reason: NotReadyReason;
10
+ };
11
+ export type AcceptResult = {
12
+ ok: true;
13
+ changed: boolean;
14
+ } | {
15
+ ok: false;
16
+ reason: NotReadyReason | 'rejected';
17
+ message: string;
18
+ };
19
+ export interface TrustStoreOptions {
20
+ rootFingerprint: string;
21
+ now: Date;
22
+ /** Extra freshness limit measured from the list's signed issued_at; can only be stricter than expires_at. */
23
+ maxListAgeMs?: number;
24
+ /** Tests only: injection points to make interleavings deterministic. Never set in production. */
25
+ testHooks?: {
26
+ beforeManifestWrite?: () => Promise<void>;
27
+ };
28
+ }
29
+ export interface TrustStore {
30
+ accept(docs: {
31
+ trustRootBytes: Uint8Array;
32
+ revocationsBytes: Uint8Array;
33
+ }, now: Date): Promise<AcceptResult>;
34
+ current(now: Date): Promise<CurrentTrust>;
35
+ }
36
+ export declare function openTrustStore(dir: string, options: TrustStoreOptions): Promise<TrustStore>;
@@ -0,0 +1,251 @@
1
+ // Exactly ONE writer process per directory is supported (the root service guarantees this in a later packet).
2
+ // Every operation re-reads manifest.json and reloads the state if another instance changed it, so a stale or
3
+ // sequential second instance is safe; truly simultaneous commits from two processes are not supported.
4
+ // Remaining limits (by design):
5
+ // - The directory must be root-only: anyone who can write it can replay an older complete committed set
6
+ // (manifest + documents) undetectably.
7
+ // - The persisted clock high-water means a single far-future `now` locks the store out until time catches up
8
+ // (intended; protect the clock).
9
+ // - Tampering after open is detected only on the next open.
10
+ import { createHash } from 'node:crypto';
11
+ import { constants as fsConstants } from 'node:fs';
12
+ import { lstat, mkdir, open, readdir, unlink } from 'node:fs/promises';
13
+ import path from 'node:path';
14
+ import { canonicalBytes, exactKeys, MAX_CANONICAL_JSON_BYTES, parseCanonicalJsonBytes, requirePositiveInteger, requireString } from "../canonical-json.js";
15
+ import { readRegularFile, writeFileAtomic } from "../fs-safe.js";
16
+ import { readRevocationsForUpdate } from "../revocations.js";
17
+ import { CLOCK_SKEW_MS, formatTimestamp, parseTimestamp, requireValidDate } from "../time.js";
18
+ import { readTrustRootForUpdate } from "../trust-root.js";
19
+ import { loadTrustContext } from "../verify.js";
20
+ const MANIFEST = 'manifest.json';
21
+ const MANIFEST_TYPE = 'mago.gate-trust-state/v1';
22
+ const TIME_PERSIST_STEP_MS = 60_000;
23
+ const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
24
+ function manifestJson(m) {
25
+ const entry = (e) => ({ file: e.file, sha256: e.sha256, version: e.version });
26
+ return canonicalBytes({
27
+ type: MANIFEST_TYPE, trust_root: entry(m.trustRoot), revocations: entry(m.revocations), high_time: formatTimestamp(m.highTime),
28
+ });
29
+ }
30
+ function parseEntry(value, label) {
31
+ const e = exactKeys(value, ['file', 'sha256', 'version'], label);
32
+ const file = requireString(e.file, `${label} file`, 128);
33
+ const digest = requireString(e.sha256, `${label} sha256`, 64);
34
+ if (!/^[0-9a-f]{64}$/u.test(digest) || path.basename(file) !== file || file.startsWith('.'))
35
+ throw new Error(`${label} is malformed`);
36
+ return { file, sha256: digest, version: requirePositiveInteger(e.version, `${label} version`) };
37
+ }
38
+ function parseManifest(bytes) {
39
+ const m = exactKeys(parseCanonicalJsonBytes(bytes, 'trust-state manifest'), ['type', 'trust_root', 'revocations', 'high_time'], 'manifest');
40
+ if (m.type !== MANIFEST_TYPE)
41
+ throw new Error('manifest has unsupported type');
42
+ return {
43
+ trustRoot: parseEntry(m.trust_root, 'manifest trust_root'),
44
+ revocations: parseEntry(m.revocations, 'manifest revocations'),
45
+ highTime: parseTimestamp(m.high_time, 'manifest high_time'),
46
+ };
47
+ }
48
+ async function fsyncDir(dir) {
49
+ const handle = await open(dir, fsConstants.O_RDONLY | (fsConstants.O_DIRECTORY ?? 0));
50
+ try {
51
+ await handle.sync();
52
+ }
53
+ finally {
54
+ await handle.close();
55
+ }
56
+ }
57
+ /** Reads and re-verifies the committed state. Throws on any mismatch (the caller maps that to state-corrupt). */
58
+ async function loadState(dir, rootFingerprint) {
59
+ let manifestBytes;
60
+ try {
61
+ manifestBytes = await readRegularFile(path.join(dir, MANIFEST), 'trust-state manifest', MAX_CANONICAL_JSON_BYTES);
62
+ }
63
+ catch (error) {
64
+ if (error?.code !== 'ENOENT')
65
+ throw error;
66
+ // A missing manifest is a fresh store only if no committed document exists; otherwise rollback state was lost.
67
+ if ((await readdir(dir)).some((name) => !/^\..*\.tmp$/u.test(name)))
68
+ throw new Error('manifest is missing but the store is not empty');
69
+ return null;
70
+ }
71
+ const manifest = parseManifest(manifestBytes);
72
+ const read = async (entry) => {
73
+ const bytes = await readRegularFile(path.join(dir, entry.file), entry.file, MAX_CANONICAL_JSON_BYTES);
74
+ if (sha256(bytes) !== entry.sha256)
75
+ throw new Error(`${entry.file} does not match the manifest`);
76
+ return bytes;
77
+ };
78
+ const trustRootBytes = await read(manifest.trustRoot);
79
+ const revocationsBytes = await read(manifest.revocations);
80
+ // Signatures only: expiry is judged per call in current().
81
+ const trustRoot = readTrustRootForUpdate(trustRootBytes, rootFingerprint);
82
+ const revocations = readRevocationsForUpdate(revocationsBytes, trustRoot.root.keyId, trustRoot.root.publicKey);
83
+ if (trustRoot.version !== manifest.trustRoot.version || revocations.version !== manifest.revocations.version)
84
+ throw new Error('document versions do not match the manifest');
85
+ return { manifest, manifestBytes, trustRootBytes, revocationsBytes };
86
+ }
87
+ export async function openTrustStore(dir, options) {
88
+ requireValidDate(options.now, 'Open time');
89
+ dir = path.resolve(dir);
90
+ await mkdir(dir, { mode: 0o700 }).catch((error) => {
91
+ if (error?.code !== 'EEXIST')
92
+ throw error;
93
+ });
94
+ const info = await lstat(dir);
95
+ if (info.isSymbolicLink() || !info.isDirectory())
96
+ throw new Error('trust store directory must be a real directory, not a symlink');
97
+ if ((info.mode & 0o022) !== 0)
98
+ throw new Error('trust store directory must not be group- or world-writable');
99
+ let corrupt = false;
100
+ let state = null;
101
+ try {
102
+ state = await loadState(dir, options.rootFingerprint);
103
+ }
104
+ catch {
105
+ corrupt = true;
106
+ }
107
+ // Highest trusted time seen, in memory; persisted in the manifest in coarse steps.
108
+ let highTime = state?.manifest.highTime ?? options.now;
109
+ const { rootFingerprint, maxListAgeMs } = options;
110
+ const clockBack = (now) => now.getTime() < highTime.getTime() - CLOCK_SKEW_MS;
111
+ async function writeManifest(manifest) {
112
+ const bytes = manifestJson(manifest);
113
+ await writeFileAtomic(path.join(dir, MANIFEST), bytes, 0o600);
114
+ await fsyncDir(dir);
115
+ return bytes;
116
+ }
117
+ /** Inside the lock: reload from disk if manifest.json is not byte-identical to what this instance last held. */
118
+ async function refresh() {
119
+ if (corrupt)
120
+ return;
121
+ let disk = null;
122
+ try {
123
+ disk = await readRegularFile(path.join(dir, MANIFEST), 'trust-state manifest', MAX_CANONICAL_JSON_BYTES);
124
+ }
125
+ catch (error) {
126
+ if (error?.code !== 'ENOENT') {
127
+ corrupt = true;
128
+ return;
129
+ }
130
+ }
131
+ const held = state?.manifestBytes ?? null;
132
+ if (disk === null ? held === null : held !== null && disk.equals(held))
133
+ return;
134
+ try {
135
+ const previous = state;
136
+ state = await loadState(dir, rootFingerprint);
137
+ // A running instance never accepts a reload that is empty or older than what it held.
138
+ if (previous && (!state
139
+ || state.manifest.trustRoot.version < previous.manifest.trustRoot.version
140
+ || state.manifest.revocations.version < previous.manifest.revocations.version)) {
141
+ corrupt = true;
142
+ return;
143
+ }
144
+ if (state && state.manifest.highTime > highTime)
145
+ highTime = state.manifest.highTime;
146
+ }
147
+ catch {
148
+ corrupt = true;
149
+ }
150
+ }
151
+ async function advance(now) {
152
+ if (now > highTime)
153
+ highTime = now;
154
+ // shortcut: persisted time lags by up to a minute, so a restart can forget that much; upgrade if tighter is needed.
155
+ if (state && highTime.getTime() - state.manifest.highTime.getTime() >= TIME_PERSIST_STEP_MS) {
156
+ const next = { ...state.manifest, highTime };
157
+ await options.testHooks?.beforeManifestWrite?.(); // tests only: pauses the time-persistence write
158
+ // a failed refresh must not break decisions; the old persisted time stays
159
+ const manifestBytes = await writeManifest(next).catch(() => null);
160
+ if (manifestBytes)
161
+ state = { ...state, manifest: next, manifestBytes };
162
+ }
163
+ }
164
+ // One promise-chain mutex: each operation runs to completion (and always releases) before the next starts.
165
+ let tail = Promise.resolve();
166
+ const locked = (fn) => {
167
+ const run = tail.then(fn);
168
+ tail = run.catch(() => { });
169
+ return run;
170
+ };
171
+ return {
172
+ current: (now) => locked(async () => {
173
+ requireValidDate(now, 'Time');
174
+ await refresh();
175
+ if (corrupt)
176
+ return { ready: false, reason: 'state-corrupt' };
177
+ if (!state)
178
+ return { ready: false, reason: 'no-state' };
179
+ if (clockBack(now))
180
+ return { ready: false, reason: 'clock-moved-backwards' };
181
+ const loaded = loadTrustContext({ trustRootBytes: state.trustRootBytes, revocationsBytes: state.revocationsBytes, rootKeyId: rootFingerprint, now });
182
+ if (!loaded.ok) {
183
+ if (loaded.verdict !== 'EXPIRED')
184
+ return { ready: false, reason: 'state-corrupt' };
185
+ return { ready: false, reason: loaded.reason.startsWith('trust root') ? 'trust-root-expired' : 'list-expired' };
186
+ }
187
+ const { revocations, trustRoot } = loaded.context;
188
+ if (maxListAgeMs !== undefined && revocations.issuedAt.getTime() + maxListAgeMs <= now.getTime())
189
+ return { ready: false, reason: 'list-expired' };
190
+ await advance(now);
191
+ return { ready: true, context: loaded.context, versions: { trustRootVersion: trustRoot.version, revocationsVersion: revocations.version } };
192
+ }),
193
+ accept: ({ trustRootBytes, revocationsBytes }, now) => locked(async () => {
194
+ requireValidDate(now, 'Time');
195
+ const reject = (reason, message) => ({ ok: false, reason, message });
196
+ await refresh();
197
+ if (corrupt)
198
+ return reject('state-corrupt', 'existing trust state is corrupt; an administrator must reset it');
199
+ if (clockBack(now))
200
+ return reject('clock-moved-backwards', 'clock is earlier than the highest trusted time');
201
+ if (trustRootBytes.length > MAX_CANONICAL_JSON_BYTES || revocationsBytes.length > MAX_CANONICAL_JSON_BYTES)
202
+ return reject('rejected', 'document exceeds the size limit');
203
+ const loaded = loadTrustContext({
204
+ trustRootBytes, revocationsBytes, rootKeyId: rootFingerprint, now,
205
+ minimum: state ? { trustRootVersion: state.manifest.trustRoot.version, revocationsVersion: state.manifest.revocations.version } : undefined,
206
+ });
207
+ if (!loaded.ok)
208
+ return reject('rejected', loaded.reason);
209
+ const { trustRoot, revocations } = loaded.context;
210
+ if (maxListAgeMs !== undefined && revocations.issuedAt.getTime() + maxListAgeMs <= now.getTime())
211
+ return reject('rejected', 'revocation list is older than the configured maximum age');
212
+ const sameTrustRoot = state !== null && Buffer.from(trustRootBytes).equals(state.trustRootBytes);
213
+ const sameList = state !== null && Buffer.from(revocationsBytes).equals(state.revocationsBytes);
214
+ if (state && !sameTrustRoot && trustRoot.version === state.manifest.trustRoot.version)
215
+ return reject('rejected', 'a different trust root with the same version was already accepted');
216
+ if (state && !sameList && revocations.version === state.manifest.revocations.version)
217
+ return reject('rejected', 'a different revocation list with the same version was already accepted');
218
+ if (sameTrustRoot && sameList) {
219
+ await advance(now);
220
+ return { ok: true, changed: false };
221
+ }
222
+ // Content-addressed names: the old files stay intact until the new manifest is in place.
223
+ const trustHash = sha256(trustRootBytes);
224
+ const listHash = sha256(revocationsBytes);
225
+ const previous = state?.manifest;
226
+ const manifest = {
227
+ trustRoot: { file: `trust-root.${trustHash}.json`, sha256: trustHash, version: trustRoot.version },
228
+ revocations: { file: `revocations.${listHash}.json`, sha256: listHash, version: revocations.version },
229
+ highTime: now > highTime ? now : highTime,
230
+ };
231
+ let manifestBytes;
232
+ try {
233
+ await writeFileAtomic(path.join(dir, manifest.trustRoot.file), trustRootBytes, 0o600);
234
+ await writeFileAtomic(path.join(dir, manifest.revocations.file), revocationsBytes, 0o600);
235
+ await fsyncDir(dir);
236
+ manifestBytes = await writeManifest(manifest); // last: this is the commit point
237
+ }
238
+ catch (error) {
239
+ return reject('rejected', `could not commit trust state: ${error.message}`);
240
+ }
241
+ state = { manifest, manifestBytes, trustRootBytes: Buffer.from(trustRootBytes), revocationsBytes: Buffer.from(revocationsBytes) };
242
+ highTime = manifest.highTime;
243
+ // Best-effort cleanup: only files the previous manifest referenced and the new one does not.
244
+ const keep = new Set([manifest.trustRoot.file, manifest.revocations.file]);
245
+ for (const name of previous ? [previous.trustRoot.file, previous.revocations.file] : [])
246
+ if (!keep.has(name))
247
+ await unlink(path.join(dir, name)).catch(() => { });
248
+ return { ok: true, changed: true };
249
+ }),
250
+ };
251
+ }
@@ -0,0 +1,8 @@
1
+ interface WorkerRequest {
2
+ request_id: string;
3
+ skill_dir: string;
4
+ skill_name: string;
5
+ policy_path: string;
6
+ }
7
+ export declare function parseWorkerRequest(bytes: Uint8Array): WorkerRequest;
8
+ export {};
@@ -0,0 +1,66 @@
1
+ // Verifier child process: one bounded request on stdin, one result line on stdout. Read-only: trust is
2
+ // loaded without recording versions, and no decision log or state file is written (the parent owns that).
3
+ // Any internal failure writes nothing to stdout, a fixed line to stderr, and exits nonzero.
4
+ import path from 'node:path';
5
+ import { isRecord } from "../canonical-json.js";
6
+ import { isMainModule } from "../main-module.js";
7
+ import { validateSkillName } from "../names.js";
8
+ import { loadPolicy, loadPolicyTrust, verifyWithPolicy } from "../policy.js";
9
+ import { unverifiable } from "../verify.js";
10
+ import { parseStrictJson } from "./strict-json.js";
11
+ const MAX_REQUEST_BYTES = 16 * 1024;
12
+ const TOKEN_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/u;
13
+ function absolutePath(value, label) {
14
+ if (typeof value !== 'string' || value.includes('\0') || !path.isAbsolute(value)
15
+ || value.split('/').includes('..') || path.normalize(value) !== value)
16
+ throw new Error(`${label} must be a normalised absolute path`);
17
+ return value;
18
+ }
19
+ export function parseWorkerRequest(bytes) {
20
+ const raw = parseStrictJson(bytes);
21
+ if (!isRecord(raw) || raw['v'] !== 1)
22
+ throw new Error('bad request');
23
+ const keys = ['v', 'request_id', 'skill_dir', 'skill_name', 'policy_path'];
24
+ if (Object.keys(raw).length !== keys.length || !keys.every((key) => Object.hasOwn(raw, key)))
25
+ throw new Error('bad request');
26
+ const id = raw['request_id'];
27
+ if (typeof id !== 'string' || !TOKEN_PATTERN.test(id))
28
+ throw new Error('bad request_id');
29
+ return {
30
+ request_id: id,
31
+ skill_dir: absolutePath(raw['skill_dir'], 'skill_dir'),
32
+ skill_name: validateSkillName(raw['skill_name']),
33
+ policy_path: absolutePath(raw['policy_path'], 'policy_path'),
34
+ };
35
+ }
36
+ async function readRequest() {
37
+ const chunks = [];
38
+ let size = 0;
39
+ for await (const chunk of process.stdin) {
40
+ size += chunk.length;
41
+ if (size > MAX_REQUEST_BYTES)
42
+ throw new Error('request too large');
43
+ chunks.push(chunk);
44
+ }
45
+ return Buffer.concat(chunks);
46
+ }
47
+ async function main() {
48
+ const request = parseWorkerRequest(await readRequest());
49
+ const now = new Date();
50
+ const policy = await loadPolicy(request.policy_path);
51
+ const trust = await loadPolicyTrust(policy, now, { recordVersions: false });
52
+ // Without an explicit name the engine derives it from SKILL.md; it must equal the requested one.
53
+ const result = trust.ok
54
+ ? await verifyWithPolicy(policy, request.skill_dir, { now, context: trust.context })
55
+ : unverifiable(request.skill_dir, request.skill_name, trust.reason, now, trust.verdict);
56
+ const mismatch = result.skillName !== request.skill_name;
57
+ const verdict = mismatch ? 'UNVERIFIABLE' : result.verdict;
58
+ const digest = mismatch ? null : result.digest;
59
+ process.stdout.write(`${JSON.stringify({ v: 1, request_id: request.request_id, verdict, ...(digest ? { digest } : {}) })}\n`);
60
+ }
61
+ if (isMainModule(import.meta.url)) {
62
+ main().catch(() => {
63
+ process.stderr.write('verifier failed\n');
64
+ process.exitCode = 1;
65
+ });
66
+ }
@@ -8,6 +8,8 @@ export * from './trust-root.ts';
8
8
  export * from './revocations.ts';
9
9
  export * from './certificate.ts';
10
10
  export * from './verify.ts';
11
+ export * from './root-events.ts';
12
+ export * from './timestamp.ts';
11
13
  export * from './policy.ts';
12
14
  export * from './admin.ts';
13
15
  export * from './diff.ts';
package/dist/src/index.js CHANGED
@@ -8,6 +8,8 @@ export * from "./trust-root.js";
8
8
  export * from "./revocations.js";
9
9
  export * from "./certificate.js";
10
10
  export * from "./verify.js";
11
+ export * from "./root-events.js";
12
+ export * from "./timestamp.js";
11
13
  export * from "./policy.js";
12
14
  export * from "./admin.js";
13
15
  export * from "./diff.js";
@@ -18,4 +18,8 @@ export declare function generateKeyPair(privatePath: string, publicPath: string)
18
18
  publicPath: string;
19
19
  }>;
20
20
  export declare function loadPrivateKey(filePath: string): Promise<PrivateKeyInfo>;
21
+ /** Parses a PKCS#8 Ed25519 PEM from bytes the caller already read. The caller zeroes `pem`. */
22
+ export declare function loadPrivateKeyBytes(pem: Buffer): PrivateKeyInfo;
21
23
  export declare function loadPublicKey(filePath: string): Promise<PublicKeyInfo>;
24
+ /** Parses an Ed25519 SPKI PEM from bytes the caller already read (at most 64 KiB). */
25
+ export declare function loadPublicKeyBytes(pem: Buffer): PublicKeyInfo;