ap2_mandate_verifier 0.8.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.
@@ -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,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ap2_mandate_verifier
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.8.0
4
+ version: 1.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - AP2 Mandate Verifier contributors
@@ -79,10 +79,11 @@ dependencies:
79
79
  - - '='
80
80
  - !ruby/object:Gem::Version
81
81
  version: 3.2.1
82
- description: Stateless verification of the fixed AP2 profile with immutable Evidence
83
- using verify_checkout and the retained verify_research API. Requires trusted Host
84
- inputs and the documented runtime; not Host authorization, payment permission or
85
- general AP2 conformance.
82
+ description: 'Framework-independent Ruby SDK for supported AP2 Checkout profiles:
83
+ Merchant JWT signing, Direct and conditional Mandate issuance and presentation,
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.'
86
87
  executables: []
87
88
  extensions: []
88
89
  extra_rdoc_files: []
@@ -90,15 +91,22 @@ files:
90
91
  - LICENSE
91
92
  - README.ja.md
92
93
  - README.md
94
+ - SECURITY.md
93
95
  - docs/BUYER_DIRECT_CHECKOUT.md
94
96
  - docs/CONDITIONAL_CHECKOUT.md
95
97
  - docs/DIAGNOSTICS.ja.md
96
98
  - docs/DIAGNOSTICS.md
99
+ - docs/INPUT_BUILDER.md
97
100
  - docs/MERCHANT_SIGNING.md
98
101
  - docs/MULTI_ITEM_CHECKOUT.md
99
- - docs/RELEASE_080_CANDIDATE.md
102
+ - docs/PAYMENT.md
103
+ - docs/POST_RELEASE_MAINTENANCE.md
104
+ - docs/PUBLIC_API.md
105
+ - docs/RELEASE_100_CANDIDATE.md
106
+ - docs/RELEASE_110_CANDIDATE.md
100
107
  - docs/SUPPORT_CONTRACT.md
101
108
  - examples/conditional_checkout.rb
109
+ - examples/payment.rb
102
110
  - lib/ap2_mandate_verifier.rb
103
111
  - lib/ap2_mandate_verifier/buyer.rb
104
112
  - lib/ap2_mandate_verifier/checkout_jwt.rb
@@ -109,6 +117,8 @@ files:
109
117
  - lib/ap2_mandate_verifier/input_builder.rb
110
118
  - lib/ap2_mandate_verifier/input_validator.rb
111
119
  - lib/ap2_mandate_verifier/merchant_signature.rb
120
+ - lib/ap2_mandate_verifier/payment.rb
121
+ - lib/ap2_mandate_verifier/payment_receipt.rb
112
122
  - lib/ap2_mandate_verifier/purchase_binding.rb
113
123
  - lib/ap2_mandate_verifier/research_result.rb
114
124
  - lib/ap2_mandate_verifier/result.rb
@@ -137,7 +147,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
137
147
  - !ruby/object:Gem::Version
138
148
  version: '0'
139
149
  requirements: []
140
- rubygems_version: 3.6.9
150
+ rubygems_version: 4.0.20
141
151
  specification_version: 4
142
- summary: Fixed-profile AP2 verification for Ruby
152
+ summary: Ruby SDK for supported AP2 Checkout and Payment Mandates
143
153
  test_files: []
