ap2_mandate_verifier 1.4.0 → 1.6.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.
Files changed (37) hide show
  1. checksums.yaml +4 -4
  2. data/README.ja.md +31 -8
  3. data/README.md +31 -8
  4. data/SECURITY.md +8 -2
  5. data/docs/LONG_PAYMENT.md +82 -0
  6. data/docs/PAYMENT_ACCEPTANCE.md +90 -0
  7. data/docs/PAYMENT_POLICY.md +4 -2
  8. data/docs/PUBLIC_API.md +16 -2
  9. data/docs/RECURRING_PAYMENT.md +54 -0
  10. data/docs/RELEASE_140_CANDIDATE.md +2 -0
  11. data/docs/RELEASE_150_CANDIDATE.md +23 -0
  12. data/docs/RELEASE_160_CANDIDATE.md +30 -0
  13. data/docs/SUPPORT_CONTRACT.md +9 -1
  14. data/examples/conditional_checkout.rb +3 -3
  15. data/examples/long_payment.rb +116 -0
  16. data/examples/long_payment_acceptance.rb +89 -0
  17. data/examples/payment_acceptance.rb +77 -0
  18. data/examples/recurring_payment.rb +99 -0
  19. data/lib/ap2_mandate_verifier/checkout_jwt.rb +1 -1
  20. data/lib/ap2_mandate_verifier/checkout_receipt.rb +10 -1
  21. data/lib/ap2_mandate_verifier/conditional_checkout.rb +43 -19
  22. data/lib/ap2_mandate_verifier/input_builder.rb +1 -1
  23. data/lib/ap2_mandate_verifier/long_payment.rb +201 -0
  24. data/lib/ap2_mandate_verifier/payment.rb +52 -12
  25. data/lib/ap2_mandate_verifier/payment_acceptance/long_sqlite_store.rb +272 -0
  26. data/lib/ap2_mandate_verifier/payment_acceptance/recurring_sqlite_store.rb +124 -0
  27. data/lib/ap2_mandate_verifier/payment_acceptance/sqlite_store.rb +344 -0
  28. data/lib/ap2_mandate_verifier/payment_acceptance.rb +285 -0
  29. data/lib/ap2_mandate_verifier/payment_policy.rb +7 -2
  30. data/lib/ap2_mandate_verifier/purchase_binding.rb +11 -5
  31. data/lib/ap2_mandate_verifier/recurring_payment.rb +111 -0
  32. data/lib/ap2_mandate_verifier/root_disclosures.rb +9 -6
  33. data/lib/ap2_mandate_verifier/scoped_constraints.rb +1 -1
  34. data/lib/ap2_mandate_verifier/selective_payment.rb +1 -1
  35. data/lib/ap2_mandate_verifier/trust_context.rb +6 -0
  36. data/lib/ap2_mandate_verifier.rb +6 -0
  37. metadata +22 -5
@@ -8,7 +8,7 @@ module ConditionalCheckoutExample
8
8
  PROFILE = M::ConditionalCheckout::PROFILE_REF
9
9
  NOW = 1_800_000_000
10
10
  def self.totals(n) = %w[subtotal total].map { |type| {"type" => type, "amount" => n} }
11
- def self.run
11
+ def self.run(currency: "USD")
12
12
  provider, agent, merchant = Array.new(3) { OpenSSL::PKey::EC.generate("prime256v1") }
13
13
  seller = {"id" => "shop", "name" => "Office supplies"}
14
14
  # This protected record is created AFTER application authentication, display
@@ -25,7 +25,7 @@ module ConditionalCheckoutExample
25
25
  "quantity" => 1, "totals" => totals(100)}
26
26
  end
27
27
  order = {"id" => "office-1", "merchant" => seller, "status" => "ready_for_complete",
28
- "currency" => "USD", "line_items" => lines, "totals" => totals(300), "links" => []}
28
+ "currency" => currency, "line_items" => lines, "totals" => totals(300), "links" => []}
29
29
  checkout = M::CheckoutJWT.sign(checkout: order, profile_ref: PROFILE,
30
30
  signer: M::CheckoutJWT.es256_signer(private_key: merchant), public_key_pem: merchant.public_to_pem)
31
31
 
@@ -41,7 +41,7 @@ module ConditionalCheckoutExample
41
41
  "not_before" => NOW - 1, "not_after" => NOW + 1000, "records" => records},
42
42
  tenant_id: "tenant", verified_at: NOW, profile_ref: PROFILE, **selectors)
43
43
  host_order = {"tenant_id" => "tenant", "buyer_account_id" => "buyer", "order_id" => "office-1",
44
- "merchant_id" => "shop", "audience" => "merchant-host", "order_version" => "1", "currency" => "USD", "expected_total" => 300}
44
+ "merchant_id" => "shop", "audience" => "merchant-host", "order_version" => "1", "currency" => currency, "expected_total" => 300}
45
45
  host_inputs = {trust: trust, order: host_order, root_presentation: opening.root_presentation, host_checkout_jws: checkout.jwt}
