ap2_mandate_verifier 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. checksums.yaml +4 -4
  2. data/README.ja.md +31 -8
  3. data/README.md +31 -8
  4. data/SECURITY.md +8 -2
  5. data/docs/LONG_PAYMENT.md +82 -0
  6. data/docs/PAYMENT_ACCEPTANCE.md +90 -0
  7. data/docs/PAYMENT_POLICY.md +4 -2
  8. data/docs/PUBLIC_API.md +16 -2
  9. data/docs/RECURRING_PAYMENT.md +54 -0
  10. data/docs/RELEASE_140_CANDIDATE.md +2 -0
  11. data/docs/RELEASE_150_CANDIDATE.md +23 -0
  12. data/docs/RELEASE_160_CANDIDATE.md +30 -0
  13. data/docs/SUPPORT_CONTRACT.md +9 -1
  14. data/examples/conditional_checkout.rb +3 -3
  15. data/examples/long_payment.rb +116 -0
  16. data/examples/long_payment_acceptance.rb +89 -0
  17. data/examples/payment_acceptance.rb +77 -0
  18. data/examples/recurring_payment.rb +99 -0
  19. data/lib/ap2_mandate_verifier/checkout_jwt.rb +1 -1
  20. data/lib/ap2_mandate_verifier/checkout_receipt.rb +10 -1
  21. data/lib/ap2_mandate_verifier/conditional_checkout.rb +43 -19
  22. data/lib/ap2_mandate_verifier/input_builder.rb +1 -1
  23. data/lib/ap2_mandate_verifier/long_payment.rb +201 -0
  24. data/lib/ap2_mandate_verifier/payment.rb +52 -12
  25. data/lib/ap2_mandate_verifier/payment_acceptance/long_sqlite_store.rb +272 -0
  26. data/lib/ap2_mandate_verifier/payment_acceptance/recurring_sqlite_store.rb +124 -0
  27. data/lib/ap2_mandate_verifier/payment_acceptance/sqlite_store.rb +344 -0
  28. data/lib/ap2_mandate_verifier/payment_acceptance.rb +285 -0
  29. data/lib/ap2_mandate_verifier/payment_policy.rb +7 -2
  30. data/lib/ap2_mandate_verifier/purchase_binding.rb +11 -5
  31. data/lib/ap2_mandate_verifier/recurring_payment.rb +111 -0
  32. data/lib/ap2_mandate_verifier/root_disclosures.rb +9 -6
  33. data/lib/ap2_mandate_verifier/scoped_constraints.rb +1 -1
  34. data/lib/ap2_mandate_verifier/selective_payment.rb +1 -1
  35. data/lib/ap2_mandate_verifier/trust_context.rb +6 -0
  36. data/lib/ap2_mandate_verifier.rb +6 -0
  37. metadata +22 -5
