ap2_mandate_verifier 1.2.0 → 1.4.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.
@@ -29,10 +29,11 @@ module AP2MandateVerifier
29
29
  def payment_rejected? = verified? && outcome == "Error"
30
30
  private_class_method :new
31
31
  end
32
- def self.reference(closed_sd_jwt:) = Payment.reference(closed_sd_jwt: closed_sd_jwt)
32
+ def self.reference(closed_sd_jwt:, profile_ref: Payment::PROFILE_REF) = Payment.reference(closed_sd_jwt: closed_sd_jwt, profile_ref: profile_ref)
33
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)
34
+ psp_confirmation_id: nil, network_confirmation_id: nil, error: nil, error_description: nil,
35
+ profile_ref: Payment::PROFILE_REF)
36
+ ref = reference(closed_sd_jwt: closed_sd_jwt, profile_ref: profile_ref)
36
37
  claims = {"iss" => issuer, "status" => outcome, "payment_id" => payment_id, "iat" => issued_at, "reference" => ref}
37
38
  {"psp_confirmation_id" => psp_confirmation_id, "network_confirmation_id" => network_confirmation_id,
38
39
  "error" => error, "error_description" => error_description}.each { |k, v| claims[k] = v unless v.nil? }
@@ -41,13 +42,13 @@ module AP2MandateVerifier
41
42
  Signed.send(:new, MerchantSignature.sign!(claims, signer, public_key_pem), ref)
42
43
  end
43
44
  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:, profile_ref: Payment::PROFILE_REF)
45
46
  [not_before, not_after, verified_at].each { |t| CheckoutReceipt.send(:epoch!, t) }
46
47
  raise Invalid unless not_before <= verified_at && verified_at <= not_after
47
48
  expected = InputValidator.snapshot!(expected_issuer, max_bytes: 512)
48
49
  id = InputValidator.snapshot!(expected_payment_id, max_bytes: 512)
49
50
  text!(expected, 512); text!(id, 512)
50
- ref = reference(closed_sd_jwt: closed_sd_jwt)
51
+ ref = reference(closed_sd_jwt: closed_sd_jwt, profile_ref: profile_ref)
51
52
  claims = RootSignature.verified_payload!(jwt, trusted_public_key_pem, expected_typ: "JWT", max_bytes: 16_384)
52
53
  validate!(claims)
53
54
  raise Invalid unless claims["iss"] == expected && claims["payment_id"] == id && claims["reference"] == ref &&
@@ -22,6 +22,14 @@ module AP2MandateVerifier
22
22
  # Internal handoff only: signature and entire closure are verified first.
23
23
  # AP2 semantics, constraints and Host authorization remain unvalidated.
24
24
  def self.verified_root!(source, issuer_pem, profile_ref: TrustContext::PROFILE_REF)
25
+ if profile_ref == TrustContext::SELECTIVE_PROFILE_REF
26
+ begin
27
+ parsed = SelectiveCheckout.send(:authenticated!, source, issuer_pem)
28
+ return {"delegate_payload" => [parsed.fetch(:opening)]}
29
+ rescue SelectiveCheckout::Invalid, KeyError
30
+ raise Rejected.new(:unsupported_disclosure_profile), cause: nil
31
+ end
32
+ end
25
33
  multi = profile_ref == "ap2.checkout.single_merchant_multi_item"
26
34
  raise Rejected, :unsupported_disclosure_profile unless multi || profile_ref == TrustContext::PROFILE_REF
27
35
  wire = InputValidator.snapshot!(source)
@@ -29,7 +29,7 @@ module AP2MandateVerifier
29
29
  raise RootSignature::Unavailable, :constraint_context_unavailable unless
30
30
  CURRENCIES.include?(currency) && CORE_INSTANCE_OF.bind_call(expected_total_minor, Integer) &&
31
31
  expected_total_minor.between?(0, MAX_AMOUNT)
32
- if profile_ref == MULTI_PROFILE_REF
32
+ if [MULTI_PROFILE_REF, TrustContext::SELECTIVE_PROFILE_REF].include?(profile_ref)
33
33
  details = PurchaseBinding.verified_details!(**binding_inputs, profile_ref: profile_ref)
34
34
  multi_constraints!(details, currency, expected_total_minor)
35
35
  return details
