@mago-foundation/mago-ski 0.4.0 → 0.4.1

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/action.yml CHANGED
@@ -31,8 +31,17 @@ runs:
31
31
  with:
32
32
  node-version: 22.23.4
33
33
 
34
+ # The base checkout goes to a path inside the workspace, which holds the pull request. Whatever the pull request put
35
+ # at that path (a folder, or a link that would send the checkout somewhere else) is removed first.
36
+ - name: Clear the base checkout path
37
+ if: github.event_name == 'pull_request' || github.event_name == 'pull_request_target'
38
+ shell: bash
39
+ run: |
40
+ set -euo pipefail
41
+ rm -rf -- "${GITHUB_WORKSPACE:?}/.mago-ski-base"
42
+
34
43
  - name: Check out the protected base revision
35
- if: github.event_name == 'pull_request'
44
+ if: github.event_name == 'pull_request' || github.event_name == 'pull_request_target'
36
45
  uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
37
46
  with:
38
47
  repository: ${{ github.repository }}
@@ -47,11 +56,21 @@ runs:
47
56
  MAGO_POLICY: ${{ inputs.policy }}
48
57
  MAGO_EVENT: ${{ github.event_name }}
49
58
  MAGO_ACTION_PATH: ${{ github.action_path }}
59
+ MAGO_BASE_SHA: ${{ github.event.pull_request.base.sha }}
50
60
  run: |
51
61
  set -euo pipefail
52
62
  policy_root="$GITHUB_WORKSPACE"
53
- if [[ "$MAGO_EVENT" == pull_request ]]; then
63
+ if [[ "$MAGO_EVENT" == pull_request || "$MAGO_EVENT" == pull_request_target ]]; then
54
64
  policy_root="$GITHUB_WORKSPACE/.mago-ski-base"
65
+ # Trust must come from the base revision itself: a real folder at that path, checked out at the base commit.
66
+ if [[ -L "$policy_root" || ! -d "$policy_root" || -L "$policy_root/.git" ]]; then
67
+ echo "::error title=mago-ski::the base checkout at .mago-ski-base is not a real folder"
68
+ exit 2
69
+ fi
70
+ if [[ "$(git -C "$policy_root" rev-parse HEAD)" != "$MAGO_BASE_SHA" ]]; then
71
+ echo "::error title=mago-ski::the base checkout at .mago-ski-base is not at the base revision"
72
+ exit 2
73
+ fi
55
74
  fi
56
75
  # The verifier runs from this action's own checkout (pinned by the caller's `uses:` ref),
57
76
  # never from code in the repository under review.
