ap2_mandate_verifier 1.1.0 → 1.3.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,97 @@
1
+ # frozen_string_literal: true
2
+ # Ordinary installed Gem only. No test fixtures, source-path loading or network.
3
+ require "ap2_mandate_verifier"
4
+ require "openssl"
5
+
6
+ module SelectiveCheckoutExample
7
+ M = AP2MandateVerifier
8
+ PROFILE = M::SelectiveCheckout::PROFILE_REF
9
+ NOW = 1_800_000_000
10
+ def self.totals(n) = %w[subtotal total].map { |type| {"type" => type, "amount" => n} }
11
+ def self.run
12
+ provider, agent, merchant = Array.new(3) { OpenSSL::PKey::EC.generate("prime256v1") }
13
+ seller = {"id" => "shop", "name" => "Office supplies"}
14
+ # This protected record is created AFTER application authentication, display
15
+ # of these conditions and authority/consent checks. No approved flag is proof.
16
+ requirements = [{"id" => "choice", "quantity" => 1,
17
+ "acceptable_items" => %w[A B].map { |id| {"id" => id, "title" => "Product #{id}"} }},
18
+ {"id" => "required", "quantity" => 2, "acceptable_items" => [{"id" => "C", "title" => "Product C"}]}]
19
+ full = M::SelectiveCheckout.issue_open(allowed_merchants: [seller, {"id" => "private-shop", "name" => "Private alternative merchant"}],
20
+ requirements: requirements, candidate_policy: :independent,
21
+ agent_public_key_pem: agent.public_to_pem, issued_at: NOW, expires_at: NOW + 600,
22
+ signer: M::CheckoutJWT.es256_signer(private_key: provider), public_key_pem: provider.public_to_pem)
23
+ # Store full securely. The complete candidate universe is not sent to the merchant.
24
+ opening = M::SelectiveCheckout.select(open_sd_jwt: full.root_presentation,
25
+ merchant_index: 0, item_indices: [[1], [0]])
26
+ visible = opening.root_presentation.split("~", -1)[1...-1].map do |part|
27
+ JSON.parse(Base64.urlsafe_decode64(part))
28
+ end
29
+ raise "privacy boundary failed" if JSON.generate(visible).include?("private-shop") ||
30
+ visible.any? { |disclosure| disclosure[1] == {"id" => "A", "title" => "Product A"} }
31
+ puts "Checkout retained full disclosures=#{full.root_presentation.count('~') - 1}; sent=#{opening.root_presentation.count('~') - 1}"
32
+ puts "Checkout issuer JWT unchanged=#{full.root_presentation.split('~').first == opening.root_presentation.split('~').first}; unselected candidate values not sent"
33
+ # Merchant Checkout has three rows, including C in two distinct rows.
34
+ lines = %w[B C C].each_with_index.map do |id, i|
35
+ {"id" => "row-#{i}", "item" => {"id" => id, "title" => "Product #{id}", "price" => 100},
36
+ "quantity" => 1, "totals" => totals(100)}
37
+ end
38
+ order = {"id" => "office-1", "merchant" => seller, "status" => "ready_for_complete",
39
+ "currency" => "USD", "line_items" => lines, "totals" => totals(300), "links" => []}
40
+ inferred = M::SelectiveCheckout.select_for_checkout(open_sd_jwt: full.root_presentation, checkout: order)
41
+ raise "selection mismatch" unless inferred.root_presentation == opening.root_presentation
42
+ checkout = M::CheckoutJWT.sign(checkout: order, profile_ref: PROFILE,
43
+ signer: M::CheckoutJWT.es256_signer(private_key: merchant), public_key_pem: merchant.public_to_pem)
44
+
45
+ # Host enrollment and challenge are synthetic authenticated application data.
46
+ roles = %w[Issuer Agent Merchant]
47
+ records = roles.zip([provider, agent, merchant]).map do |role, key|
48
+ {"role" => role, "identity" => role == "Merchant" ? "shop" : role.downcase,
49
+ "tenant_id" => "tenant", "purpose" => "checkout", "key_ref" => role.downcase,
50
+ "public_key_pem" => key.public_to_pem, "active" => true, "not_before" => NOW - 1, "not_after" => NOW + 1000}
51
+ end
52
+ selectors = records.to_h { |record| [record["role"].downcase.to_sym, record.slice("identity", "purpose", "key_ref")] }
53
+ trust = M::InputBuilder.trust(snapshot: {"id" => "registry", "policy_version" => "1", "active" => true,
54
+ "not_before" => NOW - 1, "not_after" => NOW + 1000, "records" => records},
55
+ tenant_id: "tenant", verified_at: NOW, profile_ref: PROFILE, **selectors)
56
+ host_order = {"tenant_id" => "tenant", "buyer_account_id" => "buyer", "order_id" => "office-1",
57
+ "merchant_id" => "shop", "audience" => "merchant-host", "order_version" => "1", "currency" => "USD", "expected_total" => 300}
58
+ host_inputs = {trust: trust, order: host_order, root_presentation: opening.root_presentation, host_checkout_jws: checkout.jwt}
59
+ saved = M::InputBuilder.prepare(**host_inputs, challenge_id: "challenge-1", nonce: "synthetic-one-use-nonce",
60
+ issuer_id: "host", not_before: NOW, not_after: NOW + 60)
61
+ # Agent receives public trust, Open, Checkout, challenge and its own signer.
62
+ # Provider signer/private key is not an input to this operation.
63
+ closed = M::SelectiveCheckout.issue_closed(root_presentation: opening.root_presentation, checkout_jwt: checkout.jwt,
64
+ trusted_issuer_public_key_pem: provider.public_to_pem, agent_public_key_pem: agent.public_to_pem,
65
+ trusted_merchant_public_key_pem: merchant.public_to_pem, expected_merchant_id: "shop",
66
+ audience: "merchant-host", nonce: "synthetic-one-use-nonce", verified_at: NOW,
67
+ signer: M::CheckoutJWT.es256_signer(private_key: agent))
68
+ wire = M::SelectiveCheckout.present(root_presentation: closed.root_presentation,
69
+ terminal_jws: closed.terminal_jws, checkout_jwt: closed.checkout_jwt)
70
+ checked = M::InputBuilder.verify(**host_inputs, terminal_jws: wire.terminal_jws,
71
+ saved_challenge: M::InputBuilder.restore(saved_challenge: saved), expected_challenge_issuer_id: "host",
72
+ clock_source_id: "synthetic-clock", verified_at: NOW)
73
+ raise "verification failed" unless checked.success?
74
+ puts "Open -> Agent Closed -> merchant evidence: verified=true; rows=3; requirements=2"
75
+ # These are ALTERNATIVE synthetic application outcomes, never two executions.
76
+ %w[Success Error].each do |outcome|
77
+ fields = outcome == "Success" ? {order_id: "office-1"} : {error: "policy_rejected", error_description: "Application declined"}
78
+ receipt = M::CheckoutReceipt.sign(closed_sd_jwt: wire.closed_sd_jwt, profile_ref: PROFILE,
79
+ issuer: "shop", outcome: outcome, issued_at: NOW, **fields,
80
+ signer: M::CheckoutJWT.es256_signer(private_key: merchant), public_key_pem: merchant.public_to_pem)
81
+ result = M::CheckoutReceipt.verify(jwt: receipt.jwt, closed_sd_jwt: wire.closed_sd_jwt,
82
+ profile_ref: PROFILE, trusted_public_key_pem: merchant.public_to_pem, expected_issuer: "shop",
83
+ not_before: NOW, not_after: NOW + 60, verified_at: NOW)
84
+ raise "receipt failed" unless result.verified? && result.outcome == outcome
85
+ puts "Receipt #{outcome}: authentic=true; purchase_succeeded=#{result.purchase_succeeded?}"
86
+ end
87
+ # Application state, not an SDK purchase permit: durable transaction/CAS in
88
+ # real code must consume approval/challenge/order once and save its receipt.
89
+ states = {"success" => :consumed, "error" => :requires_new_policy_decision, "missing_receipt" => :pending}
90
+ raise "unknown replay" unless states["missing_receipt"] == :pending
91
+ puts "Success=consumed; Error=policy decision; missing Receipt/uncertain commit=pending"
92
+ puts "Synthetic only; evidence and Receipt authenticity are not payment completion."
93
+ {opening: opening, closed: closed, result: checked, host_inputs: host_inputs, saved: saved,
94
+ keys: [provider, agent, merchant], requirements: requirements, checkout: order}
95
+ end
96
+ end
97
+ SelectiveCheckoutExample.run if $PROGRAM_NAME == __FILE__
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+ # Installed SDK only. Confidential issuance stays local; simulated payments only.
3
+ require "ap2_mandate_verifier"
4
+ require_relative "selective_checkout"
5
+ module SelectiveCheckoutPaymentExample
6
+ M = AP2MandateVerifier
7
+ NOW = SelectiveCheckoutExample::NOW
8
+ def self.run
9
+ state = SelectiveCheckoutExample.run
10
+ provider, agent, merchant = state.fetch(:keys)
11
+ signer = ->(key) { M::CheckoutJWT.es256_signer(private_key: key) }
12
+ checkout = state.fetch(:closed).checkout_jwt
13
+ chosen_instrument = {"id" => "synthetic-card-A", "type" => "card"}
14
+ details = M::Payment.details(checkout_jwt: checkout, trusted_merchant_public_key_pem: merchant.public_to_pem,
15
+ expected_merchant_id: "shop", payment_instrument: chosen_instrument)
16
+ payees = [details.fetch("payee"), {"id" => "another-shop", "name" => "Private alternative payee"}]
17
+ instruments = [chosen_instrument, {"id" => "private-alternative-B", "type" => "card"}]
18
+ conditions = [{"type" => "payment.amount_range", "currency" => "USD", "min" => 100, "max" => 300},
19
+ {"type" => "payment.allowed_payees", "allowed" => payees},
20
+ {"type" => "payment.allowed_payment_instruments", "allowed" => instruments}]
21
+ # This list comes from the app's PROTECTED approval record: every crossproduct
22
+ # combination is expressly approved. Do not expand a correlated subset here.
23
+ approved_combinations = [[0, 0], [0, 1], [1, 0], [1, 1]]
24
+ full = M::SelectivePayment.issue_open(open_checkout_sd_jwt: state.fetch(:opening).root_presentation,
25
+ checkout_profile_ref: M::SelectiveCheckout::PROFILE_REF,
26
+ constraints: conditions, fixed: {}, approved_combinations: approved_combinations, selective: :both,
27
+ agent_public_key_pem: agent.public_to_pem, issued_at: NOW, expires_at: NOW+60,
28
+ signer: signer.call(provider), public_key_pem: provider.public_to_pem)
29
+ reduced = M::SelectivePayment.select(open_sd_jwt: full, payee_index: 0, instrument_index: 0)
30
+ transmitted_disclosures = reduced.split("~", -1)[1...-1]
31
+ visible = transmitted_disclosures.map { |wire| JSON.parse(Base64.urlsafe_decode64(wire)) }
32
+ hidden_leaves = full.split("~", -1)[1...-1].select do |wire|
33
+ value = JSON.parse(Base64.urlsafe_decode64(wire))[1]
34
+ value == payees[1] || value == instruments[1]
35
+ end
36
+ raise "privacy boundary failed" unless (hidden_leaves & transmitted_disclosures).empty? &&
37
+ !JSON.generate(visible).include?("Private alternative") && !JSON.generate(visible).include?("private-alternative-B")
38
+ # Keep full confidential issuance in protected storage; send only reduced.
39
+ # No original unselected disclosure or confidential full wire is printed.
40
+ puts "Retained locally: payees=2; instruments=2; disclosures=#{full.count('~')-1}; bytes=#{full.bytesize}"
41
+ puts "Sent: chosen payee=shop; chosen instrument=synthetic-card-A; disclosures=#{reduced.count('~')-1}; bytes=#{reduced.bytesize}"
42
+ puts "Issuer JWT unchanged=#{full.split('~').first == reduced.split('~').first}; presentation bytes changed=#{full != reduced}"
43
+ closed = M::SelectivePayment.issue_closed(open_presentation: reduced, payment: details,
44
+ trusted_provider_public_key_pem: provider.public_to_pem, agent_public_key_pem: agent.public_to_pem,
45
+ audience: "credential-provider", nonce: "synthetic-selective-payment-nonce", verified_at: NOW,
46
+ signer: signer.call(agent))
47
+ restored = M::SelectivePayment.present(open_presentation: reduced, closed_sd_jwt: closed.closed_sd_jwt)
48
+ checkout_inputs = M::InputBuilder.inputs(**state.fetch(:host_inputs), saved_challenge: state.fetch(:saved),
49
+ terminal_jws: state.fetch(:closed).terminal_jws, expected_challenge_issuer_id: "host",
50
+ clock_source_id: "synthetic-clock", verified_at: NOW)
51
+ verified = M::SelectivePayment.verify(open_presentation: restored.open_sd_jwt, closed_sd_jwt: restored.closed_sd_jwt,
52
+ checkout_inputs: checkout_inputs, expected_payment: details, trusted_provider_public_key_pem: provider.public_to_pem,
53
+ expected_agent_public_key_pem: agent.public_to_pem, expected_audience: "credential-provider",
54
+ expected_nonce: "synthetic-selective-payment-nonce", verified_at: NOW)
55
+ raise "selective verification failed" unless verified.verified?
56
+ puts "Selected Payment verified=true; unselected candidate values/disclosures were not sent"
57
+ %w[Success Error].each do |outcome|
58
+ fields = outcome == "Success" ? {psp_confirmation_id: "synthetic-psp", network_confirmation_id: "synthetic-network"} :
59
+ {error: "declined", error_description: "Simulated rejection"}
60
+ receipt = M::PaymentReceipt.sign(closed_sd_jwt: restored.closed_sd_jwt, issuer: "processor",
61
+ payment_id: "synthetic-selective-payment", outcome: outcome, issued_at: NOW, **fields,
62
+ signer: signer.call(merchant), public_key_pem: merchant.public_to_pem)
63
+ checked = M::PaymentReceipt.verify(jwt: receipt.jwt, closed_sd_jwt: restored.closed_sd_jwt,
64
+ trusted_public_key_pem: merchant.public_to_pem, expected_issuer: "processor", expected_payment_id: "synthetic-selective-payment",
65
+ not_before: NOW, not_after: NOW+60, verified_at: NOW)
66
+ raise "receipt failed" unless checked.verified? && checked.outcome == outcome
67
+ puts "Payment Receipt #{outcome}: authentic=#{checked.verified?}; reported_success=#{checked.payment_succeeded?}"
68
+ end
69
+ puts "Synthetic only. Verification is not execution permission; one-use atomic state belongs to the app; unknown outcome remains pending."
70
+ end
71
+ end
72
+ SelectiveCheckoutPaymentExample.run if $PROGRAM_NAME == __FILE__
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+ # Installed SDK only. Confidential issuance stays local; simulated payments only.
3
+ require "ap2_mandate_verifier"
4
+ require_relative "conditional_checkout"
5
+ module SelectivePaymentExample
6
+ M = AP2MandateVerifier
7
+ NOW = ConditionalCheckoutExample::NOW
8
+ def self.run
9
+ state = ConditionalCheckoutExample.run
10
+ provider, agent, merchant = state.fetch(:keys)
11
+ signer = ->(key) { M::CheckoutJWT.es256_signer(private_key: key) }
12
+ checkout = state.fetch(:closed).checkout_jwt
13
+ chosen_instrument = {"id" => "synthetic-card-A", "type" => "card"}
14
+ details = M::Payment.details(checkout_jwt: checkout, trusted_merchant_public_key_pem: merchant.public_to_pem,
15
+ expected_merchant_id: "shop", payment_instrument: chosen_instrument)
16
+ payees = [details.fetch("payee"), {"id" => "another-shop", "name" => "Private alternative payee"}]
17
+ instruments = [chosen_instrument, {"id" => "private-alternative-B", "type" => "card"}]
18
+ conditions = [{"type" => "payment.amount_range", "currency" => "USD", "min" => 100, "max" => 300},
19
+ {"type" => "payment.allowed_payees", "allowed" => payees},
20
+ {"type" => "payment.allowed_payment_instruments", "allowed" => instruments}]
21
+ # This list comes from the app's PROTECTED approval record: every crossproduct
22
+ # combination is expressly approved. Do not expand a correlated subset here.
23
+ approved_combinations = [[0, 0], [0, 1], [1, 0], [1, 1]]
24
+ full = M::SelectivePayment.issue_open(open_checkout_sd_jwt: state.fetch(:opening).root_presentation,
25
+ constraints: conditions, fixed: {}, approved_combinations: approved_combinations, selective: :both,
26
+ agent_public_key_pem: agent.public_to_pem, issued_at: NOW, expires_at: NOW+60,
27
+ signer: signer.call(provider), public_key_pem: provider.public_to_pem)
28
+ reduced = M::SelectivePayment.select(open_sd_jwt: full, payee_index: 0, instrument_index: 0)
29
+ transmitted_disclosures = reduced.split("~", -1)[1...-1]
30
+ visible = transmitted_disclosures.map { |wire| JSON.parse(Base64.urlsafe_decode64(wire)) }
31
+ hidden_leaves = full.split("~", -1)[1...-1].select do |wire|
32
+ value = JSON.parse(Base64.urlsafe_decode64(wire))[1]
33
+ value == payees[1] || value == instruments[1]
34
+ end
35
+ raise "privacy boundary failed" unless (hidden_leaves & transmitted_disclosures).empty? &&
36
+ !JSON.generate(visible).include?("Private alternative") && !JSON.generate(visible).include?("private-alternative-B")
37
+ # Keep full confidential issuance in protected storage; send only reduced.
38
+ # No original unselected disclosure or confidential full wire is printed.
39
+ puts "Retained locally: payees=2; instruments=2; disclosures=#{full.count('~')-1}; bytes=#{full.bytesize}"
40
+ puts "Sent: chosen payee=shop; chosen instrument=synthetic-card-A; disclosures=#{reduced.count('~')-1}; bytes=#{reduced.bytesize}"
41
+ puts "Issuer JWT unchanged=#{full.split('~').first == reduced.split('~').first}; presentation bytes changed=#{full != reduced}"
42
+ closed = M::SelectivePayment.issue_closed(open_presentation: reduced, payment: details,
43
+ trusted_provider_public_key_pem: provider.public_to_pem, agent_public_key_pem: agent.public_to_pem,
44
+ audience: "credential-provider", nonce: "synthetic-selective-payment-nonce", verified_at: NOW,
45
+ signer: signer.call(agent))
46
+ restored = M::SelectivePayment.present(open_presentation: reduced, closed_sd_jwt: closed.closed_sd_jwt)
47
+ checkout_inputs = M::InputBuilder.inputs(**state.fetch(:host_inputs), saved_challenge: state.fetch(:saved),
48
+ terminal_jws: state.fetch(:closed).terminal_jws, expected_challenge_issuer_id: "host",
49
+ clock_source_id: "synthetic-clock", verified_at: NOW)
50
+ verified = M::SelectivePayment.verify(open_presentation: restored.open_sd_jwt, closed_sd_jwt: restored.closed_sd_jwt,
51
+ checkout_inputs: checkout_inputs, expected_payment: details, trusted_provider_public_key_pem: provider.public_to_pem,
52
+ expected_agent_public_key_pem: agent.public_to_pem, expected_audience: "credential-provider",
53
+ expected_nonce: "synthetic-selective-payment-nonce", verified_at: NOW)
54
+ raise "selective verification failed" unless verified.verified?
55
+ puts "Selected Payment verified=true; unselected candidate values/disclosures were not sent"
56
+ %w[Success Error].each do |outcome|
57
+ fields = outcome == "Success" ? {psp_confirmation_id: "synthetic-psp", network_confirmation_id: "synthetic-network"} :
58
+ {error: "declined", error_description: "Simulated rejection"}
59
+ receipt = M::PaymentReceipt.sign(closed_sd_jwt: restored.closed_sd_jwt, issuer: "processor",
60
+ payment_id: "synthetic-selective-payment", outcome: outcome, issued_at: NOW, **fields,
61
+ signer: signer.call(merchant), public_key_pem: merchant.public_to_pem)
62
+ checked = M::PaymentReceipt.verify(jwt: receipt.jwt, closed_sd_jwt: restored.closed_sd_jwt,
63
+ trusted_public_key_pem: merchant.public_to_pem, expected_issuer: "processor", expected_payment_id: "synthetic-selective-payment",
64
+ not_before: NOW, not_after: NOW+60, verified_at: NOW)
65
+ raise "receipt failed" unless checked.verified? && checked.outcome == outcome
66
+ puts "Payment Receipt #{outcome}: authentic=#{checked.verified?}; reported_success=#{checked.payment_succeeded?}"
67
+ end
68
+ puts "Synthetic only. Verification is not execution permission; one-use atomic state belongs to the app; unknown outcome remains pending."
69
+ end
70
+ end
71
+ SelectivePaymentExample.run if $PROGRAM_NAME == __FILE__
@@ -72,7 +72,7 @@ module AP2MandateVerifier
72
72
 
