@invonetwork/web-sdk 0.2.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 CHANGED
@@ -1,8 +1,39 @@
1
1
  # @invonetwork/web-sdk
2
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.
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
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**.
5
+ > **Status:** `v0.3.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
+ - [Player balance](#player-balance)
30
+ - [Sends & transfers (move currency between players)](#sends--transfers-move-currency-between-players)
31
+ - [Passkeys (enroll, approve, link)](#passkeys-enroll-approve-link)
32
+ - [Webhooks](#webhooks)
33
+ - [Resilience & observability](#resilience--observability)
34
+ - [Errors](#errors)
35
+ - [API reference](#api-reference)
36
+ - [Scripts & versioning](#scripts--versioning)
6
37
 
7
38
  ## Install
8
39
 
@@ -10,203 +41,415 @@ INVO Web SDK for partner **web** platforms — **currency purchase** + **passkey
10
41
  npm install @invonetwork/web-sdk
11
42
  ```
12
43
 
13
- > Published under the INVO-owned `@invonetwork` npm org. (Until the first `npm publish`, develop with `npm link` or a local install.)
44
+ Node 18 on the server (uses the global `fetch`). The browser build ships ESM + CJS + types.
14
45
 
15
- ## Two entry points (the game secret never reaches the browser)
46
+ ## Get your account & game secret (INVO console)
16
47
 
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 |
48
+ 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:
21
49
 
22
- ## Base URLs
50
+ | Environment | Console — sign up, manage games, copy your game secret | API `baseUrl` |
51
+ |---|---|---|
52
+ | **Testing / sandbox** | **https://dev.console.invo.network** | `https://sandbox.invo.network/sandbox` |
53
+ | **Production** | **https://console.invo.network** | `https://invo.network` |
23
54
 
24
- - Production: `https://invo.network`
25
- - Sandbox: `https://sandbox.invo.network/sandbox`
55
+ 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.
26
56
 
27
- `baseUrl` must be `https://` (the game secret and player token travel in request headers); `http://localhost` is allowed for local development only.
57
+ ## Architecture & the two entry points
28
58
 
29
- ## Server (Node)
59
+ ```
60
+ ┌──────────────────────────────┐ ┌──────────────────────────────┐
61
+ │ YOUR SERVER (trusted) │ │ THE BROWSER (untrusted) │
62
+ │ @invonetwork/web-sdk/server │ │ @invonetwork/web-sdk │
63
+ │ │ mint │ │
64
+ │ • holds X-Game-Secret-Key │ ──────► │ • holds short-lived token │
65
+ │ • mintPlayerToken() │ token │ (~15 min, game-scoped) │
66
+ │ • initiateSend/Transfer() │ │ • enrollPasskey() │
67
+ │ • createCheckout() │ │ • approveSend/Transfer() │
68
+ │ • purchaseCurrency() │ │ • confirmReceipt*() │
69
+ │ • purchaseItem() │ │ • linkDevice() │
70
+ └───────────────┬───────────────┘ └───────────────┬──────────────┘
71
+ └──────────────► INVO BACKEND ◄────────────┘
72
+ ```
30
73
 
31
- ```ts
32
- import { InvoServer } from "@invonetwork/web-sdk/server";
74
+ | Import | Runs on | Holds | Responsibilities |
75
+ |---|---|---|---|
76
+ | `@invonetwork/web-sdk/server` | your backend (Node ≥18) | the **game secret** | mint player tokens; initiate sends/transfers; currency purchase; item purchase |
77
+ | `@invonetwork/web-sdk` | the browser | a short-lived **player token** | passkey enroll, approve, self-claim, device link |
33
78
 
34
- const invo = new InvoServer({
35
- gameSecret: process.env.INVO_GAME_SECRET!, // server-side only
36
- baseUrl: "https://sandbox.invo.network/sandbox",
37
- });
79
+ **Never import `/server` into browser code** — it carries the game secret. The two entries are built separately for exactly this reason.
38
80
 
39
- // 1. mint a short-lived token for the browser
40
- const { token } = await invo.mintPlayerToken({ playerEmail: "p@example.com" });
81
+ ## Deployment prerequisites
41
82
 
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")
83
+ INVO provisions these per tenant before the flows go live (most are super_admin-only, set by INVO coordinate with your INVO contact):
50
84
 
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
- ```
85
+ **For sends/transfers + passkeys**
86
+ - `SDK_TRANSFER_VERIFICATION_ENABLED` (master) on.
87
+ - `SDK_WEBAUTHN_ENABLED` (master) — on.
88
+ - `SDK_TRANSFER_CONFIRM_RECEIPT_ENABLED` required for **transfer** self-claim.
89
+ - Tenant migrated (`games.sdk_verification_enabled`).
90
+ - **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.
91
+
92
+ **For currency purchase**
93
+ - `platform` (card) rail is always on; `game`/`steam` rails are off by default and each gated by their own flag + per-game config.
94
+ - Honors the platform `purchases` kill switch (`503 flow_paused` when paused).
66
95
 
