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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 15d0bfe9861d614a8fbd5b4ba72ca9d9257409abab50470417e79ebfb645c5da
4
- data.tar.gz: f3f689285448bd4795fe36566d69db76d7fd515b3b12e3e856cdea0d5a46baef
3
+ metadata.gz: a49ede00de8d815ca3caedfbaa55b3c0274835bf5248fcc0832556e8e5715cfb
4
+ data.tar.gz: af2c21da9fc7e9c640864e946acd84e5e264f368d3654535f877a17080b61288
5
5
  SHA512:
6
- metadata.gz: 7d918280c8b8f693dbcd4afb36c6d98ca511ee2eb38bc0499e3fc488a19806edc3201309f66314da019dba11ef9bec3d6d29ad0268f04bde184a1484cf753249
7
- data.tar.gz: 5224e1fae4f1c61a0b0f3dcd33d5bbde4c5f9f8db7179936ef7daa284da023e5894a326446b4e7fb1d6ae18f4cd2dcdf301129a8ca686f5ca56fa88354c3fdfb
6
+ metadata.gz: 7d7940dc59fbba9f8c5408c9cb649361c16105b205dc3f5aba7064f4ab96957e3f70acc7364760539167dec7797251ab50b5d53910c0e611081234f9130e33d3
7
+ data.tar.gz: 9d4c4d24a52f0b47e82c32146926924408de946d775435e0129619dfd6e675ce924916ac62fcf3afbbd941bbacd055fdb43b1f8ba655ab39eeedce6708c35b6c
data/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.3.0 — 2026-12-03
4
+
5
+ - Payments: refund to wallet. `payments.refund_to_wallet(payment_id, { amount:, reason:, programId:, customerId: }, idempotency_key:)` (`POST /api/v1/payments/{id}/refund-to-wallet`, permission `payment:refund-to-wallet`, signed, key required as for `refund`; `amount` a positive minor-unit string, left out = the remaining refundable amount and no body is sent; no wallet user found → the refund goes to the card; marketplace / split payments refused) and the read-only `payments.refund_to_wallet_eligibility(payment_id, { customerId:, programId: })` (`POST …/refund-to-wallet/eligibility`, no key, an empty request sends `{}`) → `{ eligible, matchedBy, matchStrength, maskedTarget, defaultDestination, reason }`. Keys are String or Symbol, camelCase or snake_case; other fields raise `ConfigurationError` before sending. New `Lunixi::REFUND_TO_WALLET_FIELDS`, `Lunixi::REFUND_TO_WALLET_ELIGIBILITY_FIELDS`, `Lunixi::RefundToWalletMatchStrength`, `Lunixi::RefundToWalletMatchedBy`, `Lunixi::RefundToWalletEligibilityReason`, `Lunixi::WALLET_PARTIAL_REFUND_UNSUPPORTED` (`payment.refund.wallet_partial_unsupported`: a payment paid with the wallet is refunded only in full).
6
+ - Wallet: `wallet.end_users.create` takes `customerContact: { email: }`; it pins the address the customer session code goes to (requires `externalCustomerId` and `accountType: PERSONAL`; checked before sending). The answer adds `customerContact` and `enrollment` (`Lunixi::WalletCustomerEnrollmentStatus`).
7
+ - Wallet: new `wallet.customer_sessions` (permission `wallet:customer-session:create`): `start` (Idempotency-Key required), `resend`, `complete`, `refresh`, `revoke` for `/api/v1/wallet/customer-sessions`, with `end_user_ip:` (`X-Lunixi-End-User-Ip`). Fields are checked before sending (`Lunixi::WALLET_CUSTOMER_SESSION_RULES`); there is no channel parameter. All five calls are sent once (no automatic retry after a 5xx or a network error) and none answers a 401 by sending again. `revoke` is a signed `DELETE` with the target in the query.
8
+ - Wallet: new portal client `wallet.portal(customer_key:, token_store:, refresh_skew_seconds: 30)` for the customer's own routes (`/api/portal/v1/wallet/me/*`, `Lunixi::WALLET_PORTAL_ROUTES`): every call carries `Authorization: Bearer <accessToken>` and the Ed25519 signature of the same key, never the merchant token. Bodies are taken whole and checked against the route table (an unknown field, or a key on a route that takes none, raises `ConfigurationError`). Account, balances, wallets, limits, KYC level, operations and receipts, card top-up, wallet-to-wallet transfer with the password + operation-code step-up, QR payment, payment code, loyalty, cashback, tier, phone verification by SMS and the wallet e-mail change (`start_email_change`, `get_email_change`, `resend_email_change`, `verify_current_email_change`, `complete_email_change`; a `reauthRequired: true` completion deletes the stored session). `end_user_ip:` / `with_end_user_ip` sends `X-Lunixi-End-User-Ip` on every portal call.
9
+ - Wallet: pluggable token store (`get` / `set` / `delete`, optional `with_lock`; you encrypt the records), `Lunixi::InMemoryWalletCustomerTokenStore`, and automatic refresh, one at a time per customer; a 409 `AUTH_REFRESH_IN_PROGRESS` waits for the other process (0.25 / 0.5 / 1 / 1.5 s) instead of sending the refresh token again.
10
+ - New errors `WalletCustomerSessionError` (`session_ended?`, `customer_key`), `WalletCustomerSessionBindingError`, `WalletCustomerRefreshReusedError`, `WalletCustomerSessionExpiredError`, `WalletCustomerSessionNotIssuedError`, `WalletCustomerRevokeIncompleteError`; values `WalletCustomerSessionErrorCode` (only the codes the gateway returns, `AUTH_UPSTREAM_ERROR` included), `WALLET_CUSTOMER_PASSWORD_POLICY_CODES`, `WalletCustomerSessionRevokeReason`, `WalletCustomerSessionDeliveryChannel`, `WalletCustomerSessionOtpPurpose`, `WalletCustomerIdentityStatus`, `WalletCustomerAttachStatus`.
11
+ - `Client#request` takes `bearer:`, `reauth:` and `end_user_ip:`.
12
+
3
13
  ## 2.2.1 — 2026-12-03