73
73
  def self.validate!(checkout, profile_ref: TrustContext::PROFILE_REF)
74
74
  profile_ref = InputValidator.snapshot!(profile_ref, max_bytes: 256)
75
- if profile_ref == ScopedConstraints::MULTI_PROFILE_REF
75
+ if [ScopedConstraints::MULTI_PROFILE_REF, TrustContext::SELECTIVE_PROFILE_REF].include?(profile_ref)
76
76
  ScopedConstraints.multi_checkout!(checkout)
77
77
  return nil
78
78
  end
@@ -113,7 +113,7 @@ module AP2MandateVerifier
113
113
  value = InputValidator.parse!(wire)
114
114
  shape!(value, %w[format_version profile_ref profile_version challenge], "saved_challenge")
115
115
  invalid!("saved_challenge", :unsupported_saved_format) unless
116
- [TrustContext::PROFILE_REF, TrustContext::MULTI_PROFILE_REF].include?(value["profile_ref"])
116
+ [TrustContext::PROFILE_REF, TrustContext::MULTI_PROFILE_REF, TrustContext::SELECTIVE_PROFILE_REF].include?(value["profile_ref"])
117
117
  profile = TrustContext.profile!(value["profile_ref"])
118
118
  invalid!("saved_challenge", :unsupported_saved_format) unless value.values_at("format_version", "profile_ref", "profile_version") ==
