ap2_mandate_verifier 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. checksums.yaml +4 -4
  2. data/README.ja.md +19 -8
  3. data/README.md +19 -8
  4. data/SECURITY.md +7 -3
  5. data/docs/LONG_PAYMENT.md +82 -0
  6. data/docs/PAYMENT_ACCEPTANCE.md +3 -1
  7. data/docs/PUBLIC_API.md +10 -2
  8. data/docs/RECURRING_PAYMENT.md +54 -0
  9. data/docs/RELEASE_150_CANDIDATE.md +2 -0
  10. data/docs/RELEASE_160_CANDIDATE.md +30 -0
  11. data/docs/SUPPORT_CONTRACT.md +6 -2
  12. data/examples/conditional_checkout.rb +3 -3
  13. data/examples/long_payment.rb +116 -0
  14. data/examples/long_payment_acceptance.rb +89 -0
  15. data/examples/recurring_payment.rb +99 -0
  16. data/lib/ap2_mandate_verifier/checkout_jwt.rb +1 -1
  17. data/lib/ap2_mandate_verifier/checkout_receipt.rb +10 -1
  18. data/lib/ap2_mandate_verifier/conditional_checkout.rb +43 -19
  19. data/lib/ap2_mandate_verifier/input_builder.rb +1 -1
  20. data/lib/ap2_mandate_verifier/long_payment.rb +201 -0
  21. data/lib/ap2_mandate_verifier/payment.rb +52 -12
  22. data/lib/ap2_mandate_verifier/payment_acceptance/long_sqlite_store.rb +272 -0
  23. data/lib/ap2_mandate_verifier/payment_acceptance/recurring_sqlite_store.rb +124 -0
  24. data/lib/ap2_mandate_verifier/payment_acceptance/sqlite_store.rb +38 -10
  25. data/lib/ap2_mandate_verifier/payment_acceptance.rb +28 -6
  26. data/lib/ap2_mandate_verifier/payment_policy.rb +7 -2
  27. data/lib/ap2_mandate_verifier/purchase_binding.rb +11 -5
  28. data/lib/ap2_mandate_verifier/recurring_payment.rb +111 -0
  29. data/lib/ap2_mandate_verifier/root_disclosures.rb +9 -6
  30. data/lib/ap2_mandate_verifier/scoped_constraints.rb +1 -1
  31. data/lib/ap2_mandate_verifier/selective_payment.rb +1 -1
  32. data/lib/ap2_mandate_verifier/trust_context.rb +6 -0
  33. data/lib/ap2_mandate_verifier.rb +4 -0
  34. metadata +16 -5
@@ -5,6 +5,7 @@ module AP2MandateVerifier
5
5
  # Optional local durable reference. Production adapters must preserve the
6
6
  # same protected-authorization + claim transaction and CAS guarantees.
7
7
  class SQLiteStore
8
+ SCHEMA_VERSION = 1
8
9
  DRIVER_VERSION = "2.10.2".freeze
9
10
  RECEIPT_FIELDS = %w[trusted_public_key_pem expected_issuer expected_payment_id not_before not_after].freeze
10
11
  SCHEMA = {
@@ -12,6 +13,12 @@ module AP2MandateVerifier
12
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))",
13
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))"
14
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
15
22
  def self.create(**arguments)
16
23
  raise Unavailable unless arguments.keys == [:path]
17
24
  path = arguments.fetch(:path)
@@ -48,12 +55,9 @@ module AP2MandateVerifier
48
55
  @db = SQLite3::Database.new(@path, flags: SQLite3::Constants::Open::READWRITE)
49
56
  @db.busy_timeout = 5000
50
57
  unless creating
51
- raise Unavailable unless @db.get_first_value("PRAGMA user_version") == 1 && @db.execute("PRAGMA quick_check") == [["ok"]]
52
- expected = SCHEMA.map { |name,sql| ["table", name, name, sql] } +
53
- [["index", "sqlite_autoindex_ap2_approvals_1", "ap2_approvals", nil],
54
- ["index", "sqlite_autoindex_ap2_approvals_2", "ap2_approvals", nil],
55
- ["index", "sqlite_autoindex_ap2_attempts_1", "ap2_attempts", nil],
56
- ["index", "sqlite_autoindex_ap2_attempts_2", "ap2_attempts", nil]]
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] }
57
61
  actual = @db.execute("SELECT type,name,tbl_name,sql FROM sqlite_master ORDER BY type,name")
58
62
  raise Unavailable unless actual == expected.sort_by { |row| row.first(2) }
59
63
  identities = @db.execute("SELECT identity FROM ap2_store")
@@ -70,11 +74,9 @@ module AP2MandateVerifier
70
74
  require "securerandom"
71
75
  @store_id = SecureRandom.hex(32)
