@charter-agreement-protocol/verifier 0.7.0 → 2.0.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,8 @@ 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 = "xiyty9a_VZTgiIYIKqGZQIAhJB-OQZRIcOX_zyNV-VQ";
9
+ // The raw index SHA-256 must also match corpus_source in reference.json.
10
+ export const CERTIFIED_INDEX_SHA256_BASE64URL = "P3HeGj26KfNYWy2LKFTPvjZZhjEU4cafd4Z2agGcc64";
10
11
  export const CERTIFIED_REGISTRY_DIGEST = "sha-256:u754joyHGcLCTm1LYV2s6eHauUUdDfJDwwyhbAbxvzc";
11
12
  // The fourth certified identity — the specification digest over the spec
12
13
  // set — is pinned in priv/release-metadata.json and enforced by the
@@ -23,7 +24,7 @@ const ALG_ROWS = [
23
24
  { name: "ML-DSA-65", minProtocolRevision: 3, keyAlgorithm: "ML-DSA-65", publicKeyBytes: 1952, signatureBytes: 3309 },
24
25
  { name: "ML-DSA-87", minProtocolRevision: 3, keyAlgorithm: "ML-DSA-87", publicKeyBytes: 2592, signatureBytes: 4627 },
25
26
  ];
26
- const ACCEPTED_PROTOCOL_REVISIONS = [1, 2, 3];
27
+ const ACCEPTED_PROTOCOL_REVISIONS = [1, 2, 3, 8];
27
28
  // The per-artifact binding rule: EdDSA at any accepted revision, Ed25519
28
29
  // from revision 2, unknown revisions fail closed. Views mix revisions
29
30
  // freely; the rule binds within one artifact.
@@ -32,6 +33,9 @@ function algBinds(alg, protocolRevision) {
32
33
  return row !== undefined && ACCEPTED_PROTOCOL_REVISIONS.includes(protocolRevision) && protocolRevision >= row.minProtocolRevision;
33
34
  }
