@cygnuxlabs/tracekit 1.5.3 → 1.6.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.
@@ -12,8 +12,10 @@
12
12
  * Monitor reports, revocations and the v1 format bridge are inputs of the reference's CLI that this one doesn't take.
13
13
  * A bundle that needs a newer verifier is UNVERIFIABLE, with the commands that verify it; one whose records carry ext
14
14
  * names this verifier doesn't interpret (format 1.4's non-critical slot) verifies, with a `not interpreted` warning
15
- * per name; it interprets `amended` (the fields an LLM gateway changed in a request to show reasoning) and
16
- * `openshell.policy` (OpenShell's sandbox policy changes, from the OpenShell middleware's OCSF import).
15
+ * per name; it interprets `amended` (the fields an LLM gateway changed in a request to show reasoning),
16
+ * `openshell.policy` (OpenShell's sandbox policy changes, from the OpenShell middleware's OCSF import), `box` (a
17
+ * Tracekit Box box's run label) and `intent.grant`, `intent.revoked` and `grant` (intent grants and the calls they
18
+ * released).
17
19
  * `verify(bundle, null)` (no trust config) checks what needs no pinned key and is never VERIFIED. web.ts is this
18
20
  * verifier as a browser page (verify.html).
19
21
  */
@@ -22,10 +24,14 @@ import { HYBRID, NoteError, SIGNER_LEAVES, b64decode, bytes, checkWitnesses, equ
22
24
  import { Detector } from "./detect.js";
23
25
  import { same, validateEvent } from "./schema.js";
24
26
  import { BadZipFile, MAX_ENTRY, Unusable, readZip } from "./zip.js";
27
+ import VERSIONS_JSON from "./versions.json" with { type: "json" };
25
28
  export { MAX_ENTRIES, MAX_ENTRY, MAX_TOTAL, Unusable, readZip } from "./zip.js";
26
29
  export { StrictJSONError, canonicalize, strictParse, strictParseBytes } from "./jcs.js";
27
- /** The bundle format version this verifier implements: a bundle needing a later one is UNVERIFIABLE. */
28
- export const VERSION = "1.5.3";
30
+ /** This verifier's release (the package's). */
31
+ export const VERSION = "1.6.0";
32
+ /** The newest bundle format version this verifier reads: the reference's VERSIONS' newest row (tracekit/bundle_v2.py),
33
+ * or VERSION when later (tracekit/verify/v2.py READS); a bundle needing a later one is UNVERIFIABLE. */
34
+ export const READS = "1.6.0";
29
35
  /** The browser verifier of the latest release (docs/RELEASING.md). */
30
36
  const PAGE = "https://cygnux-labs.github.io/Tracekit/verify/";
31
37
  export const EXIT_OK = 0, EXIT_FAIL = 1, EXIT_BAD = 2, EXIT_WARN = 3;
@@ -65,6 +71,10 @@ export class Report {
65
71
  findings = null;
66
72
  /** Checks the bundle needs that this verifier does not implement. */
67
73
  unsupported = [];
74
+ /** For the box check: the pinned witnesses' cosignatures of the checkpoint, `name (class) at time`, and the seqs of
75
+ * the bundle's own runs' first records. */
76
+ anchored = [];
77
+ firsts = new Set();
68
78
  check(check, ok, detail = "", problems = [], warn = false) {
69
79
  this.checks.push({ check, status: ok ? "pass" : warn ? "warn" : "fail", detail, problems });
70
80
  if (!ok)
@@ -285,7 +295,7 @@ export async function verify(bundle, trust, names = { bundle: "BUNDLE", trust: "
285
295
  const need = manifest.verifier_min_version;
286
296
  if (!(typeof need === "string" && /^\d{1,9}(\.\d{1,9}){0,2}$/.test(need)))
287
297
  throw new Unusable("verifier_min_version is not a version number");
288
- if (newer(need, VERSION)) {
298
+ if (newer(need, READS)) {
289
299
  rep.integrity = `UNVERIFIABLE (needs tracekit >= ${need})`;
290
300
  rep.check("bundle readable", false, rep.integrity, upgrade(need, names));
291
301
  return { report: rep, code: EXIT_BAD };
@@ -388,11 +398,11 @@ async function check(rep, manifest, files, trust, floats) {
388
398
  && (k.until === null || seq <= num(k.until))).map((k) => k.spki);
389
399
  /** Signature, schema and log membership of one record under `keys`, the SPKIs valid at its position. */
390
400
  const checkRecord = async (r, keys, problems) => {
391
- const err = await verifyRecord(r, keys, trust.algs);
401
+ const err = await verifyRecord(r, keys, trust.algs, floats);
392
402
  if (err) {
393
403
  const seq = err === "unknown kid" ? get(r.event, "seq") : null; // a well-formed record by then
394
404
  const retired = [...timeline.values()].filter((k) => Number.isInteger(seq) && k.until !== null && k.until < seq);
395
- if (retired.length && !await verifyRecord(r, retired.map((k) => k.spki), trust.algs))
405
+ if (retired.length && !await verifyRecord(r, retired.map((k) => k.spki), trust.algs, floats))
396
406
  problems.push(`seq ${seq}: signed by key ${cut(r.kid, 80)} after its key.retire`);
397
407
  else
398
408
  problems.push(`seq ${repr(get(get(r, "event", {}), "seq"))}: ${err}`);
@@ -422,6 +432,10 @@ async function check(rep, manifest, files, trust, floats) {
422
432
  keyProblems.push(`seq ${e.seq}: key ${cut(str(k.kid), 80)} has no certificate, and the trust config pins issuers`);
423
433
  continue;
424
434
  }
435
+ if (has(k, "cert") && !trust.issuers.length) { // §11 step 5: no pinned issuer can have signed it
436
+ keyProblems.push(`seq ${e.seq}: key ${cut(str(k.kid), 80)}: certificate not signed by a pinned issuer`);
437
+ continue;
438
+ }
425
439
  // lean: a certified key is taken as declared and the bundle left UNVERIFIABLE; port docs/issuer.md's checks
426
440
  // (issuance log notes, validity, tenants, revocations) when certified record keys are in use
427
441
  if (has(k, "cert"))
@@ -429,14 +443,14 @@ async function check(rep, manifest, files, trust, floats) {
429
443
  declared.set(k.kid, { spki: der, from: e.seq, until: null });
430
444
  }
431
445
  }
432
- await checkRecord(r, [...keysAt(e.seq), ...[...declared.values()].map((k) => k.spki)], keyProblems);
433
- if (e.type === "key.retire") {
446
+ if (e.type === "key.retire") { // first: a key.retire is a record too, valid only under a key valid at its seq
434
447
  const kid = at(at(e, "data"), "kid");
435
448
  if (!timeline.has(kid))
436
449
  keyProblems.push(`seq ${e.seq}: retires an unknown key`);
437
450
  else
438
451
  timeline.get(kid).until = at(e.data, "last_seq");
439
452
  }
453
+ await checkRecord(r, [...keysAt(e.seq), ...[...declared.values()].map((k) => k.spki)], keyProblems);
440
454
  for (const [kid, k] of declared)
441
455
  timeline.set(kid, k);
442
456
  }
@@ -533,7 +547,9 @@ async function check(rep, manifest, files, trust, floats) {
533
547
  rep.integrity = !open.length ? "VERIFIED" : only ? `VERIFIED TO HEAD ${str(get(open[0].at(-1).event, "run_seq"))} (open)`
534
548
  : `VERIFIED (${open.length} run(s) open)`;
535
549
  const events = every.map((r) => r.event), typed = (t) => events.filter((e) => get(e, "type") === t);
536
- const selfApproved = typed("approval").some((e) => get(at(e, "data"), "self_approved") === true);
550
+ // a grant the run's own user issued (intent.grant) approves the calls it releases: a self-approval too
551
+ const selfApproved = [...typed("approval"), ...typed("ext").filter((e) => get(at(e, "data"), "name") === "intent.grant")]
552
+ .some((e) => get(at(e, "data"), "self_approved") === true);
537
553
  const gaps = (k) => typed("capture.gap").filter((e) => get(at(e, "data"), "kind") === k)
538
554
  .map((e) => `seq ${e.seq}: ${cut(str(get(e.data, "reason")), 200)}`);
539
555
  const against = gaps("executed_against_policy");
@@ -667,8 +683,12 @@ async function check(rep, manifest, files, trust, floats) {
667
683
  if (glass.length)
668
684
  rep.check("break-glass approvals", false, `${glass.length} approval(s) answered under the break-glass role`, glass.map((e) => `seq ${e.seq}: ${str(at(e.data, "decision"))} ${str(get(e.data, "approval_id"))} by `
669
685
  + `${cut(text(at(e.data, "approver")), 256)}: ${repr(cut(str(get(e.data, "reason")), 200))}`).slice(0, 20), true);
670
- checkExt(rep, [...new Map([...keyRecords, ...pointed, ...every].map((r) => [at(at(r, "event"), "seq"), r.event]))
671
- .values()], get(manifest, "verifier_version"));
686
+ rep.anchored = [...cosigs].sort((a, b) => a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)
687
+ .map(([k, ts]) => `${k.split("+")[0]} (${witnesses.get(k)}) at ${fmt(ts)}`);
688
+ rep.firsts = new Set(firsts.map((e) => at(e, "seq")));
689
+ const all = [...new Map([...keyRecords, ...pointed, ...every].map((r) => [at(at(r, "event"), "seq"), r.event])).values()];
690
+ await checkExt(rep, all, get(manifest, "verifier_version"), floats);
691
+ checkMinimum(rep, all, [...files.keys()], str(get(manifest, "verifier_min_version")));
672
692
  }
673
693
  /**
674
694
  * ext.amended: the JSON pointers of the fields an LLM gateway changed in a model request before sending it, to show the
@@ -715,23 +735,433 @@ function checkOpenshellPolicy(rep, events) {
715
735
  + `${good.length} time(s)` + (shown.length ? ` (${shown.join(", ")})` : "") + ", as OpenShell reported it", bad.map((e) => `seq ${str(get(e, "seq"))}: ext.openshell.policy is not an OpenShell policy change the signer `
716
736
  + "recorded").slice(0, 20), true);
717
737
  }
738
+ /** A Tracekit Box engine, as verify names what its box is (tracekit/signer/service.py ENGINES). */
739
+ const ENGINES = { firecracker: "micro-VM" };
740
+ const BOXED = "PROOF AGAINST THE BOXED AGENT";
741
+ const DOORS = "the box's doors (its connections and file writes)";
742
+ /**
743
+ * Whether `e` carries ext.box as the signer writes it: on run.registered only, {id, image_digest, allow, engine,
744
+ * channel?}, under a Box daemon's identity (a uid): its box run, or with parent_run a run of its box's agent channel.
745
+ */
746
+ function boxLabel(e) {
747
+ const v = isObj(get(e, "ext")) ? get(e.ext, "box") : null, d = get(e, "data");
748
+ const i = isObj(d) ? get(d, "identity") : null, keys = isObj(v) ? Object.keys(v) : [];
749
+ return get(e, "type") === "run.registered" && isObj(v) && isObj(i) && get(i, "scheme") === "uid"
750
+ && ["id", "image_digest", "allow", "engine"].every((k) => keys.includes(k))
751
+ && keys.every((k) => ["id", "image_digest", "allow", "engine", "channel"].includes(k))
752
+ && typeof v.id === "string" && /^[A-Za-z0-9._:-]{1,128}$/.test(v.id) && typeof v.image_digest === "string"
753
+ && /^sha256:[0-9a-f]{64}$/.test(v.image_digest) && Array.isArray(v.allow)
754
+ && v.allow.every((a) => typeof a === "string") && typeof v.engine === "string"
755
+ && Object.hasOwn(ENGINES, v.engine) && (!Object.hasOwn(v, "channel") || v.channel === "agent");
756
+ }
757
+ /**
758
+ * ext.box: the label of a Tracekit Box box's run (its daemon's account of the box, with the engine from the signer's
759
+ * own config) and of each run its agent channel registered (a copy, with parent_run). The signing key was outside that
760
+ * box, so the runs are proof against the agent in it, and no more: an agent run's records are its own account, the
761
+ * box's doors held it, and anything running as the daemon's or the signer's user on the host is outside the claim.
762
+ * Anywhere else, or in another shape, a warning and no claim. Only the bundle's own runs are claimed for
763
+ * (rep.firsts): a run-set's records of other runs carry their labels too.
764
+ */
765
+ function checkBox(rep, events) {
766
+ const bad = events.filter((e) => !boxLabel(e));
767
+ if (bad.length) {
768
+ rep.check("boxed agent", false, `${bad.length} record(s) carry ext.box where or how the signer never writes it: `
769
+ + "no proof against a boxed agent", bad.map((e) => `seq ${str(get(e, "seq"))}: ext.box is not a box's label on `
770
+ + "its run.registered").slice(0, 20), true);
771
+ return;
772
+ }
773
+ const good = events.filter((e) => rep.firsts.has(get(e, "seq")));
774
+ if (!good.length)
775
+ return; // labels of runs this bundle doesn't hold
776
+ const one = good.length === 1, agent = good.some((e) => Object.hasOwn(e.data, "parent_run"));
777
+ const kinds = [...new Set(good.map((e) => ENGINES[e.ext.box.engine]))].sort(byCodePoint).join(", ");
778
+ rep.check("boxed agent", true, `${BOXED} (${kinds}): the signing key was outside its box for `
779
+ + `${one ? "this run" : `these ${good.length} runs`}.`, [one && agent
780
+ ? `This run's records are the agent's own account of its calls; ${DOORS} are the record of what it could do.`
781
+ : one ? `This run's records are ${DOORS}, as the Box daemon recorded them.`
782
+ : `In these runs, the agent's records are its own account of its calls; ${DOORS} are the record of what it `
783
+ + "could do.",
784
+ "Before you run anything the box wrote, review it: code you run on this machine can reach the key.",
785
+ ...rep.anchored.map((a) => `anchored by ${a}`)]);
786
+ }
787
+ /** Whether the parser read `o[k]` as a number token with a fraction or exponent: Python's float, never an int. */
788
+ const isFloat = (floats, o, k) => !!floats.get(o)?.has(k);
789
+ const NO_FLOATS = new WeakMap(); // for values this verifier computed
790
+ /** A number as Python prints it: a float-written whole number with `.0`. */
791
+ // lean: integral floats below 1e16 only; Python's repr of others (1e+16, 1e-05) differs from JavaScript's
792
+ const pyNum = (v, float) => float && Number.isInteger(v) && Math.abs(v) < 1e16 ? `${v}.0` : JSON.stringify(v);
793
+ /** Python's json.dumps(v), as the reference's messages print values: ", " and ": " between items, and every character
794
+ * past ASCII escaped; `float`: v was written as a float. */
795
+ function dumps(v, floats = NO_FLOATS, float = false) {
796
+ if (Array.isArray(v))
797
+ return `[${v.map((x, i) => dumps(x, floats, isFloat(floats, v, i))).join(", ")}]`;
798
+ if (isObj(v))
799
+ return `{${Object.entries(v).map(([k, x]) => `${dumps(k)}: ${dumps(x, floats, isFloat(floats, v, k))}`)
800
+ .join(", ")}}`;
801
+ if (typeof v === "number")
802
+ return pyNum(v, float);
803
+ return JSON.stringify(v).replace(/[\x7f-\uffff]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"));
804
+ }
805
+ /** Python's str(v), as an f-string prints a value: a list or an object with its items' repr (`['g-1', None]`). */
806
+ function pyStr(v, floats = NO_FLOATS, float = false) {
807
+ const item = (x, f) => typeof x === "string" ? quoted(x) : pyStr(x, floats, f);
808
+ return Array.isArray(v) ? `[${v.map((x, i) => item(x, isFloat(floats, v, i))).join(", ")}]`
809
+ : isObj(v) ? `{${Object.entries(v).map(([k, x]) => `${quoted(k)}: ${item(x, isFloat(floats, v, k))}`).join(", ")}}`
810
+ : typeof v === "number" ? pyNum(v, float) : str(v);
811
+ }
812
+ // intent grants (docs/intent-grants.md), as tracekit/grants.py and tracekit/pcm read them; payments are the one intent
813
+ /** The minor units of each currency an amount is shown in (grants.DECIMALS). */
814
+ const DECIMALS = { USD: 2, EUR: 2, GBP: 2, INR: 2, CAD: 2, AUD: 2, CHF: 2, SGD: 2, JPY: 0,
815
+ USDC: 6, USDT: 6 };
816
+ /** payment.send's schema document (grants.PAYMENT): a grant's intent names its hash. */
817
+ const PAYMENT = { pcm_schema: 0, name: "payment.send", grant: true, fields: {
818
+ amount: { type: "int", min: 1, max: Number.MAX_SAFE_INTEGER },
819
+ currency: { type: "id", pattern: "[A-Z][A-Z0-9]{2,9}" },
820
+ payee: { type: "id", pattern: "[A-Za-z0-9._:@/+=-]{1,128}" }
821
+ } };
822
+ const FIELDS = PAYMENT.fields;
823
+ const CAVEAT_OPS = { int: ["==", "<=", ">=", "<", ">"], id: ["==", "in"] };
824
+ const GRANT_KEYS = ["name", "id", "grant", "tools", "limits", "used", "self_approved", "first", "description"];
825
+ const MAX_TOOLS = 16; // the tools one grant names (grants.MAX_TOOLS)
826
+ const ID_RE = /^[A-Za-z0-9._:-]{1,128}$/, NAME_RE = /^[a-z][a-z0-9_]{0,63}$/;
827
+ // rpc_schema.TS, whose \d Python's re reads as any decimal digit
828
+ const TS_RE = /^\p{Nd}{4}-\p{Nd}{2}-\p{Nd}{2}T\p{Nd}{2}:\p{Nd}{2}:\p{Nd}{2}\.\p{Nd}{6}Z$/u;
829
+ /** Whether `o` is an object with every key of `need` and no key outside `need` and `may` (a closed JSON Schema). */
830
+ const shaped = (o, need, may = []) => isObj(o) && need.every((k) => Object.hasOwn(o, k))
831
+ && Object.keys(o).every((k) => need.includes(k) || may.includes(k));
832
+ /** Whether `v` is a string of at most `n` characters, all of it matching `re`. */
833
+ const short = (v, n, re) => typeof v === "string" && [...v].length <= n && (!re || re.test(v));
834
+ const opt = (o, k, ok) => !Object.hasOwn(o, k) || ok(o[k]);
835
+ /** A PCM grant as rpc_schema.PCM_GRANT has it. */
836
+ const isPcmGrant = (g, floats) => shaped(g, ["pcm_grant", "ts", "issuer", "subject", "intent", "caveats",
837
+ "expires_at", "delegable", "parent", "sig"]) && g.pcm_grant === 0 && !isFloat(floats, g, "pcm_grant")
838
+ && short(g.ts, 27, TS_RE) && short(g.expires_at, 27, TS_RE)
839
+ && shaped(g.issuer, ["kind", "id", "run", "tenant"], ["person", "approval_id"])
840
+ && ["person", "agent"].includes(g.issuer.kind) && short(g.issuer.id, 256) && opt(g.issuer, "person", (v) => short(v, 256))
841
+ && short(g.issuer.run, 128, ID_RE) && short(g.issuer.tenant, 128, ID_RE)
842
+ && opt(g.issuer, "approval_id", (v) => short(v, 128, ID_RE)) && short(g.subject, 256, /^[a-z0-9_]+:[^\n]+$/)
843
+ && short(g.intent, 136, /^[a-z][a-z0-9_.-]{0,63}@sha256:[0-9a-f]{64}$/) && Array.isArray(g.caveats)
844
+ && g.caveats.length <= 16 && g.caveats.every((c) => shaped(c, ["field", "op", "value"]) && short(c.field, 64, NAME_RE)
845
+ && ["==", "<=", ">=", "<", ">", "in"].includes(c.op)) && typeof g.delegable === "boolean"
846
+ && (g.parent === null || short(g.parent, 71, /^sha256:[0-9a-f]{64}$/))
847
+ && shaped(g.sig, ["key", "sig"]) && short(g.sig.key, 300) && g.sig.key !== "" && short(g.sig.sig, 88);
848
+ /** A grant's limits as rpc_schema._LIMITS has them. */
849
+ const isLimits = (v, floats) => Array.isArray(v) && v.length >= 1 && v.length <= 4 && v.every((x) => shaped(x, ["op", "max"], ["field"]) && ["sum", "count"].includes(x.op) && opt(x, "field", (f) => short(f, 64, NAME_RE))
850
+ && Number.isSafeInteger(x.max) && !isFloat(floats, x, "max") && x.max >= 1);
851
+ /** pcm._FITS: whether `v` is a valid value of field `f`; `float`: v was written as a float, which is no int. */
852
+ // lean: the int and id rules, the types payment.send uses; port the rest with an intent whose fields use them
853
+ const fits = (f, v, float) => f.type === "int" ? Number.isInteger(v) && !float && f.min <= v && v <= f.max
854
+ : typeof v === "string" && [...v].length <= 128 && new RegExp(`^(?:${f.pattern})$`).test(v);
855
+ /** pcm.check_args of payment.send: what is wrong with call `fields`, an object. */
856
+ function argErrors(fields, floats) {
857
+ const out = Object.keys(fields).filter((k) => !Object.hasOwn(FIELDS, k)).map((k) => `args.${k}: not in the schema`);
858
+ for (const [k, f] of Object.entries(FIELDS)) {
859
+ if (!Object.hasOwn(fields, k))
860
+ out.push(`args.${k}: missing`);
861
+ else if (!fits(f, fields[k], isFloat(floats, fields, k)))
862
+ out.push(`args.${k}: ${dumps(fields[k], floats, isFloat(floats, fields, k)).slice(0, 64)} is not a valid ${f.type}`);
863
+ }
864
+ return out;
865
+ }
866
+ /** A grant's short id (grants.grant_id): `g-` and the first 16 hex digits of its hash. */
867
+ const grantId = async (g) => "g-" + (await sha256hex(bytes(canonicalize(g)))).slice(0, 16);
868
+ /** grants.number: minor units as the number a person reads (`200`, `0.5`); the minor units for an unknown currency. */
869
+ function number(minor, cur) {
870
+ const d = typeof cur === "string" && Object.hasOwn(DECIMALS, cur) ? DECIMALS[cur] : null;
871
+ if (d === null || !Number.isInteger(minor))
872
+ return dumps(minor).slice(0, 32);
873
+ const frac = minor % 10 ** d;
874
+ return `${(minor - frac) / 10 ** d}` + (frac ? "." + String(frac).padStart(d, "0").replace(/0+$/, "") : "");
875
+ }
876
+ /** grants.show: minor units as a person reads them (`200 USDC`), by name for an unknown currency. */
877
+ const show = (minor, cur) => `${number(minor, cur)} `
878
+ + (typeof cur === "string" && Object.hasOwn(DECIMALS, cur) && Number.isInteger(minor) ? cur : `${str(cur)} (minor units)`);
879
+ /** grants.problems for a payment grant, as a verifier asks (no ceiling), of caveats and limits already of their shape;
880
+ * `tools`: the record's, the tools whose calls the grant covers. */
881
+ function grantProblems(caveats, limits, tools, expiresAt, now, floats) {
882
+ const out = [], pinned = new Map(), seen = new Set();
883
+ for (const c of caveats) { // pcm.check_caveats
884
+ const f = Object.hasOwn(FIELDS, c.field) ? FIELDS[c.field] : null, vals = c.op === "in" ? c.value : [c.value];
885
+ const said = `${c.field} ${c.op} ${dumps(c.value, floats, isFloat(floats, c, "value")).slice(0, 64)}`;
886
+ if (!f)
887
+ out.push(`${said}: no field ${c.field} in payment.send`);
888
+ else if (!CAVEAT_OPS[f.type].includes(c.op))
889
+ out.push(`${said}: ${c.op} does not apply to a ${f.type} field`);
890
+ else if (!(Array.isArray(vals) && vals.length >= 1 && vals.length <= 64 && vals.every((x, i) => fits(f, x, c.op === "in" ? isFloat(floats, vals, i) : isFloat(floats, c, "value"))) && new Set(vals).size === vals.length))
891
+ out.push(`${said}: not a valid ${f.type} value`);
892
+ }
893
+ if (!(Array.isArray(tools) && tools.length > 0 && tools.length <= MAX_TOOLS && new Set(tools).size === tools.length
894
+ && tools.every((t) => typeof t === "string" && t !== "" && [...t].length <= 256)))
895
+ out.push(`a grant names the tools whose calls it covers: 1 to ${MAX_TOOLS} distinct tool names`);
896
+ for (const c of caveats)
897
+ if (c.op === "==" || c.op === "in")
898
+ pinned.set(c.field, c);
899
+ const cur = pinned.get("currency");
900
+ if (cur?.op !== "==")
901
+ out.push("a payment grant names its one currency (currency == USDC)");
902
+ else if (typeof cur.value === "string" && !Object.hasOwn(DECIMALS, cur.value)) // else check_caveats said it
903
+ out.push(`tracekit knows the units of ${Object.keys(DECIMALS).sort().join(", ")}; ${cur.value} isn't one of them`);
904
+ if (!pinned.has("payee"))
905
+ out.push("a payment grant names its payees (payee in [...])");
906
+ for (const x of limits) { // the rest of a limit's rule is its shape's (isLimits)
907
+ const k = JSON.stringify([x.op, x.field ?? null]);
908
+ const f = x.field ?? "amount";
909
+ if ((x.op === "sum") !== Object.hasOwn(x, "field") || !(Object.hasOwn(FIELDS, f) && FIELDS[f].type === "int"))
910
+ out.push(`limit ${dumps(x, floats).slice(0, 96)}: a limit is {op: sum, field, max} of a whole-number field (amount) `
911
+ + "or {op: count, max}, max a whole number above zero");
912
+ else if (seen.has(k))
913
+ out.push(`limit ${x.op} ${x.field ?? ""}: given twice`.replace(/ /g, " "));
914
+ seen.add(k);
915
+ }
916
+ if (!limits.some((x) => x.op === "sum" && x.field === "amount"))
917
+ out.push("a payment grant has a total (a sum limit of amount)");
918
+ const day = new Date(Date.parse(now.slice(0, 19) + "Z") + 86400_000).toISOString().slice(0, 19) + now.slice(19);
919
+ if (!(now < expiresAt && expiresAt <= day))
920
+ out.push(`expires_at ${expiresAt} is not in the next 24 h`);
921
+ return out;
922
+ }
923
+ /** grants._why: why `fields` break caveat `c`, in words. */
924
+ function brokenBy(c, fields) {
925
+ const v = get(fields, c.field), cur = get(fields, "currency");
926
+ if (c.field === "amount" && (c.op === "<=" || c.op === "<"))
927
+ return `amount ${show(v, cur)} is over ${show(c.value - Number(c.op === "<"), cur)} each`;
928
+ if (c.field === "amount" && (c.op === ">=" || c.op === ">"))
929
+ return `amount ${show(v, cur)} is under ${show(c.value + Number(c.op === ">"), cur)} each`;
930
+ const allowed = c.op === "in" ? c.value : [c.value];
931
+ return `${c.field} ${dumps(v).slice(0, 64)} is not ${allowed.length > 1 ? "one of " : ""}`
932
+ + allowed.slice(0, 8).map((x) => dumps(x).slice(0, 64)).join(", ")
933
+ + (allowed.length > 8 ? ` and ${allowed.length - 8} more` : "");
934
+ }
935
+ /**
936
+ * grants.check: [the totals after a call with `fields`, null] when grant `gid`'s entry `g` ({grant, limits, used,
937
+ * revoked}) releases it at `now`, else [null, why not]. Its caveats passed grantProblems and the fields argErrors, so
938
+ * each caveat compares values of one type (pcm.satisfies).
939
+ */
940
+ function grantCheck(gid, g, fields, now) {
941
+ if (g.revoked)
942
+ return [null, `grant ${gid} was revoked`];
943
+ if (now >= g.grant.expires_at)
944
+ return [null, `grant ${gid} expired at ${g.grant.expires_at}`];
945
+ for (const c of g.grant.caveats) {
946
+ const v = fields[c.field], w = c.value;
947
+ if (!(c.op === "in" ? w.includes(v) : c.op === "==" ? v === w : c.op === "<=" ? v <= w : c.op === "<" ? v < w
948
+ : c.op === ">=" ? v >= w : v > w))
949
+ return [null, `grant ${gid}: ${brokenBy(c, fields)}`];
950
+ }
951
+ const used = g.limits.map((x, i) => g.used[i] + (x.op === "sum" ? fields[x.field] : 1));
952
+ for (const [i, x] of g.limits.entries()) {
953
+ if (used[i] <= x.max)
954
+ continue;
955
+ const before = g.used[i], cur = fields.currency;
956
+ return [null, `grant ${gid}: ` + (x.op === "count" ? `${str(before)} of ${x.max} payments made`
957
+ : `${number(before, cur)} of ${show(x.max, cur)} used; this call needs ${show(used[i] - before, cur)}`)];
958
+ }
959
+ return [used, null];
960
+ }
961
+ /**
962
+ * Why `e` is not an intent.grant record as the signer writes one (SignerService._grant_issue), or null: a PCM grant of
963
+ * payment.send (`payment`, its schema ref), issued by a person for this very run and tenant, never passed on, its id its
964
+ * hash's; caveats, tools and limits a grant may have, an expiry within 24 h of its issue; and its totals those of no
965
+ * call, or of the held call it was issued from (`first`), which must be within it.
966
+ */
967
+ async function grantIssued(e, payment, floats) {
968
+ const d = get(e, "data");
969
+ if (get(e, "source") !== "signer" || !isObj(d) || !Object.keys(d).every((k) => GRANT_KEYS.includes(k))
970
+ || typeof get(d, "id") !== "string" || !Array.isArray(get(d, "used"))
971
+ || !d.used.every((u, i) => Number.isInteger(u) && !isFloat(floats, d.used, i)) || !isPcmGrant(get(d, "grant"), floats)
972
+ || !isLimits(get(d, "limits"), floats) || typeof get(d, "self_approved") !== "boolean")
973
+ return "an intent.grant record that is not as the signer writes one";
974
+ const g = d.grant;
975
+ if (g.intent !== payment)
976
+ return `a grant of intent ${cut(g.intent, 80)}, which this verifier doesn't know`;
977
+ const id = await grantId(g);
978
+ if (d.id !== id)
979
+ return `grant ${cut(d.id, 24)} is not its grant's id (${id})`;
980
+ if (g.issuer.kind !== "person" || g.issuer.run !== get(e, "run_id") || g.issuer.tenant !== get(e, "tenant")
981
+ || g.parent !== null || g.delegable !== false)
982
+ return `grant ${id} is not a person's, for this run and tenant, kept to its run`;
983
+ const bad = grantProblems(g.caveats, d.limits, get(d, "tools"), g.expires_at, g.ts, floats);
984
+ if (bad.length)
985
+ return `grant ${id}: ${cut(bad.join("; "), 300)}`;
986
+ let used = d.limits.map(() => 0);
987
+ const f = get(d, "first");
988
+ if (f !== null) {
989
+ const fields = isObj(f) ? get(f, "fields") : null;
990
+ if (!(isObj(fields) && !argErrors(fields, floats).length && typeof get(f, "approval_id") === "string"
991
+ && typeof get(f, "tool_call_id") === "string"))
992
+ return `grant ${id}: its first use is not a held call's`;
993
+ const [after, why] = grantCheck(id, { grant: g, limits: d.limits, used, revoked: false }, fields, g.ts);
994
+ if (why)
995
+ return `grant ${id} was issued from a held call outside it (${why})`;
996
+ used = after;
997
+ }
998
+ if (!same(d.used, used))
999
+ return `grant ${id} starts with totals ${dumps(d.used, floats).slice(0, 64)}, not ${dumps(used)}`;
1000
+ if (Object.hasOwn(d, "description") && !short(d.description, 512))
1001
+ return `grant ${id}: its description is not a string of at most 512 characters`;
1002
+ return null;
1003
+ }
1004
+ /** Whether `e` is a decision whose rule ids name TK-GRANT: one a grant released, as its ext.grant must say. */
1005
+ const tkGrant = (e) => get(e, "type") === "policy.decision" && isObj(get(e, "data"))
1006
+ && Array.isArray(get(e.data, "rule_ids")) && e.data.rule_ids.includes("TK-GRANT");
1007
+ /**
1008
+ * intent.grant, intent.revoked and ext.grant (docs/intent-grants.md): the grants people issued for a run, their
1009
+ * revocations, and the calls they released. Each grant is checked as grantIssued says; each released call against its
1010
+ * grant, as the signer decided it: a policy.decision flagged with TK-GRANT, its grant recorded earlier in the same run
1011
+ * and not revoked before it, decided before the grant expired, of a tool the grant covers, its fields those of the
1012
+ * intent (whole numbers where they count) and within every caveat, its totals the previous call's plus its own, whole
1013
+ * numbers within every limit, and its tier the record's (T2: an executor or gateway decided and ran the call; T1: the
1014
+ * arguments the harness reported). A release that breaks its grant fails the line, and so does one whose grant the
1015
+ * bundle doesn't hold earlier in its run, or holds only in a record a signer never writes, a decision flagged TK-GRANT
1016
+ * without ext.grant, and a tier that isn't the record's: the records are the signer's own word that the call was within
1017
+ * a person's grant. Any other record in a shape the signer never writes is a warning, as for every ext name. `events`
1018
+ * also holds the decisions TK-GRANT names (checkExt); `floats`: the parser's, so a number written as a float is no whole
1019
+ * number.
1020
+ */
1021
+ export async function checkGrants(rep, events, floats) {
1022
+ const payment = `payment.send@sha256:${await sha256hex(bytes(canonicalize(PAYMENT)))}`;
1023
+ const live = new Map(), invalid = new Set(), bad = [], broken = [];
1024
+ const issuers = new Set();
1025
+ const tiers = { T1: 0, T2: 0 };
1026
+ let issued = 0, selfish = 0, revoked = 0;
1027
+ const seq = (e) => Number.isInteger(get(e, "seq")) ? e.seq : -1;
1028
+ for (const e of [...events].sort((a, b) => seq(a) - seq(b))) {
1029
+ const where = `seq ${pyStr(get(e, "seq"), floats, isFloat(floats, e, "seq"))}`, d = get(e, "data");
1030
+ const key = (id) => JSON.stringify([get(e, "tenant"), get(e, "run_id"), id]); // a grant's id is a string
1031
+ const name = get(e, "type") === "ext" && isObj(d) ? get(d, "name") : null;
1032
+ if (name === "intent.grant") {
1033
+ const why = await grantIssued(e, payment, floats);
1034
+ if (why) {
1035
+ bad.push(`${where}: ${why}`);
1036
+ if (typeof get(d, "id") === "string")
1037
+ invalid.add(key(d.id)); // what it released is released under no valid grant
1038
+ continue;
1039
+ }
1040
+ live.set(key(d.id), { grant: d.grant, tools: d.tools, limits: d.limits, used: d.used, revoked: false });
1041
+ issued++;
1042
+ selfish += Number(d.self_approved);
1043
+ if (!d.self_approved)
1044
+ issuers.add(d.grant.issuer.person || d.grant.issuer.id);
1045
+ }
1046
+ else if (name === "intent.revoked") {
1047
+ const g = typeof get(d, "id") === "string" ? live.get(key(d.id)) : undefined;
1048
+ if (get(e, "source") !== "signer" || !g || g.revoked)
1049
+ bad.push(`${where}: revokes no grant still live in its run`);
1050
+ else {
1051
+ g.revoked = true;
1052
+ revoked++;
1053
+ }
1054
+ }
1055
+ if (!(isObj(get(e, "ext")) && Object.hasOwn(e.ext, "grant"))) {
1056
+ if (tkGrant(e))
1057
+ broken.push(`${where}: a decision flagged TK-GRANT carries no ext.grant: it names no grant it was released under`);
1058
+ continue;
1059
+ }
1060
+ const x = e.ext.grant, g = isObj(x) && typeof get(x, "id") === "string" ? live.get(key(x.id)) : undefined;
1061
+ if (!(tkGrant(e) && get(d, "decision") === "flag" && shaped(x, ["id", "fields", "used", "tier"]))) {
1062
+ bad.push(`${where}: ext.grant is not on a decision a grant released, as the signer writes it`);
1063
+ continue;
1064
+ }
1065
+ const errs = !g ? [] : isObj(x.fields) ? argErrors(x.fields, floats) : ["not an object"];
1066
+ if (!g && typeof x.id === "string" && invalid.has(key(x.id)))
1067
+ broken.push(`${where}: released under grant ${cut(x.id, 24)}, whose record is not as the signer writes one`);
1068
+ else if (!g)
1069
+ broken.push(`${where}: names grant ${cut(pyStr(x.id, floats, isFloat(floats, x, "id")), 24)}, which this `
1070
+ + "bundle doesn't hold earlier in the run (export the whole run to check it)");
1071
+ else if (errs.length)
1072
+ broken.push(`${where}: the fields it records are not a payment.send call's (${cut(errs[0], 120)})`);
1073
+ else if (!g.tools.includes(get(d, "tool")))
1074
+ broken.push(`${where}: released a call of ${dumps(get(d, "tool"), floats, isFloat(floats, d, "tool")).slice(0, 64)}, `
1075
+ + `a tool grant ${x.id} doesn't cover`);
1076
+ else {
1077
+ const [used, why] = grantCheck(x.id, g, x.fields, get(e, "ts") || "");
1078
+ if (why)
1079
+ broken.push(`${where}: released a call the grant holds (${why})`);
1080
+ else if (!(Array.isArray(x.used) && x.used.every((u, i) => Number.isInteger(u) && !isFloat(floats, x.used, i))
1081
+ && same(x.used, used)))
1082
+ broken.push(`${where}: records totals ${dumps(x.used, floats).slice(0, 64)}, not ${dumps(used)}`);
1083
+ else if (x.tier !== (get(e, "tier") === "T2" ? "T2" : "T1"))
1084
+ broken.push(`${where}: says tier ${cut(pyStr(x.tier, floats, isFloat(floats, x, "tier")), 8)}, the record `
1085
+ + (truthy(get(e, "tier")) ? pyStr(e.tier, floats, isFloat(floats, e, "tier")) : "T1"));
1086
+ else {
1087
+ g.used = used;
1088
+ tiers[x.tier]++;
1089
+ }
1090
+ }
1091
+ }
1092
+ rep.check("intent grants", !bad.length && !broken.length, `${issued} grant(s)`
1093
+ + (issuers.size ? ` by ${cut([...issuers].sort(byCodePoint).join(", "), 200)}` : "")
1094
+ + (selfish ? ` (${selfish} self-approved: issued by the run's own user, which the agent can be)` : "")
1095
+ + (revoked ? `, ${revoked} revoked` : "") + `; ${tiers.T1 + tiers.T2} call(s) released within them (${tiers.T2} at `
1096
+ + `T2, decided and run by an executor or gateway; ${tiers.T1} at T1, on the arguments the harness reported), each `
1097
+ + "re-checked against its grant and its running totals", [...broken, ...bad].slice(0, 20), !broken.length);
1098
+ }
718
1099
  /**
719
1100
  * The ext names this verifier interprets (the VERSIONS rows' "ext" in tracekit/bundle_v2.py): name -> its check, whose
720
- * lines are its own: every other line of the report reads the same without them (docs/format-v2.md §9).
1101
+ * lines are its own: every other line of the report reads the same without them (docs/format-v2.md §9). Names that
1102
+ * share a check are read together, once: a grant, its revocation and the calls it released.
721
1103
  */
722
- const EXT_CHECKS = new Map([["amended", checkAmended],
723
- ["openshell.policy", checkOpenshellPolicy]]);
1104
+ const EXT_CHECKS = new Map([["amended", checkAmended], ["openshell.policy", checkOpenshellPolicy],
1105
+ ["box", checkBox], ["intent.grant", checkGrants], ["intent.revoked", checkGrants], ["grant", checkGrants]]);
724
1106
  const MAX_UNREAD = 20; // `not interpreted` lines, one per ext name; the rest on one line
725
1107
  /** A run's problems past which its later records go unchecked: forged records cost a verifier little. */
726
1108
  const RUN_PROBLEMS = 20;
727
1109
  /** The ext names an event carries: its `ext` field's keys, and an `ext` record's name. */
728
1110
  const extNames = (e) => [...Object.keys(isObj(get(e, "ext")) ? e.ext : {}),
729
1111
  ...get(e, "type") === "ext" ? [at(at(e, "data"), "name")] : []];
1112
+ const ROWS = VERSIONS_JSON, EXT_SLOT = "1.4.0", EXT_NAME = "ext name ";
1113
+ const usesSlot = (e) => Object.hasOwn(e, "ext") || get(e, "type") === "ext";
1114
+ /** The entries of `row` that `e` uses: `type`, `type.field`, `type.field=value` (by type too) and EXT_NAME + name. */
1115
+ function entries(e, row) {
1116
+ const typ = str(get(e, "type")), data = isObj(get(e, "data")) ? e.data : {};
1117
+ return [...row.types.includes(typ) ? [typ] : [],
1118
+ ...(row.fields[typ] ?? []).filter((f) => Object.hasOwn(data, f)).map((f) => `${typ}.${f}`),
1119
+ ...Object.entries(row.values[typ] ?? {}).filter(([f, vs]) => Object.hasOwn(data, f) && vs.some((v) => v === data[f]))
1120
+ .map(([f]) => `${typ}.${f}=${str(data[f])}`),
1121
+ ...extNames(e).filter((n) => (row.ext ?? []).includes(n)).map((n) => EXT_NAME + str(n))];
1122
+ }
1123
+ /** The verifier_min_version records `events` in `layout` need: the newest row whose entries other than ext names they
1124
+ * use, EXT_SLOT at least when one uses the slot. */
1125
+ function needs(events, layout) {
1126
+ const order = ["1.0.0", ...Object.keys(ROWS)];
1127
+ let need = "1.0.0";
1128
+ for (const [version, row] of Object.entries(ROWS))
1129
+ if (layout.some((x) => (row.layout ?? []).includes(x))
1130
+ || events.some((e) => entries(e, row).some((x) => !x.startsWith(EXT_NAME))))
1131
+ need = version;
1132
+ return events.some(usesSlot) && order.indexOf(need) < order.indexOf(EXT_SLOT) ? EXT_SLOT : need;
1133
+ }
1134
+ /** What makes `events` in `layout` need `version`, with the seqs of the records (the first five). */
1135
+ function raisedBy(events, version, layout) {
1136
+ const seqs = new Map();
1137
+ for (const e of events)
1138
+ for (const x of [...entries(e, ROWS[version] ?? { types: [], fields: {}, values: {} }).filter((x) => !x.startsWith(EXT_NAME)),
1139
+ ...version === EXT_SLOT && usesSlot(e) ? ["ext"] : []]) {
1140
+ if (!seqs.has(x))
1141
+ seqs.set(x, []);
1142
+ seqs.get(x).push(get(e, "seq"));
1143
+ }
1144
+ return [...[...seqs].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([x, s]) => `${x}: seq ${s.slice(0, 5).map(str)
1145
+ .join(", ")}` + (s.length > 5 ? ` and ${s.length - 5} more` : "")),
1146
+ ...layout.filter((x) => (ROWS[version]?.layout ?? []).includes(x))];
1147
+ }
1148
+ /** `verifier minimum`, a warning only when the manifest's verifier_min_version (`said`) is below what the records and
1149
+ * the layout of `names` need: the manifest is never signed, and edited down it lets an older verifier claim more. A
1150
+ * record it can't read (no type, data or seq: other checks fail it) needs nothing. */
1151
+ function checkMinimum(rep, all, names, said) {
1152
+ const events = all.filter((e) => isObj(e) && typeof e.type === "string" && Object.hasOwn(e, "seq") && isObj(e.data)
1153
+ && (e.type !== "ext" || Object.hasOwn(e.data, "name")));
1154
+ const layout = names.some((n) => PART.test(n)) ? ["run parts"] : [], need = needs(events, layout);
1155
+ if (need !== "1.0.0" && newer(need, said)) // a row raised it (0.x bundles need the base)
1156
+ rep.check("verifier minimum", false, `the records need tracekit >= ${need}, the manifest asks for ${said}: a verifier `
1157
+ + `older than ${need} may have read this bundle and claimed more than its records show`, raisedBy(events, need, layout).slice(0, 20), true);
1158
+ }
730
1159
  /**
731
1160
  * A line per ext name the records carry: its EXT_CHECKS check, or a `not interpreted` warning. The records were checked
732
- * like every other (signature, chain, inclusion); `full`: the manifest's advisory verifier_version.
1161
+ * like every other (signature, chain, inclusion); `full`: the manifest's advisory verifier_version; `floats`: the
1162
+ * parser's.
733
1163
  */
734
- function checkExt(rep, events, full) {
1164
+ export async function checkExt(rep, events, full, floats) {
735
1165
  const carry = new Map(); // name -> the events carrying it
736
1166
  for (const e of events)
737
1167
  for (const n of new Set(extNames(e).map((x) => cut(str(x), 64)))) {
@@ -739,13 +1169,23 @@ function checkExt(rep, events, full) {
739
1169
  carry.set(n, []);
740
1170
  carry.get(n).push(e);
741
1171
  }
742
- const later = typeof full === "string" && /^\d{1,9}(\.\d{1,9}){0,2}$/.test(full) && newer(full, VERSION)
1172
+ const later = typeof full === "string" && /^\d{1,9}(\.\d{1,9}){0,2}$/.test(full) && newer(full, READS)
743
1173
  ? `; tracekit >= ${full} checks it` : "";
744
1174
  let shown = 0, more = 0;
1175
+ const done = new Set();
1176
+ // records a check reads beside its names' own: the decisions TK-GRANT names, ext.grant or not
1177
+ const also = new Map([[checkGrants, events.filter(tkGrant)]]);
1178
+ const run = async (f) => {
1179
+ done.add(f);
1180
+ await f(rep, [...new Set([...[...carry].filter(([k]) => EXT_CHECKS.get(k) === f).flatMap(([, v]) => v),
1181
+ ...also.get(f) ?? []])], floats);
1182
+ };
745
1183
  for (const [n, es] of [...carry].sort(byKey)) {
746
1184
  const interpret = EXT_CHECKS.get(n);
747
- if (interpret)
748
- interpret(rep, es);
1185
+ if (interpret) {
1186
+ if (!done.has(interpret))
1187
+ await run(interpret);
1188
+ }
749
1189
  else if (shown < MAX_UNREAD) {
750
1190
  shown++;
751
1191
  rep.check("not interpreted", false, `${es.length} record(s) carry ext.${n}: their signatures, chain and `
@@ -757,6 +1197,9 @@ function checkExt(rep, events, full) {
757
1197
  if (more)
758
1198
  rep.check("not interpreted", false, `${more} more ext name(s), on records whose signatures, chain and inclusion `
759
1199
  + `are checked above; what they mean is not checked${later}`, [], true);
1200
+ for (const [f, extra] of also) // a check whose names no record carries reads what it reads beside them
1201
+ if (extra.length && !done.has(f))
1202
+ await run(f);
760
1203
  }
761
1204
  /** Approvals by people and by agents, each on a line of its own. An agent's approval fails the line unless its run
762
1205
  * holds the approval.request and policy.decision it answered, the signer called the request agent-eligible
@@ -1117,10 +1560,11 @@ function honoured(events, pointers) {
1117
1560
  return problems;
1118
1561
  }
1119
1562
  /** §4: null when `r` is a v2 record signed by one of `keys` (SPKI DER) with an allowed algorithm that is the key's own,
1120
- * else why not. */
1121
- export async function verifyRecord(r, keys, algs) {
1563
+ * else why not. `floats`: where the parser read number tokens with a fraction or exponent (`v` is the integer 2). */
1564
+ export async function verifyRecord(r, keys, algs, floats) {
1122
1565
  if (!isObj(r) || Object.keys(r).length !== 6 || !["v", "event", "hash", "alg", "kid", "sig"].every((k) => Object.hasOwn(r, k))
1123
- || !same(r.v, 2) || !isObj(r.event) || !["hash", "alg", "kid", "sig"].every((k) => typeof r[k] === "string"))
1566
+ || !same(r.v, 2) || floats?.get(r)?.has("v") || !isObj(r.event)
1567
+ || !["hash", "alg", "kid", "sig"].every((k) => typeof r[k] === "string"))
1124
1568
  return "not a v2 record";
1125
1569
  let h;
1126
1570
  try {
@@ -1342,8 +1786,10 @@ async function assurance(origin, cosigs, witnesses, trust, algs, selfApproved, r
1342
1786
  /** `x` without control characters and the bidirectional and zero-width format characters that would reorder or hide
1343
1787
  * the text around them, as the report prints bundle-derived strings. */
1344
1788
  export const clean = (x) => x.replace(/[\x00-\x1f\x7f-\x9f\u061c\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, "");
1345
- /** The Assurance line as the reports print it: an assurance level rates only evidence that verified. */
1346
- export const assuranceLine = (rep) => `Assurance: ${rep.integrity === "FAILED" ? "not rated (the bundle failed verification)" : clean(rep.assurance)}.`;
1789
+ /** A failed bundle's assurance: a level rates only evidence that verified. */
1790
+ export const NOT_RATED = "not rated (the bundle failed verification)";
1791
+ /** The Assurance line as the reports print it. */
1792
+ export const assuranceLine = (rep) => `Assurance: ${rep.integrity === "FAILED" ? NOT_RATED : clean(rep.assurance)}.`;
1347
1793
  /** The report as text, as the reference CLI prints it; `clean` drops characters from bundle-derived strings. */
1348
1794
  export function formatReport(rep) {
1349
1795
  let s = "";