@sanning/proof 0.10.0 → 0.11.1

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