@mago-foundation/mago-ski 0.0.0-stage → 0.1.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 (55) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +121 -2
  4. package/action.yml +58 -0
  5. package/dist/hosts/github/run.d.ts +21 -0
  6. package/dist/hosts/github/run.js +119 -0
  7. package/dist/hosts/pi/index.d.ts +11 -0
  8. package/dist/hosts/pi/index.js +388 -0
  9. package/dist/hosts/pi/paths.d.ts +9 -0
  10. package/dist/hosts/pi/paths.js +55 -0
  11. package/dist/src/admin.d.ts +70 -0
  12. package/dist/src/admin.js +115 -0
  13. package/dist/src/canonical-json.d.ts +12 -0
  14. package/dist/src/canonical-json.js +104 -0
  15. package/dist/src/certificate.d.ts +34 -0
  16. package/dist/src/certificate.js +104 -0
  17. package/dist/src/cli.d.ts +2 -0
  18. package/dist/src/cli.js +419 -0
  19. package/dist/src/diff.d.ts +30 -0
  20. package/dist/src/diff.js +148 -0
  21. package/dist/src/dsse.d.ts +23 -0
  22. package/dist/src/dsse.js +55 -0
  23. package/dist/src/experimental/sigstore.d.ts +26 -0
  24. package/dist/src/experimental/sigstore.js +153 -0
  25. package/dist/src/fs-safe.d.ts +11 -0
  26. package/dist/src/fs-safe.js +96 -0
  27. package/dist/src/index.d.ts +14 -0
  28. package/dist/src/index.js +14 -0
  29. package/dist/src/keys.d.ts +21 -0
  30. package/dist/src/keys.js +108 -0
  31. package/dist/src/main-module.d.ts +5 -0
  32. package/dist/src/main-module.js +19 -0
  33. package/dist/src/names.d.ts +7 -0
  34. package/dist/src/names.js +40 -0
  35. package/dist/src/policy.d.ts +59 -0
  36. package/dist/src/policy.js +237 -0
  37. package/dist/src/revocations.d.ts +28 -0
  38. package/dist/src/revocations.js +91 -0
  39. package/dist/src/time.d.ts +9 -0
  40. package/dist/src/time.js +32 -0
  41. package/dist/src/tree-digest.d.ts +43 -0
  42. package/dist/src/tree-digest.js +243 -0
  43. package/dist/src/trust-root.d.ts +33 -0
  44. package/dist/src/trust-root.js +115 -0
  45. package/dist/src/verify.d.ts +73 -0
  46. package/dist/src/verify.js +134 -0
  47. package/docs/hosts/adapter-interface.md +33 -0
  48. package/docs/hosts/github-action.md +45 -0
  49. package/docs/hosts/pi.md +36 -0
  50. package/docs/spec/skill-certificate-v1.md +60 -0
  51. package/docs/spec/skill-tree-v2.md +59 -0
  52. package/docs/spec/trust-documents-v1.md +103 -0
  53. package/docs/spec/verification.md +46 -0
  54. package/docs/threat-model.md +44 -0
  55. package/package.json +74 -4