@@ -0,0 +1,261 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Explicit bounded leaf-candidate profile, never a generic SD-JWT resolver.
5
+ module SelectiveCheckout
6
+ PROFILE_REF = "ap2.checkout.selective_candidates.1".freeze
7
+ MAX_DISCLOSURES = 73
8
+ MAX_SEGMENT = 8_192
9
+ class Invalid < ArgumentError
10
+ def initialize = super("invalid selective checkout information")
11
+ end
12
+ class Open
13
+ attr_reader :root_presentation
14
+ alias open_sd_jwt root_presentation
15
+ def initialize(wire)
16
+ @root_presentation = wire.freeze
17
+ freeze
18
+ end
19
+ private_class_method :new
20
+ end
21
+
22
+ # The protected consent must approve independent merchant/product lists.
23
+ # Relationships between lists require separate Open Mandates.
24
+ def self.issue_open(allowed_merchants:, requirements:, candidate_policy:, agent_public_key_pem:,
25
+ issued_at:, expires_at:, signer:, public_key_pem:)
26
+ RootSignature.send(:dependencies!)
27
+ raise Invalid unless candidate_policy == :independent
28
+ agent = InputValidator.snapshot!(agent_public_key_pem, max_bytes: 1_024)
29
+ provider = InputValidator.snapshot!(public_key_pem, max_bytes: 1_024)
30
+ opening = {"vct" => "mandate.checkout.open.1", "iat" => issued_at, "exp" => expires_at,
31
+ "cnf" => {"jwk" => RootSignature.public_jwk!(agent)}, "constraints" => [
32
+ {"type" => "checkout.line_items", "items" => InputBuilder.send(:copy!, requirements)},
33
+ {"type" => "checkout.allowed_merchants", "allowed" => InputBuilder.send(:copy!, allowed_merchants)}]}
34
+ validate_open!(opening, complete: true)
35
+ disclosures = []
36
+ opening["constraints"][0]["items"].each do |group|
37
+ group["acceptable_items"] = group["acceptable_items"].map { |item| disclose!(item, disclosures) }
38
+ end
39
+ opening["constraints"][1]["allowed"] = opening["constraints"][1]["allowed"].map { |m| disclose!(m, disclosures) }
40
+ content = []
41
+ marker = disclose!(opening, content)
42
+ payload = {"ap2_profile" => PROFILE_REF, "_sd_alg" => "sha-256", "delegate_payload" => [marker]}
43
+ preview = [encode({"alg" => "ES256", "typ" => "example+sd-jwt"}), encode(payload), encode("\0" * 64)].join(".")
44
+ parse!(([preview] + content + disclosures + [""]).join("~"), complete: true)
45
+ jwt = MerchantSignature.sign!(payload, signer, provider, typ: "example+sd-jwt")
46
+ Open.send(:new, ([jwt] + content + disclosures + [""]).join("~"))
47
+ end
48
+
49
+ def self.select(open_sd_jwt:, merchant_index:, item_indices:)
50
+ parsed = parse!(open_sd_jwt, complete: true)
51
+ indices = InputBuilder.send(:copy!, item_indices)
52
+ groups = parsed.fetch(:item_slots)
53
+ raise Invalid unless indices.instance_of?(Array) && indices.size == groups.size
54
+ keep = [parsed.fetch(:content_digest), index!(parsed.fetch(:merchant_slots), merchant_index)]
55
+ groups.each_with_index do |slots, i|
56
+ chosen = indices[i]
57
+ raise Invalid unless chosen.instance_of?(Array) && chosen.size.between?(1, slots.size) && chosen.uniq.size == chosen.size
58
+ chosen.each { |n| keep << index!(slots, n) }
59
+ end
60
+ wire = ([parsed.fetch(:compact)] + parsed.fetch(:disclosures).select { |d| keep.include?(digest(d)) } + [""]).join("~")
61
+ parse!(wire, complete: false)
62
+ Open.send(:new, wire)
63
+ end
64
+
65
+ # Preparation from caller-owned checkout data only; not Merchant trust.
66
+ def self.select_for_checkout(open_sd_jwt:, checkout:)
67
+ parsed = parse!(open_sd_jwt, complete: true)
68
+ cart = InputBuilder.send(:copy!, checkout)
69
+ ScopedConstraints.multi_checkout!(cart)
70
+ opening = parsed.fetch(:opening)
71
+ merchants = opening.fetch("constraints")[1].fetch("allowed")
72
+ merchant = merchants.index(cart.fetch("merchant"))
73
+ raise Invalid unless merchant
74
+ ids = cart.fetch("line_items").map { |line| line.fetch("item").fetch("id") }
75
+ indices = opening.fetch("constraints")[0].fetch("items").map do |group|
76
+ group.fetch("acceptable_items").each_index.select { |i| ids.include?(group["acceptable_items"][i]["id"]) }
77
+ end
78
+ selected = select(open_sd_jwt: parsed.fetch(:wire), merchant_index: merchant, item_indices: indices)
79
+ details = {open: parse!(selected.root_presentation, complete: false).fetch(:opening), checkout: cart}
80
+ ScopedConstraints.send(:multi_constraints!, details, cart.fetch("currency"), ScopedConstraints.multi_checkout!(cart))
81
+ selected
82
+ end
83
+
84
+ def self.issue_closed(root_presentation:, checkout_jwt:, trusted_issuer_public_key_pem:,
85
+ agent_public_key_pem:, trusted_merchant_public_key_pem:, expected_merchant_id:,
86
+ audience:, nonce:, verified_at:, signer:)
87
+ provider = InputValidator.snapshot!(trusted_issuer_public_key_pem, max_bytes: 1_024)
88
+ agent = InputValidator.snapshot!(agent_public_key_pem, max_bytes: 1_024)
89
+ merchant = InputValidator.snapshot!(trusted_merchant_public_key_pem, max_bytes: 1_024)
90
+ identity = InputValidator.snapshot!(expected_merchant_id, max_bytes: 256)
91
+ checkout = InputValidator.snapshot!(checkout_jwt, max_bytes: 16_384)
92
+ aud = InputValidator.snapshot!(audience, max_bytes: 512)
93
+ challenge = InputValidator.snapshot!(nonce, max_bytes: 512)
94
+ raise Invalid if aud.empty? || challenge.empty?
95
+ CheckoutReceipt.send(:epoch!, verified_at)
96
+ parsed = authenticated!(root_presentation, provider)
97
+ opening = parsed.fetch(:opening)
98
+ PurchaseBinding.send(:times!, opening, verified_at)
99
+ raise Invalid unless opening["cnf"]["jwk"] == RootSignature.public_jwk!(agent)
100
+ checked = CheckoutJWT.verify(jwt: checkout, trusted_public_key_pem: merchant,
101
+ expected_merchant_id: identity, profile_ref: PROFILE_REF)
102
+ ScopedConstraints.send(:multi_constraints!, {open: opening, checkout: checked.checkout},
103
+ checked.checkout.fetch("currency"), ScopedConstraints.multi_checkout!(checked.checkout))
104
+ closed = {"vct" => "mandate.checkout.1", "iat" => opening.fetch("iat"), "exp" => opening.fetch("exp"),
105
+ "checkout_jwt" => checkout, "checkout_hash" => checked.checkout_hash}
106
+ claims = {"aud" => aud, "nonce" => challenge, "iat" => verified_at,
107
+ "sd_hash" => digest(parsed.fetch(:wire)), "delegate_payload" => [closed]}
108
+ Payment.send(:preflight!, claims, "kb+sd-jwt")
109
+ terminal = MerchantSignature.sign!(claims, signer, agent, typ: "kb+sd-jwt")
110
+ ScopedConstraints.check!(root_presentation: parsed.fetch(:wire), terminal_jws: terminal, host_checkout_jws: checkout,
111
+ trusted_issuer_public_key_pem: provider, expected_agent_public_key_pem: agent,
112
+ trusted_merchant_public_key_pem: merchant, expected_aud: aud, expected_nonce: challenge,
113
+ verified_at: verified_at, expected_checkout_id: checked.checkout.fetch("id"), expected_merchant_id: identity,
114
+ expected_currency: checked.checkout.fetch("currency"), expected_total_minor: ScopedConstraints.multi_checkout!(checked.checkout),
115
+ profile_ref: PROFILE_REF)
116
+ ConditionalCheckout::Closed.send(:new, parsed.fetch(:wire), terminal, checkout)
117
+ end
118
+
119
+ # Transport restoration only; authenticate with the genuine Host inputs.
120
+ def self.present(root_presentation:, terminal_jws:, checkout_jwt:)
121
+ parsed = parse!(root_presentation, complete: false)
122
+ terminal = InputValidator.snapshot!(terminal_jws, max_bytes: 32_768)
123
+ checkout = InputValidator.snapshot!(checkout_jwt, max_bytes: 16_384)
124
+ CheckoutReceipt.reference(closed_sd_jwt: terminal + "~", profile_ref: PROFILE_REF)
125
+ claims = Payment.send(:jwt_payload!, terminal, "kb+sd-jwt")
126
+ closed = claims.fetch("delegate_payload").first
127
+ raise Invalid unless claims["sd_hash"] == digest(parsed.fetch(:wire)) && closed["checkout_jwt"] == checkout &&
128
+ %w[iat exp].all? { |f| closed[f] == parsed.fetch(:opening)[f] }
129
+ ConditionalCheckout::Closed.send(:new, parsed.fetch(:wire), terminal, checkout)
130
+ end
131
+
132
+ def self.authenticated!(source, provider)
133
+ wire, parts = split!(source)
134
+ RootSignature.verified_payload!(parts.first, provider)
135
+ parse!(wire, complete: false)
136
+ end
137
+
138
+ def self.split!(source)
139
+ wire = InputValidator.snapshot!(source)
140
+ raise Invalid unless wire.ascii_only? && wire.end_with?("~")
141
+ parts = wire.split("~", -1)
142
+ raise Invalid unless parts.size.between?(5, MAX_DISCLOSURES + 2) && parts.last == "" && parts[0...-1].none?(&:empty?)
143
+ InputValidator.snapshot!(parts.first, max_bytes: 16_384)
144
+ [wire, parts]
145
+ end
146
+
147
+ def self.parse!(source, complete:)
148
+ RootSignature.send(:dependencies!)
149
+ wire, parts = split!(source)
150
+ claims = Payment.send(:jwt_payload!, parts.first, "example+sd-jwt")
151
+ PurchaseBinding.send(:exact!, claims, %w[ap2_profile _sd_alg delegate_payload])
152
+ raise Invalid unless claims["ap2_profile"] == PROFILE_REF && claims["_sd_alg"] == "sha-256" &&
153
+ claims["delegate_payload"].instance_of?(Array) && claims["delegate_payload"].size == 1
154
+ marker = claims["delegate_payload"].first
155
+ PurchaseBinding.send(:exact!, marker, ["..."])
156
+ hash!(marker["..."])
157
+ values = {}; salts = []
158
+ disclosures = parts[1...-1]
159
+ disclosures.each do |part|
160
+ raise Invalid if part.bytesize > MAX_SEGMENT
161
+ value = Buyer.send(:decode_disclosure!, part, 2)
162
+ hash = digest(part)
163
+ raise Invalid if values.key?(hash) || salts.include?(value[0])
164
+ salts << value[0]; values[hash] = value[1]
165
+ end
166
+ content = marker.fetch("...")
167
+ opening = InputBuilder.send(:copy!, values.fetch(content))
168
+ PurchaseBinding.send(:exact!, opening, %w[cnf constraints exp iat vct])
169
+ cs = opening.fetch("constraints")
170
+ raise Invalid unless cs.instance_of?(Array) && cs.size == 2
171
+ PurchaseBinding.send(:exact!, cs[0], %w[type items])
172
+ PurchaseBinding.send(:exact!, cs[1], %w[type allowed])
173
+ raise Invalid unless cs[0]["type"] == "checkout.line_items" && cs[1]["type"] == "checkout.allowed_merchants"
174
+ groups = cs[0]["items"]
175
+ raise Invalid unless groups.instance_of?(Array) && groups.size.between?(1, 8)
176
+ commitments = [content]; used = [content]
177
+ item_slots = groups.map do |group|
178
+ PurchaseBinding.send(:exact!, group, %w[id quantity acceptable_items])
179
+ resolve_list!(group, "acceptable_items", values, commitments, used, complete, false)
180
+ end
181
+ merchant_slots = resolve_list!(cs[1], "allowed", values, commitments, used, complete, true)
182
+ raise Invalid unless used.sort == values.keys.sort
183
+ validate_open!(opening, complete: complete)
184
+ {wire: wire, compact: parts.first, disclosures: disclosures, content_digest: content,
185
+ opening: opening, item_slots: item_slots, merchant_slots: merchant_slots}
186
+ end
187
+
188
+ def self.resolve_list!(owner, field, values, commitments, used, complete, merchant)
189
+ list = owner.fetch(field)
190
+ raise Invalid unless list.instance_of?(Array) && list.size.between?(1, 8)
191
+ selected = []
192
+ slots = list.map do |marker|
193
+ PurchaseBinding.send(:exact!, marker, ["..."])
194
+ h = marker.fetch("..."); hash!(h)
195
+ raise Invalid if commitments.include?(h)
196
+ commitments << h
197
+ if values.key?(h)
198
+ selected << values.fetch(h); used << h
199
+ elsif complete
200
+ raise Invalid
201
+ end
202
+ h
203
+ end
204
+ raise Invalid unless selected.size.between?(1, merchant && !complete ? 1 : 8)
205
+ owner[field] = selected
206
+ slots
207
+ end
208
+
209
+ def self.validate_open!(opening, complete:)
210
+ PurchaseBinding.send(:exact!, opening, %w[cnf constraints exp iat vct])
211
+ raise Invalid unless opening["vct"] == "mandate.checkout.open.1"
212
+ PurchaseBinding.send(:times!, opening, opening["iat"])
213
+ PurchaseBinding.send(:exact!, opening["cnf"], ["jwk"])
214
+ jwk = opening["cnf"]["jwk"]
215
+ PurchaseBinding.send(:exact!, jwk, %w[kty crv x y])
216
+ raise Invalid unless jwk["kty"] == "EC" && jwk["crv"] == "P-256" &&
217
+ %w[x y].all? { |f| RootSignature.send(:decode!, jwk[f], 32).bytesize == 32 }
218
+ cs = opening["constraints"]
219
+ raise Invalid unless cs.instance_of?(Array) && cs.size == 2
220
+ PurchaseBinding.send(:exact!, cs[1], %w[type allowed])
221
+ raise Invalid unless cs[1]["type"] == "checkout.allowed_merchants"
222
+ merchants = cs[1]["allowed"]
223
+ raise Invalid unless merchants.instance_of?(Array) && merchants.size.between?(1, complete ? 8 : 1)
224
+ ScopedConstraints.send(:unique_ids!, merchants)
225
+ merchants.each do |m|
226
+ PurchaseBinding.send(:exact!, m, %w[id name]); ScopedConstraints.send(:text!, m["name"], 512)
227
+ end
228
+ # Reuse the reviewed multi-item grammar with each approved merchant.
229
+ merchants.each do |m|
230
+ ScopedConstraints.send(:multi_open!, [cs[0], {"type" => "checkout.allowed_merchants", "allowed" => [m]}])
231
+ end
232
+ end
233
+ def self.index!(slots, n)
234
+ raise Invalid unless Object.instance_method(:instance_of?).bind_call(n, Integer) && n.between?(0, slots.size - 1)
235
+ slots.fetch(n)
236
+ end
237
+ def self.hash!(h)
238
+ raise Invalid unless h.instance_of?(String) && h.match?(/\A[A-Za-z0-9_-]{43}\z/) && RootSignature.send(:decode!, h, 32).bytesize == 32
239
+ end
240
+ def self.disclose!(value, disclosures)
241
+ require "securerandom"
242
+ part = encode([encode(SecureRandom.random_bytes(16)), value])
243
+ disclosures << part
244
+ {"..." => digest(part)}
245
+ end
246
+ def self.encode(value) = Buyer.send(:encode, value)
247
+ def self.digest(value) = Payment.send(:digest, value)
248
+
249
+ %i[issue_open select select_for_checkout issue_closed present].each do |name|
250
+ implementation = method(name)
251
+ fields = implementation.parameters.map(&:last).freeze
252
+ define_singleton_method(name) do |**args|
253
+ raise Invalid unless (fields - args.keys).empty? && (args.keys - fields).empty?
254
+ implementation.call(**args)
255
+ rescue StandardError, LoadError
256
+ raise Invalid.new, cause: nil
257
+ end
258
+ end
259
+ singleton_methods(false).reject { |n| %i[issue_open select select_for_checkout issue_closed present].include?(n) }.each { |n| private_class_method n }
260
+ end
261
+ end
@@ -15,18 +15,21 @@ module AP2MandateVerifier
15
15
  # All candidates and their exact Cartesian authorization come from a
