@verax-ai/proxy 0.4.1 → 0.4.3

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.
@@ -51,6 +51,39 @@
51
51
  * that verified. A key taken from the file shows the checkpoints agree
52
52
  * with each other, not that the key was ever trusted.
53
53
  *
54
+ * Inputs are a further statement. The writer appends a call's inputs row
55
+ * before the record whose `inputsHash` commits to it, so a crash leaves at
56
+ * most an inputs row with no record, never the reverse. Each record that
57
+ * carries an `inputsHash` must find an inputs row under its ref whose
58
+ * canonical SHA-256 is that hash. A missing row is `inputs row missing`, a
59
+ * row under that ref with another hash is `inputs row does not match`, and
60
+ * either makes `ok` false: the approver block of an approval lives in that
61
+ * row, and an unbound row could be rewritten from a signed approval into an
62
+ * unsigned one. A row with no record is the crash case and is not named.
63
+ *
64
+ * Checkpoint counts are checked too. For every checkpoint that verified, its
65
+ * head must be a record the ledger holds, the verified records in its window
66
+ * up to that head must be its `receiptCount` ending at the head, and their
67
+ * allow, deny and defer counts must be its totals; a record appended later
68
+ * with a time in the window is not counted. Null totals (redacted) are not
69
+ * compared; the count still is.
70
+ *
71
+ * Anchors are the last statement. `checkpoint-anchors.jsonl` holds COSE
72
+ * Receipts from a Transparency Service for checkpoints `verax anchor`
73
+ * registered. A receipt names no key, so it is checked only under a key the
74
+ * reader supplies (`anchorPublicKeyPem`): each row must name a checkpoint that
75
+ * verified, its leaf entry must be the one the route defines, and the receipt
76
+ * must verify over the root its inclusion proof rebuilds. Without that key the
77
+ * receipts are counted and said to be unchecked; that is not a failure.
78
+ *
79
+ * Control records are a further statement. An allow whose subject is
80
+ * `verax.halt` opens a halt window; an allow whose subject is `verax.resume`
81
+ * closes it. An allow whose subject does not start with `verax.` while a
82
+ * window is open is `allow-while-halted <ref>` and `ok` is false. A deny
83
+ * whose reason is `halted` and which sits outside every window is the
84
+ * warning `halted-deny-without-halt-record <ref>` and does not change `ok`.
85
+ * A ledger with no control record says so, and that sentence is not a violation.
86
+ *
54
87
  * And a fourth, which matters most and is the easiest to fudge: **which key**.
55
88
  * A ledger checked against the key sitting next to it is internally
56
89
  * consistent and nothing more — whatever could write the file could write
@@ -62,12 +95,14 @@
62
95
  import { createPublicKey } from "node:crypto";
63
96
  import { existsSync, lstatSync, readFileSync } from "node:fs";
64
97
  import { join } from "node:path";
65
- import { findCheckpointChainBreak, verifyCheckpoint, verifyCheckpointUnderPin, } from "@cedulon/checkpoint";
98
+ import { checkpointHash, findCheckpointChainBreak, totalsFromDecisionRecords, verifyCheckpoint, verifyCheckpointUnderPin, } from "@cedulon/checkpoint";
66
99
  import { canonical, decisionRecordHash, findDecisionRecordChainBreak, verifyDecisionRecord } from "@cedulon/core";
67
100
  import { coseFromHex, decodeCoseSign1, verifyCoseSign1 } from "@cedulon/cose";
68
101
  import { verifyEffectExtract } from "@cedulon/effect-extract";
102
+ import { anchorEntryHash, readAnchors } from "./anchors.js";
69
103
  import { checkpointsPath, readCheckpointFile } from "./checkpoints.js";
70
104
  import { sha256Canonical } from "./hash.js";
105
+ import { verifyReceipt } from "./transparency-receipt.js";
71
106
  import { ledgerPiecePathProblem, readLedgerManifest, requireLedgerPiecePath, indexPath, manifestPath, parseIndexText, } from "./ledger-manifest.js";
