@charter-agreement-protocol/verifier 0.5.0 → 0.6.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 CHANGED
@@ -6,7 +6,7 @@ const CASE_FORMAT = "charter-agreement-protocol-conformance-cases";
6
6
  const REPORT_FORMAT = "charter-agreement-protocol-conformance-report";
7
7
  const MAXIMUM_CORPUS_FILES = 64;
8
8
  const MAXIMUM_CORPUS_BYTES = 33_554_432;
9
- export const CERTIFIED_INDEX_SHA256_BASE64URL = "f--8DXp39J4wJkrpkD8ZTQpHkMlduX43Xvnz0HeObeA";
9
+ export const CERTIFIED_INDEX_SHA256_BASE64URL = "n2Se2on9kG3cdeFMiy9OW9lKalvM_02Fmdw-XbYe-A4";
10
10
  export const CERTIFIED_REGISTRY_DIGEST = "sha-256:u754joyHGcLCTm1LYV2s6eHauUUdDfJDwwyhbAbxvzc";
11
11
  // The fourth certified identity — the specification digest over the spec
12
12
  // set — is pinned in priv/release-metadata.json and enforced by the
@@ -57,38 +57,45 @@ const CLASSES = [
57
57
  "missing_required", "non_canonical_bytes", "digest_mismatch", "signature_invalid",
58
58
  "chain_invalid", "descriptor_superseded", "descriptor_fork", "equivocation",
59
59
  "chain_fork", "profile_algorithm_outside", "profile_revision_outside", "profile_narrow_valid",
60
- "supersession", "precedence_selection", "outcome_indeterminate",
60
+ "supersession", "precedence_selection", "terminated", "outcome_indeterminate",
61
61
  "extension_unknown_critical", "extension_optional_roundtrip", "extension_invalid",
62
62
  ];
63
63
  const REQUIRED = {
64
+ "acceptance.equivocation": ["equivocation", "invalid_constraint"],
65
+ "acceptance.verify": ["valid", "invalid_constraint", "signature_invalid", "unknown_member", "profile_narrow_valid", "profile_algorithm_outside", "profile_revision_outside"],
64
66
  "base64url.decode": ["valid", "exact_bound", "invalid_encoding"],
65
- "json.decode": ["valid", "boundary_near", "exact_bound", "maximum_plus_one", "invalid_encoding", "invalid_type"],
66
67
  "canonicalization.encode": ["valid", "invalid_encoding", "invalid_type", "non_canonical_bytes"],
68
+ "chain.verify": ["valid", "exact_bound", "maximum_plus_one", "chain_fork", "supersession", "chain_invalid"],
69
+ "chain.verify_profile": ["profile_algorithm_outside", "profile_revision_outside", "profile_narrow_valid"],
70
+ "charter_revision.decode": ["valid", "invalid_encoding", "invalid_type", "invalid_constraint", "invalid_cardinality", "unknown_member", "missing_required", "non_canonical_bytes", "extension_unknown_critical", "extension_invalid"],
71
+ "descriptor_chain.verify": ["signature_invalid", "chain_invalid", "descriptor_superseded", "descriptor_fork"],
67
72
  "digest.hash": ["valid", "invalid_type", "digest_mismatch"],
73
+ "governing_revision": ["precedence_selection", "terminated"],
74
+ "json.decode": ["valid", "boundary_near", "exact_bound", "maximum_plus_one", "invalid_encoding", "invalid_type"],
75
+ "party_descriptor.verify": ["valid", "signature_invalid", "invalid_encoding", "unknown_member", "invalid_constraint", "profile_narrow_valid", "profile_algorithm_outside", "profile_revision_outside"],
76
+ "receipt.verify": ["valid", "invalid_constraint", "signature_invalid", "unknown_member", "chain_fork", "terminated", "outcome_indeterminate", "extension_optional_roundtrip", "invalid_encoding", "extension_invalid", "profile_narrow_valid", "profile_algorithm_outside", "profile_revision_outside"],
68
77
  "schema.validate": ["valid", "invalid_type", "invalid_constraint", "invalid_cardinality", "unknown_member", "missing_required", "maximum_plus_one"],
69
- "party_descriptor.verify": ["valid", "signature_invalid", "invalid_encoding", "unknown_member", "invalid_constraint"],
70
- "descriptor_chain.verify": ["signature_invalid", "chain_invalid", "descriptor_superseded", "descriptor_fork"],
71
- "charter_revision.decode": ["valid", "invalid_type", "invalid_constraint", "invalid_cardinality", "unknown_member", "missing_required", "extension_unknown_critical", "extension_invalid"],
72
- "acceptance.verify": ["valid", "invalid_constraint", "signature_invalid"],
73
- "acceptance.equivocation": ["equivocation", "invalid_constraint"],
74
- "termination.verify": ["valid", "invalid_constraint", "signature_invalid"],
75
- "chain.verify": ["valid", "chain_fork", "supersession", "chain_invalid"],
76
- "chain.verify_profile": ["profile_algorithm_outside", "profile_revision_outside", "profile_narrow_valid"],
77
- "governing_revision": ["precedence_selection"],
78
- "receipt.verify": ["valid", "invalid_constraint", "signature_invalid", "chain_fork", "outcome_indeterminate", "extension_optional_roundtrip", "invalid_encoding", "extension_invalid"],
78
+ "termination.verify": ["valid", "invalid_constraint", "signature_invalid", "unknown_member", "profile_narrow_valid", "profile_algorithm_outside", "profile_revision_outside"],
79
79
  };
80
80
  const ok = (value) => ({ ok: true, value });
81
81
  const fail = (code) => ({ ok: false, code });
82
82
  const valid = (output) => ({ status: "valid", output });
83
83
  const invalid = (code) => ({ status: "invalid", error_code: code });
84
84
  const project = (result, projector) => result.ok ? valid(projector(result.value)) : invalid(result.code);