119
119
  [FORMAT_VERSION, profile[:ref], profile[:version]]
@@ -59,9 +59,9 @@ module AP2MandateVerifier
59
59
  # Reference is calculated over exact original Open Checkout, never rebuilt JSON.
60
60
  # The app authenticates consent to these conditions before invoking this API.
61
61
  def self.issue_open(open_checkout_sd_jwt:, constraints:, fixed:, agent_public_key_pem:,
62
- issued_at:, expires_at:, signer:, public_key_pem:)
62
+ issued_at:, expires_at:, signer:, public_key_pem:, checkout_profile_ref: ScopedConstraints::MULTI_PROFILE_REF)
63
63
  RootSignature.send(:dependencies!)
64
- root = checkout_open!(open_checkout_sd_jwt)
64
+ root = checkout_open!(open_checkout_sd_jwt, profile_ref: checkout_profile_ref)
65
65
  conditions = InputBuilder.send(:copy!, constraints)
66
66
  raise Invalid unless conditions.instance_of?(Array)
67
67
  conditions << {"type" => "payment.reference", "conditional_transaction_id" => digest(root)}
@@ -76,6 +76,7 @@ module AP2MandateVerifier
76
76
  # Provider signer is deliberately absent. Existing signed Open grants the hop.
77
77
  def self.issue_closed(open_sd_jwt:, payment:, trusted_provider_public_key_pem:, agent_public_key_pem:,
78
78
  audience:, nonce:, verified_at:, signer:)
