ap2_mandate_verifier 1.5.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 (34) hide show
  1. checksums.yaml +4 -4
  2. data/README.ja.md +19 -8
  3. data/README.md +19 -8
  4. data/SECURITY.md +7 -3
  5. data/docs/LONG_PAYMENT.md +82 -0
  6. data/docs/PAYMENT_ACCEPTANCE.md +3 -1
  7. data/docs/PUBLIC_API.md +10 -2
  8. data/docs/RECURRING_PAYMENT.md +54 -0
  9. data/docs/RELEASE_150_CANDIDATE.md +2 -0
  10. data/docs/RELEASE_160_CANDIDATE.md +30 -0
  11. data/docs/SUPPORT_CONTRACT.md +6 -2
  12. data/examples/conditional_checkout.rb +3 -3
  13. data/examples/long_payment.rb +116 -0
  14. data/examples/long_payment_acceptance.rb +89 -0
  15. data/examples/recurring_payment.rb +99 -0
  16. data/lib/ap2_mandate_verifier/checkout_jwt.rb +1 -1
  17. data/lib/ap2_mandate_verifier/checkout_receipt.rb +10 -1
  18. data/lib/ap2_mandate_verifier/conditional_checkout.rb +43 -19
  19. data/lib/ap2_mandate_verifier/input_builder.rb +1 -1
  20. data/lib/ap2_mandate_verifier/long_payment.rb +201 -0
  21. data/lib/ap2_mandate_verifier/payment.rb +52 -12
  22. data/lib/ap2_mandate_verifier/payment_acceptance/long_sqlite_store.rb +272 -0
  23. data/lib/ap2_mandate_verifier/payment_acceptance/recurring_sqlite_store.rb +124 -0
  24. data/lib/ap2_mandate_verifier/payment_acceptance/sqlite_store.rb +38 -10
  25. data/lib/ap2_mandate_verifier/payment_acceptance.rb +28 -6
  26. data/lib/ap2_mandate_verifier/payment_policy.rb +7 -2
  27. data/lib/ap2_mandate_verifier/purchase_binding.rb +11 -5
  28. data/lib/ap2_mandate_verifier/recurring_payment.rb +111 -0
  29. data/lib/ap2_mandate_verifier/root_disclosures.rb +9 -6
  30. data/lib/ap2_mandate_verifier/scoped_constraints.rb +1 -1
  31. data/lib/ap2_mandate_verifier/selective_payment.rb +1 -1
  32. data/lib/ap2_mandate_verifier/trust_context.rb +6 -0
  33. data/lib/ap2_mandate_verifier.rb +4 -0
  34. metadata +16 -5