85
+ const NOT_VERIFIED_FLOOR = ["tenancy", "live_policy", "authority", "effect_ownership", "execution", "billing", "evaluation_truth", "legal_validity", "term_satisfaction", "view_completeness", "counterparty_view", "wall_clock"];
86
+ function factsRecord(attrs, additions = []) {
87
+ return { protocol_revision: null, alg: null, ...attrs, not_verified: [...new Set([...NOT_VERIFIED_FLOOR, ...additions])] };
88
+ }
85
89
  export function canonical(value) {
86
90
  if (value instanceof Number)
87
91
  return JSON.stringify(value.valueOf());
88
92
  if (value === null || typeof value === "boolean" || typeof value === "string")
89
93
  return JSON.stringify(value);
90
- if (typeof value === "number" && Number.isFinite(value))
94
+ if (typeof value === "number" && Number.isFinite(value)) {
95
+ if (Number.isInteger(value) && !Number.isSafeInteger(value))
96
+ throw new Error("integer_magnitude");
91
97
  return JSON.stringify(value);
98
+ }
92
99
  if (Array.isArray(value))
93
100
  return `[${value.map(canonical).join(",")}]`;
94
101
  if (value && typeof value === "object") {
@@ -135,13 +142,20 @@ function strictBase64url(text) {
135
142
  // closed codes, in the decoder's own order.
136
143
  const MAXIMUM_SAFE_INTEGER = 9007199254740991n;
137
144
  const NUMBER_TOKEN = /(?:-?(?:0|[1-9][0-9]*))(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
138
- function readJsonValue(text, index) {
145
+ // Retain text order separately from JavaScript's integer-key enumeration.
146
+ // Plain property access remains compatible with existing artifact consumers.
147
+ const JSON_MEMBER_ORDER = new WeakMap();
148
+ function readJsonValue(text, index, limits, depth = 0) {
139
149
  index = skipWhitespace(text, index);
140
150
  const char = text[index];
141
151
  if (char === undefined)
142
152
  return { status: "need-character" };
153
+ if ((char === "{" || char === "[") && depth + 1 > limits.max_depth)
154
+ return { status: "error", code: "limit_exceeded" };
143
155
  if (char === "{") {
144
156
  const members = new Map();
157
+ let duplicate = false;
158
+ let count = 0;
145
159
  let cursor = skipWhitespace(text, index + 1);
146
160
  if (text[cursor] === "}")
147
161
  return { status: "ok", value: {}, index: cursor + 1 };
@@ -151,15 +165,23 @@ function readJsonValue(text, index) {
151
165
  const key = readJsonString(text, cursor);
152
166
  if (key.status !== "ok")
153
167
  return key;
168
+ if (Buffer.byteLength(key.value) > limits.max_string_bytes)
169
+ return { status: "error", code: "limit_exceeded" };
154
170
  cursor = skipWhitespace(text, key.index);
155
171
  if (text[cursor] !== ":")
156
172
  return { status: "syntax" };
157
- const item = readJsonValue(text, skipWhitespace(text, cursor + 1));
173
+ const item = readJsonValue(text, skipWhitespace(text, cursor + 1), limits, depth + 1);
158
174
  if (item.status !== "ok")
159
175
  return item;
160
- const duplicate = members.has(key.value);
161
- members.set(key.value, item.value);
162
176
  cursor = skipWhitespace(text, item.index);
177
+ if (text[cursor] !== "," && text[cursor] !== "}")
178
+ return { status: "syntax" };
179
+ if (item.deferredCode)
180
+ return { status: "error", code: item.deferredCode };
181
+ if (++count > limits.max_object_members)
182
+ return { status: "error", code: "limit_exceeded" };
183
+ duplicate ||= members.has(key.value);
184
+ members.set(key.value, item.value);
163
185
  if (text[cursor] === ",") {
164
186
  cursor = skipWhitespace(text, cursor + 1);
165
187
  continue;
@@ -167,7 +189,9 @@ function readJsonValue(text, index) {
167
189
  if (text[cursor] === "}") {
168
190
  if (duplicate)
169
191
  return { status: "error", code: "duplicate_member" };
170
- return { status: "ok", value: Object.fromEntries(members), index: cursor + 1 };
192
+ const object = Object.fromEntries(members);
193
+ JSON_MEMBER_ORDER.set(object, [...members.keys()]);
194
+ return { status: "ok", value: object, index: cursor + 1 };
171
195
  }
172
196
  return { status: "syntax" };
173
197
  }
@@ -178,11 +202,17 @@ function readJsonValue(text, index) {
178
202
  if (text[cursor] === "]")
179
203
  return { status: "ok", value: items, index: cursor + 1 };
180
204
  for (;;) {
181
- const item = readJsonValue(text, cursor);
205
+ const item = readJsonValue(text, cursor, limits, depth + 1);
182
206
  if (item.status !== "ok")
183
207
  return item;
184
- items.push(item.value);
185
208
  cursor = skipWhitespace(text, item.index);
209
+ if (text[cursor] !== "," && text[cursor] !== "]")
210
+ return { status: "syntax" };
211
+ if (item.deferredCode)
212
+ return { status: "error", code: item.deferredCode };
213
+ if (items.length >= limits.max_array_items)
214
+ return { status: "error", code: "limit_exceeded" };
215
+ items.push(item.value);
186
216
  if (text[cursor] === ",") {
187
217
  cursor = skipWhitespace(text, cursor + 1);
188
218
  continue;
@@ -194,6 +224,8 @@ function readJsonValue(text, index) {
194
224
  }
195
225
  if (char === '"') {
196
226
  const string = readJsonString(text, index);
227
+ if (string.status === "ok" && Buffer.byteLength(string.value) > limits.max_string_bytes)
228
+ return { status: "error", code: "limit_exceeded" };
197
229
  return string.status === "ok" ? { status: "ok", value: string.value, index: string.index } : string;
198
230
  }
199
231
  for (const [literal, value] of [["true", true], ["false", false], ["null", null]]) {
@@ -204,15 +236,28 @@ function readJsonValue(text, index) {
204
236
  const token = NUMBER_TOKEN.exec(text);
205
237
  if (token) {
206
238
  const literal = token[0];
239
+ // A fraction or exponent that starts without its digits is a syntax error,
240
+ // as in the reference: "1." and "1e" are invalid_syntax, while a "." after
241
+ // a fraction or an "e" after an exponent is ordinary trailing input.
242
+ const next = text[index + literal.length];
243
+ if ((next === "." && !/[.eE]/.test(literal)) || ((next === "e" || next === "E") && !/[eE]/.test(literal)))
244
+ return { status: "syntax" };
245
+ const numberError = (code) => ({ status: "ok", deferredCode: code, index: index + literal.length });
207
246
  if (/^-?[0-9]+$/.test(literal)) {
247
+ if (literal.replace(/^-/, "").length > 21)
248
+ return numberError("number_not_double_expressible");
208
249
  const magnitude = BigInt(literal);
209
- if ((magnitude > MAXIMUM_SAFE_INTEGER || magnitude < -MAXIMUM_SAFE_INTEGER) &&
210
- magnitude !== BigInt(Number(literal))) {
211
- return { status: "error", code: "number_not_double_expressible" };
250
+ if (magnitude > MAXIMUM_SAFE_INTEGER || magnitude < -MAXIMUM_SAFE_INTEGER) {
251
+ if (JSON.stringify(Number(literal)) !== literal)
252
+ return numberError("number_not_double_expressible");
253
+ return { status: "ok", value: new Number(Number(literal)), index: index + literal.length };
212
254
  }
213
255
  }
214
- else if (!Number.isFinite(Number(literal))) {
215
- return { status: "error", code: "invalid_number" };
256
+ else {
257
+ if (literal.length > 32)
258
+ return numberError("number_not_double_expressible");
259
+ if (!Number.isFinite(Number(literal)))
260
+ return numberError("invalid_number");
216
261
  }
217
262
  // Float-ness follows the lexeme (fraction or exponent), never the value:
218
263
  // "0.0" and "2e0" are floats even though their double is integral, so the
@@ -260,25 +305,36 @@ function skipWhitespace(text, index) {
260
305
  index += 1;
261
306
  return index;
262
307
  }
263
- export function decodeJsonText(text) {
264
- const value = readJsonValue(text, 0);
308
+ export function decodeJsonText(text, selected = {}) {
309
+ if (!validLimits(selected))
310
+ return fail("invalid_limits");
311
+ if (typeof text !== "string")
312
+ return fail("invalid_type");
313
+ const limits = { ...DEFAULT_LIMITS, ...selected };
314
+ if (Buffer.byteLength(text) > limits.max_bytes)
315
+ return fail("limit_exceeded");
316
+ const value = readJsonValue(text, 0, limits);
265
317
  if (value.status === "need-character" || value.status === "syntax")
266
318
  return fail("invalid_syntax");
267
319
  if (value.status === "error")
268
320
  return fail(value.code);
269
321
  if (value.index === undefined || skipWhitespace(text, value.index) !== text.length)
270
322
  return fail("trailing_bytes");
323
+ if (value.deferredCode)
324
+ return fail(value.deferredCode);
271
325
  return ok(value.value);
272
326
  }
273
- function decodeJsonBytes(bytes) {
327
+ function decodeJsonBytes(bytes, limits = DEFAULT_LIMITS) {
274
328
  try {
275
- return decodeJsonText(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
329
+ if (bytes.length > limits.max_bytes)
330
+ return fail("limit_exceeded");
331
+ return decodeJsonText(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes), limits);
276
332
  }
277
333
  catch (_error) {
278
334
  return fail("invalid_encoding");
279
335
  }
280
336
  }
281
- const JSON_DEFAULT_LIMITS = {
337
+ export const DEFAULT_LIMITS = Object.freeze({
282
338
  max_bytes: 1_048_576,
283
339
  max_depth: 64,
284
340
  max_object_members: 1_024,
@@ -286,10 +342,11 @@ const JSON_DEFAULT_LIMITS = {
286
342
  max_string_bytes: 65_536,
287
343
  max_artifact_set_items: 1_024,
288
344
  max_artifact_set_bytes: 67_108_864,
289
- };
345
+ });
346
+ const JSON_DEFAULT_LIMITS = DEFAULT_LIMITS;
290
347
  // The compiled maximums mirror lib/charter_agreement_protocol/limits.ex: the
291
348
  // greatest caller-selectable value per field, not the defaults.
292
- const LIMIT_MAXIMUMS = {
349
+ export const MAXIMUM_LIMITS = Object.freeze({
293
350
  max_bytes: 16_777_216,
294
351
  max_depth: 128,
295
352
  max_object_members: 65_536,
@@ -297,12 +354,13 @@ const LIMIT_MAXIMUMS = {
297
354
  max_string_bytes: 1_048_576,
298
355
  max_artifact_set_items: 4_096,
299
356
  max_artifact_set_bytes: 1_073_741_824,
300
- };
357
+ });
358
+ const LIMIT_MAXIMUMS = MAXIMUM_LIMITS;
301
359
  function validLimits(selected) {
302
- if (typeof selected !== "object" || selected === null)
360
+ if (!isRecord(selected))
303
361
  return false;
304
362
  const maximums = LIMIT_MAXIMUMS;
305
- return Object.entries(selected).every(([name, value]) => name in maximums && Number.isInteger(value) && value >= 0 && value <= maximums[name]);
363
+ return Object.entries(selected).every(([name, value]) => Object.hasOwn(maximums, name) && Number.isInteger(value) && value >= 0 && value <= maximums[name]);
306
364
  }
307
365
  function jsonWithinLimits(value, bytes, selected = {}) {
308
366
  const limits = { ...JSON_DEFAULT_LIMITS, ...selected };
@@ -320,7 +378,7 @@ function jsonWithinLimits(value, bytes, selected = {}) {
320
378
  item.forEach((child) => visit(child, depth + 1));
321
379
  return;
322
380
  }
323
- if (item && typeof item === "object") {
381
+ if (item && typeof item === "object" && !(item instanceof Number)) {
324
382
  const entries = Object.entries(item);
325
383
  if (depth + 1 > limits.max_depth || entries.length > limits.max_object_members)
326
384
  throw new Error("limit");
@@ -349,7 +407,7 @@ export function jsonProjection(value) {
349
407
  if (Array.isArray(value))
350
408
  return { tag: "array", items: value.map(jsonProjection) };
351
409
  if (value && typeof value === "object")
352
- return { tag: "object", members: Object.entries(value).map(([key, item]) => [key, jsonProjection(item)]) };
410
+ return { tag: "object", members: (JSON_MEMBER_ORDER.get(value) ?? Object.keys(value)).map((key) => [key, jsonProjection(value[key])]) };
353
411
  if (typeof value === "string")
354
412
  return { tag: "string", value };
355
413
  if (typeof value === "boolean")
@@ -357,46 +415,49 @@ export function jsonProjection(value) {
357
415
  return { tag: "float", value };
358
416
  }
359
417
  const PROTECTED_MEMBERS = ["alg", "kid", "typ"];
360
- function decodeJws(compact) {
418
+ function canonicalTextError(value, text) {
419
+ try {
420
+ return canonical(value) === text ? null : "non_canonical_bytes";
421
+ }
422
+ catch (error) {
423
+ return error instanceof Error ? error.message : "invalid_type";
424
+ }
425
+ }
426
+ function decodeJws(compact, limits = DEFAULT_LIMITS, expectedTyp) {
361
427
  if (typeof compact !== "string")
362
428
  return fail("compact_invalid");
363
- if (Buffer.byteLength(compact) > JSON_DEFAULT_LIMITS.max_bytes)
429
+ if (Buffer.byteLength(compact) > limits.max_bytes)
364
430
  return fail("limit_exceeded");
365
431
  const segments = compact.split(".");
366
432
  if (segments.length !== 3)
367
433
  return fail("compact_invalid");
368
- const decoded = segments.map(strictBase64url);
369
- if (decoded.some((one) => !one.ok))
434
+ const protectedBytes = strictBase64url(segments[0]);
435
+ const payloadBytes = strictBase64url(segments[1]);
436
+ const signatureBytes = strictBase64url(segments[2]);
437
+ if (!protectedBytes.ok || !payloadBytes.ok)
370
438
  return fail("compact_invalid");
371
- const headerBytes = decoded[0].value;
372
- const payloadBytes = decoded[1].value;
373
- // Strict I-JSON decode under the default ceilings — the reference verifier
374
- // never hands raw JSON.parse bytes; every header/payload failure maps to the
375
- // framing-layer code the reference decoder emits for that segment.
376
- const headerValue = decodeJsonBytes(headerBytes);
377
- if (!headerValue.ok)
439
+ if (!signatureBytes.ok)
440
+ return fail("signature_invalid");
441
+ const headerValue = decodeJsonBytes(protectedBytes.value, limits);
442
+ if (!headerValue.ok || !isRecord(headerValue.value) || canonicalTextError(headerValue.value, protectedBytes.value.toString()))
378
443
  return fail("protected_header_invalid");
379
- const payloadValue = decodeJsonBytes(payloadBytes);
380
- if (!payloadValue.ok)
381
- return fail("non_canonical_bytes");
382
444
  const header = headerValue.value;
383
- const payload = payloadValue.value;
384
- const headerKeys = Object.keys(header);
385
- if (headerKeys.length !== 3 || PROTECTED_MEMBERS.some((member) => !headerKeys.includes(member))) {
445
+ if (!exactKeys(header, PROTECTED_MEMBERS) || typeof header.alg !== "string" || !ALG_ROWS.some((row) => row.name === header.alg) ||
446
+ typeof header.typ !== "string" || (expectedTyp !== undefined && header.typ !== expectedTyp) ||
447
+ typeof header.kid !== "string" || !/^[A-Za-z0-9._~-]{1,128}$/.test(header.kid))
386
448
  return fail("protected_header_invalid");
387
- }
388
- if (canonical(header) !== headerBytes.toString() || canonical(payload) !== payloadBytes.toString())
449
+ const payloadValue = decodeJsonBytes(payloadBytes.value, limits);
450
+ if (!payloadValue.ok || canonicalTextError(payloadValue.value, payloadBytes.value.toString()))
389
451
  return fail("non_canonical_bytes");
390
- const revision = payload.protocol_revision;
391
- if (typeof revision !== "number" || !Number.isInteger(revision) || !algBinds(header.alg, revision))
452
+ if (!isRecord(payloadValue.value))
453
+ return fail("protected_header_invalid");
454
+ const payload = payloadValue.value;
455
+ if (typeof payload.protocol_revision !== "number" || !Number.isInteger(payload.protocol_revision) || !algBinds(header.alg, payload.protocol_revision))
392
456
  return fail("protected_header_invalid");
393
- // Per-row signature length: checked only after the header names the
394
- // algorithm (64 for the classical rows, 2420/3309/4627 for ML-DSA).
395
457
  const row = ALG_ROWS.find((one) => one.name === header.alg);
396
- const signature = decoded[2].value;
397
- if (!row || signature.length !== row.signatureBytes)
458
+ if (signatureBytes.value.length !== row.signatureBytes)
398
459
  return fail("signature_invalid");
399
- return ok({ header, payload, payloadBytes, signature, signingInput: Buffer.from(`${segments[0]}.${segments[1]}`) });
460
+ return ok({ header, payload, payloadBytes: payloadBytes.value, signature: signatureBytes.value, signingInput: Buffer.from(`${segments[0]}.${segments[1]}`) });
400
461
  }
401
462
  const ED25519_FIELD_PRIME = 2n ** 255n - 19n;
402
463
  const ED25519_SUBGROUP_ORDER = 2n ** 252n + 27742317777372353535851937790883648493n;
@@ -479,16 +540,32 @@ function keyMatchesRow(key, row) {
479
540
  const bytes = Buffer.from(key.public_key, "base64url");
480
541
  return bytes.length === row.publicKeyBytes && bytes.toString("base64url") === key.public_key;
481
542
  }
482
- function verifyDecodedJws(decoded, typ, keys) {
543
+ function verifyDecodedJws(decoded, typ, keys, settings = DEFAULT_SETTINGS) {
544
+ const admission = profileError(decoded.header.alg, decoded.payload.protocol_revision, settings);
545
+ if (admission)
546
+ return fail(admission);
483
547
  const row = ALG_ROWS.find((one) => one.name === decoded.header.alg);
484
548
  if (!row || decoded.header.typ !== typ || typeof decoded.header.kid !== "string")
485
- return false;
549
+ return fail("signature_invalid");
486
550
  const key = keys.find((one) => one.key_id === decoded.header.kid && keyMatchesRow(one, row));
487
551
  if (!key)
488
- return false;
489
- return row.keyAlgorithm === "Ed25519" ?
490
- ed25519(key.public_key, decoded.signingInput, decoded.signature) :
491
- mldsa(row.keyAlgorithm, key.public_key, decoded.signingInput, decoded.signature);
552
+ return fail("signature_invalid");
553
+ const bytes = Buffer.from(key.public_key, "base64url");
554
+ if (decoded.signature.length !== row.signatureBytes || bytes.length !== row.publicKeyBytes)
555
+ return fail("signature_invalid");
556
+ if (row.keyAlgorithm === "Ed25519" && (!strictEd25519Point(bytes) || !strictEd25519Point(decoded.signature.subarray(0, 32)) || decodeLittleEndian(decoded.signature.subarray(32)) >= ED25519_SUBGROUP_ORDER))
557
+ return fail("signature_invalid");
558
+ if (!runtimeSupportsAlgorithm(row.keyAlgorithm))
559
+ return fail("algorithm_unsupported_on_substrate");
560
+ try {
561
+ const prefix = row.keyAlgorithm === "Ed25519" ? Buffer.from("302a300506032b6570032100", "hex") : ML_DSA_SPKI_PREFIXES[row.keyAlgorithm];
562
+ const spki = createPublicKey({ key: Buffer.concat([prefix, bytes]), format: "der", type: "spki" });
563
+ const verified = nodeVerifySignature(null, decoded.signingInput, spki, decoded.signature);
564
+ return verified ? ok(null) : fail("signature_invalid");
565
+ }
566
+ catch (_error) {
567
+ return fail(katVerifies(row.keyAlgorithm) ? "signature_invalid" : "algorithm_unsupported_on_substrate");
568
+ }
492
569
  }
493
570
  const TIMESTAMP_GRAMMAR = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?Z$/;
494
571
  // Exact RFC 3339 UTC parse mirroring Timestamp.ex: real calendar date, hour
@@ -503,10 +580,9 @@ function parseTimestamp(value) {
503
580
  if (!match)
504
581
  return null;
505
582
  const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
506
- if (year < 1)
507
- return null;
508
- const utc = Date.UTC(year, month - 1, day);
509
- const date = new Date(utc);
583
+ const date = new Date(0);
584
+ date.setUTCFullYear(year, month - 1, day);
585
+ const utc = date.getTime();
510
586
  if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day)
511
587
  return null;
512
588
  if (hour > 23 || minute > 59 || second > 60)
@@ -527,49 +603,45 @@ function compareTimestamps(left, right) {
527
603
  return 0;
528
604
  return paddedLeft < paddedRight ? -1 : 1;
529
605
  }
530
- function descriptorFromCompact(compact, predecessor = null) {
531
- const decoded = decodeJws(compact);
606
+ function descriptorFromCompact(compact, predecessor = null, settings = DEFAULT_SETTINGS) {
607
+ const decoded = decodeJws(compact, settings.limits, "cap+party");
532
608
  if (!decoded.ok)
533
609
  return decoded;
534
610
  const payload = decoded.value.payload;
535
611
  const keys = predecessor ? predecessor.payload.verification_keys : payload.verification_keys;
536
- const descriptorRow = ALG_ROWS.find((one) => one.name === decoded.value.header.alg);
537
- const grammar = keyGrammarError(payload);
612
+ const grammar = descriptorClaimsError(payload);
538
613
  if (grammar)
539
614
  return fail(grammar);
540
- // The descriptor timestamp floor mirrors the reference SCHEMA-stage
541
- // constraint (checked before key resolution and signature work there):
542
- // a spelling outside 1..64 BYTES is not a legal member value — the same
543
- // floor the seven sibling timestamp members carry. Byte length, not
544
- // UTF-16 units.
545
- if (typeof payload.effective_from !== "string" ||
546
- Buffer.byteLength(payload.effective_from, "utf8") < 1 ||
547
- Buffer.byteLength(payload.effective_from, "utf8") > 64) {
548
- return fail("constraint_violation");
549
- }
550
- const resolved = Array.isArray(keys) && keys.find((one) => one.key_id === decoded.value.header.kid && keyMatchesRow(one, descriptorRow));
551
- if (!resolved)
552
- return fail("descriptor_key_invalid");
553
- if (!verifyDecodedJws(decoded.value, "cap+party", keys))
554
- return fail("signature_invalid");
555
- if (!parseTimestamp(payload.effective_from)) {
556
- return fail("timestamp_invalid");
557
- }
558
615
  const digest = taggedHash("party_descriptor_content", decoded.value.payloadBytes);
559
616
  if (payload.descriptor_number === 1) {
617
+ if (predecessor)
618
+ return fail("descriptor_chain_invalid");
560
619
  if (payload.prev_descriptor_digest !== undefined)
561
620
  return fail("descriptor_invalid");
562
621
  }
563
- else if (!predecessor || payload.prev_descriptor_digest !== predecessor.digest || payload.descriptor_number !== predecessor.payload.descriptor_number + 1) {
622
+ else if (!predecessor || payload.prev_descriptor_digest !== predecessor.digest || payload.descriptor_number !== predecessor.payload.descriptor_number + 1 || payload.party_id !== (predecessor.payload.party_id ?? predecessor.digest)) {
564
623
  return fail("descriptor_chain_invalid");
565
624
  }
566
- return ok({ ...decoded.value, digest, compact });
625
+ // The envelope is admitted before its kid is looked up, as in the
626
+ // reference, so an out-of-profile artifact whose kid names no key reports
627
+ // the profile code. Acceptances and terminations do the same.
628
+ const descriptorAdmission = profileError(decoded.value.header.alg, payload.protocol_revision, settings);
629
+ if (descriptorAdmission)
630
+ return fail(descriptorAdmission);
631
+ const resolved = Array.isArray(keys) && keys.find((one) => one.key_id === decoded.value.header.kid && one.status === "active");
632
+ if (!resolved)
633
+ return fail("descriptor_key_invalid");
634
+ if (!parseTimestamp(payload.effective_from)) {
635
+ return fail("timestamp_invalid");
636
+ }
637
+ const signature = verifyDecodedJws(decoded.value, "cap+party", keys, settings);
638
+ if (!signature.ok)
639
+ return signature;
640
+ return ok(factsRecord({ ...decoded.value, digest, compact, lineage: [compact, ...(predecessor?.lineage ?? [])], protocol_revision: payload.protocol_revision, alg: decoded.value.header.alg }));
567
641
  }
568
- // The key-grammar gate mirrors the reference codec's two stages: an unknown
569
- // key algorithm or a wrong-length encoding fails the nested schema constraint
570
- // (nested_invalid), while an ML-DSA key inside a revision-1 or revision-2
571
- // descriptor passes the schema and rejects at the codec's revision gate
572
- // (descriptor_invalid) — no honest producer could have minted it.
642
+ // The nested schema admits registry encoding lengths; extraction checks
643
+ // the decoded bytes against the selected algorithm and canonical spelling.
644
+ // Those extraction failures use descriptor_invalid.
573
645
  function keyGrammarError(payload) {
574
646
  if (!Array.isArray(payload.verification_keys) || payload.verification_keys.length === 0) {
575
647
  return "nested_invalid";
@@ -585,7 +657,7 @@ function keyGrammarError(payload) {
585
657
  return "nested_invalid";
586
658
  const bytes = Buffer.from(one.public_key, "base64url");
587
659
  if (bytes.length !== row.publicKeyBytes || bytes.toString("base64url") !== one.public_key) {
588
- return "nested_invalid";
660
+ return "descriptor_invalid";
589
661
  }
590
662
  if (one.algorithm !== "Ed25519" &&
591
663
  !(Number.isInteger(payload.protocol_revision) && payload.protocol_revision >= 3)) {
@@ -594,43 +666,86 @@ function keyGrammarError(payload) {
594
666
  }
595
667
  return null;
596
668
  }
597
- function descriptorChain(compacts) {
669
+ function descriptorChain(compacts, settings = DEFAULT_SETTINGS) {
598
670
  if (!Array.isArray(compacts) || compacts.length === 0)
599
671
  return fail("descriptor_chain_invalid");
600
- const pending = [...compacts];
601
- const descriptors = [];
602
- while (pending.length > 0) {
603
- let progressed = false;
604
- for (let index = pending.length - 1; index >= 0; index -= 1) {
605
- const decoded = decodeJws(pending[index]);
606
- if (!decoded.ok)
607
- return fail("descriptor_chain_invalid");
608
- const prev = decoded.value.payload.prev_descriptor_digest;
609
- const predecessor = prev ? descriptors.find((one) => one.digest === prev) : null;
610
- if (prev && !predecessor)
611
- continue;
612
- const verified = descriptorFromCompact(pending[index], predecessor);
613
- if (!verified.ok)
614
- return fail("descriptor_chain_invalid");
615
- descriptors.push(verified.value);
616
- pending.splice(index, 1);
617
- progressed = true;
618
- }
619
- if (!progressed)
672
+ if (compacts.length > settings.limits.max_artifact_set_items)
673
+ return fail("limit_exceeded");
674
+ const entries = [];
675
+ for (const compact of compacts) {
676
+ const decoded = decodeJws(compact, settings.limits, "cap+party");
677
+ if (!decoded.ok || descriptorClaimsError(decoded.value.payload))
620
678
  return fail("descriptor_chain_invalid");
679
+ entries.push({ compact, digest: taggedHash("party_descriptor_content", decoded.value.payloadBytes), payload: decoded.value.payload });
621
680
  }
681
+ const roots = entries.filter((entry) => entry.payload.descriptor_number === 1);
682
+ if (roots.length !== 1 || new Set(entries.map((entry) => entry.digest)).size !== entries.length)
683
+ return fail("descriptor_chain_invalid");
684
+ const root = descriptorFromCompact(roots[0].compact, null, settings);
685
+ if (!root.ok)
686
+ return historyFailure([root.code]);
687
+ const descriptors = [root.value];
622
688
  const children = new Map();
623
- for (const descriptor of descriptors) {
624
- const prev = descriptor.payload.prev_descriptor_digest;
689
+ for (const entry of entries) {
690
+ const prev = entry.payload.prev_descriptor_digest;
625
691
  if (prev)
626
- children.set(prev, [...(children.get(prev) || []), descriptor.digest]);
627
- }
628
- const fork = [...children.values()].find((values) => values.length > 1);
692
+ children.set(prev, [...(children.get(prev) ?? []), entry]);
693
+ }
694
+ for (let i = 0; i < descriptors.length; i++) {
695
+ const siblings = children.get(descriptors[i].digest) ?? [];
696
+ const results = siblings.map((entry) => descriptorFromCompact(entry.compact, descriptors[i], settings));
697
+ const failures = results.filter((result) => !result.ok).map((result) => result.code);
698
+ if (failures.length > 0)
699
+ return historyFailure(failures);
700
+ for (const result of results)
701
+ if (result.ok)
702
+ descriptors.push(result.value);
703
+ }
704
+ if (descriptors.length !== entries.length)
705
+ return fail("descriptor_chain_invalid");
706
+ const siblings = [...children.values()].filter((group) => group.length > 1).flat().map((entry) => entry.digest);
707
+ const fork = siblings.length > 0;
708
+ descriptors.sort((a, b) => a.payload.descriptor_number - b.payload.descriptor_number || a.digest.localeCompare(b.digest));
629
709
  const positions = Object.fromEntries(descriptors.map((one) => [one.digest, fork ? "contested" : (children.has(one.digest) ? "superseded" : "head")]));
630
- return ok({ descriptors, topology: fork ? "forked" : "linear", positions, siblingDescriptors: fork ? [...fork].sort() : [] });
710
+ for (const descriptor of descriptors)
711
+ Object.assign(descriptor, { descriptor_position: positions[descriptor.digest] });
712
+ const fork_evidence = fork ? factsRecord({ kind: "sibling_descriptors", sibling_descriptors: [...new Set(siblings)].sort() }) : null;
713
+ return ok(factsRecord({ descriptors, topology: fork ? "forked" : "linear", positions, siblingDescriptors: [...new Set(siblings)].sort(), fork_evidence }));
714
+ }
715
+ function historyFailure(codes) {
716
+ const ordered = ["algorithm_outside_profile", "revision_outside_profile", "algorithm_unsupported_on_substrate"];
717
+ if (codes.some((code) => !ordered.includes(code)))
718
+ return fail("descriptor_chain_invalid");
719
+ return fail(ordered.find((code) => codes.includes(code)));
720
+ }
721
+ function descriptorViews(compacts, settings = DEFAULT_SETTINGS) {
722
+ if (!Array.isArray(compacts))
723
+ return fail("chain_invalid");
724
+ const groups = new Map();
725
+ for (const compact of compacts) {
726
+ const decoded = decodeJws(compact, settings.limits, "cap+party");
727
+ if (!decoded.ok)
728
+ return decoded;
729
+ const shape = descriptorClaimsError(decoded.value.payload);
730
+ if (shape)
731
+ return fail(shape);
732
+ const id = decoded.value.payload.party_id ?? taggedHash("party_descriptor_content", decoded.value.payloadBytes);
733
+ groups.set(id, [...(groups.get(id) ?? []), compact]);
734
+ }
735
+ if (groups.size !== 2)
736
+ return fail("chain_invalid");
737
+ const histories = [];
738
+ for (const id of [...groups.keys()].sort()) {
739
+ const chain = descriptorChain(groups.get(id), settings);
740
+ if (!chain.ok)
741
+ return chain;
742
+ histories.push(chain.value);
743
+ }
744
+ return ok(factsRecord({ histories, descriptors: histories.flatMap((chain) => chain.descriptors),
745
+ positions: Object.assign({}, ...histories.map((chain) => chain.positions)),
746
+ siblingDescriptors: histories.flatMap((chain) => chain.siblingDescriptors),
747
+ topology: histories.some((chain) => chain.topology === "forked") ? "forked" : "linear" }));
631
748
  }
632
- 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"];
633
- const REVISION_REQUIRED = ["abp_bindings", "attribution_declaration", "effective_from", "extensions", "legal_text", "parties", "precedence_declaration", "protocol_revision", "receipt_profile", "revision_number", "termination_rules"];
634
749
  const EXTENSION_PROFILES = [
635
750
  { 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" },
636
751
  { 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" },
@@ -658,69 +773,199 @@ function extensionRegistryDigest() {
658
773
  ]));
659
774
  return taggedHash("extension_registry", Buffer.from(canonical(document)));
660
775
  }
661
- function revisionFromText(text) {
662
- if (typeof text !== "string")
663
- return fail("revision_invalid");
664
- let value;
665
- try {
666
- value = JSON.parse(text);
776
+ function isRecord(value) {
777
+ return value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Number);
778
+ }
779
+ function field(name, type, constraint, required = true) {
780
+ return { name, type, constraint, required };
781
+ }
782
+ const stringBytes = (min, max) => (value) => Buffer.byteLength(value) >= min && Buffer.byteLength(value) <= max;
783
+ const integerRange = (min, max) => (value) => value >= min && value <= max;
784
+ const oneOf = (...values) => (value) => values.includes(value);
785
+ const digestPattern = (value) => /^sha-256:[A-Za-z0-9_-]{43}$/.test(value);
786
+ const digestField = (name, required = true) => field(name, "string", digestPattern, required);
787
+ const safeIntegerField = (name) => field(name, "integer", integerRange(1, Number.MAX_SAFE_INTEGER));
788
+ const roleField = (name) => field(name, "string", stringBytes(1, 128));
789
+ const timeField = (name, required = true) => field(name, "string", stringBytes(1, 64), required);
790
+ const nestedField = (name, type, nested, cardinality) => ({ name, type, required: true, nested, cardinality });
791
+ function schemaError(value, fields) {
792
+ if (!isRecord(value))
793
+ return "invalid_type";
794
+ if (Object.keys(value).some((name) => !fields.some((rule) => rule.name === name)))
795
+ return "unknown_member";
796
+ if (fields.some((rule) => rule.required && !Object.hasOwn(value, rule.name)))
797
+ return "missing_required";
798
+ const present = fields.filter((rule) => Object.hasOwn(value, rule.name));
799
+ for (const rule of present) {
800
+ const item = value[rule.name];
801
+ const typed = rule.type === "object" ? isRecord(item) : rule.type === "array" ? Array.isArray(item) :
802
+ rule.type === "integer" ? typeof item === "number" && Number.isInteger(item) : typeof item === "string";
803
+ if (!typed)
804
+ return "invalid_type";
805
+ }
806
+ if (present.some((rule) => rule.constraint && !rule.constraint(value[rule.name])))
807
+ return "constraint_violation";
808
+ if (present.some((rule) => rule.cardinality && (value[rule.name].length < rule.cardinality[0] || value[rule.name].length > rule.cardinality[1])))
809
+ return "cardinality_violation";
810
+ for (const rule of present) {
811
+ if (!rule.nested)
812
+ continue;
813
+ const items = rule.type === "array" ? value[rule.name] : [value[rule.name]];
814
+ if (items.some((item) => schemaError(item, rule.nested) !== null))
815
+ return "nested_invalid";
667
816
  }
668
- catch (_error) {
669
- return fail("invalid_syntax");
817
+ return null;
818
+ }
819
+ const REVISION_SCHEMA = [
820
+ field("protocol_revision", "integer", integerRange(1, 2)), digestField("charter_id", false),
821
+ safeIntegerField("revision_number"), digestField("prev_revision_digest", false),
822
+ nestedField("parties", "array", [digestField("party_descriptor_digest"), roleField("role")], [2, 2]),
823
+ nestedField("legal_text", "object", [digestField("content_digest"), field("media_type", "string", stringBytes(1, 255)), field("uri_hint", "string", stringBytes(1, 2048), false)]),
824
+ field("precedence_declaration", "string", oneOf("legal_text_governs", "machine_terms_govern")),
825
+ nestedField("attribution_declaration", "object", [field("basis", "string", oneOf("bound_deployments", "legal_text")), digestField("detail_digest", false)]),
826
+ timeField("effective_from"), timeField("effective_until", false),
827
+ nestedField("termination_rules", "object", [{ name: "reason_codes", type: "array", required: true, cardinality: [1, 64] }]),
828
+ nestedField("abp_bindings", "array", [roleField("party_role"), field("blueprint_id", "string", (v) => stringBytes(3, 512)(v) && /^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/.test(v)), safeIntegerField("release_number"), digestField("content_digest"), digestField("deployment_digest")], [0, 64]),
829
+ field("receipt_profile", "string", (v) => stringBytes(3, 512)(v) && /^[a-z0-9][a-z0-9.-]*\/[a-z0-9][a-z0-9.-]*$/.test(v)),
830
+ { name: "supersedes", type: "array", required: false, cardinality: [0, 8] }, field("extensions", "object"),
831
+ ];
832
+ const DESCRIPTOR_SCHEMA = [
833
+ field("protocol_revision", "integer", integerRange(1, 3)), digestField("party_id", false),
834
+ safeIntegerField("descriptor_number"), digestField("prev_descriptor_digest", false),
835
+ nestedField("verification_keys", "array", [
836
+ field("key_id", "string", (v) => /^[A-Za-z0-9._~-]{1,128}$/.test(v)),
837
+ field("algorithm", "string", oneOf("Ed25519", "ML-DSA-44", "ML-DSA-65", "ML-DSA-87")),
838
+ field("public_key", "string", (v) => /^(?:[A-Za-z0-9_-]{43}|[A-Za-z0-9_-]{1750}|[A-Za-z0-9_-]{2603}|[A-Za-z0-9_-]{3456})$/.test(v)),
839
+ field("status", "string", oneOf("active", "retired")),
840
+ ], [1, 32]),
841
+ nestedField("attestation_hints", "array", [field("kind", "string", stringBytes(1, 64)), field("uri", "string", stringBytes(1, 2048))], [0, 16]),
842
+ field("extensions", "object"), timeField("effective_from"),
843
+ ];
844
+ const ACCEPTANCE_SCHEMA = [
845
+ field("protocol_revision", "integer", integerRange(1, 3)), digestField("charter_id"),
846
+ safeIntegerField("revision_number"), digestField("revision_digest"), digestField("prev_revision_digest", false),
847
+ digestField("party_descriptor_digest"), roleField("party_role"), timeField("accepted_at"),
848
+ ];
849
+ const TERMINATION_SCHEMA = [
850
+ field("protocol_revision", "integer", integerRange(1, 3)), digestField("charter_id"),
851
+ digestField("governing_revision_digest"), digestField("party_descriptor_digest"),
852
+ roleField("party_role"), roleField("reason_code"), timeField("effective_at"), timeField("issued_at"), digestField("detail_digest", false),
853
+ ];
854
+ const RECEIPT_SCHEMA = [
855
+ field("protocol_revision", "integer", integerRange(1, 3)), digestField("charter_id"),
856
+ safeIntegerField("revision_number"), digestField("revision_digest"), roleField("issuing_party_role"), roleField("agent_party_role"), digestField("deployment_digest"),
857
+ nestedField("grant", "object", [field("scheme", "string", oneOf("bap", "host")), field("id", "string", stringBytes(1, 512)), digestField("grant_digest", false)]),
858
+ field("invocation_id", "string", stringBytes(1, 512)), field("decision", "string", oneOf("accepted", "rejected")),
859
+ field("outcome", "string", oneOf("effect_committed", "no_effect", "indeterminate")),
860
+ timeField("occurred_at"), timeField("recorded_at"), field("extensions", "object"),
861
+ ];
862
+ const INDEXED_CURRENCIES = new Set("AED AFN ALL AMD AOA ARS AUD AWG AZN BAM BBD BDT BHD BIF BMD BND BOB BOV BRL BSD BTN BWP BYN BZD CAD CDF CHE CHF CHW CLF CLP CNY COP COU CRC CUP CVE CZK DJF DKK DOP DZD EGP ERN ETB EUR FJD FKP GBP GEL GHS GIP GMD GNF GTQ GYD HKD HNL HTG HUF IDR ILS INR IQD IRR ISK JMD JOD JPY KES KGS KHR KMF KPW KRW KWD KYD KZT LAK LBP LKR LRD LSL LYD MAD MDL MGA MKD MMK MNT MOP MRU MUR MVR MWK MXN MXV MYR MZN NAD NGN NIO NOK NPR NZD OMR PAB PEN PGK PHP PKR PLN PYG QAR RON RSD RUB RWF SAR SBD SCR SDG SEK SGD SHP SLE SOS SRD SSP STN SVC SYP SZL THB TJS TMT TND TOP TRY TTD TWD TZS UAH UGX USD USN UYI UYU UYW UZS VED VES VND VUV WST XAD XAF XAG XAU XBA XBB XBC XBD XCD XCG XDR XOF XPD XPF XPT XSU XTS XUA XXX YER ZAR ZMW ZWG".split(" "));
863
+ const INDEXED_TERMS_SCHEMA = [
864
+ field("currency", "string", (v) => INDEXED_CURRENCIES.has(v)),
865
+ field("base_amount_minor", "integer", integerRange(0, Number.MAX_SAFE_INTEGER)),
866
+ nestedField("index", "object", [digestField("series_document_digest"), field("series_id", "string", stringBytes(1, 128)), field("observation_lag_days", "integer", integerRange(0, 90))]),
867
+ field("formula", "string", oneOf("index_plus_spread")),
868
+ field("spread_bps", "integer", integerRange(-10000, 10000)),
869
+ field("floor_amount_minor", "integer", integerRange(0, Number.MAX_SAFE_INTEGER), false),
870
+ field("cap_amount_minor", "integer", integerRange(0, Number.MAX_SAFE_INTEGER), false),
871
+ field("tolerance_bps", "integer", integerRange(0, 10000)),
872
+ ];
873
+ const INDEXED_OBSERVATION_SCHEMA = [
874
+ digestField("observed_index_digest"), field("observation_instant", "string", (v) => parseTimestamp(v) !== null),
875
+ field("computed_amount_minor", "integer", integerRange(0, Number.MAX_SAFE_INTEGER)),
876
+ ];
877
+ function indexedBodyError(namespace, body) {
878
+ const shape = schemaError(body, namespace === "com.example/pricing-indexed" ? INDEXED_TERMS_SCHEMA : INDEXED_OBSERVATION_SCHEMA);
879
+ if (shape)
880
+ return shape;
881
+ const values = body;
882
+ if (namespace === "com.example/pricing-indexed" && values.floor_amount_minor !== undefined && values.cap_amount_minor !== undefined && values.floor_amount_minor > values.cap_amount_minor)
883
+ return "cross_field_invalid";
884
+ return null;
885
+ }
886
+ function extensionError(envelope, surface) {
887
+ if (!isRecord(envelope))
888
+ return "invalid_type";
889
+ if (!exactKeys(envelope, ["critical", "optional"]) || !isRecord(envelope.critical) || !isRecord(envelope.optional))
890
+ return "unknown_member";
891
+ const names = [...Object.keys(envelope.critical), ...Object.keys(envelope.optional)];
892
+ if (names.some((namespace) => !stringBytes(1, 512)(namespace) || !/^[a-z0-9][a-z0-9.-]*\/[a-z0-9][a-z0-9.-]*$/.test(namespace)))
893
+ return "extension_namespace_invalid";
894
+ if (new Set(names).size !== names.length)
895
+ return "extension_duplicate";
896
+ if (names.length > 32)
897
+ return "cardinality_violation";
898
+ for (const position of ["critical", "optional"]) {
899
+ for (const namespace of Object.keys(envelope[position])) {
900
+ const entry = EXTENSION_PROFILES.find((profile) => profile.namespace === namespace);
901
+ if (!entry || entry.state === "reserved" || entry.state === "retired") {
902
+ if (position === "optional")
903
+ continue;
904
+ return entry?.state === "retired" ? "extension_retired" : "extension_unknown_critical";
905
+ }
906
+ if (entry.criticality !== position)
907
+ return "extension_criticality_conflict";
908
+ if (entry.surface !== surface)
909
+ return "extension_scope_invalid";
910
+ if (entry.schema_digest === null)
911
+ return "extension_schema_unavailable";
912
+ const body = indexedBodyError(namespace, envelope[position][namespace]);
913
+ if (body)
914
+ return body;
915
+ }
670
916
  }
671
- if (!value || typeof value !== "object" || Array.isArray(value))
917
+ return null;
918
+ }
919
+ function validTaggedDigest(value) {
920
+ return digestPattern(value) && strictBase64url(value.slice(8)).ok;
921
+ }
922
+ function revisionFromText(text, limits = DEFAULT_LIMITS) {
923
+ if (typeof text !== "string")
924
+ return fail("invalid_type");
925
+ const decoded = decodeJsonText(text, limits);
926
+ if (!decoded.ok)
927
+ return decoded;
928
+ const encoding = canonicalTextError(decoded.value, text);
929
+ if (encoding)
930
+ return fail(encoding);
931
+ const value = decoded.value;
932
+ const shape = schemaError(value, REVISION_SCHEMA);
933
+ if (shape)
934
+ return fail(shape);
935
+ const digests = [value.charter_id, value.prev_revision_digest, value.legal_text.content_digest, value.attribution_declaration.detail_digest, ...value.parties.map((party) => party.party_descriptor_digest)].filter((v) => v !== undefined);
936
+ if (digests.some((v) => !validTaggedDigest(v)))
672
937
  return fail("revision_invalid");
673
- const unknown = Object.keys(value).find((key) => !REVISION_FIELDS.includes(key));
674
- if (unknown)
675
- return fail("unknown_member");
676
- const missing = REVISION_REQUIRED.find((key) => !(key in value));
677
- if (missing)
678
- return fail("missing_required");
679
- if (!Array.isArray(value.parties) || new Set(value.parties.map((one) => one.role)).size !== value.parties.length)
938
+ const from = parseTimestamp(value.effective_from);
939
+ const until = value.effective_until === undefined ? null : parseTimestamp(value.effective_until);
940
+ if (!from || (value.effective_until !== undefined && !until))
941
+ return fail("timestamp_invalid");
942
+ const reasons = value.termination_rules.reason_codes;
943
+ if (reasons.some((v) => typeof v !== "string" || !stringBytes(1, 128)(v)) || new Set(reasons).size !== reasons.length)
680
944
  return fail("revision_invalid");
681
- if (!Array.isArray(value.termination_rules.reason_codes) || value.termination_rules.reason_codes.length === 0)
682
- return fail("nested_invalid");
683
- if (value.revision_number === 1 && (value.supersedes !== undefined || value.prev_revision_digest !== undefined || value.charter_id !== undefined))
945
+ if (value.abp_bindings.some((binding) => !validTaggedDigest(binding.content_digest) || !validTaggedDigest(binding.deployment_digest)))
684
946
  return fail("revision_invalid");
685
- if (value.supersedes !== undefined && (!Array.isArray(value.supersedes) || value.supersedes.some((one) => typeof one !== "string")))
947
+ const supersedes = value.supersedes ?? [];
948
+ if (supersedes.some((v) => typeof v !== "string" || !validTaggedDigest(v)) || new Set(supersedes).size !== supersedes.length)
949
+ return fail("revision_invalid");
950
+ const extensions = extensionError(value.extensions, "charter_revision");
951
+ if (extensions)
952
+ return fail(extensions);
953
+ if (!EXTENSION_PROFILES.some((profile) => profile.namespace === value.receipt_profile && profile.surface === "receipt" && profile.state === "active" && profile.criticality === "optional"))
954
+ return fail("revision_invalid");
955
+ if (value.revision_number === 1 ? (value.charter_id !== undefined || value.prev_revision_digest !== undefined || supersedes.length !== 0) : (value.charter_id === undefined || value.prev_revision_digest === undefined))
956
+ return fail("revision_invalid");
957
+ if (until && compareTimestamps(from, until) >= 0)
958
+ return fail("revision_invalid");
959
+ const roles = value.parties.map((party) => party.role);
960
+ if (new Set(value.parties.map((party) => party.party_descriptor_digest)).size !== value.parties.length)
961
+ return fail("revision_invalid");
962
+ if (new Set(roles).size !== roles.length || value.abp_bindings.some((binding) => !roles.includes(binding.party_role)))
686
963
  return fail("revision_invalid");
687
- const critical = value.extensions?.critical || {};
688
- const optional = value.extensions?.optional || {};
689
- const names = [...Object.keys(critical), ...Object.keys(optional)];
690
- if (names.some((namespace) => Buffer.byteLength(namespace) > 512 || !/^[a-z0-9][a-z0-9.-]*\/[a-z0-9][a-z0-9.-]*$/.test(namespace))) {
691
- return fail("extension_namespace_invalid");
692
- }
693
- if (new Set(names).size !== names.length)
694
- return fail("extension_duplicate");
695
- for (const namespace of Object.keys(critical)) {
696
- const profile = EXTENSION_PROFILES.find((entry) => entry.namespace === namespace);
697
- if (!profile || profile.state === "reserved")
698
- return fail("extension_unknown_critical");
699
- if (profile.state === "retired")
700
- return fail("extension_retired");
701
- if (profile.criticality !== "critical")
702
- return fail("extension_criticality_conflict");
703
- if (profile.surface !== "charter_revision")
704
- return fail("extension_scope_invalid");
705
- if (profile.schema_digest === null)
706
- return fail("extension_schema_unavailable");
707
- if (namespace === "com.example/pricing-indexed" && critical[namespace]?.formula !== "index_plus_spread")
708
- return fail("constraint_violation");
709
- }
710
- for (const namespace of Object.keys(optional)) {
711
- const profile = EXTENSION_PROFILES.find((entry) => entry.namespace === namespace);
712
- if (!profile || profile.state === "reserved" || profile.state === "retired")
713
- continue;
714
- if (profile.surface !== "charter_revision")
715
- return fail("extension_scope_invalid");
716
- if (profile.schema_digest === null)
717
- return fail("extension_schema_unavailable");
718
- }
719
964
  const bytes = Buffer.from(text);
720
- return ok({ value, bytes, digest: taggedHash("charter_revision_content", bytes) });
965
+ return ok(factsRecord({ value, bytes, digest: taggedHash("charter_revision_content", bytes), protocol_revision: value.protocol_revision }));
721
966
  }
722
- function acceptanceFromCompact(compact, revision, chain) {
723
- const decoded = decodeJws(compact);
967
+ function acceptanceFromCompact(compact, revision, chain, settings = DEFAULT_SETTINGS) {
968
+ const decoded = decodeJws(compact, settings.limits, "cap+acceptance");
724
969
  if (!decoded.ok)
725
970
  return decoded;
726
971
  const claims = decoded.value.payload;
@@ -728,31 +973,47 @@ function acceptanceFromCompact(compact, revision, chain) {
728
973
  if (acceptanceShape)
729
974
  return fail(acceptanceShape);
730
975
  const descriptor = chain.descriptors.find((one) => one.digest === claims.party_descriptor_digest);
731
- if (!descriptor || !verifyDecodedJws(decoded.value, "cap+acceptance", descriptor.payload.verification_keys))
732
- return fail("signature_invalid");
733
976
  const expectedCharter = revision.value.charter_id || revision.digest;
734
977
  const party = revision.value.parties.find((one) => one.party_descriptor_digest === claims.party_descriptor_digest);
735
978
  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);
736
979
  if (mismatch)
737
980
  return fail("acceptance_claims_mismatch");
738
- return ok({ claims, digest: taggedHash("acceptance_content", decoded.value.payloadBytes), descriptorPosition: chain.positions[claims.party_descriptor_digest] });
739
- }
740
- function terminationFromCompact(compact, revision, chain) {
741
- const decoded = decodeJws(compact);
981
+ if (!descriptor)
982
+ return fail("acceptance_claims_mismatch");
983
+ const acceptanceAdmission = profileError(decoded.value.header.alg, claims.protocol_revision, settings);
984
+ if (acceptanceAdmission)
985
+ return fail(acceptanceAdmission);
986
+ if (!descriptor.payload.verification_keys.some((key) => key.key_id === decoded.value.header.kid && key.status === "active"))
987
+ return fail("acceptance_invalid");
988
+ const signature = verifyDecodedJws(decoded.value, "cap+acceptance", descriptor.payload.verification_keys, settings);
989
+ if (!signature.ok)
990
+ return signature;
991
+ return ok(factsRecord({ claims, digest: taggedHash("acceptance_content", decoded.value.payloadBytes), descriptorPosition: chain.positions[claims.party_descriptor_digest], protocol_revision: claims.protocol_revision, alg: decoded.value.header.alg }));
992
+ }
993
+ function terminationFromCompact(compact, revision, chain, settings = DEFAULT_SETTINGS) {
994
+ const decoded = decodeJws(compact, settings.limits, "cap+termination");
742
995
  if (!decoded.ok)
743
996
  return decoded;
744
997
  const claims = decoded.value.payload;
998
+ const terminationShape = terminationClaimsError(claims);
999
+ if (terminationShape)
1000
+ return fail(terminationShape);
745
1001
  const descriptor = chain.descriptors.find((one) => one.digest === claims.party_descriptor_digest);
746
- if (!descriptor || !verifyDecodedJws(decoded.value, "cap+termination", descriptor.payload.verification_keys))
747
- return fail("signature_invalid");
748
1002
  const expectedCharter = revision.value.charter_id || revision.digest;
749
1003
  const party = revision.value.parties.find((one) => one.party_descriptor_digest === claims.party_descriptor_digest);
750
1004
  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))
751
1005
  return fail("termination_claims_mismatch");
752
- const terminationShape = terminationClaimsError(claims);
753
- if (terminationShape)
754
- return fail(terminationShape);
755
- return ok({ claims, digest: taggedHash("termination_content", decoded.value.payloadBytes), descriptorPosition: chain.positions[claims.party_descriptor_digest] });
1006
+ if (!descriptor)
1007
+ return fail("termination_claims_mismatch");
1008
+ const terminationAdmission = profileError(decoded.value.header.alg, claims.protocol_revision, settings);
1009
+ if (terminationAdmission)
1010
+ return fail(terminationAdmission);
1011
+ if (!descriptor.payload.verification_keys.some((key) => key.key_id === decoded.value.header.kid && key.status === "active"))
1012
+ return fail("termination_invalid");
1013
+ const signature = verifyDecodedJws(decoded.value, "cap+termination", descriptor.payload.verification_keys, settings);
1014
+ if (!signature.ok)
1015
+ return signature;
1016
+ return ok(factsRecord({ claims, digest: taggedHash("termination_content", decoded.value.payloadBytes), descriptorPosition: chain.positions[claims.party_descriptor_digest], protocol_revision: claims.protocol_revision, alg: decoded.value.header.alg }));
756
1017
  }
757
1018
  // Chain-level structural checks mirroring Chain.verify: unique revision
758
1019
  // digests, exactly one genesis defining one charter identity, exact
@@ -784,7 +1045,7 @@ const KNOWN_ANSWERS = {
784
1045
  signature: "j-2qiavUPiB8LInhWxrc6J9StRzbPMtqB3qR44jMgb4bWaL1DNGlFx9C8EVuJivnvwC1zTmTbVwiJOTyskFgO_pUdaOtx0CNtTn3-zrTnoKO9aLNFYebPtij4oXt1BlIZWH9pIlELIUYBk3jjWaZWF0L8nq99J2_Khz7N_lp7n5WXjLJY4f3YQlUp-DOolf3ZuCIvP9A43st0OCK3CRlR8FWK3ODu_RUq-TYRRCDJ-1NBVU7fzGwICnjzp5HrDWHHXXwML2fgbUtWUul4bn8DquFtuibqSy8pejuWyZ7XfOr8RXPbkLgBBVum-SUzD--I35CeI9Q9itRosyuYjyZLQxJici_U3YUW3KmRolIiq1egZQwZCiN9U6Rw5NxqCJZdq5rvxS_DpmHNZrGf2WPKRjTgoW4hOdSqsJjnAHS49b7zOBeJiN_tJQeyz5ENEW_tmjPcfGGnIkKSR5rMpz5qZ-IEQNVstiAmHZBKTw_Um2_nSL10n40JhU67OUyjbb3A4PbBQTXesQlagkLaQD5KapPLfsadKfL299wsGvHKFfBw4zHcoZ_L878ceWVBKaGO0dlzUr6f2xrGG7n2Ck3Duyimz2BVGzWbUUsDk8AZwHJpuw_vQ8yKzusQUabOkX7j5ml03wDe9UVaW6MoZSghs_P5xuSokmhkpUFGxvgEvhCy9lMt97atPZBkpk_czeMaRbXy6f0Divr4ZVNKGOZxh67nszIPhzFeaLCz03MHm-KK6wHL2BKCCatGf6qEI7pOUywCSsRY7eyTLGinChHvwKLwd__87sOjrWAbB9-o5Cqgr7sauFwxJTdgBjOdWwFkiu9mq-Ulm8HuGXZr5CIMr1Kmq5PXAoIw4SBdrYs1Sbzp6GFcMOrttC4v4QDEnGUiZ47QnJrSVlzVXzPaE28hy3mMHgc7_8t_L1bgPrPr8GfYKsGyUcA0455FuLMonGC_Avbxxt-RbdUxoJlT0dWYOHAXWYXMHxaTbM83FmQi0wqs8miwQ090TCrhbVp69D-XfEBjTk8ghW6zM76KRrSQdG3dNHxN841zzOYY2OI4hgcsIOfB17EE-WbgHX_FRZubkKIbmcHvr0i3Ac78fr2Aojj4Cgk8wPp_s5Xg09R3Ta-H0qxlTwEpjDctyhAZhIhXsTN2lGHi67LE6Zi_RxMJUZCXH1BBzDlEnRAQy1_vkiQFYMquE0spBRzrZHwVCAwVwPNDE8rY4X0eoo4wrCcpUb9S7D8AFiVbFdjgaCdprJTbIUccascWKmvrKy9A4UHhlnuT2tnyjOKMETj_LafMgrGhOuhb9wAn0EpurT3-XKSY89GdLOa4Y1ORGXKM0PymYyzff1W26HOXO19oh2SP0ANMzQcC8Oea58ksvtJ2hAOTCyfVP1Ao_Sz3VIbOAF65Vvi3NRDBtRyx8atM3dL-T22AfhVMcD-fRpPuGw36k3T_h1EZ52-3XRuw93ykhsjSzZcgSJs9GWHIjBmzY5M0iAmi-L6xO7HoPYDj-9TJNasniOPXLbcdRPrdcbqL0jcslch6PGRQOQvkBsWcXLC1rdY4FFPz-PVbJ7gDArpmdviRwjVUEiUXFMHHsDmlUjPtUYfodbXdJDeFCTgwTwLADsJzUVxSC_8FW-B1UlTHGeVUu9O72GwiMWnA4sj0ddD2Z4Rsg78WXKrC8Sjfl1Ozw3MpFj5pWadCnrQmm2LFYUC1Km1uwPgWqPel-MvXJBiMIVTJkgT_5ASNGPXWXSeQqyCq1f-KhcY1wD_0or77TDBQkdbp4G0DqszWKKilPAmUSX1ak0ZkNh-7Oa984na4YgvXhZFsOQXU35kvgPXeHs4FYDYN39V807zM_6FlwMF7RBMBq9900RvNpLUEZS64ecvG_q0Wp91U0LNcmdSvXBxS040K2inHBoWWNrVODhFN51houdCh6Z59LjGJNcCJPvYRTX9susKPaNuBWRymvMqMa3NVjXNd0jJKrov06DJsRS4J3Qapql6s6KvjUwq0Dff5cPgMuTk6oW-SPETdbnqPs_8BqrYP6pClgBSNfAqt2FeaLLdT4SCW6j_nLZS9RTWpTV9Qf45MUJdKeYsQSb1cQ9_V7AEyCRRuaNJKKDPfYoU1FBfROTCHt2UyiSA2BStpRa9iRM0YHgSZVYYBpDLV9EF6WDJI7ishp3VDT3lmJed4R5hUbwnsgKh4zmjcapkllUxWs3S7zpBPtvbeVqOvywBovC5Rc01_K12eU45C7DKRMA0JTQxuFer1ZKq-IX0W1VfTo3oSAIhTk41PbgdJiVdUa2eN5YgaIwRwoR83JU1J-9WcsnKZ0vnH-kveePVdpOnLoZtF6gP4gLLMAy88KHoBFbtLsq7VFkiV-6HYWQYpdpnoTJflJ-E6NLq-stDf-eWHYsYw_uzU2vwAHQv5VZ8Be0ASWBrEpqeeVwfwVcAVne8WB-qJro7YEScBRd7o3GKIZA5DmClYtyQ46HUgcSQe-SBWrxE2PHP5KaZrljLqb28y8oDYaKtFXjAukKIibESHtE_106Hk8F1vUbkio_N3v2vHrpLc1CFauuxPoJZq70odCljjW7vDsl1qvelYaiFWF1yElCI9UxYUl8o0s-7EuiJgRLJQRw2AmLed9dlYBeFXnPrZBQw48ceoCLi0UuRS1MT78SC7YQzsgLHCqfsAiYuuDYlb8uIH3XTKvYYCRQMSdDQdHoCbUrEQGbF1mMarDDpHCwHCIWzbqLp9K_Rkwm2_QU91KhZlEGXyR-hhOV828atC-mTUM10XcrrOPt8zcyyu86uErMDgSNKFVd5Qx1H7z6ZOMWeI5QMJHOqih7Go-fwTWZWkIbk7h97Y98Ii3i7-Z3Ov2UHNjk02Dh6pQmAr2fvKZN5gz-nX8-raVgKQt3Du63cE6pPbb4BrcbwoL20X5hw8haQVhh6A-k0eZdPpSzR7RacpVZOKeuhDbzD6JMXM6CBmtyObvqGO7fcTeQNNm7OGyiAVY7HcZufSkXDA0Q8tZr8VftOFeYjGNaRBvDs6yTepx4JRSwtKbCfU-n5CHUHXSQzf1EKdnvfQOSUkvLA_cYr4hTIp9yRSexo49PYSZy6-HbTwI5vOO03M2jNmm1BqKI3WxzO6BmNtCFOsjC3bfjF2Ccgjt4uAoX2Vtp3amwR8h6EHe0wDgcQnC5nQWYEBXgVTPwVivOXLZaoyF1PtLBhOygsTyFUUNvsL1fJ05PyfLgbrCJgeZKZCB6wtLiZEAHC_umNh-go91Ig4sW7mM5F1xfiSHWfpnI12EFyUL8muqgjtjiPEvXjTtQzJDZ8zKuYZJ_q8C4oWGTFlU_dVJmzR3xBeLKwqIMqKgfUko73WjEYIalD6hFkUExhdkRQ2c7VPF2iz_3b11O4aK_wlrfOk9hpfmg7AOo-fJ8yOaHTn1rymp33osZ_bRWYmRnfSIMPFaTO7miRrInp2tXWkWrYXFOlIVFtuz-lR52cx-ukm9rPrAhKxohAZ1y9RowhmjPgI55t7L2Y-9i0K1ujjx-T2LRCOPZMpRBwIPDtFP65yCe0xS824g1vxnrzwBI82RsoutcMx7hYNnLoShqwp-rV-SAMOtQtb2euo2e5HPnP7esD5JnBjal2d_p5Mhnk0AOcZrYaF2MsAgGnPFSPLYsN00dlncP75kJ8m7x4f6bI13QvRRzeYDcftLuMcOtJxvQz6gTkQd0kSGGbPrAMJYnr1kPi_pOxLULV3bwyCs_zS-KMwkAAx9EsaGFvBKU3I9twipP52sJlw8cEN9NYLy5zREbpCRZMYluXlpUi3ArT4ql-sTh8unsNA6stT_tdJhS1SL-7gyT5g0KIWV_We2gEs5LFxaQpmNqKiUeIH-qXw8nMJqjqmvCi16nMh4DdzFHvtFHzeIS5PrzHw8k5XutgyfMkqiEvaBZfWNj0ayklwWoin-5ng9WpvjITN5A4TZzkERUTFh74qTofUMbk8xrNOdOv_d4rqETZHVhsHHcflnDTk7ARMiw8oJBVMD6qY5m1Oelt5fVgoVdGlJGiDK2Szv8jErmmCgGzrt771KLIkYJ3o0Og84rOdBVL4gj6XjoM7T3UvAI99LC69QVN7tU6oHK7QTzH1JYqdZdsZKwCAqzOY6unEBiiQUF8hM84SSLb7WJWDWqfKA5J7qXVooWGiwelFAnPyabcXxuEVK9STQCx7BGxlBjN6CVCyfJf5tjdXtgGrjBdYd44BsAq6pesLGNNh3p6rnfFy93vBhBaEWIlfQLI5c1DsFqeSrvFzNf8vTEBvlY3rdGn7sf41QAj-YNqIePeyQB5rLSRo7Y7Kxw7h4bC8paIg4EC8KGT7L-PjXcLDFfIQ3HJXBtngXgtSGhSK8yrTDyPxHrIvUs3mJKs0M_5hKFsbo0oSpGLBBAEYnAreh-elu4o0YCdRgSXo3ZFlu2HR2kGvaxs-0UOdH8F0IqxEIvy5GAAvjYVSMQI-6jR48QZAOk6CqJ7earG30_IVWq9OhhtFHN3zmddnfYGIlF-t253LDxqQ1VsncwtvaogKe-09_1V93s1UBM9dax8xBzmth8KKMpUQAqUbVn7mUr1bEFwGtcqLZZQ_L7l0rLYDE0gwFQKi951wQxkG9ERYp3YHksyOy1yNpuMtvdMtWgiS5mur-i2GGPHgjrN2vRCbrC3AkB_6sJmE9hvx3aSqsBNnlbKAtE2pmokWqr1aL8jCcfg7-5mr0fe2bJfKSWJXYdynwSBc08h2RfS43UkPlrn6dFBZdJk2auRuP3kxwFe-UaXAaQW-n3cA3hUqIGROnEmkpWj19Rb-u_T-eY5Ra0tZ_dg3Fq5aQsXthvOdktH8MxZ3MNWIG0fsL_VbHje_KW2fOLz0vSZnzGNa4V2xL3NjwRqBolto85T3AH5Ak88idXytIbnwD-IqMWoL2Fywr22M-Wp481HPHlCsVUj6IutIuSaDcX2_Hkytg4jjVU8eTnemMneB1NzL2eOlWphv-T062KwBnqLZabzpGjBURD-NcysF_9Taw52f_ue49hdvIZ3bXVSwQFotcTQmZ7mXtBGI3RRe3cZzt-8hJV99T-7PQ4q1UxViYpANPPHzBgxWGHMkPnoIObb6qz1GEaFDGGwywwyoYlnUB0rkmFCCv1ySWd1jVZrqltojW4aTjJmk_GeSGcEDza0-80nZROjCALgJBOCzZkOJOxnxK0sTduenwg5hvUBxVkx0k6VlaysboxmwTTg-cLDRPFdxoWDC1LN0foC55TP6JHROrBu7R5HsxtrshorWfMrEcZshvvrGBVNngVVYAFsVdzM6oC62i7HO7l4RhC-fXOipxPikMHflFVv6l5FDeaqxij7Cs-dH5xI1RULaKRMLNRb15Y2haRZpd8GmzgjvmOVYNcEKP8GDgh4Z7Z5TZpo_iUsM3s60zgBVyP7f5mR4xjTVo6egji5UjDcCusEVG8xEaezpuschogoRt6XRUuwFI8az6wqmFzoIz8GLbkvRYwp5vSyFLpg71xWB4JZSfqc-8OxWelhSt4dqJGZHSNh-VpiDDjnuLRZds2nVASDOk0f_8p2JO-UCHvtT5I_rP2ZFEVvzr0MIPt7x1SBVsiqRX17_h8XsvrGI0PDY0geoLtfP_3ZPF2PQ4MhsujUUKb7wc180S5TuKTLJeKa-WRu5s1oV4HviSDcd3-EWIYX0rJSdS0pSMQHTTm1BubGGXCjvoulSRNlKHnA4JjjiWTXrvkszmBC5ekHwr_AFwdy4UWXQ-XHhX99bDWOO5xSEnggqGIIriMYS2uhGpyOfDhaI4D7RM6PCheKpt7XwsTQDDJNc-OSwH_NoSxeaPMLtnew-KgT0_VGRtlvQPWn1o5NkaeKs3CUjW260yCsCHoVArVTeAsOSCtpTTtxyKRgHCPJ3VA1fNIpXGBPPeQgv30DHTMpHpsr-zsPNZ5PU7TlQb3AUI-UnP_0XLSY5-UyMKRPeGgf2fo8agKKbhIbRlcRRzfWPd3bSaNpdZ2AI-bbprJEnwkgbM4A0p7wBXuLHzhS4rC24QMQj92dxBrqzUmZfL-Ihj--5dgcvQqVZIq-9mMCYuhZZt4NHSidqLLoCRchOTuFqsno8iw3Ro-W7jVyAxMgMnmCzdHS8_gOGhwmlekEMEbE3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADChQaHCctMg",
785
1046
  },
786
1047
  };
787
- function katVerifies(keyAlgorithm) {
1048
+ function katVerifies(keyAlgorithm, message = KNOWN_ANSWER_MESSAGE) {
788
1049
  const vector = KNOWN_ANSWERS[keyAlgorithm];
789
1050
  if (!vector)
790
1051
  return false;
@@ -797,13 +1058,44 @@ function katVerifies(keyAlgorithm) {
797
1058
  Buffer.from(vector.publicKey, "base64url"),
798
1059
  ]);
799
1060
  const key = createPublicKey({ key: spki, format: "der", type: "spki" });
800
- return nodeVerifySignature(null, KNOWN_ANSWER_MESSAGE, key, signature);
1061
+ return nodeVerifySignature(null, message, key, signature);
801
1062
  }
802
1063
  catch (_error) {
803
1064
  return false;
804
1065
  }
805
1066
  }
806
- return mldsa(keyAlgorithm, vector.publicKey, KNOWN_ANSWER_MESSAGE, signature);
1067
+ return mldsa(keyAlgorithm, vector.publicKey, message, signature);
1068
+ }
1069
+ // The known-answer signature over any other message must fail: a runtime
1070
+ // whose verify accepts everything is never counted as supporting a key type.
1071
+ const KNOWN_ANSWER_TAMPERED = Buffer.from("charter-agreement-protocol capability known-answer, tampered");
1072
+ // Importing an algorithm-specific SPKI asks the runtime whether it knows
1073
+ // that key type without running a signature vector. This works on Node 24.8
1074
+ // as well as runtimes that support the ML-DSA key types. A runtime whose key
1075
+ // objects do not report their type (Bun's ML-DSA keys, for example) is asked
1076
+ // once through the known-answer vector instead, and the answer is kept. A
1077
+ // provider failure during the real crypto call is classified by the selected
1078
+ // vector only.
1079
+ const UNTYPED_KEY_SUPPORT = new Map();
1080
+ function runtimeSupportsAlgorithm(keyAlgorithm) {
1081
+ const vector = KNOWN_ANSWERS[keyAlgorithm];
1082
+ if (!vector)
1083
+ return false;
1084
+ const prefix = keyAlgorithm === "Ed25519" ? Buffer.from("302a300506032b6570032100", "hex") : ML_DSA_SPKI_PREFIXES[keyAlgorithm];
1085
+ try {
1086
+ const key = createPublicKey({ key: Buffer.concat([prefix, Buffer.from(vector.publicKey, "base64url")]), format: "der", type: "spki" });
1087
+ if (key.asymmetricKeyType !== undefined)
1088
+ return key.asymmetricKeyType === keyAlgorithm.toLowerCase();
1089
+ }
1090
+ catch (_error) {
1091
+ return false;
1092
+ }
1093
+ const known = UNTYPED_KEY_SUPPORT.get(keyAlgorithm);
1094
+ if (known !== undefined)
1095
+ return known;
1096
+ const supported = katVerifies(keyAlgorithm) && !katVerifies(keyAlgorithm, KNOWN_ANSWER_TAMPERED);
1097
+ UNTYPED_KEY_SUPPORT.set(keyAlgorithm, supported);
1098
+ return supported;
807
1099
  }
808
1100
  export function capabilities() {
809
1101
  const algorithms = ALG_ROWS.map((row) => ({
@@ -811,7 +1103,9 @@ export function capabilities() {
811
1103
  keyAlgorithm: row.keyAlgorithm,
812
1104
  verifiable: katVerifies(row.keyAlgorithm),
813
1105
  }));
814
- return { linkedCrypto: process.versions.openssl ?? "", algorithms };
1106
+ // A browser page has no `process`; it then reports no linked library.
1107
+ const versions = typeof process === "undefined" ? undefined : process.versions;
1108
+ return { linkedCrypto: versions?.openssl ?? "", algorithms };
815
1109
  }
816
1110
  // The signature registry's published identity, mirroring the reference
817
1111
  // Algorithm.registry_digest/0 byte for byte: the canonical object of every
@@ -863,76 +1157,75 @@ function parseProfile(spec) {
863
1157
  }
864
1158
  return { ok: true, algorithms, minRevision, maxRevision };
865
1159
  }
866
- // "ok" | "algorithm" | "revision" | "invalid_type" | "invalid_profile" |
867
- // "decode": the admission walk mirrors the reference Chain.verify STAGE
868
- // order (descriptors, then revisions, then acceptances and terminations),
869
- // so a view whose defects are in different stages reports the same stage
870
- // in both implementations. Within one stage, admission defects are
871
- // decided before signature work here exactly as there. A view with BOTH a
872
- // structural defect and an admission defect in the SAME stage may differ
873
- // (this mirror reports the admission code; the reference reports the
874
- // structural one) — no certified corpus case carries that shape.
875
- function admitView(input) {
876
- const profile = parseProfile(input.profile);
1160
+ const DEFAULT_SETTINGS = { limits: DEFAULT_LIMITS, profile: { algorithms: ALG_ROWS.map((row) => row.name), minRevision: 1, maxRevision: 3 } };
1161
+ function resolveOptions(options = {}) {
1162
+ if (!isRecord(options) || (options.limits !== undefined && !validLimits(options.limits)))
1163
+ return fail("invalid_limits");
1164
+ if (options.profile !== undefined && (!isRecord(options.profile) || Object.keys(options.profile).some((key) => key !== "algorithms" && key !== "revisions")))
1165
+ return fail("invalid_profile");
1166
+ const profile = parseProfile(options.profile);
877
1167
  if (!profile.ok)
878
- return profile.code;
879
- const admitEnvelope = (compact) => {
880
- const decoded = decodeJws(compact);
881
- if (!decoded.ok)
882
- return "decode";
883
- const revision = decoded.value.payload.protocol_revision;
884
- if (typeof revision !== "number")
885
- return "decode";
886
- if (!profile.algorithms.includes(decoded.value.header.alg))
887
- return "algorithm";
888
- if (revision < profile.minRevision || revision > profile.maxRevision)
889
- return "revision";
890
- return "ok";
891
- };
892
- for (const compact of Array.isArray(input.descriptors) ? input.descriptors : []) {
893
- const outcome = admitEnvelope(compact);
894
- if (outcome !== "ok")
895
- return outcome;
896
- }
897
- for (const text of Array.isArray(input.revisions) ? input.revisions : []) {
898
- let parsed;
899
- try {
900
- parsed = JSON.parse(text);
901
- }
902
- catch (_error) {
903
- return "decode";
1168
+ return fail("invalid_profile");
1169
+ return ok({ limits: { ...DEFAULT_LIMITS, ...options.limits }, profile });
1170
+ }
1171
+ function profileError(alg, revision, settings) {
1172
+ if (alg !== null && !settings.profile.algorithms.includes(alg))
1173
+ return "algorithm_outside_profile";
1174
+ if (revision < settings.profile.minRevision || revision > settings.profile.maxRevision)
1175
+ return "revision_outside_profile";
1176
+ return null;
1177
+ }
1178
+ function revisionWithProfile(text, settings) {
1179
+ const revision = revisionFromText(text, settings.limits);
1180
+ if (!revision.ok)
1181
+ return revision;
1182
+ const admission = profileError(null, revision.value.value.protocol_revision, settings);
1183
+ return admission ? fail(admission) : revision;
1184
+ }
1185
+ function boundedArtifacts(lists, limits) {
1186
+ let bytes = 0;
1187
+ for (const list of lists) {
1188
+ if (!Array.isArray(list))
1189
+ return "invalid_type";
1190
+ for (let i = 0; i < list.length; i++) {
1191
+ if (i >= limits.max_artifact_set_items)
1192
+ return "limit_exceeded";
1193
+ if (typeof list[i] !== "string")
1194
+ return "invalid_type";
904
1195
  }
905
- if (typeof parsed !== "object" || parsed === null)
906
- return "decode";
907
- const revision = parsed.protocol_revision;
908
- if (typeof revision !== "number")
909
- return "decode";
910
- if (revision < profile.minRevision || revision > profile.maxRevision)
911
- return "revision";
912
- }
913
- for (const compact of [
914
- ...(Array.isArray(input.acceptances) ? input.acceptances : []),
915
- ...(Array.isArray(input.terminations) ? input.terminations : []),
916
- ]) {
917
- const outcome = admitEnvelope(compact);
918
- if (outcome !== "ok")
919
- return outcome;
920
- }
921
- return "ok";
922
- }
923
- function chainFromInput(input) {
1196
+ bytes += list.reduce((total, text) => total + Buffer.byteLength(text), 0);
1197
+ if (bytes > limits.max_artifact_set_bytes)
1198
+ return "limit_exceeded";
1199
+ }
1200
+ return null;
1201
+ }
1202
+ function chainWithOptions(input, options = {}) {
1203
+ const settings = resolveOptions(options);
1204
+ return settings.ok ? chainFromInput(input, settings.value) : settings;
1205
+ }
1206
+ function chainFromInput(input, settings = DEFAULT_SETTINGS) {
1207
+ if (!isRecord(input))
1208
+ return fail("chain_invalid");
1209
+ const bounded = boundedArtifacts([input.revisions, input.acceptances, input.descriptors, input.terminations], settings.limits);
1210
+ if (bounded)
1211
+ return fail(bounded);
924
1212
  if (!Array.isArray(input.revisions) || input.revisions.length === 0)
925
1213
  return fail("chain_invalid");
926
- const descriptors = descriptorChain(input.descriptors);
1214
+ const descriptors = descriptorViews(input.descriptors, settings);
927
1215
  if (!descriptors.ok)
928
- return fail("chain_invalid");
1216
+ return descriptors;
929
1217
  const revisions = [];
930
1218
  for (const text of input.revisions) {
931
- const revision = revisionFromText(text);
1219
+ const revision = revisionFromText(text, settings.limits);
932
1220
  if (!revision.ok)
933
- return fail("chain_invalid");
1221
+ return revision;
934
1222
  revisions.push(revision.value);
935
1223
  }
1224
+ for (const revision of revisions) {
1225
+ const admission = profileError(null, revision.value.protocol_revision, settings);
1226
+ if (admission)
1227
+ return fail(admission);
1228
+ }
936
1229
  const byDigest = new Map(revisions.map((one) => [one.digest, one]));
937
1230
  if (byDigest.size !== revisions.length)
938
1231
  return fail("chain_invalid");
@@ -958,35 +1251,37 @@ function chainFromInput(input) {
958
1251
  }
959
1252
  }
960
1253
  }
1254
+ const owners = new Map(descriptors.value.descriptors.map((one) => [one.digest, one.payload.party_id ?? one.digest]));
1255
+ const named = new Set();
1256
+ for (const revision of revisions) {
1257
+ const parties = revision.value.parties.map((party) => owners.get(party.party_descriptor_digest)).filter((id) => id !== undefined);
1258
+ if (new Set(parties).size !== parties.length)
1259
+ return fail("chain_invalid");
1260
+ for (const id of parties)
1261
+ named.add(id);
1262
+ }
1263
+ if (descriptors.value.histories.some((history) => !named.has(history.descriptors[0].payload.party_id ?? history.descriptors[0].digest)))
1264
+ return fail("chain_invalid");
961
1265
  const acceptances = [];
962
1266
  const coordinates = new Set();
963
1267
  for (const compact of (input.acceptances || [])) {
964
- const decoded = decodeJws(compact);
1268
+ const decoded = decodeJws(compact, settings.limits, "cap+acceptance");
965
1269
  if (!decoded.ok)
1270
+ return decoded;
1271
+ if (typeof decoded.value.payload.revision_digest !== "string" || typeof decoded.value.payload.party_descriptor_digest !== "string")
966
1272
  return fail("chain_invalid");
967
1273
  const revision = byDigest.get(decoded.value.payload.revision_digest);
968
- if (!revision)
1274
+ if (!revision || !descriptors.value.descriptors.some((one) => one.digest === decoded.value.payload.party_descriptor_digest))
969
1275
  return fail("chain_invalid");
970
- const verified = acceptanceFromCompact(compact, revision, descriptors.value);
1276
+ const verified = acceptanceFromCompact(compact, revision, descriptors.value, settings);
971
1277
  if (!verified.ok)
972
- return fail("chain_invalid");
1278
+ return verified;
973
1279
  const coordinate = `${verified.value.claims.revision_digest}\0${verified.value.claims.party_descriptor_digest}\0${verified.value.claims.party_role}`;
974
1280
  if (coordinates.has(coordinate))
975
1281
  return fail("chain_invalid");
976
1282
  coordinates.add(coordinate);
977
1283
  acceptances.push(verified.value);
978
1284
  }
979
- for (const compact of (input.terminations || [])) {
980
- const decoded = decodeJws(compact);
981
- if (!decoded.ok)
982
- return fail("chain_invalid");
983
- const revision = byDigest.get(decoded.value.payload.governing_revision_digest);
984
- if (!revision)
985
- return fail("chain_invalid");
986
- const verified = terminationFromCompact(compact, revision, descriptors.value);
987
- if (!verified.ok)
988
- return fail("chain_invalid");
989
- }
990
1285
  const accepted = revisions.filter((revision) => {
991
1286
  const expected = new Set(revision.value.parties.map((party) => `${party.party_descriptor_digest}\0${party.role}`));
992
1287
  const actual = new Set(acceptances
@@ -999,6 +1294,24 @@ function chainFromInput(input) {
999
1294
  return false;
1000
1295
  return true;
1001
1296
  });
1297
+ const acceptedSet = new Set(accepted.map((one) => one.digest));
1298
+ if (accepted.some((one) => (one.value.supersedes ?? []).some((digest) => !acceptedSet.has(digest))))
1299
+ return fail("chain_invalid");
1300
+ const terminations = [];
1301
+ for (const compact of (input.terminations || [])) {
1302
+ const decoded = decodeJws(compact, settings.limits, "cap+termination");
1303
+ if (!decoded.ok)
1304
+ return decoded;
1305
+ if (typeof decoded.value.payload.governing_revision_digest !== "string" || typeof decoded.value.payload.party_descriptor_digest !== "string")
1306
+ return fail("chain_invalid");
1307
+ const revision = byDigest.get(decoded.value.payload.governing_revision_digest);
1308
+ if (!revision || !descriptors.value.descriptors.some((one) => one.digest === decoded.value.payload.party_descriptor_digest))
1309
+ return fail("chain_invalid");
1310
+ const verified = terminationFromCompact(compact, revision, descriptors.value, settings);
1311
+ if (!verified.ok)
1312
+ return verified;
1313
+ terminations.push(verified.value);
1314
+ }
1002
1315
  const superseded = new Set(accepted.flatMap((one) => one.value.supersedes || []));
1003
1316
  const active = accepted.filter((one) => !superseded.has(one.digest));
1004
1317
  const maximum = Math.max(...active.map((one) => one.value.revision_number));
@@ -1022,7 +1335,7 @@ function chainFromInput(input) {
1022
1335
  };
1023
1336
  const linear = heads.length === 1 && ancestryCovers(heads[0].digest);
1024
1337
  const topology = active.length > 0 && !linear ? "forked" : "linear";
1025
- return ok({ descriptors: descriptors.value, revisions, acceptances, accepted, acceptedDigests: accepted.map((one) => one.digest).sort(), supersededDigests: [...superseded].sort(), topology, charterId });
1338
+ return ok(factsRecord({ descriptors: descriptors.value, revisions, acceptances, terminations, accepted, acceptedDigests: accepted.map((one) => one.digest).sort(), supersededDigests: [...superseded].sort(), topology, charterId }));
1026
1339
  }
1027
1340
  // Governing mirrors the reference semantics exactly: candidates are accepted,
1028
1341
  // non-superseded, and effective at the instant (start-inclusive, end-exclusive
@@ -1039,6 +1352,14 @@ function effectiveAt(revision, at) {
1039
1352
  return until !== null && compareTimestamps(at, until) < 0;
1040
1353
  }
1041
1354
  function governing(chain, at) {
1355
+ const closed = chain.terminations.some((notice) => {
1356
+ const effective = parseTimestamp(notice.claims.effective_at);
1357
+ return compareTimestamps(effective, at) <= 0 &&
1358
+ selectGoverning(chain, effective) === notice.claims.governing_revision_digest;
1359
+ });
1360
+ return closed ? "none" : selectGoverning(chain, at);
1361
+ }
1362
+ function selectGoverning(chain, at) {
1042
1363
  const applicable = chain.accepted.filter((one) => !chain.supersededDigests.includes(one.digest) && effectiveAt(one, at));
1043
1364
  if (applicable.length === 0)
1044
1365
  return "none";
@@ -1093,8 +1414,10 @@ function receiptSigningKeys(chain, claimedRevision, role) {
1093
1414
  }));
1094
1415
  return [...new Map(keys.map((key) => [canonical(key), key])).values()];
1095
1416
  }
1096
- function receiptFromCompact(compact, chain) {
1097
- const decoded = decodeJws(compact);
1417
+ function receiptFromCompact(compact, context, settings = DEFAULT_SETTINGS) {
1418
+ const revisionOnly = context.kind === "revision";
1419
+ const chain = context.kind === "chain" ? context.chain : { accepted: [context.revision], charterId: context.revision.value.charter_id || context.revision.digest };
1420
+ const decoded = decodeJws(compact, settings.limits, "cap+receipt");
1098
1421
  if (!decoded.ok)
1099
1422
  return decoded;
1100
1423
  const claims = decoded.value.payload;
@@ -1102,19 +1425,46 @@ function receiptFromCompact(compact, chain) {
1102
1425
  if (receiptShape)
1103
1426
  return fail(receiptShape);
1104
1427
  const claimedRevision = chain.accepted.find((one) => one.digest === claims.revision_digest);
1105
- const verifiedPublicKeys = new Set(receiptSigningKeys(chain, claimedRevision, claims.issuing_party_role)
1106
- .filter((key) => verifyDecodedJws(decoded.value, "cap+receipt", [key]))
1107
- .map((key) => key.public_key));
1108
- if (verifiedPublicKeys.size !== 1)
1109
- return fail("signature_invalid");
1110
1428
  const receiptTiming = receiptTimingError(claims);
1111
1429
  if (receiptTiming)
1112
1430
  return fail(receiptTiming);
1113
- const governingDigest = governing(chain, parseTimestamp(claims.occurred_at));
1431
+ const governingDigest = context.kind === "revision" ? "contested" : governing(context.chain, parseTimestamp(claims.occurred_at));
1114
1432
  const projection = projectReceipt(claims, chain, governingDigest);
1115
1433
  if (!projection.ok)
1116
1434
  return projection;
1117
- return ok({ claims, digest: taggedHash("receipt_content", decoded.value.payloadBytes), ...projection.value, optionalExtensions: Object.keys(claims.extensions?.optional || {}).sort() });
1435
+ if (revisionOnly) {
1436
+ if (!claimedRevision)
1437
+ return fail("receipt_claims_mismatch");
1438
+ const admission = profileError(decoded.value.header.alg, claims.protocol_revision, settings);
1439
+ if (admission)
1440
+ return fail(admission);
1441
+ return ok(factsRecord({ claims, digest: taggedHash("receipt_content", decoded.value.payloadBytes), ...projection.value, optionalExtensions: Object.keys(claims.extensions?.optional || {}).sort(), protocol_revision: claims.protocol_revision, alg: decoded.value.header.alg }, ["signature"]));
1442
+ }
1443
+ // The envelope is admitted before any key is looked up, so an
1444
+ // out-of-profile receipt reports the profile rejection in both context
1445
+ // forms, even when its kid names no key in the view.
1446
+ const envelopeAdmission = profileError(decoded.value.header.alg, claims.protocol_revision, settings);
1447
+ if (envelopeAdmission)
1448
+ return fail(envelopeAdmission);
1449
+ const candidates = receiptSigningKeys(context.chain, claimedRevision, claims.issuing_party_role)
1450
+ .filter((key) => key.key_id === decoded.value.header.kid && key.status === "active")
1451
+ .map((key) => ({ key, result: verifyDecodedJws(decoded.value, "cap+receipt", [key], settings) }));
1452
+ const verifiedPublicKeys = new Set(candidates.filter((one) => one.result.ok).map((one) => one.key.public_key));
1453
+ if (verifiedPublicKeys.size !== 1) {
1454
+ const diagnostic = candidates.find((one) => !one.result.ok && ["algorithm_outside_profile", "revision_outside_profile", "algorithm_unsupported_on_substrate"].includes(one.result.code));
1455
+ return fail(verifiedPublicKeys.size === 0 && diagnostic && !diagnostic.result.ok ? diagnostic.result.code : "signature_invalid");
1456
+ }
1457
+ return ok(factsRecord({ claims, digest: taggedHash("receipt_content", decoded.value.payloadBytes), ...projection.value, optionalExtensions: Object.keys(claims.extensions?.optional || {}).sort(), protocol_revision: claims.protocol_revision, alg: decoded.value.header.alg }));
1458
+ }
1459
+ function receiptWithContext(compact, context, settings) {
1460
+ if (typeof context === "string") {
1461
+ const revision = revisionWithProfile(context, settings);
1462
+ if (!revision.ok)
1463
+ return revision;
1464
+ return receiptFromCompact(compact, { kind: "revision", revision: revision.value }, settings);
1465
+ }
1466
+ const chain = chainFromInput(context, settings);
1467
+ return chain.ok ? receiptFromCompact(compact, { kind: "chain", chain: chain.value }, settings) : chain;
1118
1468
  }
1119
1469
  function execute(one) {
1120
1470
  const input = one.input;
@@ -1127,7 +1477,7 @@ function execute(one) {
1127
1477
  if (input.limits !== undefined && !validLimits(input.limits))
1128
1478
  return invalid("invalid_limits");
1129
1479
  const bytes = "text" in input ? Buffer.from(input.text) : Buffer.from(input.bytes_base64url, "base64url");
1130
- const decoded = decodeJsonBytes(bytes);
1480
+ const decoded = decodeJsonBytes(bytes, { ...DEFAULT_LIMITS, ...input.limits });
1131
1481
  if (!decoded.ok)
1132
1482
  return invalid(decoded.code);
1133
1483
  return project(jsonWithinLimits(decoded.value, bytes, input.limits), jsonProjection);
@@ -1182,8 +1532,19 @@ function execute(one) {
1182
1532
  return valid({ members });
1183
1533
  }
1184
1534
  case "party_descriptor.verify": {
1185
- const descriptor = descriptorFromCompact(input.compact);
1186
- return project(descriptor, (oneDescriptor) => ({ descriptor_digest: oneDescriptor.digest, party_id: oneDescriptor.digest, descriptor_number: oneDescriptor.payload.descriptor_number }));
1535
+ // A case may name its predecessor history, genesis first; each entry
1536
+ // verifies under the full profile against the one before it.
1537
+ let predecessor = null;
1538
+ for (const compact of (input.predecessor_compacts ?? [])) {
1539
+ const verified = verifyDescriptor(compact, predecessor);
1540
+ if (!verified.ok)
1541
+ throw new Error("corpus predecessor history does not verify");
1542
+ predecessor = verified.facts;
1543
+ }
1544
+ const verified = verifyDescriptor(input.compact, predecessor, { profile: input.profile });
1545
+ if (!verified.ok)
1546
+ return invalid(verified.code);
1547
+ return valid({ descriptor_digest: verified.facts.descriptor_digest, party_id: verified.facts.party_id, descriptor_number: verified.facts.descriptor_number });
1187
1548
  }
1188
1549
  case "descriptor_chain.verify": {
1189
1550
  const chain = descriptorChain(input.compacts);
@@ -1194,11 +1555,12 @@ function execute(one) {
1194
1555
  case "charter_revision.decode":
1195
1556
  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 } }));
1196
1557
  case "acceptance.verify": {
1197
- const revision = revisionFromText(input.revision_text);
1198
- const chain = descriptorChain(input.descriptor_compacts);
1199
- if (!revision.ok || !chain.ok)
1200
- return invalid("acceptance_invalid");
1201
- 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 }));
1558
+ // The runner calls the public function, so the corpus checks the code
1559
+ // consumers run.
1560
+ const verified = verifyAcceptance(input.compact, input.revision_text, input.descriptor_compacts, { profile: input.profile });
1561
+ if (!verified.ok)
1562
+ return invalid(verified.code);
1563
+ return valid({ acceptance_digest: verified.facts.acceptance_digest, revision_digest: verified.facts.claims.revision_digest, party_descriptor_digest: verified.facts.claims.party_descriptor_digest, descriptor_position: verified.facts.descriptor_position });
1202
1564
  }
1203
1565
  case "acceptance.equivocation": {
1204
1566
  const chain = descriptorChain(input.descriptor_compacts);
@@ -1220,40 +1582,24 @@ function execute(one) {
1220
1582
  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 });
1221
1583
  }
1222
1584
  case "termination.verify": {
1223
- const revision = revisionFromText(input.revision_text);
1224
- const chain = descriptorChain(input.descriptor_compacts);
1225
- if (!revision.ok || !chain.ok)
1226
- return invalid("termination_invalid");
1227
- 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 }));
1585
+ const verified = verifyTermination(input.compact, input.revision_text, input.descriptor_compacts, { profile: input.profile });
1586
+ if (!verified.ok)
1587
+ return invalid(verified.code);
1588
+ return valid({ termination_digest: verified.facts.termination_digest, governing_revision_digest: verified.facts.claims.governing_revision_digest, party_descriptor_digest: verified.facts.claims.party_descriptor_digest, reason_code: verified.facts.claims.reason_code, descriptor_position: verified.facts.descriptor_position });
1228
1589
  }
1229
1590
  case "chain.verify": {
1230
- const chain = chainFromInput(input);
1591
+ const chain = chainWithOptions(input, { limits: input.limits });
1231
1592
  return project(chain, (facts) => ({ charter_id: facts.charterId, topology: facts.topology, accepted_revision_digests: facts.acceptedDigests, superseded_revision_digests: facts.supersededDigests }));
1232
1593
  }
1233
1594
  case "chain.verify_profile": {
1234
- // The capability-profile mirror. The admission walk mirrors the
1235
- // reference Chain.verify STAGE order (descriptors, then revisions,
1236
- // then acceptances and terminations), so a view whose defects are in
1237
- // different stages reports the same stage in both implementations.
1238
- // Within one stage, admission defects are decided before signature
1239
- // work here exactly as there. A view with BOTH a structural defect
1240
- // and an admission defect in the SAME stage may differ (this mirror
1241
- // reports the admission code; the reference reports the structural
1242
- // one) — no certified corpus case carries that shape.
1243
- const admission = admitView(input);
1244
- if (admission === "algorithm")
1245
- return invalid("algorithm_outside_profile");
1246
- if (admission === "revision")
1247
- return invalid("revision_outside_profile");
1248
- if (admission === "invalid_type")
1249
- return invalid("invalid_type");
1250
- if (admission === "invalid_profile")
1251
- return invalid("invalid_profile");
1252
- const chain = chainFromInput(input);
1595
+ const profile = parseProfile(input.profile);
1596
+ if (!profile.ok)
1597
+ return invalid(profile.code);
1598
+ const chain = chainWithOptions(input, { profile: input.profile });
1253
1599
  return project(chain, (facts) => ({ charter_id: facts.charterId, topology: facts.topology }));
1254
1600
  }
1255
1601
  case "governing_revision": {
1256
- const chain = chainFromInput(input);
1602
+ const chain = chainWithOptions(input, { limits: input.limits });
1257
1603
  if (!chain.ok)
1258
1604
  return invalid("governing_invalid");
1259
1605
  return valid({
@@ -1264,10 +1610,10 @@ function execute(one) {
1264
1610
  });
1265
1611
  }
1266
1612
  case "receipt.verify": {
1267
- const chain = chainFromInput(input.chain);
1268
- if (!chain.ok)
1269
- return invalid("receipt_invalid");
1270
- 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 }));
1613
+ const settings = resolveOptions({ profile: input.profile });
1614
+ if (!settings.ok)
1615
+ return invalid(settings.code);
1616
+ return project(receiptWithContext(input.compact, input.revision_text ?? input.chain, settings.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 }));
1271
1617
  }
1272
1618
  default:
1273
1619
  throw new Error("unsupported surface");
@@ -1344,6 +1690,8 @@ export function reportFor(root) {
1344
1690
  const corpus = loadCorpus(root);
1345
1691
  const results = corpus.cases.map((one) => {
1346
1692
  const actual = execute(one);
1693
+ if (actual.status === "invalid" && actual.error_code === "algorithm_unsupported_on_substrate")
1694
+ throw new Error("algorithm_unsupported_on_substrate: corpus verification unavailable");
1347
1695
  return { id: one.id, surface: one.surface, agree: canonical(actual) === canonical(one.expect), expected: one.expect, actual };
1348
1696
  });
1349
1697
  const agreed = results.filter((one) => one.agree).length;
@@ -1461,7 +1809,7 @@ export function selfChecks() {
1461
1809
  if (parseTimestamp("2026-06-30T23:59:60Z") === null || parseTimestamp("2024-03-31T23:59:60Z") !== null) {
1462
1810
  throw new Error("leap-second window drifted");
1463
1811
  }
1464
- if (parseTimestamp("2026-02-30T00:00:00Z") !== null || parseTimestamp("0000-01-01T00:00:00Z") !== null) {
1812
+ if (parseTimestamp("2026-02-30T00:00:00Z") !== null || parseTimestamp("0000-01-01T00:00:00Z") === null || parseTimestamp("0000-02-29T00:00:00Z") === null) {
1465
1813
  throw new Error("calendar validation drifted");
1466
1814
  }
1467
1815
  const halfMs = parseTimestamp("2026-01-01T00:00:00.0005Z");
@@ -1502,11 +1850,14 @@ export function decodeArtifact(compact) {
1502
1850
  if (!decoded.ok)
1503
1851
  return { ok: false, code: decoded.code };
1504
1852
  const { header, payload } = decoded.value;
1505
- return { ok: true, facts: { alg: header.alg, kid: header.kid, typ: header.typ, payload } };
1853
+ return { ok: true, facts: factsRecord({ alg: header.alg, kid: header.kid, typ: header.typ, payload, protocol_revision: payload.protocol_revision }, ["signature"]) };
1506
1854
  }
1507
1855
  // Strict signature verification over exact bytes with a base64url public
1508
1856
  // key under the registry row for `alg` — the wrong-key guard primitive.
1509
- export function verifySignature(message, signature, publicKeyBase64url, alg) {
1857
+ export function verifySignature(message, signature, publicKeyBase64url, alg, options = {}) {
1858
+ const settings = resolveOptions(options);
1859
+ if (!settings.ok || !settings.value.profile.algorithms.includes(alg) || message.length > settings.value.limits.max_bytes)
1860
+ return false;
1510
1861
  const row = ALG_ROWS.find((one) => one.name === alg);
1511
1862
  if (!row)
1512
1863
  return false;
@@ -1517,68 +1868,114 @@ export function verifySignature(message, signature, publicKeyBase64url, alg) {
1517
1868
  return ed25519(publicKeyBase64url, message, signature);
1518
1869
  return mldsa(row.keyAlgorithm, publicKeyBase64url, message, signature);
1519
1870
  }
1520
- export function verifyDescriptor(compact, predecessor = null) {
1521
- const verified = descriptorFromCompact(compact, predecessor ? { digest: predecessor.digest, payload: predecessor.claims } : null);
1871
+ const PREDECESSOR_PASS_THROUGH = new Set(["algorithm_outside_profile", "revision_outside_profile", "algorithm_unsupported_on_substrate"]);
1872
+ function reverifyPredecessor(supplied, settings) {
1873
+ if (supplied === null)
1874
+ return ok(null);
1875
+ if (!isRecord(supplied) || !Array.isArray(supplied.lineage) || supplied.lineage.length === 0)
1876
+ return fail("descriptor_chain_invalid");
1877
+ let previous = null;
1878
+ for (const compact of [...supplied.lineage].reverse()) {
1879
+ if (typeof compact !== "string")
1880
+ return fail("descriptor_chain_invalid");
1881
+ const verified = descriptorFromCompact(compact, previous, settings);
1882
+ // A profile rejection, or a runtime that cannot check the signature, is
1883
+ // reported as itself, as a chain view reports it; any other failure is a
1884
+ // broken chain.
1885
+ if (!verified.ok)
1886
+ return PREDECESSOR_PASS_THROUGH.has(verified.code) ? verified : fail("descriptor_chain_invalid");
1887
+ previous = verified.value;
1888
+ }
1889
+ if (!previous || (supplied.descriptor_digest ?? supplied.digest) !== previous.digest ||
1890
+ (supplied.digest !== undefined && supplied.digest !== previous.digest))
1891
+ return fail("descriptor_chain_invalid");
1892
+ return ok(previous);
1893
+ }
1894
+ export function verifyDescriptor(compact, predecessor = null, options = {}) {
1895
+ const settings = resolveOptions(options);
1896
+ if (!settings.ok)
1897
+ return settings;
1898
+ const previous = reverifyPredecessor(predecessor, settings.value);
1899
+ if (!previous.ok)
1900
+ return previous;
1901
+ const verified = descriptorFromCompact(compact, previous.value, settings.value);
1522
1902
  if (!verified.ok)
1523
1903
  return { ok: false, code: verified.code };
1524
1904
  const one = verified.value;
1525
1905
  return {
1526
1906
  ok: true,
1527
- facts: {
1907
+ facts: factsRecord({
1528
1908
  descriptor_digest: one.digest,
1529
- party_id: one.digest,
1909
+ party_id: one.payload.party_id ?? one.digest,
1530
1910
  descriptor_number: one.payload.descriptor_number,
1911
+ lineage: [...one.lineage],
1531
1912
  protocol_revision: one.payload.protocol_revision,
1532
- },
1913
+ alg: one.header.alg,
1914
+ }),
1533
1915
  };
1534
1916
  }
1535
- export function verifyDescriptorChain(compacts) {
1536
- const verified = descriptorChain(compacts);
1917
+ export function verifyDescriptorChain(compacts, options = {}) {
1918
+ const settings = resolveOptions(options);
1919
+ if (!settings.ok)
1920
+ return settings;
1921
+ const verified = descriptorChain(compacts, settings.value);
1537
1922
  if (!verified.ok)
1538
1923
  return { ok: false, code: verified.code };
1539
1924
  return { ok: true, facts: verified.value };
1540
1925
  }
1541
- export function verifyAcceptance(compact, revisionText, descriptorCompacts) {
1542
- const revision = revisionFromText(revisionText);
1543
- const chain = descriptorChain(descriptorCompacts);
1544
- if (!revision.ok || !chain.ok)
1545
- return { ok: false, code: "acceptance_invalid" };
1546
- const verified = acceptanceFromCompact(compact, revision.value, chain.value);
1926
+ export function verifyAcceptance(compact, revisionText, descriptorCompacts, options = {}) {
1927
+ const settings = resolveOptions(options);
1928
+ if (!settings.ok)
1929
+ return settings;
1930
+ const revision = revisionWithProfile(revisionText, settings.value);
1931
+ if (!revision.ok)
1932
+ return revision;
1933
+ const chain = descriptorChain(descriptorCompacts, settings.value);
1934
+ if (!chain.ok)
1935
+ return chain;
1936
+ const verified = acceptanceFromCompact(compact, revision.value, chain.value, settings.value);
1547
1937
  if (!verified.ok)
1548
1938
  return { ok: false, code: verified.code };
1549
- return { ok: true, facts: { acceptance_digest: verified.value.digest, claims: verified.value.claims, descriptor_position: verified.value.descriptorPosition } };
1550
- }
1551
- export function verifyTermination(compact, revisionText, descriptorCompacts) {
1552
- const revision = revisionFromText(revisionText);
1553
- const chain = descriptorChain(descriptorCompacts);
1554
- if (!revision.ok || !chain.ok)
1555
- return { ok: false, code: "termination_invalid" };
1556
- const verified = terminationFromCompact(compact, revision.value, chain.value);
1939
+ return { ok: true, facts: factsRecord({ acceptance_digest: verified.value.digest, claims: verified.value.claims, descriptor_position: verified.value.descriptorPosition, protocol_revision: verified.value.protocol_revision, alg: verified.value.alg }) };
1940
+ }
1941
+ export function verifyTermination(compact, revisionText, descriptorCompacts, options = {}) {
1942
+ const settings = resolveOptions(options);
1943
+ if (!settings.ok)
1944
+ return settings;
1945
+ const revision = revisionWithProfile(revisionText, settings.value);
1946
+ if (!revision.ok)
1947
+ return revision;
1948
+ const chain = descriptorChain(descriptorCompacts, settings.value);
1949
+ if (!chain.ok)
1950
+ return chain;
1951
+ const verified = terminationFromCompact(compact, revision.value, chain.value, settings.value);
1557
1952
  if (!verified.ok)
1558
1953
  return { ok: false, code: verified.code };
1559
- return { ok: true, facts: { termination_digest: verified.value.digest, claims: verified.value.claims, descriptor_position: verified.value.descriptorPosition } };
1954
+ return { ok: true, facts: factsRecord({ termination_digest: verified.value.digest, claims: verified.value.claims, descriptor_position: verified.value.descriptorPosition, protocol_revision: verified.value.protocol_revision, alg: verified.value.alg }) };
1560
1955
  }
1561
- export function verifyChain(chainInput) {
1562
- const verified = chainFromInput(chainInput);
1956
+ export function verifyChain(chainInput, options = {}) {
1957
+ const verified = chainWithOptions(chainInput, options);
1563
1958
  if (!verified.ok)
1564
1959
  return { ok: false, code: verified.code };
1565
1960
  return { ok: true, facts: verified.value };
1566
1961
  }
1567
- export function verifyReceipt(compact, chainInput) {
1568
- const chain = chainFromInput(chainInput);
1569
- if (!chain.ok)
1570
- return { ok: false, code: "receipt_invalid" };
1571
- const verified = receiptFromCompact(compact, chain.value);
1962
+ export function verifyReceipt(compact, context, options = {}) {
1963
+ const settings = resolveOptions(options);
1964
+ if (!settings.ok)
1965
+ return settings;
1966
+ const verified = receiptWithContext(compact, context, settings.value);
1572
1967
  if (!verified.ok)
1573
1968
  return { ok: false, code: verified.code };
1574
1969
  return {
1575
1970
  ok: true,
1576
- facts: {
1971
+ facts: factsRecord({
1972
+ protocol_revision: verified.value.protocol_revision,
1973
+ alg: verified.value.alg,
1577
1974
  receipt_digest: verified.value.digest,
1578
1975
  claims: verified.value.claims,
1579
1976
  governing_match: verified.value.governingMatch,
1580
1977
  chain_conflict: verified.value.chainConflict,
1581
- },
1978
+ }, typeof context === "string" ? ["signature"] : []),
1582
1979
  };
1583
1980
  }
1584
1981
  // ---------------------------------------------------------------------------
@@ -1592,47 +1989,69 @@ export function verifyReceipt(compact, chainInput) {
1592
1989
  export function checkSigningClaims(kind, claims) {
1593
1990
  if (!claims || typeof claims !== "object" || Array.isArray(claims))
1594
1991
  return { ok: false, code: "invalid_type" };
1595
- const error = kind === "descriptor" ? descriptorClaimsError(claims) :
1992
+ const error = kind === "descriptor" ? signingDescriptorError(claims) :
1596
1993
  kind === "acceptance" ? acceptanceClaimsError(claims) :
1597
1994
  kind === "termination" ? terminationClaimsError(claims) :
1598
1995
  kind === "receipt" ? (receiptGrantError(claims) ?? receiptTimingError(claims)) :
1599
1996
  "invalid_type";
1600
1997
  return error ? { ok: false, code: error } : { ok: true };
1601
1998
  }
1999
+ // Preserve the preflight helper's existing local-code precedence.
2000
+ function signingDescriptorError(claims) {
2001
+ if (claims.descriptor_number === 1 && claims.prev_descriptor_digest !== undefined)
2002
+ return "descriptor_invalid";
2003
+ const grammar = keyGrammarError(claims);
2004
+ return grammar ?? descriptorClaimsError(claims);
2005
+ }
1602
2006
  function acceptanceClaimsError(claims) {
1603
- if ((claims.revision_number === 1) !== (claims.prev_revision_digest === undefined))
2007
+ const shape = schemaError(claims, ACCEPTANCE_SCHEMA);
2008
+ if (shape)
2009
+ return shape;
2010
+ if ([claims.charter_id, claims.revision_digest, claims.prev_revision_digest, claims.party_descriptor_digest].filter((value) => value !== undefined).some((value) => !validTaggedDigest(value)))
1604
2011
  return "acceptance_invalid";
1605
2012
  if (!parseTimestamp(claims.accepted_at))
1606
2013
  return "timestamp_invalid";
2014
+ if ((claims.revision_number === 1) !== (claims.prev_revision_digest === undefined))
2015
+ return "acceptance_invalid";
1607
2016
  return null;
1608
2017
  }
1609
2018
  function terminationClaimsError(claims) {
2019
+ const shape = schemaError(claims, TERMINATION_SCHEMA);
2020
+ if (shape)
2021
+ return shape;
2022
+ if ([claims.charter_id, claims.governing_revision_digest, claims.party_descriptor_digest, claims.detail_digest].filter((value) => value !== undefined).some((value) => !validTaggedDigest(value)))
2023
+ return "termination_invalid";
1610
2024
  const issuedAt = parseTimestamp(claims.issued_at);
1611
2025
  const effectiveAt = parseTimestamp(claims.effective_at);
1612
- if (!issuedAt || !effectiveAt || compareTimestamps(issuedAt, effectiveAt) > 0)
2026
+ if (!issuedAt || !effectiveAt)
2027
+ return "timestamp_invalid";
2028
+ if (compareTimestamps(issuedAt, effectiveAt) > 0)
1613
2029
  return "termination_invalid";
1614
2030
  return null;
1615
2031
  }
1616
2032
  function receiptGrantError(claims) {
1617
- if (claims.grant?.scheme === "bap" && claims.grant?.grant_digest === undefined)
2033
+ const shape = schemaError(claims, RECEIPT_SCHEMA);
2034
+ if (shape)
2035
+ return shape;
2036
+ if ([claims.charter_id, claims.revision_digest, claims.deployment_digest, claims.grant.grant_digest].filter((value) => value !== undefined).some((value) => !validTaggedDigest(value)))
1618
2037
  return "receipt_invalid";
1619
- const optional = claims.extensions?.optional || {};
1620
- for (const namespace of Object.keys(optional)) {
1621
- const profile = EXTENSION_PROFILES.find((entry) => entry.namespace === namespace);
1622
- if (!profile || profile.state === "reserved" || profile.state === "retired")
1623
- continue;
1624
- if (profile.surface !== "receipt")
1625
- return "extension_scope_invalid";
1626
- if (profile.schema_digest === null)
1627
- return "extension_schema_unavailable";
1628
- }
1629
- return null;
2038
+ const allowed = receiptTimingMatrixError(claims);
2039
+ if (allowed)
2040
+ return allowed;
2041
+ if (claims.grant.scheme === "bap" && claims.grant.grant_digest === undefined)
2042
+ return "receipt_invalid";
2043
+ return extensionError(claims.extensions, "receipt");
1630
2044
  }
1631
2045
  function receiptTimingError(claims) {
1632
2046
  const occurredAt = parseTimestamp(claims.occurred_at);
1633
2047
  const recordedAt = parseTimestamp(claims.recorded_at);
1634
- if (!occurredAt || !recordedAt || compareTimestamps(recordedAt, occurredAt) < 0)
2048
+ if (!occurredAt || !recordedAt)
2049
+ return "timestamp_invalid";
2050
+ if (compareTimestamps(recordedAt, occurredAt) < 0)
1635
2051
  return "receipt_invalid";
2052
+ return receiptTimingMatrixError(claims);
2053
+ }
2054
+ function receiptTimingMatrixError(claims) {
1636
2055
  // The closed matrix mirrors the reference decoder: rejected requires
1637
2056
  // no_effect; accepted admits effect_committed, no_effect, or indeterminate.
1638
2057
  const outcomeAllowed = claims.decision === "rejected" ? claims.outcome === "no_effect" :
@@ -1642,12 +2061,22 @@ function receiptTimingError(claims) {
1642
2061
  return null;
1643
2062
  }
1644
2063
  function descriptorClaimsError(payload) {
2064
+ const shape = schemaError(payload, DESCRIPTOR_SCHEMA);
2065
+ if (shape)
2066
+ return shape;
2067
+ if ([payload.party_id, payload.prev_descriptor_digest].filter((value) => value !== undefined).some((value) => !validTaggedDigest(value)))
2068
+ return "descriptor_invalid";
1645
2069
  const grammar = keyGrammarError(payload);
1646
2070
  if (grammar)
1647
2071
  return grammar;
2072
+ if (new Set(payload.verification_keys.map((key) => key.key_id)).size !== payload.verification_keys.length || !payload.verification_keys.some((key) => key.status === "active"))
2073
+ return "descriptor_invalid";
2074
+ const extensions = extensionError(payload.extensions, "party_descriptor");
2075
+ if (extensions)
2076
+ return extensions;
1648
2077
  if (!parseTimestamp(payload.effective_from))
1649
2078
  return "timestamp_invalid";
1650
- if (payload.descriptor_number === 1 && payload.prev_descriptor_digest !== undefined)
2079
+ if (payload.descriptor_number === 1 ? (payload.prev_descriptor_digest !== undefined || payload.party_id !== undefined) : (payload.prev_descriptor_digest === undefined || payload.party_id === undefined))
1651
2080
  return "descriptor_invalid";
1652
2081
  return null;
1653
2082
  }
@@ -1659,28 +2088,31 @@ function descriptorClaimsError(payload) {
1659
2088
  // ---------------------------------------------------------------------------
1660
2089
  // The unique governing revision in a verified view at one UTC instant -
1661
2090
  // a digest, or "contested"/"none" (never silently resolved).
1662
- export function governingRevision(chainInput, at) {
2091
+ export function governingRevision(chainInput, at, options = {}) {
1663
2092
  const instant = typeof at === "string" ? parseTimestamp(at) : null;
1664
2093
  if (!instant)
1665
2094
  return { ok: false, code: "invalid_type" };
1666
2095
  if (!chainInput || typeof chainInput !== "object" || Array.isArray(chainInput)) {
1667
2096
  return { ok: false, code: "signing_input_invalid" };
1668
2097
  }
1669
- const chain = chainFromInput(chainInput);
2098
+ const chain = chainWithOptions(chainInput, options);
1670
2099
  if (!chain.ok)
1671
- return { ok: false, code: "chain_invalid" };
2100
+ return chain;
1672
2101
  return { ok: true, governing: governing(chain.value, instant) };
1673
2102
  }
1674
2103
  // Decode one canonical unsigned Charter Revision: the parsed claims plus
1675
2104
  // its content digest, computed over the exact text bytes.
1676
- export function decodeCharterRevision(text) {
1677
- const revision = revisionFromText(text);
2105
+ export function decodeCharterRevision(text, options = {}) {
2106
+ const settings = resolveOptions(options);
2107
+ if (!settings.ok)
2108
+ return settings;
2109
+ const revision = revisionFromText(text, settings.value.limits);
1678
2110
  if (!revision.ok)
1679
2111
  return { ok: false, code: revision.code };
1680
2112
  return { ok: true, revision: revision.value.value, digest: revision.value.digest };
1681
2113
  }
1682
- export function revisionDigest(text) {
1683
- const revision = decodeCharterRevision(text);
2114
+ export function revisionDigest(text, options = {}) {
2115
+ const revision = decodeCharterRevision(text, options);
1684
2116
  if (!revision.ok)
1685
2117
  return revision;
1686
2118
  return { ok: true, digest: revision.digest };
@@ -1734,13 +2166,13 @@ function jsonValueError(value) {
1734
2166
  // decode (the reference producer's exact ordering, so error precedence
1735
2167
  // matches too).
1736
2168
  function buildSigningInput(kind, kid, claims, algorithm) {
1737
- if (typeof algorithm === "undefined" || algorithm === null)
2169
+ if (typeof algorithm === "undefined")
1738
2170
  algorithm = defaultEmissionName();
1739
2171
  if (typeof algorithm !== "string" || !(algorithm in emissions())) {
1740
- return { ok: false, code: "algorithm_unsupported" };
2172
+ return { ok: false, code: "signing_input_invalid" };
1741
2173
  }
1742
2174
  if (!claims || typeof claims !== "object" || Array.isArray(claims)) {
1743
- return { ok: false, code: "invalid_type" };
2175
+ return { ok: false, code: "signing_input_invalid" };
1744
2176
  }
1745
2177
  const record = claims;
1746
2178
  if (jsonValueError(record))
@@ -1754,7 +2186,7 @@ function buildSigningInput(kind, kid, claims, algorithm) {
1754
2186
  }
1755
2187
  const row = ALG_ROWS.find((one) => one.name === algorithm);
1756
2188
  if (!row)
1757
- return { ok: false, code: "algorithm_unsupported" };
2189
+ return { ok: false, code: "signing_input_invalid" };
1758
2190
  const payloadSegment = encodeBase64url(Buffer.from(canonical(record), "utf8"));
1759
2191
  const protectedSegment = encodeBase64url(Buffer.from(canonical({ alg: algorithm, kid, typ: PRODUCER_TYPES[kind] }), "utf8"));
1760
2192
  const message = Buffer.from(`${protectedSegment}.${payloadSegment}`, "utf8");
@@ -1767,12 +2199,12 @@ function buildSigningInput(kind, kid, claims, algorithm) {
1767
2199
  // decode_for_signing inside the Elixir build pipeline.
1768
2200
  const claimsGate = checkSigningClaims(kind, record);
1769
2201
  if (!claimsGate.ok)
1770
- return { ok: false, code: claimsGate.code };
2202
+ return { ok: false, code: "signing_input_invalid" };
1771
2203
  // The provisional check: a zero signature at the row's exact length must
1772
2204
  // frame and bind.
1773
2205
  const zeroSignature = Buffer.alloc(row.signatureBytes);
1774
2206
  const provisional = `${protectedSegment}.${payloadSegment}.${encodeBase64url(zeroSignature)}`;
1775
- const decoded = decodeArtifact(provisional);
2207
+ const decoded = decodeSigningArtifact(provisional);
1776
2208
  if (!decoded.ok)
1777
2209
  return { ok: false, code: "signing_input_invalid" };
1778
2210
  return { ok: true, input: { alg: algorithm, protectedSegment, payloadSegment, message } };
@@ -1804,8 +2236,18 @@ export function terminationSigningInput(kid, claims, chainInput, algorithm) {
1804
2236
  return { ok: false, code: refusal.code };
1805
2237
  return built;
1806
2238
  }
2239
+ function decodeSigningArtifact(compact) {
2240
+ const decoded = decodeJws(compact);
2241
+ if (!decoded.ok)
2242
+ return decoded;
2243
+ const kind = Object.keys(PRODUCER_TYPES).find((one) => PRODUCER_TYPES[one] === decoded.value.header.typ);
2244
+ if (!kind)
2245
+ return fail("signing_input_invalid");
2246
+ const checked = checkSigningClaims(kind, decoded.value.payload);
2247
+ return checked.ok ? ok(null) : checked;
2248
+ }
1807
2249
  // Assemble a validated signing input and its exact raw signature (the
1808
- // reference assemble): registry-row length, framing re-decode, size gate.
2250
+ // reference assemble): registry-row length, full artifact decode, size gate.
1809
2251
  export function assembleCompact(input, signature) {
1810
2252
  if (!input || typeof input !== "object" || !Buffer.isBuffer(signature))
1811
2253
  return { ok: false, code: "invalid_type" };
@@ -1824,7 +2266,7 @@ export function assembleCompact(input, signature) {
1824
2266
  const compact = `${input.message.toString("utf8")}.${encodeBase64url(signature)}`;
1825
2267
  if (Buffer.byteLength(compact) > JSON_DEFAULT_LIMITS.max_bytes)
1826
2268
  return { ok: false, code: "signing_input_invalid" };
1827
- const decoded = decodeArtifact(compact);
2269
+ const decoded = decodeSigningArtifact(compact);
1828
2270
  if (!decoded.ok)
1829
2271
  return { ok: false, code: "signing_input_invalid" };
1830
2272
  return { ok: true, compact };
@@ -1848,7 +2290,7 @@ function refusalChain(chainInput) {
1848
2290
  if (!chainInput || typeof chainInput !== "object" || Array.isArray(chainInput))
1849
2291
  return { invalidSet: "signing_input_invalid" };
1850
2292
  const chain = chainFromInput(chainInput);
1851
- return chain.ok ? { chain: chain.value } : { invalidSet: "chain_invalid" };
2293
+ return chain.ok ? { chain: chain.value } : { invalidSet: chain.code === "invalid_type" ? "invalid_type" : "chain_invalid" };
1852
2294
  }
1853
2295
  function refusalPartyMatches(revision, claims) {
1854
2296
  return revision.value.parties.some((party) => party.role === claims.party_role && party.party_descriptor_digest === claims.party_descriptor_digest);