16
16
  # protected approval record. This confidential issuance MUST NOT be sent.
17
17
  def self.issue_open(open_checkout_sd_jwt:, constraints:, fixed:, approved_combinations:, selective:,
18
- agent_public_key_pem:, issued_at:, expires_at:, signer:, public_key_pem:)
18
+ agent_public_key_pem:, issued_at:, expires_at:, signer:, public_key_pem:,
19
+ checkout_profile_ref: ScopedConstraints::MULTI_PROFILE_REF, profile_ref: PROFILE_REF, candidate_policy: nil)
20
+ profile_ref = PaymentPolicy.profile!(profile_ref, selective: true)
21
+ PaymentPolicy.candidate_policy!(profile_ref, candidate_policy)
19
22
  RootSignature.send(:dependencies!)
20
23
  raise Invalid unless %i[payees instruments both].include?(selective)
21
- checkout = Payment.send(:checkout_open!, open_checkout_sd_jwt)
24
+ checkout = Payment.send(:checkout_open!, open_checkout_sd_jwt, profile_ref: checkout_profile_ref)
22
25
  cs = InputBuilder.send(:copy!, constraints)
23
26
  raise Invalid unless cs.instance_of?(Array)
24
27
  cs << {"type" => "payment.reference", "conditional_transaction_id" => digest(checkout)}