34
35
  const SEPARATORS = {
36
+ signer_key: "charter-agreement-protocol/signer-key",
37
+ descriptor_next_keys: "charter-agreement-protocol/descriptor-next-keys",
38
+ descriptor_publication_content: "charter-agreement-protocol/descriptor-publication-content",
35
39
  party_descriptor_content: "charter-agreement-protocol/party-descriptor-content",
36
40
  charter_revision_content: "charter-agreement-protocol/charter-revision-content",
37
41
  acceptance_content: "charter-agreement-protocol/acceptance-content",
@@ -47,9 +51,9 @@ const SEPARATORS = {
47
51
  };
48
52
  const SURFACES = [
49
53
  "base64url.decode", "json.decode", "canonicalization.encode", "digest.hash",
50
- "schema.validate", "party_descriptor.verify", "descriptor_chain.verify",
54
+ "schema.validate", "party_descriptor.verify", "descriptor_chain.verify", "descriptor_publication.verify",
51
55
  "charter_revision.decode", "acceptance.verify", "acceptance.equivocation",
52
- "termination.verify", "chain.verify", "chain.verify_profile", "governing_revision", "receipt.verify",
56
+ "termination.verify", "chain.verify", "chain.verify_profile", "governing_revision", "receipt.verify", "receipt.inspect",
53
57
  "signing.prepare",
54
58
  ];
55
59
  const CLASSES = [
@@ -70,11 +74,13 @@ const REQUIRED = {
70
74
  "chain.verify_profile": ["profile_algorithm_outside", "profile_revision_outside", "profile_narrow_valid", "invalid_type"],
71
75
  "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
76
  "descriptor_chain.verify": ["signature_invalid", "chain_invalid", "descriptor_superseded", "descriptor_fork", "invalid_type"],
77
+ "descriptor_publication.verify": ["valid", "invalid_type", "invalid_constraint", "unknown_member", "non_canonical_bytes", "maximum_plus_one", "signature_invalid", "profile_revision_outside", "profile_algorithm_outside"],
73
78
  "digest.hash": ["valid", "invalid_type", "digest_mismatch"],
74
79
  "governing_revision": ["precedence_selection", "terminated", "invalid_type"],
75
80
  "json.decode": ["valid", "boundary_near", "exact_bound", "maximum_plus_one", "invalid_encoding", "invalid_type"],
76
81
  "party_descriptor.verify": ["valid", "signature_invalid", "invalid_encoding", "unknown_member", "invalid_constraint", "profile_narrow_valid", "profile_algorithm_outside", "profile_revision_outside", "invalid_type"],
77
82
  "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"],
83
+ "receipt.inspect": ["valid", "invalid_type", "invalid_constraint", "signature_invalid", "chain_fork", "terminated", "maximum_plus_one"],
78
84
  "schema.validate": ["valid", "invalid_type", "invalid_constraint", "invalid_cardinality", "unknown_member", "missing_required", "maximum_plus_one"],
79
85
  "signing.prepare": ["valid", "exact_bound", "maximum_plus_one", "invalid_type", "invalid_constraint", "chain_invalid", "profile_algorithm_outside", "profile_revision_outside"],
80
86
  "termination.verify": ["valid", "invalid_constraint", "signature_invalid", "unknown_member", "profile_narrow_valid", "profile_algorithm_outside", "profile_revision_outside", "invalid_type"],
@@ -90,7 +96,7 @@ function factsRecord(attrs, additions = []) {
90
96
  }
91
97
  export function canonical(value) {
92
98
  if (value instanceof Number)
93
- return JSON.stringify(value.valueOf());
99
+ return JSON.stringify(Number.prototype.valueOf.call(value));
94
100
  if (value === null || typeof value === "boolean" || typeof value === "string")
95
101
  return JSON.stringify(value);
96
102
  if (typeof value === "number" && Number.isFinite(value)) {
@@ -109,7 +115,7 @@ function rawHash(bytes) {
109
115
  return createHash("sha256").update(bytes).digest("base64url");
110
116
  }
111
117
  function taggedHash(domain, bytes) {
112
- const preimage = Buffer.concat([Buffer.from(SEPARATORS[domain]), Buffer.from([0]), Buffer.from(bytes)]);
118
+ const preimage = Buffer.concat([Buffer.from(SEPARATORS[domain]), Buffer.from([0]), bytes]);
113
119
  return `sha-256:${rawHash(preimage)}`;
114
120
  }
115
121
  function exactKeys(object, keys) {
@@ -439,7 +445,7 @@ export function jsonProjection(value) {
439
445
  if (value === null)
440
446
  return { tag: "null" };
441
447
  if (value instanceof Number)
442
- return { tag: "float", value: value.valueOf() };
448
+ return { tag: "float", value: Number.prototype.valueOf.call(value) };
443
449
  if (Number.isInteger(value))
444
450
  return { tag: "integer", value };
445
451
  if (Array.isArray(value))
@@ -495,6 +501,8 @@ function decodeJws(compact, limits = DEFAULT_LIMITS, expectedTyp) {
495
501
  if (!isRecord(payloadValue.value))
496
502
  return fail("protected_header_invalid");
497
503
  const payload = payloadValue.value;
504
+ if (payload.protocol_revision === 8 && !["cap+party", "cap+acceptance", "cap+termination"].includes(header.typ))
505
+ return fail("protected_header_invalid");
498
506
  if (typeof payload.protocol_revision !== "number" || !Number.isInteger(payload.protocol_revision) || !algBinds(header.alg, payload.protocol_revision))
499
507
  return fail("protected_header_invalid");
500
508
  const row = ALG_ROWS.find((one) => one.name === header.alg);
@@ -648,8 +656,8 @@ function verifyDecodedJws(decoded, typ, keys, settings = DEFAULT_SETTINGS) {
648
656
  return fail(runtimeSupportsAlgorithm(row.keyAlgorithm) ? "signature_invalid" : "algorithm_unsupported_on_substrate");
649
657
  }
650
658
  }
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 });
659
+ function preparedArtifact(decoded, keys, facts, missingKeyCode, unnamed = false, scopeStatus = facts.scope_status ?? "not_required") {
660
+ return ok({ decoded, keys: keys.filter((key) => key.key_id === decoded.header.kid && key.status === "active"), facts, missingKeyCode, unnamed, scopeStatus });
653
661
  }
654
662
  function finishPreparedArtifact(prepared, settings) {
655
663
  if (!prepared.ok)
@@ -661,15 +669,26 @@ function finishPreparedArtifact(prepared, settings) {
661
669
  return fail(missingKeyCode);
662
670
  if (decoded.header.typ !== "cap+receipt") {
663
671
  const signature = verifyDecodedJws(decoded, decoded.header.typ, keys, settings);
664
- return signature.ok ? ok(facts) : signature;
672
+ if (!signature.ok)
673
+ return signature;
674
+ if (decoded.header.typ === "cap+party" && prepared.value.scopeStatus === "outside")
675
+ return fail("descriptor_chain_invalid");
676
+ return ok(facts);
665
677
  }
678
+ const verified = verifiedReceiptKey(prepared.value, settings);
679
+ return verified.ok ? ok(facts) : verified;
680
+ }
681
+ function verifiedReceiptKey(prepared, settings) {
682
+ const { decoded, keys } = prepared;
666
683
  const candidates = keys.map((key) => ({ key, result: verifyDecodedJws(decoded, "cap+receipt", [key], settings) }));
667
684
  const verifiedPublicKeys = new Set(candidates.filter((one) => one.result.ok).map((one) => one.key.public_key));
668
685
  if (verifiedPublicKeys.size !== 1) {
669
686
  const diagnostic = candidates.find((one) => !one.result.ok && ["algorithm_outside_profile", "revision_outside_profile", "algorithm_unsupported_on_substrate"].includes(one.result.code));
670
687
  return fail(verifiedPublicKeys.size === 0 && diagnostic && !diagnostic.result.ok ? diagnostic.result.code : "signature_invalid");
671
688
  }
672
- return ok(facts);
689
+ const holders = prepared.holderKeys ?? keys;
690
+ return holders.some((key) => verifiedPublicKeys.has(key.public_key))
691
+ ? ok(candidates.find((one) => one.result.ok).key) : fail("receipt_claims_mismatch");
673
692
  }
674
693
  const TIMESTAMP_GRAMMAR = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?Z$/;
675
694
  // Exact RFC 3339 UTC parse mirroring Timestamp.ex: real calendar date, hour
@@ -711,12 +730,14 @@ function prepareDescriptor(compact, predecessor = null, settings = DEFAULT_SETTI
711
730
  const decoded = decodeJws(compact, settings.limits, "cap+party");
712
731
  if (!decoded.ok)
713
732
  return decoded;
714
- const payload = decoded.value.payload;
715
- const keys = predecessor ? predecessor.payload.verification_keys : payload.verification_keys;
716
- const grammar = descriptorClaimsError(payload);
733
+ const grammar = descriptorClaimsError(decoded.value.payload);
717
734
  if (grammar)
718
735
  return fail(grammar);
719
- const digest = taggedHash("party_descriptor_content", decoded.value.payloadBytes);
736
+ return prepareDecodedDescriptor(compact, decoded.value, predecessor, settings);
737
+ }
738
+ function prepareDecodedDescriptor(compact, decoded, predecessor, settings, digest = taggedHash("party_descriptor_content", decoded.payloadBytes)) {
739
+ const { payload } = decoded;
740
+ const keys = predecessor ? predecessor.payload.verification_keys : payload.verification_keys;
720
741
  if (payload.descriptor_number === 1) {
721
742
  if (predecessor)
722
743
  return fail("descriptor_chain_invalid");
@@ -729,14 +750,56 @@ function prepareDescriptor(compact, predecessor = null, settings = DEFAULT_SETTI
729
750
  // The envelope is admitted before its kid is looked up, as in the
730
751
  // reference, so an out-of-profile artifact whose kid names no key reports
731
752
  // the profile code. Acceptances and terminations do the same.
732
- const descriptorAdmission = profileError(decoded.value.header.alg, payload.protocol_revision, settings);
753
+ const descriptorAdmission = profileError(decoded.header.alg, payload.protocol_revision, settings);
733
754
  if (descriptorAdmission)
734
755
  return fail(descriptorAdmission);
756
+ const promise = predecessor?.payload.next_key_commitment;
757
+ if (promise !== undefined &&
758
+ (payload.protocol_revision !== 8 || !equalDigest(promise, commitmentDigest(payload.verification_keys)))) {
759
+ return fail("descriptor_commitment_mismatch");
760
+ }
735
761
  if (!parseTimestamp(payload.effective_from)) {
736
762
  return fail("timestamp_invalid");
737
763
  }
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");
764
+ const facts = factsRecord({ ...decoded, digest, compact, lineage: [compact, ...(predecessor?.lineage ?? [])], protocol_revision: payload.protocol_revision, alg: decoded.header.alg });
765
+ const scopeStatus = predecessor?.payload.signing_scopes === undefined ? "not_required" :
766
+ scopeForKey(predecessor.payload, decoded.header.kid, null, "descriptor").scope_status;
767
+ return preparedArtifact(decoded, keys, facts, "descriptor_key_invalid", false, scopeStatus);
768
+ }
769
+ function equalDigest(left, right) {
770
+ if (left.length !== right.length)
771
+ return false;
772
+ let difference = 0;
773
+ for (let i = 0; i < left.length; i++)
774
+ difference |= left.charCodeAt(i) ^ right.charCodeAt(i);
775
+ return difference === 0;
776
+ }
777
+ function keyThumbprint(key) {
778
+ return taggedHash("signer_key", Buffer.from(canonical({ algorithm: key.algorithm, public_key: key.public_key })));
779
+ }
780
+ function activeThumbprints(keys) {
781
+ return keys.filter((key) => key.status === "active").map(keyThumbprint);
782
+ }
783
+ function commitmentDigest(keys) {
784
+ return taggedHash("descriptor_next_keys", Buffer.from(canonical(activeThumbprints(keys).sort())));
785
+ }
786
+ const SCOPE_KINDS = ["acceptance", "descriptor", "receipt", "termination"];
787
+ const UNVERIFIED_SCOPE = { scope_status: "not_verified", signer_thumbprint: null };
788
+ function scopeForKey(descriptor, kid, role, kind) {
789
+ const key = descriptor?.verification_keys.find((one) => one.key_id === kid && one.status === "active");
790
+ if (!key)
791
+ return UNVERIFIED_SCOPE;
792
+ const thumbprint = keyThumbprint(key);
793
+ const scopes = descriptor?.signing_scopes;
794
+ if (scopes === undefined)
795
+ return { scope_status: "not_required", signer_thumbprint: thumbprint };
796
+ const matched = scopes.some((scope) => (kind === "descriptor" || scope.role === role) &&
797
+ scope.signers.some((signer) => signer.key_thumbprint === thumbprint && signer.artifact_kinds.includes(kind)));
798
+ return { scope_status: matched ? "matched" : "outside", signer_thumbprint: thumbprint };
799
+ }
800
+ function scopeProjection(facts) {
801
+ const { scope_status, signer_thumbprint } = facts;
802
+ return scope_status === "matched" || scope_status === "outside" ? { scope_status, signer_thumbprint } : {};
740
803
  }
741
804
  function descriptorFromCompact(compact, predecessor = null, settings = DEFAULT_SETTINGS) {
742
805
  return finishPreparedArtifact(prepareDescriptor(compact, predecessor, settings), settings);
@@ -785,29 +848,34 @@ function descriptorChain(compacts, settings = DEFAULT_SETTINGS) {
785
848
  return fail("descriptor_chain_invalid");
786
849
  const root = descriptorFromCompact(roots[0].compact, null, settings);
787
850
  if (!root.ok)
788
- return historyFailure([root.code]);
789
- const descriptors = [root.value];
851
+ return root;
852
+ const pending = [root.value];
853
+ const descriptors = [];
790
854
  const children = new Map();
791
855
  for (const entry of entries) {
792
856
  const prev = entry.payload.prev_descriptor_digest;
793
857
  if (prev)
794
858
  children.set(prev, [...(children.get(prev) ?? []), entry]);
795
859
  }
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));
860
+ while (pending.length > 0) {
861
+ const predecessor = pending.pop();
862
+ descriptors.push(predecessor);
863
+ const siblings = children.get(predecessor.digest) ?? [];
864
+ const results = siblings.map((entry) => descriptorFromCompact(entry.compact, predecessor, settings));
799
865
  const failures = results.filter((result) => !result.ok).map((result) => result.code);
800
866
  if (failures.length > 0)
801
867
  return historyFailure(failures);
802
- for (const result of results)
868
+ // Complete each child's branch before evaluating the next child's descendants.
869
+ for (const result of results.reverse())
803
870
  if (result.ok)
804
- descriptors.push(result.value);
871
+ pending.push(result.value);
805
872
  }
806
873
  if (descriptors.length !== entries.length)
807
874
  return fail("descriptor_chain_invalid");
808
875
  const siblings = [...children.values()].filter((group) => group.length > 1).flat().map((entry) => entry.digest);
809
876
  const fork = siblings.length > 0;
810
- descriptors.sort((a, b) => a.payload.descriptor_number - b.payload.descriptor_number || a.digest.localeCompare(b.digest));
877
+ descriptors.sort((a, b) => a.payload.descriptor_number - b.payload.descriptor_number ||
878
+ (a.digest < b.digest ? -1 : a.digest > b.digest ? 1 : 0));
811
879
  const positions = Object.fromEntries(descriptors.map((one) => [one.digest, fork ? "contested" : (children.has(one.digest) ? "superseded" : "head")]));
812
880
  for (const descriptor of descriptors)
813
881
  Object.assign(descriptor, { descriptor_position: positions[descriptor.digest] });
@@ -834,7 +902,7 @@ function descriptorViews(compacts, settings = DEFAULT_SETTINGS) {
834
902
  const id = decoded.value.payload.party_id ?? taggedHash("party_descriptor_content", decoded.value.payloadBytes);
835
903
  groups.set(id, [...(groups.get(id) ?? []), compact]);
836
904
  }
837
- if (groups.size !== 2)
905
+ if (groups.size < 2)
838
906
  return fail("chain_invalid");
839
907
  const histories = [];
840
908
  for (const id of [...groups.keys()].sort()) {
@@ -878,6 +946,9 @@ function extensionRegistryDigest() {
878
946
  function isRecord(value) {
879
947
  return value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Number);
880
948
  }
949
+ function isCanonicalObject(value) {
950
+ return value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Number);
951
+ }
881
952
  function field(name, type, constraint, required = true) {
882
953
  return { name, type, constraint, required };
883
954
  }
@@ -936,8 +1007,10 @@ function integerTokenError(value, fields) {
936
1007
  return "invalid_type";
937
1008
  if (!rule.nested)
938
1009
  continue;
939
- const items = rule.type === "array" && Array.isArray(item) ? item : [item];
940
- for (const child of items) {
1010
+ const children = rule.type === "array" ? item : [item];
1011
+ if (!Array.isArray(children))
1012
+ continue;
1013
+ for (const child of children) {
941
1014
  const error = integerTokenError(child, rule.nested);
942
1015
  if (error)
943
1016
  return error;
@@ -958,18 +1031,60 @@ const REVISION_SCHEMA = [
958
1031
  field("receipt_profile", "string", (v) => stringBytes(3, 512)(v) && /^[a-z0-9][a-z0-9.-]*\/[a-z0-9][a-z0-9.-]*$/.test(v)),
959
1032
  { name: "supersedes", type: "array", required: false, cardinality: [0, 8] }, field("extensions", "object"),
960
1033
  ];
1034
+ const QUORUM_FIELDS = [
1035
+ { name: "roles", type: "array", required: true, cardinality: [0, 64] },
1036
+ field("threshold", "integer", integerRange(0, 64)),
1037
+ ];
1038
+ const QUORUM_REVISION_SCHEMA = [
1039
+ ...REVISION_SCHEMA.map((rule) => {
1040
+ if (rule.name === "protocol_revision")
1041
+ return field("protocol_revision", "integer", integerRange(8, 8));
1042
+ if (rule.name === "parties") {
1043
+ return nestedField("parties", "array", [
1044
+ digestField("party_descriptor_digest"), roleField("role"),
1045
+ field("participation", "string", oneOf("acceptor", "arbiter")),
1046
+ ], [2, 64]);
1047
+ }
1048
+ if (rule.name === "termination_rules") {
1049
+ return nestedField("termination_rules", "object", [
1050
+ ...(rule.nested ?? []), nestedField("quorum", "object", QUORUM_FIELDS),
1051
+ ]);
1052
+ }
1053
+ return rule;
1054
+ }),
1055
+ nestedField("acceptance_quorum", "object", QUORUM_FIELDS),
1056
+ { ...nestedField("party_replacements", "array", [
1057
+ roleField("role"), digestField("assignor_party_id"),
1058
+ digestField("assignor_descriptor_digest"), digestField("assignee_descriptor_digest"),
1059
+ nestedField("assent_quorum", "object", QUORUM_FIELDS),
1060
+ ], [0, 64]), required: false },
1061
+ ];
1062
+ const VERIFICATION_KEY_FIELDS = [
1063
+ field("key_id", "string", (v) => /^[A-Za-z0-9._~-]{1,128}$/.test(v)),
1064
+ field("algorithm", "string", oneOf("Ed25519", "ML-DSA-44", "ML-DSA-65", "ML-DSA-87")),
1065
+ 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)),
1066
+ field("status", "string", oneOf("active", "retired")),
1067
+ ];
961
1068
  const DESCRIPTOR_SCHEMA = [
962
1069
  field("protocol_revision", "integer", integerRange(1, 3)), digestField("party_id", false),
963
1070
  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]),
1071
+ nestedField("verification_keys", "array", VERIFICATION_KEY_FIELDS, [1, 32]),
970
1072
  nestedField("attestation_hints", "array", [field("kind", "string", stringBytes(1, 64)), field("uri", "string", stringBytes(1, 2048))], [0, 16]),
971
1073
  field("extensions", "object"), timeField("effective_from"),
972
1074
  ];
1075
+ const COMMITTED_DESCRIPTOR_SCHEMA = [
1076
+ ...DESCRIPTOR_SCHEMA.map((rule) => rule.name === "protocol_revision"
1077
+ ? field("protocol_revision", "integer", integerRange(8, 8))
1078
+ : rule),
1079
+ digestField("next_key_commitment", false),
1080
+ { ...nestedField("signing_scopes", "array", [
1081
+ roleField("role"),
1082
+ nestedField("signers", "array", [
1083
+ field("key_thumbprint", "string", (value) => value.length === 51 && digestPattern(value)),
1084
+ { name: "artifact_kinds", type: "array", required: true, cardinality: [0, 4] },
1085
+ ], [0, 32]),
1086
+ ], [0, 64]), required: false },
1087
+ ];
973
1088
  const ACCEPTANCE_SCHEMA = [
974
1089
  field("protocol_revision", "integer", integerRange(1, 3)), digestField("charter_id"),
975
1090
  safeIntegerField("revision_number"), digestField("revision_digest"), digestField("prev_revision_digest", false),
@@ -980,6 +1095,14 @@ const TERMINATION_SCHEMA = [
980
1095
  digestField("governing_revision_digest"), digestField("party_descriptor_digest"),
981
1096
  roleField("party_role"), roleField("reason_code"), timeField("effective_at"), timeField("issued_at"), digestField("detail_digest", false),
982
1097
  ];
1098
+ const quorumRevisionField = (rule) => rule.name === "protocol_revision"
1099
+ ? field("protocol_revision", "integer", integerRange(8, 8))
1100
+ : rule;
1101
+ const QUORUM_ACCEPTANCE_SCHEMA = [
1102
+ ...ACCEPTANCE_SCHEMA.map(quorumRevisionField),
1103
+ field("replacement_role", "string", stringBytes(1, 128), false),
1104
+ ];
1105
+ const QUORUM_TERMINATION_SCHEMA = TERMINATION_SCHEMA.map(quorumRevisionField);
983
1106
  const RECEIPT_SCHEMA = [
984
1107
  field("protocol_revision", "integer", integerRange(1, 3)), digestField("charter_id"),
985
1108
  safeIntegerField("revision_number"), digestField("revision_digest"), roleField("issuing_party_role"), roleField("agent_party_role"), digestField("deployment_digest"),
@@ -1046,7 +1169,70 @@ function extensionError(envelope, surface) {
1046
1169
  return null;
1047
1170
  }
1048
1171
  function validTaggedDigest(value) {
1049
- return digestPattern(value) && strictBase64url(value.slice(8)).ok;
1172
+ return typeof value === "string" && digestPattern(value) && strictBase64url(value.slice(8)).ok;
1173
+ }
1174
+ function sortedUniqueStrings(values) {
1175
+ return values.every((value, index) => index === 0 || Buffer.compare(Buffer.from(values[index - 1]), Buffer.from(value)) < 0);
1176
+ }
1177
+ function validQuorum(rule, eligible, minimum) {
1178
+ return rule.roles.every((role) => typeof role === "string" && eligible.includes(role)) &&
1179
+ sortedUniqueStrings(rule.roles) && rule.threshold >= minimum && rule.threshold <= rule.roles.length;
1180
+ }
1181
+ function replacements(value) {
1182
+ return value.party_replacements ?? [];
1183
+ }
1184
+ function validQuorumRevision(value, roles) {
1185
+ const records = replacements(value);
1186
+ const changed = records.map((record) => record.role);
1187
+ const acceptance = value.acceptance_quorum;
1188
+ const acceptors = value.parties
1189
+ .filter((party) => party.participation === "acceptor").map((party) => party.role);
1190
+ const remaining = acceptance.roles.filter((role) => !changed.includes(role));
1191
+ const minimum = changed.length === roles.length ? 0 : 1;
1192
+ return sortedUniqueStrings(roles) &&
1193
+ validQuorum(acceptance, acceptors, 1) &&
1194
+ validQuorum(value.termination_rules.quorum, roles, 1) &&
1195
+ sortedUniqueStrings(changed) &&
1196
+ records.every((record) => acceptance.roles.includes(record.role) &&
1197
+ validQuorum(record.assent_quorum, remaining, minimum) &&
1198
+ [record.assignor_party_id, record.assignor_descriptor_digest, record.assignee_descriptor_digest]
1199
+ .every(validTaggedDigest));
1200
+ }
1201
+ function acceptanceRule(revision) {
1202
+ const parties = revision.value.parties;
1203
+ return revision.value.acceptance_quorum ?? { roles: parties.map((party) => party.role), threshold: parties.length };
1204
+ }
1205
+ function participationReason(revision, role) {
1206
+ if (revision?.value.protocol_revision !== 8)
1207
+ return null;
1208
+ const party = revision.value.parties.find((one) => one.role === role);
1209
+ if (party?.participation === "arbiter")
1210
+ return "arbiter_not_counted";
1211
+ return acceptanceRule(revision).roles.includes(role) ? null : "role_outside_quorum";
1212
+ }
1213
+ function acceptanceParticipationReason(claims, revision, predecessor) {
1214
+ const role = claims.party_role;
1215
+ if (claims.replacement_role !== undefined)
1216
+ return participationReason(predecessor, role);
1217
+ const reason = participationReason(revision, role);
1218
+ if (reason === "role_outside_quorum" && predecessor && acceptanceRule(predecessor).roles.includes(role))
1219
+ return null;
1220
+ return reason;
1221
+ }
1222
+ function terminationRule(revision) {
1223
+ const parties = revision.value.parties;
1224
+ return revision.value.termination_rules.quorum ?? { roles: parties.map((party) => party.role), threshold: 1 };
1225
+ }
1226
+ function quorumMet(rule, roles) {
1227
+ const votes = new Set(roles);
1228
+ return rule.roles.filter((role) => votes.has(role)).length >= rule.threshold;
1229
+ }
1230
+ function acceptanceBindingMatches(revision, claims) {
1231
+ if (claims.replacement_role === undefined)
1232
+ return refusalPartyMatches(revision, claims);
1233
+ return claims.replacement_role === claims.party_role &&
1234
+ replacements(revision.value).some((record) => record.role === claims.replacement_role &&
1235
+ record.assignor_descriptor_digest === claims.party_descriptor_digest);
1050
1236
  }
1051
1237
  function revisionFromText(text, limits = DEFAULT_LIMITS) {
1052
1238
  if (typeof text !== "string")
@@ -1054,14 +1240,16 @@ function revisionFromText(text, limits = DEFAULT_LIMITS) {
1054
1240
  const decoded = decodeJsonText(text, limits);
1055
1241
  if (!decoded.ok)
1056
1242
  return decoded;
1057
- const integerError = integerTokenError(decoded.value, REVISION_SCHEMA);
1243
+ const schema = isCanonicalObject(decoded.value) && decoded.value.protocol_revision === 8
1244
+ ? QUORUM_REVISION_SCHEMA : REVISION_SCHEMA;
1245
+ const integerError = integerTokenError(decoded.value, schema);
1058
1246
  if (integerError)
1059
1247
  return fail(integerError);
1060
1248
  const encoding = canonicalTextError(decoded.value, text);
1061
1249
  if (encoding)
1062
1250
  return fail(encoding);
1063
1251
  const value = decoded.value;
1064
- const shape = schemaError(value, REVISION_SCHEMA);
1252
+ const shape = schemaError(value, schema);
1065
1253
  if (shape)
1066
1254
  return fail(shape);
1067
1255
  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);
@@ -1089,6 +1277,8 @@ function revisionFromText(text, limits = DEFAULT_LIMITS) {
1089
1277
  if (until && compareTimestamps(from, until) >= 0)
1090
1278
  return fail("revision_invalid");
1091
1279
  const roles = value.parties.map((party) => party.role);
1280
+ if (value.protocol_revision === 8 && !validQuorumRevision(value, roles))
1281
+ return fail("revision_invalid");
1092
1282
  if (new Set(value.parties.map((party) => party.party_descriptor_digest)).size !== value.parties.length)
1093
1283
  return fail("revision_invalid");
1094
1284
  if (new Set(roles).size !== roles.length || value.abp_bindings.some((binding) => !roles.includes(binding.party_role)))
@@ -1106,8 +1296,7 @@ function prepareAcceptance(compact, revision, chain, settings = DEFAULT_SETTINGS
1106
1296
  return fail(acceptanceShape);
1107
1297
  const descriptor = chain.descriptors.find((one) => one.digest === claims.party_descriptor_digest);
1108
1298
  const expectedCharter = revision.value.charter_id || revision.digest;
1109
- const party = revision.value.parties.find((one) => one.party_descriptor_digest === claims.party_descriptor_digest);
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);
1299
+ const mismatch = (claims.protocol_revision === 8) !== (revision.value.protocol_revision === 8) || claims.charter_id !== expectedCharter || claims.revision_number !== revision.value.revision_number || claims.revision_digest !== revision.digest || !acceptanceBindingMatches(revision, claims) || (revision.value.prev_revision_digest || undefined) !== (claims.prev_revision_digest || undefined);
1111
1300
  if (mismatch)
1112
1301
  return fail("acceptance_claims_mismatch");
1113
1302
  if (!descriptor)
@@ -1115,7 +1304,8 @@ function prepareAcceptance(compact, revision, chain, settings = DEFAULT_SETTINGS
1115
1304
  const acceptanceAdmission = profileError(decoded.value.header.alg, claims.protocol_revision, settings);
1116
1305
  if (acceptanceAdmission)
1117
1306
  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 });
1307
+ const scope = scopeForKey(descriptor.payload, decoded.value.header.kid, claims.party_role, "acceptance");
1308
+ 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, ...scope });
1119
1309
  return preparedArtifact(decoded.value, descriptor.payload.verification_keys, facts, "acceptance_invalid");
1120
1310
  }
1121
1311
  function acceptanceFromCompact(compact, revision, chain, settings = DEFAULT_SETTINGS) {
@@ -1132,14 +1322,16 @@ function prepareTermination(compact, revision, chain, settings = DEFAULT_SETTING
1132
1322
  const descriptor = chain.descriptors.find((one) => one.digest === claims.party_descriptor_digest);
1133
1323
  const expectedCharter = revision.value.charter_id || revision.digest;
1134
1324
  const party = revision.value.parties.find((one) => one.party_descriptor_digest === claims.party_descriptor_digest);
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))
1325
+ if ((claims.protocol_revision === 8) !== (revision.value.protocol_revision === 8) ||
1326
+ 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))
1136
1327
  return fail("termination_claims_mismatch");
1137
1328
  if (!descriptor)
1138
1329
  return fail("termination_claims_mismatch");
1139
1330
  const terminationAdmission = profileError(decoded.value.header.alg, claims.protocol_revision, settings);
1140
1331
  if (terminationAdmission)
1141
1332
  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 });
1333
+ const scope = scopeForKey(descriptor.payload, decoded.value.header.kid, claims.party_role, "termination");
1334
+ 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, ...scope });
1143
1335
  return preparedArtifact(decoded.value, descriptor.payload.verification_keys, facts, "termination_invalid");
1144
1336
  }
