ap2_mandate_verifier 1.0.0 → 1.1.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.
@@ -1,13 +1,22 @@
1
1
  # AP2 Checkout Ruby SDK — support contract and history
2
2
 
3
- ## Current contract and unpublished 1.0.0 preparation
4
-
5
- **Published stable remains 0.8.0. The working 1.0.0 candidate is unpublished.**
6
- The candidate preserves the existing product implementation and acceptance
7
- contracts. Its intended 1.x public surface is catalogued in
8
- [PUBLIC_API](PUBLIC_API.md); candidate evidence and outstanding decisions are in
9
- [the preparation record](RELEASE_100_CANDIDATE.md). Historical observations below
10
- are not new 1.0.0 test results.
3
+ ## Current contract — published 1.0.0
4
+
5
+ **Published stable is 1.0.0.** It preserves the 0.8.0 product implementation and
6
+ acceptance contracts. The stable 1.x public surface is catalogued in
7
+ [PUBLIC_API](PUBLIC_API.md); exact distribution identity and validation are in
8
+ [the publication record](POST_RELEASE_100.md). The earlier
9
+ [preparation record](RELEASE_100_CANDIDATE.md) and older observations below retain
10
+ their historical scope; they are not new post-publication test results.
11
+
12
+ Registered 2026-11-01 **08:13:29.733 UTC**; official download comparison completed
13
+ **08:16:01 UTC**. The 102,912-byte Gem, SHA256
14
+ `a107101b0178c54ba417be7a2bd7e22feb2fd9a07bda089043e8c5ea8e65e12b`,
15
+ matches the retained candidate exactly, and all 33 payloads match source
16
+ `59e344ad865ed867d0993120456f9411d82bcdec`. Source association comes from
17
+ candidate/payload comparison, not RubyGems source attestation.
18
+ [Publication receipt](evidence/1.0.0_publication.json). The published Gem's documents
19
+ retain their preparation snapshot; repository updates do not rebuild or replace it.
11
20
 
12
21
  | Current supported flow | Contract |
13
22
  | --- | --- |
@@ -30,12 +39,16 @@ The app owns current trust, consent, durable state and final execution. Ruby SDK
30
39
  support does not establish general AP2 compatibility, Payment support, actual
31
40
  Issuer trust or a particular Host's production authorization.
32
41
 
33
- The [maintenance policy](POST_RELEASE_MAINTENANCE.md) governs proposed 1.x
42
+ The [maintenance policy](POST_RELEASE_MAINTENANCE.md) governs 1.x
34
43
  versioning, dependency changes, security corrections and deprecation. The sections
35
44
  below preserve older publication evidence and API details; statements explicitly
36
45
  scoped to old versions do not remove the current flows listed above.
37
46
 
38
- ## Published 0.8.0 conditional delegation
47
+ Documented 0.8.0 API use needs no source migration. A constraint such as `~> 0.8.0`
48
+ does not select 1.0.0; use an appropriate 1.x constraint such as `~> 1.0` and update
49
+ the application lockfile. See [release and migration notes](RELEASE_100.md).
50
+
51
+ ## Historical 0.8.0: conditional delegation
39
52
 
40
53
  `ConditionalCheckout.issue_open/issue_closed/present` add conditional delegation
41
54
  issuance and original-wire presentation under the unchanged explicit multi-item