@@ -27,3 +27,12 @@ export interface GitHubCheckResult {
27
27
  /** Names and paths come from the pull request; keep them inert inside a Markdown table cell. */
28
28
  export declare function markdownCell(value: string): string;
29
29
  export declare function runGitHubCheck(options: GitHubCheckOptions): Promise<GitHubCheckResult>;
30
+ /** Escapes the message part of a workflow command (after the `::`). */
31
+ export declare function escapeAnnotation(value: string): string;
32
+ /**
33
+ * Escapes a property value of a workflow command (`file=...`). Properties are separated by `,` and end at `::`, so a path
34
+ * from the pull request must not be able to add a property or end the list: `:` and `,` are escaped as well.
35
+ */
36
+ export declare function escapeAnnotationProperty(value: string): string;
37
+ /** One annotation line for a failing Skill. */
38
+ export declare function annotationLine(level: 'error' | 'warning', file: string | null, verdict: string, message: string): string;
@@ -4,7 +4,7 @@
4
4
  // therefore add certificates but cannot change who is trusted to issue them.
5
5
  import { appendFile, realpath } from 'node:fs/promises';
6
6
  import path from 'node:path';
7
- import { isInside } from "../../src/fs-safe.js";
7
+ import { isInside, realpathAllowingMissing } from "../../src/fs-safe.js";
8
8
  import { isMainModule } from "../../src/main-module.js";
9
9
  import { DiscoveryBudgetError, findSkillDirs, loadPolicy, loadPolicyTrust, tooDeepResult, trustFailureEvent, verifyWithPolicy, } from "../../src/policy.js";
10
10
  import { unverifiable } from "../../src/verify.js";
@@ -27,23 +27,23 @@ function within(root, target, label) {
27
27
  /** Containment on resolved paths, so a symlink cannot point a policy path outside its checkout. */
28
28
  async function withinReal(root, target, label) {
29
29
  within(root, target, label);
30
- let resolved;
31
- try {
32
- resolved = await realpath(target);
33
- }
34
- catch (error) {
35
- if (error?.code === 'ENOENT')
36
- return target;
37
- throw error;
38
- }
30
+ // The existing part of the path is resolved even when the last parts are missing: a link on the way still counts.
31
+ const resolved = await realpathAllowingMissing(target);
39
32
  if (!isInside(await realpath(root), resolved))
40
33
  throw new Error(`${label} must stay inside ${root} (it resolves to ${resolved})`);
41
34
  return target;
42
35
  }
43
- /** Re-anchors a path from the policy checkout into the workspace checkout. */
36
+ /**
37
+ * Re-anchors a path from the policy checkout into the workspace checkout. The action places the base checkout inside the
38
+ * workspace (`.mago-ski-base`), so "inside the workspace" is not enough: a path of the pull request that resolves into the
39
+ * base checkout would have the check read the base revision's Skills or certificates instead of the pull request's.
40
+ */
44
41
  async function toWorkspace(policyRoot, workspace, target, label) {
45
42
  const relative = path.relative(policyRoot, within(policyRoot, target, label));
46
- return await withinReal(workspace, path.join(workspace, relative), label);
43
+ const moved = await withinReal(workspace, path.join(workspace, relative), label);
44
+ if (policyRoot !== workspace && isInside(await realpathAllowingMissing(policyRoot), await realpathAllowingMissing(moved)))
45
+ throw new Error(`${label} must not resolve into the base checkout (${policyRoot})`);
46
+ return moved;
47
47
  }
48
48
  export async function runGitHubCheck(options) {
49
49
  const now = options.now ?? new Date();
@@ -95,7 +95,8 @@ export async function runGitHubCheck(options) {
95
95
  }
96
96
  let discovery;
97
97
  try {
98
- discovery = await findSkillDirs(policy.skillDirs);
98
+ // The base checkout sits inside the workspace on pull requests; its Skills are not the pull request's.
99
+ discovery = await findSkillDirs(policy.skillDirs, undefined, policyRoot === workspace ? {} : { exclude: [policyRoot] });
99
100
  }
100
101
  catch (error) {
101
102
  if (!(error instanceof DiscoveryBudgetError))
@@ -138,9 +139,22 @@ export async function runGitHubCheck(options) {
138
139
  ].join('\n');
139
140
  return { mode: policy.mode, results, exitCode: failures.length > 0 && policy.mode === 'enforce' ? 1 : 0, summary };
140
141
  }
141
- function escapeAnnotation(value) {
142
+ /** Escapes the message part of a workflow command (after the `::`). */
143
+ export function escapeAnnotation(value) {
142
144
  return value.replace(/%/gu, '%25').replace(/\r/gu, '%0D').replace(/\n/gu, '%0A');
143
145
  }
146
+ /**
147
+ * Escapes a property value of a workflow command (`file=...`). Properties are separated by `,` and end at `::`, so a path
148
+ * from the pull request must not be able to add a property or end the list: `:` and `,` are escaped as well.
149
+ */
150
+ export function escapeAnnotationProperty(value) {
151
+ return escapeAnnotation(value).replace(/:/gu, '%3A').replace(/,/gu, '%2C');
152
+ }
153
+ /** One annotation line for a failing Skill. */
154
+ export function annotationLine(level, file, verdict, message) {
155
+ const location = file === null ? '' : `file=${escapeAnnotationProperty(file)},`;
156
+ return `::${level} ${location}title=mago-ski ${escapeAnnotationProperty(verdict)}::${escapeAnnotation(message)}\n`;
157
+ }
144
158
  async function main() {
145
159
  const [policyRoot, workspace, policy] = process.argv.slice(2);
146
160
  if (!policyRoot || !workspace || !policy)
@@ -156,8 +170,8 @@ async function main() {
156
170
  }
157
171
  annotations += 1;
158
172
  const level = result.mode === 'enforce' || result.trustFailure === 'root-revoked' ? 'error' : 'warning';
159
- const location = result.budgetExceeded || result.trustFailure ? '' : `file=${escapeAnnotation(path.relative(path.resolve(workspace), path.join(entry.skillDir, 'SKILL.md')))},`;
160
- process.stdout.write(`::${level} ${location}title=mago-ski ${entry.verdict}::${escapeAnnotation(`${entry.skillName}: ${entry.reason}`)}\n`);
173
+ const file = result.budgetExceeded || result.trustFailure ? null : path.relative(path.resolve(workspace), path.join(entry.skillDir, 'SKILL.md'));
174
+ process.stdout.write(annotationLine(level, file, entry.verdict, `${entry.skillName}: ${entry.reason}`));
161
175
  }
162
176
  process.stdout.write(`${result.summary}\n`);
163
177
  if (process.env.GITHUB_STEP_SUMMARY)
@@ -152,7 +152,9 @@ export function createMagoSkiExtension(options = {}) {
152
152
  policy = await loadPolicy(policyPath);
153
153
  }
154
154
  catch (error) {
155
- if (error?.code === 'ENOENT') {
155
+ // No policy at the default place means mago-ski is not set up here. A policy that was named (the option, or
156
+ // MAGO_SKI_POLICY) and is missing is a broken setup: a mistyped path must not switch checking off.
157
+ if (error?.code === 'ENOENT' && explicit === undefined) {
156
158
  if (ctx.hasUI)
157
159
  ctx.ui.notify(`mago-ski: no policy at ${policyPath}; Skills are not being checked`, 'warning');
158
160
  return;
@@ -288,7 +290,7 @@ export function createMagoSkiExtension(options = {}) {
288
290
  * a line is kept only if it names something that exists under `root` and is not in an unverified
289
291
  * Skill. Returns null when nothing had to be removed.
290
292
  */
291
- async function filterListing(text, root, unverified) {
293
+ async function filterListing(text, root, unverified, hit) {
292
294
  const notice = /\n\n(\[(?:\d+ (?:results|entries) limit reached(?:\. Use limit=\d+ for more(?:, or refine pattern)?)?|[\d.]+KB limit reached)(?:\. [\d.]+KB limit reached)?\])$/u.exec(text);
293
295
  const body = notice ? text.slice(0, notice.index) : text;
294
296
  if (body === '(empty directory)' || body === 'No files found matching pattern')
@@ -302,7 +304,11 @@ export function createMagoSkiExtension(options = {}) {
302
304
  try {
303
305
  await lstat(abs);
304
306
  const real = await canonical(abs);
305
- inSkill = unverified.some((entry) => dirsOf(entry).some((dir) => isInside(dir, abs) || isInside(dir, real)));
307
+ for (const entry of unverified)
308
+ if (dirsOf(entry).some((dir) => isInside(dir, abs) || isInside(dir, real))) {
309
+ inSkill = true;
310
+ hit.add(entry);
311
+ }
306
312
  }
307
313
  catch {
308
314
  inSkill = true; // not a real path (part of a name with a newline) or unreadable: do not pass it on
@@ -326,13 +332,22 @@ export function createMagoSkiExtension(options = {}) {
326
332
  await log(recordFor(entry, event, verdict, reason), false);
327
333
  return enforcing() ? { block: true, reason: `mago-ski: Skill "${entry.name}" ${verdict}: ${reason}` } : undefined;
328
334
  }
329
- async function checkShell(toolName, command) {
335
+ /** The spellings of Skill directories a command could use: absolute, `~/...`, and relative to the working directory. */
336
+ function shellForms(dirs, cwd) {
337
+ const forms = new Set(dirs);
338
+ for (const dir of [...forms]) {
339
+ if (dir.startsWith(homedir()))
340
+ forms.add(`~${dir.slice(homedir().length)}`);
341
+ const relative = path.relative(cwd, dir);
342
+ if (relative !== '' && !path.isAbsolute(relative))
343
+ forms.add(relative);
344
+ }
345
+ return forms;
346
+ }
347
+ async function checkShell(toolName, command, cwd) {
330
348
  // Best-effort: shell commands can reach files in ways a string match cannot see.
331
349
  for (const entry of [...entries]) {
332
- const forms = new Set([...dirsOf(entry), entry.baseDir]);
333
- for (const dir of [...forms])
334
- if (dir.startsWith(homedir()))
335
- forms.add(`~${dir.slice(homedir().length)}`);
350
+ const forms = shellForms([...dirsOf(entry), entry.baseDir], cwd);
336
351
  if (![...forms].some((form) => command.includes(form)))
337
352
  continue;
338
353
  const current = entry.result.verdict === 'VERIFIED' ? await reverify(entry) : entry;
@@ -399,7 +414,7 @@ export function createMagoSkiExtension(options = {}) {
399
414
  const unverified = inside.find((entry) => entry.result.verdict !== 'VERIFIED');
400
415
  if (unverified)
401
416
  return await judge(unverified, `tool:${toolName}`, unverified.result.verdict, unverified.result.reason);
402
- const entry = inside[0];
417
+ let entry = inside[0];
403
418
  if (!entry)
404
419
  return undefined;
405
420
  if (toolName === 'edit' || toolName === 'write') {
@@ -407,6 +422,11 @@ export function createMagoSkiExtension(options = {}) {
407
422
  }
408
423
  if (toolName !== 'read')
409
424
  return undefined; // find and ls show names, not contents
425
+ // Like the shell, grep and /skill: paths: the whole Skill and its trust are checked again, so a revocation, an expiry
426
+ // or a change to another file of the Skill since the run started also stops a read.
427
+ entry = await reverify(entry);
428
+ if (entry.result.verdict !== 'VERIFIED')
429
+ return await judge(entry, 'tool:read', entry.result.verdict, entry.result.reason);
410
430
  const opened = piReadTarget(piPath);
411
431
  const resolved = await canonical(opened).catch(() => opened);
412
432
  if (!isInside(entry.realDir, resolved)) {
@@ -432,10 +452,7 @@ export function createMagoSkiExtension(options = {}) {
432
452
  const reason = 'mago-ski: Skill verification failed earlier in this run; Skill files are blocked until it succeeds';
433
453
  if (SHELL_TOOLS.has(toolName)) {
434
454
  const command = String(input.command ?? '');
435
- const forms = new Set(knownDirs);
436
- for (const dir of knownDirs)
437
- if (dir.startsWith(homedir()))
438
- forms.add(`~${dir.slice(homedir().length)}`);
455
+ const forms = shellForms(knownDirs, cwd);
439
456
  return [...forms].some((form) => command.includes(form)) ? { block: true, reason } : undefined;
440
457
  }
441
458
  const rawPath = typeof input.path === 'string' && input.path !== '' ? input.path : '.';
@@ -465,7 +482,7 @@ export function createMagoSkiExtension(options = {}) {
465
482
  // Pi lists each Skill's path to the model; a verified Skill whose path is not plainly spelled stays out of the list.
466
483
  const unsafe = new Set();
467
484
  for (const entry of checked) {
468
- const problem = promptPathProblem(entry.filePath, [ctx.cwd, homedir()]);
485
+ const problem = promptPathProblem(entry.filePath, [ctx.cwd, homedir()]) ?? promptPathProblem(entry.baseDir, [ctx.cwd, homedir()]);
469
486
  if (!problem || entry.result.verdict !== 'VERIFIED')
470
487
  continue;
471
488
  unsafe.add(entry.lexDir);
@@ -543,16 +560,19 @@ export function createMagoSkiExtension(options = {}) {
543
560
  const input = event.input;
544
561
  const rawPath = typeof input.path === 'string' && input.path !== '' ? input.path : '.';
545
562
  const { targets, piPath } = await toolTargets(event.toolName, rawPath, ctx.cwd);
546
- const unverified = contained(targets).filter((entry) => entry.result.verdict !== 'VERIFIED');
563
+ // Every unverified Skill, not only those below the searched directory: a link inside it can lead to one elsewhere.
564
+ const unverified = entries.filter((entry) => entry.result.verdict !== 'VERIFIED');
547
565
  if (unverified.length === 0)
548
566
  return undefined;
567
+ const hit = new Set();
568
+ const below = new Set(contained(targets));
549
569
  const content = [...event.content];
550
570
  let list;
551
571
  let removed = 0;
552
572
  for (const [index, item] of content.entries()) {
553
573
  if (item.type !== 'text')
554
574
  continue;
555
- const filtered = await filterListing(item.text, piPath, unverified);
575
+ const filtered = await filterListing(item.text, piPath, unverified, hit);
556
576
  if (!filtered)
557
577
  continue;
558
578
  content[index] = { ...item, text: filtered.text };
@@ -561,8 +581,10 @@ export function createMagoSkiExtension(options = {}) {
561
581
  }
562
582
  if (removed === 0)
563
583
  return undefined;
584
+ // Lines hidden for another reason (not a real path) are attributed to the unverified Skills below the searched directory.
564
585
  for (const entry of unverified)
565
- await judge(entry, `tool:${event.toolName}`, entry.result.verdict, entry.result.reason);
586
+ if (hit.has(entry) || (hit.size === 0 && below.has(entry)))
587
+ await judge(entry, `tool:${event.toolName}`, entry.result.verdict, entry.result.reason);
566
588
  if (!enforcing())
567
589
  return undefined;
568
590
  // The truncation record in `details` carries the unfiltered text too.
@@ -584,7 +606,7 @@ export function createMagoSkiExtension(options = {}) {
584
606
  if (entries.length === 0)
585
607
  return undefined;
586
608
  if (SHELL_TOOLS.has(toolName))
587
- return await checkShell(toolName, typeof input.command === 'string' ? input.command : '');
609
+ return await checkShell(toolName, typeof input.command === 'string' ? input.command : '', ctx.cwd);
588
610
  const rawPath = typeof input.path === 'string' && input.path !== '' ? input.path : '.';
589
611
  return await checkFileTool(toolName, rawPath, ctx.cwd);
590
612
  });
@@ -205,5 +205,6 @@ export declare function approveSkill(options: {
205
205
  skillName: string;
206
206
  digest: string;
207
207
  certificateId: string;
208
- expiresAt: Date;
208
+ expiresAt: Date; /** Paths a `.skilldigestignore` keeps out of the digest: this approval does not cover them. */
209
+ notCovered: string[];
209
210
  }>;
package/dist/src/admin.js CHANGED
@@ -8,7 +8,7 @@ import { validateDigest, validateScope } from "./names.js";
8
8
  import { isDisplaySafeText } from "./root-events.js";
9
9
  import { readRevocationsForUpdate, signRevocations } from "./revocations.js";
10
10
  import { addDuration, truncateToSecond } from "./time.js";
11
- import { CERTIFICATE_FILENAME, collectSkillTree, sha256Hex, requireSkillRoot, SKILL_FILENAME } from "./tree-digest.js";
11
+ import { CERTIFICATE_FILENAME, collectSkillTree, pathsNotCovered, sha256Hex, requireSkillRoot, SKILL_FILENAME } from "./tree-digest.js";
12
12
  import { MAX_APPROVERS, MAX_SCOPES, readTrustRootForUpdate, signTrustRoot } from "./trust-root.js";
13
13
  import { skillNameFromSkillFile } from "./verify.js";
14
14
  export const DEFAULT_TRUST_ROOT_EXPIRY = '365d';
@@ -368,13 +368,14 @@ export async function approveSkill(options) {
368
368
  await options.beforeSign?.({ skillName, digest: tree.digest });
369
369
  const targetPath = options.out
370
370
  ?? (options.outDir === undefined ? path.join(tree.root, CERTIFICATE_FILENAME) : path.join(options.outDir, `${skillName}.cert.json`));
371
+ const parsed = parseCertificate(bytes); // before the write: a certificate that cannot be read back is never left on disk
371
372
  const written = await writeFileAtomic(targetPath, bytes);
372
- const parsed = parseCertificate(bytes);
373
373
  return {
374
374
  path: written,
375
375
  skillName,
376
376
  digest: tree.digest,
377
377
  certificateId: parsed.id,
378
378
  expiresAt,
379
+ notCovered: pathsNotCovered(tree.excluded),
379
380
  };
380
381
  }
@@ -5,6 +5,12 @@ export type JsonValue = null | boolean | number | string | JsonValue[] | {
5
5
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
6
6
  export declare function serializeCanonicalJson(value: unknown): string;
7
7
  export declare function canonicalBytes(value: unknown): Buffer;
8
+ /**
9
+ * canonicalBytes for a document that will be read back with parseCanonicalJsonBytes: refuses bytes the reader would refuse
10
+ * for size. A signed document must not be written when no verifier can load it (a revocation list that grew too large
11
+ * would otherwise replace a working one and block every host).
12
+ */
13
+ export declare function readableCanonicalBytes(value: unknown, label: string): Buffer;
8
14
  export declare function parseCanonicalJsonBytes(input: Uint8Array, label?: string): unknown;
9
15
  export declare function exactKeys(value: unknown, keys: readonly string[], label: string): Record<string, unknown>;
10
16
  export declare function requireString(value: unknown, label: string, maxLength?: number): string;
@@ -65,6 +65,17 @@ export function serializeCanonicalJson(value) {
65
65
  export function canonicalBytes(value) {
66
66
  return Buffer.from(serializeCanonicalJson(value), 'utf8');
67
67
  }
68
+ /**
69
+ * canonicalBytes for a document that will be read back with parseCanonicalJsonBytes: refuses bytes the reader would refuse
70
+ * for size. A signed document must not be written when no verifier can load it (a revocation list that grew too large
71
+ * would otherwise replace a working one and block every host).
72
+ */
73
+ export function readableCanonicalBytes(value, label) {
74
+ const bytes = canonicalBytes(value);
75
+ if (bytes.byteLength > MAX_CANONICAL_JSON_BYTES)
76
+ throw new Error(`${label} would be ${bytes.byteLength} bytes; the limit for a document is ${MAX_CANONICAL_JSON_BYTES} bytes. Nothing was written`);
77
+ return bytes;
78
+ }
68
79
  export function parseCanonicalJsonBytes(input, label = 'JSON document') {
69
80
  let text;
70
81
  let value;
package/dist/src/cli.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import type { AskAdmin } from './gate/admin-client.ts';
3
3
  import type { DoctorOptions, InitOptions } from './gate/setup.ts';
4
+ /** Text from a Skill or its folder, for one terminal line: control, line-separator and bidirectional characters are escaped. */
5
+ export declare function terminalSafe(value: string): string;
4
6
  export interface GateCliSeams extends Pick<InitOptions, 'base' | 'rootUid' | 'platform' | 'installRoot' | 'nodePath' | 'envPath' | 'checkExec' | 'resolveHostExe' | 'chattr' | 'isImmutable'> {
5
7
  /** The calling uid (default process.getuid()). */
6
8
  uid?: number;
package/dist/src/cli.js CHANGED
@@ -11,7 +11,7 @@ import { appendDecision, decisionRecord, defaultPolicyPath, effectiveMode, findS
11
11
  import { adoptTrustDocuments, appendRootEvent, buildRecoverySet, currentRootState, describeRootEvent, initRootEventLog, prepareRootEvent, recoverySetJson, showRootEvent, signPolicyTimestamp, signRootEvent, } from "./recovery-admin.js";
12
12
  import { isMainModule } from "./main-module.js";
13
13
  import { formatTimestamp } from "./time.js";
14
- import { collectSkillTree, TREE_PROFILE } from "./tree-digest.js";
14
+ import { collectSkillTree, pathsNotCovered, TREE_PROFILE } from "./tree-digest.js";
15
15
  import { verifyTrustRoot } from "./trust-root.js";
16
16
  import { resolveSkillName, unverifiable } from "./verify.js";
17
17
  import { createRequire } from 'node:module';
@@ -546,7 +546,23 @@ function printResult(result, json) {
546
546
  return;
547
547
  }
548
548
  const mark = result.verdict === 'VERIFIED' ? 'ok' : 'FAIL';
549
- process.stdout.write(`${mark.padEnd(4)} ${result.verdict.padEnd(17)} ${result.skillName} ${result.reason}\n`);
549
+ // A VERIFIED line must not read as "everything in this folder is approved" when the Skill excludes files from its digest.
550
+ const notCovered = result.verdict === 'VERIFIED' ? pathsNotCovered(result.excluded) : [];
551
+ const note = notCovered.length > 0 ? ` (${notCovered.length} path${notCovered.length === 1 ? '' : 's'} not covered by the certificate: ${shownPaths(notCovered)})` : '';
552
+ // The name can be a folder's name when SKILL.md could not be read, and a reason can quote paths: neither may carry a
553
+ // line break or a terminal escape that would draw a second, made-up result line.
554
+ process.stdout.write(`${mark.padEnd(4)} ${result.verdict.padEnd(17)} ${terminalSafe(result.skillName)} ${terminalSafe(result.reason)}${note}\n`);
555
+ }
556
+ /** Text from a Skill or its folder, for one terminal line: control, line-separator and bidirectional characters are escaped. */
557
+ export function terminalSafe(value) {
558
+ return value.replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u2028-\u202e\u2066-\u2069]/gu, (c) => `\\u${c.codePointAt(0).toString(16).padStart(4, '0')}`);
559
+ }
560
+ /** Up to three paths, escaped for the terminal (the names come from the Skill). */
561
+ function shownPaths(paths) {
562
+ return `${paths.slice(0, 3).map(terminalSafe).join(', ')}${paths.length > 3 ? ', ...' : ''}`;
563
+ }
564
+ function notCoveredNote(paths) {
565
+ return `${paths.length} path${paths.length === 1 ? ' is' : 's are'} excluded from the digest by .skilldigestignore (${shownPaths(paths)}).`;
550
566
  }
551
567
  /* ****************************************************************************************** */
552
568
  async function runRoot(sub, parsed, now) {
@@ -855,7 +871,12 @@ async function runPolicyCheck(sub, parsed, now) {
855
871
  report.verdict = trust.verdict;
856
872
  report.reason = trust.reason;
857
873
  }
874
+ // Without a state file a host remembers nothing between runs, so an older, still valid trust root, revocation list,
875
+ // root event log or timestamp is accepted again. The policy loads, so this is said here, where a setup is checked.
876
+ report.rollback_protection = policy.statePath !== null;
858
877
  print(report);
878
+ if (policy.statePath === null)
879
+ process.stderr.write('warning: the policy has no state_file, so this host does not remember the versions it has seen: an older, still valid trust root or revocation list would be accepted again. Add "state_file" to the policy.\n');
859
880
  return trust.ok ? 0 : 1;
860
881
  }
861
882
  async function runVerify(parsed, now) {
@@ -1253,8 +1274,11 @@ export async function runCli(argv = process.argv.slice(2), now = new Date(), gat
1253
1274
  digest: result.digest,
1254
1275
  certificate_id: result.certificateId,
1255
1276
  expires_at: formatTimestamp(result.expiresAt),
1256
- certificate: result.path
1277
+ certificate: result.path,
1278
+ ...(result.notCovered.length > 0 ? { not_covered: result.notCovered } : {}),
1257
1279
  });
1280
+ if (result.notCovered.length > 0)
1281
+ process.stderr.write(`warning: ${notCoveredNote(result.notCovered)} This approval does not cover them: they can change without invalidating it.\n`);
1258
1282
  return 0;
1259
1283
  }
1260
1284
  case 'verify':
@@ -1276,6 +1300,9 @@ export async function runCli(argv = process.argv.slice(2), now = new Date(), gat
1276
1300
  allow(parsed, ['--base', '--candidate'], 0);
1277
1301
  const result = await diffSkillTrees(one(parsed, '--base'), one(parsed, '--candidate'));
1278
1302
  print(result);
1303
+ const skipped = [...new Set([...result.not_compared.base, ...result.not_compared.candidate])];
1304
+ if (skipped.length > 0)
1305
+ process.stderr.write(`warning: ${notCoveredNote(skipped)} They were not compared.\n`);
1279
1306
  return result.recertification_required ? 1 : 0;
1280
1307
  }
1281
1308
  case 'inspect': {
@@ -22,5 +22,10 @@ export interface DiffResult {
22
22
  };
23
23
  diff_truncated: boolean;
24
24
  files: FileChange[];
25
+ /** Paths each side's `.skilldigestignore` keeps out of the digest. They are not compared: UNCHANGED says nothing about them. */
26
+ not_compared: {
27
+ base: string[];
28
+ candidate: string[];
29
+ };
25
30
  }
26
31
  export declare function diffSkillTrees(baseRoot: string, candidateRoot: string): Promise<DiffResult>;
package/dist/src/diff.js CHANGED
@@ -1,4 +1,4 @@
1
- import { collectSkillTree, compareTreePaths, sha256Hex } from "./tree-digest.js";
1
+ import { collectSkillTree, compareTreePaths, pathsNotCovered, sha256Hex } from "./tree-digest.js";
2
2
  const textDecoder = new TextDecoder('utf-8', { fatal: true });
3
3
  const MAX_ANALYZED_TEXT_BYTES = 2 * 1024 * 1024;
4
4
  /** Before + after bytes, summed over every file: per-file limits alone allow ~500 MiB of parsing. */
@@ -400,5 +400,6 @@ export async function diffSkillTrees(baseRoot, candidateRoot) {
400
400
  },
401
401
  diff_truncated: diff.truncated,
402
402
  files: diff.files,
403
+ not_compared: { base: pathsNotCovered(base.excluded), candidate: pathsNotCovered(candidate.excluded) },
403
404
  };
404
405
  }
package/dist/src/dsse.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // DSSE (Dead Simple Signing Envelope) v1 with exactly one Ed25519 signature.
2
2
  // https://github.com/secure-systems-lab/dsse/blob/master/protocol.md
3
3
  import { sign, verify } from 'node:crypto';
4
- import { canonicalBytes, exactKeys, parseCanonicalJsonBytes, requireArray, requireString } from "./canonical-json.js";
4
+ import { exactKeys, parseCanonicalJsonBytes, readableCanonicalBytes, requireArray, requireString } from "./canonical-json.js";
5
5
  import { validateKeyId } from "./keys.js";
6
6
  const BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;
7
7
  /** Pre-Authentication Encoding: "DSSEv1" SP LEN(type) SP type SP LEN(body) SP body, lengths in bytes. */
@@ -26,7 +26,7 @@ export function signEnvelope(payloadType, payload, keyId, privateKey) {
26
26
  };
27
27
  }
28
28
  export function envelopeBytes(envelope) {
29
- return canonicalBytes(envelope);
29
+ return readableCanonicalBytes(envelope, 'The signed document');
30
30
  }
31
31
  function decodeBase64(value, label, maxLength) {
32
32
  if (typeof value !== 'string' || value.length === 0 || value.length > maxLength || !BASE64_PATTERN.test(value)) {
@@ -4,6 +4,12 @@ export declare class CosignVerificationError extends Error {
4
4
  readonly exitCode = 1;
5
5
  constructor(message?: string);
6
6
  }
7
+ /**
8
+ * The environment for a verification: without the variables cosign and its libraries read as configuration
9
+ * (COSIGN_*, SIGSTORE_*, TUF_*), which can replace the trust material or relax checks. Signing keeps them: it needs the
10
+ * caller's identity token.
11
+ */
12
+ export declare function verificationEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
7
13
  export declare function assertPinnedCosignBinary(binaryPath: string): Promise<string>;
8
14
  export declare function buildCosignSignArgs(bundlePath: string, payloadPath: string): string[];
9
15
  export declare function buildCosignVerifyArgs(bundlePath: string, trustedRootPath: string, identity: string, issuer: string, payloadPath: string): string[];
@@ -66,10 +66,18 @@ async function hashFile(filePath) {
66
66
  await handle.close();
67
67
  }
68
68
  }
69
- async function runProcess(binaryPath, args, timeout) {
69
+ /**
70
+ * The environment for a verification: without the variables cosign and its libraries read as configuration
71
+ * (COSIGN_*, SIGSTORE_*, TUF_*), which can replace the trust material or relax checks. Signing keeps them: it needs the
72
+ * caller's identity token.
73
+ */
74
+ export function verificationEnv(env) {
75
+ return Object.fromEntries(Object.entries(env).filter(([name]) => !/^(COSIGN|SIGSTORE|TUF)_/iu.test(name)));
76
+ }
77
+ async function runProcess(binaryPath, args, timeout, env = process.env) {
70
78
  try {
71
79
  const { stdout, stderr } = await execFileAsync(binaryPath, args, {
72
- timeout, maxBuffer: 1024 * 1024, windowsHide: true, encoding: 'utf8', shell: false, env: process.env,
80
+ timeout, maxBuffer: 1024 * 1024, windowsHide: true, encoding: 'utf8', shell: false, env,
73
81
  });
74
82
  return { stdout, stderr };
75
83
  }
@@ -114,9 +122,9 @@ export function buildCosignVerifyArgs(bundlePath, trustedRootPath, identity, iss
114
122
  '--certificate-identity', identity, '--certificate-oidc-issuer', issuer, payloadPath,
115
123
  ];
116
124
  }
117
- async function runCosign(binaryPath, args, timeout) {
125
+ async function runCosign(binaryPath, args, timeout, env) {
118
126
  const canonical = await assertPinnedCosignBinary(binaryPath);
119
- await runProcess(canonical, args, timeout);
127
+ await runProcess(canonical, args, timeout, env);
120
128
  if (await hashFile(canonical) !== COSIGN_BINARY_SHA256[platformKey()]) {
121
129
  throw new CosignVerificationError('Pinned Cosign binary changed during the operation');
122
130
  }
@@ -148,6 +156,6 @@ export async function verifySigstoreBlob(options) {
148
156
  throw new Error('A configured Sigstore certificate identity is required');
149
157
  if (!options.certificateOidcIssuer)
150
158
  throw new Error('A configured Sigstore OIDC issuer is required');
151
- await runCosign(options.binaryPath, buildCosignVerifyArgs(bundle, trustedRoot, options.certificateIdentity, options.certificateOidcIssuer, payload), 60_000);
159
+ await runCosign(options.binaryPath, buildCosignVerifyArgs(bundle, trustedRoot, options.certificateIdentity, options.certificateOidcIssuer, payload), 60_000, verificationEnv(process.env));
152
160
  return { valid: true };
153
161
  }
@@ -47,6 +47,7 @@ export async function loadConfig(file, rootUid = 0, extraKeys = []) {
47
47
  const st = await lstat(file);
48
48
  if (!st.isFile() || (st.mode & 0o022) !== 0 || st.uid !== rootUid)
49
49
  throw new Error('config must be a regular, root-owned, non-writable file');
50
+ // nosemgrep: mago-no-raw-read-of-signed-input -- the hook config, checked just above as a root-owned regular file that only root can write
50
51
  const raw = parseStrictJson(await readFile(file));
51
52
  if (!isRecord(raw))
52
53
  throw new Error('config must be an object');
@@ -305,6 +305,7 @@ async function dotenvMayMoveHome(codexHome) {
305
305
  const st = await lstat(file);
306
306
  if (!st.isFile() || st.size > MAX_ENVIRON_BYTES)
307
307
  return true; // symlink, FIFO, directory, huge: not inspected
308
+ // nosemgrep: mago-no-raw-read-of-signed-input -- /proc/<pid>/environ of the host process, size checked above; only searched for HOME
308
309
  return (await readFile(file)).includes('HOME');
309
310
  }
310
311
  catch (e) {
@@ -494,7 +495,9 @@ function inspectCommand(raw, cfg) {
494
495
  // Any mention of a user/repo Skill location in any spelling (~, $HOME, relative), or of a SKILL.md file other than an
495
496
  // admin Skill's own `<admin_root>/<name>/SKILL.md`.
496
497
  const start = '(?<=^|[\\s\'"`=;|&()<>])'; // the admin path must start a word: `<other>/<admin>/x/SKILL.md` is not admin
497
- const outsideAdmin = command.replace(new RegExp(`${start}${esc}/[A-Za-z0-9][A-Za-z0-9._-]*/SKILL\\.md`, 'giu'), '');
498
+ // Case-sensitive, like the admin-name match below: a spelling such as `<admin_root>` in another case is a different path.
499
+ // It must not be removed here (it would then be neither rogue nor checked by the gate).
500
+ const outsideAdmin = command.replace(new RegExp(`${start}${esc}/[A-Za-z0-9][A-Za-z0-9._-]*/SKILL\\.md`, 'gu'), '');
498
501
  const rogue = /\.(agents|codex)(?![A-Za-z0-9_-])/u.test(command) || /skill\.md/iu.test(outsideAdmin)
499
502
  || cfg.skillRoots.some((r) => command.includes(collapse(r)));
500
503
  const admin = new Set();
@@ -437,10 +437,12 @@ export async function readGeneration(generationsRoot, name, digest) {
437
437
  async function seal(dir, files) {
438
438
  const dirs = new Set(['']);
439
439
  for (const f of files) {
440
+ // nosemgrep: mago-no-path-chown-chmod -- sealing a generation inside the service's root-owned generation store; no user can write there
440
441
  await chmod(path.join(dir, f.path), f.exec ? 0o555 : 0o444);
441
442
  for (let d = path.posix.dirname(f.path); d !== '.'; d = path.posix.dirname(d))
442
443
  dirs.add(d);
443
444
  }
445
+ // nosemgrep: mago-no-path-chown-chmod -- sealing a generation inside the service's root-owned generation store; no user can write there
444
446
  for (const d of [...dirs].sort((a, b) => b.length - a.length))
445
447
  await chmod(path.join(dir, d), 0o555);
446
448
  }
@@ -83,6 +83,7 @@ export async function readInstanceConfig(file, rootUid = 0) {
83
83
  throw new Error(`${file} must be a regular file`);
84
84
  if (info.uid !== rootUid || (info.mode & 0o022) !== 0)
85
85
  throw new Error(`${file} must be owned by root and not writable by group or others`);
86
+ // nosemgrep: mago-no-raw-read-of-signed-input -- the instance config, checked just above as root-owned and not writable by others
86
87
  return parseInstanceConfig(parseStrictJson(await readFile(file)));
87
88
  }
88
89
  /** The service's own config for an instance. */
@@ -14,6 +14,12 @@ export declare function assertGatePlatform(platform?: NodeJS.Platform): void;
14
14
  export declare function bootId(): Promise<string>;
15
15
  /** Milliseconds since boot (CLOCK_BOOTTIME, so suspend counts and wall-clock steps do not matter). */
16
16
  export declare function bootMs(): Promise<number>;
17
+ /**
18
+ * The first field of /proc/uptime (`seconds.hundredths`) in milliseconds, with integer arithmetic. `Number("2.01") * 1000`
19
+ * is 2009.9999999999998, which floors to 2009: one millisecond before the same instant as processFacts computes it from
20
+ * clock ticks. A host that asked in the tick it started in was then refused as "started in the future".
21
+ */
22
+ export declare function parseUptimeMs(text: string): number;
17
23
  /**
18
24
  * Start time and uid of a PROCESS (a thread-group leader), without its exe. Throws if gone, unreadable, a thread id
19
25
  * (a thread starts later than its process, which would shorten a session's generation set) or a process of a nested
@@ -23,10 +23,21 @@ export async function bootId() {
23
23
  }
24
24
  /** Milliseconds since boot (CLOCK_BOOTTIME, so suspend counts and wall-clock steps do not matter). */
25
25
  export async function bootMs() {
26
- const first = (await readFile('/proc/uptime', 'utf8')).split(' ')[0] ?? '';
27
- if (!/^\d+\.\d+$/u.test(first))
26
+ return parseUptimeMs(await readFile('/proc/uptime', 'utf8'));
27
+ }
28
+ /**
29
+ * The first field of /proc/uptime (`seconds.hundredths`) in milliseconds, with integer arithmetic. `Number("2.01") * 1000`
30
+ * is 2009.9999999999998, which floors to 2009: one millisecond before the same instant as processFacts computes it from
31
+ * clock ticks. A host that asked in the tick it started in was then refused as "started in the future".
32
+ */
33
+ export function parseUptimeMs(text) {
34
+ const m = /^(\d+)\.(\d+)$/u.exec(text.split(' ')[0] ?? '');
35
+ if (!m)
36
+ throw new Error('unexpected /proc/uptime format');
37
+ const ms = Number(m[1]) * 1000 + Number(m[2].padEnd(3, '0').slice(0, 3));
38
+ if (!Number.isSafeInteger(ms))
28
39
  throw new Error('unexpected /proc/uptime format');
29
- return Math.floor(Number(first) * 1000);
40
+ return ms;
30
41
  }
31
42
  /**
32
43
  * Start time and uid of a PROCESS (a thread-group leader), without its exe. Throws if gone, unreadable, a thread id