ap2_mandate_verifier 1.0.0 → 1.2.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.
@@ -0,0 +1,259 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Explicit conditional-Payment profile. Unknown hidden conditions are never
5
+ # inferred to be absent; unresolved commitments exist only at candidate slots.
6
+ module SelectivePayment
7
+ PROFILE_REF = "ap2.payment.selective_candidates.1".freeze
8
+ MAX_WIRE = 65_536
9
+ MAX_DISCLOSURES = 17
10
+ AXES = {"payment.allowed_payees" => "payee", "payment.allowed_payment_instruments" => "payment_instrument"}.freeze
11
+ class Invalid < ArgumentError
12
+ def initialize = super("invalid selective payment information")
13
+ end
14
+
15
+ # All candidates and their exact Cartesian authorization come from a
16
+ # protected approval record. This confidential issuance MUST NOT be sent.
17
+ def self.issue_open(open_checkout_sd_jwt:, constraints:, fixed:, approved_combinations:, selective:,
18
+ agent_public_key_pem:, issued_at:, expires_at:, signer:, public_key_pem:)
19
+ RootSignature.send(:dependencies!)
20
+ raise Invalid unless %i[payees instruments both].include?(selective)
21
+ checkout = Payment.send(:checkout_open!, open_checkout_sd_jwt)
22
+ cs = InputBuilder.send(:copy!, constraints)
23
+ raise Invalid unless cs.instance_of?(Array)
24
+ cs << {"type" => "payment.reference", "conditional_transaction_id" => digest(checkout)}
25
+ value = InputBuilder.send(:copy!, fixed)
26
+ raise Invalid unless value.instance_of?(Hash) && (value.keys - Payment::FIELDS.drop(1)).empty?
27
+ opening = value.merge("vct" => "mandate.payment.open.1", "iat" => issued_at, "exp" => expires_at,
28
+ "cnf" => {"jwk" => RootSignature.public_jwk!(agent_public_key_pem)}, "constraints" => cs)
29
+ Payment.send(:open!, opening)
30
+ payees = constraint!(opening, "payment.allowed_payees").fetch("allowed")
31
+ instruments = constraint!(opening, "payment.allowed_payment_instruments").fetch("allowed")
32
+ pairs = InputBuilder.send(:copy!, approved_combinations)
33
+ expected = payees.each_index.flat_map { |p| instruments.each_index.map { |i| [p, i] } }
34
+ raise Invalid unless pairs.instance_of?(Array) && pairs.size == expected.size && pairs.all? do |pair|
35
+ pair.instance_of?(Array) && pair.size == 2 && pair.all? { |n| Object.instance_method(:instance_of?).bind_call(n, Integer) }
36
+ end
37
+ raise Invalid unless pairs.sort == expected.sort
38
+ AXES.each do |type, field|
39
+ raise Invalid if opening.key?(field) && !constraint!(opening, type).fetch("allowed").include?(opening[field])
40
+ end
41
+ disclosures = []
42
+ modes = selective == :both ? AXES.keys : [selective == :payees ? AXES.keys[0] : AXES.keys[1]]
43
+ modes.each do |type|
44
+ c = constraint!(opening, type)
45
+ c["allowed"] = c["allowed"].map { |candidate| disclose!(candidate, disclosures) }
46
+ end
47
+ content = []
48
+ pointer = disclose!(opening, content)
49
+ payload = {"ap2_profile" => PROFILE_REF, "_sd_alg" => "sha-256", "delegate_payload" => [pointer]}
50
+ preview = [encode({"alg" => "ES256", "typ" => "example+sd-jwt"}), encode(payload), encode("\0" * 64)].join(".")
51
+ wire = ([preview] + content + disclosures + [""]).join("~")
52
+ parse!(wire, complete: true) # Full wire/disclosure bounds BEFORE signer effects.
53
+ jwt = MerchantSignature.sign!(payload, signer, public_key_pem, typ: "example+sd-jwt")
54
+ ([jwt] + content + disclosures + [""]).join("~").freeze
55
+ end
56
+
57
+ # Each selective index selects one original signed candidate slot. For an
58
+ # inline/nonselective axis, pass nil: every approved inline value is visible.
59
+ def self.select(open_sd_jwt:, payee_index:, instrument_index:)
60
+ parsed = parse!(open_sd_jwt, complete: true)
61
+ keep = [parsed.fetch(:content_digest)]
62
+ {"payment.allowed_payees" => payee_index, "payment.allowed_payment_instruments" => instrument_index}.each do |type, index|
63
+ c = constraint!(parsed.fetch(:original), type)
64
+ slots = parsed.fetch(:slots).fetch(type)
65
+ if slots.empty?
66
+ raise Invalid unless index.nil?
67
+ else
68
+ raise Invalid unless Object.instance_method(:instance_of?).bind_call(index, Integer) && index.between?(0, slots.size - 1)
69
+ keep << slots.fetch(index)
70
+ field = AXES.fetch(type)
71
+ selected = parsed.fetch(:values).fetch(slots.fetch(index))
72
+ raise Invalid if parsed.fetch(:original).key?(field) && parsed.fetch(:original)[field] != selected
73
+ end
74
+ end
75
+ wire = ([parsed.fetch(:compact)] + parsed.fetch(:disclosures).select { |d| keep.include?(digest(d)) } + [""]).join("~")
76
+ parse!(wire, complete: false)
77
+ wire.freeze
78
+ end
79
+
80
+ def self.issue_closed(open_presentation:, payment:, trusted_provider_public_key_pem:, agent_public_key_pem:,
81
+ audience:, nonce:, verified_at:, signer:)
82
+ agent = InputValidator.snapshot!(agent_public_key_pem, max_bytes: 1_024)
83
+ provider = InputValidator.snapshot!(trusted_provider_public_key_pem, max_bytes: 1_024)
84
+ aud = InputValidator.snapshot!(audience, max_bytes: 512)
85
+ challenge = InputValidator.snapshot!(nonce, max_bytes: 512)
86
+ parsed = authenticated!(open_presentation, provider)
87
+ opening = parsed.fetch(:opening)
88
+ Payment.send(:valid_now!, opening, verified_at)
89
+ raise Invalid unless opening.fetch("cnf") == {"jwk" => RootSignature.public_jwk!(agent)}
90
+ closed = Payment.send(:copy_details!, payment).merge("vct" => "mandate.payment.1", "iat" => verified_at, "exp" => opening.fetch("exp"))
91
+ Payment.send(:closed!, closed); Payment.send(:conditions!, opening, closed)
92
+ Payment.send(:text!, aud, 512); Payment.send(:text!, challenge, 512)
93
+ claims = {"delegate_payload" => [closed], "iat" => verified_at, "aud" => aud, "nonce" => challenge,
94
+ "sd_hash" => digest(parsed.fetch(:wire))}
95
+ Payment.send(:preflight!, claims, "kb+sd-jwt")
96
+ terminal = MerchantSignature.sign!(claims, signer, agent, typ: "kb+sd-jwt")
97
+ Payment::Presentation.send(:new, parsed.fetch(:wire), terminal + "~")
98
+ end
99
+
100
+ # Structural restoration only. It never authenticates a stored presentation.
101
+ def self.present(open_presentation:, closed_sd_jwt:)
102
+ root = parse!(open_presentation, complete: false)
103
+ terminal, wire = Payment.send(:final!, closed_sd_jwt, conditional: true)
104
+ closed = terminal.fetch("delegate_payload").first
105
+ bind_terminal!(root, terminal, closed)
106
+ Payment::Presentation.send(:new, root.fetch(:wire), wire)
107
+ end
108
+
109
+ def self.verify(open_presentation:, closed_sd_jwt:, checkout_inputs:, expected_payment:,
110
+ trusted_provider_public_key_pem:, expected_agent_public_key_pem:,
111
+ expected_audience:, expected_nonce:, verified_at:)
112
+ CheckoutReceipt.send(:epoch!, verified_at)
113
+ agent = InputValidator.snapshot!(expected_agent_public_key_pem, max_bytes: 1_024)
114
+ provider = InputValidator.snapshot!(trusted_provider_public_key_pem, max_bytes: 1_024)
115
+ aud = InputValidator.snapshot!(expected_audience, max_bytes: 512)
116
+ nonce = InputValidator.snapshot!(expected_nonce, max_bytes: 512)
117
+ fields = %i[trust_json selection_json host_json root_presentation terminal_jws host_checkout_jws verified_at]
118
+ raise Invalid unless checkout_inputs.instance_of?(Hash) && checkout_inputs.size == fields.size &&
119
+ fields.all? { |f| checkout_inputs.key?(f) } && checkout_inputs[:verified_at] == verified_at
120
+ limits = {host_json: 32_768, terminal_jws: 32_768, host_checkout_jws: 16_384}
121
+ inputs = checkout_inputs.to_h do |key, value|
122
+ [key, key == :verified_at ? value : InputValidator.snapshot!(value, max_bytes: limits.fetch(key, 131_072))]
123
+ end.freeze
124
+ raise Invalid unless inputs.size == fields.size && fields.all? { |f| inputs.key?(f) } && inputs[:verified_at] == verified_at
125
+ expected = Payment.send(:copy_details!, expected_payment)
126
+ checkout = AP2MandateVerifier.verify_checkout(**inputs)
127
+ raise Invalid unless checkout.success?
128
+ raise Invalid unless expected.fetch("transaction_id") == digest(inputs.fetch(:host_checkout_jws))
129
+ binding = checkout.evidence["checkout_binding"]
130
+ amount = expected.fetch("payment_amount")
131
+ raise Invalid unless expected.fetch("payee").fetch("id") == binding.fetch("merchant_id") &&
132
+ amount.fetch("currency") == binding.fetch("currency") && amount.fetch("amount") == binding.fetch("expected_total")
133
+ Payment.send(:bind_checkout!, expected, Payment.send(:jwt_payload!, inputs.fetch(:host_checkout_jws), "JWT"))
134
+ parsed = authenticated!(open_presentation, provider)
135
+ opening = parsed.fetch(:opening)
136
+ Payment.send(:valid_now!, opening, verified_at)
137
+ raise Invalid unless opening.fetch("cnf") == {"jwk" => RootSignature.public_jwk!(agent)}
138
+ terminal, wire = Payment.send(:final!, closed_sd_jwt, conditional: true)
139
+ RootSignature.verified_payload!(wire.split("~", -1).first, agent,
140
+ expected_typ: "kb+sd-jwt", max_bytes: 32_768)
141
+ Payment.send(:text!, aud, 512); Payment.send(:text!, nonce, 512)
142
+ raise Invalid unless terminal.fetch("aud") == aud && terminal.fetch("nonce") == nonce &&
143
+ terminal.fetch("iat") <= verified_at && verified_at - terminal.fetch("iat") <= 300
144
+ closed = terminal.fetch("delegate_payload").first
145
+ bind_terminal!(parsed, terminal, closed)
146
+ Payment.send(:valid_now!, closed, verified_at)
147
+ ref = constraint!(opening, "payment.reference").fetch("conditional_transaction_id")
148
+ raise Invalid unless ref == digest(inputs.fetch(:root_presentation)) && closed.slice(*Payment::FIELDS) == expected
149
+ Payment::Verification.send(:new, closed, wire)
150
+ rescue StandardError, LoadError
151
+ Payment::Verification.send(:new)
152
+ end
153
+
154
+ def self.bind_terminal!(root, terminal, closed)
155
+ opening = root.fetch(:opening)
156
+ Payment.send(:closed!, closed)
157
+ raise Invalid unless terminal.fetch("sd_hash") == digest(root.fetch(:wire)) && terminal.fetch("iat") == closed.fetch("iat") &&
158
+ closed.fetch("iat") >= opening.fetch("iat") && closed.fetch("exp") <= opening.fetch("exp")
159
+ Payment.send(:conditions!, opening, closed)
160
+ end
161
+ def self.authenticated!(wire, key)
162
+ parsed = parse!(wire, complete: false)
163
+ RootSignature.verified_payload!(parsed.fetch(:compact), key, max_bytes: 16_384)
164
+ parsed
165
+ end
166
+ def self.parse!(source, complete:)
167
+ RootSignature.send(:dependencies!)
168
+ wire = InputValidator.snapshot!(source, max_bytes: MAX_WIRE)
169
+ raise Invalid unless wire.ascii_only? && wire.end_with?("~")
170
+ compact, *disclosures = wire.split("~", -1)
171
+ disclosures.pop
172
+ raise Invalid unless disclosures.size.between?(2, MAX_DISCLOSURES) && disclosures.none?(&:empty?)
173
+ compact = InputValidator.snapshot!(compact, max_bytes: 16_384)
174
+ claims = Payment.send(:jwt_payload!, compact, "example+sd-jwt")
175
+ Payment.send(:exact!, claims, %w[ap2_profile _sd_alg delegate_payload])
176
+ raise Invalid unless claims["ap2_profile"] == PROFILE_REF && claims["_sd_alg"] == "sha-256" &&
177
+ claims["delegate_payload"].instance_of?(Array) && claims["delegate_payload"].size == 1
178
+ pointer = claims.fetch("delegate_payload").first
179
+ Payment.send(:exact!, pointer, ["..."])
180
+ hash!(pointer["..."])
181
+ values = {}; salts = []
182
+ disclosures.each do |disclosure|
183
+ value = Buyer.send(:decode_disclosure!, disclosure, 2)
184
+ hash = digest(disclosure)
185
+ raise Invalid if values.key?(hash) || salts.include?(value[0])
186
+ salts << value[0]
187
+ values[hash] = value[1]
188
+ end
189
+ content_digest = pointer.fetch("...")
190
+ original = values.fetch(content_digest)
191
+ raise Invalid unless original.instance_of?(Hash) && original["constraints"].instance_of?(Array)
192
+ opening = InputBuilder.send(:copy!, original)
193
+ slots = {}; used = [content_digest]; all_commitments = [content_digest]
194
+ AXES.each do |type, field|
195
+ c = constraint!(opening, type)
196
+ Payment.send(:exact!, c, %w[type allowed])
197
+ list = c.fetch("allowed")
198
+ raise Invalid unless list.instance_of?(Array) && list.size.between?(1, 8)
199
+ markers = list.map { |item| item.instance_of?(Hash) && item.keys == ["..."] }
200
+ raise Invalid unless markers.all? || markers.none?
201
+ slots[type] = []
202
+ if markers.all?
203
+ selected = []
204
+ list.each do |item|
205
+ h = item.fetch("..."); hash!(h)
206
+ raise Invalid if all_commitments.include?(h)
207
+ all_commitments << h; slots[type] << h
208
+ if values.key?(h)
209
+ selected << values.fetch(h); used << h
210
+ elsif complete
211
+ raise Invalid
212
+ end
213
+ end
214
+ raise Invalid unless complete ? selected.size == list.size : selected.size == 1
215
+ c["allowed"] = selected
216
+ end
217
+ end
218
+ raise Invalid if slots.values.all?(&:empty?)
219
+ raise Invalid unless used.sort == values.keys.sort
220
+ Payment.send(:open!, opening) # Only candidate markers were resolved/omitted.
221
+ {wire: wire, compact: compact, disclosures: disclosures, opening: opening,
222
+ original: original, content_digest: content_digest, slots: slots, values: values}
223
+ end
224
+ def self.constraint!(opening, type)
225
+ cs = opening.fetch("constraints")
226
+ raise Invalid unless cs.instance_of?(Array)
227
+ found = cs.select { |c| c.instance_of?(Hash) && c["type"] == type }
228
+ raise Invalid unless found.size == 1
229
+ found.first
230
+ end
231
+ def self.disclose!(value, disclosures)
232
+ require "securerandom"
233
+ wire = encode([encode(SecureRandom.random_bytes(16)), value])
234
+ disclosures << wire
235
+ {"..." => digest(wire)}
236
+ end
237
+ def self.hash!(value)
238
+ raise Invalid unless value.instance_of?(String) && value.match?(/\A[A-Za-z0-9_-]{43}\z/)
239
+ end
240
+ def self.encode(value) = Buyer.send(:encode, value)
241
+ def self.digest(wire) = Payment.send(:digest, wire)
242
+
243
+ %i[issue_open select issue_closed present verify].each do |name|
244
+ implementation = method(name)
245
+ fields = implementation.parameters.map(&:last).freeze
246
+ define_singleton_method(name) do |**args|
247
+ unless (fields - args.keys).empty? && (args.keys - fields).empty?
248
+ next Payment::Verification.send(:new) if name == :verify
249
+ raise Invalid
250
+ end
251
+ implementation.call(**args)
252
+ rescue StandardError, LoadError
253
+ next Payment::Verification.send(:new) if name == :verify
254
+ raise Invalid.new, cause: nil
255
+ end
256
+ end
257
+ singleton_methods(false).reject { |n| %i[issue_open select issue_closed present verify].include?(n) }.each { |n| private_class_method n }
258
+ end
259
+ end
@@ -15,6 +15,9 @@ require_relative "ap2_mandate_verifier/checkout_jwt"
15
15
  require_relative "ap2_mandate_verifier/checkout_receipt"