67
- ## Browser
96
+ **For item purchase**
97
+ - The game must be in `live` or `testing` state (else `403`). No passkey/payment flags involved — it's a balance debit.
98
+
99
+ **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.
100
+
101
+ ## Configuration
68
102
 
69
103
  ```ts
104
+ import { InvoServer } from "@invonetwork/web-sdk/server";
70
105
  import { InvoClient } from "@invonetwork/web-sdk";
71
106
 
72
- const invo = new InvoClient({
73
- token,
107
+ const server = new InvoServer({
108
+ gameSecret: process.env.INVO_GAME_SECRET!, // server-side only
109
+ baseUrl: "https://sandbox.invo.network/sandbox", // prod: "https://invo.network"
110
+ timeoutMs: 30_000, // optional, default 30s
111
+ maxRetries: 2, // optional, default 2 (0 disables)
112
+ // retryBaseDelayMs: 250, // optional backoff base
113
+ // fetch: customFetch, // optional override
114
+ // hooks: { onRequest, onResponse, onError }, // optional observability (see below)
115
+ });
116
+
117
+ const client = new InvoClient({
118
+ token, // from your /mint endpoint
74
119
  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),
120
+ refreshToken: () => // optional: auto re-mint + retry on token expiry
121
+ fetch("/invo/token", { method: "POST" }).then((r) => r.json()).then((j) => j.token),
79
122
  });
123
+ ```
80
124
 
