ap2_mandate_verifier 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+ # Installed SDK only. Synthetic registry, approval and keys; no actual payment.
3
+ require "ap2_mandate_verifier"
4
+ require "time"
5
+ require_relative "selective_checkout"
6
+ module PaymentPolicyExample
7
+ M = AP2MandateVerifier
8
+ NOW = SelectiveCheckoutExample::NOW
9
+ def self.run
10
+ state = SelectiveCheckoutExample.run
11
+ provider, agent, merchant = state.fetch(:keys)
12
+ signer = ->(key) { M::CheckoutJWT.es256_signer(private_key: key) }
13
+ # These synthetic registry entries represent independently authenticated app
14
+ # state. Production code validates enrollment/channel/QWAC/revocation itself.
15
+ registry = {"processor-A" => {"legal_name" => "Example Payment Services Ltd.",
16
+ "brand_name" => "ExamplePay", "domain_name" => "pay.example"}}
17
+ trusted_pisp = registry.fetch("processor-A")
18
+ planned = Time.at(NOW + 3600).utc
19
+ date = planned.iso8601(3)
20
+ execution_at = planned.getlocal("+09:00").iso8601(3) # Same instant, different representation.
21
+ profile = M::PaymentPolicy::PROFILE_REF
22
+ selective_profile = M::PaymentPolicy::SELECTIVE_PROFILE_REF
23
+ checkout = state.fetch(:closed).checkout_jwt
24
+ details = M::Payment.details(checkout_jwt: checkout, trusted_merchant_public_key_pem: merchant.public_to_pem,
25
+ expected_merchant_id: "shop", payment_instrument: {"id" => "synthetic-card-A", "type" => "card"},
26
+ pisp: trusted_pisp, execution_date: date, profile_ref: profile)
27
+ direct_checkout = M::Buyer.issue_closed(checkout_jwt: checkout, approved_checkout_jwt: checkout,
28
+ trusted_merchant_public_key_pem: merchant.public_to_pem, expected_merchant_id: "shop", issued_at: NOW,
29
+ expires_at: NOW + 60, signer: signer.call(provider), public_key_pem: provider.public_to_pem)
30
+ direct_inputs = {closed_sd_jwt: direct_checkout.closed_sd_jwt, expected_checkout_jwt: checkout,
31
+ trusted_provider_public_key_pem: provider.public_to_pem, trusted_merchant_public_key_pem: merchant.public_to_pem,
32
+ expected_merchant_id: "shop", verified_at: NOW}
33
+ direct = M::Payment.issue_direct(payment: details, approved_payment: details, issued_at: NOW,
34
+ expires_at: NOW + 60, signer: signer.call(provider), public_key_pem: provider.public_to_pem, profile_ref: profile)
35
+ base = {expected_payment: details, trusted_provider_public_key_pem: provider.public_to_pem,
36
+ trusted_pisp: trusted_pisp, execution_at: execution_at, verified_at: NOW, profile_ref: profile}
37
+ direct_args = base.merge(closed_sd_jwt: direct.closed_sd_jwt, checkout_mode: :direct, checkout_inputs: direct_inputs)
38
+ raise "Direct policy verification failed" unless M::Payment.verify(**direct_args).verified?
39
+ wrong_pisp = trusted_pisp.merge("brand_name" => "Unapproved brand")
40
+ raise "PISP context mismatch accepted" if M::Payment.verify(**direct_args.merge(trusted_pisp: wrong_pisp)).verified?
41
+ raise "execution context mismatch accepted" if M::Payment.verify(**direct_args.merge(execution_at: (planned + 1).iso8601(3))).verified?
42
+ puts "Direct: approved PISP/date verified; wrong independent PISP/time rejected"
43
+
44
+ payees = [details.fetch("payee"), {"id" => "private-alternative", "name" => "Private alternative payee"}]
45
+ instruments = [details.fetch("payment_instrument"), {"id" => "private-card", "type" => "card"}]
46
+ conditions = [{"type" => "payment.amount_range", "currency" => "USD", "max" => 300},
47
+ {"type" => "payment.allowed_payees", "allowed" => payees},
48
+ {"type" => "payment.allowed_payment_instruments", "allowed" => instruments},
49
+ {"type" => "payment.allowed_pisps", "allowed" => [trusted_pisp]},
50
+ {"type" => "payment.execution_date", "not_before" => (planned - 1).iso8601(3), "not_after" => (planned + 1).iso8601(3)}]
51
+ open_args = {open_checkout_sd_jwt: state.fetch(:opening).root_presentation, constraints: conditions, fixed: {},
52
+ agent_public_key_pem: agent.public_to_pem, issued_at: NOW, expires_at: NOW + 60,
53
+ signer: signer.call(provider), public_key_pem: provider.public_to_pem,
54
+ checkout_profile_ref: M::SelectiveCheckout::PROFILE_REF, candidate_policy: :independent}
55
+ open = M::Payment.issue_open(**open_args, profile_ref: profile)
56
+ close_args = {payment: details, trusted_provider_public_key_pem: provider.public_to_pem,
57
+ agent_public_key_pem: agent.public_to_pem, audience: "credential-provider", nonce: "synthetic-policy-nonce",
58
+ verified_at: NOW, signer: signer.call(agent)}
59
+ closed = M::Payment.issue_closed(**close_args, open_sd_jwt: open, profile_ref: profile)
60
+ restored = M::Payment.present(open_sd_jwt: open, closed_sd_jwt: closed.closed_sd_jwt, profile_ref: profile)
61
+ raw = M::InputBuilder.inputs(**state.fetch(:host_inputs), saved_challenge: state.fetch(:saved),
62
+ terminal_jws: state.fetch(:closed).terminal_jws, expected_challenge_issuer_id: "host", clock_source_id: "synthetic-clock", verified_at: NOW)
63
+ expected_agent = {expected_agent_public_key_pem: agent.public_to_pem, expected_audience: "credential-provider", expected_nonce: "synthetic-policy-nonce"}
64
+ checked = M::Payment.verify(**base, **expected_agent, closed_sd_jwt: restored.closed_sd_jwt,
65
+ open_sd_jwt: restored.open_sd_jwt, checkout_mode: :conditional, checkout_inputs: raw)
66
+ raise "conditional policy verification failed" unless checked.verified?
67
+ begin
68
+ M::Payment.issue_closed(**close_args.merge(payment: details.merge("execution_date" => (planned + 2).iso8601(3))), open_sd_jwt: open, profile_ref: profile)
69
+ raise "outside execution window accepted"
70
+ rescue M::Payment::Invalid
71
+ puts "Conditional: allowed PISP/inclusive window verified; outside window rejected"
72
+ end
73
+ full = M::SelectivePayment.issue_open(**open_args, profile_ref: selective_profile,
74
+ approved_combinations: [[0,0],[0,1],[1,0],[1,1]], selective: :both)
75
+ reduced = M::SelectivePayment.select(open_sd_jwt: full, payee_index: 0, instrument_index: 0, profile_ref: selective_profile)
76
+ selective_closed = M::SelectivePayment.issue_closed(**close_args, open_presentation: reduced, profile_ref: selective_profile)
77
+ selective = M::SelectivePayment.present(open_presentation: reduced, closed_sd_jwt: selective_closed.closed_sd_jwt, profile_ref: selective_profile)
78
+ result = M::SelectivePayment.verify(**base.merge(profile_ref: selective_profile), **expected_agent,
79
+ open_presentation: reduced, closed_sd_jwt: selective.closed_sd_jwt, checkout_inputs: raw)
80
+ raise "selective policy verification failed" unless result.verified?
81
+ visible = reduced.split("~", -1)[1...-1].map { |s| JSON.parse(Base64.urlsafe_decode64(s)) }
82
+ raise "hidden candidate leaked" if JSON.generate(visible).include?("private-alternative") || JSON.generate(visible).include?("private-card")
83
+ puts "Selective: Checkout and Payment verified; unselected payee/instrument hidden; PISP/date conditions fully visible"
84
+ [[direct, profile], [restored, profile], [selective, selective_profile]].each do |payment, ref|
85
+ %w[Success Error].each do |outcome|
86
+ fields = outcome == "Success" ? {psp_confirmation_id: "synthetic-psp", network_confirmation_id: "synthetic-network"} :
87
+ {error: "declined", error_description: "Simulated refusal"}
88
+ receipt = M::PaymentReceipt.sign(closed_sd_jwt: payment.closed_sd_jwt, profile_ref: ref, issuer: "processor-A",
89
+ payment_id: "synthetic-policy-payment", outcome: outcome, issued_at: NOW, **fields,
90
+ signer: signer.call(merchant), public_key_pem: merchant.public_to_pem)
91
+ verified = M::PaymentReceipt.verify(jwt: receipt.jwt, closed_sd_jwt: payment.closed_sd_jwt, profile_ref: ref,
92
+ trusted_public_key_pem: merchant.public_to_pem, expected_issuer: "processor-A", expected_payment_id: "synthetic-policy-payment",
93
+ not_before: NOW, not_after: NOW + 60, verified_at: NOW)
94
+ raise "policy Receipt failed" unless verified.verified? && verified.outcome == outcome
95
+ end
96
+ end
97
+ puts "Success/Error Payment Receipts authenticated for all three modes"
98
+ puts "Synthetic plan only: no QWAC provenance, scheduling, execution permission or settlement is established."
99
+ end
100
+ end
101
+ PaymentPolicyExample.run if $PROGRAM_NAME == __FILE__
@@ -36,71 +36,90 @@ module AP2MandateVerifier
36
36
 
