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.
- checksums.yaml +4 -4
- data/README.ja.md +95 -172
- data/README.md +119 -199
- data/SECURITY.md +7 -3
- data/docs/LONG_PAYMENT.md +84 -0
- data/docs/PAYMENT_ACCEPTANCE.md +8 -1
- data/docs/PUBLIC_API.md +10 -2
- data/docs/RECURRING_PAYMENT.md +56 -0
- data/docs/RELEASE_150_CANDIDATE.md +2 -0
- data/docs/RELEASE_160_CANDIDATE.md +30 -0
- data/docs/RELEASE_161_CANDIDATE.md +30 -0
- data/docs/RUBY_INTEGRATION.ja.md +204 -0
- data/docs/RUBY_INTEGRATION.md +222 -0
- data/docs/SUPPORT_CONTRACT.md +19 -2
- data/examples/conditional_checkout.rb +3 -3
- data/examples/integration/inputs.rb +169 -0
- data/examples/integration/processor.rb +39 -0
- data/examples/long_payment.rb +116 -0
- data/examples/long_payment_acceptance.rb +89 -0
- data/examples/recurring_payment.rb +99 -0
- data/examples/ruby_integration.rb +161 -0
- data/lib/ap2_mandate_verifier/checkout_jwt.rb +1 -1
- data/lib/ap2_mandate_verifier/checkout_receipt.rb +10 -1
- data/lib/ap2_mandate_verifier/conditional_checkout.rb +43 -19
- data/lib/ap2_mandate_verifier/input_builder.rb +1 -1
- data/lib/ap2_mandate_verifier/long_payment.rb +201 -0
- data/lib/ap2_mandate_verifier/payment.rb +52 -12
- data/lib/ap2_mandate_verifier/payment_acceptance/long_sqlite_store.rb +272 -0
- data/lib/ap2_mandate_verifier/payment_acceptance/recurring_sqlite_store.rb +124 -0
- data/lib/ap2_mandate_verifier/payment_acceptance/sqlite_store.rb +38 -10
- data/lib/ap2_mandate_verifier/payment_acceptance.rb +28 -6
- data/lib/ap2_mandate_verifier/payment_policy.rb +7 -2
- data/lib/ap2_mandate_verifier/purchase_binding.rb +11 -5
- data/lib/ap2_mandate_verifier/recurring_payment.rb +111 -0
- data/lib/ap2_mandate_verifier/root_disclosures.rb +9 -6
- data/lib/ap2_mandate_verifier/scoped_constraints.rb +1 -1
- data/lib/ap2_mandate_verifier/selective_payment.rb +1 -1
- data/lib/ap2_mandate_verifier/trust_context.rb +6 -0
- data/lib/ap2_mandate_verifier.rb +4 -0
- metadata +23 -6
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
# Ruby-only synthetic application: no network, Rails, A2A or real payment.
|
|
3
|
+
require "ap2_mandate_verifier"
|
|
4
|
+
require "json"
|
|
5
|
+
require_relative "integration/inputs"
|
|
6
|
+
require_relative "integration/processor"
|
|
7
|
+
module RubyIntegration
|
|
8
|
+
M = AP2MandateVerifier
|
|
9
|
+
A = M::PaymentAcceptance
|
|
10
|
+
NOW = 1_800_000_000 # Explicit virtual clock. NEVER use this clock in a real app.
|
|
11
|
+
SCENARIOS = %w[success error pause-before-start expired-before-start crash-before-start crash-after-start crash-after-charge unknown delayed].freeze
|
|
12
|
+
class App
|
|
13
|
+
def self.init(directory)
|
|
14
|
+
# Partial bootstrap is a STOP. Never delete/recreate an existing directory.
|
|
15
|
+
Dir.mkdir(directory, 0o700)
|
|
16
|
+
data = Inputs.bootstrap(now: NOW)
|
|
17
|
+
File.open(File.join(directory, "app.json"), File::WRONLY | File::CREAT | File::EXCL, 0o600) do |file|
|
|
18
|
+
file.write(JSON.generate(data)); file.flush; file.fsync
|
|
19
|
+
end
|
|
20
|
+
store = A::SQLiteStore.create(path: File.join(directory, "acceptance.sqlite3"))
|
|
21
|
+
store.authorize!(**data.fetch("scope").transform_keys(&:to_sym), mode: :conditional,
|
|
22
|
+
profile_ref: M::Payment::PROFILE_REF, checkout: data.fetch("checkout"),
|
|
23
|
+
payment: data.fetch("expected_payment"), receipt_context: data.fetch("receipt_context"))
|
|
24
|
+
store.close
|
|
25
|
+
Processor.create(File.join(directory, "processor.sqlite3"))
|
|
26
|
+
File.open(directory, File::RDONLY) { |file| file.fsync }
|
|
27
|
+
{event: "initialized", sdk_state: "not_reserved", mock_dispatches: 0}
|
|
28
|
+
ensure
|
|
29
|
+
store&.close rescue nil
|
|
30
|
+
end
|
|
31
|
+
def initialize(directory)
|
|
32
|
+
@directory = directory
|
|
33
|
+
@data = current_data
|
|
34
|
+
@scope = @data.fetch("scope").transform_keys(&:to_sym)
|
|
35
|
+
@store = A::SQLiteStore.new(path: File.join(directory, "acceptance.sqlite3"))
|
|
36
|
+
@service = A::Service.new(store: @store)
|
|
37
|
+
@processor = Processor.new(File.join(directory, "processor.sqlite3"))
|
|
38
|
+
end
|
|
39
|
+
def close
|
|
40
|
+
@processor&.close
|
|
41
|
+
@store&.close
|
|
42
|
+
end
|
|
43
|
+
def current_data
|
|
44
|
+
path = File.join(@directory, "app.json")
|
|
45
|
+
raise "application state unavailable" unless File.file?(path) && File.size(path) <= 131_072
|
|
46
|
+
JSON.parse(File.binread(path))
|
|
47
|
+
end
|
|
48
|
+
def run(scenario)
|
|
49
|
+
raise "unknown scenario" unless SCENARIOS.include?(scenario)
|
|
50
|
+
inputs = Inputs.verification(current_data, now: NOW)
|
|
51
|
+
# Educational check only: accept/start reverify raw CURRENT inputs themselves.
|
|
52
|
+
raise "verification failed" unless M::Payment.verify(**inputs).verified?
|
|
53
|
+
accepted = @service.accept(**@scope, mode: :conditional, verification_inputs: inputs)
|
|
54
|
+
unless accepted.ticket
|
|
55
|
+
require_existing!(accepted)
|
|
56
|
+
return summary("no_new_ticket", accepted)
|
|
57
|
+
end
|
|
58
|
+
crash("reserved_before_start", accepted) if scenario == "crash-before-start"
|
|
59
|
+
# Same-process interruption retains the opaque Ticket. Restart does not.
|
|
60
|
+
if scenario == "pause-before-start"
|
|
61
|
+
@store.close
|
|
62
|
+
@store = A::SQLiteStore.new(path: File.join(@directory, "acceptance.sqlite3"))
|
|
63
|
+
@service = A::Service.new(store: @store)
|
|
64
|
+
end
|
|
65
|
+
fresh = Inputs.verification(current_data, now: scenario == "expired-before-start" ? NOW + 61 : NOW)
|
|
66
|
+
execution = @service.start(ticket: accepted.ticket, verification_inputs: fresh)
|
|
67
|
+
return summary("start_blocked", @service.lookup(**@scope)) unless execution
|
|
68
|
+
crash("started_before_dispatch", @service.lookup(**@scope)) if scenario == "crash-after-start"
|
|
69
|
+
issued_at = scenario == "delayed" ? NOW + 120 : NOW
|
|
70
|
+
receipt = unless scenario == "unknown"
|
|
71
|
+
Inputs.receipt(@data, wire: execution.closed_sd_jwt, outcome: scenario == "error" ? "Error" : "Success", now: issued_at)
|
|
72
|
+
end
|
|
73
|
+
@processor.dispatch(execution, receipt: receipt)
|
|
74
|
+
crash("processor_committed_before_finish", @service.lookup(**@scope)) if scenario == "crash-after-charge"
|
|
75
|
+
if %w[unknown delayed].include?(scenario)
|
|
76
|
+
return summary("awaiting_reconciliation", @service.unknown(ticket: accepted.ticket))
|
|
77
|
+
end
|
|
78
|
+
final = @service.finish(ticket: accepted.ticket, receipt_jwt: receipt, verified_at: NOW)
|
|
79
|
+
raise "Receipt finalization failed" unless %i[receipt_success receipt_error].include?(final.status)
|
|
80
|
+
summary("finished", final)
|
|
81
|
+
end
|
|
82
|
+
def retry(resigned: false)
|
|
83
|
+
fresh = Inputs.verification(current_data, now: NOW)
|
|
84
|
+
fresh[:closed_sd_jwt] = Inputs.resign(@data, now: NOW) if resigned
|
|
85
|
+
previous = @service.lookup(**@scope)
|
|
86
|
+
raise "no existing attempt" unless previous.processor_key
|
|
87
|
+
result = @service.accept(**@scope, mode: :conditional, verification_inputs: fresh)
|
|
88
|
+
raise "retry changed identity" if result.ticket || result.processor_key != previous.processor_key ||
|
|
89
|
+
result.closed_sd_jwt != previous.closed_sd_jwt || result.reference != previous.reference
|
|
90
|
+
summary(resigned ? "resigned_retry" : "exact_retry", result).merge(original_identity_preserved: true)
|
|
91
|
+
end
|
|
92
|
+
def recover
|
|
93
|
+
original = @service.lookup(**@scope)
|
|
94
|
+
require_existing!(original)
|
|
95
|
+
saved = @processor.query(original.processor_key) # QUERY only, never dispatch.
|
|
96
|
+
raise "processor reference mismatch" if saved && saved.fetch("reference") != original.reference
|
|
97
|
+
receipt = saved && saved.fetch("receipt")
|
|
98
|
+
unless receipt
|
|
99
|
+
return summary("operator_reconciliation_required", original).merge(result: "unknown")
|
|
100
|
+
end
|
|
101
|
+
# Receipt window is independent of the expired Mandate/challenge.
|
|
102
|
+
final = @service.reconcile(**@scope, receipt_jwt: receipt, verified_at: NOW + 120)
|
|
103
|
+
raise "recovery changed identity" if final.ticket || (final.processor_key && final.processor_key != original.processor_key)
|
|
104
|
+
raise "Receipt reconciliation failed" unless %i[receipt_success receipt_error].include?(final.status)
|
|
105
|
+
summary("reconciled", final)
|
|
106
|
+
end
|
|
107
|
+
def require_existing!(result)
|
|
108
|
+
raise "attempt unavailable or invalid" unless result.processor_key &&
|
|
109
|
+
%i[pending unknown receipt_success receipt_error].include?(result.status)
|
|
110
|
+
end
|
|
111
|
+
def inspect_state
|
|
112
|
+
result = @service.lookup(**@scope)
|
|
113
|
+
require_existing!(result)
|
|
114
|
+
summary("inspection", result)
|
|
115
|
+
end
|
|
116
|
+
def summary(event, result)
|
|
117
|
+
raise "invalid result state" unless result.processor_key &&
|
|
118
|
+
%i[reserved pending unknown receipt_success receipt_error].include?(result.status)
|
|
119
|
+
value = {event: event, sdk_state: result.status, ticket: !result.ticket.nil?, mock_dispatches: @processor.count}
|
|
120
|
+
if %i[receipt_success receipt_error].include?(result.status)
|
|
121
|
+
value[:receipt_authentic] = true
|
|
122
|
+
value[:reported_outcome] = result.status == :receipt_success ? "Success" : "Error"
|
|
123
|
+
end
|
|
124
|
+
value
|
|
125
|
+
end
|
|
126
|
+
def crash(event, result)
|
|
127
|
+
puts JSON.generate(summary(event, result).merge(simulated_process_exit: 75))
|
|
128
|
+
$stdout.flush
|
|
129
|
+
Process.exit!(75) # No ensure/normal cleanup; next CLI is a different Ruby process.
|
|
130
|
+
end
|
|
131
|
+
end
|
|
132
|
+
def self.cli(args)
|
|
133
|
+
command, directory, option = args
|
|
134
|
+
raise "invalid command" unless args.size.between?(2, 3) && directory &&
|
|
135
|
+
%w[init run recover retry inspect].include?(command) &&
|
|
136
|
+
(command == "run" || command == "retry" || option.nil?) &&
|
|
137
|
+
(command != "retry" || option.nil? || option == "resigned")
|
|
138
|
+
result = if command == "init"
|
|
139
|
+
App.init(directory)
|
|
140
|
+
else
|
|
141
|
+
app = App.new(directory)
|
|
142
|
+
case command
|
|
143
|
+
when "run" then app.run(option || "success")
|
|
144
|
+
when "retry" then app.retry(resigned: option == "resigned")
|
|
145
|
+
when "recover" then app.recover
|
|
146
|
+
when "inspect" then app.inspect_state
|
|
147
|
+
end
|
|
148
|
+
end
|
|
149
|
+
feature = $LOADED_FEATURES.find { |path| path.end_with?("/ap2_mandate_verifier.rb") }
|
|
150
|
+
spec = Gem.loaded_specs["ap2_mandate_verifier"]
|
|
151
|
+
puts JSON.generate(result.merge(sdk_version: spec&.version&.to_s || "source",
|
|
152
|
+
sdk_load: spec && feature.start_with?(spec.full_gem_path + "/") ? "installed_gem" : "repository_lib",
|
|
153
|
+
ruby: RUBY_VERSION, fixture_clock: NOW))
|
|
154
|
+
rescue StandardError, LoadError
|
|
155
|
+
warn "STOP: invalid command or unavailable/inconsistent state; preserve all files and investigate."
|
|
156
|
+
return 1
|
|
157
|
+
ensure
|
|
158
|
+
app&.close
|
|
159
|
+
end
|
|
160
|
+
end
|
|
161
|
+
exit(RubyIntegration.cli(ARGV) || 0) 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
|
-
|
|
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
|
-
|
|
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:
|
|
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
|
-
|
|
81
|
-
"sd_hash" => digest(root), "delegate_payload" => [closed]}
|
|
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:
|
|
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
|
-
|
|
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:
|
|
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:
|
|
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 (
|
|
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
|