16
16
  require_relative "ap2_mandate_verifier/buyer"
17
17
  require_relative "ap2_mandate_verifier/conditional_checkout"
18
+ require_relative "ap2_mandate_verifier/payment"
19
+ require_relative "ap2_mandate_verifier/payment_receipt"
20
+ require_relative "ap2_mandate_verifier/selective_payment"
18
21
 
19
22
  module AP2MandateVerifier
20
23
  # 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.0.0
4
+ version: 1.2.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-01 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: json
@@ -81,9 +81,10 @@ dependencies:
81
81
  version: 3.2.1
82
82
  description: 'Framework-independent Ruby SDK for supported AP2 Checkout profiles:
83
83
  Merchant JWT signing, Direct and conditional Mandate issuance and presentation,
84
- full verification with immutable Evidence, and Checkout Receipt signing and verification.
85
- Requires independently trusted application inputs; verification does not grant purchase
86
- or payment permission.'
84
+ full verification with immutable Evidence, Checkout Receipts, Direct and conditional
85
+ Payment Mandates, and Payment Receipts. Adds opt-in selective Payment candidate
86
+ disclosure. Requires independently trusted application inputs; verification does
87
+ not grant purchase or payment permission.'
87
88
  executables: []
88
89
  extensions: []
89
90
  extra_rdoc_files: []