37
37
  # Checkout JWT and key must be from independently trusted application state.
38
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:)
39
+ def self.details(checkout_jwt:, trusted_merchant_public_key_pem:, expected_merchant_id:, payment_instrument:,
40
+ profile_ref: PROFILE_REF, pisp: nil, execution_date: nil)
41
+ profile = PaymentPolicy.profile!(profile_ref)
42
+ if PaymentPolicy.enabled?(profile)
43
+ planned = InputBuilder.send(:copy!, {"pisp" => pisp, "execution_date" => execution_date})
44
+ PaymentPolicy.details!(planned)
45
+ else
46
+ raise Invalid unless pisp.nil? && execution_date.nil?
47
+ end
40
48
  checked = CheckoutJWT.verify(jwt: checkout_jwt, trusted_public_key_pem: trusted_merchant_public_key_pem,
41
49
  expected_merchant_id: expected_merchant_id, profile_ref: ScopedConstraints::MULTI_PROFILE_REF)
42
50
  instrument = InputBuilder.send(:copy!, payment_instrument)
43
51
  instrument!(instrument)
44
- ResearchEvidence.send(:copy_frozen, {"transaction_id" => checked.checkout_hash,
52
+ value = {"transaction_id" => checked.checkout_hash,
45
53
  "payee" => checked.checkout.fetch("merchant"), "payment_instrument" => instrument,
46
54
  "payment_amount" => {"currency" => checked.checkout.fetch("currency"),
47
- "amount" => ScopedConstraints.multi_checkout!(checked.checkout)}})
55
+ "amount" => ScopedConstraints.multi_checkout!(checked.checkout)}}
56
+ if PaymentPolicy.enabled?(profile)
57
+ value.merge!(planned)
58
+ end
59
+ ResearchEvidence.send(:copy_frozen, copy_details!(value, profile_ref: profile))
48
60
  end
