@mago-foundation/mago-ski 0.0.0-stage → 0.2.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.
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +139 -2
- package/action.yml +58 -0
- package/dist/hosts/github/run.d.ts +27 -0
- package/dist/hosts/github/run.js +152 -0
- package/dist/hosts/pi/index.d.ts +13 -0
- package/dist/hosts/pi/index.js +550 -0
- package/dist/hosts/pi/paths.d.ts +9 -0
- package/dist/hosts/pi/paths.js +55 -0
- package/dist/src/admin.d.ts +74 -0
- package/dist/src/admin.js +243 -0
- package/dist/src/canonical-json.d.ts +12 -0
- package/dist/src/canonical-json.js +149 -0
- package/dist/src/certificate.d.ts +34 -0
- package/dist/src/certificate.js +112 -0
- package/dist/src/cli.d.ts +2 -0
- package/dist/src/cli.js +595 -0
- package/dist/src/diff.d.ts +26 -0
- package/dist/src/diff.js +404 -0
- package/dist/src/dsse.d.ts +25 -0
- package/dist/src/dsse.js +71 -0
- package/dist/src/experimental/sigstore.d.ts +26 -0
- package/dist/src/experimental/sigstore.js +153 -0
- package/dist/src/fs-safe.d.ts +27 -0
- package/dist/src/fs-safe.js +229 -0
- package/dist/src/index.d.ts +14 -0
- package/dist/src/index.js +14 -0
- package/dist/src/keys.d.ts +21 -0
- package/dist/src/keys.js +154 -0
- package/dist/src/main-module.d.ts +5 -0
- package/dist/src/main-module.js +19 -0
- package/dist/src/names.d.ts +7 -0
- package/dist/src/names.js +38 -0
- package/dist/src/policy.d.ts +81 -0
- package/dist/src/policy.js +349 -0
- package/dist/src/revocations.d.ts +28 -0
- package/dist/src/revocations.js +93 -0
- package/dist/src/time.d.ts +25 -0
- package/dist/src/time.js +74 -0
- package/dist/src/tree-digest.d.ts +46 -0
- package/dist/src/tree-digest.js +268 -0
- package/dist/src/trust-root.d.ts +38 -0
- package/dist/src/trust-root.js +136 -0
- package/dist/src/verify.d.ts +96 -0
- package/dist/src/verify.js +380 -0
- package/docs/hosts/adapter-interface.md +33 -0
- package/docs/hosts/github-action.md +45 -0
- package/docs/hosts/pi.md +41 -0
- package/docs/spec/root-recovery-v1.md +430 -0
- package/docs/spec/skill-certificate-v1.md +60 -0
- package/docs/spec/skill-tree-v2.md +59 -0
- package/docs/spec/trust-documents-v1.md +103 -0
- package/docs/spec/verification.md +56 -0
- package/docs/threat-model.md +45 -0
- package/package.json +77 -4
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
import { lstat, opendir, stat } from 'node:fs/promises';
|
|
2
|
+
import { homedir, hostname } from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { canonicalBytes, exactKeys, isRecord, parseCanonicalJsonBytes, requireArray, requireString } from "./canonical-json.js";
|
|
5
|
+
import { appendToRegularFile, isInside, readRegularFile, realpathAllowingMissing, resolveInsideDirectory, writeFileAtomic } from "./fs-safe.js";
|
|
6
|
+
import { 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
|
+
const MAX_CERTIFICATE_BYTES = 8 * 1024 * 1024;
|
|
12
|
+
/** Per-Skill budget across all certificate candidates (explicit file, policy directories, in-Skill file). */
|
|
13
|
+
export const MAX_CERTIFICATE_CANDIDATES = 64;
|
|
14
|
+
export const MAX_CERTIFICATE_TOTAL_BYTES = 32 * 1024 * 1024;
|
|
15
|
+
const POLICY_KEYS = ['policy_version', 'mode', 'root_fingerprint', 'trust_root', 'revocations', 'certificate_dirs', 'skill_dirs', 'state_file', 'decision_log'];
|
|
16
|
+
const REQUIRED_POLICY_KEYS = ['policy_version', 'mode', 'root_fingerprint', 'trust_root', 'revocations'];
|
|
17
|
+
/*
|
|
18
|
+
* Where hosts and the CLI read policy when none is given: $MAGO_SKI_POLICY (absolute, or "~/..."), else ~/.mago-ski/policy.json.
|
|
19
|
+
* Never a path in the current directory, because the project being checked may be controlled by the code under review.
|
|
20
|
+
*/
|
|
21
|
+
export function defaultPolicyPath(env = process.env, home = homedir()) {
|
|
22
|
+
const configured = env.MAGO_SKI_POLICY;
|
|
23
|
+
if (!configured)
|
|
24
|
+
return path.join(home, '.mago-ski', 'policy.json');
|
|
25
|
+
if (configured === '~' || configured.startsWith('~/'))
|
|
26
|
+
return path.join(home, configured.slice(2));
|
|
27
|
+
if (!path.isAbsolute(configured))
|
|
28
|
+
throw new Error(`MAGO_SKI_POLICY must be an absolute path (or start with "~/"); got "${configured}"`);
|
|
29
|
+
return configured;
|
|
30
|
+
}
|
|
31
|
+
/** Policy files are hand-edited JSON; paths are relative to the policy file's directory. */
|
|
32
|
+
export async function loadPolicy(policyPath) {
|
|
33
|
+
const absolute = path.resolve(policyPath);
|
|
34
|
+
const bytes = await readRegularFile(absolute, 'Policy file', 256 * 1024);
|
|
35
|
+
let value;
|
|
36
|
+
try {
|
|
37
|
+
value = JSON.parse(bytes.toString('utf8'));
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
throw new Error(`Policy file ${absolute} is not valid JSON`);
|
|
41
|
+
}
|
|
42
|
+
if (!isRecord(value))
|
|
43
|
+
throw new Error('Policy file must contain a JSON object');
|
|
44
|
+
for (const key of Object.keys(value))
|
|
45
|
+
if (!POLICY_KEYS.includes(key))
|
|
46
|
+
throw new Error(`Policy file has unsupported field "${key}"`);
|
|
47
|
+
for (const key of REQUIRED_POLICY_KEYS)
|
|
48
|
+
if (!(key in value))
|
|
49
|
+
throw new Error(`Policy file is missing "${key}"`);
|
|
50
|
+
if (value.policy_version !== POLICY_VERSION)
|
|
51
|
+
throw new Error(`Policy file must declare policy_version "${POLICY_VERSION}"`);
|
|
52
|
+
if (value.mode !== 'shadow' && value.mode !== 'enforce')
|
|
53
|
+
throw new Error('Policy mode must be "shadow" or "enforce"');
|
|
54
|
+
const base = path.dirname(absolute);
|
|
55
|
+
const resolvePath = (item, label) => path.resolve(base, requireString(item, `Policy ${label}`, 4096));
|
|
56
|
+
// decision_log and state_file are files this tool writes, so the policy may only place them in its own directory.
|
|
57
|
+
const writablePath = async (item, label) => item === undefined || item === null ? null : await resolveInsideDirectory(base, requireString(item, `Policy ${label}`, 4096), `Policy ${label}`);
|
|
58
|
+
const optionalList = (item, label) => item === undefined ? [] : requireArray(item, `Policy ${label}`, 256).map((entry, index) => resolvePath(entry, `${label}[${index}]`));
|
|
59
|
+
const policy = {
|
|
60
|
+
path: absolute,
|
|
61
|
+
mode: value.mode,
|
|
62
|
+
rootKeyId: validateKeyId(value.root_fingerprint, 'Policy root_fingerprint'),
|
|
63
|
+
trustRootPath: resolvePath(value.trust_root, 'trust_root'),
|
|
64
|
+
revocationsPath: resolvePath(value.revocations, 'revocations'),
|
|
65
|
+
certificateDirs: optionalList(value.certificate_dirs, 'certificate_dirs'),
|
|
66
|
+
skillDirs: optionalList(value.skill_dirs, 'skill_dirs'),
|
|
67
|
+
statePath: await writablePath(value.state_file, 'state_file'),
|
|
68
|
+
decisionLogPath: await writablePath(value.decision_log, 'decision_log'),
|
|
69
|
+
};
|
|
70
|
+
await rejectWriteTargetsThatOverlapInputs(policy);
|
|
71
|
+
return policy;
|
|
72
|
+
}
|
|
73
|
+
/** A path with symlinks resolved where possible; falls back to the lexical path (the read itself will fail later). */
|
|
74
|
+
async function canonicalOrLexical(target) {
|
|
75
|
+
try {
|
|
76
|
+
return await realpathAllowingMissing(target);
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return path.resolve(target);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/** decision_log and state_file are overwritten or appended to, so they must not be a file the policy reads. */
|
|
83
|
+
async function rejectWriteTargetsThatOverlapInputs(policy) {
|
|
84
|
+
const inputs = [
|
|
85
|
+
['the policy file', policy.path], ['trust_root', policy.trustRootPath], ['revocations', policy.revocationsPath],
|
|
86
|
+
];
|
|
87
|
+
const directories = await Promise.all(policy.certificateDirs.map(canonicalOrLexical));
|
|
88
|
+
const targets = [['state_file', policy.statePath], ['decision_log', policy.decisionLogPath]];
|
|
89
|
+
const seen = [];
|
|
90
|
+
for (const [label, target] of targets) {
|
|
91
|
+
if (!target)
|
|
92
|
+
continue;
|
|
93
|
+
const canonical = await canonicalOrLexical(target);
|
|
94
|
+
for (const [name, input] of inputs) {
|
|
95
|
+
if (canonical === await canonicalOrLexical(input))
|
|
96
|
+
throw new Error(`Policy ${label} must not be ${name}`);
|
|
97
|
+
}
|
|
98
|
+
if (directories.some((directory) => isInside(directory, canonical)))
|
|
99
|
+
throw new Error(`Policy ${label} must not be inside a certificate_dirs directory`);
|
|
100
|
+
for (const [other, otherPath] of seen)
|
|
101
|
+
if (canonical === otherPath)
|
|
102
|
+
throw new Error(`Policy ${label} must not be the same file as ${other}`);
|
|
103
|
+
seen.push([label, canonical]);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
async function readState(statePath) {
|
|
107
|
+
let bytes;
|
|
108
|
+
try {
|
|
109
|
+
bytes = await readRegularFile(statePath, 'Host state file', 1024 * 1024);
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
if (error?.code === 'ENOENT')
|
|
113
|
+
return {};
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
const value = exactKeys(parseCanonicalJsonBytes(bytes, 'host state'), ['type', 'roots'], 'host state');
|
|
117
|
+
if (value.type !== STATE_TYPE || !isRecord(value.roots))
|
|
118
|
+
throw new Error('host state file has an unsupported format');
|
|
119
|
+
const roots = {};
|
|
120
|
+
for (const [rootKeyId, entry] of Object.entries(value.roots)) {
|
|
121
|
+
const fields = exactKeys(entry, ['trust_root_version', 'revocations_version'], 'host state root');
|
|
122
|
+
roots[validateKeyId(rootKeyId, 'host state root key')] = {
|
|
123
|
+
trust_root_version: Number(fields.trust_root_version), revocations_version: Number(fields.revocations_version),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
return roots;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Loads trust documents for a policy, enforcing rollback protection through the state file.
|
|
130
|
+
* With `recordVersions: false` the state file is still read (the same rollback minimums apply) but never written:
|
|
131
|
+
* for observers such as the GUI, which must not move a host's rollback memory.
|
|
132
|
+
*/
|
|
133
|
+
export async function loadPolicyTrust(policy, now, options = {}) {
|
|
134
|
+
let trustRootBytes;
|
|
135
|
+
let revocationsBytes;
|
|
136
|
+
let roots = {};
|
|
137
|
+
try {
|
|
138
|
+
trustRootBytes = await readRegularFile(policy.trustRootPath, 'Trust root', 4 * 1024 * 1024);
|
|
139
|
+
revocationsBytes = await readRegularFile(policy.revocationsPath, 'Revocation list', 8 * 1024 * 1024);
|
|
140
|
+
if (policy.statePath)
|
|
141
|
+
roots = await readState(policy.statePath);
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
return { ok: false, verdict: 'UNVERIFIABLE', reason: error.message };
|
|
145
|
+
}
|
|
146
|
+
const seen = roots[policy.rootKeyId];
|
|
147
|
+
const minimum = seen ? { trustRootVersion: seen.trust_root_version, revocationsVersion: seen.revocations_version } : undefined;
|
|
148
|
+
const result = loadTrustContext({ trustRootBytes, revocationsBytes, rootKeyId: policy.rootKeyId, now, minimum });
|
|
149
|
+
if (result.ok && policy.statePath && options.recordVersions !== false) {
|
|
150
|
+
const next = { trust_root_version: result.context.trustRoot.version, revocations_version: result.context.revocations.version };
|
|
151
|
+
if (!seen || next.trust_root_version > seen.trust_root_version || next.revocations_version > seen.revocations_version) {
|
|
152
|
+
roots[policy.rootKeyId] = {
|
|
153
|
+
trust_root_version: Math.max(next.trust_root_version, seen?.trust_root_version ?? 0),
|
|
154
|
+
revocations_version: Math.max(next.revocations_version, seen?.revocations_version ?? 0),
|
|
155
|
+
};
|
|
156
|
+
try {
|
|
157
|
+
await writeFileAtomic(policy.statePath, canonicalBytes({ type: STATE_TYPE, roots }), 0o600);
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
return { ok: false, verdict: 'UNVERIFIABLE', reason: `cannot record trust versions in ${policy.statePath}: ${error.message}` };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return result;
|
|
165
|
+
}
|
|
166
|
+
async function readOptional(filePath, label) {
|
|
167
|
+
try {
|
|
168
|
+
return await readRegularFile(filePath, label, MAX_CERTIFICATE_BYTES);
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
if (error?.code === 'ENOENT')
|
|
172
|
+
return undefined;
|
|
173
|
+
throw error;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/*
|
|
177
|
+
* Certificate lookup order: explicit file, policy certificate directories (<name>.cert.json), then the in-Skill certificate.
|
|
178
|
+
* Candidates are read lazily, one at a time, so a caller that stops early never reads the rest and none are retained here.
|
|
179
|
+
* Candidates come from the checkout under review, so a Skill may have at most MAX_CERTIFICATE_CANDIDATES candidate files
|
|
180
|
+
* totalling MAX_CERTIFICATE_TOTAL_BYTES; going over throws (the Skill is UNVERIFIABLE) instead of reading further.
|
|
181
|
+
*/
|
|
182
|
+
export async function* iterateCertificates(skillName, skillRoot, certificateDirs, explicit) {
|
|
183
|
+
let count = 0;
|
|
184
|
+
let totalBytes = 0;
|
|
185
|
+
const seen = new Set();
|
|
186
|
+
const account = (source, bytes) => {
|
|
187
|
+
count += 1;
|
|
188
|
+
totalBytes += bytes.length;
|
|
189
|
+
if (count > MAX_CERTIFICATE_CANDIDATES)
|
|
190
|
+
throw new Error(`more than ${MAX_CERTIFICATE_CANDIDATES} certificate candidates for this Skill; reduce certificate_dirs or remove stray certificates`);
|
|
191
|
+
if (totalBytes > MAX_CERTIFICATE_TOTAL_BYTES)
|
|
192
|
+
throw new Error(`certificate candidates for this Skill exceed ${MAX_CERTIFICATE_TOTAL_BYTES} bytes in total`);
|
|
193
|
+
return { source, bytes };
|
|
194
|
+
};
|
|
195
|
+
if (explicit) {
|
|
196
|
+
const candidate = path.resolve(explicit);
|
|
197
|
+
seen.add(candidate);
|
|
198
|
+
yield account(candidate, await readRegularFile(candidate, 'Certificate', MAX_CERTIFICATE_BYTES));
|
|
199
|
+
}
|
|
200
|
+
for (const directory of certificateDirs) {
|
|
201
|
+
const candidate = path.join(directory, `${skillName}.cert.json`);
|
|
202
|
+
if (seen.has(candidate))
|
|
203
|
+
continue;
|
|
204
|
+
seen.add(candidate);
|
|
205
|
+
const bytes = await readOptional(candidate, 'Certificate');
|
|
206
|
+
if (bytes)
|
|
207
|
+
yield account(candidate, bytes);
|
|
208
|
+
}
|
|
209
|
+
const inSkill = path.join(skillRoot, CERTIFICATE_FILENAME);
|
|
210
|
+
if (!seen.has(inSkill)) {
|
|
211
|
+
const bytes = await readOptional(inSkill, 'Certificate');
|
|
212
|
+
if (bytes)
|
|
213
|
+
yield account(inSkill, bytes);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
/** Collects every candidate (within the same budget). Prefer `iterateCertificates`, which retains nothing. */
|
|
217
|
+
export async function discoverCertificates(skillName, skillRoot, certificateDirs, explicit) {
|
|
218
|
+
const sources = [];
|
|
219
|
+
for await (const source of iterateCertificates(skillName, skillRoot, certificateDirs, explicit))
|
|
220
|
+
sources.push(source);
|
|
221
|
+
return sources;
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Finds Skill directories (directories containing SKILL.md) under the given roots.
|
|
225
|
+
* Symbolic links are never skipped silently: hosts such as Pi follow them, so a linked Skill
|
|
226
|
+
* directory or a linked SKILL.md is returned as a Skill, and verification then rejects it.
|
|
227
|
+
*/
|
|
228
|
+
export const MAX_DISCOVERY_DEPTH = 16;
|
|
229
|
+
/** Work budget for one discovery run over untrusted trees; exceeding either throws DiscoveryBudgetError. */
|
|
230
|
+
export const MAX_DISCOVERED_SKILLS = 1_000;
|
|
231
|
+
export const MAX_DISCOVERY_ENTRIES = 50_000;
|
|
232
|
+
/** Discovery stopped because the tree is larger than the budget. It never returns a partial list: callers must fail closed. */
|
|
233
|
+
export class DiscoveryBudgetError extends Error {
|
|
234
|
+
constructor(message) {
|
|
235
|
+
super(message);
|
|
236
|
+
this.name = 'DiscoveryBudgetError';
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
export async function findSkillDirs(roots, maxDepth = MAX_DISCOVERY_DEPTH, limits = {}) {
|
|
240
|
+
const maxSkills = limits.maxSkills ?? MAX_DISCOVERED_SKILLS;
|
|
241
|
+
const maxEntries = limits.maxEntries ?? MAX_DISCOVERY_ENTRIES;
|
|
242
|
+
const found = new Set();
|
|
243
|
+
const tooDeep = new Set();
|
|
244
|
+
let entries = 0;
|
|
245
|
+
const checkSkills = () => {
|
|
246
|
+
if (found.size + tooDeep.size > maxSkills)
|
|
247
|
+
throw new DiscoveryBudgetError(`more than ${maxSkills} Skills found under skill_dirs; narrow skill_dirs or split the repository`);
|
|
248
|
+
};
|
|
249
|
+
async function walk(directory, depth) {
|
|
250
|
+
try {
|
|
251
|
+
await lstat(path.join(directory, 'SKILL.md'));
|
|
252
|
+
found.add(directory);
|
|
253
|
+
checkSkills();
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
catch (error) {
|
|
257
|
+
if (error?.code !== 'ENOENT')
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
260
|
+
let dir;
|
|
261
|
+
try {
|
|
262
|
+
dir = await opendir(directory);
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
if (error?.code === 'ENOENT')
|
|
266
|
+
return;
|
|
267
|
+
throw error;
|
|
268
|
+
}
|
|
269
|
+
for await (const child of dir) {
|
|
270
|
+
entries += 1;
|
|
271
|
+
if (entries > maxEntries)
|
|
272
|
+
throw new DiscoveryBudgetError(`more than ${maxEntries} directory entries under skill_dirs; narrow skill_dirs or split the repository`);
|
|
273
|
+
const childPath = path.join(directory, child.name);
|
|
274
|
+
if (child.isSymbolicLink()) {
|
|
275
|
+
try {
|
|
276
|
+
if ((await stat(childPath)).isDirectory())
|
|
277
|
+
found.add(childPath);
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
// A dangling link has nothing a host could load.
|
|
281
|
+
}
|
|
282
|
+
checkSkills();
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
if (!child.isDirectory() || child.name === '.git' || child.name === 'node_modules')
|
|
286
|
+
continue;
|
|
287
|
+
// Hosts such as Pi search without a depth limit, so never skip deeper directories silently.
|
|
288
|
+
if (depth + 1 > maxDepth) {
|
|
289
|
+
tooDeep.add(childPath);
|
|
290
|
+
checkSkills();
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
await walk(childPath, depth + 1);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
for (const root of roots)
|
|
297
|
+
await walk(path.resolve(root), 0);
|
|
298
|
+
return { skillDirs: [...found].sort(), tooDeep: [...tooDeep].sort() };
|
|
299
|
+
}
|
|
300
|
+
/** Result for a directory discovery could not search; it fails in enforce mode and is reported in shadow mode. */
|
|
301
|
+
export function tooDeepResult(directory, now) {
|
|
302
|
+
return unverifiable(directory, path.basename(directory), `directory is deeper than the discovery limit (${MAX_DISCOVERY_DEPTH} levels below skill_dirs); Skills below it were not checked. Point skill_dirs closer to the Skills`, now);
|
|
303
|
+
}
|
|
304
|
+
export function actionFor(mode, verified) {
|
|
305
|
+
if (verified)
|
|
306
|
+
return 'allow';
|
|
307
|
+
return mode === 'enforce' ? 'block' : 'would-block';
|
|
308
|
+
}
|
|
309
|
+
export async function appendDecision(logPath, record) {
|
|
310
|
+
if (!logPath)
|
|
311
|
+
return;
|
|
312
|
+
// One JSON object per line. JSON.stringify escapes newlines and control characters; also escape the Unicode
|
|
313
|
+
// line separators some JSON Lines readers split on, plus C1 controls, DEL and bidi controls. The text is data, not shell syntax: never source a log.
|
|
314
|
+
const line = JSON.stringify(record).replace(/[\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/gu, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
|
|
315
|
+
await appendToRegularFile(logPath, `${line}\n`, 'Decision log');
|
|
316
|
+
}
|
|
317
|
+
/* */
|
|
318
|
+
export function decisionRecord(result, mode, event, host = `${hostname()}`) {
|
|
319
|
+
return {
|
|
320
|
+
timestamp: result.checkedAt,
|
|
321
|
+
host,
|
|
322
|
+
mode,
|
|
323
|
+
action: actionFor(mode, result.verdict === 'VERIFIED'),
|
|
324
|
+
event,
|
|
325
|
+
skill: result.skillName,
|
|
326
|
+
skill_dir: result.skillDir,
|
|
327
|
+
digest: result.digest,
|
|
328
|
+
certificate_id: result.certificateId,
|
|
329
|
+
verdict: result.verdict,
|
|
330
|
+
reason: result.reason,
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
/** Verifies one Skill under a policy, including trust loading. */
|
|
334
|
+
export async function verifyWithPolicy(policy, skillDir, options) {
|
|
335
|
+
let context = options.context;
|
|
336
|
+
if (!context) {
|
|
337
|
+
const loaded = await loadPolicyTrust(policy, options.now);
|
|
338
|
+
if (!loaded.ok)
|
|
339
|
+
return unverifiable(path.resolve(skillDir), options.skillName ?? path.basename(path.resolve(skillDir)), loaded.reason, options.now, loaded.verdict);
|
|
340
|
+
context = loaded.context;
|
|
341
|
+
}
|
|
342
|
+
return verifySkill({
|
|
343
|
+
skillDir,
|
|
344
|
+
skillName: options.skillName,
|
|
345
|
+
context,
|
|
346
|
+
now: options.now,
|
|
347
|
+
certificates: (name, root) => iterateCertificates(name, root, policy.certificateDirs, options.certificate),
|
|
348
|
+
});
|
|
349
|
+
}
|
|
@@ -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,93 @@
|
|
|
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, requireValidDate } 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
|
+
// The freshness check below compares against `now`; an invalid Date would let an expired list through.
|
|
67
|
+
requireValidDate(now, 'Verification time');
|
|
68
|
+
let revocations;
|
|
69
|
+
try {
|
|
70
|
+
revocations = readRevocationsForUpdate(bytes, trustRoot.root.keyId, trustRoot.root.publicKey);
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
throw new TrustDocumentError('UNVERIFIABLE', error.message);
|
|
74
|
+
}
|
|
75
|
+
if (revocations.expiresAt <= now) {
|
|
76
|
+
throw new TrustDocumentError('EXPIRED', `revocation list expired at ${formatTimestamp(revocations.expiresAt)}; publish a fresh one`);
|
|
77
|
+
}
|
|
78
|
+
return revocations;
|
|
79
|
+
}
|
|
80
|
+
/** Verifies the root signature without the freshness check, for editing. */
|
|
81
|
+
export function readRevocationsForUpdate(bytes, rootKeyId, rootPublicKey) {
|
|
82
|
+
const envelope = parseEnvelope(bytes, 'revocation list');
|
|
83
|
+
if (envelope.payloadType !== REVOCATIONS_PAYLOAD_TYPE)
|
|
84
|
+
throw new Error('revocation list has the wrong payload type');
|
|
85
|
+
if (envelope.signatures[0].keyid !== rootKeyId)
|
|
86
|
+
throw new Error('revocation list is not signed by the root key');
|
|
87
|
+
const revocations = parseRevocationsPayload(envelope.payloadBytes);
|
|
88
|
+
if (revocations.rootKeyId !== rootKeyId)
|
|
89
|
+
throw new Error('revocation list names a different root key');
|
|
90
|
+
if (!verifyEnvelopeSignature(envelope, rootPublicKey))
|
|
91
|
+
throw new Error('revocation list signature is invalid');
|
|
92
|
+
return revocations;
|
|
93
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
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
|
+
/**
|
|
4
|
+
* Throws unless `date` is a Date that holds a real time.
|
|
5
|
+
* An invalid Date holds NaN, and every comparison with NaN is false,
|
|
6
|
+
* so an expiry check against it would silently pass.
|
|
7
|
+
* Every function that compares documents against the current time calls this on `now` first.
|
|
8
|
+
*/
|
|
9
|
+
export declare function requireValidDate(date: Date, label: string): void;
|
|
10
|
+
/**
|
|
11
|
+
* Writes a date as a UTC timestamp with whole seconds, e.g. 2026-10-09T12:00:00Z.
|
|
12
|
+
* Milliseconds are dropped.
|
|
13
|
+
*/
|
|
14
|
+
export declare function formatTimestamp(date: Date): string;
|
|
15
|
+
/**
|
|
16
|
+
* Reads a timestamp in the exact format formatTimestamp writes.
|
|
17
|
+
* Dates that do not exist (2026-02-30, 24:00:00) are rejected.
|
|
18
|
+
*/
|
|
19
|
+
export declare function parseTimestamp(value: unknown, label: string): Date;
|
|
20
|
+
/** Reads a duration such as 90d, 12h or 30m and returns it in milliseconds. */
|
|
21
|
+
export declare function parseDuration(value: string, label?: string): number;
|
|
22
|
+
/** Returns `start` plus a duration such as 90d, rounded down to a whole second. */
|
|
23
|
+
export declare function addDuration(start: Date, duration: string, label?: string): Date;
|
|
24
|
+
/** Drops the milliseconds, so the date survives formatTimestamp and parseTimestamp unchanged. */
|
|
25
|
+
export declare function truncateToSecond(date: Date): Date;
|
package/dist/src/time.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/** The only timestamp format accepted: UTC with whole seconds, e.g. 2026-10-09T12:00:00Z. */
|
|
2
|
+
const TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/u;
|
|
3
|
+
/** A duration is 1 to 5 digits plus a unit; 99999d (about 273 years) is the largest. */
|
|
4
|
+
const DURATION_PATTERN = /^(\d{1,5})([dhm])$/u;
|
|
5
|
+
const UNIT_MS = {
|
|
6
|
+
d: 24 * 60 * 60 * 1000,
|
|
7
|
+
h: 60 * 60 * 1000,
|
|
8
|
+
m: 60 * 1000,
|
|
9
|
+
};
|
|
10
|
+
/** Allowed clock skew when checking that a signed object was not issued in the future. */
|
|
11
|
+
export const CLOCK_SKEW_MS = 5 * 60 * 1000;
|
|
12
|
+
/**
|
|
13
|
+
* Throws unless `date` is a Date that holds a real time.
|
|
14
|
+
* An invalid Date holds NaN, and every comparison with NaN is false,
|
|
15
|
+
* so an expiry check against it would silently pass.
|
|
16
|
+
* Every function that compares documents against the current time calls this on `now` first.
|
|
17
|
+
*/
|
|
18
|
+
export function requireValidDate(date, label) {
|
|
19
|
+
if (!(date instanceof Date) || Number.isNaN(date.getTime()))
|
|
20
|
+
throw new Error(`${label} must be a valid date`);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Writes a date as a UTC timestamp with whole seconds, e.g. 2026-10-09T12:00:00Z.
|
|
24
|
+
* Milliseconds are dropped.
|
|
25
|
+
*/
|
|
26
|
+
export function formatTimestamp(date) {
|
|
27
|
+
requireValidDate(date, 'Date to format');
|
|
28
|
+
const text = date.toISOString().replace(/\.\d{3}Z$/u, 'Z');
|
|
29
|
+
// toISOString writes years outside 0000-9999 as "+010000-..." or "-000001-...".
|
|
30
|
+
// parseTimestamp rejects those, so a document signed with one could never be read back.
|
|
31
|
+
if (!TIMESTAMP_PATTERN.test(text))
|
|
32
|
+
throw new Error('Timestamp must fall between the years 0000 and 9999');
|
|
33
|
+
return text;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Reads a timestamp in the exact format formatTimestamp writes.
|
|
37
|
+
* Dates that do not exist (2026-02-30, 24:00:00) are rejected.
|
|
38
|
+
*/
|
|
39
|
+
export function parseTimestamp(value, label) {
|
|
40
|
+
if (typeof value !== 'string' || !TIMESTAMP_PATTERN.test(value))
|
|
41
|
+
throw new Error(`${label} must be a UTC timestamp like 2026-10-09T12:00:00Z`);
|
|
42
|
+
// Date quietly rolls impossible values over (2026-02-30 becomes March 2),
|
|
43
|
+
// so the parsed date must format back to exactly the same text.
|
|
44
|
+
const date = new Date(value);
|
|
45
|
+
if (Number.isNaN(date.getTime()) || formatTimestamp(date) !== value)
|
|
46
|
+
throw new Error(`${label} is not a valid timestamp`);
|
|
47
|
+
return date;
|
|
48
|
+
}
|
|
49
|
+
/** Reads a duration such as 90d, 12h or 30m and returns it in milliseconds. */
|
|
50
|
+
export function parseDuration(value, label = 'duration') {
|
|
51
|
+
// The type says string, but this is a public export: plain JavaScript callers can pass anything.
|
|
52
|
+
const match = typeof value === 'string' ? DURATION_PATTERN.exec(value) : null;
|
|
53
|
+
if (!match)
|
|
54
|
+
throw new Error(`${label} must look like 90d, 12h or 30m`);
|
|
55
|
+
const amount = Number(match[1]);
|
|
56
|
+
if (amount < 1)
|
|
57
|
+
throw new Error(`${label} must be positive`);
|
|
58
|
+
// Five digits at most keeps the result (at most 8.64e12) well inside the safe integer range.
|
|
59
|
+
const unit = match[2];
|
|
60
|
+
return amount * UNIT_MS[unit];
|
|
61
|
+
}
|
|
62
|
+
/** Returns `start` plus a duration such as 90d, rounded down to a whole second. */
|
|
63
|
+
export function addDuration(start, duration, label = 'duration') {
|
|
64
|
+
requireValidDate(start, `${label} start`);
|
|
65
|
+
// Past the largest date JavaScript can hold (year 275760) the sum becomes an invalid Date.
|
|
66
|
+
const end = new Date(start.getTime() + parseDuration(duration, label));
|
|
67
|
+
requireValidDate(end, `${label} end`);
|
|
68
|
+
return truncateToSecond(end);
|
|
69
|
+
}
|
|
70
|
+
/** Drops the milliseconds, so the date survives formatTimestamp and parseTimestamp unchanged. */
|
|
71
|
+
export function truncateToSecond(date) {
|
|
72
|
+
requireValidDate(date, 'Date to truncate');
|
|
73
|
+
return new Date(Math.floor(date.getTime() / 1000) * 1000);
|
|
74
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { type BigIntStats } from 'node:fs';
|
|
2
|
+
export declare const TREE_PROFILE = "mago.skill-tree/v2";
|
|
3
|
+
export declare const CERTIFICATE_FILENAME = ".mago-ski-cert.json";
|
|
4
|
+
export declare const IGNORE_FILENAME = ".skilldigestignore";
|
|
5
|
+
/** Always covered: it holds the instructions and the description hosts show the model. */
|
|
6
|
+
export declare const SKILL_FILENAME = "SKILL.md";
|
|
7
|
+
export declare const MAX_TREE_FILES = 20000;
|
|
8
|
+
export declare const MAX_TREE_ENTRIES = 50000;
|
|
9
|
+
export declare const MAX_FILE_BYTES: number;
|
|
10
|
+
export declare const MAX_TREE_BYTES: number;
|
|
11
|
+
export declare const MAX_RELATIVE_PATH_BYTES = 4096;
|
|
12
|
+
export interface TreeFile {
|
|
13
|
+
path: string;
|
|
14
|
+
size: number;
|
|
15
|
+
sha256: string;
|
|
16
|
+
exec: boolean;
|
|
17
|
+
}
|
|
18
|
+
export interface SkillTree {
|
|
19
|
+
profile: typeof TREE_PROFILE;
|
|
20
|
+
digest: string;
|
|
21
|
+
root: string;
|
|
22
|
+
files: TreeFile[];
|
|
23
|
+
totalBytes: number;
|
|
24
|
+
/** Paths left out of the digest: the root `.git`, the in-tree certificate, and `.skilldigestignore` entries. */
|
|
25
|
+
excluded: string[];
|
|
26
|
+
}
|
|
27
|
+
/** Executable bit of a regular file. Windows has no POSIX mode bits, so it always reports false there. */
|
|
28
|
+
export declare function isExecutable(mode: number | bigint): boolean;
|
|
29
|
+
export declare function sha256Hex(bytes: Uint8Array): string;
|
|
30
|
+
/** Hashes one file for read-time checks. Returns the same fields the certificate records. */
|
|
31
|
+
export declare function hashFile(absolutePath: string, relativePath: string): Promise<TreeFile>;
|
|
32
|
+
export interface IgnoreRule {
|
|
33
|
+
pattern: string;
|
|
34
|
+
directoryOnly: boolean;
|
|
35
|
+
}
|
|
36
|
+
export declare function parseIgnoreFile(text: string): IgnoreRule[];
|
|
37
|
+
/** Checks that a Skill root exists and is a real directory, with messages that name the path. */
|
|
38
|
+
export declare function requireSkillRoot(root: string): Promise<BigIntStats>;
|
|
39
|
+
export declare function compareTreePaths(left: string, right: string): number;
|
|
40
|
+
/** The tree digest is SHA-256 over the canonical JSON of the profile and the sorted per-file list. */
|
|
41
|
+
export declare function digestFileList(files: readonly TreeFile[]): string;
|
|
42
|
+
export declare function collectSkillTree(rootPath: string, { includeContents }?: {
|
|
43
|
+
includeContents?: boolean | undefined;
|
|
44
|
+
}): Promise<SkillTree & {
|
|
45
|
+
contents?: Map<string, Buffer>;
|
|
46
|
+
}>;
|