@invonetwork/web-sdk 0.2.0 → 0.2.1

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.
Files changed (3) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +393 -219
  3. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -3,6 +3,17 @@
3
3
  All notable changes to `@invonetwork/web-sdk` are documented here. This project follows
4
4
  [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## [0.2.1] — 2026-06-30
7
+
8
+ Docs only — no code change (republished so the npm page README is current).
9
+
10
+ - Rewrote the README into a complete integration/deployment guide: capability
11
+ overview, architecture, deployment prerequisites, per-flow sections (currency
12
+ purchase, item purchase, sends, transfers, passkeys), webhooks, errors, and a
13
+ full API reference for both entries.
14
+ - Added INVO console onboarding: `https://console.invo.network` (production) and
15
+ `https://dev.console.invo.network` (testing/sandbox), mapped to their API base URLs.
16
+
6
17
  ## [0.2.0] — 2026-06-30
7
18
 
8
19
  Adds **item purchase** (spend existing game currency on an in-game item, §4.8) — an
package/README.md CHANGED
@@ -1,219 +1,393 @@
1
- # @invonetwork/web-sdk
2
-
3
- INVO Web SDK for partner **web** platforms **currency purchase** + **passkey (WebAuthn)** verification for cross-game **sends/transfers**. The web analog of the Unity/UE plugins.
4
-
5
- > **Status:** v0.1.0. The backend this wraps is **live** — the INVO-hosted checkout page, sessions, rails, and webhooks are deployed on sandbox + production, so you can build and test against sandbox today. Full, current API reference + flow docs: **https://docs.invo.network/docs/currency-purchase** and **https://docs.invo.network/docs/game-developer-integration**.
6
-
7
- ## Install
8
-
9
- ```bash
10
- npm install @invonetwork/web-sdk
11
- ```
12
-
13
- > Published under the INVO-owned `@invonetwork` npm org. (Until the first `npm publish`, develop with `npm link` or a local install.)
14
-
15
- ## Two entry points (the game secret never reaches the browser)
16
-
17
- | Import | Runs | Holds | Does |
18
- |---|---|---|---|
19
- | `@invonetwork/web-sdk/server` | your server (Node ≥18) | the **game secret** | mint player token, initiate send/transfer, currency purchase, item purchase |
20
- | `@invonetwork/web-sdk` | the browser | a short-lived **player token** | enroll passkey, approve, self-claim |
21
-
22
- ## Base URLs
23
-
24
- - Production: `https://invo.network`
25
- - Sandbox: `https://sandbox.invo.network/sandbox`
26
-
27
- `baseUrl` must be `https://` (the game secret and player token travel in request headers); `http://localhost` is allowed for local development only.
28
-
29
- ## Server (Node)
30
-
31
- ```ts
32
- import { InvoServer } from "@invonetwork/web-sdk/server";
33
-
34
- const invo = new InvoServer({
35
- gameSecret: process.env.INVO_GAME_SECRET!, // server-side only
36
- baseUrl: "https://sandbox.invo.network/sandbox",
37
- });
38
-
39
- // 1. mint a short-lived token for the browser
40
- const { token } = await invo.mintPlayerToken({ playerEmail: "p@example.com" });
41
-
42
- // 2a. buy currency hosted checkout (recommended; INVO's page handles the processor)
43
- const { checkoutUrl } = await invo.createCheckout({
44
- playerEmail: "p@example.com",
45
- usdAmount: "20.00",
46
- rail: "platform", // optional: "platform" (card, default) | "game" | "steam"
47
- metadata: { yourOrderId: "ord_42" }, // echoed back on the purchase.completed webhook
48
- });
49
- // → open checkoutUrl in a WebView/redirect or an iframe (see "Consuming the checkout")
50
-
51
- // 2b. or initiate a send; inspect verificationMethod
52
- const send = await invo.initiateSend({
53
- clientRequestId: crypto.randomUUID(),
54
- senderPlayerName: "P", senderPlayerEmail: "p@example.com", senderPlayerPhone: "+15555550100",
55
- receiverPlayerEmail: "q@example.com", receiverPlayerPhone: "+15555550111",
56
- receivingGameId: 123456, amount: "50",
57
- });
58
- if (send.verificationMethod === "in_app") {
59
- // hand send.transactionId + the player token to the browser to approve via passkey
60
- } else if (send.verificationMethod === "sms") {
61
- // sender not enrolled — fall back to the SMS-PIN UI
62
- } else if (send.guardianApproval) {
63
- // minor/guardian path (HTTP 202): pending guardian approval — do NOT show the PIN UI
64
- }
65
- ```
66
-
67
- ## Browser
68
-
69
- ```ts
70
- import { InvoClient } from "@invonetwork/web-sdk";
71
-
72
- const invo = new InvoClient({
73
- token,
74
- baseUrl: "https://sandbox.invo.network/sandbox",
75
- // Optional: player tokens live ~15 min. If a call fails with SDK_TOKEN_EXPIRED,
76
- // the SDK calls this once for a fresh token (re-minted by your backend) and
77
- // retries the request transparently.
78
- refreshToken: () => fetch("/invo/token").then((r) => r.json()).then((j) => j.token),
79
- });
80
-
81
- await invo.enrollPasskey(); // once per user
82
- await invo.approveSend(transactionId); // or approveTransfer(...)
83
- await invo.confirmReceiptSend(transactionId); // recipient self-claim
84
-
85
- // Interchangeable methods (optional): prove an already-enrolled method (e.g. the
86
- // INVO app device key) to authorize adding this passkey, then enroll it.
87
- await invo.linkDevice(linkId); // → { status: "authorized" }
88
- await invo.enrollPasskey();
89
- ```
90
-
91
- Currency purchase has **no browser SDK method** the server mints `checkoutUrl`; the browser just opens it.
92
-
93
- ## Consuming the checkout (browser)
94
-
95
- `createCheckout` returns a `checkoutUrl` (15-min, single-use). Open it either way:
96
-
97
- - **WebView / full-page redirect** (works everywhere, no setup): on success the page redirects to your `successUrl`.
98
- - **Embedded `<iframe>`** — **works by default** (any https origin may frame it; no allow-listing): the page does *not* redirect your top window — listen for the `INVO_CHECKOUT_COMPLETE` postMessage.
99
-
100
- ```ts
101
- const iframe = document.createElement("iframe");
102
- iframe.src = checkoutUrl;
103
- iframe.style.cssText = "width:440px;height:720px;border:0";
104
- document.body.appendChild(iframe);
105
-
106
- window.addEventListener("message", (e) => {
107
- if (e.origin !== "https://invo.network") return; // sandbox: "https://sandbox.invo.network"
108
- if (e.data?.type === "INVO_CHECKOUT_COMPLETE") {
109
- // UX hint only (unsigned). data = { status:'success', new_balance, currency_name, transaction_id }
110
- refreshBalanceOptimistically(e.data.data.new_balance);
111
- }
112
- });
113
- ```
114
-
115
- The hosted page handles **card entry, saved cards, and 3-D Secure** (including a top-level break-out when embedded). You build no payment UI and never touch card data.
116
-
117
- **Completion is authoritative via the `purchase.completed` webhook** (HMAC-signed). **Dedupe on `X-Invo-Idempotency-Key`** (stable across retries/replays — *not* `X-Invo-Event-Id`, which changes per delivery). Treat `INVO_CHECKOUT_COMPLETE` as a UX hint; grant currency off the webhook (or re-read the balance).
118
-
119
- ## Payment rails (neutral names)
120
-
121
- The `rail` passed to `createCheckout` selects the in-page experience — all branded as INVO, no visible redirect:
122
- - `"platform"` (default) card checkout on the hosted page.
123
- - `"game"` — regional / game-store methods, embedded in-page.
124
- - `"steam"` Steam titles use the dedicated Steam flow; a `steam` session only shows an in-client hand-off, it doesn't drive the purchase.
125
-
126
- Provider/processor names are an internal backend detail and never appear in the API. (`purchaseCurrency()` on the server is an advanced direct path for partners who tokenize cards themselves most integrations should use `createCheckout`.)
127
-
128
- ## Sends & transfers (move existing game currency, no real money)
129
-
130
- Distinct from *purchase* (which brings real money in), **sends** and **transfers** move
131
- already-owned game currency from one player to another and are authorized by the
132
- sender's **passkey** (or an SMS PIN if they aren't enrolled). The two are parallel
133
- flows with the same shape:
134
-
135
- | | Send | Transfer |
136
- |---|---|---|
137
- | Initiate (server) | `initiateSend` → `/api/currency-sends/initiate-send` | `initiateTransfer` → `/api/transfers/initiate-transfer` |
138
- | Parties | `sender*` / `receiver*`, `receivingGameId` | `source*` / `target*`, `targetGameId` |
139
- | Approve (browser) | `approveSend` | `approveTransfer` (also returns the sender's **claim code**) |
140
- | Recipient claim (browser) | `confirmReceiptSend` | `confirmReceiptTransfer` |
141
-
142
- ### End-to-end (transfer shown; send is identical with `*Send` methods)
143
-
144
- ```ts
145
- // 1. SERVER — initiate, then branch on how the sender must verify
146
- const t = await invo.initiateTransfer({
147
- clientRequestId: crypto.randomUUID(),
148
- sourcePlayerName: "P", sourcePlayerEmail: "p@example.com", sourcePlayerPhone: "+15555550100",
149
- targetPlayerEmail: "q@example.com", targetPlayerPhone: "+15555550111",
150
- targetGameId: 123456, amount: "50",
151
- });
152
- // t.verificationMethod: "in_app" (passkey) | "sms" (PIN fallback) | undefined (+ t.guardianApproval on the minor/guardian path)
153
-
154
- // 2. BROWSER — the sender approves with their passkey (hand them t.transactionId + the player token)
155
- const approved = await invo.approveTransfer(t.transactionId);
156
- // approved.claimCode + approved.claimCodeExpiresAt — deliver to the recipient if they can't self-claim
157
-
158
- // 3. BROWSER — the recipient claims. If they have a passkey, self-claim; else fall back to the claim code.
159
- try {
160
- await invo.confirmReceiptTransfer(t.transactionId);
161
- } catch (e) {
162
- if (e instanceof InvoError && e.isReceiverNotEnrolled) {
163
- // recipient has no passkey here → show a claim-code entry UI using approved.claimCode
164
- } else throw e;
165
- }
166
- ```
167
-
168
- - **`verificationMethod`** comes from initiate: `"in_app"` → passkey approve; `"sms"` → the sender wasn't enrolled and a PIN was sent (build a PIN-entry fallback); `undefined` with `guardianApproval` → minor/guardian path (do **not** show the PIN UI).
169
- - **Claim codes** are only returned by `approveTransfer` (transfer flow). They're the out-of-band fallback when the recipient isn't passkey-enrolled.
170
- - **`isReceiverNotEnrolled`** on the `confirmReceipt*` error is the explicit signal to switch to claim-code entry.
171
- - Transfer self-claim additionally requires the tenant's `SDK_TRANSFER_CONFIRM_RECEIPT_ENABLED` flag; if it's off, surface the claim-code path instead.
172
-
173
- ## Item purchase (spend game currency on an in-game item)
174
-
175
- Distinct from *currency purchase* (real money **in**): an **item purchase spends the
176
- currency a player already owns** to buy an in-game item. It's a balance debit — **no
177
- real money, no payment rail, no passkey** authenticated server-side by the game
178
- secret, so it lives on the **`/server`** entry. Amounts are in **game-currency units**
179
- (not USD).
180
-
181
- ```ts
182
- const item = await invo.purchaseItem({
183
- clientRequestId: crypto.randomUUID(), // idempotency key, unique per game
184
- playerEmail: "p@example.com",
185
- playerName: "P",
186
- itemId: "sword_001",
187
- itemName: "Legendary Sword",
188
- itemQuantity: 1,
189
- unitPrice: "100.00",
190
- totalPrice: "100.00", // must equal unitPrice × itemQuantity (±0.01)
191
- // optional: playerPhone, itemDescription, itemCategory
192
- });
193
- // item.status === "success", item.newBalance (post-spend), item.previousBalance,
194
- // item.transactionId, item.orderId, item.financialBreakdown { total_paid, developer_revenue, platform_fee }
195
- ```
196
-
197
- - **Grant the item off the `item.purchased` webhook**, not just this response the webhook fires atomically with the spend (dedupe on `X-Invo-Idempotency-Key`). INVO debits currency; your game owns the catalog and grants the item.
198
- - **Idempotent** on `clientRequestId` — a duplicate throws a `409` `InvoError` (`err.isDuplicateRequest`).
199
- - **Insufficient balance** throws a `400` (`err.isInsufficientBalance`; `required_amount` + `current_balance` on `err.body`).
200
- - **Throttles** return `429` with `err.retryAfter` (seconds). Validation (missing fields, quantity outside `1..1000`, price `≤0`/`>999999.99`/non-decimal, total ≠ unit×qty) throws `INVALID_INPUT` **before** any network call.
201
- - Fee split is **90% developer / 10% INVO** by default (per-partner override). Not guardian-gated (the currency was already guardian-approved when it entered the wallet).
202
-
203
- Companion reads (server): `invo.getItemPurchaseHistory({ playerEmail, limit?, offset? })` and `invo.getItemOrderDetails({ orderId | transactionId | clientRequestId })` pass **exactly one** id; use `clientRequestId` for recovery ("did this purchase complete?").
204
-
205
- ## Errors
206
-
207
- Every failure throws `InvoError` with `.code` (when present), `.status`, `.message`, `.body`. Branch on `.code`; for the handful of state errors with no `code` (e.g. `receiver_not_enrolled_use_claim_code`), use `.message` / the `.isReceiverNotEnrolled` helper. `.isTokenExpired` flags an expired token — if you pass `refreshToken` to `InvoClient` the SDK handles this for you (one re-mint + retry); otherwise re-mint server-side and retry. Client-side input guards (e.g. a USD amount outside `0 < x ≤ 999.99`, a missing `purchaseReference`, or `rail:"steam"` on `purchaseCurrency`) also throw `InvoError` with `.status === 0` before any network call.
208
-
209
- ## Scripts
210
-
211
- ```bash
212
- npm run build # tsup → dist (ESM + CJS + d.ts)
213
- npm run typecheck # tsc --noEmit
214
- npm test # vitest
215
- ```
216
-
217
- ## License
218
-
219
- Proprietary — © Invo Tech Inc. See `LICENSE` (the partner-distribution license is a business decision; swap to MIT/Apache-2.0 if preferred).
1
+ # @invonetwork/web-sdk
2
+
3
+ First-party TypeScript SDK for integrating **INVO** into partner **web** platforms (storefronts, web games, dashboards). It wraps INVO's web money flows behind a typed, versioned API — the web analog of the Unity/Unreal plugins.
4
+
5
+ > **Status:** `v0.2.0`, published on npm. The backend it wraps is **live** on sandbox + production, so you can build and test against sandbox today.
6
+ > Canonical partner reference: **https://docs.invo.network/docs/currency-purchase** and **https://docs.invo.network/docs/game-developer-integration**.
7
+
8
+ ## What it does
9
+
10
+ Four money flows plus passkey (WebAuthn) authentication, split across a trusted server entry and an untrusted browser entry:
11
+
12
+ | Flow | Direction | Real money? | Passkey? | Where |
13
+ |---|---|---|---|---|
14
+ | **Currency purchase** | real money **→** game currency | yes (card/rails) | no | server initiates, browser opens hosted checkout |
15
+ | **Item purchase** | game currency **→** in-game item | no (balance debit) | no | server only |
16
+ | **Send** | currency **→** another player (cross-game) | no | yes (sender approves) | server initiates, browser approves/claims |
17
+ | **Transfer** | currency **→** another player (transfer rail) | no | yes (sender approves) | server initiates, browser approves/claims |
18
+
19
+ The **game secret stays on your server**; the browser only ever holds a short-lived, game-scoped **player token**.
20
+
21
+ ## Contents
22
+
23
+ - [Install](#install)
24
+ - [Architecture & the two entry points](#architecture--the-two-entry-points)
25
+ - [Deployment prerequisites](#deployment-prerequisites)
26
+ - [Configuration](#configuration)
27
+ - [Currency purchase (real money in)](#currency-purchase-real-money-in)
28
+ - [Item purchase (spend game currency)](#item-purchase-spend-game-currency)
29
+ - [Sends & transfers (move currency between players)](#sends--transfers-move-currency-between-players)
30
+ - [Passkeys (enroll, approve, link)](#passkeys-enroll-approve-link)
31
+ - [Webhooks](#webhooks)
32
+ - [Errors](#errors)
33
+ - [API reference](#api-reference)
34
+ - [Scripts & versioning](#scripts--versioning)
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ npm install @invonetwork/web-sdk
40
+ ```
41
+
42
+ Node 18 on the server (uses the global `fetch`). The browser build ships ESM + CJS + types.
43
+
44
+ ## Get your account & game secret (INVO console)
45
+
46
+ Sign up, create your game, and copy its credentials (the **game secret**, plus your WebAuthn **RP ID / origins**) in the INVO console. Use the console that matches the environment you're building against:
47
+
48
+ | Environment | Console — sign up, manage games, copy your game secret | API `baseUrl` |
49
+ |---|---|---|
50
+ | **Testing / sandbox** | **https://dev.console.invo.network** | `https://sandbox.invo.network/sandbox` |
51
+ | **Production** | **https://console.invo.network** | `https://invo.network` |
52
+
53
+ Build and test against the **dev console + sandbox** first, then switch to the **production console + `https://invo.network`** for launch. **Each environment has its own game secret — never mix them**, and keep the secret server-side only.
54
+
55
+ ## Architecture & the two entry points
56
+
57
+ ```
58
+ ┌──────────────────────────────┐ ┌──────────────────────────────┐
59
+ YOUR SERVER (trusted) │ │ THE BROWSER (untrusted) │
60
+ │ @invonetwork/web-sdk/server │ │ @invonetwork/web-sdk │
61
+ │ │ mint │ │
62
+ │ • holds X-Game-Secret-Key │ ──────► │ • holds short-lived token │
63
+ mintPlayerToken() token │ (~15 min, game-scoped) │
64
+ │ • initiateSend/Transfer() │ │ • enrollPasskey() │
65
+ │ • createCheckout() │ │ • approveSend/Transfer() │
66
+ │ • purchaseCurrency() │ │ • confirmReceipt*() │
67
+ │ • purchaseItem() │ │ • linkDevice() │
68
+ └───────────────┬───────────────┘ └───────────────┬──────────────┘
69
+ └──────────────► INVO BACKEND ◄────────────┘
70
+ ```
71
+
72
+ | Import | Runs on | Holds | Responsibilities |
73
+ |---|---|---|---|
74
+ | `@invonetwork/web-sdk/server` | your backend (Node ≥18) | the **game secret** | mint player tokens; initiate sends/transfers; currency purchase; item purchase |
75
+ | `@invonetwork/web-sdk` | the browser | a short-lived **player token** | passkey enroll, approve, self-claim, device link |
76
+
77
+ **Never import `/server` into browser code** — it carries the game secret. The two entries are built separately for exactly this reason.
78
+
79
+ ## Deployment prerequisites
80
+
81
+ INVO provisions these per tenant before the flows go live (most are super_admin-only, set by INVO — coordinate with your INVO contact):
82
+
83
+ **For sends/transfers + passkeys**
84
+ - `SDK_TRANSFER_VERIFICATION_ENABLED` (master) — on.
85
+ - `SDK_WEBAUTHN_ENABLED` (master) on.
86
+ - `SDK_TRANSFER_CONFIRM_RECEIPT_ENABLED` required for **transfer** self-claim.
87
+ - Tenant migrated (`games.sdk_verification_enabled`).
88
+ - **Per-tenant RP ID + origins** (`webauthn_rp_id`, `webauthn_origins`). There's no separate "webauthn on" flag — *the presence of a valid RP ID is the gate*. Until it's set, WebAuthn endpoints return `403 WEBAUTHN_NOT_ENABLED_FOR_TENANT`. **You must serve your integration from an origin listed in `webauthn_origins`,** or passkeys won't validate.
89
+
90
+ **For currency purchase**
91
+ - `platform` (card) rail is always on; `game`/`steam` rails are off by default and each gated by their own flag + per-game config.
92
+ - Honors the platform `purchases` kill switch (`503 flow_paused` when paused).
93
+
94
+ **For item purchase**
95
+ - The game must be in `live` or `testing` state (else `403`). No passkey/payment flags involved — it's a balance debit.
96
+
97
+ **On your side:** store the game secret in server-side config/secrets (never ship it to the browser), and expose a small endpoint that calls `mintPlayerToken` so the browser can fetch/refresh its token.
98
+
99
+ ## Configuration
100
+
101
+ ```ts
102
+ import { InvoServer } from "@invonetwork/web-sdk/server";
103
+ import { InvoClient } from "@invonetwork/web-sdk";
104
+
105
+ const server = new InvoServer({
106
+ gameSecret: process.env.INVO_GAME_SECRET!, // server-side only
107
+ baseUrl: "https://sandbox.invo.network/sandbox", // prod: "https://invo.network"
108
+ timeoutMs: 30_000, // optional, default 30s
109
+ // fetch: customFetch, // optional override
110
+ });
111
+
112
+ const client = new InvoClient({
113
+ token, // from your /mint endpoint
114
+ baseUrl: "https://sandbox.invo.network/sandbox",
115
+ refreshToken: () => // optional: auto re-mint + retry on token expiry
116
+ fetch("/invo/token", { method: "POST" }).then((r) => r.json()).then((j) => j.token),
117
+ });
118
+ ```
119
+
120
+ **Base URLs** (manage each environment in its [console](#get-your-account--game-secret-invo-console))
121
+ - Production: `https://invo.network` console: `https://console.invo.network`
122
+ - Sandbox / testing: `https://sandbox.invo.network/sandbox` — console: `https://dev.console.invo.network` (sandbox prepends the `/sandbox` prefix; the SDK absorbs it via `baseUrl`)
123
+
124
+ `baseUrl` must be `https://` the game secret and player token travel in request headers, so plaintext is rejected. `http://localhost` is allowed for local dev only.
125
+
126
+ **Player tokens** live ~15 minutes and are game-scoped. Mint one per browser session. If you pass `refreshToken` to `InvoClient`, the SDK transparently re-mints and retries once on `SDK_TOKEN_EXPIRED` (it re-runs the whole passkey ceremony so it never replays a single-use challenge).
127
+
128
+ ---
129
+
130
+ ## Currency purchase (real money in)
131
+
132
+ Buy game currency with real money. Authenticated by the **payment rail**, not a passkey there's no WebAuthn step. Two paths:
133
+
134
+ ### Hosted checkout (recommended — PCI-light, you never touch card data)
135
+
136
+ ```ts
137
+ // SERVER
138
+ const { checkoutUrl, sessionId, expiresAt } = await server.createCheckout({
139
+ playerEmail: "p@example.com",
140
+ usdAmount: "20.00", // USD, 0 < x 999.99
141
+ rail: "platform", // optional: "platform" (default) | "game" | "steam"
142
+ successUrl: "https://you/buy/ok",
143
+ cancelUrl: "https://you/buy/cancel",
144
+ metadata: { yourOrderId: "ord_42" }, // echoed on the purchase.completed webhook
145
+ });
146
+ // send the browser to checkoutUrl (single-use, ~15 min)
147
+ ```
148
+
149
+ Open `checkoutUrl` either way:
150
+
151
+ - **Full-page redirect / WebView** — works everywhere; on success the page redirects to your `successUrl`.
152
+ - **Embedded `<iframe>`** works by default from any https origin (no allow-listing). The page does *not* redirect your top window; listen for the `INVO_CHECKOUT_COMPLETE` postMessage:
153
+
154
+ ```ts
155
+ // BROWSER
156
+ const iframe = document.createElement("iframe");
157
+ iframe.src = checkoutUrl;
158
+ iframe.style.cssText = "width:440px;height:720px;border:0";
159
+ document.body.appendChild(iframe);
160
+
161
+ window.addEventListener("message", (e) => {
162
+ if (e.origin !== "https://invo.network") return; // sandbox: "https://sandbox.invo.network"
163
+ if (e.data?.type === "INVO_CHECKOUT_COMPLETE") {
164
+ // UX hint ONLY (unsigned). data = { status, new_balance, currency_name, transaction_id }
165
+ refreshBalanceOptimistically(e.data.data.new_balance);
166
+ }
167
+ });
168
+ ```
169
+
170
+ The hosted page handles card entry, saved cards, and 3-D Secure (with a top-level break-out when framed). **Grant currency off the `purchase.completed` webhook**, not the postMessage hint. Currency purchase has **no browser SDK method** — the browser only opens the URL.
171
+
172
+ ### Payment rails (neutral names)
173
+
174
+ The `rail` selects the in-page experience — all branded INVO, no visible redirect:
175
+ - `"platform"` (default) card checkout.
176
+ - `"game"` regional / game-store methods.
177
+ - `"steam"` Steam titles hand off to the in-client Steam flow.
178
+
179
+ Provider/processor names are an internal detail and never appear in the API.
180
+
181
+ ### Direct rail (advanced — you tokenize the card yourself)
182
+
183
+ ```ts
184
+ const purchase = await server.purchaseCurrency({
185
+ playerEmail: "p@example.com",
186
+ usdAmount: "20.00",
187
+ purchaseReference: crypto.randomUUID(), // idempotency key, required
188
+ rail: "platform",
189
+ paymentMethodId: "pm_...", // a tokenized payment method
190
+ });
191
+ // purchase.status:
192
+ // "success" → captured, purchase.newBalance updated
193
+ // "requires_action" → 3-D Secure: run the client action with purchase.clientSecret,
194
+ // then call server.confirmPayment({ paymentIntentId })
195
+ // "pending_payment" → redirect the browser to purchase.paymentUrl (game rail)
196
+ ```
197
+ `rail: "steam"` is rejected here (`WRONG_RAIL_ENDPOINT`) Steam uses its own in-client flow. Reconcile with `server.getOrderDetails({ orderId })`. Most browser integrations should use hosted checkout instead.
198
+
199
+ ---
200
+
201
+ ## Item purchase (spend game currency)
202
+
203
+ Spend the currency a player **already owns** to buy an in-game item. A balance debit **no real money, no payment rail, no passkey** server-side only. Amounts are in **game-currency units** (not USD).
204
+
205
+ ```ts
206
+ const item = await server.purchaseItem({
207
+ clientRequestId: crypto.randomUUID(), // idempotency key, unique per game
208
+ playerEmail: "p@example.com",
209
+ playerName: "P",
210
+ itemId: "sword_001",
211
+ itemName: "Legendary Sword",
212
+ itemQuantity: 1, // integer 1..1000
213
+ unitPrice: "100.00", // > 0 and ≤ 999999.99
214
+ totalPrice: "100.00", // must equal unitPrice × itemQuantity (±0.01)
215
+ // optional: playerPhone, itemDescription, itemCategory
216
+ });
217
+ // item.status === "success"
218
+ // item.newBalance / item.previousBalance / item.currencyName
219
+ // item.transactionId / item.orderId
220
+ // item.financialBreakdown { total_paid, developer_revenue, platform_fee }
221
+ ```
222
+
223
+ - **Grant the item off the `item.purchased` webhook**, not just this response. INVO debits currency and records the purchase; **your game owns the item catalog and grants the item.** The webhook fires atomically with the spend.
224
+ - **Idempotent** on `clientRequestId` — a duplicate throws `409` (`err.isDuplicateRequest`).
225
+ - **Insufficient balance** throws `400` (`err.isInsufficientBalance`; `required_amount` + `current_balance` on `err.body`).
226
+ - **Throttled** calls throw `429` with `err.retryAfter` (seconds).
227
+ - Client-side validation (missing fields, quantity outside `1..1000`, bad price, total ≠ unit×qty) throws `INVALID_INPUT` **before** any network call.
228
+ - Fee split: **90% developer / 10% INVO** by default (per-partner override). Not guardian-gated.
229
+
230
+ **Companion reads:** `server.getItemPurchaseHistory({ playerEmail, limit?, offset? })` and `server.getItemOrderDetails({ orderId | transactionId | clientRequestId })` (pass **exactly one** id — use `clientRequestId` for recovery: "did this purchase complete?").
231
+
232
+ ---
233
+
234
+ ## Sends & transfers (move currency between players)
235
+
236
+ Move already-owned game currency from one player to another, authorized by the **sender's passkey** (or an SMS PIN if they aren't enrolled). **Send** and **transfer** are parallel flows:
237
+
238
+ | | Send | Transfer |
239
+ |---|---|---|
240
+ | Initiate (server) | `initiateSend` | `initiateTransfer` |
241
+ | Parties | `sender*` / `receiver*` + `receivingGameId` | `source*` / `target*` + `targetGameId` |
242
+ | Approve (browser) | `approveSend` | `approveTransfer` — also returns the sender's **claim code** |
243
+ | Recipient claim (browser) | `confirmReceiptSend` | `confirmReceiptTransfer` |
244
+
245
+ ```ts
246
+ // 1. SERVER — initiate, then branch on how the sender must verify
247
+ const t = await server.initiateTransfer({
248
+ clientRequestId: crypto.randomUUID(),
249
+ sourcePlayerName: "P", sourcePlayerEmail: "p@example.com", sourcePlayerPhone: "+15555550100",
250
+ targetPlayerEmail: "q@example.com", targetPlayerPhone: "+15555550111",
251
+ targetGameId: 123456, amount: "50",
252
+ });
253
+ // (initiateSend uses sender*/receiver* + receivingGameId instead)
254
+
255
+ switch (true) {
256
+ case t.verificationMethod === "in_app": // sender is passkey-enrolled → approve in the browser
257
+ case t.verificationMethod === "sms": // not enrolled, a PIN was sent → show a PIN-entry fallback
258
+ case !!t.guardianApproval: // minor/guardian path (HTTP 202) → do NOT show the PIN UI
259
+ }
260
+
261
+ // 2. BROWSER — the sender approves with their passkey (give them t.transactionId + the player token)
262
+ const approved = await client.approveTransfer(t.transactionId); // or approveSend(...)
263
+ // approved.claimCode + approved.claimCodeExpiresAt (transfer only) — deliver if the recipient can't self-claim
264
+
265
+ // 3. BROWSER — the recipient claims with their passkey; fall back to the claim code if not enrolled
266
+ try {
267
+ await client.confirmReceiptTransfer(t.transactionId); // or confirmReceiptSend(...)
268
+ } catch (e) {
269
+ if (e instanceof InvoError && e.isReceiverNotEnrolled) {
270
+ // recipient has no passkey here → show claim-code entry using approved.claimCode
271
+ } else throw e;
272
+ }
273
+ ```
274
+
275
+ - **`verificationMethod`** (from initiate): `"in_app"` → passkey approve; `"sms"` → un-enrolled, PIN sent; `undefined` + `guardianApproval` → minor/guardian (HTTP 202), do **not** show the PIN UI.
276
+ - **Claim codes** are returned only by `approveTransfer`; they're the out-of-band fallback when the recipient isn't enrolled.
277
+ - **`err.isReceiverNotEnrolled`** on `confirmReceipt*` is the explicit signal to switch to claim-code entry.
278
+ - Transfer self-claim additionally requires `SDK_TRANSFER_CONFIRM_RECEIPT_ENABLED`; if it's off, surface the claim-code path.
279
+
280
+ ---
281
+
282
+ ## Passkeys (enroll, approve, link)
283
+
284
+ Passkeys (WebAuthn) replace the SMS PIN for approving sends/transfers. The browser SDK wraps `navigator.credentials.create/get`, base64url encoding, challenge round-trips, and error mapping.
285
+
286
+ ```ts
287
+ // Enroll once per user (no-op to call again — the backend excludes already-enrolled credentials)
288
+ await client.enrollPasskey();
289
+
290
+ // Interchangeable methods (optional): prove an already-enrolled method (e.g. the INVO app
291
+ // device key) to authorize adding THIS passkey, then enroll. Without this, enrolling a second
292
+ // method is blocked with ENROLLMENT_REQUIRES_PROOF.
293
+ await client.linkDevice(linkId); // → { status: "authorized" }
294
+ await client.enrollPasskey();
295
+ ```
296
+
297
+ - **User verification is required** on every approve/claim (a missing-UV assertion fails closed).
298
+ - Challenges are single-use and bound to `{flow}:{transactionId}`.
299
+ - The SDK passes the backend's WebAuthn options through unchanged (it does not hard-code `pubKeyCredParams`/`timeout`/`attestation`).
300
+
301
+ ---
302
+
303
+ ## Webhooks
304
+
305
+ The synchronous responses are for UX; **reconcile and grant value off webhooks.** They're HMAC-signed; **dedupe on the `X-Invo-Idempotency-Key` header** (stable across retries/replays — *not* `X-Invo-Event-Id`, which changes per delivery).
306
+
307
+ | Event | Fires for | Use it to |
308
+ |---|---|---|
309
+ | `purchase.completed` | every currency-purchase rail | grant currency (payload: `transaction_id, order_id, player_email, identity_id, usd_amount, currency_amount, currency_name, new_balance, rail`) |
310
+ | `purchase.failed` / `purchase.disputed` | `platform` rail only | handle failures/disputes |
311
+ | `purchase.refunded` | `game` / `steam` rails | handle refunds |
312
+ | `item.purchased` | every item purchase | **grant the in-game item** (payload includes `transaction_id, order_id, player_email, identity_id, item_id, item_name, item_quantity, unit_price, total_price, currency_name, new_balance, fee_breakdown`) |
313
+
314
+ Don't block waiting on `purchase.failed` for the `game`/`steam` rails — they only emit `completed`/`refunded`. Reconcile off `*.completed` + the status endpoints.
315
+
316
+ ---
317
+
318
+ ## Errors
319
+
320
+ Every failure throws **`InvoError`** with:
321
+ - `.code` — stable machine code when present (some txn-state errors have none — branch on `.message` for those)
322
+ - `.status` — HTTP status (`0` for client-side validation and network errors)
323
+ - `.message` — human-readable
324
+ - `.body` — the raw parsed response
325
+
326
+ Helpers:
327
+
328
+ | Helper | Meaning |
329
+ |---|---|
330
+ | `.isTokenExpired` | player token expired — re-mint + retry (automatic if `refreshToken` is set) |
331
+ | `.isReceiverNotEnrolled` | recipient has no passkey → switch to claim-code entry |
332
+ | `.isInsufficientBalance` | item purchase failed (400); `required_amount` + `current_balance` on `.body` |
333
+ | `.isDuplicateRequest` | idempotency-keyed request was a duplicate (409) |
334
+ | `.retryAfter` | seconds to back off on a 429 throttle |
335
+
336
+ Client-side guards (bad amount, missing idempotency key, `rail:"steam"` on `purchaseCurrency`, item validation) throw `InvoError` with `.status === 0` **before** any network call. Notable backend codes: `SDK_TOKEN_EXPIRED`, `TENANT_NOT_MIGRATED`, `WEBAUTHN_NOT_ENABLED_FOR_TENANT`, `WEBAUTHN_UV_REQUIRED`, `ENROLLMENT_REQUIRES_PROOF`, `WRONG_RAIL_ENDPOINT`, `flow_paused`.
337
+
338
+ ```ts
339
+ import { InvoError } from "@invonetwork/web-sdk"; // or "@invonetwork/web-sdk/server"
340
+ try {
341
+ await server.purchaseItem(/* … */);
342
+ } catch (e) {
343
+ if (e instanceof InvoError && e.isInsufficientBalance) {
344
+ showTopUp(e.body); // { required_amount, current_balance }
345
+ } else throw e;
346
+ }
347
+ ```
348
+
349
+ ---
350
+
351
+ ## API reference
352
+
353
+ ### `InvoServer` (`@invonetwork/web-sdk/server`)
354
+
355
+ | Method | Returns |
356
+ |---|---|
357
+ | `mintPlayerToken({ playerEmail })` | `{ token, expiresAt, identityId }` |
358
+ | `initiateSend(input)` | `{ transactionId, verificationMethod, guardianApproval?, raw }` |
359
+ | `initiateTransfer(input)` | `{ transactionId, verificationMethod, guardianApproval?, raw }` |
360
+ | `createCheckout(input)` | `{ sessionId, checkoutUrl, expiresAt, raw }` |
361
+ | `purchaseCurrency(input)` | `{ status, clientSecret?, paymentIntentId?, paymentUrl?, transactionId?, orderId?, newBalance?, raw }` |
362
+ | `confirmPayment({ paymentIntentId, orderId? })` | raw backend body |
363
+ | `getOrderDetails({ orderId? \| transactionId? })` | raw backend body |
364
+ | `purchaseItem(input)` | `{ status, transactionId, orderId, newBalance, previousBalance, currencyName, financialBreakdown?, raw }` |
365
+ | `getItemPurchaseHistory({ playerEmail, limit?, offset? })` | raw backend body |
366
+ | `getItemOrderDetails({ orderId? \| transactionId? \| clientRequestId? })` | raw backend body |
367
+
368
+ ### `InvoClient` (`@invonetwork/web-sdk`)
369
+
370
+ | Method | Returns |
371
+ |---|---|
372
+ | `enrollPasskey()` | `{ status, device, raw }` |
373
+ | `approveSend(txnId)` / `approveTransfer(txnId)` | `{ status, next, transactionId, claimCode?, claimCodeExpiresAt?, raw }` |
374
+ | `confirmReceiptSend(txnId)` / `confirmReceiptTransfer(txnId)` | `{ status, raw }` |
375
+ | `linkDevice(linkId)` | `{ status, raw }` |
376
+
377
+ Every method throws `InvoError` on failure. Full inline types ship with the package.
378
+
379
+ ---
380
+
381
+ ## Scripts & versioning
382
+
383
+ ```bash
384
+ npm run build # tsup → dist (ESM + CJS + d.ts)
385
+ npm run typecheck # tsc --noEmit
386
+ npm test # vitest
387
+ ```
388
+
389
+ The package follows **semver**: patch = fixes, minor = additive surface, major = breaking changes (rare, with a migration note). The server contract is backward-compatible within a major, so an old pinned SDK keeps working. Pin a version and subscribe to release notes for security updates. See [`CHANGELOG.md`](CHANGELOG.md).
390
+
391
+ ## License
392
+
393
+ Proprietary — © Invo Tech Inc. See [`LICENSE`](LICENSE).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@invonetwork/web-sdk",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "INVO Web SDK — currency purchase + passkey (WebAuthn) verification for partner web platforms.",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,