ap2_mandate_verifier 1.5.0 → 1.6.1

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 (40) hide show
  1. checksums.yaml +4 -4
  2. data/README.ja.md +95 -172
  3. data/README.md +119 -199
  4. data/SECURITY.md +7 -3
  5. data/docs/LONG_PAYMENT.md +84 -0
  6. data/docs/PAYMENT_ACCEPTANCE.md +8 -1
  7. data/docs/PUBLIC_API.md +10 -2
  8. data/docs/RECURRING_PAYMENT.md +56 -0
  9. data/docs/RELEASE_150_CANDIDATE.md +2 -0
  10. data/docs/RELEASE_160_CANDIDATE.md +30 -0
  11. data/docs/RELEASE_161_CANDIDATE.md +30 -0
  12. data/docs/RUBY_INTEGRATION.ja.md +204 -0
  13. data/docs/RUBY_INTEGRATION.md +222 -0
  14. data/docs/SUPPORT_CONTRACT.md +19 -2
  15. data/examples/conditional_checkout.rb +3 -3
  16. data/examples/integration/inputs.rb +169 -0
  17. data/examples/integration/processor.rb +39 -0
  18. data/examples/long_payment.rb +116 -0
  19. data/examples/long_payment_acceptance.rb +89 -0
  20. data/examples/recurring_payment.rb +99 -0
  21. data/examples/ruby_integration.rb +161 -0
  22. data/lib/ap2_mandate_verifier/checkout_jwt.rb +1 -1
  23. data/lib/ap2_mandate_verifier/checkout_receipt.rb +10 -1
  24. data/lib/ap2_mandate_verifier/conditional_checkout.rb +43 -19
  25. data/lib/ap2_mandate_verifier/input_builder.rb +1 -1
  26. data/lib/ap2_mandate_verifier/long_payment.rb +201 -0
  27. data/lib/ap2_mandate_verifier/payment.rb +52 -12
  28. data/lib/ap2_mandate_verifier/payment_acceptance/long_sqlite_store.rb +272 -0
  29. data/lib/ap2_mandate_verifier/payment_acceptance/recurring_sqlite_store.rb +124 -0
  30. data/lib/ap2_mandate_verifier/payment_acceptance/sqlite_store.rb +38 -10
  31. data/lib/ap2_mandate_verifier/payment_acceptance.rb +28 -6
  32. data/lib/ap2_mandate_verifier/payment_policy.rb +7 -2
  33. data/lib/ap2_mandate_verifier/purchase_binding.rb +11 -5
  34. data/lib/ap2_mandate_verifier/recurring_payment.rb +111 -0
  35. data/lib/ap2_mandate_verifier/root_disclosures.rb +9 -6
  36. data/lib/ap2_mandate_verifier/scoped_constraints.rb +1 -1
  37. data/lib/ap2_mandate_verifier/selective_payment.rb +1 -1
  38. data/lib/ap2_mandate_verifier/trust_context.rb +6 -0
  39. data/lib/ap2_mandate_verifier.rb +4 -0
  40. metadata +23 -6
