@mago-foundation/mago-ski 0.4.0 → 0.5.0-beta.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.
Files changed (59) hide show
  1. package/README.md +5 -3
  2. package/action.yml +21 -2
  3. package/dist/hosts/github/check.d.ts +21 -0
  4. package/dist/hosts/github/check.js +124 -0
  5. package/dist/hosts/github/publish.d.ts +7 -0
  6. package/dist/hosts/github/publish.js +52 -0
  7. package/dist/hosts/github/run.d.ts +12 -0
  8. package/dist/hosts/github/run.js +32 -18
  9. package/dist/hosts/pi/index.js +40 -18
  10. package/dist/src/admin.d.ts +2 -1
  11. package/dist/src/admin.js +3 -2
  12. package/dist/src/admission-evidence.d.ts +15 -0
  13. package/dist/src/admission-evidence.js +48 -0
  14. package/dist/src/admission.d.ts +102 -0
  15. package/dist/src/admission.js +316 -0
  16. package/dist/src/canonical-json.d.ts +6 -0
  17. package/dist/src/canonical-json.js +11 -0
  18. package/dist/src/cli.d.ts +2 -0
  19. package/dist/src/cli.js +229 -5
  20. package/dist/src/diff.d.ts +9 -0
  21. package/dist/src/diff.js +3 -2
  22. package/dist/src/dsse.js +2 -2
  23. package/dist/src/experimental/sigstore.d.ts +30 -0
  24. package/dist/src/experimental/sigstore.js +35 -5
  25. package/dist/src/fs-safe.d.ts +15 -2
  26. package/dist/src/fs-safe.js +68 -50
  27. package/dist/src/gate/adapters/claude-code.js +8 -5
  28. package/dist/src/gate/adapters/codex.js +5 -6
  29. package/dist/src/gate/generations.js +2 -0
  30. package/dist/src/gate/instance.js +7 -7
  31. package/dist/src/gate/proc.d.ts +6 -0
  32. package/dist/src/gate/proc.js +14 -3
  33. package/dist/src/gate/service.js +3 -0
  34. package/dist/src/gate/setup.d.ts +5 -5
  35. package/dist/src/gate/setup.js +128 -88
  36. package/dist/src/policy.d.ts +7 -0
  37. package/dist/src/policy.js +19 -2
  38. package/dist/src/profile.d.ts +34 -0
  39. package/dist/src/profile.js +182 -0
  40. package/dist/src/published-by.d.ts +64 -0
  41. package/dist/src/published-by.js +227 -0
  42. package/dist/src/recovery-admin.js +7 -4
  43. package/dist/src/root-events.d.ts +2 -0
  44. package/dist/src/root-events.js +61 -4
  45. package/dist/src/tree-digest.d.ts +6 -0
  46. package/dist/src/tree-digest.js +8 -0
  47. package/dist/src/usf-check.d.ts +28 -0
  48. package/dist/src/usf-check.js +128 -0
  49. package/dist/src/usf.d.ts +48 -0
  50. package/dist/src/usf.js +238 -0
  51. package/docs/hosts/publish.md +65 -0
  52. package/docs/hosts/skill-check.md +91 -0
  53. package/docs/spec/admission-v0.md +84 -0
  54. package/docs/spec/gui-admin-rack-v1.md +1 -1
  55. package/docs/spec/observed-profile-v1.md +51 -0
  56. package/docs/spec/root-recovery-v1.md +3 -2
  57. package/docs/spec/trust-documents-v1.md +1 -1
  58. package/docs/threat-model.md +12 -0
  59. package/package.json +5 -1
package/dist/src/cli.js CHANGED
@@ -5,13 +5,18 @@ import { fileURLToPath } from 'node:url';
5
5
  import { addApprover, approveSkill, initRoot, removeApprover, renewTrustRoot, updateRevocations } from "./admin.js";
6
6
  import { parseCertificate } from "./certificate.js";
7
7
  import { diffSkillTrees } from "./diff.js";
8
+ import { checkSkill } from "./usf-check.js";
9
+ import { verifyPublishedBy } from "./published-by.js";
10
+ import { AdmissionRulesError, evaluate, parseRules, replay } from "./admission.js";
11
+ import { collectSkillFacts } from "./admission-evidence.js";
12
+ import { appendFile } from 'node:fs/promises';
8
13
  import { readRegularFile } from "./fs-safe.js";