1145
1337
  function terminationFromCompact(compact, revision, chain, settings = DEFAULT_SETTINGS) {
@@ -1245,7 +1437,7 @@ export function algorithmRegistryDigest() {
1245
1437
  ["signature_bytes", row.signatureBytes],
1246
1438
  ]),
1247
1439
  ]));
1248
- return taggedDigest("signature_registry", Buffer.from(canonical(value), "utf8"));
1440
+ return taggedHash("signature_registry", Buffer.from(canonical(value), "utf8"));
1249
1441
  }
1250
1442
  // Strict like the reference Profile.new/1: shape errors report invalid_type;
1251
1443
  // unknown names or out-of-accepted-range bounds report invalid_profile.
@@ -1257,13 +1449,17 @@ function parseProfile(spec) {
1257
1449
  if (!Array.isArray(spec.algorithms))
1258
1450
  return { ok: false, code: "invalid_type" };
1259
1451
  const names = spec.algorithms;
1260
- if (names.length === 0 || new Set(names).size !== names.length)
1452
+ const length = names.length;
1453
+ if (!Number.isInteger(length) || length < 1 || length > registryNames.length)
1261
1454
  return { ok: false, code: "invalid_profile" };
1262
- for (const name of names) {
1263
- if (typeof name !== "string" || !registryNames.includes(name))
1455
+ const selected = new Set();
1456
+ for (let i = 0; i < length; i++) {
1457
+ const name = names[i];
1458
+ if (typeof name !== "string" || !registryNames.includes(name) || selected.has(name))
1264
1459
  return { ok: false, code: "invalid_profile" };
1460
+ selected.add(name);
1265
1461
  }
1266
- algorithms = names;
1462
+ algorithms = [...selected];
1267
1463
  }
1268
1464
  let minRevision = Math.min(...ACCEPTED_PROTOCOL_REVISIONS);
1269
1465
  let maxRevision = Math.max(...ACCEPTED_PROTOCOL_REVISIONS);
@@ -1282,7 +1478,7 @@ function parseProfile(spec) {
1282
1478
  }
1283
1479
  return { ok: true, algorithms, minRevision, maxRevision };
1284
1480
  }
1285
- const DEFAULT_SETTINGS = { limits: DEFAULT_LIMITS, profile: { algorithms: ALG_ROWS.map((row) => row.name), minRevision: 1, maxRevision: 3 } };
1481
+ const DEFAULT_SETTINGS = { limits: DEFAULT_LIMITS, profile: { algorithms: ALG_ROWS.map((row) => row.name), minRevision: 1, maxRevision: Math.max(...ACCEPTED_PROTOCOL_REVISIONS) } };
1286
1482
  function resolveOptions(options = {}) {
1287
1483
  if (!isRecord(options) || (options.limits !== undefined && !validLimits(options.limits)))
1288
1484
  return fail("invalid_limits");
@@ -1307,38 +1503,65 @@ function revisionWithProfile(text, settings) {
1307
1503
  const admission = profileError(null, revision.value.value.protocol_revision, settings);
1308
1504
  return admission ? fail(admission) : revision;
1309
1505
  }
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";
1320
- }
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
1506
  function chainWithOptions(input, options = {}) {
1328
1507
  const settings = resolveOptions(options);
1329
1508
  return settings.ok ? chainFromInput(input, settings.value) : settings;
1330
1509
  }
1510
+ function validPartyTransition(revision, previous, owners) {
1511
+ if (revision.value.protocol_revision !== 8)
1512
+ return previous?.value.protocol_revision !== 8;
1513
+ const parties = revision.value.parties;
1514
+ const records = replacements(revision.value);
1515
+ if (!parties.every((party) => owners.has(party.party_descriptor_digest)))
1516
+ return false;
1517
+ if (!previous)
1518
+ return records.length === 0;
1519
+ const old = previous.value.parties;
1520
+ const oldOwners = new Set(old.map((party) => owners.get(party.party_descriptor_digest)));
1521
+ return old.length === parties.length && parties.every((party) => {
1522
+ const predecessor = old.find((binding) => binding.role === party.role);
1523
+ if (!predecessor || (predecessor.participation ?? "acceptor") !== party.participation)
1524
+ return false;
1525
+ const record = records.find((one) => one.role === party.role);
1526
+ const from = owners.get(predecessor.party_descriptor_digest);
1527
+ const to = owners.get(party.party_descriptor_digest);
1528
+ if (from === undefined || to === undefined)
1529
+ return false;
1530
+ if (from === to)
1531
+ return record === undefined;
1532
+ return record !== undefined && !oldOwners.has(to) &&
1533
+ record.assignor_party_id === from &&
1534
+ record.assignor_descriptor_digest === predecessor.party_descriptor_digest &&
1535
+ record.assignee_descriptor_digest === party.party_descriptor_digest;
1536
+ });
1537
+ }
1538
+ function revisionAssent(revision, matches, inherited) {
1539
+ const records = replacements(revision.value);
1540
+ const changed = new Set(records.map((record) => record.role));
1541
+ const incoming = matches.filter((one) => one.claims.replacement_role === undefined)
1542
+ .map((one) => one.claims.party_role);
1543
+ const outgoing = matches.filter((one) => one.claims.replacement_role !== undefined)
1544
+ .map((one) => one.claims.party_role);
1545
+ const prior = outgoing.concat(incoming.filter((role) => !changed.has(role)));
1546
+ const quorum = quorumMet(acceptanceRule(revision), incoming) &&
1547
+ (revision.value.protocol_revision !== 8 || inherited === undefined || quorumMet(acceptanceRule(inherited), prior));
1548
+ const missing = records.length === 0 ? [] : revision.value.parties
1549
+ .map((party) => party.role)
1550
+ .filter((role) => !incoming.includes(role) || (changed.has(role) && !outgoing.includes(role)));
1551
+ return { quorum, missing };
1552
+ }
1331
1553
  function chainFromInput(input, settings = DEFAULT_SETTINGS) {
1332
1554
  if (!isRecord(input))
1333
- return fail("chain_invalid");
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);
1555
+ return fail("invalid_type");
1556
+ const snapshot = copyChainArtifacts(input, settings.limits);
1557
+ if (!snapshot.ok)
1558
+ return snapshot;
1559
+ const view = snapshot.value;
1560
+ const descriptors = descriptorViews(view.descriptors, settings);
1338
1561
  if (!descriptors.ok)
1339
1562
  return descriptors;
1340
1563
  const revisions = [];
1341
- for (const text of input.revisions) {
1564
+ for (const text of view.revisions) {
1342
1565
  const revision = revisionFromText(text, settings.limits);
1343
1566
  if (!revision.ok)
1344
1567
  return revision;
@@ -1374,11 +1597,15 @@ function chainFromInput(input, settings = DEFAULT_SETTINGS) {
1374
1597
  }
1375
1598
  }
1376
1599
  }
1600
+ if (descriptors.value.histories.length !== 2 &&
1601
+ revisions.every((revision) => revision.value.protocol_revision !== 8))
1602
+ return fail("chain_invalid");
1377
1603
  const owners = new Map(descriptors.value.descriptors.map((one) => [one.digest, one.payload.party_id ?? one.digest]));
1378
1604
  const named = new Set();
1379
1605
  for (const revision of revisions) {
1380
1606
  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)
1607
+ if (new Set(parties).size !== parties.length ||
1608
+ !validPartyTransition(revision, byDigest.get(revision.value.prev_revision_digest), owners))
1382
1609
  return fail("chain_invalid");
1383
1610
  for (const id of parties)
1384
1611
  named.add(id);