72
76
  @db.execute("BEGIN IMMEDIATE")
73
- @db.execute(SCHEMA.fetch("ap2_store"))
77
+ self.class::SCHEMA.each_value { |sql| @db.execute(sql) }
74
78
  @db.execute("INSERT INTO ap2_store(identity) VALUES (?)", [@store_id])
75
- @db.execute(SCHEMA.fetch("ap2_approvals"))
76
- @db.execute(SCHEMA.fetch("ap2_attempts"))
77
- @db.execute("PRAGMA user_version=1")
79
+ @db.execute("PRAGMA user_version=#{self.class::SCHEMA_VERSION}")
78
80
  @db.execute("COMMIT")
79
81
  end
80
82
  @mutex = Mutex.new
@@ -91,6 +93,7 @@ module AP2MandateVerifier
91
93
  scope = PaymentAcceptance.scope!({"tenant_id" => tenant_id, "merchant_id" => merchant_id,
92
94
  "operation_id" => operation_id, "approval_id" => approval_id, "occurrence_id" => occurrence_id, "order_id" => order_id})
93
95
  profile = PaymentAcceptance.profile!(mode, profile_ref)
96
+ approval_policy!(profile)
94
97
  cart = InputBuilder.send(:copy!, checkout)
95
98
  raise Invalid unless cart["id"] == scope["order_id"] && cart.dig("merchant", "id") == scope["merchant_id"]
96
99
  instruction = PaymentAcceptance.instruction!(mode, profile, cart, payment)
@@ -128,6 +131,7 @@ module AP2MandateVerifier
128
131
  check_grant!(grant)
129
132
  raise Invalid unless grant[3] == 1
130
133
  raise Conflict unless grant[0] == PaymentAcceptance.canonical(scope) && grant[1] == instruction
134
+ validate_reservation!(scope, record)
131
135
  old = load_record(key)
132
136
  if old
133
137
  raise Conflict unless old["instruction"] == instruction
@@ -136,6 +140,7 @@ module AP2MandateVerifier
136
140
  reused = @db.get_first_value("SELECT operation_key FROM ap2_attempts WHERE tenant=? AND merchant=? AND closed_reference=?",
137
141
  [scope.fetch("tenant_id"), scope.fetch("merchant_id"), record.fetch("reference")])
138
142
  raise Conflict if reused
143
+ charge_reservation!(scope, record)
139
144
  require "securerandom"
140
145
  fence = SecureRandom.hex(32)
141
146
  value = record.merge("state" => "reserved", "processor_key" => SecureRandom.hex(32),
@@ -154,6 +159,10 @@ module AP2MandateVerifier
154
159
  end
155
160
 
156
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)
157
166
  key, fence = ticket_parts!(ticket)
158
167
  transaction do
159
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])
@@ -164,7 +173,13 @@ module AP2MandateVerifier
164
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])
165
174
  raise Invalid unless grant && grant[0] == 1 && grant[1] == instruction &&
166
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
167
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)
168
183
  record["state"] = "processing"
169
184
  record["started_at"] = verified_at
170
185
  @db.execute("UPDATE ap2_attempts SET state='processing',record=? WHERE operation_key=? AND fence=? AND state='reserved'", [JSON.generate(record), key, fence])
@@ -173,6 +188,8 @@ module AP2MandateVerifier
173
188
  end
174
189
  end
175
190
 
191
+ private :start_record!
192
+
176
193
  def ticket_record!(ticket:)
177
194
  key, fence = ticket_parts!(ticket)
178
195
  transaction do
@@ -240,6 +257,17 @@ module AP2MandateVerifier
240
257
  end
241
258
 
242
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
243
271
  def ticket_parts!(ticket)
244
272
  raise Invalid unless ticket.instance_of?(Ticket)
245
273
  key = ticket.send(:key)
@@ -37,10 +37,11 @@ module AP2MandateVerifier
37
37
  private_class_method :new
38
38
  end
39
39
  class Execution
40
- attr_reader :processor_key, :closed_sd_jwt, :reference, :payment
40
+ attr_reader :processor_key, :closed_sd_jwt, :reference, :payment, :valid_until
41
41
  def initialize(record)
42
42
  @processor_key, @closed_sd_jwt, @reference = record.values_at("processor_key", "closed_sd_jwt", "reference").map(&:freeze)
43
43
  @payment = ResearchEvidence.send(:copy_frozen, record.fetch("payment"))
44
+ @valid_until = record.fetch("valid_until")
44
45
  freeze
45
46
  end
46
47
  def inspect = "#<AP2MandateVerifier::PaymentAcceptance::Execution>"
@@ -71,9 +72,20 @@ module AP2MandateVerifier
71
72
  old = @store.ticket_record!(ticket: ticket)
