@invonetwork/web-sdk 3.6.0 → 3.7.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/dist/server.js CHANGED
@@ -1,5 +1,5 @@
1
- import { InvoError, assertSecureBaseUrl, Http, toDestinationsResult } from './chunk-MBKE6ULW.js';
2
- export { InvoError } from './chunk-MBKE6ULW.js';
1
+ import { InvoError, assertSecureBaseUrl, Http, toDestinationsResult } from './chunk-23TGMTII.js';
2
+ export { InvoError } from './chunk-23TGMTII.js';
3
3
  import { createHmac, timingSafeEqual } from 'crypto';
4
4
 
5
5
  var DEFAULT_TOLERANCE_SEC = 300;
@@ -304,6 +304,133 @@ function toPhoneShareApproveResult(raw) {
304
304
  raw
305
305
  };
306
306
  }
307
+ var DEVICE_APPROVAL_FLOWS = /* @__PURE__ */ new Set([
308
+ "transfer",
309
+ "send",
310
+ "send_receipt",
311
+ "transfer_receipt"
312
+ ]);
313
+ var DEVICE_APPROVAL_CHANNELS = /* @__PURE__ */ new Set([
314
+ "qr",
315
+ "app_browser",
316
+ "popup"
317
+ ]);
318
+ var DEVICE_POLL_OUTCOME_TOKENS = /* @__PURE__ */ new Set([
319
+ "authorization_pending",
320
+ "slow_down",
321
+ "expired_token",
322
+ "access_denied"
323
+ ]);
324
+ function deviceApprovalSettlePath(flow, transactionId) {
325
+ const id = encodeURIComponent(transactionId);
326
+ switch (flow) {
327
+ case "transfer":
328
+ return `/api/sdk/transfers/${id}/approve`;
329
+ case "send":
330
+ return `/api/sdk/send/${id}/approve`;
331
+ case "send_receipt":
332
+ return `/api/sdk/send/${id}/confirm-receipt`;
333
+ case "transfer_receipt":
334
+ return `/api/sdk/transfers/${id}/confirm-receipt`;
335
+ }
336
+ }
337
+ var DEVICE_SETTLED_STATUSES = {
338
+ // Sender's approve: anything from "approved, awaiting the claim" onwards.
339
+ transfer: /* @__PURE__ */ new Set([
340
+ "pending_claim",
341
+ "verified",
342
+ "pin_verified_awaiting_claim",
343
+ "completed",
344
+ "distributed"
345
+ ]),
346
+ send: /* @__PURE__ */ new Set([
347
+ "pending_claim",
348
+ "verified",
349
+ "pin_verified_awaiting_claim",
350
+ "completed",
351
+ "distributed"
352
+ ]),
353
+ // Recipient's collect: only a finished transaction is past it. `pending_claim` and
354
+ // `verified` are this step's own gate statuses, not states beyond it.
355
+ send_receipt: /* @__PURE__ */ new Set(["completed", "distributed"]),
356
+ transfer_receipt: /* @__PURE__ */ new Set(["completed", "distributed"])
357
+ };
358
+ function isPastThisStep(flow, currentStatus) {
359
+ return DEVICE_SETTLED_STATUSES[flow].has(currentStatus.trim().toLowerCase());
360
+ }
361
+ function assertPlayerToken(playerToken) {
362
+ if (typeof playerToken !== "string" || !playerToken.trim()) {
363
+ throw invalidInput("playerToken", playerToken, "is required (the player's session token, not the game secret)");
364
+ }
365
+ }
366
+ function assertDeviceApprovalFlow(flow) {
367
+ if (typeof flow !== "string" || !DEVICE_APPROVAL_FLOWS.has(flow)) {
368
+ throw invalidInput("flow", flow, 'must be "transfer" | "send" | "send_receipt" | "transfer_receipt"');
369
+ }
370
+ }
371
+ function toDeviceApprovalGrant(raw) {
372
+ return {
373
+ deviceCode: requireField(raw["device_code"], "device_code", raw),
374
+ userCode: String(raw["user_code"] ?? ""),
375
+ verificationUri: String(raw["verification_uri"] ?? ""),
376
+ verificationUriComplete: requireField(raw["verification_uri_complete"], "verification_uri_complete", raw),
377
+ expiresIn: Number(raw["expires_in"] ?? 0) || 0,
378
+ interval: Math.max(1, Number(raw["interval"] ?? 5) || 5),
379
+ channel: String(raw["channel"] ?? "qr"),
380
+ raw
381
+ };
382
+ }
383
+ function toDeviceApprovalEnrollment(raw) {
384
+ return {
385
+ state: String(raw["state"] ?? ""),
386
+ deviceLabel: String(raw["device_label"] ?? ""),
387
+ matchCode: String(raw["match_code"] ?? ""),
388
+ recovery: raw["recovery"] === true,
389
+ requestedAt: raw["requested_at"] ?? null,
390
+ raw
391
+ };
392
+ }
393
+ function toDevicePollOutcome(token, body) {
394
+ const interval = Number(body["interval"]);
395
+ const enrollment = body["enrollment"];
396
+ return {
397
+ status: token,
398
+ interval: Number.isFinite(interval) && interval > 0 ? interval : void 0,
399
+ enrollment: enrollment && typeof enrollment === "object" ? toDeviceApprovalEnrollment(enrollment) : void 0,
400
+ raw: body
401
+ };
402
+ }
403
+ function toDeviceApprovalSettleResult(raw, input) {
404
+ const holdReason = raw["error_code"] ?? raw["code"];
405
+ return {
406
+ status: String(raw["status"] ?? ""),
407
+ transactionId: String(raw["transaction_id"] ?? input.transactionId),
408
+ flow: input.flow,
409
+ alreadySettled: false,
410
+ next: raw["next"],
411
+ claimCode: raw["claim_code"],
412
+ claimCodeExpiresAt: raw["claim_code_expires_at"],
413
+ amountReceived: raw["amount_received"] == null ? void 0 : String(raw["amount_received"]),
414
+ holdReason: typeof holdReason === "string" ? holdReason : void 0,
415
+ risk: raw["risk"],
416
+ guardianApproval: raw["guardian_approval"] ?? void 0,
417
+ pollEndpoint: raw["poll_endpoint"],
418
+ raw
419
+ };
420
+ }
421
+ function sleepFor(ms, signal) {
422
+ return new Promise((resolve) => {
423
+ if (signal?.aborted) return resolve();
424
+ const timer = setTimeout(done, ms);
425
+ const onAbort = () => done();
426
+ function done() {
427
+ clearTimeout(timer);
428
+ signal?.removeEventListener("abort", onAbort);
429
+ resolve();
430
+ }
431
+ signal?.addEventListener("abort", onAbort, { once: true });
432
+ });
433
+ }
307
434
  function toCurrencyBalance(row) {
308
435
  return {
309
436
  currencyId: row["currency_id"] ?? "",
@@ -1368,6 +1495,299 @@ var InvoServer = class {
1368
1495
  );
1369
1496
  return { approved: raw["approved"] === true, raw };
1370
1497
  }
1498
+ // ---- Device approval grant (RFC 8628) — consoles, TVs, native Steam / desktop ----
1499
+ //
1500
+ // These take the PLAYER TOKEN explicitly: on a console the game server minted it and
1501
+ // holds it, and every call below authenticates with it — the game secret is never
1502
+ // sent. The grant is a FACTOR. `beginDeviceApproval` + `pollDeviceApproval` reaching
1503
+ // `approved` settles NOTHING; `approveWithDeviceCode` is the step that moves the money.
1504
+ /**
1505
+ * Stage 1 — start a device approval for ONE transaction (RFC 8628 §3.1/§3.2).
1506
+ *
1507
+ * Returns the grant: render `verificationUriComplete` as the QR (print `userCode`
1508
+ * under it for a TV with no camera), keep `deviceCode` on your server, then poll.
1509
+ * A repeat `begin` while an earlier grant is merely PENDING supersedes it (fresh code;
1510
+ * a page still open on the old one is told to scan again). A grant the player already
1511
+ * APPROVED blocks a new `begin` for its window with `409 DEVICE_APPROVAL_ALREADY_PENDING`
1512
+ * (`err.isDeviceApprovalAlreadyPending`, `err.deviceApprovalExpiresAt`) — the missing
1513
+ * step there is `approveWithDeviceCode`, not a new code.
1514
+ *
1515
+ * For `transfer` / `send` the backend also pushes the transaction's own approval
1516
+ * window past the grant's expiry, so an approval at minute nine cannot land on a
1517
+ * transfer that has already been refunded. Auth: the player token. `channel: "popup"`
1518
+ * is browser-only (`InvoClient.approveHosted`) and is refused before the network.
1519
+ */
1520
+ async beginDeviceApproval(input, opts) {
1521
+ assertPlayerToken(input.playerToken);
1522
+ if (typeof input.transactionId !== "string" || !input.transactionId.trim()) {
1523
+ throw invalidInput("transactionId", input.transactionId, "is required");
1524
+ }
1525
+ assertDeviceApprovalFlow(input.flow);
1526
+ const channel = input.channel ?? "qr";
1527
+ if (!DEVICE_APPROVAL_CHANNELS.has(channel)) {
1528
+ throw invalidInput("channel", channel, 'must be "qr" | "app_browser" ("popup" is browser-only)');
1529
+ }
1530
+ if (channel === "popup") {
1531
+ throw new InvoError({
1532
+ message: `channel "popup" is browser-only \u2014 the page must call begin itself so its Origin becomes the popup's opener. Use InvoClient.approveHosted() there; server-side use "qr" or "app_browser".`,
1533
+ code: "INVALID_INPUT",
1534
+ status: 0
1535
+ });
1536
+ }
1537
+ const raw = await this.http.post(
1538
+ "/api/sdk/approvals/device/begin",
1539
+ { transaction_id: input.transactionId, flow: input.flow, channel },
1540
+ { kind: "bearer", token: input.playerToken },
1541
+ // PLAYER token — never the game secret
1542
+ // Safe to retry: a lost-response retry supersedes the unseen pending grant with a
1543
+ // fresh code (one live grant per transaction + flow either way).
1544
+ { idempotent: true, signal: opts?.signal }
1545
+ );
1546
+ return toDeviceApprovalGrant(raw);
1547
+ }
1548
+ /**
1549
+ * Stage 3 — one poll (RFC 8628 §3.4/§3.5). Call it no faster than `interval` seconds.
1550
+ *
1551
+ * Returns `status`:
1552
+ * - `authorization_pending` — keep polling. While a first-time phone waits on your
1553
+ * screen, `enrollment` is present: show "Set up INVO on <deviceLabel>? Code
1554
+ * <matchCode>" and answer with `confirmDeviceEnrollment`.
1555
+ * - `slow_down` — add 5 s to your interval, then resume.
1556
+ * - `approved` — **now call `approveWithDeviceCode`**. Nothing has moved yet.
1557
+ * - `access_denied` — the player declined; do not retry silently.
1558
+ * - `expired_token` — the grant lapsed; `beginDeviceApproval` again.
1559
+ * Throws `InvoError` for `invalid_grant` (`err.code === "invalid_grant"`: unknown code,
1560
+ * or not this player's — one answer for both, deliberately) and for transport failures
1561
+ * after the retry budget (429 / 5xx are retried: this is an idempotent read).
1562
+ */
1563
+ async pollDeviceApproval(input, opts) {
1564
+ assertPlayerToken(input.playerToken);
1565
+ if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
1566
+ throw invalidInput("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
1567
+ }
1568
+ let raw;
1569
+ try {
1570
+ raw = await this.http.post(
1571
+ "/api/sdk/approvals/device/poll",
1572
+ { device_code: input.deviceCode },
1573
+ { kind: "bearer", token: input.playerToken },
1574
+ { idempotent: true, signal: opts?.signal }
1575
+ // a read; safe to retry
1576
+ );
1577
+ } catch (err) {
1578
+ if (err instanceof InvoError && err.status === 400 && typeof err.code === "string" && DEVICE_POLL_OUTCOME_TOKENS.has(err.code)) {
1579
+ const body = err.body && typeof err.body === "object" ? err.body : {};
1580
+ return toDevicePollOutcome(err.code, body);
1581
+ }
1582
+ throw err;
1583
+ }
1584
+ return {
1585
+ status: "approved",
1586
+ transactionId: raw["transaction_id"],
1587
+ flow: raw["flow"],
1588
+ approvedAt: raw["approved_at"] ?? null,
1589
+ raw
1590
+ };
1591
+ }
1592
+ /**
1593
+ * Stage 3b — answer the on-screen match-code prompt for a first-time phone.
1594
+ *
1595
+ * `approve` = "yes, the phone I just scanned with shows this code" (the phone then
1596
+ * creates its INVO passkey and approves); `deny` ends the whole grant — the next poll
1597
+ * answers `access_denied`. Answered once: `409 DEVICE_APPROVAL_ENROLLMENT_ALREADY_DECIDED`
1598
+ * means the backup email got there first — take the prompt down quietly.
1599
+ * `409 DEVICE_APPROVAL_NO_ENROLLMENT_PENDING`: no phone has asked. Not auto-retried.
1600
+ */
1601
+ async confirmDeviceEnrollment(input, opts) {
1602
+ assertPlayerToken(input.playerToken);
1603
+ if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
1604
+ throw invalidInput("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
1605
+ }
1606
+ if (input.decision !== "approve" && input.decision !== "deny") {
1607
+ throw invalidInput("decision", input.decision, 'must be "approve" or "deny"');
1608
+ }
1609
+ const raw = await this.http.post(
1610
+ "/api/sdk/approvals/device/confirm-enrollment",
1611
+ { device_code: input.deviceCode, decision: input.decision },
1612
+ { kind: "bearer", token: input.playerToken },
1613
+ { signal: opts?.signal }
1614
+ // a decision — never auto-retried
1615
+ );
1616
+ return { status: String(raw["status"] ?? ""), raw };
1617
+ }
1618
+ /**
1619
+ * Stage 4 — THE MONEY STEP. Once the poll says `approved`, call this with the same
1620
+ * player token and the grant's `deviceCode`. Routes by `flow`:
1621
+ *
1622
+ * transfer → POST /api/sdk/transfers/{id}/approve
1623
+ * send → POST /api/sdk/send/{id}/approve
1624
+ * send_receipt → POST /api/sdk/send/{id}/confirm-receipt
1625
+ * transfer_receipt → POST /api/sdk/transfers/{id}/confirm-receipt
1626
+ *
1627
+ * The grant proves WHO approved; this call runs every gate the in-app passkey approve
1628
+ * runs (guardian, risk, recovery cooldown) and moves the money. A grant that is never
1629
+ * followed by this call moves nothing, and is consumed by nothing.
1630
+ *
1631
+ * Result: `status: "approved"` + `next: "pending_claim"` (transfer/send; `claimCode`
1632
+ * on a transfer) or `status: "completed"` + `amountReceived` (receipt flows). A 202
1633
+ * hold returns `holdReason` (money held, not refused). A repeat call after the code was
1634
+ * consumed returns `status: "not_pending"` with `currentStatus` and `alreadySettled`
1635
+ * — the backend's `TRANSACTION_NOT_PENDING` mapped into a result rather than thrown,
1636
+ * because for this call it is the normal answer to "did my earlier attempt land?".
1637
+ *
1638
+ * Throws `InvoError`: `err.isDeviceApprovalNotApproved` (400 — wrong/foreign code,
1639
+ * wrong flow, or the poll never said approved), `err.isPasskeyRecoveryCooldown` (403,
1640
+ * money-out after a passkey recovery — `err.retryAfterAt`), guardian terminal states
1641
+ * (410). Never auto-retried: the device_code is a single-use factor.
1642
+ *
1643
+ * **A FAILURE HERE IS AMBIGUOUS ABOUT THE MONEY.** The backend commits the transfer and
1644
+ * *then* builds its 200 by reading the transaction back, so a fault raised after that
1645
+ * commit answers `SEND_APPROVE_FAILED` / `TRANSFER_APPROVE_FAILED` /
1646
+ * `CONFIRM_RECEIPT_FAILED` (`err.isSettleFault`, `err.errorRef`) for money that already
1647
+ * moved. A `status === 0` (timeout, connection dropped) is ambiguous for the same
1648
+ * reason, and this call is deliberately not auto-retried. So on either: read
1649
+ * `getTransferStatus` / `getSendStatus`, or wait for the `transfer.claim_pending`
1650
+ * webhook, BEFORE you tell the player it failed — and never auto-start a replacement
1651
+ * transaction.
1652
+ */
1653
+ async approveWithDeviceCode(input, opts) {
1654
+ assertPlayerToken(input.playerToken);
1655
+ if (typeof input.transactionId !== "string" || !input.transactionId.trim()) {
1656
+ throw invalidInput("transactionId", input.transactionId, "is required");
1657
+ }
1658
+ assertDeviceApprovalFlow(input.flow);
1659
+ if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
1660
+ throw invalidInput("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
1661
+ }
1662
+ let raw;
1663
+ try {
1664
+ raw = await this.http.post(
1665
+ deviceApprovalSettlePath(input.flow, input.transactionId),
1666
+ { device_code: input.deviceCode },
1667
+ { kind: "bearer", token: input.playerToken },
1668
+ // PLAYER token — never the game secret
1669
+ { signal: opts?.signal }
1670
+ // NOT idempotent — the device_code is single-use; never auto-retried
1671
+ );
1672
+ } catch (err) {
1673
+ if (err instanceof InvoError && err.isTransactionNotPending) {
1674
+ const body = err.body && typeof err.body === "object" ? err.body : {};
1675
+ const currentStatus = err.currentTransactionStatus ?? "";
1676
+ return {
1677
+ status: "not_pending",
1678
+ transactionId: input.transactionId,
1679
+ flow: input.flow,
1680
+ alreadySettled: currentStatus !== "" && isPastThisStep(input.flow, currentStatus),
1681
+ currentStatus: currentStatus || void 0,
1682
+ raw: body
1683
+ };
1684
+ }
1685
+ throw err;
1686
+ }
1687
+ return toDeviceApprovalSettleResult(raw, input);
1688
+ }
1689
+ /**
1690
+ * Convenience only — stages 3 and 4 in one call, for a server that can hold the loop
1691
+ * open (a per-request worker, a job). Polls `pollDeviceApproval` on `interval`, adds
1692
+ * 5 s on `slow_down`, forwards the poll's `enrollment` to `onEnrollment` (answer with
1693
+ * `respond`), and on `approved` calls `approveWithDeviceCode` — THEN resolves.
1694
+ * `respond` is best-effort: a prompt the grant has outlived (`expired_token`,
1695
+ * `invalid_grant`) or that was already answered elsewhere resolves quietly rather than
1696
+ * rejecting, because callers fire it from UI code without awaiting it.
1697
+ * You still call `beginDeviceApproval` yourself first, because your game has to draw
1698
+ * the QR between begin and the first poll.
1699
+ *
1700
+ * Resolves `{ status: "approved", settlement }` | `denied` | `expired` | `aborted`.
1701
+ * Rejects on `invalid_grant`, on a refused approve (e.g. `PASSKEY_RECOVERY_COOLDOWN`),
1702
+ * and after 5 consecutive transport failures on the poll.
1703
+ *
1704
+ * **Record the attempt in your own store BEFORE you call this.** It blocks for as long
1705
+ * as the player takes and then moves money from inside the loop, so if your process
1706
+ * dies between the approve call and its response, a row you wrote first — plus
1707
+ * `getTransferStatus` / `getSendStatus` — is the only way to learn whether the money
1708
+ * moved. Servers that must not block a request use the three calls directly and keep
1709
+ * `deviceCode` in their own store.
1710
+ *
1711
+ * `respond` (handed to `onEnrollment`) is best-effort: a prompt the grant has outlived
1712
+ * resolves quietly rather than rejecting. Any other confirm-enrollment refusal
1713
+ * propagates, so `await` it if you want to see one.
1714
+ */
1715
+ async completeDeviceApproval(input, opts) {
1716
+ assertPlayerToken(input.playerToken);
1717
+ if (typeof input.transactionId !== "string" || !input.transactionId.trim()) {
1718
+ throw invalidInput("transactionId", input.transactionId, "is required");
1719
+ }
1720
+ assertDeviceApprovalFlow(input.flow);
1721
+ if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
1722
+ throw invalidInput("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
1723
+ }
1724
+ const signal = input.signal ?? opts?.signal;
1725
+ const { playerToken, deviceCode } = input;
1726
+ let interval = Math.max(1, Number(input.interval) || 5);
1727
+ let lastPoll;
1728
+ let lastEnrollmentKey = null;
1729
+ let transientFailures = 0;
1730
+ const MAX_TRANSIENT = 5;
1731
+ const respond = async (decision) => {
1732
+ try {
1733
+ await this.confirmDeviceEnrollment({ playerToken, deviceCode, decision }, { signal });
1734
+ } catch (err) {
1735
+ if (err instanceof InvoError && (err.code === "DEVICE_APPROVAL_ENROLLMENT_ALREADY_DECIDED" || err.code === "DEVICE_APPROVAL_NO_ENROLLMENT_PENDING" || err.code === "expired_token" || err.code === "invalid_grant")) {
1736
+ return;
1737
+ }
1738
+ throw err;
1739
+ }
1740
+ };
1741
+ const publishEnrollment = (e) => {
1742
+ if (!input.onEnrollment) return;
1743
+ const key = e ? `${e.state}|${e.matchCode}|${e.deviceLabel}|${e.recovery}` : null;
1744
+ if (key === lastEnrollmentKey) return;
1745
+ lastEnrollmentKey = key;
1746
+ input.onEnrollment(e ?? null, respond);
1747
+ };
1748
+ for (; ; ) {
1749
+ await sleepFor(interval * 1e3, signal);
1750
+ if (signal?.aborted) return { status: "aborted", lastPoll };
1751
+ let poll;
1752
+ try {
1753
+ poll = await this.pollDeviceApproval({ playerToken, deviceCode }, { signal });
1754
+ } catch (err) {
1755
+ if (signal?.aborted) return { status: "aborted", lastPoll };
1756
+ const transient = err instanceof InvoError && (err.status === 0 || err.status === 429 || err.status >= 500);
1757
+ if (transient && ++transientFailures < MAX_TRANSIENT) {
1758
+ const ra = err instanceof InvoError && err.status === 429 ? err.retryAfter : void 0;
1759
+ if (typeof ra === "number" && ra > interval) interval = ra;
1760
+ continue;
1761
+ }
1762
+ throw err;
1763
+ }
1764
+ transientFailures = 0;
1765
+ lastPoll = poll;
1766
+ switch (poll.status) {
1767
+ case "authorization_pending":
1768
+ if (poll.interval) interval = poll.interval;
1769
+ publishEnrollment(poll.enrollment);
1770
+ continue;
1771
+ case "slow_down":
1772
+ interval = Math.max(interval + 5, poll.interval ?? 0);
1773
+ continue;
1774
+ case "expired_token":
1775
+ publishEnrollment(void 0);
1776
+ return { status: "expired", lastPoll };
1777
+ case "access_denied":
1778
+ publishEnrollment(void 0);
1779
+ return { status: "denied", lastPoll };
1780
+ case "approved": {
1781
+ publishEnrollment(void 0);
1782
+ const settlement = await this.approveWithDeviceCode(
1783
+ { playerToken, transactionId: input.transactionId, flow: input.flow, deviceCode },
1784
+ { signal }
1785
+ );
1786
+ return { status: "approved", settlement, lastPoll };
1787
+ }
1788
+ }
1789
+ }
1790
+ }
1371
1791
  toInitiateResult(raw) {
1372
1792
  const vm = raw["verification_method"];
1373
1793
  const guardian = raw["guardian_approval"];