@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,998 @@
1
+ /**
2
+ * A file part's BYTES, and what a receiver holding them commits to.
3
+ *
4
+ * `envelope-spec.md` section 4.1 (v1.13, amendment A18, proof#145, ratified by
5
+ * Phil 2026-09-22). The Python half is `src/sanning_proof/message_parts.py` and
6
+ * the two are held together by `cross-kernel/run_parts.sh`.
7
+ *
8
+ * THE DEFECT THIS CLOSES. Section 4.1 said "Binary and file parts are committed
9
+ * by their own content hash inside that canonical object" and stopped, which
10
+ * decided half of "an altered part fails". Measured against both SDKs
11
+ * (anchor#219, attack 1, in both languages): a transport that keeps a part's
12
+ * DESCRIPTOR and swaps its BYTES produces `accepted`. No exception, no finding,
13
+ * and nothing in either record: the descriptor's hash and the bytes' hash sit
14
+ * side by side and no rule ever compared them, so both sides commit to the same
15
+ * message object and the pair reads `verified`. Swapping the bytes AND the
16
+ * descriptor was caught all along. This is the sixth instance of one class in
17
+ * this section, "a deviation produces nothing and a reader is obliged to call
18
+ * it clean", and the repair is the same shape as A13's and A14's: remove the
19
+ * silent branch rather than narrow it.
20
+ *
21
+ * THE RULE, which is the smallest additive one that closes it:
22
+ *
23
+ * * a file part is `kind: "file"` plus `content_hash` (64 hex characters,
24
+ * either case, the SHA-256 of the part's exact bytes) and `content_length`
25
+ * (a safe integer), and the bytes are NOT in the message;
26
+ * * a receiver handed a part's bytes MUST hash them, and where the digest is
27
+ * not the descriptor's, or the byte count is not the descriptor's, it
28
+ * commits to the message AS IT ACTUALLY HELD IT: that part's
29
+ * `content_hash` and `content_length` replaced by the held bytes' own,
30
+ * nothing else touched. Its `handoff.received` then commits to a different
31
+ * message object from the sender's, so the formed pair FAILS on
32
+ * `message_hash`, a failure section 4.1 already names, and the receiving
33
+ * side writes `outcome: "rejected"`. That is the ONE reading that moves,
34
+ * and it moves only for a receiver that holds the bytes;
35
+ * * every other deviation is named and none is silent. Three of them are
36
+ * REFUSALS of one supply, so a receiver's own decoding defect never becomes
37
+ * permanent evidence against an honest sender;
38
+ * * an inline part is ACCEPTED, and it is committed by the MESSAGE ITSELF
39
+ * (proof#157, ratified by Phil 2026-09-22). `message_hash` is SHA-256 over
40
+ * the canonical bytes of the message object, so a part carrying its content
41
+ * inside the message is already committed: alter that content and the
42
+ * message object changes, the hash changes, and the pair fails. None of the
43
+ * swapped-bytes attack applies, because that attack works only where a
44
+ * descriptor's hash and bytes travelling BESIDE the message are two
45
+ * separate things with nothing comparing them. Inline is not the risky
46
+ * shape, it is the safest one. Where an inline part ALSO carries a
47
+ * `content_hash` or a `content_length`, the receiver checks BOTH against
48
+ * the inline content and names a disagreement: one commitment governs, and
49
+ * a second one present and disagreeing is itself a finding.
50
+ *
51
+ * WHY THE HELD MESSAGE RATHER THAN A FINDING ON THE RECEIVING SIDE. A finding
52
+ * only the receiving side's own reader sees is the shape of every laundering
53
+ * path this section has closed: the party being audited publishes the pack, so
54
+ * a deviation that lives outside the committed record is a deviation that party
55
+ * chooses whether anyone reads. `message_hash` is the one value both sides
56
+ * publish and a reader already grades.
57
+ *
58
+ * WHAT DOES NOT MOVE. A receiver that never holds a part's bytes checks
59
+ * nothing, substitutes nothing and reads exactly as it did before this
60
+ * amendment: every file part is `PART_UNCHECKED`, and section 4.1 forbids
61
+ * treating an unchecked part as a checked one. No envelope field moves, no
62
+ * `spec_version` moves, no verdict word and no record-layer finding is coined.
63
+ *
64
+ * A REFUSAL IS SCOPED TO ITS PART, AND THE RECORD IS STILL WRITTEN (proof#156
65
+ * gate). The first cut of this module refused GLOBALLY: one refusal anywhere
66
+ * set `heldMessage` to null and dropped every substitution. That made the
67
+ * attack A18 exists to close launderable (a genuine swap on part 0 plus any
68
+ * refusal-triggering supply on part 1 wrote nothing at all), let a SENDER deny
69
+ * the receiver a record with an upper-case `content_hash` or a `"bytes": null`
70
+ * on an otherwise conformant descriptor, and contradicted section 4.1's own
71
+ * paragraph saying an uncheckable part is NAMED in the receiver's reading. So
72
+ * a problem with one part names that part, leaves the rest of the reading
73
+ * intact, and `heldMessage` is never null. A message-level problem is reserved
74
+ * for a message-level condition, and even then it produces a named result:
75
+ * `PARTS_NOT_AN_ARRAY`, and the entry-scoped `BYTES_FOR_UNKNOWN_PART`.
76
+ *
77
+ * WHAT THE CALLER STILL OWES, AND THE ONE FUNCTION THAT STATES IT.
78
+ * `substituted` decides whether a hand-off is `rejected`; it does NOT decide
79
+ * whether one is clean. A part that was refused reads `PART_UNCHECKED`,
80
+ * section 4.1 forbids a reader treating an unchecked part as a checked one,
81
+ * and a surface reporting a hand-off states how many parts were checked. A
82
+ * caller that wrote `accepted` on "nothing was substituted" alone would be
83
+ * calling a part it never established clean, which is the class this whole
84
+ * section keeps repairing.
85
+ *
86
+ * The sharp version, measured (proof#156 second gate, F5): deliver a tampered
87
+ * copy of a part ALONE and it is `part_mismatched`, substituted, and the pair
88
+ * fails on `message_hash`. Deliver the tampered copy AND the true one and it
89
+ * is `conflicting_part_bytes`, `part_unchecked`, nothing substituted, a
90
+ * `heldMessage` byte-identical to the sender's, and the pair VERIFIES. Adding
91
+ * data suppresses detection, and the refusal that names it lives only in
92
+ * `refusals`, which is a finding only the receiving side's own reader sees:
93
+ * the exact shape the paragraph above refuses to create.
94
+ * `PART_ENCODING_MISMATCH` has the same property.
95
+ *
96
+ * Until that round the obligation was PROSE IN THIS COMMENT with no mechanism,
97
+ * which is a rule a caller has to read to obey. `uncheckedHeldParts` is the
98
+ * mechanism's additive half: it names the parts the receiver HELD bytes for
99
+ * and did not check, so a caller writes `accepted` only where `substituted` is
100
+ * empty AND that list is empty, instead of re-deriving it from the refusals.
101
+ * It cannot make the mistake IMPOSSIBLE, because this module reads and does
102
+ * not write the record. What the record layer does with the list was
103
+ * proof#162, and Phil ratified it on 2026-09-22: `outcome: "accepted"` keeps
104
+ * meaning what it means today, and the count of held-but-unchecked parts
105
+ * rides in an ADDITIVE `context` key, REQUIRED when it is not zero. Its force
106
+ * is against SDKs through conformance vectors rather than against records
107
+ * through readers, since only the receiver knows what bytes it held, so THIS
108
+ * LIST IS WHAT EVERY SDK BUILT ON THE RULE WILL COUNT. A part missing from it
109
+ * is a part no record will ever mention (anchor#191 is the first caller).
110
+ *
111
+ * WHAT THIS MODULE DOES NOT DO. It does not canonicalize and it does not hash
112
+ * the message. It returns the message a receiver commits to, and the caller
113
+ * hashes that with the rule section 4.1 already states, so this module has no
114
+ * failure mode of its own for a message too deep or not serializable and there
115
+ * is no branch here where one kernel throws and the other returns.
116
+ */
117
+ import { sha256Hex } from "./crypto.js";
118
+
119
+ /**
120
+ * The result of a part whose supplied bytes hash to its `content_hash` AND
121
+ * count to its `content_length`.
122
+ */
123
+ export const PART_MATCHED = "part_matched";
124
+
125
+ /**
126
+ * The result of a part whose supplied bytes miss either of those, with no
127
+ * respelling of them that explains the digest. The held-message substitution
128
+ * applies to this part, and it replaces BOTH values with the held bytes' own.
129
+ */
130
+ export const PART_MISMATCHED = "part_mismatched";
131
+
132
+ /**
133
+ * A file part whose bytes were not supplied, or whose supply was REFUSED. It is
134
+ * not checked and it is not clean: section 4.1 forbids a reader treating it as
135
+ * checked.
136
+ */
137
+ export const PART_UNCHECKED = "part_unchecked";
138
+
139
+ /**
140
+ * A `kind: "file"` part carrying its content inside the message, and ACCEPTED
141
+ * (proof#157, ratified by Phil 2026-09-22). It is committed by the MESSAGE
142
+ * ITSELF: `message_hash` is SHA-256 over the canonical bytes of the message
143
+ * object, so altering that content changes the message, changes the hash, and
144
+ * fails the pair. Nothing is hashed against it here and nothing is substituted,
145
+ * because there is nothing travelling beside the message for the message to
146
+ * disagree with. That is why the swapped-bytes attack cannot reach this shape.
147
+ */
148
+ export const PART_INLINE_BYTES = "part_inline_bytes";
149
+
150
+ /**
151
+ * An inline part whose `content_hash`, `content_length` or both DISAGREE with
152
+ * its inline content: no single reading of that content satisfies every claim
153
+ * the part writes beside it. The message's own commitment still governs and
154
+ * nothing is substituted; this names the SECOND claim that disagrees with it,
155
+ * which is a finding in its own right (proof#157).
156
+ *
157
+ * ONE name for both claims, exactly as `PART_MISMATCHED` is one name for both
158
+ * on a descriptor part. It was `part_inline_hash_mismatch` for one round of
159
+ * this unmerged PR, when only the hash was compared; a name that says "hash"
160
+ * about a result that also covers a length asserts more than its body does, so
161
+ * the name was re-cut with the rule (proof#156 second gate, F4).
162
+ *
163
+ * The check is deliberately permissive ACROSS readings: the raw UTF-8 of the
164
+ * value, its base64 decoding and its hex decoding are all tried, so this fires
165
+ * only where no reading agrees at all. It is not permissive BETWEEN claims: one
166
+ * reading has to satisfy all of them, because a hash that agrees under the
167
+ * base64 decoding beside a length that agrees under the raw text describes no
168
+ * blob that exists.
169
+ */
170
+ export const PART_INLINE_MISMATCHED = "part_inline_mismatched";
171
+
172
+ /**
173
+ * `kind: "file"` without a conformant `content_hash` and `content_length`. A
174
+ * sender's defect rather than a receiver's, so it is named rather than refused:
175
+ * the receiver did nothing wrong by holding it.
176
+ */
177
+ export const PART_MALFORMED_DESCRIPTOR = "part_malformed_descriptor";
178
+
179
+ /**
180
+ * Any other part. It is committed as ordinary JSON content and this rule checks
181
+ * nothing about it.
182
+ */
183
+ export const PART_NOT_A_FILE = "part_not_a_file";
184
+
185
+ /**
186
+ * REFUSAL of ONE supplied entry. Bytes were supplied for no part of the
187
+ * message, or for a part this rule cannot check. The caller and the message
188
+ * disagree about what was sent, and hashing bytes against a part that is not
189
+ * there establishes nothing. Where the entry names a part that EXISTS but is
190
+ * not checkable, the refusal carries that part's index and the part keeps the
191
+ * result it classified to; where it names no part at all, the refusal carries
192
+ * the entry position and no part. Neither stops the record being written.
193
+ */
194
+ export const BYTES_FOR_UNKNOWN_PART = "bytes_for_unknown_part";
195
+
196
+ /**
197
+ * REFUSAL. Two DIFFERENT byte strings were supplied for one part. A receiver
198
+ * holding two answers has not established which one it held.
199
+ */
200
+ export const CONFLICTING_PART_BYTES = "conflicting_part_bytes";
201
+
202
+ /**
203
+ * REFUSAL of ONE supplied entry. The supplied bytes miss the descriptor, but a
204
+ * base64 or hex RESPELLING of them in EITHER direction hashes to it: either the
205
+ * bytes DECODE to the part (the receiver's stack never decoded what it was
206
+ * handed) or they ENCODE to it (the receiver's stack decoded bytes the sender
207
+ * committed in their encoded spelling, which is what a single-line DER
208
+ * attachment, a PEM body and a JWT all are). That is a coding defect in the
209
+ * receiver, not a tamper by the sender: a proto3 JSON transcoder re-encodes
210
+ * base64 URL-safe and unpadded while behaving honestly, and under the silence
211
+ * this amendment removes it produced a permanent tamper record against a sender
212
+ * who did nothing. Recording evidence out of a receiver's own bug is the one
213
+ * outcome worse than recording nothing, so BOTH directions are guarded
214
+ * (proof#156 gate): guarding only the decoding direction left the other half of
215
+ * one honest stack's behavior reading as a tamper.
216
+ */
217
+ export const PART_ENCODING_MISMATCH = "part_encoding_mismatch";
218
+
219
+ /**
220
+ * A MESSAGE-LEVEL result. The message carries a `parts` key whose value is
221
+ * present and is not an array, which is how proto3 JSON encodes a map and so is
222
+ * reachable from the same transport family the motivating example comes from.
223
+ * Section 4.1 asks for one result per part; a message shaped like this has
224
+ * part-shaped content and no parts, and before proof#156's gate it produced
225
+ * zero readings and an accepted record. It is named rather than refused: the
226
+ * receiver did nothing wrong by holding it, and nothing in it is checked. A
227
+ * `parts` written as `null` is an ABSENT `parts` and is not this, on A14's
228
+ * ruling that an absent value and one written as `null` name one thing.
229
+ */
230
+ export const PARTS_NOT_AN_ARRAY = "parts_not_an_array";
231
+
232
+ /**
233
+ * NOTE, not a refusal. One part supplied more than once with IDENTICAL bytes is
234
+ * one supply stated twice, and the part is checked normally. Different bytes for
235
+ * one part are `CONFLICTING_PART_BYTES`.
236
+ */
237
+ export const PART_SUPPLIED_TWICE = "part_supplied_twice";
238
+
239
+ /**
240
+ * The order refusals are reported in, fixed so two kernels report one list
241
+ * rather than two orderings of it.
242
+ */
243
+ export const REFUSAL_ORDER = [
244
+ BYTES_FOR_UNKNOWN_PART,
245
+ CONFLICTING_PART_BYTES,
246
+ PART_ENCODING_MISMATCH,
247
+ ] as const;
248
+
249
+ /**
250
+ * The order message-level results are reported in, for the same reason as
251
+ * `REFUSAL_ORDER`.
252
+ */
253
+ export const MESSAGE_RESULT_ORDER = [PARTS_NOT_AN_ARRAY] as const;
254
+
255
+ /**
256
+ * The results that put a HELD part into `uncheckedHeldParts`, written out so a
257
+ * third kernel reads the rule rather than inferring it from one kernel's
258
+ * filter (proof#156 third gate, C1).
259
+ *
260
+ * The line is whether the MESSAGE ITSELF commits the part's content. It does
261
+ * not for these two: `PART_UNCHECKED` is a supply the rule refused to grade,
262
+ * and `PART_MALFORMED_DESCRIPTOR` is a part whose content lives BESIDE the
263
+ * message under a claim no receiver can use, so in both the receiver holds
264
+ * bytes that nothing in the committed record covers.
265
+ *
266
+ * The other three results a supply can be refused against are excluded, and
267
+ * excluded for a reason rather than by omission. `PART_INLINE_BYTES`,
268
+ * `PART_INLINE_MISMATCHED` and `PART_NOT_A_FILE` all carry their content
269
+ * INSIDE the message, which `message_hash` already commits on both sides:
270
+ * bytes supplied beside one of those grade nothing and hide nothing, because
271
+ * a reader of either pack reads the content itself. Counting them would make
272
+ * the caller's obligation fire on parts no attack can reach.
273
+ */
274
+ const HELD_UNCHECKED_RESULTS: readonly string[] = [
275
+ PART_UNCHECKED,
276
+ PART_MALFORMED_DESCRIPTOR,
277
+ ];
278
+
279
+ /**
280
+ * The keys that make a part carry its content INLINE, in the order they are
281
+ * read. Named rather than inferred: `bytes` is A2A's spelling of an inline file
282
+ * part, and `data` and `content` are the two other spellings in the wild. The
283
+ * FIRST of them present with a value that is not `null` is the inline content,
284
+ * so a part spelling it twice reads one way in both kernels.
285
+ *
286
+ * A key present with `null` is an ABSENT inline value, on A14's ruling that an
287
+ * absent value and one written as `null` name one thing. That matters: an A2A
288
+ * `FilePart` with `uri` set carries `"bytes": null`, and so does proto3 JSON,
289
+ * and reading those as inline made a conformant DESCRIPTOR part uncheckable
290
+ * (proof#156 gate). They fall through to the descriptor rule, which is what
291
+ * they are.
292
+ */
293
+ // A conformant DESCRIPTOR part that also carries a `content` or `data` key
294
+ // meaning something else (a filename, a metadata blob) is reclassified by this
295
+ // list and never checked against supplied bytes. That is inside section 4.1's
296
+ // stated rule, and whether these parts ought to fall into it is proof#163.
297
+ export const INLINE_BYTES_KEYS = ["bytes", "content", "data"] as const;
298
+
299
+ const HEX64 = /^[0-9a-fA-F]{64}$/;
300
+ const HEX_CHARSET = /^[0-9a-fA-F]+$/;
301
+ const LOWER_HEX = "0123456789abcdef";
302
+ const UPPER_HEX = "0123456789ABCDEF";
303
+
304
+ /**
305
+ * The largest integer a double carries exactly, the same bound section 4.1 puts
306
+ * on `event.sequence`: a `content_length` outside it is a value the two kernels
307
+ * would read as two numbers.
308
+ */
309
+ export const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
310
+
311
+ const BASE64_STANDARD = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
312
+ const BASE64_URLSAFE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
313
+
314
+ /**
315
+ * One byte string a receiver holds, and the part it holds it for.
316
+ *
317
+ * `part` is an INDEX into the message's `parts` array. It is an index rather
318
+ * than a content hash on purpose: keying the supply by the value the check is
319
+ * about to grade would mean a receiver could only supply bytes it had already
320
+ * agreed with, which is the whole defect stated backwards.
321
+ */
322
+ export interface SuppliedPart {
323
+ part: unknown;
324
+ data: Uint8Array;
325
+ }
326
+
327
+ /** What the receiver reports for one part of the message, one per part. */
328
+ export interface PartReading {
329
+ index: number;
330
+ result: string;
331
+ }
332
+
333
+ /**
334
+ * A caller error. Nothing is written, nothing is signed, no record made.
335
+ *
336
+ * `part` is the part index where the refusal is about a part of the message,
337
+ * and `entry` is the POSITION of the offending supplied entry in the sequence
338
+ * the caller passed. The position is recorded rather than the value the caller
339
+ * named, so a caller that names a part with a float or a string cannot make two
340
+ * kernels serialize one reading two ways.
341
+ */
342
+ export interface Refusal {
343
+ name: string;
344
+ part: number | null;
345
+ entry: number | null;
346
+ }
347
+
348
+ /**
349
+ * Something worth reporting that refuses nothing and checks nothing out. Same
350
+ * shape as a `Refusal` and carried in its own list, so no caller can read a
351
+ * note as a refusal by looking only at a name.
352
+ */
353
+ export type Note = Refusal;
354
+
355
+ /**
356
+ * The message a receiver commits to, and everything it found on the way.
357
+ *
358
+ * `heldMessage` is ALWAYS the message the receiver commits to and is never
359
+ * null: a refusal is scoped to the supply it is about and never denies the
360
+ * receiver a record (proof#156 gate). The caller commits `event.message_hash`
361
+ * as SHA-256 over its JCS (RFC 8785) canonical bytes, which is the rule section
362
+ * 4.1 already states and the reason this module does not hash anything itself.
363
+ *
364
+ * `messageResults` carries the message-level named results, in
365
+ * `MESSAGE_RESULT_ORDER`. It is empty for every message whose shape the rule
366
+ * reads.
367
+ *
368
+ * `substituted` carries the indexes of the parts whose descriptor the receiver
369
+ * replaced with the held bytes' own hash and length. It is empty for an honest
370
+ * hand-off, and where it is not empty the receiving side writes
371
+ * `outcome: "rejected"`.
372
+ */
373
+ export interface HeldMessage {
374
+ parts: PartReading[];
375
+ messageResults: string[];
376
+ refusals: Refusal[];
377
+ notes: Note[];
378
+ heldMessage: unknown | null;
379
+ substituted: number[];
380
+ }
381
+
382
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
383
+ return value !== null && typeof value === "object" && !Array.isArray(value);
384
+ }
385
+
386
+ function hasOwn(value: Record<string, unknown>, key: string): boolean {
387
+ return Object.prototype.hasOwnProperty.call(value, key);
388
+ }
389
+
390
+ /**
391
+ * 64 hex characters, in EITHER case. Phil ratified proof#135 as "pin the hex
392
+ * charset only": a case-only difference names the same value, and refusing
393
+ * upper case here would contradict a ratified decision and punish a producer
394
+ * who did nothing wrong. Every comparison against a digest lowercases both
395
+ * sides, which is what the other kernels already do.
396
+ */
397
+ function isHex64(value: unknown): boolean {
398
+ return typeof value === "string" && HEX64.test(value);
399
+ }
400
+
401
+ /**
402
+ * A byte count: an integer at least zero and inside the safe range. `true` is
403
+ * not a number. Zero is a legal length: the empty part is a real part, and a
404
+ * rule that read zero as "no length" would leave it unchecked in silence.
405
+ */
406
+ function isSafeLength(value: unknown): boolean {
407
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
408
+ }
409
+
410
+ function isSafeIndex(value: unknown): boolean {
411
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
412
+ }
413
+
414
+ /**
415
+ * Distinguishes "no inline content" from an inline content of `null`, which
416
+ * A14's ruling says is the same thing but which a plain `null` could not be
417
+ * told apart from a legitimate value.
418
+ */
419
+ const ABSENT = Symbol("absent");
420
+
421
+ /**
422
+ * The part's inline content, or `ABSENT` where it carries none: the FIRST of
423
+ * `INLINE_BYTES_KEYS` present with a value that is not `null`, so a part
424
+ * spelling it twice reads one way in both kernels.
425
+ */
426
+ function inlineValue(part: Record<string, unknown>): unknown | typeof ABSENT {
427
+ for (const key of INLINE_BYTES_KEYS) {
428
+ if (hasOwn(part, key) && part[key] !== null && part[key] !== undefined) {
429
+ return part[key];
430
+ }
431
+ }
432
+ return ABSENT;
433
+ }
434
+
435
+ /**
436
+ * Every byte string a reader can form from an inline value: the raw UTF-8 of
437
+ * the string, its base64 decoding and its hex decoding. Deliberately
438
+ * permissive: this exists only to decide whether a `content_hash` sitting
439
+ * BESIDE inline content agrees with it, and the message's own commitment
440
+ * governs either way, so the finding fires only where no reading agrees at all.
441
+ * A value that is not a string carries no readings, so a `content_hash` beside
442
+ * one has nothing to agree with.
443
+ */
444
+ function inlineReadings(value: unknown): Uint8Array[] {
445
+ if (typeof value !== "string") return [];
446
+ const encoded = new TextEncoder().encode(value);
447
+ const raw = new Uint8Array(encoded.length);
448
+ raw.set(encoded);
449
+ const out: Uint8Array[] = [raw];
450
+ for (const decoded of [base64Decode(raw), hexDecode(raw)]) {
451
+ if (decoded !== null) out.push(decoded);
452
+ }
453
+ return out;
454
+ }
455
+
456
+ /**
457
+ * The SHAPE a part reads with before any supplied bytes are considered, or
458
+ * `null` where the part is one this rule checks against them.
459
+ *
460
+ * Shape only, and synchronous on purpose: the inline hash agreement needs
461
+ * SHA-256, which is async here and not in Python, so refining
462
+ * `PART_INLINE_BYTES` to `PART_INLINE_MISMATCHED` happens in the reading
463
+ * loop instead. Keeping it out of here is what lets `isFilePart` mean the same
464
+ * thing, and have the same signature, in both kernels.
465
+ */
466
+ function classify(part: unknown): string | null {
467
+ if (!isPlainObject(part)) return PART_NOT_A_FILE;
468
+ if (part.kind !== "file") return PART_NOT_A_FILE;
469
+ // ACCEPTED, and committed by the message itself (proof#157).
470
+ if (inlineValue(part) !== ABSENT) return PART_INLINE_BYTES;
471
+ if (!isHex64(part.content_hash)) return PART_MALFORMED_DESCRIPTOR;
472
+ if (!isSafeLength(part.content_length)) return PART_MALFORMED_DESCRIPTOR;
473
+ return null;
474
+ }
475
+
476
+ /**
477
+ * Whether the claims written BESIDE an inline part's content agree with it.
478
+ *
479
+ * Two claims can sit beside inline content, `content_hash` and
480
+ * `content_length`, and BOTH are read (proof#156 second gate, F4). The length
481
+ * was skipped for one round of this unmerged PR, on the argument that a reader
482
+ * holding the message can see a contradiction between the content and the
483
+ * claim from the message alone. That argument is true and it is also true of
484
+ * `content_hash`, which is compared: accepting it deletes the neighboring
485
+ * check. So the rule is the one section 4.1 already applies to a descriptor
486
+ * part, where a hash that misses and a count that misses reach one result: two
487
+ * claims about one blob, and reading one of them lets the other be false in
488
+ * silence.
489
+ *
490
+ * A claim that is ABSENT, or is not the shape the table names, is not a claim:
491
+ * it is not compared and it cannot disagree. A part writing neither agrees by
492
+ * default, because the message's own commitment governs and this only ever
493
+ * names a SECOND claim that contradicts it.
494
+ *
495
+ * ONE reading has to satisfy EVERY claim present, rather than each claim
496
+ * finding its own. Grading them separately would let a `content_hash` that
497
+ * agrees under the base64 decoding sit beside a `content_length` that agrees
498
+ * under the raw text, a pair no blob in the world satisfies, and call it clean.
499
+ */
500
+ async function inlineClaimsAgree(part: Record<string, unknown>): Promise<boolean> {
501
+ const wanted = isHex64(part.content_hash)
502
+ ? (part.content_hash as string).toLowerCase()
503
+ : null;
504
+ const length = isSafeLength(part.content_length)
505
+ ? (part.content_length as number)
506
+ : null;
507
+ if (wanted === null && length === null) return true;
508
+ for (const reading of inlineReadings(inlineValue(part))) {
509
+ if (wanted !== null && (await sha256Hex(reading)) !== wanted) continue;
510
+ if (length !== null && reading.length !== length) continue;
511
+ return true;
512
+ }
513
+ return false;
514
+ }
515
+
516
+ /**
517
+ * Whether this part is one this rule CHECKS against bytes travelling BESIDE the
518
+ * message: a conformant descriptor part. Exactly the three conditions section
519
+ * 4.1 states, in the order that keeps inline content out. An INLINE part is
520
+ * accepted and committed by the message itself (proof#157), so there is nothing
521
+ * here for supplied bytes to be checked against and this answers `false`.
522
+ */
523
+ export function isFilePart(part: unknown): boolean {
524
+ return classify(part) === null;
525
+ }
526
+
527
+ /**
528
+ * The parts of a message, or none at all.
529
+ *
530
+ * A message that carries no `parts` array carries no file parts, and that is
531
+ * not a deviation: it is the common case, a JSON-only message. Every supplied
532
+ * byte string then has no part to belong to and is refused, which is the
533
+ * reading section 4.1 asks for and not an exception.
534
+ */
535
+ function messageParts(message: unknown): unknown[] {
536
+ if (!isPlainObject(message)) return [];
537
+ const parts = message.parts;
538
+ return Array.isArray(parts) ? [...parts] : [];
539
+ }
540
+
541
+ /**
542
+ * The message-level named results, before any part is read.
543
+ *
544
+ * One condition reaches this today: a `parts` that is present, is not null and
545
+ * is not an array. It gets a name rather than the silence it had (proof#156
546
+ * gate), because a message with part-shaped content and no parts is exactly the
547
+ * shape section 4.1's "one result per part" leaves nothing to say about.
548
+ */
549
+ function messageResults(message: unknown): string[] {
550
+ if (!isPlainObject(message)) return [];
551
+ if (!hasOwn(message, "parts")) return [];
552
+ const parts = message.parts;
553
+ if (parts === null || parts === undefined || Array.isArray(parts)) return [];
554
+ return [PARTS_NOT_AN_ARRAY];
555
+ }
556
+
557
+ function sameBytes(left: Uint8Array, right: Uint8Array): boolean {
558
+ if (left.length !== right.length) return false;
559
+ for (let i = 0; i < left.length; i++) {
560
+ if (left[i] !== right[i]) return false;
561
+ }
562
+ return true;
563
+ }
564
+
565
+ function asAscii(data: Uint8Array): string {
566
+ let out = "";
567
+ for (const byte of data) out += String.fromCharCode(byte);
568
+ return out;
569
+ }
570
+
571
+ /**
572
+ * Strict ASCII hex. Written out rather than delegated, because Python's
573
+ * `bytes.fromhex` skips ASCII whitespace and a charset test does not: a decoder
574
+ * the two kernels disagree about would put a record on one side of
575
+ * `part_encoding_mismatch` in one language and the other side of it in the
576
+ * other.
577
+ *
578
+ * EVERY GUARD HERE AND IN `base64Decode` IS PINNED BY A CORPUS VECTOR CARRYING
579
+ * A HAND-WRITTEN EXPECTATION (proof#156 second gate, F3), named in the comment
580
+ * beside it. Until that round, six of the seven produced no signal when
581
+ * deleted: the whole ladder and the whole leg stayed green, so a third kernel
582
+ * that delegated to `atob` or `base64.b64decode` reproduced the entire corpus
583
+ * byte for byte, was conformant under `architecture.md` K3, and still put a
584
+ * record on the other side of `part_encoding_mismatch`. An agreement case
585
+ * cannot close that: the leg grades two kernels against each other, so a guard
586
+ * deleted from both is invisible to it. Only a hand-written `expected` block
587
+ * states which side of the boundary an input falls on.
588
+ */
589
+ function hexDecode(data: Uint8Array): Uint8Array | null {
590
+ // An odd number of characters is not hex. Deleting this line lets `"ab0"`
591
+ // read as `0xab 0x00`, so a receiver handed a truncated hex string writes
592
+ // `part_encoding_mismatch` where it owes `part_mismatched` and a
593
+ // substitution: `parts-decoder-hex-odd-length-01`.
594
+ if (data.length === 0 || data.length % 2 !== 0) return null;
595
+ const text = asAscii(data);
596
+ if (!HEX_CHARSET.test(text)) return null;
597
+ const out = new Uint8Array(data.length / 2);
598
+ for (let i = 0; i < out.length; i++) {
599
+ out[i] = Number.parseInt(text.slice(i * 2, i * 2 + 2), 16);
600
+ }
601
+ return out;
602
+ }
603
+
604
+ /**
605
+ * Strict base64, standard OR URL-safe, padded or not, canonical only.
606
+ *
607
+ * Written out for the same reason as `hexDecode`: Python's `base64.b64decode`
608
+ * and JavaScript's `atob` disagree about padding, about the URL-safe alphabet
609
+ * and about non-zero trailing bits, and each of those disagreements decides
610
+ * whether a receiver refuses its own decoding defect or records a tamper
611
+ * against an honest sender. The two alphabets are not mixed: a string carrying
612
+ * one character from each is neither spelling and decodes to nothing.
613
+ *
614
+ * TWO GUARDS THAT STOOD HERE WERE DELETED IN THE PROOF#156 SECOND GATE'S
615
+ * ROUND, because they could not change a decode for any input and so read as
616
+ * protection that was not there:
617
+ *
618
+ * * `pad > 0 && text.length % 4 !== 0` is the SAME PREDICATE as the
619
+ * `(body.length + pad) % 4` test below it. The strip loop above makes
620
+ * `text` exactly `body + "=".repeat(pad)`, so the two lengths are equal by
621
+ * construction and the two conditions are one condition written twice.
622
+ * Each masked the other, which is why deleting either alone changed
623
+ * nothing;
624
+ * * `body.includes("=")` is subsumed by the alphabet test three lines below
625
+ * it: `=` is in neither alphabet, so a body carrying one is refused there.
626
+ *
627
+ * Checked exhaustively over every byte string of length 0 to 2 across all 256
628
+ * byte values, exhaustively over lengths 3 to 6 on the 16-character alphabet
629
+ * that reaches these branches, and over 500,000 random byte strings: zero
630
+ * decodes move.
631
+ * The remaining guards each carry the vector that pins them.
632
+ */
633
+ function base64Decode(data: Uint8Array): Uint8Array | null {
634
+ if (data.length === 0) return null;
635
+ const text = asAscii(data);
636
+ let body = text;
637
+ let pad = 0;
638
+ while (body.endsWith("=")) {
639
+ body = body.slice(0, -1);
640
+ pad += 1;
641
+ }
642
+ // At most two padding characters. Deleting this line lets `"===="` and any
643
+ // aligned body followed by four `=` decode as though the padding were not
644
+ // there: `parts-decoder-base64-four-pad-chars-01`.
645
+ if (pad > 2) return null;
646
+
647
+ const standard = [...body].every((c) => BASE64_STANDARD.includes(c));
648
+ const urlsafe = [...body].every((c) => BASE64_URLSAFE.includes(c));
649
+ // One alphabet or the other, never a merge of the two. `"-/AA"` is neither
650
+ // spelling, and deleting this line does not merge the alphabets: it picks
651
+ // the URL-safe one and asks it for `/`, where `indexOf` answers -1 and
652
+ // garbles the arithmetic into `f7 f0 00`. TWO vectors pin that, one per
653
+ // shape of third kernel: `parts-decoder-base64-mixed-alphabet-01` commits
654
+ // the bytes a kernel that MERGES the alphabets reads, and
655
+ // `parts-decoder-base64-mixed-alphabet-02` commits the bytes this kernel's
656
+ // own -1 produces, which is the one that goes red HERE (proof#156 third
657
+ // gate, C2: deleting this line left all 2224 TypeScript tests green).
658
+ if (!standard && !urlsafe) return null;
659
+ const alphabet = standard ? BASE64_STANDARD : BASE64_URLSAFE;
660
+ // A lone trailing character carries six bits and no encoder emits one.
661
+ // Deleting this lets `"A"` read as the EMPTY blob, so any of the four
662
+ // characters whose low bits are zero could claim to be it:
663
+ // `parts-decoder-base64-single-character-01`.
664
+ if (body.length % 4 === 1) return null;
665
+ // Padding that does not align the string. Deleting this lets a 36-character
666
+ // body followed by one `=` decode as though the `=` were not there:
667
+ // `parts-decoder-base64-padding-misaligned-01`.
668
+ if (pad > 0 && (body.length + pad) % 4 !== 0) return null;
669
+
670
+ let bits = 0;
671
+ let width = 0;
672
+ const out: number[] = [];
673
+ for (const char of body) {
674
+ bits = bits * 64 + alphabet.indexOf(char);
675
+ width += 6;
676
+ if (width >= 8) {
677
+ width -= 8;
678
+ out.push(Math.floor(bits / 2 ** width) & 0xff);
679
+ bits = bits % 2 ** width;
680
+ }
681
+ }
682
+ // Canonical only: the unused low bits of the last character are zero in every
683
+ // encoder's output, and accepting them non-zero would let two spellings of one
684
+ // blob decode to one value. Both `atob` and `base64.b64decode` accept them,
685
+ // which is the sharpest reason this decoder is written out: deleting this
686
+ // line lets `"QR=="` read as `"A"`, so a receiver handed one of the sixteen
687
+ // non-canonical spellings of a one-byte part writes `part_encoding_mismatch`
688
+ // where it owes `part_mismatched` and a substitution:
689
+ // `parts-decoder-non-canonical-tail-01`.
690
+ if (width > 0 && bits !== 0) return null;
691
+ return new Uint8Array(out);
692
+ }
693
+
694
+ /**
695
+ * The inverse of `base64Decode`, written out for the same reason: `btoa` and
696
+ * Python's `base64` module differ in what they accept and in how they pad, and
697
+ * this value is compared against a digest a sender committed, so the two
698
+ * kernels have to emit the same characters.
699
+ */
700
+ function base64Encode(data: Uint8Array, alphabet: string, pad: boolean): Uint8Array {
701
+ let out = "";
702
+ for (let start = 0; start < data.length; start += 3) {
703
+ const chunk = data.subarray(start, start + 3);
704
+ const bits =
705
+ (chunk[0]! << 16) | ((chunk[1] ?? 0) << 8) | (chunk[2] ?? 0);
706
+ const chars = [18, 12, 6, 0].map((shift) => alphabet[(bits >> shift) & 0x3f]!);
707
+ const keep = chunk.length + 1;
708
+ out += chars.slice(0, keep).join("");
709
+ if (pad && keep < 4) out += "=".repeat(4 - keep);
710
+ }
711
+ return asciiBytes(out);
712
+ }
713
+
714
+ function hexEncode(data: Uint8Array, alphabet: string): Uint8Array {
715
+ let out = "";
716
+ for (const byte of data) out += alphabet[byte >> 4]! + alphabet[byte & 0x0f]!;
717
+ return asciiBytes(out);
718
+ }
719
+
720
+ function asciiBytes(text: string): Uint8Array {
721
+ const out = new Uint8Array(text.length);
722
+ for (let i = 0; i < text.length; i++) out[i] = text.charCodeAt(i) & 0xff;
723
+ return out;
724
+ }
725
+
726
+ /**
727
+ * Every spelling of `data` an honest stack might have been handed.
728
+ *
729
+ * The ENCODING direction of the encoding guard. A receiver whose stack decoded
730
+ * what it was given holds the decoded bytes while the sender committed the
731
+ * encoded text, which is what a single-line DER attachment, a PEM body and a
732
+ * JWT each are: the part's bytes ARE the base64 text. Guarding only the
733
+ * decoding direction told that receiver it held a tamper and fired the
734
+ * substitution, which is the one outcome this module calls worse than recording
735
+ * nothing.
736
+ *
737
+ * The list is fixed and short, the same six spellings the decoder accepts, so
738
+ * the two kernels try the same candidates in the same order and the cost is
739
+ * linear in the length of the supply.
740
+ *
741
+ * A `data.length === 0` guard stood here and was deleted in the proof#156
742
+ * second gate's round, for the same reason as the two in `base64Decode`: it
743
+ * could not change an answer. This is reached only from `respellingExplains`,
744
+ * and only after `sha256(data)` has already been compared to `contentHash` and
745
+ * missed. Every spelling of the empty byte string is the empty byte string, so
746
+ * the one candidate it would have produced is the digest that just failed. An
747
+ * optimization written as a guard reads as protection that is not there.
748
+ */
749
+ function respellings(data: Uint8Array): Uint8Array[] {
750
+ return [
751
+ base64Encode(data, BASE64_STANDARD, true),
752
+ base64Encode(data, BASE64_STANDARD, false),
753
+ base64Encode(data, BASE64_URLSAFE, true),
754
+ base64Encode(data, BASE64_URLSAFE, false),
755
+ hexEncode(data, LOWER_HEX),
756
+ hexEncode(data, UPPER_HEX),
757
+ ];
758
+ }
759
+
760
+ /**
761
+ * Whether a base64 or hex respelling of `data`, in EITHER direction, hashes to
762
+ * `contentHash`. `contentHash` arrives lowercased: the charset is pinned and
763
+ * the case is not (proof#135), so every comparison in this module is made on
764
+ * one spelling.
765
+ */
766
+ async function respellingExplains(data: Uint8Array, contentHash: string): Promise<boolean> {
767
+ for (const decoded of [base64Decode(data), hexDecode(data)]) {
768
+ if (decoded !== null && (await sha256Hex(decoded)) === contentHash) return true;
769
+ }
770
+ for (const encoded of respellings(data)) {
771
+ if ((await sha256Hex(encoded)) === contentHash) return true;
772
+ }
773
+ return false;
774
+ }
775
+
776
+ /**
777
+ * What a receiver commits to, given the message and the bytes it holds.
778
+ *
779
+ * `supplied` is the bytes the receiver actually holds, each named by the index
780
+ * of the part it belongs to. An empty list is the common case, a receiver that
781
+ * holds no part's bytes, and it reads exactly as section 4.1 read before this
782
+ * amendment: every file part is `PART_UNCHECKED` and the message a receiver
783
+ * commits to is the message it was given.
784
+ *
785
+ * Where a part's bytes hash to something other than its `content_hash`, or
786
+ * where their count is not its `content_length`, the returned `heldMessage`
787
+ * carries that part's `content_hash` and `content_length` replaced by the held
788
+ * bytes' own. The receiver commits `event.message_hash` over THAT, so its
789
+ * record and the sender's disagree and the pair fails on `message_hash`.
790
+ *
791
+ * A refusal is scoped to the supplied entry it is about: the part it names is
792
+ * not checked and not substituted, every other part reads as it would have, and
793
+ * `heldMessage` is returned either way. Nothing a caller or a sender can do
794
+ * denies the receiver a record.
795
+ */
796
+ export async function commitHeldMessage(
797
+ message: unknown,
798
+ supplied: readonly SuppliedPart[] = [],
799
+ ): Promise<HeldMessage> {
800
+ const parts = messageParts(message);
801
+ const classifications = parts.map(classify);
802
+ // The inline hash agreement, refined out of the shape pass because it hashes.
803
+ for (let i = 0; i < parts.length; i++) {
804
+ if (classifications[i] !== PART_INLINE_BYTES) continue;
805
+ if (!(await inlineClaimsAgree(parts[i] as Record<string, unknown>))) {
806
+ classifications[i] = PART_INLINE_MISMATCHED;
807
+ }
808
+ }
809
+
810
+ const refusals: Refusal[] = [];
811
+ const notes: Note[] = [];
812
+ const byPart = new Map<number, { entry: number; data: Uint8Array }[]>();
813
+
814
+ supplied.forEach((item, entry) => {
815
+ const index = item.part;
816
+ if (!isSafeIndex(index) || (index as number) >= parts.length) {
817
+ // No part of this message: the only genuinely message-level refusal, and
818
+ // it still names itself rather than going quiet.
819
+ refusals.push({ name: BYTES_FOR_UNKNOWN_PART, part: null, entry });
820
+ return;
821
+ }
822
+ if (classifications[index as number] !== null) {
823
+ // A part that EXISTS and cannot be checked. Scoped to that part, so a
824
+ // sender cannot buy silence by emitting one uncheckable part beside the
825
+ // part it altered.
826
+ refusals.push({ name: BYTES_FOR_UNKNOWN_PART, part: index as number, entry });
827
+ return;
828
+ }
829
+ const key = index as number;
830
+ const existing = byPart.get(key);
831
+ if (existing === undefined) byPart.set(key, [{ entry, data: item.data }]);
832
+ else existing.push({ entry, data: item.data });
833
+ });
834
+
835
+ const readings: PartReading[] = [];
836
+ const substituted: number[] = [];
837
+ const replacements = new Map<number, { contentHash: string; contentLength: number }>();
838
+
839
+ for (let index = 0; index < parts.length; index++) {
840
+ const pre = classifications[index];
841
+ if (pre !== null) {
842
+ readings.push({ index, result: pre });
843
+ continue;
844
+ }
845
+ const entries = byPart.get(index) ?? [];
846
+ if (entries.length === 0) {
847
+ readings.push({ index, result: PART_UNCHECKED });
848
+ continue;
849
+ }
850
+
851
+ const first = entries[0]!;
852
+ const conflicting = entries.slice(1).find((e) => !sameBytes(e.data, first.data));
853
+ if (conflicting !== undefined) {
854
+ refusals.push({ name: CONFLICTING_PART_BYTES, part: index, entry: conflicting.entry });
855
+ readings.push({ index, result: PART_UNCHECKED });
856
+ continue;
857
+ }
858
+ if (entries.length > 1) {
859
+ notes.push({ name: PART_SUPPLIED_TWICE, part: index, entry: entries[1]!.entry });
860
+ }
861
+
862
+ const part = parts[index] as Record<string, unknown>;
863
+ const contentHash = (part.content_hash as string).toLowerCase();
864
+ const contentLength = part.content_length as number;
865
+ const digest = await sha256Hex(first.data);
866
+ if (digest === contentHash) {
867
+ // The LENGTH is compared too, and a disagreement substitutes exactly as a
868
+ // hash disagreement does (proof#156 gate). Before that, a part whose
869
+ // stated length the receiver could see was false read `part_matched`, so
870
+ // the receiver certified the part and committed the false length with it.
871
+ if (first.data.length === contentLength) {
872
+ readings.push({ index, result: PART_MATCHED });
873
+ continue;
874
+ }
875
+ readings.push({ index, result: PART_MISMATCHED });
876
+ substituted.push(index);
877
+ replacements.set(index, { contentHash: digest, contentLength: first.data.length });
878
+ continue;
879
+ }
880
+ if (await respellingExplains(first.data, contentHash)) {
881
+ refusals.push({ name: PART_ENCODING_MISMATCH, part: index, entry: first.entry });
882
+ readings.push({ index, result: PART_UNCHECKED });
883
+ continue;
884
+ }
885
+
886
+ readings.push({ index, result: PART_MISMATCHED });
887
+ substituted.push(index);
888
+ replacements.set(index, { contentHash: digest, contentLength: first.data.length });
889
+ }
890
+
891
+ const rank = (r: Refusal): [number, number, number] => [
892
+ (REFUSAL_ORDER as readonly string[]).indexOf(r.name),
893
+ r.part === null ? -1 : r.part,
894
+ r.entry === null ? -1 : r.entry,
895
+ ];
896
+ refusals.sort((a, b) => {
897
+ const [an, ap, ae] = rank(a);
898
+ const [bn, bp, be] = rank(b);
899
+ return an - bn || ap - bp || ae - be;
900
+ });
901
+ notes.sort((a, b) => {
902
+ if (a.name !== b.name) return a.name < b.name ? -1 : 1;
903
+ return (a.part === null ? -1 : a.part) - (b.part === null ? -1 : b.part);
904
+ });
905
+
906
+ let held: unknown = message;
907
+ if (replacements.size > 0) {
908
+ // Rebuilt rather than mutated in place: the message a caller handed in is
909
+ // the caller's, and a reading that edits its input is a reading that
910
+ // changes what the caller commits to on the honest path too.
911
+ const heldParts = parts.map((part, index) => {
912
+ const replacement = replacements.get(index);
913
+ if (replacement === undefined) return part;
914
+ return {
915
+ ...(part as Record<string, unknown>),
916
+ content_hash: replacement.contentHash,
917
+ content_length: replacement.contentLength,
918
+ };
919
+ });
920
+ held = { ...(message as Record<string, unknown>), parts: heldParts };
921
+ }
922
+
923
+ const order = MESSAGE_RESULT_ORDER as readonly string[];
924
+ return {
925
+ parts: readings,
926
+ messageResults: messageResults(message).sort(
927
+ (a, b) => order.indexOf(a) - order.indexOf(b),
928
+ ),
929
+ refusals,
930
+ notes,
931
+ heldMessage: held,
932
+ substituted,
933
+ };
934
+ }
935
+
936
+ /**
937
+ * The parts the receiver HELD bytes for and did NOT check.
938
+ *
939
+ * The gap between "nothing was substituted" and "every part is clean", named
940
+ * so a caller does not have to re-derive it from the refusal list (proof#156
941
+ * second gate, F5). A part is in here where a refusal NAMES it and its reading
942
+ * is one of `HELD_UNCHECKED_RESULTS`: the receiver had bytes for that part,
943
+ * the rule declined to grade them, and NOTHING about that reaches the
944
+ * committed record.
945
+ *
946
+ * THE RULE, in one sentence, because a filter is not a rule. A part is in here
947
+ * where the receiver held bytes for it AND the message itself does not commit
948
+ * its content. `PART_UNCHECKED` is a refused supply;
949
+ * `PART_MALFORMED_DESCRIPTOR` is a part whose content travels BESIDE the
950
+ * message under a claim no receiver can use, so the receiver's bytes are
951
+ * exactly as ungraded and the record says as little. The first cut of this
952
+ * function omitted the second, which the third gate measured: a `kind: "file"`
953
+ * part with a non-conformant `content_hash` or `content_length`, bytes held,
954
+ * read `[]` here, so a caller following the rule this module prescribes wrote
955
+ * `accepted` over a part it held bytes for and never checked. That is the
956
+ * class the mechanism exists to close, and Phil named it in proof#162's
957
+ * ratification as the gap that decision inherits unless it is closed here.
958
+ *
959
+ * Three results are excluded ON PURPOSE. An inline part (`PART_INLINE_BYTES`,
960
+ * `PART_INLINE_MISMATCHED`) and a non-file part (`PART_NOT_A_FILE`) carry
961
+ * their content INSIDE the message, and `message_hash` commits it on both
962
+ * sides: bytes supplied beside one of those grade nothing and hide nothing,
963
+ * because a reader of either pack reads the content itself. Naming them would
964
+ * fire the caller's obligation on parts the swapped-bytes attack cannot reach
965
+ * at all.
966
+ *
967
+ * Why it is worth a function rather than a note. Delivering a tampered copy of
968
+ * a part alone is `part_mismatched`, is substituted, and fails the pair on
969
+ * `message_hash`. Delivering the tampered copy AND the true one is
970
+ * `conflicting_part_bytes`, is never substituted, and the pair VERIFIES, so
971
+ * adding data suppresses detection and the only trace is a refusal the
972
+ * receiving side publishes at its own discretion.
973
+ *
974
+ * NOT the same as "this part reads `PART_UNCHECKED`". A receiver that holds no
975
+ * bytes at all reads every file part that way, and that is the COMMON CASE,
976
+ * unchanged by A18 and not a reason to withhold `accepted`. Only a part whose
977
+ * bytes the receiver actually held and could not grade is in here.
978
+ *
979
+ * What this does NOT do: it cannot stop a caller writing `accepted` anyway.
980
+ * This module reads and does not write the record. proof#162 ratified what the
981
+ * record layer does instead (Phil, 2026-09-22): `accepted` keeps its meaning
982
+ * and the COUNT of these parts rides in an additive `context` key, REQUIRED
983
+ * when it is not zero, enforced against SDKs through conformance vectors. So a
984
+ * part missing from this list is a part no record built on that rule will ever
985
+ * mention.
986
+ */
987
+ export function uncheckedHeldParts(reading: HeldMessage): number[] {
988
+ const unchecked = new Set(
989
+ reading.parts
990
+ .filter((p) => HELD_UNCHECKED_RESULTS.includes(p.result))
991
+ .map((p) => p.index),
992
+ );
993
+ const named = new Set<number>();
994
+ for (const refusal of reading.refusals) {
995
+ if (refusal.part !== null && unchecked.has(refusal.part)) named.add(refusal.part);
996
+ }
997
+ return [...named].sort((a, b) => a - b);
998
+ }