25
28
  value = InputBuilder.send(:copy!, fixed)
26
- raise Invalid unless value.instance_of?(Hash) && (value.keys - Payment::FIELDS.drop(1)).empty?
29
+ raise Invalid unless value.instance_of?(Hash) && (value.keys - PaymentPolicy.fields(profile_ref).drop(1)).empty?
27
30
  opening = value.merge("vct" => "mandate.payment.open.1", "iat" => issued_at, "exp" => expires_at,
28
31
  "cnf" => {"jwk" => RootSignature.public_jwk!(agent_public_key_pem)}, "constraints" => cs)
29
- Payment.send(:open!, opening)
32
+ Payment.send(:open!, opening, profile_ref: profile_ref)
30
33
  payees = constraint!(opening, "payment.allowed_payees").fetch("allowed")
31
34
  instruments = constraint!(opening, "payment.allowed_payment_instruments").fetch("allowed")
32
35
  pairs = InputBuilder.send(:copy!, approved_combinations)
@@ -46,18 +49,19 @@ module AP2MandateVerifier
46
49
  end
47
50
  content = []
48
51
  pointer = disclose!(opening, content)
49
- payload = {"ap2_profile" => PROFILE_REF, "_sd_alg" => "sha-256", "delegate_payload" => [pointer]}
52
+ payload = {"ap2_profile" => profile_ref, "_sd_alg" => "sha-256", "delegate_payload" => [pointer]}
50
53
  preview = [encode({"alg" => "ES256", "typ" => "example+sd-jwt"}), encode(payload), encode("\0" * 64)].join(".")