49
61
 
50
62
  # 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)
63
+ def self.issue_direct(payment:, approved_payment:, issued_at:, expires_at:, signer:, public_key_pem:, profile_ref: PROFILE_REF)
64
+ profile_ref = PaymentPolicy.profile!(profile_ref)
65
+ value = copy_details!(payment, profile_ref: profile_ref)
66
+ raise Invalid unless value == copy_details!(approved_payment, profile_ref: profile_ref)
54
67
  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))
68
+ closed!(closed, profile_ref: profile_ref)
69
+ Presentation.send(:new, nil, sign_root!(closed, signer, public_key_pem, profile_ref: profile_ref))
57
70
  end
58
71
 
59
72
  # Reference is calculated over exact original Open Checkout, never rebuilt JSON.
60
73
  # The app authenticates consent to these conditions before invoking this API.
61
74
  def self.issue_open(open_checkout_sd_jwt:, constraints:, fixed:, agent_public_key_pem:,
62
- issued_at:, expires_at:, signer:, public_key_pem:, checkout_profile_ref: ScopedConstraints::MULTI_PROFILE_REF)
75
+ issued_at:, expires_at:, signer:, public_key_pem:, checkout_profile_ref: ScopedConstraints::MULTI_PROFILE_REF,
76
+ profile_ref: PROFILE_REF, candidate_policy: nil)
77
+ profile_ref = PaymentPolicy.profile!(profile_ref)
78
+ PaymentPolicy.candidate_policy!(profile_ref, candidate_policy)
63
79
  RootSignature.send(:dependencies!)