79
+ agent_public_key_pem = InputValidator.snapshot!(agent_public_key_pem, max_bytes: 1_024)
79
80
  opening, root = verified_root!(open_sd_jwt, trusted_provider_public_key_pem)
80
81
  open!(opening); valid_now!(opening, verified_at)
81
82
  raise Invalid unless opening.fetch("cnf") == {"jwk" => RootSignature.public_jwk!(agent_public_key_pem)}
@@ -124,6 +125,10 @@ module AP2MandateVerifier
124
125
  checkout_inputs = checkout_inputs.to_h do |key, value|
125
126
  [key, key == :verified_at ? value : InputValidator.snapshot!(value, max_bytes: limits.fetch(key, 131_072))]
126
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
127
132
  expected = copy_details!(expected_payment)
128
133
  case checkout_mode
129
134
  when :direct
@@ -266,9 +271,15 @@ module AP2MandateVerifier
266
271
  CheckoutReceipt.send(:epoch!, now)
267
272
  raise Invalid unless v.fetch("iat") <= now && now < v.fetch("exp")
268
273
  end
269
- def self.checkout_open!(wire)
274
+ def self.checkout_open!(wire, profile_ref: ScopedConstraints::MULTI_PROFILE_REF)
270
275
  wire = InputValidator.snapshot!(wire)
271
- opening = RootDisclosures.send(:structural_root!, wire).fetch("delegate_payload").first
276
+ profile = InputValidator.snapshot!(profile_ref, max_bytes: 256)
277
+ opening = if profile == TrustContext::SELECTIVE_PROFILE_REF
278
+ SelectiveCheckout.send(:parse!, wire, complete: false).fetch(:opening)
279
+ else
280
+ raise Invalid unless profile == ScopedConstraints::MULTI_PROFILE_REF
281
+ RootDisclosures.send(:structural_root!, wire).fetch("delegate_payload").first
282
+ end
272
283
  raise Invalid unless opening.fetch("vct") == "mandate.checkout.open.1"
273
284
  wire
274
285
  end
@@ -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