@sanning/proof 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/evidence.ts CHANGED
@@ -73,6 +73,33 @@ export const ANCHOR_TRACE_BODY_TYPES = [
73
73
  // verifyExportBody (§5).
74
74
  export const EXPORT_BODY_TYPE = "sanning.evidence.export/v1";
75
75
 
76
+ /**
77
+ * The Sanning-signed interval stamp body (evidence-bundle.md §5.2, DL-58).
78
+ *
79
+ * Its own `body_type` rather than a widened anchor-trace body, and the reason
80
+ * is the whole decision: an anchor-trace checkpoint carries a PRODUCER-signed
81
+ * `sanning.events/v1` envelope, and a stamp has no producer signature at all —
82
+ * Sanning places it, under DL-52, for a customer who holds no chain identity.
83
+ * The two rejected options were making `envelope` optional and synthesising an
84
+ * envelope that Sanning signs; the second would have made a Sanning
85
+ * attestation indistinguishable ON THE WIRE from a producer's, which is
86
+ * unrecoverable once witnessed.
87
+ */
88
+ export const STAMP_TRACE_BODY_TYPE = "sanning.stamp.trace/v1";
89
+
90
+ /**
91
+ * The version string INSIDE a witnessed stamp body — a different string from
92
+ * the `body_type` above, and the two are easy to confuse.
93
+ *
94
+ * `sanning.stamp.trace/v1` discriminates the BUNDLE BODY: it is the reader's
95
+ * dispatch key. `sanning.stamp/v1` is the control plane's own version of the
96
+ * bytes it hands a witness (`control-plane/src/stamp-tree.ts`,
97
+ * `STAMP_BODY_VERSION`). A `sanning.stamp.trace/v1` body pins the inner
98
+ * version to exactly this value: two answers to one question inside one
99
+ * signature is the §5.1.2 mixed-vocabulary reject, one layer down.
100
+ */
101
+ export const STAMP_BODY_VERSION = "sanning.stamp/v1";
102
+
76
103
  // ---- Wire types (evidence-bundle.md §2 + §5.1) ------------------------------
77
104
 
78
105
  export interface EvidenceIssuer {
@@ -160,6 +187,64 @@ export interface AnchorTraceBody {
160
187
  events: TraceEvent[];
161
188
  }
162
189
 
190
+ // ---- `sanning.stamp.trace/v1` wire types (evidence-bundle.md §5.2) ---------
191
+
192
+ /**
193
+ * One sub-tree of a stamp, as the WITNESSED bytes carry it.
194
+ *
195
+ * Keyed in the body by a blinded reference (an HMAC under a per-org secret we
196
+ * never publish), so a reader learns that the org runs N agents and their
197
+ * relative volumes and learns no name. The RANGE is deliberately in the clear:
198
+ * it is what makes a later per-agent slice claim checkable by a third party
199
+ * without Sanning, and hiding it would put us back in the trust path.
200
+ */
201
+ export interface StampSubtree {
202
+ first_leaf: number;
203
+ leaf_count: number;
204
+ /** Hex RFC-9162 root over this sub-tree's leaves alone. */
205
+ root: string;
206
+ }
207
+
208
+ /**
209
+ * The stamp body as the control plane witnesses it
210
+ * (`control-plane/src/stamp-tree.ts`, `StampBody`).
211
+ *
212
+ * Never read from the bundle directly — it is parsed out of `stamp_bytes`,
213
+ * which is the only authority. Present as a type so the parse has a shape.
214
+ */
215
+ export interface StampBody {
216
+ stamp_version: string;
217
+ /** The org, BLINDED. Not an org id, and not reversible without the secret. */
218
+ org_ref: string;
219
+ interval_start: string;
220
+ interval_end: string;
221
+ merkle_root: string;
222
+ leaf_count: number;
223
+ subtrees: Record<string, StampSubtree>;
224
+ }
225
+
226
+ /** One entry of a `sanning.stamp.trace/v1` body's `stamps[]` (§5.2). */
227
+ export interface StampEntry {
228
+ /**
229
+ * The stamp's identity within this bundle, DERIVED: hex SHA-256 of the
230
+ * DECODED `stamp_bytes`, not of the hex text. A verifier MUST recompute it.
231
+ */
232
+ stamp_ref: string;
233
+ /** Lowercase hex of the exact JCS bytes that were handed to the witness. */
234
+ stamp_bytes: string;
235
+ /**
236
+ * Where the stamp was witnessed, IF IT HAS BEEN (§5.1.1). Absent is honest:
237
+ * a sealed-but-unconfirmed stamp is witnessed by nobody, and an emitter that
238
+ * filled this in from a submission receipt would be claiming a chain
239
+ * position that does not exist yet.
240
+ */
241
+ anchor_ref?: AnchorRef;
242
+ }
243
+
244
+ export interface StampTraceBody {
245
+ stamps: StampEntry[];
246
+ }
247
+
163
248
  export interface EvidenceBundle {
164
249
  spec_version: string;
165
250
  body_type: string;
@@ -265,6 +350,56 @@ export interface EventResult {
265
350
  errors: string[];
266
351
  }
267
352
 
353
+ /** One sub-tree's recomputed result (§5.2). */
354
+ export interface StampSubtreeResult {
355
+ /** The blinded key the body spells it under. Meaningless without the org's secret. */
356
+ ref: string;
357
+ firstLeaf: number;
358
+ leafCount: number;
359
+ root: string;
360
+ }
361
+
362
+ /** One `stamps[]` entry's result (§5.2). */
363
+ export interface StampResult {
364
+ /** The stamp's derived identity, as the bundle spells it. "" when unusable. */
365
+ stampRef: string;
366
+ /** The asserted `stamp_ref` equals SHA-256 of the decoded `stamp_bytes`. */
367
+ stampRefOk: boolean;
368
+ /**
369
+ * The witnessed bytes decoded, parsed, and re-canonicalized to themselves.
370
+ *
371
+ * The last clause is not pedantry. The plane stores these bytes as TEXT and
372
+ * replays them verbatim precisely because a round-trip through a normalizing
373
+ * serializer is not guaranteed to reproduce what was signed; a body that is
374
+ * not JCS-canonical is one that every re-deriving reader hashes differently.
375
+ */
376
+ bodyOk: boolean;
377
+ stampVersion: string | null;
378
+ intervalStart: string | null;
379
+ intervalEnd: string | null;
380
+ merkleRoot: string | null;
381
+ leafCount: number | null;
382
+ /**
383
+ * Every sub-tree range accounts for exactly one leaf of the stamp: the
384
+ * ranges sorted by `first_leaf` tile `[0, leaf_count)` with no gap and no
385
+ * overlap, and their counts sum to `leaf_count`.
386
+ */
387
+ subtreesOk: boolean;
388
+ subtrees: StampSubtreeResult[];
389
+ /**
390
+ * Where it was witnessed, or `null` for a stamp nothing has witnessed yet.
391
+ *
392
+ * `null` is NOT a failure and never an accusation — it is the honest state
393
+ * of every stamp for the first minutes of its life and the permanent state
394
+ * of every stamp when no witness is configured. It does hold the bundle at
395
+ * `partial`: a stamp is Sanning's own assertion until something independent
396
+ * carries it.
397
+ */
398
+ anchorRef: AnchorRef | null;
399
+ ok: boolean;
400
+ errors: string[];
401
+ }
402
+
268
403
  export interface EvidenceBundleResult {
269
404
  status: EvidenceStatus;
270
405
  // The wrapper: accepted major, body_hash recompute, Ed25519 wrapper signature.
@@ -284,6 +419,12 @@ export interface EvidenceBundleResult {
284
419
  // above are the recomputed SOURCE-bundle results in that case. Absent for a
285
420
  // plain anchor-trace bundle — additive, backward-compatible.
286
421
  export?: ExportResult;
422
+ // Present ONLY for a `sanning.stamp.trace/v1` body (evidence-bundle.md §5.2):
423
+ // the per-stamp recomputed results. `checkpoints`/`events` stay empty for
424
+ // such a bundle — a stamp body carries neither, and reporting an empty list
425
+ // as "nothing was wrong" is the exact confusion `partial` exists to prevent.
426
+ // Absent for every other body — additive, backward-compatible.
427
+ stamps?: StampResult[];
287
428
  errors: string[];
288
429
  }
289
430
 
@@ -572,6 +713,13 @@ export async function verifyEvidenceBundle(
572
713
  return verifyExportBody(b, specVersionOk, assertedStatus, errors, options);
573
714
  }
574
715
 
716
+ // The Sanning-signed interval stamp body (evidence-bundle.md §5.2). The
717
+ // wrapper is authentic — and for this body that IS "Sanning signed it", since
718
+ // a stamp carries no second signature of its own inside the bundle.
719
+ if (bodyType === STAMP_TRACE_BODY_TYPE) {
720
+ return verifyStampTrace(b, specVersionOk, assertedStatus, errors);
721
+ }
722
+
575
723
  if (bodyType !== ANCHOR_TRACE_BODY_TYPE && bodyType !== ANCHOR_TRACE_BODY_TYPE_V1) {
576
724
  // The wrapper is authentic but we don't know this body's structure. Per
577
725
  // wrap-don't-merge, that is "partial" (cryptographically sound wrapper,
@@ -1117,6 +1265,332 @@ async function verifyAnchorTrace(
1117
1265
  };
1118
1266
  }
1119
1267
 
1268
+ // ===========================================================================
1269
+ // `sanning.stamp.trace/v1` — the Sanning-signed interval stamp (§5.2, DL-58)
1270
+ //
1271
+ // ── What this can prove, and what it deliberately does not claim ──
1272
+ //
1273
+ // A stamp is not a producer artifact. Under DL-52 the customer signs an
1274
+ // envelope and POSTs it; the commitment is witnessed later, on an interval, by
1275
+ // a stamp the customer never sees and holds no key for. So there is no
1276
+ // producer signature inside this body to check, and — this is the part worth
1277
+ // being precise about — there is no SECOND Sanning signature either. The
1278
+ // control plane stores the stamp's canonical bytes and hands them to a witness
1279
+ // as a signed chain data item; the signature lives on the chain, not in the
1280
+ // `stamps` table and not in this body.
1281
+ //
1282
+ // What "Sanning signed this" means for a stamp bundle is therefore exactly the
1283
+ // WRAPPER signature, verified generically before this function is reached. And
1284
+ // what makes the stamp evidence rather than an assertion is the witness, which
1285
+ // is on a chain and not checkable offline. Hence the rollup below: a stamp we
1286
+ // can read but nobody has witnessed holds the bundle at `partial`.
1287
+ //
1288
+ // So the checkable surface here is the stamp's INTERNAL consistency against
1289
+ // the one authority in the bundle — the witnessed bytes:
1290
+ //
1291
+ // 1. `stamp_ref` is SHA-256 of the DECODED bytes (derived, not asserted).
1292
+ // 2. Those bytes parse and re-canonicalize to themselves under JCS.
1293
+ // 3. Their `stamp_version` is the one this body_type pins.
1294
+ // 4. Every sub-tree range accounts for exactly one leaf of the stamp.
1295
+ //
1296
+ // (4) is the one that carries customer weight. R-8's whole per-agent story is
1297
+ // "prove this agent was under evidence over window W", answered by a
1298
+ // contiguous `first_leaf`/`leaf_count` slice of the org tree. Ranges that do
1299
+ // not tile `[0, leaf_count)` describe a partition that does not exist, so a
1300
+ // slice claim resting on them is unfounded — and unlike a bad signature,
1301
+ // nothing else in the stack would ever notice.
1302
+ // ===========================================================================
1303
+
1304
+ /** Lowercase hex, even length, non-empty. The family's serialization rule. */
1305
+ function isLowerHex(s: unknown, nibbles?: number): s is string {
1306
+ if (typeof s !== "string" || s.length === 0 || s.length % 2 !== 0) return false;
1307
+ if (nibbles !== undefined && s.length !== nibbles) return false;
1308
+ return /^[0-9a-f]+$/.test(s);
1309
+ }
1310
+
1311
+ function isNonNegInt(n: unknown): n is number {
1312
+ return typeof n === "number" && Number.isInteger(n) && n >= 0;
1313
+ }
1314
+
1315
+ /**
1316
+ * Parse and check one stamp's witnessed bytes.
1317
+ *
1318
+ * Errors accumulate rather than short-circuit wherever a later check is still
1319
+ * meaningful, so a bundle with two independent defects reports two — a
1320
+ * verifier that stops at the first one turns a second fix into a second
1321
+ * round-trip.
1322
+ */
1323
+ async function verifyStampEntry(
1324
+ raw: unknown,
1325
+ seen: Set<string>,
1326
+ ): Promise<StampResult> {
1327
+ const errors: string[] = [];
1328
+ const base: StampResult = {
1329
+ stampRef: "",
1330
+ stampRefOk: false,
1331
+ bodyOk: false,
1332
+ stampVersion: null,
1333
+ intervalStart: null,
1334
+ intervalEnd: null,
1335
+ merkleRoot: null,
1336
+ leafCount: null,
1337
+ subtreesOk: false,
1338
+ subtrees: [],
1339
+ anchorRef: null,
1340
+ ok: false,
1341
+ errors,
1342
+ };
1343
+
1344
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
1345
+ errors.push("stamp entry is not an object");
1346
+ return base;
1347
+ }
1348
+ const e = raw as Partial<StampEntry> & Record<string, unknown>;
1349
+
1350
+ // --- the witnessed bytes, which are the only authority in this body -------
1351
+ if (!isLowerHex(e.stamp_bytes)) {
1352
+ errors.push("stamp_bytes is missing or not lowercase hex");
1353
+ return base;
1354
+ }
1355
+ let bytes: Uint8Array;
1356
+ try {
1357
+ bytes = hexToBytes(e.stamp_bytes);
1358
+ } catch (err) {
1359
+ errors.push(`stamp_bytes is not hex: ${stringifyErr(err)}`);
1360
+ return base;
1361
+ }
1362
+
1363
+ // --- the derived identity -------------------------------------------------
1364
+ const derived = await sha256Hex(bytes);
1365
+ if (typeof e.stamp_ref !== "string" || e.stamp_ref === "") {
1366
+ errors.push("stamp entry missing stamp_ref");
1367
+ } else if (e.stamp_ref.toLowerCase() !== derived) {
1368
+ // The bytes were edited and the label was not — or the label was edited
1369
+ // and the bytes were not. Either way the bundle names a stamp it is not
1370
+ // carrying, and quoting that name to a witness would resolve to something
1371
+ // else entirely.
1372
+ errors.push(
1373
+ `stamp_ref does not match SHA-256(stamp_bytes): claimed=${e.stamp_ref} derived=${derived}`,
1374
+ );
1375
+ } else {
1376
+ base.stampRefOk = true;
1377
+ base.stampRef = derived;
1378
+ if (seen.has(derived)) {
1379
+ errors.push(`duplicate stamp_ref ${derived}`);
1380
+ base.stampRefOk = false;
1381
+ } else {
1382
+ seen.add(derived);
1383
+ }
1384
+ }
1385
+
1386
+ // --- the body itself ------------------------------------------------------
1387
+ let body: StampBody;
1388
+ try {
1389
+ const parsed: unknown = JSON.parse(new TextDecoder().decode(bytes));
1390
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
1391
+ errors.push("stamp body is not a JSON object");
1392
+ return base;
1393
+ }
1394
+ body = parsed as StampBody;
1395
+ // Re-canonicalize and compare. The plane replays these bytes verbatim on
1396
+ // every submit attempt for exactly this reason: a non-canonical body makes
1397
+ // a retry a DIFFERENT submission, and makes every independent re-derivation
1398
+ // of the stamp disagree with the one that was witnessed.
1399
+ if (jcs(body as unknown as Record<string, unknown>) !== new TextDecoder().decode(bytes)) {
1400
+ errors.push("stamp_bytes are not JCS-canonical (RFC 8785)");
1401
+ return base;
1402
+ }
1403
+ } catch (err) {
1404
+ errors.push(`stamp body is not JSON: ${stringifyErr(err)}`);
1405
+ return base;
1406
+ }
1407
+
1408
+ if (body.stamp_version !== STAMP_BODY_VERSION) {
1409
+ // A `sanning.stamp.trace/v1` body whose inner version is something else is
1410
+ // two answers to one question inside one signature. The body_type is the
1411
+ // reader's dispatch key and it said v1; honouring the other spelling is
1412
+ // how a reader half-parses a shape it does not know.
1413
+ errors.push(
1414
+ `unsupported stamp_version ${JSON.stringify(body.stamp_version)} in a ` +
1415
+ `${STAMP_TRACE_BODY_TYPE} body (expected ${STAMP_BODY_VERSION})`,
1416
+ );
1417
+ return base;
1418
+ }
1419
+ base.stampVersion = body.stamp_version;
1420
+ base.bodyOk = true;
1421
+
1422
+ for (const f of ["org_ref", "interval_start", "interval_end"] as const) {
1423
+ if (typeof body[f] !== "string" || body[f] === "") {
1424
+ errors.push(`stamp body ${f} is missing or not a non-empty string`);
1425
+ base.bodyOk = false;
1426
+ }
1427
+ }
1428
+ base.intervalStart = typeof body.interval_start === "string" ? body.interval_start : null;
1429
+ base.intervalEnd = typeof body.interval_end === "string" ? body.interval_end : null;
1430
+
1431
+ if (!isLowerHex(body.merkle_root, 64)) {
1432
+ errors.push("stamp body merkle_root is not 64 lowercase hex characters");
1433
+ base.bodyOk = false;
1434
+ } else {
1435
+ base.merkleRoot = body.merkle_root;
1436
+ }
1437
+ if (!isNonNegInt(body.leaf_count)) {
1438
+ errors.push("stamp body leaf_count is not a non-negative integer");
1439
+ base.bodyOk = false;
1440
+ } else {
1441
+ base.leafCount = body.leaf_count;
1442
+ }
1443
+
1444
+ // --- the sub-tree ranges --------------------------------------------------
1445
+ base.subtreesOk = checkSubtrees(body, base, errors);
1446
+
1447
+ base.anchorRef = parseAnchorRef(e.anchor_ref, errors);
1448
+
1449
+ base.ok =
1450
+ base.stampRefOk && base.bodyOk && base.subtreesOk && errors.length === 0;
1451
+ return base;
1452
+ }
1453
+
1454
+ /**
1455
+ * The range arithmetic (§5.2), and the reason it is a hard check.
1456
+ *
1457
+ * `buildStampTree` orders a stamp's leaves agent-major, which is the only
1458
+ * reason `first_leaf` + `leaf_count` can describe an agent's slice at all: the
1459
+ * ranges partition `[0, leaf_count)` exactly, by construction. A body whose
1460
+ * ranges do not is either not a stamp this stack built or one built wrong, and
1461
+ * in both cases the per-agent claim the ranges exist to support is unfounded.
1462
+ *
1463
+ * The sum is checked BEFORE the tiling and reports its own message, so a body
1464
+ * that is merely short does not get filed under a gap it does not have.
1465
+ */
1466
+ function checkSubtrees(body: StampBody, out: StampResult, errors: string[]): boolean {
1467
+ const raw = body.subtrees;
1468
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
1469
+ errors.push("stamp body subtrees is not an object");
1470
+ return false;
1471
+ }
1472
+
1473
+ let shapeOk = true;
1474
+ const subtrees: StampSubtreeResult[] = [];
1475
+ for (const [ref, v] of Object.entries(raw)) {
1476
+ if (v === null || typeof v !== "object" || Array.isArray(v)) {
1477
+ errors.push(`sub-tree ${ref} is not an object`);
1478
+ shapeOk = false;
1479
+ continue;
1480
+ }
1481
+ const s = v as Partial<StampSubtree>;
1482
+ if (!isNonNegInt(s.first_leaf)) {
1483
+ errors.push(`sub-tree ${ref} first_leaf is not a non-negative integer`);
1484
+ shapeOk = false;
1485
+ }
1486
+ // A zero-leaf sub-tree is not a slice of anything, and admitting one lets
1487
+ // an arbitrary number of empty ranges sit inside a tiling that still adds
1488
+ // up.
1489
+ if (!isNonNegInt(s.leaf_count) || s.leaf_count === 0) {
1490
+ errors.push(`sub-tree ${ref} leaf_count is not a positive integer`);
1491
+ shapeOk = false;
1492
+ }
1493
+ if (!isLowerHex(s.root, 64)) {
1494
+ errors.push(`sub-tree ${ref} root is not 64 lowercase hex characters`);
1495
+ shapeOk = false;
1496
+ }
1497
+ if (!shapeOk) continue;
1498
+ subtrees.push({
1499
+ ref,
1500
+ firstLeaf: s.first_leaf as number,
1501
+ leafCount: s.leaf_count as number,
1502
+ root: s.root as string,
1503
+ });
1504
+ }
1505
+ subtrees.sort((a, b) => a.firstLeaf - b.firstLeaf);
1506
+ out.subtrees = subtrees;
1507
+ if (!shapeOk) return false;
1508
+
1509
+ const total = body.leaf_count;
1510
+ if (!isNonNegInt(total)) return false; // already reported by the caller
1511
+
1512
+ const sum = subtrees.reduce((n, s) => n + s.leafCount, 0);
1513
+ if (sum !== total) {
1514
+ errors.push(
1515
+ `sub-tree leaf_count sum ${sum} does not equal the stamp's leaf_count ${total}`,
1516
+ );
1517
+ return false;
1518
+ }
1519
+
1520
+ let next = 0;
1521
+ for (const s of subtrees) {
1522
+ if (s.firstLeaf !== next) {
1523
+ errors.push(
1524
+ `sub-tree ranges do not tile [0, ${total}): expected a range at leaf ` +
1525
+ `${next}, found one at ${s.firstLeaf}`,
1526
+ );
1527
+ return false;
1528
+ }
1529
+ next += s.leafCount;
1530
+ }
1531
+ return true;
1532
+ }
1533
+
1534
+ async function verifyStampTrace(
1535
+ b: EvidenceBundle,
1536
+ specVersionOk: boolean,
1537
+ assertedStatus: string | null,
1538
+ errors: string[],
1539
+ ): Promise<EvidenceBundleResult> {
1540
+ const body = b.body as StampTraceBody;
1541
+ if (!Array.isArray(body?.stamps)) {
1542
+ return malformed(`${STAMP_TRACE_BODY_TYPE} body must have stamps[]`, true);
1543
+ }
1544
+
1545
+ const seen = new Set<string>();
1546
+ const stamps: StampResult[] = [];
1547
+ for (const entry of body.stamps) {
1548
+ stamps.push(await verifyStampEntry(entry, seen));
1549
+ }
1550
+
1551
+ // --- Rollup ----------------------------------------------------------------
1552
+ const anyHardFailure = stamps.some((s) => !s.ok);
1553
+ const anyUnwitnessed = stamps.some((s) => s.anchorRef === null);
1554
+
1555
+ let status: EvidenceStatus;
1556
+ if (anyHardFailure) {
1557
+ status = "failed";
1558
+ } else if (stamps.length === 0) {
1559
+ // A bundle asserting nothing. Not a failure — nothing here is wrong — but
1560
+ // it must never read `verified`, which a caller would take as a witness it
1561
+ // does not have.
1562
+ status = "partial";
1563
+ errors.push(`${STAMP_TRACE_BODY_TYPE} body carries no stamps`);
1564
+ } else if (anyUnwitnessed) {
1565
+ // The honest half of P-10, one layer up. A stamp with no `anchor_ref` is
1566
+ // sealed and unwitnessed: `retained-by-sanning`, which is a statement about
1567
+ // our coverage and never an accusation about their evidence. It is also not
1568
+ // `verified`, because for a stamp the witness is the entire independent
1569
+ // part — unlike an anchor-trace checkpoint, which still carries a producer
1570
+ // signature and an inclusion proof that stand on their own offline.
1571
+ status = "partial";
1572
+ errors.push(
1573
+ "one or more stamps carries no anchor_ref — sealed by Sanning, witnessed by nobody",
1574
+ );
1575
+ } else {
1576
+ status = "verified";
1577
+ }
1578
+
1579
+ return {
1580
+ status,
1581
+ specVersionOk,
1582
+ bodyHashOk: true,
1583
+ signatureOk: true,
1584
+ bodyType: STAMP_TRACE_BODY_TYPE,
1585
+ onChainChecked: false,
1586
+ checkpoints: [],
1587
+ events: [],
1588
+ assertedStatus,
1589
+ stamps,
1590
+ errors,
1591
+ };
1592
+ }
1593
+
1120
1594
  // ===========================================================================
1121
1595
  // Ingest: materializing the disclosed raw bytes (evidence-bundle.md §5.1).
1122
1596
  //
@@ -1306,7 +1780,13 @@ export async function disclosedContent(
1306
1780
  // wrapper(s) to the inline source bundle — mirroring how verifyEvidenceBundle
1307
1781
  // recurses into `source_bundle`, so the events line up with its results.
1308
1782
  // `undefined` when there is no anchor-trace body to materialize from.
1309
- function resolveTraceEvents(bundle: unknown): TraceEvent[] | undefined {
1783
+ //
1784
+ // Exported for `chain.ts`, which needs the same descent and must not derive it
1785
+ // again: two answers to "which events is this bundle actually about" inside one
1786
+ // kernel is two implementations of one rule, and the one that drifted would be
1787
+ // the one nobody was looking at. Deliberately NOT re-exported from `index.ts` —
1788
+ // same posture as `side-content.ts`, internal and shared.
1789
+ export function resolveTraceEvents(bundle: unknown): TraceEvent[] | undefined {
1310
1790
  let cur: unknown = bundle;
1311
1791
  for (let depth = 0; depth < MAX_EXPORT_UNWRAP; depth++) {
1312
1792
  if (cur === null || typeof cur !== "object" || Array.isArray(cur)) return undefined;
package/src/index.ts CHANGED
@@ -64,6 +64,8 @@ export {
64
64
  ANCHOR_TRACE_BODY_TYPE_V1,
65
65
  ANCHOR_TRACE_BODY_TYPES,
66
66
  EXPORT_BODY_TYPE,
67
+ STAMP_BODY_VERSION,
68
+ STAMP_TRACE_BODY_TYPE,
67
69
  disclosedContent,
68
70
  recomputeExportVerdict,
69
71
  verifyEvidenceBundle,
@@ -90,6 +92,12 @@ export type {
90
92
  OnChainResult,
91
93
  PerGatewayOutcome,
92
94
  AnchorRef,
95
+ StampBody,
96
+ StampEntry,
97
+ StampResult,
98
+ StampSubtree,
99
+ StampSubtreeResult,
100
+ StampTraceBody,
93
101
  TraceCheckpoint,
94
102
  TraceCheckpointV1,
95
103
  TraceEvent,
@@ -136,6 +144,40 @@ export type {
136
144
  PackVerdict,
137
145
  } from "./grading.js";
138
146
 
147
+ // Chain reading (src/chain.ts): following the pointer every sanning.events/v1
148
+ // record carries to the record before it, over the records ONE bundle presents.
149
+ //
150
+ // Every anchored event has carried that pointer since the profile was ratified
151
+ // and nothing we shipped read it, so a bundle with an event removed — and a
152
+ // chain that restarted after a crash and now asserts two beginnings — passed
153
+ // every check we had (proof#43). The verifier was right not to do this: it
154
+ // verifies a single envelope and says so. Nothing above it did it either.
155
+ //
156
+ // Pure — data in, data out, no I/O — so the kernel's scope boundary
157
+ // (specs/architecture.md §3) is unchanged, and the rule ships as
158
+ // `vectors/chain-reading.json` beside the pack-grading table for the same
159
+ // reason: a rule consumers must agree with needs a statement they can fetch.
160
+ //
161
+ // It returns FINDINGS, never a verdict, and it feeds no status. Chain links are
162
+ // deletion/reorder-evidence for the events present and NOT a completeness proof
163
+ // (`anchor/docs/profile-sanning.events-v1.md` §5) — drop the last N events of a
164
+ // chain and nothing dangles. `CHAIN_READING_SCOPE` is that sentence, exported so
165
+ // every surface prints the same limit rather than paraphrasing it into a claim.
166
+ // Additive — no existing export changes.
167
+ export {
168
+ ADAPTER_CHAIN_NAMESPACES,
169
+ CHAIN_READING_SCOPE,
170
+ readChains,
171
+ renderChainFinding,
172
+ } from "./chain.js";
173
+ export type {
174
+ ChainFinding,
175
+ ChainFindingKind,
176
+ ChainReading,
177
+ ChainSource,
178
+ ChainSummary,
179
+ } from "./chain.js";
180
+
139
181
  // The `proof export` composer (specs/evidence-export.md §5, phase 2): produce a
140
182
  // signed, offline-verifiable sanning.evidence.export/v1 artifact from a source
141
183
  // anchor-trace bundle + operator attestations + an exporter Ed25519 key. The
package/src/verifier.ts CHANGED
@@ -228,6 +228,20 @@ export async function verifyEnvelope(
228
228
  typeof optionsOrContentHash === "string"
229
229
  ? { expectedContentHash: optionsOrContentHash }
230
230
  : (optionsOrContentHash ?? {});
231
+ // REFUSE an unknown option key rather than ignore it. `expected_content_hash`
232
+ // — the Python kernel's spelling — previously fell through as `undefined`, so
233
+ // the content bind silently never ran and the caller got a clean pass with no
234
+ // errors at all. A check that quietly does not happen is worse than one that
235
+ // fails: the caller believes they verified an artifact they never checked.
236
+ const KNOWN_VERIFY_OPTIONS = new Set(["payloadBytes", "expectedContentHash"]);
237
+ const unknownOptions = Object.keys(opts).filter((k) => !KNOWN_VERIFY_OPTIONS.has(k));
238
+ if (unknownOptions.length > 0) {
239
+ throw new TypeError(
240
+ `verifyEnvelope: unknown option(s) ${unknownOptions.join(", ")}. ` +
241
+ `Did you mean ${[...KNOWN_VERIFY_OPTIONS].join(" / ")}? ` +
242
+ "Option keys are camelCase in the TypeScript kernel; the Python kernel uses snake_case.",
243
+ );
244
+ }
231
245
  const expectedContentHash = opts.expectedContentHash;
232
246
  const errors: string[] = [];
233
247
 
@@ -313,19 +327,47 @@ export async function verifyEnvelope(
313
327
  let contentHashOk: boolean | null = null;
314
328
  let contentRole: ContentRole | null = null;
315
329
  if (expectedContentHash !== undefined) {
316
- const want = expectedContentHash.toLowerCase();
317
- const match = contentHashes(env).find((c) => c.hash.toLowerCase() === want);
318
- contentHashOk = match !== undefined;
319
- contentRole = match ? match.role : null;
320
- if (!contentHashOk) {
321
- errors.push("provided content hash does not match any hash this envelope commits to");
330
+ const committed = contentHashes(env);
331
+ if (committed.length === 0) {
332
+ // UNDETERMINED, not failed. An external-commitment envelope
333
+ // (`sanning.events/v1`) has no inline payload, so it commits to no
334
+ // envelope-readable content hash and there is nothing here to compare
335
+ // against. Reporting that as a failure would render "we cannot check
336
+ // this" as "it did not match" — what P-10 and I-5 exist to prevent — and
337
+ // would fail every envelope on the DL-52 path.
338
+ //
339
+ // The caller is still told the check did not happen; silence would be
340
+ // worse than either verdict.
341
+ contentHashOk = null;
342
+ errors.push(
343
+ "this envelope commits to no readable content hash (external-commitment " +
344
+ "profile), so the provided content hash could not be checked — " +
345
+ "undetermined, not failed",
346
+ );
347
+ } else {
348
+ const want = expectedContentHash.toLowerCase();
349
+ const match = committed.find((c) => c.hash.toLowerCase() === want);
350
+ contentHashOk = match !== undefined;
351
+ contentRole = match ? match.role : null;
352
+ if (!contentHashOk) {
353
+ errors.push("provided content hash does not match any hash this envelope commits to");
354
+ }
322
355
  }
323
356
  }
324
357
 
325
358
  return {
326
359
  // null (binding not checkable) does not fail the verdict — Python-kernel
327
360
  // parity: ok = spec && sig && payloadHashOk is not False.
328
- ok: specVersionOk && signatureOk && payloadHashOk !== false,
361
+ // A supplied `expectedContentHash` that matches nothing this envelope
362
+ // commits to is a FAILING verdict, not a side note (proof#42). This is the
363
+ // check an external auditor runs — "does this file match what was
364
+ // anchored" — and reporting it only in `contentHashOk` meant the top-level
365
+ // verdict, the field a caller naturally reads, said pass over a file that
366
+ // does not match.
367
+ //
368
+ // Absence stays undetermined: `contentHashOk` is null when no hash was
369
+ // supplied, and null must not fail (P-10 — absence is not failure).
370
+ ok: specVersionOk && signatureOk && payloadHashOk !== false && contentHashOk !== false,
329
371
  specVersionOk,
330
372
  payloadHashOk,
331
373
  signatureOk,