@binopartner/pay-sdk 0.1.0 → 0.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.
- package/README.md +148 -7
- package/dist/core/api-base.d.ts +49 -0
- package/dist/core/api-base.js +196 -0
- package/dist/core/appearance.d.ts +17 -0
- package/dist/core/appearance.js +122 -0
- package/dist/core/auth.d.ts +32 -0
- package/dist/core/auth.js +233 -0
- package/dist/core/client.d.ts +71 -0
- package/dist/core/client.js +307 -0
- package/dist/core/clock.d.ts +7 -0
- package/dist/core/clock.js +17 -0
- package/dist/core/errors.d.ts +29 -0
- package/dist/core/errors.js +87 -0
- package/dist/core/events.d.ts +50 -0
- package/dist/core/events.js +1 -0
- package/dist/core/flows/deposit.d.ts +63 -0
- package/dist/core/flows/deposit.js +502 -0
- package/dist/core/flows/withdraw.d.ts +51 -0
- package/dist/core/flows/withdraw.js +413 -0
- package/dist/core/i18n/ar.d.ts +2 -0
- package/dist/core/i18n/ar.js +314 -0
- package/dist/core/i18n/base.d.ts +14 -0
- package/dist/core/i18n/base.js +86 -0
- package/dist/core/i18n/cs.d.ts +2 -0
- package/dist/core/i18n/cs.js +314 -0
- package/dist/core/i18n/de.d.ts +2 -0
- package/dist/core/i18n/de.js +314 -0
- package/dist/core/i18n/en-ui.d.ts +39 -0
- package/dist/core/i18n/en-ui.js +39 -0
- package/dist/core/i18n/en.d.ts +316 -0
- package/dist/core/i18n/en.js +280 -0
- package/dist/core/i18n/es.d.ts +2 -0
- package/dist/core/i18n/es.js +314 -0
- package/dist/core/i18n/fr.d.ts +2 -0
- package/dist/core/i18n/fr.js +314 -0
- package/dist/core/i18n/hi.d.ts +2 -0
- package/dist/core/i18n/hi.js +314 -0
- package/dist/core/i18n/index.d.ts +16 -0
- package/dist/core/i18n/index.js +39 -0
- package/dist/core/i18n/it.d.ts +2 -0
- package/dist/core/i18n/it.js +314 -0
- package/dist/core/i18n/ru.d.ts +2 -0
- package/dist/core/i18n/ru.js +314 -0
- package/dist/core/i18n/tr.d.ts +2 -0
- package/dist/core/i18n/tr.js +314 -0
- package/dist/core/i18n/ua.d.ts +2 -0
- package/dist/core/i18n/ua.js +314 -0
- package/dist/core/index.d.ts +37 -0
- package/dist/core/index.js +19 -0
- package/dist/core/intent.d.ts +13 -0
- package/dist/core/intent.js +45 -0
- package/dist/core/money.d.ts +22 -0
- package/dist/core/money.js +178 -0
- package/dist/core/poll.d.ts +16 -0
- package/dist/core/poll.js +100 -0
- package/dist/core/requisites-frame.d.ts +32 -0
- package/dist/core/requisites-frame.js +202 -0
- package/dist/core/rules/address.d.ts +3 -0
- package/dist/core/rules/address.js +29 -0
- package/dist/core/rules/limits.d.ts +17 -0
- package/dist/core/rules/limits.js +19 -0
- package/dist/core/rules/paying.d.ts +10 -0
- package/dist/core/rules/paying.js +32 -0
- package/dist/core/rules/receipt.d.ts +6 -0
- package/dist/core/rules/receipt.js +33 -0
- package/dist/core/rules/requisites.d.ts +42 -0
- package/dist/core/rules/requisites.js +68 -0
- package/dist/core/rules/slippage.d.ts +1 -0
- package/dist/core/rules/slippage.js +7 -0
- package/dist/core/store.d.ts +15 -0
- package/dist/core/store.js +53 -0
- package/dist/core/types.d.ts +244 -0
- package/dist/core/types.js +1 -0
- package/dist/core/wire.d.ts +178 -0
- package/dist/core/wire.js +602 -0
- package/dist/elements/Root.d.ts +37 -0
- package/dist/elements/Root.js +143 -0
- package/dist/elements/chains.d.ts +1 -0
- package/dist/elements/chains.js +1 -0
- package/dist/elements/components/Qr.d.ts +17 -0
- package/dist/elements/components/Qr.js +28 -0
- package/dist/elements/components/basic.d.ts +42 -0
- package/dist/elements/components/basic.js +129 -0
- package/dist/elements/components/deposit.d.ts +61 -0
- package/dist/elements/components/deposit.js +272 -0
- package/dist/elements/components/inputs.d.ts +24 -0
- package/dist/elements/components/inputs.js +92 -0
- package/dist/elements/components/pickers.d.ts +32 -0
- package/dist/elements/components/pickers.js +267 -0
- package/dist/elements/components/status.d.ts +25 -0
- package/dist/elements/components/status.js +221 -0
- package/dist/elements/context.d.ts +47 -0
- package/dist/elements/context.js +33 -0
- package/dist/elements/hooks/deposit.d.ts +52 -0
- package/dist/elements/hooks/deposit.js +215 -0
- package/dist/elements/hooks/root.d.ts +70 -0
- package/dist/elements/hooks/root.js +125 -0
- package/dist/elements/hooks/withdraw.d.ts +30 -0
- package/dist/elements/hooks/withdraw.js +145 -0
- package/dist/elements/index.d.ts +28 -0
- package/dist/elements/index.js +14 -0
- package/dist/elements/part.d.ts +2 -0
- package/dist/elements/part.js +1 -0
- package/dist/elements/presets/DepositForm.d.ts +32 -0
- package/dist/elements/presets/DepositForm.js +97 -0
- package/dist/elements/presets/WithdrawForm.d.ts +25 -0
- package/dist/elements/presets/WithdrawForm.js +44 -0
- package/dist/elements/presets/focus.d.ts +2 -0
- package/dist/elements/presets/focus.js +26 -0
- package/dist/elements.css +2777 -0
- package/dist/fonts.css +31 -0
- package/dist/frame.d.ts +1 -0
- package/dist/frame.js +41 -9
- package/dist/react.js +1 -0
- package/dist/types.d.ts +2 -0
- package/dist/ui/chains.d.ts +3 -0
- package/dist/ui/chains.js +42 -0
- package/dist/ui/context.d.ts +51 -0
- package/dist/ui/context.js +63 -0
- package/dist/ui/crypto.d.ts +67 -0
- package/dist/ui/crypto.js +68 -0
- package/dist/ui/entry.d.ts +25 -0
- package/dist/ui/entry.js +26 -0
- package/dist/ui/fiat.d.ts +94 -0
- package/dist/ui/fiat.js +149 -0
- package/dist/ui/fields.d.ts +76 -0
- package/dist/ui/fields.js +71 -0
- package/dist/ui/fonts.d.ts +4 -0
- package/dist/ui/fonts.js +31 -0
- package/dist/ui/icons.d.ts +39 -0
- package/dist/ui/icons.js +116 -0
- package/dist/ui/index.d.ts +31 -0
- package/dist/ui/index.js +17 -0
- package/dist/ui/layout.d.ts +36 -0
- package/dist/ui/layout.js +44 -0
- package/dist/ui/logos.d.ts +14 -0
- package/dist/ui/logos.js +61 -0
- package/dist/ui/part.d.ts +32 -0
- package/dist/ui/part.js +33 -0
- package/dist/ui/pickers.d.ts +71 -0
- package/dist/ui/pickers.js +167 -0
- package/dist/ui/qr-encode.d.ts +30 -0
- package/dist/ui/qr-encode.js +340 -0
- package/dist/ui/summary.d.ts +31 -0
- package/dist/ui/summary.js +36 -0
- package/dist/ui/types.d.ts +67 -0
- package/dist/ui/types.js +1 -0
- package/dist/ui/urls.d.ts +4 -0
- package/dist/ui/urls.js +41 -0
- package/dist/ui/withdraw.d.ts +38 -0
- package/dist/ui/withdraw.js +30 -0
- package/dist/ui.css +2699 -0
- package/dist/widget-url.d.ts +2 -0
- package/dist/widget-url.js +29 -0
- package/package.json +46 -5
package/README.md
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
# @binopartner/pay-sdk
|
|
2
2
|
|
|
3
|
-
Embed
|
|
3
|
+
Embed Binodex deposits and withdrawals in a broker site. The package has two integrations that share one session endpoint:
|
|
4
|
+
|
|
5
|
+
- **Iframe widget** (`@binopartner/pay-sdk`, `@binopartner/pay-sdk/react`): the payment form runs inside an iframe on the Binodex origin. The sections from "React" to "Protocol" below describe it. It is unchanged in 0.2.
|
|
6
|
+
- **Elements** (`@binopartner/pay-sdk/elements`, `@binopartner/pay-sdk/core`, `@binopartner/pay-sdk/elements.css`): the form is rendered by your page with React components and hooks over a headless core that calls the Binodex pay API directly. See [Elements](#elements).
|
|
7
|
+
|
|
8
|
+
The rest of this introduction is about the iframe widget. The SDK gives you a root component and composable parts for React, and a `mount()` function for any other stack. The payment form itself runs inside an iframe on the Binodex origin, so the SDK never handles payment providers, requisites or user data.
|
|
4
9
|
|
|
5
10
|
- `Root` holds one widget session and renders nothing until every required part is present.
|
|
6
11
|
- Parts (`Frame`, `Trigger`, `Close`, `Loader`, `Status`) are placed anywhere inside `Root`, inside your own layout.
|
|
@@ -24,12 +29,12 @@ npm install
|
|
|
24
29
|
npm run build -w @binopartner/pay-sdk
|
|
25
30
|
```
|
|
26
31
|
|
|
27
|
-
Releases are published from CI, see [PUBLISHING.md](PUBLISHING.md).
|
|
28
|
-
|
|
29
32
|
## Your backend: the session endpoint
|
|
30
33
|
|
|
31
34
|
Your server creates a one-time widget session with the Broker API and returns the response unchanged. The SDK needs nothing else: no client secret and no Broker API token in the browser.
|
|
32
35
|
|
|
36
|
+
`user_ip` must be the IP address of the end user's browser (from your edge or load balancer, for example the first entry of `X-Forwarded-For` that your own proxy appended), never the IP of your server. Binodex uses it to pick the regional host that is reachable for that user; with your server's IP every user is routed as if they were in your data center.
|
|
37
|
+
|
|
33
38
|
```ts
|
|
34
39
|
// POST /api/widget-session body: { mode: "deposit" | "withdraw" }
|
|
35
40
|
const response = await fetch("https://api.binodex.app/v1/broker/widget-sessions", {
|
|
@@ -41,9 +46,13 @@ const response = await fetch("https://api.binodex.app/v1/broker/widget-sessions"
|
|
|
41
46
|
body: JSON.stringify({ origin: "https://broker.example", mode, user_ip: clientIp }),
|
|
42
47
|
});
|
|
43
48
|
return Response.json(await response.json(), { status: response.status });
|
|
44
|
-
// { session: "wss_…", expires_in: 60, widget_url?: "https://…/embed/pay?…", widget_origin?: "https://…"
|
|
49
|
+
// { session: "wss_…", expires_in: 60, widget_url?: "https://…/embed/pay?…", widget_origin?: "https://…",
|
|
50
|
+
// region?: "ru" | "global", geo?: "ru" | "global" | "unknown", api_base?: "https://api.…/v1", api_bases?: [...],
|
|
51
|
+
// widget_origins?: [...], pay_api?: true }
|
|
45
52
|
```
|
|
46
53
|
|
|
54
|
+
Relay the body as is: Elements read `api_bases`, `widget_origins`, `geo`, `region` and `pay_api` from it. The iframe widget reads `widget_origins` too: if the widget does not answer within 8 seconds, it reopens the same form on the next Binodex domain from that list (for example the one reachable from Russia), keeping the same session and channel. It never switches once the widget has answered, tries only https origins allowed by `allowedWidgetOrigins`, and keeps waiting on the last domain instead of failing. A session without `widget_origins` behaves as before.
|
|
55
|
+
|
|
47
56
|
The SDK calls this endpoint with `POST { mode }` (same-origin cookies included) whenever it needs a session: once to open the widget and again when the widget asks for re-authentication. On a non-2xx answer it shows `error.message` from the JSON body.
|
|
48
57
|
|
|
49
58
|
## React
|
|
@@ -100,6 +109,7 @@ A session is created only when the widget opens and is dropped when it closes. U
|
|
|
100
109
|
| `onCredited` | `({ amount, asset }) => void` | | A deposit was credited. UI signal only, see Security. |
|
|
101
110
|
| `onStatusChange`, `onError` | | | See Status. |
|
|
102
111
|
| `requireChannel` | `boolean` | `false` | Refuse frames that do not prove the channel (no legacy fallback). |
|
|
112
|
+
| `allowedWidgetOrigins` | `string[]` | | Origins the widget may be served from, for example `["https://binodex.app"]`. A widget URL on any other origin is refused with `invalid_widget_url` and no iframe is created. An empty list refuses every widget. Not set: any https origin the session names is accepted. |
|
|
103
113
|
| `required` | `PayPart[]` | `[]` | Extra parts that must be present, on top of `frame`. |
|
|
104
114
|
|
|
105
115
|
## Parts
|
|
@@ -178,7 +188,8 @@ What is checked:
|
|
|
178
188
|
- Your page → widget: `init` is posted with an exact target origin, never `*`, so a widget frame navigated elsewhere never receives the session. The widget accepts `init` only from its parent window, only from an origin registered for your client, only with the exact expected fields and, with a channel, only with its own channel.
|
|
179
189
|
- Widget → your page: the SDK accepts a message only when it comes from its own iframe window, from the widget origin, has a known type with valid fields and, once the widget proved the channel, carries that channel. Another iframe, a popup or a second widget instance on the page cannot drive yours.
|
|
180
190
|
- Secrets: the SDK only ever hands the widget the one-time `wss_` session (single use, valid for 60 seconds, bound to the user, client and mode). The widget exchanges it for a short-lived token inside the iframe.
|
|
181
|
-
- `widget_url` must be https (plain http only on loopback hosts), must not carry credentials and must match `widget_origin`. Take it from the Broker API response only, never from user input.
|
|
191
|
+
- `widget_url` must be https (plain http only on loopback hosts), must not carry credentials and must match `widget_origin`. Take it from the Broker API response only, never from user input. Set `allowedWidgetOrigins` to pin the widget to the Binodex origins you expect: if your session route ever returns a foreign `widget_url`, the SDK refuses it and never hands the session to that origin. The session response can name a regional widget host, so list every Binodex widget origin you expect.
|
|
192
|
+
- The iframe permissions (`payment`, `clipboard-write`) are granted to the widget origin only, not to every origin.
|
|
182
193
|
- The iframe is created with `referrerpolicy="origin"`: the widget learns your origin to verify it, never your page path.
|
|
183
194
|
|
|
184
195
|
Out of scope, and how to handle it:
|
|
@@ -187,6 +198,138 @@ Out of scope, and how to handle it:
|
|
|
187
198
|
- Script running on your page (your code, a compromised dependency, an XSS) acts as your page, with everything your page can do, widget sessions included. The SDK cannot protect you from it: keep a strict CSP, add `frame-src` for the Binodex origin, and guard your session route like any authenticated endpoint.
|
|
188
199
|
- Clickjacking by the embedding page itself is not something an iframe can prevent.
|
|
189
200
|
|
|
201
|
+
## Elements
|
|
202
|
+
|
|
203
|
+
Elements render the payment form in your own DOM with your own styles. They talk to the Binodex pay API (`/v1/broker/pay/*`) directly from the browser with a short-lived token that the SDK obtains from your session endpoint. Requires React 18 or newer.
|
|
204
|
+
|
|
205
|
+
```tsx
|
|
206
|
+
"use client";
|
|
207
|
+
import * as Pay from "@binopartner/pay-sdk/elements";
|
|
208
|
+
import "@binopartner/pay-sdk/elements.css";
|
|
209
|
+
|
|
210
|
+
export function DepositPanel({ onClose }: { onClose: () => void }) {
|
|
211
|
+
return (
|
|
212
|
+
<Pay.Root
|
|
213
|
+
mode="deposit"
|
|
214
|
+
sessionEndpoint="/api/widget-session"
|
|
215
|
+
locale="ru"
|
|
216
|
+
fallback="iframe"
|
|
217
|
+
onOpenChange={(open) => !open && onClose()}
|
|
218
|
+
onEvent={(event) => {
|
|
219
|
+
if (event.type === "deposit.credited") refreshBalanceFromYourServer();
|
|
220
|
+
}}
|
|
221
|
+
>
|
|
222
|
+
<Pay.DepositForm />
|
|
223
|
+
</Pay.Root>
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
`Pay.WithdrawForm` is the withdrawal preset. A deposit token cannot withdraw and a withdrawal token cannot deposit: a page with both tabs renders two `Pay.Root` elements, one per mode.
|
|
229
|
+
|
|
230
|
+
### `Pay.Root` props
|
|
231
|
+
|
|
232
|
+
| Prop | Default | Notes |
|
|
233
|
+
| --- | --- | --- |
|
|
234
|
+
| `mode` | required | `"deposit"` or `"withdraw"`. |
|
|
235
|
+
| `sessionEndpoint` / `createSession` | | Same contract as the iframe widget. |
|
|
236
|
+
| `clientId` | from `widget_url` | Your Broker API client id, needed to redeem the session. Taken from the session's `widget_url` when not set. |
|
|
237
|
+
| `allowedApiOrigins` | | Pin the pay API hosts, for example `["https://api.binodex.app", "https://api.binodex.pro"]`. A session naming any other host is refused with `INVALID_API_BASE`. |
|
|
238
|
+
| `allowedWidgetOrigins` | | Pin the origins the requisites frame (and the iframe fallback) may load from. |
|
|
239
|
+
| `locale` | browser language | `de`, `en`, `es`, `fr`, `hi`, `it`, `ru`, `tr`, `ua` (also `uk`), `ar` (RTL), `cs`. An unknown value falls back to the browser language, then English. |
|
|
240
|
+
| `messages` | | Override any message by key, for example `{ "submit.deposit": "Top up" }`. |
|
|
241
|
+
| `appearance` | | `{ theme: "light" \| "dark" \| "auto", skin: "classic" \| "black", variables: { "color-accent": "#00c853", "radius-md": "4px" } }`. `dark` is the Classic navy palette of binodex; `skin: "black"` switches it to the black skin. |
|
|
242
|
+
| `assetBaseUrl` | the reachable Binodex domain | Where bank logos, coin and network icons and country flags are loaded from (`<assetBaseUrl>/img/...`). Not set: the Binodex domain from `widget_origins` whose pay API answered, so a user in Russia gets them from the Russia-reachable domain. Point it at your own copy to keep every request on your origin. |
|
|
243
|
+
| `fontBaseUrl` | the reachable Binodex domain | Where Gilroy is loaded from (`<fontBaseUrl>/Gilroy-*.woff2`). Not set: the reachable Binodex domain first, the other domains of the session as fallbacks. `false` loads no font. |
|
|
244
|
+
| `open`, `defaultOpen`, `onOpenChange` | `defaultOpen = true` | A token is requested only while open; closing drops it. |
|
|
245
|
+
| `onEvent` | | Receives every `PayEvent`, see below. |
|
|
246
|
+
| `fallback` | `"error"` | `"iframe"` renders the iframe widget instead when the pay API is switched off (`pay_api: false`, `PAY_API_DISABLED`) or the backend is older and sends no `api_base`. Pass `platformUrl` for the iframe's fallback URL as before. |
|
|
247
|
+
| `returnUrl` | | Where a hosted payment page sends the user back. Must be an origin registered for your client. |
|
|
248
|
+
| `unstyled` | `false` | Drops every `bp-*` class; data attributes stay. |
|
|
249
|
+
| `apiBase` | | Local development only: overrides the host from the session. |
|
|
250
|
+
|
|
251
|
+
### Components
|
|
252
|
+
|
|
253
|
+
Every component accepts `className`, `style` and `unstyled`, forwards its ref and carries `data-binodex-pay="<part>"` plus state attributes (`data-step`, `data-status`, `data-selected`, `data-pending`, `data-invalid`, `data-error`), so Tailwind or shadcn can target it: `[&_[data-binodex-pay=submit][data-pending]]:opacity-50`.
|
|
254
|
+
|
|
255
|
+
| Component | Renders |
|
|
256
|
+
| --- | --- |
|
|
257
|
+
| `Trigger`, `Close` | Open and close buttons, same semantics as the iframe parts. |
|
|
258
|
+
| `Loader` | While the session or the first data loads. `role="status"`. |
|
|
259
|
+
| `ErrorMessage` | Session and flow errors from the error code (never the server text), with a retry button for transient errors. Children may be `(error) => node`. |
|
|
260
|
+
| `Balance` | `variant="available" \| "withdrawable"`. |
|
|
261
|
+
| `MethodPicker`, `CurrencyPicker`, `NetworkPicker` | Crypto routes, fiat rails and the card onramp. `filter` and `renderItem` props. |
|
|
262
|
+
| `AmountInput`, `PhoneInput`, `AddressInput`, `TwoFactorInput` | Inputs with limits, validation hints and `one-time-code` autocomplete for 2FA. `PhoneInput` is optional and renders only with `always` (the phone is never required by the API). |
|
|
263
|
+
| `Quote` | Fees, amount received, ETA, slippage. |
|
|
264
|
+
| `CryptoAddress` | Address, copy button, QR code (rendered locally, no image host), network warning, high-fee warning. |
|
|
265
|
+
| `Requisites` | Fiat payment details: raw rows with copy buttons, or the requisites frame (see Security). `data-delivery="raw" \| "frame"`. |
|
|
266
|
+
| `RequisitesFrame`, `ReceiptUpload`, `Countdown`, `RedirectButton`, `Onramp` | Frame, receipt upload (RU deposits in raw mode; in frame mode the receipt is uploaded inside the frame), server-clock countdown, hosted page link, onramp (`display="embed" \| "tab"`). |
|
|
267
|
+
| `SlippageWarning`, `SubmitButton`, `Status`, `BackButton`, `Qr` | |
|
|
268
|
+
| `RestartButton`, `MethodNotice` | Cancel / new payment for card deposits (and a new withdrawal after a final status); the receipt notice under the amount for rails that may need a receipt. |
|
|
269
|
+
| `DepositForm`, `WithdrawForm` | Full screens composed from the parts above, laid out like the binodex payment modal: a card with the title, the balance and a close button, the Crypto / Card tabs, the payment country and the bank tiles. Replace any piece: `<Pay.DepositForm components={{ MethodPicker: MyPicker }} />`. |
|
|
270
|
+
|
|
271
|
+
### Hooks
|
|
272
|
+
|
|
273
|
+
`usePay()`, `usePayContext()`, `useBalance()`, `usePaymentMethods()`, `useDepositQuote(methodId, amount)`, `useCryptoDeposit({ chainId, currency })`, `useCreateDeposit()`, `useDeposit(id)`, `useAttachReceipt(id)`, `useOnramp()`, `useWithdrawQuote({ methodId, address, amount })`, `useCreateWithdrawal()`, `useWithdrawal(id)`, `useDepositFlow()`, `useWithdrawFlow()`, `useCountdown(expiresAt)`, `usePayEvents(handler)`, `usePayMessages()`. All of them read external stores through `useSyncExternalStore`; no data-fetching library is needed. Money is created only from event handlers (`submit`, `create`, `request`), never from effects, so React StrictMode cannot create a second deposit.
|
|
274
|
+
|
|
275
|
+
### Theming
|
|
276
|
+
|
|
277
|
+
`elements.css` (it already contains `ui.css`) puts every rule into `@layer binopartner-pay` with class or zero-specificity selectors under `.bp-root`, so any rule of yours wins. The default look is the binodex payment modal in three palettes: light, Classic navy (`theme: "dark"`) and black (`skin: "black"`). Tokens are CSS variables on the root element: `--bp-font-family`, `--bp-font-size-xs|sm|md|lg`, `--bp-color-bg`, `--bp-color-surface`, `--bp-color-surface-2`, `--bp-color-surface-raised`, `--bp-color-surface-hover`, `--bp-color-text`, `--bp-color-text-muted`, `--bp-color-border`, `--bp-color-border-strong`, `--bp-color-accent`, `--bp-color-accent-text`, `--bp-color-on-accent`, `--bp-color-overlay`, `--bp-color-skeleton`, `--bp-color-veil`, `--bp-color-success|warning|danger|focus`, `--bp-radius-sm|md|lg|pill`, `--bp-space-1..6`, `--bp-control-height`, `--bp-shadow`, `--bp-transition` (`TOKEN_NAMES` in `/core`), plus `--bp-focus-width`, `--bp-focus-offset` for the keyboard focus ring and `--bp-brand-filter` for the logo in the header. Defaults come from your partner cabinet branding, then `appearance.variables`, then your CSS. Nothing is written outside the root element.
|
|
278
|
+
|
|
279
|
+
**Font.** The form uses Gilroy, like binodex, with a system fallback. `Root` registers the four weights through the `FontFace` API once the session names its domains: from the Binodex domain whose pay API answered, with the other domains as fallbacks. No `<style>` element is written, so a strict `style-src` needs nothing; `font-src` must allow both domains. A weight is downloaded only when text uses it, so a `--bp-font-family` of your own downloads nothing. To self-host, copy the files and pass `fontBaseUrl="https://your.cdn/fonts"`; `fontBaseUrl={false}` turns it off. Outside `Root` (the `/ui` views, a headless UI) call `registerFontFaces(client.widgetOrigins().map((origin) => origin + "/fonts"))` from `@binopartner/pay-sdk/ui`, or inject `fontFaceCss(url)`. `@binopartner/pay-sdk/fonts.css` stays for pages without a client, and loads from `https://binodex.app/fonts/` only, which is not reachable from Russia. Using Gilroy on your own domain may need its own font licence: check before self-hosting.
|
|
280
|
+
|
|
281
|
+
**Remote images.** Bank logos, coin and network icons and country flags are images under `assetBaseUrl` (they fall back to a coloured initial when an image does not load). Not set, that is the reachable Binodex domain of the session. Allow both Binodex domains in `img-src` or self-host the images.
|
|
282
|
+
|
|
283
|
+
### UI views
|
|
284
|
+
|
|
285
|
+
`@binopartner/pay-sdk/ui` (with `@binopartner/pay-sdk/ui.css`) exports the views the elements are built from, without any client, flow or network code: `PayCard`, `PayHeader`, `PayBody`, `EntryTabs`, `EntryOptions`, `MethodGrid`, `RoutePicker`, `RouteColumn`, `CountrySelect`, `AmountField`, `TextField`, `TwoFactorField`, `Summary`, `QuoteRows`, `DetailsAccordion`, `CryptoAddressCard`, `CreditBanner`, `Requisites`, `StatusPanel`, `ReceiptForm`, `PdfReceiptWarning`, `ReceiptAttached`, `SlippageWarning`, `WithdrawResult`, `StatusSteps`, `SubmitButton`, `LinkButton`, `RetryButton`, `ErrorBox`, `Notice`, `Hint`, `Skeleton`, `Loader`, `PollNotice`, `GeoBlock`, the layout pieces `CardTab`, `RailForm`, `ReceiptBlock`, `BrandLogo` and the icons. `ReceiptForm` keeps the picked file itself, or hands it to you with `file` + `onFileChange` (then you validate it) and shows a preview button with `onPreview`. Props in, callbacks out; they render on the server. Wrap them in `<PayUiRoot theme skin t={createTranslator("ru")}>` (or `PayUiProvider` inside your own `.bp-root`); without `t` the views speak English.
|
|
286
|
+
|
|
287
|
+
### Events
|
|
288
|
+
|
|
289
|
+
`session.ready`, `session.expired`, `method.selected`, `deposit.created`, `deposit.status`, `deposit.credited`, `withdrawal.created`, `withdrawal.status`, `close.requested`, `error`. Each carries `{ type, at, source: "client" }` and the server ids (`depositId`, `withdrawalId`, `paymentId`) to verify on your server. `deposit.credited` comes from the Binodex activity feed while a deposit form is open; its `paymentId` is the same id as in `GET /v1/broker/user/payments` and in postbacks.
|
|
290
|
+
|
|
291
|
+
### Headless core
|
|
292
|
+
|
|
293
|
+
`@binopartner/pay-sdk/core` has no dependencies and no React: `createPayClient(options)` (session, token, host selection, typed calls, error codes), `createDepositFlow(client)` and `createWithdrawFlow(client)` (state machines with `subscribe`/`getSnapshot`, debounced quotes, polling, idempotency keys), plus the formatting and validation rules the elements use. Use it to build a UI in any framework.
|
|
294
|
+
|
|
295
|
+
Amounts are written the way binodex writes them in every language: dollars as `$1250.00`, fiat grouped by its own currency with the symbol after a space (`formatMoney`: `5 007 ₽`, `1,00,000 ₹`), the amount to transfer on a paying screen with kopecks and hryvnia cents (`formatPayingAmount`: `22 227,00 ₽`), limits as `0.05 SOL` or `$10.00` (`formatMinLimit`).
|
|
296
|
+
|
|
297
|
+
## Security (elements)
|
|
298
|
+
|
|
299
|
+
- **Grant nothing on events.** Events are UI hints; any script on your page can fake them, and so can the user. Credit, ship or unlock only after your server confirmed the payment with `GET /v1/broker/user/payments` or a postback (postbacks are unsigned: verify them against the Broker API).
|
|
300
|
+
- **Token.** The widget token (15 minutes, one user, one mode, bound to your origin) lives only in memory inside the client closure. It is never written to `localStorage`, `sessionStorage`, cookies or URLs, never passed to events and has no public getter. It is renewed through your session endpoint 60 seconds before expiry or after the first `401`, once for all concurrent requests. A script that runs on your page can still intercept `fetch`; protect your page, see CSP below. If you suspect a leak, contact Binodex: every widget token of your client can be revoked at once.
|
|
301
|
+
- **Hosts.** The session response names the pay API hosts. The SDK accepts only `https://<host>/v1` (plain http only on localhost) without credentials, query or fragment, and only hosts in `allowedApiOrigins` when you set it. It probes the preferred host (`GET /v1/broker/pay/ping`, 2.5 s), falls back to the next one, races them when the user's region is unknown, and switches hosts once after a network error. The region hint is `geo` (with `region` as the fallback for older backends); when it is `unknown` both hosts are probed at once. Idempotency keys make that retry safe.
|
|
302
|
+
- **Requisites.** Card numbers, phones and recipient names of fiat payments are third-party data. By default they are shown in a small frame on the Binodex origin (the same host the SDK proved reachable), so session replay tools and other scripts on your page do not read them. Brokers enabled for raw delivery get them as JSON; the SDK then marks those nodes with `data-hj-suppress`, `data-sentry-mask`, `data-private` and `ym-hide-content`. These attributes are best effort for the tools that honour them, not protection.
|
|
303
|
+
- **What is never sent to the browser:** provider names, provider order ids, rates, commissions beyond the displayed one, risk flags.
|
|
304
|
+
- **Idempotency.** Every create carries an `Idempotency-Key` bound to the exact request body (amount, address, quote, 2FA code and so on). The key is reused only to retry the identical body after a network error, a 5xx or `IDEMPOTENCY_IN_PROGRESS`; any other answer, or any change of the body, starts a new key. On `IDEMPOTENCY_CONFLICT` the withdrawal form reloads the context and shows the withdrawal already in flight.
|
|
305
|
+
|
|
306
|
+
### CSP
|
|
307
|
+
|
|
308
|
+
The pay API and the requisites frame are served by two regional host pairs (global and Russia-reachable). Allow both pairs:
|
|
309
|
+
|
|
310
|
+
```
|
|
311
|
+
connect-src 'self' https://api.binodex.app https://api.binodex.pro;
|
|
312
|
+
frame-src https://binodex.app https://binodex.pro https://*.onramper.com;
|
|
313
|
+
font-src https://binodex.app https://binodex.pro;
|
|
314
|
+
img-src 'self' data: https:;
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
Replace the hosts with the ones in your session responses (`api_bases`, `widget_origins`) and in `allowedApiOrigins` / `allowedWidgetOrigins`. `img-src` covers the bank logos, coin icons and flags from the Binodex domains, your logo from the partner cabinet and providers that send a QR image instead of a QR payload; crypto QR codes are drawn locally as SVG. With `assetBaseUrl` / `fontBaseUrl` on your own host, list that host instead.
|
|
318
|
+
|
|
319
|
+
## Migration from the iframe widget
|
|
320
|
+
|
|
321
|
+
| Iframe (`/react`, `mount`) | Elements (`/elements`) |
|
|
322
|
+
| --- | --- |
|
|
323
|
+
| `PayWidget.Root` + `PayWidget.Frame` | `Pay.Root` + `Pay.DepositForm` / `Pay.WithdrawForm`, or your own composition of parts |
|
|
324
|
+
| `Trigger`, `Close`, `Loader` | same names, same semantics |
|
|
325
|
+
| `Status` (errors) | `Pay.ErrorMessage`; `Pay.Status` now shows the payment status |
|
|
326
|
+
| `usePayWidget()` | `usePay()` (superset) |
|
|
327
|
+
| `onCredited` | `onEvent` with `deposit.credited`, which now actually fires |
|
|
328
|
+
| `onStatusChange`, `onError` | `onEvent` (`session.*`, `error`) |
|
|
329
|
+
| `allowedWidgetOrigins`, `requireChannel` | kept for the fallback; add `allowedApiOrigins` |
|
|
330
|
+
|
|
331
|
+
Your session endpoint stays the same; relay the Broker API response unchanged and send the end user's IP as `user_ip`. Start with `fallback="iframe"`: if the pay API is switched off or your backend region does not serve it yet, users get the iframe widget as before. If you wired side effects to `onCredited`, note that it never fired in production while `deposit.credited` does: keep crediting from your server only.
|
|
332
|
+
|
|
190
333
|
## Development
|
|
191
334
|
|
|
192
335
|
```sh
|
|
@@ -194,5 +337,3 @@ npm run build -w @binopartner/pay-sdk # ESM + .d.ts into dist/
|
|
|
194
337
|
npm run typecheck -w @binopartner/pay-sdk
|
|
195
338
|
npm test -w @binopartner/pay-sdk # vitest + jsdom
|
|
196
339
|
```
|
|
197
|
-
|
|
198
|
-
Releases go out through the `Publish pay-sdk` GitHub Actions workflow, see [PUBLISHING.md](PUBLISHING.md).
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { PayRegion } from "./types.js";
|
|
2
|
+
export declare const PROBE_TIMEOUT_MS = 2500;
|
|
3
|
+
export declare const normalizeOrigins: (entries: readonly string[]) => string[];
|
|
4
|
+
export declare const validateApiBase: (value: unknown, allowedOrigins?: readonly string[]) => string | null;
|
|
5
|
+
export declare const validateWidgetOrigin: (value: unknown, allowedOrigins?: readonly string[]) => string | null;
|
|
6
|
+
export interface ResolvedHosts {
|
|
7
|
+
apiBases: string[];
|
|
8
|
+
widgetOrigins: string[];
|
|
9
|
+
widgetOriginByBase: Record<string, string>;
|
|
10
|
+
}
|
|
11
|
+
export declare const resolveHosts: (input: {
|
|
12
|
+
apiBases: readonly unknown[];
|
|
13
|
+
widgetOrigins: readonly unknown[];
|
|
14
|
+
widgetUrl?: string | null;
|
|
15
|
+
allowedApiOrigins?: readonly string[];
|
|
16
|
+
allowedWidgetOrigins?: readonly string[];
|
|
17
|
+
}) => ResolvedHosts;
|
|
18
|
+
export declare const orderFrameOrigins: (input: {
|
|
19
|
+
declared: readonly unknown[];
|
|
20
|
+
proven: readonly string[];
|
|
21
|
+
allowedWidgetOrigins?: readonly string[];
|
|
22
|
+
}) => string[];
|
|
23
|
+
export type ProbeResult = {
|
|
24
|
+
ok: true;
|
|
25
|
+
serverTime: number | null;
|
|
26
|
+
} | {
|
|
27
|
+
ok: false;
|
|
28
|
+
disabled: boolean;
|
|
29
|
+
};
|
|
30
|
+
export declare const probeApiBase: (fetcher: typeof fetch, base: string, signal: AbortSignal) => Promise<ProbeResult>;
|
|
31
|
+
export interface Timers {
|
|
32
|
+
setTimeout: (callback: () => void, ms: number) => unknown;
|
|
33
|
+
clearTimeout: (handle: unknown) => void;
|
|
34
|
+
}
|
|
35
|
+
export declare const defaultTimers: Timers;
|
|
36
|
+
export interface SelectHostInput {
|
|
37
|
+
bases: readonly string[];
|
|
38
|
+
region: PayRegion | null;
|
|
39
|
+
fetch: typeof fetch;
|
|
40
|
+
signal: AbortSignal;
|
|
41
|
+
timeoutMs?: number;
|
|
42
|
+
timers?: Timers;
|
|
43
|
+
exclude?: ReadonlySet<string>;
|
|
44
|
+
}
|
|
45
|
+
export interface SelectedHost {
|
|
46
|
+
base: string;
|
|
47
|
+
serverTime: number | null;
|
|
48
|
+
}
|
|
49
|
+
export declare const selectApiBase: (input: SelectHostInput) => Promise<SelectedHost>;
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { PayError, isAbortError } from "./errors.js";
|
|
2
|
+
import { PATHS, readError, readPing } from "./wire.js";
|
|
3
|
+
const LOOPBACK_HOST = /^(?:localhost|127\.0\.0\.1|\[::1\])$|\.localhost$/;
|
|
4
|
+
const API_PATH = /^\/v1\/?$/;
|
|
5
|
+
export const PROBE_TIMEOUT_MS = 2500;
|
|
6
|
+
const isTransportAllowed = (url) => url.protocol === "https:" ||
|
|
7
|
+
(url.protocol === "http:" && LOOPBACK_HOST.test(url.hostname));
|
|
8
|
+
export const normalizeOrigins = (entries) => entries.flatMap((entry) => {
|
|
9
|
+
try {
|
|
10
|
+
const url = new URL(entry);
|
|
11
|
+
return isTransportAllowed(url) ? [url.origin] : [];
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return [];
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
export const validateApiBase = (value, allowedOrigins) => {
|
|
18
|
+
if (typeof value !== "string" || value.length === 0)
|
|
19
|
+
return null;
|
|
20
|
+
try {
|
|
21
|
+
const url = new URL(value);
|
|
22
|
+
if (!isTransportAllowed(url))
|
|
23
|
+
return null;
|
|
24
|
+
if (url.username || url.password || url.search || url.hash)
|
|
25
|
+
return null;
|
|
26
|
+
if (!API_PATH.test(url.pathname))
|
|
27
|
+
return null;
|
|
28
|
+
if (value.includes("?") || value.includes("#"))
|
|
29
|
+
return null;
|
|
30
|
+
if (allowedOrigins && !normalizeOrigins(allowedOrigins).includes(url.origin)) {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
return `${url.origin}/v1`;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
export const validateWidgetOrigin = (value, allowedOrigins) => {
|
|
40
|
+
if (typeof value !== "string" || value.length === 0)
|
|
41
|
+
return null;
|
|
42
|
+
try {
|
|
43
|
+
const url = new URL(value);
|
|
44
|
+
if (!isTransportAllowed(url) || url.username || url.password)
|
|
45
|
+
return null;
|
|
46
|
+
if (allowedOrigins && !normalizeOrigins(allowedOrigins).includes(url.origin)) {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
return url.origin;
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
const unique = (values) => Array.from(new Set(values));
|
|
56
|
+
export const resolveHosts = (input) => {
|
|
57
|
+
const apiBases = unique(input.apiBases.flatMap((base) => {
|
|
58
|
+
const valid = validateApiBase(base, input.allowedApiOrigins);
|
|
59
|
+
return valid ? [valid] : [];
|
|
60
|
+
}));
|
|
61
|
+
const declared = input.widgetOrigins.length
|
|
62
|
+
? input.widgetOrigins
|
|
63
|
+
: input.widgetUrl
|
|
64
|
+
? [input.widgetUrl]
|
|
65
|
+
: [];
|
|
66
|
+
const widgetOrigins = unique(declared.flatMap((entry) => {
|
|
67
|
+
const valid = validateWidgetOrigin(entry, input.allowedWidgetOrigins);
|
|
68
|
+
return valid ? [valid] : [];
|
|
69
|
+
}));
|
|
70
|
+
const widgetOriginByBase = {};
|
|
71
|
+
input.apiBases.forEach((base, index) => {
|
|
72
|
+
const api = validateApiBase(base, input.allowedApiOrigins);
|
|
73
|
+
const widget = validateWidgetOrigin(input.widgetOrigins[index], input.allowedWidgetOrigins);
|
|
74
|
+
if (api && widget && !(api in widgetOriginByBase))
|
|
75
|
+
widgetOriginByBase[api] = widget;
|
|
76
|
+
});
|
|
77
|
+
return { apiBases, widgetOrigins, widgetOriginByBase };
|
|
78
|
+
};
|
|
79
|
+
export const orderFrameOrigins = (input) => {
|
|
80
|
+
const declared = unique(input.declared.flatMap((entry) => {
|
|
81
|
+
const valid = validateWidgetOrigin(entry, input.allowedWidgetOrigins);
|
|
82
|
+
return valid ? [valid] : [];
|
|
83
|
+
}));
|
|
84
|
+
if (declared.length === 0)
|
|
85
|
+
return [...input.proven];
|
|
86
|
+
if (input.proven.length === 0)
|
|
87
|
+
return declared;
|
|
88
|
+
return input.proven.filter((origin) => declared.includes(origin));
|
|
89
|
+
};
|
|
90
|
+
export const probeApiBase = async (fetcher, base, signal) => {
|
|
91
|
+
try {
|
|
92
|
+
const response = await fetcher(`${base}${PATHS.ping}`, {
|
|
93
|
+
method: "GET",
|
|
94
|
+
headers: { Accept: "application/json" },
|
|
95
|
+
credentials: "omit",
|
|
96
|
+
cache: "no-store",
|
|
97
|
+
signal,
|
|
98
|
+
});
|
|
99
|
+
const data = await response.json().catch(() => null);
|
|
100
|
+
if (!response.ok) {
|
|
101
|
+
return {
|
|
102
|
+
ok: false,
|
|
103
|
+
disabled: readError(response.status, data).code === "PAY_API_DISABLED",
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
return { ok: true, serverTime: readPing(data).serverTime };
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
if (signal.aborted && isAbortError(error))
|
|
110
|
+
throw error;
|
|
111
|
+
return { ok: false, disabled: false };
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
export const defaultTimers = {
|
|
115
|
+
setTimeout: (callback, ms) => globalThis.setTimeout(callback, ms),
|
|
116
|
+
clearTimeout: (handle) => globalThis.clearTimeout(handle),
|
|
117
|
+
};
|
|
118
|
+
const probeWithTimeout = (fetcher, base, signal, timeoutMs, timers) => {
|
|
119
|
+
const controller = new AbortController();
|
|
120
|
+
const onAbort = () => controller.abort();
|
|
121
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
122
|
+
let handle;
|
|
123
|
+
const timeout = new Promise((resolve) => {
|
|
124
|
+
handle = timers.setTimeout(() => {
|
|
125
|
+
controller.abort();
|
|
126
|
+
resolve({ ok: false, disabled: false });
|
|
127
|
+
}, timeoutMs);
|
|
128
|
+
});
|
|
129
|
+
const probe = probeApiBase(fetcher, base, controller.signal).catch(() => ({ ok: false, disabled: false }));
|
|
130
|
+
return Promise.race([probe, timeout]).finally(() => {
|
|
131
|
+
timers.clearTimeout(handle);
|
|
132
|
+
signal.removeEventListener("abort", onAbort);
|
|
133
|
+
controller.abort();
|
|
134
|
+
});
|
|
135
|
+
};
|
|
136
|
+
const throwIfAborted = (signal) => {
|
|
137
|
+
if (signal.aborted) {
|
|
138
|
+
const error = new Error("Aborted");
|
|
139
|
+
error.name = "AbortError";
|
|
140
|
+
throw error;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
const unreachable = () => new PayError("HOST_UNREACHABLE", "No payment API host answered");
|
|
144
|
+
const disabled = () => new PayError("PAY_API_DISABLED", "Pay API is not available", { status: 404 });
|
|
145
|
+
export const selectApiBase = async (input) => {
|
|
146
|
+
const timers = input.timers ?? defaultTimers;
|
|
147
|
+
const timeoutMs = input.timeoutMs ?? PROBE_TIMEOUT_MS;
|
|
148
|
+
const candidates = input.bases.filter((base) => !input.exclude?.has(base));
|
|
149
|
+
if (candidates.length === 0)
|
|
150
|
+
throw unreachable();
|
|
151
|
+
if (input.region === "unknown" && candidates.length > 1) {
|
|
152
|
+
const race = new AbortController();
|
|
153
|
+
const onAbort = () => race.abort();
|
|
154
|
+
input.signal.addEventListener("abort", onAbort, { once: true });
|
|
155
|
+
try {
|
|
156
|
+
const outcome = await new Promise((resolve) => {
|
|
157
|
+
let pending = candidates.length;
|
|
158
|
+
let sawDisabled = false;
|
|
159
|
+
candidates.forEach((base) => {
|
|
160
|
+
void probeWithTimeout(input.fetch, base, race.signal, timeoutMs, timers).then((result) => {
|
|
161
|
+
if (result.ok) {
|
|
162
|
+
resolve({ base, serverTime: result.serverTime });
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (result.disabled)
|
|
166
|
+
sawDisabled = true;
|
|
167
|
+
pending -= 1;
|
|
168
|
+
if (pending === 0)
|
|
169
|
+
resolve(sawDisabled ? "disabled" : "unreachable");
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
throwIfAborted(input.signal);
|
|
174
|
+
if (outcome === "disabled")
|
|
175
|
+
throw disabled();
|
|
176
|
+
if (outcome === "unreachable")
|
|
177
|
+
throw unreachable();
|
|
178
|
+
return outcome;
|
|
179
|
+
}
|
|
180
|
+
finally {
|
|
181
|
+
race.abort();
|
|
182
|
+
input.signal.removeEventListener("abort", onAbort);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
let sawDisabled = false;
|
|
186
|
+
for (const base of candidates) {
|
|
187
|
+
throwIfAborted(input.signal);
|
|
188
|
+
const result = await probeWithTimeout(input.fetch, base, input.signal, timeoutMs, timers);
|
|
189
|
+
throwIfAborted(input.signal);
|
|
190
|
+
if (result.ok)
|
|
191
|
+
return { base, serverTime: result.serverTime };
|
|
192
|
+
if (result.disabled)
|
|
193
|
+
sawDisabled = true;
|
|
194
|
+
}
|
|
195
|
+
throw sawDisabled ? disabled() : unreachable();
|
|
196
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Branding } from "./types.js";
|
|
2
|
+
export declare const TOKEN_NAMES: readonly ["font-family", "font-family-mono", "font-size-xs", "font-size-sm", "font-size-md", "font-size-lg", "font-weight-regular", "font-weight-medium", "font-weight-bold", "line-height", "color-bg", "color-surface", "color-surface-raised", "color-text", "color-text-muted", "color-border", "color-accent", "color-on-accent", "color-success", "color-warning", "color-danger", "color-focus", "radius-sm", "radius-md", "radius-lg", "radius-pill", "border-width", "space-1", "space-2", "space-3", "space-4", "space-5", "space-6", "control-height", "shadow", "transition", "color-surface-2", "color-surface-hover", "color-skeleton", "color-veil", "color-border-strong", "color-accent-text", "color-overlay"];
|
|
3
|
+
export type TokenName = (typeof TOKEN_NAMES)[number];
|
|
4
|
+
export type AppearanceTheme = "light" | "dark" | "auto";
|
|
5
|
+
export type AppearanceSkin = "classic" | "black";
|
|
6
|
+
export interface Appearance {
|
|
7
|
+
theme?: AppearanceTheme;
|
|
8
|
+
skin?: AppearanceSkin;
|
|
9
|
+
variables?: Partial<Record<TokenName, string>>;
|
|
10
|
+
}
|
|
11
|
+
export declare const resolveSkin: (appearance: Appearance | undefined) => AppearanceSkin;
|
|
12
|
+
export declare const safeColor: (value: string | null | undefined) => string | null;
|
|
13
|
+
export declare const safeBackground: (value: string | null | undefined) => string | null;
|
|
14
|
+
export declare const safeImageUrl: (value: string | null | undefined) => string | null;
|
|
15
|
+
export declare const readableOn: (color: string | null) => string;
|
|
16
|
+
export declare const resolveTheme: (appearance: Appearance | undefined, branding: Branding | null | undefined) => AppearanceTheme;
|
|
17
|
+
export declare const themeVariables: (branding: Branding | null | undefined, appearance: Appearance | undefined) => Record<string, string>;
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
export const TOKEN_NAMES = [
|
|
2
|
+
"font-family",
|
|
3
|
+
"font-family-mono",
|
|
4
|
+
"font-size-xs",
|
|
5
|
+
"font-size-sm",
|
|
6
|
+
"font-size-md",
|
|
7
|
+
"font-size-lg",
|
|
8
|
+
"font-weight-regular",
|
|
9
|
+
"font-weight-medium",
|
|
10
|
+
"font-weight-bold",
|
|
11
|
+
"line-height",
|
|
12
|
+
"color-bg",
|
|
13
|
+
"color-surface",
|
|
14
|
+
"color-surface-raised",
|
|
15
|
+
"color-text",
|
|
16
|
+
"color-text-muted",
|
|
17
|
+
"color-border",
|
|
18
|
+
"color-accent",
|
|
19
|
+
"color-on-accent",
|
|
20
|
+
"color-success",
|
|
21
|
+
"color-warning",
|
|
22
|
+
"color-danger",
|
|
23
|
+
"color-focus",
|
|
24
|
+
"radius-sm",
|
|
25
|
+
"radius-md",
|
|
26
|
+
"radius-lg",
|
|
27
|
+
"radius-pill",
|
|
28
|
+
"border-width",
|
|
29
|
+
"space-1",
|
|
30
|
+
"space-2",
|
|
31
|
+
"space-3",
|
|
32
|
+
"space-4",
|
|
33
|
+
"space-5",
|
|
34
|
+
"space-6",
|
|
35
|
+
"control-height",
|
|
36
|
+
"shadow",
|
|
37
|
+
"transition",
|
|
38
|
+
"color-surface-2",
|
|
39
|
+
"color-surface-hover",
|
|
40
|
+
"color-skeleton",
|
|
41
|
+
"color-veil",
|
|
42
|
+
"color-border-strong",
|
|
43
|
+
"color-accent-text",
|
|
44
|
+
"color-overlay",
|
|
45
|
+
];
|
|
46
|
+
export const resolveSkin = (appearance) => appearance?.skin === "black" ? "black" : "classic";
|
|
47
|
+
const HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
|
|
48
|
+
const TOKEN_SET = new Set(TOKEN_NAMES);
|
|
49
|
+
const UNSAFE_VALUE = /[;{}<>\\]|url\s*\(|expression\s*\(/i;
|
|
50
|
+
export const safeColor = (value) => {
|
|
51
|
+
if (!value)
|
|
52
|
+
return null;
|
|
53
|
+
const trimmed = value.trim();
|
|
54
|
+
return HEX_COLOR.test(trimmed) ? trimmed : null;
|
|
55
|
+
};
|
|
56
|
+
export const safeBackground = (value) => {
|
|
57
|
+
if (!value)
|
|
58
|
+
return null;
|
|
59
|
+
const trimmed = value.trim().toLowerCase();
|
|
60
|
+
if (trimmed === "transparent")
|
|
61
|
+
return trimmed;
|
|
62
|
+
return HEX_COLOR.test(trimmed) ? trimmed : null;
|
|
63
|
+
};
|
|
64
|
+
export const safeImageUrl = (value) => {
|
|
65
|
+
if (!value)
|
|
66
|
+
return null;
|
|
67
|
+
try {
|
|
68
|
+
return new URL(value).protocol === "https:" ? value : null;
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
export const readableOn = (color) => {
|
|
75
|
+
if (!color)
|
|
76
|
+
return "#0b0d11";
|
|
77
|
+
const raw = color.slice(1);
|
|
78
|
+
const hex = raw.length === 3
|
|
79
|
+
? raw
|
|
80
|
+
.split("")
|
|
81
|
+
.map((value) => value + value)
|
|
82
|
+
.join("")
|
|
83
|
+
: raw.slice(0, 6);
|
|
84
|
+
const red = Number.parseInt(hex.slice(0, 2), 16);
|
|
85
|
+
const green = Number.parseInt(hex.slice(2, 4), 16);
|
|
86
|
+
const blue = Number.parseInt(hex.slice(4, 6), 16);
|
|
87
|
+
if (![red, green, blue].every(Number.isFinite))
|
|
88
|
+
return "#0b0d11";
|
|
89
|
+
return (red * 299 + green * 587 + blue * 114) / 1000 > 150 ? "#0b0d11" : "#ffffff";
|
|
90
|
+
};
|
|
91
|
+
export const resolveTheme = (appearance, branding) => appearance?.theme ?? branding?.theme ?? "auto";
|
|
92
|
+
export const themeVariables = (branding, appearance) => {
|
|
93
|
+
const vars = {};
|
|
94
|
+
const accent = safeColor(branding?.accentColor);
|
|
95
|
+
if (accent) {
|
|
96
|
+
vars["--bp-color-accent"] = accent;
|
|
97
|
+
vars["--bp-color-on-accent"] = readableOn(accent);
|
|
98
|
+
}
|
|
99
|
+
const background = safeBackground(branding?.backgroundColor);
|
|
100
|
+
if (background)
|
|
101
|
+
vars["--bp-color-bg"] = background;
|
|
102
|
+
const overrides = appearance?.variables ?? {};
|
|
103
|
+
for (const [name, value] of Object.entries(overrides)) {
|
|
104
|
+
if (!TOKEN_SET.has(name) || typeof value !== "string")
|
|
105
|
+
continue;
|
|
106
|
+
if (!value.trim() || UNSAFE_VALUE.test(value))
|
|
107
|
+
continue;
|
|
108
|
+
vars[`--bp-${name}`] = value.trim();
|
|
109
|
+
}
|
|
110
|
+
if (overrides["color-accent"] && !overrides["color-on-accent"]) {
|
|
111
|
+
const custom = safeColor(overrides["color-accent"]);
|
|
112
|
+
if (custom)
|
|
113
|
+
vars["--bp-color-on-accent"] = readableOn(custom);
|
|
114
|
+
}
|
|
115
|
+
const ink = vars["--bp-color-on-accent"];
|
|
116
|
+
if (ink) {
|
|
117
|
+
vars["--bp-accent-ink"] = ink;
|
|
118
|
+
vars["--bp-accent-ink-withdraw"] = ink;
|
|
119
|
+
vars["--bp-accent-ink-trade"] = ink;
|
|
120
|
+
}
|
|
121
|
+
return vars;
|
|
122
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type Timers } from "./api-base.js";
|
|
2
|
+
import type { ServerClock } from "./clock.js";
|
|
3
|
+
import type { PayEventInput } from "./events.js";
|
|
4
|
+
import type { PayMode, SessionSourceOptions } from "./types.js";
|
|
5
|
+
export declare const RENEW_LEAD_MS = 60000;
|
|
6
|
+
export interface AuthOptions extends SessionSourceOptions {
|
|
7
|
+
mode: PayMode;
|
|
8
|
+
clientId?: string;
|
|
9
|
+
apiBase?: string;
|
|
10
|
+
allowedApiOrigins?: readonly string[];
|
|
11
|
+
allowedWidgetOrigins?: readonly string[];
|
|
12
|
+
fetch: typeof fetch;
|
|
13
|
+
timers?: Timers;
|
|
14
|
+
probeTimeoutMs?: number;
|
|
15
|
+
clock: ServerClock;
|
|
16
|
+
pageOrigin: () => string;
|
|
17
|
+
emit: (event: PayEventInput) => void;
|
|
18
|
+
onPhase: (phase: "session" | "ready") => void;
|
|
19
|
+
}
|
|
20
|
+
export interface Auth {
|
|
21
|
+
ensure: (signal?: AbortSignal) => Promise<void>;
|
|
22
|
+
renewIfStale: (generation: number, signal?: AbortSignal) => Promise<void>;
|
|
23
|
+
failover: (failedBase: string, signal?: AbortSignal) => Promise<boolean>;
|
|
24
|
+
authorize: (headers: Record<string, string>) => void;
|
|
25
|
+
generation: () => number;
|
|
26
|
+
base: () => string | null;
|
|
27
|
+
widgetOrigins: () => string[];
|
|
28
|
+
frameOrigins: (declared: readonly unknown[]) => string[];
|
|
29
|
+
destroy: () => void;
|
|
30
|
+
}
|
|
31
|
+
export declare const raceAbort: <T>(promise: Promise<T>, signal?: AbortSignal) => Promise<T>;
|
|
32
|
+
export declare const createAuth: (options: AuthOptions) => Auth;
|