@charter-agreement-protocol/verifier 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 = "xiyty9a_VZTgiIYIKqGZQIAhJB-OQZRIcOX_zyNV-VQ";
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
@@ -50,6 +50,7 @@ const SURFACES = [
50
50
  "schema.validate", "party_descriptor.verify", "descriptor_chain.verify",
51
51
  "charter_revision.decode", "acceptance.verify", "acceptance.equivocation",
52
52
  "termination.verify", "chain.verify", "chain.verify_profile", "governing_revision", "receipt.verify",
53
+ "signing.prepare",
53
54
  ];
54
55
  const CLASSES = [
55
56
  "valid", "boundary_near", "exact_bound", "maximum_plus_one", "invalid_encoding",
@@ -57,38 +58,46 @@ const CLASSES = [
57
58
  "missing_required", "non_canonical_bytes", "digest_mismatch", "signature_invalid",
58
59
  "chain_invalid", "descriptor_superseded", "descriptor_fork", "equivocation",
59
60
  "chain_fork", "profile_algorithm_outside", "profile_revision_outside", "profile_narrow_valid",
60
- "supersession", "precedence_selection", "outcome_indeterminate",
61
+ "supersession", "precedence_selection", "terminated", "outcome_indeterminate",
61
62
  "extension_unknown_critical", "extension_optional_roundtrip", "extension_invalid",
62
63
  ];
63
64
  const REQUIRED = {
64
- "base64url.decode": ["valid", "exact_bound", "invalid_encoding"],
65
- "json.decode": ["valid", "boundary_near", "exact_bound", "maximum_plus_one", "invalid_encoding", "invalid_type"],
65
+ "acceptance.equivocation": ["equivocation", "invalid_constraint", "invalid_type"],
66
+ "acceptance.verify": ["valid", "invalid_constraint", "signature_invalid", "unknown_member", "profile_narrow_valid", "profile_algorithm_outside", "profile_revision_outside", "invalid_type"],
67
+ "base64url.decode": ["valid", "exact_bound", "invalid_encoding", "invalid_type"],
66
68
  "canonicalization.encode": ["valid", "invalid_encoding", "invalid_type", "non_canonical_bytes"],
69
+ "chain.verify": ["valid", "exact_bound", "maximum_plus_one", "chain_fork", "supersession", "chain_invalid", "invalid_type"],
70
+ "chain.verify_profile": ["profile_algorithm_outside", "profile_revision_outside", "profile_narrow_valid", "invalid_type"],
71
+ "charter_revision.decode": ["valid", "invalid_encoding", "invalid_type", "invalid_constraint", "invalid_cardinality", "unknown_member", "missing_required", "non_canonical_bytes", "extension_unknown_critical", "extension_invalid"],
72
+ "descriptor_chain.verify": ["signature_invalid", "chain_invalid", "descriptor_superseded", "descriptor_fork", "invalid_type"],
67
73
  "digest.hash": ["valid", "invalid_type", "digest_mismatch"],
74
+ "governing_revision": ["precedence_selection", "terminated", "invalid_type"],
75
+ "json.decode": ["valid", "boundary_near", "exact_bound", "maximum_plus_one", "invalid_encoding", "invalid_type"],
76
+ "party_descriptor.verify": ["valid", "signature_invalid", "invalid_encoding", "unknown_member", "invalid_constraint", "profile_narrow_valid", "profile_algorithm_outside", "profile_revision_outside", "invalid_type"],
77
+ "receipt.verify": ["valid", "maximum_plus_one", "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", "invalid_type"],
68
78
  "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"],
79
+ "signing.prepare": ["valid", "exact_bound", "maximum_plus_one", "invalid_type", "invalid_constraint", "chain_invalid", "profile_algorithm_outside", "profile_revision_outside"],
80
+ "termination.verify": ["valid", "invalid_constraint", "signature_invalid", "unknown_member", "profile_narrow_valid", "profile_algorithm_outside", "profile_revision_outside", "invalid_type"],
79
81
  };
80
82
  const ok = (value) => ({ ok: true, value });
81
83
  const fail = (code) => ({ ok: false, code });
82
84
  const valid = (output) => ({ status: "valid", output });
83
85
  const invalid = (code) => ({ status: "invalid", error_code: code });
84
86
  const project = (result, projector) => result.ok ? valid(projector(result.value)) : invalid(result.code);