@@ -0,0 +1,169 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ap2_mandate_verifier"
4
+ require "openssl"
5
+
6
+ module RubyIntegration
7
+ # Synthetic application storage, NOT enrollment or consent authentication.
8
+ # In production these records come from independently authenticated services.
9
+ # Never populate trust, order or approval from the received Payment Mandate.
10
+ module Inputs
11
+ M = AP2MandateVerifier
12
+ CHECKOUT_PROFILE = M::ConditionalCheckout::PROFILE_REF
13
+ module_function
14
+
15
+ def totals(amount)
16
+ %w[subtotal total].map { |type| {"type" => type, "amount" => amount} }
17
+ end
18
+
19
+ def signer(key) = M::CheckoutJWT.es256_signer(private_key: key)
20
+
21
+ def bootstrap(now:)
22
+ provider, agent, merchant = Array.new(3) { OpenSSL::PKey::EC.generate("prime256v1") }
23
+ seller = {"id" => "shop", "name" => "Synthetic office supplies"}
24
+ item = {"id" => "paper", "title" => "Synthetic paper"}
25
+ instrument = {"id" => "synthetic-card", "type" => "card"}
26
+ # Retain what the authenticated owner approved BEFORE issuing either Open.
27
+ # These local conditions are never reconstructed from an incoming Mandate.
28
+ approval = {"payment_instrument" => instrument,
29
+ "checkout_requirements" => [{"id" => "paper-choice", "quantity" => 1, "acceptable_items" => [item]}],
30
+ "payment_constraints" => [{"type" => "payment.amount_range", "currency" => "USD", "max" => 300},
31
+ {"type" => "payment.allowed_payees", "allowed" => [seller]},
32
+ {"type" => "payment.allowed_payment_instruments", "allowed" => [instrument]}]}
33
+ checkout = {"id" => "office-1", "merchant" => seller, "status" => "ready_for_complete",
34
+ "currency" => "USD", "line_items" => [{"id" => "row-1", "item" => item.merge("price" => 300),
35
+ "quantity" => 1, "totals" => totals(300)}], "totals" => totals(300), "links" => []}
36
+ opening = M::ConditionalCheckout.issue_open(merchant: seller,
37
+ requirements: approval.fetch("checkout_requirements"),
38
+ agent_public_key_pem: agent.public_to_pem, issued_at: now, expires_at: now + 60,
39
+ signer: signer(provider), public_key_pem: provider.public_to_pem)
40
+ checkout_jwt = M::CheckoutJWT.sign(checkout: checkout, profile_ref: CHECKOUT_PROFILE,
41
+ signer: signer(merchant), public_key_pem: merchant.public_to_pem).jwt
42
+
43
+ # Fixed IDs describe ONE protected state directory and ONE approved attempt.
44
+ # A new occurrence must get a separate authenticated application approval.
45
+ records = %w[Issuer Agent Merchant].zip([provider, agent, merchant]).map do |role, key|
46
+ {"role" => role, "identity" => role == "Merchant" ? "shop" : role.downcase,
47
+ "tenant_id" => "tenant", "purpose" => "checkout", "key_ref" => role.downcase,
48
+ "public_key_pem" => key.public_to_pem, "active" => true,
49
+ "not_before" => now - 1, "not_after" => now + 1000}
50
+ end
51
+ data = {
52
+ "now" => now,
53
+ "checkout" => checkout,
54
+ "order" => {"tenant_id" => "tenant", "buyer_account_id" => "buyer", "order_id" => "office-1",
55
+ "merchant_id" => "shop", "audience" => "merchant-host", "order_version" => "1",
56
+ "currency" => "USD", "expected_total" => 300},
57
+ "approval" => approval,
58
+ "trust_snapshot" => {"id" => "registry", "policy_version" => "1", "active" => true,
59
+ "not_before" => now - 1, "not_after" => now + 1000, "records" => records},
60
+ "selectors" => records.to_h do |record|
61
+ [record.fetch("role").downcase, record.slice("identity", "purpose", "key_ref")]
62
+ end,
63
+ "nonce" => "synthetic-one-use-nonce",
64
+ "challenge_issuer" => "host",
65
+ "scope" => {"tenant_id" => "tenant", "merchant_id" => "shop", "operation_id" => "operation-1",
66
+ "approval_id" => "approval-1", "occurrence_id" => "one", "order_id" => "office-1"},
67
+ "receipt_context" => {"trusted_public_key_pem" => merchant.public_to_pem,
68
+ "expected_issuer" => "shop", "expected_payment_id" => "payment-1",
69
+ "not_before" => now, "not_after" => now + 1000},
70
+ "wires" => {"checkout_open" => opening.root_presentation, "checkout_jwt" => checkout_jwt},
71
+ # Mock processor uses the synthetic merchant key. Provider private key
72
+ # is discarded; only these two mock actors need to sign after restart.
73
+ "mock_private_keys" => {"merchant" => merchant.private_to_pem, "agent" => agent.private_to_pem}
74
+ }
75
+ data["saved_challenge"] = M::InputBuilder.prepare(**host_inputs(data, now: now),
76
+ challenge_id: "challenge-1", nonce: data.fetch("nonce"), issuer_id: data.fetch("challenge_issuer"),
77
+ not_before: now, not_after: now + 60)
78
+ closed = M::ConditionalCheckout.issue_closed(root_presentation: opening.root_presentation,
79
+ checkout_jwt: checkout_jwt, trusted_issuer_public_key_pem: provider.public_to_pem,
80
+ agent_public_key_pem: agent.public_to_pem, trusted_merchant_public_key_pem: merchant.public_to_pem,
81
+ expected_merchant_id: "shop", audience: "merchant-host", nonce: data.fetch("nonce"),
82
+ verified_at: now, signer: signer(agent))
83
+ data.fetch("wires")["checkout_terminal"] = closed.terminal_jws
84
+ data.fetch("wires")["checkout_closed"] = M::ConditionalCheckout.present(
85
+ root_presentation: closed.root_presentation, terminal_jws: closed.terminal_jws,
86
+ checkout_jwt: closed.checkout_jwt).closed_sd_jwt
87
+ payment = expected_payment(data)
88
+ data["expected_payment"] = payment
89
+ data.fetch("wires")["payment_open"] = M::Payment.issue_open(
90
+ open_checkout_sd_jwt: opening.root_presentation,
91
+ constraints: data.fetch("approval").fetch("payment_constraints"), fixed: {},
92
+ agent_public_key_pem: agent.public_to_pem, issued_at: now, expires_at: now + 60,
93
+ signer: signer(provider), public_key_pem: provider.public_to_pem)
94
+ data.fetch("wires")["payment_closed"] = resign(data, now: now)
95
+ data
96
+ end
97
+
98
+ # Select from the CURRENT protected registry, never from JWT headers/claims.
99
+ def public_key(data, role)
100
+ selector = data.fetch("selectors").fetch(role)
101
+ records = data.fetch("trust_snapshot").fetch("records").select do |entry|
102
+ entry.fetch("role").downcase == role &&
103
+ entry.fetch("tenant_id") == data.fetch("order").fetch("tenant_id") &&
104
+ selector.all? { |field, value| entry.fetch(field) == value }
105
+ end
106
+ raise ArgumentError, "missing or ambiguous protected trust record" unless records.length == 1
107
+ records.first.fetch("public_key_pem")
108
+ end
109
+
110
+ def host_inputs(data, now:)
111
+ selectors = data.fetch("selectors").transform_keys(&:to_sym)
112
+ trust = M::InputBuilder.trust(snapshot: data.fetch("trust_snapshot"),
113
+ tenant_id: data.fetch("order").fetch("tenant_id"), verified_at: now,
114
+ profile_ref: CHECKOUT_PROFILE, **selectors)
115
+ {trust: trust, order: data.fetch("order"), root_presentation: data.fetch("wires").fetch("checkout_open"),
116
+ host_checkout_jws: data.fetch("wires").fetch("checkout_jwt")}
117
+ end
118
+
119
+ # Derive from our signed Checkout and separately approved instrument, not
120
+ # from the Payment being verified. Reconstruct on each accept/start call.
121
+ def expected_payment(data)
122
+ M::Payment.details(checkout_jwt: data.fetch("wires").fetch("checkout_jwt"),
123
+ trusted_merchant_public_key_pem: public_key(data, "merchant"),
124
+ expected_merchant_id: data.fetch("order").fetch("merchant_id"),
125
+ payment_instrument: data.fetch("approval").fetch("payment_instrument"))
126
+ end
127
+
128
+ def verification(data, now:)
129
+ # Presentation restores exact saved bytes; it does NOT authenticate them.
130
+ payment = M::Payment.present(open_sd_jwt: data.fetch("wires").fetch("payment_open"),
131
+ closed_sd_jwt: data.fetch("wires").fetch("payment_closed"))
132
+ checkout_inputs = M::InputBuilder.inputs(**host_inputs(data, now: now),
133
+ saved_challenge: M::InputBuilder.restore(saved_challenge: data.fetch("saved_challenge")),
134
+ terminal_jws: data.fetch("wires").fetch("checkout_terminal"),
135
+ expected_challenge_issuer_id: data.fetch("challenge_issuer"),
136
+ clock_source_id: "synthetic-clock", verified_at: now)
137
+ {open_sd_jwt: payment.open_sd_jwt,
138
+ closed_sd_jwt: payment.closed_sd_jwt, checkout_mode: :conditional,
139
+ checkout_inputs: checkout_inputs, expected_payment: expected_payment(data),
140
+ trusted_provider_public_key_pem: public_key(data, "issuer"),
141
+ expected_agent_public_key_pem: public_key(data, "agent"),
142
+ expected_audience: data.fetch("order").fetch("audience"), expected_nonce: data.fetch("nonce"),
143
+ verified_at: now}
144
+ end
145
+
146
+ # Return alternate bytes without ever replacing the first persisted wire.
147
+ def resign(data, now:)
148
+ key = OpenSSL::PKey.read(data.fetch("mock_private_keys").fetch("agent"))
149
+ M::Payment.issue_closed(open_sd_jwt: data.fetch("wires").fetch("payment_open"),
150
+ payment: expected_payment(data), trusted_provider_public_key_pem: public_key(data, "issuer"),
151
+ agent_public_key_pem: public_key(data, "agent"), audience: data.fetch("order").fetch("audience"),
152
+ nonce: data.fetch("nonce"), verified_at: now, signer: signer(key)).closed_sd_jwt
153
+ end
154
+
155
+ # A signed mock outcome proves authenticity/binding, not real settlement.
156
+ def receipt(data, wire:, outcome:, now:)
157
+ fields = case outcome
158
+ when "Success" then {psp_confirmation_id: "synthetic-psp", network_confirmation_id: "synthetic-network"}
159
+ when "Error" then {error: "declined", error_description: "Synthetic processor declined"}
160
+ else raise ArgumentError, "unsupported mock outcome"
161
+ end
162
+ context = data.fetch("receipt_context")
163
+ key = OpenSSL::PKey.read(data.fetch("mock_private_keys").fetch("merchant"))
164
+ M::PaymentReceipt.sign(closed_sd_jwt: wire, issuer: context.fetch("expected_issuer"),
165
+ payment_id: context.fetch("expected_payment_id"), outcome: outcome, issued_at: now,
166
+ signer: signer(key), public_key_pem: context.fetch("trusted_public_key_pem"), **fields).jwt
167
+ end
168
+ end
169
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+ gem "sqlite3", "= 2.10.2"
3
+ require "sqlite3"
4
+ module RubyIntegration
5
+ # Separate mock processor ledger: a committed row IS the synthetic side effect.
6
+ # This is not atomicity between an external PSP and an application's database.
7
+ class Processor
8
+ SCHEMA = "CREATE TABLE results (processor_key TEXT PRIMARY KEY, reference TEXT NOT NULL, receipt TEXT)"
9
+ def self.create(path)
10
+ File.open(path, File::WRONLY | File::CREAT | File::EXCL, 0o600) { |f| f.fsync }
11
+ db = SQLite3::Database.new(path, flags: SQLite3::Constants::Open::READWRITE)
12
+ db.execute(SCHEMA)
13
+ db.close
14
+ end
15
+ def initialize(path)
16
+ @db = SQLite3::Database.new(path, flags: SQLite3::Constants::Open::READWRITE)
17
+ raise "mock storage unavailable" unless @db.get_first_value("PRAGMA quick_check") == "ok" &&
18
+ @db.get_first_value("SELECT sql FROM sqlite_master WHERE name='results'") == SCHEMA
19
+ @db.busy_timeout = 5000
20
+ @db.execute("PRAGMA synchronous=FULL")
21
+ end
22
+ def dispatch(execution, receipt:)
23
+ @db.transaction(:immediate) do
24
+ old = query(execution.processor_key)
25
+ if old
26
+ raise "mock reference conflict" unless old.fetch("reference") == execution.reference
27
+ else
28
+ @db.execute("INSERT INTO results VALUES (?,?,?)", [execution.processor_key, execution.reference, receipt])
29
+ end
30
+ end
31
+ end
32
+ def query(key)
33
+ row = @db.get_first_row("SELECT reference,receipt FROM results WHERE processor_key=?", [key])
34
+ row && {"reference" => row[0], "receipt" => row[1]}
35
+ end
36
+ def count = @db.get_first_value("SELECT count(*) FROM results")
37
+ def close = @db.close
38
+ end
39
+ end
@@ -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,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__