72
73
  fresh = verified_record(old.fetch("mode").to_sym, verification_inputs, old.fetch("scope"))
73
74
  raise Invalid unless old.fetch("instruction") == fresh.fetch("instruction") && old.fetch("signed_wires") == fresh.fetch("signed_wires")
74
- record = @store.start!(ticket: ticket, verified_at: fresh.fetch("accepted_at"),
75
- instruction: fresh.fetch("instruction"), signed_wires: fresh.fetch("signed_wires"))
76
- Execution.send(:new, record) if record
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
77
89
  rescue StandardError, LoadError
78
90
  nil # An uncertain commit NEVER produces an execution handle.
79
91
  end
@@ -86,7 +98,7 @@ module AP2MandateVerifier
86
98
  result = case mode
87
99
  when :direct, :conditional
88
100
  raise Invalid unless args[:checkout_mode] == mode
89
- Payment.verify(**args)
101
+ LongPayment.profile?(profile) ? LongPayment.verify(**args) : Payment.verify(**args)
90
102
  when :selective then SelectivePayment.verify(**args)
91
103
  else raise Invalid
92
104
  end
@@ -113,11 +125,21 @@ module AP2MandateVerifier
113
125
  else
114
126
  checkout_args.slice(:root_presentation, :terminal_jws, :host_checkout_jws)
115
127
  end
116
- {"scope" => scope, "mode" => mode.to_s, "profile_ref" => profile, "instruction" => instruction,
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,
117
137
  "payment" => result.payment, "closed_sd_jwt" => closed, "reference" => result.reference,
118
138
  "signed_wires" => {"payment" => args.slice(:open_sd_jwt, :open_presentation, :closed_sd_jwt).transform_keys(&:to_s),
119
139
  "checkout" => checkout_wires.transform_keys(&:to_s)},
120
140
  "accepted_at" => args.fetch(:verified_at), "valid_until" => valid_until}
141
+ record["authority_binding"] = authority.fetch(:authority_binding) if authority
142
+ record
121
143
  end
122
144
  public
123
145
 
@@ -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)
@@ -48,13 +48,18 @@ module AP2MandateVerifier
48
48
  open = root.fetch("delegate_payload").first
49
49
  exact!(open, %w[cnf constraints exp iat vct])
50
50
  raise Rejected, :unsupported_purchase_profile unless open["vct"] == "mandate.checkout.open.1"
51
- times!(open, verified_at)
51
+ times!(open, verified_at, profile_ref: profile_ref)
52
52
  exact!(open["cnf"], %w[jwk])
53
53
  exact!(open["cnf"]["jwk"], %w[kty crv x y])
54
54
  raise Rejected, :agent_key_mismatch unless open["cnf"]["jwk"] == RootSignature.public_jwk!(agent_pem)
55
55
 
56
56
  terminal = RootSignature.verified_payload!(terminal_wire, agent_pem, expected_typ: "kb+sd-jwt")
57
- exact!(terminal, %w[aud delegate_payload iat nonce sd_hash])
57
+ fields = %w[aud delegate_payload iat nonce sd_hash]
58
+ if profile_ref == TrustContext::LONG_PROFILE_REF
59
+ fields += ["ap2_profile"]
60
+ raise Rejected, :unsupported_purchase_profile unless terminal["ap2_profile"] == profile_ref
61
+ end
62
+ exact!(terminal, fields)
58
63
  raise Rejected, :root_binding_mismatch unless terminal["sd_hash"] == hash(root_wire)
59
64
  raise Rejected, :audience_mismatch unless terminal["aud"] == aud
60
65
  raise Rejected, :nonce_mismatch unless terminal["nonce"] == nonce
@@ -66,7 +71,7 @@ module AP2MandateVerifier
66
71
  closed = payloads.first
67
72
  exact!(closed, %w[checkout_hash checkout_jwt exp iat vct])
68
73
  raise Rejected, :unsupported_purchase_profile unless closed["vct"] == "mandate.checkout.1"
69
- times!(closed, verified_at)
74
+ times!(closed, verified_at, profile_ref: profile_ref)
70
75
  # R06 fixed shared claims: no shortening or extending Issuer iat/exp.
71
76
  raise Rejected, :delegation_claim_mismatch unless closed["iat"] == open["iat"] && closed["exp"] == open["exp"]
72
77
  raise Rejected, :checkout_binding_mismatch unless closed["checkout_jwt"] == checkout_wire &&
@@ -90,11 +95,12 @@ module AP2MandateVerifier
90
95
  raise RootSignature::Unavailable, :purchase_context_unavailable
91
96
  end
92
97
 
93
- def self.times!(claims, now)
98
+ def self.times!(claims, now, profile_ref: TrustContext::PROFILE_REF)
94
99
  iat, exp = claims.values_at("iat", "exp")