51
54
  wire = ([preview] + content + disclosures + [""]).join("~")
52
- parse!(wire, complete: true) # Full wire/disclosure bounds BEFORE signer effects.
55
+ parse!(wire, complete: true, profile_ref: profile_ref) # Full wire/disclosure bounds BEFORE signer effects.
53
56
  jwt = MerchantSignature.sign!(payload, signer, public_key_pem, typ: "example+sd-jwt")
54
57
  ([jwt] + content + disclosures + [""]).join("~").freeze
55
58
  end
56
59
 
57
60
  # Each selective index selects one original signed candidate slot. For an
58
61
  # inline/nonselective axis, pass nil: every approved inline value is visible.
59
- def self.select(open_sd_jwt:, payee_index:, instrument_index:)
60
- parsed = parse!(open_sd_jwt, complete: true)
62
+ def self.select(open_sd_jwt:, payee_index:, instrument_index:, profile_ref: PROFILE_REF)
63
+ profile_ref = PaymentPolicy.profile!(profile_ref, selective: true)
64
+ parsed = parse!(open_sd_jwt, complete: true, profile_ref: profile_ref)
61
65
  keep = [parsed.fetch(:content_digest)]
62
66
  {"payment.allowed_payees" => payee_index, "payment.allowed_payment_instruments" => instrument_index}.each do |type, index|
63
67
  c = constraint!(parsed.fetch(:original), type)
@@ -73,42 +77,47 @@ module AP2MandateVerifier
73
77
  end
74
78
  end
75
79
  wire = ([parsed.fetch(:compact)] + parsed.fetch(:disclosures).select { |d| keep.include?(digest(d)) } + [""]).join("~")
76
- parse!(wire, complete: false)
80
+ parse!(wire, complete: false, profile_ref: profile_ref)
77
81
  wire.freeze
78
82
  end
79
83
 
80
84
  def self.issue_closed(open_presentation:, payment:, trusted_provider_public_key_pem:, agent_public_key_pem:,
81
- audience:, nonce:, verified_at:, signer:)
85
+ audience:, nonce:, verified_at:, signer:, profile_ref: PROFILE_REF)
86
+ profile_ref = PaymentPolicy.profile!(profile_ref, selective: true)
82
87
  agent = InputValidator.snapshot!(agent_public_key_pem, max_bytes: 1_024)
83
88
  provider = InputValidator.snapshot!(trusted_provider_public_key_pem, max_bytes: 1_024)
84
89
  aud = InputValidator.snapshot!(audience, max_bytes: 512)
85
90
  challenge = InputValidator.snapshot!(nonce, max_bytes: 512)
86
- parsed = authenticated!(open_presentation, provider)
91
+ parsed = authenticated!(open_presentation, provider, profile_ref: profile_ref)
87
92
  opening = parsed.fetch(:opening)
88
93
  Payment.send(:valid_now!, opening, verified_at)
89
94
  raise Invalid unless opening.fetch("cnf") == {"jwk" => RootSignature.public_jwk!(agent)}
90
- closed = Payment.send(:copy_details!, payment).merge("vct" => "mandate.payment.1", "iat" => verified_at, "exp" => opening.fetch("exp"))
91
- Payment.send(:closed!, closed); Payment.send(:conditions!, opening, closed)
95
+ closed = Payment.send(:copy_details!, payment, profile_ref: profile_ref).merge("vct" => "mandate.payment.1", "iat" => verified_at, "exp" => opening.fetch("exp"))
96
+ Payment.send(:closed!, closed, profile_ref: profile_ref); Payment.send(:conditions!, opening, closed, profile_ref: profile_ref)
92
97
  Payment.send(:text!, aud, 512); Payment.send(:text!, challenge, 512)
93
98
  claims = {"delegate_payload" => [closed], "iat" => verified_at, "aud" => aud, "nonce" => challenge,
94
99
  "sd_hash" => digest(parsed.fetch(:wire))}
95
- Payment.send(:preflight!, claims, "kb+sd-jwt")
100
+ claims["ap2_profile"] = profile_ref if PaymentPolicy.enabled?(profile_ref)
101
+ Payment.send(:preflight!, claims, "kb+sd-jwt", profile_ref: profile_ref)
96
102
  terminal = MerchantSignature.sign!(claims, signer, agent, typ: "kb+sd-jwt")
97
103
  Payment::Presentation.send(:new, parsed.fetch(:wire), terminal + "~")