@@ -99,11 +100,19 @@ files:
99
100
  - docs/INPUT_BUILDER.md
100
101
  - docs/MERCHANT_SIGNING.md
101
102
  - docs/MULTI_ITEM_CHECKOUT.md
103
+ - docs/PAYMENT.md
104
+ - docs/POST_RELEASE_110.md
102
105
  - docs/POST_RELEASE_MAINTENANCE.md
103
106
  - docs/PUBLIC_API.md
104
107
  - docs/RELEASE_100_CANDIDATE.md
108
+ - docs/RELEASE_110_CANDIDATE.md
109
+ - docs/RELEASE_120_CANDIDATE.md
110
+ - docs/SELECTIVE_PAYMENT.md
105
111
  - docs/SUPPORT_CONTRACT.md
112
+ - docs/evidence/1.1.0_publication.json
106
113
  - examples/conditional_checkout.rb
114
+ - examples/payment.rb
115
+ - examples/selective_payment.rb
107
116
  - lib/ap2_mandate_verifier.rb
108
117
  - lib/ap2_mandate_verifier/buyer.rb
109
118
  - lib/ap2_mandate_verifier/checkout_jwt.rb
@@ -114,12 +123,15 @@ files:
114
123
  - lib/ap2_mandate_verifier/input_builder.rb
