@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,107 @@
1
+ import { canonicalBytes, exactKeys, parseCanonicalJsonBytes, requirePositiveInteger } from "./canonical-json.js";
2
+ import { envelopeBytes, parseEnvelope, signEnvelope, verifyEnvelopeSignature } from "./dsse.js";
3
+ import { parseSpki, validateKeyId } from "./keys.js";
4
+ import { CLOCK_SKEW_MS, formatTimestamp, parseTimestamp, requireValidDate } from "./time.js";
5
+ export const TIMESTAMP_PAYLOAD_TYPE = 'application/vnd.mago-ski.timestamp+json';
6
+ export const TIMESTAMP_TYPE = 'mago.timestamp/v1';
7
+ export const MAX_TIMESTAMP_BYTES = 64 * 1024;
8
+ export const DEFAULT_MAX_TIMESTAMP_LIFETIME = '24h';
9
+ export const MAX_TIMESTAMP_LIFETIME_MS = 7 * 24 * 60 * 60 * 1000;
10
+ const SHA256_HEX = /^[0-9a-f]{64}$/u;
11
+ /** The timestamp is older than one this host has already seen; callers match on the class, not the message. */
12
+ export class TimestampRollbackError extends Error {
13
+ }
14
+ /** The timestamp names other document digests than the files the host read. */
15
+ export class TimestampBindingError extends Error {
16
+ }
17
+ function requireSha256(value, label) {
18
+ if (typeof value !== 'string' || !SHA256_HEX.test(value))
19
+ throw new Error(`${label} must be 64 lowercase hex characters`);
20
+ return value;
21
+ }
22
+ function requireCount(value, label) {
23
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
24
+ throw new Error(`${label} must be a non-negative integer`);
25
+ return value;
26
+ }
27
+ export function timestampPayload(timestamp) {
28
+ return {
29
+ type: TIMESTAMP_TYPE,
30
+ version: timestamp.version,
31
+ issued_at: formatTimestamp(timestamp.issuedAt),
32
+ expires_at: formatTimestamp(timestamp.expiresAt),
33
+ timestamp_key: { key_id: timestamp.key.keyId, public_key: timestamp.key.spki },
34
+ root_events: { sha256: timestamp.rootEvents.sha256, count: timestamp.rootEvents.count },
35
+ trust_root: { sha256: timestamp.trustRoot.sha256, version: timestamp.trustRoot.version },
36
+ revocations: { sha256: timestamp.revocations.sha256, version: timestamp.revocations.version },
37
+ };
38
+ }
39
+ export function signTimestamp(timestamp, privateKey) {
40
+ return envelopeBytes(signEnvelope(TIMESTAMP_PAYLOAD_TYPE, canonicalBytes(timestampPayload(timestamp)), timestamp.key.keyId, privateKey));
41
+ }
42
+ export function parseTimestampPayload(bytes) {
43
+ const label = 'timestamp';
44
+ const value = exactKeys(parseCanonicalJsonBytes(bytes, label), ['type', 'version', 'issued_at', 'expires_at', 'timestamp_key', 'root_events', 'trust_root', 'revocations'], label);
45
+ if (value.type !== TIMESTAMP_TYPE)
46
+ throw new Error(`${label} has unsupported type`);
47
+ const keyEntry = exactKeys(value.timestamp_key, ['key_id', 'public_key'], `${label} timestamp_key`);
48
+ const key = parseSpki(keyEntry.public_key, `${label} timestamp_key public_key`, validateKeyId(keyEntry.key_id, `${label} timestamp_key key_id`));
49
+ const events = exactKeys(value.root_events, ['sha256', 'count'], `${label} root_events`);
50
+ const trustRoot = exactKeys(value.trust_root, ['sha256', 'version'], `${label} trust_root`);
51
+ const revocations = exactKeys(value.revocations, ['sha256', 'version'], `${label} revocations`);
52
+ const issuedAt = parseTimestamp(value.issued_at, `${label} issued_at`);
53
+ const expiresAt = parseTimestamp(value.expires_at, `${label} expires_at`);
54
+ if (expiresAt <= issuedAt)
55
+ throw new Error(`${label} expires before it is issued`);
56
+ return {
57
+ version: requirePositiveInteger(value.version, `${label} version`),
58
+ issuedAt,
59
+ expiresAt,
60
+ key,
61
+ rootEvents: { sha256: requireSha256(events.sha256, `${label} root_events sha256`), count: requireCount(events.count, `${label} root_events count`) },
62
+ trustRoot: { sha256: requireSha256(trustRoot.sha256, `${label} trust_root sha256`), version: requirePositiveInteger(trustRoot.version, `${label} trust_root version`) },
63
+ revocations: { sha256: requireSha256(revocations.sha256, `${label} revocations sha256`), version: requirePositiveInteger(revocations.version, `${label} revocations version`) },
64
+ };
65
+ }
66
+ /** Reads a timestamp signed by `keyId` without the time checks (for the signing job, to find the next version). */
67
+ export function readTimestampForUpdate(bytes, keyId) {
68
+ if (bytes.byteLength > MAX_TIMESTAMP_BYTES)
69
+ throw new Error(`timestamp exceeds the ${MAX_TIMESTAMP_BYTES}-byte limit`);
70
+ const envelope = parseEnvelope(bytes, 'timestamp');
71
+ if (envelope.payloadType !== TIMESTAMP_PAYLOAD_TYPE)
72
+ throw new Error('timestamp has the wrong payload type');
73
+ if (envelope.signatures[0].keyid !== keyId)
74
+ throw new Error(`timestamp is not signed by the active timestamp key ${keyId}`);
75
+ const timestamp = parseTimestampPayload(envelope.payloadBytes);
76
+ if (timestamp.key.keyId !== keyId)
77
+ throw new Error('timestamp names a different timestamp key than the one that signed it');
78
+ if (!verifyEnvelopeSignature(envelope, timestamp.key.publicKey))
79
+ throw new Error('timestamp signature is invalid');
80
+ return timestamp;
81
+ }
82
+ /**
83
+ * Verifies a timestamp against the active timestamp key, the clock, the policy's lifetime cap and the lowest version
84
+ * the host accepts, then checks that it names exactly the files the host read. Throws with the reason on any failure.
85
+ * The trust root and revocation list versions are compared by the caller once those documents are parsed.
86
+ */
87
+ export function verifyTimestamp(bytes, options) {
88
+ requireValidDate(options.now, 'Verification time');
89
+ const timestamp = readTimestampForUpdate(bytes, options.keyId);
90
+ const now = options.now.getTime();
91
+ if (timestamp.issuedAt.getTime() > now + CLOCK_SKEW_MS)
92
+ throw new Error(`timestamp is issued in the future (${formatTimestamp(timestamp.issuedAt)})`);
93
+ if (timestamp.expiresAt.getTime() - timestamp.issuedAt.getTime() > options.maxLifetimeMs)
94
+ throw new Error('timestamp lifetime is longer than the policy\'s freshness max_lifetime');
95
+ if (timestamp.expiresAt.getTime() <= now)
96
+ throw new Error(`timestamp expired at ${formatTimestamp(timestamp.expiresAt)}; the timestamp job may have stopped`);
97
+ if (options.minimumVersion !== undefined && timestamp.version < options.minimumVersion)
98
+ throw new TimestampRollbackError(`timestamp version ${timestamp.version} is older than version ${options.minimumVersion} already seen (rollback)`);
99
+ const { inputs } = options;
100
+ if (timestamp.rootEvents.sha256 !== inputs.rootEvents.sha256 || timestamp.rootEvents.count !== inputs.rootEvents.count)
101
+ throw new TimestampBindingError('the root event log does not match the timestamp');
102
+ if (timestamp.trustRoot.sha256 !== inputs.trustRoot.sha256)
103
+ throw new TimestampBindingError('the trust root does not match the timestamp');
104
+ if (timestamp.revocations.sha256 !== inputs.revocations.sha256)
105
+ throw new TimestampBindingError('the revocation list does not match the timestamp');
106
+ return timestamp;
107
+ }
@@ -1,3 +1,4 @@
1
+ import { type BigIntStats } from 'node:fs';
1
2
  export declare const TREE_PROFILE = "mago.skill-tree/v2";