98
104
  end
99
105
 
100
106
  # Structural restoration only. It never authenticates a stored presentation.
101
- def self.present(open_presentation:, closed_sd_jwt:)
102
- root = parse!(open_presentation, complete: false)
103
- terminal, wire = Payment.send(:final!, closed_sd_jwt, conditional: true)
107
+ def self.present(open_presentation:, closed_sd_jwt:, profile_ref: PROFILE_REF)
108
+ profile_ref = PaymentPolicy.profile!(profile_ref, selective: true)
109
+ root = parse!(open_presentation, complete: false, profile_ref: profile_ref)
110
+ terminal, wire = Payment.send(:final!, closed_sd_jwt, conditional: true, profile_ref: profile_ref)
104
111
  closed = terminal.fetch("delegate_payload").first
105
- bind_terminal!(root, terminal, closed)
112
+ bind_terminal!(root, terminal, closed, profile_ref: profile_ref)
106
113
  Payment::Presentation.send(:new, root.fetch(:wire), wire)
107
114
  end
108
115
 
109
116
  def self.verify(open_presentation:, closed_sd_jwt:, checkout_inputs:, expected_payment:,
110
117
  trusted_provider_public_key_pem:, expected_agent_public_key_pem:,
111
- expected_audience:, expected_nonce:, verified_at:)
118
+ expected_audience:, expected_nonce:, verified_at:, profile_ref: PROFILE_REF, trusted_pisp: nil, execution_at: nil)
119
+ profile_ref = PaymentPolicy.profile!(profile_ref, selective: true)
120
+ context = PaymentPolicy.context!(profile_ref, trusted_pisp, execution_at)
112
121
  CheckoutReceipt.send(:epoch!, verified_at)
113
122
  agent = InputValidator.snapshot!(expected_agent_public_key_pem, max_bytes: 1_024)
114
123
  provider = InputValidator.snapshot!(trusted_provider_public_key_pem, max_bytes: 1_024)
@@ -122,7 +131,7 @@ module AP2MandateVerifier
122
131
  [key, key == :verified_at ? value : InputValidator.snapshot!(value, max_bytes: limits.fetch(key, 131_072))]
123
132
  end.freeze
124
133
  raise Invalid unless inputs.size == fields.size && fields.all? { |f| inputs.key?(f) } && inputs[:verified_at] == verified_at
125
- expected = Payment.send(:copy_details!, expected_payment)
134
+ expected = Payment.send(:copy_details!, expected_payment, profile_ref: profile_ref)
126
135
  checkout = AP2MandateVerifier.verify_checkout(**inputs)
127
136
  raise Invalid unless checkout.success?
128
137
  raise Invalid unless expected.fetch("transaction_id") == digest(inputs.fetch(:host_checkout_jws))
@@ -131,39 +140,40 @@ module AP2MandateVerifier
131
140
  raise Invalid unless expected.fetch("payee").fetch("id") == binding.fetch("merchant_id") &&
132
141
  amount.fetch("currency") == binding.fetch("currency") && amount.fetch("amount") == binding.fetch("expected_total")
133
142
  Payment.send(:bind_checkout!, expected, Payment.send(:jwt_payload!, inputs.fetch(:host_checkout_jws), "JWT"))
134
- parsed = authenticated!(open_presentation, provider)
143
+ parsed = authenticated!(open_presentation, provider, profile_ref: profile_ref)
135
144
  opening = parsed.fetch(:opening)
136
145
  Payment.send(:valid_now!, opening, verified_at)
137
146
  raise Invalid unless opening.fetch("cnf") == {"jwk" => RootSignature.public_jwk!(agent)}
138
- terminal, wire = Payment.send(:final!, closed_sd_jwt, conditional: true)
147
+ terminal, wire = Payment.send(:final!, closed_sd_jwt, conditional: true, profile_ref: profile_ref)
139
148
  RootSignature.verified_payload!(wire.split("~", -1).first, agent,
140
149
  expected_typ: "kb+sd-jwt", max_bytes: 32_768)
141
150
  Payment.send(:text!, aud, 512); Payment.send(:text!, nonce, 512)
142
151
  raise Invalid unless terminal.fetch("aud") == aud && terminal.fetch("nonce") == nonce &&
143
152
  terminal.fetch("iat") <= verified_at && verified_at - terminal.fetch("iat") <= 300
144
153
  closed = terminal.fetch("delegate_payload").first
145
- bind_terminal!(parsed, terminal, closed)
154
+ bind_terminal!(parsed, terminal, closed, profile_ref: profile_ref)
146
155
  Payment.send(:valid_now!, closed, verified_at)
147
156
  ref = constraint!(opening, "payment.reference").fetch("conditional_transaction_id")
148
- raise Invalid unless ref == digest(inputs.fetch(:root_presentation)) && closed.slice(*Payment::FIELDS) == expected
157
+ PaymentPolicy.bind_context!(closed, context) if context
158
+ raise Invalid unless ref == digest(inputs.fetch(:root_presentation)) && closed.slice(*PaymentPolicy.fields(profile_ref)) == expected
149
159
  Payment::Verification.send(:new, closed, wire)
150
160
  rescue StandardError, LoadError
151
161
  Payment::Verification.send(:new)
152
162
  end
153
163
 
154
- def self.bind_terminal!(root, terminal, closed)
164
+ def self.bind_terminal!(root, terminal, closed, profile_ref: PROFILE_REF)
155
165
  opening = root.fetch(:opening)
156
- Payment.send(:closed!, closed)
166
+ Payment.send(:closed!, closed, profile_ref: profile_ref)
157
167
  raise Invalid unless terminal.fetch("sd_hash") == digest(root.fetch(:wire)) && terminal.fetch("iat") == closed.fetch("iat") &&