9
14
  import { generateKeyPair, validateKeyId } from "./keys.js";
10
15
  import { appendDecision, decisionRecord, defaultPolicyPath, effectiveMode, findSkillDirs, forbiddenApproverKeys, loadPolicy, loadPolicyTrust, tooDeepResult, trustFailureEvent, trustFailureRecord, verifyWithPolicy, } from "./policy.js";
11
16
  import { adoptTrustDocuments, appendRootEvent, buildRecoverySet, currentRootState, describeRootEvent, initRootEventLog, prepareRootEvent, recoverySetJson, showRootEvent, signPolicyTimestamp, signRootEvent, } from "./recovery-admin.js";
12
17
  import { isMainModule } from "./main-module.js";
13
18
  import { formatTimestamp } from "./time.js";
14
- import { collectSkillTree, TREE_PROFILE } from "./tree-digest.js";
19
+ import { collectSkillTree, pathsNotCovered, TREE_PROFILE } from "./tree-digest.js";
15
20
  import { verifyTrustRoot } from "./trust-root.js";
16
21
  import { resolveSkillName, unverifiable } from "./verify.js";
17
22
  import { createRequire } from 'node:module';
@@ -46,6 +51,14 @@ CHECKING SKILLS
46
51
  verify SKILL_DIR Check one Skill, print its verdict
47
52
  verify-all Check every Skill in the policy
48
53
  digest SKILL_DIR Print a Skill's tree digest
54
+ check SKILL_DIR Show what a Skill's files contain and check its USF declaration
55
+ attestation verify SKILL_DIR
56
+ Check a publisher's published-by attestation for a Skill's exact bytes
57
+
58
+ ADMISSION RULES (organisation; preview: hosts do not enforce them yet)
59
+ admit SKILL_DIR Decide whether a Skill is admitted under a rule file
60
+ admission check RULES Check a rule file
61
+ admission diff OLD NEW Show which logged decisions a new rule file would change
49
62
  diff Compare two versions of a Skill
50
63
  inspect CERTIFICATE Print a certificate's contents
51
64
  policy check Check a policy the way a host does