@@ -0,0 +1,344 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ module PaymentAcceptance
5
+ # Optional local durable reference. Production adapters must preserve the
6
+ # same protected-authorization + claim transaction and CAS guarantees.
7
+ class SQLiteStore
8
+ SCHEMA_VERSION = 1
9
+ DRIVER_VERSION = "2.10.2".freeze
10
+ RECEIPT_FIELDS = %w[trusted_public_key_pem expected_issuer expected_payment_id not_before not_after].freeze
11
+ SCHEMA = {
12
+ "ap2_store" => "CREATE TABLE ap2_store (identity TEXT NOT NULL)",
13
+ "ap2_approvals" => "CREATE TABLE ap2_approvals (operation_key TEXT PRIMARY KEY, tenant TEXT NOT NULL, merchant TEXT NOT NULL, approval TEXT NOT NULL, occurrence TEXT NOT NULL, scope TEXT NOT NULL, instruction TEXT NOT NULL, receipt_context TEXT NOT NULL, active INTEGER NOT NULL DEFAULT 1 CHECK(active IN (0,1)), UNIQUE(tenant,merchant,approval,occurrence))",
14
+ "ap2_attempts" => "CREATE TABLE ap2_attempts (operation_key TEXT PRIMARY KEY REFERENCES ap2_approvals(operation_key), tenant TEXT NOT NULL, merchant TEXT NOT NULL, closed_reference TEXT NOT NULL, fence TEXT NOT NULL, state TEXT NOT NULL CHECK(state IN ('reserved','processing','unknown','receipt_success','receipt_error')), record TEXT NOT NULL, UNIQUE(tenant,merchant,closed_reference))"
15
+ }.transform_values(&:freeze).freeze
16
+ INDEXES = [
17
+ ["sqlite_autoindex_ap2_approvals_1", "ap2_approvals"],
18
+ ["sqlite_autoindex_ap2_approvals_2", "ap2_approvals"],
19
+ ["sqlite_autoindex_ap2_attempts_1", "ap2_attempts"],
20
+ ["sqlite_autoindex_ap2_attempts_2", "ap2_attempts"]
21
+ ].map(&:freeze).freeze
22
+ def self.create(**arguments)
23
+ raise Unavailable unless arguments.keys == [:path]
24
+ path = arguments.fetch(:path)
25
+ dependencies!
26
+ checked = path!(path)
27
+ File.open(checked, File::WRONLY | File::CREAT | File::EXCL, 0o600) { |f| f.fsync }
28
+ value = allocate
29
+ value.send(:setup!, checked, true)
30
+ value
31
+ rescue StandardError, LoadError
32
+ raise Unavailable.new, cause: nil
33
+ end
34
+ def self.dependencies!
35
+ gem "sqlite3", "= #{DRIVER_VERSION}"
36
+ require "sqlite3"
37
+ raise Unavailable unless Gem.loaded_specs.fetch("sqlite3").version.to_s == DRIVER_VERSION
38
+ end
39
+ def self.path!(path)
40
+ checked = InputValidator.snapshot!(path, max_bytes: 4096)
41
+ raise Invalid if checked.empty? || checked == ":memory:" || checked.include?("\0") || checked.start_with?("file:")
42
+ checked
43
+ end
44
+ private_class_method :dependencies!, :path!
45
+ def initialize(**arguments)
46
+ raise Unavailable unless arguments.keys == [:path]
47
+ setup!(self.class.send(:path!, arguments.fetch(:path)), false)
48
+ rescue StandardError, LoadError
49
+ raise Unavailable.new, cause: nil
50
+ end
51
+ def inspect = "#<AP2MandateVerifier::PaymentAcceptance::SQLiteStore>"
52
+ def setup!(path, creating)
53
+ self.class.send(:dependencies!)
54
+ @path = path
55
+ @db = SQLite3::Database.new(@path, flags: SQLite3::Constants::Open::READWRITE)
56
+ @db.busy_timeout = 5000
57
+ unless creating
58
+ raise Unavailable unless @db.get_first_value("PRAGMA user_version") == self.class::SCHEMA_VERSION && @db.execute("PRAGMA quick_check") == [["ok"]]
59
+ expected = self.class::SCHEMA.map { |name,sql| ["table", name, name, sql] } +
60
+ self.class::INDEXES.map { |name,table| ["index", name, table, nil] }
61
+ actual = @db.execute("SELECT type,name,tbl_name,sql FROM sqlite_master ORDER BY type,name")
62
+ raise Unavailable unless actual == expected.sort_by { |row| row.first(2) }
63
+ identities = @db.execute("SELECT identity FROM ap2_store")
64
+ raise Unavailable unless identities.size == 1 && identities[0].size == 1
65
+ @store_id = identities[0][0]
66
+ raise Unavailable unless @store_id.instance_of?(String) && @store_id.match?(/\A[0-9a-f]{64}\z/)
67
+ end
68
+ @db.execute("PRAGMA journal_mode=DELETE")
69
+ @db.execute("PRAGMA synchronous=FULL")
70
+ @db.execute("PRAGMA foreign_keys=ON")
71
+ raise Unavailable unless @db.get_first_value("PRAGMA journal_mode") == "delete" &&
72
+ @db.get_first_value("PRAGMA synchronous") == 2 && @db.get_first_value("PRAGMA foreign_keys") == 1
73
+ if creating
74
+ require "securerandom"
75
+ @store_id = SecureRandom.hex(32)
76
+ @db.execute("BEGIN IMMEDIATE")
77
+ self.class::SCHEMA.each_value { |sql| @db.execute(sql) }
78
+ @db.execute("INSERT INTO ap2_store(identity) VALUES (?)", [@store_id])
79
+ @db.execute("PRAGMA user_version=#{self.class::SCHEMA_VERSION}")
80
+ @db.execute("COMMIT")
81
+ end
82
+ @mutex = Mutex.new
83
+ rescue StandardError, LoadError
84
+ @db&.close rescue nil
85
+ raise Unavailable.new, cause: nil
86
+ end
87
+ private :setup!
88
+
89
+ # Only a protected Host approval backend may enroll this immutable grant.
90
+ # A received ID/flag never enrolls or alters an approved occurrence.
91
+ def authorize!(tenant_id:, merchant_id:, operation_id:, approval_id:, occurrence_id:, order_id:,
92
+ mode:, profile_ref:, checkout:, payment:, receipt_context:)
93
+ scope = PaymentAcceptance.scope!({"tenant_id" => tenant_id, "merchant_id" => merchant_id,
94
+ "operation_id" => operation_id, "approval_id" => approval_id, "occurrence_id" => occurrence_id, "order_id" => order_id})
95
+ profile = PaymentAcceptance.profile!(mode, profile_ref)
96
+ approval_policy!(profile)
97
+ cart = InputBuilder.send(:copy!, checkout)
98
+ raise Invalid unless cart["id"] == scope["order_id"] && cart.dig("merchant", "id") == scope["merchant_id"]
99
+ instruction = PaymentAcceptance.instruction!(mode, profile, cart, payment)
100
+ context = PaymentAcceptance.copy!(receipt_context).transform_keys(&:to_s)
101
+ raise Invalid unless context.keys.sort == RECEIPT_FIELDS.sort
102
+ RootSignature.public_jwk!(context["trusted_public_key_pem"])
103
+ %w[expected_issuer expected_payment_id].each { |f| CheckoutReceipt.send(:text!, context[f], 512) }
104
+ %w[not_before not_after].each { |f| CheckoutReceipt.send(:epoch!, context[f]) }
105
+ raise Invalid unless context["not_before"] <= context["not_after"]
106
+ row = [PaymentAcceptance.canonical(scope), instruction, PaymentAcceptance.canonical(context)]
107
+ transaction do
108
+ alias_key = @db.get_first_value("SELECT operation_key FROM ap2_approvals WHERE tenant=? AND merchant=? AND approval=? AND occurrence=?",
109
+ scope.values_at("tenant_id", "merchant_id", "approval_id", "occurrence_id"))
110
+ raise Conflict if alias_key && alias_key != PaymentAcceptance.key(scope)
111
+ old = @db.get_first_row("SELECT CASE WHEN length(CAST(scope AS BLOB))<=131072 THEN scope END,CASE WHEN length(CAST(instruction AS BLOB))<=131072 THEN instruction END,CASE WHEN length(CAST(receipt_context AS BLOB))<=8192 THEN receipt_context END FROM ap2_approvals WHERE operation_key=?", [PaymentAcceptance.key(scope)])
112
+ check_grant!(old) if old
113
+ raise Conflict if old && old != row
114
+ unless old
115
+ begin
116
+ @db.execute("INSERT INTO ap2_approvals(operation_key,tenant,merchant,approval,occurrence,scope,instruction,receipt_context) VALUES (?,?,?,?,?,?,?,?)",
117
+ [PaymentAcceptance.key(scope), *scope.values_at("tenant_id", "merchant_id", "approval_id", "occurrence_id"), *row])
118
+ rescue SQLite3::ConstraintException
119
+ raise Conflict
120
+ end
121
+ end
122
+ true
123
+ end
124
+ end
125
+
126
+ def reserve!(scope:, instruction:, record:)
127
+ transaction do
128
+ key = PaymentAcceptance.key(scope)
129
+ grant = @db.get_first_row("SELECT CASE WHEN length(CAST(scope AS BLOB))<=131072 THEN scope END,CASE WHEN length(CAST(instruction AS BLOB))<=131072 THEN instruction END,CASE WHEN length(CAST(receipt_context AS BLOB))<=8192 THEN receipt_context END,active FROM ap2_approvals WHERE operation_key=?", [key])
130
+ raise Invalid unless grant
131
+ check_grant!(grant)
132
+ raise Invalid unless grant[3] == 1
133
+ raise Conflict unless grant[0] == PaymentAcceptance.canonical(scope) && grant[1] == instruction
134
+ validate_reservation!(scope, record)
135
+ old = load_record(key)
136
+ if old
137
+ raise Conflict unless old["instruction"] == instruction
138
+ next PaymentAcceptance.result(old)
139
+ end
140
+ reused = @db.get_first_value("SELECT operation_key FROM ap2_attempts WHERE tenant=? AND merchant=? AND closed_reference=?",
141
+ [scope.fetch("tenant_id"), scope.fetch("merchant_id"), record.fetch("reference")])
142
+ raise Conflict if reused
143
+ charge_reservation!(scope, record)
144
+ require "securerandom"
145
+ fence = SecureRandom.hex(32)
146
+ value = record.merge("state" => "reserved", "processor_key" => SecureRandom.hex(32),
147
+ "receipt_context" => decode!(grant[2], 8192))
148
+ raise Invalid if JSON.generate(value).bytesize > 1_048_576
149
+ begin
150
+ @db.execute("INSERT INTO ap2_attempts(operation_key,tenant,merchant,closed_reference,fence,state,record) VALUES (?,?,?,?,?,?,?)",
151
+ [key, scope.fetch("tenant_id"), scope.fetch("merchant_id"), record.fetch("reference"), fence, "reserved", JSON.generate(value)])
152
+ rescue SQLite3::ConstraintException
153
+ raise Conflict
154
+ end
155
+ # Returned only after COMMIT succeeds. A commit error is unavailable,
156
+ # even if SQLite may have persisted the row; no capability is returned.
157
+ Result.send(:new, :reserved, value, Ticket.send(:new, @store_id + key, fence))
158
+ end
159
+ end
160
+
161
+ def start!(ticket:, verified_at:, instruction:, signed_wires:)
162
+ start_record!(ticket: ticket, verified_at: verified_at, instruction: instruction, signed_wires: signed_wires)
163
+ end
164
+
165
+ def start_record!(ticket:, verified_at:, instruction:, signed_wires:, authority: nil, fresh_valid_until: nil)
166
+ key, fence = ticket_parts!(ticket)
167
+ transaction do
168
+ row = @db.get_first_row("SELECT state,CASE WHEN length(CAST(record AS BLOB))<=1048576 THEN record ELSE NULL END FROM ap2_attempts WHERE operation_key=? AND fence=?", [key, fence])
169
+ raise Invalid unless row
170
+ next nil unless row[0] == "reserved"
171
+ record = decode!(row[1], 1_048_576)
172
+ raise Unavailable unless record["state"] == row[0]
173
+ grant = @db.get_first_row("SELECT active,CASE WHEN length(CAST(instruction AS BLOB))<=131072 THEN instruction END FROM ap2_approvals WHERE operation_key=?", [key])
174
+ raise Invalid unless grant && grant[0] == 1 && grant[1] == instruction &&
175
+ record["instruction"] == instruction && record["signed_wires"] == signed_wires
176
+ if fresh_valid_until
177
+ CheckoutReceipt.send(:epoch!, fresh_valid_until)
178
+ record["valid_until"] = [record.fetch("valid_until"), fresh_valid_until].min
179
+ end
180
+ next nil unless verified_at >= record["accepted_at"] && verified_at < record["valid_until"]
181
+ validate_start!(record, verified_at)
182
+ validate_current_authority!(record, verified_at, authority)
183
+ record["state"] = "processing"
184
+ record["started_at"] = verified_at
185
+ @db.execute("UPDATE ap2_attempts SET state='processing',record=? WHERE operation_key=? AND fence=? AND state='reserved'", [JSON.generate(record), key, fence])
186
+ raise Unavailable unless @db.changes == 1
187
+ record
188
+ end
189
+ end
190
+
191
+ private :start_record!
192
+
193
+ def ticket_record!(ticket:)
194
+ key, fence = ticket_parts!(ticket)
195
+ transaction do
196
+ row = @db.get_first_row("SELECT CASE WHEN length(CAST(record AS BLOB))<=1048576 THEN record ELSE NULL END FROM ap2_attempts WHERE operation_key=? AND fence=?", [key, fence])
197
+ raise Invalid unless row
198
+ decode!(row[0], 1_048_576)
199
+ end
200
+ end
201
+
202
+ def lookup_record!(scope:)
203
+ transaction do
204
+ record = load_record(PaymentAcceptance.key(scope))
205
+ raise Conflict if record && record["scope"] != scope
206
+ record
207
+ end
208
+ end
209
+
210
+ def unknown!(ticket:)
211
+ key, fence = ticket_parts!(ticket)
212
+ transaction do
213
+ record = load_record(key, fence)
214
+ raise Invalid unless record
215
+ if record["state"] == "processing"
216
+ record["state"] = "unknown"
217
+ save(key, record)
218
+ elsif record["state"] != "unknown"
219
+ raise Invalid
220
+ end
221
+ PaymentAcceptance.result(record)
222
+ end
223
+ end
224
+
225
+ def finish!(scope:, ticket:, receipt_jwt:, status:)
226
+ raise Invalid unless %w[receipt_success receipt_error].include?(status)
227
+ key = PaymentAcceptance.key(scope)
228
+ fence = ticket_parts!(ticket)[1] if ticket
229
+ raise Invalid if ticket && ticket_parts!(ticket)[0] != key
230
+ transaction do
231
+ record = load_record(key, fence)
232
+ raise Invalid unless record && record["scope"] == scope
233
+ if %w[receipt_success receipt_error].include?(record["state"])
234
+ raise Conflict unless record["receipt_jwt"] == receipt_jwt && record["state"] == status
235
+ else
236
+ raise Invalid unless %w[processing unknown].include?(record["state"])
237
+ record["state"], record["receipt_jwt"] = status, receipt_jwt
238
+ save(key, record)
239
+ end
240
+ PaymentAcceptance.result(record)
241
+ end
242
+ end
243
+
244
+ def close
245
+ @mutex.synchronize { @db.close }
246
+ rescue StandardError
247
+ raise Unavailable.new, cause: nil
248
+ end
249
+
250
+ def revoke!(**scope)
251
+ scope = PaymentAcceptance.scope_keywords!(scope)
252
+ transaction do
253
+ @db.execute("UPDATE ap2_approvals SET active=0 WHERE operation_key=? AND scope=?", [PaymentAcceptance.key(scope), PaymentAcceptance.canonical(scope)])
254
+ raise Invalid unless @db.changes == 1
255
+ true
256
+ end
257
+ end
258
+
259
+ private
260
+ # Extension hooks execute inside the SAME SQLite transaction as reservation/start.
261
+ # The old schema must never accept a profile requiring an absent quota ledger.
262
+ def approval_policy!(profile)
263
+ raise Invalid if RecurringPayment.profile?(profile) || LongPayment.profile?(profile)
264
+ end
265
+ def validate_reservation!(_scope, record) = approval_policy!(record.fetch("profile_ref"))
266
+ def charge_reservation!(_scope, _record); end
267
+ def validate_start!(_record, _verified_at); end
268
+ def validate_current_authority!(_record, _at, authority)
269
+ raise Invalid unless authority.nil?
270
+ end
271
+ def ticket_parts!(ticket)
272
+ raise Invalid unless ticket.instance_of?(Ticket)
273
+ key = ticket.send(:key)
274
+ raise Invalid unless key.start_with?(@store_id) && key.bytesize == 128
275
+ [key[64,64], ticket.send(:fence)]
276
+ end
277
+ def load_record(key, fence = nil)
278
+ sql = "SELECT state,CASE WHEN length(CAST(record AS BLOB))<=1048576 THEN record ELSE NULL END FROM ap2_attempts WHERE operation_key=?"
279
+ args = [key]
280
+ if fence
281
+ sql += " AND fence=?"; args << fence
282
+ end
283
+ row = @db.get_first_row(sql, args)
284
+ if row
285
+ record = decode!(row[1], 1_048_576)
286
+ raise Unavailable unless record["state"] == row[0]
287
+ record
288
+ end
289
+ end
290
+ def save(key, record)
291
+ raise Unavailable if JSON.generate(record).bytesize > 1_048_576
292
+ @db.execute("UPDATE ap2_attempts SET state=?,record=? WHERE operation_key=?", [record.fetch("state"), JSON.generate(record), key])
293
+ raise Unavailable unless @db.changes == 1
294
+ end
295
+ def check_grant!(row)
296
+ [131_072,131_072,8192].each_with_index { |limit,i| InputValidator.snapshot!(row[i], max_bytes: limit) }
297
+ end
298
+ def decode!(source, max)
299
+ wire = InputValidator.snapshot!(source, max_bytes: max)
300
+ InputValidator.send(:reject_extensions!, wire)
301
+ raise Unavailable unless JSON::VERSION == InputValidator::JSON_VERSION
302
+ JSON.parse(wire, create_additions: false, symbolize_names: false, max_nesting: 24,
303
+ allow_nan: false, allow_duplicate_key: false, allow_trailing_comma: false)
304
+ rescue StandardError
305
+ raise Unavailable.new, cause: nil
306
+ end
307
+ def transaction
308
+ @mutex.synchronize do
309
+ @db.execute("BEGIN IMMEDIATE")
310
+ begin
311
+ value = yield
312
+ @db.execute("COMMIT")
313
+ value
314
+ rescue StandardError
315
+ @db.execute("ROLLBACK") rescue nil
316
+ raise
317
+ end
318
+ end
319
+ rescue Invalid, Conflict
320
+ raise
321
+ rescue StandardError
322
+ raise Unavailable.new, cause: nil
323
+ end
324
+
325
+ %i[authorize! reserve! start! ticket_record! lookup_record! unknown! finish! close revoke!].each do |name|
326
+ implementation = instance_method(name)
327
+ required = implementation.parameters.filter_map { |kind, key| key if kind == :keyreq }.freeze
328
+ allowed = implementation.parameters.filter_map { |kind, key| key if %i[keyreq key].include?(kind) }.freeze
329
+ rest = implementation.parameters.any? { |kind,_| kind == :keyrest }
330
+ define_method(name) do |**arguments|
331
+ raise Invalid unless (required - arguments.keys).empty? && (rest || (arguments.keys - allowed).empty?)
332
+ implementation.bind_call(self, **arguments)
333
+ rescue Conflict
334
+ raise Conflict.new("payment acceptance conflict"), cause: nil
335
+ rescue Unavailable
336
+ raise Unavailable.new, cause: nil
337
+ rescue StandardError, LoadError
338
+ raise Invalid.new, cause: nil
339
+ end
340
+ public name
341
+ end
342
+ end
343
+ end
344
+ end
@@ -0,0 +1,285 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Application-side single-attempt coordination, not a PSP execution engine.
5
+ module PaymentAcceptance
6
+ SCOPE = %w[tenant_id merchant_id operation_id approval_id occurrence_id order_id].freeze
7
+ class Invalid < ArgumentError
8
+ def initialize = super("invalid payment acceptance information")
9
+ end
10
+ class Unavailable < StandardError
11
+ def initialize = super("payment acceptance storage unavailable")
12
+ end
13
+ class Conflict < StandardError; end
14
+
15
+ class Ticket
16
+ def initialize(key, fence)
17
+ @key, @fence = key.freeze, fence.freeze
18
+ freeze
19
+ end
20
+ def inspect = "#<AP2MandateVerifier::PaymentAcceptance::Ticket>"
21
+ private
22
+ attr_reader :key, :fence
23
+ private_class_method :new
24
+ end
25
+ class Result
26
+ attr_reader :status, :ticket, :closed_sd_jwt, :reference, :receipt_jwt, :processor_key, :signed_wires
27
+ def initialize(status, record = nil, ticket = nil)
28
+ @status, @ticket = status, ticket
29
+ if record
30
+ @closed_sd_jwt, @reference, @receipt_jwt = record.values_at("closed_sd_jwt", "reference", "receipt_jwt").map { |v| v&.freeze }
31
+ @processor_key = record.fetch("processor_key").freeze
32
+ @signed_wires = ResearchEvidence.send(:copy_frozen, record.fetch("signed_wires"))
33
+ end
34
+ freeze
35
+ end
36
+ def inspect = "#<AP2MandateVerifier::PaymentAcceptance::Result status=#{status}>"
37
+ private_class_method :new
38
+ end
39
+ class Execution
40
+ attr_reader :processor_key, :closed_sd_jwt, :reference, :payment, :valid_until
41
+ def initialize(record)
42
+ @processor_key, @closed_sd_jwt, @reference = record.values_at("processor_key", "closed_sd_jwt", "reference").map(&:freeze)
43
+ @payment = ResearchEvidence.send(:copy_frozen, record.fetch("payment"))
44
+ @valid_until = record.fetch("valid_until")
45
+ freeze
46
+ end
47
+ def inspect = "#<AP2MandateVerifier::PaymentAcceptance::Execution>"
48
+ private_class_method :new
49
+ end
50
+
51
+ class Service
52
+ def initialize(**arguments)
53
+ raise Invalid.new, cause: nil unless arguments.keys == [:store]
54
+ @store = arguments.fetch(:store)
55
+ end
56
+ def inspect = "#<AP2MandateVerifier::PaymentAcceptance::Service>"
57
+ # Every call starts from raw verifier inputs, never a caller-made proof.
58
+ def accept(mode:, verification_inputs:, tenant_id:, merchant_id:, operation_id:, approval_id:, occurrence_id:, order_id:)
59
+ scope = PaymentAcceptance.scope!({"tenant_id" => tenant_id, "merchant_id" => merchant_id, "operation_id" => operation_id,
60
+ "approval_id" => approval_id, "occurrence_id" => occurrence_id, "order_id" => order_id})
61
+ record = verified_record(mode, verification_inputs, scope)
62
+ @store.reserve!(scope: scope, instruction: record.fetch("instruction"), record: record)
63
+ rescue Conflict
64
+ Result.send(:new, :conflict)
65
+ rescue Unavailable
66
+ Result.send(:new, :unavailable)
67
+ rescue StandardError, LoadError
68
+ Result.send(:new, :rejected)
69
+ end
70
+
71
+ def start(ticket:, verification_inputs:)
72
+ old = @store.ticket_record!(ticket: ticket)
73
+ fresh = verified_record(old.fetch("mode").to_sym, verification_inputs, old.fetch("scope"))
74
+ raise Invalid unless old.fetch("instruction") == fresh.fetch("instruction") && old.fetch("signed_wires") == fresh.fetch("signed_wires")
75
+ record = if LongPayment.profile?(old.fetch("profile_ref"))
76
+ @store.start_long!(ticket: ticket, verified_at: fresh.fetch("accepted_at"),
77
+ instruction: fresh.fetch("instruction"), signed_wires: fresh.fetch("signed_wires"),
78
+ authority_binding: fresh.fetch("authority_binding"), valid_until: fresh.fetch("valid_until"))
79
+ else
80
+ @store.start!(ticket: ticket, verified_at: fresh.fetch("accepted_at"),
81
+ instruction: fresh.fetch("instruction"), signed_wires: fresh.fetch("signed_wires"))
82
+ end
83
+ if record
84
+ # Existing adapters retain their public signature. The returned handle
85
+ # must still expose the freshly verified shorter Host deadline.
86
+ record = record.merge("valid_until" => [record.fetch("valid_until"), fresh.fetch("valid_until")].min)
87
+ Execution.send(:new, record)
88
+ end
89
+ rescue StandardError, LoadError
90
+ nil # An uncertain commit NEVER produces an execution handle.
91
+ end
92
+
93
+ private
94
+ def verified_record(mode, verification_inputs, scope)
95
+ args = PaymentAcceptance.copy!(verification_inputs)
96
+ raise Invalid unless args.instance_of?(Hash)
97
+ profile = PaymentAcceptance.profile!(mode, args.fetch(:profile_ref, mode == :selective ? SelectivePayment::PROFILE_REF : Payment::PROFILE_REF))
98
+ result = case mode
99
+ when :direct, :conditional
100
+ raise Invalid unless args[:checkout_mode] == mode
101
+ LongPayment.profile?(profile) ? LongPayment.verify(**args) : Payment.verify(**args)
102
+ when :selective then SelectivePayment.verify(**args)
103
+ else raise Invalid
104
+ end
105
+ raise Invalid unless result.verified?
106
+ checkout_args = args.fetch(:checkout_inputs)
107
+ if mode == :direct
108
+ checkout = Buyer.verify(**checkout_args)
109
+ raise Invalid unless checkout.verified?
110
+ cart = checkout.checkout
111
+ valid_until = [checkout.expires_at, result.expires_at].min
112
+ else
113
+ checkout = AP2MandateVerifier.verify_checkout(**checkout_args)
114
+ raise Invalid unless checkout.success?
115
+ raise Invalid unless checkout.evidence["checkout_binding"].fetch("tenant_id") == scope["tenant_id"]
116
+ cart = Payment.send(:jwt_payload!, checkout_args.fetch(:host_checkout_jws), "JWT")
117
+ valid_until = [checkout.evidence["valid_until"], result.expires_at].min
118
+ end
119
+ raise Invalid unless cart.fetch("id") == scope["order_id"] && cart.fetch("merchant").fetch("id") == scope["merchant_id"]
120
+ payment = result.payment.slice(*PaymentPolicy.fields(profile))
121
+ instruction = PaymentAcceptance.instruction!(mode, profile, cart, payment)
122
+ closed = InputValidator.snapshot!(args.fetch(:closed_sd_jwt), max_bytes: 32_769)
123
+ checkout_wires = if mode == :direct
124
+ checkout_args.slice(:closed_sd_jwt, :expected_checkout_jwt)
125
+ else
126
+ checkout_args.slice(:root_presentation, :terminal_jws, :host_checkout_jws)
127
+ end
128
+ authority = nil
129
+ if LongPayment.profile?(profile)
130
+ authority = LongPayment.authority!(checkout_inputs: checkout_args,
131
+ provider_key: args.fetch(:trusted_provider_public_key_pem), agent_key: args.fetch(:expected_agent_public_key_pem),
132
+ merchant_id: scope.fetch("merchant_id"), verified_at: args.fetch(:verified_at))
133
+ proof = Payment.send(:jwt_payload!, closed.split("~", 2).first, "kb+sd-jwt")
134
+ valid_until = [valid_until, authority.fetch(:valid_until), proof.fetch("iat") + 301].min
135
+ end
136
+ record = {"scope" => scope, "mode" => mode.to_s, "profile_ref" => profile, "instruction" => instruction,
137
+ "payment" => result.payment, "closed_sd_jwt" => closed, "reference" => result.reference,
138
+ "signed_wires" => {"payment" => args.slice(:open_sd_jwt, :open_presentation, :closed_sd_jwt).transform_keys(&:to_s),
139
+ "checkout" => checkout_wires.transform_keys(&:to_s)},
140
+ "accepted_at" => args.fetch(:verified_at), "valid_until" => valid_until}
141
+ record["authority_binding"] = authority.fetch(:authority_binding) if authority
142
+ record
143
+ end
144
+ public
145
+
146
+ def finish(ticket:, receipt_jwt:, verified_at:)
147
+ record = @store.ticket_record!(ticket: ticket)
148
+ finalize(record, receipt_jwt, verified_at, ticket)
149
+ rescue Conflict
150
+ Result.send(:new, :conflict)
151
+ rescue Unavailable
152
+ Result.send(:new, :unavailable)
153
+ rescue StandardError, LoadError
154
+ Result.send(:new, :rejected)
155
+ end
156
+
157
+ def unknown(ticket:)
158
+ @store.unknown!(ticket: ticket)
159
+ rescue Unavailable
160
+ Result.send(:new, :unavailable)
161
+ rescue StandardError
162
+ Result.send(:new, :rejected)
163
+ end
164
+
165
+ # Receipt reconciliation can finalize an uncertain attempt but cannot
166
+ # recover its fence, reserve it again, or grant another execution handle.
167
+ def reconcile(receipt_jwt:, verified_at:, **scope)
168
+ record = @store.lookup_record!(scope: PaymentAcceptance.scope_keywords!(scope))
169
+ raise Invalid unless record
170
+ finalize(record, receipt_jwt, verified_at, nil)
171
+ rescue Conflict
172
+ Result.send(:new, :conflict)
173
+ rescue Unavailable
174
+ Result.send(:new, :unavailable)
175
+ rescue StandardError, LoadError
176
+ Result.send(:new, :rejected)
177
+ end
178
+
179
+ def lookup(**scope)
180
+ record = @store.lookup_record!(scope: PaymentAcceptance.scope_keywords!(scope))
181
+ record ? PaymentAcceptance.result(record) : Result.send(:new, :rejected)
182
+ rescue Unavailable
183
+ Result.send(:new, :unavailable)
184
+ rescue StandardError
185
+ Result.send(:new, :rejected)
186
+ end
187
+
188
+ private
189
+ def finalize(record, receipt_jwt, verified_at, ticket)
190
+ jwt = InputValidator.snapshot!(receipt_jwt, max_bytes: 16_384)
191
+ context = record.fetch("receipt_context").transform_keys(&:to_sym)
192
+ raise Invalid unless record.key?("started_at")
193
+ context[:not_before] = [context.fetch(:not_before), record.fetch("started_at")].max
194
+ receipt = PaymentReceipt.verify(jwt: jwt, closed_sd_jwt: record.fetch("closed_sd_jwt"),
195
+ profile_ref: record.fetch("profile_ref") == SelectivePayment::PROFILE_REF ? Payment::PROFILE_REF : record.fetch("profile_ref"),
196
+ verified_at: verified_at, **context)
197
+ raise Invalid unless receipt.verified?
198
+ status = receipt.payment_succeeded? ? "receipt_success" : "receipt_error"
199
+ @store.finish!(scope: record.fetch("scope"), ticket: ticket, receipt_jwt: jwt, status: status)
200
+ end
201
+
202
+ %i[accept start finish unknown reconcile lookup].each do |name|
203
+ implementation = instance_method(name)
204
+ required = implementation.parameters.filter_map { |kind, key| key if kind == :keyreq }.freeze
205
+ allowed = implementation.parameters.filter_map { |kind, key| key if %i[keyreq key].include?(kind) }.freeze
206
+ rest = implementation.parameters.any? { |kind,_| kind == :keyrest }
207
+ define_method(name) do |**arguments|
208
+ raise Invalid unless (required - arguments.keys).empty? && (rest || (arguments.keys - allowed).empty?)
209
+ implementation.bind_call(self, **arguments)
210
+ rescue StandardError, LoadError
211
+ name == :start ? nil : Result.send(:new, :rejected)
212
+ end
213
+ public name
214
+ end
215
+ end
216
+
217
+ def self.scope!(value)
218
+ scope = copy!(value)
219
+ raise Invalid unless scope.instance_of?(Hash) && scope.keys.sort == SCOPE.sort
220
+ scope.each_value { |v| CheckoutReceipt.send(:text!, v, 256) }
221
+ ResearchEvidence.send(:copy_frozen, scope)
222
+ end
223
+ def self.scope_keywords!(value)
224
+ scope!(copy!(value).transform_keys { |key| key.instance_of?(Symbol) ? key.to_s : key })
225
+ end
226
+ def self.profile!(mode, value)
227
+ raise Invalid unless %i[direct conditional selective].include?(mode)
228
+ PaymentPolicy.profile!(value, selective: mode == :selective)
229
+ end
230
+ def self.instruction!(mode, profile, checkout, payment)
231
+ cart = InputBuilder.send(:copy!, checkout)
232
+ ScopedConstraints.multi_checkout!(cart)
233
+ details = Payment.send(:copy_details!, payment, profile_ref: profile)
234
+ terms = details.reject { |k,_| k == "transaction_id" }
235
+ if terms.key?("execution_date")
236
+ instant = PaymentPolicy.instant!(terms["execution_date"])
237
+ terms["execution_date"] = {"numerator" => instant.numerator, "denominator" => instant.denominator}
238
+ end
239
+ canonical({"mode" => mode.to_s, "profile_ref" => profile, "checkout" => cart, "payment" => terms})
240
+ end
241
+ def self.key(scope)
242
+ digest(canonical(scope.slice("tenant_id", "merchant_id", "operation_id")))
243
+ end
244
+ def self.canonical(value)
245
+ require "json"
246
+ raise Unavailable unless JSON::VERSION == InputValidator::JSON_VERSION
247
+ normalized = case value
248
+ when Hash then value.keys.sort.to_h { |k| [k, JSON.parse(canonical(value[k]))] }
249
+ when Array then value.map { |v| JSON.parse(canonical(v)) }
250
+ else value
251
+ end
252
+ JSON.generate(normalized)
253
+ end
254
+ def self.digest(value) = Digest::SHA256.hexdigest(value)
255
+ def self.result(record)
256
+ status = %w[reserved processing].include?(record.fetch("state")) ? :pending : record.fetch("state").to_sym
257
+ Result.send(:new, status, record)
258
+ end
259
+ # Raw verifier keyword graphs include Symbols. Bound/copy without invoking
260
+ # caller coercions or singleton callbacks, before any signature or storage.
261
+ def self.copy!(value, depth = 0, budget = [0, 0])
262
+ raise Invalid if depth > 20 || (budget[0] += 1) > 4096
263
+ raise Invalid unless Object.instance_method(:singleton_methods).bind_call(value, true).empty?
264
+ klass = Object.instance_method(:class).bind_call(value)
265
+ if klass == String
266
+ s = InputValidator.snapshot!(value)
267
+ raise Invalid if (budget[1] += s.bytesize) > 1_048_576
268
+ s
269
+ elsif klass == Hash
270
+ raise Invalid if value.size > 64
271
+ value.to_h do |k,v|
272
+ raise Invalid unless k.instance_of?(Symbol) || k.instance_of?(String)
273
+ [k.instance_of?(String) ? InputValidator.snapshot!(k, max_bytes: 256) : k, copy!(v, depth + 1, budget)]
274
+ end.freeze
275
+ elsif klass == Array
276
+ raise Invalid if value.size > 256
277
+ value.map { |v| copy!(v, depth + 1, budget) }.freeze
278
+ elsif [Integer, Symbol, NilClass, TrueClass, FalseClass].include?(klass)
279
+ value
280
+ else
281
+ raise Invalid
282
+ end
283
+ end
284
+ end
285
+ end
@@ -10,14 +10,19 @@ module AP2MandateVerifier
10
10
  def self.enabled?(profile)