81
- await invo.enrollPasskey(); // once per user
82
- await invo.approveSend(transactionId); // or approveTransfer(...)
83
- await invo.confirmReceiptSend(transactionId); // recipient self-claim
125
+ **Base URLs** (manage each environment in its [console](#get-your-account--game-secret-invo-console))
126
+ - Production: `https://invo.network` console: `https://console.invo.network`
127
+ - Sandbox / testing: `https://sandbox.invo.network/sandbox` — console: `https://dev.console.invo.network` (sandbox prepends the `/sandbox` prefix; the SDK absorbs it via `baseUrl`)
84
128
 
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
- ```
129
+ `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.
90
130
 
91
- Currency purchase has **no browser SDK method** the server mints `checkoutUrl`; the browser just opens it.
131
+ **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).
92
132
 
93
- ## Consuming the checkout (browser)
133
+ ---
94
134
 
95
- `createCheckout` returns a `checkoutUrl` (15-min, single-use). Open it either way:
135
+ ## Currency purchase (real money in)
96
136
 
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.
137
+ Buy game currency with real money. Authenticated by the **payment rail**, not a passkey there's no WebAuthn step. Two paths:
138
+
139
+ ### Hosted checkout (recommended — PCI-light, you never touch card data)
140
+
141
+ ```ts
142
+ // SERVER
143
+ const { checkoutUrl, sessionId, expiresAt } = await server.createCheckout({
144
+ playerEmail: "p@example.com",
145
+ usdAmount: "20.00", // USD, 0 < x ≤ 999.99
146
+ rail: "platform", // optional: "platform" (default) | "game" | "steam"
147
+ successUrl: "https://you/buy/ok",
148
+ cancelUrl: "https://you/buy/cancel",
149
+ metadata: { yourOrderId: "ord_42" }, // echoed on the purchase.completed webhook
150
+ });
151
+ // → send the browser to checkoutUrl (single-use, ~15 min)
152
+ ```
153
+
154
+ Open `checkoutUrl` either way:
155
+
156
+ - **Full-page redirect / WebView** — works everywhere; on success the page redirects to your `successUrl`.
157
+ - **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:
99
158
 
100
159
  ```ts
160
+ // BROWSER
101
161
  const iframe = document.createElement("iframe");
102
162
  iframe.src = checkoutUrl;
103
163
  iframe.style.cssText = "width:440px;height:720px;border:0";
104
164
  document.body.appendChild(iframe);
105
165
 
106
166
  window.addEventListener("message", (e) => {
107
- if (e.origin !== "https://invo.network") return; // sandbox: "https://sandbox.invo.network"
167
+ if (e.origin !== "https://invo.network") return; // sandbox: "https://sandbox.invo.network"
108
168
  if (e.data?.type === "INVO_CHECKOUT_COMPLETE") {
109
- // UX hint only (unsigned). data = { status:'success', new_balance, currency_name, transaction_id }
169
+ // UX hint ONLY (unsigned). data = { status, new_balance, currency_name, transaction_id }
110
170
  refreshBalanceOptimistically(e.data.data.new_balance);
111
171
  }
112
172
  });
113
173
  ```
114
174
 
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.
175
+ 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.
176
+
177
+ ### Payment rails (neutral names)
178
+
179
+ The `rail` selects the in-page experience — all branded INVO, no visible redirect:
180
+ - `"platform"` (default) — card checkout.
181
+ - `"game"` — regional / game-store methods.
182
+ - `"steam"` — Steam titles hand off to the in-client Steam flow.
183
+
184
+ Provider/processor names are an internal detail and never appear in the API.
185
+
186
+ ### Direct rail (advanced — you tokenize the card yourself)
187
+
188
+ ```ts
189
+ const purchase = await server.purchaseCurrency({
190
+ playerEmail: "p@example.com",
191
+ usdAmount: "20.00",
192
+ purchaseReference: crypto.randomUUID(), // idempotency key, required
193
+ rail: "platform",
194
+ paymentMethodId: "pm_...", // a tokenized payment method
195
+ });
196
+ // purchase.status:
197
+ // "success" → captured, purchase.newBalance updated
198
+ // "requires_action" → 3-D Secure: run the client action with purchase.clientSecret,
199
+ // then call server.confirmPayment({ paymentIntentId })
200
+ // "pending_payment" → redirect the browser to purchase.paymentUrl (game rail)
201
+ ```
202
+ `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.
203
+
204
+ ---
205
+
206
+ ## Item purchase (spend game currency)
207
+
208
+ 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).
209
+
210
+ ```ts
211
+ const item = await server.purchaseItem({
212
+ clientRequestId: crypto.randomUUID(), // idempotency key, unique per game
213
+ playerEmail: "p@example.com",
214
+ playerName: "P",
215
+ itemId: "sword_001",
216
+ itemName: "Legendary Sword",
217
+ itemQuantity: 1, // integer 1..1000
218
+ unitPrice: "100.00", // > 0 and ≤ 999999.99
219
+ totalPrice: "100.00", // must equal unitPrice × itemQuantity (±0.01)
220
+ // optional: playerPhone, itemDescription, itemCategory
221
+ });
222
+ // item.status === "success"
223
+ // item.newBalance / item.previousBalance / item.currencyName
224
+ // item.transactionId / item.orderId
225
+ // item.financialBreakdown { total_paid, developer_revenue, platform_fee }
226
+ ```
227
+
228
+ - **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.
229
+ - **Idempotent** on `clientRequestId` — a duplicate throws `409` (`err.isDuplicateRequest`).
230
+ - **Insufficient balance** throws `400` (`err.isInsufficientBalance`; `required_amount` + `current_balance` on `err.body`).
231
+ - **Throttled** calls throw `429` with `err.retryAfter` (seconds).
232
+ - Client-side validation (missing fields, quantity outside `1..1000`, bad price, total ≠ unit×qty) throws `INVALID_INPUT` **before** any network call.
233
+ - Fee split: **90% developer / 10% INVO** by default (per-partner override). Not guardian-gated.
234
+
235
+ **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?").
236
+
237
+ ---
116
238
 
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).
239
+ ## Player balance
118
240
 
119
- ## Payment rails (neutral names)
241
+ Read a player's currency balances (server-side, game-secret) by email or player id:
120
242
 
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.
243
+ ```ts
244
+ const { balances, summary } = await server.getPlayerBalance({ playerEmail: "p@example.com" });
245
+ // balances: [{ currencyName, availableBalance, reservedBalance, totalBalance, currencySymbol, raw }]
246
+ // or: server.getPlayerBalance({ playerId: 12345 })
247
+ ```
125
248
 
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`.)
249
+ ---
127
250
 
128
- ## Sends & transfers (move existing game currency, no real money)
251
+ ## Sends & transfers (move currency between players)
129
252
 
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:
253
+ 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:
134
254
 
135
255
  | | Send | Transfer |
