@invonetwork/web-sdk 2.0.0 → 2.1.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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,51 @@ All notable changes to `@invonetwork/web-sdk` are documented here. This project
4
4
  [Semantic Versioning](https://semver.org/). Releases are managed with
5
5
  [changesets](https://github.com/changesets/changesets).
6
6
 
7
+ ## [2.1.1] — 2026-07-06
8
+
9
+ **Security & correctness hardening** from a full audit + red-team of both SDKs. No API changes;
10
+ upgrade recommended.
11
+
12
+ - **Fail closed on HTTP redirects (security).** The transport now sends `redirect:"manual"` and
13
+ throws `UNEXPECTED_REDIRECT` on any 3xx instead of following it. Previously a redirect from
14
+ the API host could cause the game-secret header to be re-sent to an unvalidated URL (matches
15
+ the Python SDK fix, where the leak also covered the player token and an `http://` downgrade).
16
+ - **`retryAfter` no longer treats a blank `retry_after` as `0`.** An empty/whitespace
17
+ `retry_after` string used to become `0` (`Number("")===0`) — an immediate, no-backoff retry.
18
+ It's now correctly `undefined`, in both `InvoError.retryAfter` and the retry layer.
19
+ - **Whitespace OTP codes rejected client-side.** `recoveryComplete`/`enrollmentVerify` now
20
+ reject a whitespace-only `code` before the network call, so it can't burn an attempt against
21
+ the attempt-capped endpoints (parity with the Python SDK).
22
+ - **Webhook verify uses `crypto.timingSafeEqual`** on the sync path (parity with Python's
23
+ `hmac.compare_digest`); the runtime-agnostic async/edge path keeps its string compare.
24
+ - **WebAuthn option mappers fail cleanly.** A malformed `register/begin` body now throws
25
+ `WEBAUTHN_OPTIONS_MALFORMED` (an `InvoError`) instead of a raw `TypeError`.
26
+
27
+ ## [2.1.0] — 2026-07-02
28
+
29
+ **Passkey recovery ("lost or replaced my passkey").** Deleting a passkey on the device never
30
+ tells the server the key is gone, so re-enrollment was dead-ended by the anti-takeover gate
31
+ (`ENROLLMENT_REQUIRES_PROOF`) with nothing left to prove possession with. The backend shipped
32
+ a self-serve, possession-proofed recovery flow; this release wires the client side.
33
+
34
+ - `InvoClient.recoveryBegin()` — sends a one-time code to the phone/email on file
35
+ (`{ status: "sent", channels }`); `InvoClient.recoveryComplete(code)` — deactivates the
36
+ stale server-side passkey and authorizes a fresh enrollment
37
+ (`{ status: "recovered", deactivatedCount, next }`). Then retry the same `enrollPasskey()`.
38
+ - New `InvoError` classifiers: `isEnrollmentCodeInvalid`, `isPasskeyRecoveryCooldown`, and
39
+ `retryAfterAt` (the ISO timestamp on the 403 cooldown — distinct from the numeric
40
+ `retryAfter` throttle field). Bare `no_channel_on_file` / `rate_limited` error tokens are
41
+ now promoted to `err.code`.
42
+ - **24-hour money cooldown surfaced:** a recovery-enrolled passkey logs in and collects
43
+ funds immediately, but `approveSend`/`approveTransfer` throw 403
44
+ `PASSKEY_RECOVERY_COOLDOWN` for 24h (SIM-swap protection). Branch on
45
+ `isPasskeyRecoveryCooldown`, show the pause message with `retryAfterAt`, don't retry-loop.
46
+ - README: recovery subsection under Passkeys, incl. the password-manager cleanup tip for
47
+ "there is a problem saving your passkey" (stale orphan entry).
48
+
49
+ Additive, no breaking changes. Routes require SDK verification enabled for the tenant
50
+ (dark 503 otherwise).
51
+
7
52
  ## [2.0.0] — 2026-07-02
8
53
 
9
54
  **BREAKING — `mintPlayerToken` now requires `playerPhone` (E.164).** Requested by the INVO
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
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:** `v2.0.0` — stable, published on npm. The backend it wraps is **live** on sandbox + production. The API is covered by a [stability commitment](#stability): no breaking changes without a major bump. **v2.0.0 is a major (breaking) release:** `mintPlayerToken` now requires `playerPhone` (E.164) — see the [CHANGELOG](CHANGELOG.md) migration note.
5
+ > **Status:** `v2.1.1` — stable, published on npm. The backend it wraps is **live** on sandbox + production. The API is covered by a [stability commitment](#stability): no breaking changes without a major bump. **Since 2.0.0 (breaking):** `mintPlayerToken` requires `playerPhone` (E.164) — see the [CHANGELOG](CHANGELOG.md) migration note. **2.1.0 adds** self-serve passkey recovery (`recoveryBegin`/`recoveryComplete`); **2.1.1** is a security/correctness hardening patch.
6
6
  > Canonical partner reference: **https://docs.invo.network/docs/currency-purchase** and **https://docs.invo.network/docs/game-developer-integration**.
7
7
 
8
8
  ## What it does
@@ -28,7 +28,7 @@ The **game secret stays on your server**; the browser only ever holds a short-li
28
28
  - [Item purchase (spend game currency)](#item-purchase-spend-game-currency)
29
29
  - [Player balance](#player-balance)
30
30
  - [Sends & transfers (move currency between players)](#sends--transfers-move-currency-between-players)
31
- - [Passkeys (enroll, approve, link)](#passkeys-enroll-approve-link)
31
+ - [Passkeys (enroll, approve, link, recover)](#passkeys-enroll-approve-link-recover)
32
32
  - [Webhooks](#webhooks)
33
33
  - [Resilience & observability](#resilience--observability)
34
34
  - [Errors](#errors)
@@ -143,7 +143,7 @@ The WebAuthn ceremony still runs in the browser (it must — it's `navigator.cre
143
143
  - **Real partner** (one login = one player) — derive the acting player from your **session**.
144
144
  - **Trusted first-party rig** (an internal tool that impersonates arbitrary test players) — the caller names `playerEmail`, guarded by a shared-secret header (`INVO_PROXY_TRUSTED_SECRET`), the same trusted pattern as a `player_email` token minter. Never expose this mode to end-user browsers.
145
145
 
146
- > **Lowest-risk first step:** adopt just `linkDevice` (passkey ↔ app device interchange) — it's purely additive and needs no refactor. See [Passkeys](#passkeys-enroll-approve-link).
146
+ > **Lowest-risk first step:** adopt just `linkDevice` (passkey ↔ app device interchange) — it's purely additive and needs no refactor. See [Passkeys](#passkeys-enroll-approve-link-recover).
147
147
 
148
148
  ## Before you go live
149
149
 
@@ -381,7 +381,7 @@ try {
381
381
 
382
382
  ---
383
383
 
384
- ## Passkeys (enroll, approve, link)
384
+ ## Passkeys (enroll, approve, link, recover)
385
385
 
386
386
  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.
387
387
 
@@ -416,6 +416,39 @@ try {
416
416
  }
417
417
  ```
418
418
 
419
+ ### Lost or replaced passkey (recovery)
420
+
421
+ Deleting a passkey on the device **never tells the server the key is gone**, so the next
422
+ `enrollPasskey()` is blocked by the anti-takeover gate with `ENROLLMENT_REQUIRES_PROOF` —
423
+ and the player has nothing left to prove possession with. Offer a **"Lost or replaced your
424
+ passkey?"** action that runs the possession-proofed recovery flow:
425
+
426
+ ```ts
427
+ try {
428
+ await client.enrollPasskey();
429
+ } catch (e) {
430
+ if (e instanceof InvoError && e.isEnrollmentProofRequired) {
431
+ // Player still HAS the other method → linkDevice (above). Lost/deleted it → recover:
432
+ await client.recoveryBegin(); // → { status:"sent", channels:["sms","email"] }
433
+ await client.recoveryComplete(codeFromUser); // → { status:"recovered", deactivatedCount }
434
+ await client.enrollPasskey(); // same call — now succeeds
435
+ } else throw e;
436
+ }
437
+ ```
438
+
439
+ - `recoveryBegin()` errors: `no_channel_on_file` (422), `rate_limited` (429 — max 5 codes / 10 min).
440
+ - `recoveryComplete(code)` errors: `ENROLLMENT_CODE_INVALID` (wrong/expired, attempt-capped — let the user retry or resend), `RECOVERY_FAILED` (500, transient).
441
+ - A recovery also sends the owner an out-of-band "your passkey was reset" SMS/email — that's the intended tamper alert; surface nothing special.
442
+ - If the **OS fails to save** a new passkey ("there is a problem saving your passkey"), have the user delete the stale entry in their password manager first (iPhone: Settings → Passwords; Android: Google Password Manager; Windows: Settings → Accounts → Passkeys).
443
+
444
+ > ⚠️ **24-hour money cooldown after recovery.** A recovery-enrolled passkey logs in and
445
+ > **collects funds immediately**, but `approveSend`/`approveTransfer` return **403
446
+ > `PASSKEY_RECOVERY_COOLDOWN`** for 24 hours (SIM-swap protection). Branch on
447
+ > `err.isPasskeyRecoveryCooldown` and show — *"For your security, transfers are paused for
448
+ > 24 hours after a passkey reset. You can still receive funds. Try again after
449
+ > `err.retryAfterAt`."* — do **not** treat it as a generic failure or retry-loop it.
450
+ > Unaffected: login, `getPendingCollect`, inbound `confirmReceipt*`.
451
+
419
452
  - **User verification is required** on every approve/claim (a missing-UV assertion fails closed).
420
453
  - Challenges are single-use and bound to `{flow}:{transactionId}`.
421
454
  - The SDK passes the backend's WebAuthn options through unchanged (it does not hard-code `pubKeyCredParams`/`timeout`/`attestation`).
@@ -528,7 +561,7 @@ Helpers:
528
561
  | `.isPhoneShareApprovalRequired` | a new-account phone needs owner approval → run the `phoneShare*` handshake, then retry |
529
562
  | `.isPhoneShareAlreadyApproved` | phone-share was already approved (e.g. from a `/reject`) |
530
563
 
531
- 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`.
564
+ 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`, `ENROLLMENT_CODE_INVALID`, `PASSKEY_RECOVERY_COOLDOWN` (403, `retryAfterAt`), `no_channel_on_file`, `rate_limited`, `WRONG_RAIL_ENDPOINT`, `flow_paused`.
532
565
 
533
566
  ```ts
534
567
  import { InvoError } from "@invonetwork/web-sdk"; // or "@invonetwork/web-sdk/server"
@@ -581,6 +614,7 @@ Every method also accepts an optional final `{ signal }` (`AbortSignal`) for can
581
614
  |---|---|
582
615
  | `enrollPasskey()` | `{ status, device, raw }` |
583
616
  | `enrollmentBegin()` / `enrollmentVerify(code)` | OTP grant for `ENROLLMENT_REQUIRES_AUTHORIZATION` (then retry `enrollPasskey`) |
617
+ | `recoveryBegin()` / `recoveryComplete(code)` | passkey recovery for `ENROLLMENT_REQUIRES_PROOF` when the passkey was lost/deleted (then retry `enrollPasskey`) — recovered keys can't move money OUT for 24h (`PASSKEY_RECOVERY_COOLDOWN`) |
584
618
  | `approveSend(txnId)` / `approveTransfer(txnId)` | `{ status, next, transactionId, claimCode?, claimCodeExpiresAt?, holdReason?, risk?, guardianApproval?, pollEndpoint?, raw }` |
585
619
  | `confirmReceiptSend(txnId)` / `confirmReceiptTransfer(txnId)` | `{ status, holdReason?, raw }` |
586
620
  | `linkDevice(linkId)` | `{ status, raw }` |
@@ -602,7 +636,7 @@ npm test # vitest
602
636
 
603
637
  ### Stability
604
638
 
605
- As of **`1.0.0`** the public API is **stable**: it follows [semver](https://semver.org/), and **no breaking change ships without a major version bump + a migration note**. Patch = fixes, minor = additive surface (new methods/fields, backward-compatible), major = breaking changes (rare). The wire contract is the same live INVO API you'd call directly, and it's backward-compatible within a major — so a pinned SDK keeps working. Safe to depend on in production; pin a version and watch [releases](https://github.com/Invo-Technologies/invo-web-sdk/releases) for security updates.
639
+ Since **`1.0.0`** the public API is **stable**: it follows [semver](https://semver.org/), and **no breaking change ships without a major version bump + a migration note** (the `2.0.0` `playerPhone` requirement is the one such change to date). Patch = fixes, minor = additive surface (new methods/fields, backward-compatible — e.g. `2.1.0`'s passkey recovery), major = breaking changes (rare). The wire contract is the same live INVO API you'd call directly, and it's backward-compatible within a major — so a pinned SDK keeps working. Safe to depend on in production; pin a version and watch [releases](https://github.com/Invo-Technologies/invo-web-sdk/releases) for security updates.
606
640
 
607
641
  Full history: [CHANGELOG](https://github.com/Invo-Technologies/invo-web-sdk/blob/main/CHANGELOG.md) · [release notes](https://github.com/Invo-Technologies/invo-web-sdk/blob/main/docs/RELEASES.md) (absolute links to `main`).
608
642
 
@@ -21,10 +21,35 @@ var InvoError = class _InvoError extends Error {
21
21
  get isEnrollmentAuthorizationRequired() {
22
22
  return this.code === "ENROLLMENT_REQUIRES_AUTHORIZATION";
23
23
  }
24
- /** True if enrolling is blocked because another method exists — use `linkDevice`. */
24
+ /**
25
+ * True if enrolling is blocked because the identity already has an enrolled method
26
+ * (anti-takeover gate, register/complete → 409). Two ways forward: `linkDevice` when
27
+ * the player still HAS the other method, or the passkey-recovery flow
28
+ * (`recoveryBegin`/`recoveryComplete` — "Lost or replaced your passkey?") when they
29
+ * deleted/lost it — the server can't know a device-side passkey is gone.
30
+ */
25
31
  get isEnrollmentProofRequired() {
26
32
  return this.code === "ENROLLMENT_REQUIRES_PROOF";
27
33
  }
34
+ /** True if the recovery OTP was wrong or expired (attempt-capped) — let the user retry or resend. */
35
+ get isEnrollmentCodeInvalid() {
36
+ return this.code === "ENROLLMENT_CODE_INVALID";
37
+ }
38
+ /**
39
+ * True if a money-OUT approve was refused because the passkey was enrolled via
40
+ * recovery less than 24h ago (SIM-swap protection, approve → 403). NOT a generic
41
+ * failure — do not retry-loop. Login and inbound confirm-receipt (collecting money)
42
+ * still work. Show: "For your security, transfers are paused for 24 hours after a
43
+ * passkey reset. You can still receive funds. Try again after {retryAfterAt}."
44
+ */
45
+ get isPasskeyRecoveryCooldown() {
46
+ return this.code === "PASSKEY_RECOVERY_COOLDOWN";
47
+ }
48
+ /** The ISO timestamp when a `PASSKEY_RECOVERY_COOLDOWN` lifts (`retry_after`), when present. */
49
+ get retryAfterAt() {
50
+ const v = this.bodyObject()["retry_after"];
51
+ return typeof v === "string" && v && Number.isNaN(Number(v)) ? v : void 0;
52
+ }
28
53
  /**
29
54
  * True if an item purchase failed because the player's balance was too low (§4.8 → 400).
30
55
  * The backend carries `required_amount` + `current_balance` on the body for the UI.
@@ -63,7 +88,7 @@ var InvoError = class _InvoError extends Error {
63
88
  /** Seconds to wait before retrying, when the backend throttled the call (429 `retry_after`). */
64
89
  get retryAfter() {
65
90
  const v = this.bodyObject()["retry_after"];
66
- const n = typeof v === "string" ? Number(v) : v;
91
+ const n = typeof v === "string" ? v.trim() === "" ? NaN : Number(v) : v;
67
92
  return typeof n === "number" && Number.isFinite(n) && n >= 0 ? n : void 0;
68
93
  }
69
94
  /** `body` as a plain object, or `{}` if it's a string/number/null (non-JSON responses).
@@ -81,7 +106,9 @@ function errorFromResponse(status, body, requestId) {
81
106
  else if (typeof b["error_code"] === "string") code = b["error_code"];
82
107
  if (typeof b["error"] === "string") message = b["error"];
83
108
  else if (typeof b["message"] === "string") message = b["message"];
84
- if (!code && typeof b["error"] === "string" && /^(flow_paused|spending_limit_exceeded|receiver_not_enrolled_use_claim_code)$/.test(b["error"])) {
109
+ if (!code && typeof b["error"] === "string" && /^(flow_paused|spending_limit_exceeded|receiver_not_enrolled_use_claim_code|no_channel_on_file|rate_limited)$/.test(
110
+ b["error"]
111
+ )) {
85
112
  code = b["error"];
86
113
  }
87
114
  } else if (typeof body === "string" && body.trim()) {
@@ -164,7 +191,13 @@ var _Http = class _Http {
164
191
  let res;
165
192
  let networkError;
166
193
  try {
167
- res = await this.fetchImpl(url, { method, headers, body: payload, signal: controller.signal });
194
+ res = await this.fetchImpl(url, {
195
+ method,
196
+ headers,
197
+ body: payload,
198
+ signal: controller.signal,
199
+ redirect: "manual"
200
+ });
168
201
  } catch (err) {
169
202
  networkError = new InvoError({
170
203
  message: err instanceof Error && err.name === "AbortError" ? `Request to ${path} timed out after ${this.timeoutMs}ms` : `Network error calling ${path}: ${err?.message ?? err}`,
@@ -185,6 +218,14 @@ var _Http = class _Http {
185
218
  }
186
219
  throw networkError;
187
220
  }
221
+ if (res.type === "opaqueredirect" || res.status >= 300 && res.status < 400) {
222
+ throw new InvoError({
223
+ message: `Refused to follow a redirect from ${path} \u2014 credentials are never re-sent to a redirected URL.`,
224
+ code: "UNEXPECTED_REDIRECT",
225
+ status: res.status || 0,
226
+ body: null
227
+ });
228
+ }
188
229
  const requestId = pickRequestId(res.headers);
189
230
  const text = await res.text();
190
231
  let parsed = null;
@@ -265,7 +306,7 @@ function pickRequestId(headers) {
265
306
  function retryAfterMs(parsed, headers) {
266
307
  if (parsed && typeof parsed === "object") {
267
308
  const v = parsed["retry_after"];
268
- const n = typeof v === "string" ? Number(v) : v;
309
+ const n = typeof v === "string" ? v.trim() === "" ? NaN : Number(v) : v;
269
310
  if (typeof n === "number" && Number.isFinite(n) && n >= 0) return n * 1e3;
270
311
  }
271
312
  const header = headers && typeof headers.get === "function" ? headers.get("retry-after") : null;
@@ -320,5 +361,5 @@ function toDestinationsResult(raw, direction) {
320
361
  }
321
362
 
322
363
  export { Http, InvoError, assertSecureBaseUrl, toDestinationsResult };
323
- //# sourceMappingURL=chunk-6XCI53XJ.js.map
324
- //# sourceMappingURL=chunk-6XCI53XJ.js.map
364
+ //# sourceMappingURL=chunk-4GNJIQY2.js.map
365
+ //# sourceMappingURL=chunk-4GNJIQY2.js.map
package/dist/index.cjs CHANGED
@@ -23,10 +23,35 @@ var InvoError = class _InvoError extends Error {
23
23
  get isEnrollmentAuthorizationRequired() {
24
24
  return this.code === "ENROLLMENT_REQUIRES_AUTHORIZATION";
25
25
  }
26
- /** True if enrolling is blocked because another method exists — use `linkDevice`. */
26
+ /**
27
+ * True if enrolling is blocked because the identity already has an enrolled method
28
+ * (anti-takeover gate, register/complete → 409). Two ways forward: `linkDevice` when
29
+ * the player still HAS the other method, or the passkey-recovery flow
30
+ * (`recoveryBegin`/`recoveryComplete` — "Lost or replaced your passkey?") when they
31
+ * deleted/lost it — the server can't know a device-side passkey is gone.
32
+ */
27
33
  get isEnrollmentProofRequired() {
28
34
  return this.code === "ENROLLMENT_REQUIRES_PROOF";
29
35
  }
36
+ /** True if the recovery OTP was wrong or expired (attempt-capped) — let the user retry or resend. */
37
+ get isEnrollmentCodeInvalid() {
38
+ return this.code === "ENROLLMENT_CODE_INVALID";
39
+ }
40
+ /**
41
+ * True if a money-OUT approve was refused because the passkey was enrolled via
42
+ * recovery less than 24h ago (SIM-swap protection, approve → 403). NOT a generic
43
+ * failure — do not retry-loop. Login and inbound confirm-receipt (collecting money)
44
+ * still work. Show: "For your security, transfers are paused for 24 hours after a
45
+ * passkey reset. You can still receive funds. Try again after {retryAfterAt}."
46
+ */
47
+ get isPasskeyRecoveryCooldown() {
48
+ return this.code === "PASSKEY_RECOVERY_COOLDOWN";
49
+ }
50
+ /** The ISO timestamp when a `PASSKEY_RECOVERY_COOLDOWN` lifts (`retry_after`), when present. */
51
+ get retryAfterAt() {
52
+ const v = this.bodyObject()["retry_after"];
53
+ return typeof v === "string" && v && Number.isNaN(Number(v)) ? v : void 0;
54
+ }
30
55
  /**
31
56
  * True if an item purchase failed because the player's balance was too low (§4.8 → 400).
32
57
  * The backend carries `required_amount` + `current_balance` on the body for the UI.
@@ -65,7 +90,7 @@ var InvoError = class _InvoError extends Error {
65
90
  /** Seconds to wait before retrying, when the backend throttled the call (429 `retry_after`). */
66
91
  get retryAfter() {
67
92
  const v = this.bodyObject()["retry_after"];
68
- const n = typeof v === "string" ? Number(v) : v;
93
+ const n = typeof v === "string" ? v.trim() === "" ? NaN : Number(v) : v;
69
94
  return typeof n === "number" && Number.isFinite(n) && n >= 0 ? n : void 0;
70
95
  }
71
96
  /** `body` as a plain object, or `{}` if it's a string/number/null (non-JSON responses).
@@ -83,7 +108,9 @@ function errorFromResponse(status, body, requestId) {
83
108
  else if (typeof b["error_code"] === "string") code = b["error_code"];
84
109
  if (typeof b["error"] === "string") message = b["error"];
85
110
  else if (typeof b["message"] === "string") message = b["message"];
86
- if (!code && typeof b["error"] === "string" && /^(flow_paused|spending_limit_exceeded|receiver_not_enrolled_use_claim_code)$/.test(b["error"])) {
111
+ if (!code && typeof b["error"] === "string" && /^(flow_paused|spending_limit_exceeded|receiver_not_enrolled_use_claim_code|no_channel_on_file|rate_limited)$/.test(
112
+ b["error"]
113
+ )) {
87
114
  code = b["error"];
88
115
  }
89
116
  } else if (typeof body === "string" && body.trim()) {
@@ -166,7 +193,13 @@ var _Http = class _Http {
166
193
  let res;
167
194
  let networkError;
168
195
  try {
169
- res = await this.fetchImpl(url, { method, headers, body: payload, signal: controller.signal });
196
+ res = await this.fetchImpl(url, {
197
+ method,
198
+ headers,
199
+ body: payload,
200
+ signal: controller.signal,
201
+ redirect: "manual"
202
+ });
170
203
  } catch (err) {
171
204
  networkError = new InvoError({
172
205
  message: err instanceof Error && err.name === "AbortError" ? `Request to ${path} timed out after ${this.timeoutMs}ms` : `Network error calling ${path}: ${err?.message ?? err}`,
@@ -187,6 +220,14 @@ var _Http = class _Http {
187
220
  }
188
221
  throw networkError;
189
222
  }
223
+ if (res.type === "opaqueredirect" || res.status >= 300 && res.status < 400) {
224
+ throw new InvoError({
225
+ message: `Refused to follow a redirect from ${path} \u2014 credentials are never re-sent to a redirected URL.`,
226
+ code: "UNEXPECTED_REDIRECT",
227
+ status: res.status || 0,
228
+ body: null
229
+ });
230
+ }
190
231
  const requestId = pickRequestId(res.headers);
191
232
  const text = await res.text();
192
233
  let parsed = null;
@@ -267,7 +308,7 @@ function pickRequestId(headers) {
267
308
  function retryAfterMs(parsed, headers) {
268
309
  if (parsed && typeof parsed === "object") {
269
310
  const v = parsed["retry_after"];
270
- const n = typeof v === "string" ? Number(v) : v;
311
+ const n = typeof v === "string" ? v.trim() === "" ? NaN : Number(v) : v;
271
312
  if (typeof n === "number" && Number.isFinite(n) && n >= 0) return n * 1e3;
272
313
  }
273
314
  const header = headers && typeof headers.get === "function" ? headers.get("retry-after") : null;
@@ -279,6 +320,13 @@ function retryAfterMs(parsed, headers) {
279
320
  }
280
321
 
281
322
  // src/shared/webauthn.ts
323
+ function malformedOptions(field) {
324
+ return new InvoError({
325
+ message: `Malformed WebAuthn options from the backend: missing/invalid \`${field}\`.`,
326
+ code: "WEBAUTHN_OPTIONS_MALFORMED",
327
+ status: 0
328
+ });
329
+ }
282
330
  function b64urlToBuffer(value) {
283
331
  const pad = value.length % 4 === 0 ? "" : "=".repeat(4 - value.length % 4);
284
332
  const b64 = value.replace(/-/g, "+").replace(/_/g, "/") + pad;
@@ -304,6 +352,8 @@ function descriptorsToBinary(list) {
304
352
  });
305
353
  }
306
354
  function toCreationOptions(json) {
355
+ if (typeof json?.["challenge"] !== "string") throw malformedOptions("challenge");
356
+ if (typeof json["user"]?.id !== "string") throw malformedOptions("user.id");
307
357
  const opts = {
308
358
  ...json,
309
359
  challenge: b64urlToBuffer(json["challenge"]),
@@ -318,6 +368,7 @@ function toCreationOptions(json) {
318
368
  return opts;
319
369
  }
320
370
  function toRequestOptions(json) {
371
+ if (typeof json?.["challenge"] !== "string") throw malformedOptions("challenge");
321
372
  const opts = {
322
373
  ...json,
323
374
  challenge: b64urlToBuffer(json["challenge"])
@@ -452,7 +503,12 @@ var InvoClient = class {
452
503
  throw new Error("WebAuthn is not available in this environment (browser required).");
453
504
  }
454
505
  }
455
- /** Enroll a passkey for the token's identity (register/begin -> create() -> register/complete). */
506
+ /**
507
+ * Enroll a passkey for the token's identity (register/begin -> create() -> register/complete).
508
+ * Gates: `ENROLLMENT_REQUIRES_AUTHORIZATION` → {@link enrollmentBegin} OTP grant;
509
+ * `ENROLLMENT_REQUIRES_PROOF` → {@link linkDevice}, or {@link recoveryBegin} when the
510
+ * player lost/deleted the old passkey ("Lost or replaced your passkey?").
511
+ */
456
512
  async enrollPasskey(opts) {
457
513
  this.assertWebAuthn();
458
514
  const signal = opts?.signal;
@@ -581,7 +637,9 @@ var InvoClient = class {
581
637
  * this to send a 6-digit code to the player's phone + email on file, collect the code,
582
638
  * call `enrollmentVerify(code)`, then RETRY the SAME `enrollPasskey()` —
583
639
  * `register/complete` auto-consumes the server-side grant (30-min TTL). For
584
- * `ENROLLMENT_REQUIRES_PROOF` (`err.isEnrollmentProofRequired`) use `linkDevice` instead.
640
+ * `ENROLLMENT_REQUIRES_PROOF` (`err.isEnrollmentProofRequired`) use `linkDevice`
641
+ * (player still has the other method) or `recoveryBegin`/`recoveryComplete`
642
+ * (player lost/deleted their passkey).
585
643
  */
586
644
  async enrollmentBegin(opts) {
587
645
  return this.withTokenRetry(async () => {
@@ -599,7 +657,7 @@ var InvoClient = class {
599
657
  }
600
658
  /** Verify the enrollment OTP (see {@link enrollmentBegin}); on success, retry `enrollPasskey()`. */
601
659
  async enrollmentVerify(code, opts) {
602
- if (!code) throw new Error("enrollmentVerify requires the OTP `code`.");
660
+ if (!code || !code.trim()) throw new Error("enrollmentVerify requires the OTP `code`.");
603
661
  return this.withTokenRetry(async () => {
604
662
  const raw = await this.post(
605
663
  "/api/sdk/device/enrollment/verify",
@@ -609,6 +667,65 @@ var InvoClient = class {
609
667
  return { status: String(raw["status"] ?? ""), raw };
610
668
  });
611
669
  }
670
+ /**
671
+ * Passkey recovery — "Lost or replaced your passkey?". Deleting a passkey on the
672
+ * device never tells the server the key is gone, so the next `enrollPasskey()` is
673
+ * blocked by the anti-takeover gate with `ENROLLMENT_REQUIRES_PROOF`
674
+ * (`err.isEnrollmentProofRequired`). When the player can't prove the old method
675
+ * (they deleted/lost it — otherwise prefer `linkDevice`), run:
676
+ *
677
+ * 1. `recoveryBegin()` — sends a one-time code to the phone/email on file
678
+ * (422 `no_channel_on_file`, 429 `rate_limited` at 5/10min).
679
+ * 2. `recoveryComplete(code)` — deactivates the stale server-side passkey and
680
+ * authorizes a fresh enrollment (400 `ENROLLMENT_CODE_INVALID` on a wrong/
681
+ * expired code — attempt-capped; let the user retry or resend).
682
+ * 3. Immediately retry the SAME `enrollPasskey()` — it now succeeds.
683
+ *
684
+ * The owner also gets an out-of-band "your passkey was reset" SMS/email — that's
685
+ * the intended tamper alert; surface nothing special for it.
686
+ *
687
+ * ⚠ 24-HOUR MONEY COOLDOWN: a recovery-enrolled passkey logs in and COLLECTS
688
+ * funds immediately, but `approveSend`/`approveTransfer` throw
689
+ * `PASSKEY_RECOVERY_COOLDOWN` (403; `err.isPasskeyRecoveryCooldown`,
690
+ * `err.retryAfterAt`) for 24h — SIM-swap protection. Show the pause message with
691
+ * the timestamp; do not retry-loop it.
692
+ *
693
+ * If the OS itself fails to SAVE a new passkey ("there is a problem saving your
694
+ * passkey"), have the user delete the stale entry in their password manager first
695
+ * (iPhone: Settings → Passwords; Android: Google Password Manager; Windows:
696
+ * Settings → Accounts → Passkeys).
697
+ */
698
+ async recoveryBegin(opts) {
699
+ return this.withTokenRetry(async () => {
700
+ const raw = await this.post(
701
+ "/api/sdk/device/recover/begin",
702
+ void 0,
703
+ opts?.signal
704
+ );
705
+ return {
706
+ status: String(raw["status"] ?? ""),
707
+ channels: Array.isArray(raw["channels"]) ? raw["channels"] : [],
708
+ raw
709
+ };
710
+ });
711
+ }
712
+ /** Verify the recovery code (see {@link recoveryBegin}); on success, call `enrollPasskey()`. */
713
+ async recoveryComplete(code, opts) {
714
+ if (!code || !code.trim()) throw new Error("recoveryComplete requires the one-time `code`.");
715
+ return this.withTokenRetry(async () => {
716
+ const raw = await this.post(
717
+ "/api/sdk/device/recover/complete",
718
+ { code },
719
+ opts?.signal
720
+ );
721
+ return {
722
+ status: String(raw["status"] ?? ""),
723
+ deactivatedCount: Number(raw["deactivated_count"] ?? 0),
724
+ next: typeof raw["next"] === "string" ? raw["next"] : void 0,
725
+ raw
726
+ };
727
+ });
728
+ }
612
729
  // --- internals ---
613
730
  /** POST with the current player token. Token-expiry retry is handled one level
614
731
  * up by withTokenRetry (which re-runs the whole ceremony, not a single call). */
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as ClientConfig, a as CallOptions, A as ApproveResult, b as ConfirmReceiptResult, L as LinkDeviceResult, P as PendingCollectResult, D as DestinationsQuery, c as DestinationsResult, B as BalanceResult, E as EnrollmentBeginResult, d as EnrollmentVerifyResult } from './types-bp0UtN_N.cjs';
2
- export { e as BalanceRow, f as DestinationGame, I as InvoError, g as InvoErrorInfo, h as InvoHooks, i as InvoRequestInfo, j as InvoResponseInfo, k as PendingCollectItem, R as Rail, V as VerificationMethod } from './types-bp0UtN_N.cjs';
1
+ import { C as ClientConfig, a as CallOptions, A as ApproveResult, b as ConfirmReceiptResult, L as LinkDeviceResult, P as PendingCollectResult, D as DestinationsQuery, c as DestinationsResult, B as BalanceResult, E as EnrollmentBeginResult, d as EnrollmentVerifyResult, R as RecoveryBeginResult, e as RecoveryCompleteResult } from './types-DtihCpOj.cjs';
2
+ export { f as BalanceRow, g as DestinationGame, I as InvoError, h as InvoErrorInfo, i as InvoHooks, j as InvoRequestInfo, k as InvoResponseInfo, l as PendingCollectItem, m as Rail, V as VerificationMethod } from './types-DtihCpOj.cjs';
3
3
 
4
4
  declare class InvoClient {
5
5
  private readonly http;
@@ -9,7 +9,12 @@ declare class InvoClient {
9
9
  private refreshInFlight;
10
10
  constructor(config: ClientConfig);
11
11
  private assertWebAuthn;
12
- /** Enroll a passkey for the token's identity (register/begin -> create() -> register/complete). */
12
+ /**
13
+ * Enroll a passkey for the token's identity (register/begin -> create() -> register/complete).
14
+ * Gates: `ENROLLMENT_REQUIRES_AUTHORIZATION` → {@link enrollmentBegin} OTP grant;
15
+ * `ENROLLMENT_REQUIRES_PROOF` → {@link linkDevice}, or {@link recoveryBegin} when the
16
+ * player lost/deleted the old passkey ("Lost or replaced your passkey?").
17
+ */
13
18
  enrollPasskey(opts?: CallOptions): Promise<{
14
19
  status: string;
15
20
  device: unknown;
@@ -58,11 +63,44 @@ declare class InvoClient {
58
63
  * this to send a 6-digit code to the player's phone + email on file, collect the code,
59
64
  * call `enrollmentVerify(code)`, then RETRY the SAME `enrollPasskey()` —
60
65
  * `register/complete` auto-consumes the server-side grant (30-min TTL). For
61
- * `ENROLLMENT_REQUIRES_PROOF` (`err.isEnrollmentProofRequired`) use `linkDevice` instead.
66
+ * `ENROLLMENT_REQUIRES_PROOF` (`err.isEnrollmentProofRequired`) use `linkDevice`
67
+ * (player still has the other method) or `recoveryBegin`/`recoveryComplete`
68
+ * (player lost/deleted their passkey).
62
69
  */
63
70
  enrollmentBegin(opts?: CallOptions): Promise<EnrollmentBeginResult>;
64
71
  /** Verify the enrollment OTP (see {@link enrollmentBegin}); on success, retry `enrollPasskey()`. */
65
72
  enrollmentVerify(code: string, opts?: CallOptions): Promise<EnrollmentVerifyResult>;
73
+ /**
74
+ * Passkey recovery — "Lost or replaced your passkey?". Deleting a passkey on the
75
+ * device never tells the server the key is gone, so the next `enrollPasskey()` is
76
+ * blocked by the anti-takeover gate with `ENROLLMENT_REQUIRES_PROOF`
77
+ * (`err.isEnrollmentProofRequired`). When the player can't prove the old method
78
+ * (they deleted/lost it — otherwise prefer `linkDevice`), run:
79
+ *
80
+ * 1. `recoveryBegin()` — sends a one-time code to the phone/email on file
81
+ * (422 `no_channel_on_file`, 429 `rate_limited` at 5/10min).
82
+ * 2. `recoveryComplete(code)` — deactivates the stale server-side passkey and
83
+ * authorizes a fresh enrollment (400 `ENROLLMENT_CODE_INVALID` on a wrong/
84
+ * expired code — attempt-capped; let the user retry or resend).
85
+ * 3. Immediately retry the SAME `enrollPasskey()` — it now succeeds.
86
+ *
87
+ * The owner also gets an out-of-band "your passkey was reset" SMS/email — that's
88
+ * the intended tamper alert; surface nothing special for it.
89
+ *
90
+ * ⚠ 24-HOUR MONEY COOLDOWN: a recovery-enrolled passkey logs in and COLLECTS
91
+ * funds immediately, but `approveSend`/`approveTransfer` throw
92
+ * `PASSKEY_RECOVERY_COOLDOWN` (403; `err.isPasskeyRecoveryCooldown`,
93
+ * `err.retryAfterAt`) for 24h — SIM-swap protection. Show the pause message with
94
+ * the timestamp; do not retry-loop it.
95
+ *
96
+ * If the OS itself fails to SAVE a new passkey ("there is a problem saving your
97
+ * passkey"), have the user delete the stale entry in their password manager first
98
+ * (iPhone: Settings → Passwords; Android: Google Password Manager; Windows:
99
+ * Settings → Accounts → Passkeys).
100
+ */
101
+ recoveryBegin(opts?: CallOptions): Promise<RecoveryBeginResult>;
102
+ /** Verify the recovery code (see {@link recoveryBegin}); on success, call `enrollPasskey()`. */
103
+ recoveryComplete(code: string, opts?: CallOptions): Promise<RecoveryCompleteResult>;
66
104
  /** POST with the current player token. Token-expiry retry is handled one level
67
105
  * up by withTokenRetry (which re-runs the whole ceremony, not a single call). */
68
106
  private post;
@@ -81,4 +119,4 @@ declare class InvoClient {
81
119
  private confirmReceipt;
82
120
  }
83
121
 
84
- export { ApproveResult, BalanceResult, CallOptions, ClientConfig, ConfirmReceiptResult, DestinationsQuery, DestinationsResult, EnrollmentBeginResult, EnrollmentVerifyResult, InvoClient, LinkDeviceResult, PendingCollectResult };
122
+ export { ApproveResult, BalanceResult, CallOptions, ClientConfig, ConfirmReceiptResult, DestinationsQuery, DestinationsResult, EnrollmentBeginResult, EnrollmentVerifyResult, InvoClient, LinkDeviceResult, PendingCollectResult, RecoveryBeginResult, RecoveryCompleteResult };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as ClientConfig, a as CallOptions, A as ApproveResult, b as ConfirmReceiptResult, L as LinkDeviceResult, P as PendingCollectResult, D as DestinationsQuery, c as DestinationsResult, B as BalanceResult, E as EnrollmentBeginResult, d as EnrollmentVerifyResult } from './types-bp0UtN_N.js';
2
- export { e as BalanceRow, f as DestinationGame, I as InvoError, g as InvoErrorInfo, h as InvoHooks, i as InvoRequestInfo, j as InvoResponseInfo, k as PendingCollectItem, R as Rail, V as VerificationMethod } from './types-bp0UtN_N.js';
1
+ import { C as ClientConfig, a as CallOptions, A as ApproveResult, b as ConfirmReceiptResult, L as LinkDeviceResult, P as PendingCollectResult, D as DestinationsQuery, c as DestinationsResult, B as BalanceResult, E as EnrollmentBeginResult, d as EnrollmentVerifyResult, R as RecoveryBeginResult, e as RecoveryCompleteResult } from './types-DtihCpOj.js';
2
+ export { f as BalanceRow, g as DestinationGame, I as InvoError, h as InvoErrorInfo, i as InvoHooks, j as InvoRequestInfo, k as InvoResponseInfo, l as PendingCollectItem, m as Rail, V as VerificationMethod } from './types-DtihCpOj.js';
3
3
 
4
4
  declare class InvoClient {
5
5
  private readonly http;
@@ -9,7 +9,12 @@ declare class InvoClient {
9
9
  private refreshInFlight;
10
10
  constructor(config: ClientConfig);
11
11
  private assertWebAuthn;
12
- /** Enroll a passkey for the token's identity (register/begin -> create() -> register/complete). */
12
+ /**
13
+ * Enroll a passkey for the token's identity (register/begin -> create() -> register/complete).
14
+ * Gates: `ENROLLMENT_REQUIRES_AUTHORIZATION` → {@link enrollmentBegin} OTP grant;
15
+ * `ENROLLMENT_REQUIRES_PROOF` → {@link linkDevice}, or {@link recoveryBegin} when the
16
+ * player lost/deleted the old passkey ("Lost or replaced your passkey?").
17
+ */
13
18
  enrollPasskey(opts?: CallOptions): Promise<{
14
19
  status: string;
15
20
  device: unknown;
@@ -58,11 +63,44 @@ declare class InvoClient {
58
63
  * this to send a 6-digit code to the player's phone + email on file, collect the code,
59
64
  * call `enrollmentVerify(code)`, then RETRY the SAME `enrollPasskey()` —
60
65
  * `register/complete` auto-consumes the server-side grant (30-min TTL). For
61
- * `ENROLLMENT_REQUIRES_PROOF` (`err.isEnrollmentProofRequired`) use `linkDevice` instead.
66
+ * `ENROLLMENT_REQUIRES_PROOF` (`err.isEnrollmentProofRequired`) use `linkDevice`
67
+ * (player still has the other method) or `recoveryBegin`/`recoveryComplete`
68
+ * (player lost/deleted their passkey).
62
69
  */
63
70
  enrollmentBegin(opts?: CallOptions): Promise<EnrollmentBeginResult>;
64
71
  /** Verify the enrollment OTP (see {@link enrollmentBegin}); on success, retry `enrollPasskey()`. */
65
72
  enrollmentVerify(code: string, opts?: CallOptions): Promise<EnrollmentVerifyResult>;
73
+ /**
74
+ * Passkey recovery — "Lost or replaced your passkey?". Deleting a passkey on the
75
+ * device never tells the server the key is gone, so the next `enrollPasskey()` is
76
+ * blocked by the anti-takeover gate with `ENROLLMENT_REQUIRES_PROOF`
77
+ * (`err.isEnrollmentProofRequired`). When the player can't prove the old method
78
+ * (they deleted/lost it — otherwise prefer `linkDevice`), run:
79
+ *
80
+ * 1. `recoveryBegin()` — sends a one-time code to the phone/email on file
81
+ * (422 `no_channel_on_file`, 429 `rate_limited` at 5/10min).
82
+ * 2. `recoveryComplete(code)` — deactivates the stale server-side passkey and
83
+ * authorizes a fresh enrollment (400 `ENROLLMENT_CODE_INVALID` on a wrong/
84
+ * expired code — attempt-capped; let the user retry or resend).
85
+ * 3. Immediately retry the SAME `enrollPasskey()` — it now succeeds.
86
+ *
87
+ * The owner also gets an out-of-band "your passkey was reset" SMS/email — that's
88
+ * the intended tamper alert; surface nothing special for it.
89
+ *
90
+ * ⚠ 24-HOUR MONEY COOLDOWN: a recovery-enrolled passkey logs in and COLLECTS
91
+ * funds immediately, but `approveSend`/`approveTransfer` throw
92
+ * `PASSKEY_RECOVERY_COOLDOWN` (403; `err.isPasskeyRecoveryCooldown`,
93
+ * `err.retryAfterAt`) for 24h — SIM-swap protection. Show the pause message with
94
+ * the timestamp; do not retry-loop it.
95
+ *
96
+ * If the OS itself fails to SAVE a new passkey ("there is a problem saving your
97
+ * passkey"), have the user delete the stale entry in their password manager first
98
+ * (iPhone: Settings → Passwords; Android: Google Password Manager; Windows:
99
+ * Settings → Accounts → Passkeys).
100
+ */
101
+ recoveryBegin(opts?: CallOptions): Promise<RecoveryBeginResult>;
102
+ /** Verify the recovery code (see {@link recoveryBegin}); on success, call `enrollPasskey()`. */
103
+ recoveryComplete(code: string, opts?: CallOptions): Promise<RecoveryCompleteResult>;
66
104
  /** POST with the current player token. Token-expiry retry is handled one level
67
105
  * up by withTokenRetry (which re-runs the whole ceremony, not a single call). */
68
106
  private post;
@@ -81,4 +119,4 @@ declare class InvoClient {
81
119
  private confirmReceipt;
82
120
  }
83
121
 
84
- export { ApproveResult, BalanceResult, CallOptions, ClientConfig, ConfirmReceiptResult, DestinationsQuery, DestinationsResult, EnrollmentBeginResult, EnrollmentVerifyResult, InvoClient, LinkDeviceResult, PendingCollectResult };
122
+ export { ApproveResult, BalanceResult, CallOptions, ClientConfig, ConfirmReceiptResult, DestinationsQuery, DestinationsResult, EnrollmentBeginResult, EnrollmentVerifyResult, InvoClient, LinkDeviceResult, PendingCollectResult, RecoveryBeginResult, RecoveryCompleteResult };
package/dist/index.js CHANGED
@@ -1,7 +1,14 @@
1
- import { assertSecureBaseUrl, Http, toDestinationsResult, InvoError } from './chunk-6XCI53XJ.js';
2
- export { InvoError } from './chunk-6XCI53XJ.js';
1
+ import { assertSecureBaseUrl, Http, toDestinationsResult, InvoError } from './chunk-4GNJIQY2.js';
2
+ export { InvoError } from './chunk-4GNJIQY2.js';
3
3
 
4
4
  // src/shared/webauthn.ts
5
+ function malformedOptions(field) {
6
+ return new InvoError({
7
+ message: `Malformed WebAuthn options from the backend: missing/invalid \`${field}\`.`,
8
+ code: "WEBAUTHN_OPTIONS_MALFORMED",
9
+ status: 0
10
+ });
11
+ }
5
12
  function b64urlToBuffer(value) {
6
13
  const pad = value.length % 4 === 0 ? "" : "=".repeat(4 - value.length % 4);
7
14
  const b64 = value.replace(/-/g, "+").replace(/_/g, "/") + pad;
@@ -27,6 +34,8 @@ function descriptorsToBinary(list) {
27
34
  });
28
35
  }
29
36
  function toCreationOptions(json) {
37
+ if (typeof json?.["challenge"] !== "string") throw malformedOptions("challenge");
38
+ if (typeof json["user"]?.id !== "string") throw malformedOptions("user.id");
30
39
  const opts = {
31
40
  ...json,
32
41
  challenge: b64urlToBuffer(json["challenge"]),
@@ -41,6 +50,7 @@ function toCreationOptions(json) {
41
50
  return opts;
42
51
  }
43
52
  function toRequestOptions(json) {
53
+ if (typeof json?.["challenge"] !== "string") throw malformedOptions("challenge");
44
54
  const opts = {
45
55
  ...json,
46
56
  challenge: b64urlToBuffer(json["challenge"])
@@ -132,7 +142,12 @@ var InvoClient = class {
132
142
  throw new Error("WebAuthn is not available in this environment (browser required).");
133
143
  }
134
144
  }
135
- /** Enroll a passkey for the token's identity (register/begin -> create() -> register/complete). */
145
+ /**
146
+ * Enroll a passkey for the token's identity (register/begin -> create() -> register/complete).
147
+ * Gates: `ENROLLMENT_REQUIRES_AUTHORIZATION` → {@link enrollmentBegin} OTP grant;
148
+ * `ENROLLMENT_REQUIRES_PROOF` → {@link linkDevice}, or {@link recoveryBegin} when the
149
+ * player lost/deleted the old passkey ("Lost or replaced your passkey?").
150
+ */
136
151
  async enrollPasskey(opts) {
137
152
  this.assertWebAuthn();
138
153
  const signal = opts?.signal;
@@ -261,7 +276,9 @@ var InvoClient = class {
261
276
  * this to send a 6-digit code to the player's phone + email on file, collect the code,
262
277
  * call `enrollmentVerify(code)`, then RETRY the SAME `enrollPasskey()` —
263
278
  * `register/complete` auto-consumes the server-side grant (30-min TTL). For
264
- * `ENROLLMENT_REQUIRES_PROOF` (`err.isEnrollmentProofRequired`) use `linkDevice` instead.
279
+ * `ENROLLMENT_REQUIRES_PROOF` (`err.isEnrollmentProofRequired`) use `linkDevice`
280
+ * (player still has the other method) or `recoveryBegin`/`recoveryComplete`
281
+ * (player lost/deleted their passkey).
265
282
  */
266
283
  async enrollmentBegin(opts) {
267
284
  return this.withTokenRetry(async () => {
@@ -279,7 +296,7 @@ var InvoClient = class {
279
296
  }
280
297
  /** Verify the enrollment OTP (see {@link enrollmentBegin}); on success, retry `enrollPasskey()`. */
281
298
  async enrollmentVerify(code, opts) {
282
- if (!code) throw new Error("enrollmentVerify requires the OTP `code`.");
299
+ if (!code || !code.trim()) throw new Error("enrollmentVerify requires the OTP `code`.");
283
300
  return this.withTokenRetry(async () => {
284
301
  const raw = await this.post(
285
302
  "/api/sdk/device/enrollment/verify",
@@ -289,6 +306,65 @@ var InvoClient = class {
289
306
  return { status: String(raw["status"] ?? ""), raw };
290
307
  });
291
308
  }
309
+ /**
310
+ * Passkey recovery — "Lost or replaced your passkey?". Deleting a passkey on the
311
+ * device never tells the server the key is gone, so the next `enrollPasskey()` is
312
+ * blocked by the anti-takeover gate with `ENROLLMENT_REQUIRES_PROOF`
313
+ * (`err.isEnrollmentProofRequired`). When the player can't prove the old method
314
+ * (they deleted/lost it — otherwise prefer `linkDevice`), run:
315
+ *
316
+ * 1. `recoveryBegin()` — sends a one-time code to the phone/email on file
317
+ * (422 `no_channel_on_file`, 429 `rate_limited` at 5/10min).
318
+ * 2. `recoveryComplete(code)` — deactivates the stale server-side passkey and
319
+ * authorizes a fresh enrollment (400 `ENROLLMENT_CODE_INVALID` on a wrong/
320
+ * expired code — attempt-capped; let the user retry or resend).
321
+ * 3. Immediately retry the SAME `enrollPasskey()` — it now succeeds.
322
+ *
323
+ * The owner also gets an out-of-band "your passkey was reset" SMS/email — that's
324
+ * the intended tamper alert; surface nothing special for it.
325
+ *
326
+ * ⚠ 24-HOUR MONEY COOLDOWN: a recovery-enrolled passkey logs in and COLLECTS
327
+ * funds immediately, but `approveSend`/`approveTransfer` throw
328
+ * `PASSKEY_RECOVERY_COOLDOWN` (403; `err.isPasskeyRecoveryCooldown`,
329
+ * `err.retryAfterAt`) for 24h — SIM-swap protection. Show the pause message with
330
+ * the timestamp; do not retry-loop it.
331
+ *
332
+ * If the OS itself fails to SAVE a new passkey ("there is a problem saving your
333
+ * passkey"), have the user delete the stale entry in their password manager first
334
+ * (iPhone: Settings → Passwords; Android: Google Password Manager; Windows:
335
+ * Settings → Accounts → Passkeys).
336
+ */
337
+ async recoveryBegin(opts) {
338
+ return this.withTokenRetry(async () => {
339
+ const raw = await this.post(
340
+ "/api/sdk/device/recover/begin",
341
+ void 0,
342
+ opts?.signal
343
+ );
344
+ return {
345
+ status: String(raw["status"] ?? ""),
346
+ channels: Array.isArray(raw["channels"]) ? raw["channels"] : [],
347
+ raw
348
+ };
349
+ });
350
+ }
351
+ /** Verify the recovery code (see {@link recoveryBegin}); on success, call `enrollPasskey()`. */
352
+ async recoveryComplete(code, opts) {
353
+ if (!code || !code.trim()) throw new Error("recoveryComplete requires the one-time `code`.");
354
+ return this.withTokenRetry(async () => {
355
+ const raw = await this.post(
356
+ "/api/sdk/device/recover/complete",
357
+ { code },
358
+ opts?.signal
359
+ );
360
+ return {
361
+ status: String(raw["status"] ?? ""),
362
+ deactivatedCount: Number(raw["deactivated_count"] ?? 0),
363
+ next: typeof raw["next"] === "string" ? raw["next"] : void 0,
364
+ raw
365
+ };
366
+ });
367
+ }
292
368
  // --- internals ---
293
369
  /** POST with the current player token. Token-expiry retry is handled one level
294
370
  * up by withTokenRetry (which re-runs the whole ceremony, not a single call). */
package/dist/server.cjs CHANGED
@@ -25,10 +25,35 @@ var InvoError = class _InvoError extends Error {
25
25
  get isEnrollmentAuthorizationRequired() {
26
26
  return this.code === "ENROLLMENT_REQUIRES_AUTHORIZATION";
27
27
  }
28
- /** True if enrolling is blocked because another method exists — use `linkDevice`. */
28
+ /**
29
+ * True if enrolling is blocked because the identity already has an enrolled method
30
+ * (anti-takeover gate, register/complete → 409). Two ways forward: `linkDevice` when
31
+ * the player still HAS the other method, or the passkey-recovery flow
32
+ * (`recoveryBegin`/`recoveryComplete` — "Lost or replaced your passkey?") when they
33
+ * deleted/lost it — the server can't know a device-side passkey is gone.
34
+ */
29
35
  get isEnrollmentProofRequired() {
30
36
  return this.code === "ENROLLMENT_REQUIRES_PROOF";
31
37
  }
38
+ /** True if the recovery OTP was wrong or expired (attempt-capped) — let the user retry or resend. */
39
+ get isEnrollmentCodeInvalid() {
40
+ return this.code === "ENROLLMENT_CODE_INVALID";
41
+ }
42
+ /**
43
+ * True if a money-OUT approve was refused because the passkey was enrolled via
44
+ * recovery less than 24h ago (SIM-swap protection, approve → 403). NOT a generic
45
+ * failure — do not retry-loop. Login and inbound confirm-receipt (collecting money)
46
+ * still work. Show: "For your security, transfers are paused for 24 hours after a
47
+ * passkey reset. You can still receive funds. Try again after {retryAfterAt}."
48
+ */
49
+ get isPasskeyRecoveryCooldown() {
50
+ return this.code === "PASSKEY_RECOVERY_COOLDOWN";
51
+ }
52
+ /** The ISO timestamp when a `PASSKEY_RECOVERY_COOLDOWN` lifts (`retry_after`), when present. */
53
+ get retryAfterAt() {
54
+ const v = this.bodyObject()["retry_after"];
55
+ return typeof v === "string" && v && Number.isNaN(Number(v)) ? v : void 0;
56
+ }
32
57
  /**
33
58
  * True if an item purchase failed because the player's balance was too low (§4.8 → 400).
34
59
  * The backend carries `required_amount` + `current_balance` on the body for the UI.
@@ -67,7 +92,7 @@ var InvoError = class _InvoError extends Error {
67
92
  /** Seconds to wait before retrying, when the backend throttled the call (429 `retry_after`). */
68
93
  get retryAfter() {
69
94
  const v = this.bodyObject()["retry_after"];
70
- const n = typeof v === "string" ? Number(v) : v;
95
+ const n = typeof v === "string" ? v.trim() === "" ? NaN : Number(v) : v;
71
96
  return typeof n === "number" && Number.isFinite(n) && n >= 0 ? n : void 0;
72
97
  }
73
98
  /** `body` as a plain object, or `{}` if it's a string/number/null (non-JSON responses).
@@ -85,7 +110,9 @@ function errorFromResponse(status, body, requestId) {
85
110
  else if (typeof b["error_code"] === "string") code = b["error_code"];
86
111
  if (typeof b["error"] === "string") message = b["error"];
87
112
  else if (typeof b["message"] === "string") message = b["message"];
88
- if (!code && typeof b["error"] === "string" && /^(flow_paused|spending_limit_exceeded|receiver_not_enrolled_use_claim_code)$/.test(b["error"])) {
113
+ if (!code && typeof b["error"] === "string" && /^(flow_paused|spending_limit_exceeded|receiver_not_enrolled_use_claim_code|no_channel_on_file|rate_limited)$/.test(
114
+ b["error"]
115
+ )) {
89
116
  code = b["error"];
90
117
  }
91
118
  } else if (typeof body === "string" && body.trim()) {
@@ -168,7 +195,13 @@ var _Http = class _Http {
168
195
  let res;
169
196
  let networkError;
170
197
  try {
171
- res = await this.fetchImpl(url, { method, headers, body: payload, signal: controller.signal });
198
+ res = await this.fetchImpl(url, {
199
+ method,
200
+ headers,
201
+ body: payload,
202
+ signal: controller.signal,
203
+ redirect: "manual"
204
+ });
172
205
  } catch (err) {
173
206
  networkError = new InvoError({
174
207
  message: err instanceof Error && err.name === "AbortError" ? `Request to ${path} timed out after ${this.timeoutMs}ms` : `Network error calling ${path}: ${err?.message ?? err}`,
@@ -189,6 +222,14 @@ var _Http = class _Http {
189
222
  }
190
223
  throw networkError;
191
224
  }
225
+ if (res.type === "opaqueredirect" || res.status >= 300 && res.status < 400) {
226
+ throw new InvoError({
227
+ message: `Refused to follow a redirect from ${path} \u2014 credentials are never re-sent to a redirected URL.`,
228
+ code: "UNEXPECTED_REDIRECT",
229
+ status: res.status || 0,
230
+ body: null
231
+ });
232
+ }
192
233
  const requestId = pickRequestId(res.headers);
193
234
  const text = await res.text();
194
235
  let parsed = null;
@@ -269,7 +310,7 @@ function pickRequestId(headers) {
269
310
  function retryAfterMs(parsed, headers) {
270
311
  if (parsed && typeof parsed === "object") {
271
312
  const v = parsed["retry_after"];
272
- const n = typeof v === "string" ? Number(v) : v;
313
+ const n = typeof v === "string" ? v.trim() === "" ? NaN : Number(v) : v;
273
314
  if (typeof n === "number" && Number.isFinite(n) && n >= 0) return n * 1e3;
274
315
  }
275
316
  const header = headers && typeof headers.get === "function" ? headers.get("retry-after") : null;
@@ -352,6 +393,12 @@ function parseSignatureHeader(header) {
352
393
  function hmacHex(secret, message) {
353
394
  return crypto.createHmac("sha256", secret).update(message).digest("hex");
354
395
  }
396
+ function safeEqualHexNode(a, b) {
397
+ const ba = Buffer.from(a, "utf8");
398
+ const bb = Buffer.from(b, "utf8");
399
+ if (ba.length !== bb.length) return false;
400
+ return crypto.timingSafeEqual(ba, bb);
401
+ }
355
402
  function safeEqualHex(a, b) {
356
403
  if (a.length !== b.length) return false;
357
404
  let diff = 0;
@@ -404,7 +451,7 @@ function verifyWebhook(rawBody, signatureHeader, secret, opts = {}) {
404
451
  );
405
452
  const matched = secrets.some((s) => {
406
453
  const expected = hmacHex(s, message);
407
- return sigs.some((sig) => safeEqualHex(sig, expected));
454
+ return sigs.some((sig) => safeEqualHexNode(sig, expected));
408
455
  });
409
456
  if (!matched) {
410
457
  throw webhookError("Webhook signature verification failed.", "WEBHOOK_SIGNATURE_INVALID");
@@ -481,7 +528,7 @@ async function hmacHexSubtle(secret, message) {
481
528
  }
482
529
 
483
530
  // src/server.ts
484
- var DEFAULT_UA = "invonetwork-web-sdk/2.0.0 (+https://invo.network)";
531
+ var DEFAULT_UA = "invonetwork-web-sdk/2.1.1 (+https://invo.network)";
485
532
  var MAX_USD_AMOUNT = 999.99;
486
533
  var MAX_ITEM_PRICE = 999999.99;
487
534
  function invalidInput(label, value, why) {
package/dist/server.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { I as InvoError, S as ServerConfig, a as CallOptions, l as PlayerToken, m as InitiateSendInput, n as InitiateResult, o as InitiateTransferInput, p as CreateCheckoutInput, q as CreateCheckoutResult, r as PurchaseInput, s as PurchaseResult, t as ConfirmPaymentResult, O as OrderDetailsResult, u as PurchaseItemInput, v as PurchaseItemResult, w as ItemHistoryQuery, x as ItemHistoryResult, y as ItemOrderQuery, z as PlayerBalanceQuery, F as PlayerBalanceResult, G as InboundPendingQuery, H as InboundPendingResult, J as LinkedIdentitiesQuery, K as LinkedIdentitiesResult, M as SmsVerifyResult, N as ClaimTransferInput, Q as ClaimResult, T as ClaimCurrencyInput, U as TransactionStatusResult, W as GuardianApprovalStatusResult, X as ServerDestinationsQuery, c as DestinationsResult, Y as PhoneShareContact, Z as PhoneShareInitiateResult, _ as PhoneShareApproveInput, $ as PhoneShareApproveResult, a0 as PhoneShareStatusResult } from './types-bp0UtN_N.cjs';
2
- export { a1 as CurrencyBalance, f as DestinationGame, a2 as InboundPendingItem, g as InvoErrorInfo, h as InvoHooks, i as InvoRequestInfo, j as InvoResponseInfo, a3 as LinkedIdentityEmail, R as Rail, V as VerificationMethod } from './types-bp0UtN_N.cjs';
1
+ import { I as InvoError, S as ServerConfig, a as CallOptions, n as PlayerToken, o as InitiateSendInput, p as InitiateResult, q as InitiateTransferInput, r as CreateCheckoutInput, s as CreateCheckoutResult, t as PurchaseInput, u as PurchaseResult, v as ConfirmPaymentResult, O as OrderDetailsResult, w as PurchaseItemInput, x as PurchaseItemResult, y as ItemHistoryQuery, z as ItemHistoryResult, F as ItemOrderQuery, G as PlayerBalanceQuery, H as PlayerBalanceResult, J as InboundPendingQuery, K as InboundPendingResult, M as LinkedIdentitiesQuery, N as LinkedIdentitiesResult, Q as SmsVerifyResult, T as ClaimTransferInput, U as ClaimResult, W as ClaimCurrencyInput, X as TransactionStatusResult, Y as GuardianApprovalStatusResult, Z as ServerDestinationsQuery, c as DestinationsResult, _ as PhoneShareContact, $ as PhoneShareInitiateResult, a0 as PhoneShareApproveInput, a1 as PhoneShareApproveResult, a2 as PhoneShareStatusResult } from './types-DtihCpOj.cjs';
2
+ export { a3 as CurrencyBalance, g as DestinationGame, a4 as InboundPendingItem, h as InvoErrorInfo, i as InvoHooks, j as InvoRequestInfo, k as InvoResponseInfo, a5 as LinkedIdentityEmail, m as Rail, V as VerificationMethod } from './types-DtihCpOj.cjs';
3
3
 
4
4
  interface VerifyWebhookOptions {
5
5
  /** Max age of the signed timestamp, in seconds. Default 300 (5 min). */
package/dist/server.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { I as InvoError, S as ServerConfig, a as CallOptions, l as PlayerToken, m as InitiateSendInput, n as InitiateResult, o as InitiateTransferInput, p as CreateCheckoutInput, q as CreateCheckoutResult, r as PurchaseInput, s as PurchaseResult, t as ConfirmPaymentResult, O as OrderDetailsResult, u as PurchaseItemInput, v as PurchaseItemResult, w as ItemHistoryQuery, x as ItemHistoryResult, y as ItemOrderQuery, z as PlayerBalanceQuery, F as PlayerBalanceResult, G as InboundPendingQuery, H as InboundPendingResult, J as LinkedIdentitiesQuery, K as LinkedIdentitiesResult, M as SmsVerifyResult, N as ClaimTransferInput, Q as ClaimResult, T as ClaimCurrencyInput, U as TransactionStatusResult, W as GuardianApprovalStatusResult, X as ServerDestinationsQuery, c as DestinationsResult, Y as PhoneShareContact, Z as PhoneShareInitiateResult, _ as PhoneShareApproveInput, $ as PhoneShareApproveResult, a0 as PhoneShareStatusResult } from './types-bp0UtN_N.js';
2
- export { a1 as CurrencyBalance, f as DestinationGame, a2 as InboundPendingItem, g as InvoErrorInfo, h as InvoHooks, i as InvoRequestInfo, j as InvoResponseInfo, a3 as LinkedIdentityEmail, R as Rail, V as VerificationMethod } from './types-bp0UtN_N.js';
1
+ import { I as InvoError, S as ServerConfig, a as CallOptions, n as PlayerToken, o as InitiateSendInput, p as InitiateResult, q as InitiateTransferInput, r as CreateCheckoutInput, s as CreateCheckoutResult, t as PurchaseInput, u as PurchaseResult, v as ConfirmPaymentResult, O as OrderDetailsResult, w as PurchaseItemInput, x as PurchaseItemResult, y as ItemHistoryQuery, z as ItemHistoryResult, F as ItemOrderQuery, G as PlayerBalanceQuery, H as PlayerBalanceResult, J as InboundPendingQuery, K as InboundPendingResult, M as LinkedIdentitiesQuery, N as LinkedIdentitiesResult, Q as SmsVerifyResult, T as ClaimTransferInput, U as ClaimResult, W as ClaimCurrencyInput, X as TransactionStatusResult, Y as GuardianApprovalStatusResult, Z as ServerDestinationsQuery, c as DestinationsResult, _ as PhoneShareContact, $ as PhoneShareInitiateResult, a0 as PhoneShareApproveInput, a1 as PhoneShareApproveResult, a2 as PhoneShareStatusResult } from './types-DtihCpOj.js';
2
+ export { a3 as CurrencyBalance, g as DestinationGame, a4 as InboundPendingItem, h as InvoErrorInfo, i as InvoHooks, j as InvoRequestInfo, k as InvoResponseInfo, a5 as LinkedIdentityEmail, m as Rail, V as VerificationMethod } from './types-DtihCpOj.js';
3
3
 
4
4
  interface VerifyWebhookOptions {
5
5
  /** Max age of the signed timestamp, in seconds. Default 300 (5 min). */
package/dist/server.js CHANGED
@@ -1,6 +1,6 @@
1
- import { InvoError, assertSecureBaseUrl, Http, toDestinationsResult } from './chunk-6XCI53XJ.js';
2
- export { InvoError } from './chunk-6XCI53XJ.js';
3
- import { createHmac } from 'crypto';
1
+ import { InvoError, assertSecureBaseUrl, Http, toDestinationsResult } from './chunk-4GNJIQY2.js';
2
+ export { InvoError } from './chunk-4GNJIQY2.js';
3
+ import { createHmac, timingSafeEqual } from 'crypto';
4
4
 
5
5
  var DEFAULT_TOLERANCE_SEC = 300;
6
6
  var ENCODER = new TextEncoder();
@@ -32,6 +32,12 @@ function parseSignatureHeader(header) {
32
32
  function hmacHex(secret, message) {
33
33
  return createHmac("sha256", secret).update(message).digest("hex");
34
34
  }
35
+ function safeEqualHexNode(a, b) {
36
+ const ba = Buffer.from(a, "utf8");
37
+ const bb = Buffer.from(b, "utf8");
38
+ if (ba.length !== bb.length) return false;
39
+ return timingSafeEqual(ba, bb);
40
+ }
35
41
  function safeEqualHex(a, b) {
36
42
  if (a.length !== b.length) return false;
37
43
  let diff = 0;
@@ -84,7 +90,7 @@ function verifyWebhook(rawBody, signatureHeader, secret, opts = {}) {
84
90
  );
85
91
  const matched = secrets.some((s) => {
86
92
  const expected = hmacHex(s, message);
87
- return sigs.some((sig) => safeEqualHex(sig, expected));
93
+ return sigs.some((sig) => safeEqualHexNode(sig, expected));
88
94
  });
89
95
  if (!matched) {
90
96
  throw webhookError("Webhook signature verification failed.", "WEBHOOK_SIGNATURE_INVALID");
@@ -161,7 +167,7 @@ async function hmacHexSubtle(secret, message) {
161
167
  }
162
168
 
163
169
  // src/server.ts
164
- var DEFAULT_UA = "invonetwork-web-sdk/2.0.0 (+https://invo.network)";
170
+ var DEFAULT_UA = "invonetwork-web-sdk/2.1.1 (+https://invo.network)";
165
171
  var MAX_USD_AMOUNT = 999.99;
166
172
  var MAX_ITEM_PRICE = 999999.99;
167
173
  function invalidInput(label, value, why) {
@@ -28,8 +28,26 @@ declare class InvoError extends Error {
28
28
  get isTokenExpired(): boolean;
29
29
  /** True if `enrollPasskey()` needs the OTP-grant flow (`enrollmentBegin`/`enrollmentVerify`). */
30
30
  get isEnrollmentAuthorizationRequired(): boolean;
31
- /** True if enrolling is blocked because another method exists — use `linkDevice`. */
31
+ /**
32
+ * True if enrolling is blocked because the identity already has an enrolled method
33
+ * (anti-takeover gate, register/complete → 409). Two ways forward: `linkDevice` when
34
+ * the player still HAS the other method, or the passkey-recovery flow
35
+ * (`recoveryBegin`/`recoveryComplete` — "Lost or replaced your passkey?") when they
36
+ * deleted/lost it — the server can't know a device-side passkey is gone.
37
+ */
32
38
  get isEnrollmentProofRequired(): boolean;
39
+ /** True if the recovery OTP was wrong or expired (attempt-capped) — let the user retry or resend. */
40
+ get isEnrollmentCodeInvalid(): boolean;
41
+ /**
42
+ * True if a money-OUT approve was refused because the passkey was enrolled via
43
+ * recovery less than 24h ago (SIM-swap protection, approve → 403). NOT a generic
44
+ * failure — do not retry-loop. Login and inbound confirm-receipt (collecting money)
45
+ * still work. Show: "For your security, transfers are paused for 24 hours after a
46
+ * passkey reset. You can still receive funds. Try again after {retryAfterAt}."
47
+ */
48
+ get isPasskeyRecoveryCooldown(): boolean;
49
+ /** The ISO timestamp when a `PASSKEY_RECOVERY_COOLDOWN` lifts (`retry_after`), when present. */
50
+ get retryAfterAt(): string | undefined;
33
51
  /**
34
52
  * True if an item purchase failed because the player's balance was too low (§4.8 → 400).
35
53
  * The backend carries `required_amount` + `current_balance` on the body for the UI.
@@ -475,6 +493,20 @@ interface EnrollmentVerifyResult {
475
493
  status: string;
476
494
  raw: Record<string, unknown>;
477
495
  }
496
+ interface RecoveryBeginResult {
497
+ status: string;
498
+ /** Channels the one-time code was sent to, e.g. ["sms","email"]. */
499
+ channels: string[];
500
+ raw: Record<string, unknown>;
501
+ }
502
+ interface RecoveryCompleteResult {
503
+ status: string;
504
+ /** How many stale server-side passkeys were deactivated. */
505
+ deactivatedCount: number;
506
+ /** Human hint from the backend (what to do next). */
507
+ next?: string;
508
+ raw: Record<string, unknown>;
509
+ }
478
510
  interface LinkDeviceResult {
479
511
  /** "authorized" on success — a single-use grant that register/complete consumes. */
480
512
  status: string;
@@ -603,4 +635,4 @@ interface PhoneShareStatusResult {
603
635
  raw: Record<string, unknown>;
604
636
  }
605
637
 
606
- export { type PhoneShareApproveResult as $, type ApproveResult as A, type BalanceResult as B, type ClientConfig as C, type DestinationsQuery as D, type EnrollmentBeginResult as E, type PlayerBalanceResult as F, type InboundPendingQuery as G, type InboundPendingResult as H, InvoError as I, type LinkedIdentitiesQuery as J, type LinkedIdentitiesResult as K, type LinkDeviceResult as L, type SmsVerifyResult as M, type ClaimTransferInput as N, type OrderDetailsResult as O, type PendingCollectResult as P, type ClaimResult as Q, type Rail as R, type ServerConfig as S, type ClaimCurrencyInput as T, type TransactionStatusResult as U, type VerificationMethod as V, type GuardianApprovalStatusResult as W, type ServerDestinationsQuery as X, type PhoneShareContact as Y, type PhoneShareInitiateResult as Z, type PhoneShareApproveInput as _, type CallOptions as a, type PhoneShareStatusResult as a0, type CurrencyBalance as a1, type InboundPendingItem as a2, type LinkedIdentityEmail as a3, type ConfirmReceiptResult as b, type DestinationsResult as c, type EnrollmentVerifyResult as d, type BalanceRow as e, type DestinationGame as f, type InvoErrorInfo as g, type InvoHooks as h, type InvoRequestInfo as i, type InvoResponseInfo as j, type PendingCollectItem as k, type PlayerToken as l, type InitiateSendInput as m, type InitiateResult as n, type InitiateTransferInput as o, type CreateCheckoutInput as p, type CreateCheckoutResult as q, type PurchaseInput as r, type PurchaseResult as s, type ConfirmPaymentResult as t, type PurchaseItemInput as u, type PurchaseItemResult as v, type ItemHistoryQuery as w, type ItemHistoryResult as x, type ItemOrderQuery as y, type PlayerBalanceQuery as z };
638
+ export { type PhoneShareInitiateResult as $, type ApproveResult as A, type BalanceResult as B, type ClientConfig as C, type DestinationsQuery as D, type EnrollmentBeginResult as E, type ItemOrderQuery as F, type PlayerBalanceQuery as G, type PlayerBalanceResult as H, InvoError as I, type InboundPendingQuery as J, type InboundPendingResult as K, type LinkDeviceResult as L, type LinkedIdentitiesQuery as M, type LinkedIdentitiesResult as N, type OrderDetailsResult as O, type PendingCollectResult as P, type SmsVerifyResult as Q, type RecoveryBeginResult as R, type ServerConfig as S, type ClaimTransferInput as T, type ClaimResult as U, type VerificationMethod as V, type ClaimCurrencyInput as W, type TransactionStatusResult as X, type GuardianApprovalStatusResult as Y, type ServerDestinationsQuery as Z, type PhoneShareContact as _, type CallOptions as a, type PhoneShareApproveInput as a0, type PhoneShareApproveResult as a1, type PhoneShareStatusResult as a2, type CurrencyBalance as a3, type InboundPendingItem as a4, type LinkedIdentityEmail as a5, type ConfirmReceiptResult as b, type DestinationsResult as c, type EnrollmentVerifyResult as d, type RecoveryCompleteResult as e, type BalanceRow as f, type DestinationGame as g, type InvoErrorInfo as h, type InvoHooks as i, type InvoRequestInfo as j, type InvoResponseInfo as k, type PendingCollectItem as l, type Rail as m, type PlayerToken as n, type InitiateSendInput as o, type InitiateResult as p, type InitiateTransferInput as q, type CreateCheckoutInput as r, type CreateCheckoutResult as s, type PurchaseInput as t, type PurchaseResult as u, type ConfirmPaymentResult as v, type PurchaseItemInput as w, type PurchaseItemResult as x, type ItemHistoryQuery as y, type ItemHistoryResult as z };
@@ -28,8 +28,26 @@ declare class InvoError extends Error {
28
28
  get isTokenExpired(): boolean;
29
29
  /** True if `enrollPasskey()` needs the OTP-grant flow (`enrollmentBegin`/`enrollmentVerify`). */
30
30
  get isEnrollmentAuthorizationRequired(): boolean;
31
- /** True if enrolling is blocked because another method exists — use `linkDevice`. */
31
+ /**
32
+ * True if enrolling is blocked because the identity already has an enrolled method
33
+ * (anti-takeover gate, register/complete → 409). Two ways forward: `linkDevice` when
34
+ * the player still HAS the other method, or the passkey-recovery flow
35
+ * (`recoveryBegin`/`recoveryComplete` — "Lost or replaced your passkey?") when they
36
+ * deleted/lost it — the server can't know a device-side passkey is gone.
37
+ */
32
38
  get isEnrollmentProofRequired(): boolean;
39
+ /** True if the recovery OTP was wrong or expired (attempt-capped) — let the user retry or resend. */
40
+ get isEnrollmentCodeInvalid(): boolean;
41
+ /**
42
+ * True if a money-OUT approve was refused because the passkey was enrolled via
43
+ * recovery less than 24h ago (SIM-swap protection, approve → 403). NOT a generic
44
+ * failure — do not retry-loop. Login and inbound confirm-receipt (collecting money)
45
+ * still work. Show: "For your security, transfers are paused for 24 hours after a
46
+ * passkey reset. You can still receive funds. Try again after {retryAfterAt}."
47
+ */
48
+ get isPasskeyRecoveryCooldown(): boolean;
49
+ /** The ISO timestamp when a `PASSKEY_RECOVERY_COOLDOWN` lifts (`retry_after`), when present. */
50
+ get retryAfterAt(): string | undefined;
33
51
  /**
34
52
  * True if an item purchase failed because the player's balance was too low (§4.8 → 400).
35
53
  * The backend carries `required_amount` + `current_balance` on the body for the UI.
@@ -475,6 +493,20 @@ interface EnrollmentVerifyResult {
475
493
  status: string;
476
494
  raw: Record<string, unknown>;
477
495
  }
496
+ interface RecoveryBeginResult {
497
+ status: string;
498
+ /** Channels the one-time code was sent to, e.g. ["sms","email"]. */
499
+ channels: string[];
500
+ raw: Record<string, unknown>;
501
+ }
502
+ interface RecoveryCompleteResult {
503
+ status: string;
504
+ /** How many stale server-side passkeys were deactivated. */
505
+ deactivatedCount: number;
506
+ /** Human hint from the backend (what to do next). */
507
+ next?: string;
508
+ raw: Record<string, unknown>;
509
+ }
478
510
  interface LinkDeviceResult {
479
511
  /** "authorized" on success — a single-use grant that register/complete consumes. */
480
512
  status: string;
@@ -603,4 +635,4 @@ interface PhoneShareStatusResult {
603
635
  raw: Record<string, unknown>;
604
636
  }
605
637
 
606
- export { type PhoneShareApproveResult as $, type ApproveResult as A, type BalanceResult as B, type ClientConfig as C, type DestinationsQuery as D, type EnrollmentBeginResult as E, type PlayerBalanceResult as F, type InboundPendingQuery as G, type InboundPendingResult as H, InvoError as I, type LinkedIdentitiesQuery as J, type LinkedIdentitiesResult as K, type LinkDeviceResult as L, type SmsVerifyResult as M, type ClaimTransferInput as N, type OrderDetailsResult as O, type PendingCollectResult as P, type ClaimResult as Q, type Rail as R, type ServerConfig as S, type ClaimCurrencyInput as T, type TransactionStatusResult as U, type VerificationMethod as V, type GuardianApprovalStatusResult as W, type ServerDestinationsQuery as X, type PhoneShareContact as Y, type PhoneShareInitiateResult as Z, type PhoneShareApproveInput as _, type CallOptions as a, type PhoneShareStatusResult as a0, type CurrencyBalance as a1, type InboundPendingItem as a2, type LinkedIdentityEmail as a3, type ConfirmReceiptResult as b, type DestinationsResult as c, type EnrollmentVerifyResult as d, type BalanceRow as e, type DestinationGame as f, type InvoErrorInfo as g, type InvoHooks as h, type InvoRequestInfo as i, type InvoResponseInfo as j, type PendingCollectItem as k, type PlayerToken as l, type InitiateSendInput as m, type InitiateResult as n, type InitiateTransferInput as o, type CreateCheckoutInput as p, type CreateCheckoutResult as q, type PurchaseInput as r, type PurchaseResult as s, type ConfirmPaymentResult as t, type PurchaseItemInput as u, type PurchaseItemResult as v, type ItemHistoryQuery as w, type ItemHistoryResult as x, type ItemOrderQuery as y, type PlayerBalanceQuery as z };
638
+ export { type PhoneShareInitiateResult as $, type ApproveResult as A, type BalanceResult as B, type ClientConfig as C, type DestinationsQuery as D, type EnrollmentBeginResult as E, type ItemOrderQuery as F, type PlayerBalanceQuery as G, type PlayerBalanceResult as H, InvoError as I, type InboundPendingQuery as J, type InboundPendingResult as K, type LinkDeviceResult as L, type LinkedIdentitiesQuery as M, type LinkedIdentitiesResult as N, type OrderDetailsResult as O, type PendingCollectResult as P, type SmsVerifyResult as Q, type RecoveryBeginResult as R, type ServerConfig as S, type ClaimTransferInput as T, type ClaimResult as U, type VerificationMethod as V, type ClaimCurrencyInput as W, type TransactionStatusResult as X, type GuardianApprovalStatusResult as Y, type ServerDestinationsQuery as Z, type PhoneShareContact as _, type CallOptions as a, type PhoneShareApproveInput as a0, type PhoneShareApproveResult as a1, type PhoneShareStatusResult as a2, type CurrencyBalance as a3, type InboundPendingItem as a4, type LinkedIdentityEmail as a5, type ConfirmReceiptResult as b, type DestinationsResult as c, type EnrollmentVerifyResult as d, type RecoveryCompleteResult as e, type BalanceRow as f, type DestinationGame as g, type InvoErrorInfo as h, type InvoHooks as i, type InvoRequestInfo as j, type InvoResponseInfo as k, type PendingCollectItem as l, type Rail as m, type PlayerToken as n, type InitiateSendInput as o, type InitiateResult as p, type InitiateTransferInput as q, type CreateCheckoutInput as r, type CreateCheckoutResult as s, type PurchaseInput as t, type PurchaseResult as u, type ConfirmPaymentResult as v, type PurchaseItemInput as w, type PurchaseItemResult as x, type ItemHistoryQuery as y, type ItemHistoryResult as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@invonetwork/web-sdk",
3
- "version": "2.0.0",
3
+ "version": "2.1.1",
4
4
  "description": "INVO Web SDK — currency purchase + passkey (WebAuthn) verification for partner web platforms.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "private": false,