46
46
  saved = M::InputBuilder.prepare(**host_inputs, challenge_id: "challenge-1", nonce: "synthetic-one-use-nonce",
47
47
  issuer_id: "host", not_before: NOW, not_after: NOW + 60)
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+ # Installed SDK only. Synthetic wire fixtures; no storage or payment execution.
3
+ require "ap2_mandate_verifier"
4
+ require "openssl"
5
+
6
+ module LongPaymentExample
7
+ M = AP2MandateVerifier
8
+ L = M::LongPayment
9
+ T0 = Time.utc(2028, 1, 1).to_i
10
+ EXP = Time.utc(2029, 1, 1).to_i
11
+ PERIODS = (1..12).to_h do |month|
12
+ finish = month == 12 ? Time.utc(2029,1,1).to_i : Time.utc(2028,month+1,1).to_i
13
+ [format("2028-%02d",month), [Time.utc(2028,month,1).to_i,finish].freeze]
14
+ end.freeze
15
+ SELLER = {"id" => "shop", "name" => "Synthetic Long Shop"}.freeze
16
+ REQUIREMENTS = [{"id" => "monthly", "quantity" => 1,
17
+ "acceptable_items" => [{"id" => "long-item", "title" => "Monthly supplies"}]}].freeze
18
+ def self.now(period) = PERIODS.fetch(period)[0] + 3600
19
+ def self.signer(key) = M::CheckoutJWT.es256_signer(private_key: key)
20
+ def self.totals(n) = %w[subtotal total].map { |kind| {"type" => kind, "amount" => n} }
21
+ def self.cart(period, amount = 40000)
22
+ raise "unknown synthetic period/amount" unless PERIODS.key?(period) && amount.instance_of?(Integer) && amount.between?(1,100000)
23
+ {"id" => "long-#{period}-#{amount}", "merchant" => SELLER, "status" => "ready_for_complete", "currency" => "JPY", "links" => [],
24
+ "line_items" => [{"id" => "row-1", "quantity" => 1, "item" => {"id" => "long-item", "title" => "Monthly supplies", "price" => amount}, "totals" => totals(amount)}], "totals" => totals(amount)}
25
+ end
26
+ def self.inputs(period:, checkout_open:, payment_open:, checkout_jwt:, checkout_closed:, payment_closed:,
27
+ provider:, agent:, merchant:, amount: 40000, authority: {})
28
+ at = now(period)
29
+ raise "unknown synthetic authority option" unless (authority.keys - %i[snapshot_id policy_version not_before not_after issuer agent merchant]).empty?
30
+ start = authority.fetch(:not_before,T0-1); finish = authority.fetch(:not_after,EXP)
31
+ keys = [authority.fetch(:issuer,provider),authority.fetch(:agent,agent),authority.fetch(:merchant,merchant)]
32
+ records = %w[Issuer Agent Merchant].zip(keys).map do |role,key|
33
+ {"role" => role,"identity" => role == "Merchant" ? "shop" : role.downcase,"tenant_id" => "long-tenant","purpose" => "checkout",
34
+ "key_ref" => role.downcase,"public_key_pem" => key,"active" => true,"not_before" => start,"not_after" => finish}
35
+ end
36
+ selectors = records.to_h { |r| [r["role"].downcase.to_sym,r.slice("identity","purpose","key_ref")] }
37
+ trust = M::InputBuilder.trust(snapshot: {"id" => authority.fetch(:snapshot_id,"long-registry-1"),"policy_version" => authority.fetch(:policy_version,"long-authority-1"),
38
+ "active" => true,"not_before" => start,"not_after" => finish,"records" => records},tenant_id:"long-tenant",verified_at:at,
39
+ profile_ref:L::CHECKOUT_PROFILE_REF,**selectors)
40
+ value = cart(period,amount)
41
+ order = {"tenant_id" => "long-tenant","buyer_account_id" => "synthetic-buyer","order_id" => value.fetch("id"),"merchant_id" => "shop",
42
+ "audience" => "merchant-host","order_version" => "1","currency" => "JPY","expected_total" => amount}
43
+ host = {trust:trust,order:order,root_presentation:checkout_open,host_checkout_jws:checkout_jwt}
44
+ saved = M::InputBuilder.prepare(**host,challenge_id:"challenge-#{period}-#{amount}",nonce:"checkout-nonce-#{period}-#{amount}",issuer_id:"host",
45
+ not_before:at-1,not_after:at+120)
46
+ raw = M::InputBuilder.inputs(**host,saved_challenge:saved,terminal_jws:checkout_closed.delete_suffix("~"),expected_challenge_issuer_id:"host",
47
+ clock_source_id:"synthetic-clock-#{period}",verified_at:at)
48
+ payment = L.details(checkout_jwt:checkout_jwt,trusted_merchant_public_key_pem:merchant,expected_merchant_id:"shop",payment_instrument:{"id"=>"synthetic-card","type"=>"card"})
49
+ {open_sd_jwt:payment_open,closed_sd_jwt:payment_closed,checkout_mode: :conditional,checkout_inputs:raw,expected_payment:payment,
50
+ trusted_provider_public_key_pem:provider,expected_agent_public_key_pem:agent,expected_audience:"payment-host",
51
+ expected_nonce:"payment-nonce-#{period}-#{amount}",verified_at:at,profile_ref:L::PROFILE_REF}
52
+ end
53
+ class Fixture
54
+ attr_reader :provider,:agent,:merchant,:checkout_open,:payment_open,:issued_at,:expires_at
55
+ def initialize(max_occurrences:12,budget:480000,amount:40000,provider:nil,agent:nil,merchant:nil,
56
+ issued_at:T0,expires_at:EXP,requirements:REQUIREMENTS,seller:SELLER,fixed:{},authority:{})
57
+ @provider,@agent,@merchant = [provider,agent,merchant].map { |key| key || OpenSSL::PKey::EC.generate("prime256v1") }
58
+ @issued_at,@expires_at,@amount = issued_at,expires_at,amount
59
+ @max_occurrences,@budget,@requirements,@seller,@fixed,@authority = max_occurrences,budget,requirements,seller,fixed,authority
60
+ @checkout_open = L.issue_checkout_open(merchant:seller,requirements:requirements,agent_public_key_pem:@agent.public_to_pem,
61
+ issued_at:issued_at,expires_at:expires_at,signer:LongPaymentExample.signer(@provider),public_key_pem:@provider.public_to_pem).root_presentation
62
+ cs = [{"type"=>"payment.amount_range","currency"=>"JPY","min"=>1,"max"=>100000},
63
+ {"type"=>"payment.allowed_payees","allowed"=>[seller]},
64
+ {"type"=>"payment.allowed_payment_instruments","allowed"=>[{"id"=>"synthetic-card","type"=>"card"}]},
65
+ {"type"=>"payment.agent_recurrence","frequency"=>"MONTHLY","max_occurrences"=>max_occurrences},
66
+ {"type"=>"payment.budget","currency"=>"JPY","max"=>budget}]
67
+ @payment_open = L.issue_open(open_checkout_sd_jwt:@checkout_open,constraints:cs,fixed:fixed,candidate_policy: :independent,
68
+ agent_public_key_pem:@agent.public_to_pem,issued_at:issued_at,expires_at:expires_at,
69
+ signer:LongPaymentExample.signer(@provider),public_key_pem:@provider.public_to_pem)
70
+ end
71
+ def month(period, amount = nil, **options)
72
+ raise "unknown synthetic month option" unless (options.keys - %i[amount authority merchant]).empty?
73
+ value = options.fetch(:amount,amount || @amount); at = LongPaymentExample.now(period)
74
+ merchant = options.fetch(:merchant,@merchant)
75
+ cart = LongPaymentExample.cart(period,value)
76
+ jwt = M::CheckoutJWT.sign(checkout:cart,profile_ref:L::CHECKOUT_PROFILE_REF,signer:LongPaymentExample.signer(merchant),public_key_pem:merchant.public_to_pem).jwt
77
+ closed_checkout = L.issue_checkout_closed(root_presentation:@checkout_open,checkout_jwt:jwt,trusted_issuer_public_key_pem:@provider.public_to_pem,
78
+ agent_public_key_pem:@agent.public_to_pem,trusted_merchant_public_key_pem:merchant.public_to_pem,expected_merchant_id:"shop",audience:"merchant-host",
79
+ nonce:"checkout-nonce-#{period}-#{value}",verified_at:at,signer:LongPaymentExample.signer(@agent))
80
+ payment = L.details(checkout_jwt:jwt,trusted_merchant_public_key_pem:merchant.public_to_pem,expected_merchant_id:"shop",payment_instrument:{"id"=>"synthetic-card","type"=>"card"})
81
+ closed_payment = L.issue_closed(open_sd_jwt:@payment_open,payment:payment,trusted_provider_public_key_pem:@provider.public_to_pem,
82
+ agent_public_key_pem:@agent.public_to_pem,audience:"payment-host",nonce:"payment-nonce-#{period}-#{value}",verified_at:at,signer:LongPaymentExample.signer(@agent))
83
+ verify = LongPaymentExample.inputs(period:period,checkout_open:@checkout_open,payment_open:@payment_open,checkout_jwt:jwt,
84
+ checkout_closed:closed_checkout.closed_sd_jwt,payment_closed:closed_payment.closed_sd_jwt,provider:@provider.public_to_pem,
85
+ agent:@agent.public_to_pem,merchant:merchant.public_to_pem,amount:value,authority:options.fetch(:authority,@authority))
86
+ raise "synthetic long wire verification failed" unless L.verify(**verify).verified?
87
+ receipts = [{kind:"checkout",key:merchant.public_to_pem,jwt:M::CheckoutReceipt.sign(closed_sd_jwt:closed_checkout.closed_sd_jwt,profile_ref:L::CHECKOUT_PROFILE_REF,
88
+ issuer:"processor",outcome:"Success",order_id:cart.fetch("id"),issued_at:at,signer:LongPaymentExample.signer(merchant),public_key_pem:merchant.public_to_pem).jwt},
89
+ {kind:"payment",key:merchant.public_to_pem,jwt:M::PaymentReceipt.sign(closed_sd_jwt:closed_payment.closed_sd_jwt,profile_ref:L::PROFILE_REF,
90
+ issuer:"processor",outcome:"Success",payment_id:"payment-#{period}",issued_at:at,psp_confirmation_id:"synthetic-psp",network_confirmation_id:"synthetic-net",
91
+ signer:LongPaymentExample.signer(merchant),public_key_pem:merchant.public_to_pem).jwt}]
92
+ {period:period,now:at,amount:value,cart:cart,checkout_jwt:jwt,checkout_closed:closed_checkout.closed_sd_jwt,payment_closed:closed_payment.closed_sd_jwt,
93
+ expected_payment:payment,verify_inputs:verify,receipts:receipts}
94
+ end
95
+ def rotate(provider:,agent:,merchant:@merchant,issued_at:,authority:)
96
+ self.class.new(provider:provider,agent:agent,merchant:merchant,issued_at:issued_at,expires_at:@expires_at,max_occurrences:@max_occurrences,budget:@budget,
97
+ amount:@amount,requirements:@requirements,seller:@seller,fixed:@fixed,authority:authority)
98
+ end
99
+ def public_fixture
100
+ months = PERIODS.keys.select { |period| @issued_at <= LongPaymentExample.now(period) && LongPaymentExample.now(period) < @expires_at }.map { |period| month(period) }
101
+ {t0:@issued_at,exp:@expires_at,checkout_open:@checkout_open,payment_open:@payment_open,provider:@provider.public_to_pem,agent:@agent.public_to_pem,
102
+ merchant:@merchant.public_to_pem,profiles:{checkout:L::CHECKOUT_PROFILE_REF,payment:L::PROFILE_REF},periods:PERIODS,months:months}
103
+ end
104
+ end
105
+ def self.run
106
+ fixture = Fixture.new
107
+ months = PERIODS.keys.map { |period| fixture.month(period) }
108
+ raise "changed long Open" unless months.all? { |m| m[:verify_inputs][:open_sd_jwt] == fixture.payment_open && m[:verify_inputs][:checkout_inputs][:root_presentation] == fixture.checkout_open }
109
+ puts "Long wire: all 12 leap-year months verified with the same complete Open Checkout and Open Payment"
110
+ puts "Shared content iat/exp preserved; outer proof, current trust, challenge and order verified freshly"
111
+ puts "Wire verification reserves no occurrence or budget; protected Host period/authority storage is required"
112
+ puts "Synthetic only; no payment, settlement or generic MONTHLY calendar conformance is established"
113
+ fixture
114
+ end
115
+ end
116
+ LongPaymentExample.run if $PROGRAM_NAME == __FILE__
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+ # Installed Gem only; optional sqlite3=2.10.2. All keys/orders/effects synthetic.
3
+ require "ap2_mandate_verifier"
4
+ require "tmpdir"
5
+ require_relative "long_payment"
6
+
7
+ module LongPaymentAcceptanceExample
8
+ M = AP2MandateVerifier
9
+ A = M::PaymentAcceptance
10
+ L = M::LongPayment
11
+ W = LongPaymentExample
12
+ def self.build(max_occurrences: 12, budget_max: 100000, amount: 40000, **wire_options)
13
+ wire = W::Fixture.new(max_occurrences: max_occurrences, budget: budget_max, amount: amount, **wire_options)
14
+ {wire: wire, series_scope: {tenant_id: "long-tenant", merchant_id: "shop", approval_id: "long-consent-1"}, amount: amount}
15
+ end
16
+ def self.periods
17
+ W::PERIODS.map { |id,(first,last)| {id: id, not_before: first, not_after: last} }
18
+ end
19
+ def self.pair_arguments(fixture, period)
20
+ raw = fixture.fetch(:wire).month(period).fetch(:verify_inputs)
21
+ {payment_open: fixture.fetch(:wire).payment_open, checkout_open: fixture.fetch(:wire).checkout_open,
22
+ trust_json: raw.fetch(:checkout_inputs).fetch(:trust_json), selection_json: raw.fetch(:checkout_inputs).fetch(:selection_json),
23
+ verified_at: raw.fetch(:verified_at)}
24
+ end
25
+ def self.enroll_series(store, fixture)
26
+ first = W::PERIODS.keys.find { |period| fixture.fetch(:wire).issued_at <= W.now(period) }
27
+ store.authorize_series!(**fixture.fetch(:series_scope), **pair_arguments(fixture, first),
28
+ periods: periods, schedule_policy_id: A::LongSQLiteStore::SCHEDULE_POLICY)
29
+ end
30
+ def self.refresh_authority(store, fixture, period)
31
+ data = pair_arguments(fixture, period).slice(:trust_json, :selection_json, :verified_at)
32
+ store.update_authority!(**fixture.fetch(:series_scope), expected_epoch: store.usage(**fixture.fetch(:series_scope)).fetch(:epoch), **data)
33
+ end
34
+ def self.occurrence(fixture, period:, id: "one", amount: nil, now: nil)
35
+ item = fixture.fetch(:wire).month(period, amount || fixture.fetch(:amount))
36
+ raw = item.fetch(:verify_inputs)
37
+ if now
38
+ raw = Marshal.load(Marshal.dump(raw))
39
+ raw[:verified_at] = now
40
+ raw[:checkout_inputs][:verified_at] = now
41
+ end
42
+ scope = fixture.fetch(:series_scope).merge(operation_id: "operation-#{period}-#{id}", occurrence_id: period,
43
+ order_id: item.fetch(:cart).fetch("id"))
44
+ merchant = fixture.fetch(:wire).merchant
45
+ context = {trusted_public_key_pem: merchant.public_to_pem, expected_issuer: "processor",
46
+ expected_payment_id: "payment-#{period}", not_before: W::PERIODS.fetch(period)[0], not_after: W::EXP + 86400}
47
+ error = M::PaymentReceipt.sign(closed_sd_jwt: raw.fetch(:closed_sd_jwt), profile_ref: L::PROFILE_REF,
48
+ issuer: "processor", payment_id: "payment-#{period}", outcome: "Error", issued_at: raw.fetch(:verified_at),
49
+ error: "synthetic", error_description: "No automatic allowance refund", signer: W.signer(merchant), public_key_pem: merchant.public_to_pem)
50
+ {scope: scope, raw: raw, authorization: scope.merge(mode: :conditional, profile_ref: L::PROFILE_REF,
51
+ checkout: item.fetch(:cart), payment: item.fetch(:expected_payment), receipt_context: context),
52
+ error_receipt: error.jwt, payment_receipt: item.fetch(:receipts).find { |receipt| receipt[:kind] == "payment" }.fetch(:jwt),
53
+ checkout: item.fetch(:cart)}
54
+ end
55
+ def self.replace_root(store, fixture, replacement, period)
56
+ current = store.usage(**fixture.fetch(:series_scope))
57
+ store.replace_root!(**fixture.fetch(:series_scope), expected_epoch: current.fetch(:epoch),
58
+ expected_root_reference: current.fetch(:root_reference), **pair_arguments(replacement, period))
59
+ end
60
+ def self.run
61
+ fixture = build(amount: 8000) # Twelve approved uses, total96000JPY within100000.
62
+ Dir.mktmpdir("synthetic-long-payment-") do |directory|
63
+ store = A::LongSQLiteStore.create(path: File.join(directory, "ledger.sqlite3"))
64
+ enroll_series(store, fixture)
65
+ service = A::Service.new(store: store)
66
+ dispatches = 0
67
+ W::PERIODS.each_key do |period|
68
+ refresh_authority(store, fixture, period)
69
+ item = occurrence(fixture, period: period)
70
+ store.authorize!(**item.fetch(:authorization))
71
+ result = service.accept(**item.fetch(:scope), mode: :conditional, verification_inputs: item.fetch(:raw))
72
+ raise "long reservation failed" unless result.status == :reserved && result.ticket
73
+ execution = service.start(ticket: result.ticket, verification_inputs: item.fetch(:raw))
74
+ raise "fresh start failed" unless execution
75
+ dispatches += 1 # Synthetic in-process mock, NOT an external payment.
76
+ service.unknown(ticket: result.ticket)
77
+ recovered = service.reconcile(**item.fetch(:scope), receipt_jwt: item.fetch(:payment_receipt), verified_at: item.fetch(:raw).fetch(:verified_at))
78
+ raise "original Receipt failed" unless recovered.status == :receipt_success && recovered.ticket.nil?
79
+ end
80
+ usage = store.usage(**fixture.fetch(:series_scope))
81
+ raise "bad long totals" unless dispatches == 12 && usage[:reserved_occurrences] == 12 && usage[:reserved_amount] == 96000
82
+ puts "Same long Open pair: 12 explicit leap-year periods, 12 mock starts, reserved96000JPY within100000JPY"
83
+ puts "Fresh proof/current authority checked before each start; original Receipts reconciled without new Tickets"
84
+ store.close
85
+ end
86
+ puts "Synthetic only; no payment/settlement. Host windows are an explicit local profile, not generic AP2 MONTHLY semantics."
87
+ end
88
+ end
89
+ LongPaymentAcceptanceExample.run if $PROGRAM_NAME == __FILE__
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+ # Installed SDK; optional sqlite3=2.10.2. Synthetic temporary DB/mock processor.
3
+ # Production uses a protected persistent existing DB, never per-request temp storage.
4
+ require "ap2_mandate_verifier"
5
+ require "tmpdir"
6
+ require_relative "selective_checkout"
7
+ module PaymentAcceptanceExample
8
+ M = AP2MandateVerifier
9
+ A = M::PaymentAcceptance
10
+ NOW = SelectiveCheckoutExample::NOW
11
+ def self.run
12
+ state = SelectiveCheckoutExample.run
13
+ provider, agent, merchant = state.fetch(:keys)
14
+ signer = ->(key) { M::CheckoutJWT.es256_signer(private_key: key) }
15
+ checkout = state.fetch(:closed).checkout_jwt
16
+ details = M::Payment.details(checkout_jwt: checkout, trusted_merchant_public_key_pem: merchant.public_to_pem,
17
+ expected_merchant_id: "shop", payment_instrument: {"id" => "synthetic-card", "type" => "card"})
18
+ buyer = M::Buyer.issue_closed(checkout_jwt: checkout, approved_checkout_jwt: checkout,
19
+ trusted_merchant_public_key_pem: merchant.public_to_pem, expected_merchant_id: "shop", issued_at: NOW,
20
+ expires_at: NOW + 60, signer: signer.call(provider), public_key_pem: provider.public_to_pem)
21
+ payment_args = {payment: details, approved_payment: details, issued_at: NOW, expires_at: NOW + 60,
22
+ signer: signer.call(provider), public_key_pem: provider.public_to_pem}
23
+ payment = M::Payment.issue_direct(**payment_args)
24
+ raw = {closed_sd_jwt: payment.closed_sd_jwt, checkout_mode: :direct, checkout_inputs: {
25
+ closed_sd_jwt: buyer.closed_sd_jwt, trusted_provider_public_key_pem: provider.public_to_pem,
26
+ trusted_merchant_public_key_pem: merchant.public_to_pem, expected_checkout_jwt: checkout,
27
+ expected_merchant_id: "shop", verified_at: NOW}, expected_payment: details,
28
+ trusted_provider_public_key_pem: provider.public_to_pem, verified_at: NOW}
29
+ # These identifiers/terms are protected authenticated Host approval state,
30
+ # never request-generated retry UUIDs or values copied from received claims.
31
+ scope = {tenant_id: "tenant", merchant_id: "shop", operation_id: "office-1/payment-1",
32
+ approval_id: "synthetic-consent-1", occurrence_id: "payment-1", order_id: "office-1"}
33
+ Dir.mktmpdir("ap2-acceptance-example") do |directory|
34
+ path = File.join(directory, "acceptance.sqlite3")
35
+ store = A::SQLiteStore.create(path: path) # Explicit ONE-TIME bootstrap only.
36
+ store.authorize!(**scope, mode: :direct, profile_ref: M::Payment::PROFILE_REF,
37
+ checkout: state.fetch(:checkout), payment: details, receipt_context: {
38
+ trusted_public_key_pem: merchant.public_to_pem, expected_issuer: "processor-A",
39
+ expected_payment_id: "synthetic-payment-1", not_before: NOW, not_after: NOW + 1000})
40
+ service = A::Service.new(store: store)
41
+ first = service.accept(**scope, mode: :direct, verification_inputs: raw)
42
+ raise "first reservation failed" unless first.status == :reserved && first.ticket
43
+ # New salt/signature changes original bytes, but not the approved business operation.
44
+ resigned = M::Payment.issue_direct(**payment_args)
45
+ replay = service.accept(**scope, mode: :direct, verification_inputs: raw.merge(closed_sd_jwt: resigned.closed_sd_jwt))
46
+ raise "retry issued another ticket" unless replay.status == :pending && replay.ticket.nil? &&
47
+ replay.closed_sd_jwt == payment.closed_sd_jwt && replay.processor_key == first.processor_key
48
+ puts "First=reserved; re-signed retry=pending; no second Ticket; first wire retained"
49
+ # Production supplies FRESH authenticated Host/trust/order/clock inputs here.
50
+ execution = service.start(ticket: first.ticket, verification_inputs: raw)
51
+ raise "start failed" unless execution && !service.start(ticket: first.ticket, verification_inputs: raw)
52
+ mock_processor = {} # This counter is a demo side effect, not real money.
53
+ mock_processor[execution.processor_key] ||= "synthetic-processor-result"
54
+ service.unknown(ticket: first.ticket) # Simulated response loss after dispatch.
55
+ store.close
56
+ # New process/service opens the SAME existing ledger. No create/reset fallback.
57
+ reopened = A::SQLiteStore.new(path: path)
58
+ recovered = A::Service.new(store: reopened)
59
+ pending = recovered.lookup(**scope)
60
+ raise "unknown attempt reopened" unless pending.status == :unknown && pending.ticket.nil? &&
61
+ pending.processor_key == execution.processor_key
62
+ puts "After reopen=unknown; original processor key available for QUERY; mock dispatches=#{mock_processor.size}"
63
+ # Delayed authentic Receipt can resolve an unknown attempt after Mandate expiry.
64
+ receipt = M::PaymentReceipt.sign(closed_sd_jwt: execution.closed_sd_jwt, issuer: "processor-A",
65
+ payment_id: "synthetic-payment-1", outcome: "Success", issued_at: NOW + 120,
66
+ psp_confirmation_id: "synthetic-psp", network_confirmation_id: "synthetic-network",
67
+ signer: signer.call(merchant), public_key_pem: merchant.public_to_pem)
68
+ final = recovered.reconcile(**scope, receipt_jwt: receipt.jwt, verified_at: NOW + 120)
69
+ raise "Receipt recovery failed" unless final.status == :receipt_success && final.ticket.nil? &&
70
+ final.reference == first.reference
71
+ puts "Delayed original-wire Receipt=receipt_success; reconciliation grants no Ticket"
72
+ reopened.close
73
+ end
74
+ puts "Synthetic temporary demo only. Durable reservation is not settlement or external exactly-once; no payment performed."
75
+ end
76
+ end
77
+ PaymentAcceptanceExample.run if $PROGRAM_NAME == __FILE__
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+ # Installed SDK, optional sqlite3=2.10.2; synthetic keys and temporary ledger only.
3
+ require "ap2_mandate_verifier"
4
+ require "tmpdir"
5
+ require_relative "conditional_checkout"
6
+
7
+ module RecurringPaymentExample
8
+ M = AP2MandateVerifier
9
+ A = M::PaymentAcceptance
10
+ R = M::RecurringPayment
11
+ NOW = ConditionalCheckoutExample::NOW
12
+ def self.sign(key) = M::CheckoutJWT.es256_signer(private_key: key)
13
+ def self.build(max_occurrences: 2, budget_max: 600)
14
+ state = ConditionalCheckoutExample.run(currency: "JPY")
15
+ provider, agent, merchant = state.fetch(:keys)
16
+ details = M::Payment.details(checkout_jwt: state.fetch(:closed).checkout_jwt,
17
+ trusted_merchant_public_key_pem: merchant.public_to_pem, expected_merchant_id: "shop",
18
+ payment_instrument: {"id" => "synthetic-card", "type" => "card"})
19
+ conditions = [
20
+ {"type" => "payment.amount_range", "currency" => "JPY", "min" => 1, "max" => 300},
21
+ {"type" => "payment.allowed_payees", "allowed" => [details.fetch("payee")]},
22
+ {"type" => "payment.allowed_payment_instruments", "allowed" => [details.fetch("payment_instrument")]},
23
+ {"type" => "payment.agent_recurrence", "frequency" => "ON_DEMAND", "max_occurrences" => max_occurrences},
24
+ {"type" => "payment.budget", "currency" => "JPY", "max" => budget_max}]
25
+ opening = R.issue_open(open_checkout_sd_jwt: state.fetch(:opening).root_presentation, constraints: conditions,
26
+ fixed: {}, agent_public_key_pem: agent.public_to_pem, issued_at: NOW, expires_at: NOW + 60,
27
+ signer: sign(provider), public_key_pem: provider.public_to_pem, candidate_policy: :independent)
28
+ {state: state, open: opening, series_scope: {tenant_id: "tenant", merchant_id: "shop", approval_id: "consent-42"}}
29
+ end
30
+ def self.enroll_series(store, fixture)
31
+ provider, agent = fixture.fetch(:state).fetch(:keys)
32
+ store.authorize_series!(**fixture.fetch(:series_scope), open_sd_jwt: fixture.fetch(:open), profile_ref: R::PROFILE_REF,
33
+ trusted_provider_public_key_pem: provider.public_to_pem, expected_agent_public_key_pem: agent.public_to_pem, verified_at: NOW)
34
+ end
35
+ def self.occurrence(fixture, id)
36
+ state = fixture.fetch(:state)
37
+ provider, agent, merchant = state.fetch(:keys)
38
+ cart = state.fetch(:checkout).merge("id" => "order-#{id}")
39
+ checkout = M::CheckoutJWT.sign(checkout: cart, profile_ref: M::ConditionalCheckout::PROFILE_REF,
40
+ signer: sign(merchant), public_key_pem: merchant.public_to_pem)
41
+ host_inputs = state.fetch(:host_inputs).merge(host_checkout_jws: checkout.jwt,
42
+ order: state.fetch(:host_inputs).fetch(:order).merge("order_id" => cart.fetch("id")))
43
+ saved = M::InputBuilder.prepare(**host_inputs, challenge_id: "challenge-#{id}", nonce: "nonce-#{id}",
44
+ issuer_id: "host", not_before: NOW, not_after: NOW + 60)
45
+ closed_checkout = M::ConditionalCheckout.issue_closed(root_presentation: state.fetch(:opening).root_presentation,
46
+ checkout_jwt: checkout.jwt, trusted_issuer_public_key_pem: provider.public_to_pem, agent_public_key_pem: agent.public_to_pem,
47
+ trusted_merchant_public_key_pem: merchant.public_to_pem, expected_merchant_id: "shop", audience: "merchant-host",
48
+ nonce: "nonce-#{id}", verified_at: NOW, signer: sign(agent))
49
+ details = M::Payment.details(checkout_jwt: checkout.jwt, trusted_merchant_public_key_pem: merchant.public_to_pem,
50
+ expected_merchant_id: "shop", payment_instrument: {"id" => "synthetic-card", "type" => "card"})
51
+ closed = R.issue_closed(open_sd_jwt: fixture.fetch(:open), payment: details,
52
+ trusted_provider_public_key_pem: provider.public_to_pem, agent_public_key_pem: agent.public_to_pem,
53
+ audience: "processor", nonce: "payment-#{id}", verified_at: NOW, signer: sign(agent))
54
+ inputs = M::InputBuilder.inputs(**host_inputs, saved_challenge: saved, terminal_jws: closed_checkout.terminal_jws,
55
+ expected_challenge_issuer_id: "host", clock_source_id: "synthetic-clock", verified_at: NOW)
56
+ raw = {closed_sd_jwt: closed.closed_sd_jwt, open_sd_jwt: fixture.fetch(:open), profile_ref: R::PROFILE_REF,
57
+ checkout_mode: :conditional, checkout_inputs: inputs, expected_payment: details,
58
+ trusted_provider_public_key_pem: provider.public_to_pem, expected_agent_public_key_pem: agent.public_to_pem,
59
+ expected_audience: "processor", expected_nonce: "payment-#{id}", verified_at: NOW}
60
+ scope = fixture.fetch(:series_scope).merge(operation_id: "operation-#{id}", occurrence_id: "occurrence-#{id}", order_id: cart.fetch("id"))
61
+ receipt_context = {trusted_public_key_pem: merchant.public_to_pem, expected_issuer: "processor", expected_payment_id: "payment-#{id}",
62
+ not_before: NOW, not_after: NOW + 300}
63
+ {scope: scope, raw: raw, authorization: scope.merge(mode: :conditional, profile_ref: R::PROFILE_REF,
64
+ checkout: cart, payment: details, receipt_context: receipt_context)}
65
+ end
66
+ def self.run
67
+ fixture = build
68
+ Dir.mktmpdir("synthetic-recurring-") do |directory|
69
+ store = A::RecurringSQLiteStore.create(path: File.join(directory, "ledger.sqlite3"))
70
+ enroll_series(store, fixture)
71
+ service = A::Service.new(store: store)
72
+ first = nil
73
+ 3.times do |index|
74
+ item = occurrence(fixture, index + 1)
75
+ store.authorize!(**item.fetch(:authorization))
76
+ accepted = service.accept(**item.fetch(:scope), mode: :conditional, verification_inputs: item.fetch(:raw))
77
+ raise "unexpected recurring acceptance" unless accepted.status == (index < 2 ? :reserved : :rejected)
78
+ first ||= [item, accepted]
79
+ end
80
+ item, accepted = first
81
+ retry_item = occurrence(fixture, 1) # Fresh signatures, same protected business occurrence.
82
+ retry_result = service.accept(**retry_item.fetch(:scope), mode: :conditional, verification_inputs: retry_item.fetch(:raw))
83
+ raise "retry gained capacity" unless retry_result.status == :pending && retry_result.ticket.nil?
84
+ execution = service.start(ticket: accepted.ticket, verification_inputs: item.fetch(:raw))
85
+ raise "missing first start" unless execution
86
+ service.unknown(ticket: accepted.ticket)
87
+ usage = store.usage(**fixture.fetch(:series_scope))
88
+ raise "quota changed" unless usage[:reserved_occurrences] == 2 && usage[:reserved_amount] == 600
89
+ puts "JPY ON_DEMAND: two authorized occurrences reserved; third exceeds quota and rejects"
90
+ puts "Re-signed retry: no new Ticket; unknown outcome retains count=2 amount=600JPY"
91
+ store.close
92
+ reopened = A::RecurringSQLiteStore.new(path: File.join(directory, "ledger.sqlite3"))
93
+ raise "lost quota" unless reopened.usage(**fixture.fetch(:series_scope)) == usage
94
+ reopened.close
95
+ end
96
+ puts "Synthetic only; no payment performed. Calendar recurrence and non-JPY budgets unsupported."
97
+ end
98
+ end
99
+ RecurringPaymentExample.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 [ScopedConstraints::MULTI_PROFILE_REF, TrustContext::SELECTIVE_PROFILE_REF].include?(profile_ref)
75
+ if [ScopedConstraints::MULTI_PROFILE_REF, TrustContext::SELECTIVE_PROFILE_REF, TrustContext::LONG_PROFILE_REF].include?(profile_ref)
76
76
  ScopedConstraints.multi_checkout!(checkout)