@@ -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__
@@ -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]]
@@ -0,0 +1,201 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Explicit long-content, fresh-proof profile. MONTHLY is enforced by a
5
+ # protected Host period policy at acceptance, never by this wire verifier.
6
+ module LongPayment
7
+ CHECKOUT_PROFILE_REF = "ap2.checkout.long_open.multi_item.1".freeze
8
+ PROFILE_REF = "ap2.payment.long_open.jpy_monthly.complete.1".freeze
9
+ MAX_CONTENT_LIFETIME = 400 * 86_400
10
+ MAX_OCCURRENCES = 1_000_000
11
+ TYPES = %w[payment.agent_recurrence payment.budget].freeze
12
+ class Invalid < ArgumentError
13
+ def initialize = super("invalid long payment information")
14
+ end
15
+ def self.profile?(value) = value == PROFILE_REF
16
+ def self.checkout_profile?(value) = value == CHECKOUT_PROFILE_REF
17
+
18
+ def self.constraints!(opening)
19
+ raise Invalid unless opening.instance_of?(Hash)
20
+ cs = opening.fetch("constraints")
21
+ raise Invalid unless cs.instance_of?(Array) && cs.size == 6 && cs.all? { |c| c.instance_of?(Hash) }
22
+ recurrence = cs.select { |c| c["type"] == TYPES[0] }
23
+ budget = cs.select { |c| c["type"] == TYPES[1] }
24
+ raise Invalid unless recurrence.size == 1 && budget.size == 1
25
+ recurrence, budget = recurrence.first, budget.first
26
+ Payment.send(:exact!, recurrence, %w[type frequency max_occurrences])
27
+ Payment.send(:exact!, budget, %w[type max currency])
28
+ raise Invalid unless recurrence["frequency"] == "MONTHLY" && recurrence["max_occurrences"].instance_of?(Integer) &&
29
+ recurrence["max_occurrences"].between?(1, MAX_OCCURRENCES) && budget["currency"] == "JPY" &&
30
+ budget["max"].instance_of?(Integer) && budget["max"].between?(1, ScopedConstraints::MAX_AMOUNT)
31
+ amount = cs.select { |c| c["type"] == "payment.amount_range" }
32
+ raise Invalid unless amount.size == 1 && amount.first["currency"] == "JPY"
33
+ raise Invalid if amount.first.fetch("min", 0).instance_of?(Integer) && amount.first.fetch("min", 0) > budget["max"]
34
+ if opening.key?("payment_amount")
35
+ Payment.send(:amount!, opening["payment_amount"])
36
+ raise Invalid unless opening["payment_amount"]["currency"] == "JPY" && opening["payment_amount"]["amount"] <= budget["max"]
37
+ end
38
+ opening.merge("constraints" => cs.reject { |c| TYPES.include?(c["type"]) })
39
+ end
40
+ def self.conditions!(opening, closed)
41
+ base = constraints!(opening)
42
+ budget = opening.fetch("constraints").find { |c| c["type"] == TYPES[1] }
43
+ raise Invalid unless closed.fetch("payment_amount").fetch("currency") == "JPY" && closed["payment_amount"]["amount"] <= budget.fetch("max")
44
+ Payment.send(:conditions!, base, closed)
45
+ end
46
+
47
+ def self.snapshot_checkout!(source, verified_at)
48
+ CheckoutReceipt.send(:epoch!, verified_at)
49
+ fields = %i[trust_json selection_json host_json root_presentation terminal_jws host_checkout_jws verified_at]
50
+ raise Invalid unless Object.instance_method(:instance_of?).bind_call(source, Hash) &&
51
+ Object.instance_method(:singleton_methods).bind_call(source, true).empty? && source.size == fields.size && fields.all? { |f| source.key?(f) }
52
+ limits = {selection_json: 16_384, host_json: 32_768, terminal_jws: 32_768, host_checkout_jws: 16_384}
53
+ value = fields.to_h { |f| [f, f == :verified_at ? source[f] : InputValidator.snapshot!(source[f], max_bytes: limits.fetch(f, 131_072))] }.freeze
54
+ CheckoutReceipt.send(:epoch!, value[:verified_at])
55
+ raise Invalid unless value[:verified_at] == verified_at
56
+ value
57
+ end
58
+ def self.current_context!(trust_json, selection_json, merchant_id, verified_at)
59
+ CheckoutReceipt.send(:epoch!, verified_at)
60
+ trust = InputValidator.snapshot!(trust_json)
61
+ selection = InputValidator.snapshot!(selection_json, max_bytes: 16_384)
62
+ identity = InputValidator.snapshot!(merchant_id, max_bytes: 256)
63
+ context = TrustContext.verified_context!(trust_json: trust, selection_json: selection,
64
+ expected_merchant_id: identity, verified_at: verified_at)
65
+ raise Invalid unless context.fetch(:references).fetch("profile_ref") == CHECKOUT_PROFILE_REF
66
+ context
67
+ end
68
+ def self.authority_projection(context)
69
+ binding = context.fetch(:references).merge("selected_keys" => context.fetch(:selected_keys))
70
+ keys = context.fetch(:keys)
71
+ principals = context.fetch(:selected_keys).to_h { |record| [record.fetch("role"), record.slice("identity", "purpose", "tenant_id")] }
72
+ fingerprints = {"issuer" => Digest::SHA256.hexdigest(keys.fetch(:trusted_issuer_public_key_pem)),
73
+ "agent" => Digest::SHA256.hexdigest(keys.fetch(:expected_agent_public_key_pem))}
74
+ {authority_binding: ResearchEvidence.send(:copy_frozen, binding), root_key_fingerprints: ResearchEvidence.send(:copy_frozen, fingerprints),
75
+ authority_principals: ResearchEvidence.send(:copy_frozen, principals),
76
+ tenant_id: context.fetch(:references).fetch("tenant_id"), valid_until: context.fetch(:valid_until)}.freeze
77
+ end
78
+ def self.current_authority!(trust_json:, selection_json:, merchant_id:, verified_at:)
79
+ authority_projection(current_context!(trust_json, selection_json, merchant_id, verified_at))
80
+ rescue StandardError, LoadError
81
+ raise Invalid.new, cause: nil
82
+ end
83
+ def self.authority!(checkout_inputs:, provider_key:, agent_key:, merchant_id:, verified_at:)
84
+ provider = InputValidator.snapshot!(provider_key, max_bytes: 1024)
85
+ agent = InputValidator.snapshot!(agent_key, max_bytes: 1024)
86
+ identity = InputValidator.snapshot!(merchant_id, max_bytes: 256)
87
+ inputs = snapshot_checkout!(checkout_inputs, verified_at)
88
+ host = InputValidator.parse!(inputs.fetch(:host_json))
89
+ raise Invalid unless host.fetch("binding").fetch("merchant_id") == identity
90
+ context = current_context!(inputs.fetch(:trust_json), inputs.fetch(:selection_json), identity, verified_at)
91
+ keys = context.fetch(:keys)
92
+ raise Invalid unless RootSignature.public_jwk!(provider) == RootSignature.public_jwk!(keys.fetch(:trusted_issuer_public_key_pem)) &&
93
+ RootSignature.public_jwk!(agent) == RootSignature.public_jwk!(keys.fetch(:expected_agent_public_key_pem))
94
+ authority_projection(context)
95
+ rescue StandardError, LoadError
96
+ raise Invalid.new, cause: nil
97
+ end
98
+
99
+ def self.validated_open!(source)
100
+ opening, wire = Payment.send(:root!, source, profile_ref: PROFILE_REF)
101
+ Payment.send(:open!, opening, profile_ref: PROFILE_REF)
102
+ recurrence = opening.fetch("constraints").find { |c| c["type"] == TYPES[0] }
103
+ budget = opening.fetch("constraints").find { |c| c["type"] == TYPES[1] }
104
+ root = wire.split("~", 2).first.freeze
105
+ {opening: ResearchEvidence.send(:copy_frozen, opening), root_wire: root, presentation_wire: wire,
106
+ reference: Payment.send(:digest, root).freeze, currency: "JPY".freeze, frequency: "MONTHLY".freeze,
107
+ max_occurrences: recurrence.fetch("max_occurrences"), budget_max: budget.fetch("max"), profile_ref: PROFILE_REF}.freeze
108
+ end
109
+ def self.approved_open!(open_sd_jwt:, trusted_provider_public_key_pem:, expected_agent_public_key_pem:, verified_at:, profile_ref: PROFILE_REF)
110
+ raise Invalid unless InputValidator.snapshot!(profile_ref, max_bytes: 256) == PROFILE_REF
111
+ wire = InputValidator.snapshot!(open_sd_jwt, max_bytes: 32_769)
112
+ provider = InputValidator.snapshot!(trusted_provider_public_key_pem, max_bytes: 1024)
113
+ agent = InputValidator.snapshot!(expected_agent_public_key_pem, max_bytes: 1024)
114
+ CheckoutReceipt.send(:epoch!, verified_at)
115
+ RootSignature.verified_payload!(wire.split("~", 2).first, provider)
116
+ checked = validated_open!(wire)
117
+ Payment.send(:valid_now!, checked.fetch(:opening), verified_at)
118
+ raise Invalid unless checked.fetch(:opening).fetch("cnf") == {"jwk" => RootSignature.public_jwk!(agent)}
119
+ checked
120
+ rescue StandardError, LoadError
121
+ raise Invalid.new, cause: nil
122
+ end
123
+ def self.approved_pair!(payment_open:, checkout_open:, trust_json:, selection_json:, merchant_id:, verified_at:)
124
+ payment_wire = InputValidator.snapshot!(payment_open, max_bytes: 32_769)
125
+ checkout_wire = InputValidator.snapshot!(checkout_open)
126
+ identity = InputValidator.snapshot!(merchant_id, max_bytes: 256)
127
+ context = current_context!(trust_json, selection_json, identity, verified_at)
128
+ keys = context.fetch(:keys)
129
+ checkout = ConditionalCheckout.send(:open!, checkout_wire, keys.fetch(:trusted_issuer_public_key_pem),
130
+ keys.fetch(:expected_agent_public_key_pem), verified_at, profile_ref: CHECKOUT_PROFILE_REF)
131
+ merchant, = ScopedConstraints.send(:multi_open!, checkout.fetch("constraints"))
132
+ raise Invalid unless merchant.fetch("id") == identity
133
+ checked = approved_open!(open_sd_jwt: payment_wire, trusted_provider_public_key_pem: keys.fetch(:trusted_issuer_public_key_pem),
134
+ expected_agent_public_key_pem: keys.fetch(:expected_agent_public_key_pem), verified_at: verified_at)
135
+ opening = checked.fetch(:opening)
136
+ reference = opening.fetch("constraints").find { |c| c["type"] == "payment.reference" }
137
+ raise Invalid unless reference.fetch("conditional_transaction_id") == Payment.send(:digest, checkout_wire)
138
+ economic_payment = opening.reject { |k,_| %w[iat exp cnf].include?(k) }.merge(
139
+ "constraints" => opening.fetch("constraints").reject { |c| c["type"] == "payment.reference" })
140
+ economic_checkout = checkout.reject { |k,_| %w[iat exp cnf].include?(k) }
141
+ economics = canonical({"payment_profile" => PROFILE_REF, "checkout_profile" => CHECKOUT_PROFILE_REF,
142
+ "checkout" => economic_checkout, "payment" => economic_payment})
143
+ projected = authority_projection(context)
144
+ checked.merge(checkout_opening: ResearchEvidence.send(:copy_frozen, checkout), checkout_reference: Payment.send(:digest, checkout_wire).freeze,
145
+ economic_contract: economics.freeze, not_before: [opening.fetch("iat"),checkout.fetch("iat")].max,
146
+ not_after: [opening.fetch("exp"),checkout.fetch("exp")].min, authority_binding: projected.fetch(:authority_binding),
147
+ root_key_fingerprints: projected.fetch(:root_key_fingerprints), tenant_id: projected.fetch(:tenant_id),
148
+ authority_principals: projected.fetch(:authority_principals),
149
+ authority_valid_until: projected.fetch(:valid_until)).freeze
150
+ rescue StandardError, LoadError
151
+ raise Invalid.new, cause: nil
152
+ end
153
+ def self.canonical(value)
154
+ normalized = case value
155
+ when Hash then value.keys.sort.to_h { |k| [k, JSON.parse(canonical(value[k]))] }
156
+ when Array then value.map { |v| JSON.parse(canonical(v)) }
157
+ else value
158
+ end
159
+ JSON.generate(normalized)
160
+ end
161
+
162
+ %i[issue_open issue_closed present verify details].each do |name|
163
+ define_singleton_method(name) do |**arguments|
164
+ if arguments.key?(:profile_ref)
165
+ raise Invalid unless InputValidator.snapshot!(arguments.delete(:profile_ref), max_bytes: 256) == PROFILE_REF
166
+ end
167
+ if arguments.key?(:checkout_profile_ref)
168
+ raise Invalid unless name == :issue_open && InputValidator.snapshot!(arguments.delete(:checkout_profile_ref), max_bytes: 256) == CHECKOUT_PROFILE_REF
169
+ end
170
+ arguments[:checkout_profile_ref] = CHECKOUT_PROFILE_REF if name == :issue_open
171
+ arguments[:checkout_mode] = :conditional if name == :verify && !arguments.key?(:checkout_mode)
172
+ Payment.public_send(name, **arguments, profile_ref: PROFILE_REF)
173
+ rescue StandardError, LoadError
174
+ next Payment::Verification.send(:new) if name == :verify
175
+ raise Invalid.new, cause: nil
176
+ end
177
+ end
178
+ {issue_checkout_open: :issue_open, issue_checkout_closed: :issue_closed, present_checkout: :present}.each do |name,target|
179
+ define_singleton_method(name) do |**arguments|
180
+ if arguments.key?(:profile_ref)
181
+ raise Invalid unless InputValidator.snapshot!(arguments.delete(:profile_ref), max_bytes: 256) == CHECKOUT_PROFILE_REF
182
+ end
183
+ ConditionalCheckout.public_send(target, **arguments, profile_ref: CHECKOUT_PROFILE_REF)
184
+ rescue StandardError, LoadError
185
+ raise Invalid.new, cause: nil
186
+ end
187
+ end
188
+ %i[current_authority! authority! approved_open! approved_pair!].each do |name|
189
+ implementation = method(name)
190
+ required = implementation.parameters.filter_map { |kind,key| key if kind == :keyreq }.freeze
191
+ fields = implementation.parameters.map(&:last).freeze
192
+ define_singleton_method(name) do |**arguments|
193
+ raise Invalid unless (required - arguments.keys).empty? && (arguments.keys - fields).empty?
194
+ implementation.call(**arguments)
195
+ rescue StandardError, LoadError
196
+ raise Invalid.new, cause: nil
197
+ end
198
+ end
199
+ private_class_method :constraints!, :conditions!, :snapshot_checkout!, :current_context!, :authority_projection, :validated_open!, :canonical
200
+ end
201
+ end