87
+ const NOT_VERIFIED_FLOOR = ["tenancy", "live_policy", "authority", "effect_ownership", "execution", "billing", "evaluation_truth", "legal_validity", "term_satisfaction", "view_completeness", "counterparty_view", "wall_clock"];
88
+ function factsRecord(attrs, additions = []) {
89
+ return { protocol_revision: null, alg: null, ...attrs, not_verified: [...new Set([...NOT_VERIFIED_FLOOR, ...additions])] };
90
+ }
85
91
  export function canonical(value) {
86
92
  if (value instanceof Number)
87
93
  return JSON.stringify(value.valueOf());
88
94
  if (value === null || typeof value === "boolean" || typeof value === "string")
89
95
  return JSON.stringify(value);
90
- if (typeof value === "number" && Number.isFinite(value))
96
+ if (typeof value === "number" && Number.isFinite(value)) {
97
+ if (Number.isInteger(value) && !Number.isSafeInteger(value))
98
+ throw new Error("integer_magnitude");
91
99
  return JSON.stringify(value);
100
+ }
92
101
  if (Array.isArray(value))
93
102
  return `[${value.map(canonical).join(",")}]`;
94
103
  if (value && typeof value === "object") {
@@ -135,31 +144,48 @@ function strictBase64url(text) {
135
144
  // closed codes, in the decoder's own order.
136
145
  const MAXIMUM_SAFE_INTEGER = 9007199254740991n;
137
146
  const NUMBER_TOKEN = /(?:-?(?:0|[1-9][0-9]*))(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
138
- function readJsonValue(text, index) {
147
+ // Retain text order separately from JavaScript's integer-key enumeration.
148
+ // Plain property access remains compatible with existing artifact consumers.
149
+ const JSON_MEMBER_ORDER = new WeakMap();
150
+ function readJsonValue(text, index, limits, depth = 0, bytes) {
139
151
  index = skipWhitespace(text, index);
140
152
  const char = text[index];
141
153
  if (char === undefined)
142
154
  return { status: "need-character" };
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);
160
+ if (text[cursor] !== "}" && text[cursor] !== '"')
161
+ return { status: "syntax" };
162
+ if (depth + 1 > limits.max_depth)
163
+ return { status: "error", code: "limit_exceeded" };
146
164
  if (text[cursor] === "}")
147
165
  return { status: "ok", value: {}, index: cursor + 1 };
148
166
  for (;;) {
149
167
  if (text[cursor] !== '"')
150
168
  return { status: "syntax" };
151
- const key = readJsonString(text, cursor);
169
+ const key = readJsonString(text, cursor, bytes);
152
170
  if (key.status !== "ok")
153
171
  return key;
172
+ if (Buffer.byteLength(key.value) > limits.max_string_bytes)
173
+ return { status: "error", code: "limit_exceeded" };
154
174
  cursor = skipWhitespace(text, key.index);
155
175
  if (text[cursor] !== ":")
156
176
  return { status: "syntax" };
157
- const item = readJsonValue(text, skipWhitespace(text, cursor + 1));
177
+ const item = readJsonValue(text, skipWhitespace(text, cursor + 1), limits, depth + 1, bytes);
158
178
  if (item.status !== "ok")
159
179
  return item;
160
- const duplicate = members.has(key.value);
161
- members.set(key.value, item.value);
162
180
  cursor = skipWhitespace(text, item.index);
181
+ if (text[cursor] !== "," && text[cursor] !== "}")
182
+ return { status: "syntax" };
183
+ if (item.deferredCode)
184
+ return { status: "error", code: item.deferredCode };
185
+ if (++count > limits.max_object_members)
186
+ return { status: "error", code: "limit_exceeded" };
187
+ duplicate ||= members.has(key.value);
188
+ members.set(key.value, item.value);
163
189
  if (text[cursor] === ",") {
164
190
  cursor = skipWhitespace(text, cursor + 1);
165
191
  continue;
@@ -167,7 +193,9 @@ function readJsonValue(text, index) {
167
193
  if (text[cursor] === "}") {
168
194
  if (duplicate)
169
195
  return { status: "error", code: "duplicate_member" };
170
- return { status: "ok", value: Object.fromEntries(members), index: cursor + 1 };
196
+ const object = Object.fromEntries(members);
197
+ JSON_MEMBER_ORDER.set(object, [...members.keys()]);
198
+ return { status: "ok", value: object, index: cursor + 1 };
171
199
  }
172
200
  return { status: "syntax" };
173
201
  }
@@ -175,14 +203,24 @@ function readJsonValue(text, index) {
175
203
  if (char === "[") {
176
204
  const items = [];
177
205
  let cursor = skipWhitespace(text, index + 1);
206
+ if (text[cursor] === undefined)
207
+ return { status: "syntax" };
208
+ if (depth + 1 > limits.max_depth)
209
+ return { status: "error", code: "limit_exceeded" };
178
210
  if (text[cursor] === "]")
179
211
  return { status: "ok", value: items, index: cursor + 1 };
180
212
  for (;;) {
181
- const item = readJsonValue(text, cursor);
213
+ const item = readJsonValue(text, cursor, limits, depth + 1, bytes);
182
214
  if (item.status !== "ok")
183
215
  return item;
184
- items.push(item.value);
185
216
  cursor = skipWhitespace(text, item.index);
217
+ if (text[cursor] !== "," && text[cursor] !== "]")
218
+ return { status: "syntax" };
219
+ if (item.deferredCode)
220
+ return { status: "error", code: item.deferredCode };
221
+ if (items.length >= limits.max_array_items)
222
+ return { status: "error", code: "limit_exceeded" };
223
+ items.push(item.value);
186
224
  if (text[cursor] === ",") {
187
225
  cursor = skipWhitespace(text, cursor + 1);
188
226
  continue;
@@ -193,7 +231,9 @@ function readJsonValue(text, index) {
193
231
  }
194
232
  }
195
233
  if (char === '"') {
196
- const string = readJsonString(text, index);
234
+ const string = readJsonString(text, index, bytes);
235
+ if (string.status === "ok" && Buffer.byteLength(string.value) > limits.max_string_bytes)
236
+ return { status: "error", code: "limit_exceeded" };
197
237
  return string.status === "ok" ? { status: "ok", value: string.value, index: string.index } : string;
198
238
  }
199
239
  for (const [literal, value] of [["true", true], ["false", false], ["null", null]]) {
@@ -204,15 +244,28 @@ function readJsonValue(text, index) {
204
244
  const token = NUMBER_TOKEN.exec(text);
205
245
  if (token) {
206
246
  const literal = token[0];
247
+ // A fraction or exponent that starts without its digits is a syntax error,
248
+ // as in the reference: "1." and "1e" are invalid_syntax, while a "." after
249
+ // a fraction or an "e" after an exponent is ordinary trailing input.
250
+ const next = text[index + literal.length];
251
+ if ((next === "." && !/[.eE]/.test(literal)) || ((next === "e" || next === "E") && !/[eE]/.test(literal)))
252
+ return { status: "syntax" };
253
+ const numberError = (code) => ({ status: "ok", deferredCode: code, index: index + literal.length });
207
254
  if (/^-?[0-9]+$/.test(literal)) {
255
+ if (literal.replace(/^-/, "").length > 21)
256
+ return numberError("number_not_double_expressible");
208
257
  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" };
258
+ if (magnitude > MAXIMUM_SAFE_INTEGER || magnitude < -MAXIMUM_SAFE_INTEGER) {
259
+ if (JSON.stringify(Number(literal)) !== literal)
260
+ return numberError("number_not_double_expressible");
261
+ return { status: "ok", value: new Number(Number(literal)), index: index + literal.length };
212
262
  }
213
263
  }
214
- else if (!Number.isFinite(Number(literal))) {
215
- return { status: "error", code: "invalid_number" };
264
+ else {
265
+ if (literal.length > 32)
266
+ return numberError("number_not_double_expressible");
267
+ if (!Number.isFinite(Number(literal)))
268
+ return numberError("invalid_number");
216
269
  }
217
270
  // Float-ness follows the lexeme (fraction or exponent), never the value:
218
271
  // "0.0" and "2e0" are floats even though their double is integral, so the
@@ -222,7 +275,7 @@ function readJsonValue(text, index) {
222
275
  }
223
276
  return { status: "syntax" };
224
277
  }
225
- function readJsonString(text, index) {
278
+ function readJsonString(text, index, bytes) {
226
279
  if (text[index] !== '"')
227
280
  return { status: "syntax" };
228
281
  let end = index + 1;
@@ -238,7 +291,16 @@ function readJsonString(text, index) {
238
291
  if (text[end] !== '"')
239
292
  return { status: "syntax" };
240
293
  try {
241
- const value = JSON.parse(text.slice(index, end + 1));
294
+ let literal = text.slice(index, end + 1);
295
+ if (bytes) {
296
+ try {
297
+ literal = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(index, end + 1));
298
+ }
299
+ catch (_error) {
300
+ return { status: "error", code: "invalid_encoding" };
301
+ }
302
+ }
303
+ const value = JSON.parse(literal);
242
304
  if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(value)) {
243
305
  return { status: "syntax" };
244
306
  }
@@ -260,25 +322,57 @@ function skipWhitespace(text, index) {
260
322
  index += 1;
261
323
  return index;
262
324
  }
263
- export function decodeJsonText(text) {
264
- const value = readJsonValue(text, 0);
325
+ export function decodeJsonText(text, selected = {}) {
326
+ try {
327
+ selected = readOptionMembers(selected, Object.keys(DEFAULT_LIMITS));
328
+ }
329
+ catch (_error) {
330
+ return fail("invalid_type");
331
+ }
332
+ if (!validLimits(selected))
333
+ return fail("invalid_limits");
334
+ if (typeof text !== "string")
335
+ return fail("invalid_type");
336
+ const limits = { ...DEFAULT_LIMITS, ...selected };
337
+ if (Buffer.byteLength(text) > limits.max_bytes)
338
+ return fail("limit_exceeded");
339
+ const value = readJsonValue(text, 0, limits);
265
340
  if (value.status === "need-character" || value.status === "syntax")
266
341
  return fail("invalid_syntax");
267
342
  if (value.status === "error")
268
343
  return fail(value.code);
269
344
  if (value.index === undefined || skipWhitespace(text, value.index) !== text.length)
270
345
  return fail("trailing_bytes");
346
+ if (value.deferredCode)
347
+ return fail(value.deferredCode);
271
348
  return ok(value.value);
272
349
  }
273
- function decodeJsonBytes(bytes) {
350
+ function decodeJsonBytes(bytes, limits = DEFAULT_LIMITS) {
274
351
  try {
275
- return decodeJsonText(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
352
+ if (bytes.length > limits.max_bytes)
353
+ return fail("limit_exceeded");
354
+ // Byte offsets stay intact while syntax and container callbacks run.
355
+ // Decode UTF-8 only when the parser reaches a string token.
356
+ const text = bytes.toString("latin1");
357
+ const value = readJsonValue(text, 0, limits, 0, bytes);
358
+ if (value.status === "error")
359
+ return fail(value.code);
360
+ if (value.status === "need-character" || value.status === "syntax") {
361
+ // The reference classifies a parse failure by the input's encoding.
362
+ new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
363
+ return fail("invalid_syntax");
364
+ }
365
+ if (value.index === undefined || skipWhitespace(text, value.index) !== text.length)
366
+ return fail("trailing_bytes");
367
+ if (value.deferredCode)
368
+ return fail(value.deferredCode);
369
+ return ok(value.value);
276
370
  }
277
371
  catch (_error) {
278
372
  return fail("invalid_encoding");
279
373
  }
280
374
  }
281
- const JSON_DEFAULT_LIMITS = {
375
+ export const DEFAULT_LIMITS = Object.freeze({
282
376
  max_bytes: 1_048_576,
283
377
  max_depth: 64,
284
378
  max_object_members: 1_024,
@@ -286,10 +380,11 @@ const JSON_DEFAULT_LIMITS = {
286
380
  max_string_bytes: 65_536,
287
381
  max_artifact_set_items: 1_024,
288
382
  max_artifact_set_bytes: 67_108_864,
289
- };
383
+ });
384
+ const JSON_DEFAULT_LIMITS = DEFAULT_LIMITS;
290
385
  // The compiled maximums mirror lib/charter_agreement_protocol/limits.ex: the
291
386
  // greatest caller-selectable value per field, not the defaults.
292
- const LIMIT_MAXIMUMS = {
387
+ export const MAXIMUM_LIMITS = Object.freeze({
293
388
  max_bytes: 16_777_216,
294
389
  max_depth: 128,
295
390
  max_object_members: 65_536,
@@ -297,12 +392,13 @@ const LIMIT_MAXIMUMS = {
297
392
  max_string_bytes: 1_048_576,
298
393
  max_artifact_set_items: 4_096,
299
394
  max_artifact_set_bytes: 1_073_741_824,
300
- };
395
+ });
396
+ const LIMIT_MAXIMUMS = MAXIMUM_LIMITS;
301
397
  function validLimits(selected) {
302
- if (typeof selected !== "object" || selected === null)
398
+ if (!isRecord(selected))
303
399
  return false;
304
400
  const maximums = LIMIT_MAXIMUMS;
305
- return Object.entries(selected).every(([name, value]) => name in maximums && Number.isInteger(value) && value >= 0 && value <= maximums[name]);
401
+ return Object.entries(selected).every(([name, value]) => Object.hasOwn(maximums, name) && Number.isInteger(value) && value >= 0 && value <= maximums[name]);
306
402
  }
307
403
  function jsonWithinLimits(value, bytes, selected = {}) {
308
404
  const limits = { ...JSON_DEFAULT_LIMITS, ...selected };
@@ -320,7 +416,7 @@ function jsonWithinLimits(value, bytes, selected = {}) {
320
416
  item.forEach((child) => visit(child, depth + 1));
321
417
  return;
322
418
  }
323
- if (item && typeof item === "object") {
419
+ if (item && typeof item === "object" && !(item instanceof Number)) {
324
420
  const entries = Object.entries(item);
325
421
  if (depth + 1 > limits.max_depth || entries.length > limits.max_object_members)
326
422
  throw new Error("limit");
@@ -349,7 +445,7 @@ export function jsonProjection(value) {
349
445
  if (Array.isArray(value))
350
446
  return { tag: "array", items: value.map(jsonProjection) };
351
447
  if (value && typeof value === "object")
352
- return { tag: "object", members: Object.entries(value).map(([key, item]) => [key, jsonProjection(item)]) };
448
+ return { tag: "object", members: (JSON_MEMBER_ORDER.get(value) ?? Object.keys(value)).map((key) => [key, jsonProjection(value[key])]) };
353
449
  if (typeof value === "string")
354
450
  return { tag: "string", value };
355
451
  if (typeof value === "boolean")
@@ -357,91 +453,133 @@ export function jsonProjection(value) {
357
453
  return { tag: "float", value };
358
454
  }
359
455
  const PROTECTED_MEMBERS = ["alg", "kid", "typ"];
360
- function decodeJws(compact) {
456
+ function canonicalTextError(value, text) {
457
+ try {
458
+ return canonical(value) === text ? null : "non_canonical_bytes";
459
+ }
460
+ catch (error) {
461
+ return error instanceof Error ? error.message : "invalid_type";
462
+ }
463
+ }
464
+ function decodeJws(compact, limits = DEFAULT_LIMITS, expectedTyp) {
361
465
  if (typeof compact !== "string")
362
466
  return fail("compact_invalid");
363
- if (Buffer.byteLength(compact) > JSON_DEFAULT_LIMITS.max_bytes)
467
+ if (Buffer.byteLength(compact) > limits.max_bytes)
364
468
  return fail("limit_exceeded");
365
469
  const segments = compact.split(".");
366
470
  if (segments.length !== 3)
367
471
  return fail("compact_invalid");
368
- const decoded = segments.map(strictBase64url);
369
- if (decoded.some((one) => !one.ok))
472
+ const protectedBytes = strictBase64url(segments[0]);
473
+ const payloadBytes = strictBase64url(segments[1]);
474
+ const signatureBytes = strictBase64url(segments[2]);
475
+ if (!protectedBytes.ok || !payloadBytes.ok)
370
476
  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)
477
+ if (!signatureBytes.ok)
478
+ return fail("signature_invalid");
479
+ const headerValue = decodeJsonBytes(protectedBytes.value, limits);
480
+ if (!headerValue.ok || !isRecord(headerValue.value) || canonicalTextError(headerValue.value, protectedBytes.value.toString()))
378
481
  return fail("protected_header_invalid");
379
- const payloadValue = decodeJsonBytes(payloadBytes);
380
- if (!payloadValue.ok)
381
- return fail("non_canonical_bytes");
382
482
  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))) {
483
+ if (!exactKeys(header, PROTECTED_MEMBERS) || typeof header.alg !== "string" || !ALG_ROWS.some((row) => row.name === header.alg) ||
484
+ typeof header.typ !== "string" || (expectedTyp !== undefined && header.typ !== expectedTyp) ||
485
+ typeof header.kid !== "string" || !/^[A-Za-z0-9._~-]{1,128}$/.test(header.kid))
386
486
  return fail("protected_header_invalid");
387
- }
388
- if (canonical(header) !== headerBytes.toString() || canonical(payload) !== payloadBytes.toString())
487
+ const payloadValue = decodeJsonBytes(payloadBytes.value, limits);
488
+ if (!payloadValue.ok)
489
+ return fail("non_canonical_bytes");
490
+ const integerError = integerTokenError(payloadValue.value, schemaForType(expectedTyp));
491
+ if (integerError)
492
+ return fail(integerError);
493
+ if (canonicalTextError(payloadValue.value, payloadBytes.value.toString()))
389
494
  return fail("non_canonical_bytes");
390
- const revision = payload.protocol_revision;
391
- if (typeof revision !== "number" || !Number.isInteger(revision) || !algBinds(header.alg, revision))
495
+ if (!isRecord(payloadValue.value))
496
+ return fail("protected_header_invalid");
497
+ const payload = payloadValue.value;
498
+ if (typeof payload.protocol_revision !== "number" || !Number.isInteger(payload.protocol_revision) || !algBinds(header.alg, payload.protocol_revision))
392
499
  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
500
  const row = ALG_ROWS.find((one) => one.name === header.alg);
396
- const signature = decoded[2].value;
397
- if (!row || signature.length !== row.signatureBytes)
501
+ if (signatureBytes.value.length !== row.signatureBytes)
398
502
  return fail("signature_invalid");
399
- return ok({ header, payload, payloadBytes, signature, signingInput: Buffer.from(`${segments[0]}.${segments[1]}`) });
503
+ return ok({ header, payload, payloadBytes: payloadBytes.value, signature: signatureBytes.value, signingInput: Buffer.from(`${segments[0]}.${segments[1]}`) });
400
504
  }
401
505
  const ED25519_FIELD_PRIME = 2n ** 255n - 19n;
402
506
  const ED25519_SUBGROUP_ORDER = 2n ** 252n + 27742317777372353535851937790883648493n;
403
- const ED25519_SMALL_ORDER_POINTS = [
404
- "0100000000000000000000000000000000000000000000000000000000000000",
405
- "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
406
- "0000000000000000000000000000000000000000000000000000000000000080",
407
- "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
408
- "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
409
- "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
410
- "0000000000000000000000000000000000000000000000000000000000000000",
411
- "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",
412
- ].map((hex) => Buffer.from(hex, "hex"));
507
+ const ED25519_D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;
508
+ const ED25519_SQRT_MINUS_ONE = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n;
509
+ function ed25519Field(value) {
510
+ const reduced = value % ED25519_FIELD_PRIME;
511
+ return reduced < 0n ? reduced + ED25519_FIELD_PRIME : reduced;
512
+ }
513
+ function squareEd25519(value, count) {
514
+ for (let i = 0; i < count; i++)
515
+ value = value * value % ED25519_FIELD_PRIME;
516
+ return value;
517
+ }
518
+ // Fixed addition chain for (p - 5) / 8 = 2^252 - 3: 251 squarings and 11 multiplies.
519
+ function ed25519Power(base) {
520
+ const x2 = squareEd25519(base, 1);
521
+ const x9 = squareEd25519(x2, 2) * base % ED25519_FIELD_PRIME;
522
+ const x11 = x9 * x2 % ED25519_FIELD_PRIME;
523
+ const x31 = squareEd25519(x11, 1) * x9 % ED25519_FIELD_PRIME;
524
+ const x10 = squareEd25519(x31, 5) * x31 % ED25519_FIELD_PRIME;
525
+ const x20 = squareEd25519(x10, 10) * x10 % ED25519_FIELD_PRIME;
526
+ const x40 = squareEd25519(x20, 20) * x20 % ED25519_FIELD_PRIME;
527
+ const x50 = squareEd25519(x40, 10) * x10 % ED25519_FIELD_PRIME;
528
+ const x100 = squareEd25519(x50, 50) * x50 % ED25519_FIELD_PRIME;
529
+ const x200 = squareEd25519(x100, 100) * x100 % ED25519_FIELD_PRIME;
530
+ const x250 = squareEd25519(x200, 50) * x50 % ED25519_FIELD_PRIME;
531
+ return squareEd25519(x250, 2) * base % ED25519_FIELD_PRIME;
532
+ }
533
+ // Homogeneous Edwards coordinates keep the doublings free of division.
534
+ function doubleEd25519Point([x, y, z]) {
535
+ const xSquared = ed25519Field(x * x);
536
+ const ySquared = ed25519Field(y * y);
537
+ const sum = ed25519Field(ySquared - xSquared);
538
+ const difference = ed25519Field(sum - 2n * z * z);
539
+ return [ed25519Field(2n * x * y * difference), ed25519Field(-sum * (xSquared + ySquared)), ed25519Field(sum * difference)];
540
+ }
413
541
  function decodeLittleEndian(buffer) {
414
542
  let value = 0n;
415
543
  for (let index = buffer.length - 1; index >= 0; index -= 1)
416
544
  value = (value << 8n) | BigInt(buffer[index]);
417
545
  return value;
418
546
  }
419
- // Strict point check mirroring Signature.strict_point?/1: the y coordinate is
420
- // canonical, the negative-zero spelling is rejected, and the complete
421
- // eight-point torsion set is refused before OpenSSL sees the key or R.
547
+ // Decode a canonical curve point, reject negative zero and small order,
548
+ // and admit mixed order. Keys and signature R share this rule.
422
549
  function strictEd25519Point(point) {
423
550
  if (point.length !== 32)
424
551
  return false;
425
- if (ED25519_SMALL_ORDER_POINTS.some((one) => one.equals(point)))
552
+ const y = decodeLittleEndian(point) & ((1n << 255n) - 1n);
553
+ const sign = BigInt(point[31] >> 7);
554
+ if (y >= ED25519_FIELD_PRIME)
555
+ return false;
556
+ const ySquared = ed25519Field(y * y);
557
+ const numerator = ed25519Field(ySquared - 1n);
558
+ const denominator = ed25519Field(ED25519_D * ySquared + 1n);
559
+ if (denominator === 0n)
560
+ return false;
561
+ // RFC 8032 section 5.1.3 combines inversion and square root in one exponentiation.
562
+ const cubed = ed25519Field(denominator * denominator * denominator);
563
+ const seventh = ed25519Field(cubed * cubed * denominator);
564
+ let root = ed25519Field(numerator * cubed * ed25519Power(ed25519Field(numerator * seventh)));
565
+ if (ed25519Field(denominator * root * root) !== numerator)
566
+ root = ed25519Field(root * ED25519_SQRT_MINUS_ONE);
567
+ if (ed25519Field(denominator * root * root) !== numerator || (root === 0n && sign === 1n))
426
568
  return false;
427
- const prefix = point.subarray(0, 31);
428
- const last = point[31];
429
- const y = decodeLittleEndian(Buffer.concat([prefix, Buffer.from([last & 0x7f])]));
430
- const negativeZero = (last & 0x80) !== 0 && (y === 1n || y === ED25519_FIELD_PRIME - 1n);
431
- return y < ED25519_FIELD_PRIME && !negativeZero;
569
+ const x = (root & 1n) === sign ? root : ed25519Field(-root);
570
+ const [x8, y8, z8] = doubleEd25519Point(doubleEd25519Point(doubleEd25519Point([x, y, 1n])));
571
+ return !(x8 === 0n && ed25519Field(y8 - z8) === 0n);
572
+ }
573
+ function strictEd25519Signature(signature) {
574
+ return signature.length === 64 && strictEd25519Point(signature.subarray(0, 32)) &&
575
+ decodeLittleEndian(signature.subarray(32)) < ED25519_SUBGROUP_ORDER;
432
576
  }
433
577
  function ed25519(rawKey, message, signature) {
434
578
  try {
435
579
  const key = Buffer.from(rawKey, "base64url");
436
580
  if (signature.length !== 64 || key.length !== 32)
437
581
  return false;
438
- if (!strictEd25519Point(key))
439
- return false;
440
- const r = signature.subarray(0, 32);
441
- const s = signature.subarray(32);
442
- if (!strictEd25519Point(r))
443
- return false;
444
- if (decodeLittleEndian(s) >= ED25519_SUBGROUP_ORDER)
582
+ if (!strictEd25519Signature(signature))
445
583
  return false;
446
584
  const prefix = Buffer.from("302a300506032b6570032100", "hex");
447
585
  const spki = createPublicKey({ key: Buffer.concat([prefix, key]), format: "der", type: "spki" });
@@ -476,19 +614,62 @@ function mldsa(keyAlgorithm, rawKey, message, signature) {
476
614
  function keyMatchesRow(key, row) {
477
615
  if (!key || key.algorithm !== row.keyAlgorithm || key.status !== "active")
478
616
  return false;
479
- const bytes = Buffer.from(key.public_key, "base64url");
480
- return bytes.length === row.publicKeyBytes && bytes.toString("base64url") === key.public_key;
617
+ return validPublicKey(key.public_key, row);
618
+ }
619
+ function validPublicKey(rawKey, row) {
620
+ const decoded = strictBase64url(rawKey);
621
+ return decoded.ok && decoded.value.length === row.publicKeyBytes &&
622
+ (row.keyAlgorithm !== "Ed25519" || strictEd25519Point(decoded.value));
481
623
  }
482
- function verifyDecodedJws(decoded, typ, keys) {
624
+ function verifyDecodedJws(decoded, typ, keys, settings = DEFAULT_SETTINGS) {
625
+ const admission = profileError(decoded.header.alg, decoded.payload.protocol_revision, settings);
626
+ if (admission)
627
+ return fail(admission);
483
628
  const row = ALG_ROWS.find((one) => one.name === decoded.header.alg);
484
629
  if (!row || decoded.header.typ !== typ || typeof decoded.header.kid !== "string")
485
- return false;
630
+ return fail("signature_invalid");
486
631
  const key = keys.find((one) => one.key_id === decoded.header.kid && keyMatchesRow(one, row));
487
632
  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);
633
+ return fail("signature_invalid");
634
+ const bytes = Buffer.from(key.public_key, "base64url");
635
+ if (decoded.signature.length !== row.signatureBytes)
636
+ return fail("signature_invalid");
637
+ if (row.keyAlgorithm === "Ed25519" && !strictEd25519Signature(decoded.signature))
638
+ return fail("signature_invalid");
639
+ if (!runtimeSupportsAlgorithm(row.keyAlgorithm))
640
+ return fail("algorithm_unsupported_on_substrate");
641
+ try {
642
+ const prefix = row.keyAlgorithm === "Ed25519" ? Buffer.from("302a300506032b6570032100", "hex") : ML_DSA_SPKI_PREFIXES[row.keyAlgorithm];
643
+ const spki = createPublicKey({ key: Buffer.concat([prefix, bytes]), format: "der", type: "spki" });
644
+ const verified = nodeVerifySignature(null, decoded.signingInput, spki, decoded.signature);
645
+ return verified ? ok(null) : fail("signature_invalid");
646
+ }
647
+ catch (_error) {
648
+ return fail(runtimeSupportsAlgorithm(row.keyAlgorithm) ? "signature_invalid" : "algorithm_unsupported_on_substrate");
649
+ }
650
+ }
651
+ function preparedArtifact(decoded, keys, facts, missingKeyCode, unnamed = false) {
652
+ return ok({ decoded, keys: keys.filter((key) => key.key_id === decoded.header.kid && key.status === "active"), facts, missingKeyCode, unnamed });
653
+ }
654
+ function finishPreparedArtifact(prepared, settings) {
655
+ if (!prepared.ok)
656
+ return prepared;
657
+ const { decoded, keys, facts, missingKeyCode, unnamed } = prepared.value;
658
+ if (unnamed)
659
+ return ok(facts);
660
+ if (keys.length === 0)
661
+ return fail(missingKeyCode);
662
+ if (decoded.header.typ !== "cap+receipt") {
663
+ const signature = verifyDecodedJws(decoded, decoded.header.typ, keys, settings);
664
+ return signature.ok ? ok(facts) : signature;
665
+ }
666
+ const candidates = keys.map((key) => ({ key, result: verifyDecodedJws(decoded, "cap+receipt", [key], settings) }));
667
+ const verifiedPublicKeys = new Set(candidates.filter((one) => one.result.ok).map((one) => one.key.public_key));
668
+ if (verifiedPublicKeys.size !== 1) {
669
+ const diagnostic = candidates.find((one) => !one.result.ok && ["algorithm_outside_profile", "revision_outside_profile", "algorithm_unsupported_on_substrate"].includes(one.result.code));
670
+ return fail(verifiedPublicKeys.size === 0 && diagnostic && !diagnostic.result.ok ? diagnostic.result.code : "signature_invalid");
671
+ }
672
+ return ok(facts);
492
673
  }
493
674
  const TIMESTAMP_GRAMMAR = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?Z$/;
494
675
  // Exact RFC 3339 UTC parse mirroring Timestamp.ex: real calendar date, hour
@@ -503,10 +684,9 @@ function parseTimestamp(value) {
503
684
  if (!match)
504
685
  return null;
505
686
  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);
687
+ const date = new Date(0);
688
+ date.setUTCFullYear(year, month - 1, day);
689
+ const utc = date.getTime();
510
690
  if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day)
511
691
  return null;
512
692
  if (hour > 23 || minute > 59 || second > 60)
@@ -527,49 +707,43 @@ function compareTimestamps(left, right) {
527
707
  return 0;
528
708
  return paddedLeft < paddedRight ? -1 : 1;
529
709
  }
530
- function descriptorFromCompact(compact, predecessor = null) {
531
- const decoded = decodeJws(compact);
710
+ function prepareDescriptor(compact, predecessor = null, settings = DEFAULT_SETTINGS) {
711
+ const decoded = decodeJws(compact, settings.limits, "cap+party");
532
712
  if (!decoded.ok)
533
713
  return decoded;
534
714
  const payload = decoded.value.payload;
535
715
  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);
716
+ const grammar = descriptorClaimsError(payload);
538
717
  if (grammar)
539
718
  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
719
  const digest = taggedHash("party_descriptor_content", decoded.value.payloadBytes);
559
720
  if (payload.descriptor_number === 1) {
721
+ if (predecessor)
722
+ return fail("descriptor_chain_invalid");
560
723
  if (payload.prev_descriptor_digest !== undefined)
561
724
  return fail("descriptor_invalid");
562
725
  }
563
- else if (!predecessor || payload.prev_descriptor_digest !== predecessor.digest || payload.descriptor_number !== predecessor.payload.descriptor_number + 1) {
726
+ 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
727
  return fail("descriptor_chain_invalid");
565
728
  }
566
- return ok({ ...decoded.value, digest, compact });
729
+ // The envelope is admitted before its kid is looked up, as in the
730
+ // reference, so an out-of-profile artifact whose kid names no key reports
731
+ // the profile code. Acceptances and terminations do the same.
732
+ const descriptorAdmission = profileError(decoded.value.header.alg, payload.protocol_revision, settings);
733
+ if (descriptorAdmission)
734
+ return fail(descriptorAdmission);
735
+ if (!parseTimestamp(payload.effective_from)) {
736
+ return fail("timestamp_invalid");
737
+ }
738
+ const facts = factsRecord({ ...decoded.value, digest, compact, lineage: [compact, ...(predecessor?.lineage ?? [])], protocol_revision: payload.protocol_revision, alg: decoded.value.header.alg });
739
+ return preparedArtifact(decoded.value, keys, facts, "descriptor_key_invalid");
567
740
  }
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.
741
+ function descriptorFromCompact(compact, predecessor = null, settings = DEFAULT_SETTINGS) {
742
+ return finishPreparedArtifact(prepareDescriptor(compact, predecessor, settings), settings);
743
+ }
744
+ // The nested schema admits registry encoding lengths; extraction checks
745
+ // the decoded bytes against the selected algorithm and canonical spelling.
746
+ // Those extraction failures use descriptor_invalid.
573
747
  function keyGrammarError(payload) {
574
748
  if (!Array.isArray(payload.verification_keys) || payload.verification_keys.length === 0) {
575
749
  return "nested_invalid";
@@ -585,7 +759,7 @@ function keyGrammarError(payload) {
585
759
  return "nested_invalid";
586
760
  const bytes = Buffer.from(one.public_key, "base64url");
587
761
  if (bytes.length !== row.publicKeyBytes || bytes.toString("base64url") !== one.public_key) {
588
- return "nested_invalid";
762
+ return "descriptor_invalid";
589
763
  }
590
764
  if (one.algorithm !== "Ed25519" &&
591
765
  !(Number.isInteger(payload.protocol_revision) && payload.protocol_revision >= 3)) {
@@ -594,43 +768,86 @@ function keyGrammarError(payload) {
594
768
  }
595
769
  return null;
596
770
  }
597
- function descriptorChain(compacts) {
771
+ function descriptorChain(compacts, settings = DEFAULT_SETTINGS) {
598
772
  if (!Array.isArray(compacts) || compacts.length === 0)
599
773
  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)
774
+ if (compacts.length > settings.limits.max_artifact_set_items)
775
+ return fail("limit_exceeded");
776
+ const entries = [];
777
+ for (const compact of compacts) {
778
+ const decoded = decodeJws(compact, settings.limits, "cap+party");
779
+ if (!decoded.ok || descriptorClaimsError(decoded.value.payload))
620
780
  return fail("descriptor_chain_invalid");
781
+ entries.push({ compact, digest: taggedHash("party_descriptor_content", decoded.value.payloadBytes), payload: decoded.value.payload });
621
782
  }
783
+ const roots = entries.filter((entry) => entry.payload.descriptor_number === 1);
784
+ if (roots.length !== 1 || new Set(entries.map((entry) => entry.digest)).size !== entries.length)
785
+ return fail("descriptor_chain_invalid");
786
+ const root = descriptorFromCompact(roots[0].compact, null, settings);
787
+ if (!root.ok)
788
+ return historyFailure([root.code]);
789
+ const descriptors = [root.value];
622
790
  const children = new Map();
623
- for (const descriptor of descriptors) {
624
- const prev = descriptor.payload.prev_descriptor_digest;
791
+ for (const entry of entries) {
792
+ const prev = entry.payload.prev_descriptor_digest;
625
793
  if (prev)
626
- children.set(prev, [...(children.get(prev) || []), descriptor.digest]);
627
- }
628
- const fork = [...children.values()].find((values) => values.length > 1);
794
+ children.set(prev, [...(children.get(prev) ?? []), entry]);
795
+ }
796
+ for (let i = 0; i < descriptors.length; i++) {
797
+ const siblings = children.get(descriptors[i].digest) ?? [];
798
+ const results = siblings.map((entry) => descriptorFromCompact(entry.compact, descriptors[i], settings));
799
+ const failures = results.filter((result) => !result.ok).map((result) => result.code);
800
+ if (failures.length > 0)
801
+ return historyFailure(failures);
802
+ for (const result of results)
803
+ if (result.ok)
804
+ descriptors.push(result.value);
805
+ }
806
+ if (descriptors.length !== entries.length)
807
+ return fail("descriptor_chain_invalid");
808
+ const siblings = [...children.values()].filter((group) => group.length > 1).flat().map((entry) => entry.digest);
809
+ const fork = siblings.length > 0;
810
+ descriptors.sort((a, b) => a.payload.descriptor_number - b.payload.descriptor_number || a.digest.localeCompare(b.digest));
629
811
  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() : [] });
812
+ for (const descriptor of descriptors)
813
+ Object.assign(descriptor, { descriptor_position: positions[descriptor.digest] });
814
+ const fork_evidence = fork ? factsRecord({ kind: "sibling_descriptors", sibling_descriptors: [...new Set(siblings)].sort() }) : null;
815
+ return ok(factsRecord({ descriptors, topology: fork ? "forked" : "linear", positions, siblingDescriptors: [...new Set(siblings)].sort(), fork_evidence }));
816
+ }
817
+ function historyFailure(codes) {
818
+ const ordered = ["algorithm_outside_profile", "revision_outside_profile", "algorithm_unsupported_on_substrate"];
819
+ if (codes.some((code) => !ordered.includes(code)))
820
+ return fail("descriptor_chain_invalid");
821
+ return fail(ordered.find((code) => codes.includes(code)));
822
+ }
823
+ function descriptorViews(compacts, settings = DEFAULT_SETTINGS) {
824
+ if (!Array.isArray(compacts))
825
+ return fail("chain_invalid");
826
+ const groups = new Map();
827
+ for (const compact of compacts) {
828
+ const decoded = decodeJws(compact, settings.limits, "cap+party");
829
+ if (!decoded.ok)
830
+ return decoded;
831
+ const shape = descriptorClaimsError(decoded.value.payload);
832
+ if (shape)
833
+ return fail(shape);
834
+ const id = decoded.value.payload.party_id ?? taggedHash("party_descriptor_content", decoded.value.payloadBytes);
835
+ groups.set(id, [...(groups.get(id) ?? []), compact]);
836
+ }
837
+ if (groups.size !== 2)
838
+ return fail("chain_invalid");
839
+ const histories = [];
840
+ for (const id of [...groups.keys()].sort()) {
841
+ const chain = descriptorChain(groups.get(id), settings);
842
+ if (!chain.ok)
843
+ return chain;
844
+ histories.push(chain.value);
845
+ }
846
+ return ok(factsRecord({ histories, descriptors: histories.flatMap((chain) => chain.descriptors),
847
+ positions: Object.assign({}, ...histories.map((chain) => chain.positions)),
848
+ siblingDescriptors: histories.flatMap((chain) => chain.siblingDescriptors),
849
+ topology: histories.some((chain) => chain.topology === "forked") ? "forked" : "linear" }));
631
850
  }
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
851
  const EXTENSION_PROFILES = [
635
852
  { 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
853
  { 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 +875,229 @@ function extensionRegistryDigest() {
658
875
  ]));
659
876
  return taggedHash("extension_registry", Buffer.from(canonical(document)));
660
877
  }
661
- function revisionFromText(text) {
662
- if (typeof text !== "string")
663
- return fail("revision_invalid");
664
- let value;
665
- try {
666
- value = JSON.parse(text);
878
+ function isRecord(value) {
879
+ return value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Number);
880
+ }
881
+ function field(name, type, constraint, required = true) {
882
+ return { name, type, constraint, required };
883
+ }
884
+ const stringBytes = (min, max) => (value) => Buffer.byteLength(value) >= min && Buffer.byteLength(value) <= max;
885
+ const integerRange = (min, max) => (value) => value >= min && value <= max;
886
+ const oneOf = (...values) => (value) => values.includes(value);
887
+ const digestPattern = (value) => /^sha-256:[A-Za-z0-9_-]{43}$/.test(value);
888
+ const digestField = (name, required = true) => field(name, "string", digestPattern, required);
889
+ const safeIntegerField = (name) => field(name, "integer", integerRange(1, Number.MAX_SAFE_INTEGER));
890
+ const roleField = (name) => field(name, "string", stringBytes(1, 128));
891
+ const timeField = (name, required = true) => field(name, "string", stringBytes(1, 64), required);
892
+ const nestedField = (name, type, nested, cardinality) => ({ name, type, required: true, nested, cardinality });
893
+ function schemaError(value, fields) {
894
+ if (!isRecord(value))
895
+ return "invalid_type";
896
+ if (Object.keys(value).some((name) => !fields.some((rule) => rule.name === name)))
897
+ return "unknown_member";
898
+ if (fields.some((rule) => rule.required && !Object.hasOwn(value, rule.name)))
899
+ return "missing_required";
900
+ const present = fields.filter((rule) => Object.hasOwn(value, rule.name));
901
+ for (const rule of present) {
902
+ const item = value[rule.name];
903
+ const typed = rule.type === "object" ? isRecord(item) : rule.type === "array" ? Array.isArray(item) :
904
+ rule.type === "integer" ? typeof item === "number" && Number.isInteger(item) : typeof item === "string";
905
+ if (!typed)
906
+ return "invalid_type";
907
+ }
908
+ if (present.some((rule) => rule.constraint && !rule.constraint(value[rule.name])))
909
+ return "constraint_violation";
910
+ if (present.some((rule) => rule.cardinality && (value[rule.name].length < rule.cardinality[0] || value[rule.name].length > rule.cardinality[1])))
911
+ return "cardinality_violation";
912
+ for (const rule of present) {
913
+ if (!rule.nested)
914
+ continue;
915
+ const items = rule.type === "array" ? value[rule.name] : [value[rule.name]];
916
+ if (items.some((item) => schemaError(item, rule.nested) !== null))
917
+ return "nested_invalid";
667
918
  }
668
- catch (_error) {
669
- return fail("invalid_syntax");
919
+ return null;
920
+ }
921
+ function schemaForType(typ) {
922
+ switch (typ) {
923
+ case "cap+party": return DESCRIPTOR_SCHEMA;
924
+ case "cap+acceptance": return ACCEPTANCE_SCHEMA;
925
+ case "cap+termination": return TERMINATION_SCHEMA;
926
+ case "cap+receipt": return RECEIPT_SCHEMA;
927
+ default: return [];
670
928
  }
671
- if (!value || typeof value !== "object" || Array.isArray(value))
929
+ }
930
+ function integerTokenError(value, fields) {
931
+ if (!isRecord(value))
932
+ return null;
933
+ for (const rule of fields) {
934
+ const item = value[rule.name];
935
+ if (rule.type === "integer" && item instanceof Number)
936
+ return "invalid_type";
937
+ if (!rule.nested)
938
+ continue;
939
+ const items = rule.type === "array" && Array.isArray(item) ? item : [item];
940
+ for (const child of items) {
941
+ const error = integerTokenError(child, rule.nested);
942
+ if (error)
943
+ return error;
944
+ }
945
+ }
946
+ return null;
947
+ }
948
+ const REVISION_SCHEMA = [
949
+ field("protocol_revision", "integer", integerRange(1, 2)), digestField("charter_id", false),
950
+ safeIntegerField("revision_number"), digestField("prev_revision_digest", false),
951
+ nestedField("parties", "array", [digestField("party_descriptor_digest"), roleField("role")], [2, 2]),
952
+ nestedField("legal_text", "object", [digestField("content_digest"), field("media_type", "string", stringBytes(1, 255)), field("uri_hint", "string", stringBytes(1, 2048), false)]),
953
+ field("precedence_declaration", "string", oneOf("legal_text_governs", "machine_terms_govern")),
954
+ nestedField("attribution_declaration", "object", [field("basis", "string", oneOf("bound_deployments", "legal_text")), digestField("detail_digest", false)]),
955
+ timeField("effective_from"), timeField("effective_until", false),
956
+ nestedField("termination_rules", "object", [{ name: "reason_codes", type: "array", required: true, cardinality: [1, 64] }]),
957
+ 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]),
958
+ field("receipt_profile", "string", (v) => stringBytes(3, 512)(v) && /^[a-z0-9][a-z0-9.-]*\/[a-z0-9][a-z0-9.-]*$/.test(v)),
959
+ { name: "supersedes", type: "array", required: false, cardinality: [0, 8] }, field("extensions", "object"),
960
+ ];
961
+ const DESCRIPTOR_SCHEMA = [
962
+ field("protocol_revision", "integer", integerRange(1, 3)), digestField("party_id", false),
963
+ safeIntegerField("descriptor_number"), digestField("prev_descriptor_digest", false),
964
+ nestedField("verification_keys", "array", [
965
+ field("key_id", "string", (v) => /^[A-Za-z0-9._~-]{1,128}$/.test(v)),
966
+ field("algorithm", "string", oneOf("Ed25519", "ML-DSA-44", "ML-DSA-65", "ML-DSA-87")),
967
+ 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)),
968
+ field("status", "string", oneOf("active", "retired")),
969
+ ], [1, 32]),
970
+ nestedField("attestation_hints", "array", [field("kind", "string", stringBytes(1, 64)), field("uri", "string", stringBytes(1, 2048))], [0, 16]),
971
+ field("extensions", "object"), timeField("effective_from"),
972
+ ];
973
+ const ACCEPTANCE_SCHEMA = [
974
+ field("protocol_revision", "integer", integerRange(1, 3)), digestField("charter_id"),
975
+ safeIntegerField("revision_number"), digestField("revision_digest"), digestField("prev_revision_digest", false),
976
+ digestField("party_descriptor_digest"), roleField("party_role"), timeField("accepted_at"),
977
+ ];
978
+ const TERMINATION_SCHEMA = [
979
+ field("protocol_revision", "integer", integerRange(1, 3)), digestField("charter_id"),
980
+ digestField("governing_revision_digest"), digestField("party_descriptor_digest"),
981
+ roleField("party_role"), roleField("reason_code"), timeField("effective_at"), timeField("issued_at"), digestField("detail_digest", false),
982
+ ];
983
+ const RECEIPT_SCHEMA = [
984
+ field("protocol_revision", "integer", integerRange(1, 3)), digestField("charter_id"),
985
+ safeIntegerField("revision_number"), digestField("revision_digest"), roleField("issuing_party_role"), roleField("agent_party_role"), digestField("deployment_digest"),
986
+ nestedField("grant", "object", [field("scheme", "string", oneOf("bap", "host")), field("id", "string", stringBytes(1, 512)), digestField("grant_digest", false)]),
987
+ field("invocation_id", "string", stringBytes(1, 512)), field("decision", "string", oneOf("accepted", "rejected")),
988
+ field("outcome", "string", oneOf("effect_committed", "no_effect", "indeterminate")),
989
+ timeField("occurred_at"), timeField("recorded_at"), field("extensions", "object"),
990
+ ];
991
+ 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(" "));
992
+ const INDEXED_TERMS_SCHEMA = [
993
+ field("currency", "string", (v) => INDEXED_CURRENCIES.has(v)),
994
+ field("base_amount_minor", "integer", integerRange(0, Number.MAX_SAFE_INTEGER)),
995
+ nestedField("index", "object", [digestField("series_document_digest"), field("series_id", "string", stringBytes(1, 128)), field("observation_lag_days", "integer", integerRange(0, 90))]),
996
+ field("formula", "string", oneOf("index_plus_spread")),
997
+ field("spread_bps", "integer", integerRange(-10000, 10000)),
998
+ field("floor_amount_minor", "integer", integerRange(0, Number.MAX_SAFE_INTEGER), false),
999
+ field("cap_amount_minor", "integer", integerRange(0, Number.MAX_SAFE_INTEGER), false),
1000
+ field("tolerance_bps", "integer", integerRange(0, 10000)),
1001
+ ];
1002
+ const INDEXED_OBSERVATION_SCHEMA = [
1003
+ digestField("observed_index_digest"), field("observation_instant", "string", (v) => parseTimestamp(v) !== null),
1004
+ field("computed_amount_minor", "integer", integerRange(0, Number.MAX_SAFE_INTEGER)),
1005
+ ];
1006
+ function indexedBodyError(namespace, body) {
1007
+ const shape = schemaError(body, namespace === "com.example/pricing-indexed" ? INDEXED_TERMS_SCHEMA : INDEXED_OBSERVATION_SCHEMA);
1008
+ if (shape)
1009
+ return shape;
1010
+ const values = body;
1011
+ if (namespace === "com.example/pricing-indexed" && values.floor_amount_minor !== undefined && values.cap_amount_minor !== undefined && values.floor_amount_minor > values.cap_amount_minor)
1012
+ return "cross_field_invalid";
1013
+ return null;
1014
+ }
1015
+ function extensionError(envelope, surface) {
1016
+ if (!isRecord(envelope))
1017
+ return "invalid_type";
1018
+ if (!exactKeys(envelope, ["critical", "optional"]) || !isRecord(envelope.critical) || !isRecord(envelope.optional))
1019
+ return "unknown_member";
1020
+ const names = [...Object.keys(envelope.critical), ...Object.keys(envelope.optional)];
1021
+ if (names.some((namespace) => !stringBytes(1, 512)(namespace) || !/^[a-z0-9][a-z0-9.-]*\/[a-z0-9][a-z0-9.-]*$/.test(namespace)))
1022
+ return "extension_namespace_invalid";
1023
+ if (new Set(names).size !== names.length)
1024
+ return "extension_duplicate";
1025
+ if (names.length > 32)
1026
+ return "cardinality_violation";
1027
+ for (const position of ["critical", "optional"]) {
1028
+ for (const namespace of Object.keys(envelope[position])) {
1029
+ const entry = EXTENSION_PROFILES.find((profile) => profile.namespace === namespace);
1030
+ if (!entry || entry.state === "reserved" || entry.state === "retired") {
1031
+ if (position === "optional")
1032
+ continue;
1033
+ return entry?.state === "retired" ? "extension_retired" : "extension_unknown_critical";
1034
+ }
1035
+ if (entry.criticality !== position)
1036
+ return "extension_criticality_conflict";
1037
+ if (entry.surface !== surface)
1038
+ return "extension_scope_invalid";
1039
+ if (entry.schema_digest === null)
1040
+ return "extension_schema_unavailable";
1041
+ const body = indexedBodyError(namespace, envelope[position][namespace]);
1042
+ if (body)
1043
+ return body;
1044
+ }
1045
+ }
1046
+ return null;
1047
+ }
1048
+ function validTaggedDigest(value) {
1049
+ return digestPattern(value) && strictBase64url(value.slice(8)).ok;
1050
+ }
1051
+ function revisionFromText(text, limits = DEFAULT_LIMITS) {
1052
+ if (typeof text !== "string")
1053
+ return fail("invalid_type");
1054
+ const decoded = decodeJsonText(text, limits);
1055
+ if (!decoded.ok)
1056
+ return decoded;
1057
+ const integerError = integerTokenError(decoded.value, REVISION_SCHEMA);
1058
+ if (integerError)
1059
+ return fail(integerError);
1060
+ const encoding = canonicalTextError(decoded.value, text);
1061
+ if (encoding)
1062
+ return fail(encoding);
1063
+ const value = decoded.value;
1064
+ const shape = schemaError(value, REVISION_SCHEMA);
1065
+ if (shape)
1066
+ return fail(shape);
1067
+ 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);
1068
+ if (digests.some((v) => !validTaggedDigest(v)))
672
1069
  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)
1070
+ const from = parseTimestamp(value.effective_from);
1071
+ const until = value.effective_until === undefined ? null : parseTimestamp(value.effective_until);
1072
+ if (!from || (value.effective_until !== undefined && !until))
1073
+ return fail("timestamp_invalid");
1074
+ const reasons = value.termination_rules.reason_codes;
1075
+ if (reasons.some((v) => typeof v !== "string" || !stringBytes(1, 128)(v)) || new Set(reasons).size !== reasons.length)
680
1076
  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))
1077
+ if (value.abp_bindings.some((binding) => !validTaggedDigest(binding.content_digest) || !validTaggedDigest(binding.deployment_digest)))
684
1078
  return fail("revision_invalid");
685
- if (value.supersedes !== undefined && (!Array.isArray(value.supersedes) || value.supersedes.some((one) => typeof one !== "string")))
1079
+ const supersedes = value.supersedes ?? [];
1080
+ if (supersedes.some((v) => typeof v !== "string" || !validTaggedDigest(v)) || new Set(supersedes).size !== supersedes.length)
1081
+ return fail("revision_invalid");
1082
+ const extensions = extensionError(value.extensions, "charter_revision");
1083
+ if (extensions)
1084
+ return fail(extensions);
1085
+ if (!EXTENSION_PROFILES.some((profile) => profile.namespace === value.receipt_profile && profile.surface === "receipt" && profile.state === "active" && profile.criticality === "optional"))
1086
+ return fail("revision_invalid");
1087
+ 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))
1088
+ return fail("revision_invalid");
1089
+ if (until && compareTimestamps(from, until) >= 0)
1090
+ return fail("revision_invalid");
1091
+ const roles = value.parties.map((party) => party.role);
1092
+ if (new Set(value.parties.map((party) => party.party_descriptor_digest)).size !== value.parties.length)
1093
+ return fail("revision_invalid");
1094
+ if (new Set(roles).size !== roles.length || value.abp_bindings.some((binding) => !roles.includes(binding.party_role)))
686
1095
  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
1096
  const bytes = Buffer.from(text);
720
- return ok({ value, bytes, digest: taggedHash("charter_revision_content", bytes) });
1097
+ return ok(factsRecord({ value, bytes, digest: taggedHash("charter_revision_content", bytes), protocol_revision: value.protocol_revision }));
721
1098
  }
722
- function acceptanceFromCompact(compact, revision, chain) {
723
- const decoded = decodeJws(compact);
1099
+ function prepareAcceptance(compact, revision, chain, settings = DEFAULT_SETTINGS) {
1100
+ const decoded = decodeJws(compact, settings.limits, "cap+acceptance");
724
1101
  if (!decoded.ok)
725
1102
  return decoded;
726
1103
  const claims = decoded.value.payload;
@@ -728,31 +1105,45 @@ function acceptanceFromCompact(compact, revision, chain) {
728
1105
  if (acceptanceShape)
729
1106
  return fail(acceptanceShape);
730
1107
  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
1108
  const expectedCharter = revision.value.charter_id || revision.digest;
734
1109
  const party = revision.value.parties.find((one) => one.party_descriptor_digest === claims.party_descriptor_digest);
735
1110
  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
1111
  if (mismatch)
737
1112
  return fail("acceptance_claims_mismatch");
738
- return ok({ claims, digest: taggedHash("acceptance_content", decoded.value.payloadBytes), descriptorPosition: chain.positions[claims.party_descriptor_digest] });
1113
+ if (!descriptor)
1114
+ return fail("acceptance_claims_mismatch");
1115
+ const acceptanceAdmission = profileError(decoded.value.header.alg, claims.protocol_revision, settings);
1116
+ if (acceptanceAdmission)
1117
+ return fail(acceptanceAdmission);
1118
+ const facts = 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 });
1119
+ return preparedArtifact(decoded.value, descriptor.payload.verification_keys, facts, "acceptance_invalid");
739
1120
  }
740
- function terminationFromCompact(compact, revision, chain) {
741
- const decoded = decodeJws(compact);
1121
+ function acceptanceFromCompact(compact, revision, chain, settings = DEFAULT_SETTINGS) {
1122
+ return finishPreparedArtifact(prepareAcceptance(compact, revision, chain, settings), settings);
1123
+ }
1124
+ function prepareTermination(compact, revision, chain, settings = DEFAULT_SETTINGS) {
1125
+ const decoded = decodeJws(compact, settings.limits, "cap+termination");
742
1126
  if (!decoded.ok)
743
1127
  return decoded;
744
1128
  const claims = decoded.value.payload;
1129
+ const terminationShape = terminationClaimsError(claims);
1130
+ if (terminationShape)
1131
+ return fail(terminationShape);
745
1132
  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
1133
  const expectedCharter = revision.value.charter_id || revision.digest;
749
1134
  const party = revision.value.parties.find((one) => one.party_descriptor_digest === claims.party_descriptor_digest);
750
1135
  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
1136
  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] });
1137
+ if (!descriptor)
1138
+ return fail("termination_claims_mismatch");
1139
+ const terminationAdmission = profileError(decoded.value.header.alg, claims.protocol_revision, settings);
1140
+ if (terminationAdmission)
1141
+ return fail(terminationAdmission);
1142
+ const facts = 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 });
1143
+ return preparedArtifact(decoded.value, descriptor.payload.verification_keys, facts, "termination_invalid");
1144
+ }
1145
+ function terminationFromCompact(compact, revision, chain, settings = DEFAULT_SETTINGS) {
1146
+ return finishPreparedArtifact(prepareTermination(compact, revision, chain, settings), settings);
756
1147
  }
757
1148
  // Chain-level structural checks mirroring Chain.verify: unique revision
758
1149
  // digests, exactly one genesis defining one charter identity, exact
@@ -784,7 +1175,7 @@ const KNOWN_ANSWERS = {
784
1175
  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
1176
  },
786
1177
  };
787
- function katVerifies(keyAlgorithm) {
1178
+ function katVerifies(keyAlgorithm, message = KNOWN_ANSWER_MESSAGE) {
788
1179
  const vector = KNOWN_ANSWERS[keyAlgorithm];
789
1180
  if (!vector)
790
1181
  return false;
@@ -797,21 +1188,48 @@ function katVerifies(keyAlgorithm) {
797
1188
  Buffer.from(vector.publicKey, "base64url"),
798
1189
  ]);
799
1190
  const key = createPublicKey({ key: spki, format: "der", type: "spki" });
800
- return nodeVerifySignature(null, KNOWN_ANSWER_MESSAGE, key, signature);
1191
+ return nodeVerifySignature(null, message, key, signature);
801
1192
  }
802
1193
  catch (_error) {
803
1194
  return false;
804
1195
  }
805
1196
  }
806
- return mldsa(keyAlgorithm, vector.publicKey, KNOWN_ANSWER_MESSAGE, signature);
1197
+ return mldsa(keyAlgorithm, vector.publicKey, message, signature);
1198
+ }
1199
+ // The known-answer signature over any other message must fail: a runtime
1200
+ // whose verify accepts everything is never counted as supporting a key type.
1201
+ const KNOWN_ANSWER_TAMPERED = Buffer.from("charter-agreement-protocol capability known-answer, tampered");
1202
+ // Keep the declared type and known-answer result once per key algorithm.
1203
+ const RUNTIME_SUPPORT = new Map();
1204
+ function runtimeSupportsAlgorithm(keyAlgorithm) {
1205
+ const known = RUNTIME_SUPPORT.get(keyAlgorithm);
1206
+ if (known !== undefined)
1207
+ return known;
1208
+ const vector = KNOWN_ANSWERS[keyAlgorithm];
1209
+ if (!vector)
1210
+ return false;
1211
+ const prefix = keyAlgorithm === "Ed25519" ? Buffer.from("302a300506032b6570032100", "hex") : ML_DSA_SPKI_PREFIXES[keyAlgorithm];
1212
+ let declared = false;
1213
+ try {
1214
+ const key = createPublicKey({ key: Buffer.concat([prefix, Buffer.from(vector.publicKey, "base64url")]), format: "der", type: "spki" });
1215
+ declared = key.asymmetricKeyType === undefined || key.asymmetricKeyType === keyAlgorithm.toLowerCase();
1216
+ }
1217
+ catch (_error) {
1218
+ declared = false;
1219
+ }
1220
+ const supported = declared && katVerifies(keyAlgorithm) && !katVerifies(keyAlgorithm, KNOWN_ANSWER_TAMPERED);
1221
+ RUNTIME_SUPPORT.set(keyAlgorithm, supported);
1222
+ return supported;
807
1223
  }
808
1224
  export function capabilities() {
809
1225
  const algorithms = ALG_ROWS.map((row) => ({
810
1226
  name: row.name,
811
1227
  keyAlgorithm: row.keyAlgorithm,
812
- verifiable: katVerifies(row.keyAlgorithm),
1228
+ verifiable: runtimeSupportsAlgorithm(row.keyAlgorithm),
813
1229
  }));
814
- return { linkedCrypto: process.versions.openssl ?? "", algorithms };
1230
+ // A browser page has no `process`; it then reports no linked library.
1231
+ const versions = typeof process === "undefined" ? undefined : process.versions;
1232
+ return { linkedCrypto: versions?.openssl ?? "", algorithms };
815
1233
  }
816
1234
  // The signature registry's published identity, mirroring the reference
817
1235
  // Algorithm.registry_digest/0 byte for byte: the canonical object of every
@@ -841,8 +1259,9 @@ function parseProfile(spec) {
841
1259
  const names = spec.algorithms;
842
1260
  if (names.length === 0 || new Set(names).size !== names.length)
843
1261
  return { ok: false, code: "invalid_profile" };
844
- if (!names.every((name) => typeof name === "string" && registryNames.includes(name))) {
845
- return { ok: false, code: "invalid_profile" };
1262
+ for (const name of names) {
1263
+ if (typeof name !== "string" || !registryNames.includes(name))
1264
+ return { ok: false, code: "invalid_profile" };
846
1265
  }
847
1266
  algorithms = names;
848
1267
  }
@@ -863,76 +1282,73 @@ function parseProfile(spec) {
863
1282
  }
864
1283
  return { ok: true, algorithms, minRevision, maxRevision };
865
1284
  }
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);
1285
+ const DEFAULT_SETTINGS = { limits: DEFAULT_LIMITS, profile: { algorithms: ALG_ROWS.map((row) => row.name), minRevision: 1, maxRevision: 3 } };
1286
+ function resolveOptions(options = {}) {
1287
+ if (!isRecord(options) || (options.limits !== undefined && !validLimits(options.limits)))
1288
+ return fail("invalid_limits");
1289
+ if (options.profile !== undefined && (!isRecord(options.profile) || Object.keys(options.profile).some((key) => key !== "algorithms" && key !== "revisions")))
1290
+ return fail("invalid_profile");
1291
+ const profile = parseProfile(options.profile);
877
1292
  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";
1293
+ return fail("invalid_profile");
1294
+ return ok({ limits: { ...DEFAULT_LIMITS, ...options.limits }, profile });
1295
+ }
1296
+ function profileError(alg, revision, settings) {
1297
+ if (alg !== null && !settings.profile.algorithms.includes(alg))
1298
+ return "algorithm_outside_profile";
1299
+ if (revision < settings.profile.minRevision || revision > settings.profile.maxRevision)
1300
+ return "revision_outside_profile";
1301
+ return null;
1302
+ }
1303
+ function revisionWithProfile(text, settings) {
1304
+ const revision = revisionFromText(text, settings.limits);
1305
+ if (!revision.ok)
1306
+ return revision;
1307
+ const admission = profileError(null, revision.value.value.protocol_revision, settings);
1308
+ return admission ? fail(admission) : revision;
1309
+ }
1310
+ function boundedArtifacts(lists, limits) {
1311
+ if (!lists.every(Array.isArray))
1312
+ return "invalid_type";
1313
+ let bytes = 0;
1314
+ for (const list of lists) {
1315
+ for (let i = 0; i < list.length; i++) {
1316
+ if (i >= limits.max_artifact_set_items)
1317
+ return "limit_exceeded";
1318
+ if (typeof list[i] !== "string")
1319
+ return "invalid_type";
904
1320
  }
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) {
924
- if (!Array.isArray(input.revisions) || input.revisions.length === 0)
1321
+ bytes += list.reduce((total, text) => total + Buffer.byteLength(text), 0);
1322
+ if (bytes > limits.max_artifact_set_bytes)
1323
+ return "limit_exceeded";
1324
+ }
1325
+ return null;
1326
+ }
1327
+ function chainWithOptions(input, options = {}) {
1328
+ const settings = resolveOptions(options);
1329
+ return settings.ok ? chainFromInput(input, settings.value) : settings;
1330
+ }
1331
+ function chainFromInput(input, settings = DEFAULT_SETTINGS) {
1332
+ if (!isRecord(input))
925
1333
  return fail("chain_invalid");
926
- const descriptors = descriptorChain(input.descriptors);
1334
+ const bounded = boundedArtifacts([input.revisions, input.acceptances, input.descriptors, input.terminations], settings.limits);
1335
+ if (bounded)
1336
+ return fail(bounded);
1337
+ const descriptors = descriptorViews(input.descriptors, settings);
927
1338
  if (!descriptors.ok)
928
- return fail("chain_invalid");
1339
+ return descriptors;
929
1340
  const revisions = [];
930
1341
  for (const text of input.revisions) {
931
- const revision = revisionFromText(text);
1342
+ const revision = revisionFromText(text, settings.limits);
932
1343
  if (!revision.ok)
933
- return fail("chain_invalid");
1344
+ return revision;
934
1345
  revisions.push(revision.value);
935
1346
  }
1347
+ for (const revision of revisions) {
1348
+ const admission = profileError(null, revision.value.protocol_revision, settings);
1349
+ if (admission)
1350
+ return fail(admission);
1351
+ }
936
1352
  const byDigest = new Map(revisions.map((one) => [one.digest, one]));
937
1353
  if (byDigest.size !== revisions.length)
938
1354
  return fail("chain_invalid");
@@ -958,35 +1374,36 @@ function chainFromInput(input) {
958
1374
  }
959
1375
  }
960
1376
  }
1377
+ const owners = new Map(descriptors.value.descriptors.map((one) => [one.digest, one.payload.party_id ?? one.digest]));
1378
+ const named = new Set();
1379
+ for (const revision of revisions) {
1380
+ const parties = revision.value.parties.map((party) => owners.get(party.party_descriptor_digest)).filter((id) => id !== undefined);
1381
+ if (new Set(parties).size !== parties.length)
1382
+ return fail("chain_invalid");
1383
+ for (const id of parties)
1384
+ named.add(id);
1385
+ }
1386
+ if (descriptors.value.histories.some((history) => !named.has(history.descriptors[0].payload.party_id ?? history.descriptors[0].digest)))
1387
+ return fail("chain_invalid");
961
1388
  const acceptances = [];
962
1389
  const coordinates = new Set();
963
1390
  for (const compact of (input.acceptances || [])) {
964
- const decoded = decodeJws(compact);
1391
+ const decoded = decodeJws(compact, settings.limits, "cap+acceptance");
965
1392
  if (!decoded.ok)
966
- return fail("chain_invalid");
967
- const revision = byDigest.get(decoded.value.payload.revision_digest);
968
- if (!revision)
969
- return fail("chain_invalid");
970
- const verified = acceptanceFromCompact(compact, revision, descriptors.value);
1393
+ return decoded;
1394
+ const routed = signingContextFromSet(byDigest, descriptors.value, decoded.value.payload.revision_digest, decoded.value.payload.party_descriptor_digest);
1395
+ if (!routed.ok)
1396
+ return routed;
1397
+ const { revision, chain } = routed.value;
1398
+ const verified = acceptanceFromCompact(compact, revision, chain, settings);
971
1399
  if (!verified.ok)
972
- return fail("chain_invalid");
1400
+ return verified;
973
1401
  const coordinate = `${verified.value.claims.revision_digest}\0${verified.value.claims.party_descriptor_digest}\0${verified.value.claims.party_role}`;
974
1402
  if (coordinates.has(coordinate))
975
1403
  return fail("chain_invalid");
976
1404
  coordinates.add(coordinate);
977
1405
  acceptances.push(verified.value);
978
1406
  }
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
1407
  const accepted = revisions.filter((revision) => {
991
1408
  const expected = new Set(revision.value.parties.map((party) => `${party.party_descriptor_digest}\0${party.role}`));
992
1409
  const actual = new Set(acceptances
@@ -999,6 +1416,23 @@ function chainFromInput(input) {
999
1416
  return false;
1000
1417
  return true;
1001
1418
  });
1419
+ const acceptedSet = new Set(accepted.map((one) => one.digest));
1420
+ if (accepted.some((one) => (one.value.supersedes ?? []).some((digest) => !acceptedSet.has(digest))))
1421
+ return fail("chain_invalid");
1422
+ const terminations = [];
1423
+ for (const compact of (input.terminations || [])) {
1424
+ const decoded = decodeJws(compact, settings.limits, "cap+termination");
1425
+ if (!decoded.ok)
1426
+ return decoded;
1427
+ const routed = signingContextFromSet(byDigest, descriptors.value, decoded.value.payload.governing_revision_digest, decoded.value.payload.party_descriptor_digest);
1428
+ if (!routed.ok)
1429
+ return routed;
1430
+ const { revision, chain } = routed.value;
1431
+ const verified = terminationFromCompact(compact, revision, chain, settings);
1432
+ if (!verified.ok)
1433
+ return verified;
1434
+ terminations.push(verified.value);
1435
+ }
1002
1436
  const superseded = new Set(accepted.flatMap((one) => one.value.supersedes || []));
1003
1437
  const active = accepted.filter((one) => !superseded.has(one.digest));
1004
1438
  const maximum = Math.max(...active.map((one) => one.value.revision_number));
@@ -1022,7 +1456,15 @@ function chainFromInput(input) {
1022
1456
  };
1023
1457
  const linear = heads.length === 1 && ancestryCovers(heads[0].digest);
1024
1458
  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 });
1459
+ return ok(factsRecord({ descriptors: descriptors.value, revisions, acceptances, terminations, accepted, acceptedDigests: accepted.map((one) => one.digest).sort(), supersededDigests: [...superseded].sort(), topology, charterId }));
1460
+ }
1461
+ // Both set verification and pre-sign checks route through this lookup.
1462
+ function signingContextFromSet(revisions, descriptors, revisionDigest, descriptorDigest, code = "chain_invalid") {
1463
+ if (typeof revisionDigest !== "string" || typeof descriptorDigest !== "string")
1464
+ return fail(code);
1465
+ const revision = revisions.get(revisionDigest);
1466
+ const chain = descriptors.histories.find((history) => history.descriptors.some((one) => one.digest === descriptorDigest));
1467
+ return revision && chain ? ok({ revision, chain }) : fail(code);
1026
1468
  }
1027
1469
  // Governing mirrors the reference semantics exactly: candidates are accepted,
1028
1470
  // non-superseded, and effective at the instant (start-inclusive, end-exclusive
@@ -1039,6 +1481,14 @@ function effectiveAt(revision, at) {
1039
1481
  return until !== null && compareTimestamps(at, until) < 0;
1040
1482
  }
1041
1483
  function governing(chain, at) {
1484
+ const closed = chain.terminations.some((notice) => {
1485
+ const effective = parseTimestamp(notice.claims.effective_at);
1486
+ return compareTimestamps(effective, at) <= 0 &&
1487
+ selectGoverning(chain, effective) === notice.claims.governing_revision_digest;
1488
+ });
1489
+ return closed ? "none" : selectGoverning(chain, at);
1490
+ }
1491
+ function selectGoverning(chain, at) {
1042
1492
  const applicable = chain.accepted.filter((one) => !chain.supersededDigests.includes(one.digest) && effectiveAt(one, at));
1043
1493
  if (applicable.length === 0)
1044
1494
  return "none";
@@ -1093,8 +1543,10 @@ function receiptSigningKeys(chain, claimedRevision, role) {
1093
1543
  }));
1094
1544
  return [...new Map(keys.map((key) => [canonical(key), key])).values()];
1095
1545
  }
1096
- function receiptFromCompact(compact, chain) {
1097
- const decoded = decodeJws(compact);
1546
+ function prepareReceipt(compact, context, settings = DEFAULT_SETTINGS) {
1547
+ const revisionOnly = context.kind === "revision";
1548
+ const chain = context.kind === "chain" ? context.chain : { accepted: [context.revision], charterId: context.revision.value.charter_id || context.revision.digest };
1549
+ const decoded = decodeJws(compact, settings.limits, "cap+receipt");
1098
1550
  if (!decoded.ok)
1099
1551
  return decoded;
1100
1552
  const claims = decoded.value.payload;
@@ -1102,73 +1554,320 @@ function receiptFromCompact(compact, chain) {
1102
1554
  if (receiptShape)
1103
1555
  return fail(receiptShape);
1104
1556
  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
1557
  const receiptTiming = receiptTimingError(claims);
1111
1558
  if (receiptTiming)
1112
1559
  return fail(receiptTiming);
1113
- const governingDigest = governing(chain, parseTimestamp(claims.occurred_at));
1560
+ const governingDigest = context.kind === "revision" ? "contested" : governing(context.chain, parseTimestamp(claims.occurred_at));
1114
1561
  const projection = projectReceipt(claims, chain, governingDigest);
1115
1562
  if (!projection.ok)
1116
1563
  return projection;
1117
- return ok({ claims, digest: taggedHash("receipt_content", decoded.value.payloadBytes), ...projection.value, optionalExtensions: Object.keys(claims.extensions?.optional || {}).sort() });
1564
+ if (revisionOnly) {
1565
+ if (!claimedRevision)
1566
+ return fail("receipt_claims_mismatch");
1567
+ const admission = profileError(decoded.value.header.alg, claims.protocol_revision, settings);
1568
+ if (admission)
1569
+ return fail(admission);
1570
+ const facts = 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"]);
1571
+ return preparedArtifact(decoded.value, [], facts, "signature_invalid", true);
1572
+ }
1573
+ // The envelope is admitted before any key is looked up, so an
1574
+ // out-of-profile receipt reports the profile rejection in both context
1575
+ // forms, even when its kid names no key in the view.
1576
+ const envelopeAdmission = profileError(decoded.value.header.alg, claims.protocol_revision, settings);
1577
+ if (envelopeAdmission)
1578
+ return fail(envelopeAdmission);
1579
+ const keys = receiptSigningKeys(context.chain, claimedRevision, claims.issuing_party_role);
1580
+ const facts = 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 });
1581
+ return preparedArtifact(decoded.value, keys, facts, "signature_invalid");
1582
+ }
1583
+ function receiptFromCompact(compact, context, settings = DEFAULT_SETTINGS) {
1584
+ return finishPreparedArtifact(prepareReceipt(compact, context, settings), settings);
1585
+ }
1586
+ function receiptWithContext(compact, context, settings) {
1587
+ if (typeof context === "string") {
1588
+ const revision = revisionWithProfile(context, settings);
1589
+ if (!revision.ok)
1590
+ return revision;
1591
+ return receiptFromCompact(compact, { kind: "revision", revision: revision.value }, settings);
1592
+ }
1593
+ if (!isRecord(context))
1594
+ return fail("invalid_type");
1595
+ const chain = chainFromInput(context, settings);
1596
+ return chain.ok ? receiptFromCompact(compact, { kind: "chain", chain: chain.value }, settings) : chain;
1597
+ }
1598
+ const CASE_OPTION_MEMBERS = {
1599
+ limits: Object.fromEntries(Object.keys(DEFAULT_LIMITS).map((name) => [name, name])),
1600
+ profile: { algorithms: "algorithms", revisions: "revisions" },
1601
+ revisions: { min: "min", max: "max" },
1602
+ };
1603
+ function mappedCaseOptions(selected, kind) {
1604
+ if (!isRecord(selected))
1605
+ return fail("invalid_type");
1606
+ const members = CASE_OPTION_MEMBERS[kind];
1607
+ const mapped = {};
1608
+ for (const [name, value] of Object.entries(selected)) {
1609
+ if (!Object.hasOwn(members, name))
1610
+ return fail("invalid_type");
1611
+ mapped[members[name]] = value;
1612
+ }
1613
+ return ok(mapped);
1614
+ }
1615
+ function closedCaseOptions(input) {
1616
+ const limits = mappedCaseOptions(Object.hasOwn(input, "limits") ? input.limits : {}, "limits");
1617
+ if (!limits.ok || !validLimits(limits.value))
1618
+ return fail("invalid_limits");
1619
+ const profile = mappedCaseOptions(Object.hasOwn(input, "profile") ? input.profile : {}, "profile");
1620
+ if (!profile.ok)
1621
+ return fail("invalid_profile");
1622
+ const range = mappedCaseOptions(Object.hasOwn(profile.value, "revisions") ? profile.value.revisions : {}, "revisions");
1623
+ if (!range.ok || !parseProfile(profile.value).ok)
1624
+ return fail("invalid_profile");
1625
+ return ok(null);
1626
+ }
1627
+ function signingCaseContext(context, options) {
1628
+ if (!isRecord(context))
1629
+ return ok({ value: context, kind: context === null ? "descriptor" : "raw" });
1630
+ if ("set" in context) {
1631
+ const set = context.set;
1632
+ const members = ["revisions", "acceptances", "descriptors", "terminations"];
1633
+ if (!isRecord(set))
1634
+ return fail("invalid_type");
1635
+ return ok({ value: Object.fromEntries(members.map((name) => [name, set?.[name] ?? null])), kind: "set" });
1636
+ }
1637
+ if ("chain" in context) {
1638
+ if (!exactKeys(context.chain, [...CHAIN_MEMBERS]))
1639
+ return fail("invalid_type");
1640
+ const verified = chainWithOptions(context.chain, { limits: options.limits });
1641
+ return verified.ok ? ok({ value: context.chain, kind: "chain" }) : fail(verified.code);
1642
+ }
1643
+ if ("revision_text" in context) {
1644
+ const decoded = decodeCharterRevision(context.revision_text);
1645
+ return decoded.ok ? ok({ value: context.revision_text, kind: "revision" }) : fail(decoded.code);
1646
+ }
1647
+ if ("predecessor_compacts" in context) {
1648
+ if (!Array.isArray(context.predecessor_compacts))
1649
+ return fail("invalid_type");
1650
+ let previous = null;
1651
+ for (const compact of context.predecessor_compacts) {
1652
+ if (typeof compact !== "string")
1653
+ return fail("invalid_type");
1654
+ const verified = verifyDescriptor(compact, previous);
1655
+ if (!verified.ok)
1656
+ return fail(verified.code);
1657
+ previous = verified.facts;
1658
+ }
1659
+ return ok({ value: previous, kind: "descriptor" });
1660
+ }
1661
+ return ok({ value: context, kind: "raw" });
1662
+ }
1663
+ function signingCaseOptions(input) {
1664
+ const limits = input.limits ?? {};
1665
+ const selectedProfile = input.profile ?? {};
1666
+ const range = selectedProfile.revisions;
1667
+ const profile = {
1668
+ algorithms: Object.hasOwn(selectedProfile, "algorithms") ? selectedProfile.algorithms : DEFAULT_SETTINGS.profile.algorithms,
1669
+ revisions: range ? { min: range.min, max: range.max } : { min: 1, max: 3 },
1670
+ };
1671
+ return { algorithm: input.algorithm, limits, profile };
1672
+ }
1673
+ function executeArtifactCase(one) {
1674
+ const input = one.input;
1675
+ switch (one.surface) {
1676
+ case "signing.prepare": {
1677
+ const options = signingCaseOptions(input);
1678
+ const context = signingCaseContext(input.context, options);
1679
+ if (!context.ok)
1680
+ return invalid(context.code);
1681
+ const key = strictBase64url(input.public_key);
1682
+ if (!key.ok)
1683
+ return invalid(key.code);
1684
+ const kind = input.kind === "party_descriptor" ? "descriptor" :
1685
+ ["acceptance", "termination", "receipt"].includes(input.kind) ? input.kind : "unknown";
1686
+ const matches = kind === "descriptor" ? context.value.kind === "descriptor" :
1687
+ kind === "receipt" ? ["chain", "revision"].includes(context.value.kind) :
1688
+ (kind === "acceptance" || kind === "termination") && context.value.kind === "set";
1689
+ const prepared = prepareSigning(kind, input.kid, input.claims, encodeBase64url(key.value), matches ? context.value.value : {}, options);
1690
+ if (!prepared.ok)
1691
+ return invalid(prepared.code);
1692
+ return valid({ protected_segment: prepared.plan.input.protectedSegment, payload_segment: prepared.plan.input.payloadSegment, key: prepared.plan.key });
1693
+ }
1694
+ case "party_descriptor.verify": {
1695
+ // A case may name its predecessor history, genesis first; each entry
1696
+ // verifies under the full profile against the one before it.
1697
+ let predecessor = null;
1698
+ if (input.predecessor_compacts !== undefined && !Array.isArray(input.predecessor_compacts))
1699
+ return invalid("invalid_type");
1700
+ for (const compact of (input.predecessor_compacts ?? [])) {
1701
+ if (typeof compact !== "string")
1702
+ return invalid("invalid_type");
1703
+ const verified = verifyDescriptor(compact, predecessor);
1704
+ if (!verified.ok)
1705
+ return invalid(verified.code);
1706
+ predecessor = verified.facts;
1707
+ }
1708
+ const verified = verifyDescriptor(input.compact, predecessor, { profile: input.profile });
1709
+ if (!verified.ok)
1710
+ return invalid(verified.code);
1711
+ return valid({ descriptor_digest: verified.facts.descriptor_digest, party_id: verified.facts.party_id, descriptor_number: verified.facts.descriptor_number });
1712
+ }
1713
+ case "acceptance.verify": {
1714
+ // The runner calls the public function, so the corpus checks the code
1715
+ // consumers run.
1716
+ const verified = verifyAcceptance(input.compact, input.revision_text, input.descriptor_compacts, { profile: input.profile });
1717
+ if (!verified.ok)
1718
+ return invalid(verified.code);
1719
+ 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 });
1720
+ }
1721
+ case "termination.verify": {
1722
+ const verified = verifyTermination(input.compact, input.revision_text, input.descriptor_compacts, { profile: input.profile });
1723
+ if (!verified.ok)
1724
+ return invalid(verified.code);
1725
+ 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 });
1726
+ }
1727
+ case "receipt.verify": {
1728
+ const settings = resolveOptions({ limits: input.limits, profile: input.profile });
1729
+ if (!settings.ok)
1730
+ return invalid(settings.code);
1731
+ if (!Object.hasOwn(input, "revision_text") && !exactKeys(input.chain, [...CHAIN_MEMBERS]))
1732
+ return invalid("invalid_type");
1733
+ if (!Object.hasOwn(input, "revision_text")) {
1734
+ const context = chainWithOptions(input.chain, { limits: input.limits });
1735
+ if (!context.ok)
1736
+ return invalid(context.code);
1737
+ }
1738
+ return project(receiptWithContext(input.compact, Object.hasOwn(input, "revision_text") ? 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 }));
1739
+ }
1740
+ default:
1741
+ return null;
1742
+ }
1118
1743
  }