64
80
  root = checkout_open!(open_checkout_sd_jwt, profile_ref: checkout_profile_ref)
65
81
  conditions = InputBuilder.send(:copy!, constraints)
66
82
  raise Invalid unless conditions.instance_of?(Array)
67
83
  conditions << {"type" => "payment.reference", "conditional_transaction_id" => digest(root)}
68
84
  value = InputBuilder.send(:copy!, fixed)
69
- raise Invalid unless value.instance_of?(Hash) && (value.keys - FIELDS.drop(1)).empty?
85
+ raise Invalid unless value.instance_of?(Hash) && (value.keys - PaymentPolicy.fields(profile_ref).drop(1)).empty?
70
86
  opening = value.merge("vct" => "mandate.payment.open.1", "iat" => issued_at, "exp" => expires_at,
71
87
  "cnf" => {"jwk" => RootSignature.public_jwk!(agent_public_key_pem)}, "constraints" => conditions)
72
- open!(opening)
73
- sign_root!(opening, signer, public_key_pem).freeze
88
+ open!(opening, profile_ref: profile_ref)
89
+ sign_root!(opening, signer, public_key_pem, profile_ref: profile_ref).freeze
74
90
  end
75
91
 
76
92
  # Provider signer is deliberately absent. Existing signed Open grants the hop.
77
93
  def self.issue_closed(open_sd_jwt:, payment:, trusted_provider_public_key_pem:, agent_public_key_pem:,
78
- audience:, nonce:, verified_at:, signer:)
94
+ audience:, nonce:, verified_at:, signer:, profile_ref: PROFILE_REF)
95
+ profile_ref = PaymentPolicy.profile!(profile_ref)
79
96
  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)
97
+ opening, root = verified_root!(open_sd_jwt, trusted_provider_public_key_pem, profile_ref: profile_ref)
98
+ open!(opening, profile_ref: profile_ref); valid_now!(opening, verified_at)
82
99
  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)
100
+ value = copy_details!(payment, profile_ref: profile_ref).merge("vct" => "mandate.payment.1", "iat" => verified_at, "exp" => opening.fetch("exp"))
101
+ closed!(value, profile_ref: profile_ref); conditions!(opening, value, profile_ref: profile_ref)
85
102
  audience = InputValidator.snapshot!(audience, max_bytes: 512)
86
103
  nonce = InputValidator.snapshot!(nonce, max_bytes: 512)
87
104
  text!(audience, 512); text!(nonce, 512)