158
168
  closed.fetch("iat") >= opening.fetch("iat") && closed.fetch("exp") <= opening.fetch("exp")
159
- Payment.send(:conditions!, opening, closed)
169
+ Payment.send(:conditions!, opening, closed, profile_ref: profile_ref)
160
170
  end
161
- def self.authenticated!(wire, key)
162
- parsed = parse!(wire, complete: false)
171
+ def self.authenticated!(wire, key, profile_ref: PROFILE_REF)
172
+ parsed = parse!(wire, complete: false, profile_ref: profile_ref)
163
173
  RootSignature.verified_payload!(parsed.fetch(:compact), key, max_bytes: 16_384)
164
174
  parsed
165
175
  end
166
- def self.parse!(source, complete:)
176
+ def self.parse!(source, complete:, profile_ref: PROFILE_REF)
167
177
  RootSignature.send(:dependencies!)
168
178
  wire = InputValidator.snapshot!(source, max_bytes: MAX_WIRE)
169
179
  raise Invalid unless wire.ascii_only? && wire.end_with?("~")
@@ -173,7 +183,7 @@ module AP2MandateVerifier
173
183
  compact = InputValidator.snapshot!(compact, max_bytes: 16_384)
174
184
  claims = Payment.send(:jwt_payload!, compact, "example+sd-jwt")
175
185
  Payment.send(:exact!, claims, %w[ap2_profile _sd_alg delegate_payload])
176
- raise Invalid unless claims["ap2_profile"] == PROFILE_REF && claims["_sd_alg"] == "sha-256" &&
186
+ raise Invalid unless claims["ap2_profile"] == profile_ref && claims["_sd_alg"] == "sha-256" &&
177
187
  claims["delegate_payload"].instance_of?(Array) && claims["delegate_payload"].size == 1
178
188
  pointer = claims.fetch("delegate_payload").first
179
189
  Payment.send(:exact!, pointer, ["..."])
@@ -217,7 +227,7 @@ module AP2MandateVerifier
217
227
  end
218
228
  raise Invalid if slots.values.all?(&:empty?)
219
229
  raise Invalid unless used.sort == values.keys.sort
220
- Payment.send(:open!, opening) # Only candidate markers were resolved/omitted.
230
+ Payment.send(:open!, opening, profile_ref: profile_ref) # Only candidate markers were resolved/omitted.
221
231
  {wire: wire, compact: compact, disclosures: disclosures, opening: opening,
222
232
  original: original, content_digest: content_digest, slots: slots, values: values}
223
233
  end
@@ -242,9 +252,10 @@ module AP2MandateVerifier
242
252
 
243
253
  %i[issue_open select issue_closed present verify].each do |name|
244
254
  implementation = method(name)
255
+ required = implementation.parameters.filter_map { |kind, field| field if kind == :keyreq }.freeze
245
256
  fields = implementation.parameters.map(&:last).freeze
246
257
  define_singleton_method(name) do |**args|
247
- unless (fields - args.keys).empty? && (args.keys - fields).empty?
258
+ unless (required - args.keys).empty? && (args.keys - fields).empty?
248
259
  next Payment::Verification.send(:new) if name == :verify
249
260
  raise Invalid
250
261
  end
@@ -12,6 +12,10 @@ module AP2MandateVerifier
12
12
  MULTI_PROFILE_VERSION = "1"
13
13
  MULTI_PROFILE_BODY = '{"profile_ref":"ap2.checkout.single_merchant_multi_item","version":"1","ap2_source":"b4587ac1d055888a73b4b21750973cffba961793","algorithm":"ES256","key_format":"canonical-public-SPKI-P256-SHA256","root_type":"example+sd-jwt","terminal_type":"kb+sd-jwt","checkout_type":"JWT","disclosure_path_semantics":"root-walker-with-synthetic-disclosed-edges","disclosure_positions":["delegate_payload[0]","delegate_payload[0].disclosed.constraints[0].items[*].acceptable_items[*]","delegate_payload[0].disclosed.constraints[1].allowed[0]"],"constraints":["checkout.line_items","checkout.allowed_merchants"],"max_disclosures":66,"max_disclosure_segment_bytes":8192,"max_root_bytes":131072,"max_graph_nodes":2048,"max_graph_depth":24,"max_array_entries":16,"max_line_items":8,"max_requirements":8,"max_candidates_per_requirement":8,"quantity_matching":"integer-max-flow-product-id-exact-coverage","duplicate_line_ids":"reject","duplicate_requirement_ids":"reject","same_product_multiple_lines":"allow","amount_model":"integer-minor-unit-no-tax-shipping-discount"}'.freeze
14
14
  MULTI_PROFILE_HASH = Digest::SHA256.hexdigest(MULTI_PROFILE_BODY).freeze
15
+ SELECTIVE_PROFILE_REF = "ap2.checkout.selective_candidates.1".freeze
16
+ SELECTIVE_PROFILE_VERSION = "1".freeze
17
+ SELECTIVE_PROFILE_BODY = '{"profile_ref":"ap2.checkout.selective_candidates.1","version":"1","ap2_source":"b4587ac1d055888a73b4b21750973cffba961793","algorithm":"ES256","root_type":"example+sd-jwt","terminal_type":"kb+sd-jwt","checkout_type":"JWT","signed_profile_marker":"ap2_profile","mandatory_content":"all-requirements-id-quantity-cnf-iat-exp","selective_positions":["constraints[0].items[*].acceptable_items[*]","constraints[1].allowed[*]"],"max_disclosures":73,"max_disclosure_segment_bytes":8192,"max_root_bytes":131072,"max_requirements":8,"max_candidates_per_requirement":8,"max_merchants":8,"merchant_selection":"exactly-one","item_selection":"nonempty-subset-per-requirement","candidate_policy":"independent-lists-no-correlation","quantity_matching":"integer-max-flow-product-id-exact-coverage","amount_model":"integer-minor-unit-no-tax-shipping-discount"}'.freeze
18
+ SELECTIVE_PROFILE_HASH = Digest::SHA256.hexdigest(SELECTIVE_PROFILE_BODY).freeze
15
19
 