77
77
  return nil
78
78
  end
@@ -50,7 +50,12 @@ module AP2MandateVerifier
50
50
  header!(header, "kb+sd-jwt")
51
51
  raise Invalid unless signature.bytesize == 64
52
52
  # Existing inline terminal grammar only, never general SD resolution.
53
- PurchaseBinding.send(:exact!, claims, %w[aud delegate_payload iat nonce sd_hash])
53
+ fields = %w[aud delegate_payload iat nonce sd_hash]
54
+ if profile_ref == TrustContext::LONG_PROFILE_REF
55
+ fields += ["ap2_profile"]
56
+ raise Invalid unless claims["ap2_profile"] == profile_ref
57
+ end
58
+ PurchaseBinding.send(:exact!, claims, fields)
54
59
  %w[aud nonce sd_hash].each { |field| text!(claims[field], 512) }
55
60
  epoch!(claims["iat"])
56
61
  raise Invalid unless claims["sd_hash"].match?(/\A[A-Za-z0-9_-]{43}\z/)
@@ -58,6 +63,10 @@ module AP2MandateVerifier
58
63
  PurchaseBinding.send(:exact!, closed, %w[checkout_hash checkout_jwt exp iat vct])
59
64
  raise Invalid unless closed["vct"] == "mandate.checkout.1"
