lunixi-sdk 2.0.2 → 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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +28 -0
- data/README.md +43 -4
- data/README.tr.md +28 -3
- data/docs/card-rewards.md +21 -0
- data/lib/lunixi/bank_connect.rb +132 -15
- data/lib/lunixi/bank_connect_filters.rb +13 -3
- data/lib/lunixi/bank_connect_pos.rb +165 -0
- data/lib/lunixi/bank_connect_values.rb +127 -5
- data/lib/lunixi/card_requests.rb +9 -1
- data/lib/lunixi/client.rb +38 -14
- data/lib/lunixi/direct_method_payment_request.rb +24 -2
- data/lib/lunixi/errors.rb +49 -0
- data/lib/lunixi/fraud.rb +3 -2
- data/lib/lunixi/fraud_uk_claims.rb +127 -0
- data/lib/lunixi/fraud_values.rb +46 -0
- data/lib/lunixi/marketplace.rb +2 -0
- data/lib/lunixi/payment_link_rules.rb +13 -1
- data/lib/lunixi/payment_link_values.rb +4 -0
- data/lib/lunixi/payment_links.rb +3 -1
- data/lib/lunixi/payment_values.rb +22 -2
- data/lib/lunixi/payments.rb +62 -6
- data/lib/lunixi/product_webhooks.rb +17 -1
- data/lib/lunixi/refund_to_wallet.rb +94 -0
- data/lib/lunixi/route_table.rb +10 -5
- data/lib/lunixi/routing_pin.rb +247 -0
- data/lib/lunixi/sanction.rb +77 -17
- data/lib/lunixi/sanction_batch.rb +215 -0
- data/lib/lunixi/sanction_values.rb +289 -5
- data/lib/lunixi/split_payment.rb +17 -2
- data/lib/lunixi/subscription_routing.rb +70 -0
- data/lib/lunixi/subscription_values.rb +26 -3
- data/lib/lunixi/subscriptions.rb +22 -2
- data/lib/lunixi/version.rb +1 -1
- data/lib/lunixi/wallet.rb +43 -7
- data/lib/lunixi/wallet_customer_sessions.rb +75 -0
- data/lib/lunixi/wallet_customer_tokens.rb +238 -0
- data/lib/lunixi/wallet_portal.rb +340 -0
- data/lib/lunixi/wallet_portal_routes.rb +171 -0
- data/lib/lunixi/wallet_routes.rb +28 -3
- data/lib/lunixi/wallet_rules.rb +131 -0
- data/lib/lunixi/wallet_values.rb +151 -0
- data/lib/lunixi.rb +12 -0
- metadata +14 -1
data/lib/lunixi/wallet.rb
CHANGED
|
@@ -18,11 +18,16 @@ module Lunixi
|
|
|
18
18
|
# WALLET_NOT_FOUND otherwise).
|
|
19
19
|
#
|
|
20
20
|
# Answers are the envelope's data; lists return a Lunixi::ListPage.
|
|
21
|
+
#
|
|
22
|
+
# Customer sessions: customer_sessions opens a merchant-vouched session for an end user created with
|
|
23
|
+
# customerContact (permission wallet:customer-session:create); portal(customer_key:, token_store:) then
|
|
24
|
+
# calls the customer's own portal routes with that session.
|
|
21
25
|
class Wallet
|
|
22
26
|
attr_reader :programs, :end_users, :wallets, :deposits, :corporate, :fees, :transfers, :withdrawals, :operations, :topups,
|
|
23
|
-
:payments, :qr, :bulk_payouts
|
|
27
|
+
:payments, :qr, :bulk_payouts, :customer_sessions
|
|
24
28
|
|
|
25
|
-
def initialize(client)
|
|
29
|
+
def initialize(client, clock: -> { Time.now.utc }, sleeper: ->(seconds) { sleep(seconds) })
|
|
30
|
+
@client = client
|
|
26
31
|
@invoker = WalletInvoker.new(client)
|
|
27
32
|
@programs = WalletPrograms.new(@invoker)
|
|
28
33
|
@end_users = WalletEndUsers.new(@invoker)
|
|
@@ -37,6 +42,10 @@ module Lunixi
|
|
|
37
42
|
@payments = WalletPayments.new(@invoker)
|
|
38
43
|
@qr = WalletQr.new(@invoker)
|
|
39
44
|
@bulk_payouts = WalletBulkPayouts.new(@invoker)
|
|
45
|
+
@customer_sessions = WalletCustomerSessions.new(@invoker)
|
|
46
|
+
# One refresher per client: the single-flight lock is per customer across every portal client this
|
|
47
|
+
# Lunixi::Client hands out.
|
|
48
|
+
@customer_tokens = WalletCustomerTokens.new(@customer_sessions, clock: clock, sleeper: sleeper)
|
|
40
49
|
end
|
|
41
50
|
|
|
42
51
|
# Checks that the key reaches the wallet (signature, product, a wallet:*:manage permission).
|
|
@@ -44,6 +53,20 @@ module Lunixi
|
|
|
44
53
|
@invoker.data('ping')
|
|
45
54
|
end
|
|
46
55
|
|
|
56
|
+
# The customer's own portal routes (/api/portal/v1/wallet/me/*) with a merchant-vouched session. Every
|
|
57
|
+
# call carries Authorization: Bearer <accessToken> and the Ed25519 signature of this client's key (the
|
|
58
|
+
# key that opened the session); the merchant access token is never sent.
|
|
59
|
+
#
|
|
60
|
+
# customer_key names the customer in token_store (for example "#{program_id}:#{external_customer_id}");
|
|
61
|
+
# token_store keeps the session tokens (get / set / delete, optional with_lock; encrypted at rest by
|
|
62
|
+
# you). The access token is refreshed when it expires within refresh_skew_seconds (0–600) or the
|
|
63
|
+
# gateway reports it expired, one refresh at a time per customer.
|
|
64
|
+
# end_user_ip: the end user's IP (IPv4 or IPv6), sent as X-Lunixi-End-User-Ip on every portal call.
|
|
65
|
+
def portal(customer_key:, token_store:, refresh_skew_seconds: WalletPortal::DEFAULT_REFRESH_SKEW_SECONDS, end_user_ip: nil)
|
|
66
|
+
WalletPortal.new(@client, @customer_tokens, customer_key: customer_key, token_store: token_store,
|
|
67
|
+
refresh_skew_seconds: refresh_skew_seconds, end_user_ip: end_user_ip)
|
|
68
|
+
end
|
|
69
|
+
|
|
47
70
|
def inspect
|
|
48
71
|
'#<Lunixi::Wallet>'
|
|
49
72
|
end
|
|
@@ -84,15 +107,19 @@ module Lunixi
|
|
|
84
107
|
end
|
|
85
108
|
|
|
86
109
|
# The raw answer of one route. params: path segments by name; body: the request Hash; query: filters.
|
|
87
|
-
|
|
110
|
+
# end_user_ip is sent as X-Lunixi-End-User-Ip; max_retries: 0 sends a single attempt; reauth: false
|
|
111
|
+
# turns the 401 re-authentication off (see Client#request).
|
|
112
|
+
def call(name, params: {}, body: nil, query: nil, idempotency_key: nil, end_user_ip: nil, max_retries: nil, reauth: true)
|
|
88
113
|
route = WALLET_ROUTES.fetch(name)
|
|
89
114
|
path = RouteRequest.path!(route['path'], params)
|
|
90
|
-
filters =
|
|
115
|
+
filters = filters_for(name, route, query)
|
|
91
116
|
payload = body_for(name, route, body)
|
|
92
117
|
key = key_for(name, route, idempotency_key)
|
|
118
|
+
ip = WalletRules.end_user_ip!(end_user_ip) unless end_user_ip.nil?
|
|
93
119
|
binary = route['binary'] == true
|
|
94
120
|
@client.request(route['method'], path, body: payload, query: filters, idempotency_key: key, binary: binary,
|
|
95
|
-
accept: binary ? QR_IMAGE_ACCEPT : Client::ACCEPT_JSON
|
|
121
|
+
accept: binary ? QR_IMAGE_ACCEPT : Client::ACCEPT_JSON,
|
|
122
|
+
max_retries: max_retries, reauth: reauth, end_user_ip: ip)
|
|
96
123
|
end
|
|
97
124
|
|
|
98
125
|
def data(name, **)
|
|
@@ -116,6 +143,12 @@ module Lunixi
|
|
|
116
143
|
|
|
117
144
|
private
|
|
118
145
|
|
|
146
|
+
def filters_for(name, route, query)
|
|
147
|
+
return WalletRules.query!(name, route, query) if route.key?('rules') || route.key?('requiredQuery')
|
|
148
|
+
|
|
149
|
+
RouteRequest.query!(query, route['query'] || [], name)
|
|
150
|
+
end
|
|
151
|
+
|
|
119
152
|
def body_for(name, route, body)
|
|
120
153
|
unless route.key?('required') || route.key?('optional')
|
|
121
154
|
raise ConfigurationError, "#{name} takes no body." unless body.nil? || body == {}
|
|
@@ -129,6 +162,8 @@ module Lunixi
|
|
|
129
162
|
nested = WALLET_NESTED_FIELDS["#{name}.#{field}"]
|
|
130
163
|
plain[field] = rows!(plain[field], nested, "#{name}.#{field}") if nested
|
|
131
164
|
end
|
|
165
|
+
plain = WalletRules.apply!(name, route['rules'], plain) if route['rules']
|
|
166
|
+
plain['customerContact'] = WalletRules.customer_contact!(name, plain) if plain.key?('customerContact')
|
|
132
167
|
plain
|
|
133
168
|
end
|
|
134
169
|
|
|
@@ -145,9 +180,10 @@ module Lunixi
|
|
|
145
180
|
|
|
146
181
|
def key_for(name, route, key)
|
|
147
182
|
return self.class.idempotency_key!(key, name) if route['idempotencyKey']
|
|
148
|
-
|
|
183
|
+
return nil if key.nil?
|
|
184
|
+
raise ConfigurationError, "#{name} does not take an Idempotency-Key." unless route['idempotencyKeyOptional']
|
|
149
185
|
|
|
150
|
-
|
|
186
|
+
self.class.idempotency_key!(key, name)
|
|
151
187
|
end
|
|
152
188
|
end
|
|
153
189
|
end
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Lunixi
|
|
4
|
+
# wallet.customer_sessions: the merchant-vouched customer session (/api/v1/wallet/customer-sessions).
|
|
5
|
+
#
|
|
6
|
+
# The end user must have been created with customerContact (else 409 WALLET_CUSTOMER_NOT_ENROLLED). The
|
|
7
|
+
# code goes to that pinned contact over the channel the platform picks; your signature replaces the
|
|
8
|
+
# password on first activation, never the code. The key needs wallet:customer-session:create and
|
|
9
|
+
# wallet:enduser:read; a missing one is always 403 auth.permission.forbidden.
|
|
10
|
+
#
|
|
11
|
+
# 1. start sends the code and returns { challengeId, destinationMasked, deliveryChannel, expiresAt,
|
|
12
|
+
# codeLength, resendAvailableAt, passwordSetupRequired, otpPurpose }. An ACTIVE customer sends password
|
|
13
|
+
# (the wallet password): signing in again, or an end user whose enrollment answered LINKED_EXISTING (an
|
|
14
|
+
# existing, phone-verified wallet identity; the code then goes to that identity's own address).
|
|
15
|
+
# 2. complete with the code (and newPassword when passwordSetupRequired) returns the tokens. Store them
|
|
16
|
+
# with wallet.portal(customer_key:, token_store:).save_session(result).
|
|
17
|
+
# 3. refresh rotates them; the portal does it for you, one at a time per customer (a reused refresh token
|
|
18
|
+
# revokes the session).
|
|
19
|
+
# 4. revoke ends this installation's access (user deleted, wallet detached, credentials changed), not on
|
|
20
|
+
# logout.
|
|
21
|
+
#
|
|
22
|
+
# end_user_ip: is sent as X-Lunixi-End-User-Ip (a signal only). All five calls are sent once: no automatic
|
|
23
|
+
# retry after a 5xx or a network error (a code must not go out twice, a code or a refresh token must not
|
|
24
|
+
# be burnt), and a 401 is a verdict on the request (wrong password, binding), never answered by re-sending.
|
|
25
|
+
class WalletCustomerSessions
|
|
26
|
+
def initialize(invoker)
|
|
27
|
+
@invoker = invoker
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# Sends the code to the pinned contact. The Idempotency-Key is required.
|
|
31
|
+
def start(request, idempotency_key: nil, end_user_ip: nil)
|
|
32
|
+
send_route('startCustomerSession', body: request, idempotency_key: idempotency_key, end_user_ip: end_user_ip, max_retries: 0)
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# Sends the same challenge's code again (resendAvailableAt tells when). The key is optional.
|
|
36
|
+
def resend(request, idempotency_key: nil, end_user_ip: nil)
|
|
37
|
+
send_route('resendCustomerSession', body: request, idempotency_key: idempotency_key, end_user_ip: end_user_ip, max_retries: 0)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Consumes the code. Sent once, never retried by the SDK: the code is consumed on the first answer. 503
|
|
41
|
+
# WALLET_CUSTOMER_SESSION_NOT_ISSUED (WalletCustomerSessionNotIssuedError) = no session was opened;
|
|
42
|
+
# start again.
|
|
43
|
+
def complete(request, idempotency_key: nil, end_user_ip: nil)
|
|
44
|
+
send_route('completeCustomerSession', body: request, idempotency_key: idempotency_key, end_user_ip: end_user_ip, max_retries: 0)
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# Rotates the tokens; signed with the key that opened the session. Sent once: re-sending a refresh
|
|
48
|
+
# token the gateway already rotated revokes the session (WalletCustomerRefreshReusedError). Prefer the
|
|
49
|
+
# portal, which serialises refreshes per customer.
|
|
50
|
+
def refresh(refresh_token, end_user_ip: nil)
|
|
51
|
+
send_route('refreshCustomerSession', body: { 'refreshToken' => refresh_token }, end_user_ip: end_user_ip, max_retries: 0)
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# { revoked: true }. target: programId, externalCustomerId, clientInstanceId and an optional reason
|
|
55
|
+
# (WalletCustomerSessionRevokeReason; the gateway's default is WALLET_DETACHED). Only this installation's
|
|
56
|
+
# device and its sessions are revoked; the wallet link stays. Idempotent: 503
|
|
57
|
+
# WALLET_CUSTOMER_REVOKE_INCOMPLETE (WalletCustomerRevokeIncompleteError) = send the same call again.
|
|
58
|
+
def revoke(target, end_user_ip: nil)
|
|
59
|
+
send_route('revokeCustomerSession', query: target, end_user_ip: end_user_ip, max_retries: 0)
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
def inspect
|
|
63
|
+
'#<Lunixi::WalletCustomerSessions>'
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
private
|
|
67
|
+
|
|
68
|
+
# A customer session route: no 401 re-authentication; typed session errors.
|
|
69
|
+
def send_route(name, **)
|
|
70
|
+
@invoker.data(name, reauth: false, **)
|
|
71
|
+
rescue ApiError => e
|
|
72
|
+
raise WalletCustomerTokens.typed_error(e)
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
end
|
|
@@ -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
|