4
14
 
5
15
  - Development dependencies: `websocket-driver` 0.9.2 (0.8.2 has a critical advisory, GHSA-pf93-24xc-xgxc). The gem itself is unchanged.
data/README.md CHANGED
@@ -96,6 +96,7 @@ The shared Lunixi form owns enabled payment methods and supports the methods con
96
96
  | Address dictionary | `reference.list_provinces`, `reference.list_districts(province_code)`, `reference.list_neighborhoods(district_code)` |
97
97
  | Capture/preauthorization | `payments.capture(id, idempotency_key:)` |
98
98
  | Full/partial refund | `payments.refund(id, idempotency_key:, reason: nil)` |
99
+ | Refund to wallet | `payments.refund_to_wallet(id, { amount:, reason:, programId:, customerId: }, idempotency_key:)` (POST `/payments/{id}/refund-to-wallet`, signed, permission `payment:refund-to-wallet`; a captured LIVE payment to the buyer's wallet; `customerId` = STRONG match, else the order's phone = WEAK; no wallet user → card; marketplace / split refused; empty request = remaining amount, no body), `payments.refund_to_wallet_eligibility(id, { customerId:, programId: })` (POST `…/refund-to-wallet/eligibility`, signed, read-only, no key) → `eligible`, `matchedBy`, `matchStrength`, `maskedTarget`, `defaultDestination` (`CARD`), `reason` |
99
100
  | Void authorization | `payments.void(id, idempotency_key:)` |
100
101
  | Split payment (1–5 legs) | `payments.split(body, idempotency_key:)` |
101
102
  | Split status/list/refund | `payments.get_split(id)`, `payments.list_splits(**filters)`, `payments.refund_split(id, amount:, idempotency_key:, reason: nil)` |
@@ -111,7 +112,7 @@ The shared Lunixi form owns enabled payment methods and supports the methods con
111
112
  | Physical POS payments | `physical_pos.create_payment(request, idempotency_key:)`, `create_reversal(payment_id, request, idempotency_key:)`, `cancel_payment`, `get_payment`, `list_payments`, `list_transactions`, `get_transaction`, `list_ambiguous_payments` |
112
113
  | Physical POS reports and end-of-day | `physical_pos.get_sales_summary`, `get_tax_summary`, `list_settlements`, `start_settlement(device_id, idempotency_key: nil)`, `list_settlement_runs`, `get_settlement_run` |
113
114
  | Physical POS management | `physical_pos_management` stores, registers, terminals (bank and provider rows, device links), devices and identity keys, end-of-day policies, catalog and overview |
114
- | Wallet | `wallet.ping`, `wallet.end_users`, `wallets`, `deposits`, `corporate`, `fees`, `transfers`, `withdrawals`, `operations`, `topups`, `payments`, `qr`, `bulk_payouts` |
115
+ | Wallet | `wallet.ping`, `wallet.end_users`, `wallets`, `deposits`, `corporate`, `fees`, `transfers`, `withdrawals`, `operations`, `topups`, `payments`, `qr`, `bulk_payouts`, `customer_sessions`, `wallet.portal` |
115
116
  | Bank accounts | `bank_connect.list_banks`, `list_connections`, `get_connection`, `list_accounts`, `get_account`, `request_sync`, `list_balances`, `list_transactions`, `get_transaction` |
116
117
  | Bank transfers and FX | `bank_connect.transfers.list_purposes`, `preview(request)`, `create(request, idempotency_key: nil)`, `list`, `get`; `bank_connect.transfer_recipients.list`, `iterate`, `create`, `update(recipient_id, changes)`, `delete`; `bank_connect.fx.list_rates`, `create_quote`, `create_order(request, idempotency_key: nil)`, `list_orders`, `get_order` |
117
118
  | POS accounts (bank records) | `bank_connect.pos_accounts.list_accounts`, `get_account`, `list_terminals`, `list_transactions`, `list_statement`, `get_day_summary(pos_account_id, business_date)`, `request_sync` (and the `iterate_*` forms) |