60
65
  epoch!(closed["iat"]); epoch!(closed["exp"])
66
+ if profile_ref == TrustContext::LONG_PROFILE_REF
67
+ PurchaseBinding.send(:times!, closed, closed["iat"], profile_ref: profile_ref)
68
+ raise Invalid unless claims["iat"] >= closed["iat"] && claims["iat"] < closed["exp"]
69
+ end
61
70
  raise Invalid unless closed["exp"] > closed["iat"] && closed["checkout_hash"].instance_of?(String) &&
62
71
  closed["checkout_hash"].match?(/\A[A-Za-z0-9_-]{43}\z/)
63
72
  checkout = InputValidator.snapshot!(closed["checkout_jwt"], max_bytes: 16_384)
@@ -25,14 +25,15 @@ module AP2MandateVerifier
25
25
  private_class_method :new
26
26
  end
27
27
 
28
- def self.issue_open(merchant:, requirements:, agent_public_key_pem:, issued_at:, expires_at:, signer:, public_key_pem:)
28
+ def self.issue_open(merchant:, requirements:, agent_public_key_pem:, issued_at:, expires_at:, signer:, public_key_pem:, profile_ref: PROFILE_REF)
29
+ profile_ref = profile!(profile_ref)
29
30
  RootSignature.send(:dependencies!)