2
3
  export declare const CERTIFICATE_FILENAME = ".mago-ski-cert.json";
3
4
  export declare const IGNORE_FILENAME = ".skilldigestignore";
@@ -23,6 +24,7 @@ export interface SkillTree {
23
24
  /** Paths left out of the digest: the root `.git`, the in-tree certificate, and `.skilldigestignore` entries. */
24
25
  excluded: string[];
25
26
  }
27
+ export declare function decodeEntryName(name: Buffer): string;
26
28
  /** Executable bit of a regular file. Windows has no POSIX mode bits, so it always reports false there. */
27
29
  export declare function isExecutable(mode: number | bigint): boolean;
28
30
  export declare function sha256Hex(bytes: Uint8Array): string;
@@ -33,6 +35,8 @@ export interface IgnoreRule {
33
35
  directoryOnly: boolean;
34
36
  }
35
37
  export declare function parseIgnoreFile(text: string): IgnoreRule[];
38
+ /** Checks that a Skill root exists and is a real directory, with messages that name the path. */
39
+ export declare function requireSkillRoot(root: string): Promise<BigIntStats>;
36
40
  export declare function compareTreePaths(left: string, right: string): number;
37
41
  /** The tree digest is SHA-256 over the canonical JSON of the profile and the sorted per-file list. */
