ap2_mandate_verifier 0.3.0 → 0.5.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.
@@ -0,0 +1,149 @@
1
+ # Merchant Checkout signing (unpublished candidate)
2
+
3
+ ## Scope and responsibility
4
+
5
+ This additive API starts from the existing single Merchant / single SKU Checkout
6
+ profile, ES256 with a P-256 key. It leaves `Verifier`, `Result`, `Evidence`,
7
+ `InputBuilder` and diagnostics unchanged. A merchant signature attests to the
8
+ merchant-authored order bytes; it does not create user authorization, establish
9
+ merchant enrollment, persist an order, consume a nonce or make a payment.
10
+
11
+ The adopted AP2 source remains
12
+ [`b4587ac1d055888a73b4b21750973cffba961793`](https://github.com/google-agentic-commerce/AP2/tree/b4587ac1d055888a73b4b21750973cffba961793).
13
+ Checkout-specific ordering is defined by the existing local fixed profile, not
14
+ all UCP shapes. Unsupported fields, multiple items, nonempty links and unsupported
15
+ currencies are rejected. Amounts are integer minor units; totals must agree.
16
+
17
+ ## Minimal executable example
18
+
19
+ Run from this repository with the documented runtime and dependencies:
20
+
21
+ ```ruby
22
+ require "ap2_mandate_verifier"
23
+ require "openssl"
24
+
25
+ key = OpenSSL::PKey::EC.generate("prime256v1") # Test only; app owns real keys.
26
+ totals = [{"type" => "subtotal", "amount" => 100}, {"type" => "total", "amount" => 100}]
27
+ checkout = {
28
+ "id" => "order-1", "merchant" => {"id" => "shop", "name" => "Demo shop"},
29
+ "status" => "ready_for_complete", "currency" => "USD", "links" => [],
30
+ "line_items" => [{"id" => "line-1", "item" => {"id" => "sku", "title" => "Sample", "price" => 100},
31
+ "quantity" => 1, "totals" => totals}], "totals" => totals
32
+ }
33
+ signing = AP2MandateVerifier::CheckoutJWT
34
+ signed = signing.sign(checkout: checkout, signer: signing.es256_signer(private_key: key),
35
+ public_key_pem: key.public_to_pem)
36
+ puts signed.jwt.split(".").length # 3
37
+ puts signed.checkout_hash.length # 43
38
+ ```
39
+
40
+ `signed.jwt` is the frozen original compact JWT to transmit and retain. Supply
41
+ that exact String as `host_checkout_jws` to InputBuilder and Verifier; supply
42
+ `signed.checkout_hash` when a test or external Agent binds a Closed Mandate.
43
+ The Gem does not issue a product Mandate API. Re-encoding claims or signing again
44
+ creates different original wire, even when the order is the same.
45
+
46
+ `signer.call(signing_input)` receives the frozen ASCII `header.payload` and returns
47
+ 64 binary bytes containing the JOSE ES256 `r || s` signature. An HSM/remote
48
+ adapter must implement this interface and handle its own authorization, timeouts
49
+ and availability. The Gem itself performs no network operation. The selected
50
+ independent canonical public SPKI PEM verifies the final signature before a
51
+ `Signed` object is returned. The token cannot choose its own verification key.
52
+ `es256_signer` is a convenience closure over an application-owned OpenSSL P-256
53
+ private key; it never serializes the private key.
54
+
55
+ Invalid orders, wrong keys, unsupported keys, failed signer calls and invalid
56
+ signer output raise `CheckoutJWT::Invalid` with a fixed message and no original
57
+ cause. They never return a signed result. All application key lifecycle and trust
58
+ registration remain outside the Gem.
59
+
60
+ ## Checkout Receipt contract and specification discrepancy
61
+
62
+ Checkout-specific Schema uses `status: Success/Error`, `iss`, `iat`, `reference`;
63
+ Success requires `order_id`; Error requires `error` and `error_description`.
64
+ The generic authorization prose instead describes `result: success/error`.
65
+ Checkout schema and generated model do not strictly forbid fields from the other
66
+ branch; a stricter local profile must be documented as such.
67
+
68
+ Normative authorization/dispute text requires the final closed SD-JWT hash in
69
+ the same manner as `sd_hash`. Fixed SDK `sdjwt/common.py` includes the terminal
70
+ `~` even without disclosures. `MandateClient.get_closed_mandate_jwt` instead
71
+ extracts only compact JWT, discarding disclosures and `~`, and recommends hashing
72
+ that. These are distinct hashes even in the existing inline terminal profile.
73
+ The adopted contract prioritizes normative `sd_hash`: explicit original
74
+ closed SD-JWT input `<terminal_jws>~`, default SHA256/base64url without padding.
75
+ This is the existing inline terminal profile serialized as its final SD-JWT.
76
+ The caller must supply this exact representation; compact-only input is rejected.
77
+ The Gem never adds a missing `~`, extracts a leaf from a chain, or guesses a
78
+ reference from unparseable input. Disclosures, extra hops, `_sd_alg` extensions
79
+ and unsupported terminal claims are rejected. Bounded `kid` is accepted exactly
80
+ as in the existing verifier but never selects a trusted key. The entire input,
81
+ including `kid` bytes and terminal `~`, contributes to the hash.
82
+
83
+ The generic `result` spelling is not accepted. Success permits only `order_id`,
84
+ and Error permits only `error` and `error_description` alongside common fields.
85
+ This branch exclusivity, nonempty bounded strings and rejection of unknown
86
+ fields are explicit local-profile constraints, stronger than the base Schema.
87
+ `iat` is an integer epoch. `not_before <= iat <= verified_at <= not_after` is an
88
+ explicit application verification window, not an upstream freshness guarantee.
89
+ The application owns trusted key enrollment, expected issuer and time policy.
90
+
91
+ ```ruby
92
+ receipt = AP2MandateVerifier::CheckoutReceipt
93
+ # closed_sd_jwt is the exact received final `<terminal_jws>~` String.
94
+ rejection = receipt.sign(closed_sd_jwt: closed_sd_jwt, issuer: "shop",
95
+ outcome: "Error", error: "declined", error_description: "Application declined",
96
+ issued_at: now, signer: signing.es256_signer(private_key: key),
97
+ public_key_pem: key.public_to_pem)
98
+ checked = receipt.verify(jwt: rejection.jwt, closed_sd_jwt: closed_sd_jwt,
99
+ trusted_public_key_pem: independently_registered_public_pem, expected_issuer: "shop",
100
+ not_before: now - 60, not_after: now + 60, verified_at: now)
101
+ p [checked.verified?, checked.purchase_succeeded?, checked.purchase_rejected?]
102
+ # => [true, false, true]
103
+ ```
104
+
105
+ A Success call replaces Error fields with `outcome: "Success", order_id: "order-1"`.
106
+ `Signed#jwt` is the immutable transmitted receipt wire and `Signed#reference` its
107
+ Mandate reference. Invalid creation raises `CheckoutReceipt::Invalid` without
108
+ input values or original cause. Verification returns an immutable
109
+ `CheckoutReceipt::Verification`: `verified?`, `outcome` (`Success` or `Error`),
110
+ `purchase_succeeded?`, `purchase_rejected?`, `order_id`, `error`,
111
+ `error_description`, and a `code`. Failure exposes no untrusted claim values and
112
+ returns false for all three predicates. It never returns existing Verifier
113
+ `Result`/`Evidence` or modifies their status/code meanings.
114
+
115
+ Reference calculation validates supported syntax and preserves byte identity;
116
+ it does not verify the Mandate's authority. Receipt authenticity does not verify
117
+ Mandate authorization or evidence of payment/order execution. Obtain authorization
118
+ through the existing complete verifier plus Host responsibilities separately.
119
+ The application must explicitly provide its final business outcome; no Verifier
120
+ success is automatically converted into a Success Receipt.
121
+
122
+ ## Current verification
123
+
124
+ Dedicated offline Docker checks exercise original-wire hashing, signer failures,
125
+ wrong keys, unsupported input and complete existing Verifier/InputBuilder
126
+ integration. `test/merchant_interop.py` uses the fixed official Python SDK's
127
+ `create_jwt` and `verify_jwt`, compares decoded checkout claims and independently
128
+ computes the original JWT SHA256; reverse-direction wrong-key verification must
129
+ reject. Synthetic private keys stay in process memory. The scripts do not imply
130
+ real issuer provenance or universal AP2 conformance.
131
+
132
+ The fixed SDK `ReceiptClient.verify_receipt` checks signature/model/callback but
133
+ not expected issuer or application time policy. Our interoperability test compares
134
+ these separately on the Ruby side and verifies every callback argument against
135
+ the independently computed expected reference; a JWT-only hash must fail.
136
+ The SDK annotation says cryptography public key, but `jwt_helper.verify_jwt` uses
137
+ jwcrypto; the test supplies a public `JWK` adapter without skipping verification.
138
+ Success creation uses SDK ReceiptClient with a deterministic test clock; Error
139
+ uses the generated CheckoutReceipt model and official signing helper. SDK model
140
+ validation is also checked against original JSON Schema. No unconditional
141
+ success callback or reference-validation bypass is used.
142
+
143
+ The pinned Receipt Schema references `types/receipt_status.json`, while the
144
+ referenced file declares `$id` `.../schemas/receipt-status.json`. The local
145
+ Schema registry explicitly registers the reference URI as an alias for the
146
+ unaltered pinned file, plus declared IDs; it performs no network fallback.
147
+ This reference-resolution adjustment is recorded by the test output and does
148
+ not rewrite Schema conditions or skip validation. Checkout and Closed Mandate
149
+ payloads are also validated with the unaltered original JSON Schemas.
@@ -1,10 +1,23 @@
1
- # Fixed-profile AP2 verification — published 0.2.1 / historical 0.2.0
1
+ # Fixed-profile AP2 verification — published 0.4.0 / historical releases
2
2
 
3
- ## Unpublished 0.3.0 input-assistance candidate
3
+ Unpublished **0.5.0 candidate** adds separate [Merchant signing and Checkout Receipt APIs](MERCHANT_SIGNING.md). They do not broaden the existing Verifier profile or change Result/Evidence/status/code. Checkout Receipt uses the dedicated Schema and normative final SD-JWT reference; unsupported forms fail closed. No product Mandate issuance, payment, persistence or real key/trust management is included.
4
+
5
+ Published 0.4.0 adds supplemental safe diagnostics; see [API and troubleshooting](DIAGNOSTICS.md). Existing verdict/Evidence contracts remain unchanged.
6
+
7
+ [0.4.0 on RubyGems](https://rubygems.org/gems/ap2_mandate_verifier/versions/0.4.0) was registered 2026-10-31 04:25:06.427 UTC and compared at 04:26:15 UTC: owner `cuichangquan`, platform `ruby`, prerelease false, not yanked at comparison; 44,032 bytes, SHA256 `b212db01e7deb18dcef1199414f9d93ef43cb1f74b62baa55306de3955dfe177`. The download matches the saved reviewed artifact and all 17 payload files match source `fc42852f53c615f96d7c165a8de494b24b252519`. RubyGems does not independently attest the source SHA. Formal MRI support and all five runtime pins below are unchanged. [Publication record](PROJECT_STATUS.md#040-publication) and [validation scope](DIAGNOSTICS_VALIDATION.md). Packaged documentation retains its preparation snapshot; repository updates do not replace published bytes.
8
+
9
+
10
+ ## Published 0.3.0 input assistance
4
11
 
5
12
  `InputBuilder` is an additive, Rails-independent conversion layer for explicit authenticated Host business records, versioned challenge preparation/restoration, and independently obtained current state. `verify` enters the unchanged complete `verify_checkout` core; assembly/restore alone never returns Evidence. Existing seven inputs, fixed profile/AP2 source, Result/Evidence v2, MRI 3.4.12/4.0.9 and all five pinned runtime dependencies remain unchanged.
6
13
 
7
- New business Hash/Array graphs are bounded before serialization and require plain built-ins with String keys; unknown fields, formats/profiles, conflicting keys and unsupported shapes fail closed. Persist the original returned challenge String and original signed wires. `restore_trust` validates and preserves exact stored trust/selection Strings. Rebuilding trust from business records creates a new snapshot whose exact bytes may differ; it must not repair old challenge references. Stored B/digests/references are never regenerated from current values. Host authentication, freshness/revocation, storage, issuance/atomic consumption and final authorization remain Host duties. See [input assistance](INPUT_BUILDER.md). These candidate statements do not authorize publication or production operation.
14
+ New business Hash/Array graphs are bounded before serialization and require plain built-ins with String keys; unknown fields, formats/profiles, conflicting keys and unsupported shapes fail closed. Persist the original returned challenge String and original signed wires. `restore_trust` validates and preserves exact stored trust/selection Strings. Rebuilding trust from business records creates a new snapshot whose exact bytes may differ; it must not repair old challenge references. Stored B/digests/references are never regenerated from current values. Host authentication, freshness/revocation, storage, issuance/atomic consumption and final authorization remain Host duties. See [input assistance](INPUT_BUILDER.md). Publication does not establish Host production authorization.
15
+
16
+ [0.3.0 is published on RubyGems](https://rubygems.org/gems/ap2_mandate_verifier/versions/0.3.0): registered 2026-10-31 01:31:40.743 UTC; official metadata fetched at 01:32:40 UTC and final comparison completed at 01:33:27 UTC. Owner `cuichangquan`, platform `ruby`, non-prerelease, not yanked at verification. Metadata, distributed Gem and saved final candidate matched: **37,376 bytes**, SHA256 `b3a31d5a8b0718f1085745dd4d97d85f210ff9a1628798110da9ff382ae546bd`, source `877f59195632f74714a60551b6afb22ac81d93e3`. RubyGems does not independently attest a source commit; the source association is from the retained reviewed candidate, whose bytes match the download. [v0.3.0 tag/Release](https://github.com/cuichangquan/ap2-mandate-verifier/releases/tag/v0.3.0) points to that exact source and was published at 01:35:52 UTC.
17
+
18
+ On Debian 12/arm64, MRI 3.4.12 and 4.0.9 each passed the merged-source existing885 + checkout190 + metadata7 + builder109 suites. The same final Gem passed ordinary installation, 14 source/archive/installed payload matches, 11 normally loaded product files and 134 installed cases per Ruby. Five runtime pins remain JSON2.19.9/JWT3.3.0/base640.3.0/OpenSSL gem4.0.2/Digest3.2.1. Scope and withdrawn-candidate history are in the [publication record](PROJECT_STATUS.md#030公開済み--現在の配布状態); these observations do not validate real Issuers, actual Hosts, performance or production GO.
19
+
20
+ The earlier archive SHA256 `5de6907cfcf0565ddaba1385b1d38ae113cc5e26d52259d769030237378a48a8` is withdrawn and was not published. [PR219](https://github.com/cuichangquan/ap2-mandate-verifier/pull/219) fixed its unregistered failure Result codes, unavailable classification and selector shape checks. Published failure handling reuses existing registered Result codes and preserves dependency-unavailable typing. The published Gem's README/contract remain the preparation snapshot; this repository update does not rebuild, repush or replace those bytes. GitHub source archives are separate from the RubyGems Gem.
8
21
 
9
22
  **Fixed-profile verification contract; Evidence is not Host ALLOW or payment permission.**
10
23
  Distribution availability is determined by the official RubyGems version listing, not by this document. Specific Host production GO remains separate.
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Merchant-authored checkout, not a Mandate or authorization decision.
5
+ module CheckoutJWT
6
+ class Invalid < ArgumentError
7
+ def initialize = super("invalid checkout signing information")
8
+ end
9
+
10
+ class Signed
11
+ attr_reader :jwt, :checkout_hash
12
+ def initialize(jwt)
13
+ @jwt = jwt.freeze
14
+ @checkout_hash = Base64.urlsafe_encode64(Digest::SHA256.digest(jwt), padding: false).freeze
15
+ freeze
16
+ end
17
+ private_class_method :new
18
+ end
19
+
20
+ # signer.call receives the exact ASCII JWS signing input and must return a
21
+ # 64-byte JOSE ES256 signature. The supplied independent public key verifies
22
+ # the result before any signed object is returned (including remote signers).
23
+ def self.sign(checkout:, signer:, public_key_pem:)
24
+ RootSignature.send(:dependencies!)
25
+ value = InputBuilder.send(:copy!, checkout)
26
+ validate!(value)
27
+ jwt = MerchantSignature.sign!(value, signer, public_key_pem)
28
+ Signed.send(:new, jwt)
29
+ rescue StandardError, LoadError
30
+ raise Invalid.new, cause: nil
31
+ end
32
+
33
+ # No key serialization, storage, lookup or logging. The application owns the
34
+ # lifetime of this key/closure. Remote signers can implement the same call.
35
+ def self.es256_signer(private_key:)
36
+ RootSignature.send(:dependencies!)
37
+ raise Invalid unless private_key.instance_of?(OpenSSL::PKey::EC) &&
38
+ private_key.private? && private_key.group.curve_name == "prime256v1"
39
+ lambda do |input|
40
+ der = private_key.dsa_sign_asn1(Digest::SHA256.digest(input))
41
+ OpenSSL::ASN1.decode(der).value.map { |n| n.value.to_s(2).rjust(32, "\0") }.join
42
+ end
43
+ rescue StandardError, LoadError
44
+ raise Invalid.new, cause: nil
45
+ end
46
+
47
+ def self.validate!(checkout)
48
+ c = ScopedConstraints
49
+ c.send(:exact!, checkout, %w[currency id line_items links merchant status totals])
50
+ c.send(:text!, checkout["id"])
51
+ raise Invalid unless checkout["status"] == "ready_for_complete" &&
52
+ c::CURRENCIES.include?(checkout["currency"]) && checkout["links"] == []
53
+ c.send(:exact!, checkout["merchant"], %w[id name])
54
+ c.send(:text!, checkout["merchant"]["id"])
55
+ c.send(:text!, checkout["merchant"]["name"], 512)
56
+ line = c.send(:one!, checkout["line_items"])
57
+ c.send(:exact!, line, %w[id item quantity totals])
58
+ c.send(:text!, line["id"])
59
+ c.send(:quantity!, line["quantity"])
60
+ item = line["item"]
61
+ c.send(:exact!, item, %w[id price title])
62
+ c.send(:text!, item["id"])
63
+ c.send(:text!, item["title"], 512)
64
+ c.send(:amount!, item["price"])
65
+ total = item["price"] * line["quantity"]
66
+ c.send(:amount!, total)
67
+ c.send(:totals!, line["totals"], total)
68
+ c.send(:totals!, checkout["totals"], total)
69
+ nil
70
+ end
71
+ %i[sign es256_signer].each do |name|
72
+ implementation = method(name)
73
+ fields = implementation.parameters.filter_map { |kind, field| field if kind == :keyreq }.freeze
74
+ define_singleton_method(name) do |**arguments|
75
+ raise Invalid.new, cause: nil unless (fields - arguments.keys).empty? && (arguments.keys - fields).empty?
76
+ implementation.call(**arguments)
77
+ end
78
+ end
79
+ private_class_method :validate!
80
+ end
81
+ end
@@ -0,0 +1,143 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Checkout-specific pinned Schema; independent of Verifier Result/Evidence.
5
+ module CheckoutReceipt
6
+ class Invalid < ArgumentError
7
+ def initialize = super("invalid checkout receipt information")
8
+ end
9
+ class Signed
10
+ attr_reader :jwt, :reference
11
+ def initialize(jwt, reference)
12
+ @jwt, @reference = jwt.freeze, reference.freeze
13
+ freeze
14
+ end
15
+ private_class_method :new
16
+ end
17
+ class Verification
18
+ attr_reader :code, :outcome, :order_id, :error, :error_description
19
+ def initialize(code, claims = nil)
20
+ @code = code
21
+ if claims
22
+ @outcome = claims.fetch("status").freeze
23
+ @order_id, @error, @error_description = claims.values_at("order_id", "error", "error_description").map { |v| v&.freeze }
24
+ end
25
+ freeze
26
+ end
27
+ def verified? = code == :receipt_verified
28
+ def purchase_succeeded? = verified? && outcome == "Success"
29
+ def purchase_rejected? = verified? && outcome == "Error"
30
+ private_class_method :new
31
+ end
32
+
33
+ # Exact received final closed SD-JWT, no disclosures or additional hop.
34
+ # A terminal compact JWS alone is intentionally not accepted or repaired.
35
+ def self.reference(closed_sd_jwt:)
36
+ wire = InputValidator.snapshot!(closed_sd_jwt, max_bytes: 32_769)
37
+ raise Invalid unless wire.ascii_only? && wire.end_with?("~") && wire.count("~") == 1
38
+ compact = wire.byteslice(0, wire.bytesize - 1)
39
+ parts = compact.split(".", -1)
40
+ raise Invalid unless parts.size == 3
41
+ RootSignature.send(:dependencies!)
42
+ header = InputValidator.parse!(RootSignature.send(:decode!, parts[0], 2_048))
43
+ claims = InputValidator.parse!(RootSignature.send(:decode!, parts[1], 24_576))
44
+ signature = RootSignature.send(:decode!, parts[2], 64)
45
+ header!(header, "kb+sd-jwt")
46
+ raise Invalid unless signature.bytesize == 64
47
+ # Existing inline terminal grammar only, never general SD resolution.
48
+ PurchaseBinding.send(:exact!, claims, %w[aud delegate_payload iat nonce sd_hash])
49
+ %w[aud nonce sd_hash].each { |field| text!(claims[field], 512) }
50
+ epoch!(claims["iat"])
51
+ raise Invalid unless claims["sd_hash"].match?(/\A[A-Za-z0-9_-]{43}\z/)
52
+ closed = ScopedConstraints.send(:one!, claims["delegate_payload"])
53
+ PurchaseBinding.send(:exact!, closed, %w[checkout_hash checkout_jwt exp iat vct])
54
+ raise Invalid unless closed["vct"] == "mandate.checkout.1"
55
+ epoch!(closed["iat"]); epoch!(closed["exp"])
56
+ raise Invalid unless closed["exp"] > closed["iat"] && closed["checkout_hash"].instance_of?(String) &&
57
+ closed["checkout_hash"].match?(/\A[A-Za-z0-9_-]{43}\z/)
58
+ checkout = InputValidator.snapshot!(closed["checkout_jwt"], max_bytes: 16_384)
59
+ raise Invalid unless checkout.ascii_only? && checkout.split(".", -1).size == 3 &&
60
+ checkout.split(".", -1).all? { |part| part.match?(/\A[A-Za-z0-9_-]+\z/) }
61
+ checkout_parts = checkout.split(".", -1)
62
+ checkout_header = InputValidator.parse!(RootSignature.send(:decode!, checkout_parts[0], 2_048))
63
+ header!(checkout_header, "JWT")
64
+ raise Invalid unless RootSignature.send(:decode!, checkout_parts[2], 64).bytesize == 64
65
+ CheckoutJWT.send(:validate!, InputValidator.parse!(RootSignature.send(:decode!, checkout_parts[1], 12_000)))
66
+ raise Invalid unless closed["checkout_hash"] == hash(checkout)
67
+ hash(wire).freeze
68
+ rescue StandardError, LoadError
69
+ raise Invalid.new, cause: nil
70
+ end
71
+
72
+ def self.sign(closed_sd_jwt:, issuer:, outcome:, issued_at:, signer:, public_key_pem:, order_id: nil, error: nil, error_description: nil)
73
+ ref = reference(closed_sd_jwt: closed_sd_jwt)
74
+ claims = {"iss" => issuer, "status" => outcome, "iat" => issued_at, "reference" => ref}
75
+ claims["order_id"] = order_id unless order_id.nil?
76
+ claims["error"] = error unless error.nil?
77
+ claims["error_description"] = error_description unless error_description.nil?
78
+ claims = InputBuilder.send(:copy!, claims)
79
+ validate!(claims)
80
+ jwt = MerchantSignature.sign!(claims, signer, public_key_pem)
81
+ Signed.send(:new, jwt, ref)
82
+ rescue StandardError, LoadError
83
+ raise Invalid.new, cause: nil
84
+ end
85
+
86
+ # The Host supplies trusted enrollment key, expected signer and explicit time
87
+ # window independently. JWT iss/kid are never used to choose trust.
88
+ # Reference authenticates byte identity, not Mandate authorization/validity.
89
+ def self.verify(jwt:, closed_sd_jwt:, trusted_public_key_pem:, expected_issuer:, not_before:, not_after:, verified_at:)
90
+ expected = InputValidator.snapshot!(expected_issuer, max_bytes: 512)
91
+ text!(expected, 512)
92
+ [not_before, not_after, verified_at].each { |t| epoch!(t) }
93
+ raise Invalid unless not_before <= verified_at && verified_at <= not_after
94
+ ref = reference(closed_sd_jwt: closed_sd_jwt)
95
+ claims = RootSignature.verified_payload!(jwt, trusted_public_key_pem, expected_typ: "JWT", max_bytes: 16_384)
96
+ validate!(claims)
97
+ return Verification.send(:new, :receipt_issuer_mismatch) unless claims["iss"] == expected
98
+ return Verification.send(:new, :receipt_reference_mismatch) unless claims["reference"] == ref
99
+ return Verification.send(:new, :receipt_time_mismatch) unless claims["iat"].between?(not_before, verified_at)
100
+ Verification.send(:new, :receipt_verified, claims)
101
+ rescue StandardError, LoadError
102
+ Verification.send(:new, :receipt_verification_failed)
103
+ end
104
+
105
+ def self.validate!(claims)
106
+ raise Invalid unless claims.instance_of?(Hash)
107
+ fields = case claims["status"]
108
+ when "Success" then %w[iss status iat reference order_id]
109
+ when "Error" then %w[iss status iat reference error error_description]
110
+ else raise Invalid
111
+ end
112
+ raise Invalid unless claims.keys.sort == fields.sort
113
+ epoch!(claims["iat"])
114
+ (fields - %w[iat]).each { |field| text!(claims[field], field == "error_description" ? 2_048 : 512) }
115
+ raise Invalid unless claims["reference"].match?(/\A[A-Za-z0-9_-]{43}\z/)
116
+ end
117
+ def self.text!(value, max)
118
+ raise Invalid unless value.instance_of?(String) && value.bytesize.between?(1, max)
119
+ end
120
+ def self.epoch!(value)
121
+ raise Invalid unless Object.instance_method(:instance_of?).bind_call(value, Integer) && value.between?(0, PurchaseBinding::MAX_EPOCH)
122
+ end
123
+ def self.header!(header, typ)
124
+ raise Invalid unless header.instance_of?(Hash) && (header.keys - %w[alg typ kid]).empty? &&
125
+ header["alg"] == "ES256" && header["typ"] == typ
126
+ text!(header["kid"], 128) if header.key?("kid")
127
+ end
128
+ def self.hash(wire) = Base64.urlsafe_encode64(Digest::SHA256.digest(wire), padding: false)
129
+ %i[reference sign verify].each do |name|
130
+ implementation = method(name)
131
+ required = implementation.parameters.filter_map { |kind, field| field if kind == :keyreq }.freeze
132
+ fields = implementation.parameters.filter_map { |kind, field| field if %i[key keyreq].include?(kind) }.freeze
133
+ define_singleton_method(name) do |**arguments|
134
+ unless (required - arguments.keys).empty? && (arguments.keys - fields).empty?
135
+ next Verification.send(:new, :receipt_verification_failed) if name == :verify
136
+ raise Invalid.new, cause: nil
137
+ end
138
+ implementation.call(**arguments)
139
+ end
140
+ end
141
+ private_class_method :validate!, :text!, :epoch!, :header!, :hash
142
+ end
143
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Supplemental guidance, never a verification decision or an input echo.
5
+ # Only the closed catalog below can construct diagnostics. No input retained.
6
+ class Diagnostic
7
+ GROUPS = {
8
+ input_validation: [%i[invalid_input_type input_too_large invalid_encoding invalid_json duplicate_key input_too_deep],
9
+ "Check original String bytes, JSON syntax, duplicate keys and documented input limits.",
10
+ "原文のString型、JSON構文、重複キー、文書記載の入力上限を確認してください。"],
11
+ signature_verification: [%i[invalid_root_jws unsupported_root_header unsupported_root_algorithm unsupported_root_type invalid_root_payload invalid_root_signature],
12
+ "Check original signed Root/Agent/Merchant bytes, the fixed header profile and independently selected public keys. A signature failure alone does not identify which input is wrong.",
13
+ "署名原文、固定ヘッダー仕様、独立に選択した公開鍵を確認してください。署名失敗だけでは誤った入力を特定できません。"],
14
+ root_disclosures: [%i[invalid_root_presentation unsupported_disclosure_profile invalid_disclosure missing_disclosure duplicate_disclosure duplicate_commitment extra_disclosure disclosure_limit_exceeded],
15
+ "Check the complete original Root presentation and disclosures against the supported profile; do not repair received signed data.",
16
+ "原Root提示全体と開示を対応profileと照合してください。受信した署名データを補修しないでください。"],
17
+ purchase_binding: [%i[unsupported_purchase_profile agent_key_mismatch root_binding_mismatch audience_mismatch nonce_mismatch invalid_purchase_time delegation_claim_mismatch checkout_binding_mismatch checkout_identity_mismatch],
18
+ "Compare original Root, Agent and Merchant wires with independent Host audience, nonce, identity and clock inputs. The code identifies a failed check, not its underlying cause.",
19
+ "Root・Agent・Merchant原文と、Hostが独立に取得したaudience、nonce、主体、時刻を照合してください。コードは失敗した検査を示し、根本原因を断定しません。"],
20
+ constraints: [%i[invalid_scoped_schema unsupported_scoped_profile unsupported_constraint constraint_mismatch amount_mismatch currency_mismatch constraint_limit_exceeded],
21
+ "Compare signed constraints, checkout items, currency and minor-unit totals with independent current order data and the fixed profile.",
22
+ "署名済み制約、購入項目、通貨、最小単位の合計額を、独立した現在の注文情報および固定profileと照合してください。"],
23
+ trust_context: [%i[invalid_trust_context trust_context_mismatch unsupported_trust_profile inactive_trust_snapshot trust_snapshot_time_mismatch invalid_trust_key trust_key_not_found ambiguous_trust_key inactive_trust_key trust_key_time_mismatch],
24
+ "Check authenticated current trust snapshot, explicit role/key selection, active state and validity at the independent verification time. Never select trust from received claims.",
25
+ "認証された現在のtrust snapshot、明示的な役割・鍵選択、active状態、独立した検証時刻での有効期間を確認してください。受信claimから信頼先を選ばないでください。"],
26
+ host_binding: [%i[invalid_host_context host_binding_mismatch challenge_state_mismatch challenge_reference_mismatch challenge_time_mismatch invalid_host_validity],
27
+ "Compare the authenticated saved challenge with independent current order, trust references, expected issuer and time. Preserve the saved record; do not rebuild it from current values.",
28
+ "認証された保存済みchallengeと、独立した現在の注文、trust参照、期待issuer、時刻を照合してください。保存記録を現在値で作り直さないでください。"]
29
+ }.freeze
30
+ GROUPS.each_value { |entry| entry[0].freeze; entry.freeze }
31
+ SPECIAL = {
32
+ invalid_purchase_time: ["Check the independent clock and the signed Open/Closed validity and terminal proof time window. This does not establish whether the clock or signed times are wrong.",
33
+ "独立した時計、署名済みOpen・Closedの有効期間、terminal proofの時刻窓を確認してください。時計と署名時刻のどちらが誤っているかは断定できません。"]
34
+ }.freeze
35
+ BUILDER_HINTS = {
36
+ missing_required_field: ["Supply the documented required field from independent Host data.", "文書記載の必須項目を、独立したHost情報から渡してください。"],
37
+ invalid_type: ["Check the documented exact Ruby/JSON type; coercion and subclasses are not supported.", "文書記載のRuby・JSONの厳密な型を確認してください。暗黙変換やサブクラスは対応外です。"],
38
+ unknown_field: ["Remove unsupported fields using the documented schema. Unknown field names are intentionally omitted.", "文書記載の構造と照合し、未対応項目を除いてください。未知の項目名は意図的に表示しません。"],
39
+ unsupported_saved_format: ["Check the saved format/profile version against this gem. Restore original authenticated bytes; do not rewrite the version.", "保存形式・profileの版がGemの対応版か確認してください。認証された原文を復元し、版を書き換えないでください。"],
40
+ invalid_value: ["Check documented bounds and supported values for this field.", "この項目の文書記載の範囲と対応値を確認してください。"],
41
+ invalid_builder_input: ["Check the InputBuilder contract and bounded, plain Ruby input shapes. The exact cause could not be safely identified.", "InputBuilder契約と上限内の通常Ruby入力構造を確認してください。正確な原因は安全に特定できませんでした。"]
42
+ }.freeze
43
+ SPECIAL.each_value(&:freeze)
44
+ BUILDER_HINTS.each_value(&:freeze)
45
+ FIELDS = (%w[order trust verified_at saved_challenge snapshot snapshot.records issuer agent merchant arguments root_presentation terminal_jws host_checkout_jws trust_json selection_json expected_challenge_issuer_id clock_source_id challenge_id nonce issuer_id not_before not_after] +
46
+ %w[tenant_id buyer_account_id order_id merchant_id audience order_version currency expected_total].map { |f| "order.#{f}" } +
47
+ %w[id policy_version active not_before not_after records].map { |f| "snapshot.#{f}" } +
48
+ %w[format_version profile_ref profile_version challenge].map { |f| "saved_challenge.#{f}" } +
49
+ %w[issuer agent merchant].flat_map { |r| %w[identity purpose key_ref].map { |f| "#{r}.#{f}" } }).each(&:freeze).freeze
50
+
51
+ attr_reader :stage, :field, :reason
52
+ def initialize(stage, field, reason, hints)
53
+ @stage, @field, @reason = stage, field, reason
54
+ @hints = hints.map { |s| s.dup.freeze }.freeze
55
+ freeze
56
+ end
57
+ private_class_method :new, :allocate
58
+ def hint(locale: :en) = @hints[locale == :ja ? 1 : 0]
59
+ def to_h(locale: :en) = {stage: stage, field: field, reason: reason, hint: hint(locale: locale)}.freeze
60
+ def [](key) = to_h[key]
61
+ def dup = self
62
+ def clone(freeze: true) = self
63
+ def self.for_result(status, code)
64
+ return nil if status == :verified_research
65
+ known = Result::CODES.fetch(status, []).include?(code)
66
+ if status == :unavailable && known
67
+ return new(:verification_unavailable, nil, code,
68
+ ["Verification could not be completed. Check supported dependency versions and service/runtime health; this is not proof of invalid business data.",
69
+ "検証を完了できませんでした。対応依存バージョンと実行環境の状態を確認してください。業務データ不正の証拠ではありません。"])
70
+ end
71
+ GROUPS.each do |stage, (codes, en, ja)|
72
+ return new(stage, nil, code, SPECIAL.fetch(code, [en, ja])) if known && codes.include?(code)
73
+ end
74
+ new(:verification, nil, :undetermined,
75
+ ["No precise diagnostic is available. Check status/code and the documented API scope; do not infer checkout permission.",
76
+ "詳細診断はありません。status・codeとAPIの保証範囲を確認してください。購入許可とは解釈しないでください。"])
77
+ end
78
+ def self.builder(field, reason)
79
+ # Look up canonical strings; never retain a caller string or arbitrary key.
80
+ safe_field = FIELDS.find { |known| known == field }
81
+ safe_reason = BUILDER_HINTS.key?(reason) ? reason : :invalid_builder_input
82
+ new(:input_assembly, safe_field, safe_reason, BUILDER_HINTS.fetch(safe_reason))
83
+ end
84
+ end
85
+ end