@coreguard/agent-commerce 0.1.3 → 0.1.4

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/aer1.mjs CHANGED
@@ -34,14 +34,205 @@ export const AER1_PARSER_VERSION = "CG-AER1/1";
34
34
  * 0.3 as current; 0.1 and 0.2 are accepted because their committed payload
35
35
  * shape is a subset. Anything else is NOT_CHECKED with the version named.
36
36
  */
37
- export const SUPPORTED_RECEIPT_SCHEMAS = Object.freeze(["0.1", "0.2", "0.3"]);
37
+ export const SUPPORTED_RECEIPT_SCHEMAS = Object.freeze(["0.1", "0.2", "0.3", "0.4"]);
38
38
 
39
39
  const DIGEST_RE = /^sha256:[0-9a-f]{64}$/;
40
+ const BASE64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
41
+ const UUID_LOWER_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
42
+
43
+ /**
44
+ * Provenance classes AER-1 defines. A value outside this set is not a weaker
45
+ * claim, it is an unknown one, and an unknown provenance may not pass as an
46
+ * executed record. Exact match only: a trailing newline or a control character
47
+ * makes the value a different string.
48
+ */
49
+ export const KNOWN_PROVENANCE_CLASSES = Object.freeze(["EXECUTED BY ZAMBO", "LOGGED BY AGENT"]);
50
+
51
+ /**
52
+ * Canonical base64 is the only accepted encoding: padded, four-character
53
+ * groups, no whitespace, and re-encoding the decoded bytes must reproduce the
54
+ * text exactly. Unpadded and pad-bit variants decode "fine" in most runtimes,
55
+ * which is precisely why a verifier has to reject them here: the bytes it
56
+ * hashes would not be the bytes another implementation hashes.
57
+ */
58
+ const RFC3339_RE = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:[Zz]|[+-](\d{2}):(\d{2}))$/;
59
+
60
+ /**
61
+ * RFC 3339 with an honest calendar: the regex alone accepts 1900-02-29 and
62
+ * 2023-02-29, and a leap second is not a value this build can verify. Absent
63
+ * is allowed here because bare records in the corpus are valid without it,
64
+ * and the field is a claim rather than ordering (see the module boundary).
65
+ */
66
+ function isRfc3339(value, { strict = false } = {}) {
67
+ if (value === undefined) return true;
68
+ if (typeof value !== "string") return false;
69
+ const m = RFC3339_RE.exec(value);
70
+ if (!m) return false;
71
+ // Schema 0.4 makes the lexeme a claim, not just the instant: lowercase t/z
72
+ // is a different spelling and the corpus rejects it. Older drafts accepted
73
+ // both, and the corpus calls those records valid, so strictness is versioned.
74
+ if (strict && (!value.includes("T") || (!value.endsWith("Z") && !/[+-]\d{2}:\d{2}$/.test(value)))) return false;
75
+ const [year, month, day, hour, minute, second] = m.slice(1, 7).map(Number);
76
+ const offsetHour = m[7] === undefined ? 0 : Number(m[7]);
77
+ const offsetMinute = m[8] === undefined ? 0 : Number(m[8]);
78
+ if (month < 1 || month > 12) return false;
79
+ if (hour > 23 || minute > 59 || second > 59) return false;
80
+ if (offsetHour > 23 || offsetMinute > 59) return false;
81
+ const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
82
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
83
+ return day >= 1 && day <= days;
84
+ }
85
+
86
+ const nonEmptyString = (v) => typeof v === "string" && v.length > 0;
87
+
88
+ /**
89
+ * A record that claims `verification_status: "verified"` attests a specific
90
+ * tool, so the descriptor there must be an object with three non-empty
91
+ * strings. A bare legacy record (no verification claim) may carry the older
92
+ * string form or none at all — the corpus has valid records of both shapes,
93
+ * and a rule that refused the string form would be a false reject.
94
+ */
95
+ const isToolDescriptor = (tool, verificationStatus) => {
96
+ const structured = isObject(tool) && nonEmptyString(tool.name) && nonEmptyString(tool.version) && nonEmptyString(tool.scope);
97
+ if (verificationStatus === "verified") return structured;
98
+ if (tool === undefined) return true;
99
+ if (typeof tool === "string") return tool.length > 0;
100
+ return structured;
101
+ };
102
+
103
+ const isCanonicalBase64 = (s) =>
104
+ typeof s === "string" && s.length > 0 && BASE64_RE.test(s) && Buffer.from(s, "base64").toString("base64") === s;
40
105
  const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
