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,272 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ module PaymentAcceptance
5
+ # Protected Host authority and period state share the occurrence transaction.
6
+ # An external registry feed must synchronize into this ledger before use.
7
+ class LongSQLiteStore < RecurringSQLiteStore
8
+ SCHEMA_VERSION = 3
9
+ MAX_CONTRACT = 524_288
10
+ SCHEDULE_POLICY = "host.utc_calendar_month_windows.1".freeze
11
+ SCHEMA = RecurringSQLiteStore::SCHEMA.merge(
12
+ "ap2_long_state" => "CREATE TABLE ap2_long_state (series_key TEXT PRIMARY KEY REFERENCES ap2_series(series_key), root_reference TEXT NOT NULL, epoch INTEGER NOT NULL CHECK(epoch>0), authority TEXT NOT NULL, authority_active INTEGER NOT NULL CHECK(authority_active IN (0,1)))",
13
+ "ap2_long_roots" => "CREATE TABLE ap2_long_roots (tenant TEXT NOT NULL, root_reference TEXT NOT NULL, series_key TEXT NOT NULL REFERENCES ap2_series(series_key), contract TEXT NOT NULL, active INTEGER NOT NULL CHECK(active IN (0,1)), PRIMARY KEY(tenant,root_reference))",
14
+ "ap2_long_periods" => "CREATE TABLE ap2_long_periods (series_key TEXT NOT NULL REFERENCES ap2_series(series_key), period_id TEXT NOT NULL, not_before INTEGER NOT NULL, not_after INTEGER NOT NULL, PRIMARY KEY(series_key,period_id))"
15
+ ).transform_values(&:freeze).freeze
16
+ INDEXES = (RecurringSQLiteStore::INDEXES + [
17
+ ["sqlite_autoindex_ap2_long_state_1", "ap2_long_state"],
18
+ ["sqlite_autoindex_ap2_long_roots_1", "ap2_long_roots"],
19
+ ["sqlite_autoindex_ap2_long_periods_1", "ap2_long_periods"]
20
+ ]).map(&:freeze).freeze
21
+
22
+ def authorize_series!(tenant_id:, merchant_id:, approval_id:, payment_open:, checkout_open:,
23
+ trust_json:, selection_json:, verified_at:, periods:, schedule_policy_id:)
24
+ ids = series_ids!(tenant_id, merchant_id, approval_id)
25
+ pair = approved_pair!(ids, payment_open, checkout_open, trust_json, selection_json, verified_at)
26
+ windows = periods!(periods, pair, schedule_policy_id)
27
+ contract = pair_contract(pair).merge("schedule_policy_id" => schedule_policy_id, "periods" => windows,
28
+ "agreement_not_before" => pair.fetch(:not_before), "agreement_not_after" => pair.fetch(:not_after))
29
+ encoded = encode_contract!(contract)
30
+ transaction do
31
+ key = series_key(ids)
32
+ old = @db.get_first_value("SELECT CASE WHEN length(CAST(contract AS BLOB))<=#{MAX_CONTRACT} THEN contract END FROM ap2_series WHERE series_key=?", [key])
33
+ if old
34
+ raise Conflict unless old == encoded
35
+ next true # Never reactivate, reset, or rotate via enrollment.
36
+ end
37
+ begin
38
+ @db.execute("INSERT INTO ap2_series(series_key,tenant,merchant,approval,root_reference,contract) VALUES (?,?,?,?,?,?)",
39
+ [key, *ids, pair.fetch(:reference), encoded])
40
+ insert_root!(ids, key, pair)
41
+ @db.execute("INSERT INTO ap2_long_state(series_key,root_reference,epoch,authority,authority_active) VALUES (?,?,1,?,1)",
42
+ [key, pair.fetch(:reference), PaymentAcceptance.canonical(pair.fetch(:authority_binding))])
43
+ windows.each do |window|
44
+ @db.execute("INSERT INTO ap2_long_periods(series_key,period_id,not_before,not_after) VALUES (?,?,?,?)",
45
+ [key, *window.values_at("id", "not_before", "not_after")])
46
+ end
47
+ rescue SQLite3::ConstraintException
48
+ raise Conflict
49
+ end
50
+ true
51
+ end
52
+ end
53
+
54
+ # Protected backend CAS, not a request-driven 'current' flag.
55
+ def update_authority!(tenant_id:, merchant_id:, approval_id:, expected_epoch:, trust_json:, selection_json:, verified_at:)
56
+ expected_epoch!(expected_epoch)
57
+ ids = series_ids!(tenant_id, merchant_id, approval_id)
58
+ context = LongPayment.current_authority!(trust_json: trust_json, selection_json: selection_json,
59
+ merchant_id: merchant_id, verified_at: verified_at)
60
+ raise Invalid unless context.fetch(:tenant_id) == tenant_id
61
+ transaction do
62
+ agreement, active = series_row!(ids)
63
+ state, root = current_root!(ids, expected_epoch)
64
+ raise Invalid unless active == 1 && root.fetch("active") == 1 && verified_at < agreement.fetch("agreement_not_after")
65
+ raise Conflict unless root.fetch("root_key_fingerprints") == context.fetch(:root_key_fingerprints) &&
66
+ agreement.fetch("authority_principals") == context.fetch(:authority_principals)
67
+ authority = PaymentAcceptance.canonical(context.fetch(:authority_binding))
68
+ next state.fetch("epoch") if state.fetch("authority_active") == 1 && state.fetch("authority") == authority
69
+ @db.execute("UPDATE ap2_long_state SET authority=?,authority_active=1,epoch=epoch+1 WHERE series_key=? AND epoch=?",
70
+ [authority, series_key(ids), expected_epoch])
71
+ raise Conflict unless @db.changes == 1
72
+ expected_epoch + 1
73
+ end
74
+ end
75
+
76
+ def invalidate_authority!(tenant_id:, merchant_id:, approval_id:, expected_epoch:)
77
+ expected_epoch!(expected_epoch)
78
+ ids = series_ids!(tenant_id, merchant_id, approval_id)
79
+ transaction do
80
+ current_root!(ids, expected_epoch)
81
+ @db.execute("UPDATE ap2_long_state SET authority_active=0,epoch=epoch+1 WHERE series_key=? AND epoch=?", [series_key(ids), expected_epoch])
82
+ raise Conflict unless @db.changes == 1
83
+ expected_epoch + 1
84
+ end
85
+ end
86
+
87
+ def replace_root!(tenant_id:, merchant_id:, approval_id:, expected_epoch:, expected_root_reference:,
88
+ payment_open:, checkout_open:, trust_json:, selection_json:, verified_at:)
89
+ expected_epoch!(expected_epoch)
90
+ ids = series_ids!(tenant_id, merchant_id, approval_id)
91
+ pair = approved_pair!(ids, payment_open, checkout_open, trust_json, selection_json, verified_at)
92
+ transaction do
93
+ agreement, active = series_row!(ids)
94
+ state, = current_root!(ids, expected_epoch)
95
+ raise Invalid unless active == 1
96
+ raise Conflict unless state.fetch("root_reference") == expected_root_reference &&
97
+ agreement.fetch("economic_contract") == pair.fetch(:economic_contract) &&
98
+ agreement.fetch("authority_principals") == pair.fetch(:authority_principals) &&
99
+ pair.fetch(:not_after) <= agreement.fetch("agreement_not_after") &&
100
+ verified_at < agreement.fetch("agreement_not_after")
101
+ # Alias tombstones are never deleted/reused, even after key revocation.
102
+ insert_root!(ids, series_key(ids), pair)
103
+ @db.execute("UPDATE ap2_long_roots SET active=0 WHERE tenant=? AND root_reference=?", [ids[0], expected_root_reference])
104
+ @db.execute("UPDATE ap2_long_state SET root_reference=?,epoch=epoch+1,authority=?,authority_active=1 WHERE series_key=? AND epoch=?",
105
+ [pair.fetch(:reference), PaymentAcceptance.canonical(pair.fetch(:authority_binding)), series_key(ids), expected_epoch])
106
+ raise Conflict unless @db.changes == 1
107
+ expected_epoch + 1
108
+ end
109
+ end
110
+
111
+ def revoke_root!(tenant_id:, merchant_id:, approval_id:, expected_epoch:)
112
+ expected_epoch!(expected_epoch)
113
+ ids = series_ids!(tenant_id, merchant_id, approval_id)
114
+ transaction do
115
+ state, = current_root!(ids, expected_epoch)
116
+ @db.execute("UPDATE ap2_long_roots SET active=0 WHERE tenant=? AND root_reference=?", [ids[0], state.fetch("root_reference")])
117
+ @db.execute("UPDATE ap2_long_state SET authority_active=0,epoch=epoch+1 WHERE series_key=? AND epoch=?", [series_key(ids), expected_epoch])
118
+ raise Conflict unless @db.changes == 1
119
+ expected_epoch + 1
120
+ end
121
+ end
122
+
123
+ def usage(tenant_id:, merchant_id:, approval_id:)
124
+ ids = series_ids!(tenant_id, merchant_id, approval_id)
125
+ transaction do
126
+ contract, active, uses, spent = series_row!(ids)
127
+ state, root = current_root!(ids)
128
+ {currency: "JPY", reserved_occurrences: uses, reserved_amount: spent,
129
+ max_occurrences: contract.fetch("max_occurrences"), budget_max: contract.fetch("budget_max"), active: active == 1,
130
+ epoch: state.fetch("epoch"), root_reference: state.fetch("root_reference").dup.freeze,
131
+ authority_active: state.fetch("authority_active") == 1 && root.fetch("active") == 1}.freeze
132
+ end
133
+ end
134
+
135
+ def start_long!(ticket:, verified_at:, instruction:, signed_wires:, authority_binding:, valid_until:)
136
+ CheckoutReceipt.send(:epoch!, valid_until)
137
+ start_record!(ticket: ticket, verified_at: verified_at, instruction: instruction, signed_wires: signed_wires,
138
+ authority: PaymentAcceptance.copy!(authority_binding), fresh_valid_until: valid_until)
139
+ end
140
+
141
+ private
142
+ def expected_epoch!(value)
143
+ raise Invalid unless value.instance_of?(Integer) && value.between?(1, 9_007_199_254_740_000)
144
+ end
145
+ def approved_pair!(ids, payment, checkout, trust, selection, now)
146
+ pair = LongPayment.approved_pair!(payment_open: payment, checkout_open: checkout,
147
+ trust_json: trust, selection_json: selection, merchant_id: ids[1], verified_at: now)
148
+ raise Invalid unless pair.fetch(:tenant_id) == ids[0]
149
+ pair
150
+ end
151
+ def pair_contract(pair)
152
+ {"profile_ref" => LongPayment::PROFILE_REF, "root_reference" => pair.fetch(:reference),
153
+ "economic_contract" => pair.fetch(:economic_contract), "opening" => pair.fetch(:opening),
154
+ "max_occurrences" => pair.fetch(:max_occurrences), "budget_max" => pair.fetch(:budget_max), "currency" => pair.fetch(:currency),
155
+ "authority_principals" => pair.fetch(:authority_principals),
156
+ "root_key_fingerprints" => pair.fetch(:root_key_fingerprints), "not_before" => pair.fetch(:not_before), "not_after" => pair.fetch(:not_after)}
157
+ end
158
+ def encode_contract!(contract)
159
+ value = PaymentAcceptance.canonical(contract)
160
+ raise Invalid if value.bytesize > MAX_CONTRACT
161
+ value
162
+ end
163
+ def periods!(source, pair, policy)
164
+ raise Invalid unless policy == SCHEDULE_POLICY
165
+ list = PaymentAcceptance.copy!(source)
166
+ raise Invalid unless list.instance_of?(Array) && list.size.between?(1, 24)
167
+ months = []
168
+ list = list.map do |value|
169
+ raise Invalid unless value.instance_of?(Hash) && value.size == 3
170
+ item = value.transform_keys { |key| key.instance_of?(Symbol) ? key.to_s : key }
171
+ raise Invalid unless item.keys.sort == %w[id not_after not_before]
172
+ CheckoutReceipt.send(:text!, item["id"], 256)
173
+ %w[not_before not_after].each { |field| CheckoutReceipt.send(:epoch!, item[field]) }
174
+ raise Invalid unless pair.fetch(:not_before) <= item["not_before"] && item["not_before"] < item["not_after"] && item["not_after"] <= pair.fetch(:not_after)
175
+ start = Time.at(item.fetch("not_before")).utc
176
+ finish = start.month == 12 ? Time.utc(start.year + 1, 1, 1).to_i : Time.utc(start.year, start.month + 1, 1).to_i
177
+ raise Invalid unless item.fetch("not_after") <= finish
178
+ months << [start.year, start.month]
179
+ item
180
+ end.sort_by { |value| value.fetch("not_before") }
181
+ raise Invalid unless months.uniq.size == months.size && list.map { |value| value.fetch("id") }.uniq.size == list.size &&
182
+ list.each_cons(2).all? { |left,right| left.fetch("not_after") <= right.fetch("not_before") }
183
+ list
184
+ end
185
+ def insert_root!(ids, key, pair)
186
+ @db.execute("INSERT INTO ap2_long_roots(tenant,root_reference,series_key,contract,active) VALUES (?,?,?,?,1)",
187
+ [ids[0], pair.fetch(:reference), key, encode_contract!(pair_contract(pair))])
188
+ rescue SQLite3::ConstraintException
189
+ raise Conflict
190
+ end
191
+ def series_row!(ids)
192
+ row = @db.get_first_row("SELECT CASE WHEN length(CAST(contract AS BLOB))<=#{MAX_CONTRACT} THEN contract END,active,uses,spent FROM ap2_series WHERE series_key=?", [series_key(ids)])
193
+ raise Invalid unless row
194
+ contract = decode!(row[0], MAX_CONTRACT)
195
+ raise Unavailable unless [row[2],row[3]].all? { |n| n.instance_of?(Integer) && n >= 0 } &&
196
+ row[2] <= contract.fetch("max_occurrences") && row[3] <= contract.fetch("budget_max")
197
+ [contract, *row.drop(1)]
198
+ end
199
+ def current_root!(ids, expected = nil)
200
+ row = @db.get_first_row("SELECT root_reference,epoch,CASE WHEN length(CAST(authority AS BLOB))<=32768 THEN authority END,authority_active FROM ap2_long_state WHERE series_key=?", [series_key(ids)])
201
+ raise Invalid unless row
202
+ raise Unavailable unless row[1].instance_of?(Integer) && row[1].between?(1, 9_007_199_254_740_000) && [0,1].include?(row[3])
203
+ raise Conflict if !expected.nil? && (!expected.instance_of?(Integer) || row[1] != expected)
204
+ state = {"root_reference" => row[0], "epoch" => row[1], "authority" => InputValidator.snapshot!(row[2], max_bytes: 32768), "authority_active" => row[3]}
205
+ root = @db.get_first_row("SELECT CASE WHEN length(CAST(contract AS BLOB))<=#{MAX_CONTRACT} THEN contract END,active FROM ap2_long_roots WHERE tenant=? AND root_reference=? AND series_key=?",
206
+ [ids[0], row[0], series_key(ids)])
207
+ raise Unavailable unless root && [0,1].include?(root[1])
208
+ [state, decode!(root[0], MAX_CONTRACT).merge("active" => root[1])]
209
+ end
210
+ def approval_policy!(profile)
211
+ raise Invalid unless LongPayment.profile?(profile)
212
+ end
213
+ def period!(ids, at, occurrence)
214
+ CheckoutReceipt.send(:epoch!, at)
215
+ rows = @db.execute("SELECT period_id,not_before,not_after FROM ap2_long_periods WHERE series_key=? AND not_before<=? AND ?<not_after", [series_key(ids), at, at])
216
+ raise Invalid unless rows.size == 1 && rows[0][0] == occurrence
217
+ rows[0]
218
+ end
219
+ def validate_reservation!(scope, record)
220
+ approval_policy!(record.fetch("profile_ref"))
221
+ ids = scope_series(scope)
222
+ agreement, active = series_row!(ids)
223
+ state, root = current_root!(ids)
224
+ raise Invalid unless active == 1 && root.fetch("active") == 1 && state.fetch("authority_active") == 1 &&
225
+ PaymentAcceptance.canonical(record.fetch("authority_binding")) == state.fetch("authority")
226
+ wire = record.fetch("signed_wires").fetch("payment").fetch("open_sd_jwt")
227
+ raise Conflict unless Payment.send(:digest, wire.split("~",2).first) == state.fetch("root_reference")
228
+ period = period!(ids, record.fetch("accepted_at"), scope.fetch("occurrence_id"))
229
+ amount = record.fetch("payment").fetch("payment_amount")
230
+ raise Invalid unless amount.fetch("currency") == "JPY" && amount.fetch("amount").instance_of?(Integer) && amount.fetch("amount") > 0
231
+ record["accepted_epoch"] = state.fetch("epoch")
232
+ record["valid_until"] = [record.fetch("valid_until"), period[2], agreement.fetch("agreement_not_after"), root.fetch("not_after")].min
233
+ end
234
+ def validate_start!(record, at)
235
+ ids = scope_series(record.fetch("scope"))
236
+ agreement, active = series_row!(ids)
237
+ state, root = current_root!(ids)
238
+ raise Invalid unless active == 1 && root.fetch("active") == 1 && state.fetch("authority_active") == 1 &&
239
+ state.fetch("epoch") == record.fetch("accepted_epoch") && at < agreement.fetch("agreement_not_after") && at < root.fetch("not_after")
240
+ period!(ids, at, record.fetch("scope").fetch("occurrence_id"))
241
+ end
242
+ def validate_current_authority!(record, _at, authority)
243
+ state, = current_root!(scope_series(record.fetch("scope")))
244
+ raise Invalid unless authority && PaymentAcceptance.canonical(authority) == state.fetch("authority") &&
245
+ PaymentAcceptance.canonical(record.fetch("authority_binding")) == state.fetch("authority")
246
+ end
247
+
248
+ %i[authorize_series! update_authority! invalidate_authority! replace_root! revoke_root! usage start_long!].each do |name|
249
+ implementation = instance_method(name)
250
+ required = implementation.parameters.map(&:last).freeze
251
+ define_method(name) do |**arguments|
252
+ if name == :start_long!
253
+ ticket = arguments.fetch(:ticket)
254
+ raise Invalid unless ticket.instance_of?(Ticket)
255
+ arguments = PaymentAcceptance.copy!(arguments.reject { |key,_| key == :ticket }).merge(ticket: ticket)
256
+ else
257
+ arguments = PaymentAcceptance.copy!(arguments)
258
+ end
259
+ raise Invalid unless arguments.keys.sort == required.sort
260
+ implementation.bind_call(self, **arguments)
261
+ rescue Conflict
262
+ raise Conflict.new("payment acceptance conflict"), cause: nil
263
+ rescue Unavailable
264
+ raise Unavailable.new, cause: nil
265
+ rescue StandardError, LoadError
266
+ raise Invalid.new, cause: nil
267
+ end
268
+ public name
269
+ end
270
+ end
271
+ end
272
+ end
@@ -0,0 +1,124 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ module PaymentAcceptance
5
+ # Explicit new database, never an automatic rewrite/reset of a v1.5 ledger.
6
+ # Quotas are charged on durable reservation, not on an untrusted Receipt.
7
+ class RecurringSQLiteStore < SQLiteStore
8
+ SCHEMA_VERSION = 2
9
+ SCHEMA = SQLiteStore::SCHEMA.merge(
10
+ "ap2_series" => "CREATE TABLE ap2_series (series_key TEXT PRIMARY KEY, tenant TEXT NOT NULL, merchant TEXT NOT NULL, approval TEXT NOT NULL, root_reference TEXT NOT NULL, contract TEXT NOT NULL, active INTEGER NOT NULL DEFAULT 1 CHECK(active IN (0,1)), uses INTEGER NOT NULL DEFAULT 0 CHECK(uses>=0), spent INTEGER NOT NULL DEFAULT 0 CHECK(spent>=0), UNIQUE(tenant,root_reference), UNIQUE(tenant,approval))"
11
+ ).freeze
12
+ INDEXES = (SQLiteStore::INDEXES + [
13
+ ["sqlite_autoindex_ap2_series_1", "ap2_series"],
14
+ ["sqlite_autoindex_ap2_series_2", "ap2_series"],
15
+ ["sqlite_autoindex_ap2_series_3", "ap2_series"]
16
+ ]).map(&:freeze).freeze
17
+
18
+ def authorize_series!(tenant_id:, merchant_id:, approval_id:, open_sd_jwt:, profile_ref:,
19
+ trusted_provider_public_key_pem:, expected_agent_public_key_pem:, verified_at:)
20
+ ids = series_ids!(tenant_id, merchant_id, approval_id)
21
+ checked = RecurringPayment.approved_open!(open_sd_jwt: open_sd_jwt, profile_ref: profile_ref,
22
+ trusted_provider_public_key_pem: trusted_provider_public_key_pem,
23
+ expected_agent_public_key_pem: expected_agent_public_key_pem, verified_at: verified_at)
24
+ contract = PaymentAcceptance.canonical({"profile_ref" => profile_ref, "root_reference" => checked.fetch(:reference),
25
+ "opening" => checked.fetch(:opening), "max_occurrences" => checked.fetch(:max_occurrences),
26
+ "budget_max" => checked.fetch(:budget_max), "currency" => checked.fetch(:currency)})
27
+ raise Invalid if contract.bytesize > 131_072
28
+ transaction do
29
+ key = series_key(ids)
30
+ old = @db.get_first_row("SELECT CASE WHEN length(CAST(contract AS BLOB))<=131072 THEN contract END FROM ap2_series WHERE series_key=?", [key])
31
+ raise Conflict if old && old[0] != contract
32
+ unless old
33
+ begin
34
+ @db.execute("INSERT INTO ap2_series(series_key,tenant,merchant,approval,root_reference,contract) VALUES (?,?,?,?,?,?)",
35
+ [key, *ids, checked.fetch(:reference), contract])
36
+ rescue SQLite3::ConstraintException
37
+ raise Conflict
38
+ end
39
+ end
40
+ true # Existing revoked grants are never reactivated or counters reset.
41
+ end
42
+ end
43
+
44
+ def revoke_series!(tenant_id:, merchant_id:, approval_id:)
45
+ ids = series_ids!(tenant_id, merchant_id, approval_id)
46
+ transaction do
47
+ @db.execute("UPDATE ap2_series SET active=0 WHERE series_key=?", [series_key(ids)])
48
+ raise Invalid unless @db.changes == 1
49
+ true
50
+ end
51
+ end
52
+
53
+ def usage(tenant_id:, merchant_id:, approval_id:)
54
+ ids = series_ids!(tenant_id, merchant_id, approval_id)
55
+ transaction do
56
+ contract, active, uses, spent = series_row!(ids)
57
+ {currency: "JPY", reserved_occurrences: uses, reserved_amount: spent,
58
+ max_occurrences: contract.fetch("max_occurrences"), budget_max: contract.fetch("budget_max"), active: active == 1}.freeze
59
+ end
60
+ end
61
+
62
+ private
63
+ def series_ids!(tenant, merchant, approval)
64
+ [tenant, merchant, approval].map { |v| InputValidator.snapshot!(v, max_bytes: 256).tap { |s| CheckoutReceipt.send(:text!, s, 256) } }.freeze
65
+ end
66
+ def series_key(ids) = PaymentAcceptance.digest(PaymentAcceptance.canonical(ids))
67
+ def scope_series(scope) = series_ids!(*scope.values_at("tenant_id", "merchant_id", "approval_id"))
68
+ def series_row!(ids)
69
+ row = @db.get_first_row("SELECT CASE WHEN length(CAST(contract AS BLOB))<=131072 THEN contract END,active,uses,spent FROM ap2_series WHERE series_key=?", [series_key(ids)])
70
+ raise Invalid unless row
71
+ contract = decode!(row[0], 131_072)
72
+ raise Unavailable unless [row[2], row[3]].all? { |v| v.instance_of?(Integer) && v >= 0 } &&
73
+ row[2] <= contract.fetch("max_occurrences") && row[3] <= contract.fetch("budget_max")
74
+ [contract, *row.drop(1)]
75
+ end
76
+ def approval_policy!(profile)
77
+ raise Invalid unless RecurringPayment.profile?(profile)
78
+ end
79
+ def validate_reservation!(scope, record)
80
+ approval_policy!(record.fetch("profile_ref"))
81
+ contract, active = series_row!(scope_series(scope))
82
+ raise Invalid unless active == 1 && contract.fetch("profile_ref") == record.fetch("profile_ref")
83
+ wires = record.fetch("signed_wires").fetch("payment")
84
+ open_wire = wires["open_sd_jwt"] || wires["open_presentation"]
85
+ raise Invalid unless open_wire.instance_of?(String) # Bounded wire was verified by Service.
86
+ # Local series identity uses base64url(SHA256(original issuer JWT)).
87
+ # AP2 Checkout/Receipt references retain their existing exact-wire semantics.
88
+ root_reference = Payment.send(:digest, open_wire.split("~", 2).first)
89
+ raise Conflict unless root_reference == contract.fetch("root_reference")
90
+ amount = record.fetch("payment").fetch("payment_amount")
91
+ raise Invalid unless amount.fetch("currency") == "JPY" && amount.fetch("amount").instance_of?(Integer) && amount.fetch("amount") > 0
92
+ end
93
+ def charge_reservation!(scope, record)
94
+ ids = scope_series(scope)
95
+ contract, active, uses, spent = series_row!(ids)
96
+ amount = record.fetch("payment").fetch("payment_amount").fetch("amount")
97
+ raise Invalid unless active == 1 && uses < contract.fetch("max_occurrences") && spent + amount <= contract.fetch("budget_max")
98
+ @db.execute("UPDATE ap2_series SET uses=uses+1,spent=spent+? WHERE series_key=? AND active=1 AND uses=? AND spent=?",
99
+ [amount, series_key(ids), uses, spent])
100
+ raise Unavailable unless @db.changes == 1
101
+ end
102
+ def validate_start!(record, verified_at)
103
+ contract, active = series_row!(scope_series(record.fetch("scope")))
104
+ raise Invalid unless active == 1 && verified_at < contract.fetch("opening").fetch("exp")
105
+ end
106
+
107
+ %i[authorize_series! revoke_series! usage].each do |name|
108
+ implementation = instance_method(name)
109
+ required = implementation.parameters.map(&:last).freeze
110
+ define_method(name) do |**arguments|
111
+ raise Invalid unless arguments.keys.sort == required.sort
112
+ implementation.bind_call(self, **arguments)
113
+ rescue Conflict
114
+ raise Conflict.new("payment acceptance conflict"), cause: nil
115
+ rescue Unavailable
116
+ raise Unavailable.new, cause: nil
117
+ rescue StandardError, LoadError
118
+ raise Invalid.new, cause: nil
119
+ end
120
+ public name
121
+ end
122
+ end
123
+ end
124
+ end