11
11
  [PROFILE_REF, SELECTIVE_PROFILE_REF].include?(profile)
12
12
  end
13
+ def self.recurring?(profile) = defined?(RecurringPayment) && RecurringPayment.profile?(profile)
14
+ def self.long?(profile) = defined?(LongPayment) && LongPayment.profile?(profile)
15
+ def self.marked?(profile) = enabled?(profile) || recurring?(profile) || long?(profile)
13
16
  def self.profile!(value, selective: false)
14
17
  profile = InputValidator.snapshot!(value, max_bytes: 256)
15
18
  old, current = selective ? [SelectivePayment::PROFILE_REF, SELECTIVE_PROFILE_REF] : [Payment::PROFILE_REF, PROFILE_REF]
16
- raise Payment::Invalid unless [old, current].include?(profile)
19
+ recurring = defined?(RecurringPayment) && (selective ? RecurringPayment::SELECTIVE_PROFILE_REF : RecurringPayment::PROFILE_REF)
20
+ long = defined?(LongPayment) && !selective && LongPayment::PROFILE_REF
21
+ raise Payment::Invalid unless [old, current, recurring, long].compact.include?(profile)
17
22
  profile
18
23
  end
19
24
  def self.candidate_policy!(profile, policy)
20
- raise Payment::Invalid unless enabled?(profile) ? policy == :independent : policy.nil?
25
+ raise Payment::Invalid unless marked?(profile) ? policy == :independent : policy.nil?
21
26
  end
22
27
  def self.fields(profile) = Payment::FIELDS + (enabled?(profile) ? FIELDS : [])
23
28
  def self.pisp!(value)