100
+ limit = profile_ref == TrustContext::LONG_PROFILE_REF ? LongPayment::MAX_CONTENT_LIFETIME : 7_200
95
101
  raise Rejected, :invalid_purchase_time unless integer?(iat) && integer?(exp) &&
96
102
  iat.between?(0, MAX_EPOCH) && exp.between?(0, MAX_EPOCH) &&
97
- iat <= now && now < exp && exp > iat && exp - iat <= 7_200
103
+ iat <= now && now < exp && exp > iat && exp - iat <= limit
98
104
  end
99
105
 
100
106
  def self.exact!(value, keys)
@@ -0,0 +1,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Narrow signed wire profile only. Aggregate occurrence/budget reservation
5
+ # belongs to the protected durable acceptance store, never to this verifier.
6
+ module RecurringPayment
7
+ PROFILE_REF = "ap2.payment.recurring.jpy_on_demand.complete.1".freeze
8
+ SELECTIVE_PROFILE_REF = "ap2.payment.recurring.jpy_on_demand.selective.1".freeze
9
+ TYPES = %w[payment.agent_recurrence payment.budget].freeze
10
+ MAX_OCCURRENCES = 1_000_000
11
+ class Invalid < ArgumentError
12
+ def initialize = super("invalid recurring payment information")
13
+ end
14
+
15
+ def self.profile?(profile) = [PROFILE_REF, SELECTIVE_PROFILE_REF].include?(profile)
16
+ def self.profile!(value)
17
+ profile = InputValidator.snapshot!(value, max_bytes: 256)
18
+ raise Invalid unless profile?(profile)
19
+ profile
20
+ end
21
+ def self.selective?(profile) = profile == SELECTIVE_PROFILE_REF
22
+
23
+ # Internal structural handoff only; it does not authenticate a signature.
24
+ def self.validated_open!(source, profile_ref:, complete:)
25
+ profile = profile!(profile_ref)
26
+ raise Invalid unless complete == true || complete == false
27
+ if selective?(profile)
28
+ parsed = SelectivePayment.send(:parse!, source, complete: complete, profile_ref: profile)
29
+ opening, wire, compact = parsed.values_at(:opening, :wire, :compact)
30
+ else
31
+ opening, wire = Payment.send(:root!, source, profile_ref: profile)
32
+ Payment.send(:open!, opening, profile_ref: profile)
33
+ compact = wire.split("~", -1).first
34
+ end
35
+ recurrence = opening.fetch("constraints").find { |c| c["type"] == TYPES[0] }
36
+ budget = opening.fetch("constraints").find { |c| c["type"] == TYPES[1] }
37
+ {opening: ResearchEvidence.send(:copy_frozen, opening), root_wire: compact.freeze,
38
+ presentation_wire: wire.freeze, reference: Payment.send(:digest, compact).freeze,
39
+ currency: "JPY".freeze, max_occurrences: recurrence.fetch("max_occurrences"), budget_max: budget.fetch("max"),
40
+ profile_ref: profile}.freeze
41
+ end
42
+
43
+ # Protected Host enrollment uses confidential complete issuance. The root
44
+ # reference covers the original JWS alone so leaf selection cannot reset it.
45
+ def self.approved_open!(open_sd_jwt:, profile_ref:, trusted_provider_public_key_pem:, expected_agent_public_key_pem:, verified_at:)
46
+ profile = profile!(profile_ref)
47
+ wire = InputValidator.snapshot!(open_sd_jwt, max_bytes: selective?(profile) ? SelectivePayment::MAX_WIRE : 32_769)
48
+ provider = InputValidator.snapshot!(trusted_provider_public_key_pem, max_bytes: 1024)
49
+ agent = InputValidator.snapshot!(expected_agent_public_key_pem, max_bytes: 1024)
50
+ CheckoutReceipt.send(:epoch!, verified_at)
51
+ # Authenticate the exact original compact JWS before parsing its graph.
52
+ RootSignature.verified_payload!(wire.split("~", -1).first, provider, max_bytes: 32_768)
53
+ parsed = validated_open!(wire, profile_ref: profile, complete: true)
54
+ opening = parsed.fetch(:opening)
55
+ Payment.send(:valid_now!, opening, verified_at)
56
+ raise Invalid unless opening.fetch("cnf") == {"jwk" => RootSignature.public_jwk!(agent)}
57
+ parsed
58
+ rescue StandardError, LoadError
59
+ raise Invalid.new, cause: nil
60
+ end
61
+
62
+ def self.constraints!(opening)
63
+ raise Invalid unless opening.instance_of?(Hash)
64
+ cs = opening.fetch("constraints")
65
+ raise Invalid unless cs.instance_of?(Array) && cs.size == 6 && cs.all? { |c| c.instance_of?(Hash) }
66
+ recurrence = cs.select { |c| c["type"] == TYPES[0] }
67
+ budget = cs.select { |c| c["type"] == TYPES[1] }
68
+ raise Invalid unless recurrence.size == 1 && budget.size == 1
69
+ recurrence, budget = recurrence.first, budget.first
70
+ Payment.send(:exact!, recurrence, %w[type frequency max_occurrences])
71
+ Payment.send(:exact!, budget, %w[type max currency])
72
+ raise Invalid unless recurrence["frequency"] == "ON_DEMAND" && integer?(recurrence["max_occurrences"]) &&
73
+ recurrence["max_occurrences"].between?(1, MAX_OCCURRENCES) && budget["currency"] == "JPY" &&
74
+ integer?(budget["max"]) && budget["max"].between?(1, ScopedConstraints::MAX_AMOUNT)
75
+ amount = cs.select { |c| c["type"] == "payment.amount_range" }
76
+ raise Invalid unless amount.size == 1 && amount.first["currency"] == "JPY"
77
+ # This only detects an impossible individual payment, not aggregate use.
78
+ raise Invalid if integer?(amount.first.fetch("min", 0)) && amount.first.fetch("min", 0) > budget["max"]
79
+ if opening.key?("payment_amount")
80
+ Payment.send(:amount!, opening["payment_amount"])
81
+ raise Invalid unless opening["payment_amount"]["currency"] == "JPY" && opening["payment_amount"]["amount"] <= budget["max"]
82
+ end
83
+ opening.merge("constraints" => cs.reject { |c| TYPES.include?(c["type"]) })
84
+ end
85
+ def self.conditions!(opening, closed)
86
+ base = constraints!(opening)
87
+ budget = opening.fetch("constraints").find { |c| c["type"] == TYPES[1] }
88
+ raise Invalid unless closed.fetch("payment_amount").fetch("currency") == "JPY" && closed["payment_amount"]["amount"] <= budget.fetch("max")
89
+ Payment.send(:conditions!, base, closed)
90
+ end
91
+ def self.integer?(value) = Object.instance_method(:instance_of?).bind_call(value, Integer)
92
+
93
+ # Same raw public lifecycle as Payment/SelectivePayment. No direct Closed
94
+ # issuance is exposed because the mandatory limits belong to signed Open.
95
+ %i[details issue_open issue_closed present verify select].each do |name|
96
+ define_singleton_method(name) do |profile_ref: PROFILE_REF, **arguments|
97
+ profile = profile!(profile_ref)
98
+ if name == :details
99
+ next Payment.details(**arguments, profile_ref: PROFILE_REF)
100
+ end
101
+ raise Invalid if name == :select && !selective?(profile)
102
+ api = selective?(profile) ? SelectivePayment : Payment
103
+ api.public_send(name, **arguments, profile_ref: profile)
104
+ rescue StandardError, LoadError
105
+ next Payment::Verification.send(:new) if name == :verify
106
+ raise Invalid.new, cause: nil
107
+ end
108
+ end
109
+ private_class_method :profile!, :validated_open!, :constraints!, :conditions!, :integer?
110
+ end
111
+ end
@@ -30,7 +30,8 @@ module AP2MandateVerifier
30
30
  raise Rejected.new(:unsupported_disclosure_profile), cause: nil