88
105
  claims = {"delegate_payload" => [value], "iat" => verified_at,
89
106
  "aud" => audience, "nonce" => nonce, "sd_hash" => digest(root)}
90
- preflight!(claims, "kb+sd-jwt")
107
+ claims["ap2_profile"] = profile_ref if PaymentPolicy.enabled?(profile_ref)
108
+ preflight!(claims, "kb+sd-jwt", profile_ref: profile_ref)
91
109
  terminal = MerchantSignature.sign!(claims, signer, agent_public_key_pem, typ: "kb+sd-jwt")
92
110
  Presentation.send(:new, root, terminal + "~")
93
111
  end
94
112
 
95
113
  # 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)
114
+ def self.present(closed_sd_jwt:, open_sd_jwt: nil, profile_ref: PROFILE_REF)
115
+ profile_ref = PaymentPolicy.profile!(profile_ref)
116
+ closed, wire = final!(closed_sd_jwt, conditional: !open_sd_jwt.nil?, profile_ref: profile_ref)
117
+ closed!(closed.fetch("delegate_payload").first, profile_ref: profile_ref)
99
118
  if open_sd_jwt
100
- opening, root = root!(open_sd_jwt)
101
- open!(opening)
119
+ opening, root = root!(open_sd_jwt, profile_ref: profile_ref)
120
+ open!(opening, profile_ref: profile_ref)
102
121
  raise Invalid unless closed.fetch("sd_hash") == digest(root)
103
- conditions!(opening, closed.fetch("delegate_payload").first)
122
+ conditions!(opening, closed.fetch("delegate_payload").first, profile_ref: profile_ref)
104
123
  end
105
124
  Presentation.send(:new, open_sd_jwt && root, wire)
106
125
  end
@@ -110,7 +129,16 @@ module AP2MandateVerifier
110
129
  # Direct uses Buyer.verify; conditional uses verify_checkout's seven inputs.
111
130
  def self.verify(closed_sd_jwt:, checkout_mode:, checkout_inputs:, expected_payment:,
112
131
  trusted_provider_public_key_pem:, verified_at:, open_sd_jwt: nil,
113
- expected_agent_public_key_pem: nil, expected_audience: nil, expected_nonce: nil)
132
+ expected_agent_public_key_pem: nil, expected_audience: nil, expected_nonce: nil,
133
+ profile_ref: PROFILE_REF, trusted_pisp: nil, execution_at: nil)
134
+ profile_ref = PaymentPolicy.profile!(profile_ref)
135
+ context = PaymentPolicy.context!(profile_ref, trusted_pisp, execution_at)
136
+ trusted_provider_public_key_pem = InputValidator.snapshot!(trusted_provider_public_key_pem, max_bytes: 1_024)
137
+ if checkout_mode == :conditional
138
+ expected_agent_public_key_pem = InputValidator.snapshot!(expected_agent_public_key_pem, max_bytes: 1_024)
139
+ expected_audience = InputValidator.snapshot!(expected_audience, max_bytes: 512)
140
+ expected_nonce = InputValidator.snapshot!(expected_nonce, max_bytes: 512)
141
+ end
114
142
  CheckoutReceipt.send(:epoch!, verified_at)
115
143
  raise Invalid unless checkout_inputs.instance_of?(Hash) && checkout_inputs[:verified_at] == verified_at
116
144
  fields = case checkout_mode
@@ -129,14 +157,14 @@ module AP2MandateVerifier
129
157
  if checkout_mode == :conditional
130
158
  expected_agent_public_key_pem = InputValidator.snapshot!(expected_agent_public_key_pem, max_bytes: 1_024)
131
159
  end
132
- expected = copy_details!(expected_payment)
160
+ expected = copy_details!(expected_payment, profile_ref: profile_ref)
133
161
  case checkout_mode
134
162
  when :direct
135
163
  raise Invalid if open_sd_jwt || expected_agent_public_key_pem || expected_audience || expected_nonce