136
256
  |---|---|---|
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**) |
257
+ | Initiate (server) | `initiateSend` | `initiateTransfer` |
258
+ | Parties | `sender*` / `receiver*` + `receivingGameId` | `source*` / `target*` + `targetGameId` |
259
+ | Approve (browser) | `approveSend` | `approveTransfer` also returns the sender's **claim code** |
140
260
  | Recipient claim (browser) | `confirmReceiptSend` | `confirmReceiptTransfer` |
141
261
 
142
- ### End-to-end (transfer shown; send is identical with `*Send` methods)
143
-
144
262
  ```ts
145
263
  // 1. SERVER — initiate, then branch on how the sender must verify
146
- const t = await invo.initiateTransfer({
264
+ const t = await server.initiateTransfer({
147
265
  clientRequestId: crypto.randomUUID(),
148
266
  sourcePlayerName: "P", sourcePlayerEmail: "p@example.com", sourcePlayerPhone: "+15555550100",
149
267
  targetPlayerEmail: "q@example.com", targetPlayerPhone: "+15555550111",
150
268
  targetGameId: 123456, amount: "50",
151
269
  });
152
- // t.verificationMethod: "in_app" (passkey) | "sms" (PIN fallback) | undefined (+ t.guardianApproval on the minor/guardian path)
270
+ // (initiateSend uses sender*/receiver* + receivingGameId instead)
153
271
 
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
272
+ switch (true) {
273
+ case t.verificationMethod === "in_app": // sender is passkey-enrolled → approve in the browser
274
+ case t.verificationMethod === "sms": // not enrolled, a PIN was sent show a PIN-entry fallback
275
+ case !!t.guardianApproval: // minor/guardian path (HTTP 202) → do NOT show the PIN UI
276
+ }
157
277
 
158
- // 3. BROWSER — the recipient claims. If they have a passkey, self-claim; else fall back to the claim code.
278
+ // 2. BROWSER — the sender approves with their passkey (give them t.transactionId + the player token)
279
+ const approved = await client.approveTransfer(t.transactionId); // or approveSend(...)
280
+ // approved.claimCode + approved.claimCodeExpiresAt (transfer only) — deliver if the recipient can't self-claim
281
+
282
+ // 3. BROWSER — the recipient claims with their passkey; fall back to the claim code if not enrolled
159
283
  try {
160
- await invo.confirmReceiptTransfer(t.transactionId);
284
+ await client.confirmReceiptTransfer(t.transactionId); // or confirmReceiptSend(...)
161
285
  } catch (e) {
162
286
  if (e instanceof InvoError && e.isReceiverNotEnrolled) {
163
- // recipient has no passkey here → show a claim-code entry UI using approved.claimCode
287
+ // recipient has no passkey here → show claim-code entry using approved.claimCode
164
288
  } else throw e;
165
289
  }
166
290
  ```
167
291
 
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.
292
+ - **`verificationMethod`** (from initiate): `"in_app"` → passkey approve; `"sms"` → un-enrolled, PIN sent; `undefined` + `guardianApproval` → minor/guardian (HTTP 202), do **not** show the PIN UI.
293
+ - **Claim codes** are returned only by `approveTransfer`; they're the out-of-band fallback when the recipient isn't enrolled.
294
+ - **`err.isReceiverNotEnrolled`** on `confirmReceipt*` is the explicit signal to switch to claim-code entry.
295
+ - Transfer self-claim additionally requires `SDK_TRANSFER_CONFIRM_RECEIPT_ENABLED`; if it's off, surface the claim-code path.
296
+
297
+ ---
172
298
 
173
- ## Item purchase (spend game currency on an in-game item)
299
+ ## Passkeys (enroll, approve, link)
174
300
 
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).
301
+ 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.
180
302
 
