@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,268 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { constants as fsConstants } from 'node:fs';
|
|
3
|
+
import { lstat, open, opendir, realpath } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { canonicalBytes } from "./canonical-json.js";
|
|
6
|
+
export const TREE_PROFILE = 'mago.skill-tree/v2';
|
|
7
|
+
export const CERTIFICATE_FILENAME = '.mago-ski-cert.json';
|
|
8
|
+
export const IGNORE_FILENAME = '.skilldigestignore';
|
|
9
|
+
/** Always covered: it holds the instructions and the description hosts show the model. */
|
|
10
|
+
export const SKILL_FILENAME = 'SKILL.md';
|
|
11
|
+
export const MAX_TREE_FILES = 20_000;
|
|
12
|
+
export const MAX_TREE_ENTRIES = 50_000;
|
|
13
|
+
export const MAX_FILE_BYTES = 64 * 1024 * 1024;
|
|
14
|
+
export const MAX_TREE_BYTES = 256 * 1024 * 1024;
|
|
15
|
+
export const MAX_RELATIVE_PATH_BYTES = 4_096;
|
|
16
|
+
const MAX_IGNORE_BYTES = 64 * 1024;
|
|
17
|
+
const MAX_IGNORE_PATTERNS = 256;
|
|
18
|
+
const utf8Decoder = new TextDecoder('utf-8', { fatal: true });
|
|
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;
|
|
22
|
+
function fail(message) {
|
|
23
|
+
throw new Error(message);
|
|
24
|
+
}
|
|
25
|
+
function decodeEntryName(name) {
|
|
26
|
+
let decoded;
|
|
27
|
+
try {
|
|
28
|
+
decoded = utf8Decoder.decode(name);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
fail('Skill tree contains a path that is not valid UTF-8');
|
|
32
|
+
}
|
|
33
|
+
if (decoded.length === 0 ||
|
|
34
|
+
decoded === '.' ||
|
|
35
|
+
decoded === '..' ||
|
|
36
|
+
decoded.includes('/') ||
|
|
37
|
+
decoded.includes('\\') ||
|
|
38
|
+
decoded.includes(':') ||
|
|
39
|
+
/[. ]$/u.test(decoded) ||
|
|
40
|
+
/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?$/iu.test(decoded) ||
|
|
41
|
+
/[\u0000-\u001f\u007f]/u.test(decoded) ||
|
|
42
|
+
decoded.normalize('NFC') !== decoded)
|
|
43
|
+
fail(`Skill tree contains an unsupported path component: ${JSON.stringify(decoded)}`);
|
|
44
|
+
return decoded;
|
|
45
|
+
}
|
|
46
|
+
function sameFileVersion(left, right) {
|
|
47
|
+
return left.dev === right.dev && left.ino === right.ino && left.size === right.size &&
|
|
48
|
+
left.mtimeNs === right.mtimeNs && left.ctimeNs === right.ctimeNs;
|
|
49
|
+
}
|
|
50
|
+
/** Executable bit of a regular file. Windows has no POSIX mode bits, so it always reports false there. */
|
|
51
|
+
export function isExecutable(mode) {
|
|
52
|
+
if (process.platform === 'win32')
|
|
53
|
+
return false;
|
|
54
|
+
return (BigInt(mode) & 73n) !== 0n;
|
|
55
|
+
}
|
|
56
|
+
async function readStable(absolutePath, label, expected) {
|
|
57
|
+
let handle;
|
|
58
|
+
try {
|
|
59
|
+
handle = await open(absolutePath, fsConstants.O_RDONLY | noFollow | nonBlock);
|
|
60
|
+
const before = await handle.stat({ bigint: true });
|
|
61
|
+
if (!before.isFile() || (expected && !sameFileVersion(expected, before)))
|
|
62
|
+
fail(`Skill file changed while being read: ${label}`);
|
|
63
|
+
if (before.size > BigInt(MAX_FILE_BYTES))
|
|
64
|
+
fail(`Skill file exceeds the ${MAX_FILE_BYTES}-byte limit: ${label}`);
|
|
65
|
+
const chunks = [];
|
|
66
|
+
let total = 0;
|
|
67
|
+
while (true) {
|
|
68
|
+
const chunk = Buffer.allocUnsafe(64 * 1024);
|
|
69
|
+
const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
|
|
70
|
+
if (bytesRead === 0)
|
|
71
|
+
break;
|
|
72
|
+
total += bytesRead;
|
|
73
|
+
if (total > MAX_FILE_BYTES)
|
|
74
|
+
fail(`Skill file exceeds the ${MAX_FILE_BYTES}-byte limit: ${label}`);
|
|
75
|
+
chunks.push(chunk.subarray(0, bytesRead));
|
|
76
|
+
}
|
|
77
|
+
const after = await handle.stat({ bigint: true });
|
|
78
|
+
if (!sameFileVersion(before, after) || total !== Number(before.size))
|
|
79
|
+
fail(`Skill file changed while being read: ${label}`);
|
|
80
|
+
return { content: Buffer.concat(chunks, total), stat: after };
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
if (error?.code === 'ELOOP')
|
|
84
|
+
fail(`Skill tree contains a symbolic link: ${label}`);
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
finally {
|
|
88
|
+
await handle?.close();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
export function sha256Hex(bytes) {
|
|
92
|
+
return createHash('sha256').update(bytes).digest('hex');
|
|
93
|
+
}
|
|
94
|
+
/** Hashes one file for read-time checks. Returns the same fields the certificate records. */
|
|
95
|
+
export async function hashFile(absolutePath, relativePath) {
|
|
96
|
+
const entry = await lstat(absolutePath, { bigint: true });
|
|
97
|
+
if (entry.isSymbolicLink() || !entry.isFile())
|
|
98
|
+
fail(`Not a regular file: ${relativePath}`);
|
|
99
|
+
const { content, stat } = await readStable(absolutePath, relativePath, entry);
|
|
100
|
+
return { path: relativePath, size: content.length, sha256: sha256Hex(content), exec: isExecutable(stat.mode) };
|
|
101
|
+
}
|
|
102
|
+
export function parseIgnoreFile(text) {
|
|
103
|
+
const rules = [];
|
|
104
|
+
for (const rawLine of text.split(/\r?\n/u)) {
|
|
105
|
+
const line = rawLine.trim();
|
|
106
|
+
const directoryOnly = line.endsWith('/');
|
|
107
|
+
const pattern = directoryOnly ? line.slice(0, -1) : line;
|
|
108
|
+
const segments = pattern.split('/');
|
|
109
|
+
if (line === '' || line.startsWith('#'))
|
|
110
|
+
continue;
|
|
111
|
+
if (rules.length >= MAX_IGNORE_PATTERNS)
|
|
112
|
+
fail(`${IGNORE_FILENAME} exceeds ${MAX_IGNORE_PATTERNS} patterns`);
|
|
113
|
+
if (pattern === '' ||
|
|
114
|
+
pattern.startsWith('/') ||
|
|
115
|
+
pattern.includes('\\') ||
|
|
116
|
+
/[*?[\]!]/u.test(pattern) ||
|
|
117
|
+
segments.some((segment) => segment === '' || segment === '.' || segment === '..') ||
|
|
118
|
+
pattern === IGNORE_FILENAME ||
|
|
119
|
+
pattern === SKILL_FILENAME ||
|
|
120
|
+
pattern.normalize('NFC') !== pattern) {
|
|
121
|
+
fail(`${IGNORE_FILENAME} contains an unsupported pattern: ${JSON.stringify(line)} (use plain relative paths; globs are not supported)`);
|
|
122
|
+
}
|
|
123
|
+
rules.push({ pattern, directoryOnly });
|
|
124
|
+
}
|
|
125
|
+
return rules;
|
|
126
|
+
}
|
|
127
|
+
function isIgnored(relativePath, isDirectory, rules) {
|
|
128
|
+
for (const rule of rules) {
|
|
129
|
+
if (relativePath === rule.pattern && (isDirectory || !rule.directoryOnly))
|
|
130
|
+
return true;
|
|
131
|
+
if (relativePath.startsWith(`${rule.pattern}/`))
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
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())
|
|
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);
|
|
156
|
+
const canonicalRoot = await realpath(root);
|
|
157
|
+
let rules = [];
|
|
158
|
+
const ignorePath = path.join(canonicalRoot, IGNORE_FILENAME);
|
|
159
|
+
try {
|
|
160
|
+
const entry = await lstat(ignorePath, { bigint: true });
|
|
161
|
+
if (entry.isSymbolicLink() || !entry.isFile())
|
|
162
|
+
fail(`${IGNORE_FILENAME} must be a regular file`);
|
|
163
|
+
if (entry.size > BigInt(MAX_IGNORE_BYTES))
|
|
164
|
+
fail(`${IGNORE_FILENAME} exceeds ${MAX_IGNORE_BYTES} bytes`);
|
|
165
|
+
const { content } = await readStable(ignorePath, IGNORE_FILENAME, entry);
|
|
166
|
+
rules = parseIgnoreFile(utf8Decoder.decode(content));
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
if (error?.code !== 'ENOENT')
|
|
170
|
+
throw error;
|
|
171
|
+
}
|
|
172
|
+
const records = [];
|
|
173
|
+
const excluded = [];
|
|
174
|
+
const seenCaseFolded = new Set();
|
|
175
|
+
let entryCount = 0;
|
|
176
|
+
async function visit(directory, relativeDirectory, depth) {
|
|
177
|
+
if (depth > 64)
|
|
178
|
+
fail('Skill tree exceeds the maximum directory depth of 64');
|
|
179
|
+
const directoryStat = await lstat(directory, { bigint: true });
|
|
180
|
+
if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink())
|
|
181
|
+
fail(`Skill tree contains a changed or symbolic-link directory: ${relativeDirectory || '.'}`);
|
|
182
|
+
const expected = relativeDirectory ? path.join(canonicalRoot, relativeDirectory) : canonicalRoot;
|
|
183
|
+
if (await realpath(directory) !== expected)
|
|
184
|
+
fail(`Skill tree directory path changed during traversal: ${relativeDirectory || '.'}`);
|
|
185
|
+
const dir = await opendir(expected, { encoding: 'buffer', bufferSize: 32 });
|
|
186
|
+
for await (const dirent of dir) {
|
|
187
|
+
entryCount += 1;
|
|
188
|
+
if (entryCount > MAX_TREE_ENTRIES)
|
|
189
|
+
fail(`Skill tree exceeds the ${MAX_TREE_ENTRIES}-entry limit`);
|
|
190
|
+
const name = decodeEntryName(dirent.name);
|
|
191
|
+
const relativePath = relativeDirectory ? `${relativeDirectory}/${name}` : name;
|
|
192
|
+
const pathBytes = Buffer.from(relativePath, 'utf8');
|
|
193
|
+
if (pathBytes.length > MAX_RELATIVE_PATH_BYTES)
|
|
194
|
+
fail(`Skill path exceeds the ${MAX_RELATIVE_PATH_BYTES}-byte limit`);
|
|
195
|
+
const caseKey = relativePath.normalize('NFKC').toLowerCase();
|
|
196
|
+
if (seenCaseFolded.has(caseKey))
|
|
197
|
+
fail(`Skill tree contains a case-insensitive path collision: ${relativePath}`);
|
|
198
|
+
seenCaseFolded.add(caseKey);
|
|
199
|
+
const absolutePath = path.join(expected, name);
|
|
200
|
+
const stat = await lstat(absolutePath, { bigint: true });
|
|
201
|
+
if (stat.isSymbolicLink())
|
|
202
|
+
fail(`Skill tree contains a symbolic link: ${relativePath}`);
|
|
203
|
+
const isDirectory = stat.isDirectory();
|
|
204
|
+
if (!relativeDirectory && (name === '.git' || (name === CERTIFICATE_FILENAME && !isDirectory))) {
|
|
205
|
+
excluded.push(isDirectory ? `${relativePath}/` : relativePath);
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
if (isIgnored(relativePath, isDirectory, rules)) {
|
|
209
|
+
excluded.push(isDirectory ? `${relativePath}/` : relativePath);
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (isDirectory) {
|
|
213
|
+
await visit(absolutePath, relativePath, depth + 1);
|
|
214
|
+
}
|
|
215
|
+
else if (stat.isFile()) {
|
|
216
|
+
if (records.length >= MAX_TREE_FILES)
|
|
217
|
+
fail(`Skill tree exceeds the ${MAX_TREE_FILES}-file limit`);
|
|
218
|
+
if (stat.size > BigInt(MAX_FILE_BYTES))
|
|
219
|
+
fail(`Skill file exceeds the ${MAX_FILE_BYTES}-byte limit: ${relativePath}`);
|
|
220
|
+
records.push({ path: relativePath, pathBytes, absolutePath, stat });
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
fail(`Skill tree contains an unsupported special file: ${relativePath}`);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
await visit(canonicalRoot, '', 0);
|
|
228
|
+
records.sort((left, right) => Buffer.compare(left.pathBytes, right.pathBytes));
|
|
229
|
+
excluded.sort();
|
|
230
|
+
return { root: canonicalRoot, records, excluded };
|
|
231
|
+
}
|
|
232
|
+
export function compareTreePaths(left, right) {
|
|
233
|
+
return Buffer.compare(Buffer.from(left, 'utf8'), Buffer.from(right, 'utf8'));
|
|
234
|
+
}
|
|
235
|
+
/** The tree digest is SHA-256 over the canonical JSON of the profile and the sorted per-file list. */
|
|
236
|
+
export function digestFileList(files) {
|
|
237
|
+
for (let index = 1; index < files.length; index += 1) {
|
|
238
|
+
if (compareTreePaths(files[index - 1].path, files[index].path) >= 0)
|
|
239
|
+
fail('File list must be sorted by UTF-8 path bytes without duplicates');
|
|
240
|
+
}
|
|
241
|
+
const body = canonicalBytes({
|
|
242
|
+
profile: TREE_PROFILE,
|
|
243
|
+
files: files.map((file) => ({ path: file.path, size: file.size, sha256: file.sha256, exec: file.exec })),
|
|
244
|
+
});
|
|
245
|
+
return `sha256:${sha256Hex(body)}`;
|
|
246
|
+
}
|
|
247
|
+
export async function collectSkillTree(rootPath, { includeContents = false } = {}) {
|
|
248
|
+
const { root, records, excluded } = await enumerate(path.resolve(rootPath));
|
|
249
|
+
const files = [];
|
|
250
|
+
const contents = includeContents ? new Map() : undefined;
|
|
251
|
+
let totalBytes = 0;
|
|
252
|
+
for (const record of records) {
|
|
253
|
+
const { content, stat } = await readStable(record.absolutePath, record.path, record.stat);
|
|
254
|
+
totalBytes += content.length;
|
|
255
|
+
if (totalBytes > MAX_TREE_BYTES)
|
|
256
|
+
fail(`Skill tree exceeds the ${MAX_TREE_BYTES}-byte total limit`);
|
|
257
|
+
files.push({ path: record.path, size: content.length, sha256: sha256Hex(content), exec: isExecutable(stat.mode) });
|
|
258
|
+
contents?.set(record.path, content);
|
|
259
|
+
}
|
|
260
|
+
if (!files.some((file) => file.path === SKILL_FILENAME))
|
|
261
|
+
fail(`Skill tree must contain ${SKILL_FILENAME} at its root`);
|
|
262
|
+
const tree = {
|
|
263
|
+
profile: TREE_PROFILE, digest: digestFileList(files), root, files, totalBytes, excluded,
|
|
264
|
+
};
|
|
265
|
+
if (contents)
|
|
266
|
+
tree.contents = contents;
|
|
267
|
+
return tree;
|
|
268
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { KeyObject } from 'node:crypto';
|
|
2
|
+
import { type PublicKeyInfo } from './keys.ts';
|
|
3
|
+
export declare const TRUST_ROOT_PAYLOAD_TYPE = "application/vnd.mago-ski.trust-root+json";
|
|
4
|
+
export declare const TRUST_ROOT_TYPE = "mago.trust-root/v1";
|
|
5
|
+
export declare const MAX_APPROVERS = 256;
|
|
6
|
+
export declare const MAX_SCOPES = 64;
|
|
7
|
+
export interface Approver extends PublicKeyInfo {
|
|
8
|
+
name: string;
|
|
9
|
+
scopes: string[];
|
|
10
|
+
expiresAt: Date;
|
|
11
|
+
}
|
|
12
|
+
export interface TrustRoot {
|
|
13
|
+
version: number;
|
|
14
|
+
issuedAt: Date;
|
|
15
|
+
expiresAt: Date;
|
|
16
|
+
root: PublicKeyInfo;
|
|
17
|
+
approvers: Approver[];
|
|
18
|
+
}
|
|
19
|
+
/** Failure of a signed policy document; `code` maps to a verdict. */
|
|
20
|
+
export declare class TrustDocumentError extends Error {
|
|
21
|
+
readonly code: 'UNVERIFIABLE' | 'EXPIRED';
|
|
22
|
+
constructor(code: 'UNVERIFIABLE' | 'EXPIRED', message: string);
|
|
23
|
+
}
|
|
24
|
+
export declare function trustRootPayload(trustRoot: TrustRoot): Record<string, unknown>;
|
|
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
|
+
*/
|
|
31
|
+
export declare function parseTrustRootPayload(bytes: Uint8Array): TrustRoot;
|
|
32
|
+
/**
|
|
33
|
+
* Verifies a signed trust root against the pinned root key fingerprint and the current time.
|
|
34
|
+
* Rollback (an older version than already seen) is checked separately against host state.
|
|
35
|
+
*/
|
|
36
|
+
export declare function verifyTrustRoot(bytes: Uint8Array, pinnedRootKeyId: string, now: Date): TrustRoot;
|
|
37
|
+
/** Parses a trust root signed by `rootKeyId` without the expiry check, for editing. */
|
|
38
|
+
export declare function readTrustRootForUpdate(bytes: Uint8Array, rootKeyId: string): TrustRoot;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { canonicalBytes, exactKeys, parseCanonicalJsonBytes, requireArray, requirePositiveInteger, requireString } from "./canonical-json.js";
|
|
2
|
+
import { envelopeBytes, parseEnvelope, signEnvelope, verifyEnvelopeSignature } from "./dsse.js";
|
|
3
|
+
import { parseSpki, validateKeyId } from "./keys.js";
|
|
4
|
+
import { validateScope } from "./names.js";
|
|
5
|
+
import { formatTimestamp, parseTimestamp, requireValidDate } from "./time.js";
|
|
6
|
+
export const TRUST_ROOT_PAYLOAD_TYPE = 'application/vnd.mago-ski.trust-root+json';
|
|
7
|
+
export const TRUST_ROOT_TYPE = 'mago.trust-root/v1';
|
|
8
|
+
export const MAX_APPROVERS = 256;
|
|
9
|
+
export const MAX_SCOPES = 64;
|
|
10
|
+
/** Failure of a signed policy document; `code` maps to a verdict. */
|
|
11
|
+
export class TrustDocumentError extends Error {
|
|
12
|
+
code;
|
|
13
|
+
constructor(code, message) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.code = code;
|
|
16
|
+
this.name = 'TrustDocumentError';
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export function trustRootPayload(trustRoot) {
|
|
20
|
+
return {
|
|
21
|
+
type: TRUST_ROOT_TYPE,
|
|
22
|
+
version: trustRoot.version,
|
|
23
|
+
issued_at: formatTimestamp(trustRoot.issuedAt),
|
|
24
|
+
expires_at: formatTimestamp(trustRoot.expiresAt),
|
|
25
|
+
root: { key_id: trustRoot.root.keyId, public_key: trustRoot.root.spki },
|
|
26
|
+
approvers: [...trustRoot.approvers]
|
|
27
|
+
.sort((left, right) => (left.keyId < right.keyId ? -1 : 1))
|
|
28
|
+
.map((approver) => ({
|
|
29
|
+
key_id: approver.keyId,
|
|
30
|
+
public_key: approver.spki,
|
|
31
|
+
name: approver.name,
|
|
32
|
+
scopes: [...approver.scopes].sort(),
|
|
33
|
+
expires_at: formatTimestamp(approver.expiresAt),
|
|
34
|
+
})),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
export function signTrustRoot(trustRoot, rootPrivateKey) {
|
|
38
|
+
const payload = canonicalBytes(trustRootPayload(trustRoot));
|
|
39
|
+
return envelopeBytes(signEnvelope(TRUST_ROOT_PAYLOAD_TYPE, payload, trustRoot.root.keyId, rootPrivateKey));
|
|
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
|
+
*/
|
|
50
|
+
export function parseTrustRootPayload(bytes) {
|
|
51
|
+
const label = 'trust-root payload';
|
|
52
|
+
const value = exactKeys(parseCanonicalJsonBytes(bytes, label), TRUST_ROOT_FIELDS, label);
|
|
53
|
+
if (value.type !== TRUST_ROOT_TYPE)
|
|
54
|
+
throw new Error(`${label} has unsupported type`);
|
|
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);
|
|
61
|
+
const approvers = [];
|
|
62
|
+
let previousKeyId = '';
|
|
63
|
+
for (const [index, item] of approverItems.entries()) {
|
|
64
|
+
const itemLabel = `${label} approvers[${index}]`;
|
|
65
|
+
const entry = exactKeys(item, APPROVER_FIELDS, itemLabel);
|
|
66
|
+
const keyId = validateKeyId(entry.key_id, `${itemLabel} key_id`);
|
|
67
|
+
// Each key_id must be larger than the one before.
|
|
68
|
+
if (keyId <= previousKeyId)
|
|
69
|
+
throw new Error(`${label} approvers must be unique and sorted by key_id`);
|
|
70
|
+
previousKeyId = keyId;
|
|
71
|
+
// The root key only signs trust roots; it must stay separate from the keys that approve Skills.
|
|
72
|
+
if (keyId === root.keyId)
|
|
73
|
+
throw new Error(`${label}: the root key must not also be an approver`);
|
|
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}]`));
|
|
77
|
+
if (scopes.length === 0)
|
|
78
|
+
throw new Error(`${itemLabel} needs at least one scope`);
|
|
79
|
+
for (let scopeIndex = 1; scopeIndex < scopes.length; scopeIndex += 1)
|
|
80
|
+
if (scopes[scopeIndex - 1] >= scopes[scopeIndex])
|
|
81
|
+
throw new Error(`${itemLabel} scopes must be unique and sorted`);
|
|
82
|
+
// The approver's public key must hash to its key_id, like the root key above.
|
|
83
|
+
approvers.push({
|
|
84
|
+
...parseSpki(entry.public_key, `${itemLabel} public_key`, keyId),
|
|
85
|
+
name: requireString(entry.name, `${itemLabel} name`, 128),
|
|
86
|
+
scopes,
|
|
87
|
+
expiresAt: parseTimestamp(entry.expires_at, `${itemLabel} expires_at`),
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
// The trust root's own lifetime: it must expire after it is issued.
|
|
91
|
+
const issuedAt = parseTimestamp(value.issued_at, `${label} issued_at`);
|
|
92
|
+
const expiresAt = parseTimestamp(value.expires_at, `${label} expires_at`);
|
|
93
|
+
if (expiresAt <= issuedAt)
|
|
94
|
+
throw new Error(`${label} expires before it is issued`);
|
|
95
|
+
const version = requirePositiveInteger(value.version, `${label} version`);
|
|
96
|
+
return { version, issuedAt, expiresAt, root, approvers };
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Verifies a signed trust root against the pinned root key fingerprint and the current time.
|
|
100
|
+
* Rollback (an older version than already seen) is checked separately against host state.
|
|
101
|
+
*/
|
|
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');
|
|
105
|
+
let trustRoot;
|
|
106
|
+
try {
|
|
107
|
+
const envelope = parseEnvelope(bytes, 'trust root');
|
|
108
|
+
if (envelope.payloadType !== TRUST_ROOT_PAYLOAD_TYPE)
|
|
109
|
+
throw new Error('trust root has the wrong payload type');
|
|
110
|
+
if (envelope.signatures[0].keyid !== pinnedRootKeyId)
|
|
111
|
+
throw new Error('trust root is not signed by the pinned root key');
|
|
112
|
+
trustRoot = parseTrustRootPayload(envelope.payloadBytes);
|
|
113
|
+
if (trustRoot.root.keyId !== pinnedRootKeyId)
|
|
114
|
+
throw new Error('trust root names a different root key than the pinned fingerprint');
|
|
115
|
+
if (!verifyEnvelopeSignature(envelope, trustRoot.root.publicKey))
|
|
116
|
+
throw new Error('trust root signature is invalid');
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
throw new TrustDocumentError('UNVERIFIABLE', error.message);
|
|
120
|
+
}
|
|
121
|
+
if (trustRoot.expiresAt <= now)
|
|
122
|
+
throw new TrustDocumentError('EXPIRED', `trust root expired at ${formatTimestamp(trustRoot.expiresAt)}`);
|
|
123
|
+
return trustRoot;
|
|
124
|
+
}
|
|
125
|
+
/** Parses a trust root signed by `rootKeyId` without the expiry check, for editing. */
|
|
126
|
+
export function readTrustRootForUpdate(bytes, rootKeyId) {
|
|
127
|
+
const envelope = parseEnvelope(bytes, 'trust root');
|
|
128
|
+
if (envelope.payloadType !== TRUST_ROOT_PAYLOAD_TYPE)
|
|
129
|
+
throw new Error('trust root has the wrong payload type');
|
|
130
|
+
const trustRoot = parseTrustRootPayload(envelope.payloadBytes);
|
|
131
|
+
if (trustRoot.root.keyId !== rootKeyId || envelope.signatures[0].keyid !== rootKeyId)
|
|
132
|
+
throw new Error('trust root belongs to a different root key');
|
|
133
|
+
if (!verifyEnvelopeSignature(envelope, trustRoot.root.publicKey))
|
|
134
|
+
throw new Error('trust root signature is invalid');
|
|
135
|
+
return trustRoot;
|
|
136
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { type Certificate } from './certificate.ts';
|
|
2
|
+
import { type Revocations } from './revocations.ts';
|
|
3
|
+
import { type SkillTree, type TreeFile } from './tree-digest.ts';
|
|
4
|
+
import { type TrustRoot } from './trust-root.ts';
|
|
5
|
+
export declare const VERDICTS: readonly ["VERIFIED", "UNAPPROVED_CHANGE", "NO_CERTIFICATE", "UNTRUSTED_SIGNER", "REVOKED", "EXPIRED", "UNVERIFIABLE"];
|
|
6
|
+
export type Verdict = (typeof VERDICTS)[number];
|
|
7
|
+
export interface TrustContext {
|
|
8
|
+
trustRoot: TrustRoot;
|
|
9
|
+
revocations: Revocations;
|
|
10
|
+
}
|
|
11
|
+
export interface MinimumVersions {
|
|
12
|
+
trustRootVersion: number;
|
|
13
|
+
revocationsVersion: number;
|
|
14
|
+
}
|
|
15
|
+
export type TrustContextResult = {
|
|
16
|
+
ok: true;
|
|
17
|
+
context: TrustContext;
|
|
18
|
+
} | {
|
|
19
|
+
ok: false;
|
|
20
|
+
verdict: 'EXPIRED' | 'UNVERIFIABLE';
|
|
21
|
+
reason: string;
|
|
22
|
+
};
|
|
23
|
+
export interface CertificateEvaluation {
|
|
24
|
+
verdict: Verdict;
|
|
25
|
+
reason: string;
|
|
26
|
+
certificate?: Certificate;
|
|
27
|
+
}
|
|
28
|
+
export interface CertificateSource {
|
|
29
|
+
source: string;
|
|
30
|
+
bytes: Uint8Array;
|
|
31
|
+
}
|
|
32
|
+
export interface VerificationResult {
|
|
33
|
+
verdict: Verdict;
|
|
34
|
+
reason: string;
|
|
35
|
+
skillName: string;
|
|
36
|
+
skillDir: string;
|
|
37
|
+
digest: string | null;
|
|
38
|
+
/** Per-file hashes of the approved version; present only when VERIFIED. */
|
|
39
|
+
files: TreeFile[] | null;
|
|
40
|
+
certificateId: string | null;
|
|
41
|
+
certificateSource: string | null;
|
|
42
|
+
approverKeyId: string | null;
|
|
43
|
+
excluded: string[];
|
|
44
|
+
checkedAt: string;
|
|
45
|
+
}
|
|
46
|
+
/** Verifies the trust root and revocation list once; every Skill check reuses the result. */
|
|
47
|
+
export declare function loadTrustContext(options: {
|
|
48
|
+
trustRootBytes: Uint8Array;
|
|
49
|
+
revocationsBytes: Uint8Array;
|
|
50
|
+
rootKeyId: string;
|
|
51
|
+
now: Date;
|
|
52
|
+
minimum?: MinimumVersions | undefined;
|
|
53
|
+
}): TrustContextResult;
|
|
54
|
+
/** Checks one certificate for one Skill: trust chain, scope, signature, expiry, revocation, then bytes. */
|
|
55
|
+
export declare function evaluateCertificate(bytes: Uint8Array, skillName: string, digest: string, context: TrustContext, now: Date): CertificateEvaluation;
|
|
56
|
+
/**
|
|
57
|
+
* The Skill name from SKILL.md's bytes: an explicit name, else frontmatter "name", else the directory name.
|
|
58
|
+
* Pure, so a caller that hashes and signs those bytes can derive the name from the very same buffer.
|
|
59
|
+
*/
|
|
60
|
+
export declare function skillNameFromSkillFile(skillDir: string, skillFile: Uint8Array | undefined, explicit?: string): string;
|
|
61
|
+
/**
|
|
62
|
+
* Resolves the Skill name. SKILL.md comes from an untrusted checkout, so it is read only if it is a regular,
|
|
63
|
+
* non-symlink file no larger than the tree collector's per-file limit; anything else throws (UNVERIFIABLE).
|
|
64
|
+
*/
|
|
65
|
+
export declare function resolveSkillName(skillDir: string, explicit?: string): Promise<string>;
|
|
66
|
+
/** Says what differs between the approved file list and the tree on disk, e.g. an executable bit with no byte changed. */
|
|
67
|
+
export declare function describeTreeChange(approved: readonly TreeFile[], found: readonly TreeFile[]): string;
|
|
68
|
+
export declare function decide(options: {
|
|
69
|
+
skillDir: string;
|
|
70
|
+
skillName: string;
|
|
71
|
+
tree: SkillTree;
|
|
72
|
+
certificates: readonly CertificateSource[];
|
|
73
|
+
context: TrustContext;
|
|
74
|
+
now: Date;
|
|
75
|
+
}): VerificationResult;
|
|
76
|
+
/**
|
|
77
|
+
* Same verdict as `decide`, but candidates are evaluated one at a time as they are produced, so only the best
|
|
78
|
+
* one is retained and the first VERIFIED candidate ends the scan (later candidates are never read).
|
|
79
|
+
*/
|
|
80
|
+
export declare function decideStreaming(options: {
|
|
81
|
+
skillDir: string;
|
|
82
|
+
skillName: string;
|
|
83
|
+
tree: SkillTree;
|
|
84
|
+
certificates: AsyncIterable<CertificateSource> | Iterable<CertificateSource>;
|
|
85
|
+
context: TrustContext;
|
|
86
|
+
now: Date;
|
|
87
|
+
}): Promise<VerificationResult>;
|
|
88
|
+
/** Full check of one Skill directory against an already-verified trust context. */
|
|
89
|
+
export declare function verifySkill(options: {
|
|
90
|
+
skillDir: string;
|
|
91
|
+
skillName?: string | undefined;
|
|
92
|
+
certificates: readonly CertificateSource[] | ((skillName: string, root: string) => Promise<readonly CertificateSource[]> | AsyncIterable<CertificateSource>);
|
|
93
|
+
context: TrustContext;
|
|
94
|
+
now: Date;
|
|
95
|
+
}): Promise<VerificationResult>;
|
|
96
|
+
export declare function unverifiable(skillDir: string, skillName: string, reason: string, now: Date, verdict?: Exclude<Verdict, 'VERIFIED'>): VerificationResult;
|