136
164
  checked = Buyer.verify(**checkout_inputs)
137
165
  raise Invalid unless checked.verified? && expected.fetch("transaction_id") == checked.checkout_hash
138
166
  bind_checkout!(expected, checked.checkout)
139
- claims, wire = verified_root!(closed_sd_jwt, trusted_provider_public_key_pem)
167
+ claims, wire = verified_root!(closed_sd_jwt, trusted_provider_public_key_pem, profile_ref: profile_ref)
140
168
  when :conditional
141
169
  checked = AP2MandateVerifier.verify_checkout(**checkout_inputs)
142
170
  raise Invalid unless checked.success?
@@ -150,10 +178,10 @@ module AP2MandateVerifier
150
178
  # Full Checkout verifier already authenticated these exact JWT bytes.
151
179
  payload = jwt_payload!(checkout, "JWT")
152
180
  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)
181
+ opening, root = verified_root!(open_sd_jwt, trusted_provider_public_key_pem, profile_ref: profile_ref)
182
+ open!(opening, profile_ref: profile_ref); valid_now!(opening, verified_at)
155
183
  raise Invalid unless opening.fetch("cnf") == {"jwk" => RootSignature.public_jwk!(expected_agent_public_key_pem)}
156
- terminal, wire = final!(closed_sd_jwt, conditional: true)
184
+ terminal, wire = final!(closed_sd_jwt, conditional: true, profile_ref: profile_ref)
157
185
  RootSignature.verified_payload!(wire.split("~", -1).first, expected_agent_public_key_pem,
158
186
  expected_typ: "kb+sd-jwt", max_bytes: 32_768)
159
187
  expected_audience = InputValidator.snapshot!(expected_audience, max_bytes: 512)
@@ -163,28 +191,31 @@ module AP2MandateVerifier
163
191
  terminal.fetch("sd_hash") == digest(root) && terminal.fetch("iat") <= verified_at &&
164
192
  verified_at - terminal.fetch("iat") <= 300
165
193
  claims = terminal.fetch("delegate_payload").first
166
- closed!(claims); valid_now!(claims, verified_at)
194
+ closed!(claims, profile_ref: profile_ref); valid_now!(claims, verified_at)
167
195
  raise Invalid unless terminal.fetch("iat") == claims.fetch("iat") && claims.fetch("iat") >= opening.fetch("iat") &&
168
196
  claims.fetch("exp") <= opening.fetch("exp")
169
- conditions!(opening, claims)
197
+ conditions!(opening, claims, profile_ref: profile_ref)
170
198
  reference = opening.fetch("constraints").find { |c| c["type"] == "payment.reference" }
171
199
  raise Invalid unless reference.fetch("conditional_transaction_id") == digest(checkout_inputs.fetch(:root_presentation))
172
200
  else raise Invalid
173
201
  end
174
- closed!(claims); valid_now!(claims, verified_at)
175
- raise Invalid unless claims.slice(*FIELDS) == expected
202
+ closed!(claims, profile_ref: profile_ref); valid_now!(claims, verified_at)
203
+ PaymentPolicy.bind_context!(claims, context) if context
204
+ raise Invalid unless claims.slice(*PaymentPolicy.fields(profile_ref)) == expected
176
205
  Verification.send(:new, claims, wire)
177
206
  rescue StandardError, LoadError
178
207
  Verification.send(:new)
179
208
  end
180
209
 
181
- def self.reference(closed_sd_jwt:)
210
+ def self.reference(closed_sd_jwt:, profile_ref: PROFILE_REF)
211
+ profile_ref = InputValidator.snapshot!(profile_ref, max_bytes: 256)
212
+ raise Invalid unless profile_ref == PROFILE_REF || PaymentPolicy.enabled?(profile_ref)
182
213
  # No trust or authorization claim: parse either supported final grammar.
183
214
  wire = InputValidator.snapshot!(closed_sd_jwt, max_bytes: 32_769)