181
303
  ```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
304
+ // Enroll once per user (no-op to call again — the backend excludes already-enrolled credentials)
305
+ await client.enrollPasskey();
306
+
307
+ // Interchangeable methods (optional): prove an already-enrolled method (e.g. the INVO app
308
+ // device key) to authorize adding THIS passkey, then enroll. Without this, enrolling a second
309
+ // method is blocked with ENROLLMENT_REQUIRES_PROOF.
310
+ await client.linkDevice(linkId); // → { status: "authorized" }
311
+ await client.enrollPasskey();
312
+ ```
313
+
314
+ - **User verification is required** on every approve/claim (a missing-UV assertion fails closed).
315
+ - Challenges are single-use and bound to `{flow}:{transactionId}`.
316
+ - The SDK passes the backend's WebAuthn options through unchanged (it does not hard-code `pubKeyCredParams`/`timeout`/`attestation`).
317
+
318
+ ---
319
+
320
+ ## Webhooks
321
+
322
+ 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).
323
+
324
+ ### Verify a webhook (server)
325
+
326
+ The SDK ships the signature check so you don't hand-roll HMAC. Pass the **raw** request bytes (never a re-serialized object) and the `X-Invo-Signature` header:
327
+
328
+ ```ts
329
+ import { verifyWebhook, InvoError } from "@invonetwork/web-sdk/server";
330
+
331
+ // e.g. Express: app.post("/invo/webhooks", express.raw({ type: "application/json" }), handler)
332
+ function handler(req, res) {
333
+ let event;
334
+ try {
335
+ event = verifyWebhook(req.body, req.get("X-Invo-Signature"), process.env.INVO_WEBHOOK_SECRET!);
336
+ } catch (e) {
337
+ return res.status(400).send((e as InvoError).code); // bad signature / stale / malformed
338
+ }
339
+ if (alreadyProcessed(req.get("X-Invo-Idempotency-Key"))) return res.status(200).end(); // dedupe
340
+
341
+ switch (event.event_type) {
342
+ case "purchase.completed": grantCurrency(event.data); break; // event.data is typed
343
+ case "item.purchased": grantItem(event.data); break;
344
+ // transfer.* , payout.status_changed , …
345
+ }
346
+ res.status(200).end(); // 2xx fast; offload slow work
347
+ }
348
+ ```
349
+
350
+ `verifyWebhook` does constant-time HMAC-SHA256 over `${t}.${rawBody}`, enforces a 5-minute replay window, and accepts an **array of secrets** during rotation (`verifyWebhook(body, sig, [oldSecret, newSecret])`). It returns a typed `InvoWebhookEvent` (discriminate on `event_type`) and throws `InvoError` (`WEBHOOK_SIGNATURE_INVALID` / `WEBHOOK_TIMESTAMP_EXPIRED` / `WEBHOOK_MALFORMED` / `WEBHOOK_SECRET_MISSING`) on any failure. **De-dupe yourself on `X-Invo-Idempotency-Key`** — the SDK verifies, it doesn't track delivery.
351
+
352
+ ### Event types
353
+
354
+ | Event | Fires for | Use it to |
355
+ |---|---|---|
356
+ | `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`) |
357
+ | `purchase.failed` / `purchase.disputed` | `platform` rail only | handle failures/disputes |
358
+ | `purchase.refunded` | `game` / `steam` rails | handle refunds |
359
+ | `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`) |
360
+
361
+ Don't block waiting on `purchase.failed` for the `game`/`steam` rails — they only emit `completed`/`refunded`. Reconcile off `*.completed` + the status endpoints.
362
+
363
+ ---
364
+
365
+ ## Resilience & observability
366
+
367
+ - **Automatic retries.** Transient failures — network errors/timeouts, `429` (honoring `retry_after`), and `5xx` — are retried with exponential backoff + jitter. Configure with `maxRetries` (default `2`, set `0` to disable) and `retryBaseDelayMs` (default `250`). Mutating calls carry idempotency keys, so retries are safe; set `maxRetries: 0` if you'd rather handle `429` abuse-throttles yourself.
368
+ - **Hooks.** Pass `hooks` to either client for tracing/metrics — all best-effort (a throwing hook never breaks a request):
369
+
370
+ ```ts
371
+ new InvoServer({
372
+ /* … */,
373
+ hooks: {
374
+ onRequest: ({ method, url, attempt }) => {},
375
+ onResponse: ({ status, durationMs, requestId, attempt }) => {},
376
+ onError: ({ error, willRetry, attempt }) => {},
377
+ },
192
378
  });
193
- // item.status === "success", item.newBalance (post-spend), item.previousBalance,
194
- // item.transactionId, item.orderId, item.financialBreakdown { total_paid, developer_revenue, platform_fee }
195
379
  ```
196
380
 
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).
381
+ > Note: hook payloads include the request `url`, which for some calls embeds a player email (e.g. balance-by-email). Tokens and the game secret are sent as headers and are **never** passed to hooks but redact the `url` if you log hook payloads.
382
+
383
+ - **Request ids.** `InvoError.requestId` carries the backend request id (from `x-invo-request-id` / `x-request-id`) quote it in support tickets.
202
384
 
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?").
385
+ ---
204
386
 
205
387
  ## Errors