16
20
  # Explicit Host policy registration. Signed token claims never select this.
17
21
  def self.profile!(reference)
@@ -20,6 +24,8 @@ module AP2MandateVerifier
20
24
  {ref: PROFILE_REF, version: PROFILE_VERSION, body: PROFILE_BODY, hash: PROFILE_HASH}.freeze
21
25
  when MULTI_PROFILE_REF
22
26
  {ref: MULTI_PROFILE_REF, version: MULTI_PROFILE_VERSION, body: MULTI_PROFILE_BODY, hash: MULTI_PROFILE_HASH}.freeze
27
+ when SELECTIVE_PROFILE_REF
28
+ {ref: SELECTIVE_PROFILE_REF, version: SELECTIVE_PROFILE_VERSION, body: SELECTIVE_PROFILE_BODY, hash: SELECTIVE_PROFILE_HASH}.freeze
23
29
  else
24
30
  reject!(:unsupported_trust_profile)
25
31
  end
@@ -18,6 +18,8 @@ require_relative "ap2_mandate_verifier/conditional_checkout"
18
18
  require_relative "ap2_mandate_verifier/payment"
19
19
  require_relative "ap2_mandate_verifier/payment_receipt"
20
20
  require_relative "ap2_mandate_verifier/selective_payment"
21
+ require_relative "ap2_mandate_verifier/selective_checkout"
22
+ require_relative "ap2_mandate_verifier/payment_policy"
21
23
 
22
24
  module AP2MandateVerifier
23
25
  # 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.2.0
4
+ version: 1.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - AP2 Mandate Verifier contributors
8
8
  bindir: bin
9
9
  cert_chain: []
10
- date: 1980-01-02 00:00:00.000000000 Z
10
+ date: 2026-11-04 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: json
@@ -82,9 +82,9 @@ dependencies:
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
84
  full verification with immutable Evidence, Checkout Receipts, Direct and conditional
85
- Payment Mandates, and Payment Receipts. Adds opt-in selective Payment candidate
86
- disclosure. Requires independently trusted application inputs; verification does
87
- not grant purchase or payment permission.'
85
+ Payment Mandates, and Payment Receipts. Adds opt-in selective Checkout and Payment
86
+ disclosure plus explicit PISP and execution-date constraints. Requires independently
87
+ trusted application inputs; verification does not grant purchase or payment permission.'
88
88
  executables: []
89
89
  extensions: []
90
90
  extra_rdoc_files: []
@@ -101,17 +101,24 @@ files:
101
101
  - docs/MERCHANT_SIGNING.md
102
102
  - docs/MULTI_ITEM_CHECKOUT.md
103
103
  - docs/PAYMENT.md
104
+ - docs/PAYMENT_POLICY.md
104
105
  - docs/POST_RELEASE_110.md
105
106
  - docs/POST_RELEASE_MAINTENANCE.md
106
107
  - docs/PUBLIC_API.md
107
108
  - docs/RELEASE_100_CANDIDATE.md
108
109
  - docs/RELEASE_110_CANDIDATE.md
109
110
  - docs/RELEASE_120_CANDIDATE.md
111
+ - docs/RELEASE_130_CANDIDATE.md
112
+ - docs/RELEASE_140_CANDIDATE.md
113
+ - docs/SELECTIVE_CHECKOUT.md
110
114
  - docs/SELECTIVE_PAYMENT.md
111
115
  - docs/SUPPORT_CONTRACT.md
112
116
  - docs/evidence/1.1.0_publication.json
113
117
  - examples/conditional_checkout.rb
114
118
  - examples/payment.rb
119
+ - examples/payment_policy.rb
120
+ - examples/selective_checkout.rb
121
+ - examples/selective_checkout_payment.rb
115
122
  - examples/selective_payment.rb
116
123
  - lib/ap2_mandate_verifier.rb
117
124
  - lib/ap2_mandate_verifier/buyer.rb
@@ -124,6 +131,7 @@ files:
124
131
  - lib/ap2_mandate_verifier/input_validator.rb
125
132
  - lib/ap2_mandate_verifier/merchant_signature.rb
126
133
  - lib/ap2_mandate_verifier/payment.rb
134
+ - lib/ap2_mandate_verifier/payment_policy.rb
127
135
  - lib/ap2_mandate_verifier/payment_receipt.rb
128
136
  - lib/ap2_mandate_verifier/purchase_binding.rb
129
137
  - lib/ap2_mandate_verifier/research_result.rb
@@ -131,6 +139,7 @@ files:
131
139
  - lib/ap2_mandate_verifier/root_disclosures.rb
132
140
  - lib/ap2_mandate_verifier/root_signature.rb
133
141
  - lib/ap2_mandate_verifier/scoped_constraints.rb
142
+ - lib/ap2_mandate_verifier/selective_checkout.rb
134
143
  - lib/ap2_mandate_verifier/selective_payment.rb
135
144
  - lib/ap2_mandate_verifier/trust_context.rb
136
145
  homepage: https://github.com/cuichangquan/ap2-mandate-verifier
@@ -154,7 +163,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
154
163
  - !ruby/object:Gem::Version
155
164
  version: '0'
156
165
  requirements: []
157
- rubygems_version: 4.0.20
166
+ rubygems_version: 3.6.9
158
167
  specification_version: 4
159
168
  summary: Ruby SDK for supported AP2 Checkout and Payment Mandates
160
169
  test_files: []