115
124
  - lib/ap2_mandate_verifier/input_validator.rb
116
125
  - lib/ap2_mandate_verifier/merchant_signature.rb
126
+ - lib/ap2_mandate_verifier/payment.rb
127
+ - lib/ap2_mandate_verifier/payment_receipt.rb
117
128
  - lib/ap2_mandate_verifier/purchase_binding.rb
118
129
  - lib/ap2_mandate_verifier/research_result.rb
119
130
  - lib/ap2_mandate_verifier/result.rb
120
131
  - lib/ap2_mandate_verifier/root_disclosures.rb
121
132
  - lib/ap2_mandate_verifier/root_signature.rb
122
133
  - lib/ap2_mandate_verifier/scoped_constraints.rb
134
+ - lib/ap2_mandate_verifier/selective_payment.rb
123
135
  - lib/ap2_mandate_verifier/trust_context.rb
124
136
  homepage: https://github.com/cuichangquan/ap2-mandate-verifier
125
137
  licenses:
@@ -142,7 +154,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
142
154
  - !ruby/object:Gem::Version
143
155
  version: '0'
144
156
  requirements: []
145
- rubygems_version: 3.6.9
157
+ rubygems_version: 4.0.20
146
158
  specification_version: 4
147
- summary: Ruby SDK for supported AP2 Checkout Mandates
159
+ summary: Ruby SDK for supported AP2 Checkout and Payment Mandates
148
160
  test_files: []