@charter-agreement-protocol/verifier 0.1.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/dist/core.js ADDED
@@ -0,0 +1,1296 @@
1
+ import { createHash, createPublicKey, verify as verifySignature } from "node:crypto";
2
+ import { lstatSync, readFileSync, readdirSync } from "node:fs";
3
+ import { join, relative, sep } from "node:path";
4
+ const INDEX_FORMAT = "charter-agreement-protocol-conformance-corpus-index";
5
+ const CASE_FORMAT = "charter-agreement-protocol-conformance-cases";
6
+ const REPORT_FORMAT = "charter-agreement-protocol-conformance-report";
7
+ const MAXIMUM_CORPUS_FILES = 64;
8
+ const MAXIMUM_CORPUS_BYTES = 33_554_432;
9
+ export const CERTIFIED_INDEX_SHA256_BASE64URL = "SQYrs8WyUX4Bj_QlupjB_KYaMyjVjrnwvQ79sNkyIao";
10
+ export const CERTIFIED_REGISTRY_DIGEST = "sha-256:u754joyHGcLCTm1LYV2s6eHauUUdDfJDwwyhbAbxvzc";
11
+ // The fourth certified identity — the specification digest over the spec
12
+ // set — is pinned in priv/release-metadata.json and enforced by the
13
+ // release-candidate gate; corpus verification does not consume it.
14
+ // The closed algorithm registry (docs/adr/algorithm-name-agility.md) — the
15
+ // TypeScript mirror of CharterAgreementProtocol.Algorithm: one row per
16
+ // accepted alg name, the minimum protocol_revision it is legal at, and the
17
+ // key algorithm it verifies with. RFC 9864's fully-specified Ed25519 names
18
+ // exactly the EdDSA-with-Ed25519-key operation, so both rows verify Ed25519.
19
+ const ALG_ROWS = [
20
+ { name: "EdDSA", minProtocolRevision: 1, keyAlgorithm: "Ed25519", publicKeyBytes: 32, signatureBytes: 64 },
21
+ { name: "Ed25519", minProtocolRevision: 2, keyAlgorithm: "Ed25519", publicKeyBytes: 32, signatureBytes: 64 },
22
+ { name: "ML-DSA-44", minProtocolRevision: 3, keyAlgorithm: "ML-DSA-44", publicKeyBytes: 1312, signatureBytes: 2420 },
23
+ { name: "ML-DSA-65", minProtocolRevision: 3, keyAlgorithm: "ML-DSA-65", publicKeyBytes: 1952, signatureBytes: 3309 },
24
+ { name: "ML-DSA-87", minProtocolRevision: 3, keyAlgorithm: "ML-DSA-87", publicKeyBytes: 2592, signatureBytes: 4627 },
25
+ ];
26
+ const ACCEPTED_PROTOCOL_REVISIONS = [1, 2, 3];
27
+ // The per-artifact binding rule: EdDSA at any accepted revision, Ed25519
28
+ // from revision 2, unknown revisions fail closed. Views mix revisions
29
+ // freely; the rule binds within one artifact.
30
+ function algBinds(alg, protocolRevision) {
31
+ const row = ALG_ROWS.find((one) => one.name === alg);
32
+ return row !== undefined && ACCEPTED_PROTOCOL_REVISIONS.includes(protocolRevision) && protocolRevision >= row.minProtocolRevision;
33
+ }
34
+ const SEPARATORS = {
35
+ party_descriptor_content: "charter-agreement-protocol/party-descriptor-content",
36
+ charter_revision_content: "charter-agreement-protocol/charter-revision-content",
37
+ acceptance_content: "charter-agreement-protocol/acceptance-content",
38
+ termination_content: "charter-agreement-protocol/termination-content",
39
+ receipt_content: "charter-agreement-protocol/receipt-content",
40
+ legal_text: "charter-agreement-protocol/legal-text",
41
+ signature: "charter-agreement-protocol/signature",
42
+ extension_schema: "charter-agreement-protocol/extension-schema",
43
+ extension_registry: "charter-agreement-protocol/extension-registry",
44
+ conformance_report: "charter-agreement-protocol/conformance-report",
45
+ corpus_index: "charter-agreement-protocol/corpus-index",
46
+ };
47
+ const SURFACES = [
48
+ "base64url.decode", "json.decode", "canonicalization.encode", "digest.hash",
49
+ "schema.validate", "party_descriptor.verify", "descriptor_chain.verify",
50
+ "charter_revision.decode", "acceptance.verify", "acceptance.equivocation",
51
+ "termination.verify", "chain.verify", "governing_revision", "receipt.verify",
52
+ ];
53
+ const CLASSES = [
54
+ "valid", "boundary_near", "exact_bound", "maximum_plus_one", "invalid_encoding",
55
+ "invalid_type", "invalid_constraint", "invalid_cardinality", "unknown_member",
56
+ "missing_required", "non_canonical_bytes", "digest_mismatch", "signature_invalid",
57
+ "chain_invalid", "descriptor_superseded", "descriptor_fork", "equivocation",
58
+ "chain_fork", "supersession", "precedence_selection", "outcome_indeterminate",
59
+ "extension_unknown_critical", "extension_optional_roundtrip", "extension_invalid",
60
+ ];
61
+ const REQUIRED = {
62
+ "base64url.decode": ["valid", "exact_bound", "invalid_encoding"],
63
+ "json.decode": ["valid", "boundary_near", "exact_bound", "maximum_plus_one", "invalid_encoding", "invalid_type"],
64
+ "canonicalization.encode": ["valid", "invalid_encoding", "invalid_type", "non_canonical_bytes"],
65
+ "digest.hash": ["valid", "invalid_type", "digest_mismatch"],
66
+ "schema.validate": ["valid", "invalid_type", "invalid_constraint", "invalid_cardinality", "unknown_member", "missing_required", "maximum_plus_one"],
67
+ "party_descriptor.verify": ["valid", "signature_invalid", "invalid_encoding", "unknown_member", "invalid_constraint"],
68
+ "descriptor_chain.verify": ["signature_invalid", "chain_invalid", "descriptor_superseded", "descriptor_fork"],
69
+ "charter_revision.decode": ["valid", "invalid_type", "invalid_constraint", "invalid_cardinality", "unknown_member", "missing_required", "extension_unknown_critical", "extension_invalid"],
70
+ "acceptance.verify": ["valid", "invalid_constraint", "signature_invalid"],
71
+ "acceptance.equivocation": ["equivocation", "invalid_constraint"],
72
+ "termination.verify": ["valid", "invalid_constraint", "signature_invalid"],
73
+ "chain.verify": ["valid", "chain_fork", "supersession", "chain_invalid"],
74
+ "governing_revision": ["precedence_selection"],
75
+ "receipt.verify": ["valid", "invalid_constraint", "signature_invalid", "chain_fork", "outcome_indeterminate", "extension_optional_roundtrip", "invalid_encoding", "extension_invalid"],
76
+ };
77
+ const ok = (value) => ({ ok: true, value });
78
+ const fail = (code) => ({ ok: false, code });
79
+ const valid = (output) => ({ status: "valid", output });
80
+ const invalid = (code) => ({ status: "invalid", error_code: code });
81
+ const project = (result, projector) => result.ok ? valid(projector(result.value)) : invalid(result.code);
82
+ export function canonical(value) {
83
+ if (value instanceof Number)
84
+ return JSON.stringify(value.valueOf());
85
+ if (value === null || typeof value === "boolean" || typeof value === "string")
86
+ return JSON.stringify(value);
87
+ if (typeof value === "number" && Number.isFinite(value))
88
+ return JSON.stringify(value);
89
+ if (Array.isArray(value))
90
+ return `[${value.map(canonical).join(",")}]`;
91
+ if (value && typeof value === "object") {
92
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
93
+ }
94
+ throw new Error("unsupported JSON value");
95
+ }
96
+ function rawHash(bytes) {
97
+ return createHash("sha256").update(bytes).digest("base64url");
98
+ }
99
+ function taggedHash(domain, bytes) {
100
+ const preimage = Buffer.concat([Buffer.from(SEPARATORS[domain]), Buffer.from([0]), Buffer.from(bytes)]);
101
+ return `sha-256:${rawHash(preimage)}`;
102
+ }
103
+ function exactKeys(object, keys) {
104
+ if (!object || typeof object !== "object" || Array.isArray(object))
105
+ return false;
106
+ return canonical(Object.keys(object).sort()) === canonical([...keys].sort());
107
+ }
108
+ function walk(root, directory = root) {
109
+ return readdirSync(directory).flatMap((name) => {
110
+ const path = join(directory, name);
111
+ const stat = lstatSync(path);
112
+ if (stat.isDirectory())
113
+ return walk(root, path);
114
+ if (!stat.isFile())
115
+ throw new Error("non-regular corpus entry");
116
+ return [{ path: relative(root, path).split(sep).join("/"), size: stat.size }];
117
+ });
118
+ }
119
+ function strictBase64url(text) {
120
+ if (typeof text !== "string")
121
+ return fail("invalid_type");
122
+ if (text.includes("="))
123
+ return fail("base64url_padded");
124
+ if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1)
125
+ return fail("base64url_invalid");
126
+ const bytes = Buffer.from(text, "base64url");
127
+ return bytes.toString("base64url") === text ? ok(bytes) : fail("base64url_invalid");
128
+ }
129
+ // The I-JSON decoder mirror: duplicate member names, trailing
130
+ // non-whitespace, integer literals beyond the ECMAScript safe range, and
131
+ // numbers that cannot round-trip a double are rejected with the decoder's
132
+ // closed codes, in the decoder's own order.
133
+ const MAXIMUM_SAFE_INTEGER = 9007199254740991n;
134
+ const NUMBER_TOKEN = /(?:-?(?:0|[1-9][0-9]*))(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
135
+ function readJsonValue(text, index) {
136
+ index = skipWhitespace(text, index);
137
+ const char = text[index];
138
+ if (char === undefined)
139
+ return { status: "need-character" };
140
+ if (char === "{") {
141
+ const members = new Map();
142
+ let cursor = skipWhitespace(text, index + 1);
143
+ if (text[cursor] === "}")
144
+ return { status: "ok", value: {}, index: cursor + 1 };
145
+ for (;;) {
146
+ if (text[cursor] !== '"')
147
+ return { status: "syntax" };
148
+ const key = readJsonString(text, cursor);
149
+ if (key.status !== "ok")
150
+ return key;
151
+ cursor = skipWhitespace(text, key.index);
152
+ if (text[cursor] !== ":")
153
+ return { status: "syntax" };
154
+ const item = readJsonValue(text, skipWhitespace(text, cursor + 1));
155
+ if (item.status !== "ok")
156
+ return item;
157
+ const duplicate = members.has(key.value);
158
+ members.set(key.value, item.value);
159
+ cursor = skipWhitespace(text, item.index);
160
+ if (text[cursor] === ",") {
161
+ cursor = skipWhitespace(text, cursor + 1);
162
+ continue;
163
+ }
164
+ if (text[cursor] === "}") {
165
+ if (duplicate)
166
+ return { status: "error", code: "duplicate_member" };
167
+ return { status: "ok", value: Object.fromEntries(members), index: cursor + 1 };
168
+ }
169
+ return { status: "syntax" };
170
+ }
171
+ }
172
+ if (char === "[") {
173
+ const items = [];
174
+ let cursor = skipWhitespace(text, index + 1);
175
+ if (text[cursor] === "]")
176
+ return { status: "ok", value: items, index: cursor + 1 };
177
+ for (;;) {
178
+ const item = readJsonValue(text, cursor);
179
+ if (item.status !== "ok")
180
+ return item;
181
+ items.push(item.value);
182
+ cursor = skipWhitespace(text, item.index);
183
+ if (text[cursor] === ",") {
184
+ cursor = skipWhitespace(text, cursor + 1);
185
+ continue;
186
+ }
187
+ if (text[cursor] === "]")
188
+ return { status: "ok", value: items, index: cursor + 1 };
189
+ return { status: "syntax" };
190
+ }
191
+ }
192
+ if (char === '"') {
193
+ const string = readJsonString(text, index);
194
+ return string.status === "ok" ? { status: "ok", value: string.value, index: string.index } : string;
195
+ }
196
+ for (const [literal, value] of [["true", true], ["false", false], ["null", null]]) {
197
+ if (text.startsWith(literal, index))
198
+ return { status: "ok", value, index: index + literal.length };
199
+ }
200
+ NUMBER_TOKEN.lastIndex = index;
201
+ const token = NUMBER_TOKEN.exec(text);
202
+ if (token) {
203
+ const literal = token[0];
204
+ if (/^-?[0-9]+$/.test(literal)) {
205
+ const magnitude = BigInt(literal);
206
+ if ((magnitude > MAXIMUM_SAFE_INTEGER || magnitude < -MAXIMUM_SAFE_INTEGER) &&
207
+ magnitude !== BigInt(Number(literal))) {
208
+ return { status: "error", code: "number_not_double_expressible" };
209
+ }
210
+ }
211
+ else if (!Number.isFinite(Number(literal))) {
212
+ return { status: "error", code: "invalid_number" };
213
+ }
214
+ // Float-ness follows the lexeme (fraction or exponent), never the value:
215
+ // "0.0" and "2e0" are floats even though their double is integral, so the
216
+ // tagged projection matches the reference decoder instead of collapsing.
217
+ const boxed = /[.eE]/.test(literal) ? new Number(Number(literal)) : Number(literal);
218
+ return { status: "ok", value: boxed, index: NUMBER_TOKEN.lastIndex };
219
+ }
220
+ return { status: "syntax" };
221
+ }
222
+ function readJsonString(text, index) {
223
+ if (text[index] !== '"')
224
+ return { status: "syntax" };
225
+ let end = index + 1;
226
+ while (end < text.length) {
227
+ if (text[end] === "\\") {
228
+ end += 2;
229
+ continue;
230
+ }
231
+ if (text[end] === '"')
232
+ break;
233
+ end += 1;
234
+ }
235
+ if (text[end] !== '"')
236
+ return { status: "syntax" };
237
+ try {
238
+ const value = JSON.parse(text.slice(index, end + 1));
239
+ if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(value)) {
240
+ return { status: "syntax" };
241
+ }
242
+ for (const codepoint of value) {
243
+ const unit = codepoint.codePointAt(0);
244
+ if ((unit >= 0xfdd0 && unit <= 0xfdef) || (unit & 0xfffe) === 0xfffe) {
245
+ return { status: "error", code: "invalid_encoding" };
246
+ }
247
+ }
248
+ return { status: "ok", value, index: end + 1 };
249
+ }
250
+ catch (_error) {
251
+ return { status: "syntax" };
252
+ }
253
+ }
254
+ const JSON_WHITESPACE = /[ \t\n\r]/;
255
+ function skipWhitespace(text, index) {
256
+ while (JSON_WHITESPACE.test(text[index]))
257
+ index += 1;
258
+ return index;
259
+ }
260
+ export function decodeJsonText(text) {
261
+ const value = readJsonValue(text, 0);
262
+ if (value.status === "need-character" || value.status === "syntax")
263
+ return fail("invalid_syntax");
264
+ if (value.status === "error")
265
+ return fail(value.code);
266
+ if (value.index === undefined || skipWhitespace(text, value.index) !== text.length)
267
+ return fail("trailing_bytes");
268
+ return ok(value.value);
269
+ }
270
+ function decodeJsonBytes(bytes) {
271
+ try {
272
+ return decodeJsonText(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
273
+ }
274
+ catch (_error) {
275
+ return fail("invalid_encoding");
276
+ }
277
+ }
278
+ const JSON_DEFAULT_LIMITS = {
279
+ max_bytes: 1_048_576,
280
+ max_depth: 64,
281
+ max_object_members: 1_024,
282
+ max_array_items: 4_096,
283
+ max_string_bytes: 65_536,
284
+ max_artifact_set_items: 1_024,
285
+ max_artifact_set_bytes: 67_108_864,
286
+ };
287
+ // The compiled maximums mirror lib/charter_agreement_protocol/limits.ex: the
288
+ // greatest caller-selectable value per field, not the defaults.
289
+ const LIMIT_MAXIMUMS = {
290
+ max_bytes: 16_777_216,
291
+ max_depth: 128,
292
+ max_object_members: 65_536,
293
+ max_array_items: 65_536,
294
+ max_string_bytes: 1_048_576,
295
+ max_artifact_set_items: 4_096,
296
+ max_artifact_set_bytes: 1_073_741_824,
297
+ };
298
+ function validLimits(selected) {
299
+ if (typeof selected !== "object" || selected === null)
300
+ return false;
301
+ const maximums = LIMIT_MAXIMUMS;
302
+ return Object.entries(selected).every(([name, value]) => name in maximums && Number.isInteger(value) && value >= 0 && value <= maximums[name]);
303
+ }
304
+ function jsonWithinLimits(value, bytes, selected = {}) {
305
+ const limits = { ...JSON_DEFAULT_LIMITS, ...selected };
306
+ if (bytes.length > limits.max_bytes)
307
+ return fail("limit_exceeded");
308
+ function visit(item, depth) {
309
+ if (typeof item === "string") {
310
+ if (Buffer.byteLength(item) > limits.max_string_bytes)
311
+ throw new Error("limit");
312
+ return;
313
+ }
314
+ if (Array.isArray(item)) {
315
+ if (depth + 1 > limits.max_depth || item.length > limits.max_array_items)
316
+ throw new Error("limit");
317
+ item.forEach((child) => visit(child, depth + 1));
318
+ return;
319
+ }
320
+ if (item && typeof item === "object") {
321
+ const entries = Object.entries(item);
322
+ if (depth + 1 > limits.max_depth || entries.length > limits.max_object_members)
323
+ throw new Error("limit");
324
+ entries.forEach(([key, child]) => {
325
+ if (Buffer.byteLength(key) > limits.max_string_bytes)
326
+ throw new Error("limit");
327
+ visit(child, depth + 1);
328
+ });
329
+ }
330
+ }
331
+ try {
332
+ visit(value, 0);
333
+ return ok(value);
334
+ }
335
+ catch (_limit) {
336
+ return fail("limit_exceeded");
337
+ }
338
+ }
339
+ export function jsonProjection(value) {
340
+ if (value === null)
341
+ return { tag: "null" };
342
+ if (value instanceof Number)
343
+ return { tag: "float", value: value.valueOf() };
344
+ if (Number.isInteger(value))
345
+ return { tag: "integer", value };
346
+ if (Array.isArray(value))
347
+ return { tag: "array", items: value.map(jsonProjection) };
348
+ if (value && typeof value === "object")
349
+ return { tag: "object", members: Object.entries(value).map(([key, item]) => [key, jsonProjection(item)]) };
350
+ if (typeof value === "string")
351
+ return { tag: "string", value };
352
+ if (typeof value === "boolean")
353
+ return { tag: "boolean", value };
354
+ return { tag: "float", value };
355
+ }
356
+ const PROTECTED_MEMBERS = ["alg", "kid", "typ"];
357
+ function decodeJws(compact) {
358
+ if (typeof compact !== "string")
359
+ return fail("compact_invalid");
360
+ if (Buffer.byteLength(compact) > JSON_DEFAULT_LIMITS.max_bytes)
361
+ return fail("limit_exceeded");
362
+ const segments = compact.split(".");
363
+ if (segments.length !== 3)
364
+ return fail("compact_invalid");
365
+ const decoded = segments.map(strictBase64url);
366
+ if (decoded.some((one) => !one.ok))
367
+ return fail("compact_invalid");
368
+ const headerBytes = decoded[0].value;
369
+ const payloadBytes = decoded[1].value;
370
+ // Strict I-JSON decode under the default ceilings — the reference verifier
371
+ // never hands raw JSON.parse bytes; every header/payload failure maps to the
372
+ // framing-layer code the reference decoder emits for that segment.
373
+ const headerValue = decodeJsonBytes(headerBytes);
374
+ if (!headerValue.ok)
375
+ return fail("protected_header_invalid");
376
+ const payloadValue = decodeJsonBytes(payloadBytes);
377
+ if (!payloadValue.ok)
378
+ return fail("non_canonical_bytes");
379
+ const header = headerValue.value;
380
+ const payload = payloadValue.value;
381
+ const headerKeys = Object.keys(header);
382
+ if (headerKeys.length !== 3 || PROTECTED_MEMBERS.some((member) => !headerKeys.includes(member))) {
383
+ return fail("protected_header_invalid");
384
+ }
385
+ if (canonical(header) !== headerBytes.toString() || canonical(payload) !== payloadBytes.toString())
386
+ return fail("non_canonical_bytes");
387
+ const revision = payload.protocol_revision;
388
+ if (typeof revision !== "number" || !Number.isInteger(revision) || !algBinds(header.alg, revision))
389
+ return fail("protected_header_invalid");
390
+ // Per-row signature length: checked only after the header names the
391
+ // algorithm (64 for the classical rows, 2420/3309/4627 for ML-DSA).
392
+ const row = ALG_ROWS.find((one) => one.name === header.alg);
393
+ const signature = decoded[2].value;
394
+ if (!row || signature.length !== row.signatureBytes)
395
+ return fail("signature_invalid");
396
+ return ok({ header, payload, payloadBytes, signature, signingInput: Buffer.from(`${segments[0]}.${segments[1]}`) });
397
+ }
398
+ const ED25519_FIELD_PRIME = 2n ** 255n - 19n;
399
+ const ED25519_SUBGROUP_ORDER = 2n ** 252n + 27742317777372353535851937790883648493n;
400
+ const ED25519_SMALL_ORDER_POINTS = [
401
+ "0100000000000000000000000000000000000000000000000000000000000000",
402
+ "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
403
+ "0000000000000000000000000000000000000000000000000000000000000080",
404
+ "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
405
+ "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
406
+ "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
407
+ "0000000000000000000000000000000000000000000000000000000000000000",
408
+ "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",
409
+ ].map((hex) => Buffer.from(hex, "hex"));
410
+ function decodeLittleEndian(buffer) {
411
+ let value = 0n;
412
+ for (let index = buffer.length - 1; index >= 0; index -= 1)
413
+ value = (value << 8n) | BigInt(buffer[index]);
414
+ return value;
415
+ }
416
+ // Strict point check mirroring Signature.strict_point?/1: the y coordinate is
417
+ // canonical, the negative-zero spelling is rejected, and the complete
418
+ // eight-point torsion set is refused before OpenSSL sees the key or R.
419
+ function strictEd25519Point(point) {
420
+ if (point.length !== 32)
421
+ return false;
422
+ if (ED25519_SMALL_ORDER_POINTS.some((one) => one.equals(point)))
423
+ return false;
424
+ const prefix = point.subarray(0, 31);
425
+ const last = point[31];
426
+ const y = decodeLittleEndian(Buffer.concat([prefix, Buffer.from([last & 0x7f])]));
427
+ const negativeZero = (last & 0x80) !== 0 && (y === 1n || y === ED25519_FIELD_PRIME - 1n);
428
+ return y < ED25519_FIELD_PRIME && !negativeZero;
429
+ }
430
+ function ed25519(rawKey, message, signature) {
431
+ try {
432
+ const key = Buffer.from(rawKey, "base64url");
433
+ if (signature.length !== 64 || key.length !== 32)
434
+ return false;
435
+ if (!strictEd25519Point(key))
436
+ return false;
437
+ const r = signature.subarray(0, 32);
438
+ const s = signature.subarray(32);
439
+ if (!strictEd25519Point(r))
440
+ return false;
441
+ if (decodeLittleEndian(s) >= ED25519_SUBGROUP_ORDER)
442
+ return false;
443
+ const prefix = Buffer.from("302a300506032b6570032100", "hex");
444
+ const spki = createPublicKey({ key: Buffer.concat([prefix, key]), format: "der", type: "spki" });
445
+ return verifySignature(null, message, spki, signature);
446
+ }
447
+ catch (_error) {
448
+ return false;
449
+ }
450
+ }
451
+ const ML_DSA_SPKI_PREFIXES = {
452
+ "ML-DSA-44": Buffer.from("30820532300b06096086480165030403110382052100", "hex"),
453
+ "ML-DSA-65": Buffer.from("308207b2300b0609608648016503040312038207a100", "hex"),
454
+ "ML-DSA-87": Buffer.from("30820a32300b060960864801650304031303820a2100", "hex"),
455
+ };
456
+ function mldsa(keyAlgorithm, rawKey, message, signature) {
457
+ try {
458
+ const key = Buffer.from(rawKey, "base64url");
459
+ const prefixes = ML_DSA_SPKI_PREFIXES;
460
+ const prefix = prefixes[keyAlgorithm];
461
+ if (!prefix || !signature || signature.length === 0)
462
+ return false;
463
+ const spki = createPublicKey({ key: Buffer.concat([prefix, key]), format: "der", type: "spki" });
464
+ return verifySignature(null, message, spki, signature);
465
+ }
466
+ catch (_error) {
467
+ return false;
468
+ }
469
+ }
470
+ // Key resolution follows the registry: the kid-resolved active key's
471
+ // algorithm must equal the envelope row's keyAlgorithm, and its decoded
472
+ // byte length must equal the row's exact value.
473
+ function keyMatchesRow(key, row) {
474
+ if (!key || key.algorithm !== row.keyAlgorithm || key.status !== "active")
475
+ return false;
476
+ const bytes = Buffer.from(key.public_key, "base64url");
477
+ return bytes.length === row.publicKeyBytes && bytes.toString("base64url") === key.public_key;
478
+ }
479
+ function verifyDecodedJws(decoded, typ, keys) {
480
+ const row = ALG_ROWS.find((one) => one.name === decoded.header.alg);
481
+ if (!row || decoded.header.typ !== typ || typeof decoded.header.kid !== "string")
482
+ return false;
483
+ const key = keys.find((one) => one.key_id === decoded.header.kid && keyMatchesRow(one, row));
484
+ if (!key)
485
+ return false;
486
+ return row.keyAlgorithm === "Ed25519" ?
487
+ ed25519(key.public_key, decoded.signingInput, decoded.signature) :
488
+ mldsa(row.keyAlgorithm, key.public_key, decoded.signingInput, decoded.signature);
489
+ }
490
+ const TIMESTAMP_GRAMMAR = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?Z$/;
491
+ // Exact RFC 3339 UTC parse mirroring Timestamp.ex: real calendar date, hour
492
+ // 0..23, minute 0..59, second 0..59 with :60 reserved for 23:59 on June 30 and
493
+ // December 31, fractions kept as trimmed decimal strings. The tick coordinate
494
+ // preserves the leap-second slot; fraction comparison pads to equal width, so
495
+ // sub-millisecond precision never truncates the way Date.parse does.
496
+ function parseTimestamp(value) {
497
+ if (typeof value !== "string")
498
+ return null;
499
+ const match = TIMESTAMP_GRAMMAR.exec(value);
500
+ if (!match)
501
+ return null;
502
+ const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
503
+ if (year < 1)
504
+ return null;
505
+ const utc = Date.UTC(year, month - 1, day);
506
+ const date = new Date(utc);
507
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day)
508
+ return null;
509
+ if (hour > 23 || minute > 59 || second > 60)
510
+ return null;
511
+ if (second === 60 && !(hour === 23 && minute === 59 && ((month === 6 && day === 30) || (month === 12 && day === 31))))
512
+ return null;
513
+ const days = Math.floor(utc / 86400000);
514
+ const base = days * 86400 + hour * 3600 + minute * 60 + Math.min(second, 59);
515
+ return { ticks: base * 2 + (second === 60 ? 1 : 0), fraction: (match[7] || "").replace(/0+$/, "") };
516
+ }
517
+ function compareTimestamps(left, right) {
518
+ if (left.ticks !== right.ticks)
519
+ return left.ticks < right.ticks ? -1 : 1;
520
+ const width = Math.max(left.fraction.length, right.fraction.length);
521
+ const paddedLeft = left.fraction.padEnd(width, "0");
522
+ const paddedRight = right.fraction.padEnd(width, "0");
523
+ if (paddedLeft === paddedRight)
524
+ return 0;
525
+ return paddedLeft < paddedRight ? -1 : 1;
526
+ }
527
+ function descriptorFromCompact(compact, predecessor = null) {
528
+ const decoded = decodeJws(compact);
529
+ if (!decoded.ok)
530
+ return decoded;
531
+ const payload = decoded.value.payload;
532
+ const keys = predecessor ? predecessor.payload.verification_keys : payload.verification_keys;
533
+ const descriptorRow = ALG_ROWS.find((one) => one.name === decoded.value.header.alg);
534
+ const grammar = keyGrammarError(payload);
535
+ if (grammar)
536
+ return fail(grammar);
537
+ const resolved = Array.isArray(keys) && keys.find((one) => one.key_id === decoded.value.header.kid && keyMatchesRow(one, descriptorRow));
538
+ if (!resolved)
539
+ return fail("descriptor_key_invalid");
540
+ if (!verifyDecodedJws(decoded.value, "cap+party", keys))
541
+ return fail("signature_invalid");
542
+ if (!parseTimestamp(payload.effective_from)) {
543
+ return fail("timestamp_invalid");
544
+ }
545
+ const digest = taggedHash("party_descriptor_content", decoded.value.payloadBytes);
546
+ if (payload.descriptor_number === 1) {
547
+ if (payload.prev_descriptor_digest !== undefined)
548
+ return fail("descriptor_invalid");
549
+ }
550
+ else if (!predecessor || payload.prev_descriptor_digest !== predecessor.digest || payload.descriptor_number !== predecessor.payload.descriptor_number + 1) {
551
+ return fail("descriptor_chain_invalid");
552
+ }
553
+ return ok({ ...decoded.value, digest, compact });
554
+ }
555
+ // The key-grammar gate mirrors the reference codec's two stages: an unknown
556
+ // key algorithm or a wrong-length encoding fails the nested schema constraint
557
+ // (nested_invalid), while an ML-DSA key inside a revision-1 or revision-2
558
+ // descriptor passes the schema and rejects at the codec's revision gate
559
+ // (descriptor_invalid) — no honest producer could have minted it.
560
+ function keyGrammarError(payload) {
561
+ if (!Array.isArray(payload.verification_keys) || payload.verification_keys.length === 0) {
562
+ return "nested_invalid";
563
+ }
564
+ for (const one of payload.verification_keys) {
565
+ const row = ALG_ROWS.find((candidate) => candidate.keyAlgorithm === one.algorithm);
566
+ if (!row)
567
+ return "nested_invalid";
568
+ const bytes = Buffer.from(one.public_key, "base64url");
569
+ if (bytes.length !== row.publicKeyBytes || bytes.toString("base64url") !== one.public_key) {
570
+ return "nested_invalid";
571
+ }
572
+ if (one.algorithm !== "Ed25519" &&
573
+ !(Number.isInteger(payload.protocol_revision) && payload.protocol_revision >= 3)) {
574
+ return "descriptor_invalid";
575
+ }
576
+ }
577
+ return null;
578
+ }
579
+ function descriptorChain(compacts) {
580
+ if (!Array.isArray(compacts) || compacts.length === 0)
581
+ return fail("descriptor_chain_invalid");
582
+ const pending = [...compacts];
583
+ const descriptors = [];
584
+ while (pending.length > 0) {
585
+ let progressed = false;
586
+ for (let index = pending.length - 1; index >= 0; index -= 1) {
587
+ const decoded = decodeJws(pending[index]);
588
+ if (!decoded.ok)
589
+ return fail("descriptor_chain_invalid");
590
+ const prev = decoded.value.payload.prev_descriptor_digest;
591
+ const predecessor = prev ? descriptors.find((one) => one.digest === prev) : null;
592
+ if (prev && !predecessor)
593
+ continue;
594
+ const verified = descriptorFromCompact(pending[index], predecessor);
595
+ if (!verified.ok)
596
+ return fail("descriptor_chain_invalid");
597
+ descriptors.push(verified.value);
598
+ pending.splice(index, 1);
599
+ progressed = true;
600
+ }
601
+ if (!progressed)
602
+ return fail("descriptor_chain_invalid");
603
+ }
604
+ const children = new Map();
605
+ for (const descriptor of descriptors) {
606
+ const prev = descriptor.payload.prev_descriptor_digest;
607
+ if (prev)
608
+ children.set(prev, [...(children.get(prev) || []), descriptor.digest]);
609
+ }
610
+ const fork = [...children.values()].find((values) => values.length > 1);
611
+ const positions = Object.fromEntries(descriptors.map((one) => [one.digest, fork ? "contested" : (children.has(one.digest) ? "superseded" : "head")]));
612
+ return ok({ descriptors, topology: fork ? "forked" : "linear", positions, siblingDescriptors: fork ? [...fork].sort() : [] });
613
+ }
614
+ const REVISION_FIELDS = ["abp_bindings", "attribution_declaration", "charter_id", "effective_from", "extensions", "legal_text", "parties", "precedence_declaration", "prev_revision_digest", "protocol_revision", "receipt_profile", "revision_number", "supersedes", "termination_rules"];
615
+ const REVISION_REQUIRED = ["abp_bindings", "attribution_declaration", "effective_from", "extensions", "legal_text", "parties", "precedence_declaration", "protocol_revision", "receipt_profile", "revision_number", "termination_rules"];
616
+ const EXTENSION_PROFILES = [
617
+ { namespace: "com.example/pricing-indexed", owner: "Example Charter Profiles", criticality: "critical", state: "active", schema_digest: "sha-256:W88CU79l5r7YYCv2vuUTELifnM4GDKfbZPULSpDgQ2Y", a2a_uri: "https://example.com/charter-profiles/pricing-indexed", promoted_at_revision: null, surface: "charter_revision" },
618
+ { namespace: "com.example/pricing-indexed-observation", owner: "Example Charter Profiles", criticality: "optional", state: "active", schema_digest: "sha-256:6e4emU-CATXhAVFi9XaIIZUzZbCAQBcGkVwJpkZzWk8", a2a_uri: "https://example.com/charter-profiles/pricing-indexed-observation", promoted_at_revision: null, surface: "receipt" },
619
+ { namespace: "com.example.charter/default", owner: "Example Charter Profiles", criticality: "optional", state: "active", schema_digest: null, a2a_uri: "https://example.com/charter-profiles/com.example.charter/default", promoted_at_revision: null, surface: "receipt" },
620
+ { namespace: "com.example/identity-vlei", owner: "Example Charter Profiles", criticality: "optional", state: "reserved", schema_digest: null, a2a_uri: "https://example.com/charter-profiles/identity-vlei", promoted_at_revision: null, surface: "party_descriptor" },
621
+ { namespace: "com.example/identity-eidas-qeaa", owner: "Example Charter Profiles", criticality: "optional", state: "reserved", schema_digest: null, a2a_uri: "https://example.com/charter-profiles/identity-eidas-qeaa", promoted_at_revision: null, surface: "party_descriptor" },
622
+ { namespace: "com.example/retired-profile", owner: "Example Charter Profiles", criticality: "critical", state: "retired", schema_digest: null, a2a_uri: "https://example.com/charter-profiles/retired-profile", promoted_at_revision: 1, surface: "charter_revision" },
623
+ ];
624
+ function criticalRevisionProfile(namespace) {
625
+ return EXTENSION_PROFILES.find((profile) => profile.namespace === namespace && profile.criticality === "critical" &&
626
+ profile.state === "active" && profile.surface === "charter_revision") || null;
627
+ }
628
+ function extensionRegistryDigest() {
629
+ const document = Object.fromEntries(EXTENSION_PROFILES.map((profile) => [
630
+ profile.namespace,
631
+ {
632
+ namespace: profile.namespace,
633
+ owner: profile.owner,
634
+ criticality: profile.criticality,
635
+ state: profile.state,
636
+ schema_digest: profile.schema_digest,
637
+ a2a_uri: profile.a2a_uri,
638
+ promoted_at_revision: profile.promoted_at_revision,
639
+ },
640
+ ]));
641
+ return taggedHash("extension_registry", Buffer.from(canonical(document)));
642
+ }
643
+ function revisionFromText(text) {
644
+ if (typeof text !== "string")
645
+ return fail("revision_invalid");
646
+ let value;
647
+ try {
648
+ value = JSON.parse(text);
649
+ }
650
+ catch (_error) {
651
+ return fail("invalid_syntax");
652
+ }
653
+ const unknown = Object.keys(value).find((key) => !REVISION_FIELDS.includes(key));
654
+ if (unknown)
655
+ return fail("unknown_member");
656
+ const missing = REVISION_REQUIRED.find((key) => !(key in value));
657
+ if (missing)
658
+ return fail("missing_required");
659
+ if (!Array.isArray(value.parties) || new Set(value.parties.map((one) => one.role)).size !== value.parties.length)
660
+ return fail("revision_invalid");
661
+ if (!Array.isArray(value.termination_rules.reason_codes) || value.termination_rules.reason_codes.length === 0)
662
+ return fail("nested_invalid");
663
+ if (value.revision_number === 1 && (value.supersedes !== undefined || value.prev_revision_digest !== undefined || value.charter_id !== undefined))
664
+ return fail("revision_invalid");
665
+ if (value.supersedes !== undefined && (!Array.isArray(value.supersedes) || value.supersedes.some((one) => typeof one !== "string")))
666
+ return fail("revision_invalid");
667
+ const critical = value.extensions?.critical || {};
668
+ const optional = value.extensions?.optional || {};
669
+ const names = [...Object.keys(critical), ...Object.keys(optional)];
670
+ if (names.some((namespace) => Buffer.byteLength(namespace) > 512 || !/^[a-z0-9][a-z0-9.-]*\/[a-z0-9][a-z0-9.-]*$/.test(namespace))) {
671
+ return fail("extension_namespace_invalid");
672
+ }
673
+ if (new Set(names).size !== names.length)
674
+ return fail("extension_duplicate");
675
+ for (const namespace of Object.keys(critical)) {
676
+ const profile = EXTENSION_PROFILES.find((entry) => entry.namespace === namespace);
677
+ if (!profile || profile.state === "reserved")
678
+ return fail("extension_unknown_critical");
679
+ if (profile.state === "retired")
680
+ return fail("extension_retired");
681
+ if (profile.criticality !== "critical")
682
+ return fail("extension_criticality_conflict");
683
+ if (profile.surface !== "charter_revision")
684
+ return fail("extension_scope_invalid");
685
+ if (profile.schema_digest === null)
686
+ return fail("extension_schema_unavailable");
687
+ if (namespace === "com.example/pricing-indexed" && critical[namespace]?.formula !== "index_plus_spread")
688
+ return fail("constraint_violation");
689
+ }
690
+ for (const namespace of Object.keys(optional)) {
691
+ const profile = EXTENSION_PROFILES.find((entry) => entry.namespace === namespace);
692
+ if (!profile || profile.state === "reserved" || profile.state === "retired")
693
+ continue;
694
+ if (profile.surface !== "charter_revision")
695
+ return fail("extension_scope_invalid");
696
+ if (profile.schema_digest === null)
697
+ return fail("extension_schema_unavailable");
698
+ }
699
+ const bytes = Buffer.from(text);
700
+ return ok({ value, bytes, digest: taggedHash("charter_revision_content", bytes) });
701
+ }
702
+ function acceptanceFromCompact(compact, revision, chain) {
703
+ const decoded = decodeJws(compact);
704
+ if (!decoded.ok)
705
+ return decoded;
706
+ const claims = decoded.value.payload;
707
+ if ((claims.revision_number === 1) !== (claims.prev_revision_digest === undefined))
708
+ return fail("acceptance_invalid");
709
+ if (!parseTimestamp(claims.accepted_at))
710
+ return fail("timestamp_invalid");
711
+ const descriptor = chain.descriptors.find((one) => one.digest === claims.party_descriptor_digest);
712
+ if (!descriptor || !verifyDecodedJws(decoded.value, "cap+acceptance", descriptor.payload.verification_keys))
713
+ return fail("signature_invalid");
714
+ const expectedCharter = revision.value.charter_id || revision.digest;
715
+ const party = revision.value.parties.find((one) => one.party_descriptor_digest === claims.party_descriptor_digest);
716
+ const mismatch = claims.charter_id !== expectedCharter || claims.revision_number !== revision.value.revision_number || claims.revision_digest !== revision.digest || claims.party_role !== party?.role || (revision.value.prev_revision_digest || undefined) !== (claims.prev_revision_digest || undefined);
717
+ if (mismatch)
718
+ return fail("acceptance_claims_mismatch");
719
+ return ok({ claims, digest: taggedHash("acceptance_content", decoded.value.payloadBytes), descriptorPosition: chain.positions[claims.party_descriptor_digest] });
720
+ }
721
+ function terminationFromCompact(compact, revision, chain) {
722
+ const decoded = decodeJws(compact);
723
+ if (!decoded.ok)
724
+ return decoded;
725
+ const claims = decoded.value.payload;
726
+ const descriptor = chain.descriptors.find((one) => one.digest === claims.party_descriptor_digest);
727
+ if (!descriptor || !verifyDecodedJws(decoded.value, "cap+termination", descriptor.payload.verification_keys))
728
+ return fail("signature_invalid");
729
+ const expectedCharter = revision.value.charter_id || revision.digest;
730
+ const party = revision.value.parties.find((one) => one.party_descriptor_digest === claims.party_descriptor_digest);
731
+ if (claims.charter_id !== expectedCharter || claims.governing_revision_digest !== revision.digest || claims.party_role !== party?.role || !revision.value.termination_rules.reason_codes.includes(claims.reason_code))
732
+ return fail("termination_claims_mismatch");
733
+ const issuedAt = parseTimestamp(claims.issued_at);
734
+ const effectiveAt = parseTimestamp(claims.effective_at);
735
+ if (!issuedAt || !effectiveAt || compareTimestamps(issuedAt, effectiveAt) > 0)
736
+ return fail("termination_invalid");
737
+ return ok({ claims, digest: taggedHash("termination_content", decoded.value.payloadBytes), descriptorPosition: chain.positions[claims.party_descriptor_digest] });
738
+ }
739
+ // Chain-level structural checks mirroring Chain.verify: unique revision
740
+ // digests, exactly one genesis defining one charter identity, exact
741
+ // predecessor linkage, well-formed supersession targets, unique acceptance
742
+ // coordinates, dual acceptance against the revision's actual party pairs (any
743
+ // two roles — never hardcoded names), verified termination notices, and the
744
+ // reference topology/governing semantics with ancestry coverage.
745
+ function chainFromInput(input) {
746
+ if (!Array.isArray(input.revisions) || input.revisions.length === 0)
747
+ return fail("chain_invalid");
748
+ const descriptors = descriptorChain(input.descriptors);
749
+ if (!descriptors.ok)
750
+ return fail("chain_invalid");
751
+ const revisions = [];
752
+ for (const text of input.revisions) {
753
+ const revision = revisionFromText(text);
754
+ if (!revision.ok)
755
+ return fail("chain_invalid");
756
+ revisions.push(revision.value);
757
+ }
758
+ const byDigest = new Map(revisions.map((one) => [one.digest, one]));
759
+ if (byDigest.size !== revisions.length)
760
+ return fail("chain_invalid");
761
+ const genesisList = revisions.filter((one) => one.value.revision_number === 1);
762
+ if (genesisList.length !== 1)
763
+ return fail("chain_invalid");
764
+ const charterId = genesisList[0].value.charter_id || genesisList[0].digest;
765
+ for (const { digest, value } of revisions) {
766
+ if ((value.charter_id || digest) !== charterId)
767
+ return fail("chain_invalid");
768
+ if (value.revision_number === 1)
769
+ continue;
770
+ const predecessor = byDigest.get(value.prev_revision_digest);
771
+ if (!predecessor || predecessor.value.revision_number !== value.revision_number - 1 ||
772
+ (predecessor.value.charter_id || value.prev_revision_digest) !== charterId) {
773
+ return fail("chain_invalid");
774
+ }
775
+ for (const target of value.supersedes || []) {
776
+ const supersededTarget = byDigest.get(target);
777
+ if (!supersededTarget || supersededTarget.value.revision_number >= value.revision_number ||
778
+ (supersededTarget.value.charter_id || target) !== charterId) {
779
+ return fail("chain_invalid");
780
+ }
781
+ }
782
+ }
783
+ const acceptances = [];
784
+ const coordinates = new Set();
785
+ for (const compact of input.acceptances) {
786
+ const decoded = decodeJws(compact);
787
+ if (!decoded.ok)
788
+ return fail("chain_invalid");
789
+ const revision = byDigest.get(decoded.value.payload.revision_digest);
790
+ if (!revision)
791
+ return fail("chain_invalid");
792
+ const verified = acceptanceFromCompact(compact, revision, descriptors.value);
793
+ if (!verified.ok)
794
+ return fail("chain_invalid");
795
+ const coordinate = `${verified.value.claims.revision_digest}\0${verified.value.claims.party_descriptor_digest}\0${verified.value.claims.party_role}`;
796
+ if (coordinates.has(coordinate))
797
+ return fail("chain_invalid");
798
+ coordinates.add(coordinate);
799
+ acceptances.push(verified.value);
800
+ }
801
+ for (const compact of (input.terminations || [])) {
802
+ const decoded = decodeJws(compact);
803
+ if (!decoded.ok)
804
+ return fail("chain_invalid");
805
+ const revision = byDigest.get(decoded.value.payload.governing_revision_digest);
806
+ if (!revision)
807
+ return fail("chain_invalid");
808
+ const verified = terminationFromCompact(compact, revision, descriptors.value);
809
+ if (!verified.ok)
810
+ return fail("chain_invalid");
811
+ }
812
+ const accepted = revisions.filter((revision) => {
813
+ const expected = new Set(revision.value.parties.map((party) => `${party.party_descriptor_digest}\0${party.role}`));
814
+ const actual = new Set(acceptances
815
+ .filter((one) => one.claims.revision_digest === revision.digest)
816
+ .map((one) => `${one.claims.party_descriptor_digest}\0${one.claims.party_role}`));
817
+ if (actual.size !== expected.size)
818
+ return false;
819
+ for (const entry of [...expected])
820
+ if (!actual.has(entry))
821
+ return false;
822
+ return true;
823
+ });
824
+ const superseded = new Set(accepted.flatMap((one) => one.value.supersedes || []));
825
+ const active = accepted.filter((one) => !superseded.has(one.digest));
826
+ const maximum = Math.max(...active.map((one) => one.value.revision_number));
827
+ const heads = active.filter((one) => one.value.revision_number === maximum);
828
+ const acceptedByDigest = new Map(accepted.map((one) => [one.digest, one]));
829
+ // Walk DOWN from the head along unbroken accepted prev links: the head and
830
+ // everything on that chain is covered. A candidate outside the chain makes
831
+ // the active view forked.
832
+ const headAncestry = (head) => {
833
+ const chain = new Set([head]);
834
+ let current = acceptedByDigest.get(head);
835
+ while (current && current.value.prev_revision_digest && acceptedByDigest.has(current.value.prev_revision_digest)) {
836
+ chain.add(current.value.prev_revision_digest);
837
+ current = acceptedByDigest.get(current.value.prev_revision_digest);
838
+ }
839
+ return chain;
840
+ };
841
+ const ancestryCovers = (head) => {
842
+ const chain = headAncestry(head);
843
+ return active.every((one) => chain.has(one.digest));
844
+ };
845
+ const linear = heads.length === 1 && ancestryCovers(heads[0].digest);
846
+ const topology = active.length > 0 && !linear ? "forked" : "linear";
847
+ return ok({ descriptors: descriptors.value, revisions, accepted, acceptedDigests: accepted.map((one) => one.digest).sort(), supersededDigests: [...superseded].sort(), topology, charterId });
848
+ }
849
+ // Governing mirrors the reference semantics exactly: candidates are accepted,
850
+ // non-superseded, and effective at the instant (start-inclusive, end-exclusive
851
+ // via exact fraction comparison); a unique highest-numbered head governs only
852
+ // when every candidate is the head or an ancestor along an unbroken accepted
853
+ // chain — otherwise the view is contested, never silently resolved.
854
+ function effectiveAt(revision, at) {
855
+ const from = parseTimestamp(revision.value.effective_from);
856
+ if (!from || compareTimestamps(from, at) > 0)
857
+ return false;
858
+ if (revision.value.effective_until === undefined || revision.value.effective_until === null)
859
+ return true;
860
+ const until = parseTimestamp(revision.value.effective_until);
861
+ return until !== null && compareTimestamps(at, until) < 0;
862
+ }
863
+ function governing(chain, at) {
864
+ const applicable = chain.accepted.filter((one) => !chain.supersededDigests.includes(one.digest) && effectiveAt(one, at));
865
+ if (applicable.length === 0)
866
+ return "none";
867
+ const maximum = Math.max(...applicable.map((one) => one.value.revision_number));
868
+ const finalists = applicable.filter((one) => one.value.revision_number === maximum);
869
+ if (finalists.length !== 1)
870
+ return "contested";
871
+ const acceptedByDigest = new Map(chain.accepted.map((one) => [one.digest, one]));
872
+ const head = finalists[0].digest;
873
+ const chainFromHead = new Set([head]);
874
+ let walk = acceptedByDigest.get(head);
875
+ while (walk && walk.value.prev_revision_digest && acceptedByDigest.has(walk.value.prev_revision_digest)) {
876
+ chainFromHead.add(walk.value.prev_revision_digest);
877
+ walk = acceptedByDigest.get(walk.value.prev_revision_digest);
878
+ }
879
+ const covers = applicable.every((one) => chainFromHead.has(one.digest));
880
+ return covers ? head : "contested";
881
+ }
882
+ function projectReceipt(claims, chain, governingDigest) {
883
+ const claimedRevision = chain.accepted.find((one) => one.digest === claims.revision_digest);
884
+ const governingMatch = governingDigest === "contested" ? "undetermined" :
885
+ (governingDigest === claims.revision_digest ? "match" : "mismatch");
886
+ if (claimedRevision) {
887
+ const revision = claimedRevision.value;
888
+ const charterId = revision.charter_id || claimedRevision.digest;
889
+ const roles = new Set(revision.parties.map((one) => one.role));
890
+ const deploymentMatched = revision.abp_bindings.some((binding) => binding.party_role === claims.agent_party_role &&
891
+ binding.deployment_digest === claims.deployment_digest);
892
+ const recognized = claims.charter_id === charterId &&
893
+ claims.revision_number === revision.revision_number &&
894
+ roles.has(claims.issuing_party_role) && roles.has(claims.agent_party_role) &&
895
+ deploymentMatched;
896
+ return recognized ? ok({ governingMatch, chainConflict: "none", deploymentMatched: true }) :
897
+ fail("receipt_claims_mismatch");
898
+ }
899
+ const roles = new Set(chain.accepted.flatMap((one) => one.value.parties.map((party) => party.role)));
900
+ const recognized = claims.charter_id === chain.charterId &&
901
+ roles.has(claims.issuing_party_role) && roles.has(claims.agent_party_role);
902
+ if (!recognized)
903
+ return fail("receipt_claims_mismatch");
904
+ const acceptedHead = Math.max(0, ...chain.accepted.map((one) => one.value.revision_number));
905
+ const chainConflict = claims.revision_number <= acceptedHead ? "fork_evidenced" : "none";
906
+ return ok({ governingMatch, chainConflict, deploymentMatched: false });
907
+ }
908
+ function receiptSigningKeys(chain, claimedRevision, role) {
909
+ const revisions = claimedRevision ? [claimedRevision] : chain.accepted;
910
+ const keys = revisions.flatMap((revision) => revision.value.parties
911
+ .filter((party) => party.role === role)
912
+ .flatMap((party) => {
913
+ const descriptor = chain.descriptors.descriptors.find((one) => one.digest === party.party_descriptor_digest);
914
+ return descriptor?.payload.verification_keys || [];
915
+ }));
916
+ return [...new Map(keys.map((key) => [canonical(key), key])).values()];
917
+ }
918
+ function receiptFromCompact(compact, chain) {
919
+ const decoded = decodeJws(compact);
920
+ if (!decoded.ok)
921
+ return decoded;
922
+ const claims = decoded.value.payload;
923
+ if (claims.grant?.scheme === "bap" && claims.grant?.grant_digest === undefined)
924
+ return fail("receipt_invalid");
925
+ const optional = claims.extensions?.optional || {};
926
+ for (const namespace of Object.keys(optional)) {
927
+ const profile = EXTENSION_PROFILES.find((entry) => entry.namespace === namespace);
928
+ if (!profile || profile.state === "reserved" || profile.state === "retired")
929
+ continue;
930
+ if (profile.surface !== "receipt")
931
+ return fail("extension_scope_invalid");
932
+ if (profile.schema_digest === null)
933
+ return fail("extension_schema_unavailable");
934
+ }
935
+ const claimedRevision = chain.accepted.find((one) => one.digest === claims.revision_digest);
936
+ const verifiedPublicKeys = new Set(receiptSigningKeys(chain, claimedRevision, claims.issuing_party_role)
937
+ .filter((key) => verifyDecodedJws(decoded.value, "cap+receipt", [key]))
938
+ .map((key) => key.public_key));
939
+ if (verifiedPublicKeys.size !== 1)
940
+ return fail("signature_invalid");
941
+ const occurredAt = parseTimestamp(claims.occurred_at);
942
+ const recordedAt = parseTimestamp(claims.recorded_at);
943
+ if (!occurredAt || !recordedAt || compareTimestamps(recordedAt, occurredAt) < 0)
944
+ return fail("receipt_invalid");
945
+ // The closed matrix mirrors the reference decoder: rejected requires
946
+ // no_effect; accepted admits effect_committed, no_effect, or indeterminate.
947
+ const outcomeAllowed = claims.decision === "rejected" ? claims.outcome === "no_effect" :
948
+ (claims.outcome === "effect_committed" || claims.outcome === "no_effect" || claims.outcome === "indeterminate");
949
+ if (!outcomeAllowed)
950
+ return fail("cross_field_invalid");
951
+ const governingDigest = governing(chain, occurredAt);
952
+ const projection = projectReceipt(claims, chain, governingDigest);
953
+ if (!projection.ok)
954
+ return projection;
955
+ return ok({ claims, digest: taggedHash("receipt_content", decoded.value.payloadBytes), ...projection.value, optionalExtensions: Object.keys(claims.extensions?.optional || {}).sort() });
956
+ }
957
+ function execute(one) {
958
+ const input = one.input;
959
+ switch (one.surface) {
960
+ case "base64url.decode":
961
+ return project(strictBase64url(input.text), (bytes) => ({ bytes_base64url: bytes.toString("base64url") }));
962
+ case "json.decode": {
963
+ if (!("text" in input) && !("bytes_base64url" in input))
964
+ return invalid("invalid_type");
965
+ if (input.limits !== undefined && !validLimits(input.limits))
966
+ return invalid("invalid_limits");
967
+ const bytes = "text" in input ? Buffer.from(input.text) : Buffer.from(input.bytes_base64url, "base64url");
968
+ const decoded = decodeJsonBytes(bytes);
969
+ if (!decoded.ok)
970
+ return invalid(decoded.code);
971
+ return project(jsonWithinLimits(decoded.value, bytes, input.limits), jsonProjection);
972
+ }
973
+ case "canonicalization.encode":
974
+ if (input.tag === "integer") {
975
+ const literal = input.text_value !== undefined ? input.text_value : String(input.value);
976
+ if (/^-?[0-9]+$/.test(literal) && (BigInt(literal) > MAXIMUM_SAFE_INTEGER || BigInt(literal) < -MAXIMUM_SAFE_INTEGER))
977
+ return invalid("integer_magnitude");
978
+ return valid({ text: literal });
979
+ }
980
+ if (input.tag === "object") {
981
+ const names = input.members.map(([key]) => key);
982
+ if (new Set(names).size !== names.length)
983
+ return invalid("duplicate_member");
984
+ return valid({ text: canonical(Object.fromEntries(input.members.map(([key, value]) => [key, value.value]))) });
985
+ }
986
+ if (input.tag === "string_codepoint")
987
+ return invalid("invalid_encoding");
988
+ if (input.kind === "improper_object")
989
+ return invalid("invalid_type");
990
+ return canonical(JSON.parse(input.text)) === input.text ? valid({ text: input.text }) : invalid("non_canonical_bytes");
991
+ case "digest.hash":
992
+ if (!("bytes_base64url" in input))
993
+ return invalid("invalid_type");
994
+ if (input.tagged !== undefined) {
995
+ if (typeof input.tagged !== "string")
996
+ return invalid("invalid_type");
997
+ const separator = input.tagged.indexOf(":");
998
+ if (separator < 1)
999
+ return invalid("digest_encoding_invalid");
1000
+ if (input.tagged.slice(0, separator) !== "sha-256")
1001
+ return invalid("digest_algorithm_unsupported");
1002
+ if (!/^[A-Za-z0-9_-]{43}$/.test(input.tagged.slice(separator + 1)))
1003
+ return invalid("digest_encoding_invalid");
1004
+ if (input.tagged !== taggedHash(input.domain || "charter_revision_content", Buffer.from(input.bytes_base64url, "base64url")))
1005
+ return invalid("digest_mismatch");
1006
+ }
1007
+ return valid({ algorithm: "sha-256" });
1008
+ case "schema.validate": {
1009
+ const members = input.members;
1010
+ if (Object.keys(members).some((key) => key !== "name"))
1011
+ return invalid("unknown_member");
1012
+ if (!("name" in members))
1013
+ return invalid("missing_required");
1014
+ if (typeof members.name !== "string")
1015
+ return invalid("invalid_type");
1016
+ if (!/^[a-z]+$/.test(members.name))
1017
+ return invalid("constraint_violation");
1018
+ if (Buffer.byteLength(members.name) < 2 || Buffer.byteLength(members.name) > 4)
1019
+ return invalid("cardinality_violation");
1020
+ return valid({ members });
1021
+ }
1022
+ case "party_descriptor.verify": {
1023
+ const descriptor = descriptorFromCompact(input.compact);
1024
+ return project(descriptor, (oneDescriptor) => ({ descriptor_digest: oneDescriptor.digest, party_id: oneDescriptor.digest, descriptor_number: oneDescriptor.payload.descriptor_number }));
1025
+ }
1026
+ case "descriptor_chain.verify": {
1027
+ const chain = descriptorChain(input.compacts);
1028
+ return project(chain, (value) => {
1029
+ return { topology: value.topology, positions: value.positions, sibling_descriptors: value.siblingDescriptors };
1030
+ });
1031
+ }
1032
+ case "charter_revision.decode":
1033
+ return project(revisionFromText(input.text), (revision) => ({ revision_digest: revision.digest, revision_number: revision.value.revision_number, precedence_declaration: revision.value.precedence_declaration, abp_binding: { blueprint_id: revision.value.abp_bindings[0].blueprint_id, release_number: revision.value.abp_bindings[0].release_number, content_digest: revision.value.abp_bindings[0].content_digest, deployment_digest: revision.value.abp_bindings[0].deployment_digest } }));
1034
+ case "acceptance.verify": {
1035
+ const revision = revisionFromText(input.revision_text);
1036
+ const chain = descriptorChain(input.descriptor_compacts);
1037
+ if (!revision.ok || !chain.ok)
1038
+ return invalid("acceptance_invalid");
1039
+ return project(acceptanceFromCompact(input.compact, revision.value, chain.value), (facts) => ({ acceptance_digest: facts.digest, revision_digest: facts.claims.revision_digest, party_descriptor_digest: facts.claims.party_descriptor_digest, descriptor_position: facts.descriptorPosition }));
1040
+ }
1041
+ case "acceptance.equivocation": {
1042
+ const chain = descriptorChain(input.descriptor_compacts);
1043
+ if (!chain.ok || !Array.isArray(input.signed_revisions) || input.signed_revisions.length !== 2) {
1044
+ return invalid("acceptance_equivocation_invalid");
1045
+ }
1046
+ const facts = input.signed_revisions.map((signed) => {
1047
+ const revision = revisionFromText(signed.revision_text);
1048
+ return revision.ok ? acceptanceFromCompact(signed.compact, revision.value, chain.value) : revision;
1049
+ });
1050
+ if (facts.length !== 2 || facts.some((oneFact) => !oneFact.ok))
1051
+ return invalid("acceptance_equivocation_invalid");
1052
+ const [left, right] = facts.map((oneFact) => oneFact.value.claims);
1053
+ const pairable = left.charter_id === right.charter_id && left.revision_number === right.revision_number &&
1054
+ left.party_descriptor_digest === right.party_descriptor_digest && left.party_role === right.party_role &&
1055
+ left.revision_digest !== right.revision_digest;
1056
+ if (!pairable)
1057
+ return invalid("acceptance_equivocation_invalid");
1058
+ return valid({ kind: "acceptance_equivocation", revision_number: facts[0].value.claims.revision_number, revision_digests: facts.map((oneFact) => oneFact.value.claims.revision_digest).sort(), winner: null });
1059
+ }
1060
+ case "termination.verify": {
1061
+ const revision = revisionFromText(input.revision_text);
1062
+ const chain = descriptorChain(input.descriptor_compacts);
1063
+ if (!revision.ok || !chain.ok)
1064
+ return invalid("termination_invalid");
1065
+ return project(terminationFromCompact(input.compact, revision.value, chain.value), (facts) => ({ termination_digest: facts.digest, governing_revision_digest: facts.claims.governing_revision_digest, party_descriptor_digest: facts.claims.party_descriptor_digest, reason_code: facts.claims.reason_code, descriptor_position: facts.descriptorPosition }));
1066
+ }
1067
+ case "chain.verify": {
1068
+ const chain = chainFromInput(input);
1069
+ return project(chain, (facts) => ({ charter_id: facts.charterId, topology: facts.topology, accepted_revision_digests: facts.acceptedDigests, superseded_revision_digests: facts.supersededDigests }));
1070
+ }
1071
+ case "governing_revision": {
1072
+ const chain = chainFromInput(input);
1073
+ if (!chain.ok)
1074
+ return invalid("governing_invalid");
1075
+ return valid({
1076
+ governing_revisions: input.queries.map((query) => {
1077
+ const at = parseTimestamp(query.at);
1078
+ return at ? governing(chain.value, at) : "none";
1079
+ }),
1080
+ });
1081
+ }
1082
+ case "receipt.verify": {
1083
+ const chain = chainFromInput(input.chain);
1084
+ if (!chain.ok)
1085
+ return invalid("receipt_invalid");
1086
+ return project(receiptFromCompact(input.compact, chain.value), (facts) => ({ receipt_digest: facts.digest, revision_number: facts.claims.revision_number, revision_digest: facts.claims.revision_digest, decision: facts.claims.decision, outcome: facts.claims.outcome, chain_conflict: facts.chainConflict, governing_match: facts.governingMatch, deployment_digest_matched: facts.deploymentMatched, optional_extensions_retained: facts.optionalExtensions }));
1087
+ }
1088
+ default:
1089
+ throw new Error("unsupported surface");
1090
+ }
1091
+ }
1092
+ function corpusDigest(index) {
1093
+ const without = { ...index };
1094
+ delete without.corpus_digest;
1095
+ return taggedHash("corpus_index", Buffer.from(canonical(without)));
1096
+ }
1097
+ export function loadCorpus(root) {
1098
+ const observedEntries = walk(root);
1099
+ if (observedEntries.length === 0 || observedEntries.length > MAXIMUM_CORPUS_FILES ||
1100
+ observedEntries.reduce((total, entry) => total + entry.size, 0) > MAXIMUM_CORPUS_BYTES) {
1101
+ throw new Error("corpus filesystem bounds");
1102
+ }
1103
+ const observedSizes = new Map(observedEntries.map((entry) => [entry.path, entry.size]));
1104
+ const indexBytes = readFileSync(join(root, "index.json"));
1105
+ if (indexBytes.length !== observedSizes.get("index.json"))
1106
+ throw new Error("index changed during read");
1107
+ const index = JSON.parse(indexBytes.toString("utf8"));
1108
+ if (canonical(index) !== indexBytes.toString("utf8"))
1109
+ throw new Error("non-canonical index");
1110
+ if (!exactKeys(index, ["applicability", "corpus_digest", "files", "format", "registry_digest", "total_cases"]))
1111
+ throw new Error("index shape");
1112
+ if (index.format !== INDEX_FORMAT || index.corpus_digest !== corpusDigest(index))
1113
+ throw new Error("index identity");
1114
+ if (index.registry_digest !== CERTIFIED_REGISTRY_DIGEST)
1115
+ throw new Error("registry identity");
1116
+ if (rawHash(indexBytes) !== CERTIFIED_INDEX_SHA256_BASE64URL)
1117
+ throw new Error("uncertified index");
1118
+ const expectedFiles = ["index.json", ...index.files.map((entry) => entry.path)].sort();
1119
+ if (canonical(observedEntries.map((entry) => entry.path).sort()) !== canonical(expectedFiles))
1120
+ throw new Error("file set");
1121
+ const cases = [];
1122
+ for (const entry of index.files) {
1123
+ const bytes = readFileSync(join(root, entry.path));
1124
+ if (bytes.length !== observedSizes.get(entry.path))
1125
+ throw new Error("case file changed during read");
1126
+ if (rawHash(bytes) !== String(entry.sha256_base64url))
1127
+ throw new Error("file hash");
1128
+ const file = JSON.parse(bytes.toString("utf8"));
1129
+ if (canonical(file) !== bytes.toString("utf8") || file.format !== CASE_FORMAT || file.cases.length !== entry.cases)
1130
+ throw new Error("case file");
1131
+ cases.push(...file.cases);
1132
+ }
1133
+ if (cases.length !== index.total_cases || cases.length === 0)
1134
+ throw new Error("case count");
1135
+ const ids = new Set();
1136
+ const observed = new Map();
1137
+ for (const one of cases) {
1138
+ if (ids.has(one.id) || !SURFACES.includes(one.surface) || !CLASSES.includes(one.class))
1139
+ throw new Error("case shape");
1140
+ ids.add(one.id);
1141
+ const key = `${one.surface}\0${one.class}`;
1142
+ observed.set(key, (observed.get(key) || 0) + 1);
1143
+ }
1144
+ for (const surface of SURFACES) {
1145
+ for (const oneClass of CLASSES) {
1146
+ const count = observed.get(`${surface}\0${oneClass}`) || 0;
1147
+ const applicability = index.applicability;
1148
+ const cell = applicability[surface][oneClass];
1149
+ if (REQUIRED[surface].includes(oneClass)) {
1150
+ if (cell !== count || count < 1)
1151
+ throw new Error("required cell");
1152
+ }
1153
+ else if (!exactKeys(cell, ["n_a"]) || cell.n_a === "" || count !== 0)
1154
+ throw new Error("not-applicable cell");
1155
+ }
1156
+ }
1157
+ return { index, indexBytes, cases };
1158
+ }
1159
+ export function reportFor(root) {
1160
+ const corpus = loadCorpus(root);
1161
+ const results = corpus.cases.map((one) => {
1162
+ const actual = execute(one);
1163
+ return { id: one.id, surface: one.surface, agree: canonical(actual) === canonical(one.expect), expected: one.expect, actual };
1164
+ });
1165
+ const agreed = results.filter((one) => one.agree).length;
1166
+ const total = results.length;
1167
+ const agreement = agreed === total && total > 0;
1168
+ const report = {
1169
+ format: REPORT_FORMAT,
1170
+ agreement,
1171
+ exit_status: agreement ? 0 : 1,
1172
+ total,
1173
+ agreed,
1174
+ disagreed: total - agreed,
1175
+ corpus_digest: corpus.index.corpus_digest,
1176
+ registry_digest: corpus.index.registry_digest,
1177
+ index_sha256_base64url: rawHash(corpus.indexBytes),
1178
+ results,
1179
+ };
1180
+ return { bytes: `${canonical(report)}\n`, exitStatus: report.exit_status };
1181
+ }
1182
+ export function selfChecks() {
1183
+ const vectors = [
1184
+ [Buffer.from(""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"],
1185
+ [Buffer.from("d3", "hex"), "28969cdfa74a12c82f3bad960b0b000aca2ac329deea5c2328ebc6f2ba9802c1"],
1186
+ [Buffer.from("b4190e", "hex"), "dff2e73091f6c05e528896c4c831b9448653dc2ff043528f6769437bc7b975c2"],
1187
+ ];
1188
+ for (const [message, expected] of vectors) {
1189
+ if (createHash("sha256").update(message).digest("hex") !== expected)
1190
+ throw new Error("SHA-256 KAT failed");
1191
+ }
1192
+ if (canonical({ b: 1, a: 2 }) !== "{\"a\":2,\"b\":1}")
1193
+ throw new Error("canonical ordering failed");
1194
+ const strictPadded = strictBase64url("AQ==");
1195
+ if (strictPadded.ok || strictPadded.code !== "base64url_padded")
1196
+ throw new Error("base64url strictness failed");
1197
+ const acceptedRevision = {
1198
+ digest: "known-revision",
1199
+ value: {
1200
+ abp_bindings: [{ party_role: "agent", deployment_digest: "known-deployment" }],
1201
+ charter_id: "known-charter",
1202
+ effective_from: "2026-01-01T00:00:00Z",
1203
+ parties: [
1204
+ { role: "issuer", party_descriptor_digest: "issuer-descriptor" },
1205
+ { role: "agent", party_descriptor_digest: "agent-descriptor" },
1206
+ ],
1207
+ revision_number: 2,
1208
+ },
1209
+ };
1210
+ const projectionChain = {
1211
+ accepted: [acceptedRevision],
1212
+ descriptors: {
1213
+ descriptors: [
1214
+ { digest: "issuer-descriptor", payload: { verification_keys: [{ key_id: "issuer", public_key: "issuer-key" }] } },
1215
+ { digest: "agent-descriptor", payload: { verification_keys: [{ key_id: "agent", public_key: "agent-key" }] } },
1216
+ ],
1217
+ },
1218
+ supersededDigests: [],
1219
+ charterId: "known-charter",
1220
+ };
1221
+ const knownClaims = {
1222
+ charter_id: "known-charter",
1223
+ revision_digest: "known-revision",
1224
+ revision_number: 2,
1225
+ issuing_party_role: "issuer",
1226
+ agent_party_role: "agent",
1227
+ deployment_digest: "known-deployment",
1228
+ };
1229
+ const knownProjection = projectReceipt(knownClaims, projectionChain, "contested");
1230
+ if (!knownProjection.ok || knownProjection.value.chainConflict !== "none" ||
1231
+ knownProjection.value.governingMatch !== "undetermined" || !knownProjection.value.deploymentMatched) {
1232
+ throw new Error("known receipt projection drifted");
1233
+ }
1234
+ const unknownProjection = projectReceipt({ ...knownClaims, revision_digest: "unknown-revision", revision_number: 2 }, projectionChain, "known-revision");
1235
+ if (!unknownProjection.ok || unknownProjection.value.chainConflict !== "fork_evidenced" || unknownProjection.value.deploymentMatched) {
1236
+ throw new Error("unknown receipt projection drifted");
1237
+ }
1238
+ const futureProjection = projectReceipt({ ...knownClaims, revision_digest: "future-revision", revision_number: 3 }, projectionChain, "known-revision");
1239
+ if (!futureProjection.ok || futureProjection.value.chainConflict !== "none") {
1240
+ throw new Error("future receipt projection drifted");
1241
+ }
1242
+ if (projectReceipt({ ...knownClaims, deployment_digest: "wrong" }, projectionChain, "known-revision").ok) {
1243
+ throw new Error("recognized receipt claim validation drifted");
1244
+ }
1245
+ const issuerKeys = receiptSigningKeys(projectionChain, acceptedRevision, "issuer");
1246
+ const issuerKey = issuerKeys[0];
1247
+ if (issuerKeys.length !== 1 || issuerKey.public_key !== "issuer-key") {
1248
+ throw new Error("receipt issuer-key selection drifted");
1249
+ }
1250
+ if (jsonWithinLimits({ nested: [["xx"]] }, Buffer.from('{"nested":[["xx"]]}'), { max_depth: 2 }).ok) {
1251
+ throw new Error("JSON depth limit drifted");
1252
+ }
1253
+ if (jsonWithinLimits({ a: 1, b: 2 }, Buffer.from('{"a":1,"b":2}'), { max_object_members: 1 }).ok ||
1254
+ jsonWithinLimits([1, 2], Buffer.from("[1,2]"), { max_array_items: 1 }).ok ||
1255
+ jsonWithinLimits("é", Buffer.from('"é"'), { max_string_bytes: 1 }).ok) {
1256
+ throw new Error("JSON structural limit drifted");
1257
+ }
1258
+ if (criticalRevisionProfile("com.example/pricing-indexed") === null ||
1259
+ criticalRevisionProfile("com.example/retired-profile") !== null) {
1260
+ throw new Error("critical extension registry drifted");
1261
+ }
1262
+ if (extensionRegistryDigest() !== CERTIFIED_REGISTRY_DIGEST) {
1263
+ throw new Error("compiled extension registry identity drifted");
1264
+ }
1265
+ // Parity invariants against the reference implementation.
1266
+ const floatDecoded = decodeJsonText('{"a":0.0,"b":2e0,"c":5}');
1267
+ if (!floatDecoded.ok)
1268
+ throw new Error("float decode drifted");
1269
+ const projected = jsonProjection(floatDecoded.value);
1270
+ const member = (name) => projected.members.find(([key]) => key === name)?.[1].tag;
1271
+ if (!floatDecoded.ok || member("a") !== "float" || member("b") !== "float" || member("c") !== "integer") {
1272
+ throw new Error("number tagging drifted");
1273
+ }
1274
+ if (decodeJsonBytes(Buffer.from('"\\ufdd0"')).ok || decodeJsonBytes(Buffer.from('"\\uffff"')).ok) {
1275
+ throw new Error("I-JSON noncharacter rejection drifted");
1276
+ }
1277
+ if (parseTimestamp("2026-06-30T23:59:60Z") === null || parseTimestamp("2024-03-31T23:59:60Z") !== null) {
1278
+ throw new Error("leap-second window drifted");
1279
+ }
1280
+ if (parseTimestamp("2026-02-30T00:00:00Z") !== null || parseTimestamp("0000-01-01T00:00:00Z") !== null) {
1281
+ throw new Error("calendar validation drifted");
1282
+ }
1283
+ const halfMs = parseTimestamp("2026-01-01T00:00:00.0005Z");
1284
+ const whole = parseTimestamp("2026-01-01T00:00:00Z");
1285
+ if (!halfMs || !whole || compareTimestamps(halfMs, whole) <= 0) {
1286
+ throw new Error("sub-millisecond fraction comparison drifted");
1287
+ }
1288
+ const halfSecond = parseTimestamp("2026-01-01T00:00:00.5Z");
1289
+ const halfSecondPadded = parseTimestamp("2026-01-01T00:00:00.500Z");
1290
+ if (halfSecond === null || halfSecondPadded === null || compareTimestamps(halfSecond, halfSecondPadded) !== 0) {
1291
+ throw new Error("fraction padding drifted");
1292
+ }
1293
+ if (LIMIT_MAXIMUMS.max_bytes !== 16_777_216 || LIMIT_MAXIMUMS.max_artifact_set_items !== 4_096) {
1294
+ throw new Error("compiled limit maximums drifted");
1295
+ }
1296
+ }