@sanning/proof 0.9.2 → 0.11.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.
@@ -0,0 +1,598 @@
1
+ // The hand-off pairing rule of specs/envelope-spec.md §4.1 (v1.9).
2
+ //
3
+ // Two agents exchange a message and each side records what it held. This module
4
+ // is the TypeScript half of the reference reading of those two records: which
5
+ // records are candidates to be the counterpart of a given one, how a candidate
6
+ // set of more than one is ordered, and what a formed pair grades to. The
7
+ // Python half is src/sanning_proof/handoff.py, and the two have to answer
8
+ // identically on identical bytes.
9
+ //
10
+ // WHY IT IS WRITTEN THIS WAY (proof#132, ratified by Phil 2026-09-21)
11
+ //
12
+ // §4.1 as ratified at v1.7 formed a pair from three conjuncts, all three chosen
13
+ // by the party being audited and none of them graded: `context.case_id`, the
14
+ // mutual naming of each other's key in `event.counterparty_public_key`, and the
15
+ // two record types. A receiving side that had tampered with a message could
16
+ // change ONE of them, form no pair at all, and have its deviation surface as
17
+ // two absences, which §4.1 obliges a reader to treat as innocent.
18
+ //
19
+ // The amended rule turns on the one thing no party can choose for another:
20
+ //
21
+ // - Candidates come from who SIGNED. The candidates for a `handoff.sent` are
22
+ // the `handoff.received` records signed by the key it named, read from each
23
+ // envelope's own `public_key`, which is the binding of §2 and cannot be
24
+ // forged. Apart from which of the two types it is, nothing a candidate
25
+ // asserts about itself takes it out of that set.
26
+ // - Narrowing orders and annotates, and never reduces what is graded.
27
+ // `context.case_id` and `event.sequence` put the candidate a reader is most
28
+ // likely to want first in the report and remove none of them from grading.
29
+ // A narrowing that could drop a candidate was itself a laundering path:
30
+ // publish the tampered receipt with one of those two fields changed beside
31
+ // a clean decoy that carries them, and the step that "leaves at least one
32
+ // candidate" leaves the decoy and drops the tamper.
33
+ // - More than one candidate is a named finding, never a free choice: a reader
34
+ // permitted to take one match can be handed an honest decoy beside a
35
+ // tampered record. The per-candidate readings travel with the report, so
36
+ // naming the record and the check that failed survives a junk record that
37
+ // outranks it.
38
+ // - A record missing a REQUIRED field of its own type is `malformed`, so a
39
+ // pair that commits to nothing never reaches the check that would have
40
+ // compared absent to absent and found them equal.
41
+ // - A pair whose two envelope signing keys are equal does not verify.
42
+ // - Every hand-off record a reader holds is read, not only the ones that pair.
43
+ //
44
+ // THE THREE ATTACKS THE ADVERSARIAL GATE LANDED (proof#133, rulings 1 to 3),
45
+ // and they are one root cause: candidacy and the self-hand-off check compared
46
+ // the envelope `public_key` as a STRING, and nothing constrains its spelling,
47
+ // so the party being audited chose it.
48
+ //
49
+ // - A key is compared as a KEY (`normalizedSigningKey`). The record side of a
50
+ // key is pinned to 64-char lowercase hex and the envelope side is pinned
51
+ // nowhere, so a receiving side that spelled its own envelope key in upper
52
+ // case decided whether its own record was a candidate at all: one character
53
+ // class on one field put a tampered receipt beside a clean decoy back at
54
+ // `verified` with no ambiguity named, and read a self-hand-off signed by
55
+ // one key as a transfer between two parties. The normalization sits on the
56
+ // `HeldRecord` boundary so a reader cannot skip it. Whether the ENVELOPE
57
+ // layer starts rejecting a non-lowercase `public_key` is a
58
+ // wire-compatibility question and a founder call (proof#135); nothing here
59
+ // changes what an envelope accepts.
60
+ // - The reserved namespace bites on any spelling a reader would take for a
61
+ // hand-off record (`isHandoffNamespace`). An exact `handoff.` prefix let
62
+ // `HANDOFF.RECEIVED`, `sanning.handoff.received`, `handoff-received` and a
63
+ // non-string `event_type` disappear from the reading entirely, not even as
64
+ // malformed, which composed with a decoy reads `verified` over proven
65
+ // tampering from one edit.
66
+ //
67
+ // THE TWO THE FOURTH HUNT LANDED ON THAT REPAIR (proof#133, rulings 1 and 2),
68
+ // and they are one root cause too: each test above was an allow-list over a
69
+ // value the audited party writes. Candidacy turned on the spelling of a key and
70
+ // scope turned on the spelling of a name, so narrowing the allow-list only
71
+ // moved the boundary and the next spelling walked around it.
72
+ //
73
+ // - Scope turns on the STRUCTURE (`isHandoffNamespace`). A record carrying
74
+ // `event.counterparty_public_key`, the field §4.1 defines and no other
75
+ // section does, is read whatever its `event_type` says, which closes the
76
+ // `ff` ligature, full-width letters, a Cyrillic `a`, `hand-off`,
77
+ // `handoffs`, a zero-width space, a BOM and a non-breaking space in one
78
+ // rule rather than by chasing Unicode. The folded name stays as an
79
+ // additional way in for a record that omits the field.
80
+ // - A key that does not parse makes the record `malformed`, never absent
81
+ // (`recordIsMalformed`). The rule it replaces let such a record drop out
82
+ // of candidacy in silence, and the other side then read
83
+ // `counterpart_absent`, which §4.1 obliges a reader to call innocent.
84
+ // Nine whitespace spellings of a real key produce a VERIFIED envelope in
85
+ // exactly that state in the Python kernel, so the first attack came back
86
+ // whole THROUGH the repair. Nothing here changes what an envelope accepts,
87
+ // and the rule holds either way proof#135 goes.
88
+ //
89
+ // WHAT THE FIFTH HUNT LANDED ON THAT REPAIR, AND WHY THIS ONE IS DIFFERENT
90
+ // (proof#136, ratified by Phil 2026-09-22). Scope was two clauses and both
91
+ // operands are written by the party being audited: an exact test for the key
92
+ // name `counterparty_public_key`, and an ASCII fold of `event_type`. One code
93
+ // point on each (`counterparty_public_k\u0435y` with a Cyrillic `\u0435`,
94
+ // `hando\ufb00.received` with a ligature) put the record in scope by NEITHER
95
+ // route, so it had no reading at all and the pile read `verified`.
96
+ //
97
+ // - Scope stops existing. `readHandoffs` returns a reading for EVERY record
98
+ // it is given, in the order given, and a record that is not a conformant
99
+ // hand-off reads with `NOT_A_HANDOFF_FINDING` rather than producing
100
+ // silence. Any rule with a silent branch is a rule the audited party
101
+ // steers into: five repairs narrowed which values reached the branch and
102
+ // five hunts found a value outside it, so the branch is removed rather
103
+ // than narrowed a sixth time.
104
+ // - The declaration names the hand-offs (`isConformantHandoffRecord`, read
105
+ // by `./declaration.ts`). The gain was that a record could be unreadable
106
+ // NOW and usable LATER; a claimed side that is not a conformant hand-off
107
+ // record now fails at the pack layer.
108
+ // - Missing and explicit null name one thing (`namedCase`). Python's missing
109
+ // value is `None` and this kernel's is `undefined`, so a candidate
110
+ // carrying `"case_id": null` was "same case" in one kernel and not in the
111
+ // other: same verdict, different candidate ORDER, on a value the audited
112
+ // party writes.
113
+ //
114
+ // No verdict word is coined: `verified`, `failed` and `malformed` are already in
115
+ // use, and `counterpart_absent`, `counterpart_ambiguous` and
116
+ // `not_a_handoff_record` are findings reported beside a verdict rather than
117
+ // verdicts.
118
+ //
119
+ // THE COST OF GRADING EVERY CANDIDATE, stated rather than left to be found. A
120
+ // reader whose pile holds two or more records of the complementary type signed
121
+ // by the counterparty key can no longer reach `verified`: every one of them is
122
+ // graded and the worst of them is the reading. Two agents that exchange more
123
+ // than one message land there. That is the price of never letting a value the
124
+ // audited party writes decide what reaches a check, and the belt is the pack
125
+ // layer: the declaration (evidence-bundle.md 5.4) says which records a pack
126
+ // claims are a pair.
127
+ export const CANDIDATE_NAMESPACE = "handoff.";
128
+ export const DEFINED_EVENT_TYPES = ["handoff.sent", "handoff.received"];
129
+ /**
130
+ * The finding a record that is not a hand-off record at all reads with.
131
+ *
132
+ * A FINDING and not a verdict: the ratified verdict words are closed
133
+ * (anchor#188) and this reading names an outcome beside one, exactly as
134
+ * `counterpart_absent`, `counterpart_ambiguous` and `malformed_record` do. It
135
+ * exists because 4.1 had a SILENT branch, and a rule with a silent branch is a
136
+ * rule the party being audited steers into (proof#136). A record TRYING to be
137
+ * a hand-off and getting it wrong reads `malformed`; a record that is not a
138
+ * hand-off at all reads this. Both are readings. Neither is silence.
139
+ */
140
+ export const NOT_A_HANDOFF_FINDING = "not_a_handoff_record";
141
+ const OUTCOMES = ["accepted", "rejected", "failed"];
142
+ const ID_PATTERN = /^[A-Za-z0-9_.:-]+$/;
143
+ const HEX64 = /^[0-9a-fA-F]{64}$/;
144
+ const LOWER_HEX64 = /^[0-9a-f]{64}$/;
145
+ // The order a reader names the checks a formed pair failed, fixed so two
146
+ // kernels report one list rather than two orderings of it.
147
+ const CHECK_ORDER = ["message_hash", "sequence", "self_handoff"];
148
+ const VERDICT_RANK = { verified: 0, failed: 1, malformed: 2 };
149
+ // ASCII whitespace, listed rather than delegated: `String.trim()` and Python's
150
+ // `str.strip()` do not strip the same set (`U+FEFF` is whitespace to one and
151
+ // not to the other), and a fold the two kernels disagree about is a divergence
152
+ // on identical bytes (proof#133 review, ruling 3).
153
+ const ASCII_WHITESPACE = new Set([" ", "\t", "\n", "\r", "\v", "\f"]);
154
+ /**
155
+ * An envelope `public_key` as a KEY rather than as a string: the 32 key bytes
156
+ * written as lowercase hex, or `null` where the value is not 64 characters of
157
+ * hex and so names no key this reading can compare.
158
+ *
159
+ * Case is the whole point: §2 states lowercase as a PRODUCER convention, the
160
+ * envelope layer accepts either case in every kernel, and the party being
161
+ * audited is the producer (proof#133 adversarial gate, ruling 1). Nothing
162
+ * wider is folded: whitespace inside the value is not stripped, because
163
+ * Python's `bytes.fromhex` skips ASCII whitespace and this kernel's charset
164
+ * check does not, a live divergence at the ENVELOPE layer and a separate
165
+ * founder call (proof#135). A reading rule that silently repaired it would
166
+ * hide it.
167
+ */
168
+ export function normalizedSigningKey(value) {
169
+ if (typeof value !== "string" || !HEX64.test(value))
170
+ return null;
171
+ return [...value]
172
+ .map((c) => (c >= "A" && c <= "Z" ? String.fromCharCode(c.charCodeAt(0) + 32) : c))
173
+ .join("");
174
+ }
175
+ /**
176
+ * Whether two envelope keys are the SAME KEY. Two values that name a key are
177
+ * equal when their key bytes are equal.
178
+ *
179
+ * Where either side names no key, the question cannot be answered from key
180
+ * bytes and the answer is the conservative one: the two are reported as one
181
+ * key, so the pair reads `failed[self_handoff]` rather than clean. Exact
182
+ * string equality was the answer here and it was the wrong way round: one key
183
+ * that signed both ends, spelled `abcd...` on one envelope and `abcd ...` on
184
+ * the other, is one party, and string equality called it two and read the
185
+ * self-hand-off `verified` (proof#133 fourth hunt, finding 1). A record whose
186
+ * own envelope key this reading cannot read is `malformed` under
187
+ * `recordIsMalformed` and a formed pair reaches `malformed` before it reaches
188
+ * this line, so the two rules are belt and braces rather than one rule stated
189
+ * twice.
190
+ */
191
+ export function sameSigningKey(left, right) {
192
+ const leftKey = normalizedSigningKey(left);
193
+ const rightKey = normalizedSigningKey(right);
194
+ if (leftKey === null || rightKey === null)
195
+ return true;
196
+ return leftKey === rightKey;
197
+ }
198
+ /**
199
+ * The spelling of an `event_type`, folded for the namespace test only: ASCII
200
+ * whitespace off each end, ASCII upper case down to lower case, and `-` and
201
+ * `_` read as the `.` separator. Every step is spelled out rather than
202
+ * delegated to `toLowerCase()` or `trim()`, which do not agree with Python on
203
+ * non-ASCII input.
204
+ */
205
+ function foldEventType(value) {
206
+ const characters = [...value];
207
+ let start = 0;
208
+ let end = characters.length;
209
+ while (start < end && ASCII_WHITESPACE.has(characters[start]))
210
+ start += 1;
211
+ while (end > start && ASCII_WHITESPACE.has(characters[end - 1]))
212
+ end -= 1;
213
+ return characters
214
+ .slice(start, end)
215
+ .map((c) => {
216
+ if (c === "-" || c === "_")
217
+ return ".";
218
+ return c >= "A" && c <= "Z" ? String.fromCharCode(c.charCodeAt(0) + 32) : c;
219
+ })
220
+ .join("");
221
+ }
222
+ /**
223
+ * Whether a reader reads this record as a hand-off record at all.
224
+ *
225
+ * §4.1 says a reader reads EVERY hand-off record it holds, and an exact
226
+ * `handoff.` prefix did not deliver that: `HANDOFF.RECEIVED`,
227
+ * `sanning.handoff.received`, `handoff-received` and a non-string `event_type`
228
+ * all vanished from the reading entirely, not even as malformed, so a receipt
229
+ * typed one character outside the prefix was never read and, beside a clean decoy,
230
+ * published `verified` over proven tampering (proof#133 adversarial gate,
231
+ * ruling 2).
232
+ *
233
+ * The rule is checkable rather than a judgement, and it is exactly two
234
+ * clauses. The FIRST is the one the adversary cannot evade: the record's
235
+ * `event` carries `counterparty_public_key`, the field §4.1 defines and no
236
+ * other section does, WHATEVER its `event_type` says. The second keeps a
237
+ * record that omits the field in scope: an `event_type` that is a string whose
238
+ * folded form has `handoff` as one of its `.`-separated segments, which leaves
239
+ * `asset_missing` and the other families alone.
240
+ *
241
+ * The order is the fix, not decoration. Every earlier version of this test was
242
+ * an ALLOW-LIST OVER A NAME THE AUDITED PARTY WRITES, so each repair narrowed
243
+ * the class and the next spelling walked around it: an exact `handoff.` prefix
244
+ * fell to `HANDOFF.RECEIVED`, and the ASCII fold that replaced it fell to the
245
+ * `ff` ligature, full-width letters, a Cyrillic `a`, `hand-off`, `handoffs`, a
246
+ * zero-width space, a BOM and a non-breaking space, each of which left a
247
+ * tampered receipt with no reading at all beside a clean decoy (proof#133
248
+ * fourth hunt, finding 2). The structural field closes all of them in one rule
249
+ * rather than by chasing Unicode, because the attack needs the field: a
250
+ * receipt that drops `counterparty_public_key` says nothing about who it came
251
+ * from.
252
+ *
253
+ * Anything in scope that is not exactly `handoff.sent` or `handoff.received`
254
+ * is `malformed`, so a spelling is never a way out.
255
+ *
256
+ * THIS IS NO LONGER A GATE ON BEING READ (proof#136). Both clauses are written
257
+ * by the party being audited, and one code point on each put a record in scope
258
+ * by neither, which produced silence. `readHandoffs` reads every record it
259
+ * holds, and this test now decides only WHICH reading a record gets: in scope
260
+ * and wrong reads `malformed`, out of scope reads `NOT_A_HANDOFF_FINDING`. A
261
+ * respelling buys a different line rather than no line.
262
+ */
263
+ export function isHandoffNamespace(held) {
264
+ if ("counterparty_public_key" in section(held.record, "event"))
265
+ return true;
266
+ const type = eventType(held);
267
+ return typeof type === "string" && foldEventType(type).split(".").includes("handoff");
268
+ }
269
+ function section(record, key) {
270
+ const value = record[key];
271
+ return value !== null && typeof value === "object" && !Array.isArray(value)
272
+ ? value
273
+ : {};
274
+ }
275
+ function eventType(held) {
276
+ return held.record.event_type;
277
+ }
278
+ function isSafeSequence(value) {
279
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
280
+ }
281
+ // Code POINTS, not UTF-16 units. `"\u{1F600}".length` is 2 in JavaScript and
282
+ // `len()` of the same character is 1 in Python, so a length bound counted in
283
+ // units makes the two kernels disagree about identical bytes (proof#133
284
+ // review, ruling 3).
285
+ function codePoints(value) {
286
+ return [...value].length;
287
+ }
288
+ // `===` rather than `==`, and the Python half now matches: `True == 1` holds in
289
+ // Python and `true === 1` does not in JavaScript, which let a record carrying
290
+ // `"sequence": true` stay in one kernel's reading and drop out of the other's.
291
+ function sameNumber(left, right) {
292
+ return left === right;
293
+ }
294
+ /**
295
+ * A record missing a REQUIRED field of its own type, or carrying one that is
296
+ * not the type §4.1 states, is malformed and fails. Stated as a rule because
297
+ * §4.1 had none: a pair where both sides omitted `message_hash` compared absent
298
+ * to absent, found them equal, and graded intact (proof#132).
299
+ *
300
+ * A record whose ENVELOPE key this reading cannot read is malformed too, and
301
+ * that one is a repair rather than an omission. The rule used to be "a value
302
+ * that is not 64 characters of hex names no key and matches nothing", so such a
303
+ * record dropped out of candidacy in silence and the subject read
304
+ * `counterpart_absent`, which §4.1 obliges a reader to call innocent. Nine
305
+ * whitespace spellings of a real key produce a VERIFIED envelope in exactly
306
+ * that state in the Python kernel, because `bytes.fromhex` skips ASCII
307
+ * whitespace, which reopened the whole of the first attack through the repair
308
+ * rather than around it (proof#133 fourth hunt, finding 1). A record a reader
309
+ * HOLDS, whose own key it cannot read, is a defect in the record and not an
310
+ * absence of one. This holds whatever the envelope layer decides about its hex
311
+ * charset (proof#135).
312
+ */
313
+ export function recordIsMalformed(held) {
314
+ if (normalizedSigningKey(held.publicKey) === null)
315
+ return true;
316
+ const type = eventType(held);
317
+ if (typeof type !== "string" || !DEFINED_EVENT_TYPES.includes(type)) {
318
+ return true; // including any other handoff.* name, which A11 forbids
319
+ }
320
+ const raw = held.record;
321
+ for (const key of ["event", "context"]) {
322
+ const value = raw[key];
323
+ if (value === null || typeof value !== "object" || Array.isArray(value))
324
+ return true;
325
+ }
326
+ const event = section(raw, "event");
327
+ const context = section(raw, "context");
328
+ if (typeof event.message_hash !== "string" || !HEX64.test(event.message_hash))
329
+ return true;
330
+ const contentType = event.content_type;
331
+ if (typeof contentType !== "string" ||
332
+ codePoints(contentType) === 0 ||
333
+ codePoints(contentType) > 128) {
334
+ return true;
335
+ }
336
+ if (typeof event.counterparty_public_key !== "string" ||
337
+ !LOWER_HEX64.test(event.counterparty_public_key)) {
338
+ return true;
339
+ }
340
+ if (!isSafeSequence(event.sequence))
341
+ return true;
342
+ if (type === "handoff.received") {
343
+ if (typeof event.outcome !== "string" || !OUTCOMES.includes(event.outcome))
344
+ return true;
345
+ }
346
+ else if ("outcome" in event) {
347
+ return true; // outcome is a handoff.received field only
348
+ }
349
+ // The OPTIONAL fields are optional: absence is never malformed, and a present
350
+ // one still has to be what §4.1 says it is.
351
+ //
352
+ // `message_bytes_hash` is NOT checked here. Its own row in 4.1 says a reader
353
+ // MUST NOT match, pair or grade on it, and calling a record malformed for it
354
+ // is grading on it (proof#133 review, ruling 5).
355
+ if ("case_id" in context) {
356
+ const value = context.case_id;
357
+ if (typeof value !== "string" || codePoints(value) > 128 || !ID_PATTERN.test(value))
358
+ return true;
359
+ }
360
+ if ("protocol" in context) {
361
+ const value = context.protocol;
362
+ if (typeof value !== "string" || codePoints(value) === 0 || codePoints(value) > 64)
363
+ return true;
364
+ }
365
+ if ("in_reply_to" in context) {
366
+ const value = context.in_reply_to;
367
+ if (typeof value !== "string" || !HEX64.test(value))
368
+ return true;
369
+ }
370
+ return false;
371
+ }
372
+ function complement(type) {
373
+ return type === "handoff.sent" ? "handoff.received" : "handoff.sent";
374
+ }
375
+ /**
376
+ * Who signed, and nothing a candidate says about itself.
377
+ *
378
+ * The complementary record type is the one conjunct that stays hard, and the
379
+ * reason is the honest two-way case rather than a preference: an honest reply is
380
+ * a `handoff.sent` signed by the other agent, naming this one, under the same
381
+ * case identifier and at the same sequence number, which is byte-for-byte the
382
+ * shape of a receiving side that mislabels its receipt. Admitting same-type
383
+ * candidates would grade an honest reply as a failed hand-off. §4.1 names that
384
+ * residual path, and the declaration (evidence-bundle.md §5.4) is its belt.
385
+ */
386
+ function candidatesFor(subject, held) {
387
+ // KEYS, never spellings of a key. Comparing the raw strings handed the
388
+ // audited party the set itself: an envelope key spelled in upper case names
389
+ // the same key, the record side is pinned to lowercase hex and the envelope
390
+ // side is pinned nowhere, so one character class took the tampered receipt
391
+ // out of the set and left the clean decoy in it (proof#133 adversarial
392
+ // gate, ruling 1).
393
+ const wanted = normalizedSigningKey(section(subject.record, "event").counterparty_public_key);
394
+ if (wanted === null)
395
+ return []; // the subject names no key
396
+ const wantedType = complement(eventType(subject));
397
+ return held.filter((candidate) => candidate !== subject &&
398
+ normalizedSigningKey(candidate.publicKey) === wanted &&
399
+ eventType(candidate) === wantedType);
400
+ }
401
+ /**
402
+ * Order a candidate set. It REMOVES NOTHING.
403
+ *
404
+ * `context.case_id` and then `event.sequence` put the candidate a reader is most
405
+ * likely to want at the front of the report, and both are written by the party
406
+ * being audited, so neither decides what gets graded. A version of this function
407
+ * that filtered, "applying a step only where it leaves at least one candidate",
408
+ * was itself a laundering path: the receiving side publishes the tampered
409
+ * receipt with its `case_id` or its `sequence` changed and a clean decoy that
410
+ * carries the subject's values, the surviving decoy keeps the step alive, the
411
+ * tamper drops out of the set, and the reading is `verified` with no ambiguity
412
+ * named (proof#133 review, ruling 1).
413
+ *
414
+ * The sort is total and deterministic, so the two kernels report one order.
415
+ */
416
+ function order(subject, candidates) {
417
+ const wantedCase = namedCase(section(subject.record, "context"));
418
+ const wantedSequence = section(subject.record, "event").sequence;
419
+ const rank = (c) => {
420
+ const context = section(c.record, "context");
421
+ const sameCase = isSameCase(namedCase(context), wantedCase);
422
+ const sameSequence = sameNumber(section(c.record, "event").sequence, wantedSequence);
423
+ return [sameCase ? 0 : 1, sameSequence ? 0 : 1, c.ref];
424
+ };
425
+ return [...candidates].sort((a, b) => {
426
+ const [ac, aq, ar] = rank(a);
427
+ const [bc, bq, br] = rank(b);
428
+ if (ac !== bc)
429
+ return ac - bc;
430
+ if (aq !== bq)
431
+ return aq - bq;
432
+ return ar < br ? -1 : ar > br ? 1 : 0;
433
+ });
434
+ }
435
+ /**
436
+ * Which case a record names, for the ordering step only.
437
+ *
438
+ * An ABSENT `context.case_id` and one written as `null` name the same thing,
439
+ * which is no case. Python's missing value is `None` and this kernel's is
440
+ * `undefined`, so a candidate carrying `"case_id": null` was "same case" in
441
+ * one kernel and not in the other when the subject lawfully omits the OPTIONAL
442
+ * key: same verdict, DIFFERENT candidate order, and the cross-kernel gate's
443
+ * own contract is that the reading it compares carries the candidates in
444
+ * order. The party being audited writes that `null` (proof#133 fifth hunt,
445
+ * closed by proof#136).
446
+ */
447
+ function namedCase(context) {
448
+ const value = context.case_id;
449
+ return value === undefined ? null : value;
450
+ }
451
+ /**
452
+ * Whether two records name the same case, for the ordering step only. Two
453
+ * records that name NO case are in the same position, and a case identifier is
454
+ * a string (4.1), so anything else names no case a reader can compare. Stated
455
+ * in one rule in both kernels so `None` and `undefined` cannot mean two
456
+ * things.
457
+ */
458
+ function isSameCase(left, right) {
459
+ if (left === null && right === null)
460
+ return true;
461
+ return typeof left === "string" && typeof right === "string" && left === right;
462
+ }
463
+ function gradePair(subject, counterpart) {
464
+ if (recordIsMalformed(subject) || recordIsMalformed(counterpart)) {
465
+ return { verdict: "malformed", checks: [] };
466
+ }
467
+ const failed = new Set();
468
+ // The same KEY, whatever the two envelopes spelled it as: one key signing
469
+ // both ends spelled upper case on one side and lower on the other read as a
470
+ // transfer between two parties (proof#133 adversarial gate, ruling 1).
471
+ if (sameSigningKey(subject.publicKey, counterpart.publicKey))
472
+ failed.add("self_handoff");
473
+ const subjectEvent = section(subject.record, "event");
474
+ const counterpartEvent = section(counterpart.record, "event");
475
+ const subjectHash = String(subjectEvent.message_hash ?? "").toLowerCase();
476
+ const counterpartHash = String(counterpartEvent.message_hash ?? "").toLowerCase();
477
+ if (subjectHash !== counterpartHash)
478
+ failed.add("message_hash");
479
+ if (!sameNumber(subjectEvent.sequence, counterpartEvent.sequence))
480
+ failed.add("sequence");
481
+ const checks = CHECK_ORDER.filter((name) => failed.has(name));
482
+ return { verdict: checks.length > 0 ? "failed" : "verified", checks: [...checks] };
483
+ }
484
+ /**
485
+ * Read ONE record against everything the reader holds.
486
+ *
487
+ * Every record gets a reading, and the two findings are how the distinction a
488
+ * reader needs survives (proof#136): a record that is not a hand-off record at
489
+ * all reads `NOT_A_HANDOFF_FINDING` with no verdict, and a record 4.1 DOES
490
+ * govern and that is wrong reads `malformed`. The scope test lives HERE and
491
+ * not in `readHandoffs`, so the two entry points cannot answer differently
492
+ * about one record.
493
+ */
494
+ export function readHandoff(subject, held) {
495
+ if (!isHandoffNamespace(subject)) {
496
+ return {
497
+ ref: subject.ref,
498
+ verdict: null,
499
+ failedChecks: [],
500
+ findings: [NOT_A_HANDOFF_FINDING],
501
+ candidates: [],
502
+ candidateReadings: [],
503
+ };
504
+ }
505
+ if (recordIsMalformed(subject)) {
506
+ return {
507
+ ref: subject.ref,
508
+ verdict: "malformed",
509
+ failedChecks: [],
510
+ findings: ["malformed_record"],
511
+ candidates: [],
512
+ candidateReadings: [],
513
+ };
514
+ }
515
+ const candidates = order(subject, candidatesFor(subject, held));
516
+ if (candidates.length === 0) {
517
+ return {
518
+ ref: subject.ref,
519
+ verdict: null,
520
+ failedChecks: [],
521
+ findings: ["counterpart_absent"],
522
+ candidates: [],
523
+ candidateReadings: [],
524
+ };
525
+ }
526
+ // EVERY candidate is graded. Ordering above chose where each one is reported
527
+ // and took none of them out of this list.
528
+ const graded = candidates.map((candidate) => {
529
+ const { verdict, checks } = gradePair(subject, candidate);
530
+ return { ref: candidate.ref, verdict, failedChecks: checks };
531
+ });
532
+ const worst = Math.max(...graded.map((g) => VERDICT_RANK[g.verdict]));
533
+ const verdict = Object.keys(VERDICT_RANK).find((name) => VERDICT_RANK[name] === worst);
534
+ // Over every candidate, not only the ones at the winning verdict: `malformed`
535
+ // outranks `failed`, so a single junk record would otherwise strip the named
536
+ // `message_hash` failure out of the report (proof#133 review, ruling 6).
537
+ const failed = new Set();
538
+ for (const g of graded)
539
+ for (const check of g.failedChecks)
540
+ failed.add(check);
541
+ const findings = [];
542
+ // Never a free choice: a reader permitted to take one match can be handed an
543
+ // honest decoy beside a tampered record.
544
+ if (candidates.length > 1)
545
+ findings.push("counterpart_ambiguous");
546
+ if (verdict === "malformed")
547
+ findings.push("malformed_record");
548
+ return {
549
+ ref: subject.ref,
550
+ verdict,
551
+ failedChecks: CHECK_ORDER.filter((name) => failed.has(name)),
552
+ findings,
553
+ candidates: candidates.map((c) => c.ref),
554
+ candidateReadings: graded,
555
+ };
556
+ }
557
+ /**
558
+ * EVERY record the reader holds gets a reading, in the order given.
559
+ *
560
+ * This function does not filter, and the branch that used to decide whether a
561
+ * record was read at all is gone (proof#136, ratified by Phil 2026-09-22).
562
+ * Scope was two clauses, an exact test for the key name
563
+ * `counterparty_public_key` and an ASCII fold of `event_type`, and both
564
+ * operands are written by the party being audited: one code point on each put
565
+ * a record in scope by NEITHER route, so it had no reading at all and the pile
566
+ * read clean. Five repairs narrowed which values reached that silent branch
567
+ * and five hunts found a value outside it, so the branch is removed rather
568
+ * than narrowed again.
569
+ *
570
+ * The distinction a reader needs survives as two findings rather than as a
571
+ * reading and a silence: a record TRYING to be a hand-off and getting it wrong
572
+ * reads `malformed` with `malformed_record`, and a record that is not a
573
+ * hand-off record at all reads `NOT_A_HANDOFF_FINDING` with no verdict.
574
+ * `isHandoffNamespace` decides which of the two, in `readHandoff`, and no
575
+ * longer whether a record is read.
576
+ *
577
+ * THE COST, stated rather than left to be found: a reader given a mixed pile
578
+ * produces a line per record, including for records that have nothing to do
579
+ * with hand-offs. 4.1 says so too.
580
+ */
581
+ export function readHandoffs(held) {
582
+ return held.map((record) => readHandoff(record, held));
583
+ }
584
+ /**
585
+ * Whether this record is a conformant hand-off record of 4.1: it is read as a
586
+ * hand-off record at all (`isHandoffNamespace`) and it is not `malformed`
587
+ * (`recordIsMalformed`), which between them mean it is exactly a
588
+ * `handoff.sent` or a `handoff.received` carrying every REQUIRED field of its
589
+ * own type, under an envelope key this reading can read.
590
+ *
591
+ * `./declaration.ts` reads this for evidence-bundle.md 5.4: a claimed
592
+ * `sent_event_id` or `received_event_id` naming a record that is not one of
593
+ * these is a DEVIATION, so a record cannot be unreadable at the record layer
594
+ * and usable at the pack layer at the same time (proof#136).
595
+ */
596
+ export function isConformantHandoffRecord(held) {
597
+ return isHandoffNamespace(held) && !recordIsMalformed(held);
598
+ }
package/dist/index.d.ts CHANGED
@@ -2,13 +2,21 @@ export { ACCEPTED_SPEC_MAJORS, contentHashes, jcs, specVersionSupported, verifyE
2
2
  export { bytesToHex, deriveOperatorAddress, ed25519Verify, hexToBytes, sha256Bytes, sha256Hex, utf8, verifyRsaPssSha256, } from "./crypto.js";
3
3
  export { EMPTY_TREE_ROOT_HEX, auditPath, leafHash, merkleRoot, nodeHash, verifyInclusion, } from "./merkle.js";
4
4
  export type { ContentRole, Envelope, Subject, VerificationResult, VerifyOptions } from "./types.js";
5
- export { ANCHOR_TRACE_BODY_TYPE, ANCHOR_TRACE_BODY_TYPE_V1, ANCHOR_TRACE_BODY_TYPES, EXPORT_BODY_TYPE, STAMP_BODY_VERSION, STAMP_TRACE_BODY_TYPE, STAMP_EVIDENCE_BODY_TYPE, disclosedContent, recomputeExportVerdict, verifyEvidenceBundle, } from "./evidence.js";
6
- export type { AnchorTraceBody, AttestationPayload, AttestationRecord, AttestationResult, CheckpointResult, ComposeVerdictResult, DisclosedContentResult, DisclosedEventContent, DisclosureStatus, EvidenceBundle, EvidenceBundleResult, EvidenceIssuer, EvidenceStatus, EvidenceVerdict, EventResult, ExportBody, ExportResult, OnChainOutcome, OnChainResult, PerGatewayOutcome, AnchorRef, StampBody, StampEntry, StampResult, StampSubtree, StampSubtreeResult, StampTraceBody, StampEvidenceBody, StampEvidenceEvent, StampEvidenceInclusion, TraceCheckpoint, TraceCheckpointV1, TraceEvent, TraceInclusion, VerdictAttestation, VerdictCheckpoint, VerdictEvent, VerdictObject, VerdictOnChain, VerdictOnChainGateway, VerifyEvidenceOptions, } from "./evidence.js";
5
+ export { ANCHOR_TRACE_BODY_TYPE, EXPORT_BODY_TYPE, STAMP_BODY_VERSION, STAMP_TRACE_BODY_TYPE, STAMP_EVIDENCE_BODY_TYPE, disclosedContent, recomputeExportVerdict, verifyEvidenceBundle, } from "./evidence.js";
6
+ export type { AnchorTraceBody, AttestationPayload, AttestationRecord, AttestationResult, CheckpointResult, ComposeVerdictResult, DisclosedContentResult, DisclosedEventContent, DisclosureStatus, EvidenceBundle, EvidenceBundleResult, EvidenceIssuer, EvidenceStatus, EvidenceVerdict, EventResult, ExportBody, ExportResult, OnChainOutcome, OnChainResult, PerGatewayOutcome, AnchorRef, StampBody, StampEntry, StampResult, StampSubtree, StampSubtreeResult, StampTraceBody, StampEvidenceBody, StampEvidenceEvent, StampEvidenceInclusion, TraceCheckpoint, TraceEvent, TraceInclusion, VerdictAttestation, VerdictCheckpoint, VerdictEvent, VerdictObject, VerdictOnChain, VerdictOnChainGateway, VerifyEvidenceOptions, } from "./evidence.js";
7
7
  export { accountDisclosure, completenessNotes, gradeCauses, gradePack, renderCause, signedLeafCount, } from "./grading.js";
8
8
  export type { CompletenessNote, DisclosureAccount, GradeInput, PackGrade, PackGradeCause, PackGradeCauseKind, PackVerdict, } from "./grading.js";
9
+ export { DECLARATION_VERSION, checkDeclaration, declarationClaims, packRecords, renderContentFinding, renderDeclarationSummary, renderDeviation, renderNote, } from "./declaration.js";
10
+ export type { DeclarationCheck, DeclarationClaims, DeclarationContentFinding, DeclarationContentKind, DeclarationDeviation, DeclarationDeviationKind, DeclarationNote, DeclarationNoteKind, DeclarationVerdict, PackRecord, } from "./declaration.js";
11
+ export { CASE_BODY_TYPES, CASE_EXCEPTION_KINDS, CASE_QUARANTINED_PROFILES, CASE_RECORD_PROFILES, CASE_VERDICTS, readCase, renderCaseSummary, renderException, } from "./case.js";
12
+ export type { CaseException, CaseExceptionKind, CasePack, CaseReading, CaseRecordReading, CaseVerdict, } from "./case.js";
9
13
  export { ADAPTER_CHAIN_NAMESPACES, CHAIN_READING_SCOPE, readChains, renderChainFinding, } from "./chain.js";
10
14
  export type { ChainFinding, ChainFindingKind, ChainReading, ChainSource, ChainSummary, } from "./chain.js";
11
15
  export { attestationSignatureToHex, composeExport } from "./compose.js";
12
16
  export type { ComposeExportOptions, ComposeExportResult, ExporterKey } from "./compose.js";
13
17
  export { AGENT_PROOF_SPEC_PREFIX, isAgentProofSpec, verifyAgentProofBundle } from "./agent-proof.js";
14
18
  export type { AgentProofBundle, AgentProofResult, VerifyAgentProofOptions, } from "./agent-proof.js";
19
+ export { CANDIDATE_NAMESPACE, DEFINED_EVENT_TYPES, NOT_A_HANDOFF_FINDING, isConformantHandoffRecord, readHandoff, readHandoffs, recordIsMalformed, } from "./handoff.js";
20
+ export type { CandidateReading, HandoffReading, HandoffRecord, HandoffVerdict, HeldRecord, } from "./handoff.js";
21
+ export { BYTES_FOR_UNKNOWN_PART, CONFLICTING_PART_BYTES, INLINE_BYTES_KEYS, MESSAGE_RESULT_ORDER, PARTS_NOT_AN_ARRAY, PART_ENCODING_MISMATCH, PART_INLINE_BYTES, PART_INLINE_MISMATCHED, PART_MALFORMED_DESCRIPTOR, PART_MATCHED, PART_MISMATCHED, PART_NOT_A_FILE, PART_SUPPLIED_TWICE, PART_UNCHECKED, REFUSAL_ORDER, commitHeldMessage, isFilePart, uncheckedHeldParts, } from "./message-parts.js";
22
+ export type { HeldMessage, Note, PartReading, Refusal, SuppliedPart } from "./message-parts.js";