@@ -1386,8 +1613,7 @@ function chainFromInput(input, settings = DEFAULT_SETTINGS) {
1386
1613
  if (descriptors.value.histories.some((history) => !named.has(history.descriptors[0].payload.party_id ?? history.descriptors[0].digest)))
1387
1614
  return fail("chain_invalid");
1388
1615
  const acceptances = [];
1389
- const coordinates = new Set();
1390
- for (const compact of (input.acceptances || [])) {
1616
+ for (const compact of view.acceptances) {
1391
1617
  const decoded = decodeJws(compact, settings.limits, "cap+acceptance");
1392
1618
  if (!decoded.ok)
1393
1619
  return decoded;
@@ -1398,29 +1624,63 @@ function chainFromInput(input, settings = DEFAULT_SETTINGS) {
1398
1624
  const verified = acceptanceFromCompact(compact, revision, chain, settings);
1399
1625
  if (!verified.ok)
1400
1626
  return verified;
1401
- const coordinate = `${verified.value.claims.revision_digest}\0${verified.value.claims.party_descriptor_digest}\0${verified.value.claims.party_role}`;
1402
- if (coordinates.has(coordinate))
1403
- return fail("chain_invalid");
1404
- coordinates.add(coordinate);
1405
- acceptances.push(verified.value);
1406
- }
1407
- const accepted = revisions.filter((revision) => {
1408
- const expected = new Set(revision.value.parties.map((party) => `${party.party_descriptor_digest}\0${party.role}`));
1409
- const actual = new Set(acceptances
1410
- .filter((one) => one.claims.revision_digest === revision.digest)
1411
- .map((one) => `${one.claims.party_descriptor_digest}\0${one.claims.party_role}`));
1412
- if (actual.size !== expected.size)
1413
- return false;
1414
- for (const entry of [...expected])
1415
- if (!actual.has(entry))
1416
- return false;
1417
- return true;
1418
- });
1419
- const acceptedSet = new Set(accepted.map((one) => one.digest));
1420
- if (accepted.some((one) => (one.value.supersedes ?? []).some((digest) => !acceptedSet.has(digest))))
1627
+ acceptances.push({ ...verified.value, credit: "not_required", credit_reason: null });
1628
+ }
1629
+ const coordinates = new Set(acceptances.map(({ claims }) => `${claims.revision_digest}\0${claims.party_descriptor_digest}\0${claims.party_role}`));
1630
+ if (coordinates.size !== acceptances.length)
1421
1631
  return fail("chain_invalid");
1632
+ const votesByRevision = new Map();
1633
+ for (const vote of acceptances) {
1634
+ const digest = vote.claims.revision_digest;
1635
+ const votes = votesByRevision.get(digest) ?? [];
1636
+ votes.push(vote);
1637
+ votesByRevision.set(digest, votes);
1638
+ }
1639
+ const acceptedSet = new Set();
1640
+ const signed = new Set();
1641
+ const inherited = new Map();
1642
+ const assignmentStatuses = {};
1643
+ const byRevisionNumber = [...revisions].sort((left, right) => left.value.revision_number - right.value.revision_number);
1644
+ for (const revision of byRevisionNumber) {
1645
+ const value = revision.value;
1646
+ const previous = inherited.get(value.prev_revision_digest);
1647
+ const rawPrevious = byDigest.get(value.prev_revision_digest);
1648
+ const predecessorRule = previous ?? rawPrevious;
1649
+ const matches = votesByRevision.get(revision.digest) ?? [];
1650
+ for (const vote of matches) {
1651
+ const reason = acceptanceParticipationReason(vote.claims, revision, predecessorRule) ??
1652
+ (vote.scope_status === "outside" ? "signer_outside_scope" : null);
1653
+ if (reason !== null) {
1654
+ vote.credit = "uncredited";
1655
+ vote.credit_reason = reason;
1656
+ }
1657
+ }
1658
+ const assigning = replacements(value).length > 0;
1659
+ // Ordinary assignment assent is required from every party. The rules
1660
+ // select the quorum roles, and an outside key supplies neither vote.
1661
+ const credited = matches.filter((vote) => vote.scope_status !== "outside" &&
1662
+ (vote.credit !== "uncredited" || (assigning && vote.claims.replacement_role === undefined)));
1663
+ const signature = revisionAssent(revision, matches, predecessorRule);
1664
+ if (signature.quorum && signature.missing.length === 0)
1665
+ signed.add(revision.digest);
1666
+ const { quorum, missing } = credited.length === matches.length
1667
+ ? signature : revisionAssent(revision, credited, predecessorRule);
1668
+ const eligible = quorum && missing.length === 0 && previous === rawPrevious;
1669
+ if (eligible)
1670
+ acceptedSet.add(revision.digest);
1671
+ inherited.set(revision.digest, eligible ? revision : previous);
1672
+ if (assigning) {
1673
+ assignmentStatuses[revision.digest] = { status: missing.length === 0 ? "accepted" : "pending", missingAssentRoles: missing };
1674
+ }
1675
+ }
1676
+ const accepted = revisions.filter((one) => acceptedSet.has(one.digest));
1677
+ for (const revision of revisions) {
1678
+ if (signed.has(revision.digest) &&
1679
+ (revision.value.supersedes ?? []).some((digest) => !signed.has(digest)))
1680
+ return fail("chain_invalid");
1681
+ }
1422
1682
  const terminations = [];
1423
- for (const compact of (input.terminations || [])) {
1683
+ for (const compact of view.terminations) {
1424
1684
  const decoded = decodeJws(compact, settings.limits, "cap+termination");
1425
1685
  if (!decoded.ok)
1426
1686
  return decoded;
@@ -1456,7 +1716,7 @@ function chainFromInput(input, settings = DEFAULT_SETTINGS) {
1456
1716
  };
1457
1717
  const linear = heads.length === 1 && ancestryCovers(heads[0].digest);
1458
1718
  const topology = active.length > 0 && !linear ? "forked" : "linear";
1459
- return ok(factsRecord({ descriptors: descriptors.value, revisions, acceptances, terminations, accepted, acceptedDigests: accepted.map((one) => one.digest).sort(), supersededDigests: [...superseded].sort(), topology, charterId }));
1719
+ return ok(factsRecord({ descriptors: descriptors.value, revisions, acceptances, terminations, accepted, acceptedDigests: [...acceptedSet].sort(), signedDigests: [...signed].sort(), supersededDigests: [...superseded].sort(), topology, charterId, assignmentStatuses }));
1460
1720
  }
1461
1721
  // Both set verification and pre-sign checks route through this lookup.
1462
1722
  function signingContextFromSet(revisions, descriptors, revisionDigest, descriptorDigest, code = "chain_invalid") {
@@ -1481,10 +1741,23 @@ function effectiveAt(revision, at) {
1481
1741
  return until !== null && compareTimestamps(at, until) < 0;
1482
1742
  }
1483
1743
  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;
1744
+ const groups = new Map();
1745
+ for (const notice of chain.terminations) {
1746
+ if (notice.scope_status === "outside")
1747
+ continue;
1748
+ const claims = notice.claims;
1749
+ const effective = parseTimestamp(claims.effective_at);
1750
+ const digest = claims.governing_revision_digest;
1751
+ const key = JSON.stringify([digest, claims.reason_code, effective.ticks, effective.fraction]);
1752
+ const group = groups.get(key) ?? { digest, effective, roles: [] };
1753
+ group.roles.push(claims.party_role);
1754
+ groups.set(key, group);
1755
+ }
1756
+ const revisions = new Map(chain.revisions.map((one) => [one.digest, one]));
1757
+ const closed = [...groups.values()].some(({ digest, effective, roles }) => {
1758
+ const revision = revisions.get(digest);
1759
+ return revision !== undefined && compareTimestamps(effective, at) <= 0 &&
1760
+ quorumMet(terminationRule(revision), roles) && selectGoverning(chain, effective) === digest;
1488
1761
  });
1489
1762
  return closed ? "none" : selectGoverning(chain, at);
1490
1763
  }
@@ -1533,15 +1806,48 @@ function projectReceipt(claims, chain, governingDigest) {
1533
1806
  const chainConflict = claims.revision_number <= acceptedHead ? "fork_evidenced" : "none";
1534
1807
  return ok({ governingMatch, chainConflict, deploymentMatched: false });
1535
1808
  }
1536
- function receiptSigningKeys(chain, claimedRevision, role) {
1809
+ function roleDescriptor(revision, role) {
1810
+ return revision.value.parties.find((party) => party.role === role)?.party_descriptor_digest;
1811
+ }
1812
+ function latestAssignmentRevision(chain, role, at) {
1813
+ const transfers = new Set(chain.accepted
1814
+ .filter((revision) => replacements(revision.value).some((record) => record.role === role))
1815
+ .map((revision) => revision.digest));
1816
+ const boundaries = chain.accepted.flatMap((revision) => [revision.value.effective_from, revision.value.effective_until].map(parseTimestamp)).filter((time) => time !== null && compareTimestamps(time, at) <= 0);
1817
+ boundaries.sort((left, right) => compareTimestamps(right, left));
1818
+ for (const boundary of boundaries) {
1819
+ const digest = governing(chain, boundary);
1820
+ if (transfers.has(digest))
1821
+ return digest;
1822
+ }
1823
+ return undefined;
1824
+ }
1825
+ function receiptSigningKeys(chain, claimedRevision, claims, governingDigest) {
1826
+ const role = claims.issuing_party_role;
1537
1827
  const revisions = claimedRevision ? [claimedRevision] : chain.accepted;
1538
- const keys = revisions.flatMap((revision) => revision.value.parties
1539
- .filter((party) => party.role === role)
1540
- .flatMap((party) => {
1541
- const descriptor = chain.descriptors.descriptors.find((one) => one.digest === party.party_descriptor_digest);
1542
- return descriptor?.payload.verification_keys || [];
1543
- }));
1544
- return [...new Map(keys.map((key) => [canonical(key), key])).values()];
1828
+ const findDescriptor = (digest) => chain.descriptors.descriptors.find((entry) => entry.digest === digest);
1829
+ const descriptors = revisions.flatMap((revision) => {
1830
+ const descriptor = findDescriptor(roleDescriptor(revision, role));
1831
+ return descriptor ? [descriptor] : [];
1832
+ });
1833
+ const keysFrom = (sources) => {
1834
+ const keys = sources.flatMap((descriptor) => descriptor.payload.verification_keys);
1835
+ return [...new Map(keys.map((key) => [canonical(key), key])).values()];
1836
+ };
1837
+ const keys = keysFrom(descriptors);
1838
+ const scopeDescriptor = claimedRevision ? descriptors[0]?.payload : undefined;
1839
+ if (!chain.accepted.some((revision) => replacements(revision.value).length > 0)) {
1840
+ return { keys, holderKeys: keys, holderMatch: "not_evaluated", scopeDescriptor };
1841
+ }
1842
+ const holderDigest = governingDigest === "none" ?
1843
+ latestAssignmentRevision(chain, role, parseTimestamp(claims.occurred_at)) : governingDigest;
1844
+ const holderRevision = chain.accepted.find((revision) => revision.digest === holderDigest);
1845
+ const holder = holderRevision && findDescriptor(roleDescriptor(holderRevision, role));
1846
+ if (!holder)
1847
+ return { keys, holderKeys: keys, holderMatch: "undetermined", scopeDescriptor };
1848
+ const owner = holder.payload.party_id ?? holder.digest;
1849
+ const holderKeys = keysFrom(descriptors.filter((descriptor) => (descriptor.payload.party_id ?? descriptor.digest) === owner));
1850
+ return { keys, holderKeys, holderMatch: governingDigest === "none" ? "undetermined" : "match", scopeDescriptor };
1545
1851
  }
1546
1852
  function prepareReceipt(compact, context, settings = DEFAULT_SETTINGS) {
1547
1853
  const revisionOnly = context.kind === "revision";
@@ -1567,7 +1873,8 @@ function prepareReceipt(compact, context, settings = DEFAULT_SETTINGS) {
1567
1873
  const admission = profileError(decoded.value.header.alg, claims.protocol_revision, settings);
1568
1874
  if (admission)
1569
1875
  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"]);
1876
+ const additions = context.revision.value.protocol_revision === 8 ? ["signature", "ownership"] : ["signature"];
1877
+ const facts = factsRecord({ claims, digest: taggedHash("receipt_content", decoded.value.payloadBytes), ...projection.value, holderMatch: "not_evaluated", optionalExtensions: Object.keys(claims.extensions?.optional || {}).sort(), protocol_revision: claims.protocol_revision, alg: decoded.value.header.alg, ...UNVERIFIED_SCOPE }, additions);
1571
1878
  return preparedArtifact(decoded.value, [], facts, "signature_invalid", true);
1572
1879
  }
1573
1880
  // The envelope is admitted before any key is looked up, so an
@@ -1576,9 +1883,11 @@ function prepareReceipt(compact, context, settings = DEFAULT_SETTINGS) {
1576
1883
  const envelopeAdmission = profileError(decoded.value.header.alg, claims.protocol_revision, settings);
1577
1884
  if (envelopeAdmission)
1578
1885
  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");
1886
+ const { keys, holderKeys, holderMatch, scopeDescriptor } = receiptSigningKeys(context.chain, claimedRevision, claims, governingDigest);
1887
+ const scope = scopeForKey(scopeDescriptor, decoded.value.header.kid, claims.issuing_party_role, "receipt");
1888
+ const facts = factsRecord({ claims, digest: taggedHash("receipt_content", decoded.value.payloadBytes), ...projection.value, holderMatch, optionalExtensions: Object.keys(claims.extensions?.optional || {}).sort(), protocol_revision: claims.protocol_revision, alg: decoded.value.header.alg, ...scope });
1889
+ const prepared = preparedArtifact(decoded.value, keys, facts, "signature_invalid");
1890
+ return prepared.ok ? ok({ ...prepared.value, holderKeys: holderKeys.filter((key) => key.key_id === decoded.value.header.kid && key.status === "active") }) : prepared;
1582
1891
  }
1583
1892
  function receiptFromCompact(compact, context, settings = DEFAULT_SETTINGS) {
1584
1893
  return finishPreparedArtifact(prepareReceipt(compact, context, settings), settings);
@@ -1666,7 +1975,7 @@ function signingCaseOptions(input) {
1666
1975
  const range = selectedProfile.revisions;
1667
1976
  const profile = {
1668
1977
  algorithms: Object.hasOwn(selectedProfile, "algorithms") ? selectedProfile.algorithms : DEFAULT_SETTINGS.profile.algorithms,
1669
- revisions: range ? { min: range.min, max: range.max } : { min: 1, max: 3 },
1978
+ revisions: range ? { min: range.min, max: range.max } : { min: 1, max: DEFAULT_SETTINGS.profile.maxRevision },
1670
1979
  };
1671
1980
  return { algorithm: input.algorithm, limits, profile };
1672
1981
  }
@@ -1682,10 +1991,10 @@ function executeArtifactCase(one) {
1682
1991
  if (!key.ok)
1683
1992
  return invalid(key.code);
1684
1993
  const kind = input.kind === "party_descriptor" ? "descriptor" :
1685
- ["acceptance", "termination", "receipt"].includes(input.kind) ? input.kind : "unknown";
1994
+ ["acceptance", "party_replacement", "termination", "receipt"].includes(input.kind) ? input.kind : "unknown";
1686
1995
  const matches = kind === "descriptor" ? context.value.kind === "descriptor" :
1687
1996
  kind === "receipt" ? ["chain", "revision"].includes(context.value.kind) :
1688
- (kind === "acceptance" || kind === "termination") && context.value.kind === "set";
1997
+ (kind === "acceptance" || kind === "party_replacement" || kind === "termination") && context.value.kind === "set";
1689
1998
  const prepared = prepareSigning(kind, input.kid, input.claims, encodeBase64url(key.value), matches ? context.value.value : {}, options);
1690
1999
  if (!prepared.ok)
1691
2000
  return invalid(prepared.code);
@@ -1716,32 +2025,56 @@ function executeArtifactCase(one) {
1716
2025
  const verified = verifyAcceptance(input.compact, input.revision_text, input.descriptor_compacts, { profile: input.profile });
1717
2026
  if (!verified.ok)
1718
2027
  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 });
2028
+ 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, ...scopeProjection(verified.facts) });
1720
2029
  }
1721
2030
  case "termination.verify": {
1722
2031
  const verified = verifyTermination(input.compact, input.revision_text, input.descriptor_compacts, { profile: input.profile });
1723
2032
  if (!verified.ok)
1724
2033
  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 });
2034
+ 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, ...scopeProjection(verified.facts) });
1726
2035
  }
1727
2036
  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 });
2037
+ const bareRevision = Object.hasOwn(input, "revision_text");
2038
+ if (!bareRevision) {
2039
+ if (!exactKeys(input.chain, [...CHAIN_MEMBERS]))
2040
+ return invalid("invalid_type");
2041
+ const context = verifyChain(input.chain, { limits: input.limits });
1735
2042
  if (!context.ok)
1736
2043
  return invalid(context.code);
1737
2044
  }
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 }));
2045
+ const verified = verifyReceipt(input.compact, bareRevision ? input.revision_text : input.chain, {
2046
+ limits: input.limits, profile: input.profile,
2047
+ });
2048
+ if (!verified.ok)
2049
+ return invalid(verified.code);
2050
+ const facts = verified.facts;
2051
+ return valid({
2052
+ receipt_digest: facts.receipt_digest,
2053
+ revision_number: facts.claims.revision_number,
2054
+ revision_digest: facts.claims.revision_digest,
2055
+ decision: facts.claims.decision,
2056
+ outcome: facts.claims.outcome,
2057
+ chain_conflict: facts.chain_conflict,
2058
+ governing_match: facts.governing_match,
2059
+ deployment_digest_matched: facts.deployment_digest_matched,
2060
+ optional_extensions_retained: facts.optional_extensions_retained,
2061
+ ...scopeProjection(facts),
2062
+ });
2063
+ }
2064
+ case "receipt.inspect": {
2065
+ if (!exactKeys(input.chain, [...CHAIN_MEMBERS]))
2066
+ return invalid("invalid_type");
2067
+ const result = inspectReceipt(input.compact, input.chain, input.grant_reference, {
2068
+ limits: input.limits, profile: input.profile,
2069
+ });
2070
+ return result.ok ? valid(result.inspection) : invalid(result.code);
1739
2071
  }
1740
2072
  default:
1741
2073
  return null;
1742
2074
  }
1743
2075
  }
1744
- function execute(one) {
2076
+ /** Execute one decoded corpus row. Use loadCorpus to authenticate the corpus. */
2077
+ export function runConformanceCase(one) {
1745
2078
  try {
1746
2079
  if (!isRecord(one) || !isRecord(one.input))
1747
2080
  return invalid("invalid_type");
@@ -1880,50 +2213,66 @@ function executeInputCase(one) {
1880
2213
  return invalid("cardinality_violation");
1881
2214
  return valid({ members });
1882
2215
  }
2216
+ case "descriptor_publication.verify": {
2217
+ const result = verifyDescriptorPublication(input.text, { limits: input.limits, profile: input.profile });
2218
+ if (!result.ok)
2219
+ return invalid(result.code);
2220
+ const { publication_digest, party_id, current_descriptor_digest, next_descriptor_digest, commitment_status } = result.facts;
2221
+ return valid({ publication_digest, party_id, current_descriptor_digest, next_descriptor_digest, commitment_status });
2222
+ }
1883
2223
  case "descriptor_chain.verify": {
1884
- const chain = descriptorChain(input.compacts);
1885
- return project(chain, (value) => {
1886
- return { topology: value.topology, positions: value.positions, sibling_descriptors: value.siblingDescriptors };
1887
- });
2224
+ const chain = verifyDescriptorChain(input.compacts);
2225
+ if (!chain.ok)
2226
+ return invalid(chain.code);
2227
+ const { topology, positions, siblingDescriptors } = chain.facts;
2228
+ return valid({ topology, positions, sibling_descriptors: siblingDescriptors });
2229
+ }
2230
+ case "charter_revision.decode": {
2231
+ const decoded = decodeCharterRevision(input.text);
2232
+ if (!decoded.ok)
2233
+ return invalid(decoded.code);
2234
+ const { abp_bindings: bindings, revision_number, precedence_declaration } = decoded.revision;
2235
+ const binding = bindings[0];
2236
+ return valid({ revision_digest: decoded.digest, revision_number, precedence_declaration,
2237
+ abp_binding: binding ? { blueprint_id: binding.blueprint_id, release_number: binding.release_number, content_digest: binding.content_digest, deployment_digest: binding.deployment_digest } : null });
1888
2238
  }
1889
- case "charter_revision.decode":
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
- });
1895
2239
  case "acceptance.equivocation": {
1896
- const chain = descriptorChain(input.descriptor_compacts);
2240
+ const chain = verifyDescriptorChain(input.descriptor_compacts);
1897
2241
  if (!chain.ok || !Array.isArray(input.signed_revisions) || input.signed_revisions.length !== 2) {
1898
2242
  return invalid("acceptance_equivocation_invalid");
1899
2243
  }
1900
2244
  const facts = input.signed_revisions.map((signed) => {
1901
- const revision = revisionFromText(signed.revision_text);
1902
- return revision.ok ? acceptanceFromCompact(signed.compact, revision.value, chain.value) : revision;
2245
+ return verifyAcceptance(signed.compact, signed.revision_text, input.descriptor_compacts);
1903
2246
  });
1904
2247
  if (facts.length !== 2 || facts.some((oneFact) => !oneFact.ok))
1905
2248
  return invalid("acceptance_equivocation_invalid");
1906
- const [left, right] = facts.map((oneFact) => oneFact.value.claims);
2249
+ const [left, right] = facts.map((oneFact) => oneFact.facts.claims);
1907
2250
  const pairable = left.charter_id === right.charter_id && left.revision_number === right.revision_number &&
1908
2251
  left.party_descriptor_digest === right.party_descriptor_digest && left.party_role === right.party_role &&
1909
2252
  left.revision_digest !== right.revision_digest;
1910
2253
  if (!pairable)
1911
2254
  return invalid("acceptance_equivocation_invalid");
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 });
2255
+ return valid({ kind: "acceptance_equivocation", revision_number: facts[0].facts.claims.revision_number, revision_digests: facts.map((oneFact) => oneFact.facts.claims.revision_digest).sort(), winner: null });
1913
2256
  }
