@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.cjs CHANGED
@@ -3,6 +3,8 @@
3
3
  var crypto = require('crypto');
4
4
 
5
5
  // src/shared/errors.ts
6
+ var LEGACY_NOT_PENDING_RE = /^transaction not pending\b|\bcannot be confirmed\b/i;
7
+ var LEGACY_CURRENT_STATUS_RE = /\((?:current )?status:\s*([^)]+)\)/i;
6
8
  var InvoError = class _InvoError extends Error {
7
9
  constructor(args) {
8
10
  super(args.message);
@@ -383,6 +385,91 @@ var InvoError = class _InvoError extends Error {
383
385
  get isAlreadyRefunded() {
384
386
  return this.code === "ALREADY_REFUNDED" || this.status === 409 && /already\s+refunded/i.test(this.message);
385
387
  }
388
+ /**
389
+ * True when an approve / confirm-receipt was refused because the transaction is no
390
+ * longer awaiting that step (`TRANSACTION_NOT_PENDING`, 400). `approveWithDeviceCode`
391
+ * maps this into a non-throwing `status: "not_pending"` result; you meet it as a thrown
392
+ * error only from a raw call. Usually "already done" (a repeat call with a device_code
393
+ * that was consumed the first time) — read `currentTransactionStatus`, do not retry-loop.
394
+ *
395
+ * The message fallback is for OLDER BACKEND RELEASES. The stable
396
+ * `TRANSACTION_NOT_PENDING` code was added on 2026-09-04; before that the same four
397
+ * endpoints answered `{"status":"error","message":"Transaction not pending PIN
398
+ * verification (current status: …)"}` — or, on the two receipt flows, "…cannot be
399
+ * confirmed (current status: …)" — with **no machine code at all**. An integrator
400
+ * running against an older deployment must still be able to tell "already done" from a
401
+ * real refusal without string-matching in their own code, so the string-matching lives
402
+ * here, once.
403
+ *
404
+ * That fallback is deliberately narrow, because it is guessing. It requires all three
405
+ * of: HTTP 400, one of those two phrases, AND a readable status clause. "cannot be
406
+ * confirmed" is an ordinary English phrase that some future refusal could reasonably
407
+ * use, so a phrase match ALONE must never be able to tell a caller that money moved —
408
+ * and with the clause required, `currentStatus` is always populated on this path, which
409
+ * is what actually decides `alreadySettled`.
410
+ */
411
+ get isTransactionNotPending() {
412
+ if (this.code === "TRANSACTION_NOT_PENDING") return true;
413
+ return this.status === 400 && LEGACY_NOT_PENDING_RE.test(this.message) && LEGACY_CURRENT_STATUS_RE.test(this.message);
414
+ }
415
+ /**
416
+ * The `current_status` a `TRANSACTION_NOT_PENDING` refusal reports (e.g. `pending_claim`,
417
+ * `completed`, `expired`).
418
+ *
419
+ * Falls back to the `(current status: …)` clause inside the message, which is where the
420
+ * older releases described above put it — they carried no `current_status` field.
421
+ */
422
+ get currentTransactionStatus() {
423
+ const v = this.bodyObject()["current_status"];
424
+ if (typeof v === "string" && v) return v;
425
+ const m = LEGACY_CURRENT_STATUS_RE.exec(this.message);
426
+ const parsed = m?.[1]?.trim();
427
+ return parsed ? parsed : void 0;
428
+ }
429
+ /**
430
+ * True when the approve endpoint did not accept the `device_code`
431
+ * (`DEVICE_APPROVAL_NOT_APPROVED`, 400): unknown, another player's, bound to a
432
+ * different transaction or FLOW, or not yet approved. Deliberately one answer for all
433
+ * of those (no oracle). Check the `flow` you passed matches the one you began with,
434
+ * and that the poll actually said `approved` before you called approve.
435
+ */
436
+ get isDeviceApprovalNotApproved() {
437
+ return this.code === "DEVICE_APPROVAL_NOT_APPROVED";
438
+ }
439
+ /**
440
+ * True when `beginDeviceApproval` was refused because an APPROVED grant for this
441
+ * transaction and flow is still inside its window (`DEVICE_APPROVAL_ALREADY_PENDING`,
442
+ * 409). The player already approved — you are missing the approve call, not a new
443
+ * code. If you still hold the `device_code`, call `approveWithDeviceCode`; otherwise
444
+ * `begin` works again after `deviceApprovalExpiresAt`. (A merely PENDING earlier grant
445
+ * does not 409 — `begin` supersedes it with a fresh code.)
446
+ */
447
+ get isDeviceApprovalAlreadyPending() {
448
+ return this.code === "DEVICE_APPROVAL_ALREADY_PENDING";
449
+ }
450
+ /** ISO time the blocking approved grant's window closes (`expires_at` on a `DEVICE_APPROVAL_ALREADY_PENDING` 409). */
451
+ get deviceApprovalExpiresAt() {
452
+ const v = this.bodyObject()["expires_at"];
453
+ return typeof v === "string" && v ? v : void 0;
454
+ }
455
+ /**
456
+ * True when a settle call failed on INVO's side rather than being refused by a rule
457
+ * (`SEND_APPROVE_FAILED` / `TRANSFER_APPROVE_FAILED` / `CONFIRM_RECEIPT_FAILED`, 400).
458
+ *
459
+ * A fault, never a rule and never retryable. Show a neutral failure and report
460
+ * {@link errorRef} — do not treat it as a decision about the player or the money.
461
+ */
462
+ get isSettleFault() {
463
+ return this.code === "SEND_APPROVE_FAILED" || this.code === "TRANSFER_APPROVE_FAILED" || this.code === "CONFIRM_RECEIPT_FAILED";
464
+ }
465
+ /**
466
+ * The `error_ref` a settle fault carries. It names the exact server log line, so quoting
467
+ * it to INVO support gets the cause in one message instead of a description of symptoms.
468
+ */
469
+ get errorRef() {
470
+ const v = this.bodyObject()["error_ref"];
471
+ return typeof v === "string" && v ? v : void 0;
472
+ }
386
473
  /** Seconds to wait before retrying, when the backend throttled the call (429 `retry_after`). */
387
474
  get retryAfter() {
388
475
  const v = this.bodyObject()["retry_after"];
@@ -406,7 +493,7 @@ function errorFromResponse(status, body, requestId) {
406
493
  code = typeof b["error_code_public"] === "string" ? b["error_code_public"] : rawCode;
407
494
  if (typeof b["error"] === "string") message = b["error"];
408
495
  else if (typeof b["message"] === "string") message = b["message"];
409
- if (!code && typeof b["error"] === "string" && /^(flow_paused|spending_limit_exceeded|receiver_not_enrolled_use_claim_code|no_channel_on_file|rate_limited|service_unavailable)$/.test(
496
+ if (!code && typeof b["error"] === "string" && /^(flow_paused|spending_limit_exceeded|receiver_not_enrolled_use_claim_code|no_channel_on_file|rate_limited|service_unavailable|authorization_pending|slow_down|expired_token|access_denied|invalid_grant)$/.test(
410
497
  b["error"]
411
498
  )) {
412
499
  code = b["error"];
@@ -963,6 +1050,133 @@ function toPhoneShareApproveResult(raw) {
963
1050
  raw
964
1051
  };
965
1052
  }
1053
+ var DEVICE_APPROVAL_FLOWS = /* @__PURE__ */ new Set([
1054
+ "transfer",
1055
+ "send",
1056
+ "send_receipt",
1057
+ "transfer_receipt"
1058
+ ]);
1059
+ var DEVICE_APPROVAL_CHANNELS = /* @__PURE__ */ new Set([
1060
+ "qr",
1061
+ "app_browser",
1062
+ "popup"
1063
+ ]);
1064
+ var DEVICE_POLL_OUTCOME_TOKENS = /* @__PURE__ */ new Set([
1065
+ "authorization_pending",
1066
+ "slow_down",
1067
+ "expired_token",
1068
+ "access_denied"
1069
+ ]);
1070
+ function deviceApprovalSettlePath(flow, transactionId) {
1071
+ const id = encodeURIComponent(transactionId);
1072
+ switch (flow) {
1073
+ case "transfer":
1074
+ return `/api/sdk/transfers/${id}/approve`;
1075
+ case "send":
1076
+ return `/api/sdk/send/${id}/approve`;
1077
+ case "send_receipt":
1078
+ return `/api/sdk/send/${id}/confirm-receipt`;
1079
+ case "transfer_receipt":
1080
+ return `/api/sdk/transfers/${id}/confirm-receipt`;
1081
+ }
1082
+ }
1083
+ var DEVICE_SETTLED_STATUSES = {
1084
+ // Sender's approve: anything from "approved, awaiting the claim" onwards.
1085
+ transfer: /* @__PURE__ */ new Set([
1086
+ "pending_claim",
1087
+ "verified",
1088
+ "pin_verified_awaiting_claim",
1089
+ "completed",
1090
+ "distributed"
1091
+ ]),
1092
+ send: /* @__PURE__ */ new Set([
1093
+ "pending_claim",
1094
+ "verified",
1095
+ "pin_verified_awaiting_claim",
1096
+ "completed",
1097
+ "distributed"
1098
+ ]),
1099
+ // Recipient's collect: only a finished transaction is past it. `pending_claim` and
1100
+ // `verified` are this step's own gate statuses, not states beyond it.
1101
+ send_receipt: /* @__PURE__ */ new Set(["completed", "distributed"]),
1102
+ transfer_receipt: /* @__PURE__ */ new Set(["completed", "distributed"])
1103
+ };
1104
+ function isPastThisStep(flow, currentStatus) {
1105
+ return DEVICE_SETTLED_STATUSES[flow].has(currentStatus.trim().toLowerCase());
1106
+ }
1107
+ function assertPlayerToken(playerToken) {
1108
+ if (typeof playerToken !== "string" || !playerToken.trim()) {
1109
+ throw invalidInput("playerToken", playerToken, "is required (the player's session token, not the game secret)");
1110
+ }
1111
+ }
1112
+ function assertDeviceApprovalFlow(flow) {
1113
+ if (typeof flow !== "string" || !DEVICE_APPROVAL_FLOWS.has(flow)) {
1114
+ throw invalidInput("flow", flow, 'must be "transfer" | "send" | "send_receipt" | "transfer_receipt"');
1115
+ }
1116
+ }
1117
+ function toDeviceApprovalGrant(raw) {
1118
+ return {
1119
+ deviceCode: requireField(raw["device_code"], "device_code", raw),
1120
+ userCode: String(raw["user_code"] ?? ""),
1121
+ verificationUri: String(raw["verification_uri"] ?? ""),
1122
+ verificationUriComplete: requireField(raw["verification_uri_complete"], "verification_uri_complete", raw),
1123
+ expiresIn: Number(raw["expires_in"] ?? 0) || 0,
1124
+ interval: Math.max(1, Number(raw["interval"] ?? 5) || 5),
1125
+ channel: String(raw["channel"] ?? "qr"),
1126
+ raw
1127
+ };
1128
+ }
1129
+ function toDeviceApprovalEnrollment(raw) {
1130
+ return {
1131
+ state: String(raw["state"] ?? ""),
1132
+ deviceLabel: String(raw["device_label"] ?? ""),
1133
+ matchCode: String(raw["match_code"] ?? ""),
1134
+ recovery: raw["recovery"] === true,
1135
+ requestedAt: raw["requested_at"] ?? null,
1136
+ raw
1137
+ };
1138
+ }
1139
+ function toDevicePollOutcome(token, body) {
1140
+ const interval = Number(body["interval"]);
1141
+ const enrollment = body["enrollment"];
1142
+ return {
1143
+ status: token,
1144
+ interval: Number.isFinite(interval) && interval > 0 ? interval : void 0,
1145
+ enrollment: enrollment && typeof enrollment === "object" ? toDeviceApprovalEnrollment(enrollment) : void 0,
1146
+ raw: body
1147
+ };
1148
+ }
1149
+ function toDeviceApprovalSettleResult(raw, input) {
1150
+ const holdReason = raw["error_code"] ?? raw["code"];
1151
+ return {
1152
+ status: String(raw["status"] ?? ""),
1153
+ transactionId: String(raw["transaction_id"] ?? input.transactionId),
1154
+ flow: input.flow,
1155
+ alreadySettled: false,
1156
+ next: raw["next"],
1157
+ claimCode: raw["claim_code"],
1158
+ claimCodeExpiresAt: raw["claim_code_expires_at"],
1159
+ amountReceived: raw["amount_received"] == null ? void 0 : String(raw["amount_received"]),
1160
+ holdReason: typeof holdReason === "string" ? holdReason : void 0,
1161
+ risk: raw["risk"],
1162
+ guardianApproval: raw["guardian_approval"] ?? void 0,
1163
+ pollEndpoint: raw["poll_endpoint"],
1164
+ raw
1165
+ };
1166
+ }
1167
+ function sleepFor(ms, signal) {
1168
+ return new Promise((resolve) => {
1169
+ if (signal?.aborted) return resolve();
1170
+ const timer = setTimeout(done, ms);
1171
+ const onAbort = () => done();
1172
+ function done() {
1173
+ clearTimeout(timer);
1174
+ signal?.removeEventListener("abort", onAbort);
1175
+ resolve();
1176
+ }
1177
+ signal?.addEventListener("abort", onAbort, { once: true });
1178
+ });
1179
+ }
966
1180
  function toCurrencyBalance(row) {
967
1181
  return {
968
1182
  currencyId: row["currency_id"] ?? "",
@@ -2027,6 +2241,299 @@ var InvoServer = class {
2027
2241
  );
2028
2242
  return { approved: raw["approved"] === true, raw };
2029
2243
  }
2244
+ // ---- Device approval grant (RFC 8628) — consoles, TVs, native Steam / desktop ----
2245
+ //
2246
+ // These take the PLAYER TOKEN explicitly: on a console the game server minted it and
2247
+ // holds it, and every call below authenticates with it — the game secret is never
2248
+ // sent. The grant is a FACTOR. `beginDeviceApproval` + `pollDeviceApproval` reaching
2249
+ // `approved` settles NOTHING; `approveWithDeviceCode` is the step that moves the money.
2250
+ /**
2251
+ * Stage 1 — start a device approval for ONE transaction (RFC 8628 §3.1/§3.2).
2252
+ *
2253
+ * Returns the grant: render `verificationUriComplete` as the QR (print `userCode`
2254
+ * under it for a TV with no camera), keep `deviceCode` on your server, then poll.
2255
+ * A repeat `begin` while an earlier grant is merely PENDING supersedes it (fresh code;
2256
+ * a page still open on the old one is told to scan again). A grant the player already
2257
+ * APPROVED blocks a new `begin` for its window with `409 DEVICE_APPROVAL_ALREADY_PENDING`
2258
+ * (`err.isDeviceApprovalAlreadyPending`, `err.deviceApprovalExpiresAt`) — the missing
2259
+ * step there is `approveWithDeviceCode`, not a new code.
2260
+ *
2261
+ * For `transfer` / `send` the backend also pushes the transaction's own approval
2262
+ * window past the grant's expiry, so an approval at minute nine cannot land on a
2263
+ * transfer that has already been refunded. Auth: the player token. `channel: "popup"`
2264
+ * is browser-only (`InvoClient.approveHosted`) and is refused before the network.
2265
+ */
2266
+ async beginDeviceApproval(input, opts) {
2267
+ assertPlayerToken(input.playerToken);
2268
+ if (typeof input.transactionId !== "string" || !input.transactionId.trim()) {
2269
+ throw invalidInput("transactionId", input.transactionId, "is required");
2270
+ }
2271
+ assertDeviceApprovalFlow(input.flow);
2272
+ const channel = input.channel ?? "qr";
2273
+ if (!DEVICE_APPROVAL_CHANNELS.has(channel)) {
2274
+ throw invalidInput("channel", channel, 'must be "qr" | "app_browser" ("popup" is browser-only)');
2275
+ }
2276
+ if (channel === "popup") {
2277
+ throw new InvoError({
2278
+ 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".`,
2279
+ code: "INVALID_INPUT",
2280
+ status: 0
2281
+ });
2282
+ }
2283
+ const raw = await this.http.post(
2284
+ "/api/sdk/approvals/device/begin",
2285
+ { transaction_id: input.transactionId, flow: input.flow, channel },
2286
+ { kind: "bearer", token: input.playerToken },
2287
+ // PLAYER token — never the game secret
2288
+ // Safe to retry: a lost-response retry supersedes the unseen pending grant with a
2289
+ // fresh code (one live grant per transaction + flow either way).
2290
+ { idempotent: true, signal: opts?.signal }
2291
+ );
2292
+ return toDeviceApprovalGrant(raw);
2293
+ }
2294
+ /**
2295
+ * Stage 3 — one poll (RFC 8628 §3.4/§3.5). Call it no faster than `interval` seconds.
2296
+ *
2297
+ * Returns `status`:
2298
+ * - `authorization_pending` — keep polling. While a first-time phone waits on your
2299
+ * screen, `enrollment` is present: show "Set up INVO on <deviceLabel>? Code
2300
+ * <matchCode>" and answer with `confirmDeviceEnrollment`.
2301
+ * - `slow_down` — add 5 s to your interval, then resume.
2302
+ * - `approved` — **now call `approveWithDeviceCode`**. Nothing has moved yet.
2303
+ * - `access_denied` — the player declined; do not retry silently.
2304
+ * - `expired_token` — the grant lapsed; `beginDeviceApproval` again.
2305
+ * Throws `InvoError` for `invalid_grant` (`err.code === "invalid_grant"`: unknown code,
2306
+ * or not this player's — one answer for both, deliberately) and for transport failures
2307
+ * after the retry budget (429 / 5xx are retried: this is an idempotent read).
2308
+ */
2309
+ async pollDeviceApproval(input, opts) {
2310
+ assertPlayerToken(input.playerToken);
2311
+ if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
2312
+ throw invalidInput("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
2313
+ }
2314
+ let raw;
2315
+ try {
2316
+ raw = await this.http.post(
2317
+ "/api/sdk/approvals/device/poll",
2318
+ { device_code: input.deviceCode },
2319
+ { kind: "bearer", token: input.playerToken },
2320
+ { idempotent: true, signal: opts?.signal }
2321
+ // a read; safe to retry
2322
+ );
2323
+ } catch (err) {
2324
+ if (err instanceof InvoError && err.status === 400 && typeof err.code === "string" && DEVICE_POLL_OUTCOME_TOKENS.has(err.code)) {
2325
+ const body = err.body && typeof err.body === "object" ? err.body : {};
2326
+ return toDevicePollOutcome(err.code, body);
2327
+ }
2328
+ throw err;
2329
+ }
2330
+ return {
2331
+ status: "approved",
2332
+ transactionId: raw["transaction_id"],
2333
+ flow: raw["flow"],
2334
+ approvedAt: raw["approved_at"] ?? null,
2335
+ raw
2336
+ };
2337
+ }
2338
+ /**
2339
+ * Stage 3b — answer the on-screen match-code prompt for a first-time phone.
2340
+ *
2341
+ * `approve` = "yes, the phone I just scanned with shows this code" (the phone then
2342
+ * creates its INVO passkey and approves); `deny` ends the whole grant — the next poll
2343
+ * answers `access_denied`. Answered once: `409 DEVICE_APPROVAL_ENROLLMENT_ALREADY_DECIDED`
2344
+ * means the backup email got there first — take the prompt down quietly.
2345
+ * `409 DEVICE_APPROVAL_NO_ENROLLMENT_PENDING`: no phone has asked. Not auto-retried.
2346
+ */
2347
+ async confirmDeviceEnrollment(input, opts) {
2348
+ assertPlayerToken(input.playerToken);
2349
+ if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
2350
+ throw invalidInput("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
2351
+ }
2352
+ if (input.decision !== "approve" && input.decision !== "deny") {
2353
+ throw invalidInput("decision", input.decision, 'must be "approve" or "deny"');
2354
+ }
2355
+ const raw = await this.http.post(
2356
+ "/api/sdk/approvals/device/confirm-enrollment",
2357
+ { device_code: input.deviceCode, decision: input.decision },
2358
+ { kind: "bearer", token: input.playerToken },
2359
+ { signal: opts?.signal }
2360
+ // a decision — never auto-retried
2361
+ );
2362
+ return { status: String(raw["status"] ?? ""), raw };
2363
+ }
2364
+ /**
2365
+ * Stage 4 — THE MONEY STEP. Once the poll says `approved`, call this with the same
2366
+ * player token and the grant's `deviceCode`. Routes by `flow`:
2367
+ *
2368
+ * transfer → POST /api/sdk/transfers/{id}/approve
2369
+ * send → POST /api/sdk/send/{id}/approve
2370
+ * send_receipt → POST /api/sdk/send/{id}/confirm-receipt
2371
+ * transfer_receipt → POST /api/sdk/transfers/{id}/confirm-receipt
2372
+ *
2373
+ * The grant proves WHO approved; this call runs every gate the in-app passkey approve
2374
+ * runs (guardian, risk, recovery cooldown) and moves the money. A grant that is never
2375
+ * followed by this call moves nothing, and is consumed by nothing.
2376
+ *
2377
+ * Result: `status: "approved"` + `next: "pending_claim"` (transfer/send; `claimCode`
2378
+ * on a transfer) or `status: "completed"` + `amountReceived` (receipt flows). A 202
2379
+ * hold returns `holdReason` (money held, not refused). A repeat call after the code was
2380
+ * consumed returns `status: "not_pending"` with `currentStatus` and `alreadySettled`
2381
+ * — the backend's `TRANSACTION_NOT_PENDING` mapped into a result rather than thrown,
2382
+ * because for this call it is the normal answer to "did my earlier attempt land?".
2383
+ *
2384
+ * Throws `InvoError`: `err.isDeviceApprovalNotApproved` (400 — wrong/foreign code,
2385
+ * wrong flow, or the poll never said approved), `err.isPasskeyRecoveryCooldown` (403,
2386
+ * money-out after a passkey recovery — `err.retryAfterAt`), guardian terminal states
2387
+ * (410). Never auto-retried: the device_code is a single-use factor.
2388
+ *
2389
+ * **A FAILURE HERE IS AMBIGUOUS ABOUT THE MONEY.** The backend commits the transfer and
2390
+ * *then* builds its 200 by reading the transaction back, so a fault raised after that
2391
+ * commit answers `SEND_APPROVE_FAILED` / `TRANSFER_APPROVE_FAILED` /
2392
+ * `CONFIRM_RECEIPT_FAILED` (`err.isSettleFault`, `err.errorRef`) for money that already
2393
+ * moved. A `status === 0` (timeout, connection dropped) is ambiguous for the same
2394
+ * reason, and this call is deliberately not auto-retried. So on either: read
2395
+ * `getTransferStatus` / `getSendStatus`, or wait for the `transfer.claim_pending`
2396
+ * webhook, BEFORE you tell the player it failed — and never auto-start a replacement
2397
+ * transaction.
2398
+ */
2399
+ async approveWithDeviceCode(input, opts) {
2400
+ assertPlayerToken(input.playerToken);
2401
+ if (typeof input.transactionId !== "string" || !input.transactionId.trim()) {
2402
+ throw invalidInput("transactionId", input.transactionId, "is required");
2403
+ }
2404
+ assertDeviceApprovalFlow(input.flow);
2405
+ if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
2406
+ throw invalidInput("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
2407
+ }
2408
+ let raw;
2409
+ try {
2410
+ raw = await this.http.post(
2411
+ deviceApprovalSettlePath(input.flow, input.transactionId),
2412
+ { device_code: input.deviceCode },
2413
+ { kind: "bearer", token: input.playerToken },
2414
+ // PLAYER token — never the game secret
2415
+ { signal: opts?.signal }
2416
+ // NOT idempotent — the device_code is single-use; never auto-retried
2417
+ );
2418
+ } catch (err) {
2419
+ if (err instanceof InvoError && err.isTransactionNotPending) {
2420
+ const body = err.body && typeof err.body === "object" ? err.body : {};
2421
+ const currentStatus = err.currentTransactionStatus ?? "";
2422
+ return {
2423
+ status: "not_pending",
2424
+ transactionId: input.transactionId,
2425
+ flow: input.flow,
2426
+ alreadySettled: currentStatus !== "" && isPastThisStep(input.flow, currentStatus),
2427
+ currentStatus: currentStatus || void 0,
2428
+ raw: body
2429
+ };
2430
+ }
2431
+ throw err;
2432
+ }
2433
+ return toDeviceApprovalSettleResult(raw, input);
2434
+ }
2435
+ /**
2436
+ * Convenience only — stages 3 and 4 in one call, for a server that can hold the loop
2437
+ * open (a per-request worker, a job). Polls `pollDeviceApproval` on `interval`, adds
2438
+ * 5 s on `slow_down`, forwards the poll's `enrollment` to `onEnrollment` (answer with
2439
+ * `respond`), and on `approved` calls `approveWithDeviceCode` — THEN resolves.
2440
+ * `respond` is best-effort: a prompt the grant has outlived (`expired_token`,
2441
+ * `invalid_grant`) or that was already answered elsewhere resolves quietly rather than
2442
+ * rejecting, because callers fire it from UI code without awaiting it.
2443
+ * You still call `beginDeviceApproval` yourself first, because your game has to draw
2444
+ * the QR between begin and the first poll.
2445
+ *
2446
+ * Resolves `{ status: "approved", settlement }` | `denied` | `expired` | `aborted`.
2447
+ * Rejects on `invalid_grant`, on a refused approve (e.g. `PASSKEY_RECOVERY_COOLDOWN`),
2448
+ * and after 5 consecutive transport failures on the poll.
2449
+ *
2450
+ * **Record the attempt in your own store BEFORE you call this.** It blocks for as long
2451
+ * as the player takes and then moves money from inside the loop, so if your process
2452
+ * dies between the approve call and its response, a row you wrote first — plus
2453
+ * `getTransferStatus` / `getSendStatus` — is the only way to learn whether the money
2454
+ * moved. Servers that must not block a request use the three calls directly and keep
2455
+ * `deviceCode` in their own store.
2456
+ *
2457
+ * `respond` (handed to `onEnrollment`) is best-effort: a prompt the grant has outlived
2458
+ * resolves quietly rather than rejecting. Any other confirm-enrollment refusal
2459
+ * propagates, so `await` it if you want to see one.
2460
+ */
2461
+ async completeDeviceApproval(input, opts) {
2462
+ assertPlayerToken(input.playerToken);
2463
+ if (typeof input.transactionId !== "string" || !input.transactionId.trim()) {
2464
+ throw invalidInput("transactionId", input.transactionId, "is required");
2465
+ }
2466
+ assertDeviceApprovalFlow(input.flow);
2467
+ if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
2468
+ throw invalidInput("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
2469
+ }
2470
+ const signal = input.signal ?? opts?.signal;
2471
+ const { playerToken, deviceCode } = input;
2472
+ let interval = Math.max(1, Number(input.interval) || 5);
2473
+ let lastPoll;
2474
+ let lastEnrollmentKey = null;
2475
+ let transientFailures = 0;
2476
+ const MAX_TRANSIENT = 5;
2477
+ const respond = async (decision) => {
2478
+ try {
2479
+ await this.confirmDeviceEnrollment({ playerToken, deviceCode, decision }, { signal });
2480
+ } catch (err) {
2481
+ 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")) {
2482
+ return;
2483
+ }
2484
+ throw err;
2485
+ }
2486
+ };
2487
+ const publishEnrollment = (e) => {
2488
+ if (!input.onEnrollment) return;
2489
+ const key = e ? `${e.state}|${e.matchCode}|${e.deviceLabel}|${e.recovery}` : null;
2490
+ if (key === lastEnrollmentKey) return;
2491
+ lastEnrollmentKey = key;
2492
+ input.onEnrollment(e ?? null, respond);
2493
+ };
2494
+ for (; ; ) {
2495
+ await sleepFor(interval * 1e3, signal);
2496
+ if (signal?.aborted) return { status: "aborted", lastPoll };
2497
+ let poll;
2498
+ try {
2499
+ poll = await this.pollDeviceApproval({ playerToken, deviceCode }, { signal });
2500
+ } catch (err) {
2501
+ if (signal?.aborted) return { status: "aborted", lastPoll };
2502
+ const transient = err instanceof InvoError && (err.status === 0 || err.status === 429 || err.status >= 500);
2503
+ if (transient && ++transientFailures < MAX_TRANSIENT) {
2504
+ const ra = err instanceof InvoError && err.status === 429 ? err.retryAfter : void 0;
2505
+ if (typeof ra === "number" && ra > interval) interval = ra;
2506
+ continue;
2507
+ }
2508
+ throw err;
2509
+ }
2510
+ transientFailures = 0;
2511
+ lastPoll = poll;
2512
+ switch (poll.status) {
2513
+ case "authorization_pending":
2514
+ if (poll.interval) interval = poll.interval;
2515
+ publishEnrollment(poll.enrollment);
2516
+ continue;
2517
+ case "slow_down":
2518
+ interval = Math.max(interval + 5, poll.interval ?? 0);
2519
+ continue;
2520
+ case "expired_token":
2521
+ publishEnrollment(void 0);
2522
+ return { status: "expired", lastPoll };
2523
+ case "access_denied":
2524
+ publishEnrollment(void 0);
2525
+ return { status: "denied", lastPoll };
2526
+ case "approved": {
2527
+ publishEnrollment(void 0);
2528
+ const settlement = await this.approveWithDeviceCode(
2529
+ { playerToken, transactionId: input.transactionId, flow: input.flow, deviceCode },
2530
+ { signal }
2531
+ );
2532
+ return { status: "approved", settlement, lastPoll };
2533
+ }
2534
+ }
2535
+ }
2536
+ }
2030
2537
  toInitiateResult(raw) {
2031
2538
  const vm = raw["verification_method"];
2032
2539
  const guardian = raw["guardian_approval"];