30
31
  merchant = InputBuilder.send(:copy!, merchant)
31
32
  requirements = InputBuilder.send(:copy!, requirements)
32
33
  constraints = [{"type" => "checkout.line_items", "items" => requirements},
33
34
  {"type" => "checkout.allowed_merchants", "allowed" => [merchant]}]
34
35
  ScopedConstraints.send(:multi_open!, constraints)
35
- PurchaseBinding.send(:times!, {"iat" => issued_at, "exp" => expires_at}, issued_at)
36
+ PurchaseBinding.send(:times!, {"iat" => issued_at, "exp" => expires_at}, issued_at, profile_ref: profile_ref)
36
37
  agent = InputValidator.snapshot!(agent_public_key_pem, max_bytes: 1_024)
37
38
  provider = InputValidator.snapshot!(public_key_pem, max_bytes: 1_024)
38
39
  jwk = RootSignature.public_jwk!(agent)
@@ -47,10 +48,16 @@ module AP2MandateVerifier
47
48
  "cnf" => {"jwk" => jwk}, "constraints" => constraints}
48
49
  content = []
49
50
  marker = disclose!(opening, content)
50
- jwt = MerchantSignature.sign!({"delegate_payload" => [marker], "_sd_alg" => "sha-256"}, signer, provider,
51
+ payload = {"delegate_payload" => [marker], "_sd_alg" => "sha-256"}
52
+ if profile_ref == TrustContext::LONG_PROFILE_REF
53
+ payload["ap2_profile"] = profile_ref
54
+ preview = compact_preview(payload, "example+sd-jwt")
55
+ RootDisclosures.send(:structural_root!, ([preview] + content + disclosures + [""]).join("~"), profile_ref: profile_ref)
56
+ end
57
+ jwt = MerchantSignature.sign!(payload, signer, provider,
51
58
  typ: "example+sd-jwt")
52
59
  wire = ([jwt] + content + disclosures + [""]).join("~")
53
- open!(wire, provider, agent, issued_at)
60
+ open!(wire, provider, agent, issued_at, profile_ref: profile_ref)
54
61
  Open.send(:new, wire)
55
62
  rescue StandardError, LoadError
56
63
  raise Invalid.new, cause: nil
@@ -59,7 +66,8 @@ module AP2MandateVerifier
59
66
  # Provider private key is deliberately absent from this Agent API.
60
67
  def self.issue_closed(root_presentation:, checkout_jwt:, trusted_issuer_public_key_pem:,
61
68
  agent_public_key_pem:, trusted_merchant_public_key_pem:, expected_merchant_id:,
62
- audience:, nonce:, verified_at:, signer:)
69
+ audience:, nonce:, verified_at:, signer:, profile_ref: PROFILE_REF)
70
+ profile_ref = profile!(profile_ref)
63
71
  root = InputValidator.snapshot!(root_presentation)