@@ -1,109 +0,0 @@
1
- # 0.8.0 candidate — conditional Checkout delegation, unpublished
2
-
3
- Compatible feature release preparation for approved conditional purchasing:
4
- `ConditionalCheckout.issue_open` → Agent `.issue_closed` → `.present` → existing
5
- full `InputBuilder.verify` → `CheckoutReceipt.sign/verify`. The installed
6
- [standalone example](../examples/conditional_checkout.rb) uses A/B×1 and C×2,
7
- three rows and repeated C products. [API/specification](CONDITIONAL_CHECKOUT.md).
8
-
9
- Published stable remains 0.7.0, verified from the official RubyGems versions API
10
- on 2026-11-01; 0.8.0 is absent, so no version-plan collision is currently observed.
11
- 0.7.0 source/tag is `9b4b78a7ed9aa95e7d35e01a64efc1281ba95be3`; its published
12
- 64,000-byte SHA256 is `baab8c68355b5e6c9351e7d86a836fab50652cdad662bbc99d1676c5e6134447`.
13
- Current base main is `50f9639a4fe316556189088ab6b737a642f5f6e2`, initially no open PRs.
14
- No verified prior artifact or previous task checkout was modified.
15
-
16
- ## Validation and compatibility
17
-
18
- All 17 source-suite entry points pass offline on MRI 3.4.12 and 4.0.9. Existing
19
- regression includes Direct, both old profiles, signed missing/unknown/duplicate
20
- disclosures, original-wire binding, InputBuilder save/restore, Result/Evidence,
21
- diagnostics and Receipt outcomes. New tests add 8 cases (123 assertions on MRI
22
- 3.4.12 / 126 on MRI 4.0.9, including installed-Gem execution) for
23
- issuance, sign-before-check prevention, bounds, 8×8 candidate/requirement cases,
24
- same-product separate rows, wrong keys/time/audience/nonce, restoration closure,
25
- and exact final Closed Receipt reference. A long-ID/title eight-row Checkout
26
- also completes through the larger existing Agent-terminal bounds while Merchant
27
- JWT and Direct signing bounds remain unchanged. Suite counts include shared legacy
28
- dependencies; no misleading aggregate of repeated assertion counters is claimed.
29
-
30
- Official pinned Python comparison passes for signatures in both directions,
31
- Open/Closed/Checkout/Receipt Schemas, complete Open commitments and normative
32
- sd_hash including final `~`, both receipt outcomes and negative controls. SDK
33
- high-level Closed helper emits an unsupported SD form; it is a rejection control,
34
- not claimed accepted interoperability. Existing max-flow shortage/empty-candidate
35
- differences and compact-only Receipt helper remain documented and fail closed.
36
-
37
- Candidate Gem identity, corresponding final source SHA, payload hashes, byte size,
38
- ordinary installation on both Rubies and exact example output are recorded in the
39
- external candidate manifest beside the Gem. The Gem includes both READMEs, this
40
- decision document, the API contract and the standalone example. Dependencies and
41
- supported MRI versions are unchanged; old callers require no migration.
42
-
43
- ## Review and external-operation status
44
-
45
- Initial independent Codex review found one substantive P2 (restoration Root
46
- closure); fixed through shared structural parsing and signed negative regression.
47
- GitHub review additionally found that the Merchant signing helper's 12,000-byte
48
- claims / 16,384-byte JWS limits prevented valid larger Agent terminals. KB terminal
49
- signing now uses its existing verifier's 24,576-byte payload / 32,768-byte wire
50
- bounds only; JWT and Direct retain the old limits. Long-ID/title eight-row Ruby
51
- and official Python signature/Schema/hash regressions exercise this fix.
52
- Latest-HEAD independent review must be completed and identified in the external
53
- verification report. Review no-findings alone is not a security proof.
54
-
55
- Initial Draft PR branch push was denied by automatic approval review before
56
- execution. Owner subsequently explicitly authorized the specified commit/branch
57
- push, Draft PR, existing-budget CI, latest-HEAD Codex review/fixes and conditional
58
- Squash Merge at 2026-11-01 14:41 JST. The branch was pushed and
59
- [Draft PR #231](https://github.com/cuichangquan/ap2-mandate-verifier/pull/231)
60
- created. No alternate route bypassed the denial; authorization resolved it first.
61
- No owner approval review is submitted. Current exact-HEAD review, CI and merge
62
- results are recorded in that PR and the external final verification report.
63
- Only existing `merchant-source-package.yml` is expected to trigger for this diff:
64
- two MRI jobs in one workflow run, existing Ubuntu runner/15-minute job timeout,
65
- public dependencies, no secrets, extra cost zero. No workflow edits. Issue #101's
66
- maximum 3 runs/PR is a ceiling, no blind reruns; the PR records every consumed run.
67
-
68
- ## Build and final candidate evidence
69
-
70
- Use the final committed tree, existing pinned Docker images and no network:
71
-
72
- ```sh
73
- gem build ap2_mandate_verifier.gemspec --output /out/ap2_mandate_verifier-0.8.0.gem
74
- sh scripts/check_candidate_package.sh /out/package /out/ap2_mandate_verifier-0.8.0.gem
75
- ```
76
-
77
- Run source regression with `sh scripts/check_ruby_compatibility.sh /out/source`.
78
- The packaging script installs the **same** built Gem with normal RubyGems
79
- resolution (`gem install --local`), audits every source/archive/installed payload,
80
- then executes detached old APIs and the example physically inside the installed
81
- Gem. Reuse one artifact across both MRI runtimes. Do not substitute an earlier
82
- working-tree package or rebuild a lookalike after approval. Exact source SHA and
83
- Gem SHA cannot be embedded recursively in their own bytes; use external manifest.
84
-
85
- ## Publication decision and recovery plan
86
-
87
- 1. Review final source SHA, strict latest-HEAD review, all tests/independent
88
- comparison, exact candidate manifest and remaining GitHub PR/CI gates.
89
- 2. Obtain separate Owner authorization for that exact Gem publication; **no push,
90
- public tag or GitHub Release is authorized by this request**.
91
- 3. After explicit authorization only, RubyGems push the approved exact artifact,
92
- fetch the official distribution and compare bytes/SHA/size and every payload.
93
- 4. Only under publication/tag/Release authorization, bind `v0.8.0` to its verified
94
- source, publish release notes and update stable install guides/demo after the
95
- registry version is actually available. A candidate README is not publication.
96
- 5. On mismatch, invalid dependency/content, signature or material regression,
97
- stop rollout and retain evidence. Do not overwrite a published version; assess
98
- scoped yank/patch publication with separate Owner decision. Keep 0.7.0 install
99
- guidance until the successor is independently verified. Preserve original
100
- saved mandates/challenges; do not reinterpret them under a changed profile.
101
-
102
- Limits: one merchant/Checkout, all candidates disclosed, ES256/P-256, exact finite
103
- profile, no real Issuer trust/production Host proof. Authentication/consent,
104
- revocation/key lifecycle, persistence/CAS/nonce consumption, execution and payment
105
- remain app responsibilities. Payment Mandates, budgets, repeating/split orders,
106
- User Credentials and tax/shipping/discount engines remain out of scope.
107
- Production/real wallet/payment/deployment, RubyGems push and public tag/Release
108
- are NOT_RUN. Release readiness requires the final exact-HEAD PR/review/CI and
109
- package gates; the external report records their actual completion state.