31
31
  end
32
32
  end
33
- multi = profile_ref == "ap2.checkout.single_merchant_multi_item"
33
+ long = profile_ref == TrustContext::LONG_PROFILE_REF
34
+ multi = long || profile_ref == "ap2.checkout.single_merchant_multi_item"
34
35
  raise Rejected, :unsupported_disclosure_profile unless multi || profile_ref == TrustContext::PROFILE_REF
35
36
  wire = InputValidator.snapshot!(source)
36
37
  raise Rejected, :invalid_root_presentation unless wire.ascii_only? && wire.end_with?("~")
@@ -39,12 +40,13 @@ module AP2MandateVerifier
39
40
  parts.last == "" && !parts.first.empty? && parts[1...-1].none?(&:empty?)
40
41
  # No disclosure decode, digest graph or trusted claims before signature.
41
42
  payload = RootSignature.verified_payload!(parts.first, issuer_pem)
42
- resolve!(parts, payload, multi)
43
+ resolve!(parts, payload, multi, marker_profile: long ? profile_ref : nil)
43
44
  end
44
45
 
45
46
  # Internal structural restoration only. Never authenticates an issuer.
46
47
  # Shares the exact closure walker with the authenticated verification path.
47
- def self.structural_root!(source)
48
+ def self.structural_root!(source, profile_ref: nil)
49
+ raise Rejected, :unsupported_disclosure_profile unless profile_ref.nil? || profile_ref == TrustContext::LONG_PROFILE_REF
48
50
  wire = InputValidator.snapshot!(source)