1119
1744
  function execute(one) {
1745
+ try {
1746
+ if (!isRecord(one) || !isRecord(one.input))
1747
+ return invalid("invalid_type");
1748
+ return executeInputCase(one);
1749
+ }
1750
+ catch (_error) {
1751
+ return invalid("invalid_type");
1752
+ }
1753
+ }
1754
+ function isIntegerToken(value) {
1755
+ return typeof value === "bigint" || (typeof value === "number" && Number.isInteger(value));
1756
+ }
1757
+ function caseKindMatches(input) {
1758
+ const value = input.value;
1759
+ switch (input.kind) {
1760
+ case "integer": return isIntegerToken(value);
1761
+ case "float": return value instanceof Number || (typeof value === "number" && !Number.isInteger(value));
1762
+ case "string": return typeof value === "string";
1763
+ case "boolean": return typeof value === "boolean";
1764
+ case "null": return value === null;
1765
+ case "array": return Array.isArray(value);
1766
+ case "object": return isRecord(value);
1767
+ default: return false;
1768
+ }
1769
+ }
1770
+ function canonicalInteger(value) {
1771
+ const integer = BigInt(value);
1772
+ return integer > MAXIMUM_SAFE_INTEGER || integer < -MAXIMUM_SAFE_INTEGER ? invalid("integer_magnitude") :
1773
+ valid({ text: integer.toString() });
1774
+ }
1775
+ function executeCanonicalCase(input) {
1776
+ if (Object.hasOwn(input, "text")) {
1777
+ const decoded = decodeJsonText(input.text);
1778
+ if (!decoded.ok)
1779
+ return invalid(decoded.code);
1780
+ return canonical(decoded.value) === input.text ? valid({ text: input.text }) : invalid("non_canonical_bytes");
1781
+ }
1782
+ if (input.tag === "integer") {
1783
+ if (typeof input.text_value !== "string" || !/^[+-]?[0-9]+$/.test(input.text_value))
1784
+ return invalid("invalid_type");
1785
+ return canonicalInteger(BigInt(input.text_value));
1786
+ }
1787
+ if (input.tag === "string_codepoint") {
1788
+ if (typeof input.value !== "string" || !/^[+-]?[0-9a-fA-F]+$/.test(input.value))
1789
+ return invalid("invalid_type");
1790
+ const point = Number.parseInt(input.value, 16);
1791
+ if (point < 0 || point > 0x10ffff || (point >= 0xd800 && point <= 0xdfff))
1792
+ return invalid("invalid_type");
1793
+ const text = JSON.stringify(String.fromCodePoint(point));
1794
+ const decoded = decodeJsonText(text);
1795
+ return decoded.ok ? valid({ text }) : invalid(decoded.code);
1796
+ }
1797
+ if (input.tag === "object" && Array.isArray(input.members)) {
1798
+ const pairs = input.members;
1799
+ if (!pairs.every((pair) => Array.isArray(pair) && pair.length === 2 && typeof pair[0] === "string" &&
1800
+ isRecord(pair[1]) && pair[1].tag === "integer" && isIntegerToken(pair[1].value)))
1801
+ return invalid("invalid_type");
1802
+ const names = pairs.map(([name]) => name);
1803
+ if (new Set(names).size !== names.length)
1804
+ return invalid("duplicate_member");
1805
+ for (const [name, item] of pairs) {
1806
+ const encodedName = decodeJsonText(JSON.stringify(name));
1807
+ if (!encodedName.ok)
1808
+ return invalid(encodedName.code);
1809
+ const encoded = canonicalInteger(item.value);
1810
+ if (encoded.status === "invalid")
1811
+ return encoded;
1812
+ }
1813
+ return valid({ text: canonical(Object.fromEntries(pairs.map(([name, item]) => [name, Number(item.value)]))) });
1814
+ }
1815
+ return invalid("invalid_type");
1816
+ }
1817
+ function executeDigestCase(input) {
1818
+ const domain = input.domain ?? "charter_revision_content";
1819
+ if (typeof domain !== "string" || !Object.hasOwn(SEPARATORS, domain) || domain === "signature_registry")
1820
+ return invalid("invalid_type");
1821
+ if (!Object.hasOwn(input, "bytes_base64url"))
1822
+ return invalid("invalid_type");
1823
+ const bytes = strictBase64url(input.bytes_base64url);
1824
+ if (!bytes.ok)
1825
+ return invalid(bytes.code);
1826
+ if (!Object.hasOwn(input, "tagged"))
1827
+ return valid({ algorithm: "sha-256" });
1828
+ if (typeof input.tagged !== "string")
1829
+ return invalid("invalid_type");
1830
+ const separator = input.tagged.indexOf(":");
1831
+ if (separator < 0)
1832
+ return invalid("digest_encoding_invalid");
1833
+ if (input.tagged.slice(0, separator) !== "sha-256")
1834
+ return invalid("digest_algorithm_unsupported");
1835
+ const declared = strictBase64url(input.tagged.slice(separator + 1));
1836
+ if (!declared.ok || declared.value.length !== 32)
1837
+ return invalid("digest_encoding_invalid");
1838
+ return input.tagged === taggedHash(domain, bytes.value) ? valid({}) : invalid("digest_mismatch");
1839
+ }
1840
+ function executeInputCase(one) {
1841
+ const options = closedCaseOptions(one.input);
1842
+ if (!options.ok)
1843
+ return invalid(options.code);
1844
+ if (Object.hasOwn(one.input, "kind") && Object.hasOwn(one.input, "value") && !caseKindMatches(one.input))
1845
+ return invalid("invalid_type");
1846
+ const artifact = executeArtifactCase(one);
1847
+ if (artifact)
1848
+ return artifact;
1120
1849
  const input = one.input;
1121
1850
  switch (one.surface) {
1122
1851
  case "base64url.decode":
1123
1852
  return project(strictBase64url(input.text), (bytes) => ({ bytes_base64url: bytes.toString("base64url") }));
1124
1853
  case "json.decode": {
1125
- if (!("text" in input) && !("bytes_base64url" in input))
1854
+ if ("text" in input)
1855
+ return project(decodeJsonText(input.text, input.limits), jsonProjection);
1856
+ if (!("bytes_base64url" in input))
1126
1857
  return invalid("invalid_type");
1127
- if (input.limits !== undefined && !validLimits(input.limits))
1128
- return invalid("invalid_limits");
1129
- const bytes = "text" in input ? Buffer.from(input.text) : Buffer.from(input.bytes_base64url, "base64url");
1130
- const decoded = decodeJsonBytes(bytes);
1131
- if (!decoded.ok)
1132
- return invalid(decoded.code);
1133
- return project(jsonWithinLimits(decoded.value, bytes, input.limits), jsonProjection);
1858
+ const bytes = strictBase64url(input.bytes_base64url);
1859
+ if (!bytes.ok)
1860
+ return invalid(bytes.code);
1861
+ return project(decodeJsonBytes(bytes.value, { ...DEFAULT_LIMITS, ...input.limits }), jsonProjection);
1134
1862
  }
1135
1863
  case "canonicalization.encode":
1136
- if (input.tag === "integer") {
1137
- const literal = input.text_value !== undefined ? input.text_value : String(input.value);
1138
- if (/^-?[0-9]+$/.test(literal) && (BigInt(literal) > MAXIMUM_SAFE_INTEGER || BigInt(literal) < -MAXIMUM_SAFE_INTEGER))
1139
- return invalid("integer_magnitude");
1140
- return valid({ text: literal });
1141
- }
1142
- if (input.tag === "object") {
1143
- const names = input.members.map(([key]) => key);
1144
- if (new Set(names).size !== names.length)
1145
- return invalid("duplicate_member");
1146
- return valid({ text: canonical(Object.fromEntries(input.members.map(([key, value]) => [key, value.value]))) });
1147
- }
1148
- if (input.tag === "string_codepoint")
1149
- return invalid("invalid_encoding");
1150
- if (input.kind === "improper_object")
1151
- return invalid("invalid_type");
1152
- return canonical(JSON.parse(input.text)) === input.text ? valid({ text: input.text }) : invalid("non_canonical_bytes");
1864
+ return executeCanonicalCase(input);
1153
1865
  case "digest.hash":
1154
- if (!("bytes_base64url" in input))
1155
- return invalid("invalid_type");
1156
- if (input.tagged !== undefined) {
1157
- if (typeof input.tagged !== "string")
1158
- return invalid("invalid_type");
1159
- const separator = input.tagged.indexOf(":");
1160
- if (separator < 1)
1161
- return invalid("digest_encoding_invalid");
1162
- if (input.tagged.slice(0, separator) !== "sha-256")
1163
- return invalid("digest_algorithm_unsupported");
1164
- if (!/^[A-Za-z0-9_-]{43}$/.test(input.tagged.slice(separator + 1)))
1165
- return invalid("digest_encoding_invalid");
1166
- if (input.tagged !== taggedHash(input.domain || "charter_revision_content", Buffer.from(input.bytes_base64url, "base64url")))
1167
- return invalid("digest_mismatch");
1168
- }
1169
- return valid({ algorithm: "sha-256" });
1866
+ return executeDigestCase(input);
1170
1867
  case "schema.validate": {
1171
1868
  const members = input.members;
1869
+ if (!isRecord(members))
1870
+ return invalid("invalid_type");
1172
1871
  if (Object.keys(members).some((key) => key !== "name"))
1173
1872
  return invalid("unknown_member");
1174
1873
  if (!("name" in members))
@@ -1181,10 +1880,6 @@ function execute(one) {
1181
1880
  return invalid("cardinality_violation");
1182
1881
  return valid({ members });
1183
1882
  }
1184
- 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 }));
1187
- }
1188
1883
  case "descriptor_chain.verify": {
1189
1884
  const chain = descriptorChain(input.compacts);
1190
1885
  return project(chain, (value) => {
@@ -1192,14 +1887,11 @@ function execute(one) {
1192
1887
  });
1193
1888
  }
1194
1889
  case "charter_revision.decode":
1195
- 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
- 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 }));
1202
- }
1890
+ return project(revisionFromText(input.text), (revision) => {
1891
+ const binding = revision.value.abp_bindings[0];
1892
+ return { revision_digest: revision.digest, revision_number: revision.value.revision_number, precedence_declaration: revision.value.precedence_declaration,
1893
+ abp_binding: binding ? { blueprint_id: binding.blueprint_id, release_number: binding.release_number, content_digest: binding.content_digest, deployment_digest: binding.deployment_digest } : null };
1894
+ });
1203
1895
  case "acceptance.equivocation": {
1204
1896
  const chain = descriptorChain(input.descriptor_compacts);
1205
1897
  if (!chain.ok || !Array.isArray(input.signed_revisions) || input.signed_revisions.length !== 2) {
@@ -1219,58 +1911,36 @@ function execute(one) {
1219
1911
  return invalid("acceptance_equivocation_invalid");
1220
1912
  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
1913
  }
1222
- 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 }));
1228
- }
1229
1914
  case "chain.verify": {
1230
- const chain = chainFromInput(input);
1915
+ const chain = chainWithOptions(input, { limits: input.limits });
1231
1916
  return project(chain, (facts) => ({ charter_id: facts.charterId, topology: facts.topology, accepted_revision_digests: facts.acceptedDigests, superseded_revision_digests: facts.supersededDigests }));
1232
1917
  }
