@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,388 @@
1
+ import { realpath } from 'node:fs/promises';
2
+ import { homedir, hostname } from 'node:os';
3
+ import path from 'node:path';
4
+ import { isInside, readRegularFile } from "../../src/fs-safe.js";
5
+ import { appendDecision, loadPolicy, loadPolicyTrust, verifyWithPolicy } from "../../src/policy.js";
6
+ import { formatTimestamp } from "../../src/time.js";
7
+ import { CERTIFICATE_FILENAME, hashFile, sha256Hex } from "../../src/tree-digest.js";
8
+ import { unverifiable } from "../../src/verify.js";
9
+ import { piReadTarget, piReadVariants, piResolveToCwd } from "./paths.js";
10
+ const SHELL_TOOLS = new Set(['bash', 'powershell']);
11
+ const FILE_TOOLS = new Set(['read', 'edit', 'write', 'grep', 'find', 'ls']);
12
+ function defaultPolicyPath() {
13
+ return process.env.MAGO_SKI_POLICY || path.join(homedir(), '.mago-ski', 'policy.json');
14
+ }
15
+ /** Resolves symlinks on the longest existing prefix. Throws on errors other than ENOENT. */
16
+ async function canonical(target) {
17
+ let current = path.resolve(target);
18
+ const rest = [];
19
+ while (true) {
20
+ try {
21
+ return path.join(await realpath(current), ...rest.reverse());
22
+ }
23
+ catch (error) {
24
+ if (error?.code !== 'ENOENT')
25
+ throw error;
26
+ const parent = path.dirname(current);
27
+ if (parent === current)
28
+ return path.resolve(target);
29
+ rest.push(path.basename(current));
30
+ current = parent;
31
+ }
32
+ }
33
+ }
34
+ function expandHome(value) {
35
+ return value === '~' ? homedir() : value.startsWith('~/') ? path.join(homedir(), value.slice(2)) : value;
36
+ }
37
+ /** Same frontmatter handling and block format as Pi's own /skill: expansion. */
38
+ export function skillBlock(name, filePath, baseDir, content, args) {
39
+ const body = content.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/u, '').trim();
40
+ const block = `<skill name="${name}" location="${filePath}">\nReferences are relative to ${baseDir}.\n\n${body}\n</skill>`;
41
+ return args ? `${block}\n\n${args}` : block;
42
+ }
43
+ function dirsOf(entry) {
44
+ return entry.lexDir === entry.realDir ? [entry.lexDir] : [entry.lexDir, entry.realDir];
45
+ }
46
+ /**
47
+ * Excluded paths that a tool could expose. The in-tree certificate is safe only when it is the
48
+ * certificate that verified this Skill; otherwise its bytes are unchecked and may hold anything.
49
+ */
50
+ function riskyExclusions(entry) {
51
+ const verifiedInTree = entry.result.certificateSource === path.join(entry.realDir, CERTIFICATE_FILENAME);
52
+ return entry.result.excluded.filter((item) => !(item === CERTIFICATE_FILENAME && verifiedInTree));
53
+ }
54
+ export function createMagoSkiExtension(options = {}) {
55
+ return function magoSki(pi) {
56
+ const now = options.now ?? (() => new Date());
57
+ let policy = null;
58
+ /** Set when a policy file exists but cannot be loaded; the extension then fails closed. */
59
+ let policyError = null;
60
+ let loaded = false;
61
+ let entries = [];
62
+ /** Lexical Skill directories from the last run, recorded before any verification can fail. */
63
+ let knownDirs = [];
64
+ /** Enforce-mode latch: verification itself crashed, so every Skill path is treated as unverified. */
65
+ let failedClosed = false;
66
+ const lastLogged = new Map();
67
+ const mode = () => (policy ? policy.mode : 'enforce');
68
+ const active = () => policy !== null || policyError !== null;
69
+ const enforcing = () => mode() === 'enforce';
70
+ async function ensurePolicy(ctx) {
71
+ if (loaded)
72
+ return;
73
+ loaded = true;
74
+ const policyPath = options.policyPath ?? defaultPolicyPath();
75
+ try {
76
+ policy = await loadPolicy(policyPath);
77
+ }
78
+ catch (error) {
79
+ if (error?.code === 'ENOENT') {
80
+ if (ctx.hasUI)
81
+ ctx.ui.notify(`mago-ski: no policy at ${policyPath}; Skills are not being checked`, 'warning');
82
+ return;
83
+ }
84
+ policyError = `cannot load policy ${policyPath}: ${error.message}`;
85
+ if (ctx.hasUI)
86
+ ctx.ui.notify(`mago-ski: ${policyError}. Blocking all Skills until fixed.`, 'error');
87
+ }
88
+ }
89
+ async function log(record, verified) {
90
+ if (!policy?.decisionLogPath)
91
+ return;
92
+ const action = verified ? 'allow' : enforcing() ? 'block' : 'would-block';
93
+ await appendDecision(policy.decisionLogPath, { timestamp: formatTimestamp(now()), host: hostname(), mode: mode(), action, ...record })
94
+ .catch(() => { });
95
+ }
96
+ async function trustContext() {
97
+ if (!policy)
98
+ return { ok: false, verdict: 'UNVERIFIABLE', reason: policyError ?? 'no policy' };
99
+ try {
100
+ return await loadPolicyTrust(policy, now());
101
+ }
102
+ catch (error) {
103
+ return { ok: false, verdict: 'UNVERIFIABLE', reason: error.message };
104
+ }
105
+ }
106
+ /** Never throws: any failure becomes an UNVERIFIABLE entry for that Skill. */
107
+ async function verifyEntry(skill, context) {
108
+ const lexDir = path.resolve(skill.baseDir);
109
+ const entry = {
110
+ name: skill.name, baseDir: skill.baseDir, lexDir, realDir: lexDir, filePath: skill.filePath,
111
+ result: unverifiable(lexDir, skill.name, 'verification did not complete', now()),
112
+ };
113
+ try {
114
+ entry.realDir = await canonical(lexDir);
115
+ if (path.basename(skill.filePath) !== 'SKILL.md') {
116
+ entry.result = unverifiable(entry.realDir, skill.name, 'standalone Markdown Skills cannot be certified; use a directory with SKILL.md', now());
117
+ }
118
+ else if (!context.ok) {
119
+ entry.result = unverifiable(entry.realDir, skill.name, context.reason, now(), context.verdict);
120
+ }
121
+ else {
122
+ entry.result = await verifyWithPolicy(policy, entry.realDir, { now: now(), skillName: skill.name, context: context.context });
123
+ }
124
+ }
125
+ catch (error) {
126
+ entry.result = unverifiable(entry.realDir, skill.name, `verification failed: ${error.message}`, now());
127
+ }
128
+ return entry;
129
+ }
130
+ function recordFor(entry, event, verdict = entry.result.verdict, reason = entry.result.reason) {
131
+ return {
132
+ event, skill: entry.name, skill_dir: entry.realDir, digest: entry.result.digest,
133
+ certificate_id: entry.result.certificateId, verdict, reason,
134
+ };
135
+ }
136
+ async function refresh(skills, ctx) {
137
+ const context = await trustContext();
138
+ const fresh = [];
139
+ for (const skill of skills)
140
+ fresh.push(await verifyEntry(skill, context));
141
+ entries = fresh;
142
+ for (const entry of fresh) {
143
+ if (lastLogged.get(entry.lexDir) === entry.result.verdict)
144
+ continue;
145
+ lastLogged.set(entry.lexDir, entry.result.verdict);
146
+ await log(recordFor(entry, 'advertise'), entry.result.verdict === 'VERIFIED');
147
+ if (entry.result.verdict !== 'VERIFIED' && ctx.hasUI) {
148
+ const verb = enforcing() ? 'blocked' : 'would block (shadow)';
149
+ ctx.ui.notify(`mago-ski ${verb} Skill "${entry.name}": ${entry.result.verdict} - ${entry.result.reason}`, enforcing() ? 'error' : 'warning');
150
+ }
151
+ }
152
+ if (ctx.hasUI) {
153
+ const ok = fresh.filter((entry) => entry.result.verdict === 'VERIFIED').length;
154
+ ctx.ui.setStatus('mago-ski', `mago-ski ${mode()}: ${ok}/${fresh.length} Skills verified`);
155
+ }
156
+ return fresh;
157
+ }
158
+ async function reverify(entry) {
159
+ const updated = await verifyEntry({ name: entry.name, baseDir: entry.baseDir, filePath: entry.filePath }, await trustContext());
160
+ entries = entries.map((item) => (item === entry ? updated : item));
161
+ return updated;
162
+ }
163
+ function byName(name) {
164
+ return entries.find((entry) => entry.name === name);
165
+ }
166
+ /** Skills a path is inside, matching the lexical and the canonical path against both Skill forms. */
167
+ function containing(paths) {
168
+ return entries.filter((entry) => dirsOf(entry).some((dir) => paths.some((target) => isInside(dir, target))));
169
+ }
170
+ /** Skills inside a directory a tool would search. */
171
+ function contained(paths) {
172
+ return entries.filter((entry) => dirsOf(entry).some((dir) => paths.some((target) => target !== dir && isInside(target, dir))));
173
+ }
174
+ /** Logs the decision; returns a block in enforce mode, undefined in shadow mode. */
175
+ async function judge(entry, event, verdict, reason) {
176
+ await log(recordFor(entry, event, verdict, reason), false);
177
+ return enforcing() ? { block: true, reason: `mago-ski: Skill "${entry.name}" ${verdict}: ${reason}` } : undefined;
178
+ }
179
+ async function checkShell(toolName, command) {
180
+ // Best-effort: shell commands can reach files in ways a string match cannot see.
181
+ for (const entry of [...entries]) {
182
+ const forms = new Set([...dirsOf(entry), entry.baseDir]);
183
+ for (const dir of [...forms])
184
+ if (dir.startsWith(homedir()))
185
+ forms.add(`~${dir.slice(homedir().length)}`);
186
+ if (![...forms].some((form) => command.includes(form)))
187
+ continue;
188
+ const current = entry.result.verdict === 'VERIFIED' ? await reverify(entry) : entry;
189
+ if (current.result.verdict !== 'VERIFIED') {
190
+ const blocked = await judge(current, `tool:${toolName}`, current.result.verdict, current.result.reason);
191
+ if (blocked)
192
+ return blocked;
193
+ }
194
+ }
195
+ return undefined;
196
+ }
197
+ async function checkGrep(affected) {
198
+ for (const entry of affected) {
199
+ if (entry.result.verdict !== 'VERIFIED') {
200
+ const blocked = await judge(entry, 'tool:grep', entry.result.verdict, entry.result.reason);
201
+ if (blocked)
202
+ return blocked;
203
+ continue;
204
+ }
205
+ const risky = riskyExclusions(entry);
206
+ if (risky.length > 0) {
207
+ const blocked = await judge(entry, 'tool:grep', 'UNAPPROVED_CHANGE', `the Skill has files excluded from its certificate (${risky.slice(0, 3).join(', ')}); grep could return them. Use read on specific files`);
208
+ if (blocked)
209
+ return blocked;
210
+ continue;
211
+ }
212
+ const current = await reverify(entry);
213
+ if (current.result.verdict !== 'VERIFIED') {
214
+ const blocked = await judge(current, 'tool:grep', current.result.verdict, current.result.reason);
215
+ if (blocked)
216
+ return blocked;
217
+ continue;
218
+ }
219
+ // Files can appear in excluded locations after the run started; check the fresh result too.
220
+ const late = riskyExclusions(current);
221
+ if (late.length > 0) {
222
+ const blocked = await judge(current, 'tool:grep', 'UNAPPROVED_CHANGE', `the Skill has files excluded from its certificate (${late.slice(0, 3).join(', ')}); grep could return them. Use read on specific files`);
223
+ if (blocked)
224
+ return blocked;
225
+ }
226
+ }
227
+ return undefined;
228
+ }
229
+ /**
230
+ * Every path a file tool call could touch: Pi's own resolution of the argument (and, for read,
231
+ * the filename variants Pi tries), a plain resolution as a fallback, and each one's canonical form.
232
+ */
233
+ async function toolTargets(toolName, rawPath, cwd) {
234
+ const piPath = piResolveToCwd(rawPath, cwd);
235
+ const lexicals = new Set([...(toolName === 'read' ? piReadVariants(piPath) : [piPath]), path.resolve(cwd, expandHome(rawPath))]);
236
+ const targets = new Set();
237
+ for (const lexical of lexicals) {
238
+ targets.add(lexical);
239
+ // An unresolvable path (for example, permission denied) is still matched lexically.
240
+ targets.add(await canonical(lexical).catch(() => lexical));
241
+ }
242
+ return { targets: [...targets], piPath };
243
+ }
244
+ async function checkFileTool(toolName, rawPath, cwd) {
245
+ const { targets, piPath } = await toolTargets(toolName, rawPath, cwd);
246
+ const inside = containing(targets);
247
+ if (toolName === 'grep')
248
+ return await checkGrep([...inside, ...contained(targets).filter((entry) => !inside.includes(entry))]);
249
+ const unverified = inside.find((entry) => entry.result.verdict !== 'VERIFIED');
250
+ if (unverified)
251
+ return await judge(unverified, `tool:${toolName}`, unverified.result.verdict, unverified.result.reason);
252
+ const entry = inside[0];
253
+ if (!entry)
254
+ return undefined;
255
+ if (toolName === 'edit' || toolName === 'write') {
256
+ return await judge(entry, `tool:${toolName}`, 'UNAPPROVED_CHANGE', 'changing an approved Skill would invalidate its certificate');
257
+ }
258
+ if (toolName !== 'read')
259
+ return undefined; // find and ls show names, not contents
260
+ const opened = piReadTarget(piPath);
261
+ const resolved = await canonical(opened).catch(() => opened);
262
+ if (!isInside(entry.realDir, resolved)) {
263
+ return await judge(entry, 'tool:read', 'UNAPPROVED_CHANGE', `${rawPath} leaves the Skill directory through a link`);
264
+ }
265
+ const relative = path.relative(entry.realDir, resolved).split(path.sep).join('/');
266
+ const approved = entry.result.files?.find((file) => file.path === relative);
267
+ if (!approved)
268
+ return await judge(entry, 'tool:read', 'UNAPPROVED_CHANGE', `${relative} is not covered by the Skill's certificate`);
269
+ try {
270
+ const actual = await hashFile(resolved, relative);
271
+ if (actual.sha256 !== approved.sha256 || actual.exec !== approved.exec)
272
+ throw new Error(`${relative} changed after verification`);
273
+ }
274
+ catch (error) {
275
+ entry.result = { ...entry.result, verdict: 'UNAPPROVED_CHANGE', reason: error.message, files: null };
276
+ return await judge(entry, 'tool:read', 'UNAPPROVED_CHANGE', error.message);
277
+ }
278
+ return undefined;
279
+ }
280
+ /** Used only after verification itself crashed in enforce mode. Matches Skill dirs in every known form. */
281
+ async function latchBlock(toolName, input, cwd) {
282
+ const reason = 'mago-ski: Skill verification failed earlier in this run; Skill files are blocked until it succeeds';
283
+ if (SHELL_TOOLS.has(toolName)) {
284
+ const command = String(input.command ?? '');
285
+ const forms = new Set(knownDirs);
286
+ for (const dir of knownDirs)
287
+ if (dir.startsWith(homedir()))
288
+ forms.add(`~${dir.slice(homedir().length)}`);
289
+ return [...forms].some((form) => command.includes(form)) ? { block: true, reason } : undefined;
290
+ }
291
+ const rawPath = typeof input.path === 'string' && input.path !== '' ? input.path : '.';
292
+ const { targets } = await toolTargets(toolName, rawPath, cwd);
293
+ const touches = knownDirs.some((dir) => targets.some((target) => isInside(dir, target) || isInside(target, dir)));
294
+ return touches ? { block: true, reason } : undefined;
295
+ }
296
+ pi.on('session_start', async (_event, ctx) => {
297
+ if (process.platform === 'win32' && ctx.hasUI) {
298
+ ctx.ui.notify('mago-ski: Windows is not supported in 0.1. Executable bits are not covered, so Skills approved on Linux or macOS may not verify.', 'warning');
299
+ }
300
+ await ensurePolicy(ctx);
301
+ });
302
+ pi.on('before_agent_start', async (event, ctx) => {
303
+ await ensurePolicy(ctx);
304
+ if (!active())
305
+ return;
306
+ knownDirs = event.systemPromptOptions.skills.map((skill) => path.resolve(skill.baseDir));
307
+ try {
308
+ for (const dir of [...knownDirs]) {
309
+ const real = await canonical(dir).catch(() => dir);
310
+ if (!knownDirs.includes(real))
311
+ knownDirs.push(real);
312
+ }
313
+ const checked = await refresh(event.systemPromptOptions.skills, ctx);
314
+ failedClosed = false;
315
+ if (enforcing()) {
316
+ const allowed = new Set(checked.filter((entry) => entry.result.verdict === 'VERIFIED').map((entry) => entry.lexDir));
317
+ event.systemPromptOptions.skills = event.systemPromptOptions.skills.filter((skill) => allowed.has(path.resolve(skill.baseDir)));
318
+ }
319
+ }
320
+ catch (error) {
321
+ // Fail closed: an unexpected error must not leave unchecked Skills advertised or readable.
322
+ if (enforcing()) {
323
+ failedClosed = true;
324
+ event.systemPromptOptions.skills = [];
325
+ }
326
+ if (ctx.hasUI)
327
+ ctx.ui.notify(`mago-ski: verification failed (${error.message}); no Skills advertised`, 'error');
328
+ }
329
+ });
330
+ pi.on('input', async (event, ctx) => {
331
+ await ensurePolicy(ctx);
332
+ if (!active() || !event.text.startsWith('/skill:'))
333
+ return { action: 'continue' };
334
+ const space = event.text.indexOf(' ');
335
+ const name = space === -1 ? event.text.slice(7) : event.text.slice(7, space);
336
+ const args = space === -1 ? '' : event.text.slice(space + 1).trim();
337
+ const known = byName(name);
338
+ if (!known) {
339
+ // Not seen yet (first prompt of a session). Never let Pi expand it unchecked: turn it into a
340
+ // plain request; the model can only use the Skill if it is advertised, and reads are checked.
341
+ if (!enforcing())
342
+ return { action: 'continue' };
343
+ return { action: 'transform', text: `Use the "${name}" skill.${args ? ` ${args}` : ''}` };
344
+ }
345
+ const entry = await reverify(known);
346
+ if (entry.result.verdict === 'VERIFIED') {
347
+ try {
348
+ const bytes = await readRegularFile(entry.filePath, 'SKILL.md', 8 * 1024 * 1024);
349
+ const approved = entry.result.files?.find((file) => file.path === 'SKILL.md');
350
+ if (!approved || approved.sha256 !== sha256Hex(bytes))
351
+ throw new Error('SKILL.md changed after verification');
352
+ return { action: 'transform', text: skillBlock(entry.name, entry.filePath, entry.baseDir, bytes.toString('utf8'), args) };
353
+ }
354
+ catch (error) {
355
+ const blocked = await judge(entry, 'skill-command', 'UNAPPROVED_CHANGE', error.message);
356
+ if (!blocked)
357
+ return { action: 'continue' };
358
+ if (ctx.hasUI)
359
+ ctx.ui.notify(blocked.reason, 'error');
360
+ return { action: 'handled' };
361
+ }
362
+ }
363
+ const blocked = await judge(entry, 'skill-command', entry.result.verdict, entry.result.reason);
364
+ if (!blocked)
365
+ return { action: 'continue' };
366
+ if (ctx.hasUI)
367
+ ctx.ui.notify(blocked.reason, 'error');
368
+ return { action: 'handled' };
369
+ });
370
+ pi.on('tool_call', async (event, ctx) => {
371
+ if (!active())
372
+ return undefined;
373
+ const input = event.input;
374
+ const toolName = event.toolName;
375
+ if (!SHELL_TOOLS.has(toolName) && !FILE_TOOLS.has(toolName))
376
+ return undefined;
377
+ if (failedClosed && enforcing())
378
+ return await latchBlock(toolName, input, ctx.cwd);
379
+ if (entries.length === 0)
380
+ return undefined;
381
+ if (SHELL_TOOLS.has(toolName))
382
+ return await checkShell(toolName, typeof input.command === 'string' ? input.command : '');
383
+ const rawPath = typeof input.path === 'string' && input.path !== '' ? input.path : '.';
384
+ return await checkFileTool(toolName, rawPath, ctx.cwd);
385
+ });
386
+ };
387
+ }
388
+ export default createMagoSkiExtension();
@@ -0,0 +1,9 @@
1
+ /** Pi's resolveToCwd: Unicode spaces, leading "@", Windows shell paths, "~", file:// URLs, then resolve. */
2
+ export declare function piResolveToCwd(input: string, cwd: string): string;
3
+ /**
4
+ * Pi's `read` tool tries these spellings in order when the resolved path does not exist
5
+ * (macOS screenshot names, NFD, curly quotes) and opens the first that exists.
6
+ */
7
+ export declare function piReadVariants(resolved: string): string[];
8
+ /** The path Pi's `read` will open: the first existing variant, or the resolved path. */
9
+ export declare function piReadTarget(resolved: string): string;
@@ -0,0 +1,55 @@
1
+ // Mirrors how Pi 1.1's built-in tools turn a tool `path` argument into a file system path
2
+ // (dist/utils/paths.js normalizePath/resolvePath and dist/core/tools/path-utils.js), so the
3
+ // extension authorizes the same file Pi will actually open. Keep in sync when Pi changes.
4
+ import { existsSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ const UNICODE_SPACES = /[  -    ]/gu;
9
+ /** Git Bash, MSYS, Cygwin and WSL drive paths, as Pi converts them on native Windows. */
10
+ function normalizeWindowsShellPath(filePath) {
11
+ if (!filePath.startsWith('/') || filePath.startsWith('//') || filePath.includes('\\'))
12
+ return filePath;
13
+ const match = /^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/iu.exec(filePath);
14
+ if (!match)
15
+ return filePath;
16
+ return `${match[1].toUpperCase()}:\\${match[2]?.replaceAll('/', '\\') ?? ''}`;
17
+ }
18
+ /** Pi's resolveToCwd: Unicode spaces, leading "@", Windows shell paths, "~", file:// URLs, then resolve. */
19
+ export function piResolveToCwd(input, cwd) {
20
+ let normalized = input.replace(UNICODE_SPACES, ' ');
21
+ if (normalized.startsWith('@'))
22
+ normalized = normalized.slice(1);
23
+ if (process.platform === 'win32')
24
+ normalized = normalizeWindowsShellPath(normalized);
25
+ if (normalized === '~') {
26
+ normalized = homedir();
27
+ }
28
+ else if (normalized.startsWith('~/') || (process.platform === 'win32' && normalized.startsWith('~\\'))) {
29
+ normalized = path.join(homedir(), normalized.slice(2));
30
+ }
31
+ else if (/^file:\/\//u.test(normalized)) {
32
+ try {
33
+ normalized = fileURLToPath(normalized);
34
+ }
35
+ catch {
36
+ // Pi would throw too; leave the text so it is still matched lexically.
37
+ }
38
+ }
39
+ return path.isAbsolute(normalized) ? path.resolve(normalized) : path.resolve(cwd, normalized);
40
+ }
41
+ /**
42
+ * Pi's `read` tool tries these spellings in order when the resolved path does not exist
43
+ * (macOS screenshot names, NFD, curly quotes) and opens the first that exists.
44
+ */
45
+ export function piReadVariants(resolved) {
46
+ const amPm = resolved.replace(/ (AM|PM)\./giu, ' $1.');
47
+ const nfd = resolved.normalize('NFD');
48
+ const curly = resolved.replace(/'/gu, '’');
49
+ const nfdCurly = nfd.replace(/'/gu, '’');
50
+ return [...new Set([resolved, amPm, nfd, curly, nfdCurly])];
51
+ }
52
+ /** The path Pi's `read` will open: the first existing variant, or the resolved path. */
53
+ export function piReadTarget(resolved) {
54
+ return piReadVariants(resolved).find((candidate) => existsSync(candidate)) ?? resolved;
55
+ }
@@ -0,0 +1,70 @@
1
+ export declare const DEFAULT_TRUST_ROOT_EXPIRY = "365d";
2
+ export declare const DEFAULT_REVOCATIONS_EXPIRY = "30d";
3
+ export declare function initRoot(options: {
4
+ rootKeyPath: string;
5
+ trustRootOut: string;
6
+ revocationsOut: string;
7
+ now: Date;
8
+ trustRootExpires?: string;
9
+ revocationsExpires?: string;
10
+ }): Promise<{
11
+ rootKeyId: string;
12
+ trustRoot: string;
13
+ revocations: string;
14
+ }>;
15
+ export declare function addApprover(options: {
16
+ rootKeyPath: string;
17
+ trustRootPath: string;
18
+ out?: string;
19
+ now: Date;
20
+ trustRootExpires?: string;
21
+ publicKeyPath: string;
22
+ name: string;
23
+ scopes: string[];
24
+ expires: string;
25
+ }): Promise<{
26
+ version: number;
27
+ path: string;
28
+ keyId: string;
29
+ }>;
30
+ export declare function removeApprover(options: {
31
+ rootKeyPath: string;
32
+ trustRootPath: string;
33
+ out?: string;
34
+ now: Date;
35
+ trustRootExpires?: string;
36
+ keyId: string;
37
+ }): Promise<{
38
+ version: number;
39
+ path: string;
40
+ }>;
41
+ export declare function updateRevocations(options: {
42
+ rootKeyPath: string;
43
+ revocationsPath: string;
44
+ out?: string;
45
+ now: Date;
46
+ expires?: string;
47
+ revokeKey?: string;
48
+ revokeDigest?: string;
49
+ reason?: string;
50
+ }): Promise<{
51
+ version: number;
52
+ path: string;
53
+ expiresAt: Date;
54
+ }>;
55
+ export declare function approveSkill(options: {
56
+ skillDir: string;
57
+ approverKeyPath: string;
58
+ now: Date;
59
+ expires: string;
60
+ reason: string;
61
+ name?: string;
62
+ previous?: string;
63
+ out?: string;
64
+ }): Promise<{
65
+ path: string;
66
+ skillName: string;
67
+ digest: string;
68
+ certificateId: string;
69
+ expiresAt: Date;
70
+ }>;
@@ -0,0 +1,115 @@
1
+ import path from 'node:path';
2
+ import { issueCertificate, parseCertificate } from "./certificate.js";
3
+ import { readRegularFile, resolveOutside, writeFileAtomic, writeNewFile } from "./fs-safe.js";
4
+ import { loadPrivateKey, loadPublicKey } from "./keys.js";
5
+ import { validateDigest, validateScope } from "./names.js";
6
+ import { readRevocationsForUpdate, signRevocations } from "./revocations.js";
7
+ import { addDuration, truncateToSecond } from "./time.js";
8
+ import { CERTIFICATE_FILENAME, collectSkillTree } from "./tree-digest.js";
9
+ import { readTrustRootForUpdate, signTrustRoot } from "./trust-root.js";
10
+ import { resolveSkillName } from "./verify.js";
11
+ export const DEFAULT_TRUST_ROOT_EXPIRY = '365d';
12
+ export const DEFAULT_REVOCATIONS_EXPIRY = '30d';
13
+ const PRIVATE_KEY_PATTERN = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----/u;
14
+ export async function initRoot(options) {
15
+ const root = await loadPrivateKey(options.rootKeyPath);
16
+ const issuedAt = truncateToSecond(options.now);
17
+ const trustRoot = {
18
+ version: 1, issuedAt, expiresAt: addDuration(issuedAt, options.trustRootExpires ?? DEFAULT_TRUST_ROOT_EXPIRY, 'trust root expiry'),
19
+ root, approvers: [],
20
+ };
21
+ const revocations = {
22
+ version: 1, issuedAt, expiresAt: addDuration(issuedAt, options.revocationsExpires ?? DEFAULT_REVOCATIONS_EXPIRY, 'revocation list expiry'),
23
+ rootKeyId: root.keyId, keys: [], digests: [],
24
+ };
25
+ const trustRootPath = await writeNewFile(options.trustRootOut, signTrustRoot(trustRoot, root.privateKey));
26
+ const revocationsPath = await writeNewFile(options.revocationsOut, signRevocations(revocations, root.privateKey));
27
+ return { rootKeyId: root.keyId, trustRoot: trustRootPath, revocations: revocationsPath };
28
+ }
29
+ async function updateTrustRoot(options, change) {
30
+ const root = await loadPrivateKey(options.rootKeyPath);
31
+ const current = readTrustRootForUpdate(await readRegularFile(options.trustRootPath, 'Trust root', 4 * 1024 * 1024), root.keyId);
32
+ const issuedAt = truncateToSecond(options.now);
33
+ const next = {
34
+ ...current,
35
+ version: current.version + 1,
36
+ issuedAt,
37
+ expiresAt: options.expires ? addDuration(issuedAt, options.expires, 'trust root expiry') : current.expiresAt,
38
+ approvers: current.approvers.map((approver) => ({ ...approver, scopes: [...approver.scopes] })),
39
+ };
40
+ change(next);
41
+ if (next.expiresAt <= issuedAt)
42
+ throw new Error('The trust root would already be expired; pass --expires to extend it');
43
+ const written = await writeFileAtomic(options.out ?? options.trustRootPath, signTrustRoot(next, root.privateKey));
44
+ return { version: next.version, path: written, trustRoot: next };
45
+ }
46
+ export async function addApprover(options) {
47
+ const approverKey = await loadPublicKey(options.publicKeyPath);
48
+ if (options.scopes.length === 0)
49
+ throw new Error('At least one --scope is required');
50
+ const scopes = [...new Set(options.scopes.map((scope) => validateScope(scope)))].sort();
51
+ const result = await updateTrustRoot({ rootKeyPath: options.rootKeyPath, trustRootPath: options.trustRootPath, out: options.out, now: options.now, expires: options.trustRootExpires }, (trustRoot) => {
52
+ if (approverKey.keyId === trustRoot.root.keyId)
53
+ throw new Error('The root key cannot be an approver; generate a separate approver key');
54
+ trustRoot.approvers = trustRoot.approvers.filter((entry) => entry.keyId !== approverKey.keyId);
55
+ trustRoot.approvers.push({ ...approverKey, name: options.name, scopes, expiresAt: addDuration(truncateToSecond(options.now), options.expires, 'approver expiry') });
56
+ });
57
+ return { version: result.version, path: result.path, keyId: approverKey.keyId };
58
+ }
59
+ export async function removeApprover(options) {
60
+ return await updateTrustRoot({ rootKeyPath: options.rootKeyPath, trustRootPath: options.trustRootPath, out: options.out, now: options.now, expires: options.trustRootExpires }, (trustRoot) => {
61
+ const before = trustRoot.approvers.length;
62
+ trustRoot.approvers = trustRoot.approvers.filter((entry) => entry.keyId !== options.keyId);
63
+ if (trustRoot.approvers.length === before)
64
+ throw new Error(`No approver with key id ${options.keyId}`);
65
+ });
66
+ }
67
+ export async function updateRevocations(options) {
68
+ const root = await loadPrivateKey(options.rootKeyPath);
69
+ const current = readRevocationsForUpdate(await readRegularFile(options.revocationsPath, 'Revocation list', 8 * 1024 * 1024), root.keyId, root.publicKey);
70
+ const issuedAt = truncateToSecond(options.now);
71
+ const next = {
72
+ ...current, version: current.version + 1, issuedAt,
73
+ expiresAt: addDuration(issuedAt, options.expires ?? DEFAULT_REVOCATIONS_EXPIRY, 'revocation list expiry'),
74
+ keys: [...current.keys], digests: [...current.digests],
75
+ };
76
+ if (options.revokeKey) {
77
+ if (next.keys.some((entry) => entry.keyId === options.revokeKey))
78
+ throw new Error(`Key ${options.revokeKey} is already revoked`);
79
+ next.keys.push({ keyId: options.revokeKey, reason: options.reason ?? 'revoked', revokedAt: issuedAt });
80
+ }
81
+ if (options.revokeDigest) {
82
+ const digest = validateDigest(options.revokeDigest);
83
+ if (next.digests.some((entry) => entry.digest === digest))
84
+ throw new Error(`Digest ${digest} is already revoked`);
85
+ next.digests.push({ digest, reason: options.reason ?? 'revoked', revokedAt: issuedAt });
86
+ }
87
+ const written = await writeFileAtomic(options.out ?? options.revocationsPath, signRevocations(next, root.privateKey));
88
+ return { version: next.version, path: written, expiresAt: next.expiresAt };
89
+ }
90
+ export async function approveSkill(options) {
91
+ const skillDir = path.resolve(options.skillDir);
92
+ const approver = await loadPrivateKey(options.approverKeyPath);
93
+ await resolveOutside(options.approverKeyPath, skillDir, 'Approver private key');
94
+ const skillName = await resolveSkillName(skillDir, options.name);
95
+ const tree = await collectSkillTree(skillDir, { includeContents: true });
96
+ for (const [filePath, content] of tree.contents) {
97
+ if (PRIVATE_KEY_PATTERN.test(content.toString('latin1'))) {
98
+ throw new Error(`Refusing to approve: ${filePath} contains a private key. Remove it from the Skill and rotate that key.`);
99
+ }
100
+ }
101
+ let previousDigest = null;
102
+ if (options.previous) {
103
+ previousDigest = options.previous.startsWith('sha256:')
104
+ ? validateDigest(options.previous, 'previous digest')
105
+ : parseCertificate(await readRegularFile(options.previous, 'Previous certificate', 8 * 1024 * 1024)).digest;
106
+ }
107
+ const issuedAt = truncateToSecond(options.now);
108
+ const expiresAt = addDuration(issuedAt, options.expires, 'certificate expiry');
109
+ const bytes = issueCertificate({
110
+ skillName, digest: tree.digest, files: tree.files, approver, issuedAt, expiresAt, reason: options.reason, previousDigest,
111
+ });
112
+ const out = options.out ?? path.join(tree.root, CERTIFICATE_FILENAME);
113
+ const written = await writeFileAtomic(out, bytes);
114
+ return { path: written, skillName, digest: tree.digest, certificateId: parseCertificate(bytes).id, expiresAt };
115
+ }
@@ -0,0 +1,12 @@
1
+ export declare const MAX_CANONICAL_JSON_BYTES: number;
2
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
3
+ [key: string]: JsonValue;
4
+ };
5
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
6
+ export declare function serializeCanonicalJson(value: unknown): string;
7
+ export declare function canonicalBytes(value: unknown): Buffer;
8
+ export declare function parseCanonicalJsonBytes(input: Uint8Array, label?: string): unknown;
9
+ export declare function exactKeys(value: unknown, keys: readonly string[], label: string): Record<string, unknown>;
10
+ export declare function requireString(value: unknown, label: string, maxLength?: number): string;
11
+ export declare function requireArray(value: unknown, label: string, maxLength: number): unknown[];
12
+ export declare function requirePositiveInteger(value: unknown, label: string): number;