49
51
  raise Rejected, :invalid_root_presentation unless wire.ascii_only? && wire.end_with?("~")
50
52
  parts = wire.split("~", -1)
@@ -57,13 +59,14 @@ module AP2MandateVerifier
57
59
  CheckoutReceipt.send(:header!, header, "example+sd-jwt")
58
60
  raise Rejected, :invalid_root_presentation unless RootSignature.send(:decode!, jwt[2], 64).bytesize == 64
59
61
  payload = InputValidator.parse!(RootSignature.send(:decode!, jwt[1], 24_576))
60
- resolve!(parts, payload, true)
62
+ resolve!(parts, payload, true, marker_profile: profile_ref)
61
63
  end
62
64
 
63
- def self.resolve!(parts, payload, multi)
65
+ def self.resolve!(parts, payload, multi, marker_profile: nil)
64
66
  raise Rejected, :unsupported_disclosure_profile unless
65
67
  payload.instance_of?(Hash) &&
66
- (payload.keys - %w[delegate_payload _sd_alg]).empty? &&
68
+ (payload.keys - (marker_profile ? %w[delegate_payload _sd_alg ap2_profile] : %w[delegate_payload _sd_alg])).empty? &&
69
+ (!marker_profile || payload["ap2_profile"] == marker_profile) &&
67
70
  (!payload.key?("_sd_alg") || payload["_sd_alg"] == "sha-256") &&
68
71
  payload["delegate_payload"].instance_of?(Array) && payload["delegate_payload"].size == 1
69
72
  require "digest"
@@ -29,7 +29,7 @@ module AP2MandateVerifier
29
29
  raise RootSignature::Unavailable, :constraint_context_unavailable unless
30
30
  CURRENCIES.include?(currency) && CORE_INSTANCE_OF.bind_call(expected_total_minor, Integer) &&
31
31
  expected_total_minor.between?(0, MAX_AMOUNT)
32
- if [MULTI_PROFILE_REF, TrustContext::SELECTIVE_PROFILE_REF].include?(profile_ref)
32
+ if [MULTI_PROFILE_REF, TrustContext::SELECTIVE_PROFILE_REF, TrustContext::LONG_PROFILE_REF].include?(profile_ref)
33
33
  details = PurchaseBinding.verified_details!(**binding_inputs, profile_ref: profile_ref)
34
34
  multi_constraints!(details, currency, expected_total_minor)
35
35
  return details
@@ -97,7 +97,7 @@ module AP2MandateVerifier
97
97
  Payment.send(:text!, aud, 512); Payment.send(:text!, challenge, 512)
98
98
  claims = {"delegate_payload" => [closed], "iat" => verified_at, "aud" => aud, "nonce" => challenge,
99
99
  "sd_hash" => digest(parsed.fetch(:wire))}
100
- claims["ap2_profile"] = profile_ref if PaymentPolicy.enabled?(profile_ref)
100
+ claims["ap2_profile"] = profile_ref if PaymentPolicy.marked?(profile_ref)
101
101
  Payment.send(:preflight!, claims, "kb+sd-jwt", profile_ref: profile_ref)
102
102
  terminal = MerchantSignature.sign!(claims, signer, agent, typ: "kb+sd-jwt")
103
103
  Payment::Presentation.send(:new, parsed.fetch(:wire), terminal + "~")
@@ -12,6 +12,10 @@ module AP2MandateVerifier
12
12
  MULTI_PROFILE_VERSION = "1"
13
13
  MULTI_PROFILE_BODY = '{"profile_ref":"ap2.checkout.single_merchant_multi_item","version":"1","ap2_source":"b4587ac1d055888a73b4b21750973cffba961793","algorithm":"ES256","key_format":"canonical-public-SPKI-P256-SHA256","root_type":"example+sd-jwt","terminal_type":"kb+sd-jwt","checkout_type":"JWT","disclosure_path_semantics":"root-walker-with-synthetic-disclosed-edges","disclosure_positions":["delegate_payload[0]","delegate_payload[0].disclosed.constraints[0].items[*].acceptable_items[*]","delegate_payload[0].disclosed.constraints[1].allowed[0]"],"constraints":["checkout.line_items","checkout.allowed_merchants"],"max_disclosures":66,"max_disclosure_segment_bytes":8192,"max_root_bytes":131072,"max_graph_nodes":2048,"max_graph_depth":24,"max_array_entries":16,"max_line_items":8,"max_requirements":8,"max_candidates_per_requirement":8,"quantity_matching":"integer-max-flow-product-id-exact-coverage","duplicate_line_ids":"reject","duplicate_requirement_ids":"reject","same_product_multiple_lines":"allow","amount_model":"integer-minor-unit-no-tax-shipping-discount"}'.freeze