184
215
  payload = jwt_payload!(wire.split("~", -1).first, nil)
185
216
  conditional = payload.key?("sd_hash")
186
- final, original = final!(wire, conditional: conditional)
187
- closed!(final.fetch("delegate_payload").first)
217
+ final, original = final!(wire, conditional: conditional, profile_ref: profile_ref)
218
+ closed!(final.fetch("delegate_payload").first, profile_ref: profile_ref)
188
219
  digest(original).freeze
189
220
  end
190
221
 
@@ -193,19 +224,25 @@ module AP2MandateVerifier
193
224
  value.fetch("payment_amount") == {"currency" => checkout.fetch("currency"),
194
225
  "amount" => ScopedConstraints.multi_checkout!(checkout)}
195
226
  end
196
- def self.copy_details!(value)
227
+ def self.copy_details!(value, profile_ref: PROFILE_REF)
197
228
  value = InputBuilder.send(:copy!, value)
198
- exact!(value, FIELDS)
229
+ exact!(value, PaymentPolicy.fields(profile_ref))
199
230
  raise Invalid unless value["transaction_id"].instance_of?(String) && value["transaction_id"].match?(/\A[A-Za-z0-9_-]{43}\z/)
200
231
  payee!(value["payee"]); amount!(value["payment_amount"]); instrument!(value["payment_instrument"])
232
+ PaymentPolicy.details!(value) if PaymentPolicy.enabled?(profile_ref)
201
233
  value
202
234
  end
203
- def self.closed!(value)
204
- exact!(value, FIELDS + %w[vct iat exp])
235
+ def self.closed!(value, profile_ref: PROFILE_REF)
236
+ exact!(value, PaymentPolicy.fields(profile_ref) + %w[vct iat exp])
205
237
  raise Invalid unless value["vct"] == "mandate.payment.1"
206
- copy_details!(value.slice(*FIELDS)); times!(value)
238
+ copy_details!(value.slice(*PaymentPolicy.fields(profile_ref)), profile_ref: profile_ref); times!(value)
207
239
  end
208
- def self.open!(value)
240
+ def self.open!(value, profile_ref: PROFILE_REF)
241
+ if PaymentPolicy.enabled?(profile_ref)
242
+ base = PaymentPolicy.constraints!(value)
243
+ open!(base)
244
+ return nil
245
+ end
209
246
  raise Invalid unless value.instance_of?(Hash) && (value.keys - FIELDS.drop(1) - %w[vct iat exp cnf constraints]).empty?
210
247
  raise Invalid unless value["vct"] == "mandate.payment.open.1"
211
248
  times!(value); exact!(value["cnf"], ["jwk"])
@@ -236,7 +273,13 @@ module AP2MandateVerifier
236
273
  end
237
274
  end
238
275
  end
239
- def self.conditions!(opening, closed)
276
+ def self.conditions!(opening, closed, profile_ref: PROFILE_REF)
277
+ if PaymentPolicy.enabled?(profile_ref)
278
+ PaymentPolicy.conditions!(opening, closed)
279
+ base = PaymentPolicy.constraints!(opening)
280
+ conditions!(base, closed)
281
+ return nil
282
+ end
240
283
  FIELDS.drop(1).each { |f| raise Invalid if opening.key?(f) && opening[f] != closed[f] }
241
284
  opening.fetch("constraints").each do |c|
242
285
  case c["type"]
@@ -292,7 +335,7 @@ module AP2MandateVerifier
292
335
  raise Invalid unless RootSignature.send(:decode!, parts[2], 64).bytesize == 64
293
336
  InputValidator.parse!(RootSignature.send(:decode!, parts[1], 24_576))
294
337
  end
295
- def self.final!(source, conditional:)
338
+ def self.final!(source, conditional:, profile_ref: PROFILE_REF)
296
339
  wire = InputValidator.snapshot!(source, max_bytes: 32_769)