72
107
  /**
73
108
  * A symbolic link is a named problem and is not read. Missing files are not
@@ -112,13 +147,17 @@ function takePieceFile(dir, rel, problems, read) {
112
147
  }
113
148
  return path;
114
149
  }
115
- /** Decision and effect files this directory holds, oldest piece first. Inputs are confined and not read. */
150
+ /**
151
+ * Decision, effect and inputs files this directory holds, oldest piece first.
152
+ * An inputs file the disk lacks is not named here: a record that needed a row
153
+ * from it is named when inputs are checked.
154
+ */
116
155
  function ledgerFiles(dir, problems) {
117
156
  const manifestFile = manifestPath(dir);
118
157
  const manifestLink = symbolicLinkProblem(manifestFile);
119
158
  if (manifestLink !== null) {
120
159
  problems.push(manifestLink);
121
- return { decisions: [], effects: [] };
160
+ return { decisions: [], effects: [], inputs: [] };
122
161
  }
123
162
  if (existsSync(manifestFile)) {
124
163
  try {
@@ -129,7 +168,7 @@ function ledgerFiles(dir, problems) {
129
168
  }
130
169
  catch (err) {
131
170
  problems.push(err instanceof Error ? err.message : "ledger-manifest-unreadable");
132
- return { decisions: [], effects: [] };
171
+ return { decisions: [], effects: [], inputs: [] };
133
172
  }
134
173
  }
135
174
  return legacyFiles(dir);
@@ -137,14 +176,17 @@ function ledgerFiles(dir, problems) {
137
176
  function legacyFiles(dir) {
138
177
  const decisionsPath = join(dir, "decisions.jsonl");
139
178
  const effectsPath = join(dir, "effects.jsonl");
179
+ const inputsPath = join(dir, "inputs.jsonl");
140
180
  return {
141
181
  decisions: existsSync(decisionsPath) ? [decisionsPath] : [],
142
182
  effects: existsSync(effectsPath) ? [effectsPath] : [],
183
+ inputs: existsSync(inputsPath) ? [inputsPath] : [],
143
184
  };
144
185
  }
145
186
  function pieceFiles(dir, pieces, problems) {
146
187
  const decisions = [];
147
188
  const effects = [];
189
+ const inputs = [];
148
190
  for (const p of pieces) {
149
191
  const decision = takePieceFile(dir, p.decisions, problems, true);
150
192
  if (decision)
@@ -152,9 +194,15 @@ function pieceFiles(dir, pieces, problems) {
152
194
  const effect = takePieceFile(dir, p.effects, problems, true);
153
195
  if (effect)
154
196
  effects.push(effect);
197
+ const before = problems.length;
155
198
  takePieceFile(dir, p.inputs, problems, false);
199
+ if (problems.length === before) {
200
+ const path = requireLedgerPiecePath(dir, p.inputs);
201
+ if (existsSync(path))
202
+ inputs.push(path);
203
+ }
156
204
  }
157
- return { decisions, effects };
205
+ return { decisions, effects, inputs };
158
206
  }
159
207
  /** Parses JSONL, reporting the line a bad row sits on rather than throwing. */
160
208
  function readJsonl(path, problems) {
@@ -414,6 +462,16 @@ const INDEX_NONE = "index: none (cannot check for removed records)";
414
462
  const EFFECT_COMPLETENESS_UNCHECKED = "effect completeness was not checked";
415
463
  const EFFECT_COMPLETENESS_CHECKED = "effect completeness checked";
416
464
  const TAIL_NONE = "tail: no checkpoint; removing the newest records with their effects is not detectable from these files";
465
+ const CONTROL_NONE = {
466
+ line: "control: no control records",
467
+ windows: 0,
468
+ warnings: [],
469
+ };
470
+ const CONTROL_UNCHECKED = {
471
+ line: "control: not checked",
472
+ windows: 0,
473
+ warnings: [],
474
+ };
417
475
  /**
418
476
  * A torn last line is the crash the writer already documents: earlier lines
419
477
  * parsed, so that tail is skipped. Any other line that is not JSON, and a
@@ -502,7 +560,7 @@ function noteEffectCompleteness(effectRefs, bound, problems) {
502
560
  }
503
561
  return EFFECT_COMPLETENESS_CHECKED;
504
562
  }
505
- function tailStatement(dir, records, checkpointPublicKeyPem) {
563
+ function tailStatement(dir, records, checkpointPublicKeyPem, attested = records) {
506
564
  const checkpointFile = checkpointsPath(dir);
507
565
  const checkpointLink = symbolicLinkProblem(checkpointFile);
508
566
  if (checkpointLink !== null) {
@@ -511,6 +569,7 @@ function tailStatement(dir, records, checkpointPublicKeyPem) {
511
569
  tail: { line: TAIL_NONE, checkpoint: null },
512
570
  checkpointTrust: checkpointTrustOf(pinned, null, 0),
513
571
  problems: [checkpointLink],
572
+ verified: [],
514
573
  };
515
574
  }
516
575
  const loaded = readCheckpointFile(dir);
@@ -520,10 +579,22 @@ function tailStatement(dir, records, checkpointPublicKeyPem) {
520
579
  const key = pinned !== "" ? pinned : taken;
521
580
  const checkpointTrust = checkpointTrustOf(pinned, taken, rows.length);
522
581
  const problems = [...loaded.problems];
582
+ const verified = [];
523
583
  noteEd25519(key, problems);
524
584
  for (let i = 0; i < rows.length; i += 1) {
525
585
  if (!checkpointRowVerifies(rows[i], key)) {
526
586
  problems.push(`checkpoint signature does not verify: checkpoint ${i}`);
587
+ continue;
588
+ }
589
+ try {
590
+ const count = rows[i].claims.receiptCount;
591
+ verified.push({ hash: checkpointHash(rows[i]), receiptCount: typeof count === "number" ? count : null });
592
+ }
593
+ catch {
594
+ // A row that verified but cannot be hashed cannot be anchored either.
595
+ }
596
+ for (const problem of checkpointCountProblems(rows[i], records, attested)) {
597
+ problems.push(`${problem}: checkpoint ${i}`);
527
598
  }
528
599
  }
529
600
  let brk = null;
@@ -541,7 +612,7 @@ function tailStatement(dir, records, checkpointPublicKeyPem) {
541
612
  const covered = brk ? rows.slice(0, brk.index) : rows;
542
613
  const newest = covered.length > 0 ? covered[covered.length - 1] : null;
543
614
  if (!newest) {
544
- return { tail: { line: TAIL_NONE, checkpoint: null }, checkpointTrust, problems };
615
+ return { tail: { line: TAIL_NONE, checkpoint: null }, checkpointTrust, problems, verified };
545
616
  }
546
617
  const claims = newest.claims;
547
618
  const receiptCount = typeof claims.receiptCount === "number" ? claims.receiptCount : null;
@@ -571,6 +642,228 @@ function tailStatement(dir, records, checkpointPublicKeyPem) {
571
642
  tail: { line, checkpoint: { receiptCount, chainHeadHash, ledgerHoldsRecord } },
572
643
  checkpointTrust,
573
644
  problems,
645
+ verified,
646
+ };
647
+ }
648
+ const ANCHORS_NONE = {
649
+ line: "anchors: none (no checkpoint is registered with a transparency service)",
650
+ receipts: 0,
651
+ verified: 0,
652
+ checked: false,
653
+ };
654
+ function anchorStatement(dir, checkpoints, keyPem, problems) {
655
+ const read = readAnchors(dir);
656
+ if (!read.present)
657
+ return ANCHORS_NONE;
658
+ problems.push(...read.problems);
659
+ const receipts = read.rows.length;
660
+ const services = [...new Set(read.rows.map((r) => r.service))].join(", ");
661
+ if (keyPem === "") {
662
+ return {
663
+ line: `anchors: ${receipts} receipt(s) from ${services || "no service"}, not checked: pin the service key with --anchor-key`,
664
+ receipts,
665
+ verified: 0,
666
+ checked: false,
667
+ };
668
+ }
669
+ const byHash = new Map(checkpoints.map((c) => [c.hash, c]));
670
+ let verified = 0;
671
+ let newestCount = null;
672
+ for (const row of read.rows) {
673
+ const short = row.checkpointHash.slice(0, 12);
674
+ const checkpoint = byHash.get(row.checkpointHash);
675
+ if (!checkpoint) {
676
+ problems.push(`anchor names a checkpoint the ledger does not hold: ${short}`);
677
+ continue;
678
+ }
679
+ let entry;
680
+ try {
681
+ entry = anchorEntryHash(row.checkpointHash, row.route);
682
+ }
683
+ catch {
684
+ problems.push(`anchor route is not one this verifier reads: ${short}`);
685
+ continue;
686
+ }
687
+ if (entry !== row.entryHash) {
688
+ problems.push(`anchor entry hash is not the checkpoint's: ${short}`);
689
+ continue;
690
+ }
691
+ const check = verifyReceipt(Buffer.from(row.receiptB64, "base64"), Buffer.from(entry, "hex"), keyPem);
692
+ if (!check.ok) {
693
+ problems.push(`anchor receipt does not verify: ${short} (${check.stage}: ${check.reason})`);
694
+ continue;
695
+ }
696
+ if (check.treeSize !== row.treeSize || check.leafIndex !== row.leafIndex) {
697
+ problems.push(`anchor row disagrees with its receipt: ${short}`);
698
+ continue;
699
+ }
700
+ verified += 1;
701
+ if (checkpoint.receiptCount !== null && (newestCount === null || checkpoint.receiptCount > newestCount)) {
702
+ newestCount = checkpoint.receiptCount;
703
+ }
704
+ }
705
+ const covers = newestCount === null ? "" : `; the newest anchored checkpoint covers ${newestCount} record(s)`;
706
+ return {
707
+ line: verified === receipts
708
+ ? `anchors: ${receipts} receipt(s) from ${services} verify under the key you supplied${covers}`
709
+ : `anchors: ${verified} of ${receipts} receipt(s) verify under the key you supplied`,
710
+ receipts,
711
+ verified,
712
+ checked: true,
713
+ };
714
+ }
715
+ const INPUTS_UNCHECKED = { line: "inputs: not checked", matched: 0, missing: 0, mismatched: 0 };
716
+ /**
717
+ * Pairs each record that carries an `inputsHash` with an inputs row under its
718
+ * ref that hashes to it. Rows are used once. A ref can hold more rows than
719
+ * records (a crash after the row, a retry), so a record is matched against
720
+ * any unused row under its ref, not the k-th.
721
+ */
722
+ function inputsStatement(paths, records, problems) {
723
+ const rowsByRef = new Map();
724
+ for (const path of paths) {
725
+ for (const row of readJsonl(path, problems)) {
726
+ if (!row || typeof row !== "object" || Array.isArray(row))
727
+ continue;
728
+ const { ref, inputs } = row;
729
+ if (typeof ref !== "string" || inputs === undefined)
730
+ continue;
731
+ let hash;
732
+ try {
733
+ hash = sha256Canonical(inputs);
734
+ }
735
+ catch {
736
+ continue;
737
+ }
738
+ const list = rowsByRef.get(ref) ?? [];
739
+ list.push(hash);
740
+ rowsByRef.set(ref, list);
741
+ }
742
+ }
743
+ let matched = 0;
744
+ let missing = 0;
745
+ let mismatched = 0;
746
+ for (let i = 0; i < records.length; i += 1) {
747
+ const claims = records[i].claims;
748
+ const expected = claims?.inputsHash;
749
+ if (typeof expected !== "string")
750
+ continue;
751
+ const ref = typeof claims.ref === "string" ? claims.ref : null;
752
+ const rows = ref === null ? undefined : rowsByRef.get(ref);
753
+ if (!rows || rows.length === 0) {
754
+ missing += 1;
755
+ problems.push(`inputs row missing: record ${i} (ref ${ref ?? "?"})`);
756
+ continue;
757
+ }
758
+ const at = rows.indexOf(expected);
759
+ if (at < 0) {
760
+ mismatched += 1;
761
+ problems.push(`inputs row does not match its record's inputsHash: record ${i} (ref ${ref})`);
762
+ continue;
763
+ }
764
+ rows.splice(at, 1);
765
+ matched += 1;
766
+ }
767
+ const line = missing === 0 && mismatched === 0
768
+ ? `inputs: ${matched} record(s), each with its inputs row`
769
+ : `inputs: ${matched} match, ${missing} missing, ${mismatched} do not match their record`;
770
+ return { line, matched, missing, mismatched };
771
+ }
772
+ /**
773
+ * What a checkpoint counted is fixed by its head. The witness counts the
774
+ * records whose time falls in `[startMs, endMs)` and names the last of them
775
+ * as the head, so the attested records in that window up to and including
776
+ * the head must be `receiptCount` records ending at the head, and their
777
+ * allow, deny and defer counts must be the signed totals (decision profile
778
+ * 4.4). A record appended later with a time inside the window was never seen
779
+ * by the witness and is not counted. A head the ledger does not hold is named
780
+ * for every checkpoint, not only the newest. A null head means the witness
781
+ * counted nothing. Null totals were redacted; the count is still checked.
782
+ */
783
+ function checkpointCountProblems(row, records, attested) {
784
+ const claims = row.claims;
785
+ const { startMs, endMs, receiptCount } = claims;
786
+ if (typeof startMs !== "number" || typeof endMs !== "number")
787
+ return ["checkpoint has no window"];
788
+ const inWindow = (r) => r.claims.timestampMs >= startMs && r.claims.timestampMs < endMs;
789
+ let counted = [];
790
+ let headRecord = null;
791
+ if (typeof claims.chainHeadHash === "string") {
792
+ const at = records.findIndex((r) => {
793
+ try {
794
+ return decisionRecordHash(r) === claims.chainHeadHash;
795
+ }
796
+ catch {
797
+ return false;
798
+ }
799
+ });
800
+ if (at < 0)
801
+ return ["checkpoint names a head the ledger does not hold"];
802
+ headRecord = records[at];
803
+ const upTo = new Set(records.slice(0, at + 1));
804
+ counted = attested.filter((r) => upTo.has(r) && inWindow(r));
805
+ }
806
+ const problems = [];
807
+ const endsAtHead = headRecord === null ? counted.length === 0 : counted[counted.length - 1] === headRecord;
808
+ if (typeof receiptCount !== "number" || receiptCount !== counted.length || !endsAtHead) {
809
+ problems.push(`checkpoint covers ${String(receiptCount)} record(s) in its window; the ledger holds ${counted.length} there up to its head`);
810
+ }
811
+ if (claims.totals !== null && claims.totals !== undefined) {
812
+ let same = false;
813
+ try {
814
+ same = canonical(totalsFromDecisionRecords(counted)) === canonical(claims.totals);
815
+ }
816
+ catch {
817
+ // A totals value that does not canonicalise is not the map the profile defines.
818
+ }
819
+ if (!same)
820
+ problems.push("checkpoint totals do not match the records in its window");
821
+ }
822
+ return problems;
823
+ }
824
+ function controlStatement(records) {
825
+ let open = false;
826
+ let windows = 0;
827
+ let controlRecords = 0;
828
+ const warnings = [];
829
+ const violations = [];
830
+ for (const record of records) {
831
+ const subject = typeof record.claims?.subject === "string" ? record.claims.subject : "";
832
+ const decision = record.claims?.decision;
833
+ const reason = record.claims?.reasonCode;
834
+ const ref = typeof record.claims?.ref === "string" ? record.claims.ref : "?";
835
+ // Only the two control subjects, with the control effect class, open or
836
+ // close a window. Any other allow inside one is a violation, including a
837
+ // downstream tool whose prefix happens to be "verax".
838
+ const control = record.claims?.effectClass === "verax.control";
839
+ const halt = control && decision === "allow" && subject === "verax.halt";
840
+ const resume = control && decision === "allow" && subject === "verax.resume";
841
+ if (halt || resume)
842
+ controlRecords += 1;
843
+ if (halt) {
844
+ if (!open)
845
+ windows += 1;
846
+ open = true;
847
+ continue;
848
+ }
849
+ if (resume) {
850
+ open = false;
851
+ continue;
852
+ }
853
+ if (decision === "allow") {
854
+ if (open)
855
+ violations.push(`allow-while-halted ${ref}`);
856
+ continue;
857
+ }
858
+ if (decision === "deny" && reason === "halted" && !open) {
859
+ warnings.push(`halted-deny-without-halt-record ${ref}`);
860
+ }
861
+ }
862
+ if (controlRecords === 0)
863
+ return { control: { ...CONTROL_NONE, warnings }, violations };
864
+ return {
865
+ control: { line: `control: ${windows} halt window(s)`, windows, warnings },
866
+ violations,
574
867
  };
575
868
  }
576
869
  function unreadableResult(dir, problem) {
@@ -592,6 +885,9 @@ function unreadableResult(dir, problem) {
592
885
  index: { present: false, missing: 0, line: INDEX_NONE },
593
886
  effectCompleteness: EFFECT_COMPLETENESS_UNCHECKED,
594
887
  tail: { line: TAIL_NONE, checkpoint: null },
888
+ control: CONTROL_UNCHECKED,
889
+ inputs: INPUTS_UNCHECKED,
890
+ anchors: ANCHORS_NONE,
595
891
  problems: [problem],
596
892
  };
597
893
  }
@@ -634,6 +930,7 @@ async function verifyLedgerUnchecked(dir, opts = {}) {
634
930
  const emptyTail = tailStatement(dir, records, opts.checkpointPublicKeyPem ?? "");
635
931
  const effectCompleteness = noteEffectCompleteness(emptyIndex.effectRefs, new Set(), problems);
636
932
  problems.push(...emptyIndex.problems, ...emptyTail.problems);
933
+ const emptyControl = controlStatement(records);
637
934
  return {
638
935
  ok: false,
639
936
  directory: dir,
@@ -651,6 +948,9 @@ async function verifyLedgerUnchecked(dir, opts = {}) {
651
948
  index: emptyIndex.index,
652
949
  effectCompleteness,
653
950
  tail: emptyTail.tail,
951
+ control: emptyControl.control,
952
+ inputs: INPUTS_UNCHECKED,
953
+ anchors: ANCHORS_NONE,
654
954
  problems,
655
955
  };
656
956
  }
@@ -671,6 +971,7 @@ async function verifyLedgerUnchecked(dir, opts = {}) {
671
971
  };
672
972
  let signaturesValid = 0;
673
973
  let signaturesInvalid = 0;
974
+ const attested = [];
674
975
  const recordRefused = ed25519Refusal(anahtar);
675
976
  if (recordRefused)
676
977
  problems.push(recordRefused);
@@ -685,6 +986,7 @@ async function verifyLedgerUnchecked(dir, opts = {}) {
685
986
  }
686
987
  if (gecerli) {
687
988
  signaturesValid += 1;
989
+ attested.push(rec);
688
990
  }
689
991
  else {
690
992
  signaturesInvalid += 1;
@@ -841,8 +1143,12 @@ async function verifyLedgerUnchecked(dir, opts = {}) {
841
1143
  }
842
1144
  const indexed = indexStatement(dir, refler);
843
1145
  const effectCompleteness = noteEffectCompleteness(indexed.effectRefs, boundPrimaryRefs, problems);
844
- const tailed = tailStatement(dir, records, opts.checkpointPublicKeyPem ?? "");
1146
+ const inputs = inputsStatement(files.inputs, records, problems);
1147
+ const tailed = tailStatement(dir, records, opts.checkpointPublicKeyPem ?? "", attested);
845
1148
  problems.push(...indexed.problems, ...tailed.problems);
1149
+ const stated = controlStatement(records);
1150
+ problems.push(...stated.violations);
1151
+ const anchors = anchorStatement(dir, tailed.verified, opts.anchorPublicKeyPem?.trim() ?? "", problems);
846
1152
  const ok = problems.length === 0 && signaturesInvalid === 0 && chainBreakAt === null && effectsOrphaned === 0;
847
1153
  return {
848
1154
  ok,
@@ -861,6 +1167,9 @@ async function verifyLedgerUnchecked(dir, opts = {}) {
861
1167
  index: indexed.index,
862
1168
  effectCompleteness,
863
1169
  tail: tailed.tail,
1170
+ control: stated.control,
1171
+ inputs,
1172
+ anchors,
864
1173
  problems,
865
1174
  };
866
1175
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verax-ai/proxy",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "engines": {