14
14
  MULTI_PROFILE_HASH = Digest::SHA256.hexdigest(MULTI_PROFILE_BODY).freeze
15
+ LONG_PROFILE_REF = "ap2.checkout.long_open.multi_item.1".freeze
16
+ LONG_PROFILE_VERSION = "1".freeze
17
+ LONG_PROFILE_BODY = '{"profile_ref":"ap2.checkout.long_open.multi_item.1","version":"1","ap2_source":"b4587ac1d055888a73b4b21750973cffba961793","algorithm":"ES256","root_type":"example+sd-jwt","terminal_type":"kb+sd-jwt","checkout_type":"JWT","signed_profile_marker":"ap2_profile","disclosure_positions":["delegate_payload[0]","delegate_payload[0].disclosed.constraints[0].items[*].acceptable_items[*]","delegate_payload[0].disclosed.constraints[1].allowed[0]"],"constraints":["checkout.line_items","checkout.allowed_merchants"],"max_content_seconds":34560000,"shared_content_iat_exp":"exact-open-closed","outer_proof_age_seconds":300,"max_disclosures":66,"max_disclosure_segment_bytes":8192,"max_root_bytes":131072,"max_graph_nodes":2048,"max_graph_depth":24,"max_line_items":8,"max_requirements":8,"max_candidates_per_requirement":8,"quantity_matching":"integer-max-flow-product-id-exact-coverage","merchant_selection":"single-complete","amount_model":"integer-minor-unit-no-tax-shipping-discount"}'.freeze
18
+ LONG_PROFILE_HASH = Digest::SHA256.hexdigest(LONG_PROFILE_BODY).freeze
15
19
  SELECTIVE_PROFILE_REF = "ap2.checkout.selective_candidates.1".freeze
16
20
  SELECTIVE_PROFILE_VERSION = "1".freeze
17
21
  SELECTIVE_PROFILE_BODY = '{"profile_ref":"ap2.checkout.selective_candidates.1","version":"1","ap2_source":"b4587ac1d055888a73b4b21750973cffba961793","algorithm":"ES256","root_type":"example+sd-jwt","terminal_type":"kb+sd-jwt","checkout_type":"JWT","signed_profile_marker":"ap2_profile","mandatory_content":"all-requirements-id-quantity-cnf-iat-exp","selective_positions":["constraints[0].items[*].acceptable_items[*]","constraints[1].allowed[*]"],"max_disclosures":73,"max_disclosure_segment_bytes":8192,"max_root_bytes":131072,"max_requirements":8,"max_candidates_per_requirement":8,"max_merchants":8,"merchant_selection":"exactly-one","item_selection":"nonempty-subset-per-requirement","candidate_policy":"independent-lists-no-correlation","quantity_matching":"integer-max-flow-product-id-exact-coverage","amount_model":"integer-minor-unit-no-tax-shipping-discount"}'.freeze
@@ -24,6 +28,8 @@ module AP2MandateVerifier
24
28
  {ref: PROFILE_REF, version: PROFILE_VERSION, body: PROFILE_BODY, hash: PROFILE_HASH}.freeze
25
29
  when MULTI_PROFILE_REF
26
30
  {ref: MULTI_PROFILE_REF, version: MULTI_PROFILE_VERSION, body: MULTI_PROFILE_BODY, hash: MULTI_PROFILE_HASH}.freeze
31
+ when LONG_PROFILE_REF
32
+ {ref: LONG_PROFILE_REF, version: LONG_PROFILE_VERSION, body: LONG_PROFILE_BODY, hash: LONG_PROFILE_HASH}.freeze
27
33
  when SELECTIVE_PROFILE_REF
28
34
  {ref: SELECTIVE_PROFILE_REF, version: SELECTIVE_PROFILE_VERSION, body: SELECTIVE_PROFILE_BODY, hash: SELECTIVE_PROFILE_HASH}.freeze
29
35
  else
@@ -20,8 +20,12 @@ require_relative "ap2_mandate_verifier/payment_receipt"
20
20
  require_relative "ap2_mandate_verifier/selective_payment"
21
21
  require_relative "ap2_mandate_verifier/selective_checkout"
22
22
  require_relative "ap2_mandate_verifier/payment_policy"
23
+ require_relative "ap2_mandate_verifier/recurring_payment"
24
+ require_relative "ap2_mandate_verifier/long_payment"
23
25
  require_relative "ap2_mandate_verifier/payment_acceptance"
24
26
  require_relative "ap2_mandate_verifier/payment_acceptance/sqlite_store"
27
+ require_relative "ap2_mandate_verifier/payment_acceptance/recurring_sqlite_store"
28
+ require_relative "ap2_mandate_verifier/payment_acceptance/long_sqlite_store"
25
29
 
