@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.
- package/README.md +6 -3
- package/dist/v2/adapters/claude-agent-sdk.d.ts +9 -2
- package/dist/v2/adapters/claude-agent-sdk.js +15 -6
- package/dist/v2/client.d.ts +5 -0
- package/dist/v2/client.js +14 -0
- package/dist/v2/executor.d.ts +2 -1
- package/dist/v2/executor.js +2 -1
- package/dist/v2/rpc_schema.d.ts +1 -1
- package/dist/v2/rpc_schema.js +7 -3
- package/dist/verify/detect.js +9 -1
- package/dist/verify/explain.js +20 -3
- package/dist/verify/index.d.ts +57 -5
- package/dist/verify/index.js +471 -25
- package/dist/verify/primitives.js +5 -2
- package/dist/verify/versions.json +7 -0
- package/dist/verify.html +507 -33
- package/package.json +5 -5
package/dist/verify.html
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8">
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
-
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-
|
|
6
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-JnXZqC3vw5PF4pZ90tcPCZPJIFlCtqUs6ZwQvlLzCIc='; style-src 'sha256-41aEPfNKIK0vxFn3JTgv68G+SOVBoDbHT4QPLHGL360='; worker-src blob:; connect-src 'none'">
|
|
7
7
|
<title>tracekit verify</title>
|
|
8
8
|
<style>
|
|
9
9
|
:root {
|
|
@@ -569,8 +569,11 @@ async function openNote(data, logKeys, witnessKeys, anchored = true) {
|
|
|
569
569
|
hybrids.delete(id);
|
|
570
570
|
}
|
|
571
571
|
else {
|
|
572
|
-
|
|
573
|
-
if (
|
|
572
|
+
// not a timestamp and a signature: damaged, whatever the log holds (tracekit/format/checkpoint.py)
|
|
573
|
+
if (sig.length !== 72)
|
|
574
|
+
throw new NoteError(`malformed cosignature from pinned witness ${name}`);
|
|
575
|
+
const ts = new DataView(sig.buffer, sig.byteOffset).getBigUint64(0);
|
|
576
|
+
if (!await verifyV2("ed25519", spkiOf(p.pub), bytes(`cosignature/v1\ntime ${ts}\n${text}`), sig.subarray(8)))
|
|
574
577
|
throw new NoteError(`bad cosignature from pinned witness ${name}`);
|
|
575
578
|
cosigs.push([k, ts]);
|
|
576
579
|
}
|
|
@@ -626,6 +629,14 @@ function glob(pat) {
|
|
|
626
629
|
}
|
|
627
630
|
return new RegExp(`^${out}$`, "u");
|
|
628
631
|
}
|
|
632
|
+
/** The owner of the run whose run.registered is `e`: the identity it records, but box:<uid>/<box id> for a run of a
|
|
633
|
+
* Tracekit Box box's agent channel (ext.box with parent_run), whose record names the daemon (tracekit/signer/detect.py
|
|
634
|
+
* recorded_owner). */
|
|
635
|
+
function recordedOwner(e) {
|
|
636
|
+
const i = e.data.identity, ext = e.ext, box = typeof ext === "object" && ext !== null ? ext.box : undefined;
|
|
637
|
+
return typeof box === "object" && box !== null && !Array.isArray(box) && typeof box.id === "string"
|
|
638
|
+
&& Object.hasOwn(e.data, "parent_run") ? `box:${i.subject}/${box.id}` : `${i.scheme}:${i.subject}`;
|
|
639
|
+
}
|
|
629
640
|
class Detector {
|
|
630
641
|
label = new Map();
|
|
631
642
|
untrusted = new Set();
|
|
@@ -694,7 +705,7 @@ class Detector {
|
|
|
694
705
|
const typ = e.type, d = e.data, rk = `${e.tenant}\0${e.run_id}`, t = ts(e.ts), fired = [];
|
|
695
706
|
const run = det.runs.get(rk) ?? null;
|
|
696
707
|
if (typ === "run.registered") {
|
|
697
|
-
det.runs.set(rk, { session: d.session ?? e.run_id, owner:
|
|
708
|
+
det.runs.set(rk, { session: d.session ?? e.run_id, owner: recordedOwner(e),
|
|
698
709
|
principal: e.principal_attested ? e.principal ?? null : null, pending: new Map(), n: new Map(),
|
|
699
710
|
capped: new Map(), minute: [0, 0, false] });
|
|
700
711
|
}
|
|
@@ -1162,8 +1173,10 @@ const __index = (() => {
|
|
|
1162
1173
|
* Monitor reports, revocations and the v1 format bridge are inputs of the reference's CLI that this one doesn't take.
|
|
1163
1174
|
* A bundle that needs a newer verifier is UNVERIFIABLE, with the commands that verify it; one whose records carry ext
|
|
1164
1175
|
* names this verifier doesn't interpret (format 1.4's non-critical slot) verifies, with a `not interpreted` warning
|
|
1165
|
-
* per name; it interprets `amended` (the fields an LLM gateway changed in a request to show reasoning)
|
|
1166
|
-
* `openshell.policy` (OpenShell's sandbox policy changes, from the OpenShell middleware's OCSF import)
|
|
1176
|
+
* per name; it interprets `amended` (the fields an LLM gateway changed in a request to show reasoning),
|
|
1177
|
+
* `openshell.policy` (OpenShell's sandbox policy changes, from the OpenShell middleware's OCSF import), `box` (a
|
|
1178
|
+
* Tracekit Box box's run label) and `intent.grant`, `intent.revoked` and `grant` (intent grants and the calls they
|
|
1179
|
+
* released).
|
|
1167
1180
|
* `verify(bundle, null)` (no trust config) checks what needs no pinned key and is never VERIFIED. web.ts is this
|
|
1168
1181
|
* verifier as a browser page (verify.html).
|
|
1169
1182
|
*/
|
|
@@ -1172,10 +1185,14 @@ const { HYBRID: HYBRID, NoteError: NoteError, SIGNER_LEAVES: SIGNER_LEAVES, b64d
|
|
|
1172
1185
|
const { Detector: Detector } = __detect;
|
|
1173
1186
|
const { same: same, validateEvent: validateEvent } = __schema;
|
|
1174
1187
|
const { BadZipFile: BadZipFile, MAX_ENTRY: MAX_ENTRY, Unusable: Unusable, readZip: readZip } = __zip;
|
|
1188
|
+
const VERSIONS_JSON = {"1.1.0":{"types":["input.observed","content.accessed","content.erased","why.finding"],"fields":{"policy.decision":["provenance","provenance_state"],"run.registered":["replay_of"]},"values":{}},"1.2.0":{"types":["run.child","approval.escalated","approval.revoked","approval.suggested","approval.agents","incident.opened","incident.updated","incident.capped","run.held","run.resumed","run.quarantined","incident.resolved","incident.response","identity.suspension","effect.observed"],"fields":{"run.registered":["parent_run","session","posture"],"capture.gap":["run_id"],"run.final":["provider_executed","paired_by_args","matrix"],"policy.decision":["via","caller","detect","incident_id"],"approval.request":["agent","via","incident_id","passkey"],"tool.result":["via"],"input.observed":["via"],"approval":["approver_kind","asserted","spent","not_before","consume_by","incident_id"],"approval.expired":["reason"],"reconcile.unexplained_effect":["observer","kind","host","port"]},"values":{"capture.gap":{"kind":["decided_not_completed","late_activity","concurrent_run","tailer_redelegated","reask_after_reject","held_call_unresolved","observer_lost","effect_outside_run"]},"run.closing":{"reason":["quarantine"]}}},"1.3.0":{"types":["reconcile.result_mismatch"],"fields":{},"values":{"capture.gap":{"kind":["result_unchecked"]}}},"1.4.0":{"types":["constraint.added"],"fields":{"effect.observed":["sensor","denied"],"review":["cites"],"model.exchange":["said_only"],"capture.gap":["sensor"]},"values":{"capture.gap":{"kind":["constraint_refused"]}},"ext":["amended","openshell.policy"],"layout":["run parts"]},"1.6.0":{"types":[],"fields":{},"values":{"ext":{"self_approved":[true]}},"ext":["box","grant","intent.grant","intent.revoked"]}};
|
|
1175
1189
|
|
|
1176
1190
|
|
|
1177
|
-
/**
|
|
1178
|
-
const VERSION = "1.
|
|
1191
|
+
/** This verifier's release (the package's). */
|
|
1192
|
+
const VERSION = "1.6.0";
|
|
1193
|
+
/** The newest bundle format version this verifier reads: the reference's VERSIONS' newest row (tracekit/bundle_v2.py),
|
|
1194
|
+
* or VERSION when later (tracekit/verify/v2.py READS); a bundle needing a later one is UNVERIFIABLE. */
|
|
1195
|
+
const READS = "1.6.0";
|
|
1179
1196
|
/** The browser verifier of the latest release (docs/RELEASING.md). */
|
|
1180
1197
|
const PAGE = "https://cygnux-labs.github.io/Tracekit/verify/";
|
|
1181
1198
|
const EXIT_OK = 0, EXIT_FAIL = 1, EXIT_BAD = 2, EXIT_WARN = 3;
|
|
@@ -1215,6 +1232,10 @@ class Report {
|
|
|
1215
1232
|
findings = null;
|
|
1216
1233
|
/** Checks the bundle needs that this verifier does not implement. */
|
|
1217
1234
|
unsupported = [];
|
|
1235
|
+
/** For the box check: the pinned witnesses' cosignatures of the checkpoint, `name (class) at time`, and the seqs of
|
|
1236
|
+
* the bundle's own runs' first records. */
|
|
1237
|
+
anchored = [];
|
|
1238
|
+
firsts = new Set();
|
|
1218
1239
|
check(check, ok, detail = "", problems = [], warn = false) {
|
|
1219
1240
|
this.checks.push({ check, status: ok ? "pass" : warn ? "warn" : "fail", detail, problems });
|
|
1220
1241
|
if (!ok)
|
|
@@ -1435,7 +1456,7 @@ async function verify(bundle, trust, names = { bundle: "BUNDLE", trust: "TRUST.j
|
|
|
1435
1456
|
const need = manifest.verifier_min_version;
|
|
1436
1457
|
if (!(typeof need === "string" && /^\d{1,9}(\.\d{1,9}){0,2}$/.test(need)))
|
|
1437
1458
|
throw new Unusable("verifier_min_version is not a version number");
|
|
1438
|
-
if (newer(need,
|
|
1459
|
+
if (newer(need, READS)) {
|
|
1439
1460
|
rep.integrity = `UNVERIFIABLE (needs tracekit >= ${need})`;
|
|
1440
1461
|
rep.check("bundle readable", false, rep.integrity, upgrade(need, names));
|
|
1441
1462
|
return { report: rep, code: EXIT_BAD };
|
|
@@ -1538,11 +1559,11 @@ async function check(rep, manifest, files, trust, floats) {
|
|
|
1538
1559
|
&& (k.until === null || seq <= num(k.until))).map((k) => k.spki);
|
|
1539
1560
|
/** Signature, schema and log membership of one record under `keys`, the SPKIs valid at its position. */
|
|
1540
1561
|
const checkRecord = async (r, keys, problems) => {
|
|
1541
|
-
const err = await verifyRecord(r, keys, trust.algs);
|
|
1562
|
+
const err = await verifyRecord(r, keys, trust.algs, floats);
|
|
1542
1563
|
if (err) {
|
|
1543
1564
|
const seq = err === "unknown kid" ? get(r.event, "seq") : null; // a well-formed record by then
|
|
1544
1565
|
const retired = [...timeline.values()].filter((k) => Number.isInteger(seq) && k.until !== null && k.until < seq);
|
|
1545
|
-
if (retired.length && !await verifyRecord(r, retired.map((k) => k.spki), trust.algs))
|
|
1566
|
+
if (retired.length && !await verifyRecord(r, retired.map((k) => k.spki), trust.algs, floats))
|
|
1546
1567
|
problems.push(`seq ${seq}: signed by key ${cut(r.kid, 80)} after its key.retire`);
|
|
1547
1568
|
else
|
|
1548
1569
|
problems.push(`seq ${repr(get(get(r, "event", {}), "seq"))}: ${err}`);
|
|
@@ -1572,6 +1593,10 @@ async function check(rep, manifest, files, trust, floats) {
|
|
|
1572
1593
|
keyProblems.push(`seq ${e.seq}: key ${cut(str(k.kid), 80)} has no certificate, and the trust config pins issuers`);
|
|
1573
1594
|
continue;
|
|
1574
1595
|
}
|
|
1596
|
+
if (has(k, "cert") && !trust.issuers.length) { // §11 step 5: no pinned issuer can have signed it
|
|
1597
|
+
keyProblems.push(`seq ${e.seq}: key ${cut(str(k.kid), 80)}: certificate not signed by a pinned issuer`);
|
|
1598
|
+
continue;
|
|
1599
|
+
}
|
|
1575
1600
|
// lean: a certified key is taken as declared and the bundle left UNVERIFIABLE; port docs/issuer.md's checks
|
|
1576
1601
|
// (issuance log notes, validity, tenants, revocations) when certified record keys are in use
|
|
1577
1602
|
if (has(k, "cert"))
|
|
@@ -1579,14 +1604,14 @@ async function check(rep, manifest, files, trust, floats) {
|
|
|
1579
1604
|
declared.set(k.kid, { spki: der, from: e.seq, until: null });
|
|
1580
1605
|
}
|
|
1581
1606
|
}
|
|
1582
|
-
|
|
1583
|
-
if (e.type === "key.retire") {
|
|
1607
|
+
if (e.type === "key.retire") { // first: a key.retire is a record too, valid only under a key valid at its seq
|
|
1584
1608
|
const kid = at(at(e, "data"), "kid");
|
|
1585
1609
|
if (!timeline.has(kid))
|
|
1586
1610
|
keyProblems.push(`seq ${e.seq}: retires an unknown key`);
|
|
1587
1611
|
else
|
|
1588
1612
|
timeline.get(kid).until = at(e.data, "last_seq");
|
|
1589
1613
|
}
|
|
1614
|
+
await checkRecord(r, [...keysAt(e.seq), ...[...declared.values()].map((k) => k.spki)], keyProblems);
|
|
1590
1615
|
for (const [kid, k] of declared)
|
|
1591
1616
|
timeline.set(kid, k);
|
|
1592
1617
|
}
|
|
@@ -1683,7 +1708,9 @@ async function check(rep, manifest, files, trust, floats) {
|
|
|
1683
1708
|
rep.integrity = !open.length ? "VERIFIED" : only ? `VERIFIED TO HEAD ${str(get(open[0].at(-1).event, "run_seq"))} (open)`
|
|
1684
1709
|
: `VERIFIED (${open.length} run(s) open)`;
|
|
1685
1710
|
const events = every.map((r) => r.event), typed = (t) => events.filter((e) => get(e, "type") === t);
|
|
1686
|
-
|
|
1711
|
+
// a grant the run's own user issued (intent.grant) approves the calls it releases: a self-approval too
|
|
1712
|
+
const selfApproved = [...typed("approval"), ...typed("ext").filter((e) => get(at(e, "data"), "name") === "intent.grant")]
|
|
1713
|
+
.some((e) => get(at(e, "data"), "self_approved") === true);
|
|
1687
1714
|
const gaps = (k) => typed("capture.gap").filter((e) => get(at(e, "data"), "kind") === k)
|
|
1688
1715
|
.map((e) => `seq ${e.seq}: ${cut(str(get(e.data, "reason")), 200)}`);
|
|
1689
1716
|
const against = gaps("executed_against_policy");
|
|
@@ -1817,8 +1844,12 @@ async function check(rep, manifest, files, trust, floats) {
|
|
|
1817
1844
|
if (glass.length)
|
|
1818
1845
|
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 `
|
|
1819
1846
|
+ `${cut(text(at(e.data, "approver")), 256)}: ${repr(cut(str(get(e.data, "reason")), 200))}`).slice(0, 20), true);
|
|
1820
|
-
|
|
1821
|
-
|
|
1847
|
+
rep.anchored = [...cosigs].sort((a, b) => a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)
|
|
1848
|
+
.map(([k, ts]) => `${k.split("+")[0]} (${witnesses.get(k)}) at ${fmt(ts)}`);
|
|
1849
|
+
rep.firsts = new Set(firsts.map((e) => at(e, "seq")));
|
|
1850
|
+
const all = [...new Map([...keyRecords, ...pointed, ...every].map((r) => [at(at(r, "event"), "seq"), r.event])).values()];
|
|
1851
|
+
await checkExt(rep, all, get(manifest, "verifier_version"), floats);
|
|
1852
|
+
checkMinimum(rep, all, [...files.keys()], str(get(manifest, "verifier_min_version")));
|
|
1822
1853
|
}
|
|
1823
1854
|
/**
|
|
1824
1855
|
* ext.amended: the JSON pointers of the fields an LLM gateway changed in a model request before sending it, to show the
|
|
@@ -1865,23 +1896,433 @@ function checkOpenshellPolicy(rep, events) {
|
|
|
1865
1896
|
+ `${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 `
|
|
1866
1897
|
+ "recorded").slice(0, 20), true);
|
|
1867
1898
|
}
|
|
1899
|
+
/** A Tracekit Box engine, as verify names what its box is (tracekit/signer/service.py ENGINES). */
|
|
1900
|
+
const ENGINES = { firecracker: "micro-VM" };
|
|
1901
|
+
const BOXED = "PROOF AGAINST THE BOXED AGENT";
|
|
1902
|
+
const DOORS = "the box's doors (its connections and file writes)";
|
|
1903
|
+
/**
|
|
1904
|
+
* Whether `e` carries ext.box as the signer writes it: on run.registered only, {id, image_digest, allow, engine,
|
|
1905
|
+
* channel?}, under a Box daemon's identity (a uid): its box run, or with parent_run a run of its box's agent channel.
|
|
1906
|
+
*/
|
|
1907
|
+
function boxLabel(e) {
|
|
1908
|
+
const v = isObj(get(e, "ext")) ? get(e.ext, "box") : null, d = get(e, "data");
|
|
1909
|
+
const i = isObj(d) ? get(d, "identity") : null, keys = isObj(v) ? Object.keys(v) : [];
|
|
1910
|
+
return get(e, "type") === "run.registered" && isObj(v) && isObj(i) && get(i, "scheme") === "uid"
|
|
1911
|
+
&& ["id", "image_digest", "allow", "engine"].every((k) => keys.includes(k))
|
|
1912
|
+
&& keys.every((k) => ["id", "image_digest", "allow", "engine", "channel"].includes(k))
|
|
1913
|
+
&& typeof v.id === "string" && /^[A-Za-z0-9._:-]{1,128}$/.test(v.id) && typeof v.image_digest === "string"
|
|
1914
|
+
&& /^sha256:[0-9a-f]{64}$/.test(v.image_digest) && Array.isArray(v.allow)
|
|
1915
|
+
&& v.allow.every((a) => typeof a === "string") && typeof v.engine === "string"
|
|
1916
|
+
&& Object.hasOwn(ENGINES, v.engine) && (!Object.hasOwn(v, "channel") || v.channel === "agent");
|
|
1917
|
+
}
|
|
1918
|
+
/**
|
|
1919
|
+
* 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
|
|
1920
|
+
* own config) and of each run its agent channel registered (a copy, with parent_run). The signing key was outside that
|
|
1921
|
+
* box, so the runs are proof against the agent in it, and no more: an agent run's records are its own account, the
|
|
1922
|
+
* box's doors held it, and anything running as the daemon's or the signer's user on the host is outside the claim.
|
|
1923
|
+
* Anywhere else, or in another shape, a warning and no claim. Only the bundle's own runs are claimed for
|
|
1924
|
+
* (rep.firsts): a run-set's records of other runs carry their labels too.
|
|
1925
|
+
*/
|
|
1926
|
+
function checkBox(rep, events) {
|
|
1927
|
+
const bad = events.filter((e) => !boxLabel(e));
|
|
1928
|
+
if (bad.length) {
|
|
1929
|
+
rep.check("boxed agent", false, `${bad.length} record(s) carry ext.box where or how the signer never writes it: `
|
|
1930
|
+
+ "no proof against a boxed agent", bad.map((e) => `seq ${str(get(e, "seq"))}: ext.box is not a box's label on `
|
|
1931
|
+
+ "its run.registered").slice(0, 20), true);
|
|
1932
|
+
return;
|
|
1933
|
+
}
|
|
1934
|
+
const good = events.filter((e) => rep.firsts.has(get(e, "seq")));
|
|
1935
|
+
if (!good.length)
|
|
1936
|
+
return; // labels of runs this bundle doesn't hold
|
|
1937
|
+
const one = good.length === 1, agent = good.some((e) => Object.hasOwn(e.data, "parent_run"));
|
|
1938
|
+
const kinds = [...new Set(good.map((e) => ENGINES[e.ext.box.engine]))].sort(byCodePoint).join(", ");
|
|
1939
|
+
rep.check("boxed agent", true, `${BOXED} (${kinds}): the signing key was outside its box for `
|
|
1940
|
+
+ `${one ? "this run" : `these ${good.length} runs`}.`, [one && agent
|
|
1941
|
+
? `This run's records are the agent's own account of its calls; ${DOORS} are the record of what it could do.`
|
|
1942
|
+
: one ? `This run's records are ${DOORS}, as the Box daemon recorded them.`
|
|
1943
|
+
: `In these runs, the agent's records are its own account of its calls; ${DOORS} are the record of what it `
|
|
1944
|
+
+ "could do.",
|
|
1945
|
+
"Before you run anything the box wrote, review it: code you run on this machine can reach the key.",
|
|
1946
|
+
...rep.anchored.map((a) => `anchored by ${a}`)]);
|
|
1947
|
+
}
|
|
1948
|
+
/** Whether the parser read `o[k]` as a number token with a fraction or exponent: Python's float, never an int. */
|
|
1949
|
+
const isFloat = (floats, o, k) => !!floats.get(o)?.has(k);
|
|
1950
|
+
const NO_FLOATS = new WeakMap(); // for values this verifier computed
|
|
1951
|
+
/** A number as Python prints it: a float-written whole number with `.0`. */
|
|
1952
|
+
// lean: integral floats below 1e16 only; Python's repr of others (1e+16, 1e-05) differs from JavaScript's
|
|
1953
|
+
const pyNum = (v, float) => float && Number.isInteger(v) && Math.abs(v) < 1e16 ? `${v}.0` : JSON.stringify(v);
|
|
1954
|
+
/** Python's json.dumps(v), as the reference's messages print values: ", " and ": " between items, and every character
|
|
1955
|
+
* past ASCII escaped; `float`: v was written as a float. */
|
|
1956
|
+
function dumps(v, floats = NO_FLOATS, float = false) {
|
|
1957
|
+
if (Array.isArray(v))
|
|
1958
|
+
return `[${v.map((x, i) => dumps(x, floats, isFloat(floats, v, i))).join(", ")}]`;
|
|
1959
|
+
if (isObj(v))
|
|
1960
|
+
return `{${Object.entries(v).map(([k, x]) => `${dumps(k)}: ${dumps(x, floats, isFloat(floats, v, k))}`)
|
|
1961
|
+
.join(", ")}}`;
|
|
1962
|
+
if (typeof v === "number")
|
|
1963
|
+
return pyNum(v, float);
|
|
1964
|
+
return JSON.stringify(v).replace(/[\x7f-\uffff]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"));
|
|
1965
|
+
}
|
|
1966
|
+
/** Python's str(v), as an f-string prints a value: a list or an object with its items' repr (`['g-1', None]`). */
|
|
1967
|
+
function pyStr(v, floats = NO_FLOATS, float = false) {
|
|
1968
|
+
const item = (x, f) => typeof x === "string" ? quoted(x) : pyStr(x, floats, f);
|
|
1969
|
+
return Array.isArray(v) ? `[${v.map((x, i) => item(x, isFloat(floats, v, i))).join(", ")}]`
|
|
1970
|
+
: isObj(v) ? `{${Object.entries(v).map(([k, x]) => `${quoted(k)}: ${item(x, isFloat(floats, v, k))}`).join(", ")}}`
|
|
1971
|
+
: typeof v === "number" ? pyNum(v, float) : str(v);
|
|
1972
|
+
}
|
|
1973
|
+
// intent grants (docs/intent-grants.md), as tracekit/grants.py and tracekit/pcm read them; payments are the one intent
|
|
1974
|
+
/** The minor units of each currency an amount is shown in (grants.DECIMALS). */
|
|
1975
|
+
const DECIMALS = { USD: 2, EUR: 2, GBP: 2, INR: 2, CAD: 2, AUD: 2, CHF: 2, SGD: 2, JPY: 0,
|
|
1976
|
+
USDC: 6, USDT: 6 };
|
|
1977
|
+
/** payment.send's schema document (grants.PAYMENT): a grant's intent names its hash. */
|
|
1978
|
+
const PAYMENT = { pcm_schema: 0, name: "payment.send", grant: true, fields: {
|
|
1979
|
+
amount: { type: "int", min: 1, max: Number.MAX_SAFE_INTEGER },
|
|
1980
|
+
currency: { type: "id", pattern: "[A-Z][A-Z0-9]{2,9}" },
|
|
1981
|
+
payee: { type: "id", pattern: "[A-Za-z0-9._:@/+=-]{1,128}" }
|
|
1982
|
+
} };
|
|
1983
|
+
const FIELDS = PAYMENT.fields;
|
|
1984
|
+
const CAVEAT_OPS = { int: ["==", "<=", ">=", "<", ">"], id: ["==", "in"] };
|
|
1985
|
+
const GRANT_KEYS = ["name", "id", "grant", "tools", "limits", "used", "self_approved", "first", "description"];
|
|
1986
|
+
const MAX_TOOLS = 16; // the tools one grant names (grants.MAX_TOOLS)
|
|
1987
|
+
const ID_RE = /^[A-Za-z0-9._:-]{1,128}$/, NAME_RE = /^[a-z][a-z0-9_]{0,63}$/;
|
|
1988
|
+
// rpc_schema.TS, whose \d Python's re reads as any decimal digit
|
|
1989
|
+
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;
|
|
1990
|
+
/** Whether `o` is an object with every key of `need` and no key outside `need` and `may` (a closed JSON Schema). */
|
|
1991
|
+
const shaped = (o, need, may = []) => isObj(o) && need.every((k) => Object.hasOwn(o, k))
|
|
1992
|
+
&& Object.keys(o).every((k) => need.includes(k) || may.includes(k));
|
|
1993
|
+
/** Whether `v` is a string of at most `n` characters, all of it matching `re`. */
|
|
1994
|
+
const short = (v, n, re) => typeof v === "string" && [...v].length <= n && (!re || re.test(v));
|
|
1995
|
+
const opt = (o, k, ok) => !Object.hasOwn(o, k) || ok(o[k]);
|
|
1996
|
+
/** A PCM grant as rpc_schema.PCM_GRANT has it. */
|
|
1997
|
+
const isPcmGrant = (g, floats) => shaped(g, ["pcm_grant", "ts", "issuer", "subject", "intent", "caveats",
|
|
1998
|
+
"expires_at", "delegable", "parent", "sig"]) && g.pcm_grant === 0 && !isFloat(floats, g, "pcm_grant")
|
|
1999
|
+
&& short(g.ts, 27, TS_RE) && short(g.expires_at, 27, TS_RE)
|
|
2000
|
+
&& shaped(g.issuer, ["kind", "id", "run", "tenant"], ["person", "approval_id"])
|
|
2001
|
+
&& ["person", "agent"].includes(g.issuer.kind) && short(g.issuer.id, 256) && opt(g.issuer, "person", (v) => short(v, 256))
|
|
2002
|
+
&& short(g.issuer.run, 128, ID_RE) && short(g.issuer.tenant, 128, ID_RE)
|
|
2003
|
+
&& opt(g.issuer, "approval_id", (v) => short(v, 128, ID_RE)) && short(g.subject, 256, /^[a-z0-9_]+:[^\n]+$/)
|
|
2004
|
+
&& short(g.intent, 136, /^[a-z][a-z0-9_.-]{0,63}@sha256:[0-9a-f]{64}$/) && Array.isArray(g.caveats)
|
|
2005
|
+
&& g.caveats.length <= 16 && g.caveats.every((c) => shaped(c, ["field", "op", "value"]) && short(c.field, 64, NAME_RE)
|
|
2006
|
+
&& ["==", "<=", ">=", "<", ">", "in"].includes(c.op)) && typeof g.delegable === "boolean"
|
|
2007
|
+
&& (g.parent === null || short(g.parent, 71, /^sha256:[0-9a-f]{64}$/))
|
|
2008
|
+
&& shaped(g.sig, ["key", "sig"]) && short(g.sig.key, 300) && g.sig.key !== "" && short(g.sig.sig, 88);
|
|
2009
|
+
/** A grant's limits as rpc_schema._LIMITS has them. */
|
|
2010
|
+
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))
|
|
2011
|
+
&& Number.isSafeInteger(x.max) && !isFloat(floats, x, "max") && x.max >= 1);
|
|
2012
|
+
/** pcm._FITS: whether `v` is a valid value of field `f`; `float`: v was written as a float, which is no int. */
|
|
2013
|
+
// lean: the int and id rules, the types payment.send uses; port the rest with an intent whose fields use them
|
|
2014
|
+
const fits = (f, v, float) => f.type === "int" ? Number.isInteger(v) && !float && f.min <= v && v <= f.max
|
|
2015
|
+
: typeof v === "string" && [...v].length <= 128 && new RegExp(`^(?:${f.pattern})$`).test(v);
|
|
2016
|
+
/** pcm.check_args of payment.send: what is wrong with call `fields`, an object. */
|
|
2017
|
+
function argErrors(fields, floats) {
|
|
2018
|
+
const out = Object.keys(fields).filter((k) => !Object.hasOwn(FIELDS, k)).map((k) => `args.${k}: not in the schema`);
|
|
2019
|
+
for (const [k, f] of Object.entries(FIELDS)) {
|
|
2020
|
+
if (!Object.hasOwn(fields, k))
|
|
2021
|
+
out.push(`args.${k}: missing`);
|
|
2022
|
+
else if (!fits(f, fields[k], isFloat(floats, fields, k)))
|
|
2023
|
+
out.push(`args.${k}: ${dumps(fields[k], floats, isFloat(floats, fields, k)).slice(0, 64)} is not a valid ${f.type}`);
|
|
2024
|
+
}
|
|
2025
|
+
return out;
|
|
2026
|
+
}
|
|
2027
|
+
/** A grant's short id (grants.grant_id): `g-` and the first 16 hex digits of its hash. */
|
|
2028
|
+
const grantId = async (g) => "g-" + (await sha256hex(bytes(canonicalize(g)))).slice(0, 16);
|
|
2029
|
+
/** grants.number: minor units as the number a person reads (`200`, `0.5`); the minor units for an unknown currency. */
|
|
2030
|
+
function number(minor, cur) {
|
|
2031
|
+
const d = typeof cur === "string" && Object.hasOwn(DECIMALS, cur) ? DECIMALS[cur] : null;
|
|
2032
|
+
if (d === null || !Number.isInteger(minor))
|
|
2033
|
+
return dumps(minor).slice(0, 32);
|
|
2034
|
+
const frac = minor % 10 ** d;
|
|
2035
|
+
return `${(minor - frac) / 10 ** d}` + (frac ? "." + String(frac).padStart(d, "0").replace(/0+$/, "") : "");
|
|
2036
|
+
}
|
|
2037
|
+
/** grants.show: minor units as a person reads them (`200 USDC`), by name for an unknown currency. */
|
|
2038
|
+
const show = (minor, cur) => `${number(minor, cur)} `
|
|
2039
|
+
+ (typeof cur === "string" && Object.hasOwn(DECIMALS, cur) && Number.isInteger(minor) ? cur : `${str(cur)} (minor units)`);
|
|
2040
|
+
/** grants.problems for a payment grant, as a verifier asks (no ceiling), of caveats and limits already of their shape;
|
|
2041
|
+
* `tools`: the record's, the tools whose calls the grant covers. */
|
|
2042
|
+
function grantProblems(caveats, limits, tools, expiresAt, now, floats) {
|
|
2043
|
+
const out = [], pinned = new Map(), seen = new Set();
|
|
2044
|
+
for (const c of caveats) { // pcm.check_caveats
|
|
2045
|
+
const f = Object.hasOwn(FIELDS, c.field) ? FIELDS[c.field] : null, vals = c.op === "in" ? c.value : [c.value];
|
|
2046
|
+
const said = `${c.field} ${c.op} ${dumps(c.value, floats, isFloat(floats, c, "value")).slice(0, 64)}`;
|
|
2047
|
+
if (!f)
|
|
2048
|
+
out.push(`${said}: no field ${c.field} in payment.send`);
|
|
2049
|
+
else if (!CAVEAT_OPS[f.type].includes(c.op))
|
|
2050
|
+
out.push(`${said}: ${c.op} does not apply to a ${f.type} field`);
|
|
2051
|
+
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))
|
|
2052
|
+
out.push(`${said}: not a valid ${f.type} value`);
|
|
2053
|
+
}
|
|
2054
|
+
if (!(Array.isArray(tools) && tools.length > 0 && tools.length <= MAX_TOOLS && new Set(tools).size === tools.length
|
|
2055
|
+
&& tools.every((t) => typeof t === "string" && t !== "" && [...t].length <= 256)))
|
|
2056
|
+
out.push(`a grant names the tools whose calls it covers: 1 to ${MAX_TOOLS} distinct tool names`);
|
|
2057
|
+
for (const c of caveats)
|
|
2058
|
+
if (c.op === "==" || c.op === "in")
|
|
2059
|
+
pinned.set(c.field, c);
|
|
2060
|
+
const cur = pinned.get("currency");
|
|
2061
|
+
if (cur?.op !== "==")
|
|
2062
|
+
out.push("a payment grant names its one currency (currency == USDC)");
|
|
2063
|
+
else if (typeof cur.value === "string" && !Object.hasOwn(DECIMALS, cur.value)) // else check_caveats said it
|
|
2064
|
+
out.push(`tracekit knows the units of ${Object.keys(DECIMALS).sort().join(", ")}; ${cur.value} isn't one of them`);
|
|
2065
|
+
if (!pinned.has("payee"))
|
|
2066
|
+
out.push("a payment grant names its payees (payee in [...])");
|
|
2067
|
+
for (const x of limits) { // the rest of a limit's rule is its shape's (isLimits)
|
|
2068
|
+
const k = JSON.stringify([x.op, x.field ?? null]);
|
|
2069
|
+
const f = x.field ?? "amount";
|
|
2070
|
+
if ((x.op === "sum") !== Object.hasOwn(x, "field") || !(Object.hasOwn(FIELDS, f) && FIELDS[f].type === "int"))
|
|
2071
|
+
out.push(`limit ${dumps(x, floats).slice(0, 96)}: a limit is {op: sum, field, max} of a whole-number field (amount) `
|
|
2072
|
+
+ "or {op: count, max}, max a whole number above zero");
|
|
2073
|
+
else if (seen.has(k))
|
|
2074
|
+
out.push(`limit ${x.op} ${x.field ?? ""}: given twice`.replace(/ /g, " "));
|
|
2075
|
+
seen.add(k);
|
|
2076
|
+
}
|
|
2077
|
+
if (!limits.some((x) => x.op === "sum" && x.field === "amount"))
|
|
2078
|
+
out.push("a payment grant has a total (a sum limit of amount)");
|
|
2079
|
+
const day = new Date(Date.parse(now.slice(0, 19) + "Z") + 86400_000).toISOString().slice(0, 19) + now.slice(19);
|
|
2080
|
+
if (!(now < expiresAt && expiresAt <= day))
|
|
2081
|
+
out.push(`expires_at ${expiresAt} is not in the next 24 h`);
|
|
2082
|
+
return out;
|
|
2083
|
+
}
|
|
2084
|
+
/** grants._why: why `fields` break caveat `c`, in words. */
|
|
2085
|
+
function brokenBy(c, fields) {
|
|
2086
|
+
const v = get(fields, c.field), cur = get(fields, "currency");
|
|
2087
|
+
if (c.field === "amount" && (c.op === "<=" || c.op === "<"))
|
|
2088
|
+
return `amount ${show(v, cur)} is over ${show(c.value - Number(c.op === "<"), cur)} each`;
|
|
2089
|
+
if (c.field === "amount" && (c.op === ">=" || c.op === ">"))
|
|
2090
|
+
return `amount ${show(v, cur)} is under ${show(c.value + Number(c.op === ">"), cur)} each`;
|
|
2091
|
+
const allowed = c.op === "in" ? c.value : [c.value];
|
|
2092
|
+
return `${c.field} ${dumps(v).slice(0, 64)} is not ${allowed.length > 1 ? "one of " : ""}`
|
|
2093
|
+
+ allowed.slice(0, 8).map((x) => dumps(x).slice(0, 64)).join(", ")
|
|
2094
|
+
+ (allowed.length > 8 ? ` and ${allowed.length - 8} more` : "");
|
|
2095
|
+
}
|
|
2096
|
+
/**
|
|
2097
|
+
* grants.check: [the totals after a call with `fields`, null] when grant `gid`'s entry `g` ({grant, limits, used,
|
|
2098
|
+
* revoked}) releases it at `now`, else [null, why not]. Its caveats passed grantProblems and the fields argErrors, so
|
|
2099
|
+
* each caveat compares values of one type (pcm.satisfies).
|
|
2100
|
+
*/
|
|
2101
|
+
function grantCheck(gid, g, fields, now) {
|
|
2102
|
+
if (g.revoked)
|
|
2103
|
+
return [null, `grant ${gid} was revoked`];
|
|
2104
|
+
if (now >= g.grant.expires_at)
|
|
2105
|
+
return [null, `grant ${gid} expired at ${g.grant.expires_at}`];
|
|
2106
|
+
for (const c of g.grant.caveats) {
|
|
2107
|
+
const v = fields[c.field], w = c.value;
|
|
2108
|
+
if (!(c.op === "in" ? w.includes(v) : c.op === "==" ? v === w : c.op === "<=" ? v <= w : c.op === "<" ? v < w
|
|
2109
|
+
: c.op === ">=" ? v >= w : v > w))
|
|
2110
|
+
return [null, `grant ${gid}: ${brokenBy(c, fields)}`];
|
|
2111
|
+
}
|
|
2112
|
+
const used = g.limits.map((x, i) => g.used[i] + (x.op === "sum" ? fields[x.field] : 1));
|
|
2113
|
+
for (const [i, x] of g.limits.entries()) {
|
|
2114
|
+
if (used[i] <= x.max)
|
|
2115
|
+
continue;
|
|
2116
|
+
const before = g.used[i], cur = fields.currency;
|
|
2117
|
+
return [null, `grant ${gid}: ` + (x.op === "count" ? `${str(before)} of ${x.max} payments made`
|
|
2118
|
+
: `${number(before, cur)} of ${show(x.max, cur)} used; this call needs ${show(used[i] - before, cur)}`)];
|
|
2119
|
+
}
|
|
2120
|
+
return [used, null];
|
|
2121
|
+
}
|
|
2122
|
+
/**
|
|
2123
|
+
* Why `e` is not an intent.grant record as the signer writes one (SignerService._grant_issue), or null: a PCM grant of
|
|
2124
|
+
* payment.send (`payment`, its schema ref), issued by a person for this very run and tenant, never passed on, its id its
|
|
2125
|
+
* hash's; caveats, tools and limits a grant may have, an expiry within 24 h of its issue; and its totals those of no
|
|
2126
|
+
* call, or of the held call it was issued from (`first`), which must be within it.
|
|
2127
|
+
*/
|
|
2128
|
+
async function grantIssued(e, payment, floats) {
|
|
2129
|
+
const d = get(e, "data");
|
|
2130
|
+
if (get(e, "source") !== "signer" || !isObj(d) || !Object.keys(d).every((k) => GRANT_KEYS.includes(k))
|
|
2131
|
+
|| typeof get(d, "id") !== "string" || !Array.isArray(get(d, "used"))
|
|
2132
|
+
|| !d.used.every((u, i) => Number.isInteger(u) && !isFloat(floats, d.used, i)) || !isPcmGrant(get(d, "grant"), floats)
|
|
2133
|
+
|| !isLimits(get(d, "limits"), floats) || typeof get(d, "self_approved") !== "boolean")
|
|
2134
|
+
return "an intent.grant record that is not as the signer writes one";
|
|
2135
|
+
const g = d.grant;
|
|
2136
|
+
if (g.intent !== payment)
|
|
2137
|
+
return `a grant of intent ${cut(g.intent, 80)}, which this verifier doesn't know`;
|
|
2138
|
+
const id = await grantId(g);
|
|
2139
|
+
if (d.id !== id)
|
|
2140
|
+
return `grant ${cut(d.id, 24)} is not its grant's id (${id})`;
|
|
2141
|
+
if (g.issuer.kind !== "person" || g.issuer.run !== get(e, "run_id") || g.issuer.tenant !== get(e, "tenant")
|
|
2142
|
+
|| g.parent !== null || g.delegable !== false)
|
|
2143
|
+
return `grant ${id} is not a person's, for this run and tenant, kept to its run`;
|
|
2144
|
+
const bad = grantProblems(g.caveats, d.limits, get(d, "tools"), g.expires_at, g.ts, floats);
|
|
2145
|
+
if (bad.length)
|
|
2146
|
+
return `grant ${id}: ${cut(bad.join("; "), 300)}`;
|
|
2147
|
+
let used = d.limits.map(() => 0);
|
|
2148
|
+
const f = get(d, "first");
|
|
2149
|
+
if (f !== null) {
|
|
2150
|
+
const fields = isObj(f) ? get(f, "fields") : null;
|
|
2151
|
+
if (!(isObj(fields) && !argErrors(fields, floats).length && typeof get(f, "approval_id") === "string"
|
|
2152
|
+
&& typeof get(f, "tool_call_id") === "string"))
|
|
2153
|
+
return `grant ${id}: its first use is not a held call's`;
|
|
2154
|
+
const [after, why] = grantCheck(id, { grant: g, limits: d.limits, used, revoked: false }, fields, g.ts);
|
|
2155
|
+
if (why)
|
|
2156
|
+
return `grant ${id} was issued from a held call outside it (${why})`;
|
|
2157
|
+
used = after;
|
|
2158
|
+
}
|
|
2159
|
+
if (!same(d.used, used))
|
|
2160
|
+
return `grant ${id} starts with totals ${dumps(d.used, floats).slice(0, 64)}, not ${dumps(used)}`;
|
|
2161
|
+
if (Object.hasOwn(d, "description") && !short(d.description, 512))
|
|
2162
|
+
return `grant ${id}: its description is not a string of at most 512 characters`;
|
|
2163
|
+
return null;
|
|
2164
|
+
}
|
|
2165
|
+
/** Whether `e` is a decision whose rule ids name TK-GRANT: one a grant released, as its ext.grant must say. */
|
|
2166
|
+
const tkGrant = (e) => get(e, "type") === "policy.decision" && isObj(get(e, "data"))
|
|
2167
|
+
&& Array.isArray(get(e.data, "rule_ids")) && e.data.rule_ids.includes("TK-GRANT");
|
|
2168
|
+
/**
|
|
2169
|
+
* intent.grant, intent.revoked and ext.grant (docs/intent-grants.md): the grants people issued for a run, their
|
|
2170
|
+
* revocations, and the calls they released. Each grant is checked as grantIssued says; each released call against its
|
|
2171
|
+
* grant, as the signer decided it: a policy.decision flagged with TK-GRANT, its grant recorded earlier in the same run
|
|
2172
|
+
* and not revoked before it, decided before the grant expired, of a tool the grant covers, its fields those of the
|
|
2173
|
+
* intent (whole numbers where they count) and within every caveat, its totals the previous call's plus its own, whole
|
|
2174
|
+
* numbers within every limit, and its tier the record's (T2: an executor or gateway decided and ran the call; T1: the
|
|
2175
|
+
* arguments the harness reported). A release that breaks its grant fails the line, and so does one whose grant the
|
|
2176
|
+
* bundle doesn't hold earlier in its run, or holds only in a record a signer never writes, a decision flagged TK-GRANT
|
|
2177
|
+
* 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
|
|
2178
|
+
* a person's grant. Any other record in a shape the signer never writes is a warning, as for every ext name. `events`
|
|
2179
|
+
* also holds the decisions TK-GRANT names (checkExt); `floats`: the parser's, so a number written as a float is no whole
|
|
2180
|
+
* number.
|
|
2181
|
+
*/
|
|
2182
|
+
async function checkGrants(rep, events, floats) {
|
|
2183
|
+
const payment = `payment.send@sha256:${await sha256hex(bytes(canonicalize(PAYMENT)))}`;
|
|
2184
|
+
const live = new Map(), invalid = new Set(), bad = [], broken = [];
|
|
2185
|
+
const issuers = new Set();
|
|
2186
|
+
const tiers = { T1: 0, T2: 0 };
|
|
2187
|
+
let issued = 0, selfish = 0, revoked = 0;
|
|
2188
|
+
const seq = (e) => Number.isInteger(get(e, "seq")) ? e.seq : -1;
|
|
2189
|
+
for (const e of [...events].sort((a, b) => seq(a) - seq(b))) {
|
|
2190
|
+
const where = `seq ${pyStr(get(e, "seq"), floats, isFloat(floats, e, "seq"))}`, d = get(e, "data");
|
|
2191
|
+
const key = (id) => JSON.stringify([get(e, "tenant"), get(e, "run_id"), id]); // a grant's id is a string
|
|
2192
|
+
const name = get(e, "type") === "ext" && isObj(d) ? get(d, "name") : null;
|
|
2193
|
+
if (name === "intent.grant") {
|
|
2194
|
+
const why = await grantIssued(e, payment, floats);
|
|
2195
|
+
if (why) {
|
|
2196
|
+
bad.push(`${where}: ${why}`);
|
|
2197
|
+
if (typeof get(d, "id") === "string")
|
|
2198
|
+
invalid.add(key(d.id)); // what it released is released under no valid grant
|
|
2199
|
+
continue;
|
|
2200
|
+
}
|
|
2201
|
+
live.set(key(d.id), { grant: d.grant, tools: d.tools, limits: d.limits, used: d.used, revoked: false });
|
|
2202
|
+
issued++;
|
|
2203
|
+
selfish += Number(d.self_approved);
|
|
2204
|
+
if (!d.self_approved)
|
|
2205
|
+
issuers.add(d.grant.issuer.person || d.grant.issuer.id);
|
|
2206
|
+
}
|
|
2207
|
+
else if (name === "intent.revoked") {
|
|
2208
|
+
const g = typeof get(d, "id") === "string" ? live.get(key(d.id)) : undefined;
|
|
2209
|
+
if (get(e, "source") !== "signer" || !g || g.revoked)
|
|
2210
|
+
bad.push(`${where}: revokes no grant still live in its run`);
|
|
2211
|
+
else {
|
|
2212
|
+
g.revoked = true;
|
|
2213
|
+
revoked++;
|
|
2214
|
+
}
|
|
2215
|
+
}
|
|
2216
|
+
if (!(isObj(get(e, "ext")) && Object.hasOwn(e.ext, "grant"))) {
|
|
2217
|
+
if (tkGrant(e))
|
|
2218
|
+
broken.push(`${where}: a decision flagged TK-GRANT carries no ext.grant: it names no grant it was released under`);
|
|
2219
|
+
continue;
|
|
2220
|
+
}
|
|
2221
|
+
const x = e.ext.grant, g = isObj(x) && typeof get(x, "id") === "string" ? live.get(key(x.id)) : undefined;
|
|
2222
|
+
if (!(tkGrant(e) && get(d, "decision") === "flag" && shaped(x, ["id", "fields", "used", "tier"]))) {
|
|
2223
|
+
bad.push(`${where}: ext.grant is not on a decision a grant released, as the signer writes it`);
|
|
2224
|
+
continue;
|
|
2225
|
+
}
|
|
2226
|
+
const errs = !g ? [] : isObj(x.fields) ? argErrors(x.fields, floats) : ["not an object"];
|
|
2227
|
+
if (!g && typeof x.id === "string" && invalid.has(key(x.id)))
|
|
2228
|
+
broken.push(`${where}: released under grant ${cut(x.id, 24)}, whose record is not as the signer writes one`);
|
|
2229
|
+
else if (!g)
|
|
2230
|
+
broken.push(`${where}: names grant ${cut(pyStr(x.id, floats, isFloat(floats, x, "id")), 24)}, which this `
|
|
2231
|
+
+ "bundle doesn't hold earlier in the run (export the whole run to check it)");
|
|
2232
|
+
else if (errs.length)
|
|
2233
|
+
broken.push(`${where}: the fields it records are not a payment.send call's (${cut(errs[0], 120)})`);
|
|
2234
|
+
else if (!g.tools.includes(get(d, "tool")))
|
|
2235
|
+
broken.push(`${where}: released a call of ${dumps(get(d, "tool"), floats, isFloat(floats, d, "tool")).slice(0, 64)}, `
|
|
2236
|
+
+ `a tool grant ${x.id} doesn't cover`);
|
|
2237
|
+
else {
|
|
2238
|
+
const [used, why] = grantCheck(x.id, g, x.fields, get(e, "ts") || "");
|
|
2239
|
+
if (why)
|
|
2240
|
+
broken.push(`${where}: released a call the grant holds (${why})`);
|
|
2241
|
+
else if (!(Array.isArray(x.used) && x.used.every((u, i) => Number.isInteger(u) && !isFloat(floats, x.used, i))
|
|
2242
|
+
&& same(x.used, used)))
|
|
2243
|
+
broken.push(`${where}: records totals ${dumps(x.used, floats).slice(0, 64)}, not ${dumps(used)}`);
|
|
2244
|
+
else if (x.tier !== (get(e, "tier") === "T2" ? "T2" : "T1"))
|
|
2245
|
+
broken.push(`${where}: says tier ${cut(pyStr(x.tier, floats, isFloat(floats, x, "tier")), 8)}, the record `
|
|
2246
|
+
+ (truthy(get(e, "tier")) ? pyStr(e.tier, floats, isFloat(floats, e, "tier")) : "T1"));
|
|
2247
|
+
else {
|
|
2248
|
+
g.used = used;
|
|
2249
|
+
tiers[x.tier]++;
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
rep.check("intent grants", !bad.length && !broken.length, `${issued} grant(s)`
|
|
2254
|
+
+ (issuers.size ? ` by ${cut([...issuers].sort(byCodePoint).join(", "), 200)}` : "")
|
|
2255
|
+
+ (selfish ? ` (${selfish} self-approved: issued by the run's own user, which the agent can be)` : "")
|
|
2256
|
+
+ (revoked ? `, ${revoked} revoked` : "") + `; ${tiers.T1 + tiers.T2} call(s) released within them (${tiers.T2} at `
|
|
2257
|
+
+ `T2, decided and run by an executor or gateway; ${tiers.T1} at T1, on the arguments the harness reported), each `
|
|
2258
|
+
+ "re-checked against its grant and its running totals", [...broken, ...bad].slice(0, 20), !broken.length);
|
|
2259
|
+
}
|
|
1868
2260
|
/**
|
|
1869
2261
|
* The ext names this verifier interprets (the VERSIONS rows' "ext" in tracekit/bundle_v2.py): name -> its check, whose
|
|
1870
|
-
* lines are its own: every other line of the report reads the same without them (docs/format-v2.md §9).
|
|
2262
|
+
* lines are its own: every other line of the report reads the same without them (docs/format-v2.md §9). Names that
|
|
2263
|
+
* share a check are read together, once: a grant, its revocation and the calls it released.
|
|
1871
2264
|
*/
|
|
1872
|
-
const EXT_CHECKS = new Map([["amended", checkAmended],
|
|
1873
|
-
["
|
|
2265
|
+
const EXT_CHECKS = new Map([["amended", checkAmended], ["openshell.policy", checkOpenshellPolicy],
|
|
2266
|
+
["box", checkBox], ["intent.grant", checkGrants], ["intent.revoked", checkGrants], ["grant", checkGrants]]);
|
|
1874
2267
|
const MAX_UNREAD = 20; // `not interpreted` lines, one per ext name; the rest on one line
|
|
1875
2268
|
/** A run's problems past which its later records go unchecked: forged records cost a verifier little. */
|
|
1876
2269
|
const RUN_PROBLEMS = 20;
|
|
1877
2270
|
/** The ext names an event carries: its `ext` field's keys, and an `ext` record's name. */
|
|
1878
2271
|
const extNames = (e) => [...Object.keys(isObj(get(e, "ext")) ? e.ext : {}),
|
|
1879
2272
|
...get(e, "type") === "ext" ? [at(at(e, "data"), "name")] : []];
|
|
2273
|
+
const ROWS = VERSIONS_JSON, EXT_SLOT = "1.4.0", EXT_NAME = "ext name ";
|
|
2274
|
+
const usesSlot = (e) => Object.hasOwn(e, "ext") || get(e, "type") === "ext";
|
|
2275
|
+
/** The entries of `row` that `e` uses: `type`, `type.field`, `type.field=value` (by type too) and EXT_NAME + name. */
|
|
2276
|
+
function entries(e, row) {
|
|
2277
|
+
const typ = str(get(e, "type")), data = isObj(get(e, "data")) ? e.data : {};
|
|
2278
|
+
return [...row.types.includes(typ) ? [typ] : [],
|
|
2279
|
+
...(row.fields[typ] ?? []).filter((f) => Object.hasOwn(data, f)).map((f) => `${typ}.${f}`),
|
|
2280
|
+
...Object.entries(row.values[typ] ?? {}).filter(([f, vs]) => Object.hasOwn(data, f) && vs.some((v) => v === data[f]))
|
|
2281
|
+
.map(([f]) => `${typ}.${f}=${str(data[f])}`),
|
|
2282
|
+
...extNames(e).filter((n) => (row.ext ?? []).includes(n)).map((n) => EXT_NAME + str(n))];
|
|
2283
|
+
}
|
|
2284
|
+
/** The verifier_min_version records `events` in `layout` need: the newest row whose entries other than ext names they
|
|
2285
|
+
* use, EXT_SLOT at least when one uses the slot. */
|
|
2286
|
+
function needs(events, layout) {
|
|
2287
|
+
const order = ["1.0.0", ...Object.keys(ROWS)];
|
|
2288
|
+
let need = "1.0.0";
|
|
2289
|
+
for (const [version, row] of Object.entries(ROWS))
|
|
2290
|
+
if (layout.some((x) => (row.layout ?? []).includes(x))
|
|
2291
|
+
|| events.some((e) => entries(e, row).some((x) => !x.startsWith(EXT_NAME))))
|
|
2292
|
+
need = version;
|
|
2293
|
+
return events.some(usesSlot) && order.indexOf(need) < order.indexOf(EXT_SLOT) ? EXT_SLOT : need;
|
|
2294
|
+
}
|
|
2295
|
+
/** What makes `events` in `layout` need `version`, with the seqs of the records (the first five). */
|
|
2296
|
+
function raisedBy(events, version, layout) {
|
|
2297
|
+
const seqs = new Map();
|
|
2298
|
+
for (const e of events)
|
|
2299
|
+
for (const x of [...entries(e, ROWS[version] ?? { types: [], fields: {}, values: {} }).filter((x) => !x.startsWith(EXT_NAME)),
|
|
2300
|
+
...version === EXT_SLOT && usesSlot(e) ? ["ext"] : []]) {
|
|
2301
|
+
if (!seqs.has(x))
|
|
2302
|
+
seqs.set(x, []);
|
|
2303
|
+
seqs.get(x).push(get(e, "seq"));
|
|
2304
|
+
}
|
|
2305
|
+
return [...[...seqs].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([x, s]) => `${x}: seq ${s.slice(0, 5).map(str)
|
|
2306
|
+
.join(", ")}` + (s.length > 5 ? ` and ${s.length - 5} more` : "")),
|
|
2307
|
+
...layout.filter((x) => (ROWS[version]?.layout ?? []).includes(x))];
|
|
2308
|
+
}
|
|
2309
|
+
/** `verifier minimum`, a warning only when the manifest's verifier_min_version (`said`) is below what the records and
|
|
2310
|
+
* the layout of `names` need: the manifest is never signed, and edited down it lets an older verifier claim more. A
|
|
2311
|
+
* record it can't read (no type, data or seq: other checks fail it) needs nothing. */
|
|
2312
|
+
function checkMinimum(rep, all, names, said) {
|
|
2313
|
+
const events = all.filter((e) => isObj(e) && typeof e.type === "string" && Object.hasOwn(e, "seq") && isObj(e.data)
|
|
2314
|
+
&& (e.type !== "ext" || Object.hasOwn(e.data, "name")));
|
|
2315
|
+
const layout = names.some((n) => PART.test(n)) ? ["run parts"] : [], need = needs(events, layout);
|
|
2316
|
+
if (need !== "1.0.0" && newer(need, said)) // a row raised it (0.x bundles need the base)
|
|
2317
|
+
rep.check("verifier minimum", false, `the records need tracekit >= ${need}, the manifest asks for ${said}: a verifier `
|
|
2318
|
+
+ `older than ${need} may have read this bundle and claimed more than its records show`, raisedBy(events, need, layout).slice(0, 20), true);
|
|
2319
|
+
}
|
|
1880
2320
|
/**
|
|
1881
2321
|
* A line per ext name the records carry: its EXT_CHECKS check, or a `not interpreted` warning. The records were checked
|
|
1882
|
-
* like every other (signature, chain, inclusion); `full`: the manifest's advisory verifier_version
|
|
2322
|
+
* like every other (signature, chain, inclusion); `full`: the manifest's advisory verifier_version; `floats`: the
|
|
2323
|
+
* parser's.
|
|
1883
2324
|
*/
|
|
1884
|
-
function checkExt(rep, events, full) {
|
|
2325
|
+
async function checkExt(rep, events, full, floats) {
|
|
1885
2326
|
const carry = new Map(); // name -> the events carrying it
|
|
1886
2327
|
for (const e of events)
|
|
1887
2328
|
for (const n of new Set(extNames(e).map((x) => cut(str(x), 64)))) {
|
|
@@ -1889,13 +2330,23 @@ function checkExt(rep, events, full) {
|
|
|
1889
2330
|
carry.set(n, []);
|
|
1890
2331
|
carry.get(n).push(e);
|
|
1891
2332
|
}
|
|
1892
|
-
const later = typeof full === "string" && /^\d{1,9}(\.\d{1,9}){0,2}$/.test(full) && newer(full,
|
|
2333
|
+
const later = typeof full === "string" && /^\d{1,9}(\.\d{1,9}){0,2}$/.test(full) && newer(full, READS)
|
|
1893
2334
|
? `; tracekit >= ${full} checks it` : "";
|
|
1894
2335
|
let shown = 0, more = 0;
|
|
2336
|
+
const done = new Set();
|
|
2337
|
+
// records a check reads beside its names' own: the decisions TK-GRANT names, ext.grant or not
|
|
2338
|
+
const also = new Map([[checkGrants, events.filter(tkGrant)]]);
|
|
2339
|
+
const run = async (f) => {
|
|
2340
|
+
done.add(f);
|
|
2341
|
+
await f(rep, [...new Set([...[...carry].filter(([k]) => EXT_CHECKS.get(k) === f).flatMap(([, v]) => v),
|
|
2342
|
+
...also.get(f) ?? []])], floats);
|
|
2343
|
+
};
|
|
1895
2344
|
for (const [n, es] of [...carry].sort(byKey)) {
|
|
1896
2345
|
const interpret = EXT_CHECKS.get(n);
|
|
1897
|
-
if (interpret)
|
|
1898
|
-
interpret
|
|
2346
|
+
if (interpret) {
|
|
2347
|
+
if (!done.has(interpret))
|
|
2348
|
+
await run(interpret);
|
|
2349
|
+
}
|
|
1899
2350
|
else if (shown < MAX_UNREAD) {
|
|
1900
2351
|
shown++;
|
|
1901
2352
|
rep.check("not interpreted", false, `${es.length} record(s) carry ext.${n}: their signatures, chain and `
|
|
@@ -1907,6 +2358,9 @@ function checkExt(rep, events, full) {
|
|
|
1907
2358
|
if (more)
|
|
1908
2359
|
rep.check("not interpreted", false, `${more} more ext name(s), on records whose signatures, chain and inclusion `
|
|
1909
2360
|
+ `are checked above; what they mean is not checked${later}`, [], true);
|
|
2361
|
+
for (const [f, extra] of also) // a check whose names no record carries reads what it reads beside them
|
|
2362
|
+
if (extra.length && !done.has(f))
|
|
2363
|
+
await run(f);
|
|
1910
2364
|
}
|
|
1911
2365
|
/** Approvals by people and by agents, each on a line of its own. An agent's approval fails the line unless its run
|
|
1912
2366
|
* holds the approval.request and policy.decision it answered, the signer called the request agent-eligible
|
|
@@ -2267,10 +2721,11 @@ function honoured(events, pointers) {
|
|
|
2267
2721
|
return problems;
|
|
2268
2722
|
}
|
|
2269
2723
|
/** §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,
|
|
2270
|
-
* else why not. */
|
|
2271
|
-
async function verifyRecord(r, keys, algs) {
|
|
2724
|
+
* else why not. `floats`: where the parser read number tokens with a fraction or exponent (`v` is the integer 2). */
|
|
2725
|
+
async function verifyRecord(r, keys, algs, floats) {
|
|
2272
2726
|
if (!isObj(r) || Object.keys(r).length !== 6 || !["v", "event", "hash", "alg", "kid", "sig"].every((k) => Object.hasOwn(r, k))
|
|
2273
|
-
|| !same(r.v, 2) ||
|
|
2727
|
+
|| !same(r.v, 2) || floats?.get(r)?.has("v") || !isObj(r.event)
|
|
2728
|
+
|| !["hash", "alg", "kid", "sig"].every((k) => typeof r[k] === "string"))
|
|
2274
2729
|
return "not a v2 record";
|
|
2275
2730
|
let h;
|
|
2276
2731
|
try {
|
|
@@ -2492,8 +2947,10 @@ async function assurance(origin, cosigs, witnesses, trust, algs, selfApproved, r
|
|
|
2492
2947
|
/** `x` without control characters and the bidirectional and zero-width format characters that would reorder or hide
|
|
2493
2948
|
* the text around them, as the report prints bundle-derived strings. */
|
|
2494
2949
|
const clean = (x) => x.replace(/[\x00-\x1f\x7f-\x9f\u061c\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, "");
|
|
2495
|
-
/**
|
|
2496
|
-
const
|
|
2950
|
+
/** A failed bundle's assurance: a level rates only evidence that verified. */
|
|
2951
|
+
const NOT_RATED = "not rated (the bundle failed verification)";
|
|
2952
|
+
/** The Assurance line as the reports print it. */
|
|
2953
|
+
const assuranceLine = (rep) => `Assurance: ${rep.integrity === "FAILED" ? NOT_RATED : clean(rep.assurance)}.`;
|
|
2497
2954
|
/** The report as text, as the reference CLI prints it; `clean` drops characters from bundle-derived strings. */
|
|
2498
2955
|
function formatReport(rep) {
|
|
2499
2956
|
let s = "";
|
|
@@ -2506,7 +2963,7 @@ function formatReport(rep) {
|
|
|
2506
2963
|
+ (rep.findings ? `Findings: ${clean(rep.findings)}.\n` : "");
|
|
2507
2964
|
}
|
|
2508
2965
|
|
|
2509
|
-
return { EXIT_BAD, EXIT_FAIL, EXIT_OK, EXIT_WARN, Report, TRUST_UNUSABLE, VERSION, assuranceLine, clean, formatReport, runFiles, verify, verifyRecord, MAX_ENTRIES: __zip.MAX_ENTRIES, MAX_ENTRY: __zip.MAX_ENTRY, MAX_TOTAL: __zip.MAX_TOTAL, Unusable: __zip.Unusable, readZip: __zip.readZip, StrictJSONError: __jcs.StrictJSONError, canonicalize: __jcs.canonicalize, strictParse: __jcs.strictParse, strictParseBytes: __jcs.strictParseBytes };
|
|
2966
|
+
return { EXIT_BAD, EXIT_FAIL, EXIT_OK, EXIT_WARN, NOT_RATED, READS, Report, TRUST_UNUSABLE, VERSION, assuranceLine, checkExt, checkGrants, clean, formatReport, runFiles, verify, verifyRecord, MAX_ENTRIES: __zip.MAX_ENTRIES, MAX_ENTRY: __zip.MAX_ENTRY, MAX_TOTAL: __zip.MAX_TOTAL, Unusable: __zip.Unusable, readZip: __zip.readZip, StrictJSONError: __jcs.StrictJSONError, canonicalize: __jcs.canonicalize, strictParse: __jcs.strictParse, strictParseBytes: __jcs.strictParseBytes };
|
|
2510
2967
|
})();
|
|
2511
2968
|
const __explain = (() => {
|
|
2512
2969
|
/**
|
|
@@ -2514,15 +2971,15 @@ const __explain = (() => {
|
|
|
2514
2971
|
* mean, what to do next, a line per check on what it means (docs/verdicts.md, shortened), and a summary of the bundle's
|
|
2515
2972
|
* runs. The report itself is the CLI's, unchanged: this module only reads it. No DOM, so Node tests it.
|
|
2516
2973
|
*/
|
|
2517
|
-
const { EXIT_FAIL: EXIT_FAIL, EXIT_OK: EXIT_OK, VERSION: VERSION, clean: clean, formatReport: formatReport, runFiles: runFiles } = __index;
|
|
2974
|
+
const { EXIT_FAIL: EXIT_FAIL, EXIT_OK: EXIT_OK, NOT_RATED: NOT_RATED, VERSION: VERSION, clean: clean, formatReport: formatReport, runFiles: runFiles } = __index;
|
|
2518
2975
|
/** `s` as one shell argument (POSIX shells; the page doesn't know the reader's). */
|
|
2519
2976
|
const sh = (s) => /^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'"'"'`)}'`;
|
|
2520
2977
|
const TRUST_FILE = "the sender's trust file: a small .json that names their signer's log key (tracekit last writes it next "
|
|
2521
2978
|
+ "to the bundle, as <name>.trust.json)";
|
|
2522
2979
|
/** The report as `tracekit verify --json` prints it (cli.ts prints this). */
|
|
2523
2980
|
const asJson = (rep, code) => ({ exit_code: code, checks: rep.checks, failures: rep.failures,
|
|
2524
|
-
warnings: rep.warnings, integrity: rep.integrity, assurance:
|
|
2525
|
-
...rep.findings ? { findings: rep.findings } : {} });
|
|
2981
|
+
warnings: rep.warnings, integrity: rep.integrity, assurance: code === EXIT_FAIL ? NOT_RATED : rep.assurance,
|
|
2982
|
+
notes: rep.notes, ...rep.findings ? { findings: rep.findings } : {} });
|
|
2526
2983
|
/** The report as `tracekit verify` prints it, then its exit code. */
|
|
2527
2984
|
const asText = (rep, code) => formatReport(rep) + `\nExit code ${code}`
|
|
2528
2985
|
+ (code === EXIT_OK && rep.warnings.length ? ` (3 with --strict: ${rep.warnings.length} warning(s))` : "") + ".\n";
|
|
@@ -2750,6 +3207,8 @@ const MEANING = {
|
|
|
2750
3207
|
"break-glass approvals": { warn: "Approvals given under the break-glass role, with who and why." },
|
|
2751
3208
|
"not interpreted": { warn: "Records carry an extension this verifier doesn't read. They verified like every other "
|
|
2752
3209
|
+ "record." },
|
|
3210
|
+
"verifier minimum": { warn: "The bundle's manifest, which isn't signed, asks for an older verifier than its records "
|
|
3211
|
+
+ "need: an older verifier may have claimed more than they show. This one read every record." },
|
|
2753
3212
|
"gateway amendments": {
|
|
2754
3213
|
pass: "Requests the LLM gateway changed so the provider shows its reasoning; each record commits to the request "
|
|
2755
3214
|
+ "as sent.",
|
|
@@ -2762,6 +3221,21 @@ const MEANING = {
|
|
|
2762
3221
|
warn: "A record carries an OpenShell policy change where or how the signer never writes one. The record verified "
|
|
2763
3222
|
+ "like every other.",
|
|
2764
3223
|
},
|
|
3224
|
+
"boxed agent": {
|
|
3225
|
+
pass: "Runs of a Tracekit Box box and of its agent: proof against the agent in that box only, whose box never held "
|
|
3226
|
+
+ "the signing key. The records are the agent's own account; the box's doors are what held it.",
|
|
3227
|
+
warn: "A record carries a box label where or how the signer never writes one: nothing is claimed about the key. "
|
|
3228
|
+
+ "The record verified like every other.",
|
|
3229
|
+
},
|
|
3230
|
+
"intent grants": {
|
|
3231
|
+
pass: "Payments people allowed the run's agent once, within limits, who allowed them, and the calls each grant let "
|
|
3232
|
+
+ "run, each re-checked against its grant and its running totals.",
|
|
3233
|
+
warn: "A grant, revocation or released call is recorded where or how the signer never writes one. The records "
|
|
3234
|
+
+ "verified like every other.",
|
|
3235
|
+
fail: "The signer recorded a call as released by a grant that doesn't allow it (another tool, other fields, over a "
|
|
3236
|
+
+ "limit, totals that don't add up), by no grant the bundle holds, or by a grant whose record a signer never "
|
|
3237
|
+
+ "writes.",
|
|
3238
|
+
},
|
|
2765
3239
|
"constraints": {
|
|
2766
3240
|
pass: "What the person's request said not to do, added while the run was open, and the calls it held.",
|
|
2767
3241
|
fail: "A call held by a live constraint comes before any constraint in its run, or wasn't held for approval: the "
|