@charter-agreement-protocol/verifier 0.2.1 → 0.4.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/README.md CHANGED
@@ -61,6 +61,18 @@ cannot verify green.
61
61
  | `decodeJsonText(text)` | Strict I-JSON decode (duplicates, noncharacters, lone surrogates, number round-tripping rejected) |
62
62
  | `jsonProjection(value)` | The tagged projection used by reports |
63
63
  | `CERTIFIED_INDEX_SHA256_BASE64URL`, `CERTIFIED_REGISTRY_DIGEST` | The certified identity pins this build carries |
64
+ | `verifyDescriptor(compact, predecessor?)` / `verifyDescriptorChain(compacts)` | Artifact-level verification: one party descriptor (with optional predecessor facts), or a full descriptor chain |
65
+ | `verifyAcceptance(compact, revisionText, descriptorCompacts)` / `verifyTermination(compact, revisionText, descriptorCompacts)` | Artifact-level verification of an acceptance / termination notice against the named revision and the signing party's descriptor chain |
66
+ | `verifyChain(chainInput)` / `verifyReceipt(compact, chainInput)` | Full chain-view verification (facts include the accepted/superseded topology and the verified acceptances); receipt verification against the verified chain |
67
+ | `checkSigningClaims(kind, claims)` | The producer build gate's claims half (the reference `decode_for_signing`): the claims-only schema checks per kind — `descriptor \| acceptance \| termination \| receipt` — shared with the verify paths; holder-side signers run it before any key is used |
68
+ | `decodeArtifact(compact)` / `verifySignature(message, signature, publicKey, alg)` | Framing-level decode (the holder-side provisional check) and the strict wrong-key guard primitive |
69
+ | `descriptorSigningInput(kid, claims, alg?)` / `receiptSigningInput(kid, claims, alg?)` | The build-only producers: the exact RFC 7515 signing input per kind (emission pair gated, claims schema gated, provisional decode) — no key, no signature |
70
+ | `acceptanceSigningInput(kid, claims, chainInput, alg?)` / `terminationSigningInput(kid, claims, chainInput, alg?)` | The set-aware producers: build first, then the R1–R3 refusal checks at the reference ordering |
71
+ | `assembleCompact(signingInput, signature)` | Assemble a validated signing input and its exact raw signature (registry-row length, framing re-decode, size gate) |
72
+ | `governingRevision(chainInput, at)` | The unique governing revision at one UTC instant — a digest, or `contested`/`none`, over the certified chain semantics |
73
+ | `decodeCharterRevision(text)` / `revisionDigest(text)` | Decode one canonical unsigned Charter Revision (claims + content digest over the exact text bytes) |
74
+ | `decodePartyDescriptor(compact)` / `descriptorDigest(compact)` | Decode one Party Descriptor's claims and digest without verifying its signature |
75
+ | `acceptanceRefusal(claims, chainInput)` / `terminationRefusal(claims, chainInput)` | The honest-signer refusal checks (R1–R3: claims-truth, no-equivocation, ancestry/governing coverage) over the caller's own view — `{ok: true}`, or `signing_refused` / `chain_invalid` / `signing_input_invalid`. Holder-side signers run these before any key is used; the rule that fired is deliberately not surfaced |
64
76
 
65
77
  ## Evidence
66
78
 
@@ -75,12 +87,23 @@ cannot verify green.
75
87
  - **This package never publishes verdict claims that were not recomputed
76
88
  from raw bytes.**
77
89
 
78
- ## Organization namespace
90
+ ## The sibling signer
79
91
 
