@sanning/proof 0.6.0 → 0.8.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/dist/evidence.js CHANGED
@@ -48,6 +48,32 @@ export const ANCHOR_TRACE_BODY_TYPES = [
48
48
  // operator attestations. verifyEvidenceBundle dispatches on it to
49
49
  // verifyExportBody (§5).
50
50
  export const EXPORT_BODY_TYPE = "sanning.evidence.export/v1";
51
+ /**
52
+ * The Sanning-signed interval stamp body (evidence-bundle.md §5.2, DL-58).
53
+ *
54
+ * Its own `body_type` rather than a widened anchor-trace body, and the reason
55
+ * is the whole decision: an anchor-trace checkpoint carries a PRODUCER-signed
56
+ * `sanning.events/v1` envelope, and a stamp has no producer signature at all —
57
+ * Sanning places it, under DL-52, for a customer who holds no chain identity.
58
+ * The two rejected options were making `envelope` optional and synthesising an
59
+ * envelope that Sanning signs; the second would have made a Sanning
60
+ * attestation indistinguishable ON THE WIRE from a producer's, which is
61
+ * unrecoverable once witnessed.
62
+ */
63
+ export const STAMP_TRACE_BODY_TYPE = "sanning.stamp.trace/v1";
64
+ export const STAMP_EVIDENCE_BODY_TYPE = "sanning.stamp.evidence/v1";
65
+ /**
66
+ * The version string INSIDE a witnessed stamp body — a different string from
67
+ * the `body_type` above, and the two are easy to confuse.
68
+ *
69
+ * `sanning.stamp.trace/v1` discriminates the BUNDLE BODY: it is the reader's
70
+ * dispatch key. `sanning.stamp/v1` is the control plane's own version of the
71
+ * bytes it hands a witness (`control-plane/src/stamp-tree.ts`,
72
+ * `STAMP_BODY_VERSION`). A `sanning.stamp.trace/v1` body pins the inner
73
+ * version to exactly this value: two answers to one question inside one
74
+ * signature is the §5.1.2 mixed-vocabulary reject, one layer down.
75
+ */
76
+ export const STAMP_BODY_VERSION = "sanning.stamp/v1";
51
77
  function isEvidenceMajorAccepted(specVersion) {
52
78
  if (typeof specVersion !== "string" || specVersion === "")
53
79
  return false;
@@ -164,6 +190,16 @@ export async function verifyEvidenceBundle(bundle, options = {}) {
164
190
  if (bodyType === EXPORT_BODY_TYPE) {
165
191
  return verifyExportBody(b, specVersionOk, assertedStatus, errors, options);
166
192
  }
193
+ // The Sanning-signed interval stamp body (evidence-bundle.md §5.2). The
194
+ // wrapper is authentic — and for this body that IS "Sanning signed it", since
195
+ // a stamp carries no second signature of its own inside the bundle.
196
+ if (bodyType === STAMP_TRACE_BODY_TYPE) {
197
+ return verifyStampTrace(b, specVersionOk, assertedStatus, errors);
198
+ }
199
+ // The DL-52 hand-over body (§5.3): stamps AND the customer's events, joined.
200
+ if (bodyType === STAMP_EVIDENCE_BODY_TYPE) {
201
+ return verifyStampEvidence(b, specVersionOk, assertedStatus, errors, options);
202
+ }
167
203
  if (bodyType !== ANCHOR_TRACE_BODY_TYPE && bodyType !== ANCHOR_TRACE_BODY_TYPE_V1) {
168
204
  // The wrapper is authentic but we don't know this body's structure. Per
169
205
  // wrap-don't-merge, that is "partial" (cryptographically sound wrapper,
@@ -492,75 +528,10 @@ async function verifyAnchorTrace(b, bodyType, specVersionOk, assertedStatus, err
492
528
  evErrors.push(`inclusion verify error: ${stringifyErr(e)}`);
493
529
  }
494
530
  }
495
- // Content (raw-log) binding — the rawLog → content_hash link the rest of
496
- // the chain (content_hash → record → payload_hash → signature → leaf →
497
- // root) already covers. The committed hash lives in the RECORD
498
- // (record.event.content_hash, minimal disclosure); for a promoted-disclosure
499
- // envelope it falls back to the envelope's own committed hashes
500
- // (contentHashes — NOT verifyEnvelope's path, which reads payload/event_type
501
- // and yields nothing for a sanning.events/v1 envelope). Disclosed bytes come
502
- // from the signed in-body `ev.content` FIRST, then the out-of-band
503
- // options.content side input. Undetermined (null) when nothing is disclosed
504
- // or nothing is committed; false ONLY on a real mismatch or an in-body vs
505
- // side-input disagreement — mirroring payloadBindingOk's never-fail-on-absent
506
- // discipline.
507
- let contentOk = null;
508
- {
509
- const committed = [];
510
- let recordContentHash;
511
- if (recordBytes !== undefined) {
512
- try {
513
- const record = JSON.parse(new TextDecoder().decode(recordBytes));
514
- const ch = record.event?.content_hash;
515
- if (typeof ch === "string" && ch)
516
- recordContentHash = ch.toLowerCase();
517
- }
518
- catch {
519
- // record not JSON — the payload binding already reflects that; content
520
- // stays undetermined rather than throwing.
521
- }
522
- }
523
- if (recordContentHash !== undefined) {
524
- committed.push(recordContentHash);
525
- }
526
- else if (ev.envelope && typeof ev.envelope === "object") {
527
- // Promoted fallback. Guarded: contentHashes() dereferences env.payload,
528
- // which throws on a null/non-object envelope — a verifier must never
529
- // raise on adversarial input (such an event already fails via envelopeOk).
530
- for (const c of contentHashes(ev.envelope))
531
- committed.push(c.hash.toLowerCase());
532
- }
533
- // Disclosed bytes, precedence: in-body (signed) → side input. A string
534
- // side input is hex; a Uint8Array is used as-is. Resolved by the SHARED
535
- // selector so `disclosedContent` hands a consumer the very bytes bound
536
- // here — one decode, not two that can drift apart.
537
- const selection = selectDisclosedBytes(ev, eventId, options.content);
538
- const { inBody, side } = selection;
539
- evErrors.push(...selection.errors);
540
- if (inBody !== undefined && side !== undefined && !bytesEqual(inBody, side)) {
541
- // Two disclosures that disagree: a genuine conflict, not undetermined.
542
- contentOk = false;
543
- evErrors.push("disclosed content disagreement: in-body events[].content and the supplied content differ");
544
- }
545
- else {
546
- const disclosed = inBody ?? side;
547
- if (disclosed === undefined || committed.length === 0) {
548
- contentOk = null;
549
- if (disclosed !== undefined && committed.length === 0) {
550
- evErrors.push("disclosed content present but no committed content_hash to bind to " +
551
- "(record withheld or record has no event.content_hash) — undetermined");
552
- }
553
- }
554
- else {
555
- const got = await sha256Hex(disclosed);
556
- contentOk = committed.includes(got);
557
- if (!contentOk) {
558
- evErrors.push("disclosed content does not match the committed content_hash: " +
559
- `sha256(disclosed)=${got} committed=${committed.join("|")}`);
560
- }
561
- }
562
- }
563
- }
531
+ // Content (raw-log) binding — shared with every other event-carrying body.
532
+ const contentRes = await verifyDisclosedContent(ev, eventId, recordBytes, options.content);
533
+ const contentOk = contentRes.contentOk;
534
+ evErrors.push(...contentRes.errors);
564
535
  eventResults.push({
565
536
  eventId,
566
537
  envelopeOk,
@@ -663,6 +634,562 @@ async function verifyAnchorTrace(b, bodyType, specVersionOk, assertedStatus, err
663
634
  errors,
664
635
  };
665
636
  }
637
+ // ===========================================================================
638
+ // `sanning.stamp.trace/v1` — the Sanning-signed interval stamp (§5.2, DL-58)
639
+ //
640
+ // ── What this can prove, and what it deliberately does not claim ──
641
+ //
642
+ // A stamp is not a producer artifact. Under DL-52 the customer signs an
643
+ // envelope and POSTs it; the commitment is witnessed later, on an interval, by
644
+ // a stamp the customer never sees and holds no key for. So there is no
645
+ // producer signature inside this body to check, and — this is the part worth
646
+ // being precise about — there is no SECOND Sanning signature either. The
647
+ // control plane stores the stamp's canonical bytes and hands them to a witness
648
+ // as a signed chain data item; the signature lives on the chain, not in the
649
+ // `stamps` table and not in this body.
650
+ //
651
+ // What "Sanning signed this" means for a stamp bundle is therefore exactly the
652
+ // WRAPPER signature, verified generically before this function is reached. And
653
+ // what makes the stamp evidence rather than an assertion is the witness, which
654
+ // is on a chain and not checkable offline. Hence the rollup below: a stamp we
655
+ // can read but nobody has witnessed holds the bundle at `partial`.
656
+ //
657
+ // So the checkable surface here is the stamp's INTERNAL consistency against
658
+ // the one authority in the bundle — the witnessed bytes:
659
+ //
660
+ // 1. `stamp_ref` is SHA-256 of the DECODED bytes (derived, not asserted).
661
+ // 2. Those bytes parse and re-canonicalize to themselves under JCS.
662
+ // 3. Their `stamp_version` is the one this body_type pins.
663
+ // 4. Every sub-tree range accounts for exactly one leaf of the stamp.
664
+ //
665
+ // (4) is the one that carries customer weight. R-8's whole per-agent story is
666
+ // "prove this agent was under evidence over window W", answered by a
667
+ // contiguous `first_leaf`/`leaf_count` slice of the org tree. Ranges that do
668
+ // not tile `[0, leaf_count)` describe a partition that does not exist, so a
669
+ // slice claim resting on them is unfounded — and unlike a bad signature,
670
+ // nothing else in the stack would ever notice.
671
+ // ===========================================================================
672
+ /** Lowercase hex, even length, non-empty. The family's serialization rule. */
673
+ function isLowerHex(s, nibbles) {
674
+ if (typeof s !== "string" || s.length === 0 || s.length % 2 !== 0)
675
+ return false;
676
+ if (nibbles !== undefined && s.length !== nibbles)
677
+ return false;
678
+ return /^[0-9a-f]+$/.test(s);
679
+ }
680
+ function isNonNegInt(n) {
681
+ return typeof n === "number" && Number.isInteger(n) && n >= 0;
682
+ }
683
+ /**
684
+ * Parse and check one stamp's witnessed bytes.
685
+ *
686
+ * Errors accumulate rather than short-circuit wherever a later check is still
687
+ * meaningful, so a bundle with two independent defects reports two — a
688
+ * verifier that stops at the first one turns a second fix into a second
689
+ * round-trip.
690
+ */
691
+ // ===========================================================================
692
+ // Disclosed-content binding, shared by every body that carries events.
693
+ //
694
+ // Extracted for `sanning.stamp.evidence/v1` (§5.3) rather than copied. The
695
+ // rawLog -> content_hash link is the one step the chain
696
+ // (content_hash -> record -> payload_hash -> signature -> leaf -> root) does
697
+ // not otherwise cover, and a second copy of it is a second place for the
698
+ // never-fail-on-absent discipline to drift. The rules are unchanged from the
699
+ // anchor-trace path this came from: undetermined (null) when nothing is
700
+ // disclosed or nothing is committed; false ONLY on a real mismatch or an
701
+ // in-body vs side-input disagreement.
702
+ // ===========================================================================
703
+ async function verifyDisclosedContent(ev, eventId, recordBytes, sideContent) {
704
+ const evErrors = [];
705
+ let contentOk = null;
706
+ const committed = [];
707
+ let recordContentHash;
708
+ if (recordBytes !== undefined) {
709
+ try {
710
+ const record = JSON.parse(new TextDecoder().decode(recordBytes));
711
+ const ch = record.event?.content_hash;
712
+ if (typeof ch === "string" && ch)
713
+ recordContentHash = ch.toLowerCase();
714
+ }
715
+ catch {
716
+ // record not JSON — the payload binding already reflects that; content
717
+ // stays undetermined rather than throwing.
718
+ }
719
+ }
720
+ if (recordContentHash !== undefined) {
721
+ committed.push(recordContentHash);
722
+ }
723
+ else if (ev.envelope && typeof ev.envelope === "object") {
724
+ // Promoted fallback. Guarded: contentHashes() dereferences env.payload,
725
+ // which throws on a null/non-object envelope — a verifier must never raise
726
+ // on adversarial input.
727
+ for (const c of contentHashes(ev.envelope))
728
+ committed.push(c.hash.toLowerCase());
729
+ }
730
+ const selection = selectDisclosedBytes(ev, eventId, sideContent);
731
+ const { inBody, side } = selection;
732
+ evErrors.push(...selection.errors);
733
+ if (inBody !== undefined && side !== undefined && !bytesEqual(inBody, side)) {
734
+ contentOk = false;
735
+ evErrors.push("disclosed content disagreement: in-body events[].content and the supplied content differ");
736
+ }
737
+ else {
738
+ const disclosed = inBody ?? side;
739
+ if (disclosed === undefined || committed.length === 0) {
740
+ contentOk = null;
741
+ if (disclosed !== undefined && committed.length === 0) {
742
+ evErrors.push("disclosed content present but no committed content_hash to bind to " +
743
+ "(record withheld or record has no event.content_hash) — undetermined");
744
+ }
745
+ }
746
+ else {
747
+ const got = await sha256Hex(disclosed);
748
+ contentOk = committed.includes(got);
749
+ if (!contentOk) {
750
+ evErrors.push("disclosed content does not match the committed content_hash: " +
751
+ `sha256(disclosed)=${got} committed=${committed.join("|")}`);
752
+ }
753
+ }
754
+ }
755
+ return { contentOk, errors: evErrors };
756
+ }
757
+ async function verifyStampEntry(raw, seen) {
758
+ const errors = [];
759
+ const base = {
760
+ stampRef: "",
761
+ stampRefOk: false,
762
+ bodyOk: false,
763
+ stampVersion: null,
764
+ intervalStart: null,
765
+ intervalEnd: null,
766
+ merkleRoot: null,
767
+ leafCount: null,
768
+ subtreesOk: false,
769
+ subtrees: [],
770
+ anchorRef: null,
771
+ ok: false,
772
+ errors,
773
+ };
774
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
775
+ errors.push("stamp entry is not an object");
776
+ return base;
777
+ }
778
+ const e = raw;
779
+ // --- the witnessed bytes, which are the only authority in this body -------
780
+ if (!isLowerHex(e.stamp_bytes)) {
781
+ errors.push("stamp_bytes is missing or not lowercase hex");
782
+ return base;
783
+ }
784
+ let bytes;
785
+ try {
786
+ bytes = hexToBytes(e.stamp_bytes);
787
+ }
788
+ catch (err) {
789
+ errors.push(`stamp_bytes is not hex: ${stringifyErr(err)}`);
790
+ return base;
791
+ }
792
+ // --- the derived identity -------------------------------------------------
793
+ const derived = await sha256Hex(bytes);
794
+ if (typeof e.stamp_ref !== "string" || e.stamp_ref === "") {
795
+ errors.push("stamp entry missing stamp_ref");
796
+ }
797
+ else if (e.stamp_ref.toLowerCase() !== derived) {
798
+ // The bytes were edited and the label was not — or the label was edited
799
+ // and the bytes were not. Either way the bundle names a stamp it is not
800
+ // carrying, and quoting that name to a witness would resolve to something
801
+ // else entirely.
802
+ errors.push(`stamp_ref does not match SHA-256(stamp_bytes): claimed=${e.stamp_ref} derived=${derived}`);
803
+ }
804
+ else {
805
+ base.stampRefOk = true;
806
+ base.stampRef = derived;
807
+ if (seen.has(derived)) {
808
+ errors.push(`duplicate stamp_ref ${derived}`);
809
+ base.stampRefOk = false;
810
+ }
811
+ else {
812
+ seen.add(derived);
813
+ }
814
+ }
815
+ // --- the body itself ------------------------------------------------------
816
+ let body;
817
+ try {
818
+ const parsed = JSON.parse(new TextDecoder().decode(bytes));
819
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
820
+ errors.push("stamp body is not a JSON object");
821
+ return base;
822
+ }
823
+ body = parsed;
824
+ // Re-canonicalize and compare. The plane replays these bytes verbatim on
825
+ // every submit attempt for exactly this reason: a non-canonical body makes
826
+ // a retry a DIFFERENT submission, and makes every independent re-derivation
827
+ // of the stamp disagree with the one that was witnessed.
828
+ if (jcs(body) !== new TextDecoder().decode(bytes)) {
829
+ errors.push("stamp_bytes are not JCS-canonical (RFC 8785)");
830
+ return base;
831
+ }
832
+ }
833
+ catch (err) {
834
+ errors.push(`stamp body is not JSON: ${stringifyErr(err)}`);
835
+ return base;
836
+ }
837
+ if (body.stamp_version !== STAMP_BODY_VERSION) {
838
+ // A `sanning.stamp.trace/v1` body whose inner version is something else is
839
+ // two answers to one question inside one signature. The body_type is the
840
+ // reader's dispatch key and it said v1; honouring the other spelling is
841
+ // how a reader half-parses a shape it does not know.
842
+ errors.push(`unsupported stamp_version ${JSON.stringify(body.stamp_version)} in a ` +
843
+ `${STAMP_TRACE_BODY_TYPE} body (expected ${STAMP_BODY_VERSION})`);
844
+ return base;
845
+ }
846
+ base.stampVersion = body.stamp_version;
847
+ base.bodyOk = true;
848
+ for (const f of ["org_ref", "interval_start", "interval_end"]) {
849
+ if (typeof body[f] !== "string" || body[f] === "") {
850
+ errors.push(`stamp body ${f} is missing or not a non-empty string`);
851
+ base.bodyOk = false;
852
+ }
853
+ }
854
+ base.intervalStart = typeof body.interval_start === "string" ? body.interval_start : null;
855
+ base.intervalEnd = typeof body.interval_end === "string" ? body.interval_end : null;
856
+ if (!isLowerHex(body.merkle_root, 64)) {
857
+ errors.push("stamp body merkle_root is not 64 lowercase hex characters");
858
+ base.bodyOk = false;
859
+ }
860
+ else {
861
+ base.merkleRoot = body.merkle_root;
862
+ }
863
+ if (!isNonNegInt(body.leaf_count)) {
864
+ errors.push("stamp body leaf_count is not a non-negative integer");
865
+ base.bodyOk = false;
866
+ }
867
+ else {
868
+ base.leafCount = body.leaf_count;
869
+ }
870
+ // --- the sub-tree ranges --------------------------------------------------
871
+ base.subtreesOk = checkSubtrees(body, base, errors);
872
+ base.anchorRef = parseAnchorRef(e.anchor_ref, errors);
873
+ base.ok =
874
+ base.stampRefOk && base.bodyOk && base.subtreesOk && errors.length === 0;
875
+ return base;
876
+ }
877
+ /**
878
+ * The range arithmetic (§5.2), and the reason it is a hard check.
879
+ *
880
+ * `buildStampTree` orders a stamp's leaves agent-major, which is the only
881
+ * reason `first_leaf` + `leaf_count` can describe an agent's slice at all: the
882
+ * ranges partition `[0, leaf_count)` exactly, by construction. A body whose
883
+ * ranges do not is either not a stamp this stack built or one built wrong, and
884
+ * in both cases the per-agent claim the ranges exist to support is unfounded.
885
+ *
886
+ * The sum is checked BEFORE the tiling and reports its own message, so a body
887
+ * that is merely short does not get filed under a gap it does not have.
888
+ */
889
+ function checkSubtrees(body, out, errors) {
890
+ const raw = body.subtrees;
891
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
892
+ errors.push("stamp body subtrees is not an object");
893
+ return false;
894
+ }
895
+ let shapeOk = true;
896
+ const subtrees = [];
897
+ for (const [ref, v] of Object.entries(raw)) {
898
+ if (v === null || typeof v !== "object" || Array.isArray(v)) {
899
+ errors.push(`sub-tree ${ref} is not an object`);
900
+ shapeOk = false;
901
+ continue;
902
+ }
903
+ const s = v;
904
+ if (!isNonNegInt(s.first_leaf)) {
905
+ errors.push(`sub-tree ${ref} first_leaf is not a non-negative integer`);
906
+ shapeOk = false;
907
+ }
908
+ // A zero-leaf sub-tree is not a slice of anything, and admitting one lets
909
+ // an arbitrary number of empty ranges sit inside a tiling that still adds
910
+ // up.
911
+ if (!isNonNegInt(s.leaf_count) || s.leaf_count === 0) {
912
+ errors.push(`sub-tree ${ref} leaf_count is not a positive integer`);
913
+ shapeOk = false;
914
+ }
915
+ if (!isLowerHex(s.root, 64)) {
916
+ errors.push(`sub-tree ${ref} root is not 64 lowercase hex characters`);
917
+ shapeOk = false;
918
+ }
919
+ if (!shapeOk)
920
+ continue;
921
+ subtrees.push({
922
+ ref,
923
+ firstLeaf: s.first_leaf,
924
+ leafCount: s.leaf_count,
925
+ root: s.root,
926
+ });
927
+ }
928
+ subtrees.sort((a, b) => a.firstLeaf - b.firstLeaf);
929
+ out.subtrees = subtrees;
930
+ if (!shapeOk)
931
+ return false;
932
+ const total = body.leaf_count;
933
+ if (!isNonNegInt(total))
934
+ return false; // already reported by the caller
935
+ const sum = subtrees.reduce((n, s) => n + s.leafCount, 0);
936
+ if (sum !== total) {
937
+ errors.push(`sub-tree leaf_count sum ${sum} does not equal the stamp's leaf_count ${total}`);
938
+ return false;
939
+ }
940
+ let next = 0;
941
+ for (const s of subtrees) {
942
+ if (s.firstLeaf !== next) {
943
+ errors.push(`sub-tree ranges do not tile [0, ${total}): expected a range at leaf ` +
944
+ `${next}, found one at ${s.firstLeaf}`);
945
+ return false;
946
+ }
947
+ next += s.leafCount;
948
+ }
949
+ return true;
950
+ }
951
+ async function verifyStampTrace(b, specVersionOk, assertedStatus, errors) {
952
+ const body = b.body;
953
+ if (!Array.isArray(body?.stamps)) {
954
+ return malformed(`${STAMP_TRACE_BODY_TYPE} body must have stamps[]`, true);
955
+ }
956
+ const seen = new Set();
957
+ const stamps = [];
958
+ for (const entry of body.stamps) {
959
+ stamps.push(await verifyStampEntry(entry, seen));
960
+ }
961
+ // --- Rollup ----------------------------------------------------------------
962
+ const anyHardFailure = stamps.some((s) => !s.ok);
963
+ const anyUnwitnessed = stamps.some((s) => s.anchorRef === null);
964
+ let status;
965
+ if (anyHardFailure) {
966
+ status = "failed";
967
+ }
968
+ else if (stamps.length === 0) {
969
+ // A bundle asserting nothing. Not a failure — nothing here is wrong — but
970
+ // it must never read `verified`, which a caller would take as a witness it
971
+ // does not have.
972
+ status = "partial";
973
+ errors.push(`${STAMP_TRACE_BODY_TYPE} body carries no stamps`);
974
+ }
975
+ else if (anyUnwitnessed) {
976
+ // The honest half of P-10, one layer up. A stamp with no `anchor_ref` is
977
+ // sealed and unwitnessed: `retained-by-sanning`, which is a statement about
978
+ // our coverage and never an accusation about their evidence. It is also not
979
+ // `verified`, because for a stamp the witness is the entire independent
980
+ // part — unlike an anchor-trace checkpoint, which still carries a producer
981
+ // signature and an inclusion proof that stand on their own offline.
982
+ status = "partial";
983
+ errors.push("one or more stamps carries no anchor_ref — sealed by Sanning, witnessed by nobody");
984
+ }
985
+ else {
986
+ status = "verified";
987
+ }
988
+ return {
989
+ status,
990
+ specVersionOk,
991
+ bodyHashOk: true,
992
+ signatureOk: true,
993
+ bodyType: STAMP_TRACE_BODY_TYPE,
994
+ onChainChecked: false,
995
+ checkpoints: [],
996
+ events: [],
997
+ assertedStatus,
998
+ stamps,
999
+ errors,
1000
+ };
1001
+ }
1002
+ // ===========================================================================
1003
+ // `sanning.stamp.evidence/v1` — the two halves, bound (evidence-bundle.md §5.3)
1004
+ //
1005
+ // The stamp half is §5.2's code unchanged (`verifyStampEntry`, which carries
1006
+ // the sub-tree partition check). The event half reuses the same primitives the
1007
+ // anchor-trace path uses — `verifyEnvelope`, `verifyInclusion`, `leafHash`,
1008
+ // `verifyDisclosedContent` — because a second copy of Merkle verification is a
1009
+ // second place for it to drift.
1010
+ //
1011
+ // What differs, and only this: the join. An event resolves `inclusion.stamp_ref`
1012
+ // to a stamps[] entry and walks its audit path to the root committed INSIDE
1013
+ // that stamp's witnessed bytes. There is no `merkle_root` field on the event to
1014
+ // read instead — repeating the root beside its own authoritative bytes would be
1015
+ // two answers to one question inside one signature (§5.1.2).
1016
+ // ===========================================================================
1017
+ async function verifyStampEvidence(b, specVersionOk, assertedStatus, errors, options) {
1018
+ const body = b.body;
1019
+ if (!Array.isArray(body?.stamps) || !Array.isArray(body?.events)) {
1020
+ return malformed(`${STAMP_EVIDENCE_BODY_TYPE} body must have stamps[] and events[]`, true);
1021
+ }
1022
+ // --- The stamp half: §5.2's rules, §5.2's code ----------------------------
1023
+ const seen = new Set();
1024
+ const stamps = [];
1025
+ for (const entry of body.stamps)
1026
+ stamps.push(await verifyStampEntry(entry, seen));
1027
+ // The join table. ONLY a stamp whose derived ref and witnessed bytes both
1028
+ // checked out is joinable: a root read out of bytes that failed their own
1029
+ // verification is not a root anyone should walk a proof to, and admitting one
1030
+ // would let a broken stamp lend its authority to an event.
1031
+ const byRef = new Map();
1032
+ for (const st of stamps) {
1033
+ if (st.stampRef && st.stampRefOk && st.bodyOk)
1034
+ byRef.set(st.stampRef, st);
1035
+ }
1036
+ // --- The event half -------------------------------------------------------
1037
+ const eventResults = [];
1038
+ for (const rawEv of body.events) {
1039
+ const evErrors = [];
1040
+ // A verifier must never RAISE on adversarial input — a caller handed a
1041
+ // stack trace instead of a verdict cannot tell a malformed pack from a
1042
+ // broken tool. `events[]` is attacker-shaped, so a null/non-object entry
1043
+ // is coerced to an empty event and fails through the normal path, exactly
1044
+ // as the Python kernel does. Found by adversarial review, not by the
1045
+ // cross-kernel leg — whose cases did not include one, and now do.
1046
+ if (rawEv === null || typeof rawEv !== "object" || Array.isArray(rawEv)) {
1047
+ // NOT an event. Graded and reported as such rather than coerced to an
1048
+ // empty one: probing verifyEnvelope with nothing asks the envelope layer
1049
+ // a question about an object that was never an envelope, and the two
1050
+ // kernels answer it differently (undetermined vs failed) — a real
1051
+ // divergence, but not this body's to resolve. Reported separately.
1052
+ eventResults.push({
1053
+ eventId: "<unknown>",
1054
+ envelopeOk: false,
1055
+ payloadBindingOk: null,
1056
+ inclusionOk: false,
1057
+ checkpointBound: false,
1058
+ contentOk: null,
1059
+ ok: false,
1060
+ errors: ["events[] entry is not an object"],
1061
+ });
1062
+ continue;
1063
+ }
1064
+ const ev = rawEv;
1065
+ const eventId = getEventId(ev.envelope);
1066
+ let envelopeOk = false;
1067
+ let payloadBindingOk = null;
1068
+ let recordBytes;
1069
+ try {
1070
+ if (typeof ev.record_bytes === "string")
1071
+ recordBytes = hexToBytes(ev.record_bytes);
1072
+ }
1073
+ catch (e) {
1074
+ evErrors.push(`event record_bytes is not hex: ${stringifyErr(e)}`);
1075
+ }
1076
+ try {
1077
+ const res = await verifyEnvelope(ev.envelope, recordBytes !== undefined ? { payloadBytes: recordBytes } : {});
1078
+ envelopeOk = res.ok; // tolerates an undetermined binding (withheld record)
1079
+ payloadBindingOk = res.payloadHashOk;
1080
+ if (!res.signatureOk)
1081
+ evErrors.push("event envelope signature failed");
1082
+ if (res.payloadHashOk === false)
1083
+ evErrors.push("event record does not bind to payload_hash");
1084
+ }
1085
+ catch (e) {
1086
+ evErrors.push(`event envelope verify error: ${stringifyErr(e)}`);
1087
+ }
1088
+ // --- The join (§5.3.3 rule 1) -------------------------------------------
1089
+ const incl = ev.inclusion;
1090
+ let st;
1091
+ if (!incl || typeof incl !== "object") {
1092
+ evErrors.push("event missing inclusion proof");
1093
+ }
1094
+ else if (incl.checkpoint_ref !== undefined || incl.checkpoint_tx_id !== undefined) {
1095
+ // One bundle speaks one vocabulary. An inclusion carrying an anchor-trace
1096
+ // join key inside this body is a mixed bundle, and resolving it anyway is
1097
+ // how an event silently binds to something nobody meant (§5.1.2).
1098
+ evErrors.push(`event inclusion carries an anchor-trace join key in a ${STAMP_EVIDENCE_BODY_TYPE} body`);
1099
+ }
1100
+ else if (typeof incl.stamp_ref !== "string") {
1101
+ evErrors.push("event inclusion missing stamp_ref");
1102
+ }
1103
+ else {
1104
+ st = byRef.get(incl.stamp_ref);
1105
+ if (st === undefined) {
1106
+ // Hard reject, never undetermined: without a resolved stamp the
1107
+ // inclusion proof has no root to check against at all.
1108
+ evErrors.push(`event inclusion.stamp_ref ${JSON.stringify(incl.stamp_ref)} resolves to no verified stamp`);
1109
+ }
1110
+ }
1111
+ const stampBound = st !== undefined;
1112
+ let inclusionOk = false;
1113
+ if (incl && stampBound && st) {
1114
+ // Rule 3: the tree walked must be the tree the stamp committed to. A
1115
+ // proof walked against a different leaf_count is a proof about a
1116
+ // different tree, and RFC 9162's path shape depends on the size.
1117
+ if (st.leafCount !== null && incl.leaf_count !== st.leafCount) {
1118
+ evErrors.push(`inclusion leaf_count ${incl.leaf_count} does not equal the stamp's committed ` +
1119
+ `leaf_count ${st.leafCount}`);
1120
+ }
1121
+ else {
1122
+ try {
1123
+ inclusionOk = await verifyInclusion(hexToBytes(incl.leaf_hash), incl.leaf_index, incl.leaf_count, (incl.audit_path ?? []).map((h) => hexToBytes(h)), hexToBytes(st.merkleRoot ?? ""));
1124
+ if (!inclusionOk) {
1125
+ evErrors.push("RFC 9162 inclusion proof did not reconstruct the stamp root");
1126
+ }
1127
+ // Defense in depth, as §5.1: the claimed leaf MUST be this event's
1128
+ // own signed envelope bytes, or a valid proof for an UNRELATED leaf
1129
+ // could be smuggled in.
1130
+ const expectedLeafHex = toHex(await leafHash(utf8(jcs(ev.envelope))));
1131
+ if (expectedLeafHex !== (incl.leaf_hash ?? "").toLowerCase()) {
1132
+ inclusionOk = false;
1133
+ evErrors.push("inclusion leaf_hash does not match SHA-256(0x00 || JCS(event envelope))");
1134
+ }
1135
+ }
1136
+ catch (e) {
1137
+ evErrors.push(`inclusion verify error: ${stringifyErr(e)}`);
1138
+ }
1139
+ }
1140
+ }
1141
+ const contentRes = await verifyDisclosedContent(ev, eventId, recordBytes, options.content);
1142
+ const contentOk = contentRes.contentOk;
1143
+ evErrors.push(...contentRes.errors);
1144
+ eventResults.push({
1145
+ eventId,
1146
+ envelopeOk,
1147
+ payloadBindingOk,
1148
+ inclusionOk,
1149
+ // Named for §5.1's join; here it reports whether `stamp_ref` resolved.
1150
+ checkpointBound: stampBound,
1151
+ contentOk,
1152
+ ok: envelopeOk && inclusionOk && stampBound && contentOk !== false,
1153
+ errors: evErrors,
1154
+ });
1155
+ }
1156
+ // --- Rollup ---------------------------------------------------------------
1157
+ // Rule 4: a declared event MUST be checked. `events[]` present and unverified
1158
+ // is the false green this body exists to prevent, so an event that did not
1159
+ // verify fails the bundle — it is never rolled up as verified.
1160
+ const anyHardFailure = stamps.some((st) => !st.ok) || eventResults.some((e) => !e.ok);
1161
+ const anyUnwitnessed = stamps.some((st) => st.anchorRef === null);
1162
+ let status;
1163
+ if (anyHardFailure) {
1164
+ status = "failed";
1165
+ }
1166
+ else if (stamps.length === 0 && eventResults.length === 0) {
1167
+ status = "partial";
1168
+ errors.push(`${STAMP_EVIDENCE_BODY_TYPE} body carries no stamps and no events`);
1169
+ }
1170
+ else if (anyUnwitnessed) {
1171
+ // §5.3.3 rule 6, inherited whole from §5.2.4: for a stamp the witness IS
1172
+ // the independent part, so the events resting on it inherit `partial`.
1173
+ status = "partial";
1174
+ errors.push("one or more stamps carries no anchor_ref — sealed by Sanning, witnessed by nobody");
1175
+ }
1176
+ else {
1177
+ status = "verified";
1178
+ }
1179
+ return {
1180
+ status,
1181
+ specVersionOk,
1182
+ bodyHashOk: true,
1183
+ signatureOk: true,
1184
+ bodyType: STAMP_EVIDENCE_BODY_TYPE,
1185
+ onChainChecked: false,
1186
+ checkpoints: [],
1187
+ events: eventResults,
1188
+ assertedStatus,
1189
+ stamps,
1190
+ errors,
1191
+ };
1192
+ }
666
1193
  // How many `sanning.evidence.export/v1` wrappers deep the source bundle may be
667
1194
  // nested before this path gives up. verifyEvidenceBundle's canonicalization
668
1195
  // depth bound already rejects a pathological bundle, but the unwrap must be
@@ -779,7 +1306,13 @@ export async function disclosedContent(bundle, options = {}) {
779
1306
  // wrapper(s) to the inline source bundle — mirroring how verifyEvidenceBundle
780
1307
  // recurses into `source_bundle`, so the events line up with its results.
781
1308
  // `undefined` when there is no anchor-trace body to materialize from.
782
- function resolveTraceEvents(bundle) {
1309
+ //
1310
+ // Exported for `chain.ts`, which needs the same descent and must not derive it
1311
+ // again: two answers to "which events is this bundle actually about" inside one
1312
+ // kernel is two implementations of one rule, and the one that drifted would be
1313
+ // the one nobody was looking at. Deliberately NOT re-exported from `index.ts` —
1314
+ // same posture as `side-content.ts`, internal and shared.
1315
+ export function resolveTraceEvents(bundle) {
783
1316
  let cur = bundle;
784
1317
  for (let depth = 0; depth < MAX_EXPORT_UNWRAP; depth++) {
785
1318
  if (cur === null || typeof cur !== "object" || Array.isArray(cur))