64
72
  checkout = InputValidator.snapshot!(checkout_jwt, max_bytes: 16_384)
65
73
  provider = InputValidator.snapshot!(trusted_issuer_public_key_pem, max_bytes: 1_024)
@@ -70,44 +78,51 @@ module AP2MandateVerifier
70
78
  challenge = InputValidator.snapshot!(nonce, max_bytes: 512)
71
79
  raise Invalid if aud.empty? || challenge.empty?
72
80
  CheckoutReceipt.send(:epoch!, verified_at)
73
- opening = open!(root, provider, agent, verified_at)
81
+ opening = open!(root, provider, agent, verified_at, profile_ref: profile_ref)
74
82
  checked = CheckoutJWT.verify(jwt: checkout, trusted_public_key_pem: merchant,
75
- expected_merchant_id: identity, profile_ref: PROFILE_REF)
83
+ expected_merchant_id: identity, profile_ref: profile_ref)
76
84
  ScopedConstraints.send(:multi_constraints!, {open: opening, checkout: checked.checkout},
77
85
  checked.checkout.fetch("currency"), ScopedConstraints.multi_checkout!(checked.checkout))
78
86
  closed = {"vct" => "mandate.checkout.1", "iat" => opening.fetch("iat"), "exp" => opening.fetch("exp"),
79
87
  "checkout_jwt" => checkout, "checkout_hash" => checked.checkout_hash}