@@ -324,6 +337,67 @@ Exits 1 if any Skill is not VERIFIED, in shadow mode too (shadow mode affects ho
324
337
  /* ****************************************************************************************** */
325
338
  /** Per-command: digest */
326
339
  /* ****************************************************************************************** */
340
+ 'attestation verify': `Usage: mago-ski attestation verify SKILL_DIR --bundle FILE --trusted-root FILE --cosign FILE --repo OWNER/NAME
341
+ [--workflow .github/workflows/FILE.yml] [--repo-id ID]
342
+
343
+ Checks a published-by attestation (made by the mago-ski publish Action through actions/attest) for the
344
+ Skill's exact current bytes, offline:
345
+
346
+ - the Sigstore signature, certificate chain and transparency-log proof, against --trusted-root
347
+ (make one with: cosign trusted-root create --with-default-services --out trusted_root.json);
348
+ - that the signer is a GitHub Actions workflow of --repo (and --workflow, when given);
349
+ - that the statement names this Skill's tree digest.
350
+
351
+ It then recomputes the observed profile and the USF declaration from the bytes and reports any difference
352
+ from what the publisher recorded. It prints who published these bytes, from which repository (with its
353
+ numeric id), workflow and commit. It does not say that the Skill is safe.
354
+
355
+ --bundle FILE the Sigstore bundle (the publish Action's bundle-path, or from the GitHub attestations API)
356
+ --trusted-root FILE Sigstore trusted root JSON; nothing is fetched during the check
357
+ --cosign FILE Cosign v3.1.3; its SHA-256 must match the official release checksum
358
+ --repo OWNER/NAME the repository that must have signed (as GitHub spells it)
359
+ --workflow PATH also require this workflow file
360
+ --repo-id ID also require this numeric repository id (survives renames; a fork or a new
361
+ repository with the same name has a different id)
362
+
363
+ Exit 0 when the attestation verifies and the record matches the bytes, 1 when it does not, 2 for usage errors.`,
364
+ admit: `Usage: mago-ski admit SKILL_DIR --rules FILE [--policy FILE] [--published-by BUNDLE]
365
+ [--base DIR [--base-published-by BUNDLE]] [--trusted-root FILE --cosign FILE] [--log FILE]
366
+
367
+ Decides whether the Skill is admitted under an admission rule file (mago.admission/v0). The decision is a
368
+ pure function of the facts, the rules and the time: no model and no network.
369
+
370
+ The facts are computed here: the observed profile and USF declaration from the bytes; a review, when
371
+ --policy names an organisation policy whose trust root has a valid certificate for these exact bytes; the
372
+ publisher, when --published-by holds a published-by bundle that verifies for these bytes (offline, with
373
+ --trusted-root and --cosign). --base names the reviewed version this one updates (its folder), for
374
+ non-escalating update rules.
375
+
376
+ --log FILE append the decision and its facts as one JSON line, for "mago-ski admission diff"
377
+
378
+ Prints the action (ALLOW, LOG_ONLY, FLAG, REQUIRE_REVIEW or BLOCK), the rule that decided it, and what
379
+ evidence is missing. Exit 0 when admitted (ALLOW, LOG_ONLY, FLAG), 1 when not, 2 for usage errors.`,
380
+ 'admission check': `Usage: mago-ski admission check RULES
381
+
382
+ Parses and checks an admission rule file: unknown keys, duplicate rule ids, BLOCK and REQUIRE_REVIEW
383
+ rules without a reason, ALLOW rules built on capability conditions (they can only make a decision
384
+ stricter) and ALLOW rules that would admit every Skill. Prints the rule ids and the file's digest.
385
+ Exit 0 when the file is valid, 1 when it is not.`,
386
+ 'admission diff': `Usage: mago-ski admission diff OLD NEW --against-log FILE
387
+
388
+ Re-evaluates every decision in a log written by "mago-ski admit --log" under both rule files, each at the
389
+ time it was made, and lists the decisions whose action would change. Run it before switching rules.
390
+ Exit 0 when nothing changes, 1 when something would, 2 for usage errors.`,
391
+ check: `Usage: mago-ski check SKILL_DIR [--require-manifest]
392
+
393
+ Prints the Skill's observed profile (mago.observed-profile/v1: websites, scripts and shell code, programs
394
+ named in shell code, files not searched) and, when SKILL.md declares its needs in an OWASP Universal Skill
395
+ Format manifest, whether the declaration covers the profile. The same check as the Skill check Action.
396
+ It states what the files contain; it does not say that a Skill is safe.
397
+
398
+ --require-manifest fail when SKILL.md has no readable USF declaration
399
+
400
+ Exit 0 when the check passes, 1 when it fails, 2 for usage or input errors.`,
327
401
  digest: `Usage: mago-ski digest SKILL_DIR [--explain]
328
402
 
329
403
  Prints the Skill's tree digest (sha256:...). --explain also lists every covered file, its hash and
@@ -458,7 +532,7 @@ function readVersion() {
458
532
  class UsageError extends Error {
459
533
  }
460
534
  /* The actual boolean flags that should take no value. */
461
- const BOOLEAN_FLAGS = new Set(['--json', '--explain', '--help', '--force', '--print', '--no-deny-read', '--lock-user-skill-folders', '--new-root']);
535
+ const BOOLEAN_FLAGS = new Set(['--require-manifest', '--json', '--explain', '--help', '--force', '--print', '--no-deny-read', '--lock-user-skill-folders', '--new-root']);
462
536
  /* Only `gate init` takes these; everywhere else they are refused, as before 0.4.0. */
463
537
  const GATE_INIT_ONLY = new Set(['--force', '--print', '--no-deny-read', '--lock-user-skill-folders', '--new-root']);
464
538
  /* flags Map: A map of flags to their values. */
@@ -546,7 +620,23 @@ function printResult(result, json) {
546
620
  return;
547
621
  }
548
622
  const mark = result.verdict === 'VERIFIED' ? 'ok' : 'FAIL';
549
- process.stdout.write(`${mark.padEnd(4)} ${result.verdict.padEnd(17)} ${result.skillName} ${result.reason}\n`);
623
+ // A VERIFIED line must not read as "everything in this folder is approved" when the Skill excludes files from its digest.
624
+ const notCovered = result.verdict === 'VERIFIED' ? pathsNotCovered(result.excluded) : [];
625
+ const note = notCovered.length > 0 ? ` (${notCovered.length} path${notCovered.length === 1 ? '' : 's'} not covered by the certificate: ${shownPaths(notCovered)})` : '';
626
+ // 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
627
+ // line break or a terminal escape that would draw a second, made-up result line.
628
+ process.stdout.write(`${mark.padEnd(4)} ${result.verdict.padEnd(17)} ${terminalSafe(result.skillName)} ${terminalSafe(result.reason)}${note}\n`);
629
+ }
630
+ /** Text from a Skill or its folder, for one terminal line: control, line-separator and bidirectional characters are escaped. */
631
+ export function terminalSafe(value) {
632
+ return value.replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u2028-\u202e\u2066-\u2069]/gu, (c) => `\\u${c.codePointAt(0).toString(16).padStart(4, '0')}`);
633
+ }
634
+ /** Up to three paths, escaped for the terminal (the names come from the Skill). */
635
+ function shownPaths(paths) {
636
+ return `${paths.slice(0, 3).map(terminalSafe).join(', ')}${paths.length > 3 ? ', ...' : ''}`;
637
+ }
638
+ function notCoveredNote(paths) {
639
+ return `${paths.length} path${paths.length === 1 ? ' is' : 's are'} excluded from the digest by .skilldigestignore (${shownPaths(paths)}).`;
550
640
  }
551
641
  /* ****************************************************************************************** */
552
642
  async function runRoot(sub, parsed, now) {
@@ -688,6 +778,53 @@ async function runRevoke(sub, parsed, now) {
688
778
  });
689
779
  return 0;
690
780
  }
781
+ async function runAdmit(parsed, now) {
782
+ allow(parsed, ['--rules', '--policy', '--published-by', '--base', '--base-published-by', '--trusted-root', '--cosign', '--log'], 1);
783
+ let rules;
784
+ try {
785
+ rules = parseRules((await readRegularFile(one(parsed, '--rules'), 'Rule file', 256 * 1024)).toString('utf8'));
786
+ }
787
+ catch (error) {
788
+ if (error instanceof AdmissionRulesError)
789
+ throw new UsageError(error.message);
790
+ throw error;
791
+ }
792
+ const policyPath = optional(parsed, '--policy');
793
+ const policy = policyPath ? await loadPolicy(policyPath) : undefined;
794
+ const trustedRootPath = optional(parsed, '--trusted-root');
795
+ const cosignPath = optional(parsed, '--cosign');
796
+ if ((trustedRootPath === undefined) !== (cosignPath === undefined))
797
+ throw new UsageError('--trusted-root and --cosign go together');
798
+ const sigstore = trustedRootPath && cosignPath ? { trustedRootPath, cosignPath } : undefined;
799
+ const base = optional(parsed, '--base');
800
+ if (base === undefined && optional(parsed, '--base-published-by') !== undefined)
801
+ throw new UsageError('--base-published-by needs --base');
802
+ const evidence = (bundle) => ({ ...(policy ? { policy } : {}), ...(bundle ? { publishedBy: bundle } : {}) });
803
+ let facts;
804
+ try {
805
+ facts = {
806
+ skill: await collectSkillFacts(parsed.positional[0], evidence(optional(parsed, '--published-by')), sigstore, now),
807
+ base: base === undefined ? null : await collectSkillFacts(base, evidence(optional(parsed, '--base-published-by')), sigstore, now),
808
+ };
809
+ }
810
+ catch (error) {
811
+ if (error instanceof RangeError)
812
+ throw new UsageError(error.message);
813
+ throw error;
814
+ }
815
+ const decision = evaluate(rules, facts, now);
816
+ const logPath = optional(parsed, '--log');
817
+ if (logPath) {
818
+ const record = { decided_at: now.toISOString(), rules_digest: rules.digest, facts, decision };
819
+ await appendFile(logPath, `${JSON.stringify(record)}\n`, { mode: 0o600 });
820
+ }
821
+ print({
822
+ skill: facts.skill.name, digest: facts.skill.digest, ...decision,
823
+ evidence: { reviewed_by: facts.skill.reviewed_by, published_by: facts.skill.published_by, declaration: facts.skill.declaration !== null, base: facts.base?.digest ?? null },
824
+ rules_digest: rules.digest,
825
+ });
826
+ return decision.admitted ? 0 : 1;
827
+ }
691
828
  /** Loads the policy named by --policy, else the host default. The checkout being verified never chooses its own root. */
692
829
  async function loadCliPolicy(parsed) {
693
830
  const explicit = optional(parsed, '--policy');
@@ -855,7 +992,12 @@ async function runPolicyCheck(sub, parsed, now) {
855
992
  report.verdict = trust.verdict;
856
993
  report.reason = trust.reason;
857
994
  }
995
+ // Without a state file a host remembers nothing between runs, so an older, still valid trust root, revocation list,
996
+ // root event log or timestamp is accepted again. The policy loads, so this is said here, where a setup is checked.
997
+ report.rollback_protection = policy.statePath !== null;
858
998
  print(report);
999
+ if (policy.statePath === null)
1000
+ 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
1001
  return trust.ok ? 0 : 1;
860
1002
  }
861
1003
  async function runVerify(parsed, now) {
@@ -1210,7 +1352,7 @@ export async function runCli(argv = process.argv.slice(2), now = new Date(), gat
1210
1352
  process.stdout.write(`${text}\n`);
1211
1353
  return 0;
1212
1354
  }
1213
- const hasSub = ['root', 'revoke', 'recovery', 'root-events', 'timestamp', 'policy', 'gate'].includes(command);
1355
+ const hasSub = ['root', 'revoke', 'recovery', 'root-events', 'timestamp', 'policy', 'gate', 'attestation', 'admission'].includes(command);
1214
1356
  const parsed = parseArgs(argv.slice(hasSub ? 2 : 1));
1215
1357
  switch (command) {
1216
1358
  case 'keygen': {
@@ -1253,8 +1395,11 @@ export async function runCli(argv = process.argv.slice(2), now = new Date(), gat
1253
1395
  digest: result.digest,
1254
1396
  certificate_id: result.certificateId,
1255
1397
  expires_at: formatTimestamp(result.expiresAt),
1256
- certificate: result.path
1398
+ certificate: result.path,
1399
+ ...(result.notCovered.length > 0 ? { not_covered: result.notCovered } : {}),
1257
1400
  });
1401
+ if (result.notCovered.length > 0)
1402
+ process.stderr.write(`warning: ${notCoveredNote(result.notCovered)} This approval does not cover them: they can change without invalidating it.\n`);
1258
1403
  return 0;
1259
1404
  }
1260
1405
  case 'verify':
@@ -1270,12 +1415,91 @@ export async function runCli(argv = process.argv.slice(2), now = new Date(), gat
1270
1415
  process.stdout.write(`${tree.digest}\n`);
1271
1416
  return 0;
1272
1417
  }
1418
+ case 'attestation': {
1419
+ if (maybeSub !== 'verify')
1420
+ throw new UsageError('Usage: mago-ski attestation verify SKILL_DIR --bundle FILE --trusted-root FILE --cosign FILE --repo OWNER/NAME');
1421
+ allow(parsed, ['--bundle', '--trusted-root', '--cosign', '--repo', '--workflow', '--repo-id'], 1);
1422
+ const workflow = parsed.flags.get('--workflow')?.[0];
1423
+ const repositoryId = parsed.flags.get('--repo-id')?.[0];
1424
+ let facts;
1425
+ try {
1426
+ facts = await verifyPublishedBy(parsed.positional[0], {
1427
+ bundlePath: one(parsed, '--bundle'), trustedRootPath: one(parsed, '--trusted-root'), cosignPath: one(parsed, '--cosign'), repository: one(parsed, '--repo'),
1428
+ ...(workflow ? { workflow } : {}), ...(repositoryId ? { repositoryId } : {}),
1429
+ });
1430
+ }
1431
+ catch (error) {
1432
+ if (error instanceof RangeError)
1433
+ throw new UsageError(error.message);
1434
+ print({ result: 'NOT_VERIFIED', reason: error.message });
1435
+ return 1;
1436
+ }
1437
+ print({ result: facts.differences.length === 0 ? 'PUBLISHED_BY' : 'RECORD_MISMATCH', digest: facts.digest, publisher: facts.publisher, differences: facts.differences, declaration: facts.recorded.declaration, profile: facts.recorded.profile });
1438
+ return facts.differences.length === 0 ? 0 : 1;
1439
+ }
1440
+ case 'admit':
1441
+ return await runAdmit(parsed, now);
1442
+ case 'admission': {
1443
+ if (maybeSub === 'check') {
1444
+ allow(parsed, [], 1);
1445
+ let rules;
1446
+ try {
1447
+ rules = parseRules((await readRegularFile(parsed.positional[0], 'Rule file', 256 * 1024)).toString('utf8'));
1448
+ }
1449
+ catch (error) {
1450
+ if (!(error instanceof AdmissionRulesError))
1451
+ throw error;
1452
+ print({ valid: false, error: error.message });
1453
+ return 1;
1454
+ }
1455
+ print({ valid: true, digest: rules.digest, default: rules.default, rules: rules.rules.map((rule) => `${rule.id}: ${rule.action}`) });
1456
+ return 0;
1457
+ }
1458
+ if (maybeSub === 'diff') {
1459
+ allow(parsed, ['--against-log'], 2);
1460
+ const load = async (file) => {
1461
+ try {
1462
+ return parseRules((await readRegularFile(file, 'Rule file', 256 * 1024)).toString('utf8'));
1463
+ }
1464
+ catch (error) {
1465
+ if (error instanceof AdmissionRulesError)
1466
+ throw new UsageError(`${file}: ${error.message}`);
1467
+ throw error;
1468
+ }
1469
+ };
1470
+ const [previous, next] = [await load(parsed.positional[0]), await load(parsed.positional[1])];
1471
+ const lines = (await readRegularFile(one(parsed, '--against-log'), 'Decision log', 256 * 1024 * 1024)).toString('utf8').split('\n').filter(Boolean);
1472
+ const records = lines.map((line, index) => {
1473
+ try {
1474
+ return JSON.parse(line);
1475
+ }
1476
+ catch {
1477
+ throw new UsageError(`log line ${index + 1} is not JSON`);
1478
+ }
1479
+ });
1480
+ const flips = replay(previous, next, records);
1481
+ print({ decisions: records.length, changed: flips.length, flips: flips.map((flip) => ({ decided_at: flip.decided_at, skill: flip.skill, digest: flip.digest, from: `${flip.before.action} (${flip.before.rule_id})`, to: `${flip.after.action} (${flip.after.rule_id})` })) });
1482
+ return flips.length === 0 ? 0 : 1;
1483
+ }
1484
+ throw new UsageError('Usage: mago-ski admission check RULES | mago-ski admission diff OLD NEW --against-log FILE');
1485
+ }
1486
+ case 'check': {
1487
+ allow(parsed, [], 1);
1488
+ const skillDir = path.resolve(parsed.positional[0]);
1489
+ const result = await checkSkill(skillDir, path.dirname(skillDir), { requireManifest: parsed.booleans.has('--require-manifest') });
1490
+ const { format: _format, dir: _dir, ...rest } = result;
1491
+ print({ skill_dir: skillDir, usf_format: result.format, ...rest });
1492
+ return result.ok ? 0 : 1;
1493
+ }
1273
1494
  case 'diff': {
1274
1495
  if (parsed.positional.length > 0)
1275
1496
  throw new UsageError(`diff takes the two directories as options: mago-ski diff --base ${parsed.positional[0]} --candidate ${parsed.positional[1] ?? 'DIR'}`);
1276
1497
  allow(parsed, ['--base', '--candidate'], 0);
1277
1498
  const result = await diffSkillTrees(one(parsed, '--base'), one(parsed, '--candidate'));
1278
1499
  print(result);
1500
+ const skipped = [...new Set([...result.not_compared.base, ...result.not_compared.candidate])];
1501
+ if (skipped.length > 0)
1502
+ process.stderr.write(`warning: ${notCoveredNote(skipped)} They were not compared.\n`);
1279
1503
  return result.recertification_required ? 1 : 0;
1280
1504
  }
1281
1505
  case 'inspect': {
@@ -22,5 +22,14 @@ 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
  }
31
+ export declare function collectOrigins(contents: Map<string, Buffer>): {
32
+ origins: string[];
33
+ complete: boolean;
34
+ };
26
35
  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. */
@@ -44,7 +44,7 @@ function trimTrailingPunctuation(value) {
44
44
  }
45
45
  return value.slice(0, end);
46
46
  }
47
- function collectOrigins(contents) {
47
+ export function collectOrigins(contents) {
48
48
  const origins = new Set();
49
49
  let complete = true;
50
50
  let candidates = 0;
@@ -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[];
@@ -24,3 +30,27 @@ export declare function verifySigstoreBlob(options: {
24
30
  }): Promise<{
25
31
  valid: true;
26
32
  }>;
33
+ export declare function buildCosignVerifyAttestationArgs(options: {
34
+ bundlePath: string;
35
+ trustedRootPath: string;
36
+ digestHex: string;
37
+ predicateType: string;
38
+ identityRegexp: string;
39
+ issuer: string;
40
+ }): string[];
41
+ /**
42
+ * Verifies an in-toto attestation in a Sigstore bundle for a subject known only by its sha256 digest, offline against
43
+ * the given trusted root: the signature, the certificate chain, the transparency-log proof, the signer identity and
44
+ * that the statement names this digest. The caller reads the statement from the same bundle bytes afterwards.
45
+ */
46
+ export declare function verifySigstoreAttestation(options: {
47
+ binaryPath: string;
48
+ bundlePath: string;
49
+ trustedRootPath: string;
50
+ digestHex: string;
51
+ predicateType: string;
52
+ identityRegexp: string;
53
+ issuer: string;
54
+ }): Promise<{
55
+ valid: true;
56
+ }>;
@@ -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,28 @@ 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));
160
+ return { valid: true };
161
+ }
162
+ export function buildCosignVerifyAttestationArgs(options) {
163
+ return [
164
+ 'verify-blob-attestation', '--bundle', options.bundlePath, '--trusted-root', options.trustedRootPath,
165
+ '--digest', options.digestHex, '--digestAlg', 'sha256', '--type', options.predicateType, '--check-claims=true',
166
+ '--certificate-identity-regexp', options.identityRegexp, '--certificate-oidc-issuer', options.issuer,
167
+ ];
168
+ }
169
+ /**
170
+ * Verifies an in-toto attestation in a Sigstore bundle for a subject known only by its sha256 digest, offline against
171
+ * the given trusted root: the signature, the certificate chain, the transparency-log proof, the signer identity and
172
+ * that the statement names this digest. The caller reads the statement from the same bundle bytes afterwards.
173
+ */
174
+ export async function verifySigstoreAttestation(options) {
175
+ const bundlePath = await requireRegularFile(options.bundlePath, 'Sigstore bundle');
176
+ const trustedRootPath = await requireRegularFile(options.trustedRootPath, 'Sigstore trusted root');
177
+ if (!/^[0-9a-f]{64}$/u.test(options.digestHex))
178
+ throw new Error('subject digest must be 64 lowercase hex characters');
179
+ if (!options.identityRegexp || !options.issuer)
180
+ throw new Error('a certificate identity and OIDC issuer are required');
181
+ await runCosign(options.binaryPath, buildCosignVerifyAttestationArgs({ ...options, bundlePath, trustedRootPath }), 60_000, verificationEnv(process.env));
152
182
  return { valid: true };
153
183
  }
@@ -1,9 +1,22 @@
1
+ export interface ReadOwnedRegularFileOptions {
2
+ maxBytes?: number;
3
+ uid: number;
4
+ disallowGroupOtherWrite?: boolean;
5
+ notRegularMessage?: string;
6
+ ownershipMessage?: string;
7
+ }
1
8
  export declare function isInside(root: string, candidate: string): boolean;
2
9
  /**
3
- * Reads a regular, non-symlink file, failing if it changes while being read.
4
- * The type and size are checked before any content is read, and at most `maxBytes` (+1 to detect growth) are read.
10
+ * Reads a regular, non-symlink file without following symlinks on the final path component, failing if it changes
11
+ * while being read. Opens directly with `O_NOFOLLOW | O_NONBLOCK`, then checks the opened handle's type and size
12
+ * before reading at most `maxBytes` (+1 to detect growth).
5
13
  */
6
14
  export declare function readRegularFile(filePath: string, label: string, maxBytes?: number): Promise<Buffer>;
15
+ /**
16
+ * Reads a regular, non-symlink file whose opened handle is owned by `options.uid` (and by default not writable by
17
+ * group or others), failing if it changes while being read.
18
+ */
19
+ export declare function readOwnedRegularFile(filePath: string, label: string, options: ReadOwnedRegularFileOptions): Promise<Buffer>;
7
20
  /** Resolves a file path and requires it to be outside `root` (both canonicalized). */
8
21
  export declare function resolveOutside(filePath: string, root: string, label: string, { allowMissing }?: {
9
22
  allowMissing?: boolean | undefined;