@@ -279,6 +280,24 @@ lunixi.wallet.transfers.complete_w2w(step['operationId'], { endUserId: end_user_
279
280
 
280
281
  Money moves in two steps: `initiate_*` reserves the limit, `complete_*` commits it with the same `integrityHash` and `nonce` (the SDK puts `operationId` in the body). Lists return `Lunixi::ListPage` (`items`, `next_cursor`, `has_more?`); `iterate` walks every page. `qr.image` returns the image bytes. `end_users.freeze_end_user(end_user_id, ...)` freezes an end user (named so that `Object#freeze` keeps its meaning).
281
282
 
283
+ ### Customer session and portal
284
+
285
+ An end user created with `customerContact: { email: }` (requires `externalCustomerId` and `accountType: 'PERSONAL'`; the address is pinned for good) can open a merchant-vouched customer session. The key needs `wallet:customer-session:create`; a missing permission is 403 `auth.permission.forbidden`. The code goes to the pinned contact over the channel the platform picks: there is no channel parameter.
286
+
287
+ ```ruby
288
+ target = { programId: program_id, externalCustomerId: customer.id, clientInstanceId: installation_id }
289
+ started = lunixi.wallet.customer_sessions.start(target.merge(clientLabel: 'Mağaza: example.com', locale: 'tr'),
290
+ idempotency_key: login.key, end_user_ip: request.remote_ip)
291
+ tokens = lunixi.wallet.customer_sessions.complete(target.merge(challengeId: started['challengeId'], code: params[:code]))
292
+ portal = lunixi.wallet.portal(customer_key: "#{program_id}:#{customer.id}", token_store: MyEncryptedTokenStore.new)
293
+ portal.save_session(tokens)
294
+ portal.get_balances
295
+ ```
296
+
297
+ `start` requires an `Idempotency-Key`; `resend` and `complete` send one only when you pass it; `refresh` and `revoke` take none. All five calls are sent once (no automatic retry after a 5xx or a network error) and none answers a 401 by sending again. `revoke(target.merge(reason: Lunixi::WalletCustomerSessionRevokeReason::USER_DELETED))` is a signed `DELETE` with the target in the query. Fields are checked before sending (`Lunixi::WALLET_CUSTOMER_SESSION_RULES`: uuids, `clientInstanceId`, `clientLabel`, `locale`, `code` 4–10 digits, `password` 1–256, `newPassword` 8–256, `refreshToken`, `reason`); an unknown field such as `otpChannel` raises `ConfigurationError`.
298
+
299
+ `wallet.portal` calls `/api/portal/v1/wallet/me/*` (`/api/portal/v1/wallet/auth/email-change` too, `Lunixi::WALLET_PORTAL_ROUTES`; bodies are taken whole and checked against it: an unknown field, or a key on a route that takes none, raises `ConfigurationError`) with `Authorization: Bearer <accessToken>` and the signature of the same key; the merchant token is never sent. `end_user_ip:` (or `portal.with_end_user_ip(ip)`) sends the end user's IP as `X-Lunixi-End-User-Ip` on every call. The wallet e-mail change runs `start_email_change` (wallet password, a key of 16–64 `[A-Za-z0-9_-]`) → `verify_current_email_change` (code to the current address) → `complete_email_change` (code to the new address); its `reauthRequired: true` answer deletes the stored session (sign in again). The token store implements `get(customer_key)`, `set(customer_key, record)`, `delete(customer_key)` and, when several processes share it, `with_lock(customer_key) { … }`; encrypt the records yourself (`Lunixi::InMemoryWalletCustomerTokenStore` is for tests and single processes). The access token is refreshed `refresh_skew_seconds` (default 30) before it expires or after a 401 `AUTH_CUSTOMER_SESSION_INVALID`, one refresh at a time per customer; a 409 `AUTH_REFRESH_IN_PROGRESS` waits for the other process instead of sending the refresh token again. Errors: `WalletCustomerSessionExpiredError` and `WalletCustomerRefreshReusedError` (`session_ended?`: the record is deleted, start a new session), `WalletCustomerSessionBindingError` (signed with another key; the record is kept), `WalletCustomerSessionNotIssuedError` (503: start again), `WalletCustomerRevokeIncompleteError` (503: send the same revoke again). Codes are in `Lunixi::WalletCustomerSessionErrorCode`.
300
+
282
301
  ## Bank accounts, transfers and FX
283
302
 
284
303
  `client.bank_connect` reads your connected bank accounts, balances and transactions; bank connections are made in the Lunixi dashboard. Every call is signed and the key decides the environment. Filters are checked before sending: values in their sets, `limit` 1–100, at most 100 account ids, minor-unit strings for `minAmountMinor` / `maxAmountMinor`, and `bookedFrom` (inclusive) / `bookedTo` (exclusive) at most 92 days apart, `bookedTo` only with `bookedFrom`.
data/README.tr.md CHANGED
@@ -94,6 +94,7 @@ HTTP 2xx, token, dönüş sayfası veya devam eden split durumu tahsilat kanıt
94
94
  | Adres sözlüğü | `reference.list_provinces`, `reference.list_districts(province_code)`, `reference.list_neighborhoods(district_code)` |
95
95
  | Capture | `payments.capture(id, idempotency_key:)` |
96
96
  | Tam/kısmi iade | `payments.refund(id, idempotency_key:, reason: nil)` |
97
+ | Cüzdana iade | `payments.refund_to_wallet(id, { amount:, reason:, programId:, customerId: }, idempotency_key:)` (POST `/payments/{id}/refund-to-wallet`, imzalı, `payment:refund-to-wallet` izni; tahsil edilmiş LIVE ödemeyi alıcının cüzdanına iade eder; `customerId` = STRONG eşleşme, yoksa siparişteki telefon = WEAK; cüzdan kullanıcısı bulunamazsa iade karta gider; marketplace / split ödemeler reddedilir; boş istek = kalan tutar, gövde gönderilmez), `payments.refund_to_wallet_eligibility(id, { customerId:, programId: })` (POST `…/refund-to-wallet/eligibility`, imzalı, salt okuma, anahtarsız) → `eligible`, `matchedBy`, `matchStrength`, `maskedTarget`, `defaultDestination` (`CARD`), `reason` |
97
98
  | Provizyon iptali | `payments.void(id, idempotency_key:)` |
98
99
  | Çoklu ödeme | `payments.split(body, idempotency_key:)` |
99
100
  | Split durum/liste/iade | `payments.get_split(id)`, `payments.list_splits(**filters)`, `payments.refund_split(id, amount:, idempotency_key:, reason: nil)` |
@@ -109,7 +110,7 @@ HTTP 2xx, token, dönüş sayfası veya devam eden split durumu tahsilat kanıt
109
110
  | Fiziki POS ödemeleri | `physical_pos.create_payment(request, idempotency_key:)`, `create_reversal(payment_id, request, idempotency_key:)`, `cancel_payment`, `get_payment`, `list_payments`, `list_transactions`, `get_transaction`, `list_ambiguous_payments` |
110
111
  | Fiziki POS raporları ve gün sonu | `physical_pos.get_sales_summary`, `get_tax_summary`, `list_settlements`, `start_settlement(device_id, idempotency_key: nil)`, `list_settlement_runs`, `get_settlement_run` |
111
112
  | Fiziki POS yönetimi | `physical_pos_management` mağazalar, kasalar, terminaller (banka ve sağlayıcı satırları, cihaz bağlantıları), cihazlar ve kimlik anahtarları, gün sonu politikaları, katalog ve genel görünüm |
112
- | Cüzdan | `wallet.ping`, `wallet.end_users`, `wallets`, `deposits`, `corporate`, `fees`, `transfers`, `withdrawals`, `operations`, `topups`, `payments`, `qr`, `bulk_payouts` |
113
+ | Cüzdan | `wallet.ping`, `wallet.end_users`, `wallets`, `deposits`, `corporate`, `fees`, `transfers`, `withdrawals`, `operations`, `topups`, `payments`, `qr`, `bulk_payouts`, `customer_sessions`, `wallet.portal` |
113
114
  | Banka hesapları | `bank_connect.list_banks`, `list_connections`, `get_connection`, `list_accounts`, `get_account`, `request_sync`, `list_balances`, `list_transactions`, `get_transaction` |
114
115
  | Banka transferleri ve döviz | `bank_connect.transfers.list_purposes`, `preview(request)`, `create(request, idempotency_key: nil)`, `list`, `get`; `bank_connect.transfer_recipients.list`, `iterate`, `create`, `update(recipient_id, changes)`, `delete`; `bank_connect.fx.list_rates`, `create_quote`, `create_order(request, idempotency_key: nil)`, `list_orders`, `get_order` |
115
116
  | POS hesapları (banka kayıtları) | `bank_connect.pos_accounts.list_accounts`, `get_account`, `list_terminals`, `list_transactions`, `list_statement`, `get_day_summary(pos_account_id, business_date)`, `request_sync` (ve `iterate_*` biçimleri) |
@@ -270,6 +271,14 @@ lunixi.wallet.transfers.complete_w2w(step['operationId'], { endUserId: end_user_
270
271
 
271
272
  Para iki adımda hareket eder: `initiate_*` limiti ayırır, `complete_*` aynı `integrityHash` ve `nonce` ile kesinleştirir (SDK `operationId` değerini gövdeye koyar). Listeler `Lunixi::ListPage` döndürür (`items`, `next_cursor`, `has_more?`); `iterate` bütün sayfaları gezer. `qr.image` görsel baytlarını döndürür. `end_users.freeze_end_user(end_user_id, ...)` bir son kullanıcıyı dondurur (`Object#freeze` anlamını korusun diye bu adı taşır).
272
273
 
274
+ ### Müşteri oturumu ve portal
275
+
276
+ `customerContact: { email: }` ile oluşturulan son kullanıcı (`externalCustomerId` ve `accountType: 'PERSONAL'` gerekir; adres kalıcı olarak sabitlenir) tüccar onaylı bir müşteri oturumu açabilir. Anahtarın `wallet:customer-session:create` yetkisi olmalıdır; eksik yetki 403 `auth.permission.forbidden` döner. Kod, platformun seçtiği kanaldan sabitlenen adrese gider; kanal parametresi yoktur.
277
+
278
+ `wallet.customer_sessions.start` `Idempotency-Key` ister; `resend` ve `complete` anahtarı yalnız verdiğinizde gönderir; `refresh` ve `revoke` anahtar almaz. Beş çağrının hepsi tek kez gönderilir (5xx veya ağ hatasında otomatik yeniden deneme yoktur) ve hiçbiri 401'i yeniden göndererek yanıtlamaz. `revoke` hedefi sorguda taşıyan imzalı bir `DELETE` isteğidir. Alanlar göndermeden önce denetlenir (`Lunixi::WALLET_CUSTOMER_SESSION_RULES`); `otpChannel` gibi bilinmeyen bir alan `ConfigurationError` oluşturur.
279
+
280
+ `wallet.portal(customer_key:, token_store:)` `/api/portal/v1/wallet/me/*` rotalarını (`Lunixi::WALLET_PORTAL_ROUTES`) `Authorization: Bearer <accessToken>` ve aynı anahtarın imzasıyla çağırır; tüccar token'ı gönderilmez. `end_user_ip:` (ya da `portal.with_end_user_ip(ip)`) son kullanıcının IP'sini her çağrıda `X-Lunixi-End-User-Ip` olarak gönderir. Cüzdan e-posta değişikliği `start_email_change` (cüzdan parolası, 16–64 karakterlik `[A-Za-z0-9_-]` anahtar) → `verify_current_email_change` (mevcut adrese giden kod) → `complete_email_change` (yeni adrese giden kod) sırasıyla yürür; `reauthRequired: true` yanıtı saklı oturumu siler (yeniden giriş gerekir). Jeton deposu `get`, `set`, `delete` ve birden fazla süreç paylaşıyorsa `with_lock(customer_key) { … }` uygular; kayıtları siz şifrelersiniz (`Lunixi::InMemoryWalletCustomerTokenStore` yalnız test ve tek süreç içindir). Erişim token'ı süresi dolmadan `refresh_skew_seconds` (varsayılan 30) önce ya da 401 `AUTH_CUSTOMER_SESSION_INVALID` sonrasında, müşteri başına tek seferde yenilenir; 409 `AUTH_REFRESH_IN_PROGRESS` aynı refresh token'ı yeniden göndermez, diğer sürecin kaydını bekler. Hatalar: `WalletCustomerSessionExpiredError` ve `WalletCustomerRefreshReusedError` (`session_ended?`: kayıt silinir, yeni oturum başlatın), `WalletCustomerSessionBindingError` (başka anahtarla imzalandı; kayıt korunur), `WalletCustomerSessionNotIssuedError` (503: yeniden başlatın), `WalletCustomerRevokeIncompleteError` (503: aynı revoke çağrısını yeniden gönderin).
281
+
273
282
  ## Banka hesapları, transferler ve döviz
274
283
 
275
284
  `client.bank_connect` bağlı banka hesaplarınızı, bakiyelerinizi ve hesap hareketlerinizi okur; banka bağlantıları Lunixi panelinden kurulur. Her çağrı imzalıdır ve ortamı anahtar belirler. Filtreler göndermeden önce denetlenir: kümelerindeki değerler, 1–100 arası `limit`, en fazla 100 hesap kimliği, `minAmountMinor` / `maxAmountMinor` için küçük birim string'leri, en fazla 92 gün arayla `bookedFrom` (dahil) / `bookedTo` (hariç) ve yalnız `bookedFrom` ile birlikte `bookedTo`.
data/lib/lunixi/client.rb CHANGED
@@ -5,12 +5,14 @@ require 'time'
5
5
 
6
6
  module Lunixi
7
7
  # Thread-safe server-side gateway client. Responses retain the gateway envelope.
8
- class Client # rubocop:disable Metrics/ClassLength -- one entry point for every product client
8
+ class Client # rubocop:disable Metrics/ClassLength -- one entry point for every product client and the one request pipeline
9
9
  AUTH_PATH = '/api/v1/auth/token'
10
10
  METHODS = %w[GET HEAD POST PUT PATCH DELETE].freeze
11
11
  ACCEPT_JSON = 'application/json'
12
12
  # The customer-portal link routes of subscriptions live under the panel API.
13
13
  PANEL_PORTAL_PATH = %r{\A/api/panel/v1/subscriptions/portal(?:/|\z)}
14
+ # A caller-supplied bearer token (the wallet customer session's access token).
15
+ BEARER_TOKEN = %r{\A[A-Za-z0-9_.:~+/=-]{1,8192}\z}
14
16
  attr_reader :payments, :fraud, :reference, :payment_links, :physical_pos, :physical_pos_management, :wallet, :bank_connect, :sanction,
15
17
  :insurance, :subscriptions, :kyc, :identity, :marketplace
16
18
 
@@ -37,7 +39,7 @@ module Lunixi
37
39
  physical_pos_gateway = PhysicalPosGateway.new(self, max_retries: max_retries, backoff: ->(attempt) { pause(attempt, {}) })
38
40
  @physical_pos = PhysicalPos.new(physical_pos_gateway)
39
41
  @physical_pos_management = PhysicalPosManagement.new(physical_pos_gateway)
40
- @wallet = Wallet.new(self)
42
+ @wallet = Wallet.new(self, clock: @clock, sleeper: @sleeper)
41
43
  @bank_connect = BankConnect.new(self, max_retries: max_retries, backoff: ->(attempt) { pause(attempt, {}) })
42
44
  # The transport also carries the bulk screening file part PUTs to storage, outside Client#request.
43
45
  @sanction = Sanction.new(self, storage_transport: @transport)
@@ -54,8 +56,13 @@ module Lunixi
54
56
  # max_retries: lowers the client's retry budget for this call (0 sends a single attempt).
55
57
  # actor_id is sent as X-Actor-Id: the person in your organization acting, on endpoints that record a
56
58
  # person's action (validated by the operation that needs it).
59
+ # bearer: sends that token as Authorization: Bearer instead of the merchant access token (the wallet
60
+ # customer session of the portal routes, which are signed as well); with bearer: a 401 is raised, never
61
+ # answered by minting a merchant token. reauth: false turns the 401 re-authentication off (routes where
62
+ # a 401 is a verdict on the request, not on the token). end_user_ip: is sent as X-Lunixi-End-User-Ip (a
63
+ # signal only; not signed).
57
64
  def request(method, path, body: nil, query: {}, idempotency_key: nil, signed: true, binary: false, accept: ACCEPT_JSON, # rubocop:disable Metrics/ParameterLists -- transport options are keyword arguments
58
- max_retries: nil, actor_id: nil)
65
+ max_retries: nil, actor_id: nil, bearer: nil, reauth: true, end_user_ip: nil)
59
66
  method = method.to_s.upcase
60
67
  raise ConfigurationError, 'Unsupported HTTP method' unless METHODS.include?(method)
61
68
  raise ConfigurationError, 'GET and HEAD cannot have a body' if %w[GET HEAD].include?(method) && !body.nil?
@@ -72,9 +79,7 @@ module Lunixi
72
79
  bytes = body.nil? ? nil : JsonBody.dump(body)
73
80
  raise ConfigurationError, 'Request body exceeds the size limit' if bytes && bytes.bytesize > 1024 * 1024
74
81
 
75
- raise ConfigurationError, 'Invalid X-Actor-Id' unless actor_id.nil? || actor_id.match?(/\A[A-Za-z0-9._@+-]{1,64}\z/)
76
-
77
- perform_request(method, path, bytes, key, signed, binary, accept, retries, actor_id)
82
+ perform_request(method, path, bytes, key, signed, binary, accept, retries, request_extra(actor_id, bearer, reauth, end_user_ip))
78
83
  end
79
84
 
80
85
  # Validates caller-owned durable keys; a generated key on every retry is unsafe.
@@ -98,13 +103,20 @@ module Lunixi
98
103
  def request_idempotency_key(path, key)
99
104
  return PhysicalPosIdentifiers.idempotency_key!(key) if path.match?(PhysicalPosRequest::ROUTE)
100
105
  return RouteRequest.printable_idempotency_key!(key) if path.match?(RouteRequest::PRINTABLE_KEY_ROUTE)
101
- return WalletInvoker.idempotency_key!(key) if path.match?(WalletInvoker::ROUTE)
106
+ return WalletInvoker.idempotency_key!(key) if path.match?(WalletInvoker::ROUTE) || path.match?(WalletPortal::ROUTE)
102
107
  return RouteTable.idempotency_key!(key) if path.match?(RouteTable::KEY_ROUTE)
103
108
  return Sanction.screening_key!(key) if path.match?(Sanction::SCREENING_ROUTE)
104
109
 
105
110
  self.class.idempotency_key!(key)
106
111
  end
107
112
 
113
+ def request_extra(actor_id, bearer, reauth, end_user_ip)
114
+ raise ConfigurationError, 'Invalid X-Actor-Id' unless actor_id.nil? || actor_id.match?(/\A[A-Za-z0-9._@+-]{1,64}\z/)
115
+ raise ConfigurationError, 'Invalid bearer token' unless bearer.nil? || (bearer.is_a?(String) && bearer.match?(BEARER_TOKEN))
116
+
117
+ { actor_id: actor_id, bearer: bearer, reauth: reauth != false, end_user_ip: end_user_ip.nil? ? nil : WalletRules.end_user_ip!(end_user_ip) }
118
+ end
119
+
108
120
  def retry_budget(max_retries)
109
121
  return @max_retries if max_retries.nil?
110
122
  raise ConfigurationError, "max_retries must be between 0 and #{@max_retries}" unless max_retries.is_a?(Integer) && max_retries.between?(0, @max_retries)
@@ -112,14 +124,17 @@ module Lunixi
112
124
  max_retries
113
125
  end
114
126
 
115
- def perform_request(method, path, bytes, key, signed, binary, accept, max_retries, actor_id = nil)
127
+ # extra: actor_id, bearer, reauth, end_user_ip (see #request).
128
+ def perform_request(method, path, bytes, key, signed, binary, accept, max_retries, extra = {})
116
129
  safe_to_retry = %w[GET HEAD].include?(method) || !key.nil?
130
+ bearer = extra[:bearer]
131
+ reauth = extra.fetch(:reauth, true) && bearer.nil?
117
132
  retries = 0
118
133
  reauthenticated = false
119
134
  loop do
120
- token = access_token
121
- response = transmit(method, path, bytes, key, token, signed, accept, actor_id)
122
- if response.status == 401 && !reauthenticated && safe_to_retry
135
+ token = bearer || access_token
136
+ response = transmit(method, path, bytes, key, token, signed, accept, extra)
137
+ if response.status == 401 && !reauthenticated && safe_to_retry && reauth
123
138
  invalidate_token(token)
124
139
  reauthenticated = true
125
140
  next
@@ -154,8 +169,9 @@ module Lunixi
154
169
  end
155
170
 
156
171
  def safe_path(path, query)
157
- unless path.is_a?(String) && (path.start_with?('/api/v1/') || path.match?(PANEL_PORTAL_PATH)) && path.match?(%r{\A/[a-zA-Z0-9_~./%-]+\z})
158
- raise ConfigurationError, 'Only relative /api/v1/ gateway paths (and the subscription portal panel routes) are accepted'
172
+ unless path.is_a?(String) && (path.start_with?('/api/v1/') || path.match?(PANEL_PORTAL_PATH) || path.match?(WalletPortal::ROUTE)) &&
173
+ path.match?(%r{\A/[a-zA-Z0-9_~./%-]+\z})
174
+ raise ConfigurationError, 'Only relative /api/v1/ gateway paths (and the subscription and wallet portal routes) are accepted'
159
175
  end
160
176
 
161
177
  path.split('/').each do |segment|
@@ -194,12 +210,13 @@ module Lunixi
194
210
  headers
195
211
  end
196
212
 
197
- def transmit(method, path, body, key, token, signed, accept = ACCEPT_JSON, actor_id = nil)
213
+ def transmit(method, path, body, key, token, signed, accept = ACCEPT_JSON, extra = {})
198
214
  headers = { 'Accept' => accept, 'User-Agent' => "lunixi-sdk-ruby/#{VERSION}" }
199
215
  headers['Authorization'] = "Bearer #{token}" if token
200
216
  headers['Content-Type'] = 'application/json' unless body.nil?
201
217
  headers['Idempotency-Key'] = key if key
202
- headers['X-Actor-Id'] = actor_id if actor_id
218
+ headers['X-Actor-Id'] = extra[:actor_id] if extra[:actor_id]
219
+ headers['X-Lunixi-End-User-Ip'] = extra[:end_user_ip] if extra[:end_user_ip]
203
220
  headers.merge!(signed_headers(method, path, body)) if signed
204
221
  response = @transport.call(method: method, uri: URI.parse(@origin + path), headers: headers.freeze, body: body)
205
222
  unless response.is_a?(Response) && response.status.is_a?(Integer) && response.headers.is_a?(Hash) && response.body.is_a?(String)
data/lib/lunixi/errors.rb CHANGED
@@ -97,4 +97,53 @@ module Lunixi
97
97
  super(code: CODE, **)
98
98
  end
99
99
  end
100
+
101
+ # Wallet customer session (merchant-vouched, /api/v1/wallet/customer-sessions, and the portal calls made
102
+ # with its tokens). session_ended is true when the session can no longer be used and the customer has to
103
+ # start a new one (wallet.customer_sessions.start); through wallet.portal the stored tokens of
104
+ # customer_key are already deleted then.
105
+ class WalletCustomerSessionError < ApiError
106
+ attr_reader :session_ended, :customer_key
107
+
108
+ def initialize(session_ended: false, customer_key: nil, **)
109
+ @session_ended = session_ended == true
110
+ @customer_key = customer_key
111
+ super(**)
112
+ end
113
+
114
+ def session_ended?
115
+ @session_ended
116
+ end
117
+
118
+ # The same error naming customer_key (used when a session route error reaches a portal call).
119
+ def with_customer_key(customer_key)
120
+ self.class.new(status: status, code: code, request_id: request_id, retry_after: retry_after, details: details,
121
+ message: message, session_ended: session_ended, customer_key: customer_key)
122
+ end
123
+ end
124
+
125
+ # 401 AUTH_SESSION_BINDING_MISMATCH (the request was signed by another key or tenant than the one that
126
+ # opened the session) or AUTH_SESSION_BINDING_REQUIRED. The session is not burned; the request was made
127
+ # with the wrong key.
128
+ class WalletCustomerSessionBindingError < WalletCustomerSessionError; end
129
+
130
+ # 401 AUTH_REFRESH_REUSED: a refresh token that was already rotated was sent again. The gateway has
131
+ # revoked the whole session; start a new one.
132
+ class WalletCustomerRefreshReusedError < WalletCustomerSessionError; end
133
+
134
+ # The session can no longer be used: expired, revoked, refresh token invalid, re-authentication
135
+ # required, or no session is stored for the customer (status 0). Start a new session.
136
+ class WalletCustomerSessionExpiredError < WalletCustomerSessionError; end
137
+
138
+ # 503 WALLET_CUSTOMER_SESSION_NOT_ISSUED: the code was accepted and consumed but no session was opened.
139
+ # Do not retry the completion; start a new session.
140
+ class WalletCustomerSessionNotIssuedError < ApiError
141
+ CODE = 'WALLET_CUSTOMER_SESSION_NOT_ISSUED'
142
+ end
143
+
144
+ # 503 WALLET_CUSTOMER_REVOKE_INCOMPLETE: the revocation was recorded but closing the access did not
145
+ # finish. Send the same revoke again (it is idempotent: an already revoked installation answers 200).
146
+ class WalletCustomerRevokeIncompleteError < ApiError
147
+ CODE = 'WALLET_CUSTOMER_REVOKE_INCOMPLETE'
148
+ end
100
149
  end
@@ -3,7 +3,7 @@
3
3
  module Lunixi
4
4
  # Explicit payment routes. The advanced Client#request method covers other
5
5
  # documented endpoints without pretending to validate their entire DTO schema.
6
- class Payments
6
+ class Payments # rubocop:disable Metrics/ClassLength -- one method per catalog operation
7
7
  BASE = '/api/v1/payments'
8
8
  BIN_BASE = '/api/v1/bin'
9
9
  PDF_ACCEPT = 'application/pdf, application/json'
@@ -214,6 +214,39 @@ module Lunixi
214
214
  client.request('POST', "#{BASE}/#{payment_id}/refund", body: body, idempotency_key: Client.idempotency_key!(idempotency_key))
215
215
  end
216
216
 
217
+ # Refund a captured LIVE payment to the buyer's wallet in your wallet program instead of the card
218
+ # (POST /payments/{id}/refund-to-wallet, permission payment:refund-to-wallet, signed; the idempotency
219
+ # key is required, as for refund).
220
+ #
221
+ # request takes only REFUND_TO_WALLET_FIELDS (String or Symbol keys, camelCase or snake_case): amount
222
+ # (positive canonical minor-unit string; leave it out to refund the remaining refundable amount),
223
+ # reason, programId (leave it out when you run a single program) and customerId (your own id of the
224
+ # buyer, a STRONG match; without it only the phone recorded on the order is tried, a WEAK match). When
225
+ # no wallet user is found the refund goes to the card. Marketplace / split payments are refused. Any
226
+ # other field raises ConfigurationError before sending; an empty request sends no body. A payment paid
227
+ # WITH the wallet is refunded with refund and only in full (WALLET_PARTIAL_REFUND_UNSUPPORTED).
228
+ # @return [Hash] the payment envelope, as refund answers
229
+ def refund_to_wallet(payment_id, request = {}, idempotency_key:)
230
+ path = "#{BASE}/#{identifier!(payment_id)}/refund-to-wallet"
231
+ body = RefundToWalletRules.body!(request, REFUND_TO_WALLET_FIELDS, 'refund_to_wallet')
232
+ key = Client.idempotency_key!(idempotency_key)
233
+ client.request('POST', path, body: body.empty? ? nil : body, idempotency_key: key)
234
+ end
235
+
236
+ # Read-only: can refund_to_wallet be offered for this payment, to whom (masked) and how strong is the
237
+ # match (POST /payments/{id}/refund-to-wallet/eligibility, same permission, signed, no idempotency key;
238
+ # a POST keeps customerId out of URLs and logs). request takes only REFUND_TO_WALLET_ELIGIBILITY_FIELDS
239
+ # (customerId, programId); an empty request sends {}. Answer data: eligible, matchedBy
240
+ # (RefundToWalletMatchedBy), matchStrength (RefundToWalletMatchStrength), maskedTarget,
241
+ # defaultDestination (always CARD), reason (RefundToWalletEligibilityReason). Nothing moves until
242
+ # refund_to_wallet is called.
243
+ # @return [Hash] the gateway envelope, unmodified
244
+ def refund_to_wallet_eligibility(payment_id, request = {})
245
+ path = "#{BASE}/#{identifier!(payment_id)}/refund-to-wallet/eligibility"
246
+ body = RefundToWalletRules.body!(request, REFUND_TO_WALLET_ELIGIBILITY_FIELDS, 'refund_to_wallet_eligibility')
247
+ client.request('POST', path, body: body)
248
+ end
249
+
217
250
  # Void an authorization without inventing a settlement success result. On a PROCESSING payment with an
218
251
  # open request waiting for the buyer (Request to Pay, bank transfer instruction, QR) the same call
219
252
  # cancels the request; the answer's code is a PaymentPendingActionCode value.
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Body members of payments.refund_to_wallet (gateway RefundToWalletDto).
5
+ REFUND_TO_WALLET_FIELDS = %w[amount reason programId customerId].freeze
6
+
7
+ # Body members of payments.refund_to_wallet_eligibility (gateway RefundToWalletEligibilityDto).
8
+ REFUND_TO_WALLET_ELIGIBILITY_FIELDS = %w[customerId programId].freeze
9
+
10
+ # A payment paid with the wallet is refunded only in full: a partial payments.refund is answered with this code.
11
+ WALLET_PARTIAL_REFUND_UNSUPPORTED = 'payment.refund.wallet_partial_unsupported'
12
+
13
+ # matchStrength of a refund-to-wallet eligibility answer.
14
+ module RefundToWalletMatchStrength
15
+ # Found by your customerId inside the wallet program.
16
+ STRONG = 'STRONG'
17
+ # Found only by the phone recorded on the order.
18
+ WEAK = 'WEAK'
19
+ NONE = 'NONE'
20
+
21
+ ALL = [STRONG, WEAK, NONE].freeze
22
+ end
23
+
24
+ # matchedBy of a refund-to-wallet eligibility answer.
25
+ module RefundToWalletMatchedBy
26
+ CUSTOMER_ID = 'CUSTOMER_ID'
27
+ PHONE = 'PHONE'
28
+ NONE = 'NONE'
29
+
30
+ ALL = [CUSTOMER_ID, PHONE, NONE].freeze
31
+ end
32
+
33
+ # reason of a refund-to-wallet eligibility answer.
34
+ module RefundToWalletEligibilityReason
35
+ MATCHED = 'MATCHED'
36
+ # No customerId and no phone on the order.
37
+ NO_CANDIDATE = 'NO_CANDIDATE'
38
+ NOT_FOUND = 'NOT_FOUND'
39
+ # The wallet could not be asked; the refund would go to the card.
40
+ LOOKUP_UNAVAILABLE = 'LOOKUP_UNAVAILABLE'
41
+ # Marketplace / split payments are refunded to the card.
42
+ MARKETPLACE_EXCLUDED = 'MARKETPLACE_EXCLUDED'
43
+ # Only a LIVE payment can be refunded to a wallet.
44
+ WALLET_REQUIRES_LIVE_PAYMENT = 'WALLET_REQUIRES_LIVE_PAYMENT'
45
+
46
+ ALL = [MATCHED, NO_CANDIDATE, NOT_FOUND, LOOKUP_UNAVAILABLE, MARKETPLACE_EXCLUDED, WALLET_REQUIRES_LIVE_PAYMENT].freeze
47
+ end
48
+
49
+ # Request rules of POST /payments/{id}/refund-to-wallet and …/refund-to-wallet/eligibility. Source of truth:
50
+ # nest-payment-gateway refund-to-wallet.controller.ts and dtos/refund-to-wallet.dto.ts.
51
+ module RefundToWalletRules
52
+ SNAKE_CASE = { 'program_id' => 'programId', 'customer_id' => 'customerId' }.freeze
53
+
54
+ module_function
55
+
56
+ # Only the allowed members (String or Symbol keys, camelCase or snake_case); amount a positive canonical
57
+ # minor-unit string, the others non-empty strings; nil members are dropped.
58
+ def body!(request, allowed, operation)
59
+ raise ConfigurationError, "#{operation} request must be a Hash" unless request.nil? || request.is_a?(Hash)
60
+
61
+ merged = merge!(request || {}, operation)
62
+ unknown = merged.keys - allowed
63
+ unless unknown.empty?
64
+ raise ConfigurationError, "#{operation} does not accept #{unknown.join(', ')} (only #{allowed.join(', ')}; the gateway rejects unknown fields)"
65
+ end
66
+
67
+ allowed.each_with_object({}) do |field, body|
68
+ value = merged[field]
69
+ body[field] = value!(field, value, operation) unless value.nil?
70
+ end
71
+ end
72
+
73
+ def merge!(request, operation)
74
+ request.each_with_object({}) do |(key, value), merged|
75
+ wire = SNAKE_CASE.fetch(key.to_s, key.to_s)
76
+ raise ConfigurationError, "#{operation}: #{wire} is given twice" if merged.key?(wire)
77
+
78
+ merged[wire] = value
79
+ end
80
+ end
81
+
82
+ def value!(field, value, operation)
83
+ if field == 'amount'
84
+ unless value.is_a?(String) && value.match?(/\A[1-9][0-9]*\z/) && value.to_i <= Money::MAX
85
+ raise ConfigurationError, "#{operation}.amount must be a positive canonical minor-unit string"
86
+ end
87
+ elsif !value.is_a?(String) || value.strip.empty?
88
+ raise ConfigurationError, "#{operation}.#{field} must be a non-empty string"
89
+ end
90
+
91
+ value
92
+ end
93
+ end
94
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Lunixi
4
- VERSION = '2.2.1'
4
+ VERSION = '2.3.0'
5
5
  end
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
- def call(name, params: {}, body: nil, query: nil, idempotency_key: nil)
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 = RouteRequest.query!(query, route['query'] || [], name)
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
- raise ConfigurationError, "#{name} does not take an Idempotency-Key." unless key.nil?
183
+ return nil if key.nil?
184
+ raise ConfigurationError, "#{name} does not take an Idempotency-Key." unless route['idempotencyKeyOptional']
149
185
 
150
- nil
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