80
- terminal = MerchantSignature.sign!({"aud" => aud, "nonce" => challenge, "iat" => verified_at,
81
- "sd_hash" => digest(root), "delegate_payload" => [closed]}, signer, agent, typ: "kb+sd-jwt")
88
+ claims = {"aud" => aud, "nonce" => challenge, "iat" => verified_at,
89
+ "sd_hash" => digest(root), "delegate_payload" => [closed]}
90
+ if profile_ref == TrustContext::LONG_PROFILE_REF
91
+ claims["ap2_profile"] = profile_ref
92
+ CheckoutReceipt.reference(closed_sd_jwt: compact_preview(claims, "kb+sd-jwt") + "~", profile_ref: profile_ref)
93
+ end
94
+ terminal = MerchantSignature.sign!(claims, signer, agent, typ: "kb+sd-jwt")
82
95
  # Final handoff repeats the complete existing signature/condition path.
83
96
  ScopedConstraints.check!(root_presentation: root, terminal_jws: terminal, host_checkout_jws: checkout,
84
97
  trusted_issuer_public_key_pem: provider, expected_agent_public_key_pem: agent,
85
98
  trusted_merchant_public_key_pem: merchant, expected_aud: aud, expected_nonce: challenge,
86
99
  verified_at: verified_at, expected_checkout_id: checked.checkout.fetch("id"), expected_merchant_id: identity,
87
100
  expected_currency: checked.checkout.fetch("currency"),
88
- expected_total_minor: ScopedConstraints.multi_checkout!(checked.checkout), profile_ref: PROFILE_REF)
101
+ expected_total_minor: ScopedConstraints.multi_checkout!(checked.checkout), profile_ref: profile_ref)
89
102
  Closed.send(:new, root, terminal, checkout)