38
42
  export declare function digestFileList(files: readonly TreeFile[]): string;
@@ -17,10 +17,12 @@ const MAX_IGNORE_BYTES = 64 * 1024;
17
17
  const MAX_IGNORE_PATTERNS = 256;
18
18
  const utf8Decoder = new TextDecoder('utf-8', { fatal: true });
19
19
  const noFollow = fsConstants.O_NOFOLLOW ?? 0;
20
+ // A FIFO swapped in after enumeration must fail the fstat check below, not block open(2).
21
+ const nonBlock = fsConstants.O_NONBLOCK ?? 0;
20
22
  function fail(message) {
21
23
  throw new Error(message);
22
24
  }
23
- function decodeEntryName(name) {
25
+ export function decodeEntryName(name) {
24
26
  let decoded;
25
27
  try {
26
28
  decoded = utf8Decoder.decode(name);
@@ -28,14 +30,17 @@ function decodeEntryName(name) {
28
30
  catch {
29
31
  fail('Skill tree contains a path that is not valid UTF-8');
30
32
  }
31
- if (decoded.length === 0 || decoded === '.' || decoded === '..' ||
32
- decoded.includes('/') || decoded.includes('\\') || decoded.includes(':') ||
33
+ if (decoded.length === 0 ||
34
+ decoded === '.' ||
35
+ decoded === '..' ||
36
+ decoded.includes('/') ||
37
+ decoded.includes('\\') ||
38
+ decoded.includes(':') ||
33
39
  /[. ]$/u.test(decoded) ||
34
40
  /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?$/iu.test(decoded) ||
35
41
  /[\u0000-\u001f\u007f]/u.test(decoded) ||
36
- decoded.normalize('NFC') !== decoded) {
42
+ decoded.normalize('NFC') !== decoded)
37
43
  fail(`Skill tree contains an unsupported path component: ${JSON.stringify(decoded)}`);
38
- }
39
44
  return decoded;
40
45
  }
41
46
  function sameFileVersion(left, right) {
@@ -51,7 +56,7 @@ export function isExecutable(mode) {
51
56
  async function readStable(absolutePath, label, expected) {
52
57
  let handle;
53
58
  try {
54
- handle = await open(absolutePath, fsConstants.O_RDONLY | noFollow);
59
+ handle = await open(absolutePath, fsConstants.O_RDONLY | noFollow | nonBlock);
55
60
  const before = await handle.stat({ bigint: true });
56
61
  if (!before.isFile() || (expected && !sameFileVersion(expected, before)))
57
62
  fail(`Skill file changed while being read: ${label}`);
@@ -98,16 +103,21 @@ export function parseIgnoreFile(text) {
98
103
  const rules = [];
99
104
  for (const rawLine of text.split(/\r?\n/u)) {
100
105
  const line = rawLine.trim();
106
+ const directoryOnly = line.endsWith('/');
107
+ const pattern = directoryOnly ? line.slice(0, -1) : line;
108
+ const segments = pattern.split('/');
101
109
  if (line === '' || line.startsWith('#'))
102
110
  continue;
103
111
  if (rules.length >= MAX_IGNORE_PATTERNS)
104
112
  fail(`${IGNORE_FILENAME} exceeds ${MAX_IGNORE_PATTERNS} patterns`);
105
- const directoryOnly = line.endsWith('/');
106
- const pattern = directoryOnly ? line.slice(0, -1) : line;
107
- const segments = pattern.split('/');
108
- if (pattern === '' || pattern.startsWith('/') || pattern.includes('\\') || /[*?[\]!]/u.test(pattern) ||
113
+ if (pattern === '' ||
114
+ pattern.startsWith('/') ||
115
+ pattern.includes('\\') ||
116
+ /[*?[\]!]/u.test(pattern) ||
109
117
  segments.some((segment) => segment === '' || segment === '.' || segment === '..') ||
110
- pattern === IGNORE_FILENAME || pattern === SKILL_FILENAME || pattern.normalize('NFC') !== pattern) {
118
+ pattern === IGNORE_FILENAME ||
119
+ pattern === SKILL_FILENAME ||
120
+ pattern.normalize('NFC') !== pattern) {
111
121
  fail(`${IGNORE_FILENAME} contains an unsupported pattern: ${JSON.stringify(line)} (use plain relative paths; globs are not supported)`);
112
122
  }
113
123
  rules.push({ pattern, directoryOnly });
@@ -123,10 +133,26 @@ function isIgnored(relativePath, isDirectory, rules) {
123
133
  }
124
134
  return false;
125
135
  }
126
- async function enumerate(root) {
127
- const rootStat = await lstat(root, { bigint: true });
128
- if (!rootStat.isDirectory() || rootStat.isSymbolicLink())
136
+ /** Checks that a Skill root exists and is a real directory, with messages that name the path. */
137
+ export async function requireSkillRoot(root) {
138
+ let rootStat;
139
+ try {
140
+ rootStat = await lstat(root, { bigint: true });
141
+ }
142
+ catch (error) {
143
+ const code = error?.code;
144
+ if (code === 'ENOENT' || code === 'ENOTDIR')
145
+ fail(`Skill directory not found: ${root}`);
146
+ throw error;
147
+ }
148
+ if (rootStat.isSymbolicLink())
129
149
  fail('Skill root must be a real directory, not a symbolic link');
150
+ if (!rootStat.isDirectory())
151
+ fail(`Skill path is not a directory: ${root}`);
152
+ return rootStat;
153
+ }
154
+ async function enumerate(root) {
155
+ const rootStat = await requireSkillRoot(root);
130
156
  const canonicalRoot = await realpath(root);
131
157
  let rules = [];
132
158
  const ignorePath = path.join(canonicalRoot, IGNORE_FILENAME);
@@ -151,9 +177,8 @@ async function enumerate(root) {
151
177
  if (depth > 64)
152
178
  fail('Skill tree exceeds the maximum directory depth of 64');
153
179
  const directoryStat = await lstat(directory, { bigint: true });
154
- if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink()) {
180
+ if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink())
155
181
  fail(`Skill tree contains a changed or symbolic-link directory: ${relativeDirectory || '.'}`);
156
- }
157
182
  const expected = relativeDirectory ? path.join(canonicalRoot, relativeDirectory) : canonicalRoot;
158
183
  if (await realpath(directory) !== expected)
159
184
  fail(`Skill tree directory path changed during traversal: ${relativeDirectory || '.'}`);
@@ -23,6 +23,11 @@ export declare class TrustDocumentError extends Error {
23
23
  }
24
24
  export declare function trustRootPayload(trustRoot: TrustRoot): Record<string, unknown>;
25
25
  export declare function signTrustRoot(trustRoot: TrustRoot, rootPrivateKey: KeyObject): Buffer;
26
+ /**
27
+ * Reads the JSON inside a signed trust root and checks that every part is well formed:
28
+ * the root key, each approver (key, name, scopes, expiry) and the document's own dates.
29
+ * It does not check the signature or whether the trust root has expired; verifyTrustRoot does.
30
+ */
26
31
  export declare function parseTrustRootPayload(bytes: Uint8Array): TrustRoot;
27
32
  /**
28
33
  * Verifies a signed trust root against the pinned root key fingerprint and the current time.
@@ -2,7 +2,7 @@ import { canonicalBytes, exactKeys, parseCanonicalJsonBytes, requireArray, requi
2
2
  import { envelopeBytes, parseEnvelope, signEnvelope, verifyEnvelopeSignature } from "./dsse.js";
3
3
  import { parseSpki, validateKeyId } from "./keys.js";
4
4
  import { validateScope } from "./names.js";
5
- import { formatTimestamp, parseTimestamp } from "./time.js";
5
+ import { formatTimestamp, parseTimestamp, requireValidDate } from "./time.js";
6
6
  export const TRUST_ROOT_PAYLOAD_TYPE = 'application/vnd.mago-ski.trust-root+json';
7
7
  export const TRUST_ROOT_TYPE = 'mago.trust-root/v1';
8
8
  export const MAX_APPROVERS = 256;
@@ -38,31 +38,48 @@ export function signTrustRoot(trustRoot, rootPrivateKey) {
38
38
  const payload = canonicalBytes(trustRootPayload(trustRoot));
39
39
  return envelopeBytes(signEnvelope(TRUST_ROOT_PAYLOAD_TYPE, payload, trustRoot.root.keyId, rootPrivateKey));
40
40
  }
41
+ /** The exact fields each part of a trust-root payload must have: no more, no fewer. */
42
+ const TRUST_ROOT_FIELDS = ['type', 'version', 'issued_at', 'expires_at', 'root', 'approvers'];
43
+ const ROOT_FIELDS = ['key_id', 'public_key'];
44
+ const APPROVER_FIELDS = ['key_id', 'public_key', 'name', 'scopes', 'expires_at'];
45
+ /**
46
+ * Reads the JSON inside a signed trust root and checks that every part is well formed:
47
+ * the root key, each approver (key, name, scopes, expiry) and the document's own dates.
48
+ * It does not check the signature or whether the trust root has expired; verifyTrustRoot does.
49
+ */
41
50
  export function parseTrustRootPayload(bytes) {
42
51
  const label = 'trust-root payload';
43
- const value = exactKeys(parseCanonicalJsonBytes(bytes, label), ['type', 'version', 'issued_at', 'expires_at', 'root', 'approvers'], label);
52
+ const value = exactKeys(parseCanonicalJsonBytes(bytes, label), TRUST_ROOT_FIELDS, label);
44
53
  if (value.type !== TRUST_ROOT_TYPE)
45
54
  throw new Error(`${label} has unsupported type`);
46
- const rootValue = exactKeys(value.root, ['key_id', 'public_key'], `${label} root`);
47
- const root = parseSpki(rootValue.public_key, `${label} root public_key`, validateKeyId(rootValue.key_id, `${label} root key_id`));
55
+ // The root key: its public key must hash to the key_id it is listed under.
56
+ const rootValue = exactKeys(value.root, ROOT_FIELDS, `${label} root`);
57
+ const rootKeyId = validateKeyId(rootValue.key_id, `${label} root key_id`);
58
+ const root = parseSpki(rootValue.public_key, `${label} root public_key`, rootKeyId);
59
+ // The approvers: at most MAX_APPROVERS of them.
60
+ const approverItems = requireArray(value.approvers, `${label} approvers`, MAX_APPROVERS);
48
61
  const approvers = [];
49
- let previous = '';
50
- for (const [index, item] of requireArray(value.approvers, `${label} approvers`, MAX_APPROVERS).entries()) {
62
+ let previousKeyId = '';
63
+ for (const [index, item] of approverItems.entries()) {
51
64
  const itemLabel = `${label} approvers[${index}]`;
52
- const entry = exactKeys(item, ['key_id', 'public_key', 'name', 'scopes', 'expires_at'], itemLabel);
65
+ const entry = exactKeys(item, APPROVER_FIELDS, itemLabel);
53
66
  const keyId = validateKeyId(entry.key_id, `${itemLabel} key_id`);
54
- if (keyId <= previous)
67
+ // Each key_id must be larger than the one before.
68
+ if (keyId <= previousKeyId)
55
69
  throw new Error(`${label} approvers must be unique and sorted by key_id`);
56
- previous = keyId;
70
+ previousKeyId = keyId;
71
+ // The root key only signs trust roots; it must stay separate from the keys that approve Skills.
57
72
  if (keyId === root.keyId)
58
73
  throw new Error(`${label}: the root key must not also be an approver`);
59
- const scopes = requireArray(entry.scopes, `${itemLabel} scopes`, MAX_SCOPES).map((scope, scopeIndex) => validateScope(scope, `${itemLabel} scopes[${scopeIndex}]`));
74
+ // Scopes name the Skills this approver may sign for: at least one, sorted, no duplicates.
75
+ const scopes = requireArray(entry.scopes, `${itemLabel} scopes`, MAX_SCOPES)
76
+ .map((scope, scopeIndex) => validateScope(scope, `${itemLabel} scopes[${scopeIndex}]`));
60
77
  if (scopes.length === 0)
61
78
  throw new Error(`${itemLabel} needs at least one scope`);
62
- for (let scopeIndex = 1; scopeIndex < scopes.length; scopeIndex += 1) {
79
+ for (let scopeIndex = 1; scopeIndex < scopes.length; scopeIndex += 1)
63
80
  if (scopes[scopeIndex - 1] >= scopes[scopeIndex])
64
81
  throw new Error(`${itemLabel} scopes must be unique and sorted`);
65
- }
82
+ // The approver's public key must hash to its key_id, like the root key above.
66
83
  approvers.push({
67
84
  ...parseSpki(entry.public_key, `${itemLabel} public_key`, keyId),
68
85
  name: requireString(entry.name, `${itemLabel} name`, 128),
@@ -70,17 +87,21 @@ export function parseTrustRootPayload(bytes) {
70
87
  expiresAt: parseTimestamp(entry.expires_at, `${itemLabel} expires_at`),
71
88
  });
72
89
  }
90
+ // The trust root's own lifetime: it must expire after it is issued.
73
91
  const issuedAt = parseTimestamp(value.issued_at, `${label} issued_at`);
74
92
  const expiresAt = parseTimestamp(value.expires_at, `${label} expires_at`);
75
93
  if (expiresAt <= issuedAt)
76
94
  throw new Error(`${label} expires before it is issued`);
77
- return { version: requirePositiveInteger(value.version, `${label} version`), issuedAt, expiresAt, root, approvers };
95
+ const version = requirePositiveInteger(value.version, `${label} version`);
96
+ return { version, issuedAt, expiresAt, root, approvers };
78
97
  }
79
98
  /**
80
99
  * Verifies a signed trust root against the pinned root key fingerprint and the current time.
81
100
  * Rollback (an older version than already seen) is checked separately against host state.
82
101
  */
83
102
  export function verifyTrustRoot(bytes, pinnedRootKeyId, now) {
103
+ // The expiry check below compares against `now`; an invalid Date would make it pass.
104
+ requireValidDate(now, 'Verification time');
84
105
  let trustRoot;
85
106
  try {
86
107
  const envelope = parseEnvelope(bytes, 'trust root');
@@ -4,9 +4,34 @@ import { type SkillTree, type TreeFile } from './tree-digest.ts';
4
4
  import { type TrustRoot } from './trust-root.ts';
5
5
  export declare const VERDICTS: readonly ["VERIFIED", "UNAPPROVED_CHANGE", "NO_CERTIFICATE", "UNTRUSTED_SIGNER", "REVOKED", "EXPIRED", "UNVERIFIABLE"];
6
6
  export type Verdict = (typeof VERDICTS)[number];
7
+ /**
8
+ * Precedence rank for candidate selection (lower rank wins):
9
+ * VERIFIED (0) beats all failures, followed by the failure priority order.
10
+ */
11
+ export declare const VERDICT_RANK: Readonly<Record<Verdict, number>>;
12
+ /** Root recovery state behind a trust context (policy v2 with "recovery"). */
13
+ export interface RootStatus {
14
+ /** root_fingerprint in the policy. */
15
+ pinnedRootKeyId: string;
16
+ /** The root key that signed the trust root and revocation list after walking the root event log. */
17
+ activeRootKeyId: string;
18
+ /** Events in the root event log. */
19
+ sequence: number;
20
+ recovery: {
21
+ keyIds: string[];
22
+ rotateThreshold: number;
23
+ revokeThreshold: number;
24
+ };
25
+ timestampKeyId: string | null;
26
+ timestamp: {
27
+ version: number;
28
+ expiresAt: Date;
29
+ } | null;
30
+ }
7
31
  export interface TrustContext {
8
32
  trustRoot: TrustRoot;
9
33
  revocations: Revocations;
34
+ root?: RootStatus;
10
35
  }
11
36
  export interface MinimumVersions {
12
37
  trustRootVersion: number;
@@ -19,22 +44,20 @@ export type TrustContextResult = {
19
44
  ok: false;
20
45
  verdict: 'EXPIRED' | 'UNVERIFIABLE';
21
46
  reason: string;
47
+ /** The active root key is revoked by a root event: every Skill is blocked, in shadow mode too. */
48
+ rootRevoked?: boolean;
49
+ /** A version, sequence or timestamp is lower than the host state's: the documents are older than already seen. */
50
+ rollback?: true;
51
+ /** The host state file is malformed (`corrupt`), could not be read (`unreadable`) or could not be written (`write`). */
52
+ stateError?: 'corrupt' | 'unreadable' | 'write';
53
+ /** The timestamp is valid but names other document digests or versions than the files read (the binding check). */
54
+ bindingMismatch?: true;
22
55
  };
23
- /** Verifies the trust root and revocation list once; every Skill check reuses the result. */
24
- export declare function loadTrustContext(options: {
25
- trustRootBytes: Uint8Array;
26
- revocationsBytes: Uint8Array;
27
- rootKeyId: string;
28
- now: Date;
29
- minimum?: MinimumVersions | undefined;
30
- }): TrustContextResult;
31
56
  export interface CertificateEvaluation {
32
57
  verdict: Verdict;
33
58
  reason: string;
34
59
  certificate?: Certificate;
35
60
  }
36
- /** Checks one certificate for one Skill: trust chain, scope, signature, expiry, revocation, then bytes. */
37
- export declare function evaluateCertificate(bytes: Uint8Array, skillName: string, digest: string, context: TrustContext, now: Date): CertificateEvaluation;
38
61
  export interface CertificateSource {
39
62
  source: string;
40
63
  bytes: Uint8Array;
@@ -53,21 +76,54 @@ export interface VerificationResult {
53
76
  excluded: string[];
54
77
  checkedAt: string;
55
78
  }
79
+ /** Verifies the trust root and revocation list once; every Skill check reuses the result. */
80
+ export declare function loadTrustContext(options: {
81
+ trustRootBytes: Uint8Array;
82
+ revocationsBytes: Uint8Array;
83
+ rootKeyId: string;
84
+ now: Date;
85
+ minimum?: MinimumVersions | undefined;
86
+ }): TrustContextResult;
87
+ /** Checks one certificate for one Skill: trust chain, scope, signature, expiry, revocation, then bytes. */
88
+ export declare function evaluateCertificate(bytes: Uint8Array, skillName: string, digest: string, context: TrustContext, now: Date): CertificateEvaluation;
89
+ /**
90
+ * The Skill name from SKILL.md's bytes: an explicit name, else frontmatter "name", else the directory name.
91
+ * Pure, so a caller that hashes and signs those bytes can derive the name from the very same buffer.
92
+ */
93
+ export declare function skillNameFromSkillFile(skillDir: string, skillFile: Uint8Array | undefined, explicit?: string): string;
94
+ /**
95
+ * Resolves the Skill name. SKILL.md comes from an untrusted checkout, so it is read only if it is a regular,
96
+ * non-symlink file no larger than the tree collector's per-file limit; anything else throws (UNVERIFIABLE).
97
+ */
56
98
  export declare function resolveSkillName(skillDir: string, explicit?: string): Promise<string>;
99
+ /** Says what differs between the approved file list and the tree on disk, e.g. an executable bit with no byte changed. */
100
+ export declare function describeTreeChange(approved: readonly TreeFile[], found: readonly TreeFile[]): string;
57
101
  export declare function decide(options: {
58
102
  skillDir: string;
59
103
  skillName: string;
60
104
  tree: SkillTree;
61
- certificates: CertificateSource[];
105
+ certificates: readonly CertificateSource[];
62
106
  context: TrustContext;
63
107
  now: Date;
64
108
  }): VerificationResult;
109
+ /**
110
+ * Same verdict as `decide`, but candidates are evaluated one at a time as they are produced, so only the best
111
+ * one is retained and the first VERIFIED candidate ends the scan (later candidates are never read).
112
+ */
113
+ export declare function decideStreaming(options: {
114
+ skillDir: string;
115
+ skillName: string;
116
+ tree: SkillTree;
117
+ certificates: AsyncIterable<CertificateSource> | Iterable<CertificateSource>;
118
+ context: TrustContext;
119
+ now: Date;
120
+ }): Promise<VerificationResult>;
65
121
  /** Full check of one Skill directory against an already-verified trust context. */
66
122
  export declare function verifySkill(options: {
67
123
  skillDir: string;
68
124
  skillName?: string | undefined;
69
- certificates: CertificateSource[] | ((skillName: string, root: string) => Promise<CertificateSource[]>);
125
+ certificates: readonly CertificateSource[] | ((skillName: string, root: string) => Promise<readonly CertificateSource[]> | AsyncIterable<CertificateSource>);
70
126
  context: TrustContext;
71
127
  now: Date;
72
128
  }): Promise<VerificationResult>;
73
- export declare function unverifiable(skillDir: string, skillName: string, reason: string, now: Date, verdict?: Verdict): VerificationResult;
129
+ export declare function unverifiable(skillDir: string, skillName: string, reason: string, now: Date, verdict?: Exclude<Verdict, 'VERIFIED'>): VerificationResult;