1914
2257
  case "chain.verify": {
1915
- const chain = chainWithOptions(input, { limits: input.limits });
1916
- return project(chain, (facts) => ({ charter_id: facts.charterId, topology: facts.topology, accepted_revision_digests: facts.acceptedDigests, superseded_revision_digests: facts.supersededDigests }));
2258
+ const chain = verifyChain(input, { limits: input.limits });
2259
+ if (!chain.ok)
2260
+ return invalid(chain.code);
2261
+ const { charterId, topology, acceptedDigests, supersededDigests } = chain.facts;
2262
+ return valid({ charter_id: charterId, topology, accepted_revision_digests: acceptedDigests, superseded_revision_digests: supersededDigests });
1917
2263
  }
1918
2264
  case "chain.verify_profile": {
1919
2265
  const profile = parseProfile(input.profile);
1920
2266
  if (!profile.ok)
1921
2267
  return invalid(profile.code);
1922
- const chain = chainWithOptions(input, { profile: input.profile });
1923
- return project(chain, (facts) => ({ charter_id: facts.charterId, topology: facts.topology }));
2268
+ const chain = verifyChain(input, { profile: input.profile });
2269
+ if (!chain.ok)
2270
+ return invalid(chain.code);
2271
+ return valid({ charter_id: chain.facts.charterId, topology: chain.facts.topology });
1924
2272
  }
1925
2273
  case "governing_revision": {
1926
- const chain = chainWithOptions(input, { limits: input.limits });
2274
+ const options = { limits: input.limits };
2275
+ const chain = verifyChain(input, options);
1927
2276
  if (!chain.ok)
1928
2277
  return invalid(chain.code);
1929
2278
  if (!Array.isArray(input.queries))
@@ -1932,10 +2281,12 @@ function executeInputCase(one) {
1932
2281
  for (const query of input.queries) {
1933
2282
  if (!isRecord(query) || typeof query.at !== "string")
1934
2283
  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));
2284
+ const selected = governingRevision(input, query.at, options);
2285
+ // The view is valid and the query is text; invalid_type here identifies
2286
+ // the timestamp grammar failure in the corpus vocabulary.
2287
+ if (!selected.ok)
2288
+ return invalid(selected.code === "invalid_type" ? "timestamp_invalid" : selected.code);
2289
+ revisions.push(selected.governing);
1939
2290
  }
1940
2291
  return valid({ governing_revisions: revisions });
1941
2292
  }