1233
1918
  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);
1919
+ const profile = parseProfile(input.profile);
1920
+ if (!profile.ok)
1921
+ return invalid(profile.code);
1922
+ const chain = chainWithOptions(input, { profile: input.profile });
1253
1923
  return project(chain, (facts) => ({ charter_id: facts.charterId, topology: facts.topology }));
1254
1924
  }
1255
1925
  case "governing_revision": {
1256
- const chain = chainFromInput(input);
1257
- if (!chain.ok)
1258
- return invalid("governing_invalid");
1259
- return valid({
1260
- governing_revisions: input.queries.map((query) => {
1261
- const at = parseTimestamp(query.at);
1262
- return at ? governing(chain.value, at) : "none";
1263
- }),
1264
- });
1265
- }
1266
- case "receipt.verify": {
1267
- const chain = chainFromInput(input.chain);
1926
+ const chain = chainWithOptions(input, { limits: input.limits });
1268
1927
  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 }));
1928
+ return invalid(chain.code);
1929
+ if (!Array.isArray(input.queries))
1930
+ return invalid("invalid_type");
1931
+ const revisions = [];
1932
+ for (const query of input.queries) {
1933
+ if (!isRecord(query) || typeof query.at !== "string")
1934
+ return invalid("invalid_type");
1935
+ const at = parseTimestamp(query.at);
1936
+ if (!at)
1937
+ return invalid("timestamp_invalid");
1938
+ revisions.push(governing(chain.value, at));
1939
+ }
1940
+ return valid({ governing_revisions: revisions });
1271
1941
  }