@@ -43,7 +56,7 @@ profile v1. [Contract, errors, limits and application responsibilities](CONDITIO
43
56
  The packaged standalone example uses only public installed APIs. No old default,
44
57
  profile definition/hash, Result/Evidence/diagnostic, saved record or Receipt
45
58
  acceptance condition is changed. All candidates remain required; no new selective
46
- disclosure profile is introduced. Published stable is 0.8.0, registered
59
+ disclosure profile is introduced. Version 0.8.0 was registered
47
60
  2026-11-01 06:01:31.103 UTC and compared 06:03:20 UTC: 79,872 bytes, SHA256
48
61
  `6c07664e4291aa8bc025b152075869322411a0d99861e1267959f1794e99acec`.
49
62
  All29 payloads match published source `5a7394c1b98f000b321423e2c2f80d50b5157808`.
@@ -61,7 +74,7 @@ match source `9b4b78a7ed9aa95e7d35e01a64efc1281ba95be3`.
61
74
  [Publication record](PROJECT_STATUS.md#070-publication). Older version statements below
62
75
  retain their historical scope; they do not exclude the new Direct APIs.
63
76
 
64
- ## Current source: explicit multi-item profile
77
+ ## Historical 0.6.0: explicit multi-item profile
65
78
 
66
79
  Published **0.6.0** adds the explicitly
67
80
  selected `ap2.checkout.single_merchant_multi_item` v1 across input preparation,
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+ # Installed Gem only; every payment/processor result is synthetic.
3
+ require "ap2_mandate_verifier"
4
+ require_relative "conditional_checkout"
5
+ module PaymentExample
6
+ M = AP2MandateVerifier
7
+ NOW = ConditionalCheckoutExample::NOW
8
+ def self.run
9
+ state = ConditionalCheckoutExample.run
10
+ provider, agent, merchant = state.fetch(:keys)
11
+ sign = ->(key) { M::CheckoutJWT.es256_signer(private_key: key) }
12
+ checkout = state.fetch(:closed).checkout_jwt
13
+ # External application selects the instrument and independently trusts order/key.
14
+ details = M::Payment.details(checkout_jwt: checkout, trusted_merchant_public_key_pem: merchant.public_to_pem,
15
+ expected_merchant_id: "shop", payment_instrument: {"id" => "synthetic-card", "type" => "card"})
16
+ direct_checkout = M::Buyer.issue_closed(checkout_jwt: checkout, approved_checkout_jwt: checkout,
17
+ trusted_merchant_public_key_pem: merchant.public_to_pem, expected_merchant_id: "shop",
18
+ issued_at: NOW, expires_at: NOW+60, signer: sign.call(provider), public_key_pem: provider.public_to_pem)
19
+ direct_inputs = {closed_sd_jwt: direct_checkout.closed_sd_jwt, expected_checkout_jwt: checkout,
20
+ trusted_provider_public_key_pem: provider.public_to_pem, trusted_merchant_public_key_pem: merchant.public_to_pem,
21
+ expected_merchant_id: "shop", verified_at: NOW}
22
+ # In a real application approved_payment is read from its protected consent record.
23
+ direct = M::Payment.issue_direct(payment: details, approved_payment: details, issued_at: NOW,
24
+ expires_at: NOW+60, signer: sign.call(provider), public_key_pem: provider.public_to_pem)
25
+ base = {expected_payment: details, trusted_provider_public_key_pem: provider.public_to_pem, verified_at: NOW}
26
+ direct_check = M::Payment.verify(**base, closed_sd_jwt: direct.closed_sd_jwt, checkout_mode: :direct, checkout_inputs: direct_inputs)
27
+ raise "Direct failed" unless direct_check.verified?
28
+
29
+ conditions = [{"type" => "payment.amount_range", "currency" => "USD", "max" => 300},
30
+ {"type" => "payment.allowed_payees", "allowed" => [details.fetch("payee")]},
31
+ {"type" => "payment.allowed_payment_instruments", "allowed" => [details.fetch("payment_instrument")]}]
32
+ opening = M::Payment.issue_open(open_checkout_sd_jwt: state.fetch(:opening).root_presentation,
33
+ constraints: conditions, fixed: {"payment_instrument" => details.fetch("payment_instrument")},
34
+ agent_public_key_pem: agent.public_to_pem, issued_at: NOW, expires_at: NOW+60,
35
+ signer: sign.call(provider), public_key_pem: provider.public_to_pem)
36
+ closed = M::Payment.issue_closed(open_sd_jwt: opening, payment: details,
37
+ trusted_provider_public_key_pem: provider.public_to_pem, agent_public_key_pem: agent.public_to_pem,
38
+ audience: "credential-provider", nonce: "synthetic-payment-nonce", verified_at: NOW, signer: sign.call(agent))
39
+ restored = M::Payment.present(open_sd_jwt: opening, closed_sd_jwt: closed.closed_sd_jwt)
40
+ # Reuse existing complete Checkout input preparation; no facts from Payment claims.
41
+ raw = M::InputBuilder.inputs(**state.fetch(:host_inputs), saved_challenge: state.fetch(:saved),
42
+ terminal_jws: state.fetch(:closed).terminal_jws, expected_challenge_issuer_id: "host",
43
+ clock_source_id: "synthetic-clock", verified_at: NOW)
44
+ checked = M::Payment.verify(**base, closed_sd_jwt: restored.closed_sd_jwt, open_sd_jwt: restored.open_sd_jwt,
45
+ checkout_mode: :conditional, checkout_inputs: raw, expected_agent_public_key_pem: agent.public_to_pem,
46
+ expected_audience: "credential-provider", expected_nonce: "synthetic-payment-nonce")
47
+ raise "Conditional failed" unless checked.verified?
48
+ puts "Direct and conditional Payment: verified; no execution permission granted"
49
+ [direct, restored].each do |payment|
50
+ # Alternative simulated outcomes, never two actual executions.
51
+ %w[Success Error].each do |outcome|
52
+ fields = outcome == "Success" ? {psp_confirmation_id: "synthetic-psp", network_confirmation_id: "synthetic-network"} :
53
+ {error: "declined", error_description: "Simulated rejection"}
54
+ receipt = M::PaymentReceipt.sign(closed_sd_jwt: payment.closed_sd_jwt, issuer: "processor",
55
+ payment_id: "synthetic-payment", outcome: outcome, issued_at: NOW, **fields,
56
+ signer: sign.call(merchant), public_key_pem: merchant.public_to_pem)
57
+ result = M::PaymentReceipt.verify(jwt: receipt.jwt, closed_sd_jwt: payment.closed_sd_jwt,
58
+ trusted_public_key_pem: merchant.public_to_pem, expected_issuer: "processor", expected_payment_id: "synthetic-payment",
59
+ not_before: NOW, not_after: NOW+60, verified_at: NOW)
60
+ raise "Receipt failed" unless result.verified? && result.outcome == outcome
61
+ puts "Payment Receipt #{outcome}: authentic=#{result.verified?}; reported_success=#{result.payment_succeeded?}"
62
+ end
63
+ end
64
+ puts "Synthetic only. Persist one-use state atomically. Missing/invalid Receipt = pending; no automatic retry."
65
+ end
66
+ end
67
+ PaymentExample.run if $PROGRAM_NAME == __FILE__
@@ -0,0 +1,361 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Complete content disclosure profile, one payment and at most one Agent hop.
5
+ # No network, consent authentication, replay ledger or execution permission.
6
+ module Payment
7
+ PROFILE_REF = "ap2.payment.single.complete.1".freeze
8
+ FIELDS = %w[transaction_id payee payment_amount payment_instrument].freeze
9
+ MAX_LIFETIME = 600
10
+ class Invalid < ArgumentError
11
+ def initialize = super("invalid payment information")
12
+ end
13
+ class Presentation
14
+ attr_reader :open_sd_jwt, :closed_sd_jwt
15
+ def initialize(opening, closed)
16
+ @open_sd_jwt, @closed_sd_jwt = opening&.freeze, closed.freeze
17
+ freeze
18
+ end
19
+ def chain = open_sd_jwt ? open_sd_jwt.chomp("~") + "~~" + closed_sd_jwt : closed_sd_jwt
20
+ private_class_method :new
21
+ end
22
+ class Verification
23
+ attr_reader :code, :payment, :reference, :expires_at
24
+ def initialize(payment = nil, wire = nil)
25
+ @code = payment ? :payment_verified : :payment_verification_failed
26
+ if payment
27
+ @payment = ResearchEvidence.send(:copy_frozen, payment)
28
+ @reference = Payment.send(:digest, wire).freeze
29
+ @expires_at = payment.fetch("exp")
30
+ end
31
+ freeze
32
+ end
33
+ def verified? = code == :payment_verified
34
+ private_class_method :new
35
+ end
36
+
37
+ # Checkout JWT and key must be from independently trusted application state.
38
+ # This prepares data, not consent or a verified Checkout Mandate.
39
+ def self.details(checkout_jwt:, trusted_merchant_public_key_pem:, expected_merchant_id:, payment_instrument:)
40
+ checked = CheckoutJWT.verify(jwt: checkout_jwt, trusted_public_key_pem: trusted_merchant_public_key_pem,
41
+ expected_merchant_id: expected_merchant_id, profile_ref: ScopedConstraints::MULTI_PROFILE_REF)
42
+ instrument = InputBuilder.send(:copy!, payment_instrument)
43
+ instrument!(instrument)
44
+ ResearchEvidence.send(:copy_frozen, {"transaction_id" => checked.checkout_hash,
45
+ "payee" => checked.checkout.fetch("merchant"), "payment_instrument" => instrument,
46
+ "payment_amount" => {"currency" => checked.checkout.fetch("currency"),
47
+ "amount" => ScopedConstraints.multi_checkout!(checked.checkout)}})
48
+ end
49
+
50
+ # Protected approval record must cover every payment detail, not just amount.
51
+ def self.issue_direct(payment:, approved_payment:, issued_at:, expires_at:, signer:, public_key_pem:)
52
+ value = copy_details!(payment)
53
+ raise Invalid unless value == copy_details!(approved_payment)
54
+ closed = value.merge("vct" => "mandate.payment.1", "iat" => issued_at, "exp" => expires_at)
55
+ closed!(closed)
56
+ Presentation.send(:new, nil, sign_root!(closed, signer, public_key_pem))
57
+ end
58
+
59
+ # Reference is calculated over exact original Open Checkout, never rebuilt JSON.
60
+ # The app authenticates consent to these conditions before invoking this API.
61
+ def self.issue_open(open_checkout_sd_jwt:, constraints:, fixed:, agent_public_key_pem:,
62
+ issued_at:, expires_at:, signer:, public_key_pem:)
63
+ RootSignature.send(:dependencies!)
64
+ root = checkout_open!(open_checkout_sd_jwt)
65
+ conditions = InputBuilder.send(:copy!, constraints)
66
+ raise Invalid unless conditions.instance_of?(Array)
67
+ conditions << {"type" => "payment.reference", "conditional_transaction_id" => digest(root)}
68
+ value = InputBuilder.send(:copy!, fixed)
69
+ raise Invalid unless value.instance_of?(Hash) && (value.keys - FIELDS.drop(1)).empty?
70
+ opening = value.merge("vct" => "mandate.payment.open.1", "iat" => issued_at, "exp" => expires_at,
71
+ "cnf" => {"jwk" => RootSignature.public_jwk!(agent_public_key_pem)}, "constraints" => conditions)
72
+ open!(opening)
73
+ sign_root!(opening, signer, public_key_pem).freeze
74
+ end
75
+
76
+ # Provider signer is deliberately absent. Existing signed Open grants the hop.
77
+ def self.issue_closed(open_sd_jwt:, payment:, trusted_provider_public_key_pem:, agent_public_key_pem:,
78
+ audience:, nonce:, verified_at:, signer:)
79
+ opening, root = verified_root!(open_sd_jwt, trusted_provider_public_key_pem)
80
+ open!(opening); valid_now!(opening, verified_at)
81
+ raise Invalid unless opening.fetch("cnf") == {"jwk" => RootSignature.public_jwk!(agent_public_key_pem)}
82
+ value = copy_details!(payment).merge("vct" => "mandate.payment.1", "iat" => verified_at, "exp" => opening.fetch("exp"))
83
+ closed!(value); conditions!(opening, value)
84
+ audience = InputValidator.snapshot!(audience, max_bytes: 512)
85
+ nonce = InputValidator.snapshot!(nonce, max_bytes: 512)
86
+ text!(audience, 512); text!(nonce, 512)
87
+ claims = {"delegate_payload" => [value], "iat" => verified_at,
88
+ "aud" => audience, "nonce" => nonce, "sd_hash" => digest(root)}
89
+ preflight!(claims, "kb+sd-jwt")
90
+ terminal = MerchantSignature.sign!(claims, signer, agent_public_key_pem, typ: "kb+sd-jwt")
91
+ Presentation.send(:new, root, terminal + "~")
92
+ end
93
+
94
+ # Original-byte restoration only. All authentication belongs to verify.
95
+ def self.present(closed_sd_jwt:, open_sd_jwt: nil)
96
+ closed, wire = final!(closed_sd_jwt, conditional: !open_sd_jwt.nil?)
97
+ closed!(closed.fetch("delegate_payload").first)
98
+ if open_sd_jwt
99
+ opening, root = root!(open_sd_jwt)
100
+ open!(opening)
101
+ raise Invalid unless closed.fetch("sd_hash") == digest(root)
102
+ conditions!(opening, closed.fetch("delegate_payload").first)
103
+ end
104
+ Presentation.send(:new, open_sd_jwt && root, wire)
105
+ end
106
+
107
+ # checkout_inputs are the complete EXISTING public verifier kwargs, supplied
108
+ # by the application, never taken from received Payment claims.
109
+ # Direct uses Buyer.verify; conditional uses verify_checkout's seven inputs.
110
+ def self.verify(closed_sd_jwt:, checkout_mode:, checkout_inputs:, expected_payment:,
111
+ trusted_provider_public_key_pem:, verified_at:, open_sd_jwt: nil,
112
+ expected_agent_public_key_pem: nil, expected_audience: nil, expected_nonce: nil)
113
+ CheckoutReceipt.send(:epoch!, verified_at)
114
+ raise Invalid unless checkout_inputs.instance_of?(Hash) && checkout_inputs[:verified_at] == verified_at
115
+ fields = case checkout_mode
116
+ when :direct then %i[closed_sd_jwt trusted_provider_public_key_pem trusted_merchant_public_key_pem expected_checkout_jwt expected_merchant_id verified_at]
117
+ when :conditional then %i[trust_json selection_json host_json root_presentation terminal_jws host_checkout_jws verified_at]
118
+ else raise Invalid
119
+ end
120
+ raise Invalid unless checkout_inputs.size == fields.size && fields.all? { |f| checkout_inputs.key?(f) }
121
+ limits = {closed_sd_jwt: 32_768, trusted_provider_public_key_pem: 1_024,
122
+ trusted_merchant_public_key_pem: 1_024, expected_checkout_jwt: 16_384, expected_merchant_id: 512,
123
+ host_json: 32_768, terminal_jws: 32_768, host_checkout_jws: 16_384}
124
+ checkout_inputs = checkout_inputs.to_h do |key, value|
125
+ [key, key == :verified_at ? value : InputValidator.snapshot!(value, max_bytes: limits.fetch(key, 131_072))]
126
+ end.freeze
127
+ expected = copy_details!(expected_payment)
128
+ case checkout_mode
129
+ when :direct
130
+ raise Invalid if open_sd_jwt || expected_agent_public_key_pem || expected_audience || expected_nonce
131
+ checked = Buyer.verify(**checkout_inputs)
132
+ raise Invalid unless checked.verified? && expected.fetch("transaction_id") == checked.checkout_hash
133
+ bind_checkout!(expected, checked.checkout)
134
+ claims, wire = verified_root!(closed_sd_jwt, trusted_provider_public_key_pem)
135
+ when :conditional
136
+ checked = AP2MandateVerifier.verify_checkout(**checkout_inputs)
137
+ raise Invalid unless checked.success?
138
+ checkout = checkout_inputs.fetch(:host_checkout_jws)
139
+ raise Invalid unless expected.fetch("transaction_id") == digest(checkout)
140
+ # Fully verified Host evidence binds independent Merchant order state.
141
+ binding = checked.evidence["checkout_binding"]
142
+ amount = expected.fetch("payment_amount")
143
+ raise Invalid unless expected.fetch("payee").fetch("id") == binding.fetch("merchant_id") &&
144
+ amount.fetch("currency") == binding.fetch("currency") && amount.fetch("amount") == binding.fetch("expected_total")
145
+ # Full Checkout verifier already authenticated these exact JWT bytes.
146
+ payload = jwt_payload!(checkout, "JWT")
147
+ bind_checkout!(expected, payload)
148
+ opening, root = verified_root!(open_sd_jwt, trusted_provider_public_key_pem)
149
+ open!(opening); valid_now!(opening, verified_at)
150
+ raise Invalid unless opening.fetch("cnf") == {"jwk" => RootSignature.public_jwk!(expected_agent_public_key_pem)}
151
+ terminal, wire = final!(closed_sd_jwt, conditional: true)
152
+ RootSignature.verified_payload!(wire.split("~", -1).first, expected_agent_public_key_pem,
153
+ expected_typ: "kb+sd-jwt", max_bytes: 32_768)
154
+ expected_audience = InputValidator.snapshot!(expected_audience, max_bytes: 512)
155
+ expected_nonce = InputValidator.snapshot!(expected_nonce, max_bytes: 512)
156
+ text!(expected_audience, 512); text!(expected_nonce, 512)
157
+ raise Invalid unless terminal.fetch("aud") == expected_audience && terminal.fetch("nonce") == expected_nonce &&
158
+ terminal.fetch("sd_hash") == digest(root) && terminal.fetch("iat") <= verified_at &&
159
+ verified_at - terminal.fetch("iat") <= 300
160
+ claims = terminal.fetch("delegate_payload").first
161
+ closed!(claims); valid_now!(claims, verified_at)
162
+ raise Invalid unless terminal.fetch("iat") == claims.fetch("iat") && claims.fetch("iat") >= opening.fetch("iat") &&
163
+ claims.fetch("exp") <= opening.fetch("exp")
164
+ conditions!(opening, claims)
165
+ reference = opening.fetch("constraints").find { |c| c["type"] == "payment.reference" }
166
+ raise Invalid unless reference.fetch("conditional_transaction_id") == digest(checkout_inputs.fetch(:root_presentation))
167
+ else raise Invalid
168
+ end
169
+ closed!(claims); valid_now!(claims, verified_at)
170
+ raise Invalid unless claims.slice(*FIELDS) == expected
171
+ Verification.send(:new, claims, wire)
172
+ rescue StandardError, LoadError
173
+ Verification.send(:new)
174
+ end
175
+
176
+ def self.reference(closed_sd_jwt:)
177
+ # No trust or authorization claim: parse either supported final grammar.
178
+ wire = InputValidator.snapshot!(closed_sd_jwt, max_bytes: 32_769)
179
+ payload = jwt_payload!(wire.split("~", -1).first, nil)
180
+ conditional = payload.key?("sd_hash")
181
+ final, original = final!(wire, conditional: conditional)
182
+ closed!(final.fetch("delegate_payload").first)
183
+ digest(original).freeze
184
+ end
185
+
186
+ def self.bind_checkout!(value, checkout)
187
+ raise Invalid unless value.fetch("payee") == checkout.fetch("merchant") &&
188
+ value.fetch("payment_amount") == {"currency" => checkout.fetch("currency"),
189
+ "amount" => ScopedConstraints.multi_checkout!(checkout)}
190
+ end
191
+ def self.copy_details!(value)
192
+ value = InputBuilder.send(:copy!, value)
193
+ exact!(value, FIELDS)
194
+ raise Invalid unless value["transaction_id"].instance_of?(String) && value["transaction_id"].match?(/\A[A-Za-z0-9_-]{43}\z/)
195
+ payee!(value["payee"]); amount!(value["payment_amount"]); instrument!(value["payment_instrument"])
196
+ value
197
+ end
198
+ def self.closed!(value)
199
+ exact!(value, FIELDS + %w[vct iat exp])
200
+ raise Invalid unless value["vct"] == "mandate.payment.1"
201
+ copy_details!(value.slice(*FIELDS)); times!(value)
202
+ end
203
+ def self.open!(value)
204
+ raise Invalid unless value.instance_of?(Hash) && (value.keys - FIELDS.drop(1) - %w[vct iat exp cnf constraints]).empty?
205
+ raise Invalid unless value["vct"] == "mandate.payment.open.1"
206
+ times!(value); exact!(value["cnf"], ["jwk"])
207
+ jwk = value["cnf"]["jwk"]
208
+ exact!(jwk, %w[kty crv x y])
209
+ raise Invalid unless jwk["kty"] == "EC" && jwk["crv"] == "P-256" &&
210
+ %w[x y].all? { |f| RootSignature.send(:decode!, jwk[f], 32).bytesize == 32 }
211
+ payee!(value["payee"]) if value.key?("payee")
212
+ amount!(value["payment_amount"]) if value.key?("payment_amount")
213
+ instrument!(value["payment_instrument"]) if value.key?("payment_instrument")
214
+ cs = value["constraints"]
215
+ raise Invalid unless cs.instance_of?(Array) && cs.size == 4 && cs.all? { |c| c.instance_of?(Hash) }
216
+ raise Invalid unless cs.map { |c| c["type"] }.sort == %w[payment.allowed_payees payment.allowed_payment_instruments payment.amount_range payment.reference].sort
217
+ cs.each do |c|
218
+ case c["type"]
219
+ when "payment.reference"
220
+ exact!(c, %w[type conditional_transaction_id])
221
+ raise Invalid unless c["conditional_transaction_id"].instance_of?(String) && c["conditional_transaction_id"].match?(/\A[A-Za-z0-9_-]{43}\z/)
222
+ when "payment.amount_range"
223
+ raise Invalid unless c.keys.sort == %w[currency max min type].sort || c.keys.sort == %w[currency max type].sort
224
+ amount!({"amount" => c["max"], "currency" => c["currency"]})
225
+ amount!({"amount" => c.fetch("min", 0), "currency" => c["currency"]})
226
+ raise Invalid unless c.fetch("min", 0) <= c["max"]
227
+ else
228
+ exact!(c, %w[type allowed])
229
+ raise Invalid unless c["allowed"].instance_of?(Array) && c["allowed"].size.between?(1, 8) && c["allowed"].uniq.size == c["allowed"].size
230
+ c["allowed"].each { |item| c["type"] == "payment.allowed_payees" ? payee!(item) : instrument!(item) }
231
+ end
232
+ end
233
+ end
234
+ def self.conditions!(opening, closed)
235
+ FIELDS.drop(1).each { |f| raise Invalid if opening.key?(f) && opening[f] != closed[f] }
236
+ opening.fetch("constraints").each do |c|
237
+ case c["type"]
238
+ when "payment.allowed_payees" then raise Invalid unless c["allowed"].include?(closed["payee"])
239
+ when "payment.allowed_payment_instruments" then raise Invalid unless c["allowed"].include?(closed["payment_instrument"])
240
+ when "payment.amount_range"
241
+ a = closed.fetch("payment_amount")
242
+ raise Invalid unless a["currency"] == c["currency"] && a["amount"].between?(c.fetch("min", 0), c["max"])
243
+ when "payment.reference" # Checked against the verified Checkout chain in verify.
244
+ else raise Invalid
245
+ end
246
+ end
247
+ end
248
+ def self.payee!(v)
249
+ raise Invalid unless v.instance_of?(Hash) && [%w[id name], %w[id name website]].include?(v.keys.sort)
250
+ v.each_value { |s| text!(s, 512) }
251
+ end
252
+ def self.instrument!(v)
253
+ raise Invalid unless v.instance_of?(Hash) && [%w[id type], %w[description id type]].include?(v.keys.sort)
254
+ v.each_value { |s| text!(s, 512) }
255
+ end
256
+ def self.amount!(v)
257
+ exact!(v, %w[amount currency])
258
+ ScopedConstraints.send(:amount!, v["amount"])
259
+ raise Invalid unless ScopedConstraints::CURRENCIES.include?(v["currency"])
260
+ end
261
+ def self.times!(v)
262
+ %w[iat exp].each { |f| CheckoutReceipt.send(:epoch!, v[f]) }
263
+ raise Invalid unless v["exp"] > v["iat"] && v["exp"] - v["iat"] <= MAX_LIFETIME
264
+ end
265
+ def self.valid_now!(v, now)
266
+ CheckoutReceipt.send(:epoch!, now)
267
+ raise Invalid unless v.fetch("iat") <= now && now < v.fetch("exp")
268
+ end
269
+ def self.checkout_open!(wire)
270
+ wire = InputValidator.snapshot!(wire)
271
+ opening = RootDisclosures.send(:structural_root!, wire).fetch("delegate_payload").first
272
+ raise Invalid unless opening.fetch("vct") == "mandate.checkout.open.1"
273
+ wire
274
+ end
275
+ def self.jwt_payload!(jwt, typ)
276
+ RootSignature.send(:dependencies!)
277
+ parts = jwt.split(".", -1)
278
+ raise Invalid unless parts.size == 3
279
+ h = InputValidator.parse!(RootSignature.send(:decode!, parts[0], 2_048))
280
+ CheckoutReceipt.send(:header!, h, typ || h["typ"])
281
+ raise Invalid unless RootSignature.send(:decode!, parts[2], 64).bytesize == 64
282
+ InputValidator.parse!(RootSignature.send(:decode!, parts[1], 24_576))
283
+ end
284
+ def self.final!(source, conditional:)
285
+ wire = InputValidator.snapshot!(source, max_bytes: 32_769)
286
+ raise Invalid unless wire.ascii_only? && wire.end_with?("~") && [1, 2].include?(wire.count("~"))
287
+ compact, *parts = wire.split("~", -1)
288
+ parts.pop
289
+ claims = jwt_payload!(compact, conditional ? "kb+sd-jwt" : "example+sd-jwt")
290
+ fields = conditional ? %w[delegate_payload iat aud nonce sd_hash] : %w[delegate_payload _sd_alg]
291
+ fields += ["_sd_alg"] if conditional && claims.key?("_sd_alg")
292
+ exact!(claims, fields)
293
+ raise Invalid if claims.key?("_sd_alg") && claims["_sd_alg"] != "sha-256"
294
+ if conditional
295
+ text!(claims["aud"], 512); text!(claims["nonce"], 512)
296
+ CheckoutReceipt.send(:epoch!, claims["iat"])
297
+ raise Invalid unless claims["sd_hash"].instance_of?(String) && claims["sd_hash"].match?(/\A[A-Za-z0-9_-]{43}\z/)
298
+ else
299
+ raise Invalid unless claims["_sd_alg"] == "sha-256"
300
+ end
301
+ raise Invalid unless claims["delegate_payload"].instance_of?(Array) && claims["delegate_payload"].size == 1
302
+ unless parts.empty?
303
+ disclosure = parts.fetch(0)
304
+ pointer = claims["delegate_payload"].first
305
+ exact!(pointer, ["..."])
306
+ raise Invalid unless pointer["..."] == digest(disclosure)
307
+ value = Buyer.send(:decode_disclosure!, disclosure, 2)
308
+ claims = claims.merge("delegate_payload" => [value[1]])
309
+ end
310
+ [claims, wire]
311
+ end
312
+ def self.root!(source)
313
+ claims, wire = final!(source, conditional: false)
314
+ [claims.fetch("delegate_payload").first, wire]
315
+ end
316
+ def self.verified_root!(source, key)
317
+ value, wire = root!(source)
318
+ RootSignature.verified_payload!(wire.split("~", -1).first, key, max_bytes: 32_768)
319
+ [value, wire]
320
+ end
321
+ def self.sign_root!(value, signer, key)
322
+ RootSignature.send(:dependencies!)
323
+ require "securerandom"
324
+ disclosure = Buyer.send(:encode, [Buyer.send(:encode, SecureRandom.random_bytes(16)), value])
325
+ claims = {"delegate_payload" => [{"..." => digest(disclosure)}], "_sd_alg" => "sha-256"}
326
+ preflight!(claims, "example+sd-jwt", disclosure)
327
+ wire = MerchantSignature.sign!(claims, signer, key,
328
+ typ: "example+sd-jwt") + "~" + disclosure + "~"
329
+ final!(wire, conditional: false)
330
+ wire
331
+ end
332
+ def self.preflight!(claims, typ, disclosure = nil)
333
+ # Bound every new Mandate signature before remote signer effects. ES256
334
+ # signatures have a fixed 64-byte width; this performs no cryptography.
335
+ compact = [Buyer.send(:encode, {"alg" => "ES256", "typ" => typ}),
336
+ Buyer.send(:encode, claims), Buyer.send(:encode, "\0" * 64)].join(".")
337
+ wire = compact + "~" + (disclosure ? disclosure + "~" : "")
338
+ final!(wire, conditional: typ == "kb+sd-jwt")
339
+ end
340
+ def self.digest(wire) = Base64.urlsafe_encode64(Digest::SHA256.digest(wire), padding: false)
341
+ def self.exact!(v, fields) = PurchaseBinding.send(:exact!, v, fields)
342
+ def self.text!(v, max) = CheckoutReceipt.send(:text!, v, max)
343
+
344
+ # Fixed redacted exceptions and keyword rejection on every new entry.
345
+ %i[details issue_direct issue_open issue_closed present reference verify].each do |name|
346
+ implementation = method(name)
347
+ required = implementation.parameters.filter_map { |kind, field| field if kind == :keyreq }.freeze
348
+ fields = implementation.parameters.map(&:last).freeze
349
+ define_singleton_method(name) do |**args|
350
+ unless (required - args.keys).empty? && (args.keys - fields).empty?
351
+ next Verification.send(:new) if name == :verify
352
+ raise Invalid
353
+ end
354
+ implementation.call(**args)
355
+ rescue StandardError, LoadError
356
+ raise Invalid.new, cause: nil
357
+ end
358
+ end
359
+ singleton_methods(false).reject { |n| %i[details issue_direct issue_open issue_closed present verify reference].include?(n) }.each { |n| private_class_method n }
360
+ end
361
+ end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Authenticity and reported outcome are separate. No automatic success/retry.
5
+ module PaymentReceipt
6
+ class Invalid < ArgumentError
7
+ def initialize = super("invalid payment 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, :payment_id, :psp_confirmation_id, :network_confirmation_id, :error, :error_description
19
+ def initialize(claims = nil)
20
+ @code = claims ? :payment_receipt_verified : :payment_receipt_verification_failed
21
+ if claims
22
+ @outcome, @payment_id, @psp_confirmation_id, @network_confirmation_id, @error, @error_description =
23
+ claims.values_at("status", "payment_id", "psp_confirmation_id", "network_confirmation_id", "error", "error_description").map { |s| s&.freeze }
24
+ end
25
+ freeze
26
+ end
27
+ def verified? = code == :payment_receipt_verified
28
+ def payment_succeeded? = verified? && outcome == "Success"
29
+ def payment_rejected? = verified? && outcome == "Error"
30
+ private_class_method :new
31
+ end
32
+ def self.reference(closed_sd_jwt:) = Payment.reference(closed_sd_jwt: closed_sd_jwt)
33
+ def self.sign(closed_sd_jwt:, issuer:, outcome:, payment_id:, issued_at:, signer:, public_key_pem:,
34
+ psp_confirmation_id: nil, network_confirmation_id: nil, error: nil, error_description: nil)
35
+ ref = reference(closed_sd_jwt: closed_sd_jwt)
36
+ claims = {"iss" => issuer, "status" => outcome, "payment_id" => payment_id, "iat" => issued_at, "reference" => ref}
37
+ {"psp_confirmation_id" => psp_confirmation_id, "network_confirmation_id" => network_confirmation_id,
38
+ "error" => error, "error_description" => error_description}.each { |k, v| claims[k] = v unless v.nil? }
39
+ claims = InputBuilder.send(:copy!, claims)
40
+ validate!(claims)
41
+ Signed.send(:new, MerchantSignature.sign!(claims, signer, public_key_pem), ref)
42
+ end
43
+ def self.verify(jwt:, closed_sd_jwt:, trusted_public_key_pem:, expected_issuer:, expected_payment_id:,
44
+ not_before:, not_after:, verified_at:)
45
+ [not_before, not_after, verified_at].each { |t| CheckoutReceipt.send(:epoch!, t) }
46
+ raise Invalid unless not_before <= verified_at && verified_at <= not_after
47
+ expected = InputValidator.snapshot!(expected_issuer, max_bytes: 512)
48
+ id = InputValidator.snapshot!(expected_payment_id, max_bytes: 512)
49
+ text!(expected, 512); text!(id, 512)
50
+ ref = reference(closed_sd_jwt: closed_sd_jwt)
51
+ claims = RootSignature.verified_payload!(jwt, trusted_public_key_pem, expected_typ: "JWT", max_bytes: 16_384)
52
+ validate!(claims)
53
+ raise Invalid unless claims["iss"] == expected && claims["payment_id"] == id && claims["reference"] == ref &&
54
+ claims["iat"].between?(not_before, verified_at)
55
+ Verification.send(:new, claims)
56
+ rescue StandardError, LoadError
57
+ Verification.send(:new)
58
+ end
59
+ def self.validate!(claims)
60
+ fields = %w[iss status iat reference payment_id] + case claims["status"]
61
+ when "Success" then %w[psp_confirmation_id network_confirmation_id]
62
+ when "Error" then %w[error error_description]
63
+ else raise Invalid
64
+ end
65
+ PurchaseBinding.send(:exact!, claims, fields)
66
+ CheckoutReceipt.send(:epoch!, claims["iat"])
67
+ (fields - ["iat"]).each { |f| text!(claims[f], f == "error_description" ? 2_048 : 512) }
68
+ raise Invalid unless claims["reference"].match?(/\A[A-Za-z0-9_-]{43}\z/)
69
+ end
70
+ def self.text!(v, max) = CheckoutReceipt.send(:text!, v, max)
71
+ %i[reference sign verify].each do |name|
72
+ implementation = method(name)
73
+ required = implementation.parameters.filter_map { |kind, field| field if kind == :keyreq }.freeze
74
+ fields = implementation.parameters.map(&:last).freeze
75
+ define_singleton_method(name) do |**args|
76
+ unless (required - args.keys).empty? && (args.keys - fields).empty?
77
+ next Verification.send(:new) if name == :verify
78
+ raise Invalid
79
+ end
80
+ implementation.call(**args)
81
+ rescue StandardError, LoadError
82
+ raise Invalid.new, cause: nil
83
+ end
84
+ end
85
+ private_class_method :validate!, :text!
86
+ end
87
+ end
@@ -15,6 +15,8 @@ require_relative "ap2_mandate_verifier/checkout_jwt"
15
15
  require_relative "ap2_mandate_verifier/checkout_receipt"
16
16
  require_relative "ap2_mandate_verifier/buyer"
17
17
  require_relative "ap2_mandate_verifier/conditional_checkout"
18
+ require_relative "ap2_mandate_verifier/payment"
19
+ require_relative "ap2_mandate_verifier/payment_receipt"
18
20
 
19
21
  module AP2MandateVerifier
20
22
  # Accepts original JSON bytes only. Syntax validity is not AP2 validity,
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ap2_mandate_verifier
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.0
4
+ version: 1.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - AP2 Mandate Verifier contributors
8
8
  bindir: bin
9
9
  cert_chain: []
10
- date: 2026-11-01 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: json
@@ -81,9 +81,9 @@ dependencies:
81
81
  version: 3.2.1
82
82
  description: 'Framework-independent Ruby SDK for supported AP2 Checkout profiles:
83
83
  Merchant JWT signing, Direct and conditional Mandate issuance and presentation,
84
- full verification with immutable Evidence, and Checkout Receipt signing and verification.
85
- Requires independently trusted application inputs; verification does not grant purchase
86
- or payment permission.'
84
+ full verification with immutable Evidence, Checkout Receipts, Direct and conditional
85
+ Payment Mandates, and Payment Receipts. Requires independently trusted application
86
+ inputs; verification does not grant purchase or payment permission.'
87
87
  executables: []
88
88
  extensions: []
89
89
  extra_rdoc_files: []
@@ -99,11 +99,14 @@ files:
99
99
  - docs/INPUT_BUILDER.md
100
100
  - docs/MERCHANT_SIGNING.md
101
101
  - docs/MULTI_ITEM_CHECKOUT.md
102
+ - docs/PAYMENT.md
102
103
  - docs/POST_RELEASE_MAINTENANCE.md
103
104
  - docs/PUBLIC_API.md
104
105
  - docs/RELEASE_100_CANDIDATE.md
106
+ - docs/RELEASE_110_CANDIDATE.md
105
107
  - docs/SUPPORT_CONTRACT.md
106
108
  - examples/conditional_checkout.rb
109
+ - examples/payment.rb
107
110
  - lib/ap2_mandate_verifier.rb
108
111
  - lib/ap2_mandate_verifier/buyer.rb
109
112
  - lib/ap2_mandate_verifier/checkout_jwt.rb
@@ -114,6 +117,8 @@ files:
114
117
  - lib/ap2_mandate_verifier/input_builder.rb
115
118
  - lib/ap2_mandate_verifier/input_validator.rb
116
119
  - lib/ap2_mandate_verifier/merchant_signature.rb
120
+ - lib/ap2_mandate_verifier/payment.rb
121
+ - lib/ap2_mandate_verifier/payment_receipt.rb
117
122
  - lib/ap2_mandate_verifier/purchase_binding.rb
118
123
  - lib/ap2_mandate_verifier/research_result.rb
119
124
  - lib/ap2_mandate_verifier/result.rb
@@ -142,7 +147,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
142
147
  - !ruby/object:Gem::Version
143
148
  version: '0'
144
149
  requirements: []
145
- rubygems_version: 3.6.9
150
+ rubygems_version: 4.0.20
146
151
  specification_version: 4
147
- summary: Ruby SDK for supported AP2 Checkout Mandates
152
+ summary: Ruby SDK for supported AP2 Checkout and Payment Mandates
148
153
  test_files: []