@@ -2031,7 +2382,7 @@ export function loadCorpus(root) {
2031
2382
  export function reportFor(root) {
2032
2383
  const corpus = loadCorpus(root);
2033
2384
  const results = corpus.cases.map((one) => {
2034
- const actual = execute(one);
2385
+ const actual = runConformanceCase(one);
2035
2386
  if (actual.status === "invalid" && actual.error_code === "algorithm_unsupported_on_substrate")
2036
2387
  throw new Error("algorithm_unsupported_on_substrate: corpus verification unavailable");
2037
2388
  return { id: one.id, surface: one.surface, agree: canonical(actual) === canonical(one.expect), expected: one.expect, actual };
@@ -2069,6 +2420,7 @@ export function selfChecks() {
2069
2420
  if (strictPadded.ok || strictPadded.code !== "base64url_padded")
2070
2421
  throw new Error("base64url strictness failed");
2071
2422
  const acceptedRevision = {
2423
+ bytes: Buffer.alloc(0),
2072
2424
  digest: "known-revision",
2073
2425
  value: {
2074
2426
  abp_bindings: [{ party_role: "agent", deployment_digest: "known-deployment" }],
@@ -2082,7 +2434,14 @@ export function selfChecks() {
2082
2434
  },
2083
2435
  };
2084
2436
  const projectionChain = {
2437
+ revisions: [acceptedRevision],
2438
+ acceptances: [],
2439
+ terminations: [],
2085
2440
  accepted: [acceptedRevision],
2441
+ acceptedDigests: [acceptedRevision.digest],
2442
+ signedDigests: [acceptedRevision.digest],
2443
+ topology: "linear",
2444
+ assignmentStatuses: {},
2086
2445
  descriptors: {
2087
2446
  descriptors: [
2088
2447
  { digest: "issuer-descriptor", payload: { verification_keys: [{ key_id: "issuer", public_key: "issuer-key" }] } },
@@ -2116,9 +2475,8 @@ export function selfChecks() {
2116
2475
  if (projectReceipt({ ...knownClaims, deployment_digest: "wrong" }, projectionChain, "known-revision").ok) {
2117
2476
  throw new Error("recognized receipt claim validation drifted");
2118
2477
  }
2119
- const issuerKeys = receiptSigningKeys(projectionChain, acceptedRevision, "issuer");
2120
- const issuerKey = issuerKeys[0];
2121
- if (issuerKeys.length !== 1 || issuerKey.public_key !== "issuer-key") {
2478
+ const { keys: issuerKeys } = receiptSigningKeys(projectionChain, acceptedRevision, knownClaims, "known-revision");
2479
+ if (issuerKeys.length !== 1 || issuerKeys[0].public_key !== "issuer-key") {
2122
2480
  throw new Error("receipt issuer-key selection drifted");
2123
2481
  }
2124
2482
  if (jsonWithinLimits({ nested: [["xx"]] }, Buffer.from('{"nested":[["xx"]]}'), { max_depth: 2 }).ok) {
@@ -2175,10 +2533,10 @@ export function emissions() {
2175
2533
  return { Ed25519: 2, "ML-DSA-65": 3 };
2176
2534
  }
2177
2535
  export function encodeBase64url(bytes) {
2178
- return bytes.toString("base64url");
2536
+ return copyBytes(bytes).toString("base64url");
2179
2537
  }
2180
2538
  export function taggedDigest(domain, bytes) {
2181
- return taggedHash(domain, bytes);
2539
+ return taggedHash(domain, copyBytes(bytes));
2182
2540
  }
2183
2541
  export function defaultEmissionName() {
2184
2542
  return "Ed25519";
@@ -2207,6 +2565,11 @@ const ARTIFACT_LIST_MEMBERS = new Set([...CHAIN_MEMBERS, "lineage"]);
2207
2565
  const COPY_LIMIT = Symbol();
2208
2566
  const COPY_CYCLE = Symbol();
2209
2567
  const typedArrayByteLength = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "byteLength").get;
2568
+ function copyBytes(bytes) {
2569
+ const plain = Buffer.alloc(typedArrayByteLength.call(bytes));
2570
+ plain.set(bytes);
2571
+ return plain;
2572
+ }
2210
2573
  function boundedMemberNames(value, maximum) {
2211
2574
  const names = [];
2212
2575
  for (const name in value) {
@@ -2221,8 +2584,9 @@ function boundedMemberNames(value, maximum) {
2221
2584
  function copyInput(input, limits, mode, members) {
2222
2585
  const frames = [];
2223
2586
  const active = new Set();
2587
+ const json = mode !== "input";
2224
2588
  let bytes = 0;
2225
- const maxBytes = mode === "json" ? limits.max_bytes : limits.max_artifact_set_bytes + limits.max_bytes;
2589
+ const maxBytes = json ? limits.max_bytes : limits.max_artifact_set_bytes + limits.max_bytes;
2226
2590
  let artifactBytes = 0;
2227
2591
  function count(size) {
2228
2592
  bytes += size;
@@ -2232,13 +2596,13 @@ function copyInput(input, limits, mode, members) {
2232
2596
  function copy(value, depth, artifacts = false, selectedMembers) {
2233
2597
  if (typeof value === "string") {
2234
2598
  const size = Buffer.byteLength(value);
2235
- if (mode === "json" && size > limits.max_string_bytes)
2599
+ if (json && size > limits.max_string_bytes)
2236
2600
  throw COPY_LIMIT;
2237
- count(mode === "json" ? Buffer.byteLength(JSON.stringify(value)) : size);
2601
+ count(json ? Buffer.byteLength(JSON.stringify(value)) : size);
2238
2602
  return value;
2239
2603
  }
2240
2604
  if (value === null || typeof value !== "object") {
2241
- if (mode === "json")
2605
+ if (json)
2242
2606
  count(["number", "boolean"].includes(typeof value) || value === null ? JSON.stringify(value).length : 5);
2243
2607
  return value;
2244
2608
  }
@@ -2249,7 +2613,7 @@ function copyInput(input, limits, mode, members) {
2249
2613
  if (length > limits.max_bytes)
2250
2614
  throw COPY_LIMIT;
2251
2615
  count(length);
2252
- return Buffer.from(value);
2616
+ return copyBytes(value);
2253
2617
  }
2254
2618
  if (value instanceof Number) {
2255
2619
  const number = Number.prototype.valueOf.call(value);
@@ -2260,15 +2624,15 @@ function copyInput(input, limits, mode, members) {
2260
2624
  throw new TypeError();
2261
2625
  if (active.has(value))
2262
2626
  throw COPY_CYCLE;
2263
- if (depth + 1 > (mode === "json" ? limits.max_depth : LIMIT_MAXIMUMS.max_depth))
2627
+ if (depth + 1 > (json ? limits.max_depth : LIMIT_MAXIMUMS.max_depth))
2264
2628
  throw COPY_LIMIT;
2265
2629
  const array = Array.isArray(value);
2266
2630
  const length = array ? value.length : 0;
2267
2631
  if (array && (!Number.isInteger(length) || length < 0 || length > 0xffff_ffff))
2268
2632
  throw new TypeError();
2269
- if (array && length > (mode === "json" ? limits.max_array_items : limits.max_artifact_set_items))
2633
+ if (array && length > (json ? limits.max_array_items : limits.max_artifact_set_items))
2270
2634
  throw COPY_LIMIT;
2271
- if (mode === "json")
2635
+ if (json)
2272
2636
  count(2);
2273
2637
  const keys = array ? null : selectedMembers ? selectedMembers.filter((name) => Object.prototype.propertyIsEnumerable.call(value, name)) : boundedMemberNames(value, limits.max_object_members);
2274
2638
  const target = array ? [] : Object.create(null);
@@ -2282,6 +2646,9 @@ function copyInput(input, limits, mode, members) {
2282
2646
  try {
2283
2647
  if (mode === "input" && (input === null || typeof input !== "object"))
2284
2648
  return ok(input);
2649
+ if (mode === "input" && members === CHAIN_MEMBERS && isRecord(input)) {
2650
+ return copyChainArtifacts(input, limits);
2651
+ }
2285
2652
  const result = copy(input, 0, mode === "input" && Array.isArray(input), members);
2286
2653
  while (frames.length) {
2287
2654
  const frame = frames[frames.length - 1];
@@ -2292,11 +2659,11 @@ function copyInput(input, limits, mode, members) {
2292
2659
  }
2293
2660
  const index = frame.index++;
2294
2661
  const key = frame.keys ? frame.keys[index] : String(index);
2295
- if (mode === "json" && index)
2662
+ if (json && index)
2296
2663
  count(1);
2297
- if (mode === "json" && frame.keys) {
2664
+ if (json && frame.keys) {
2298
2665
  const size = Buffer.byteLength(key);
2299
- if (mode === "json" && size > limits.max_string_bytes)
2666
+ if (json && size > limits.max_string_bytes)
2300
2667
  throw COPY_LIMIT;
2301
2668
  count(Buffer.byteLength(JSON.stringify(key)) + 1);
2302
2669
  }
@@ -2356,10 +2723,45 @@ function retainedInput(value, members) {
2356
2723
  if (Object.prototype.propertyIsEnumerable.call(value, name))
2357
2724
  retained[name] = value[name];
2358
2725
  }
2359
- if (members === CHAIN_MEMBERS && !CHAIN_MEMBERS.every((name) => Array.isArray(retained[name])))
2360
- return fail("invalid_type");
2361
2726
  return ok(retained);
2362
2727
  }
2728
+ function copyChainArtifacts(input, limits) {
2729
+ const lists = CHAIN_MEMBERS.map((name) => input[name]);
2730
+ if (!lists.every(Array.isArray))
2731
+ return fail("invalid_type");
2732
+ const copied = { revisions: [], acceptances: [], descriptors: [], terminations: [] };
2733
+ let remainingBytes = limits.max_artifact_set_bytes;
2734
+ for (const [index, name] of CHAIN_MEMBERS.entries()) {
2735
+ const bounded = boundArtifactList(lists[index], limits, remainingBytes, copied[name]);
2736
+ if (!bounded.ok)
2737
+ return bounded;
2738
+ remainingBytes = bounded.value;
2739
+ }
2740
+ return ok(copied);
2741
+ }
2742
+ function boundArtifactList(list, limits, remainingBytes, copy) {
2743
+ const length = list.length;
2744
+ if (!Number.isInteger(length) || length < 0 || length > 0xffff_ffff)
2745
+ return fail("invalid_type");
2746
+ // Reject an oversized proxy-reported length before reading any elements.
2747
+ // For actual arrays, the first invalid element can precede the item bound.
2748
+ if (length > LIMIT_MAXIMUMS.max_artifact_set_items &&
2749
+ length !== Object.getOwnPropertyDescriptor(list, "length")?.value)
2750
+ return fail("limit_exceeded");
2751
+ for (let item = 0; item < length; item++) {
2752
+ if (item >= limits.max_artifact_set_items)
2753
+ return fail("limit_exceeded");
2754
+ const text = list[item];
2755
+ if (typeof text !== "string")
2756
+ return fail("invalid_type");
2757
+ if (remainingBytes >= 0) {
2758
+ remainingBytes -= text.length > remainingBytes ? text.length : Buffer.byteLength(text);
2759
+ if (remainingBytes >= 0)
2760
+ copy?.push(text);
2761
+ }
2762
+ }
2763
+ return remainingBytes < 0 ? fail("limit_exceeded") : ok(remainingBytes);
2764
+ }
2363
2765
  function plainVerificationInputs(options, inputs, jsonIndex = -1, predecessorIndex = -1, inputMembers = {}) {
2364
2766
  try {
2365
2767
  const selected = readOptionMembers(options, ["limits", "profile", "algorithm"], {
@@ -2371,6 +2773,9 @@ function plainVerificationInputs(options, inputs, jsonIndex = -1, predecessorInd
2371
2773
  const settings = resolveOptions(selected);
2372
2774
  if (!settings.ok)
2373
2775
  return settings;
2776
+ if (selected?.profile?.algorithms !== undefined) {
2777
+ selected.profile.algorithms = settings.value.profile.algorithms;
2778
+ }
2374
2779
  const copiedOptions = copyInput(selected, { ...MAXIMUM_LIMITS, max_artifact_set_bytes: MAXIMUM_LIMITS.max_bytes }, "input", ["limits", "profile", "algorithm"]);
2375
2780
  if (!copiedOptions.ok)
2376
2781
  return copiedOptions;
@@ -2449,18 +2854,194 @@ export function verifyDescriptor(compact, predecessor = null, options = {}) {
2449
2854
  const verified = descriptorFromCompact(compact, previous.value, settings.value);
2450
2855
  if (!verified.ok)
2451
2856
  return { ok: false, code: verified.code };
2452
- const one = verified.value;
2453
- return {
2454
- ok: true,
2455
- facts: factsRecord({
2456
- descriptor_digest: one.digest,
2457
- party_id: one.payload.party_id ?? one.digest,
2458
- descriptor_number: one.payload.descriptor_number,
2459
- lineage: [...one.lineage],
2460
- protocol_revision: one.payload.protocol_revision,
2461
- alg: one.header.alg,
2462
- }),
2463
- };
2857
+ return { ok: true, facts: descriptorFacts(verified.value) };
2858
+ }
2859
+ function descriptorFacts(descriptor, lineage = descriptor.lineage) {
2860
+ return factsRecord({
2861
+ descriptor_digest: descriptor.digest,
2862
+ party_id: descriptor.payload.party_id ?? descriptor.digest,
2863
+ descriptor_number: descriptor.payload.descriptor_number,
2864
+ lineage: [...lineage],
2865
+ protocol_revision: descriptor.payload.protocol_revision,
2866
+ alg: descriptor.header.alg,
2867
+ });
2868
+ }
2869
+ function descriptorJsonInput(input, options) {
2870
+ const plain = plainVerificationInputs(options, []);
2871
+ if (!plain.ok)
2872
+ return plain;
2873
+ const settings = resolveOptions(plain.value[0]);
2874
+ if (!settings.ok)
2875
+ return settings;
2876
+ const copied = copyInput(input, settings.value.limits, "verification_json");
2877
+ if (!copied.ok)
2878
+ return copied;
2879
+ return ok({ value: copied.value, limits: settings.value.limits });
2880
+ }
2881
+ /** Identify a closed verification-key declaration by its algorithm and public bytes. */
2882
+ export function signerThumbprint(key) {
2883
+ const plain = copyInput(key, MAXIMUM_LIMITS, "json");
2884
+ if (!plain.ok)
2885
+ return plain;
2886
+ const shape = schemaError(plain.value, VERIFICATION_KEY_FIELDS);
2887
+ if (shape)
2888
+ return fail(shape);
2889
+ const grammar = keyGrammarError({ protocol_revision: 8, verification_keys: [plain.value] });
2890
+ return grammar ? fail(grammar) : ok(keyThumbprint(plain.value));
2891
+ }
2892
+ const KEY_SET_FIELDS = [nestedField("verification_keys", "array", VERIFICATION_KEY_FIELDS, [1, 32])];
2893
+ /** Commit to the complete active successor key set. */
2894
+ export function descriptorNextKeyCommitment(keys, options = {}) {
2895
+ const plain = descriptorJsonInput(keys, options);
2896
+ if (!plain.ok)
2897
+ return plain;
2898
+ const { value: declarations, limits } = plain.value;
2899
+ if (!Array.isArray(declarations))
2900
+ return fail("invalid_type");
2901
+ if (declarations.length > 32)
2902
+ return fail("descriptor_invalid");
2903
+ const value = { verification_keys: declarations };
2904
+ const shape = schemaError(value, KEY_SET_FIELDS);
2905
+ if (shape)
2906
+ return fail(shape);
2907
+ const decoded = decodeJsonText(canonical(value), limits);
2908
+ if (!decoded.ok)
2909
+ return decoded;
2910
+ const grammar = keyGrammarError({ ...value, protocol_revision: 8 });
2911
+ if (grammar)
2912
+ return fail(grammar);
2913
+ const ids = new Set(declarations.map((key) => key.key_id));
2914
+ const active = activeThumbprints(declarations);
2915
+ if (ids.size !== declarations.length || active.length === 0 || new Set(active).size !== active.length) {
2916
+ return fail("descriptor_invalid");
2917
+ }
2918
+ return ok(commitmentDigest(declarations));
2919
+ }
2920
+ const PUBLICATION_MEMBERS = [
2921
+ "protocol_revision", "party_id", "current_descriptor_digest", "next_descriptor_digest", "descriptors",
2922
+ ];
2923
+ function validPublicationShape(value) {
2924
+ if (!isRecord(value) || !exactKeys(value, PUBLICATION_MEMBERS))
2925
+ return false;
2926
+ const fields = value;
2927
+ const { protocol_revision, party_id, current_descriptor_digest, next_descriptor_digest, descriptors } = fields;
2928
+ return protocol_revision === 8 && validTaggedDigest(party_id) &&
2929
+ validTaggedDigest(current_descriptor_digest) && validTaggedDigest(next_descriptor_digest) &&
2930
+ Array.isArray(descriptors) && descriptors.length >= 2 && descriptors.length <= 4096 &&
2931
+ descriptors.every((compact) => typeof compact === "string" && compact.length > 0);
2932
+ }
2933
+ function decodeDescriptorPublication(text, limits) {
2934
+ const parsed = decodeJsonText(text, limits);
2935
+ if (!parsed.ok)
2936
+ return fail(parsed.code === "limit_exceeded" ? parsed.code : "descriptor_publication_invalid");
2937
+ const value = parsed.value;
2938
+ if (!validPublicationShape(value) || canonicalTextError(value, text))
2939
+ return fail("descriptor_publication_invalid");
2940
+ const bounded = boundArtifactList(value.descriptors, limits, limits.max_artifact_set_bytes);
2941
+ return bounded.ok ? ok(value) : bounded;
2942
+ }
2943
+ /** Encode the closed, unsigned publication under caller limits. */
2944
+ export function encodeDescriptorPublication(claims, options = {}) {
2945
+ const plain = descriptorJsonInput(claims, options);
2946
+ if (!plain.ok)
2947
+ return plain;
2948
+ const { value, limits } = plain.value;
2949
+ if (!isRecord(value))
2950
+ return fail("invalid_type");
2951
+ const revision = value.protocol_revision;
2952
+ if (revision instanceof Number || (typeof revision === "number" && Number.isFinite(revision) && !Number.isInteger(revision))) {
2953
+ return fail("invalid_type");
2954
+ }
2955
+ if (!validPublicationShape(value))
2956
+ return fail("descriptor_publication_invalid");
2957
+ const text = canonical(value);
2958
+ const document = decodeDescriptorPublication(text, limits);
2959
+ return document.ok ? ok(text) : document;
2960
+ }
2961
+ /** Hash the exact publication bytes. */
2962
+ export function descriptorPublicationDigest(text) {
2963
+ return taggedHash("descriptor_publication_content", Buffer.from(text));
2964
+ }
2965
+ /** Verify every signature and select the final direct current and next pair. */
2966
+ export function verifyDescriptorPublication(text, options = {}) {
2967
+ const plain = plainVerificationInputs(options, [text]);
2968
+ if (!plain.ok)
2969
+ return plain;
2970
+ const [value, checkedOptions] = plain.value;
2971
+ const settings = resolveOptions(checkedOptions);
2972
+ if (!settings.ok)
2973
+ return settings;
2974
+ if (typeof value !== "string")
2975
+ return fail("invalid_type");
2976
+ const decoded = decodeDescriptorPublication(value, settings.value.limits);
2977
+ if (!decoded.ok)
2978
+ return decoded;
2979
+ const document = decoded.value;
2980
+ const admission = profileError(null, 8, settings.value);
2981
+ if (admission)
2982
+ return fail(admission);
2983
+ const entries = [];
2984
+ for (const compact of document.descriptors) {
2985
+ const member = decodeJws(compact, settings.value.limits, "cap+party");
2986
+ if (!member.ok || descriptorClaimsError(member.value.payload))
2987
+ return fail("descriptor_chain_invalid");
2988
+ entries.push({ ...member.value, compact, digest: taggedHash("party_descriptor_content", member.value.payloadBytes) });
2989
+ }
2990
+ const invalid = () => fail("descriptor_publication_invalid");
2991
+ const root = entries[0];
2992
+ const byDigest = new Map(entries.map((entry) => [entry.digest, entry]));
2993
+ if (root.payload.descriptor_number !== 1 || byDigest.size !== entries.length)
2994
+ return invalid();
2995
+ for (let i = 1; i < entries.length; i++) {
2996
+ const entry = entries[i];
2997
+ const previousInOrder = entries[i - 1];
2998
+ const number = entry.payload.descriptor_number;
2999
+ const parent = byDigest.get(entry.payload.prev_descriptor_digest);
3000
+ if (!parent || number !== parent.payload.descriptor_number + 1 || entry.payload.party_id !== root.digest ||
3001
+ number < previousInOrder.payload.descriptor_number ||
3002
+ (number === previousInOrder.payload.descriptor_number && entry.digest < previousInOrder.digest))
3003
+ return invalid();
3004
+ }
3005
+ const verified = new Map();
3006
+ const parents = new Set();
3007
+ for (const entry of entries) {
3008
+ const parent = entry.payload.prev_descriptor_digest;
3009
+ const previous = verified.get(parent);
3010
+ const predecessor = previous ? { digest: previous.digest, payload: previous.payload } : null;
3011
+ const prepared = prepareDecodedDescriptor(entry.compact, entry, predecessor, settings.value, entry.digest);
3012
+ const result = finishPreparedArtifact(prepared, settings.value);
3013
+ if (!result.ok)
3014
+ return result;
3015
+ verified.set(entry.digest, result.value);
3016
+ if (parent !== undefined)
3017
+ parents.add(parent);
3018
+ }
3019
+ const next = entries[entries.length - 1];
3020
+ const current = byDigest.get(document.current_descriptor_digest);
3021
+ if (!current)
3022
+ return invalid();
3023
+ const currentTime = parseTimestamp(current.payload.effective_from);
3024
+ const nextTime = parseTimestamp(next.payload.effective_from);
3025
+ if (parents.size !== entries.length - 1 || document.party_id !== root.digest ||
3026
+ document.current_descriptor_digest !== current.digest || document.next_descriptor_digest !== next.digest ||
3027
+ next.payload.prev_descriptor_digest !== current.digest || compareTimestamps(currentTime, nextTime) >= 0)
3028
+ return invalid();
3029
+ const lineage = entries.map((entry) => entry.compact).reverse();
3030
+ const currentDescriptor = descriptorFacts(verified.get(current.digest), lineage.slice(1));
3031
+ const nextDescriptor = descriptorFacts(verified.get(next.digest), lineage);
3032
+ return { ok: true, facts: factsRecord({
3033
+ protocol_revision: 8,
3034
+ canonical_bytes: value,
3035
+ publication_digest: descriptorPublicationDigest(value),
3036
+ party_id: root.digest,
3037
+ current_descriptor: currentDescriptor,
3038
+ next_descriptor: nextDescriptor,
3039
+ current_descriptor_digest: current.digest,
3040
+ next_descriptor_digest: next.digest,
3041
+ current_effective_from: current.payload.effective_from,
3042
+ next_effective_from: next.payload.effective_from,
3043
+ commitment_status: current.payload.next_key_commitment === undefined ? "not_present" : "opened",
3044
+ }) };
2464
3045
  }
2465
3046
  export function verifyDescriptorChain(compacts, options = {}) {
2466
3047
  const plain = plainVerificationInputs(options, [compacts]);
@@ -2492,7 +3073,17 @@ export function verifyAcceptance(compact, revisionText, descriptorCompacts, opti
2492
3073
  const verified = acceptanceFromCompact(compact, revision.value, chain.value, settings.value);
2493
3074
  if (!verified.ok)
2494
3075
  return { ok: false, code: verified.code };
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 }) };
3076
+ return { ok: true, facts: factsRecord({
3077
+ acceptance_digest: verified.value.digest,
3078
+ claims: verified.value.claims,
3079
+ descriptor_position: verified.value.descriptorPosition,
3080
+ protocol_revision: verified.value.protocol_revision,
3081
+ alg: verified.value.alg,
3082
+ scope_status: verified.value.scope_status,
3083
+ signer_thumbprint: verified.value.signer_thumbprint,
3084
+ credit: "not_evaluated",
3085
+ credit_reason: null,
3086
+ }) };
2496
3087
  }
2497
3088
  export function verifyTermination(compact, revisionText, descriptorCompacts, options = {}) {
2498
3089
  const plain = plainVerificationInputs(options, [compact, revisionText, descriptorCompacts]);
@@ -2511,7 +3102,7 @@ export function verifyTermination(compact, revisionText, descriptorCompacts, opt
2511
3102
  const verified = terminationFromCompact(compact, revision.value, chain.value, settings.value);
2512
3103
  if (!verified.ok)
2513
3104
  return { ok: false, code: verified.code };
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 }) };
3105
+ 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, scope_status: verified.value.scope_status, signer_thumbprint: verified.value.signer_thumbprint }) };
2515
3106
  }
2516
3107
  export function verifyChain(chainInput, options = {}) {
2517
3108
  const plain = plainVerificationInputs(options, [chainInput], -1, -1, { 0: CHAIN_MEMBERS });
@@ -2542,10 +3133,109 @@ export function verifyReceipt(compact, context, options = {}) {
2542
3133
  receipt_digest: verified.value.digest,
2543
3134
  claims: verified.value.claims,
2544
3135
  governing_match: verified.value.governingMatch,
3136
+ holder_match: verified.value.holderMatch,
2545
3137
  chain_conflict: verified.value.chainConflict,
2546
- }, typeof context === "string" ? ["signature"] : []),
3138
+ deployment_digest_matched: verified.value.deploymentMatched,
3139
+ optional_extensions_retained: verified.value.optionalExtensions,
3140
+ scope_status: verified.value.scope_status,
3141
+ signer_thumbprint: verified.value.signer_thumbprint,
3142
+ }, verified.value.not_verified),
3143
+ };
3144
+ }
3145
+ function receiptAgreement(chain, claims) {
3146
+ const digest = governing(chain, parseTimestamp(claims.occurred_at));
3147
+ if (digest === "contested" || digest === "none") {
3148
+ return {
3149
+ status: "not_verified",
3150
+ reason: digest === "contested" ? "contested_governing_revision" : "no_governing_revision",
3151
+ fields: [],
3152
+ governing_revision_digest: null,
3153
+ governing_revision_number: null,
3154
+ };
3155
+ }
3156
+ const revision = chain.accepted.find((one) => one.digest === digest).value;
3157
+ const roles = new Set(revision.parties.map((party) => party.role));
3158
+ const fields = [];
3159
+ if (!roles.has(claims.agent_party_role))
3160
+ fields.push("agent_party_role");
3161
+ if (!revision.abp_bindings.some((binding) => binding.party_role === claims.agent_party_role && binding.deployment_digest === claims.deployment_digest)) {
3162
+ fields.push("deployment_digest");
3163
+ }
3164
+ if (!roles.has(claims.issuing_party_role))
3165
+ fields.push("issuing_party_role");
3166
+ if (digest !== claims.revision_digest)
3167
+ fields.push("revision_digest");
3168
+ if (revision.revision_number !== claims.revision_number)
3169
+ fields.push("revision_number");
3170
+ return {
3171
+ status: fields.length === 0 ? "matches" : "differs",
3172
+ reason: null,
3173
+ fields,
3174
+ governing_revision_digest: digest,
3175
+ governing_revision_number: revision.revision_number,
2547
3176
  };
2548
3177
  }
3178
+ function receiptGrantComparison(claimed, reference) {
3179
+ const coordinates = { claimed_digest: claimed, reference_digest: reference };
3180
+ if (claimed === null)
3181
+ return { ...coordinates, status: "not_verified", reason: "receipt_grant_digest_missing" };
3182
+ if (reference === null)
3183
+ return { ...coordinates, status: "not_verified", reason: "grant_reference_missing" };
3184
+ return { ...coordinates, status: equalDigest(claimed, reference) ? "matches" : "differs", reason: null };
3185
+ }
3186
+ /** Inspect a signed receipt and its retained charter artifacts. CAP never authorizes. */
3187
+ export function inspectReceipt(compact, chainInput, grantReference = null, options = {}) {
3188
+ const plain = plainVerificationInputs(options, [compact, chainInput], -1, -1, { 1: CHAIN_MEMBERS });
3189
+ if (!plain.ok)
3190
+ return plain;
3191
+ [compact, chainInput, options] = plain.value;
3192
+ const settings = resolveOptions(options);
3193
+ if (!settings.ok)
3194
+ return settings;
3195
+ if (grantReference !== null && typeof grantReference !== "string")
3196
+ return fail("invalid_type");
3197
+ if (grantReference !== null && !validTaggedDigest(grantReference))
3198
+ return fail("digest_encoding_invalid");
3199
+ const chain = chainFromInput(chainInput, settings.value);
3200
+ if (!chain.ok)
3201
+ return chain;
3202
+ if (typeof compact !== "string")
3203
+ return fail("invalid_type");
3204
+ const prepared = prepareReceipt(compact, { kind: "chain", chain: chain.value }, settings.value);
3205
+ if (!prepared.ok)
3206
+ return prepared;
3207
+ const key = verifiedReceiptKey(prepared.value, settings.value);
3208
+ if (!key.ok)
3209
+ return key;
3210
+ const { decoded, facts } = prepared.value;
3211
+ const claims = decoded.payload;
3212
+ const [protected_segment, payload_segment, signature_segment] = compact.split(".");
3213
+ return { ok: true, inspection: {
3214
+ signed: {
3215
+ protected_segment,
3216
+ payload_segment,
3217
+ signature_segment,
3218
+ protected_segment_digest: `sha-256:${rawHash(Buffer.from(protected_segment))}`,
3219
+ payload_segment_digest: `sha-256:${rawHash(Buffer.from(payload_segment))}`,
3220
+ receipt_digest: facts.digest,
3221
+ },
3222
+ claims,
3223
+ provenance: {
3224
+ charter_id: claims.charter_id,
3225
+ revision_digest: claims.revision_digest,
3226
+ revision_number: claims.revision_number,
3227
+ issuing_party_role: claims.issuing_party_role,
3228
+ signing_key_id: decoded.header.kid,
3229
+ signer_thumbprint: keyThumbprint(key.value),
3230
+ alg: decoded.header.alg,
3231
+ revision_status: facts.deploymentMatched ? "verified" : "not_verified",
3232
+ scope_status: facts.scope_status,
3233
+ },
3234
+ grant: receiptGrantComparison(claims.grant.grant_digest ?? null, grantReference),
3235
+ agreement: receiptAgreement(chain.value, claims),
3236
+ not_verified: facts.not_verified,
3237
+ } };
3238
+ }
2549
3239
  // ---------------------------------------------------------------------------
2550
3240
  // The producer build gate's claims half (the reference decode_for_signing):
2551
3241
  // the schema checks that depend only on the claims, shared with the verify
@@ -2576,7 +3266,7 @@ function signingDescriptorError(claims) {
2576
3266
  return grammar ?? descriptorClaimsError(claims);
2577
3267
  }
2578
3268
  function acceptanceClaimsError(claims) {
2579
- const shape = schemaError(claims, ACCEPTANCE_SCHEMA);
3269
+ const shape = schemaError(claims, claims.protocol_revision === 8 ? QUORUM_ACCEPTANCE_SCHEMA : ACCEPTANCE_SCHEMA);
2580
3270
  if (shape)
2581
3271
  return shape;
2582
3272
  if ([claims.charter_id, claims.revision_digest, claims.prev_revision_digest, claims.party_descriptor_digest].filter((value) => value !== undefined).some((value) => !validTaggedDigest(value)))
@@ -2588,7 +3278,7 @@ function acceptanceClaimsError(claims) {
2588
3278
  return null;
2589
3279
  }
2590
3280
  function terminationClaimsError(claims) {
2591
- const shape = schemaError(claims, TERMINATION_SCHEMA);
3281
+ const shape = schemaError(claims, claims.protocol_revision === 8 ? QUORUM_TERMINATION_SCHEMA : TERMINATION_SCHEMA);
2592
3282
  if (shape)
2593
3283
  return shape;
2594
3284
  if ([claims.charter_id, claims.governing_revision_digest, claims.party_descriptor_digest, claims.detail_digest].filter((value) => value !== undefined).some((value) => !validTaggedDigest(value)))
@@ -2633,16 +3323,24 @@ function receiptTimingMatrixError(claims) {
2633
3323
  return null;
2634
3324
  }
2635
3325
  function descriptorClaimsError(payload) {
2636
- const shape = schemaError(payload, DESCRIPTOR_SCHEMA);
3326
+ const shape = schemaError(payload, payload.protocol_revision === 8 ? COMMITTED_DESCRIPTOR_SCHEMA : DESCRIPTOR_SCHEMA);
2637
3327
  if (shape)
2638
3328
  return shape;
2639
- if ([payload.party_id, payload.prev_descriptor_digest].filter((value) => value !== undefined).some((value) => !validTaggedDigest(value)))
3329
+ if ([payload.party_id, payload.prev_descriptor_digest, payload.next_key_commitment].filter((value) => value !== undefined).some((value) => !validTaggedDigest(value)))
2640
3330
  return "descriptor_invalid";
2641
3331
  const grammar = keyGrammarError(payload);
2642
3332
  if (grammar)
2643
3333
  return grammar;
2644
3334
  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
3335
  return "descriptor_invalid";
3336
+ if (payload.protocol_revision === 8) {
3337
+ const thumbprints = activeThumbprints(payload.verification_keys);
3338
+ if (new Set(thumbprints).size !== thumbprints.length)
3339
+ return "descriptor_invalid";
3340
+ const scopes = payload.signing_scopes;
3341
+ if (scopes !== undefined && !validSigningScopes(scopes, new Set(thumbprints)))
3342
+ return "descriptor_invalid";
3343
+ }
2646
3344
  const extensions = extensionError(payload.extensions, "party_descriptor");
2647
3345
  if (extensions)
2648
3346
  return extensions;
@@ -2652,6 +3350,11 @@ function descriptorClaimsError(payload) {
2652
3350
  return "descriptor_invalid";
2653
3351
  return null;
2654
3352
  }
3353
+ function validSigningScopes(scopes, active) {
3354
+ return sortedUniqueStrings(scopes.map((scope) => scope.role)) && scopes.every(({ signers }) => sortedUniqueStrings(signers.map((signer) => signer.key_thumbprint)) &&
3355
+ signers.every(({ key_thumbprint, artifact_kinds }) => active.has(key_thumbprint) && artifact_kinds.every((kind) => SCOPE_KINDS.includes(kind)) &&
3356
+ sortedUniqueStrings(artifact_kinds)));
3357
+ }
2655
3358
  // ---------------------------------------------------------------------------
2656
3359
  // The query/decode surface: the reference's governing-revision computation
2657
3360
  // and the revision/descriptor decode+digest pairs, over the same certified
@@ -2763,6 +3466,23 @@ export class SigningPlan {
2763
3466
  }
2764
3467
  /** Check everything that can be checked before producing a signature. */
2765
3468
  export function prepareSigning(kind, kid, claims, publicKey, context, options = {}) {
3469
+ const parameters = signingParameters(kind, context, options);
3470
+ if (!parameters.ok)
3471
+ return parameters;
3472
+ return prepareWithContext(kind, kid, claims, publicKey, parameters.value.options, () => copySigningContext(kind, context, parameters.value.limits));
3473
+ }
3474
+ /** Snapshot a caller's context before awaiting custody, preserving preparation error order. */
3475
+ export function retainSigningContext(kind, context, options = {}) {
3476
+ const parameters = signingParameters(kind, context, options);
3477
+ if (!parameters.ok)
3478
+ return parameters;
3479
+ const retained = copySigningContext(kind, context, parameters.value.limits);
3480
+ return ok(retainedPreparation(kind, parameters.value.options, retained));
3481
+ }
3482
+ function retainedPreparation(kind, options, retained) {
3483
+ return (kid, claims, publicKey) => prepareWithContext(kind, kid, claims, publicKey, options, () => retained);
3484
+ }
3485
+ function signingParameters(kind, context, options) {
2766
3486
  const optionInputs = plainVerificationInputs(options, []);
2767
3487
  if (!optionInputs.ok)
2768
3488
  return optionInputs;
@@ -2773,7 +3493,7 @@ export function prepareSigning(kind, kid, claims, publicKey, context, options =
2773
3493
  (member("descriptor_digest") || member("digest")));
2774
3494
  const setContext = isRecord(context) && ["revisions", "acceptances", "descriptors", "terminations"].every(member);
2775
3495
  const validContext = kind === "descriptor" ? descriptorContext :
2776
- kind === "acceptance" || kind === "termination" ? setContext :
3496
+ kind === "acceptance" || kind === "party_replacement" || kind === "termination" ? setContext :
2777
3497
  kind === "receipt" ? typeof context === "string" || setContext : false;
2778
3498
  if (!validContext)
2779
3499
  return fail("invalid_type");
@@ -2781,6 +3501,39 @@ export function prepareSigning(kind, kid, claims, publicKey, context, options =
2781
3501
  catch (_error) {
2782
3502
  return fail("invalid_type");
2783
3503
  }
3504
+ const settings = resolveOptions(options);
3505
+ return settings.ok ? ok({ options, limits: settings.value.limits }) : settings;
3506
+ }
3507
+ function copySigningContext(kind, context, limits) {
3508
+ if (typeof context === "string") {
3509
+ return context.length > limits.max_bytes || Buffer.byteLength(context) > limits.max_bytes ?
3510
+ fail("limit_exceeded") : ok(context);
3511
+ }
3512
+ const members = kind === "descriptor" ? PREDECESSOR_MEMBERS : CHAIN_MEMBERS;
3513
+ try {
3514
+ const retained = retainedInput(context, members);
3515
+ if (!retained.ok)
3516
+ return retained;
3517
+ const copied = copyInput(retained.value, kind === "descriptor" ? predecessorCopyLimits(limits) : limits, "input", members);
3518
+ if (kind !== "descriptor" || !copied.ok || copied.value === null)
3519
+ return copied;
3520
+ const previous = copied.value;
3521
+ if (!Array.isArray(previous.lineage))
3522
+ return fail("invalid_type");
3523
+ // Keep the position of a bad entry for the verifier's lineage walk.
3524
+ previous.lineage = previous.lineage.map((entry) => typeof entry === "string" ? entry : null);
3525
+ for (const field of ["digest", "descriptor_digest"]) {
3526
+ const digest = previous[field];
3527
+ if (digest !== null && digest !== undefined && typeof digest !== "string")
3528
+ previous[field] = "";
3529
+ }
3530
+ return copied;
3531
+ }
3532
+ catch (_error) {
3533
+ return fail("invalid_type");
3534
+ }
3535
+ }
3536
+ function prepareWithContext(kind, kid, claims, publicKey, options, readContext) {
2784
3537
  const plain = plainVerificationInputs(options, [kind, kid, claims, publicKey], 2);
2785
3538
  if (!plain.ok)
2786
3539
  return plain;
@@ -2788,26 +3541,18 @@ export function prepareSigning(kind, kid, claims, publicKey, context, options =
2788
3541
  const settings = resolveOptions(options);
2789
3542
  if (!settings.ok)
2790
3543
  return settings;
3544
+ const artifactKind = kind === "party_replacement" ? "acceptance" : kind;
2791
3545
  const built = buildSigningInput(kind, kid, claims, options.algorithm, settings.value.limits);
2792
3546
  if (!built.ok)
2793
3547
  return built;
2794
3548
  const row = ALG_ROWS.find((one) => one.name === built.input.alg);
2795
3549
  if (!validPublicKey(publicKey, row))
2796
3550
  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);
3551
+ const copiedContext = readContext();
2807
3552
  if (!copiedContext.ok)
2808
3553
  return copiedContext;
2809
- context = copiedContext.value;
2810
- const provisional = `${built.input.message.toString("utf8")}.${encodeBase64url(Buffer.alloc(row.signatureBytes))}`;
3554
+ const context = copiedContext.value;
3555
+ const provisional = `${built.input.message.toString("utf8")}.${Buffer.alloc(row.signatureBytes).toString("base64url")}`;
2811
3556
  let prepared;
2812
3557
  let verifyWith;
2813
3558
  if (kind === "descriptor") {
@@ -2817,15 +3562,15 @@ export function prepareSigning(kind, kid, claims, publicKey, context, options =
2817
3562
  prepared = prepareDescriptor(provisional, previous.value, settings.value);
2818
3563
  verifyWith = { kind, predecessor: previous.value ? { descriptor_digest: previous.value.digest, lineage: [...previous.value.lineage] } : null };
2819
3564
  }
2820
- else if (kind === "acceptance" || kind === "termination") {
3565
+ else if (artifactKind === "acceptance" || artifactKind === "termination") {
2821
3566
  // Limits cover the whole set; the caller's profile covers the routed view.
2822
3567
  const chain = chainFromInput(context, { ...settings.value, profile: DEFAULT_SETTINGS.profile });
2823
3568
  if (!chain.ok)
2824
3569
  return chain;
2825
- const refusal = kind === "acceptance" ? acceptanceRefusalInChain(claims, chain.value) : terminationRefusalInChain(claims, chain.value);
3570
+ const refusal = signingRefusalInChain(artifactKind, kid, claims, chain.value);
2826
3571
  if (!refusal.ok)
2827
3572
  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`);
3573
+ const routed = signingContextFromSet(new Map(chain.value.revisions.map((one) => [one.digest, one])), chain.value.descriptors, artifactKind === "acceptance" ? claims.revision_digest : claims.governing_revision_digest, claims.party_descriptor_digest, `${artifactKind}_claims_mismatch`);
2829
3574
  if (!routed.ok)
2830
3575
  return routed;
2831
3576
  const revisionText = routed.value.revision.bytes.toString("utf8");
@@ -2836,29 +3581,36 @@ export function prepareSigning(kind, kid, claims, publicKey, context, options =
2836
3581
  const partyChain = descriptorChain(descriptorCompacts, settings.value);
2837
3582
  if (!partyChain.ok)
2838
3583
  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] };
3584
+ prepared = artifactKind === "acceptance" ? prepareAcceptance(provisional, revision.value, partyChain.value, settings.value) : prepareTermination(provisional, revision.value, partyChain.value, settings.value);
3585
+ verifyWith = { kind: artifactKind, revisionText, descriptorCompacts: [...descriptorCompacts] };
2841
3586
  }
2842
3587
  else if (typeof context === "string") {
2843
3588
  const revision = revisionWithProfile(context, settings.value);
2844
3589
  if (!revision.ok)
2845
3590
  return revision;
2846
3591
  prepared = prepareReceipt(provisional, { kind: "revision", revision: revision.value }, settings.value);
2847
- verifyWith = { kind, context };
3592
+ if (prepared.ok && revision.value.value.protocol_revision === 8)
3593
+ return fail("signing_refused");
3594
+ verifyWith = { kind: "receipt", context };
2848
3595
  }
2849
3596
  else {
2850
3597
  const chain = chainFromInput(context, settings.value);
2851
3598
  if (!chain.ok)
2852
3599
  return chain;
2853
3600
  prepared = prepareReceipt(provisional, { kind: "chain", chain: chain.value }, settings.value);
2854
- verifyWith = { kind, context: context };
3601
+ verifyWith = { kind: "receipt", context: context };
2855
3602
  }
2856
3603
  if (!prepared.ok)
2857
3604
  return prepared;
2858
- if (!prepared.value.unnamed && !prepared.value.keys.some((key) => keyMatchesRow(key, row) && key.public_key === publicKey))
3605
+ const eligibleKeys = prepared.value.holderKeys ?? prepared.value.keys;
3606
+ if (prepared.value.keys.length > 0 && eligibleKeys.length === 0)
3607
+ return fail("receipt_claims_mismatch");
3608
+ if (!prepared.value.unnamed && !eligibleKeys.some((key) => keyMatchesRow(key, row) && key.public_key === publicKey))
2859
3609
  return fail("signing_key_mismatch");
2860
3610
  if (!runtimeSupportsAlgorithm(row.keyAlgorithm))
2861
3611
  return fail("algorithm_unsupported_on_substrate");
3612
+ if (prepared.value.scopeStatus === "outside")
3613
+ return fail(kind === "descriptor" ? "descriptor_chain_invalid" : "signing_refused");
2862
3614
  return { ok: true, plan: createSigningPlan(kind, built.input, prepared.value.unnamed ? "unnamed" : "matched", publicKey, verifyWith, settings.value) };
2863
3615
  }
2864
3616
  /** Assemble under the retained limits and run public verification. */
@@ -2902,15 +3654,20 @@ function jsonValueError(value) {
2902
3654
  // binding -> kid -> framing -> size gate -> claims schema -> provisional
2903
3655
  // decode (the reference producer's exact ordering, so error precedence
2904
3656
  // matches too).
2905
- function buildSigningInput(kind, kid, claims, algorithm, limits = DEFAULT_LIMITS) {
3657
+ function buildSigningInput(operation, kid, claims, algorithm, limits = DEFAULT_LIMITS) {
3658
+ const kind = operation === "party_replacement" ? "acceptance" : operation;
2906
3659
  if (typeof algorithm === "undefined")
2907
3660
  algorithm = defaultEmissionName();
2908
- if (typeof algorithm !== "string" || !(algorithm in emissions())) {
2909
- return { ok: false, code: "signing_input_invalid" };
3661
+ if (typeof algorithm !== "string" || typeof kid !== "string" ||
3662
+ !claims || typeof claims !== "object" || Array.isArray(claims)) {
3663
+ return fail("signing_input_invalid");
2910
3664
  }
2911
- if (!claims || typeof claims !== "object" || Array.isArray(claims)) {
2912
- return { ok: false, code: "signing_input_invalid" };
3665
+ if (kind === "acceptance" &&
3666
+ (operation === "party_replacement") !== Object.hasOwn(claims, "replacement_role")) {
3667
+ return fail("signing_refused");
2913
3668
  }
3669
+ if (!(algorithm in emissions()))
3670
+ return fail("signing_input_invalid");
2914
3671
  const record = claims;
2915
3672
  try {
2916
3673
  if (jsonValueError(record))
@@ -2922,10 +3679,10 @@ function buildSigningInput(kind, kid, claims, algorithm, limits = DEFAULT_LIMITS
2922
3679
  if (integerTokenError(record, schemaForType(PRODUCER_TYPES[kind])))
2923
3680
  return fail("signing_input_invalid");
2924
3681
  const revision = record.protocol_revision;
2925
- if (typeof revision !== "number" || !Number.isInteger(revision) || revision !== emissions()[algorithm]) {
3682
+ if (typeof revision !== "number" || !Number.isInteger(revision) || (revision !== emissions()[algorithm] && !(revision === 8 && kind !== "receipt"))) {
2926
3683
  return { ok: false, code: "signing_input_invalid" };
2927
3684
  }
2928
- if (typeof kid !== "string" || kid.length === 0 || kid.length > 128 || !/^[A-Za-z0-9._~-]+$/.test(kid)) {
3685
+ if (kid.length === 0 || kid.length > 128 || !/^[A-Za-z0-9._~-]+$/.test(kid)) {
2929
3686
  return { ok: false, code: "signing_input_invalid" };
2930
3687
  }
2931
3688
  const row = ALG_ROWS.find((one) => one.name === algorithm);
@@ -2933,12 +3690,12 @@ function buildSigningInput(kind, kid, claims, algorithm, limits = DEFAULT_LIMITS
2933
3690
  return { ok: false, code: "signing_input_invalid" };
2934
3691
  let payloadSegment;
2935
3692
  try {
2936
- payloadSegment = encodeBase64url(Buffer.from(canonical(record), "utf8"));
3693
+ payloadSegment = Buffer.from(canonical(record), "utf8").toString("base64url");
2937
3694
  }
2938
3695
  catch (_error) {
2939
3696
  return { ok: false, code: "signing_input_invalid" };
2940
3697
  }
2941
- const protectedSegment = encodeBase64url(Buffer.from(canonical({ alg: algorithm, kid, typ: PRODUCER_TYPES[kind] }), "utf8"));
3698
+ const protectedSegment = Buffer.from(canonical({ alg: algorithm, kid, typ: PRODUCER_TYPES[kind] }), "utf8").toString("base64url");
2942
3699
  const message = Buffer.from(`${protectedSegment}.${payloadSegment}`, "utf8");
2943
3700
  const signatureSegmentLength = Math.ceil((row.signatureBytes * 4) / 3);
2944
3701
  if (message.length + 1 + signatureSegmentLength > limits.max_bytes) {
@@ -2953,7 +3710,7 @@ function buildSigningInput(kind, kid, claims, algorithm, limits = DEFAULT_LIMITS
2953
3710
  // The provisional check: a zero signature at the row's exact length must
2954
3711
  // frame and bind.
2955
3712
  const zeroSignature = Buffer.alloc(row.signatureBytes);
2956
- const provisional = `${protectedSegment}.${payloadSegment}.${encodeBase64url(zeroSignature)}`;
3713
+ const provisional = `${protectedSegment}.${payloadSegment}.${zeroSignature.toString("base64url")}`;
2957
3714
  const decoded = decodeSigningArtifact(provisional, limits);
2958
3715
  if (!decoded.ok)
2959
3716
  return { ok: false, code: "signing_input_invalid" };
@@ -2973,34 +3730,42 @@ export function receiptSigningInput(kid, claims, algorithm) {
2973
3730
  [kid, claims, algorithm] = plain.value;
2974
3731
  return buildSigningInput("receipt", kid, claims, algorithm);
2975
3732
  }
2976
- // The reference producer ordering: build (shape, emission binding, framing,
2977
- // claims schema) FIRST, then the set-aware R1-R3 refusal checks - so a
2978
- // claims defect reports the producer code even when the view is also bad.
3733
+ // Set-aware producers check the outer context, then build the signing input
3734
+ // before validating the contents of the set and applying the refusal rules.
2979
3735
  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;
2984
- const built = buildSigningInput("acceptance", kid, claims, algorithm);
2985
- if (!built.ok)
2986
- return built;
2987
- const refusal = acceptanceRefusal(claims, chainInput);
2988
- if (!refusal.ok)
2989
- return { ok: false, code: refusal.code };
2990
- return built;
3736
+ return setSigningInput("acceptance", kid, claims, chainInput, algorithm);
3737
+ }
3738
+ /** Build an assignor's acceptance after checking the declared replacement. */
3739
+ export function partyReplacementSigningInput(kid, claims, chainInput, algorithm) {
3740
+ return setSigningInput("party_replacement", kid, claims, chainInput, algorithm);
2991
3741
  }
2992
3742
  export function terminationSigningInput(kid, claims, chainInput, algorithm) {
2993
- const plain = plainVerificationInputs({}, [kid, claims, chainInput, algorithm], 1, -1, { 2: CHAIN_MEMBERS });
3743
+ return setSigningInput("termination", kid, claims, chainInput, algorithm);
3744
+ }
3745
+ function setSigningInput(operation, kid, claims, chainInput, algorithm) {
3746
+ try {
3747
+ if (!isRecord(chainInput))
3748
+ return fail("signing_input_invalid");
3749
+ }
3750
+ catch (_error) {
3751
+ return fail("invalid_type");
3752
+ }
3753
+ const plain = plainVerificationInputs({}, [kid, claims, algorithm], 1);
2994
3754
  if (!plain.ok)
2995
3755
  return plain;
2996
- [kid, claims, chainInput, algorithm] = plain.value;
2997
- const built = buildSigningInput("termination", kid, claims, algorithm);
3756
+ [kid, claims, algorithm] = plain.value;
3757
+ const built = buildSigningInput(operation, kid, claims, algorithm);
2998
3758
  if (!built.ok)
2999
3759
  return built;
3000
- const refusal = terminationRefusal(claims, chainInput);
3001
- if (!refusal.ok)
3002
- return { ok: false, code: refusal.code };
3003
- return built;
3760
+ const context = plainVerificationInputs({}, [chainInput], -1, -1, { 0: CHAIN_MEMBERS });
3761
+ if (!context.ok)
3762
+ return context;
3763
+ const resolved = refusalChain(context.value[0]);
3764
+ if ("invalidSet" in resolved)
3765
+ return fail(resolved.invalidSet);
3766
+ const kind = operation === "termination" ? "termination" : "acceptance";
3767
+ const refusal = signingRefusalInChain(kind, kid, claims, resolved.chain);
3768
+ return refusal.ok ? built : refusal;
3004
3769
  }
3005
3770
  function decodeSigningArtifact(compact, limits = DEFAULT_LIMITS) {
3006
3771
  const decoded = decodeJws(compact, limits);
@@ -3027,7 +3792,7 @@ function assembleUnderLimits(input, signature, limits) {
3027
3792
  // The input is a struct the producer minted: the message must BE the
3028
3793
  // protected/payload framing (a caller-modified copy is invalid, never
3029
3794
  // silently assembled).
3030
- if (typeof input.protectedSegment !== "string" || typeof input.payloadSegment !== "string" ||
3795
+ if (typeof input.alg !== "string" || typeof input.protectedSegment !== "string" || typeof input.payloadSegment !== "string" ||
3031
3796
  !Buffer.isBuffer(input.message) || input.message.toString("utf8") !== `${input.protectedSegment}.${input.payloadSegment}`) {
3032
3797
  return { ok: false, code: "signing_input_invalid" };
3033
3798
  }
@@ -3036,7 +3801,7 @@ function assembleUnderLimits(input, signature, limits) {
3036
3801
  return { ok: false, code: "algorithm_unsupported" };
3037
3802
  if (signature.length !== row.signatureBytes)
3038
3803
  return { ok: false, code: "signature_invalid" };
3039
- const compact = `${input.message.toString("utf8")}.${encodeBase64url(signature)}`;
3804
+ const compact = `${input.message.toString("utf8")}.${signature.toString("base64url")}`;
3040
3805
  if (Buffer.byteLength(compact) > limits.max_bytes)
3041
3806
  return { ok: false, code: "signing_input_invalid" };
3042
3807
  const decoded = decodeSigningArtifact(compact, limits);
@@ -3065,6 +3830,13 @@ function refusalChain(chainInput) {
3065
3830
  const chain = chainFromInput(chainInput);
3066
3831
  return chain.ok ? { chain: chain.value } : { invalidSet: chain.code };
3067
3832
  }
3833
+ function signingRefusalInChain(kind, kid, claims, chain) {
3834
+ const refusal = kind === "acceptance" ? acceptanceRefusalInChain(claims, chain) : terminationRefusalInChain(claims, chain);
3835
+ if (!refusal.ok)
3836
+ return refusal;
3837
+ const descriptor = chain.descriptors.descriptors.find((one) => one.digest === claims.party_descriptor_digest);
3838
+ return scopeForKey(descriptor?.payload, kid, claims.party_role, kind).scope_status === "outside" ? refused() : refusal;
3839
+ }
3068
3840
  function refusalPartyMatches(revision, claims) {
3069
3841
  return revision.value.parties.some((party) => party.role === claims.party_role && party.party_descriptor_digest === claims.party_descriptor_digest);
3070
3842
  }
@@ -3095,13 +3867,24 @@ function acceptanceRefusalInChain(claims, chain) {
3095
3867
  const revision = chain.revisions.find((one) => one.digest === claims.revision_digest);
3096
3868
  if (!revision)
3097
3869
  return refused();
3870
+ const partyMatches = acceptanceBindingMatches(revision, claims);
3871
+ if (claims.replacement_role !== undefined && !partyMatches)
3872
+ return fail("acceptance_claims_mismatch");
3098
3873
  const charterId = revision.value.charter_id || revision.digest;
3099
3874
  if (claims.charter_id !== charterId ||
3100
3875
  claims.revision_number !== revision.value.revision_number ||
3101
3876
  (revision.value.prev_revision_digest || undefined) !== (claims.prev_revision_digest || undefined) ||
3102
- !refusalPartyMatches(revision, claims)) {
3877
+ (claims.protocol_revision === 8) !== (revision.value.protocol_revision === 8) ||
3878
+ !partyMatches) {
3103
3879
  return refused();
3104
3880
  }
3881
+ const predecessor = chain.accepted.find((one) => one.digest === revision.value.prev_revision_digest);
3882
+ if (revision.value.revision_number !== 1 && (!predecessor ||
3883
+ (revision.value.supersedes ?? []).some((digest) => !chain.acceptedDigests.includes(digest))))
3884
+ return refused();
3885
+ const ordinaryAssignmentAssent = claims.replacement_role === undefined && replacements(revision.value).length > 0;
3886
+ if (!ordinaryAssignmentAssent && acceptanceParticipationReason(claims, revision, predecessor) !== null)
3887
+ return refused();
3105
3888
  // R2 no-equivocation: no existing acceptance holds this charter/number
3106
3889
  // coordinate for a different revision.
3107
3890
  const equivocation = chain.acceptances.some((one) => one.claims.charter_id === claims.charter_id &&
@@ -3144,7 +3927,8 @@ function terminationRefusalInChain(claims, chain) {
3144
3927
  const charterId = revision.value.charter_id || revision.digest;
3145
3928
  if (claims.charter_id !== charterId ||
3146
3929
  !revision.value.termination_rules.reason_codes.includes(claims.reason_code) ||
3147
- !refusalPartyMatches(revision, claims)) {
3930
+ (claims.protocol_revision === 8) !== (revision.value.protocol_revision === 8) ||
3931
+ !refusalPartyMatches(revision, claims) || !terminationRule(revision).roles.includes(claims.party_role)) {
3148
3932
  return refused();
3149
3933
  }
3150
3934
  // R3 governing coverage: the named revision must be THE unique governing