26
30
  module AP2MandateVerifier
27
31
  # Accepts original JSON bytes only. Syntax validity is not AP2 validity,
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ap2_mandate_verifier
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.5.0
4
+ version: 1.6.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - AP2 Mandate Verifier contributors
8
8
  bindir: bin
9
9
  cert_chain: []
10
- date: 2026-11-04 00:00:00.000000000 Z
10
+ date: 2026-11-05 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: json
@@ -83,9 +83,10 @@ description: 'Framework-independent Ruby SDK for supported AP2 Checkout profiles
83
83
  Merchant JWT signing, Direct and conditional Mandate issuance and presentation,
84
84
  full verification with immutable Evidence, Checkout Receipts, Direct and conditional
85
85
  Payment Mandates, and Payment Receipts. Adds selective Checkout/Payment, PISP/date
86
- constraints and opt-in transactional Payment acceptance/idempotency support. Requires
87
- independently trusted application inputs; verification does not grant purchase or
88
- payment permission.'
86
+ constraints opt-in transactional Payment acceptance/idempotency support and explicit
87
+ bounded JPY/ON_DEMAND quotas and separate long Open UTC-monthly JPY profiles with
88
+ protected current authority and Root/key continuity. Requires independently trusted
89
+ application inputs; verification does not grant purchase or payment permission.'
89
90
  executables: []
90
91
  extensions: []
91
92
  extra_rdoc_files: []
@@ -99,6 +100,7 @@ files:
99
100
  - docs/DIAGNOSTICS.ja.md
100
101
  - docs/DIAGNOSTICS.md
101
102
  - docs/INPUT_BUILDER.md
103
+ - docs/LONG_PAYMENT.md
102
104
  - docs/MERCHANT_SIGNING.md
103
105
  - docs/MULTI_ITEM_CHECKOUT.md
104
106
  - docs/PAYMENT.md
@@ -107,20 +109,25 @@ files:
107
109
  - docs/POST_RELEASE_110.md
108
110
  - docs/POST_RELEASE_MAINTENANCE.md
109
111
  - docs/PUBLIC_API.md
112
+ - docs/RECURRING_PAYMENT.md
110
113
  - docs/RELEASE_100_CANDIDATE.md
111
114
  - docs/RELEASE_110_CANDIDATE.md
112
115
  - docs/RELEASE_120_CANDIDATE.md
113
116
  - docs/RELEASE_130_CANDIDATE.md
114
117
  - docs/RELEASE_140_CANDIDATE.md
115
118
  - docs/RELEASE_150_CANDIDATE.md
119
+ - docs/RELEASE_160_CANDIDATE.md
116
120
  - docs/SELECTIVE_CHECKOUT.md
117
121
  - docs/SELECTIVE_PAYMENT.md
118
122
  - docs/SUPPORT_CONTRACT.md
119
123
  - docs/evidence/1.1.0_publication.json
120
124
  - examples/conditional_checkout.rb
125
+ - examples/long_payment.rb
126
+ - examples/long_payment_acceptance.rb
121
127
  - examples/payment.rb
122
128
  - examples/payment_acceptance.rb
123
129
  - examples/payment_policy.rb
130
+ - examples/recurring_payment.rb
124
131
  - examples/selective_checkout.rb
125
132
  - examples/selective_checkout_payment.rb
126
133
  - examples/selective_payment.rb
@@ -133,13 +140,17 @@ files:
133
140
  - lib/ap2_mandate_verifier/host_binding.rb
134
141
  - lib/ap2_mandate_verifier/input_builder.rb
135
142
  - lib/ap2_mandate_verifier/input_validator.rb
143
+ - lib/ap2_mandate_verifier/long_payment.rb
136
144
  - lib/ap2_mandate_verifier/merchant_signature.rb
137
145
  - lib/ap2_mandate_verifier/payment.rb
138
146
  - lib/ap2_mandate_verifier/payment_acceptance.rb
147
+ - lib/ap2_mandate_verifier/payment_acceptance/long_sqlite_store.rb
148
+ - lib/ap2_mandate_verifier/payment_acceptance/recurring_sqlite_store.rb
139
149
  - lib/ap2_mandate_verifier/payment_acceptance/sqlite_store.rb
140
150
  - lib/ap2_mandate_verifier/payment_policy.rb
141
151
  - lib/ap2_mandate_verifier/payment_receipt.rb
142
152
  - lib/ap2_mandate_verifier/purchase_binding.rb
153
+ - lib/ap2_mandate_verifier/recurring_payment.rb
143
154
  - lib/ap2_mandate_verifier/research_result.rb
144
155
  - lib/ap2_mandate_verifier/result.rb
145
156
  - lib/ap2_mandate_verifier/root_disclosures.rb