@gbitx/pay-react-native 0.1.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/CHANGELOG.md +11 -0
- package/LICENSE +21 -0
- package/README.md +247 -0
- package/SECURITY.md +28 -0
- package/dist/index.cjs +693 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.mts +98 -0
- package/dist/index.d.ts +98 -0
- package/dist/index.mjs +685 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +79 -0
- package/src/CheckoutModal.tsx +334 -0
- package/src/GbitXPay.ts +16 -0
- package/src/GbitXPayProvider.tsx +29 -0
- package/src/config.ts +219 -0
- package/src/controller.ts +100 -0
- package/src/errors.ts +89 -0
- package/src/index.ts +33 -0
- package/src/messageHandler.ts +124 -0
- package/src/redact.ts +58 -0
- package/src/types.ts +99 -0
- package/src/useGbitXPay.ts +16 -0
- package/src/validation.ts +78 -0
- package/src/version.ts +4 -0
- package/src/webviewPolicy.ts +55 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/validation.ts","../src/redact.ts","../src/config.ts","../src/controller.ts","../src/GbitXPay.ts","../src/messageHandler.ts","../src/webviewPolicy.ts","../src/CheckoutModal.tsx","../src/GbitXPayProvider.tsx","../src/useGbitXPay.ts","../src/version.ts"],"names":["useColorScheme","useState","useRef","useCallback","_a","useEffect","BackHandler","Platform","StatusBar","jsx","Modal","jsxs","View","Text","TouchableOpacity","Fragment","WebView","ActivityIndicator","StyleSheet","useMemo"],"mappings":";;;;;;;;AA6CO,IAAM,aAAA,GAAN,MAAM,cAAA,SAAsB,KAAA,CAAM;AAAA,EAIvC,WAAA,CAAY,IAAA,EAAyB,OAAA,EAAiB,IAAA,EAA0B;AAC9E,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAGZ,IAA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comes (cancelled / expired\n// / failed) are NOT errors — they resolve as a PaymentResult. Throw/reject\n// only for SDK or credential faults. `code` is a stable, closed union;\n// changing it is a semver-major event.\n\nexport type GbitXPayErrorCode =\n // present() called before configure() completed successfully.\n | 'not_configured'\n // present() called with no <GbitXPayProvider> mounted in the tree.\n | 'not_mounted'\n // publishable key wrong/revoked/malformed, or a config 4xx.\n | 'invalid_key'\n // a SECRET key (gk_) was handed to the SDK — a serious integration bug.\n | 'secret_key_used'\n // key environment and server environment disagree.\n | 'environment_mismatch'\n // merchant not yet approved for this (live) key.\n | 'onboarding_required'\n // merchant account suspended.\n | 'merchant_suspended'\n // config endpoint rate-limited (429).\n | 'rate_limited'\n // could not reach GbitX (DNS/TLS/offline/timeout).\n | 'network_error'\n // GbitX reachable but returned 5xx or an unusable body.\n | 'server_error'\n // bad arguments to configure()/present() (e.g. malformed paymentId).\n | 'invalid_arguments';\n\n// Publicly readable meta — ONLY safe, serializable fields. The transport\n// `cause` is accepted by the constructor but is never placed on an enumerable\n// property (see below), so it can't be captured by `{...error}`, JSON, or a\n// crash reporter that walks own-enumerable keys.\nexport interface GbitXPayErrorMeta {\n // Present on 'onboarding_required'.\n onboardingStatus?: string;\n // Present on 'rate_limited' when the server sent Retry-After.\n retryAfterSec?: number;\n}\n\n// What the constructor accepts. `cause` may reference a Request/URL holding a\n// token, so it is stored non-enumerably on the standard Error `cause` slot and\n// kept out of `meta`, `message`, and `toJSON()`.\nexport type GbitXPayErrorInit = GbitXPayErrorMeta & { cause?: unknown };\n\nexport class GbitXPayError extends Error {\n readonly code: GbitXPayErrorCode;\n readonly meta?: GbitXPayErrorMeta;\n\n constructor(code: GbitXPayErrorCode, message: string, init?: GbitXPayErrorInit) {\n super(message);\n this.name = 'GbitXPayError';\n this.code = code;\n\n // Only safe fields go on the enumerable, serializable `meta`.\n const meta: GbitXPayErrorMeta = {};\n if (init?.onboardingStatus) meta.onboardingStatus = init.onboardingStatus;\n if (typeof init?.retryAfterSec === 'number') meta.retryAfterSec = init.retryAfterSec;\n this.meta = Object.keys(meta).length ? meta : undefined;\n\n // The cause (if any) is stored NON-enumerably so spreads / JSON / crash\n // reporters that walk own-enumerable keys never see it.\n if (init && 'cause' in init) {\n Object.defineProperty(this, 'cause', { value: init.cause, enumerable: false, writable: false, configurable: true });\n }\n\n // Keep instanceof working across transpile targets / bundlers.\n Object.setPrototypeOf(this, GbitXPayError.prototype);\n }\n\n // Custom serialization so a crash reporter or JSON.stringify() can never\n // leak `cause` (which might hold the checkout URL with #t=<clientToken>).\n // Only the safe, non-sensitive fields are emitted.\n toJSON() {\n const out: Record<string, unknown> = {\n name: this.name,\n code: this.code,\n message: this.message,\n };\n if (this.meta?.onboardingStatus) out.onboardingStatus = this.meta.onboardingStatus;\n if (typeof this.meta?.retryAfterSec === 'number') out.retryAfterSec = this.meta.retryAfterSec;\n return out;\n }\n}\n\n// Narrowing helper for consumers who don't want `instanceof`.\nexport function isGbitXPayError(e: unknown): e is GbitXPayError {\n return e instanceof GbitXPayError || (typeof e === 'object' && e !== null && (e as { name?: string }).name === 'GbitXPayError');\n}\n","import { GbitXPayError } from './errors';\nimport type { Environment } from './types';\n\n// A publishable key: pk_{live|test}_ + 32 random bytes hex (256-bit), exactly\n// matching generateApiKey() in gatewayService/src/utils/crypto.js.\nconst PUBLISHABLE_KEY_RE = /^pk_(live|test)_[0-9a-f]{64}$/;\n\n// paymentId is a cuid from Prisma (@default(cuid())): url-safe, no\n// slash/dot/whitespace. We reject anything that could rewrite the URL\n// path/query/fragment rather than relying on encoding alone.\nconst PAYMENT_ID_RE = /^[A-Za-z0-9_-]{8,64}$/;\n\n// clientToken is the payment cancelToken (crypto.randomBytes(16).hex = 32 hex\n// chars today). Kept a bounded alphanumeric charset so it can never carry\n// control chars into the URL fragment; permissive on length for future-proofing.\nconst CLIENT_TOKEN_RE = /^[A-Za-z0-9]{16,128}$/;\n\n// Validate the publishable key BEFORE any network call. A secret key gets its\n// own security-flavored error so an integrator immediately pulls it out of the\n// binary. The key value is NEVER included in an error message.\nexport function assertPublishableKey(publishableKey: unknown): { key: string; environment: Environment } {\n if (typeof publishableKey !== 'string' || publishableKey.trim() === '') {\n throw new GbitXPayError('invalid_key', 'A publishableKey string is required.');\n }\n const key = publishableKey.trim();\n if (key.startsWith('gk_')) {\n throw new GbitXPayError(\n 'secret_key_used',\n 'A SECRET key (gk_) was passed to the SDK. Use a publishable key (pk_) only, and remove the secret key from your app immediately.',\n );\n }\n if (!PUBLISHABLE_KEY_RE.test(key)) {\n throw new GbitXPayError('invalid_key', 'publishableKey must look like pk_live_… or pk_test_….');\n }\n const environment: Environment = key.startsWith('pk_live_') ? 'live' : 'test';\n return { key, environment };\n}\n\n// Validate present() arguments BEFORE building any URL or presenting anything.\nexport function assertPaymentArgs(\n paymentId: unknown,\n clientToken: unknown,\n): { paymentId: string; clientToken: string } {\n const id = typeof paymentId === 'string' ? paymentId.trim() : '';\n const token = typeof clientToken === 'string' ? clientToken.trim() : '';\n if (!PAYMENT_ID_RE.test(id)) {\n throw new GbitXPayError('invalid_arguments', 'paymentId is missing or malformed.');\n }\n if (!CLIENT_TOKEN_RE.test(token)) {\n throw new GbitXPayError('invalid_arguments', 'clientToken is missing or malformed.');\n }\n return { paymentId: id, clientToken: token };\n}\n\n// Assert an https origin and return its canonical origin form. Used for both\n// the API base and the server-returned checkout base.\nexport function assertHttpsOrigin(raw: unknown, label: string): string {\n if (typeof raw !== 'string' || raw.trim() === '') {\n throw new GbitXPayError('invalid_arguments', `${label} is required.`);\n }\n let u: URL;\n try {\n u = new URL(raw.trim());\n } catch {\n throw new GbitXPayError('invalid_arguments', `${label} is not a valid URL.`);\n }\n if (u.protocol !== 'https:') {\n throw new GbitXPayError('invalid_arguments', `${label} must be https.`);\n }\n return u.origin;\n}\n\n// Build the checkout URL. Args are pre-validated; we still encodeURIComponent\n// as belt-and-suspenders. The clientToken rides in the fragment (#t=) exactly\n// like POST /v1/payments returns, so the page's existing hash-capture works.\nexport function buildCheckoutUrl(checkoutOrigin: string, paymentId: string, clientToken: string): string {\n return `${checkoutOrigin}/p/${encodeURIComponent(paymentId)}?embed=native#t=${encodeURIComponent(clientToken)}`;\n}\n","// Credential hygiene. The publishable key, the client token, and the full\n// checkout URL (which carries #t=<clientToken>) must NEVER hit a log, a\n// breadcrumb, or a serialized error. Everything here is defensive: even the\n// debug logger routes through redaction.\n\n// Reduce a URL to origin + pathname, dropping the query and fragment (where\n// the token lives). Use this anywhere a URL might be surfaced.\nexport function redactUrl(url: string): string {\n try {\n const u = new URL(url);\n return `${u.origin}${u.pathname}`;\n } catch {\n return '[unparseable-url]';\n }\n}\n\n// Scrub key-shaped and token substrings from arbitrary text.\nexport function redactSecrets(input: string): string {\n return input\n // gk_/pk_ live/test keys -> keep the class prefix, redact the body.\n .replace(/([gp]k_(?:live|test)_)[0-9a-f]{6,}/gi, '$1redacted')\n // t= token in a fragment OR query string (#t=…, ?t=…, &t=…).\n .replace(/([#?&]t=)[^\\s&\"']+/g, '$1redacted')\n // Authorization: Bearer <key/token>.\n .replace(/(Bearer\\s+)[^\\s\"']+/gi, '$1redacted');\n}\n\nfunction safeStringify(value: unknown): string {\n const seen = new WeakSet<object>();\n try {\n return JSON.stringify(value, (_k, v) => {\n if (typeof v === 'object' && v !== null) {\n if (seen.has(v)) return '[circular]';\n seen.add(v);\n }\n return v;\n });\n } catch {\n return String(value);\n }\n}\n\nlet _debug = false;\nexport function setDebug(on: boolean): void {\n _debug = !!on;\n}\n\n// Debug logger. Off by default; even when on it redacts every line.\nexport function debugLog(...parts: unknown[]): void {\n if (!_debug) return;\n try {\n const line = parts.map((p) => (typeof p === 'string' ? p : safeStringify(p))).join(' ');\n // eslint-disable-next-line no-console\n console.log('[GbitXPay]', redactSecrets(line));\n } catch {\n /* logging must never throw */\n }\n}\n","import { GbitXPayError } from './errors';\nimport { assertPublishableKey, assertHttpsOrigin } from './validation';\nimport { debugLog, setDebug, redactSecrets } from './redact';\nimport type { ConfigureOptions, Environment, MerchantInfo } from './types';\n\n// Bootstrap API base — where /v1/sdk/config lives (distinct from the checkout\n// host returned by that endpoint). Overridable via configure({ apiBaseUrl })\n// for staging, but must be https.\nconst DEFAULT_API_BASE = 'https://gateway.gbitx.com';\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst MIN_TIMEOUT_MS = 1_000;\nconst MAX_TIMEOUT_MS = 60_000;\n\nexport interface ResolvedConfig {\n publishableKey: string;\n environment: Environment;\n // Frozen https origin of the checkout host (e.g. https://pay.gbitx.com).\n // The single root of trust for the WebView source, originWhitelist, and\n // every message-origin check. Server-authoritative, asserted https.\n checkoutOrigin: string;\n merchant: MerchantInfo;\n}\n\ntype State = 'unconfigured' | 'configuring' | 'configured' | 'configure_failed';\n\nlet _state: State = 'unconfigured';\nlet _config: ResolvedConfig | null = null;\nlet _inflight: Promise<ResolvedConfig> | null = null;\nlet _inflightKey: string | null = null;\n\nexport function isConfigured(): boolean {\n return _state === 'configured' && _config !== null;\n}\n\nexport function getResolvedConfig(): ResolvedConfig | null {\n return _config;\n}\n\n// Test-only reset of module state. Not exported from the package index.\nexport function __resetConfigForTest(): void {\n _state = 'unconfigured';\n _config = null;\n _inflight = null;\n _inflightKey = null;\n}\n\nfunction normalizeTimeout(ms: unknown): number {\n if (typeof ms !== 'number' || !Number.isFinite(ms)) return DEFAULT_TIMEOUT_MS;\n return Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, Math.floor(ms)));\n}\n\n// Only echo a server-provided message after scrubbing it (defense in depth —\n// the publishableKeyAuth messages are static today, but never trust that).\nfunction safeMessage(msg: unknown, fallback: string): string {\n return typeof msg === 'string' && msg.trim() ? redactSecrets(msg.trim()) : fallback;\n}\n\n// Map a non-2xx GET /v1/sdk/config response to a typed error, keyed off the\n// real backend shapes (publishableKeyAuth.js). Pure + unit-tested.\nexport function mapConfigError(\n status: number,\n body: { code?: string; message?: string; onboardingStatus?: string } | null | undefined,\n retryAfterHeader?: string | null,\n): GbitXPayError {\n const b = body || {};\n if (status === 403 && b.code === 'ONBOARDING_REQUIRED') {\n return new GbitXPayError('onboarding_required', safeMessage(b.message, 'This publishable key is not active yet. Complete onboarding to activate.'), {\n onboardingStatus: typeof b.onboardingStatus === 'string' ? b.onboardingStatus : undefined,\n });\n }\n if (status === 403) {\n return new GbitXPayError('merchant_suspended', safeMessage(b.message, 'This merchant account is not active.'));\n }\n if (status === 429) {\n const ra = Number(retryAfterHeader);\n return new GbitXPayError('rate_limited', safeMessage(b.message, 'Too many requests. Please try again shortly.'), {\n retryAfterSec: Number.isFinite(ra) && ra > 0 ? ra : undefined,\n });\n }\n if (status >= 500) {\n return new GbitXPayError('server_error', safeMessage(b.message, 'GbitXPay is temporarily unavailable. Please try again.'));\n }\n // 401 and any other 4xx -> the key was rejected.\n return new GbitXPayError('invalid_key', safeMessage(b.message, 'The publishable key was rejected.'));\n}\n\n// Validate a 2xx body's shape so 'configured' means the REAL backend answered\n// correctly (a captive portal / CDN error page / partial deploy that returns\n// 200 with junk is treated as server_error, not silently accepted). Pure.\nexport function parseConfigSuccess(body: unknown): { environment: Environment; checkoutOrigin: string; merchant: MerchantInfo } {\n const b = body as {\n success?: unknown;\n environment?: unknown;\n checkoutBaseUrl?: unknown;\n merchant?: { name?: unknown; website?: unknown } | null;\n } | null;\n\n if (!b || b.success !== true) {\n throw new GbitXPayError('server_error', 'Unexpected response while validating the key.');\n }\n if (b.environment !== 'live' && b.environment !== 'test') {\n throw new GbitXPayError('server_error', 'Unexpected config response (environment).');\n }\n let checkoutOrigin: string;\n try {\n checkoutOrigin = assertHttpsOrigin(b.checkoutBaseUrl, 'checkoutBaseUrl');\n } catch {\n throw new GbitXPayError('server_error', 'Insecure or invalid checkout origin from server.');\n }\n const m = b.merchant;\n if (!m || typeof m !== 'object' || Array.isArray(m)) {\n throw new GbitXPayError('server_error', 'Unexpected config response (merchant).');\n }\n const name = typeof m.name === 'string' && m.name.trim() ? m.name.trim() : 'Merchant';\n const website = typeof m.website === 'string' && m.website.trim() ? m.website.trim() : null;\n return { environment: b.environment, checkoutOrigin, merchant: { name, website } };\n}\n\nasync function fetchConfig(key: string, apiBase: string, timeoutMs: number): Promise<ResolvedConfig> {\n const url = `${apiBase}/v1/sdk/config`;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n\n let res: Response;\n try {\n res = await fetch(url, {\n method: 'GET',\n signal: controller.signal,\n headers: { Authorization: `Bearer ${key}`, Accept: 'application/json' },\n });\n } catch (cause) {\n throw new GbitXPayError('network_error', 'Could not reach GbitXPay to validate the publishable key.', { cause });\n } finally {\n clearTimeout(timer);\n }\n\n // Body may be non-JSON (proxy/CDN error page) — parse defensively.\n const body = await res.json().catch(() => null);\n\n if (!res.ok) {\n throw mapConfigError(res.status, body as never, res.headers?.get?.('retry-after'));\n }\n\n const parsed = parseConfigSuccess(body);\n return {\n publishableKey: key,\n environment: parsed.environment,\n checkoutOrigin: parsed.checkoutOrigin,\n merchant: parsed.merchant,\n };\n}\n\n// Validate the publishable key against the GbitX backend and prepare the SDK.\n// Must complete successfully before present() can run. Safe to call more than\n// once (an in-flight call for the SAME key is shared; the last successful\n// configure wins).\nexport async function configure(options: ConfigureOptions): Promise<void> {\n if (options && options.debug) setDebug(true);\n\n const { key, environment: prefixEnv } = assertPublishableKey(options?.publishableKey);\n\n if (options.environment && options.environment !== prefixEnv) {\n throw new GbitXPayError('environment_mismatch', 'The environment option does not match the publishable key.');\n }\n\n const timeoutMs = normalizeTimeout(options.timeoutMs);\n const apiBase = options.apiBaseUrl ? assertHttpsOrigin(options.apiBaseUrl, 'apiBaseUrl') : DEFAULT_API_BASE;\n\n // Share an in-flight configure for the same key.\n if (_inflight && _inflightKey === key) {\n await _inflight;\n return;\n }\n\n _state = 'configuring';\n debugLog('configure: validating key against', `${apiBase}/v1/sdk/config`);\n\n const run = (async (): Promise<ResolvedConfig> => {\n const resolved = await fetchConfig(key, apiBase, timeoutMs);\n // Cross-check the key prefix against the server's environment. A mismatch\n // is a fatal misconfiguration (mis-issued/tampered key or wrong backend).\n if (resolved.environment !== prefixEnv) {\n throw new GbitXPayError('environment_mismatch', 'Key environment and server environment disagree.');\n }\n if (options.environment && options.environment !== resolved.environment) {\n throw new GbitXPayError('environment_mismatch', 'The environment option does not match the server environment.');\n }\n return resolved;\n })();\n\n _inflight = run;\n _inflightKey = key;\n\n try {\n const resolved = await run;\n // Only commit if THIS run is still the current in-flight one. A later\n // configure() (different key) may have superseded us while we awaited; a\n // stale, superseded run must never overwrite the winning checkoutOrigin\n // (the root of trust). If superseded, drop our result silently.\n if (_inflight === run) {\n _config = resolved;\n _state = 'configured';\n debugLog('configure: ok, environment =', resolved.environment);\n }\n } catch (err) {\n // Only flip to failed if this run is still the current one (a newer\n // configure() may have superseded us).\n if (_inflight === run) {\n _state = 'configure_failed';\n _config = null;\n }\n throw err;\n } finally {\n if (_inflight === run) {\n _inflight = null;\n _inflightKey = null;\n }\n }\n}\n","import { GbitXPayError } from './errors';\nimport { assertPaymentArgs, buildCheckoutUrl } from './validation';\nimport { getResolvedConfig, isConfigured, type ResolvedConfig } from './config';\nimport type { PaymentResult, PresentOptions } from './types';\n\n// One active checkout session, handed to the mounted host (GbitXPayProvider)\n// to render. `settle` is the SINGLE exit: the controller dedupes it and\n// resolves the present() promise, then tells the host to unmount.\nexport interface CheckoutSession {\n paymentId: string;\n clientToken: string;\n url: string;\n config: ResolvedConfig;\n onLoaded?: () => void;\n onEvent?: PresentOptions['onEvent'];\n settle: (result: PaymentResult) => void;\n}\n\ntype HostListener = (session: CheckoutSession | null) => void;\n\nlet _host: HostListener | null = null;\nlet _active: CheckoutSession | null = null;\n\n// The provider registers exactly one host. If a host is already registered\n// (two providers mounted — a merchant mistake), the last one wins and we warn\n// via the returned unregister being scoped to the specific listener.\nexport function registerHost(listener: HostListener): () => void {\n _host = listener;\n if (_active) listener(_active); // replay a pending session to a late host\n return () => {\n if (_host === listener) _host = null;\n };\n}\n\nexport function hasHost(): boolean {\n return _host !== null;\n}\n\n// Test-only.\nexport function __resetControllerForTest(): void {\n _host = null;\n _active = null;\n}\n\n// Open the hosted checkout for one payment. Resolves with the terminal\n// PaymentResult (confirmed / cancelled / expired / failed). Rejects ONLY for\n// SDK/credential faults (GbitXPayError). A terminal outcome is never a reject.\nexport function present(options: PresentOptions): Promise<PaymentResult> {\n return new Promise<PaymentResult>((resolve, reject) => {\n if (!isConfigured()) {\n reject(new GbitXPayError('not_configured', 'Call and await GbitXPay.configure({ publishableKey }) before present().'));\n return;\n }\n if (!_host) {\n reject(new GbitXPayError('not_mounted', 'Mount <GbitXPayProvider> once near your app root before calling present().'));\n return;\n }\n if (_active) {\n reject(new GbitXPayError('invalid_arguments', 'A checkout is already open.'));\n return;\n }\n\n let args: { paymentId: string; clientToken: string };\n try {\n args = assertPaymentArgs(options?.paymentId, options?.clientToken);\n } catch (e) {\n reject(e);\n return;\n }\n\n const config = getResolvedConfig();\n if (!config) {\n // Guarded by isConfigured() above; defensive.\n reject(new GbitXPayError('not_configured', 'Configuration was lost. Call configure() again.'));\n return;\n }\n\n const url = buildCheckoutUrl(config.checkoutOrigin, args.paymentId, args.clientToken);\n\n let done = false;\n const session: CheckoutSession = {\n paymentId: args.paymentId,\n clientToken: args.clientToken,\n url,\n config,\n onLoaded: options.onLoaded,\n onEvent: options.onEvent,\n settle: (result: PaymentResult) => {\n if (done) return; // controller-level latch (the modal has its own too)\n done = true;\n _active = null;\n _host?.(null); // ask the host to unmount the modal/WebView\n resolve(result);\n },\n };\n\n _active = session;\n _host(session);\n });\n}\n","import { configure } from './config';\nimport { present } from './controller';\n\n// The imperative singleton. `configure` once at startup; `present` per payment.\n//\n// import { GbitXPay } from '@gbitx/pay-react-native';\n// await GbitXPay.configure({ publishableKey: 'pk_live_…' });\n// const result = await GbitXPay.present({ paymentId, clientToken });\n// if (result.status === 'confirmed') showThankYou();\n// // …but only fulfil the order from your signed server webhook.\nexport const GbitXPay = {\n configure,\n present,\n} as const;\n\nexport type GbitXPayApi = typeof GbitXPay;\n","import type { CheckoutEventType, PaymentResult, PaymentStatus, SanitizedPayment } from './types';\n\n// Exact set of bridge event types the checkout page emits. Anything else is\n// dropped. Keys are the wire `type` strings; values are the short event names.\nconst KNOWN_TYPES: Record<string, CheckoutEventType> = {\n 'gbitx:payment:loaded': 'loaded',\n 'gbitx:payment:confirmed': 'confirmed',\n 'gbitx:payment:cancelled': 'cancelled',\n 'gbitx:payment:expired': 'expired',\n 'gbitx:payment:failed': 'failed',\n 'gbitx:payment:closed': 'closed',\n};\n\n// A bridge message is a single JSON string. Cap it well under any sane size so\n// a hostile page can't feed us a giant string before we even parse.\nconst MAX_MESSAGE_BYTES = 8192;\n\nconst PAYMENT_STATUSES: readonly PaymentStatus[] = [\n 'PENDING', 'AWAITING_PAYMENT', 'UNDERPAID', 'CONFIRMING', 'CONFIRMED', 'EXPIRED', 'FAILED', 'CANCELLED',\n];\n\nexport interface ParsedMessage {\n type: CheckoutEventType;\n // null for :loaded (the page sends {}) or when a payment payload is absent\n // / malformed. Terminal handling tolerates null (webhook is truth).\n payment: SanitizedPayment | null;\n}\n\nfunction asString(v: unknown): string | null {\n return typeof v === 'string' ? v : null;\n}\n\n// Accept string OR finite number for decimal amount fields (the page sends\n// strings — Prisma Decimal — but we stay tolerant) and normalize to a plain\n// decimal string. A number whose String() form uses exponential notation\n// (very large, or small like 1e-8) is dropped to null rather than surfaced as\n// \"1e-8\"/\"1e+21\"; the field is display-only, so null is safer than a\n// misleading exponent.\nfunction asDecimalString(v: unknown): string | null {\n if (typeof v === 'string') return v;\n if (typeof v === 'number' && Number.isFinite(v)) {\n const s = String(v);\n return s.includes('e') || s.includes('E') ? null : s;\n }\n return null;\n}\n\n// Re-pick ONLY the whitelisted fields into a fresh object. This discards any\n// extra keys (prototype-pollution vectors, functions, nested junk, and the\n// fields the page deliberately strips). Returns null if the payload is not a\n// usable payment (no id or unknown status).\nexport function sanitizePayment(input: unknown): SanitizedPayment | null {\n if (!input || typeof input !== 'object' || Array.isArray(input)) return null;\n const p = input as Record<string, unknown>;\n\n const id = asString(p.id);\n const status = asString(p.status);\n if (!id || !status || !(PAYMENT_STATUSES as readonly string[]).includes(status)) return null;\n\n const mode = p.mode === 'LIVE' || p.mode === 'SANDBOX' ? p.mode : 'SANDBOX';\n\n return {\n id,\n status: status as PaymentStatus,\n amount: asDecimalString(p.amount) ?? '',\n currency: asString(p.currency) ?? '',\n crypto: asString(p.crypto),\n network: asString(p.network),\n amountCrypto: asDecimalString(p.amountCrypto),\n amountPaid: asDecimalString(p.amountPaid),\n mode,\n confirmedAt: asString(p.confirmedAt),\n expiresAt: asString(p.expiresAt) ?? '',\n };\n}\n\n// Defensively parse a raw onMessage string into a known event, or null. Never\n// throws. Callers MUST have already verified the message origin (the WebView's\n// committed top-frame URL) before invoking this.\nexport function parseBridgeMessage(raw: unknown): ParsedMessage | null {\n if (typeof raw !== 'string' || raw.length === 0 || raw.length > MAX_MESSAGE_BYTES) return null;\n\n let obj: unknown;\n try {\n obj = JSON.parse(raw);\n } catch {\n return null;\n }\n if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return null;\n\n const type = (obj as { type?: unknown }).type;\n if (typeof type !== 'string') return null;\n const mapped = KNOWN_TYPES[type];\n if (!mapped) return null;\n\n return {\n type: mapped,\n payment: sanitizePayment((obj as { payment?: unknown }).payment),\n };\n}\n\n// True for the events that end a checkout session.\nexport function isTerminal(type: CheckoutEventType): boolean {\n return type !== 'loaded';\n}\n\n// Map a terminal event to a PaymentResult. `loaded` is non-terminal -> null.\n// `closed` and `cancelled` collapse to a single cancelled representation.\nexport function terminalResult(type: CheckoutEventType, payment: SanitizedPayment | null): PaymentResult | null {\n switch (type) {\n case 'confirmed':\n return { status: 'confirmed', payment };\n case 'cancelled':\n case 'closed':\n return { status: 'cancelled', reason: 'user_closed', payment };\n case 'expired':\n return { status: 'expired', reason: 'expired', payment };\n case 'failed':\n return { status: 'failed', payment };\n case 'loaded':\n default:\n return null;\n }\n}\n","// Pure, unit-testable WebView security policy — the exact origin decisions the\n// SDK's trust rests on. Kept free of any react-native import so it can be\n// tested in Node and so the decisions are auditable in isolation.\n//\n// EXACT origin equality everywhere (never startsWith / includes). The library's\n// own `originWhitelist` prop is a *prefix* match (unanchored regex), so\n// `https://pay.gbitx.com` there would also match `https://pay.gbitx.com.evil.com`\n// and `https://pay.gbitx.company`. We therefore set originWhitelist to ['*'] in\n// the component and make THIS module the single authoritative gate.\n\nfunction parse(url: unknown): URL | null {\n if (typeof url !== 'string' || url === '') return null;\n try {\n return new URL(url);\n } catch {\n return null;\n }\n}\n\n// May a navigation load inside the WebView? In native embed mode the checkout\n// is fully self-contained — it performs NO off-origin navigation and uses NO\n// wallet deep-links (verified against PaymentPage.jsx: redirects are suppressed\n// and \"return to merchant\" links are swapped for close buttons). So the only\n// thing allowed to load is the pinned checkout origin over https; everything\n// else is blocked and opened nowhere (no Linking), removing the \"a compromised\n// page force-opens an external URL / deep-link\" vector entirely.\nexport function mayLoadInWebView(checkoutOrigin: string, url: unknown): boolean {\n const u = parse(url);\n return !!u && u.protocol === 'https:' && u.origin === checkoutOrigin;\n}\n\n// Is a URL the pinned checkout origin over https? EXACT origin, NO path clause.\n// Used to validate the per-message authenticated sender URL, whose shape differs\n// by platform: on iOS react-native-webview reports the full frame URL, but on\n// Android it reports the sender ORIGIN only (no path). Requiring a /p/ path here\n// would reject every legitimate Android message. The /p/ path is instead asserted\n// on the committed top-frame URL (isTrustedMessageSource) — exactly how the iOS\n// native SDK splits frameInfo.securityOrigin (origin) from the committed URL (path).\n//\n// Caveat vs the native SDKs: on react-native-webview's Android path this URL is the\n// TOP-frame value, not a per-frame authenticated sender origin, so it cannot by\n// itself isolate a sub-frame. That residual is covered by the hosted page's CSP\n// (frame-src 'none' blocks injected iframes) plus the page shipping no iframes.\nexport function isTrustedMessageOrigin(checkoutOrigin: string, url: unknown): boolean {\n const u = parse(url);\n return !!u && u.protocol === 'https:' && u.origin === checkoutOrigin;\n}\n\n// Is a URL the pinned origin over https AND on a payment path (/p/...)? Applied to\n// the committed top-frame URL (from onNavigationStateChange), which always carries\n// the full path. This is the native mirror of the page's own embed-origin boundary.\nexport function isTrustedMessageSource(checkoutOrigin: string, url: unknown): boolean {\n const u = parse(url);\n return !!u && u.protocol === 'https:' && u.origin === checkoutOrigin && u.pathname.startsWith('/p/');\n}\n","import React, { useCallback, useEffect, useRef, useState } from 'react';\nimport {\n ActivityIndicator,\n BackHandler,\n Modal,\n Platform,\n StatusBar,\n StyleSheet,\n Text,\n TouchableOpacity,\n useColorScheme,\n View,\n} from 'react-native';\nimport { WebView } from 'react-native-webview';\nimport type {\n ShouldStartLoadRequest,\n WebViewMessageEvent,\n WebViewNavigation,\n} from 'react-native-webview/lib/WebViewTypes';\n\nimport type { CheckoutSession } from './controller';\nimport type { PaymentResult } from './types';\nimport { parseBridgeMessage, terminalResult } from './messageHandler';\nimport { mayLoadInWebView, isTrustedMessageSource, isTrustedMessageOrigin } from './webviewPolicy';\nimport { debugLog, redactUrl } from './redact';\n\n// Absolute ceiling on a single checkout session. The server payment expires in\n// 60 minutes; this fixed backstop (payment window + grace) guarantees present()\n// resolves even if the WebView is backgrounded/offline and the page can never\n// emit its own 'expired'. Fixed (not derived from any device-controlled\n// payload) so it can neither be shortened by a hostile page nor overflow the\n// 32-bit setTimeout delay.\nconst SESSION_MAX_MS = 65 * 60 * 1000;\n\ninterface ThemeTokens {\n bg: string;\n text: string;\n sub: string;\n border: string;\n spinner: string;\n}\n\nfunction useTheme(): ThemeTokens {\n const scheme = useColorScheme();\n return scheme === 'dark'\n ? { bg: '#0a0f0c', text: '#f2f5f3', sub: '#9aa5a0', border: '#1c2620', spinner: '#3ecf6b' }\n : { bg: '#ffffff', text: '#0a0f0c', sub: '#5b6660', border: '#e6ebe8', spinner: '#07811f' };\n}\n\nexport function CheckoutModal({ session }: { session: CheckoutSession }): React.ReactElement {\n const theme = useTheme();\n const checkoutOrigin = session.config.checkoutOrigin;\n\n const [pageReady, setPageReady] = useState(false);\n const [loadError, setLoadError] = useState(false);\n\n // Refs so async handlers always see current values without re-subscribing.\n const settledRef = useRef(false);\n const loadedFiredRef = useRef(false);\n const committedUrlRef = useRef<string>(session.url);\n const backstopRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const webViewRef = useRef<WebView>(null);\n\n // The SINGLE exit. Idempotent. Clears timers, forgets the token-bearing URL,\n // and hands the result to the controller (which also dedupes and unmounts us).\n const settle = useCallback(\n (result: PaymentResult) => {\n if (settledRef.current) return;\n settledRef.current = true;\n if (backstopRef.current) {\n clearTimeout(backstopRef.current);\n backstopRef.current = null;\n }\n committedUrlRef.current = ''; // drop the URL (carries #t=token) from memory\n debugLog('settle', result.status, 'reason' in result ? result.reason ?? '' : '');\n session.settle(result);\n },\n [session],\n );\n\n // ── WebView: navigation lock (sole authoritative gate) ─────────────────────\n // originWhitelist is set to ['*'] so the library never auto-decides (its\n // whitelist is a loose prefix match); every navigation is routed here and only\n // the exact pinned origin over https may load. Off-origin is blocked and NOT\n // opened anywhere.\n const handleShouldStart = useCallback(\n (req: ShouldStartLoadRequest): boolean => mayLoadInWebView(checkoutOrigin, req.url),\n [checkoutOrigin],\n );\n\n // Never spawn a child WebView or open anything. window.open / target=_blank\n // are already suppressed by the props below; this is defense in depth.\n const handleOpenWindow = useCallback(() => {\n /* no-op: never open a second browsing context */\n }, []);\n\n // ── WebView: message trust gate + dispatch ─────────────────────────────────\n const handleMessage = useCallback(\n (event: WebViewMessageEvent) => {\n // Trust gate (two independent checks, mirroring the iOS native SDK):\n // 1. The per-message sender URL must be the pinned origin over https.\n // react-native-webview reports this differently per platform — a FULL\n // frame URL on iOS, but the sender ORIGIN ONLY (no path) on Android —\n // so we check ORIGIN here, never a path (a /p/ requirement would drop\n // every legitimate Android message and hang the checkout).\n // 2. The committed top-frame URL (always full, from onNavigationStateChange)\n // must be the pinned origin on a /p/ path.\n // Both must hold. If the platform provides no sender URL, fall back to the\n // committed /p/ gate alone. Fail closed on any mismatch.\n const senderUrl = event?.nativeEvent?.url;\n const committedOnCheckout = isTrustedMessageSource(checkoutOrigin, committedUrlRef.current || session.url);\n if (typeof senderUrl === 'string' && senderUrl !== '') {\n if (!isTrustedMessageOrigin(checkoutOrigin, senderUrl) || !committedOnCheckout) return;\n } else if (!committedOnCheckout) {\n return;\n }\n\n const parsed = parseBridgeMessage(event?.nativeEvent?.data);\n if (!parsed) return;\n\n // Bind to THIS payment: a message whose payload is for a different payment\n // id is dropped (the origin gate + single active session already scope us,\n // this closes id-confusion for good).\n if (parsed.payment && parsed.payment.id !== session.paymentId) return;\n\n session.onEvent?.({ type: parsed.type, payment: parsed.payment ?? undefined });\n\n if (parsed.type === 'loaded') {\n setPageReady(true);\n if (!loadedFiredRef.current) {\n loadedFiredRef.current = true;\n session.onLoaded?.();\n }\n return; // non-terminal\n }\n\n const result = terminalResult(parsed.type, parsed.payment);\n if (result) settle(result);\n },\n [checkoutOrigin, session, settle],\n );\n\n // ── WebView: load/crash error handling (main-frame only) ───────────────────\n const isMainFrameUrl = useCallback(\n (url: string | undefined): boolean => {\n if (!url) return true; // top-level failure with no url\n try {\n const u = new URL(url);\n return u.origin === checkoutOrigin && u.pathname.startsWith('/p/');\n } catch {\n return false;\n }\n },\n [checkoutOrigin],\n );\n\n const handleLoadError = useCallback(\n (e: { nativeEvent?: { url?: string } }) => {\n if (isMainFrameUrl(e?.nativeEvent?.url)) setLoadError(true);\n },\n [isMainFrameUrl],\n );\n\n const handleCrash = useCallback((): void => {\n // Renderer died. Do NOT blind-reload into an unknown state — surface an\n // error the user can retry. A success can only come from a trusted message.\n setLoadError(true);\n }, []);\n\n const retry = useCallback(() => {\n setLoadError(false);\n setPageReady(false);\n webViewRef.current?.reload();\n }, []);\n\n // ── Android hardware back + fixed backstop + unmount cleanup ────────────────\n useEffect(() => {\n // Absolute session backstop (fixed duration — see SESSION_MAX_MS).\n backstopRef.current = setTimeout(() => settle({ status: 'expired', reason: 'client_backstop' }), SESSION_MAX_MS);\n\n const onBack = (): boolean => {\n settle({ status: 'cancelled', reason: 'back_button' });\n return true; // we own the back gesture while checkout is open\n };\n const sub = BackHandler.addEventListener('hardwareBackPress', onBack);\n\n return () => {\n sub.remove();\n if (backstopRef.current) {\n clearTimeout(backstopRef.current);\n backstopRef.current = null;\n }\n webViewRef.current?.stopLoading?.();\n // If we unmount without a terminal event, settle once so the merchant's\n // promise never hangs and no orphaned WebView keeps polling.\n if (!settledRef.current) {\n settledRef.current = true;\n session.settle({ status: 'cancelled', reason: 'dismissed' });\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // One redacted breadcrumb (origin + path only — never the #t= token).\n useEffect(() => {\n debugLog('present', redactUrl(session.url));\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const topInset = Platform.OS === 'android' ? StatusBar.currentHeight ?? 0 : 0;\n\n return (\n <Modal\n visible\n animationType=\"slide\"\n presentationStyle=\"pageSheet\"\n statusBarTranslucent\n onRequestClose={() => settle({ status: 'cancelled', reason: 'back_button' })}\n onDismiss={() => {\n if (!settledRef.current) settle({ status: 'cancelled', reason: 'dismissed' });\n }}\n >\n <View style={[styles.container, { backgroundColor: theme.bg, paddingTop: topInset }]}>\n <View style={[styles.header, { borderBottomColor: theme.border }]}>\n <Text style={[styles.title, { color: theme.text }]} numberOfLines={1}>\n {session.config.merchant.name}\n </Text>\n <TouchableOpacity\n onPress={() => settle({ status: 'cancelled', reason: 'user_closed' })}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close checkout\"\n hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}\n style={styles.closeBtn}\n >\n <Text style={[styles.closeIcon, { color: theme.text }]}>✕</Text>\n </TouchableOpacity>\n </View>\n\n <View style={styles.body}>\n {loadError ? (\n <View style={styles.center} accessibilityLabel=\"Checkout failed to load\">\n <Text style={[styles.errorTitle, { color: theme.text }]}>Could not load checkout</Text>\n <Text style={[styles.errorSub, { color: theme.sub }]}>Check your connection and try again.</Text>\n <TouchableOpacity onPress={retry} accessibilityRole=\"button\" style={[styles.retryBtn, { borderColor: theme.border }]}>\n <Text style={[styles.retryText, { color: theme.text }]}>Retry</Text>\n </TouchableOpacity>\n <TouchableOpacity\n onPress={() => settle({ status: 'cancelled', reason: 'load_failed' })}\n accessibilityRole=\"button\"\n style={styles.closeLink}\n >\n <Text style={[styles.closeLinkText, { color: theme.sub }]}>Close</Text>\n </TouchableOpacity>\n </View>\n ) : (\n <>\n <WebView\n ref={webViewRef}\n source={{ uri: session.url }}\n // ── origin + navigation lock (this handler is the sole gate) ──\n originWhitelist={['*']}\n onShouldStartLoadWithRequest={handleShouldStart}\n onNavigationStateChange={(s: WebViewNavigation) => {\n committedUrlRef.current = s.url;\n // Defense in depth: originWhitelist is ['*'] so handleShouldStart\n // is the sole nav gate. If the committed top frame ever lands on\n // an http(s) URL that is NOT the pinned origin (a library\n // regression bypassing the gate), stop trusting the session.\n if (typeof s.url === 'string' && /^https?:/i.test(s.url) && !mayLoadInWebView(checkoutOrigin, s.url)) {\n if (!settledRef.current) {\n webViewRef.current?.stopLoading?.();\n setLoadError(true);\n }\n }\n }}\n onMessage={handleMessage}\n onOpenWindow={handleOpenWindow}\n // ── window / file / storage lockdown ──\n setSupportMultipleWindows={false}\n javaScriptCanOpenWindowsAutomatically={false}\n allowFileAccess={false}\n allowFileAccessFromFileURLs={false}\n allowUniversalAccessFromFileURLs={false}\n thirdPartyCookiesEnabled={false}\n sharedCookiesEnabled={false}\n incognito={false}\n mixedContentMode=\"never\"\n // ── media (no autoplay, no camera/mic grants) ──\n allowsInlineMediaPlayback\n mediaPlaybackRequiresUserAction\n // ── load + crash handling ──\n onError={handleLoadError}\n onHttpError={handleLoadError}\n onContentProcessDidTerminate={handleCrash}\n onRenderProcessGone={handleCrash}\n onLoadEnd={() => setPageReady(true)}\n style={{ flex: 1, backgroundColor: theme.bg }}\n />\n {!pageReady ? (\n <View style={[styles.loadingOverlay, { backgroundColor: theme.bg }]} accessibilityLabel=\"Loading checkout\">\n <ActivityIndicator size=\"large\" color={theme.spinner} />\n </View>\n ) : null}\n </>\n )}\n </View>\n </View>\n </Modal>\n );\n}\n\nconst styles = StyleSheet.create({\n container: { flex: 1 },\n header: {\n flexDirection: 'row',\n alignItems: 'center',\n justifyContent: 'space-between',\n paddingHorizontal: 16,\n height: 52,\n borderBottomWidth: StyleSheet.hairlineWidth,\n },\n title: { fontSize: 15, fontWeight: '500', flex: 1, marginRight: 12 },\n closeBtn: { width: 32, height: 32, alignItems: 'center', justifyContent: 'center' },\n closeIcon: { fontSize: 18, fontWeight: '400' },\n body: { flex: 1 },\n loadingOverlay: { ...StyleSheet.absoluteFillObject, alignItems: 'center', justifyContent: 'center' },\n center: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: 32 },\n errorTitle: { fontSize: 16, fontWeight: '500', marginBottom: 8 },\n errorSub: { fontSize: 13, textAlign: 'center', marginBottom: 20 },\n retryBtn: { paddingHorizontal: 24, paddingVertical: 10, borderRadius: 10, borderWidth: 1 },\n retryText: { fontSize: 14, fontWeight: '500' },\n closeLink: { marginTop: 14, padding: 8 },\n closeLinkText: { fontSize: 13 },\n});\n","import React, { useEffect, useState } from 'react';\nimport { registerHost, type CheckoutSession } from './controller';\nimport { CheckoutModal } from './CheckoutModal';\n\n// Mount ONCE near your app root. It renders nothing until a checkout is\n// presented, then hosts the full-screen checkout modal. Imperative\n// GbitXPay.present() drives it via the module controller.\n//\n// export default function App() {\n// return (\n// <GbitXPayProvider>\n// <YourApp />\n// </GbitXPayProvider>\n// );\n// }\nexport function GbitXPayProvider({ children }: { children?: React.ReactNode }): React.ReactElement {\n const [session, setSession] = useState<CheckoutSession | null>(null);\n\n useEffect(() => registerHost(setSession), []);\n\n return (\n <>\n {children}\n {/* key by paymentId so each checkout gets a fresh modal (fresh latch,\n fresh state) and nothing leaks across payments. */}\n {session ? <CheckoutModal key={session.paymentId} session={session} /> : null}\n </>\n );\n}\n","import { useMemo } from 'react';\nimport { configure } from './config';\nimport { present } from './controller';\nimport type { ConfigureOptions, PresentOptions, PaymentResult } from './types';\n\nexport interface UseGbitXPay {\n configure: (options: ConfigureOptions) => Promise<void>;\n present: (options: PresentOptions) => Promise<PaymentResult>;\n}\n\n// Hook flavor of the API for components that prefer it. Thin, stable wrapper\n// over the same singleton — configure/present are module-level, so this holds\n// no state of its own; the identity is memoized for dependency arrays.\nexport function useGbitXPay(): UseGbitXPay {\n return useMemo(() => ({ configure, present }), []);\n}\n","// Single source of truth for the SDK version. Surfaced in the WebView\n// userAgent suffix (never with any credential appended) for abuse\n// throttling and analytics. Keep in sync with package.json \"version\".\nexport const SDK_VERSION = '0.1.0';\n"]}
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
|
|
3
|
+
type GbitXPayErrorCode = 'not_configured' | 'not_mounted' | 'invalid_key' | 'secret_key_used' | 'environment_mismatch' | 'onboarding_required' | 'merchant_suspended' | 'rate_limited' | 'network_error' | 'server_error' | 'invalid_arguments';
|
|
4
|
+
interface GbitXPayErrorMeta {
|
|
5
|
+
onboardingStatus?: string;
|
|
6
|
+
retryAfterSec?: number;
|
|
7
|
+
}
|
|
8
|
+
type GbitXPayErrorInit = GbitXPayErrorMeta & {
|
|
9
|
+
cause?: unknown;
|
|
10
|
+
};
|
|
11
|
+
declare class GbitXPayError extends Error {
|
|
12
|
+
readonly code: GbitXPayErrorCode;
|
|
13
|
+
readonly meta?: GbitXPayErrorMeta;
|
|
14
|
+
constructor(code: GbitXPayErrorCode, message: string, init?: GbitXPayErrorInit);
|
|
15
|
+
toJSON(): Record<string, unknown>;
|
|
16
|
+
}
|
|
17
|
+
declare function isGbitXPayError(e: unknown): e is GbitXPayError;
|
|
18
|
+
|
|
19
|
+
type Environment = 'live' | 'test';
|
|
20
|
+
type PaymentStatus = 'PENDING' | 'AWAITING_PAYMENT' | 'UNDERPAID' | 'CONFIRMING' | 'CONFIRMED' | 'EXPIRED' | 'FAILED' | 'CANCELLED';
|
|
21
|
+
interface SanitizedPayment {
|
|
22
|
+
id: string;
|
|
23
|
+
status: PaymentStatus;
|
|
24
|
+
amount: string;
|
|
25
|
+
currency: string;
|
|
26
|
+
crypto: string | null;
|
|
27
|
+
network: string | null;
|
|
28
|
+
amountCrypto: string | null;
|
|
29
|
+
amountPaid: string | null;
|
|
30
|
+
mode: 'LIVE' | 'SANDBOX';
|
|
31
|
+
confirmedAt: string | null;
|
|
32
|
+
expiresAt: string;
|
|
33
|
+
}
|
|
34
|
+
type CancelReason = 'user_closed' | 'dismissed' | 'back_button' | 'load_failed';
|
|
35
|
+
type ExpiredReason = 'expired' | 'client_backstop';
|
|
36
|
+
type PaymentResult = {
|
|
37
|
+
status: 'confirmed';
|
|
38
|
+
payment: SanitizedPayment | null;
|
|
39
|
+
} | {
|
|
40
|
+
status: 'cancelled';
|
|
41
|
+
reason?: CancelReason;
|
|
42
|
+
payment?: SanitizedPayment | null;
|
|
43
|
+
} | {
|
|
44
|
+
status: 'expired';
|
|
45
|
+
reason?: ExpiredReason;
|
|
46
|
+
payment?: SanitizedPayment | null;
|
|
47
|
+
} | {
|
|
48
|
+
status: 'failed';
|
|
49
|
+
payment?: SanitizedPayment | null;
|
|
50
|
+
};
|
|
51
|
+
interface ConfigureOptions {
|
|
52
|
+
publishableKey: string;
|
|
53
|
+
environment?: Environment;
|
|
54
|
+
timeoutMs?: number;
|
|
55
|
+
apiBaseUrl?: string;
|
|
56
|
+
debug?: boolean;
|
|
57
|
+
}
|
|
58
|
+
interface MerchantInfo {
|
|
59
|
+
name: string;
|
|
60
|
+
website: string | null;
|
|
61
|
+
}
|
|
62
|
+
type CheckoutEventType = 'loaded' | 'confirmed' | 'cancelled' | 'expired' | 'failed' | 'closed';
|
|
63
|
+
interface CheckoutEvent {
|
|
64
|
+
type: CheckoutEventType;
|
|
65
|
+
payment?: SanitizedPayment;
|
|
66
|
+
}
|
|
67
|
+
interface PresentOptions {
|
|
68
|
+
paymentId: string;
|
|
69
|
+
clientToken: string;
|
|
70
|
+
onLoaded?: () => void;
|
|
71
|
+
onEvent?: (event: CheckoutEvent) => void;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
declare function configure(options: ConfigureOptions): Promise<void>;
|
|
75
|
+
|
|
76
|
+
declare function present(options: PresentOptions): Promise<PaymentResult>;
|
|
77
|
+
|
|
78
|
+
declare const GbitXPay: {
|
|
79
|
+
readonly configure: typeof configure;
|
|
80
|
+
readonly present: typeof present;
|
|
81
|
+
};
|
|
82
|
+
type GbitXPayApi = typeof GbitXPay;
|
|
83
|
+
|
|
84
|
+
declare function GbitXPayProvider({ children }: {
|
|
85
|
+
children?: React.ReactNode;
|
|
86
|
+
}): React.ReactElement;
|
|
87
|
+
|
|
88
|
+
interface UseGbitXPay {
|
|
89
|
+
configure: (options: ConfigureOptions) => Promise<void>;
|
|
90
|
+
present: (options: PresentOptions) => Promise<PaymentResult>;
|
|
91
|
+
}
|
|
92
|
+
declare function useGbitXPay(): UseGbitXPay;
|
|
93
|
+
|
|
94
|
+
declare function setDebug(on: boolean): void;
|
|
95
|
+
|
|
96
|
+
declare const SDK_VERSION = "0.1.0";
|
|
97
|
+
|
|
98
|
+
export { type CancelReason, type CheckoutEvent, type CheckoutEventType, type ConfigureOptions, type Environment, type ExpiredReason, GbitXPay, type GbitXPayApi, GbitXPayError, type GbitXPayErrorCode, type GbitXPayErrorMeta, GbitXPayProvider, type MerchantInfo, type PaymentResult, type PaymentStatus, type PresentOptions, SDK_VERSION, type SanitizedPayment, type UseGbitXPay, isGbitXPayError, setDebug, useGbitXPay };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
|
|
3
|
+
type GbitXPayErrorCode = 'not_configured' | 'not_mounted' | 'invalid_key' | 'secret_key_used' | 'environment_mismatch' | 'onboarding_required' | 'merchant_suspended' | 'rate_limited' | 'network_error' | 'server_error' | 'invalid_arguments';
|
|
4
|
+
interface GbitXPayErrorMeta {
|
|
5
|
+
onboardingStatus?: string;
|
|
6
|
+
retryAfterSec?: number;
|
|
7
|
+
}
|
|
8
|
+
type GbitXPayErrorInit = GbitXPayErrorMeta & {
|
|
9
|
+
cause?: unknown;
|
|
10
|
+
};
|
|
11
|
+
declare class GbitXPayError extends Error {
|
|
12
|
+
readonly code: GbitXPayErrorCode;
|
|
13
|
+
readonly meta?: GbitXPayErrorMeta;
|
|
14
|
+
constructor(code: GbitXPayErrorCode, message: string, init?: GbitXPayErrorInit);
|
|
15
|
+
toJSON(): Record<string, unknown>;
|
|
16
|
+
}
|
|
17
|
+
declare function isGbitXPayError(e: unknown): e is GbitXPayError;
|
|
18
|
+
|
|
19
|
+
type Environment = 'live' | 'test';
|
|
20
|
+
type PaymentStatus = 'PENDING' | 'AWAITING_PAYMENT' | 'UNDERPAID' | 'CONFIRMING' | 'CONFIRMED' | 'EXPIRED' | 'FAILED' | 'CANCELLED';
|
|
21
|
+
interface SanitizedPayment {
|
|
22
|
+
id: string;
|
|
23
|
+
status: PaymentStatus;
|
|
24
|
+
amount: string;
|
|
25
|
+
currency: string;
|
|
26
|
+
crypto: string | null;
|
|
27
|
+
network: string | null;
|
|
28
|
+
amountCrypto: string | null;
|
|
29
|
+
amountPaid: string | null;
|
|
30
|
+
mode: 'LIVE' | 'SANDBOX';
|
|
31
|
+
confirmedAt: string | null;
|
|
32
|
+
expiresAt: string;
|
|
33
|
+
}
|
|
34
|
+
type CancelReason = 'user_closed' | 'dismissed' | 'back_button' | 'load_failed';
|
|
35
|
+
type ExpiredReason = 'expired' | 'client_backstop';
|
|
36
|
+
type PaymentResult = {
|
|
37
|
+
status: 'confirmed';
|
|
38
|
+
payment: SanitizedPayment | null;
|
|
39
|
+
} | {
|
|
40
|
+
status: 'cancelled';
|
|
41
|
+
reason?: CancelReason;
|
|
42
|
+
payment?: SanitizedPayment | null;
|
|
43
|
+
} | {
|
|
44
|
+
status: 'expired';
|
|
45
|
+
reason?: ExpiredReason;
|
|
46
|
+
payment?: SanitizedPayment | null;
|
|
47
|
+
} | {
|
|
48
|
+
status: 'failed';
|
|
49
|
+
payment?: SanitizedPayment | null;
|
|
50
|
+
};
|
|
51
|
+
interface ConfigureOptions {
|
|
52
|
+
publishableKey: string;
|
|
53
|
+
environment?: Environment;
|
|
54
|
+
timeoutMs?: number;
|
|
55
|
+
apiBaseUrl?: string;
|
|
56
|
+
debug?: boolean;
|
|
57
|
+
}
|
|
58
|
+
interface MerchantInfo {
|
|
59
|
+
name: string;
|
|
60
|
+
website: string | null;
|
|
61
|
+
}
|
|
62
|
+
type CheckoutEventType = 'loaded' | 'confirmed' | 'cancelled' | 'expired' | 'failed' | 'closed';
|
|
63
|
+
interface CheckoutEvent {
|
|
64
|
+
type: CheckoutEventType;
|
|
65
|
+
payment?: SanitizedPayment;
|
|
66
|
+
}
|
|
67
|
+
interface PresentOptions {
|
|
68
|
+
paymentId: string;
|
|
69
|
+
clientToken: string;
|
|
70
|
+
onLoaded?: () => void;
|
|
71
|
+
onEvent?: (event: CheckoutEvent) => void;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
declare function configure(options: ConfigureOptions): Promise<void>;
|
|
75
|
+
|
|
76
|
+
declare function present(options: PresentOptions): Promise<PaymentResult>;
|
|
77
|
+
|
|
78
|
+
declare const GbitXPay: {
|
|
79
|
+
readonly configure: typeof configure;
|
|
80
|
+
readonly present: typeof present;
|
|
81
|
+
};
|
|
82
|
+
type GbitXPayApi = typeof GbitXPay;
|
|
83
|
+
|
|
84
|
+
declare function GbitXPayProvider({ children }: {
|
|
85
|
+
children?: React.ReactNode;
|
|
86
|
+
}): React.ReactElement;
|
|
87
|
+
|
|
88
|
+
interface UseGbitXPay {
|
|
89
|
+
configure: (options: ConfigureOptions) => Promise<void>;
|
|
90
|
+
present: (options: PresentOptions) => Promise<PaymentResult>;
|
|
91
|
+
}
|
|
92
|
+
declare function useGbitXPay(): UseGbitXPay;
|
|
93
|
+
|
|
94
|
+
declare function setDebug(on: boolean): void;
|
|
95
|
+
|
|
96
|
+
declare const SDK_VERSION = "0.1.0";
|
|
97
|
+
|
|
98
|
+
export { type CancelReason, type CheckoutEvent, type CheckoutEventType, type ConfigureOptions, type Environment, type ExpiredReason, GbitXPay, type GbitXPayApi, GbitXPayError, type GbitXPayErrorCode, type GbitXPayErrorMeta, GbitXPayProvider, type MerchantInfo, type PaymentResult, type PaymentStatus, type PresentOptions, SDK_VERSION, type SanitizedPayment, type UseGbitXPay, isGbitXPayError, setDebug, useGbitXPay };
|