1272
1942
  default:
1273
- throw new Error("unsupported surface");
1943
+ return invalid("invalid_type");
1274
1944
  }
1275
1945
  }
1276
1946
  function corpusDigest(index) {
@@ -1278,6 +1948,24 @@ function corpusDigest(index) {
1278
1948
  delete without.corpus_digest;
1279
1949
  return taggedHash("corpus_index", Buffer.from(canonical(without)));
1280
1950
  }
1951
+ function readCaseJson(text) {
1952
+ return JSON.parse(text, (_key, value, context) => typeof value !== "number" || !context?.source ? value : /[.eE]/.test(context.source) ? new Number(value) :
1953
+ Number.isSafeInteger(value) ? value : BigInt(context.source));
1954
+ }
1955
+ function encodeCaseJson(value) {
1956
+ if (typeof value === "bigint")
1957
+ return value.toString();
1958
+ if (value instanceof Number) {
1959
+ const text = canonical(value);
1960
+ return /^-?[0-9]+$/.test(text) ? `${text}.0` : text;
1961
+ }
1962
+ if (Array.isArray(value))
1963
+ return `[${value.map(encodeCaseJson).join(",")}]`;
1964
+ if (isRecord(value)) {
1965
+ return `{${Object.keys(value).sort().map((key) => `${canonical(key)}:${encodeCaseJson(value[key])}`).join(",")}}`;
1966
+ }
1967
+ return canonical(value);
1968
+ }
1281
1969
  export function loadCorpus(root) {
1282
1970
  const observedEntries = walk(root);
1283
1971
  if (observedEntries.length === 0 || observedEntries.length > MAXIMUM_CORPUS_FILES ||
@@ -1309,8 +1997,8 @@ export function loadCorpus(root) {
1309
1997
  throw new Error("case file changed during read");
1310
1998
  if (rawHash(bytes) !== String(entry.sha256_base64url))
1311
1999
  throw new Error("file hash");
1312
- const file = JSON.parse(bytes.toString("utf8"));
1313
- if (canonical(file) !== bytes.toString("utf8") || file.format !== CASE_FORMAT || file.cases.length !== entry.cases)
2000
+ const file = readCaseJson(bytes.toString("utf8"));
2001
+ if (encodeCaseJson(file) !== bytes.toString("utf8") || file.format !== CASE_FORMAT || file.cases.length !== entry.cases)
1314
2002
  throw new Error("case file");
1315
2003
  cases.push(...file.cases);
1316
2004
  }
@@ -1344,6 +2032,8 @@ export function reportFor(root) {
1344
2032
  const corpus = loadCorpus(root);
1345
2033
  const results = corpus.cases.map((one) => {
1346
2034
  const actual = execute(one);
2035
+ if (actual.status === "invalid" && actual.error_code === "algorithm_unsupported_on_substrate")
2036
+ throw new Error("algorithm_unsupported_on_substrate: corpus verification unavailable");
1347
2037
  return { id: one.id, surface: one.surface, agree: canonical(actual) === canonical(one.expect), expected: one.expect, actual };
1348
2038
  });
1349
2039
  const agreed = results.filter((one) => one.agree).length;
@@ -1461,7 +2151,7 @@ export function selfChecks() {
1461
2151
  if (parseTimestamp("2026-06-30T23:59:60Z") === null || parseTimestamp("2024-03-31T23:59:60Z") !== null) {
1462
2152
  throw new Error("leap-second window drifted");
1463
2153
  }
1464
- if (parseTimestamp("2026-02-30T00:00:00Z") !== null || parseTimestamp("0000-01-01T00:00:00Z") !== null) {
2154
+ if (parseTimestamp("2026-02-30T00:00:00Z") !== null || parseTimestamp("0000-01-01T00:00:00Z") === null || parseTimestamp("0000-02-29T00:00:00Z") === null) {
1465
2155
  throw new Error("calendar validation drifted");
1466
2156
  }
1467
2157
  const halfMs = parseTimestamp("2026-01-01T00:00:00.0005Z");
@@ -1502,83 +2192,358 @@ export function decodeArtifact(compact) {
1502
2192
  if (!decoded.ok)
1503
2193
  return { ok: false, code: decoded.code };
1504
2194
  const { header, payload } = decoded.value;
1505
- return { ok: true, facts: { alg: header.alg, kid: header.kid, typ: header.typ, payload } };
2195
+ return { ok: true, facts: factsRecord({ alg: header.alg, kid: header.kid, typ: header.typ, payload, protocol_revision: payload.protocol_revision }, ["signature"]) };
1506
2196
  }
1507
2197
  // Strict signature verification over exact bytes with a base64url public
1508
2198
  // key under the registry row for `alg` — the wrong-key guard primitive.
1509
- export function verifySignature(message, signature, publicKeyBase64url, alg) {
2199
+ const uint8ArrayTag = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
2200
+ function isUint8Array(value) {
2201
+ return ArrayBuffer.isView(value) && uint8ArrayTag.call(value) === "Uint8Array";
2202
+ }
2203
+ const CHAIN_MEMBERS = ["revisions", "acceptances", "descriptors", "terminations"];
2204
+ const PREDECESSOR_MEMBERS = ["lineage", "descriptor_digest", "digest"];
2205
+ const FRAMING_MEMBERS = ["alg", "protectedSegment", "payloadSegment", "message"];
2206
+ const ARTIFACT_LIST_MEMBERS = new Set([...CHAIN_MEMBERS, "lineage"]);
2207
+ const COPY_LIMIT = Symbol();
2208
+ const COPY_CYCLE = Symbol();
2209
+ const typedArrayByteLength = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "byteLength").get;
2210
+ function boundedMemberNames(value, maximum) {
2211
+ const names = [];
2212
+ for (const name in value) {
2213
+ if (!Object.hasOwn(value, name))
2214
+ continue;
2215
+ if (names.length >= maximum)
2216
+ throw COPY_LIMIT;
2217
+ names.push(name);
2218
+ }
2219
+ return names;
2220
+ }
2221
+ function copyInput(input, limits, mode, members) {
2222
+ const frames = [];
2223
+ const active = new Set();
2224
+ let bytes = 0;
2225
+ const maxBytes = mode === "json" ? limits.max_bytes : limits.max_artifact_set_bytes + limits.max_bytes;
2226
+ let artifactBytes = 0;
2227
+ function count(size) {
2228
+ bytes += size;
2229
+ if (bytes > maxBytes)
2230
+ throw COPY_LIMIT;
2231
+ }
2232
+ function copy(value, depth, artifacts = false, selectedMembers) {
2233
+ if (typeof value === "string") {
2234
+ const size = Buffer.byteLength(value);
2235
+ if (mode === "json" && size > limits.max_string_bytes)
2236
+ throw COPY_LIMIT;
2237
+ count(mode === "json" ? Buffer.byteLength(JSON.stringify(value)) : size);
2238
+ return value;
2239
+ }
2240
+ if (value === null || typeof value !== "object") {
2241
+ if (mode === "json")
2242
+ count(["number", "boolean"].includes(typeof value) || value === null ? JSON.stringify(value).length : 5);
2243
+ return value;
2244
+ }
2245
+ if (ArrayBuffer.isView(value) && !isUint8Array(value))
2246
+ throw new TypeError();
2247
+ if (isUint8Array(value)) {
2248
+ const length = typedArrayByteLength.call(value);
2249
+ if (length > limits.max_bytes)
2250
+ throw COPY_LIMIT;
2251
+ count(length);
2252
+ return Buffer.from(value);
2253
+ }
2254
+ if (value instanceof Number) {
2255
+ const number = Number.prototype.valueOf.call(value);
2256
+ count(JSON.stringify(number).length);
2257
+ return new Number(number);
2258
+ }
2259
+ if (mode === "input" && !Array.isArray(value) && !selectedMembers)
2260
+ throw new TypeError();
2261
+ if (active.has(value))
2262
+ throw COPY_CYCLE;
2263
+ if (depth + 1 > (mode === "json" ? limits.max_depth : LIMIT_MAXIMUMS.max_depth))
2264
+ throw COPY_LIMIT;
2265
+ const array = Array.isArray(value);
2266
+ const length = array ? value.length : 0;
2267
+ if (array && (!Number.isInteger(length) || length < 0 || length > 0xffff_ffff))
2268
+ throw new TypeError();
2269
+ if (array && length > (mode === "json" ? limits.max_array_items : limits.max_artifact_set_items))
2270
+ throw COPY_LIMIT;
2271
+ if (mode === "json")
2272
+ count(2);
2273
+ const keys = array ? null : selectedMembers ? selectedMembers.filter((name) => Object.prototype.propertyIsEnumerable.call(value, name)) : boundedMemberNames(value, limits.max_object_members);
2274
+ const target = array ? [] : Object.create(null);
2275
+ active.add(value);
2276
+ frames.push({ source: value, target, keys, length: array ? length : keys.length, index: 0, depth: depth + 1, artifacts });
2277
+ const order = JSON_MEMBER_ORDER.get(value);
2278
+ if (order)
2279
+ JSON_MEMBER_ORDER.set(target, [...order]);
2280
+ return target;
2281
+ }
2282
+ try {
2283
+ if (mode === "input" && (input === null || typeof input !== "object"))
2284
+ return ok(input);
2285
+ const result = copy(input, 0, mode === "input" && Array.isArray(input), members);
2286
+ while (frames.length) {
2287
+ const frame = frames[frames.length - 1];
2288
+ if (frame.index === frame.length) {
2289
+ active.delete(frame.source);
2290
+ frames.pop();
2291
+ continue;
2292
+ }
2293
+ const index = frame.index++;
2294
+ const key = frame.keys ? frame.keys[index] : String(index);
2295
+ if (mode === "json" && index)
2296
+ count(1);
2297
+ if (mode === "json" && frame.keys) {
2298
+ const size = Buffer.byteLength(key);
2299
+ if (mode === "json" && size > limits.max_string_bytes)
2300
+ throw COPY_LIMIT;
2301
+ count(Buffer.byteLength(JSON.stringify(key)) + 1);
2302
+ }
2303
+ const value = frame.source[key];
2304
+ if (frame.artifacts && typeof value === "string") {
2305
+ artifactBytes += Buffer.byteLength(value);
2306
+ if (artifactBytes > limits.max_artifact_set_bytes)
2307
+ throw COPY_LIMIT;
2308
+ }
2309
+ const nestedMembers = mode === "input" ? key === "limits" ? Object.keys(DEFAULT_LIMITS) :
2310
+ key === "profile" ? ["algorithms", "revisions"] : key === "revisions" && !Array.isArray(value) ? ["min", "max"] : undefined : undefined;
2311
+ frame.target[key] = copy(value, frame.depth, mode === "input" && ARTIFACT_LIST_MEMBERS.has(key), nestedMembers);
2312
+ }
2313
+ return ok(result);
2314
+ }
2315
+ catch (error) {
2316
+ if (error === COPY_LIMIT)
2317
+ return fail(mode === "json" ? "signing_input_invalid" : "limit_exceeded");
2318
+ if (error === COPY_CYCLE && mode === "json")
2319
+ return fail("signing_input_invalid");
2320
+ return fail("invalid_type");
2321
+ }
2322
+ }
2323
+ function plainInputs(...inputs) {
2324
+ const copies = [];
2325
+ for (const input of inputs) {
2326
+ const copied = copyInput(input, DEFAULT_LIMITS, "input");
2327
+ if (!copied.ok)
2328
+ return copied;
2329
+ copies.push(copied.value);
2330
+ }
2331
+ return ok(copies);
2332
+ }
2333
+ function readOptionMembers(value, names, nested = {}) {
2334
+ if (!isRecord(value))
2335
+ return value;
2336
+ const record = Object.create(null);
2337
+ for (const name of boundedMemberNames(value, LIMIT_MAXIMUMS.max_object_members)) {
2338
+ if (!names.includes(name))
2339
+ record[name] = null;
2340
+ }
2341
+ for (const name of names) {
2342
+ const member = value[name];
2343
+ if (member !== undefined || name in value)
2344
+ record[name] = nested[name] ? nested[name](member) : member;
2345
+ }
2346
+ return record;
2347
+ }
2348
+ function predecessorCopyLimits(limits) {
2349
+ return { ...limits, max_artifact_set_items: LIMIT_MAXIMUMS.max_artifact_set_items, max_artifact_set_bytes: LIMIT_MAXIMUMS.max_artifact_set_bytes };
2350
+ }
2351
+ function retainedInput(value, members) {
2352
+ if (!isRecord(value))
2353
+ return ok(value);
2354
+ const retained = Object.create(null);
2355
+ for (const name of members) {
2356
+ if (Object.prototype.propertyIsEnumerable.call(value, name))
2357
+ retained[name] = value[name];
2358
+ }
2359
+ if (members === CHAIN_MEMBERS && !CHAIN_MEMBERS.every((name) => Array.isArray(retained[name])))
2360
+ return fail("invalid_type");
2361
+ return ok(retained);
2362
+ }
2363
+ function plainVerificationInputs(options, inputs, jsonIndex = -1, predecessorIndex = -1, inputMembers = {}) {
2364
+ try {
2365
+ const selected = readOptionMembers(options, ["limits", "profile", "algorithm"], {
2366
+ limits: (value) => readOptionMembers(value, Object.keys(DEFAULT_LIMITS)),
2367
+ profile: (value) => readOptionMembers(value, ["algorithms", "revisions"], {
2368
+ revisions: (range) => readOptionMembers(range, ["min", "max"]),
2369
+ }),
2370
+ });
2371
+ const settings = resolveOptions(selected);
2372
+ if (!settings.ok)
2373
+ return settings;
2374
+ const copiedOptions = copyInput(selected, { ...MAXIMUM_LIMITS, max_artifact_set_bytes: MAXIMUM_LIMITS.max_bytes }, "input", ["limits", "profile", "algorithm"]);
2375
+ if (!copiedOptions.ok)
2376
+ return copiedOptions;
2377
+ for (const [index, members] of Object.entries(inputMembers)) {
2378
+ const retained = retainedInput(inputs[Number(index)], members);
2379
+ if (!retained.ok)
2380
+ return retained;
2381
+ inputs[Number(index)] = retained.value;
2382
+ }
2383
+ const copies = [];
2384
+ for (let i = 0; i < inputs.length; i++) {
2385
+ const copied = copyInput(inputs[i], i === predecessorIndex ? predecessorCopyLimits(settings.value.limits) : settings.value.limits, i === jsonIndex ? "json" : "input", i === predecessorIndex ? PREDECESSOR_MEMBERS : inputMembers[i]);
2386
+ if (!copied.ok)
2387
+ return copied;
2388
+ copies.push(copied.value);
2389
+ }
2390
+ return ok([...copies, copiedOptions.value]);
2391
+ }
2392
+ catch (_error) {
2393
+ return fail("invalid_type");
2394
+ }
2395
+ }
2396
+ export function verifySignature(message, signature, publicKeyBase64url, alg, options = {}) {
2397
+ const plain = plainVerificationInputs(options, [message, signature, publicKeyBase64url, alg]);
2398
+ if (!plain.ok)
2399
+ return false;
2400
+ [message, signature, publicKeyBase64url, alg, options] = plain.value;
2401
+ if (!isUint8Array(message) || !isUint8Array(signature) || typeof publicKeyBase64url !== "string" || typeof alg !== "string")
2402
+ return false;
2403
+ const settings = resolveOptions(options);
2404
+ if (!settings.ok || !settings.value.profile.algorithms.includes(alg) || message.length > settings.value.limits.max_bytes)
2405
+ return false;
1510
2406
  const row = ALG_ROWS.find((one) => one.name === alg);
1511
2407
  if (!row)
1512
2408
  return false;
1513
- const key = Buffer.from(publicKeyBase64url, "base64url");
1514
- if (key.length !== row.publicKeyBytes)
2409
+ if (!validPublicKey(publicKeyBase64url, row) || !runtimeSupportsAlgorithm(row.keyAlgorithm))
1515
2410
  return false;
1516
2411
  if (row.keyAlgorithm === "Ed25519")
1517
- return ed25519(publicKeyBase64url, message, signature);
1518
- return mldsa(row.keyAlgorithm, publicKeyBase64url, message, signature);
1519
- }
1520
- export function verifyDescriptor(compact, predecessor = null) {
1521
- const verified = descriptorFromCompact(compact, predecessor ? { digest: predecessor.digest, payload: predecessor.claims } : null);
2412
+ return ed25519(publicKeyBase64url, Buffer.from(message), Buffer.from(signature));
2413
+ return mldsa(row.keyAlgorithm, publicKeyBase64url, Buffer.from(message), Buffer.from(signature));
2414
+ }
2415
+ const PREDECESSOR_PASS_THROUGH = new Set(["algorithm_outside_profile", "revision_outside_profile", "algorithm_unsupported_on_substrate"]);
2416
+ function reverifyPredecessor(supplied, settings) {
2417
+ if (supplied === null)
2418
+ return ok(null);
2419
+ if (!isRecord(supplied) || !Array.isArray(supplied.lineage) || supplied.lineage.length === 0)
2420
+ return fail("invalid_type");
2421
+ let previous = null;
2422
+ for (const compact of [...supplied.lineage].reverse()) {
2423
+ if (typeof compact !== "string")
2424
+ return fail("invalid_type");
2425
+ const verified = descriptorFromCompact(compact, previous, settings);
2426
+ // A profile rejection, or a runtime that cannot check the signature, is
2427
+ // reported as itself, as a chain view reports it; any other failure is a
2428
+ // broken chain.
2429
+ if (!verified.ok)
2430
+ return PREDECESSOR_PASS_THROUGH.has(verified.code) ? verified : fail("descriptor_chain_invalid");
2431
+ previous = verified.value;
2432
+ }
2433
+ if (!previous || (supplied.descriptor_digest ?? supplied.digest) !== previous.digest ||
2434
+ (supplied.digest !== undefined && supplied.digest !== previous.digest))
2435
+ return fail("descriptor_chain_invalid");
2436
+ return ok(previous);
2437
+ }
2438
+ export function verifyDescriptor(compact, predecessor = null, options = {}) {
2439
+ const plain = plainVerificationInputs(options, [compact, predecessor], -1, 1);
2440
+ if (!plain.ok)
2441
+ return plain;
2442
+ [compact, predecessor, options] = plain.value;
2443
+ const settings = resolveOptions(options);
2444
+ if (!settings.ok)
2445
+ return settings;
2446
+ const previous = reverifyPredecessor(predecessor, settings.value);
2447
+ if (!previous.ok)
2448
+ return previous;
2449
+ const verified = descriptorFromCompact(compact, previous.value, settings.value);
1522
2450
  if (!verified.ok)
1523
2451
  return { ok: false, code: verified.code };
1524
2452
  const one = verified.value;
1525
2453
  return {
1526
2454
  ok: true,
1527
- facts: {
2455
+ facts: factsRecord({
1528
2456
  descriptor_digest: one.digest,
1529
- party_id: one.digest,
2457
+ party_id: one.payload.party_id ?? one.digest,
1530
2458
  descriptor_number: one.payload.descriptor_number,
2459
+ lineage: [...one.lineage],
1531
2460
  protocol_revision: one.payload.protocol_revision,
1532
- },
2461
+ alg: one.header.alg,
2462
+ }),
1533
2463
  };
1534
2464
  }
1535
- export function verifyDescriptorChain(compacts) {
1536
- const verified = descriptorChain(compacts);
2465
+ export function verifyDescriptorChain(compacts, options = {}) {
2466
+ const plain = plainVerificationInputs(options, [compacts]);
2467
+ if (!plain.ok)
2468
+ return plain;
2469
+ [compacts, options] = plain.value;
2470
+ const settings = resolveOptions(options);
2471
+ if (!settings.ok)
2472
+ return settings;
2473
+ const verified = descriptorChain(compacts, settings.value);
1537
2474
  if (!verified.ok)
1538
2475
  return { ok: false, code: verified.code };
1539
2476
  return { ok: true, facts: verified.value };
1540
2477
  }
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);
2478
+ export function verifyAcceptance(compact, revisionText, descriptorCompacts, options = {}) {
2479
+ const plain = plainVerificationInputs(options, [compact, revisionText, descriptorCompacts]);
2480
+ if (!plain.ok)
2481
+ return plain;
2482
+ [compact, revisionText, descriptorCompacts, options] = plain.value;
2483
+ const settings = resolveOptions(options);
2484
+ if (!settings.ok)
2485
+ return settings;
2486
+ const revision = revisionWithProfile(revisionText, settings.value);
2487
+ if (!revision.ok)
2488
+ return revision;
2489
+ const chain = descriptorChain(descriptorCompacts, settings.value);
2490
+ if (!chain.ok)
2491
+ return chain;
2492
+ const verified = acceptanceFromCompact(compact, revision.value, chain.value, settings.value);
1547
2493
  if (!verified.ok)
1548
2494
  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);
2495
+ 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 }) };
2496
+ }
2497
+ export function verifyTermination(compact, revisionText, descriptorCompacts, options = {}) {
2498
+ const plain = plainVerificationInputs(options, [compact, revisionText, descriptorCompacts]);
2499
+ if (!plain.ok)
2500
+ return plain;
2501
+ [compact, revisionText, descriptorCompacts, options] = plain.value;
2502
+ const settings = resolveOptions(options);
2503
+ if (!settings.ok)
2504
+ return settings;
2505
+ const revision = revisionWithProfile(revisionText, settings.value);
2506
+ if (!revision.ok)
2507
+ return revision;
2508
+ const chain = descriptorChain(descriptorCompacts, settings.value);
2509
+ if (!chain.ok)
2510
+ return chain;
2511
+ const verified = terminationFromCompact(compact, revision.value, chain.value, settings.value);
1557
2512
  if (!verified.ok)
1558
2513
  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 } };
1560
- }
1561
- export function verifyChain(chainInput) {
1562
- const verified = chainFromInput(chainInput);
2514
+ 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 }) };
2515
+ }
2516
+ export function verifyChain(chainInput, options = {}) {
2517
+ const plain = plainVerificationInputs(options, [chainInput], -1, -1, { 0: CHAIN_MEMBERS });
2518
+ if (!plain.ok)
2519
+ return plain;
2520
+ [chainInput, options] = plain.value;
2521
+ const verified = chainWithOptions(chainInput, options);
1563
2522
  if (!verified.ok)
1564
2523
  return { ok: false, code: verified.code };
1565
2524
  return { ok: true, facts: verified.value };
1566
2525
  }
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);
2526
+ export function verifyReceipt(compact, context, options = {}) {
2527
+ const plain = plainVerificationInputs(options, [compact, context], -1, -1, { 1: CHAIN_MEMBERS });
2528
+ if (!plain.ok)
2529
+ return plain;
2530
+ [compact, context, options] = plain.value;
2531
+ const settings = resolveOptions(options);
2532
+ if (!settings.ok)
2533
+ return settings;
2534
+ const verified = receiptWithContext(compact, context, settings.value);
1572
2535
  if (!verified.ok)
1573
2536
  return { ok: false, code: verified.code };
1574
2537
  return {
1575
2538
  ok: true,
1576
- facts: {
2539
+ facts: factsRecord({
2540
+ protocol_revision: verified.value.protocol_revision,
2541
+ alg: verified.value.alg,
1577
2542
  receipt_digest: verified.value.digest,
1578
2543
  claims: verified.value.claims,
1579
2544
  governing_match: verified.value.governingMatch,
1580
2545
  chain_conflict: verified.value.chainConflict,
1581
- },
2546
+ }, typeof context === "string" ? ["signature"] : []),
1582
2547
  };
1583
2548
  }