206
388
 
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.
389
+ Every failure throws **`InvoError`** with:
390
+ - `.code` — stable machine code when present (some txn-state errors have none — branch on `.message` for those)
391
+ - `.status` — HTTP status (`0` for client-side validation and network errors)
392
+ - `.message` — human-readable
393
+ - `.body` — the raw parsed response
394
+
395
+ Helpers:
396
+
397
+ | Helper | Meaning |
398
+ |---|---|
399
+ | `.isTokenExpired` | player token expired — re-mint + retry (automatic if `refreshToken` is set) |
400
+ | `.isReceiverNotEnrolled` | recipient has no passkey → switch to claim-code entry |
401
+ | `.isInsufficientBalance` | item purchase failed (400); `required_amount` + `current_balance` on `.body` |
402
+ | `.isDuplicateRequest` | idempotency-keyed request was a duplicate (409) |
403
+ | `.retryAfter` | seconds to back off on a 429 throttle |
208
404
 
209
- ## Scripts
405
+ 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`.
406
+
407
+ ```ts
408
+ import { InvoError } from "@invonetwork/web-sdk"; // or "@invonetwork/web-sdk/server"
409
+ try {
410
+ await server.purchaseItem(/* … */);
411
+ } catch (e) {
412
+ if (e instanceof InvoError && e.isInsufficientBalance) {
413
+ showTopUp(e.body); // { required_amount, current_balance }
414
+ } else throw e;
415
+ }
416
+ ```
417
+
418
+ ---
419
+
420
+ ## API reference
421
+
422
+ ### `InvoServer` (`@invonetwork/web-sdk/server`)
423
+
424
+ | Method | Returns |
425
+ |---|---|
426
+ | `mintPlayerToken({ playerEmail })` | `{ token, expiresAt, identityId }` |
427
+ | `initiateSend(input)` | `{ transactionId, verificationMethod, guardianApproval?, raw }` |
428
+ | `initiateTransfer(input)` | `{ transactionId, verificationMethod, guardianApproval?, raw }` |
429
+ | `createCheckout(input)` | `{ sessionId, checkoutUrl, expiresAt, raw }` |
430
+ | `purchaseCurrency(input)` | `{ status, clientSecret?, paymentIntentId?, paymentUrl?, transactionId?, orderId?, newBalance?, raw }` |
431
+ | `confirmPayment({ paymentIntentId, orderId? })` | `{ status, transactionId?, newBalance?, raw }` |
432
+ | `getOrderDetails({ orderId? \| transactionId? })` | `{ order, financialSummary, statusTimeline, raw }` |
433
+ | `purchaseItem(input)` | `{ status, transactionId, orderId, newBalance, previousBalance, currencyName, financialBreakdown?, raw }` |
434
+ | `getItemPurchaseHistory({ playerEmail, limit?, offset? })` | `{ history, pagination, raw }` |
435
+ | `getItemOrderDetails({ orderId? \| transactionId? \| clientRequestId? })` | `{ order, financialSummary, statusTimeline, raw }` |
436
+ | `getPlayerBalance({ playerEmail? \| playerId? })` | `{ player, balances, summary, raw }` |
437
+ | `verifyWebhook(rawBody, signatureHeader, secret \| secrets, opts?)` | typed `InvoWebhookEvent` (throws on bad signature) |
438
+
439
+ ### `InvoClient` (`@invonetwork/web-sdk`)
440
+
441
+ | Method | Returns |
442
+ |---|---|
443
+ | `enrollPasskey()` | `{ status, device, raw }` |
444
+ | `approveSend(txnId)` / `approveTransfer(txnId)` | `{ status, next, transactionId, claimCode?, claimCodeExpiresAt?, raw }` |
445
+ | `confirmReceiptSend(txnId)` / `confirmReceiptTransfer(txnId)` | `{ status, raw }` |
446
+ | `linkDevice(linkId)` | `{ status, raw }` |
447
+
448
+ Every method throws `InvoError` on failure. Full inline types ship with the package.
449
+
450
+ ---
451
+
452
+ ## Scripts & versioning
210
453
 
211
454
  ```bash
212
455
  npm run build # tsup → dist (ESM + CJS + d.ts)
@@ -214,6 +457,8 @@ npm run typecheck # tsc --noEmit
214
457
  npm test # vitest
215
458
  ```
216
459
 
460
+ 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).
461
+
217
462
  ## License
218
463
 
219
- Proprietary — © Invo Tech Inc. See `LICENSE` (the partner-distribution license is a business decision; swap to MIT/Apache-2.0 if preferred).
464
+ Proprietary — © Invo Tech Inc. See [`LICENSE`](LICENSE).