80
- The `charter-agreement-protocol` npm organization hosts this protocol family's
81
- TypeScript packages: `@charter-agreement-protocol/verifier` (this package) and
82
- `@charter-agreement-protocol/signer` (reserved for the holder-side companion
83
- signer's TypeScript package).
92
+ The `charter-agreement-protocol` npm organization hosts this protocol
93
+ family's two independent TypeScript packages — no Elixir code or dependency
94
+ at runtime; the Elixir reference is the certification oracle (this
95
+ package's vendored corpus is certified against it, and its CI
96
+ cross-verifies TypeScript-signed artifacts from raw bytes):
97
+
98
+ - **This package** — `@charter-agreement-protocol/verifier`: verification
99
+ and the pure producer surface (signing inputs, refusal guards, assembly).
100
+ - [`@charter-agreement-protocol/signer`](https://www.npmjs.com/package/@charter-agreement-protocol/signer)
101
+ — the holder-side companion: key custody, the wrong-key guard, and
102
+ post-sign verification, delegating all protocol logic here.
103
+
104
+ The pair releases together: the signer depends on this package, so a
105
+ verifier release stages first and the signer locks and releases against
106
+ the published version immediately after.
84
107
 
85
108
  ## SemVer
86
109
 
package/dist/core.d.ts CHANGED
@@ -130,4 +130,79 @@ export declare function verifyAcceptance(compact: string, revisionText: string,
130
130
  export declare function verifyTermination(compact: string, revisionText: string, descriptorCompacts: string[]): VerifyResult;
131
131
  export declare function verifyChain(chainInput: AnyRecord): VerifyResult;
132
132
  export declare function verifyReceipt(compact: string, chainInput: AnyRecord): VerifyResult;
133
+ export declare function checkSigningClaims(kind: "descriptor" | "acceptance" | "termination" | "receipt", claims: AnyRecord): {
134
+ ok: true;
135
+ } | {
136
+ ok: false;
137
+ code: string;
138
+ };
139
+ export declare function governingRevision(chainInput: AnyRecord, at: string): {
140
+ ok: true;
141
+ governing: string;
142
+ } | {
143
+ ok: false;
144
+ code: string;
145
+ };
146
+ export declare function decodeCharterRevision(text: unknown): {
147
+ ok: true;
148
+ revision: AnyRecord;
149
+ digest: string;
150
+ } | {
151
+ ok: false;
152
+ code: string;
153
+ };
154
+ export declare function revisionDigest(text: unknown): {
155
+ ok: true;
156
+ digest: string;
157
+ } | {
158
+ ok: false;
159
+ code: string;
160
+ };
161
+ export declare function decodePartyDescriptor(compact: unknown): {
162
+ ok: true;
163
+ claims: AnyRecord;
164
+ digest: string;
165
+ } | {
166
+ ok: false;
167
+ code: string;
168
+ };
169
+ export declare function descriptorDigest(compact: unknown): {
170
+ ok: true;
171
+ digest: string;
172
+ } | {
173
+ ok: false;
174
+ code: string;
175
+ };
176
+ export type SigningInput = {
177
+ alg: string;
178
+ protectedSegment: string;
179
+ payloadSegment: string;
180
+ message: Buffer;
181
+ };
182
+ export type ProducerResult = {
183
+ ok: true;
184
+ input: SigningInput;
185
+ } | {
186
+ ok: false;
187
+ code: string;
188
+ };
189
+ export declare function descriptorSigningInput(kid: string, claims: AnyRecord, algorithm?: string): ProducerResult;
190
+ export declare function receiptSigningInput(kid: string, claims: AnyRecord, algorithm?: string): ProducerResult;
191
+ export declare function acceptanceSigningInput(kid: string, claims: AnyRecord, chainInput: AnyRecord, algorithm?: string): ProducerResult;
192
+ export declare function terminationSigningInput(kid: string, claims: AnyRecord, chainInput: AnyRecord, algorithm?: string): ProducerResult;
193
+ export declare function assembleCompact(input: SigningInput, signature: Buffer): {
194
+ ok: true;
195
+ compact: string;
196
+ } | {
197
+ ok: false;
198
+ code: string;
199
+ };
200
+ export type RefusalResult = {
201
+ ok: true;
202
+ } | {
203
+ ok: false;
204
+ code: string;
205
+ };
206
+ export declare function acceptanceRefusal(claims: AnyRecord, chainInput: AnyRecord): RefusalResult;
207
+ export declare function terminationRefusal(claims: AnyRecord, chainInput: AnyRecord): RefusalResult;
133
208
  export {};
package/dist/core.js CHANGED
@@ -562,6 +562,11 @@ function keyGrammarError(payload) {
562
562
  return "nested_invalid";
563
563
  }
564
564
  for (const one of payload.verification_keys) {
565
+ // Malformed entries carry the typed code, never a dereference throw -
566
+ // the pre-sign claims gate and the verify path share this walk.
567
+ if (!one || typeof one !== "object" || typeof one.algorithm !== "string" || typeof one.public_key !== "string") {
568
+ return "nested_invalid";
569
+ }
565
570
  const row = ALG_ROWS.find((candidate) => candidate.keyAlgorithm === one.algorithm);
566
571
  if (!row)
567
572
  return "nested_invalid";
@@ -650,6 +655,8 @@ function revisionFromText(text) {
650
655
  catch (_error) {
651
656
  return fail("invalid_syntax");
652
657
  }
658
+ if (!value || typeof value !== "object" || Array.isArray(value))
659
+ return fail("revision_invalid");
653
660
  const unknown = Object.keys(value).find((key) => !REVISION_FIELDS.includes(key));
654
661
  if (unknown)
655
662
  return fail("unknown_member");
@@ -704,10 +711,9 @@ function acceptanceFromCompact(compact, revision, chain) {
704
711
  if (!decoded.ok)
705
712
  return decoded;
706
713
  const claims = decoded.value.payload;
707
- if ((claims.revision_number === 1) !== (claims.prev_revision_digest === undefined))
708
- return fail("acceptance_invalid");
709
- if (!parseTimestamp(claims.accepted_at))
710
- return fail("timestamp_invalid");
714
+ const acceptanceShape = acceptanceClaimsError(claims);
715
+ if (acceptanceShape)
716
+ return fail(acceptanceShape);
711
717
  const descriptor = chain.descriptors.find((one) => one.digest === claims.party_descriptor_digest);
712
718
  if (!descriptor || !verifyDecodedJws(decoded.value, "cap+acceptance", descriptor.payload.verification_keys))
713
719
  return fail("signature_invalid");
@@ -730,10 +736,9 @@ function terminationFromCompact(compact, revision, chain) {
730
736
  const party = revision.value.parties.find((one) => one.party_descriptor_digest === claims.party_descriptor_digest);
731
737
  if (claims.charter_id !== expectedCharter || claims.governing_revision_digest !== revision.digest || claims.party_role !== party?.role || !revision.value.termination_rules.reason_codes.includes(claims.reason_code))
732
738
  return fail("termination_claims_mismatch");
733
- const issuedAt = parseTimestamp(claims.issued_at);
734
- const effectiveAt = parseTimestamp(claims.effective_at);
735
- if (!issuedAt || !effectiveAt || compareTimestamps(issuedAt, effectiveAt) > 0)
736
- return fail("termination_invalid");
739
+ const terminationShape = terminationClaimsError(claims);
740
+ if (terminationShape)
741
+ return fail(terminationShape);
737
742
  return ok({ claims, digest: taggedHash("termination_content", decoded.value.payloadBytes), descriptorPosition: chain.positions[claims.party_descriptor_digest] });
738
743
  }
739
744
  // Chain-level structural checks mirroring Chain.verify: unique revision
@@ -782,7 +787,7 @@ function chainFromInput(input) {
782
787
  }
783
788
  const acceptances = [];
784
789
  const coordinates = new Set();
785
- for (const compact of input.acceptances) {
790
+ for (const compact of (input.acceptances || [])) {
786
791
  const decoded = decodeJws(compact);
787
792
  if (!decoded.ok)
788
793
  return fail("chain_invalid");
@@ -844,7 +849,7 @@ function chainFromInput(input) {
844
849
  };
845
850
  const linear = heads.length === 1 && ancestryCovers(heads[0].digest);
846
851
  const topology = active.length > 0 && !linear ? "forked" : "linear";
847
- return ok({ descriptors: descriptors.value, revisions, accepted, acceptedDigests: accepted.map((one) => one.digest).sort(), supersededDigests: [...superseded].sort(), topology, charterId });
852
+ return ok({ descriptors: descriptors.value, revisions, acceptances, accepted, acceptedDigests: accepted.map((one) => one.digest).sort(), supersededDigests: [...superseded].sort(), topology, charterId });
848
853
  }
849
854
  // Governing mirrors the reference semantics exactly: candidates are accepted,
850
855
  // non-superseded, and effective at the instant (start-inclusive, end-exclusive
@@ -920,35 +925,19 @@ function receiptFromCompact(compact, chain) {
920
925
  if (!decoded.ok)
921
926
  return decoded;
922
927
  const claims = decoded.value.payload;
923
- if (claims.grant?.scheme === "bap" && claims.grant?.grant_digest === undefined)
924
- return fail("receipt_invalid");
925
- const optional = claims.extensions?.optional || {};
926
- for (const namespace of Object.keys(optional)) {
927
- const profile = EXTENSION_PROFILES.find((entry) => entry.namespace === namespace);
928
- if (!profile || profile.state === "reserved" || profile.state === "retired")
929
- continue;
930
- if (profile.surface !== "receipt")
931
- return fail("extension_scope_invalid");
932
- if (profile.schema_digest === null)
933
- return fail("extension_schema_unavailable");
934
- }
928
+ const receiptShape = receiptGrantError(claims);
929
+ if (receiptShape)
930
+ return fail(receiptShape);
935
931
  const claimedRevision = chain.accepted.find((one) => one.digest === claims.revision_digest);
936
932
  const verifiedPublicKeys = new Set(receiptSigningKeys(chain, claimedRevision, claims.issuing_party_role)
937
933
  .filter((key) => verifyDecodedJws(decoded.value, "cap+receipt", [key]))
938
934
  .map((key) => key.public_key));
939
935
  if (verifiedPublicKeys.size !== 1)
940
936
  return fail("signature_invalid");
941
- const occurredAt = parseTimestamp(claims.occurred_at);
942
- const recordedAt = parseTimestamp(claims.recorded_at);
943
- if (!occurredAt || !recordedAt || compareTimestamps(recordedAt, occurredAt) < 0)
944
- return fail("receipt_invalid");
945
- // The closed matrix mirrors the reference decoder: rejected requires
946
- // no_effect; accepted admits effect_committed, no_effect, or indeterminate.
947
- const outcomeAllowed = claims.decision === "rejected" ? claims.outcome === "no_effect" :
948
- (claims.outcome === "effect_committed" || claims.outcome === "no_effect" || claims.outcome === "indeterminate");
949
- if (!outcomeAllowed)
950
- return fail("cross_field_invalid");
951
- const governingDigest = governing(chain, occurredAt);
937
+ const receiptTiming = receiptTimingError(claims);
938
+ if (receiptTiming)
939
+ return fail(receiptTiming);
940
+ const governingDigest = governing(chain, parseTimestamp(claims.occurred_at));
952
941
  const projection = projectReceipt(claims, chain, governingDigest);
953
942
  if (!projection.ok)
954
943
  return projection;
@@ -1397,3 +1386,349 @@ export function verifyReceipt(compact, chainInput) {
1397
1386
  },
1398
1387
  };
1399
1388
  }
1389
+ // ---------------------------------------------------------------------------
1390
+ // The producer build gate's claims half (the reference decode_for_signing):
1391
+ // the schema checks that depend only on the claims, shared with the verify
1392
+ // paths below so the pre-sign gate and the post-sign discipline are ONE
1393
+ // implementation. Holder-side signers run checkSigningClaims before any key
1394
+ // is used; malformed claims are a typed producer rejection, never a burned
1395
+ // key operation.
1396
+ // ---------------------------------------------------------------------------
1397
+ export function checkSigningClaims(kind, claims) {
1398
+ if (!claims || typeof claims !== "object" || Array.isArray(claims))
1399
+ return { ok: false, code: "invalid_type" };
1400
+ const error = kind === "descriptor" ? descriptorClaimsError(claims) :
1401
+ kind === "acceptance" ? acceptanceClaimsError(claims) :
1402
+ kind === "termination" ? terminationClaimsError(claims) :
1403
+ kind === "receipt" ? (receiptGrantError(claims) ?? receiptTimingError(claims)) :
1404
+ "invalid_type";
1405
+ return error ? { ok: false, code: error } : { ok: true };
1406
+ }
1407
+ function acceptanceClaimsError(claims) {
1408
+ if ((claims.revision_number === 1) !== (claims.prev_revision_digest === undefined))
1409
+ return "acceptance_invalid";
1410
+ if (!parseTimestamp(claims.accepted_at))
1411
+ return "timestamp_invalid";
1412
+ return null;
1413
+ }
1414
+ function terminationClaimsError(claims) {
1415
+ const issuedAt = parseTimestamp(claims.issued_at);
1416
+ const effectiveAt = parseTimestamp(claims.effective_at);
1417
+ if (!issuedAt || !effectiveAt || compareTimestamps(issuedAt, effectiveAt) > 0)
1418
+ return "termination_invalid";
1419
+ return null;
1420
+ }
1421
+ function receiptGrantError(claims) {
1422
+ if (claims.grant?.scheme === "bap" && claims.grant?.grant_digest === undefined)
1423
+ return "receipt_invalid";
1424
+ const optional = claims.extensions?.optional || {};
1425
+ for (const namespace of Object.keys(optional)) {
1426
+ const profile = EXTENSION_PROFILES.find((entry) => entry.namespace === namespace);
1427
+ if (!profile || profile.state === "reserved" || profile.state === "retired")
1428
+ continue;
1429
+ if (profile.surface !== "receipt")
1430
+ return "extension_scope_invalid";
1431
+ if (profile.schema_digest === null)
1432
+ return "extension_schema_unavailable";
1433
+ }
1434
+ return null;
1435
+ }
1436
+ function receiptTimingError(claims) {
1437
+ const occurredAt = parseTimestamp(claims.occurred_at);
1438
+ const recordedAt = parseTimestamp(claims.recorded_at);
1439
+ if (!occurredAt || !recordedAt || compareTimestamps(recordedAt, occurredAt) < 0)
1440
+ return "receipt_invalid";
1441
+ // The closed matrix mirrors the reference decoder: rejected requires
1442
+ // no_effect; accepted admits effect_committed, no_effect, or indeterminate.
1443
+ const outcomeAllowed = claims.decision === "rejected" ? claims.outcome === "no_effect" :
1444
+ (claims.outcome === "effect_committed" || claims.outcome === "no_effect" || claims.outcome === "indeterminate");
1445
+ if (!outcomeAllowed)
1446
+ return "cross_field_invalid";
1447
+ return null;
1448
+ }
1449
+ function descriptorClaimsError(payload) {
1450
+ const grammar = keyGrammarError(payload);
1451
+ if (grammar)
1452
+ return grammar;
1453
+ if (!parseTimestamp(payload.effective_from))
1454
+ return "timestamp_invalid";
1455
+ if (payload.descriptor_number === 1 && payload.prev_descriptor_digest !== undefined)
1456
+ return "descriptor_invalid";
1457
+ return null;
1458
+ }
1459
+ // ---------------------------------------------------------------------------
1460
+ // The query/decode surface: the reference's governing-revision computation
1461
+ // and the revision/descriptor decode+digest pairs, over the same certified
1462
+ // internals the verify paths use. Every export fails closed with typed
1463
+ // codes; none of them verifies signatures.
1464
+ // ---------------------------------------------------------------------------
1465
+ // The unique governing revision in a verified view at one UTC instant -
1466
+ // a digest, or "contested"/"none" (never silently resolved).
1467
+ export function governingRevision(chainInput, at) {
1468
+ const instant = typeof at === "string" ? parseTimestamp(at) : null;
1469
+ if (!instant)
1470
+ return { ok: false, code: "invalid_type" };
1471
+ if (!chainInput || typeof chainInput !== "object" || Array.isArray(chainInput)) {
1472
+ return { ok: false, code: "signing_input_invalid" };
1473
+ }
1474
+ const chain = chainFromInput(chainInput);
1475
+ if (!chain.ok)
1476
+ return { ok: false, code: "chain_invalid" };
1477
+ return { ok: true, governing: governing(chain.value, instant) };
1478
+ }
1479
+ // Decode one canonical unsigned Charter Revision: the parsed claims plus
1480
+ // its content digest, computed over the exact text bytes.
1481
+ export function decodeCharterRevision(text) {
1482
+ const revision = revisionFromText(text);
1483
+ if (!revision.ok)
1484
+ return { ok: false, code: revision.code };
1485
+ return { ok: true, revision: revision.value.value, digest: revision.value.digest };
1486
+ }
1487
+ export function revisionDigest(text) {
1488
+ const revision = decodeCharterRevision(text);
1489
+ if (!revision.ok)
1490
+ return revision;
1491
+ return { ok: true, digest: revision.digest };
1492
+ }
1493
+ // Decode one Party Descriptor's claims without verifying its signature -
1494
+ // the framing, the descriptor schema, and the content digest.
1495
+ export function decodePartyDescriptor(compact) {
1496
+ const decoded = decodeJws(compact);
1497
+ if (!decoded.ok)
1498
+ return { ok: false, code: decoded.code };
1499
+ if (decoded.value.header.typ !== "cap+party")
1500
+ return { ok: false, code: "descriptor_invalid" };
1501
+ const claimsError = descriptorClaimsError(decoded.value.payload);
1502
+ if (claimsError)
1503
+ return { ok: false, code: claimsError };
1504
+ return { ok: true, claims: decoded.value.payload, digest: taggedHash("party_descriptor_content", decoded.value.payloadBytes) };
1505
+ }
1506
+ export function descriptorDigest(compact) {
1507
+ const decoded = decodePartyDescriptor(compact);
1508
+ if (!decoded.ok)
1509
+ return decoded;
1510
+ return { ok: true, digest: decoded.digest };
1511
+ }
1512
+ const PRODUCER_TYPES = {
1513
+ descriptor: "cap+party",
1514
+ acceptance: "cap+acceptance",
1515
+ termination: "cap+termination",
1516
+ receipt: "cap+receipt",
1517
+ };
1518
+ // The reference producer's tagged/1: claims must be pure JSON values -
1519
+ // undefined, functions, symbols, bigints, and non-finite numbers get the
1520
+ // typed producer code, never a canonicalization throw.
1521
+ function jsonValueError(value) {
1522
+ if (value === null)
1523
+ return false;
1524
+ const type = typeof value;
1525
+ if (type === "string" || type === "boolean")
1526
+ return false;
1527
+ if (type === "number")
1528
+ return !Number.isFinite(value);
1529
+ if (type !== "object")
1530
+ return true;
1531
+ if (Array.isArray(value))
1532
+ return value.some(jsonValueError);
1533
+ if (Buffer.isBuffer(value))
1534
+ return true;
1535
+ return Object.values(value).some(jsonValueError);
1536
+ }
1537
+ // The shared build path: algorithm -> claims shape/JSON values -> emission
1538
+ // binding -> kid -> framing -> size gate -> claims schema -> provisional
1539
+ // decode (the reference producer's exact ordering, so error precedence
1540
+ // matches too).
1541
+ function buildSigningInput(kind, kid, claims, algorithm) {
1542
+ if (typeof algorithm === "undefined" || algorithm === null)
1543
+ algorithm = defaultEmissionName();
1544
+ if (typeof algorithm !== "string" || !(algorithm in emissions())) {
1545
+ return { ok: false, code: "algorithm_unsupported" };
1546
+ }
1547
+ if (!claims || typeof claims !== "object" || Array.isArray(claims)) {
1548
+ return { ok: false, code: "invalid_type" };
1549
+ }
1550
+ const record = claims;
1551
+ if (jsonValueError(record))
1552
+ return { ok: false, code: "signing_input_invalid" };
1553
+ const revision = record.protocol_revision;
1554
+ if (typeof revision !== "number" || !Number.isInteger(revision) || revision !== emissions()[algorithm]) {
1555
+ return { ok: false, code: "signing_input_invalid" };
1556
+ }
1557
+ if (typeof kid !== "string" || kid.length === 0 || kid.length > 128 || !/^[A-Za-z0-9._~-]+$/.test(kid)) {
1558
+ return { ok: false, code: "signing_input_invalid" };
1559
+ }
1560
+ const row = ALG_ROWS.find((one) => one.name === algorithm);
1561
+ if (!row)
1562
+ return { ok: false, code: "algorithm_unsupported" };
1563
+ const payloadSegment = encodeBase64url(Buffer.from(canonical(record), "utf8"));
1564
+ const protectedSegment = encodeBase64url(Buffer.from(canonical({ alg: algorithm, kid, typ: PRODUCER_TYPES[kind] }), "utf8"));
1565
+ const message = Buffer.from(`${protectedSegment}.${payloadSegment}`, "utf8");
1566
+ const signatureSegmentLength = Math.ceil((row.signatureBytes * 4) / 3);
1567
+ if (message.length + 1 + signatureSegmentLength > JSON_DEFAULT_LIMITS.max_bytes) {
1568
+ return { ok: false, code: "signing_input_invalid" };
1569
+ }
1570
+ // The reference build's decode step: the claims schema gate runs inside
1571
+ // the producer, after framing and size - the same precedence as
1572
+ // decode_for_signing inside the Elixir build pipeline.
1573
+ const claimsGate = checkSigningClaims(kind, record);
1574
+ if (!claimsGate.ok)
1575
+ return { ok: false, code: claimsGate.code };
1576
+ // The provisional check: a zero signature at the row's exact length must
1577
+ // frame and bind.
1578
+ const zeroSignature = Buffer.alloc(row.signatureBytes);
1579
+ const provisional = `${protectedSegment}.${payloadSegment}.${encodeBase64url(zeroSignature)}`;
1580
+ const decoded = decodeArtifact(provisional);
1581
+ if (!decoded.ok)
1582
+ return { ok: false, code: "signing_input_invalid" };
1583
+ return { ok: true, input: { alg: algorithm, protectedSegment, payloadSegment, message } };
1584
+ }
1585
+ export function descriptorSigningInput(kid, claims, algorithm) {
1586
+ return buildSigningInput("descriptor", kid, claims, algorithm);
1587
+ }
1588
+ export function receiptSigningInput(kid, claims, algorithm) {
1589
+ return buildSigningInput("receipt", kid, claims, algorithm);
1590
+ }
1591
+ // The reference producer ordering: build (shape, emission binding, framing,
1592
+ // claims schema) FIRST, then the set-aware R1-R3 refusal checks - so a
1593
+ // claims defect reports the producer code even when the view is also bad.
1594
+ export function acceptanceSigningInput(kid, claims, chainInput, algorithm) {
1595
+ const built = buildSigningInput("acceptance", kid, claims, algorithm);
1596
+ if (!built.ok)
1597
+ return built;
1598
+ const refusal = acceptanceRefusal(claims, chainInput);
1599
+ if (!refusal.ok)
1600
+ return { ok: false, code: refusal.code };
1601
+ return built;
1602
+ }
1603
+ export function terminationSigningInput(kid, claims, chainInput, algorithm) {
1604
+ const built = buildSigningInput("termination", kid, claims, algorithm);
1605
+ if (!built.ok)
1606
+ return built;
1607
+ const refusal = terminationRefusal(claims, chainInput);
1608
+ if (!refusal.ok)
1609
+ return { ok: false, code: refusal.code };
1610
+ return built;
1611
+ }
1612
+ // Assemble a validated signing input and its exact raw signature (the
1613
+ // reference assemble): registry-row length, framing re-decode, size gate.
1614
+ export function assembleCompact(input, signature) {
1615
+ if (!input || typeof input !== "object" || !Buffer.isBuffer(signature))
1616
+ return { ok: false, code: "invalid_type" };
1617
+ // The input is a struct the producer minted: the message must BE the
1618
+ // protected/payload framing (a caller-modified copy is invalid, never
1619
+ // silently assembled).
1620
+ if (typeof input.protectedSegment !== "string" || typeof input.payloadSegment !== "string" ||
1621
+ !Buffer.isBuffer(input.message) || input.message.toString("utf8") !== `${input.protectedSegment}.${input.payloadSegment}`) {
1622
+ return { ok: false, code: "signing_input_invalid" };
1623
+ }
1624
+ const row = ALG_ROWS.find((one) => one.name === input.alg);
1625
+ if (!row)
1626
+ return { ok: false, code: "algorithm_unsupported" };
1627
+ if (signature.length !== row.signatureBytes)
1628
+ return { ok: false, code: "signature_invalid" };
1629
+ const compact = `${input.message.toString("utf8")}.${encodeBase64url(signature)}`;
1630
+ if (Buffer.byteLength(compact) > JSON_DEFAULT_LIMITS.max_bytes)
1631
+ return { ok: false, code: "signing_input_invalid" };
1632
+ const decoded = decodeArtifact(compact);
1633
+ if (!decoded.ok)
1634
+ return { ok: false, code: "signing_input_invalid" };
1635
+ return { ok: true, compact };
1636
+ }
1637
+ function refused() {
1638
+ return { ok: false, code: "signing_refused" };
1639
+ }
1640
+ // The producer build gate these checks assume already ran upstream in the
1641
+ // reference: fields the refusal rules consume must be well-typed, or the
1642
+ // caller gets the typed producer code instead of a refusal.
1643
+ function refusalClaimsShape(claims, stringFields, integerFields) {
1644
+ if (!claims || typeof claims !== "object" || Array.isArray(claims))
1645
+ return false;
1646
+ return stringFields.every((field) => typeof claims[field] === "string") &&
1647
+ integerFields.every((field) => typeof claims[field] === "number" && Number.isInteger(claims[field]));
1648
+ }
1649
+ // A non-object view mirrors the reference producer's non-ArtifactSet arm
1650
+ // (the typed producer code); an object that fails the chain discipline is
1651
+ // the caller's invalid set. Neither may throw out of the refusal boundary.
1652
+ function refusalChain(chainInput) {
1653
+ if (!chainInput || typeof chainInput !== "object" || Array.isArray(chainInput))
1654
+ return { invalidSet: "signing_input_invalid" };
1655
+ const chain = chainFromInput(chainInput);
1656
+ return chain.ok ? { chain: chain.value } : { invalidSet: "chain_invalid" };
1657
+ }
1658
+ function refusalPartyMatches(revision, claims) {
1659
+ return revision.value.parties.some((party) => party.role === claims.party_role && party.party_descriptor_digest === claims.party_descriptor_digest);
1660
+ }
1661
+ // Walk up the candidate's prev links through the whole verified revision
1662
+ // index; the verified chain guarantees strictly decreasing numbers, so the
1663
+ // walk terminates. Identity is ancestry (re-accepting a head covers itself).
1664
+ function refusalAncestorOf(candidate, target, byDigest) {
1665
+ if (candidate === target)
1666
+ return true;
1667
+ const previous = byDigest.get(candidate)?.value.prev_revision_digest;
1668
+ return typeof previous === "string" ? refusalAncestorOf(previous, target, byDigest) : false;
1669
+ }
1670
+ export function acceptanceRefusal(claims, chainInput) {
1671
+ if (!refusalClaimsShape(claims, ["revision_digest", "charter_id", "party_role", "party_descriptor_digest"], ["revision_number"])) {
1672
+ return { ok: false, code: "signing_input_invalid" };
1673
+ }
1674
+ const resolved = refusalChain(chainInput);
1675
+ if ("invalidSet" in resolved)
1676
+ return { ok: false, code: resolved.invalidSet };
1677
+ const chain = resolved.chain;
1678
+ // R1 claims-truth: the named revision exists and every coordinate binds.
1679
+ const revision = chain.revisions.find((one) => one.digest === claims.revision_digest);
1680
+ if (!revision)
1681
+ return refused();
1682
+ const charterId = revision.value.charter_id || revision.digest;
1683
+ if (claims.charter_id !== charterId ||
1684
+ claims.revision_number !== revision.value.revision_number ||
1685
+ (revision.value.prev_revision_digest || undefined) !== (claims.prev_revision_digest || undefined) ||
1686
+ !refusalPartyMatches(revision, claims)) {
1687
+ return refused();
1688
+ }
1689
+ // R2 no-equivocation: no existing acceptance holds this charter/number
1690
+ // coordinate for a different revision.
1691
+ const equivocation = chain.acceptances.some((one) => one.claims.charter_id === claims.charter_id &&
1692
+ one.claims.revision_number === claims.revision_number &&
1693
+ one.claims.revision_digest !== claims.revision_digest);
1694
+ if (equivocation)
1695
+ return refused();
1696
+ // R3 ancestry coverage: every maximum accepted head is superseded by the
1697
+ // candidate or an ancestor of it (an empty accepted set covers trivially).
1698
+ const maximum = Math.max(...chain.accepted.map((one) => one.value.revision_number));
1699
+ const heads = chain.accepted.filter((one) => one.value.revision_number === maximum).map((one) => one.digest);
1700
+ const byDigest = new Map(chain.revisions.map((one) => [one.digest, one]));
1701
+ const covered = heads.every((head) => (revision.value.supersedes || []).includes(head) || refusalAncestorOf(revision.digest, head, byDigest));
1702
+ if (!covered)
1703
+ return refused();
1704
+ return { ok: true };
1705
+ }
1706
+ export function terminationRefusal(claims, chainInput) {
1707
+ if (!refusalClaimsShape(claims, ["governing_revision_digest", "charter_id", "party_role", "party_descriptor_digest", "reason_code"], [])) {
1708
+ return { ok: false, code: "signing_input_invalid" };
1709
+ }
1710
+ const effectiveAt = parseTimestamp(claims.effective_at);
1711
+ if (!effectiveAt)
1712
+ return { ok: false, code: "signing_input_invalid" };
1713
+ const resolved = refusalChain(chainInput);
1714
+ if ("invalidSet" in resolved)
1715
+ return { ok: false, code: resolved.invalidSet };
1716
+ const chain = resolved.chain;
1717
+ // R1 claims-truth: the named revision exists, the reason is listed in its
1718
+ // termination rules, and the signing party is one of its parties.
1719
+ const revision = chain.revisions.find((one) => one.digest === claims.governing_revision_digest);
1720
+ if (!revision)
1721
+ return refused();
1722
+ const charterId = revision.value.charter_id || revision.digest;
1723
+ if (claims.charter_id !== charterId ||
1724
+ !revision.value.termination_rules.reason_codes.includes(claims.reason_code) ||
1725
+ !refusalPartyMatches(revision, claims)) {
1726
+ return refused();
1727
+ }
1728
+ // R3 governing coverage: the named revision must be THE unique governing
1729
+ // revision at the notice's own effective instant — a stale or contested
1730
+ // view refuses.
1731
+ if (governing(chain, effectiveAt) !== revision.digest)
1732
+ return refused();
1733
+ return { ok: true };
1734
+ }
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export { canonical, loadCorpus, reportFor, selfChecks, decodeJsonText, jsonProjection, type CanonicalValue, type Projection, type DecodeResult, type CaseResult, type CorpusFile, type CorpusIndex, type ConformanceCase, type LoadedCorpus, type CaseOutcome, type ConformanceReport, type ReportOutput, } from "./core.ts";
2
- export { CERTIFIED_INDEX_SHA256_BASE64URL, CERTIFIED_REGISTRY_DIGEST, algorithmRegistry, emissions, defaultEmissionName, encodeBase64url, taggedDigest, decodeArtifact, verifySignature, verifyDescriptor, verifyDescriptorChain, verifyAcceptance, verifyTermination, verifyChain, verifyReceipt, type AlgRow, type VerifyResult, } from "./core.ts";
2
+ export { CERTIFIED_INDEX_SHA256_BASE64URL, CERTIFIED_REGISTRY_DIGEST, algorithmRegistry, emissions, defaultEmissionName, encodeBase64url, taggedDigest, decodeArtifact, verifySignature, verifyDescriptor, verifyDescriptorChain, verifyAcceptance, verifyTermination, verifyChain, verifyReceipt, acceptanceRefusal, checkSigningClaims, terminationRefusal, descriptorSigningInput, receiptSigningInput, acceptanceSigningInput, terminationSigningInput, assembleCompact, governingRevision, decodeCharterRevision, revisionDigest, decodePartyDescriptor, descriptorDigest, type SigningInput, type ProducerResult, type AlgRow, type VerifyResult, type RefusalResult, } from "./core.ts";
package/dist/index.js CHANGED
@@ -5,4 +5,4 @@
5
5
  // and the self-check battery. Every verdict traces to corpus agreement with
6
6
  // the Elixir reference implementation, recomputed from raw bytes.
7
7
  export { canonical, loadCorpus, reportFor, selfChecks, decodeJsonText, jsonProjection, } from "./core.js";
8
- export { CERTIFIED_INDEX_SHA256_BASE64URL, CERTIFIED_REGISTRY_DIGEST, algorithmRegistry, emissions, defaultEmissionName, encodeBase64url, taggedDigest, decodeArtifact, verifySignature, verifyDescriptor, verifyDescriptorChain, verifyAcceptance, verifyTermination, verifyChain, verifyReceipt, } from "./core.js";
8
+ export { CERTIFIED_INDEX_SHA256_BASE64URL, CERTIFIED_REGISTRY_DIGEST, algorithmRegistry, emissions, defaultEmissionName, encodeBase64url, taggedDigest, decodeArtifact, verifySignature, verifyDescriptor, verifyDescriptorChain, verifyAcceptance, verifyTermination, verifyChain, verifyReceipt, acceptanceRefusal, checkSigningClaims, terminationRefusal, descriptorSigningInput, receiptSigningInput, acceptanceSigningInput, terminationSigningInput, assembleCompact, governingRevision, decodeCharterRevision, revisionDigest, decodePartyDescriptor, descriptorDigest, } from "./core.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@charter-agreement-protocol/verifier",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "Independent TypeScript verifier for the Charter Agreement Protocol (CAP) — byte-exact, offline re-verification of signed charter evidence. CAP verifies; it never authorizes.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",