106
+
107
+ /**
108
+ * Canonical JSON for the schema 0.4 input_hash: member names ordered by code
109
+ * point, no whitespace, string bytes left as UTF-8 (no NFC/NFD rewriting).
110
+ * The hash is over the claim as written, so a reordered key list is a different
111
+ * input set, exactly as the corpus's key-order vector requires.
112
+ */
113
+ const byCodePoint = (a, b) => {
114
+ const left = Array.from(a, (c) => c.codePointAt(0));
115
+ const right = Array.from(b, (c) => c.codePointAt(0));
116
+ for (let i = 0; i < Math.min(left.length, right.length); i += 1) {
117
+ if (left[i] !== right[i]) return left[i] - right[i];
118
+ }
119
+ return left.length - right.length;
120
+ };
121
+ function canonicalJson(value) {
122
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
123
+ if (isObject(value)) {
124
+ return `{${Object.keys(value)
125
+ .sort(byCodePoint)
126
+ .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`)
127
+ .join(",")}}`;
128
+ }
129
+ return JSON.stringify(value);
130
+ }
41
131
  const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");
42
132
 
43
133
  const check = (name, ok, detail) => (detail === undefined ? { name, ok } : { name, ok, detail });
44
134
 
135
+ /**
136
+ * findDuplicateMembers(jsonText) -> [{ path, key }]
137
+ *
138
+ * JSON.parse silently keeps the last of two same-named members, so two parsers
139
+ * can read two different commitments from identical bytes. The only place the
140
+ * duplicate is still visible is the text, which is why a caller that has the
141
+ * bytes should pass them in. This is a small scanner, not a validator: it
142
+ * walks the same grammar JSON.parse accepts and reports keys seen twice per
143
+ * object. Malformed text simply stops the walk; JSON.parse is the authority on
144
+ * whether the document is well formed.
145
+ */
146
+ export function findDuplicateMembers(jsonText) {
147
+ const duplicates = [];
148
+ const n = jsonText.length;
149
+ let i = 0;
150
+ const skipWs = () => {
151
+ while (i < n && (jsonText[i] === " " || jsonText[i] === "\t" || jsonText[i] === "\n" || jsonText[i] === "\r")) i += 1;
152
+ };
153
+ const readString = () => {
154
+ i += 1; // opening quote
155
+ while (i < n) {
156
+ if (jsonText[i] === "\\") {
157
+ i += 2;
158
+ continue;
159
+ }
160
+ if (jsonText[i] === '"') {
161
+ i += 1;
162
+ return;
163
+ }
164
+ i += 1;
165
+ }
166
+ };
167
+ const readValue = (path) => {
168
+ skipWs();
169
+ const c = jsonText[i];
170
+ if (c === "{") {
171
+ i += 1;
172
+ skipWs();
173
+ if (jsonText[i] === "}") {
174
+ i += 1;
175
+ return;
176
+ }
177
+ const seen = new Set();
178
+ for (;;) {
179
+ skipWs();
180
+ const start = i;
181
+ readString();
182
+ let key;
183
+ try {
184
+ key = JSON.parse(jsonText.slice(start, i));
185
+ } catch {
186
+ return;
187
+ }
188
+ if (seen.has(key)) duplicates.push({ path: path || "$", key });
189
+ seen.add(key);
190
+ skipWs();
191
+ if (jsonText[i] === ":") i += 1;
192
+ readValue(path ? `${path}.${key}` : key);
193
+ skipWs();
194
+ if (jsonText[i] === ",") {
195
+ i += 1;
196
+ continue;
197
+ }
198
+ if (jsonText[i] === "}") i += 1;
199
+ return;
200
+ }
201
+ }
202
+ if (c === "[") {
203
+ i += 1;
204
+ skipWs();
205
+ if (jsonText[i] === "]") {
206
+ i += 1;
207
+ return;
208
+ }
209
+ let index = 0;
210
+ for (;;) {
211
+ readValue(`${path}[${index}]`);
212
+ index += 1;
213
+ skipWs();
214
+ if (jsonText[i] === ",") {
215
+ i += 1;
216
+ continue;
217
+ }
218
+ if (jsonText[i] === "]") i += 1;
219
+ return;
220
+ }
221
+ }
222
+ if (c === '"') {
223
+ readString();
224
+ return;
225
+ }
226
+ while (i < n && !" \t\n\r,]}:".includes(jsonText[i])) i += 1;
227
+ };
228
+ try {
229
+ readValue("");
230
+ } catch {
231
+ // malformed text: nothing to report here, JSON.parse decides validity
232
+ }
233
+ return duplicates;
234
+ }
235
+
45
236
  /**
46
237
  * parseAer1Record(record, { expectedId, resolvedRecord })
47
238
  *
@@ -52,7 +243,7 @@ const check = (name, ok, detail) => (detail === undefined ? { name, ok } : { nam
52
243
  * Returns frozen facts plus one verdict. Nothing here throws on a malformed
53
244
  * artifact: a caller handing us garbage is evidence, not a program defect.
54
245
  */
55
- export function parseAer1Record(record, { expectedId, resolvedRecord } = {}) {
246
+ export function parseAer1Record(record, { expectedId, resolvedRecord, rawText } = {}) {
56
247
  if (!isObject(record)) {
57
248
  const structure = [check("artifact is an object", false)];
58
249
  return freeze({
@@ -76,9 +267,39 @@ export function parseAer1Record(record, { expectedId, resolvedRecord } = {}) {
76
267
  const claimed = typeof record.output_hash === "string" ? record.output_hash : null;
77
268
  const encoded = typeof record.canonical_bytes === "string" ? record.canonical_bytes : null;
78
269
 
270
+ // Duplicate member names must be refused before any value is trusted: the
271
+ // parsed object no longer shows them, so only the original text can.
272
+ if (typeof rawText === "string") {
273
+ const duplicates = findDuplicateMembers(rawText);
274
+ structure.push(
275
+ check("record text has no duplicate member names", duplicates.length === 0, duplicates.length === 0 ? undefined : duplicates),
276
+ );
277
+ }
278
+
79
279
  structure.push(check("id is present (outer envelope)", idPresent));
280
+ structure.push(check("id is a lowercase UUID", idPresent && UUID_LOWER_RE.test(record.id)));
281
+ structure.push(
282
+ check("id is not the nil UUID", !idPresent || record.id !== "00000000-0000-0000-0000-000000000000"),
283
+ );
284
+ structure.push(
285
+ check("created_at is RFC 3339 (when present)", isRfc3339(record.created_at, { strict: version === "0.4" })),
286
+ );
287
+ structure.push(
288
+ check(
289
+ "tool names a real descriptor when the record claims verification",
290
+ isToolDescriptor(record.tool, record.verification_status),
291
+ ),
292
+ );
293
+ structure.push(
294
+ check(
295
+ "provenance_class is a known class (when present)",
296
+ record.provenance_class === undefined ||
297
+ (typeof record.provenance_class === "string" && KNOWN_PROVENANCE_CLASSES.includes(record.provenance_class)),
298
+ ),
299
+ );
80
300
  structure.push(check("output_hash is sha256:<64 hex>", claimed !== null && DIGEST_RE.test(claimed)));
81
301
  structure.push(check("canonical_bytes is base64 text", encoded !== null && encoded.length > 0));
302
+ structure.push(check("canonical_bytes is canonical base64", isCanonicalBase64(encoded)));
82
303
 
83
304
  let computed = null;
84
305
  let byteLength = null;
@@ -97,6 +318,58 @@ export function parseAer1Record(record, { expectedId, resolvedRecord } = {}) {
97
318
  }
98
319
  structure.push(check("canonical_bytes decode to a byte string", byteLength > 0));
99
320
  structure.push(check("canonical_bytes parse to a JSON object", payloadParses));
321
+ if (payloadParses) {
322
+ const payloadDuplicates = findDuplicateMembers(bytes.toString("utf8"));
323
+ structure.push(
324
+ check(
325
+ "committed payload has no duplicate member names",
326
+ payloadDuplicates.length === 0,
327
+ payloadDuplicates.length === 0 ? undefined : payloadDuplicates,
328
+ ),
329
+ );
330
+ // A canonical execution record commits both sides of the work. Legacy
331
+ // artifacts commit neither, and the corpus calls those valid, so the
332
+ // strict rules apply only where the payload carries an execution result.
333
+ const canonicalExecution = payload.inputs !== undefined || payload.outputs !== undefined;
334
+ if (canonicalExecution) {
335
+ structure.push(check("committed payload carries an inputs object", isObject(payload.inputs)));
336
+ if (record.verification_status !== undefined) {
337
+ structure.push(
338
+ check(
339
+ "verification_status is verified when the record claims it",
340
+ record.verification_status === "verified",
341
+ record.verification_status === "verified" ? undefined : { found: record.verification_status },
342
+ ),
343
+ );
344
+ }
345
+ }
346
+ if (version === "0.4") {
347
+ // The outer input_hash binds the recorded inputs, not the whole payload.
348
+ // A reordered key list is a different claim even though JSON.parse
349
+ // produces the same object, so the hash runs over canonical text.
350
+ if (record.input_hash !== undefined) {
351
+ const expectedInputHash = isObject(payload.inputs) ? `sha256:${sha256(Buffer.from(canonicalJson(payload.inputs), "utf8"))}` : null;
352
+ structure.push(
353
+ check("input_hash binds the canonical JSON of the recorded inputs", expectedInputHash !== null && expectedInputHash === record.input_hash, {
354
+ expected: expectedInputHash,
355
+ found: record.input_hash,
356
+ }),
357
+ );
358
+ }
359
+ // Schema 0.4 commits the provenance claim twice: outside the digest and
360
+ // inside issuer_claims. One side missing, or a different class, is a
361
+ // broken binding, not a weaker provenance claim.
362
+ const committed = payload.issuer_claims;
363
+ const committedClass = isObject(committed) && typeof committed.provenance_class === "string" ? committed.provenance_class : null;
364
+ structure.push(
365
+ check(
366
+ "provenance_class matches the committed issuer_claims",
367
+ committedClass !== null && record.provenance_class === committedClass,
368
+ { outer: record.provenance_class ?? null, committed: committedClass },
369
+ ),
370
+ );
371
+ }
372
+ }
100
373
  }
101
374
 
102
375
  const byteLengthClaimed =
@@ -109,6 +382,12 @@ export function parseAer1Record(record, { expectedId, resolvedRecord } = {}) {
109
382
  }),
110
383
  );
111
384
  }
385
+ if (record.metadata_hash !== undefined) {
386
+ // The vendored corpus exercises only the format of this 0.4 member; it
387
+ // publishes no preimage rule, so this build checks the shape and says so
388
+ // rather than inventing a recomputation nobody can reproduce.
389
+ structure.push(check("metadata_hash is sha256:<64 hex>", typeof record.metadata_hash === "string" && DIGEST_RE.test(record.metadata_hash)));
390
+ }
112
391
 
113
392
  const digestOk = computed !== null && claimed !== null && `sha256:${computed}` === claimed;
114
393
  structure.push(check("output_hash matches the recomputed digest", digestOk));
@@ -233,6 +512,422 @@ function freeze(value) {
233
512
  return Object.freeze(value);
234
513
  }
235
514
 
515
+ /**
516
+ * AER-1 timelines — the part of the record that lives across receipts.
517
+ *
518
+ * Three constructions are implemented here, each pinned by the corpus:
519
+ * v1 draft Section 7 before -07: entry digest over the decoded bytes
520
+ * v07 entry digest binds prev_digest, seq, job_id, close, id, tool,
521
+ * provenance_class and the output commitment, serialized as canonical
522
+ * JSON with member names sorted by code point and strings escaped per
523
+ * RFC 8259, non-ASCII as \uXXXX
524
+ * workflow a binary Merkle tree over step leaves: receipt_id (receipt-id-v0)
525
+ * or "seq:output_hash" (seq-output-v1), last-duplicate on odd levels
526
+ *
527
+ * Boundary, standing: no clock, no network, no anchoring. A chain that verifies
528
+ * proves its own order and metadata; it does not prove the work happened.
529
+ */
530
+ export const AER1_CHAIN_VERSIONS = Object.freeze(["v1", "v07"]);
531
+ export const AER1_MERKLE_VERSIONS = Object.freeze(["receipt-id-v0", "seq-output-v1"]);
532
+
533
+ const ZERO_DIGEST = "0".repeat(64);
534
+ const LOWER_HEX_64 = /^[0-9a-f]{64}$/;
535
+ const isLowerHex64 = (value) => typeof value === "string" && LOWER_HEX_64.test(value);
536
+ const isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
537
+
538
+ /** RFC 8259 string escaping with every non-ASCII code point written as \uXXXX. */
539
+ function aer1Escape(value) {
540
+ let out = "";
541
+ for (const char of value) {
542
+ const cp = char.codePointAt(0);
543
+ if (char === '"') out += '\\"';
544
+ else if (char === "\\") out += "\\\\";
545
+ else if (cp === 0x08) out += "\\b";
546
+ else if (cp === 0x09) out += "\\t";
547
+ else if (cp === 0x0a) out += "\\n";
548
+ else if (cp === 0x0c) out += "\\f";
549
+ else if (cp === 0x0d) out += "\\r";
550
+ else if (cp < 0x20) out += `\\u${cp.toString(16).padStart(4, "0")}`;
551
+ else if (cp > 0x7e) {
552
+ if (cp > 0xffff) {
553
+ const offset = cp - 0x10000;
554
+ out += "\\u" + (0xd800 + (offset >> 10)).toString(16) + "\\u" + (0xdc00 + (offset & 0x3ff)).toString(16);
555
+ } else out += `\\u${cp.toString(16).padStart(4, "0")}`;
556
+ } else out += char;
557
+ }
558
+ return out;
559
+ }
560
+ const aer1Quoted = (value) => `"${aer1Escape(String(value))}"`;
561
+
562
+ const sha256Hex = (buffer) => createHash("sha256").update(buffer).digest("hex");
563
+
564
+ /** The v1 entry digest: SHA-256 over the base64-decoded canonical bytes. */
565
+ function entryDigestV1(entry) {
566
+ if (!isNonEmptyString(entry?.canonical_bytes)) return null;
567
+ return sha256Hex(Buffer.from(entry.canonical_bytes, "base64"));
568
+ }
569
+
570
+ /**
571
+ * The v07 entry digest: canonical JSON with exactly the eight members named in
572
+ * Section 7.1, sorted by code point, no whitespace outside strings.
573
+ */
574
+ function entryDigestV07(entry) {
575
+ if (!isNonEmptyString(entry?.canonical_bytes)) return null;
576
+ const output = sha256Hex(Buffer.from(entry.canonical_bytes, "base64"));
577
+ const members = [
578
+ ["close", entry.close === undefined ? false : entry.close],
579
+ ["id", entry.id],
580
+ ["job_id", entry.job_id],
581
+ ["output_hash", output],
582
+ ["prev_digest", entry.prev_digest],
583
+ ["provenance_class", entry.provenance_class],
584
+ ["seq", entry.seq],
585
+ ["tool", entry.tool],
586
+ ];
587
+ const body = members
588
+ .map(([key, value]) => {
589
+ const encoded =
590
+ typeof value === "number" && Number.isInteger(value)
591
+ ? String(value)
592
+ : typeof value === "boolean"
593
+ ? String(value)
594
+ : aer1Quoted(value ?? "");
595
+ return `${aer1Quoted(key)}:${encoded}`;
596
+ })
597
+ .join(",");
598
+ return sha256Hex(Buffer.from(`{${body}}`, "utf8"));
599
+ }
600
+
601
+ /**
602
+ * verifyAer1Chain(timeline, { version })
603
+ *
604
+ * Returns { version, ok, checks, code } and never throws on hostile input. The
605
+ * checks are named so a caller can report which rule refused a timeline.
606
+ */
607
+ export function verifyAer1Chain(timeline, { version = "v07" } = {}) {
608
+ const checks = [];
609
+ const add = (name, ok) => checks.push({ name, ok });
610
+ const done = (code) => ({ version, ok: checks.every((c) => c.ok), checks, code: checks.every((c) => c.ok) ? null : code });
611
+
612
+ if (!AER1_CHAIN_VERSIONS.includes(version)) return { version, ok: false, checks: [], code: "CHAIN_VERSION_UNSUPPORTED" };
613
+ add("timeline is a non-empty array", Array.isArray(timeline) && timeline.length > 0);
614
+ if (!Array.isArray(timeline) || timeline.length === 0) return done("CHAIN_EMPTY");
615
+
616
+ const first = timeline[0];
617
+ add("first entry carries the zero genesis digest", first?.prev_digest === ZERO_DIGEST);
618
+
619
+ let linksOk = true;
620
+ let metadataOk = true;
621
+ let closeOk = true;
622
+ for (let i = 0; i < timeline.length; i += 1) {
623
+ const entry = timeline[i] ?? {};
624
+ if (i > 0) {
625
+ const previous = timeline[i - 1];
626
+ const expected = version === "v07" ? entryDigestV07(previous) : entryDigestV1(previous);
627
+ if (expected === null || entry.prev_digest !== expected) linksOk = false;
628
+ }
629
+ if (entry.close !== undefined && typeof entry.close !== "boolean") closeOk = false;
630
+ if (i < timeline.length - 1 && entry.close === true) closeOk = false;
631
+ if (version === "v07") {
632
+ if (!Number.isInteger(entry.seq) || entry.seq !== i + 1) metadataOk = false;
633
+ if (!isNonEmptyString(entry.job_id) || entry.job_id !== first.job_id) metadataOk = false;
634
+ if (!isNonEmptyString(entry.id)) metadataOk = false;
635
+ if (!isNonEmptyString(entry.tool)) metadataOk = false;
636
+ if (!isNonEmptyString(entry.provenance_class)) metadataOk = false;
637
+ }
638
+ }
639
+
640
+ add("every link recomputes from the previous entry", linksOk);
641
+ if (version === "v07"){
642
+ add("seq is contiguous from 1 and the job id is constant", metadataOk);
643
+ add("each entry names an id, tool and provenance class", metadataOk);
644
+ }
645
+ add("close is boolean and true only on the last entry", closeOk);
646
+ add("the timeline ends with a closing entry", timeline[timeline.length - 1]?.close === true);
647
+
648
+ return done(!linksOk ? "CHAIN_LINK_MISMATCH" : !metadataOk ? "CHAIN_METADATA_INVALID" : "CHAIN_NOT_CLOSED");
649
+ }
650
+
651
+ /**
652
+ * verifyAer1Commitment(timeline, commitment, { entryCountLexeme })
653
+ *
654
+ * The external commitment binds a chain's job, length, final entry digest and
655
+ * publication time. `entryCountLexeme` is the raw JSON text of entry_count when
656
+ * the caller has it: `5.0` is the same number as `5` but a different claim, and
657
+ * the corpus rejects the fractional spelling.
658
+ */
659
+ export function verifyAer1Commitment(timeline, commitment, { entryCountLexeme } = {}) {
660
+ const checks = [];
661
+ const add = (name, ok) => checks.push({ name, ok });
662
+ const chain = verifyAer1Chain(timeline, { version: "v07" });
663
+ add("the timeline verifies under the v07 chain rules", chain.ok);
664
+ const isObjectCommitment = isObject(commitment);
665
+ add("commitment is an object", isObjectCommitment);
666
+
667
+ if (isObjectCommitment) {
668
+ add(
669
+ "commitment carries job_id, final_entry_digest, entry_count and published_at",
670
+ ["job_id", "final_entry_digest", "entry_count", "published_at"].every((key) => commitment[key] !== undefined),
671
+ );
672
+ const jobOk = isNonEmptyString(commitment.job_id) && Array.isArray(timeline) && timeline[0]?.job_id === commitment.job_id;
673
+ add("commitment job_id matches the timeline's job", jobOk);
674
+
675
+ const finalDigest = Array.isArray(timeline) && timeline.length > 0 ? entryDigestV07(timeline[timeline.length - 1]) : null;
676
+ add(
677
+ "final_entry_digest is lowercase hex and matches the last entry",
678
+ isLowerHex64(commitment.final_entry_digest) && finalDigest !== null && commitment.final_entry_digest === finalDigest,
679
+ );
680
+
681
+ const countOk =
682
+ Number.isInteger(commitment.entry_count) && Array.isArray(timeline) && commitment.entry_count === timeline.length;
683
+ const lexemeOk = entryCountLexeme === undefined || entryCountLexeme === null || !/[.eE]/.test(entryCountLexeme);
684
+ add("entry_count is an integer equal to the number of entries", countOk && lexemeOk);
685
+
686
+ add("published_at is an RFC 3339 timestamp", isRfc3339(commitment.published_at) && typeof commitment.published_at === "string");
687
+ }
688
+
689
+ return { ok: checks.every((c) => c.ok), checks, code: checks.every((c) => c.ok) ? null : "COMMITMENT_INVALID" };
690
+ }
691
+
692
+ /**
693
+ * verifyAer1WorkflowMerkle({ steps, merkleRoot, merkleVersion, merkleVersionPresent })
694
+ *
695
+ * Leaf construction follows the declared merkle_version; an absent member means
696
+ * receipt-id-v0. An unknown version is a refusal, never a guess: the two
697
+ * constructions give different roots for the same workflow.
698
+ */
699
+ export function verifyAer1WorkflowMerkle({ steps, merkleRoot, merkleVersion, merkleVersionPresent = true } = {}) {
700
+ const checks = [];
701
+ const add = (name, ok) => checks.push({ name, ok });
702
+ const declared = merkleVersionPresent === false || merkleVersion === undefined ? "receipt-id-v0" : merkleVersion;
703
+ add("merkle_version is one this build implements", AER1_MERKLE_VERSIONS.includes(declared));
704
+
705
+ const stepsOk =
706
+ Array.isArray(steps) &&
707
+ steps.length > 0 &&
708
+ steps.every((step, index) => isObject(step) && step.seq === index + 1 && isNonEmptyString(step.receipt_id));
709
+ add("steps are a non-empty ordered array with seq from 1", stepsOk);
710
+
711
+ if (stepsOk) {
712
+ const ids = steps.map((step) => step.receipt_id);
713
+ add("no receipt id appears twice", new Set(ids).size === ids.length);
714
+ if (declared === "seq-output-v1") {
715
+ add("every step carries an output_hash", steps.every((step) => isLowerHex64(String(step.output_hash ?? "").replace(/^sha256:/, ""))));
716
+ }
717
+ }
718
+
719
+ let computed = null;
720
+ if (stepsOk && AER1_MERKLE_VERSIONS.includes(declared)) {
721
+ const leaf = (step) =>
722
+ declared === "seq-output-v1"
723
+ ? sha256Hex(Buffer.from(`${step.seq}:${String(step.output_hash).replace(/^sha256:/, "")}`, "utf8"))
724
+ : sha256Hex(Buffer.from(step.receipt_id, "utf8"));
725
+ let level = steps.map((step) => Buffer.from(leaf(step), "hex"));
726
+ while (level.length > 1) {
727
+ if (level.length % 2 === 1) level = [...level, level[level.length - 1]];
728
+ const next = [];
729
+ for (let i = 0; i < level.length; i += 2) {
730
+ next.push(Buffer.from(sha256Hex(Buffer.concat([level[i], level[i + 1]])), "hex"));
731
+ }
732
+ level = next;
733
+ }
734
+ computed = level[0].toString("hex");
735
+ }
736
+
737
+ add(
738
+ "merkle_root is lowercase hex and matches the recomputed root",
739
+ computed !== null && isLowerHex64(merkleRoot) && computed === merkleRoot,
740
+ );
741
+
742
+ return { ok: checks.every((c) => c.ok), computed, declared, checks, code: checks.every((c) => c.ok) ? null : "WORKFLOW_MERKLE_INVALID" };
743
+ }
744
+
745
+ /**
746
+ * verifyAer1MerkleVector(vector) — corpus family `merkle`, 9 vectors / 12 kit
747
+ * checks. Section 8.1 is one construction only: leaf = SHA-256(UTF-8
748
+ * receipt_id), internal node = SHA-256(raw left || raw right), last node
749
+ * duplicated at an odd level, and an empty workflow's root is SHA-256(empty).
750
+ *
751
+ * The corpus also pins two ways to be wrong. A legacy `seq:receipt_hash`
752
+ * preimage tree produces a different root and is refused on sight, and a
753
+ * duplicate receipt_id that happens to recompute the canonical root is still
754
+ * an invalid workflow under Section 8.2. No root-only shortcut: both checks
755
+ * have to be made before a verdict is returned.
756
+ */
757
+ export function verifyAer1MerkleVector(vector) {
758
+ const checks = [];
759
+ const add = (name, ok) => checks.push({ name, ok });
760
+ const v = isObject(vector) ? vector : {};
761
+ const ids = v.receipt_ids;
762
+ add("vector carries receipt_ids, not the legacy preimage form", Array.isArray(ids) && v.leaves === undefined);
763
+ const idsOk = Array.isArray(ids) && ids.every((id) => isNonEmptyString(id));
764
+ add("every receipt_id is a non-empty string", idsOk);
765
+ add("no receipt_id appears twice", !idsOk || new Set(ids).size === ids.length);
766
+ let computed = null;
767
+ if (idsOk) {
768
+ let level = ids.map((id) => Buffer.from(sha256Hex(Buffer.from(id, "utf8")), "hex"));
769
+ if (level.length === 0) computed = sha256Hex(Buffer.alloc(0));
770
+ else {
771
+ while (level.length > 1) {
772
+ if (level.length % 2 === 1) level = [...level, level[level.length - 1]];
773
+ const next = [];
774
+ for (let i = 0; i < level.length; i += 2) {
775
+ next.push(Buffer.from(sha256Hex(Buffer.concat([level[i], level[i + 1]])), "hex"));
776
+ }
777
+ level = next;
778
+ }
779
+ computed = level[0].toString("hex");
780
+ }
781
+ }
782
+ add("expected_root is lowercase hex", isLowerHex64(v.expected_root));
783
+ add("merkle root recomputes from the receipt ids in file order", computed !== null && computed === v.expected_root);
784
+ if (v.must_not_equal !== undefined) {
785
+ add("the root is not the rejected construction's root", computed !== null && computed !== v.must_not_equal);
786
+ }
787
+ const ok = checks.every((c) => c.ok);
788
+ return { ok, computed, checks, code: ok ? null : "MERKLE_VECTOR_INVALID" };
789
+ }
790
+
791
+ /**
792
+ * verifyAer1UnicodeVector(vector) — corpus family `unicode`, 5 vectors.
793
+ * The commitment is over the payload's exact bytes. No NFC/NFD rewriting, no
794
+ * re-encoding, no "visually identical" equivalence: the two spellings of café
795
+ * hash differently and the corpus pins both directions of that difference.
796
+ */
797
+ export function verifyAer1UnicodeVector(vector) {
798
+ const checks = [];
799
+ const add = (name, ok) => checks.push({ name, ok });
800
+ const v = isObject(vector) ? vector : {};
801
+ const encoded = v.payload_base64;
802
+ add("payload_base64 is canonical base64 text", isCanonicalBase64(encoded));
803
+ let bytes = null;
804
+ let computed = null;
805
+ if (isCanonicalBase64(encoded)) {
806
+ bytes = Buffer.from(encoded, "base64");
807
+ computed = sha256Hex(bytes);
808
+ }
809
+ add("payload_utf8_hex is the exact decoded bytes", bytes !== null && typeof v.payload_utf8_hex === "string" && bytes.toString("hex") === v.payload_utf8_hex);
810
+ add("sha256 is lowercase hex", isLowerHex64(v.sha256));
811
+ add("the digest recomputes from the raw bytes without normalization", computed !== null && computed === v.sha256);
812
+ const ok = checks.every((c) => c.ok);
813
+ return { ok, computed, checks, code: ok ? null : "UNICODE_VECTOR_INVALID" };
814
+ }
815
+
816
+ /** The four members that make an anchor a Section 3.3 profile at all. */
817
+ export const AER1_ANCHOR_MEMBERS = Object.freeze(["log", "leaf_hash", "anchored_at", "proof"]);
818
+ const UUID_V4_LOWER = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
819
+
820
+ /**
821
+ * The corpus decides resolvability offline: a `.invalid` host (RFC 2606) is
822
+ * unresolvable by construction, and an `example` host is the pinned resolvable
823
+ * convention. This is a REPLAY rule, not a network lookup and not evidence that
824
+ * a real log accepted anything. A production caller must inject a resolver
825
+ * that performs real resolution and records its evidence; this default is only
826
+ * honest inside the pinned fixture set.
827
+ */
828
+ function corpusAnchorResolver({ host, receipt }) {
829
+ if (host === null) return { resolvable: false, source: "offline-corpus-convention", reason: "anchor.log has no parseable host" };
830
+ if (host.endsWith(".invalid")) return { resolvable: false, source: "offline-corpus-convention", reason: "RFC 2606 .invalid host is unresolvable by construction" };
831
+ const bytes = typeof receipt?.canonical_bytes === "string" && isCanonicalBase64(receipt.canonical_bytes) ? Buffer.from(receipt.canonical_bytes, "base64") : null;
832
+ return {
833
+ resolvable: true,
834
+ source: "offline-corpus-convention",
835
+ reason: "pinned replay convention; no network call made",
836
+ leaf: { id: receipt?.id ?? null, digest: bytes === null ? null : `sha256:${sha256Hex(bytes)}` },
837
+ };
838
+ }
839
+
840
+ /**
841
+ * reportAer1Anchor(receipt, { evaluate, resolveLog })
842
+ *
843
+ * Produces the five-value AER-1 anchor report the corpus pins:
844
+ * absent | not checked | verified | verification failed |
845
+ * rejected: unresolvable record
846
+ *
847
+ * Two separations are load-bearing:
848
+ * - `evaluate: false` is honoured BEFORE content is read. A record that was
849
+ * never checked cannot be convicted by a bad leaf it happens to carry.
850
+ * - an unresolvable log is a RESOURCE outcome and wins over content checks.
851
+ * The corpus pins a vector with both a .invalid host and a wrong leaf; its
852
+ * outcome is unresolvable, not verification failed.
853
+ *
854
+ * A `verified` outcome means the pinned resolution fact was supplied and the
855
+ * receipt's own anchor claims agree with its committed bytes. It does not mean
856
+ * this module contacted a log, and it is not physical-world truth.
857
+ */
858
+ export function reportAer1Anchor(receipt, { evaluate = true, resolveLog = corpusAnchorResolver } = {}) {
859
+ const anchor = isObject(receipt) && isObject(receipt.anchor) ? receipt.anchor : null;
860
+ const present = anchor !== null && Object.keys(anchor).some((key) => AER1_ANCHOR_MEMBERS.includes(key));
861
+ if (!evaluate) {
862
+ return {
863
+ present,
864
+ evaluated: false,
865
+ outcome: "not checked",
866
+ checks: [{ name: "evaluation was not requested", ok: true }],
867
+ reason: "evaluate=false; no anchor content was read",
868
+ };
869
+ }
870
+ if (!present) {
871
+ return {
872
+ present: false,
873
+ evaluated: false,
874
+ outcome: "absent",
875
+ checks: [{ name: "no Section 3.3 anchor member is present", ok: true }],
876
+ reason: "no log / leaf_hash / anchored_at / proof member on the record",
877
+ };
878
+ }
879
+
880
+ const checks = [];
881
+ const add = (name, ok, detail) => checks.push(detail === undefined ? { name, ok } : { name, ok, ...detail });
882
+ add(
883
+ "anchor carries exactly the Section 3.3 profile",
884
+ AER1_ANCHOR_MEMBERS.every((key) => Object.prototype.hasOwnProperty.call(anchor, key)),
885
+ { presentMembers: Object.keys(anchor).filter((key) => AER1_ANCHOR_MEMBERS.includes(key)) },
886
+ );
887
+
888
+ let host = null;
889
+ if (typeof anchor.log === "string") {
890
+ try {
891
+ host = new URL(anchor.log).hostname.toLowerCase();
892
+ } catch {
893
+ host = null;
894
+ }
895
+ }
896
+ let resolution = null;
897
+ try {
898
+ resolution = resolveLog({ log: anchor.log ?? null, host, receipt });
899
+ } catch (error) {
900
+ resolution = { resolvable: false, source: "resolver-error", reason: error instanceof Error ? error.message : String(error) };
901
+ }
902
+ const resolvable = isObject(resolution) && resolution.resolvable === true;
903
+ // No log member is a profile-shape failure, not a resource outcome. A
904
+ // missing URL cannot be "unresolvable" — there is nothing to resolve, and
905
+ // the corpus pins that case as verification failed.
906
+ if (typeof anchor.log === "string") {
907
+ add("anchor log resolution is available", resolvable, { host, source: resolution?.source ?? null, reason: resolution?.reason ?? null });
908
+ const leaf = isObject(resolution) && isObject(resolution.leaf) ? resolution.leaf : null;
909
+ add("the resolved leaf names the anchored receipt id", leaf !== null && leaf.id === receipt?.id, { expected: receipt?.id ?? null, found: leaf?.id ?? null });
910
+ add("the resolved leaf digest equals the committed leaf_hash", leaf !== null && leaf.digest === anchor.leaf_hash, { expected: anchor.leaf_hash ?? null, found: leaf?.digest ?? null });
911
+ }
912
+
913
+ add("anchored receipt id is a lowercase UUID v4", typeof receipt?.id === "string" && UUID_V4_LOWER.test(receipt.id));
914
+ let recomputed = null;
915
+ if (typeof receipt?.canonical_bytes === "string" && isCanonicalBase64(receipt.canonical_bytes)) {
916
+ recomputed = `sha256:${sha256Hex(Buffer.from(receipt.canonical_bytes, "base64"))}`;
917
+ }
918
+ add("leaf_hash equals the digest of canonical_bytes", recomputed !== null && anchor.leaf_hash === recomputed, { computed: recomputed, found: anchor.leaf_hash ?? null });
919
+ add("leaf_hash equals the receipt output_hash", typeof anchor.leaf_hash === "string" && anchor.leaf_hash === receipt?.output_hash, { claimed: receipt?.output_hash ?? null, found: anchor.leaf_hash ?? null });
920
+ add("anchored_at is a calendar-valid RFC 3339 instant", typeof anchor.anchored_at === "string" && isRfc3339(anchor.anchored_at, { strict: true }));
921
+ add("proof is present and non-empty", isObject(anchor.proof) && Object.keys(anchor.proof).length > 0);
922
+
923
+ const failed = checks.filter((c) => !c.ok).map((c) => c.name);
924
+ if (typeof anchor.log === "string" && !resolvable) {
925
+ return { present: true, evaluated: true, outcome: "rejected: unresolvable record", checks, reason: "anchor log could not be resolved; resource outcome takes precedence over content" };
926
+ }
927
+ if (failed.length > 0) return { present: true, evaluated: true, outcome: "verification failed", checks, reason: failed.join("; ") };
928
+ return { present: true, evaluated: true, outcome: "verified", checks, reason: null };
929
+ }
930
+
236
931
  /** Self-check: the parser's own invariants, for callers that cannot run tests. */
237
932
  export function selfCheck() {
238
933
  const bytes = Buffer.from(JSON.stringify({ receipt_schema_version: "0.3", output: { text: "ok" } }), "utf8");
@@ -253,6 +948,7 @@ export function selfCheck() {
253
948
  { name: "the same id binds as matched", pass: matched.id.verdict === "matched" },
254
949
  { name: "a swapped id is mismatched", pass: swapped.id.verdict === "mismatched" },
255
950
  { name: "an unimplemented version is not checked", pass: future.supportedVersion === false },
951
+ { name: "a duplicate member name is refused", pass: findDuplicateMembers('{"a":1,"a":2}').length === 1 },
256
952
  ];
257
953
  return Object.freeze({ ok: checks.every((c) => c.pass), checks });
258
954
  }