90
103
  rescue StandardError, LoadError
91
104
  raise Invalid.new, cause: nil
92
105
  end
93
106
 
94
107
  # Storage/transport only, never an authentication or authorization result.
95
- def self.present(root_presentation:, terminal_jws:, checkout_jwt:)
108
+ def self.present(root_presentation:, terminal_jws:, checkout_jwt:, profile_ref: PROFILE_REF)
109
+ profile_ref = profile!(profile_ref)
96
110
  root = InputValidator.snapshot!(root_presentation)
97
111
  terminal = InputValidator.snapshot!(terminal_jws, max_bytes: 32_768)
98
112
  checkout = InputValidator.snapshot!(checkout_jwt, max_bytes: 16_384)
99
113
  # Exact commitment closure without claiming signature authentication.
100
- opening = RootDisclosures.send(:structural_root!, root).fetch("delegate_payload").first
114
+ root_claims = profile_ref == TrustContext::LONG_PROFILE_REF ? RootDisclosures.send(:structural_root!, root, profile_ref: profile_ref) : RootDisclosures.send(:structural_root!, root)
115
+ opening = root_claims.fetch("delegate_payload").first
101
116
  PurchaseBinding.send(:exact!, opening, %w[cnf constraints exp iat vct])
102
117
  raise Invalid unless opening["vct"] == "mandate.checkout.open.1"
103
- PurchaseBinding.send(:times!, opening, opening["iat"])
118
+ PurchaseBinding.send(:times!, opening, opening["iat"], profile_ref: profile_ref)
104
119
  PurchaseBinding.send(:exact!, opening["cnf"], %w[jwk])
105
120
  PurchaseBinding.send(:exact!, opening["cnf"]["jwk"], %w[kty crv x y])
106
121
  jwk = opening["cnf"]["jwk"]
107
122
  raise Invalid unless jwk["kty"] == "EC" && jwk["crv"] == "P-256" &&
108
123
  %w[x y].all? { |f| RootSignature.send(:decode!, jwk[f], 32).bytesize == 32 }
109
124
  ScopedConstraints.send(:multi_open!, opening["constraints"])
110
- CheckoutReceipt.reference(closed_sd_jwt: terminal + "~", profile_ref: PROFILE_REF)
125
+ CheckoutReceipt.reference(closed_sd_jwt: terminal + "~", profile_ref: profile_ref)
111
126
  claims = InputValidator.parse!(RootSignature.send(:decode!, terminal.split(".", -1)[1], 24_576))
112
127
  raise Invalid unless claims["sd_hash"] == digest(root) &&
113
128
  claims.fetch("delegate_payload").first.fetch("checkout_jwt") == checkout &&
@@ -117,17 +132,25 @@ module AP2MandateVerifier
117
132
  raise Invalid.new, cause: nil
118
133
  end
119
134
 
120
- def self.open!(wire, provider, agent, now)
121
- opening = RootDisclosures.verified_root!(wire, provider, profile_ref: PROFILE_REF).fetch("delegate_payload").first
135
+ def self.open!(wire, provider, agent, now, profile_ref: PROFILE_REF)
136
+ opening = RootDisclosures.verified_root!(wire, provider, profile_ref: profile_ref).fetch("delegate_payload").first
122
137
  PurchaseBinding.send(:exact!, opening, %w[cnf constraints exp iat vct])
123
138
  raise Invalid unless opening["vct"] == "mandate.checkout.open.1"
124
- PurchaseBinding.send(:times!, opening, now)
139
+ PurchaseBinding.send(:times!, opening, now, profile_ref: profile_ref)
125
140
  PurchaseBinding.send(:exact!, opening["cnf"], %w[jwk])
126
141
  raise Invalid unless opening["cnf"]["jwk"] == RootSignature.public_jwk!(agent)
127
142
  ScopedConstraints.send(:multi_open!, opening["constraints"])
128
143
  opening
129
144
  end
130
145
  def self.digest(wire) = Base64.urlsafe_encode64(Digest::SHA256.digest(wire), padding: false)
146
+ def self.profile!(source)
147
+ value = InputValidator.snapshot!(source, max_bytes: 256)
148
+ raise Invalid unless [PROFILE_REF, TrustContext::LONG_PROFILE_REF].include?(value)
149
+ value
150
+ end
151
+ def self.compact_preview(claims, typ)
152
+ [Buyer.send(:encode, {"alg" => "ES256", "typ" => typ}), Buyer.send(:encode, claims), Buyer.send(:encode, "\0" * 64)].join(".")
153
+ end
131
154
  def self.disclose!(value, disclosures)
132
155
  require "securerandom"
133
156
  salt = Base64.urlsafe_encode64(SecureRandom.random_bytes(16), padding: false)
@@ -137,14 +160,15 @@ module AP2MandateVerifier
137
160
  end
138
161
  %i[issue_open issue_closed present].each do |name|
139
162
  implementation = method(name)
163
+ required = implementation.parameters.filter_map { |kind, field| field if kind == :keyreq }.freeze
140
164
  fields = implementation.parameters.map(&:last).freeze
141
165
  define_singleton_method(name) do |**arguments|
142
- unless (fields - arguments.keys).empty? && (arguments.keys - fields).empty?
166
+ unless (required - arguments.keys).empty? && (arguments.keys - fields).empty?
143
167
  raise Invalid.new, cause: nil
144
168
  end
145
169
  implementation.call(**arguments)
146
170
  end
147
171
  end
148
- private_class_method :open!, :digest, :disclose!
172
+ private_class_method :open!, :digest, :disclose!, :profile!, :compact_preview
149
173
  end
150
174
  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, TrustContext::SELECTIVE_PROFILE_REF].include?(value["profile_ref"])
116
+ [TrustContext::PROFILE_REF, TrustContext::MULTI_PROFILE_REF, TrustContext::SELECTIVE_PROFILE_REF, TrustContext::LONG_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]]