297
340
  raise Invalid unless wire.ascii_only? && wire.end_with?("~") && [1, 2].include?(wire.count("~"))
298
341
  compact, *parts = wire.split("~", -1)
@@ -300,6 +343,10 @@ module AP2MandateVerifier
300
343
  claims = jwt_payload!(compact, conditional ? "kb+sd-jwt" : "example+sd-jwt")
301
344
  fields = conditional ? %w[delegate_payload iat aud nonce sd_hash] : %w[delegate_payload _sd_alg]
302
345
  fields += ["_sd_alg"] if conditional && claims.key?("_sd_alg")
346
+ if PaymentPolicy.enabled?(profile_ref)
347
+ fields += ["ap2_profile"]
348
+ raise Invalid unless claims["ap2_profile"] == profile_ref
349
+ end
303
350
  exact!(claims, fields)
304
351
  raise Invalid if claims.key?("_sd_alg") && claims["_sd_alg"] != "sha-256"
305
352
  if conditional
@@ -320,33 +367,34 @@ module AP2MandateVerifier
320
367
  end
321
368
  [claims, wire]
322
369
  end
323
- def self.root!(source)
324
- claims, wire = final!(source, conditional: false)
370
+ def self.root!(source, profile_ref: PROFILE_REF)
371
+ claims, wire = final!(source, conditional: false, profile_ref: profile_ref)
325
372
  [claims.fetch("delegate_payload").first, wire]
326
373
  end
327
- def self.verified_root!(source, key)
328
- value, wire = root!(source)
374
+ def self.verified_root!(source, key, profile_ref: PROFILE_REF)
375
+ value, wire = root!(source, profile_ref: profile_ref)
329
376
  RootSignature.verified_payload!(wire.split("~", -1).first, key, max_bytes: 32_768)
330
377
  [value, wire]
331
378
  end
332
- def self.sign_root!(value, signer, key)
379
+ def self.sign_root!(value, signer, key, profile_ref: PROFILE_REF)
333
380
  RootSignature.send(:dependencies!)
334
381
  require "securerandom"
335
382
  disclosure = Buyer.send(:encode, [Buyer.send(:encode, SecureRandom.random_bytes(16)), value])
336
383
  claims = {"delegate_payload" => [{"..." => digest(disclosure)}], "_sd_alg" => "sha-256"}
337
- preflight!(claims, "example+sd-jwt", disclosure)
384
+ claims["ap2_profile"] = profile_ref if PaymentPolicy.enabled?(profile_ref)
385
+ preflight!(claims, "example+sd-jwt", disclosure, profile_ref: profile_ref)
338
386
  wire = MerchantSignature.sign!(claims, signer, key,
339
387
  typ: "example+sd-jwt") + "~" + disclosure + "~"
340
- final!(wire, conditional: false)
388
+ final!(wire, conditional: false, profile_ref: profile_ref)
341
389
  wire
342
390
  end
343
- def self.preflight!(claims, typ, disclosure = nil)
391
+ def self.preflight!(claims, typ, disclosure = nil, profile_ref: PROFILE_REF)
344
392
  # Bound every new Mandate signature before remote signer effects. ES256
345
393
  # signatures have a fixed 64-byte width; this performs no cryptography.
346
394
  compact = [Buyer.send(:encode, {"alg" => "ES256", "typ" => typ}),
347
395
  Buyer.send(:encode, claims), Buyer.send(:encode, "\0" * 64)].join(".")
348
396
  wire = compact + "~" + (disclosure ? disclosure + "~" : "")
349
- final!(wire, conditional: typ == "kb+sd-jwt")
397
+ final!(wire, conditional: typ == "kb+sd-jwt", profile_ref: profile_ref)
350
398
  end
351
399
  def self.digest(wire) = Base64.urlsafe_encode64(Digest::SHA256.digest(wire), padding: false)
352
400
  def self.exact!(v, fields) = PurchaseBinding.send(:exact!, v, fields)