1584
2549
  // ---------------------------------------------------------------------------
@@ -1590,49 +2555,75 @@ export function verifyReceipt(compact, chainInput) {
1590
2555
  // key operation.
1591
2556
  // ---------------------------------------------------------------------------
1592
2557
  export function checkSigningClaims(kind, claims) {
2558
+ const plain = copyInput(claims, MAXIMUM_LIMITS, "json");
2559
+ return plain.ok ? signingClaims(kind, plain.value) : plain;
2560
+ }
2561
+ function signingClaims(kind, claims) {
1593
2562
  if (!claims || typeof claims !== "object" || Array.isArray(claims))
1594
2563
  return { ok: false, code: "invalid_type" };
1595
- const error = kind === "descriptor" ? descriptorClaimsError(claims) :
2564
+ const error = kind === "descriptor" ? signingDescriptorError(claims) :
1596
2565
  kind === "acceptance" ? acceptanceClaimsError(claims) :
1597
2566
  kind === "termination" ? terminationClaimsError(claims) :
1598
2567
  kind === "receipt" ? (receiptGrantError(claims) ?? receiptTimingError(claims)) :
1599
2568
  "invalid_type";
1600
2569
  return error ? { ok: false, code: error } : { ok: true };
1601
2570
  }
2571
+ // Preserve the preflight helper's existing local-code precedence.
2572
+ function signingDescriptorError(claims) {
2573
+ if (claims.descriptor_number === 1 && claims.prev_descriptor_digest !== undefined)
2574
+ return "descriptor_invalid";
2575
+ const grammar = keyGrammarError(claims);
2576
+ return grammar ?? descriptorClaimsError(claims);
2577
+ }
1602
2578
  function acceptanceClaimsError(claims) {
1603
- if ((claims.revision_number === 1) !== (claims.prev_revision_digest === undefined))
2579
+ const shape = schemaError(claims, ACCEPTANCE_SCHEMA);
2580
+ if (shape)
2581
+ return shape;
2582
+ if ([claims.charter_id, claims.revision_digest, claims.prev_revision_digest, claims.party_descriptor_digest].filter((value) => value !== undefined).some((value) => !validTaggedDigest(value)))
1604
2583
  return "acceptance_invalid";
1605
2584
  if (!parseTimestamp(claims.accepted_at))
1606
2585
  return "timestamp_invalid";
2586
+ if ((claims.revision_number === 1) !== (claims.prev_revision_digest === undefined))
2587
+ return "acceptance_invalid";
1607
2588
  return null;
1608
2589
  }
1609
2590
  function terminationClaimsError(claims) {
2591
+ const shape = schemaError(claims, TERMINATION_SCHEMA);
2592
+ if (shape)
2593
+ return shape;
2594
+ if ([claims.charter_id, claims.governing_revision_digest, claims.party_descriptor_digest, claims.detail_digest].filter((value) => value !== undefined).some((value) => !validTaggedDigest(value)))
2595
+ return "termination_invalid";
1610
2596
  const issuedAt = parseTimestamp(claims.issued_at);
1611
2597
  const effectiveAt = parseTimestamp(claims.effective_at);
1612
- if (!issuedAt || !effectiveAt || compareTimestamps(issuedAt, effectiveAt) > 0)
2598
+ if (!issuedAt || !effectiveAt)
2599
+ return "timestamp_invalid";
2600
+ if (compareTimestamps(issuedAt, effectiveAt) > 0)
1613
2601
  return "termination_invalid";
1614
2602
  return null;
1615
2603
  }
1616
2604
  function receiptGrantError(claims) {
1617
- if (claims.grant?.scheme === "bap" && claims.grant?.grant_digest === undefined)
2605
+ const shape = schemaError(claims, RECEIPT_SCHEMA);
2606
+ if (shape)
2607
+ return shape;
2608
+ if ([claims.charter_id, claims.revision_digest, claims.deployment_digest, claims.grant.grant_digest].filter((value) => value !== undefined).some((value) => !validTaggedDigest(value)))
1618
2609
  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;
2610
+ const allowed = receiptTimingMatrixError(claims);
2611
+ if (allowed)
2612
+ return allowed;
2613
+ if (claims.grant.scheme === "bap" && claims.grant.grant_digest === undefined)
2614
+ return "receipt_invalid";
2615
+ return extensionError(claims.extensions, "receipt");
1630
2616
  }
1631
2617
  function receiptTimingError(claims) {
1632
2618
  const occurredAt = parseTimestamp(claims.occurred_at);
1633
2619
  const recordedAt = parseTimestamp(claims.recorded_at);
1634
- if (!occurredAt || !recordedAt || compareTimestamps(recordedAt, occurredAt) < 0)
2620
+ if (!occurredAt || !recordedAt)
2621
+ return "timestamp_invalid";
2622
+ if (compareTimestamps(recordedAt, occurredAt) < 0)
1635
2623
  return "receipt_invalid";
2624
+ return receiptTimingMatrixError(claims);
2625
+ }
2626
+ function receiptTimingMatrixError(claims) {
1636
2627
  // The closed matrix mirrors the reference decoder: rejected requires
1637
2628
  // no_effect; accepted admits effect_committed, no_effect, or indeterminate.
1638
2629
  const outcomeAllowed = claims.decision === "rejected" ? claims.outcome === "no_effect" :
@@ -1642,12 +2633,22 @@ function receiptTimingError(claims) {
1642
2633
  return null;
1643
2634
  }
1644
2635
  function descriptorClaimsError(payload) {
2636
+ const shape = schemaError(payload, DESCRIPTOR_SCHEMA);
2637
+ if (shape)
2638
+ return shape;
2639
+ if ([payload.party_id, payload.prev_descriptor_digest].filter((value) => value !== undefined).some((value) => !validTaggedDigest(value)))
2640
+ return "descriptor_invalid";
1645
2641
  const grammar = keyGrammarError(payload);
1646
2642
  if (grammar)
1647
2643
  return grammar;
2644
+ if (new Set(payload.verification_keys.map((key) => key.key_id)).size !== payload.verification_keys.length || !payload.verification_keys.some((key) => key.status === "active"))
2645
+ return "descriptor_invalid";
2646
+ const extensions = extensionError(payload.extensions, "party_descriptor");
2647
+ if (extensions)
2648
+ return extensions;
1648
2649
  if (!parseTimestamp(payload.effective_from))
1649
2650
  return "timestamp_invalid";
1650
- if (payload.descriptor_number === 1 && payload.prev_descriptor_digest !== undefined)
2651
+ if (payload.descriptor_number === 1 ? (payload.prev_descriptor_digest !== undefined || payload.party_id !== undefined) : (payload.prev_descriptor_digest === undefined || payload.party_id === undefined))
1651
2652
  return "descriptor_invalid";
1652
2653
  return null;
1653
2654
  }
@@ -1659,28 +2660,39 @@ function descriptorClaimsError(payload) {
1659
2660
  // ---------------------------------------------------------------------------
1660
2661
  // The unique governing revision in a verified view at one UTC instant -
1661
2662
  // a digest, or "contested"/"none" (never silently resolved).
1662
- export function governingRevision(chainInput, at) {
2663
+ export function governingRevision(chainInput, at, options = {}) {
2664
+ const plain = plainVerificationInputs(options, [chainInput, at], -1, -1, { 0: CHAIN_MEMBERS });
2665
+ if (!plain.ok)
2666
+ return plain;
2667
+ [chainInput, at, options] = plain.value;
1663
2668
  const instant = typeof at === "string" ? parseTimestamp(at) : null;
1664
2669
  if (!instant)
1665
2670
  return { ok: false, code: "invalid_type" };
1666
2671
  if (!chainInput || typeof chainInput !== "object" || Array.isArray(chainInput)) {
1667
2672
  return { ok: false, code: "signing_input_invalid" };
1668
2673
  }
1669
- const chain = chainFromInput(chainInput);
2674
+ const chain = chainWithOptions(chainInput, options);
1670
2675
  if (!chain.ok)
1671
- return { ok: false, code: "chain_invalid" };
2676
+ return chain;
1672
2677
  return { ok: true, governing: governing(chain.value, instant) };
1673
2678
  }
1674
2679
  // Decode one canonical unsigned Charter Revision: the parsed claims plus
1675
2680
  // its content digest, computed over the exact text bytes.
1676
- export function decodeCharterRevision(text) {
1677
- const revision = revisionFromText(text);
2681
+ export function decodeCharterRevision(text, options = {}) {
2682
+ const plain = plainVerificationInputs(options, [text]);
2683
+ if (!plain.ok)
2684
+ return plain;
2685
+ [text, options] = plain.value;
2686
+ const settings = resolveOptions(options);
2687
+ if (!settings.ok)
2688
+ return settings;
2689
+ const revision = revisionFromText(text, settings.value.limits);
1678
2690
  if (!revision.ok)
1679
2691
  return { ok: false, code: revision.code };
1680
2692
  return { ok: true, revision: revision.value.value, digest: revision.value.digest };
1681
2693
  }
1682
- export function revisionDigest(text) {
1683
- const revision = decodeCharterRevision(text);
2694
+ export function revisionDigest(text, options = {}) {
2695
+ const revision = decodeCharterRevision(text, options);
1684
2696
  if (!revision.ok)
1685
2697
  return revision;
1686
2698
  return { ok: true, digest: revision.digest };
@@ -1704,6 +2716,163 @@ export function descriptorDigest(compact) {
1704
2716
  return decoded;
1705
2717
  return { ok: true, digest: decoded.digest };
1706
2718
  }
2719
+ let createSigningPlan;
2720
+ let finishSigningPlan;
2721
+ const SIGNING_PLAN_TOKEN = Symbol();
2722
+ /** A prepared input with retained verification context and settings. */
2723
+ export class SigningPlan {
2724
+ kind;
2725
+ key;
2726
+ #input;
2727
+ #publicKey;
2728
+ #context;
2729
+ #limits;
2730
+ #profile;
2731
+ constructor(token, kind, input, key, publicKey, context, settings) {
2732
+ if (token !== SIGNING_PLAN_TOKEN)
2733
+ throw new TypeError("SigningPlan requires prepareSigning");
2734
+ this.kind = kind;
2735
+ this.key = key;
2736
+ this.#input = { ...input, message: Buffer.from(input.message) };
2737
+ this.#publicKey = publicKey;
2738
+ this.#context = context;
2739
+ this.#limits = { ...settings.limits };
2740
+ this.#profile = { ...settings.profile, algorithms: [...settings.profile.algorithms] };
2741
+ Object.freeze(this);
2742
+ }
2743
+ get input() {
2744
+ return { ...this.#input, message: Buffer.from(this.#input.message) };
2745
+ }
2746
+ static {
2747
+ createSigningPlan = (kind, input, key, publicKey, context, settings) => new SigningPlan(SIGNING_PLAN_TOKEN, kind, input, key, publicKey, context, settings);
2748
+ finishSigningPlan = (plan, signature) => {
2749
+ if (!(#input in plan) || !isUint8Array(signature))
2750
+ return fail("invalid_type");
2751
+ const assembled = assembleUnderLimits(plan.#input, Buffer.from(signature), plan.#limits);
2752
+ if (!assembled.ok)
2753
+ return assembled;
2754
+ const options = { limits: plan.#limits, profile: { algorithms: plan.#profile.algorithms, revisions: { min: plan.#profile.minRevision, max: plan.#profile.maxRevision } } };
2755
+ const context = plan.#context;
2756
+ const verified = context.kind === "descriptor" ? verifyDescriptor(assembled.compact, context.predecessor, options) :
2757
+ context.kind === "acceptance" ? verifyAcceptance(assembled.compact, context.revisionText, context.descriptorCompacts, options) :
2758
+ context.kind === "termination" ? verifyTermination(assembled.compact, context.revisionText, context.descriptorCompacts, options) :
2759
+ verifyReceipt(assembled.compact, context.context, options);
2760
+ return verified.ok ? assembled : fail(verified.code);
2761
+ };
2762
+ }
2763
+ }
2764
+ /** Check everything that can be checked before producing a signature. */
2765
+ export function prepareSigning(kind, kid, claims, publicKey, context, options = {}) {
2766
+ const optionInputs = plainVerificationInputs(options, []);
2767
+ if (!optionInputs.ok)
2768
+ return optionInputs;
2769
+ options = optionInputs.value[0];
2770
+ try {
2771
+ const member = (name) => Object.prototype.propertyIsEnumerable.call(context, name);
2772
+ const descriptorContext = context === null || (isRecord(context) && member("lineage") &&
2773
+ (member("descriptor_digest") || member("digest")));
2774
+ const setContext = isRecord(context) && ["revisions", "acceptances", "descriptors", "terminations"].every(member);
2775
+ const validContext = kind === "descriptor" ? descriptorContext :
2776
+ kind === "acceptance" || kind === "termination" ? setContext :
2777
+ kind === "receipt" ? typeof context === "string" || setContext : false;
2778
+ if (!validContext)
2779
+ return fail("invalid_type");
2780
+ }
2781
+ catch (_error) {
2782
+ return fail("invalid_type");
2783
+ }
2784
+ const plain = plainVerificationInputs(options, [kind, kid, claims, publicKey], 2);
2785
+ if (!plain.ok)
2786
+ return plain;
2787
+ [kind, kid, claims, publicKey, options] = plain.value;
2788
+ const settings = resolveOptions(options);
2789
+ if (!settings.ok)
2790
+ return settings;
2791
+ const built = buildSigningInput(kind, kid, claims, options.algorithm, settings.value.limits);
2792
+ if (!built.ok)
2793
+ return built;
2794
+ const row = ALG_ROWS.find((one) => one.name === built.input.alg);
2795
+ if (!validPublicKey(publicKey, row))
2796
+ return fail("signing_key_invalid");
2797
+ try {
2798
+ const retained = retainedInput(context, kind === "descriptor" ? PREDECESSOR_MEMBERS : CHAIN_MEMBERS);
2799
+ if (!retained.ok)
2800
+ return retained;
2801
+ context = retained.value;
2802
+ }
2803
+ catch (_error) {
2804
+ return fail("invalid_type");
2805
+ }
2806
+ const copiedContext = copyInput(context, kind === "descriptor" ? predecessorCopyLimits(settings.value.limits) : settings.value.limits, "input", kind === "descriptor" ? PREDECESSOR_MEMBERS : CHAIN_MEMBERS);
2807
+ if (!copiedContext.ok)
2808
+ return copiedContext;
2809
+ context = copiedContext.value;
2810
+ const provisional = `${built.input.message.toString("utf8")}.${encodeBase64url(Buffer.alloc(row.signatureBytes))}`;
2811
+ let prepared;
2812
+ let verifyWith;
2813
+ if (kind === "descriptor") {
2814
+ const previous = reverifyPredecessor(context, settings.value);
2815
+ if (!previous.ok)
2816
+ return previous;
2817
+ prepared = prepareDescriptor(provisional, previous.value, settings.value);
2818
+ verifyWith = { kind, predecessor: previous.value ? { descriptor_digest: previous.value.digest, lineage: [...previous.value.lineage] } : null };
2819
+ }
2820
+ else if (kind === "acceptance" || kind === "termination") {
2821
+ // Limits cover the whole set; the caller's profile covers the routed view.
2822
+ const chain = chainFromInput(context, { ...settings.value, profile: DEFAULT_SETTINGS.profile });
2823
+ if (!chain.ok)
2824
+ return chain;
2825
+ const refusal = kind === "acceptance" ? acceptanceRefusalInChain(claims, chain.value) : terminationRefusalInChain(claims, chain.value);
2826
+ if (!refusal.ok)
2827
+ return refusal;
2828
+ const routed = signingContextFromSet(new Map(chain.value.revisions.map((one) => [one.digest, one])), chain.value.descriptors, kind === "acceptance" ? claims.revision_digest : claims.governing_revision_digest, claims.party_descriptor_digest, `${kind}_claims_mismatch`);
2829
+ if (!routed.ok)
2830
+ return routed;
2831
+ const revisionText = routed.value.revision.bytes.toString("utf8");
2832
+ const descriptorCompacts = routed.value.chain.descriptors.map((one) => one.compact);
2833
+ const revision = revisionWithProfile(revisionText, settings.value);
2834
+ if (!revision.ok)
2835
+ return revision;
2836
+ const partyChain = descriptorChain(descriptorCompacts, settings.value);
2837
+ if (!partyChain.ok)
2838
+ return partyChain;
2839
+ prepared = kind === "acceptance" ? prepareAcceptance(provisional, revision.value, partyChain.value, settings.value) : prepareTermination(provisional, revision.value, partyChain.value, settings.value);
2840
+ verifyWith = { kind, revisionText, descriptorCompacts: [...descriptorCompacts] };
2841
+ }
2842
+ else if (typeof context === "string") {
2843
+ const revision = revisionWithProfile(context, settings.value);
2844
+ if (!revision.ok)
2845
+ return revision;
2846
+ prepared = prepareReceipt(provisional, { kind: "revision", revision: revision.value }, settings.value);
2847
+ verifyWith = { kind, context };
2848
+ }
2849
+ else {
2850
+ const chain = chainFromInput(context, settings.value);
2851
+ if (!chain.ok)
2852
+ return chain;
2853
+ prepared = prepareReceipt(provisional, { kind: "chain", chain: chain.value }, settings.value);
2854
+ verifyWith = { kind, context: context };
2855
+ }
2856
+ if (!prepared.ok)
2857
+ return prepared;
2858
+ if (!prepared.value.unnamed && !prepared.value.keys.some((key) => keyMatchesRow(key, row) && key.public_key === publicKey))
2859
+ return fail("signing_key_mismatch");
2860
+ if (!runtimeSupportsAlgorithm(row.keyAlgorithm))
2861
+ return fail("algorithm_unsupported_on_substrate");
2862
+ return { ok: true, plan: createSigningPlan(kind, built.input, prepared.value.unnamed ? "unnamed" : "matched", publicKey, verifyWith, settings.value) };
2863
+ }
2864
+ /** Assemble under the retained limits and run public verification. */
2865
+ export function finishSigning(plan, signature) {
2866
+ try {
2867
+ if (!(plan instanceof SigningPlan))
2868
+ return fail("invalid_type");
2869
+ const plain = plainInputs(signature);
2870
+ return plain.ok ? finishSigningPlan(plan, plain.value[0]) : plain;
2871
+ }
2872
+ catch (_error) {
2873
+ return fail("invalid_type");
2874
+ }
2875
+ }
1707
2876
  const PRODUCER_TYPES = {
1708
2877
  descriptor: "cap+party",
1709
2878
  acceptance: "cap+acceptance",
@@ -1733,18 +2902,25 @@ function jsonValueError(value) {
1733
2902
  // binding -> kid -> framing -> size gate -> claims schema -> provisional
1734
2903
  // decode (the reference producer's exact ordering, so error precedence
1735
2904
  // matches too).
1736
- function buildSigningInput(kind, kid, claims, algorithm) {
1737
- if (typeof algorithm === "undefined" || algorithm === null)
2905
+ function buildSigningInput(kind, kid, claims, algorithm, limits = DEFAULT_LIMITS) {
2906
+ if (typeof algorithm === "undefined")
1738
2907
  algorithm = defaultEmissionName();
1739
2908
  if (typeof algorithm !== "string" || !(algorithm in emissions())) {
1740
- return { ok: false, code: "algorithm_unsupported" };
2909
+ return { ok: false, code: "signing_input_invalid" };
1741
2910
  }
1742
2911
  if (!claims || typeof claims !== "object" || Array.isArray(claims)) {
1743
- return { ok: false, code: "invalid_type" };
2912
+ return { ok: false, code: "signing_input_invalid" };
1744
2913
  }
1745
2914
  const record = claims;
1746
- if (jsonValueError(record))
2915
+ try {
2916
+ if (jsonValueError(record))
2917
+ return { ok: false, code: "signing_input_invalid" };
2918
+ }
2919
+ catch (_error) {
1747
2920
  return { ok: false, code: "signing_input_invalid" };
2921
+ }
2922
+ if (integerTokenError(record, schemaForType(PRODUCER_TYPES[kind])))
2923
+ return fail("signing_input_invalid");
1748
2924
  const revision = record.protocol_revision;
1749
2925
  if (typeof revision !== "number" || !Number.isInteger(revision) || revision !== emissions()[algorithm]) {
1750
2926
  return { ok: false, code: "signing_input_invalid" };
@@ -1754,39 +2930,57 @@ function buildSigningInput(kind, kid, claims, algorithm) {
1754
2930
  }
1755
2931
  const row = ALG_ROWS.find((one) => one.name === algorithm);
1756
2932
  if (!row)
1757
- return { ok: false, code: "algorithm_unsupported" };
1758
- const payloadSegment = encodeBase64url(Buffer.from(canonical(record), "utf8"));
2933
+ return { ok: false, code: "signing_input_invalid" };
2934
+ let payloadSegment;
2935
+ try {
2936
+ payloadSegment = encodeBase64url(Buffer.from(canonical(record), "utf8"));
2937
+ }
2938
+ catch (_error) {
2939
+ return { ok: false, code: "signing_input_invalid" };
2940
+ }
1759
2941
  const protectedSegment = encodeBase64url(Buffer.from(canonical({ alg: algorithm, kid, typ: PRODUCER_TYPES[kind] }), "utf8"));
1760
2942
  const message = Buffer.from(`${protectedSegment}.${payloadSegment}`, "utf8");
1761
2943
  const signatureSegmentLength = Math.ceil((row.signatureBytes * 4) / 3);
1762
- if (message.length + 1 + signatureSegmentLength > JSON_DEFAULT_LIMITS.max_bytes) {
2944
+ if (message.length + 1 + signatureSegmentLength > limits.max_bytes) {
1763
2945
  return { ok: false, code: "signing_input_invalid" };
1764
2946
  }
1765
2947
  // The reference build's decode step: the claims schema gate runs inside
1766
2948
  // the producer, after framing and size - the same precedence as
1767
2949
  // decode_for_signing inside the Elixir build pipeline.
1768
- const claimsGate = checkSigningClaims(kind, record);
2950
+ const claimsGate = signingClaims(kind, record);
1769
2951
  if (!claimsGate.ok)
1770
- return { ok: false, code: claimsGate.code };
2952
+ return { ok: false, code: "signing_input_invalid" };
1771
2953
  // The provisional check: a zero signature at the row's exact length must
1772
2954
  // frame and bind.
1773
2955
  const zeroSignature = Buffer.alloc(row.signatureBytes);
1774
2956
  const provisional = `${protectedSegment}.${payloadSegment}.${encodeBase64url(zeroSignature)}`;
1775
- const decoded = decodeArtifact(provisional);
2957
+ const decoded = decodeSigningArtifact(provisional, limits);
1776
2958
  if (!decoded.ok)
1777
2959
  return { ok: false, code: "signing_input_invalid" };
1778
2960
  return { ok: true, input: { alg: algorithm, protectedSegment, payloadSegment, message } };
1779
2961
  }
1780
2962
  export function descriptorSigningInput(kid, claims, algorithm) {
2963
+ const plain = plainVerificationInputs({}, [kid, claims, algorithm], 1);
2964
+ if (!plain.ok)
2965
+ return plain;
2966
+ [kid, claims, algorithm] = plain.value;
1781
2967
  return buildSigningInput("descriptor", kid, claims, algorithm);
1782
2968
  }
1783
2969
  export function receiptSigningInput(kid, claims, algorithm) {
2970
+ const plain = plainVerificationInputs({}, [kid, claims, algorithm], 1);
2971
+ if (!plain.ok)
2972
+ return plain;
2973
+ [kid, claims, algorithm] = plain.value;
1784
2974
  return buildSigningInput("receipt", kid, claims, algorithm);
1785
2975
  }
1786
2976
  // The reference producer ordering: build (shape, emission binding, framing,
1787
2977
  // claims schema) FIRST, then the set-aware R1-R3 refusal checks - so a
1788
2978
  // claims defect reports the producer code even when the view is also bad.
1789
2979
  export function acceptanceSigningInput(kid, claims, chainInput, algorithm) {
2980
+ const plain = plainVerificationInputs({}, [kid, claims, chainInput, algorithm], 1, -1, { 2: CHAIN_MEMBERS });
2981
+ if (!plain.ok)
2982
+ return plain;
2983
+ [kid, claims, chainInput, algorithm] = plain.value;
1790
2984
  const built = buildSigningInput("acceptance", kid, claims, algorithm);
1791
2985
  if (!built.ok)
1792
2986
  return built;
@@ -1796,6 +2990,10 @@ export function acceptanceSigningInput(kid, claims, chainInput, algorithm) {
1796
2990
  return built;
1797
2991
  }
1798
2992
  export function terminationSigningInput(kid, claims, chainInput, algorithm) {
2993
+ const plain = plainVerificationInputs({}, [kid, claims, chainInput, algorithm], 1, -1, { 2: CHAIN_MEMBERS });
2994
+ if (!plain.ok)
2995
+ return plain;
2996
+ [kid, claims, chainInput, algorithm] = plain.value;
1799
2997
  const built = buildSigningInput("termination", kid, claims, algorithm);
1800
2998
  if (!built.ok)
1801
2999
  return built;
@@ -1804,9 +3002,26 @@ export function terminationSigningInput(kid, claims, chainInput, algorithm) {
1804
3002
  return { ok: false, code: refusal.code };
1805
3003
  return built;
1806
3004
  }
3005
+ function decodeSigningArtifact(compact, limits = DEFAULT_LIMITS) {
3006
+ const decoded = decodeJws(compact, limits);
3007
+ if (!decoded.ok)
3008
+ return decoded;
3009
+ const kind = Object.keys(PRODUCER_TYPES).find((one) => PRODUCER_TYPES[one] === decoded.value.header.typ);
3010
+ if (!kind)
3011
+ return fail("signing_input_invalid");
3012
+ const checked = signingClaims(kind, decoded.value.payload);
3013
+ return checked.ok ? ok(null) : checked;
3014
+ }
1807
3015
  // Assemble a validated signing input and its exact raw signature (the
1808
- // reference assemble): registry-row length, framing re-decode, size gate.
3016
+ // reference assemble): registry-row length, full artifact decode, size gate.
1809
3017
  export function assembleCompact(input, signature) {
3018
+ const plain = plainVerificationInputs({}, [input, signature], -1, -1, { 0: FRAMING_MEMBERS });
3019
+ if (!plain.ok)
3020
+ return plain.code === "limit_exceeded" ? fail("signing_input_invalid") : plain;
3021
+ [input, signature] = plain.value;
3022
+ return assembleUnderLimits(input, signature, DEFAULT_LIMITS);
3023
+ }
3024
+ function assembleUnderLimits(input, signature, limits) {
1810
3025
  if (!input || typeof input !== "object" || !Buffer.isBuffer(signature))
1811
3026
  return { ok: false, code: "invalid_type" };
1812
3027
  // The input is a struct the producer minted: the message must BE the
@@ -1822,9 +3037,9 @@ export function assembleCompact(input, signature) {
1822
3037
  if (signature.length !== row.signatureBytes)
1823
3038
  return { ok: false, code: "signature_invalid" };
1824
3039
  const compact = `${input.message.toString("utf8")}.${encodeBase64url(signature)}`;
1825
- if (Buffer.byteLength(compact) > JSON_DEFAULT_LIMITS.max_bytes)
3040
+ if (Buffer.byteLength(compact) > limits.max_bytes)
1826
3041
  return { ok: false, code: "signing_input_invalid" };
1827
- const decoded = decodeArtifact(compact);
3042
+ const decoded = decodeSigningArtifact(compact, limits);
1828
3043
  if (!decoded.ok)
1829
3044
  return { ok: false, code: "signing_input_invalid" };
1830
3045
  return { ok: true, compact };
@@ -1848,7 +3063,7 @@ function refusalChain(chainInput) {
1848
3063
  if (!chainInput || typeof chainInput !== "object" || Array.isArray(chainInput))
1849
3064
  return { invalidSet: "signing_input_invalid" };
1850
3065
  const chain = chainFromInput(chainInput);
1851
- return chain.ok ? { chain: chain.value } : { invalidSet: "chain_invalid" };
3066
+ return chain.ok ? { chain: chain.value } : { invalidSet: chain.code };
1852
3067
  }
1853
3068
  function refusalPartyMatches(revision, claims) {
1854
3069
  return revision.value.parties.some((party) => party.role === claims.party_role && party.party_descriptor_digest === claims.party_descriptor_digest);
@@ -1863,13 +3078,19 @@ function refusalAncestorOf(candidate, target, byDigest) {
1863
3078
  return typeof previous === "string" ? refusalAncestorOf(previous, target, byDigest) : false;
1864
3079
  }
1865
3080
  export function acceptanceRefusal(claims, chainInput) {
3081
+ const plain = plainVerificationInputs({}, [claims, chainInput], 0, -1, { 1: CHAIN_MEMBERS });
3082
+ if (!plain.ok)
3083
+ return plain;
3084
+ [claims, chainInput] = plain.value;
1866
3085
  if (!refusalClaimsShape(claims, ["revision_digest", "charter_id", "party_role", "party_descriptor_digest"], ["revision_number"])) {
1867
3086
  return { ok: false, code: "signing_input_invalid" };
1868
3087
  }
1869
3088
  const resolved = refusalChain(chainInput);
1870
3089
  if ("invalidSet" in resolved)
1871
3090
  return { ok: false, code: resolved.invalidSet };
1872
- const chain = resolved.chain;
3091
+ return acceptanceRefusalInChain(claims, resolved.chain);
3092
+ }
3093
+ function acceptanceRefusalInChain(claims, chain) {
1873
3094
  // R1 claims-truth: the named revision exists and every coordinate binds.
1874
3095
  const revision = chain.revisions.find((one) => one.digest === claims.revision_digest);
1875
3096
  if (!revision)
@@ -1899,6 +3120,10 @@ export function acceptanceRefusal(claims, chainInput) {
1899
3120
  return { ok: true };
1900
3121
  }
1901
3122
  export function terminationRefusal(claims, chainInput) {
3123
+ const plain = plainVerificationInputs({}, [claims, chainInput], 0, -1, { 1: CHAIN_MEMBERS });
3124
+ if (!plain.ok)
3125
+ return plain;
3126
+ [claims, chainInput] = plain.value;
1902
3127
  if (!refusalClaimsShape(claims, ["governing_revision_digest", "charter_id", "party_role", "party_descriptor_digest", "reason_code"], [])) {
1903
3128
  return { ok: false, code: "signing_input_invalid" };
1904
3129
  }
@@ -1908,7 +3133,9 @@ export function terminationRefusal(claims, chainInput) {
1908
3133
  const resolved = refusalChain(chainInput);
1909
3134
  if ("invalidSet" in resolved)
1910
3135
  return { ok: false, code: resolved.invalidSet };
1911
- const chain = resolved.chain;
3136
+ return terminationRefusalInChain(claims, resolved.chain);
3137
+ }
3138
+ function terminationRefusalInChain(claims, chain) {
1912
3139
  // R1 claims-truth: the named revision exists, the reason is listed in its
1913
3140
  // termination rules, and the signing party is one of its parties.
1914
3141
  const revision = chain.revisions.find((one) => one.digest === claims.governing_revision_digest);
@@ -1923,7 +3150,7 @@ export function terminationRefusal(claims, chainInput) {
1923
3150
  // R3 governing coverage: the named revision must be THE unique governing
1924
3151
  // revision at the notice's own effective instant — a stale or contested
1925
3152
  // view refuses.
1926
- if (governing(chain, effectiveAt) !== revision.digest)
3153
+ if (governing(chain, parseTimestamp(claims.effective_at)) !== revision.digest)
1927
3154
  return refused();
1928
3155
  return { ok: true };
1929
3156
  }