@@ -0,0 +1,108 @@
1
+ import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync } from 'node:crypto';
2
+ import { lstat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { readRegularFile, writeNewFile } from "./fs-safe.js";
5
+ export const KEY_ID_PATTERN = /^sha256:[0-9a-f]{64}$/u;
6
+ const BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;
7
+ export function keyIdFromSpkiDer(der) {
8
+ return `sha256:${createHash('sha256').update(der).digest('hex')}`;
9
+ }
10
+ function describe(publicKey) {
11
+ if (publicKey.asymmetricKeyType !== 'ed25519')
12
+ throw new Error('Key is not Ed25519');
13
+ const der = publicKey.export({ format: 'der', type: 'spki' });
14
+ return { keyId: keyIdFromSpkiDer(der), publicKey, spki: der.toString('base64') };
15
+ }
16
+ export function validateKeyId(value, label) {
17
+ if (typeof value !== 'string' || !KEY_ID_PATTERN.test(value))
18
+ throw new Error(`${label} must be a sha256:<64 hex> key identifier`);
19
+ return value;
20
+ }
21
+ /** Parses a canonical base64 Ed25519 SPKI and, if given, checks it hashes to `expectedKeyId`. */
22
+ export function parseSpki(spki, label, expectedKeyId) {
23
+ if (typeof spki !== 'string' || spki.length === 0 || spki.length > 256 || !BASE64_PATTERN.test(spki)) {
24
+ throw new Error(`${label} must be canonical base64 SubjectPublicKeyInfo`);
25
+ }
26
+ const der = Buffer.from(spki, 'base64');
27
+ if (der.toString('base64') !== spki)
28
+ throw new Error(`${label} must be canonical base64 SubjectPublicKeyInfo`);
29
+ let publicKey;
30
+ try {
31
+ publicKey = createPublicKey({ key: der, format: 'der', type: 'spki' });
32
+ }
33
+ catch {
34
+ throw new Error(`${label} is not a valid public key`);
35
+ }
36
+ const info = describe(publicKey);
37
+ if (info.spki !== spki)
38
+ throw new Error(`${label} is not in canonical DER form`);
39
+ if (expectedKeyId !== undefined && info.keyId !== expectedKeyId)
40
+ throw new Error(`${label} does not match key id ${expectedKeyId}`);
41
+ return info;
42
+ }
43
+ /** Private keys must never be written where a Skill (and so its certificate and hosts) could include them. */
44
+ async function refuseInsideSkill(filePath) {
45
+ let directory = path.dirname(filePath);
46
+ while (true) {
47
+ try {
48
+ await lstat(path.join(directory, 'SKILL.md'));
49
+ throw new Error(`Refusing to write a private key inside a Skill directory (${directory}); keep keys outside every Skill tree`);
50
+ }
51
+ catch (error) {
52
+ if (error?.code !== 'ENOENT' && error?.code !== 'ENOTDIR')
53
+ throw error;
54
+ }
55
+ const parent = path.dirname(directory);
56
+ if (parent === directory)
57
+ return;
58
+ directory = parent;
59
+ }
60
+ }
61
+ export async function generateKeyPair(privatePath, publicPath) {
62
+ const privateTarget = path.resolve(privatePath);
63
+ const publicTarget = path.resolve(publicPath);
64
+ if (privateTarget === publicTarget)
65
+ throw new Error('Private and public key paths must differ');
66
+ await refuseInsideSkill(privateTarget);
67
+ const pair = generateKeyPairSync('ed25519');
68
+ const privatePem = pair.privateKey.export({ type: 'pkcs8', format: 'pem' });
69
+ const publicPem = pair.publicKey.export({ type: 'spki', format: 'pem' });
70
+ await writeNewFile(privateTarget, Buffer.from(privatePem), 0o600);
71
+ try {
72
+ await writeNewFile(publicTarget, Buffer.from(publicPem), 0o644);
73
+ }
74
+ catch (error) {
75
+ const { unlink } = await import('node:fs/promises');
76
+ await unlink(privateTarget).catch(() => { });
77
+ throw error;
78
+ }
79
+ return { ...describe(pair.publicKey), privatePath: privateTarget, publicPath: publicTarget };
80
+ }
81
+ export async function loadPrivateKey(filePath) {
82
+ const entry = await lstat(filePath);
83
+ if (process.platform !== 'win32' && (entry.mode & 0o077) !== 0) {
84
+ throw new Error('Private key permissions must deny group and other access (chmod 600)');
85
+ }
86
+ const pem = await readRegularFile(filePath, 'Private key', 64 * 1024);
87
+ let privateKey;
88
+ try {
89
+ privateKey = createPrivateKey(pem);
90
+ }
91
+ catch {
92
+ throw new Error('Private key is not a valid PKCS#8 key');
93
+ }
94
+ if (privateKey.asymmetricKeyType !== 'ed25519')
95
+ throw new Error('Private key is not Ed25519');
96
+ return { ...describe(createPublicKey(privateKey)), privateKey };
97
+ }
98
+ export async function loadPublicKey(filePath) {
99
+ const pem = await readRegularFile(filePath, 'Public key', 64 * 1024);
100
+ let publicKey;
101
+ try {
102
+ publicKey = createPublicKey(pem);
103
+ }
104
+ catch {
105
+ throw new Error('Public key is not a valid SPKI PEM key');
106
+ }
107
+ return describe(publicKey);
108
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * True when this module is the script Node was asked to run. Paths are compared after resolving
3
+ * symlinks, because npm installs commands as links (node_modules/.bin/mago-ski -> dist/src/cli.js).
4
+ */
5
+ export declare function isMainModule(moduleUrl: string): boolean;
@@ -0,0 +1,19 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ /**
5
+ * True when this module is the script Node was asked to run. Paths are compared after resolving
6
+ * symlinks, because npm installs commands as links (node_modules/.bin/mago-ski -> dist/src/cli.js).
7
+ */
8
+ export function isMainModule(moduleUrl) {
9
+ const entry = process.argv[1];
10
+ if (!entry)
11
+ return false;
12
+ const self = fileURLToPath(moduleUrl);
13
+ try {
14
+ return realpathSync(entry) === realpathSync(self);
15
+ }
16
+ catch {
17
+ return path.resolve(entry) === self;
18
+ }
19
+ }
@@ -0,0 +1,7 @@
1
+ export declare function validateSkillName(value: unknown, label?: string): string;
2
+ /** Scopes: "*" (every Skill), "prefix*" (names starting with prefix), or an exact Skill name. */
3
+ export declare function validateScope(value: unknown, label?: string): string;
4
+ export declare function scopeMatches(scope: string, skillName: string): boolean;
5
+ export declare function validateDigest(value: unknown, label?: string): string;
6
+ /** Reads the `name` field from SKILL.md frontmatter, if present. */
7
+ export declare function skillNameFromFrontmatter(text: string): string | undefined;
@@ -0,0 +1,40 @@
1
+ const SKILL_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
2
+ const SCOPE_PATTERN = /^(?:\*|[A-Za-z0-9][A-Za-z0-9._-]{0,127}\*?)$/u;
3
+ const DIGEST_PATTERN = /^sha256:[0-9a-f]{64}$/u;
4
+ export function validateSkillName(value, label = 'Skill name') {
5
+ if (typeof value !== 'string' || !SKILL_NAME_PATTERN.test(value)) {
6
+ throw new Error(`${label} must be 1-128 ASCII letters, digits, dot, underscore or hyphen, starting with a letter or digit`);
7
+ }
8
+ return value;
9
+ }
10
+ /** Scopes: "*" (every Skill), "prefix*" (names starting with prefix), or an exact Skill name. */
11
+ export function validateScope(value, label = 'scope') {
12
+ if (typeof value !== 'string' || !SCOPE_PATTERN.test(value)) {
13
+ throw new Error(`${label} must be "*", an exact Skill name, or a name prefix ending in "*"`);
14
+ }
15
+ return value;
16
+ }
17
+ export function scopeMatches(scope, skillName) {
18
+ if (scope === '*')
19
+ return true;
20
+ if (scope.endsWith('*'))
21
+ return skillName.startsWith(scope.slice(0, -1));
22
+ return scope === skillName;
23
+ }
24
+ export function validateDigest(value, label = 'digest') {
25
+ if (typeof value !== 'string' || !DIGEST_PATTERN.test(value))
26
+ throw new Error(`${label} must be sha256:<64 lowercase hex>`);
27
+ return value;
28
+ }
29
+ /** Reads the `name` field from SKILL.md frontmatter, if present. */
30
+ export function skillNameFromFrontmatter(text) {
31
+ const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(text);
32
+ if (!match)
33
+ return undefined;
34
+ for (const line of match[1].split(/\r?\n/u)) {
35
+ const field = /^name:\s*(?:"([^"]*)"|'([^']*)'|(\S+))\s*$/u.exec(line);
36
+ if (field)
37
+ return field[1] ?? field[2] ?? field[3];
38
+ }
39
+ return undefined;
40
+ }
@@ -0,0 +1,59 @@
1
+ import { type CertificateSource, type TrustContext, type TrustContextResult, type VerificationResult } from './verify.ts';
2
+ export declare const POLICY_VERSION = "mago.policy/v1";
3
+ export declare const STATE_TYPE = "mago.host-state/v1";
4
+ export declare const DEFAULT_POLICY_PATH: string;
5
+ export type Mode = 'shadow' | 'enforce';
6
+ export interface Policy {
7
+ path: string;
8
+ mode: Mode;
9
+ rootKeyId: string;
10
+ trustRootPath: string;
11
+ revocationsPath: string;
12
+ certificateDirs: string[];
13
+ skillDirs: string[];
14
+ statePath: string | null;
15
+ decisionLogPath: string | null;
16
+ }
17
+ /** Policy files are hand-edited JSON; paths are relative to the policy file's directory. */
18
+ export declare function loadPolicy(policyPath: string): Promise<Policy>;
19
+ /** Loads trust documents for a policy, enforcing rollback protection through the state file. */
20
+ export declare function loadPolicyTrust(policy: Policy, now: Date): Promise<TrustContextResult>;
21
+ /** Certificate lookup order: explicit file, policy certificate directories (<name>.cert.json), then the in-Skill certificate. */
22
+ export declare function discoverCertificates(skillName: string, skillRoot: string, certificateDirs: string[], explicit?: string): Promise<CertificateSource[]>;
23
+ /**
24
+ * Finds Skill directories (directories containing SKILL.md) under the given roots.
25
+ * Symbolic links are never skipped silently: hosts such as Pi follow them, so a linked Skill
26
+ * directory or a linked SKILL.md is returned as a Skill, and verification then rejects it.
27
+ */
28
+ export declare const MAX_DISCOVERY_DEPTH = 16;
29
+ export interface SkillDiscovery {
30
+ skillDirs: string[];
31
+ /** Directories at the depth limit that have subdirectories; Skills below them were not searched. */
32
+ tooDeep: string[];
33
+ }
34
+ export declare function findSkillDirs(roots: string[], maxDepth?: number): Promise<SkillDiscovery>;
35
+ /** Result for a directory discovery could not search; it fails in enforce mode and is reported in shadow mode. */
36
+ export declare function tooDeepResult(directory: string, now: Date): VerificationResult;
37
+ export interface DecisionRecord {
38
+ timestamp: string;
39
+ host: string;
40
+ mode: Mode;
41
+ action: 'allow' | 'block' | 'would-block';
42
+ event: string;
43
+ skill: string;
44
+ skill_dir: string;
45
+ digest: string | null;
46
+ certificate_id: string | null;
47
+ verdict: string;
48
+ reason: string;
49
+ }
50
+ export declare function actionFor(mode: Mode, verified: boolean): DecisionRecord['action'];
51
+ export declare function appendDecision(logPath: string | null, record: DecisionRecord): Promise<void>;
52
+ export declare function decisionRecord(result: VerificationResult, mode: Mode, event: string, host?: string): DecisionRecord;
53
+ /** Verifies one Skill under a policy, including trust loading. */
54
+ export declare function verifyWithPolicy(policy: Policy, skillDir: string, options: {
55
+ now: Date;
56
+ skillName?: string;
57
+ certificate?: string;
58
+ context?: TrustContext;
59
+ }): Promise<VerificationResult>;
@@ -0,0 +1,237 @@
1
+ import { appendFile, lstat, opendir, stat } from 'node:fs/promises';
2
+ import { hostname } from 'node:os';
3
+ import path from 'node:path';
4
+ import { canonicalBytes, exactKeys, isRecord, parseCanonicalJsonBytes, requireArray, requireString } from "./canonical-json.js";
5
+ import { readRegularFile, writeFileAtomic } from "./fs-safe.js";
6
+ import { validateKeyId } from "./keys.js";
7
+ import { CERTIFICATE_FILENAME } from "./tree-digest.js";
8
+ import { loadTrustContext, unverifiable, verifySkill, } from "./verify.js";
9
+ export const POLICY_VERSION = 'mago.policy/v1';
10
+ export const STATE_TYPE = 'mago.host-state/v1';
11
+ export const DEFAULT_POLICY_PATH = path.join('.mago-ski', 'policy.json');
12
+ const MAX_CERTIFICATE_BYTES = 8 * 1024 * 1024;
13
+ const POLICY_KEYS = ['policy_version', 'mode', 'root_fingerprint', 'trust_root', 'revocations', 'certificate_dirs', 'skill_dirs', 'state_file', 'decision_log'];
14
+ const REQUIRED_POLICY_KEYS = ['policy_version', 'mode', 'root_fingerprint', 'trust_root', 'revocations'];
15
+ /** Policy files are hand-edited JSON; paths are relative to the policy file's directory. */
16
+ export async function loadPolicy(policyPath) {
17
+ const absolute = path.resolve(policyPath);
18
+ const bytes = await readRegularFile(absolute, 'Policy file', 256 * 1024);
19
+ let value;
20
+ try {
21
+ value = JSON.parse(bytes.toString('utf8'));
22
+ }
23
+ catch {
24
+ throw new Error(`Policy file ${absolute} is not valid JSON`);
25
+ }
26
+ if (!isRecord(value))
27
+ throw new Error('Policy file must contain a JSON object');
28
+ for (const key of Object.keys(value))
29
+ if (!POLICY_KEYS.includes(key))
30
+ throw new Error(`Policy file has unsupported field "${key}"`);
31
+ for (const key of REQUIRED_POLICY_KEYS)
32
+ if (!(key in value))
33
+ throw new Error(`Policy file is missing "${key}"`);
34
+ if (value.policy_version !== POLICY_VERSION)
35
+ throw new Error(`Policy file must declare policy_version "${POLICY_VERSION}"`);
36
+ if (value.mode !== 'shadow' && value.mode !== 'enforce')
37
+ throw new Error('Policy mode must be "shadow" or "enforce"');
38
+ const base = path.dirname(absolute);
39
+ const resolvePath = (item, label) => path.resolve(base, requireString(item, `Policy ${label}`, 4096));
40
+ const optionalList = (item, label) => item === undefined ? [] : requireArray(item, `Policy ${label}`, 256).map((entry, index) => resolvePath(entry, `${label}[${index}]`));
41
+ return {
42
+ path: absolute,
43
+ mode: value.mode,
44
+ rootKeyId: validateKeyId(value.root_fingerprint, 'Policy root_fingerprint'),
45
+ trustRootPath: resolvePath(value.trust_root, 'trust_root'),
46
+ revocationsPath: resolvePath(value.revocations, 'revocations'),
47
+ certificateDirs: optionalList(value.certificate_dirs, 'certificate_dirs'),
48
+ skillDirs: optionalList(value.skill_dirs, 'skill_dirs'),
49
+ statePath: value.state_file === undefined || value.state_file === null ? null : resolvePath(value.state_file, 'state_file'),
50
+ decisionLogPath: value.decision_log === undefined || value.decision_log === null ? null : resolvePath(value.decision_log, 'decision_log'),
51
+ };
52
+ }
53
+ async function readState(statePath) {
54
+ let bytes;
55
+ try {
56
+ bytes = await readRegularFile(statePath, 'Host state file', 1024 * 1024);
57
+ }
58
+ catch (error) {
59
+ if (error?.code === 'ENOENT')
60
+ return {};
61
+ throw error;
62
+ }
63
+ const value = exactKeys(parseCanonicalJsonBytes(bytes, 'host state'), ['type', 'roots'], 'host state');
64
+ if (value.type !== STATE_TYPE || !isRecord(value.roots))
65
+ throw new Error('host state file has an unsupported format');
66
+ const roots = {};
67
+ for (const [rootKeyId, entry] of Object.entries(value.roots)) {
68
+ const fields = exactKeys(entry, ['trust_root_version', 'revocations_version'], 'host state root');
69
+ roots[validateKeyId(rootKeyId, 'host state root key')] = {
70
+ trust_root_version: Number(fields.trust_root_version), revocations_version: Number(fields.revocations_version),
71
+ };
72
+ }
73
+ return roots;
74
+ }
75
+ /** Loads trust documents for a policy, enforcing rollback protection through the state file. */
76
+ export async function loadPolicyTrust(policy, now) {
77
+ let trustRootBytes;
78
+ let revocationsBytes;
79
+ let roots = {};
80
+ try {
81
+ trustRootBytes = await readRegularFile(policy.trustRootPath, 'Trust root', 4 * 1024 * 1024);
82
+ revocationsBytes = await readRegularFile(policy.revocationsPath, 'Revocation list', 8 * 1024 * 1024);
83
+ if (policy.statePath)
84
+ roots = await readState(policy.statePath);
85
+ }
86
+ catch (error) {
87
+ return { ok: false, verdict: 'UNVERIFIABLE', reason: error.message };
88
+ }
89
+ const seen = roots[policy.rootKeyId];
90
+ const minimum = seen ? { trustRootVersion: seen.trust_root_version, revocationsVersion: seen.revocations_version } : undefined;
91
+ const result = loadTrustContext({ trustRootBytes, revocationsBytes, rootKeyId: policy.rootKeyId, now, minimum });
92
+ if (result.ok && policy.statePath) {
93
+ const next = { trust_root_version: result.context.trustRoot.version, revocations_version: result.context.revocations.version };
94
+ if (!seen || next.trust_root_version > seen.trust_root_version || next.revocations_version > seen.revocations_version) {
95
+ roots[policy.rootKeyId] = {
96
+ trust_root_version: Math.max(next.trust_root_version, seen?.trust_root_version ?? 0),
97
+ revocations_version: Math.max(next.revocations_version, seen?.revocations_version ?? 0),
98
+ };
99
+ try {
100
+ await writeFileAtomic(policy.statePath, canonicalBytes({ type: STATE_TYPE, roots }), 0o600);
101
+ }
102
+ catch (error) {
103
+ return { ok: false, verdict: 'UNVERIFIABLE', reason: `cannot record trust versions in ${policy.statePath}: ${error.message}` };
104
+ }
105
+ }
106
+ }
107
+ return result;
108
+ }
109
+ async function readOptional(filePath, label) {
110
+ try {
111
+ return await readRegularFile(filePath, label, MAX_CERTIFICATE_BYTES);
112
+ }
113
+ catch (error) {
114
+ if (error?.code === 'ENOENT')
115
+ return undefined;
116
+ throw error;
117
+ }
118
+ }
119
+ /** Certificate lookup order: explicit file, policy certificate directories (<name>.cert.json), then the in-Skill certificate. */
120
+ export async function discoverCertificates(skillName, skillRoot, certificateDirs, explicit) {
121
+ const sources = [];
122
+ if (explicit) {
123
+ const bytes = await readRegularFile(path.resolve(explicit), 'Certificate', MAX_CERTIFICATE_BYTES);
124
+ sources.push({ source: path.resolve(explicit), bytes });
125
+ }
126
+ for (const directory of certificateDirs) {
127
+ const candidate = path.join(directory, `${skillName}.cert.json`);
128
+ const bytes = await readOptional(candidate, 'Certificate');
129
+ if (bytes)
130
+ sources.push({ source: candidate, bytes });
131
+ }
132
+ const inSkill = path.join(skillRoot, CERTIFICATE_FILENAME);
133
+ const bytes = await readOptional(inSkill, 'Certificate');
134
+ if (bytes)
135
+ sources.push({ source: inSkill, bytes });
136
+ return sources;
137
+ }
138
+ /**
139
+ * Finds Skill directories (directories containing SKILL.md) under the given roots.
140
+ * Symbolic links are never skipped silently: hosts such as Pi follow them, so a linked Skill
141
+ * directory or a linked SKILL.md is returned as a Skill, and verification then rejects it.
142
+ */
143
+ export const MAX_DISCOVERY_DEPTH = 16;
144
+ export async function findSkillDirs(roots, maxDepth = MAX_DISCOVERY_DEPTH) {
145
+ const found = new Set();
146
+ const tooDeep = new Set();
147
+ async function walk(directory, depth) {
148
+ try {
149
+ await lstat(path.join(directory, 'SKILL.md'));
150
+ found.add(directory);
151
+ return;
152
+ }
153
+ catch (error) {
154
+ if (error?.code !== 'ENOENT')
155
+ throw error;
156
+ }
157
+ let dir;
158
+ try {
159
+ dir = await opendir(directory);
160
+ }
161
+ catch (error) {
162
+ if (error?.code === 'ENOENT')
163
+ return;
164
+ throw error;
165
+ }
166
+ for await (const child of dir) {
167
+ const childPath = path.join(directory, child.name);
168
+ if (child.isSymbolicLink()) {
169
+ try {
170
+ if ((await stat(childPath)).isDirectory())
171
+ found.add(childPath);
172
+ }
173
+ catch {
174
+ // A dangling link has nothing a host could load.
175
+ }
176
+ continue;
177
+ }
178
+ if (!child.isDirectory() || child.name === '.git' || child.name === 'node_modules')
179
+ continue;
180
+ // Hosts such as Pi search without a depth limit, so never skip deeper directories silently.
181
+ if (depth + 1 > maxDepth) {
182
+ tooDeep.add(childPath);
183
+ continue;
184
+ }
185
+ await walk(childPath, depth + 1);
186
+ }
187
+ }
188
+ for (const root of roots)
189
+ await walk(path.resolve(root), 0);
190
+ return { skillDirs: [...found].sort(), tooDeep: [...tooDeep].sort() };
191
+ }
192
+ /** Result for a directory discovery could not search; it fails in enforce mode and is reported in shadow mode. */
193
+ export function tooDeepResult(directory, now) {
194
+ 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);
195
+ }
196
+ export function actionFor(mode, verified) {
197
+ if (verified)
198
+ return 'allow';
199
+ return mode === 'enforce' ? 'block' : 'would-block';
200
+ }
201
+ export async function appendDecision(logPath, record) {
202
+ if (!logPath)
203
+ return;
204
+ await appendFile(logPath, `${JSON.stringify(record)}\n`, { encoding: 'utf8', mode: 0o600 });
205
+ }
206
+ export function decisionRecord(result, mode, event, host = `${hostname()}`) {
207
+ return {
208
+ timestamp: result.checkedAt,
209
+ host,
210
+ mode,
211
+ action: actionFor(mode, result.verdict === 'VERIFIED'),
212
+ event,
213
+ skill: result.skillName,
214
+ skill_dir: result.skillDir,
215
+ digest: result.digest,
216
+ certificate_id: result.certificateId,
217
+ verdict: result.verdict,
218
+ reason: result.reason,
219
+ };
220
+ }
221
+ /** Verifies one Skill under a policy, including trust loading. */
222
+ export async function verifyWithPolicy(policy, skillDir, options) {
223
+ let context = options.context;
224
+ if (!context) {
225
+ const loaded = await loadPolicyTrust(policy, options.now);
226
+ if (!loaded.ok)
227
+ return unverifiable(path.resolve(skillDir), options.skillName ?? path.basename(path.resolve(skillDir)), loaded.reason, options.now, loaded.verdict);
228
+ context = loaded.context;
229
+ }
230
+ return verifySkill({
231
+ skillDir,
232
+ skillName: options.skillName,
233
+ context,
234
+ now: options.now,
235
+ certificates: (name, root) => discoverCertificates(name, root, policy.certificateDirs, options.certificate),
236
+ });
237
+ }
@@ -0,0 +1,28 @@
1
+ import type { KeyObject } from 'node:crypto';
2
+ import { type TrustRoot } from './trust-root.ts';
3
+ export declare const REVOCATIONS_PAYLOAD_TYPE = "application/vnd.mago-ski.revocations+json";
4
+ export declare const REVOCATIONS_TYPE = "mago.revocations/v1";
5
+ export interface RevokedKey {
6
+ keyId: string;
7
+ reason: string;
8
+ revokedAt: Date;
9
+ }
10
+ export interface RevokedDigest {
11
+ digest: string;
12
+ reason: string;
13
+ revokedAt: Date;
14
+ }
15
+ export interface Revocations {
16
+ version: number;
17
+ issuedAt: Date;
18
+ expiresAt: Date;
19
+ rootKeyId: string;
20
+ keys: RevokedKey[];
21
+ digests: RevokedDigest[];
22
+ }
23
+ export declare function revocationsPayload(revocations: Revocations): Record<string, unknown>;
24
+ export declare function signRevocations(revocations: Revocations, rootPrivateKey: KeyObject): Buffer;
25
+ export declare function parseRevocationsPayload(bytes: Uint8Array): Revocations;
26
+ export declare function verifyRevocations(bytes: Uint8Array, trustRoot: TrustRoot, now: Date): Revocations;
27
+ /** Verifies the root signature without the freshness check, for editing. */
28
+ export declare function readRevocationsForUpdate(bytes: Uint8Array, rootKeyId: string, rootPublicKey: KeyObject): Revocations;
@@ -0,0 +1,91 @@
1
+ import { canonicalBytes, exactKeys, parseCanonicalJsonBytes, requireArray, requirePositiveInteger, requireString } from "./canonical-json.js";
2
+ import { envelopeBytes, parseEnvelope, signEnvelope, verifyEnvelopeSignature } from "./dsse.js";
3
+ import { validateKeyId } from "./keys.js";
4
+ import { validateDigest } from "./names.js";
5
+ import { formatTimestamp, parseTimestamp } from "./time.js";
6
+ import { TrustDocumentError } from "./trust-root.js";
7
+ export const REVOCATIONS_PAYLOAD_TYPE = 'application/vnd.mago-ski.revocations+json';
8
+ export const REVOCATIONS_TYPE = 'mago.revocations/v1';
9
+ const MAX_REVOCATIONS = 10_000;
10
+ export function revocationsPayload(revocations) {
11
+ return {
12
+ type: REVOCATIONS_TYPE,
13
+ version: revocations.version,
14
+ issued_at: formatTimestamp(revocations.issuedAt),
15
+ expires_at: formatTimestamp(revocations.expiresAt),
16
+ root_key_id: revocations.rootKeyId,
17
+ revoked_keys: [...revocations.keys].sort((a, b) => (a.keyId < b.keyId ? -1 : 1))
18
+ .map((entry) => ({ key_id: entry.keyId, reason: entry.reason, revoked_at: formatTimestamp(entry.revokedAt) })),
19
+ revoked_digests: [...revocations.digests].sort((a, b) => (a.digest < b.digest ? -1 : 1))
20
+ .map((entry) => ({ digest: entry.digest, reason: entry.reason, revoked_at: formatTimestamp(entry.revokedAt) })),
21
+ };
22
+ }
23
+ export function signRevocations(revocations, rootPrivateKey) {
24
+ const payload = canonicalBytes(revocationsPayload(revocations));
25
+ return envelopeBytes(signEnvelope(REVOCATIONS_PAYLOAD_TYPE, payload, revocations.rootKeyId, rootPrivateKey));
26
+ }
27
+ function sortedUnique(values, label) {
28
+ for (let index = 1; index < values.length; index += 1) {
29
+ if (values[index - 1] >= values[index])
30
+ throw new Error(`${label} must be unique and sorted`);
31
+ }
32
+ }
33
+ export function parseRevocationsPayload(bytes) {
34
+ const label = 'revocations payload';
35
+ const value = exactKeys(parseCanonicalJsonBytes(bytes, label), ['type', 'version', 'issued_at', 'expires_at', 'root_key_id', 'revoked_keys', 'revoked_digests'], label);
36
+ if (value.type !== REVOCATIONS_TYPE)
37
+ throw new Error(`${label} has unsupported type`);
38
+ const keys = requireArray(value.revoked_keys, `${label} revoked_keys`, MAX_REVOCATIONS).map((item, index) => {
39
+ const entry = exactKeys(item, ['key_id', 'reason', 'revoked_at'], `${label} revoked_keys[${index}]`);
40
+ return {
41
+ keyId: validateKeyId(entry.key_id, `${label} revoked_keys[${index}] key_id`),
42
+ reason: requireString(entry.reason, `${label} revoked_keys[${index}] reason`, 512),
43
+ revokedAt: parseTimestamp(entry.revoked_at, `${label} revoked_keys[${index}] revoked_at`),
44
+ };
45
+ });
46
+ const digests = requireArray(value.revoked_digests, `${label} revoked_digests`, MAX_REVOCATIONS).map((item, index) => {
47
+ const entry = exactKeys(item, ['digest', 'reason', 'revoked_at'], `${label} revoked_digests[${index}]`);
48
+ return {
49
+ digest: validateDigest(entry.digest, `${label} revoked_digests[${index}] digest`),
50
+ reason: requireString(entry.reason, `${label} revoked_digests[${index}] reason`, 512),
51
+ revokedAt: parseTimestamp(entry.revoked_at, `${label} revoked_digests[${index}] revoked_at`),
52
+ };
53
+ });
54
+ sortedUnique(keys.map((entry) => entry.keyId), `${label} revoked_keys`);
55
+ sortedUnique(digests.map((entry) => entry.digest), `${label} revoked_digests`);
56
+ const issuedAt = parseTimestamp(value.issued_at, `${label} issued_at`);
57
+ const expiresAt = parseTimestamp(value.expires_at, `${label} expires_at`);
58
+ if (expiresAt <= issuedAt)
59
+ throw new Error(`${label} expires before it is issued`);
60
+ return {
61
+ version: requirePositiveInteger(value.version, `${label} version`), issuedAt, expiresAt,
62
+ rootKeyId: validateKeyId(value.root_key_id, `${label} root_key_id`), keys, digests,
63
+ };
64
+ }
65
+ export function verifyRevocations(bytes, trustRoot, now) {
66
+ let revocations;
67
+ try {
68
+ revocations = readRevocationsForUpdate(bytes, trustRoot.root.keyId, trustRoot.root.publicKey);
69
+ }
70
+ catch (error) {
71
+ throw new TrustDocumentError('UNVERIFIABLE', error.message);
72
+ }
73
+ if (revocations.expiresAt <= now) {
74
+ throw new TrustDocumentError('EXPIRED', `revocation list expired at ${formatTimestamp(revocations.expiresAt)}; publish a fresh one`);
75
+ }
76
+ return revocations;
77
+ }
78
+ /** Verifies the root signature without the freshness check, for editing. */
79
+ export function readRevocationsForUpdate(bytes, rootKeyId, rootPublicKey) {
80
+ const envelope = parseEnvelope(bytes, 'revocation list');
81
+ if (envelope.payloadType !== REVOCATIONS_PAYLOAD_TYPE)
82
+ throw new Error('revocation list has the wrong payload type');
83
+ if (envelope.signatures[0].keyid !== rootKeyId)
84
+ throw new Error('revocation list is not signed by the root key');
85
+ const revocations = parseRevocationsPayload(envelope.payloadBytes);
86
+ if (revocations.rootKeyId !== rootKeyId)
87
+ throw new Error('revocation list names a different root key');
88
+ if (!verifyEnvelopeSignature(envelope, rootPublicKey))
89
+ throw new Error('revocation list signature is invalid');
90
+ return revocations;
91
+ }
@@ -0,0 +1,9 @@
1
+ /** Allowed clock skew when checking that a signed object was not issued in the future. */
2
+ export declare const CLOCK_SKEW_MS: number;
3
+ /** UTC timestamp with second precision, e.g. 2026-10-09T12:00:00Z. */
4
+ export declare function formatTimestamp(date: Date): string;
5
+ export declare function parseTimestamp(value: unknown, label: string): Date;
6
+ /** Parses durations like 90d, 12h, 30m. */
7
+ export declare function parseDuration(value: string, label?: string): number;
8
+ export declare function addDuration(now: Date, duration: string, label?: string): Date;
9
+ export declare function truncateToSecond(date: Date): Date;
@@ -0,0 +1,32 @@
1
+ const TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/u;
2
+ /** Allowed clock skew when checking that a signed object was not issued in the future. */
3
+ export const CLOCK_SKEW_MS = 5 * 60 * 1000;
4
+ /** UTC timestamp with second precision, e.g. 2026-10-09T12:00:00Z. */
5
+ export function formatTimestamp(date) {
6
+ return date.toISOString().replace(/\.\d{3}Z$/u, 'Z');
7
+ }
8
+ export function parseTimestamp(value, label) {
9
+ if (typeof value !== 'string' || !TIMESTAMP_PATTERN.test(value))
10
+ throw new Error(`${label} must be a UTC timestamp like 2026-10-09T12:00:00Z`);
11
+ const date = new Date(value);
12
+ if (Number.isNaN(date.getTime()) || formatTimestamp(date) !== value)
13
+ throw new Error(`${label} is not a valid timestamp`);
14
+ return date;
15
+ }
16
+ /** Parses durations like 90d, 12h, 30m. */
17
+ export function parseDuration(value, label = 'duration') {
18
+ const match = /^(\d{1,5})([dhm])$/u.exec(value);
19
+ if (!match)
20
+ throw new Error(`${label} must look like 90d, 12h or 30m`);
21
+ const amount = Number(match[1]);
22
+ if (amount < 1)
23
+ throw new Error(`${label} must be positive`);
24
+ const unit = match[2] === 'd' ? 86_400_000 : match[2] === 'h' ? 3_600_000 : 60_000;
25
+ return amount * unit;
26
+ }
27
+ export function addDuration(now, duration, label) {
28
+ return new Date(Math.floor((now.getTime() + parseDuration(duration, label)) / 1000) * 1000);
29
+ }
30
+ export function truncateToSecond(date) {
31
+ return new Date(Math.floor(date.getTime() / 1000) * 1000);
32
+ }