lunixi-sdk 2.2.1 → 2.3.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,238 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # In-memory token store of the wallet customer session: one process only, for tests and single-process
5
+ # apps. It hands out copies.
6
+ #
7
+ # Token store contract (token_store: of wallet.portal), one record per customer key:
8
+ #
9
+ # get(customer_key) -> record Hash or nil
10
+ # set(customer_key, record) -> stores the record
11
+ # delete(customer_key) -> removes it
12
+ # with_lock(customer_key) { … } optional: runs the block while holding a lock that other processes
13
+ # sharing the store respect, and returns its value
14
+ #
15
+ # record = { 'accessToken', 'refreshToken', 'sessionId', 'expiresAt', 'refreshExpiresAt' } (expiresAt /
16
+ # refreshExpiresAt: epoch seconds, Integer). The tokens are secrets: encrypt them at rest. Each portal call
17
+ # and each refresh must also carry the signature of the key that opened the session, so a leaked token
18
+ # alone does not open the wallet; keep them encrypted all the same.
19
+ #
20
+ # Refresh is single-flight per customer key inside this process. Implement with_lock when several
21
+ # processes or servers share the store (Puma workers, Sidekiq, a cluster): a refresh token sent twice
22
+ # revokes the whole session (401 AUTH_REFRESH_REUSED).
23
+ class InMemoryWalletCustomerTokenStore
24
+ def initialize
25
+ @records = {}
26
+ @mutex = Mutex.new
27
+ end
28
+
29
+ def get(customer_key)
30
+ @mutex.synchronize { @records[customer_key]&.dup }
31
+ end
32
+
33
+ def set(customer_key, record)
34
+ @mutex.synchronize { @records[customer_key] = record.dup }
35
+ nil
36
+ end
37
+
38
+ def delete(customer_key)
39
+ @mutex.synchronize { @records.delete(customer_key) }
40
+ nil
41
+ end
42
+
43
+ def inspect
44
+ '#<Lunixi::InMemoryWalletCustomerTokenStore>'
45
+ end
46
+ end
47
+
48
+ # Hands out a usable access token per customer and refreshes it, one refresh at a time per customer key
49
+ # (every portal client of one Lunixi::Client shares this lock). Not a public API.
50
+ class WalletCustomerTokens
51
+ Code = WalletCustomerSessionErrorCode
52
+ # Codes after which the session cannot be used any more (start a new one).
53
+ SESSION_ENDED_CODES = [Code::SESSION_EXPIRED, Code::REFRESH_INVALID, Code::CUSTOMER_REAUTH_REQUIRED, Code::DEVICE_REVERIFY_REQUIRED].freeze
54
+ BINDING_CODES = [Code::SESSION_BINDING_MISMATCH, Code::SESSION_BINDING_REQUIRED].freeze
55
+ # How long to wait for another process's refresh, in seconds (gateway lock: 5 s).
56
+ REFRESH_IN_PROGRESS_WAITS = [0.25, 0.5, 1.0, 1.5].freeze
57
+ RECORD_KEYS = %w[accessToken refreshToken sessionId expiresAt refreshExpiresAt].freeze
58
+
59
+ # One refresh in flight: the first caller runs it, the others wait for its record or its error.
60
+ class Flight
61
+ def initialize
62
+ @mutex = Mutex.new
63
+ @done = ConditionVariable.new
64
+ @finished = false
65
+ end
66
+
67
+ def finish(record: nil, error: nil)
68
+ @mutex.synchronize do
69
+ @record = record
70
+ @error = error
71
+ @finished = true
72
+ @done.broadcast
73
+ end
74
+ end
75
+
76
+ def wait
77
+ @mutex.synchronize { @done.wait(@mutex) until @finished }
78
+ raise @error if @error
79
+
80
+ @record
81
+ end
82
+ end
83
+
84
+ # A gateway error of a customer session route or portal call as the typed session error; other errors
85
+ # are returned unchanged. session_ended: true turns any ApiError into WalletCustomerSessionExpiredError.
86
+ def self.typed_error(error, customer_key: nil, session_ended: nil)
87
+ if error.is_a?(WalletCustomerSessionError)
88
+ return customer_key && error.customer_key.nil? ? error.with_customer_key(customer_key) : error
89
+ end
90
+ return error if !error.is_a?(ApiError) || error.is_a?(WalletCustomerSessionNotIssuedError) || error.is_a?(WalletCustomerRevokeIncompleteError)
91
+
92
+ fields = { status: error.status, code: error.code, request_id: error.request_id, retry_after: error.retry_after, details: error.details }
93
+ case error.code
94
+ when Code::SESSION_NOT_ISSUED then WalletCustomerSessionNotIssuedError.new(**fields)
95
+ when Code::REVOKE_INCOMPLETE then WalletCustomerRevokeIncompleteError.new(**fields)
96
+ when *BINDING_CODES then WalletCustomerSessionBindingError.new(**fields, customer_key: customer_key, session_ended: false)
97
+ when Code::REFRESH_REUSED then WalletCustomerRefreshReusedError.new(**fields, customer_key: customer_key, session_ended: true)
98
+ else
99
+ ended = SESSION_ENDED_CODES.include?(error.code) || session_ended == true
100
+ ended ? WalletCustomerSessionExpiredError.new(**fields, customer_key: customer_key, session_ended: true) : error
101
+ end
102
+ end
103
+
104
+ # The stored record of a complete / refresh answer.
105
+ def self.session_record(issued, previous, now)
106
+ data = issued.is_a?(Hash) ? issued.transform_keys(&:to_s) : {}
107
+ data = data['data'].transform_keys(&:to_s) if data['data'].is_a?(Hash)
108
+ expires_in = data['expiresIn']
109
+ refresh_expires_at = data['refreshExpiresAt']
110
+ unless data['accessToken'].is_a?(String) && data['accessToken'].start_with?('at_cust_') &&
111
+ data['refreshToken'].is_a?(String) && data['refreshToken'].start_with?('at_custr_') &&
112
+ expires_in.is_a?(Numeric) && expires_in.positive? && refresh_expires_at.is_a?(Numeric)
113
+ raise ApiError.new(status: 0, message: 'The customer session answer did not carry customer tokens.')
114
+ end
115
+
116
+ { 'accessToken' => data['accessToken'], 'refreshToken' => data['refreshToken'],
117
+ 'sessionId' => data['sessionId'].is_a?(String) ? data['sessionId'] : previous&.fetch('sessionId', nil),
118
+ 'expiresAt' => now + expires_in.floor, 'refreshExpiresAt' => refresh_expires_at.floor }
119
+ end
120
+
121
+ def self.missing_session(customer_key, message = 'No customer session is stored for this customer; start a new session.')
122
+ WalletCustomerSessionExpiredError.new(status: 0, message: message, customer_key: customer_key, session_ended: true)
123
+ end
124
+
125
+ # refresher: answers #refresh(refresh_token) (wallet.customer_sessions). clock: Time; sleeper: seconds.
126
+ def initialize(refresher, clock: -> { Time.now.utc }, sleeper: ->(seconds) { sleep(seconds) })
127
+ @refresher = refresher
128
+ @clock = clock
129
+ @sleeper = sleeper
130
+ @lock = Mutex.new
131
+ @inflight = {}
132
+ end
133
+
134
+ def now
135
+ @clock.call.to_i
136
+ end
137
+
138
+ # The stored record; a missing session is WalletCustomerSessionExpiredError (status 0).
139
+ def read(customer_key, store)
140
+ record = store.get(customer_key)
141
+ raise self.class.missing_session(customer_key) if record.nil?
142
+
143
+ record = record.transform_keys(&:to_s) if record.is_a?(Hash)
144
+ unless record.is_a?(Hash) && record['accessToken'].is_a?(String) && record['refreshToken'].is_a?(String) &&
145
+ record['expiresAt'].is_a?(Integer) && record['refreshExpiresAt'].is_a?(Integer)
146
+ raise ConfigurationError, 'token_store.get returned a record without accessToken, refreshToken, expiresAt and refreshExpiresAt.'
147
+ end
148
+
149
+ record
150
+ end
151
+
152
+ def save(customer_key, store, issued)
153
+ record = self.class.session_record(issued, nil, now)
154
+ store.set(customer_key, record)
155
+ record
156
+ end
157
+
158
+ # An access token valid for at least skew_seconds more; refreshed first otherwise.
159
+ def access_token(customer_key, store, skew_seconds)
160
+ record = read(customer_key, store)
161
+ return record['accessToken'] if record['expiresAt'] - skew_seconds > now
162
+
163
+ refresh(customer_key, store, record['accessToken']).fetch('accessToken')
164
+ end
165
+
166
+ # Refreshes the customer's session once, however many threads ask at the same time. stale_access_token
167
+ # is the token the caller found unusable: when the store already holds another, unexpired one
168
+ # (refreshed meanwhile, here or by another process), that one is used and no refresh is sent.
169
+ def refresh(customer_key, store, stale_access_token)
170
+ flight, leader = @lock.synchronize do
171
+ running = @inflight[customer_key]
172
+ running ? [running, false] : [(@inflight[customer_key] = Flight.new), true]
173
+ end
174
+ return flight.wait unless leader
175
+
176
+ outcome = nil
177
+ begin
178
+ record = locked(customer_key, store) { rotate(customer_key, store, stale_access_token) }
179
+ outcome = [record, nil]
180
+ record
181
+ rescue StandardError => e
182
+ outcome = [nil, e]
183
+ raise
184
+ ensure
185
+ @lock.synchronize { @inflight.delete(customer_key) if @inflight[customer_key].equal?(flight) }
186
+ outcome ||= [nil, ConfigurationError.new('The customer session refresh was interrupted; retry.')]
187
+ flight.finish(record: outcome[0], error: outcome[1])
188
+ end
189
+ end
190
+
191
+ def inspect
192
+ '#<Lunixi::WalletCustomerTokens>'
193
+ end
194
+
195
+ private
196
+
197
+ def locked(customer_key, store, &)
198
+ store.respond_to?(:with_lock) ? store.with_lock(customer_key, &) : yield
199
+ end
200
+
201
+ def rotate(customer_key, store, stale_access_token)
202
+ current = read(customer_key, store)
203
+ return current if current['accessToken'] != stale_access_token && current['expiresAt'] > now
204
+
205
+ if current['refreshExpiresAt'] <= now
206
+ store.delete(customer_key)
207
+ raise self.class.missing_session(customer_key, 'The customer session has expired; start a new session.')
208
+ end
209
+ begin
210
+ issued = @refresher.refresh(current['refreshToken'])
211
+ rescue ApiError => e
212
+ return await_other_refresh(customer_key, store, current['refreshToken'], e) if e.code == Code::REFRESH_IN_PROGRESS
213
+
214
+ typed = self.class.typed_error(e, customer_key: customer_key)
215
+ store.delete(customer_key) if typed.is_a?(WalletCustomerSessionError) && typed.session_ended
216
+ raise typed
217
+ end
218
+ record = self.class.session_record(issued, current, now)
219
+ store.set(customer_key, record)
220
+ record
221
+ end
222
+
223
+ # Another process holds the gateway's refresh lock for this session. Never re-send the same refresh
224
+ # token (it may already be rotated, which would revoke the session): wait for the other process to
225
+ # store the new tokens.
226
+ def await_other_refresh(customer_key, store, old_refresh_token, error)
227
+ REFRESH_IN_PROGRESS_WAITS.each do |seconds|
228
+ @sleeper.call(seconds)
229
+ record = store.get(customer_key)
230
+ record = record.transform_keys(&:to_s) if record.is_a?(Hash)
231
+ return record if record.is_a?(Hash) && record['refreshToken'] != old_refresh_token && record['expiresAt'].is_a?(Integer) && record['expiresAt'] > now
232
+ end
233
+ raise WalletCustomerSessionError.new(status: error.status, code: error.code, request_id: error.request_id, details: error.details,
234
+ message: 'Another refresh of this customer session is in progress; retry shortly.',
235
+ customer_key: customer_key, session_ended: false)
236
+ end
237
+ end
238
+ end
@@ -0,0 +1,340 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Wallet portal for one customer: /api/portal/v1/wallet/me/* and auth/email-change with the merchant-vouched session stored
5
+ # under customer_key (client.wallet.portal(customer_key:, token_store:)).
6
+ #
7
+ # Every call sends Authorization: Bearer <accessToken> and the Ed25519 signature of this client's key.
8
+ # The access token is refreshed when it expires within refresh_skew_seconds (default 30) or when the
9
+ # gateway answers 401 AUTH_CUSTOMER_SESSION_INVALID (the request is then sent once more with the new
10
+ # token: it was refused before any work was done).
11
+ #
12
+ # Errors: WalletCustomerSessionExpiredError / WalletCustomerRefreshReusedError (session_ended: the stored
13
+ # tokens are deleted; start a new session), WalletCustomerSessionBindingError (signed with another key
14
+ # than the one that opened the session), otherwise the gateway's ApiError.
15
+ #
16
+ # Money moves in two steps as on the merchant API: initiate_w2w / pay_qr return { operationId,
17
+ # integrityHash, nonce, otpRequired, stepUpRequired, … }; when a step-up is required,
18
+ # start_operation_step_up(operation_id, { password: }) sends a code bound to the operation and
19
+ # verify_operation_step_up(operation_id, { challengeId:, code: }) returns the single-use trustedActionToken
20
+ # for complete_w2w / complete_qr_pay. Bodies are taken whole and checked against WALLET_PORTAL_ROUTES (an
21
+ # unknown field is a ConfigurationError, never dropped); they take the wire names (String or Symbol;
22
+ # snake_case works too).
23
+ class WalletPortal
24
+ ROUTE = %r{\A/api/portal/v1/wallet/}
25
+ DEFAULT_REFRESH_SKEW_SECONDS = 30
26
+ CUSTOMER_KEY_MAX = 512
27
+
28
+ attr_reader :customer_key, :refresh_skew_seconds, :end_user_ip
29
+
30
+ # end_user_ip: sent as X-Lunixi-End-User-Ip on every call of this portal (IPv4 or IPv6, a signal only).
31
+ def initialize(client, tokens, customer_key:, token_store:, refresh_skew_seconds: DEFAULT_REFRESH_SKEW_SECONDS, end_user_ip: nil)
32
+ unless customer_key.is_a?(String) && !customer_key.strip.empty? && customer_key.length <= CUSTOMER_KEY_MAX
33
+ raise ConfigurationError, "customer_key must be a non-empty string of at most #{CUSTOMER_KEY_MAX} characters."
34
+ end
35
+ unless %i[get set delete].all? { |name| token_store.respond_to?(name) }
36
+ raise ConfigurationError, 'token_store must implement get(customer_key), set(customer_key, record) and delete(customer_key).'
37
+ end
38
+ unless refresh_skew_seconds.is_a?(Integer) && refresh_skew_seconds.between?(0, 600)
39
+ raise ConfigurationError, 'refresh_skew_seconds must be an integer 0-600.'
40
+ end
41
+
42
+ @client = client
43
+ @tokens = tokens
44
+ @token_store = token_store
45
+ @customer_key = customer_key
46
+ @refresh_skew_seconds = refresh_skew_seconds
47
+ @end_user_ip = end_user_ip.nil? ? nil : WalletRules.end_user_ip!(end_user_ip)
48
+ end
49
+
50
+ # The same portal sending the end user's IP (X-Lunixi-End-User-Ip) on every call.
51
+ def with_end_user_ip(end_user_ip)
52
+ self.class.new(@client, @tokens, customer_key: @customer_key, token_store: @token_store,
53
+ refresh_skew_seconds: @refresh_skew_seconds, end_user_ip: end_user_ip)
54
+ end
55
+
56
+ # Session record
57
+
58
+ # Stores the answer of customer_sessions.complete (or of a refresh you made yourself) for this customer.
59
+ # Returns { 'sessionId', 'expiresAt', 'refreshExpiresAt' } (epoch seconds).
60
+ def save_session(issued)
61
+ record = @tokens.save(@customer_key, @token_store, issued)
62
+ record.slice('sessionId', 'expiresAt', 'refreshExpiresAt')
63
+ end
64
+
65
+ # True when a session is stored whose refresh token has not expired.
66
+ def has_session? # rubocop:disable Naming/PredicatePrefix -- public portal API (hasSession in every SDK)
67
+ record = @token_store.get(@customer_key)
68
+ record = record.transform_keys(&:to_s) if record.is_a?(Hash)
69
+ record.is_a?(Hash) && record['refreshExpiresAt'].is_a?(Integer) && record['refreshExpiresAt'] > @tokens.now
70
+ end
71
+
72
+ # Deletes the stored tokens (your logout). It does not revoke anything at the gateway; revoke this
73
+ # installation's access with wallet.customer_sessions.revoke.
74
+ def forget_session
75
+ @token_store.delete(@customer_key)
76
+ nil
77
+ end
78
+
79
+ # Account
80
+
81
+ # Identity, program and wallet provisioning state.
82
+ def get_me # rubocop:disable Naming/AccessorMethodName -- portal operation (same name in every SDK)
83
+ data('getMe')
84
+ end
85
+
86
+ def get_balances # rubocop:disable Naming/AccessorMethodName -- portal operation (same name in every SDK)
87
+ data('getBalances')
88
+ end
89
+
90
+ def list_wallets
91
+ data('listWallets')
92
+ end
93
+
94
+ def get_limits(operation_type: nil, currency: nil)
95
+ data('getLimits', query: { 'operationType' => operation_type, 'currency' => currency })
96
+ end
97
+
98
+ # Current and effective KYC level and what each level unlocks.
99
+ def get_kyc_level # rubocop:disable Naming/AccessorMethodName -- portal operation (same name in every SDK)
100
+ data('getKycLevel')
101
+ end
102
+
103
+ # Operations
104
+
105
+ # A Lunixi::ListPage; statuses may be an Array (sent comma-separated).
106
+ def list_operations(**filters)
107
+ RouteResponse.page(send_route('listOperations', query: filters))
108
+ end
109
+
110
+ def iterate_operations(**filters, &block)
111
+ RouteResponse.each_item(filters, block) { |query| list_operations(**query) }
112
+ end
113
+
114
+ def get_operation(operation_id)
115
+ data('getOperation', params: { 'operationId' => operation_id })
116
+ end
117
+
118
+ def get_operation_receipt(operation_id)
119
+ data('getOperationReceipt', params: { 'operationId' => operation_id })
120
+ end
121
+
122
+ # Top-up
123
+
124
+ # Card top-up into one of the customer's accounts. Render the answer's form or follow its 3-D Secure
125
+ # redirect; the wallet is credited when the card payment completes.
126
+ def start_card_topup(request, idempotency_key: nil)
127
+ data('startCardTopup', body: request, idempotency_key: idempotency_key)
128
+ end
129
+
130
+ def get_topup(operation_id)
131
+ data('getTopup', params: { 'operationId' => operation_id })
132
+ end
133
+
134
+ # Wallet-to-wallet transfer
135
+
136
+ def quote_w2w(request)
137
+ data('quoteW2W', body: request)
138
+ end
139
+
140
+ def initiate_w2w(request, idempotency_key: nil)
141
+ data('initiateW2W', body: request, idempotency_key: idempotency_key)
142
+ end
143
+
144
+ # { integrityHash, nonce } from initiate_w2w, plus otpCode and/or trustedActionToken.
145
+ def complete_w2w(operation_id, request, idempotency_key: nil)
146
+ data('completeW2W', params: { 'operationId' => operation_id }, body: request, idempotency_key: idempotency_key)
147
+ end
148
+
149
+ # Step-up (wallet password + operation code)
150
+
151
+ # Checks the wallet password and sends a code bound to this operation (its amount and beneficiary). The
152
+ # key (8–100 of [A-Za-z0-9_-]) is required. Answer: { requiresOtp, otpPurpose, otpChallengeId,
153
+ # otpExpiresAt, otpCodeLength, otpResendAvailableAt, destinationMasked }.
154
+ # request: { password, locale? }.
155
+ def start_operation_step_up(operation_id, request, idempotency_key: nil)
156
+ data('startOperationStepUp', params: { 'operationId' => operation_id }, body: request, idempotency_key: idempotency_key)
157
+ end
158
+
159
+ # request: { challengeId, code }. Answer: { operationId, trustedActionToken, expiresAt }: the token is
160
+ # single-use and short-lived. The route takes no Idempotency-Key (one given is refused).
161
+ def verify_operation_step_up(operation_id, request, idempotency_key: nil)
162
+ data('verifyOperationStepUp', params: { 'operationId' => operation_id }, body: request, idempotency_key: idempotency_key)
163
+ end
164
+
165
+ # QR payment
166
+
167
+ # Pays a scanned QR: amount only for a static QR.
168
+ def pay_qr(request, idempotency_key: nil)
169
+ data('payQr', body: request, idempotency_key: idempotency_key)
170
+ end
171
+
172
+ # { operationId, integrityHash, nonce } from pay_qr, plus otpCode and/or trustedActionToken.
173
+ def complete_qr_pay(qr_id, request, idempotency_key: nil)
174
+ data('completeQrPay', params: { 'qrId' => qr_id }, body: request, idempotency_key: idempotency_key)
175
+ end
176
+
177
+ # Payment code (shown at the till)
178
+
179
+ # The plain code is only in this answer; a new code revokes the previous one.
180
+ def mint_payment_code(currency)
181
+ data('mintPaymentCode', body: { 'currency' => currency })
182
+ end
183
+
184
+ def revoke_payment_code
185
+ data('revokePaymentCode')
186
+ end
187
+
188
+ # Loyalty, cashback, tier
189
+
190
+ def list_loyalty_programs
191
+ data('listLoyaltyPrograms')
192
+ end
193
+
194
+ def get_loyalty_balance(loyalty_program_id, lot_limit: nil)
195
+ data('getLoyaltyBalance', query: { 'loyaltyProgramId' => loyalty_program_id, 'lotLimit' => lot_limit })
196
+ end
197
+
198
+ def get_loyalty_history(loyalty_program_id, limit: nil)
199
+ data('getLoyaltyHistory', query: { 'loyaltyProgramId' => loyalty_program_id, 'limit' => limit })
200
+ end
201
+
202
+ # Redeems points into a wallet account. request: { loyaltyProgramId, walletAccountId, points }; the key
203
+ # (8–128 characters) is sent in the body as idempotencyKey.
204
+ def redeem_loyalty_points(request, idempotency_key: nil)
205
+ key = WalletInvoker.idempotency_key!(idempotency_key, 'redeemLoyaltyPoints')
206
+ plain = RouteRequest.wire_hash!(request || {}, 'redeemLoyaltyPoints')
207
+ raise ConfigurationError, 'redeemLoyaltyPoints takes the key as idempotency_key:, not in the body.' if plain.key?('idempotencyKey')
208
+
209
+ data('redeemLoyaltyPoints', body: plain.merge('idempotencyKey' => key))
210
+ end
211
+
212
+ def get_cashback(limit: nil)
213
+ data('getCashback', query: { 'limit' => limit })
214
+ end
215
+
216
+ def get_tier # rubocop:disable Naming/AccessorMethodName -- portal operation (same name in every SDK)
217
+ data('getTier')
218
+ end
219
+
220
+ # Phone verification (SMS)
221
+
222
+ # Sends a code by SMS to the identity's phone. Answer: { phoneVerified: false, challengeId,
223
+ # destinationMasked, deliveryChannel: 'SMS', expiresAt, codeLength, resendAvailableAt }, or
224
+ # { phoneVerified: true, phoneVerifiedAt } when it is already verified (no code is sent). 503
225
+ # AUTH_OTP_CHANNEL_UNAVAILABLE while the SMS channel is off. The optional key is 16–64 of [A-Za-z0-9_-].
226
+ # request: { locale? } (an empty body is sent as {}).
227
+ def start_phone_verification(request = {}, idempotency_key: nil)
228
+ data('startPhoneVerification', body: request, idempotency_key: idempotency_key)
229
+ end
230
+
231
+ # request: { challengeId, code }. Answer: { phoneVerified: true, phoneVerifiedAt }. Only the session that
232
+ # started it can complete it. The route takes no Idempotency-Key (one given is refused).
233
+ def complete_phone_verification(request, idempotency_key: nil)
234
+ data('completePhoneVerification', body: request, idempotency_key: idempotency_key)
235
+ end
236
+
237
+ # Wallet e-mail change (wallet password + a code to the current address + a code to the new address)
238
+
239
+ # request: { newEmail, password, locale? }; the key (16–64 of [A-Za-z0-9_-]) is required. Answer: the
240
+ # change request (changeId, phase, destinationMasked …); a code goes to the current address.
241
+ def start_email_change(request, idempotency_key: nil)
242
+ data('startEmailChange', body: request, idempotency_key: idempotency_key)
243
+ end
244
+
245
+ # The change request: changeId, phase (CURRENT | NEW | COMPLETED | EXPIRED …), masks.
246
+ def get_email_change(change_id)
247
+ data('getEmailChange', params: { 'changeId' => change_id })
248
+ end
249
+
250
+ # A new code to the address of the current phase. request: { locale? }.
251
+ def resend_email_change(change_id, request = {}, idempotency_key: nil)
252
+ data('resendEmailChange', params: { 'changeId' => change_id }, body: request, idempotency_key: idempotency_key)
253
+ end
254
+
255
+ # The code sent to the current address (6–10 digits). request: { code, locale? }; a code then goes to the
256
+ # new address.
257
+ def verify_current_email_change(change_id, request, idempotency_key: nil)
258
+ data('verifyCurrentEmailChange', params: { 'changeId' => change_id }, body: request, idempotency_key: idempotency_key)
259
+ end
260
+
261
+ # The code sent to the new address. request: { code, locale? }. On success (phase COMPLETED,
262
+ # reauthRequired: true) the platform ends the customer's sessions: the stored record is deleted and the
263
+ # customer signs in again (codes now go to the new address).
264
+ def complete_email_change(change_id, request, idempotency_key: nil)
265
+ answer = data('completeEmailChange', params: { 'changeId' => change_id }, body: request, idempotency_key: idempotency_key)
266
+ @token_store.delete(@customer_key) if answer.is_a?(Hash) && answer['reauthRequired'] == true
267
+ answer
268
+ end
269
+
270
+ def inspect
271
+ "#<Lunixi::WalletPortal customer_key=#{@customer_key.inspect}>"
272
+ end
273
+
274
+ private
275
+
276
+ def data(name, **)
277
+ RouteResponse.unwrap(send_route(name, **))
278
+ end
279
+
280
+ # Sends one route of WALLET_PORTAL_ROUTES with the customer's bearer token and the client's signature,
281
+ # checked before sending like the merchant wallet routes. A 401 AUTH_CUSTOMER_SESSION_INVALID (access
282
+ # token expired or rotated elsewhere) refreshes once and re-sends; if the fresh token is refused too, the
283
+ # session was revoked: the record is deleted.
284
+ def send_route(name, params: {}, body: nil, query: nil, idempotency_key: nil)
285
+ route = WALLET_PORTAL_ROUTES.fetch(name)
286
+ path = RouteRequest.path!(route['path'], params)
287
+ filters = query.nil? ? {} : WalletRules.query!(name, route, query)
288
+ payload = body_for(name, route, body)
289
+ key = key_for(name, route, idempotency_key)
290
+ token = @tokens.access_token(@customer_key, @token_store, @refresh_skew_seconds)
291
+ attempt = 0
292
+ begin
293
+ @client.request(route['method'], path, body: payload, query: filters, idempotency_key: key, bearer: token, end_user_ip: @end_user_ip)
294
+ rescue ApiError => e
295
+ expired = e.status == 401 && e.code == WalletCustomerSessionErrorCode::CUSTOMER_SESSION_INVALID
296
+ if expired && attempt.zero?
297
+ attempt += 1
298
+ token = @tokens.refresh(@customer_key, @token_store, token).fetch('accessToken')
299
+ retry
300
+ end
301
+ typed = WalletCustomerTokens.typed_error(e, customer_key: @customer_key, session_ended: expired ? true : nil)
302
+ @token_store.delete(@customer_key) if typed.is_a?(WalletCustomerSessionError) && typed.session_ended
303
+ raise typed
304
+ end
305
+ end
306
+
307
+ def body_for(name, route, body)
308
+ return nil unless route['method'] == 'POST' && (route.key?('required') || route.key?('optional'))
309
+
310
+ plain = RouteRequest.fields!(body || {}, route['required'] || [], route['optional'] || [], name)
311
+ plain = WalletRules.apply!(name, route['rules'], plain) if route['rules']
312
+ (route['passThrough'] || []).each do |field|
313
+ raise ConfigurationError, "#{name}.#{field} must be a Hash." if plain.key?(field) && !plain[field].is_a?(Hash)
314
+ end
315
+ WALLET_PORTAL_AMOUNT_FIELDS.each do |field|
316
+ plain[field] = WalletInvoker.amount!(plain[field], "#{name}.#{field}") if plain.key?(field)
317
+ end
318
+ plain
319
+ end
320
+
321
+ def key_for(name, route, key)
322
+ pattern = route['idempotencyKeyPattern']
323
+ return portal_key!(name, key, pattern) if route['idempotencyKey']
324
+ return nil if key.nil?
325
+ raise ConfigurationError, "#{name} does not take an Idempotency-Key." unless route['idempotencyKeyOptional']
326
+
327
+ portal_key!(name, key, pattern)
328
+ end
329
+
330
+ def portal_key!(name, key, pattern)
331
+ return WalletInvoker.idempotency_key!(key, name) unless pattern
332
+
333
+ value = key.is_a?(String) ? key.strip : ''
334
+ raise ConfigurationError, "A stable Idempotency-Key is required for #{name}. Reuse the same key when retrying the same operation." if value.empty?
335
+ raise ConfigurationError, "Idempotency-Key for #{name} has an invalid format." unless value.match?(pattern)
336
+
337
+ value
338
+ end
339
+ end
340
+ end