ap2_mandate_verifier 1.0.0 → 1.2.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.
- checksums.yaml +4 -4
- data/README.ja.md +44 -20
- data/README.md +50 -24
- data/SECURITY.md +3 -3
- data/docs/PAYMENT.md +70 -0
- data/docs/POST_RELEASE_110.md +39 -0
- data/docs/POST_RELEASE_MAINTENANCE.md +18 -14
- data/docs/PUBLIC_API.md +19 -10
- data/docs/RELEASE_100_CANDIDATE.md +7 -1
- data/docs/RELEASE_110_CANDIDATE.md +32 -0
- data/docs/RELEASE_120_CANDIDATE.md +32 -0
- data/docs/SELECTIVE_PAYMENT.md +67 -0
- data/docs/SUPPORT_CONTRACT.md +25 -12
- data/docs/evidence/1.1.0_publication.json +101 -0
- data/examples/payment.rb +67 -0
- data/examples/selective_payment.rb +71 -0
- data/lib/ap2_mandate_verifier/payment.rb +366 -0
- data/lib/ap2_mandate_verifier/payment_receipt.rb +87 -0
- data/lib/ap2_mandate_verifier/selective_payment.rb +259 -0
- data/lib/ap2_mandate_verifier.rb +3 -0
- metadata +19 -7
|
@@ -0,0 +1,366 @@
|
|
|
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
|
+
agent_public_key_pem = InputValidator.snapshot!(agent_public_key_pem, max_bytes: 1_024)
|
|
80
|
+
opening, root = verified_root!(open_sd_jwt, trusted_provider_public_key_pem)
|
|
81
|
+
open!(opening); valid_now!(opening, verified_at)
|
|
82
|
+
raise Invalid unless opening.fetch("cnf") == {"jwk" => RootSignature.public_jwk!(agent_public_key_pem)}
|
|
83
|
+
value = copy_details!(payment).merge("vct" => "mandate.payment.1", "iat" => verified_at, "exp" => opening.fetch("exp"))
|
|
84
|
+
closed!(value); conditions!(opening, value)
|
|
85
|
+
audience = InputValidator.snapshot!(audience, max_bytes: 512)
|
|
86
|
+
nonce = InputValidator.snapshot!(nonce, max_bytes: 512)
|
|
87
|
+
text!(audience, 512); text!(nonce, 512)
|
|
88
|
+
claims = {"delegate_payload" => [value], "iat" => verified_at,
|
|
89
|
+
"aud" => audience, "nonce" => nonce, "sd_hash" => digest(root)}
|
|
90
|
+
preflight!(claims, "kb+sd-jwt")
|
|
91
|
+
terminal = MerchantSignature.sign!(claims, signer, agent_public_key_pem, typ: "kb+sd-jwt")
|
|
92
|
+
Presentation.send(:new, root, terminal + "~")
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
# Original-byte restoration only. All authentication belongs to verify.
|
|
96
|
+
def self.present(closed_sd_jwt:, open_sd_jwt: nil)
|
|
97
|
+
closed, wire = final!(closed_sd_jwt, conditional: !open_sd_jwt.nil?)
|
|
98
|
+
closed!(closed.fetch("delegate_payload").first)
|
|
99
|
+
if open_sd_jwt
|
|
100
|
+
opening, root = root!(open_sd_jwt)
|
|
101
|
+
open!(opening)
|
|
102
|
+
raise Invalid unless closed.fetch("sd_hash") == digest(root)
|
|
103
|
+
conditions!(opening, closed.fetch("delegate_payload").first)
|
|
104
|
+
end
|
|
105
|
+
Presentation.send(:new, open_sd_jwt && root, wire)
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# checkout_inputs are the complete EXISTING public verifier kwargs, supplied
|
|
109
|
+
# by the application, never taken from received Payment claims.
|
|
110
|
+
# Direct uses Buyer.verify; conditional uses verify_checkout's seven inputs.
|
|
111
|
+
def self.verify(closed_sd_jwt:, checkout_mode:, checkout_inputs:, expected_payment:,
|
|
112
|
+
trusted_provider_public_key_pem:, verified_at:, open_sd_jwt: nil,
|
|
113
|
+
expected_agent_public_key_pem: nil, expected_audience: nil, expected_nonce: nil)
|
|
114
|
+
CheckoutReceipt.send(:epoch!, verified_at)
|
|
115
|
+
raise Invalid unless checkout_inputs.instance_of?(Hash) && checkout_inputs[:verified_at] == verified_at
|
|
116
|
+
fields = case checkout_mode
|
|
117
|
+
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]
|
|
118
|
+
when :conditional then %i[trust_json selection_json host_json root_presentation terminal_jws host_checkout_jws verified_at]
|
|
119
|
+
else raise Invalid
|
|
120
|
+
end
|
|
121
|
+
raise Invalid unless checkout_inputs.size == fields.size && fields.all? { |f| checkout_inputs.key?(f) }
|
|
122
|
+
limits = {closed_sd_jwt: 32_768, trusted_provider_public_key_pem: 1_024,
|
|
123
|
+
trusted_merchant_public_key_pem: 1_024, expected_checkout_jwt: 16_384, expected_merchant_id: 512,
|
|
124
|
+
host_json: 32_768, terminal_jws: 32_768, host_checkout_jws: 16_384}
|
|
125
|
+
checkout_inputs = checkout_inputs.to_h do |key, value|
|
|
126
|
+
[key, key == :verified_at ? value : InputValidator.snapshot!(value, max_bytes: limits.fetch(key, 131_072))]
|
|
127
|
+
end.freeze
|
|
128
|
+
raise Invalid unless checkout_inputs[:verified_at] == verified_at
|
|
129
|
+
if checkout_mode == :conditional
|
|
130
|
+
expected_agent_public_key_pem = InputValidator.snapshot!(expected_agent_public_key_pem, max_bytes: 1_024)
|
|
131
|
+
end
|
|
132
|
+
expected = copy_details!(expected_payment)
|
|
133
|
+
case checkout_mode
|
|
134
|
+
when :direct
|
|
135
|
+
raise Invalid if open_sd_jwt || expected_agent_public_key_pem || expected_audience || expected_nonce
|
|
136
|
+
checked = Buyer.verify(**checkout_inputs)
|
|
137
|
+
raise Invalid unless checked.verified? && expected.fetch("transaction_id") == checked.checkout_hash
|
|
138
|
+
bind_checkout!(expected, checked.checkout)
|
|
139
|
+
claims, wire = verified_root!(closed_sd_jwt, trusted_provider_public_key_pem)
|
|
140
|
+
when :conditional
|
|
141
|
+
checked = AP2MandateVerifier.verify_checkout(**checkout_inputs)
|
|
142
|
+
raise Invalid unless checked.success?
|
|
143
|
+
checkout = checkout_inputs.fetch(:host_checkout_jws)
|
|
144
|
+
raise Invalid unless expected.fetch("transaction_id") == digest(checkout)
|
|
145
|
+
# Fully verified Host evidence binds independent Merchant order state.
|
|
146
|
+
binding = checked.evidence["checkout_binding"]
|
|
147
|
+
amount = expected.fetch("payment_amount")
|
|
148
|
+
raise Invalid unless expected.fetch("payee").fetch("id") == binding.fetch("merchant_id") &&
|
|
149
|
+
amount.fetch("currency") == binding.fetch("currency") && amount.fetch("amount") == binding.fetch("expected_total")
|
|
150
|
+
# Full Checkout verifier already authenticated these exact JWT bytes.
|
|
151
|
+
payload = jwt_payload!(checkout, "JWT")
|
|
152
|
+
bind_checkout!(expected, payload)
|
|
153
|
+
opening, root = verified_root!(open_sd_jwt, trusted_provider_public_key_pem)
|
|
154
|
+
open!(opening); valid_now!(opening, verified_at)
|
|
155
|
+
raise Invalid unless opening.fetch("cnf") == {"jwk" => RootSignature.public_jwk!(expected_agent_public_key_pem)}
|
|
156
|
+
terminal, wire = final!(closed_sd_jwt, conditional: true)
|
|
157
|
+
RootSignature.verified_payload!(wire.split("~", -1).first, expected_agent_public_key_pem,
|
|
158
|
+
expected_typ: "kb+sd-jwt", max_bytes: 32_768)
|
|
159
|
+
expected_audience = InputValidator.snapshot!(expected_audience, max_bytes: 512)
|
|
160
|
+
expected_nonce = InputValidator.snapshot!(expected_nonce, max_bytes: 512)
|
|
161
|
+
text!(expected_audience, 512); text!(expected_nonce, 512)
|
|
162
|
+
raise Invalid unless terminal.fetch("aud") == expected_audience && terminal.fetch("nonce") == expected_nonce &&
|
|
163
|
+
terminal.fetch("sd_hash") == digest(root) && terminal.fetch("iat") <= verified_at &&
|
|
164
|
+
verified_at - terminal.fetch("iat") <= 300
|
|
165
|
+
claims = terminal.fetch("delegate_payload").first
|
|
166
|
+
closed!(claims); valid_now!(claims, verified_at)
|
|
167
|
+
raise Invalid unless terminal.fetch("iat") == claims.fetch("iat") && claims.fetch("iat") >= opening.fetch("iat") &&
|
|
168
|
+
claims.fetch("exp") <= opening.fetch("exp")
|
|
169
|
+
conditions!(opening, claims)
|
|
170
|
+
reference = opening.fetch("constraints").find { |c| c["type"] == "payment.reference" }
|
|
171
|
+
raise Invalid unless reference.fetch("conditional_transaction_id") == digest(checkout_inputs.fetch(:root_presentation))
|
|
172
|
+
else raise Invalid
|
|
173
|
+
end
|
|
174
|
+
closed!(claims); valid_now!(claims, verified_at)
|
|
175
|
+
raise Invalid unless claims.slice(*FIELDS) == expected
|
|
176
|
+
Verification.send(:new, claims, wire)
|
|
177
|
+
rescue StandardError, LoadError
|
|
178
|
+
Verification.send(:new)
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
def self.reference(closed_sd_jwt:)
|
|
182
|
+
# No trust or authorization claim: parse either supported final grammar.
|
|
183
|
+
wire = InputValidator.snapshot!(closed_sd_jwt, max_bytes: 32_769)
|
|
184
|
+
payload = jwt_payload!(wire.split("~", -1).first, nil)
|
|
185
|
+
conditional = payload.key?("sd_hash")
|
|
186
|
+
final, original = final!(wire, conditional: conditional)
|
|
187
|
+
closed!(final.fetch("delegate_payload").first)
|
|
188
|
+
digest(original).freeze
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
def self.bind_checkout!(value, checkout)
|
|
192
|
+
raise Invalid unless value.fetch("payee") == checkout.fetch("merchant") &&
|
|
193
|
+
value.fetch("payment_amount") == {"currency" => checkout.fetch("currency"),
|
|
194
|
+
"amount" => ScopedConstraints.multi_checkout!(checkout)}
|
|
195
|
+
end
|
|
196
|
+
def self.copy_details!(value)
|
|
197
|
+
value = InputBuilder.send(:copy!, value)
|
|
198
|
+
exact!(value, FIELDS)
|
|
199
|
+
raise Invalid unless value["transaction_id"].instance_of?(String) && value["transaction_id"].match?(/\A[A-Za-z0-9_-]{43}\z/)
|
|
200
|
+
payee!(value["payee"]); amount!(value["payment_amount"]); instrument!(value["payment_instrument"])
|
|
201
|
+
value
|
|
202
|
+
end
|
|
203
|
+
def self.closed!(value)
|
|
204
|
+
exact!(value, FIELDS + %w[vct iat exp])
|
|
205
|
+
raise Invalid unless value["vct"] == "mandate.payment.1"
|
|
206
|
+
copy_details!(value.slice(*FIELDS)); times!(value)
|
|
207
|
+
end
|
|
208
|
+
def self.open!(value)
|
|
209
|
+
raise Invalid unless value.instance_of?(Hash) && (value.keys - FIELDS.drop(1) - %w[vct iat exp cnf constraints]).empty?
|
|
210
|
+
raise Invalid unless value["vct"] == "mandate.payment.open.1"
|
|
211
|
+
times!(value); exact!(value["cnf"], ["jwk"])
|
|
212
|
+
jwk = value["cnf"]["jwk"]
|
|
213
|
+
exact!(jwk, %w[kty crv x y])
|
|
214
|
+
raise Invalid unless jwk["kty"] == "EC" && jwk["crv"] == "P-256" &&
|
|
215
|
+
%w[x y].all? { |f| RootSignature.send(:decode!, jwk[f], 32).bytesize == 32 }
|
|
216
|
+
payee!(value["payee"]) if value.key?("payee")
|
|
217
|
+
amount!(value["payment_amount"]) if value.key?("payment_amount")
|
|
218
|
+
instrument!(value["payment_instrument"]) if value.key?("payment_instrument")
|
|
219
|
+
cs = value["constraints"]
|
|
220
|
+
raise Invalid unless cs.instance_of?(Array) && cs.size == 4 && cs.all? { |c| c.instance_of?(Hash) }
|
|
221
|
+
raise Invalid unless cs.map { |c| c["type"] }.sort == %w[payment.allowed_payees payment.allowed_payment_instruments payment.amount_range payment.reference].sort
|
|
222
|
+
cs.each do |c|
|
|
223
|
+
case c["type"]
|
|
224
|
+
when "payment.reference"
|
|
225
|
+
exact!(c, %w[type conditional_transaction_id])
|
|
226
|
+
raise Invalid unless c["conditional_transaction_id"].instance_of?(String) && c["conditional_transaction_id"].match?(/\A[A-Za-z0-9_-]{43}\z/)
|
|
227
|
+
when "payment.amount_range"
|
|
228
|
+
raise Invalid unless c.keys.sort == %w[currency max min type].sort || c.keys.sort == %w[currency max type].sort
|
|
229
|
+
amount!({"amount" => c["max"], "currency" => c["currency"]})
|
|
230
|
+
amount!({"amount" => c.fetch("min", 0), "currency" => c["currency"]})
|
|
231
|
+
raise Invalid unless c.fetch("min", 0) <= c["max"]
|
|
232
|
+
else
|
|
233
|
+
exact!(c, %w[type allowed])
|
|
234
|
+
raise Invalid unless c["allowed"].instance_of?(Array) && c["allowed"].size.between?(1, 8) && c["allowed"].uniq.size == c["allowed"].size
|
|
235
|
+
c["allowed"].each { |item| c["type"] == "payment.allowed_payees" ? payee!(item) : instrument!(item) }
|
|
236
|
+
end
|
|
237
|
+
end
|
|
238
|
+
end
|
|
239
|
+
def self.conditions!(opening, closed)
|
|
240
|
+
FIELDS.drop(1).each { |f| raise Invalid if opening.key?(f) && opening[f] != closed[f] }
|
|
241
|
+
opening.fetch("constraints").each do |c|
|
|
242
|
+
case c["type"]
|
|
243
|
+
when "payment.allowed_payees" then raise Invalid unless c["allowed"].include?(closed["payee"])
|
|
244
|
+
when "payment.allowed_payment_instruments" then raise Invalid unless c["allowed"].include?(closed["payment_instrument"])
|
|
245
|
+
when "payment.amount_range"
|
|
246
|
+
a = closed.fetch("payment_amount")
|
|
247
|
+
raise Invalid unless a["currency"] == c["currency"] && a["amount"].between?(c.fetch("min", 0), c["max"])
|
|
248
|
+
when "payment.reference" # Checked against the verified Checkout chain in verify.
|
|
249
|
+
else raise Invalid
|
|
250
|
+
end
|
|
251
|
+
end
|
|
252
|
+
end
|
|
253
|
+
def self.payee!(v)
|
|
254
|
+
raise Invalid unless v.instance_of?(Hash) && [%w[id name], %w[id name website]].include?(v.keys.sort)
|
|
255
|
+
v.each_value { |s| text!(s, 512) }
|
|
256
|
+
end
|
|
257
|
+
def self.instrument!(v)
|
|
258
|
+
raise Invalid unless v.instance_of?(Hash) && [%w[id type], %w[description id type]].include?(v.keys.sort)
|
|
259
|
+
v.each_value { |s| text!(s, 512) }
|
|
260
|
+
end
|
|
261
|
+
def self.amount!(v)
|
|
262
|
+
exact!(v, %w[amount currency])
|
|
263
|
+
ScopedConstraints.send(:amount!, v["amount"])
|
|
264
|
+
raise Invalid unless ScopedConstraints::CURRENCIES.include?(v["currency"])
|
|
265
|
+
end
|
|
266
|
+
def self.times!(v)
|
|
267
|
+
%w[iat exp].each { |f| CheckoutReceipt.send(:epoch!, v[f]) }
|
|
268
|
+
raise Invalid unless v["exp"] > v["iat"] && v["exp"] - v["iat"] <= MAX_LIFETIME
|
|
269
|
+
end
|
|
270
|
+
def self.valid_now!(v, now)
|
|
271
|
+
CheckoutReceipt.send(:epoch!, now)
|
|
272
|
+
raise Invalid unless v.fetch("iat") <= now && now < v.fetch("exp")
|
|
273
|
+
end
|
|
274
|
+
def self.checkout_open!(wire)
|
|
275
|
+
wire = InputValidator.snapshot!(wire)
|
|
276
|
+
opening = RootDisclosures.send(:structural_root!, wire).fetch("delegate_payload").first
|
|
277
|
+
raise Invalid unless opening.fetch("vct") == "mandate.checkout.open.1"
|
|
278
|
+
wire
|
|
279
|
+
end
|
|
280
|
+
def self.jwt_payload!(jwt, typ)
|
|
281
|
+
RootSignature.send(:dependencies!)
|
|
282
|
+
parts = jwt.split(".", -1)
|
|
283
|
+
raise Invalid unless parts.size == 3
|
|
284
|
+
h = InputValidator.parse!(RootSignature.send(:decode!, parts[0], 2_048))
|
|
285
|
+
CheckoutReceipt.send(:header!, h, typ || h["typ"])
|
|
286
|
+
raise Invalid unless RootSignature.send(:decode!, parts[2], 64).bytesize == 64
|
|
287
|
+
InputValidator.parse!(RootSignature.send(:decode!, parts[1], 24_576))
|
|
288
|
+
end
|
|
289
|
+
def self.final!(source, conditional:)
|
|
290
|
+
wire = InputValidator.snapshot!(source, max_bytes: 32_769)
|
|
291
|
+
raise Invalid unless wire.ascii_only? && wire.end_with?("~") && [1, 2].include?(wire.count("~"))
|
|
292
|
+
compact, *parts = wire.split("~", -1)
|
|
293
|
+
parts.pop
|
|
294
|
+
claims = jwt_payload!(compact, conditional ? "kb+sd-jwt" : "example+sd-jwt")
|
|
295
|
+
fields = conditional ? %w[delegate_payload iat aud nonce sd_hash] : %w[delegate_payload _sd_alg]
|
|
296
|
+
fields += ["_sd_alg"] if conditional && claims.key?("_sd_alg")
|
|
297
|
+
exact!(claims, fields)
|
|
298
|
+
raise Invalid if claims.key?("_sd_alg") && claims["_sd_alg"] != "sha-256"
|
|
299
|
+
if conditional
|
|
300
|
+
text!(claims["aud"], 512); text!(claims["nonce"], 512)
|
|
301
|
+
CheckoutReceipt.send(:epoch!, claims["iat"])
|
|
302
|
+
raise Invalid unless claims["sd_hash"].instance_of?(String) && claims["sd_hash"].match?(/\A[A-Za-z0-9_-]{43}\z/)
|
|
303
|
+
else
|
|
304
|
+
raise Invalid unless claims["_sd_alg"] == "sha-256"
|
|
305
|
+
end
|
|
306
|
+
raise Invalid unless claims["delegate_payload"].instance_of?(Array) && claims["delegate_payload"].size == 1
|
|
307
|
+
unless parts.empty?
|
|
308
|
+
disclosure = parts.fetch(0)
|
|
309
|
+
pointer = claims["delegate_payload"].first
|
|
310
|
+
exact!(pointer, ["..."])
|
|
311
|
+
raise Invalid unless pointer["..."] == digest(disclosure)
|
|
312
|
+
value = Buyer.send(:decode_disclosure!, disclosure, 2)
|
|
313
|
+
claims = claims.merge("delegate_payload" => [value[1]])
|
|
314
|
+
end
|
|
315
|
+
[claims, wire]
|
|
316
|
+
end
|
|
317
|
+
def self.root!(source)
|
|
318
|
+
claims, wire = final!(source, conditional: false)
|
|
319
|
+
[claims.fetch("delegate_payload").first, wire]
|
|
320
|
+
end
|
|
321
|
+
def self.verified_root!(source, key)
|
|
322
|
+
value, wire = root!(source)
|
|
323
|
+
RootSignature.verified_payload!(wire.split("~", -1).first, key, max_bytes: 32_768)
|
|
324
|
+
[value, wire]
|
|
325
|
+
end
|
|
326
|
+
def self.sign_root!(value, signer, key)
|
|
327
|
+
RootSignature.send(:dependencies!)
|
|
328
|
+
require "securerandom"
|
|
329
|
+
disclosure = Buyer.send(:encode, [Buyer.send(:encode, SecureRandom.random_bytes(16)), value])
|
|
330
|
+
claims = {"delegate_payload" => [{"..." => digest(disclosure)}], "_sd_alg" => "sha-256"}
|
|
331
|
+
preflight!(claims, "example+sd-jwt", disclosure)
|
|
332
|
+
wire = MerchantSignature.sign!(claims, signer, key,
|
|
333
|
+
typ: "example+sd-jwt") + "~" + disclosure + "~"
|
|
334
|
+
final!(wire, conditional: false)
|
|
335
|
+
wire
|
|
336
|
+
end
|
|
337
|
+
def self.preflight!(claims, typ, disclosure = nil)
|
|
338
|
+
# Bound every new Mandate signature before remote signer effects. ES256
|
|
339
|
+
# signatures have a fixed 64-byte width; this performs no cryptography.
|
|
340
|
+
compact = [Buyer.send(:encode, {"alg" => "ES256", "typ" => typ}),
|
|
341
|
+
Buyer.send(:encode, claims), Buyer.send(:encode, "\0" * 64)].join(".")
|
|
342
|
+
wire = compact + "~" + (disclosure ? disclosure + "~" : "")
|
|
343
|
+
final!(wire, conditional: typ == "kb+sd-jwt")
|
|
344
|
+
end
|
|
345
|
+
def self.digest(wire) = Base64.urlsafe_encode64(Digest::SHA256.digest(wire), padding: false)
|
|
346
|
+
def self.exact!(v, fields) = PurchaseBinding.send(:exact!, v, fields)
|
|
347
|
+
def self.text!(v, max) = CheckoutReceipt.send(:text!, v, max)
|
|
348
|
+
|
|
349
|
+
# Fixed redacted exceptions and keyword rejection on every new entry.
|
|
350
|
+
%i[details issue_direct issue_open issue_closed present reference verify].each do |name|
|
|
351
|
+
implementation = method(name)
|
|
352
|
+
required = implementation.parameters.filter_map { |kind, field| field if kind == :keyreq }.freeze
|
|
353
|
+
fields = implementation.parameters.map(&:last).freeze
|
|
354
|
+
define_singleton_method(name) do |**args|
|
|
355
|
+
unless (required - args.keys).empty? && (args.keys - fields).empty?
|
|
356
|
+
next Verification.send(:new) if name == :verify
|
|
357
|
+
raise Invalid
|
|
358
|
+
end
|
|
359
|
+
implementation.call(**args)
|
|
360
|
+
rescue StandardError, LoadError
|
|
361
|
+
raise Invalid.new, cause: nil
|
|
362
|
+
end
|
|
363
|
+
end
|
|
364
|
+
singleton_methods(false).reject { |n| %i[details issue_direct issue_open issue_closed present verify reference].include?(n) }.each { |n| private_class_method n }
|
|
365
|
+
end
|
|
366
|
+
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
|