@invonetwork/web-sdk 3.6.0 → 3.8.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/CHANGELOG.md +119 -0
- package/README.md +711 -62
- package/dist/{chunk-MBKE6ULW.js → chunk-HYGBTUEJ.js} +193 -6
- package/dist/index.cjs +191 -4
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/server.cjs +1472 -5
- package/dist/server.d.cts +606 -3
- package/dist/server.d.ts +606 -3
- package/dist/server.js +1278 -4
- package/dist/{types-ZNoG09S5.d.cts → types-DqRuqbqI.d.cts} +857 -11
- package/dist/{types-ZNoG09S5.d.ts → types-DqRuqbqI.d.ts} +857 -11
- package/package.json +1 -1
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);
|
|
@@ -346,6 +348,7 @@ var InvoError = class _InvoError extends Error {
|
|
|
346
348
|
* instead of the backend's vocabulary. Only `Init` (and an absent status)
|
|
347
349
|
* can mean "not yet"; every named status that is not Init is an outcome. */
|
|
348
350
|
get isSteamAuthorizationPending() {
|
|
351
|
+
if (this.code === "STEAM_AUTHORIZATION_PENDING") return true;
|
|
349
352
|
const b = this.body;
|
|
350
353
|
if (!b || b["status"] !== "not_authorized") return false;
|
|
351
354
|
const st = String(b["steam_status"] ?? "").toLowerCase();
|
|
@@ -383,6 +386,187 @@ var InvoError = class _InvoError extends Error {
|
|
|
383
386
|
get isAlreadyRefunded() {
|
|
384
387
|
return this.code === "ALREADY_REFUNDED" || this.status === 409 && /already\s+refunded/i.test(this.message);
|
|
385
388
|
}
|
|
389
|
+
/**
|
|
390
|
+
* True when an approve / confirm-receipt was refused because the transaction is no
|
|
391
|
+
* longer awaiting that step (`TRANSACTION_NOT_PENDING`, 400). `approveWithDeviceCode`
|
|
392
|
+
* maps this into a non-throwing `status: "not_pending"` result; you meet it as a thrown
|
|
393
|
+
* error only from a raw call. Usually "already done" (a repeat call with a device_code
|
|
394
|
+
* that was consumed the first time) — read `currentTransactionStatus`, do not retry-loop.
|
|
395
|
+
*
|
|
396
|
+
* The message fallback is for OLDER BACKEND RELEASES. The stable
|
|
397
|
+
* `TRANSACTION_NOT_PENDING` code was added on 2026-09-04; before that the same four
|
|
398
|
+
* endpoints answered `{"status":"error","message":"Transaction not pending PIN
|
|
399
|
+
* verification (current status: …)"}` — or, on the two receipt flows, "…cannot be
|
|
400
|
+
* confirmed (current status: …)" — with **no machine code at all**. An integrator
|
|
401
|
+
* running against an older deployment must still be able to tell "already done" from a
|
|
402
|
+
* real refusal without string-matching in their own code, so the string-matching lives
|
|
403
|
+
* here, once.
|
|
404
|
+
*
|
|
405
|
+
* That fallback is deliberately narrow, because it is guessing. It requires all three
|
|
406
|
+
* of: HTTP 400, one of those two phrases, AND a readable status clause. "cannot be
|
|
407
|
+
* confirmed" is an ordinary English phrase that some future refusal could reasonably
|
|
408
|
+
* use, so a phrase match ALONE must never be able to tell a caller that money moved —
|
|
409
|
+
* and with the clause required, `currentStatus` is always populated on this path, which
|
|
410
|
+
* is what actually decides `alreadySettled`.
|
|
411
|
+
*/
|
|
412
|
+
get isTransactionNotPending() {
|
|
413
|
+
if (this.code === "TRANSACTION_NOT_PENDING") return true;
|
|
414
|
+
return this.status === 400 && LEGACY_NOT_PENDING_RE.test(this.message) && LEGACY_CURRENT_STATUS_RE.test(this.message);
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* The `current_status` a `TRANSACTION_NOT_PENDING` refusal reports (e.g. `pending_claim`,
|
|
418
|
+
* `completed`, `expired`).
|
|
419
|
+
*
|
|
420
|
+
* Falls back to the `(current status: …)` clause inside the message, which is where the
|
|
421
|
+
* older releases described above put it — they carried no `current_status` field.
|
|
422
|
+
*/
|
|
423
|
+
get currentTransactionStatus() {
|
|
424
|
+
const v = this.bodyObject()["current_status"];
|
|
425
|
+
if (typeof v === "string" && v) return v;
|
|
426
|
+
const m = LEGACY_CURRENT_STATUS_RE.exec(this.message);
|
|
427
|
+
const parsed = m?.[1]?.trim();
|
|
428
|
+
return parsed ? parsed : void 0;
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* True when the approve endpoint did not accept the `device_code`
|
|
432
|
+
* (`DEVICE_APPROVAL_NOT_APPROVED`, 400): unknown, another player's, bound to a
|
|
433
|
+
* different transaction or FLOW, or not yet approved. Deliberately one answer for all
|
|
434
|
+
* of those (no oracle). Check the `flow` you passed matches the one you began with,
|
|
435
|
+
* and that the poll actually said `approved` before you called approve.
|
|
436
|
+
*/
|
|
437
|
+
get isDeviceApprovalNotApproved() {
|
|
438
|
+
return this.code === "DEVICE_APPROVAL_NOT_APPROVED";
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* True when `beginDeviceApproval` was refused because an APPROVED grant for this
|
|
442
|
+
* transaction and flow is still inside its window (`DEVICE_APPROVAL_ALREADY_PENDING`,
|
|
443
|
+
* 409). The player already approved — you are missing the approve call, not a new
|
|
444
|
+
* code. If you still hold the `device_code`, call `approveWithDeviceCode`; otherwise
|
|
445
|
+
* `begin` works again after `deviceApprovalExpiresAt`. (A merely PENDING earlier grant
|
|
446
|
+
* does not 409 — `begin` supersedes it with a fresh code.)
|
|
447
|
+
*/
|
|
448
|
+
get isDeviceApprovalAlreadyPending() {
|
|
449
|
+
return this.code === "DEVICE_APPROVAL_ALREADY_PENDING";
|
|
450
|
+
}
|
|
451
|
+
/** ISO time the blocking approved grant's window closes (`expires_at` on a `DEVICE_APPROVAL_ALREADY_PENDING` 409). */
|
|
452
|
+
get deviceApprovalExpiresAt() {
|
|
453
|
+
const v = this.bodyObject()["expires_at"];
|
|
454
|
+
return typeof v === "string" && v ? v : void 0;
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* True when a settle call failed on INVO's side rather than being refused by a rule
|
|
458
|
+
* (`SEND_APPROVE_FAILED` / `TRANSFER_APPROVE_FAILED` / `CONFIRM_RECEIPT_FAILED`, 400).
|
|
459
|
+
*
|
|
460
|
+
* A fault, never a rule and never retryable. Show a neutral failure and report
|
|
461
|
+
* {@link errorRef} — do not treat it as a decision about the player or the money.
|
|
462
|
+
*/
|
|
463
|
+
get isSettleFault() {
|
|
464
|
+
return this.code === "SEND_APPROVE_FAILED" || this.code === "TRANSFER_APPROVE_FAILED" || this.code === "CONFIRM_RECEIPT_FAILED";
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* The `error_ref` a settle fault carries. It names the exact server log line, so quoting
|
|
468
|
+
* it to INVO support gets the cause in one message instead of a description of symptoms.
|
|
469
|
+
*/
|
|
470
|
+
get errorRef() {
|
|
471
|
+
const v = this.bodyObject()["error_ref"];
|
|
472
|
+
return typeof v === "string" && v ? v : void 0;
|
|
473
|
+
}
|
|
474
|
+
// ---- Subscriptions ----
|
|
475
|
+
/**
|
|
476
|
+
* True when a create (`subscriptions.create` / `steamInit`) was refused because the
|
|
477
|
+
* player already has a LIVE subscription to this `itemId` (`ACTIVE_SUBSCRIPTION_EXISTS`,
|
|
478
|
+
* 409). Use `existingSubscriptionId`. This is what you hit if you regenerate
|
|
479
|
+
* `clientRequestId` inside a retry loop: replay the same key instead.
|
|
480
|
+
*/
|
|
481
|
+
get isActiveSubscriptionExists() {
|
|
482
|
+
return this.code === "ACTIVE_SUBSCRIPTION_EXISTS";
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* The `subscription_id` a create refusal names: the LIVE subscription on
|
|
486
|
+
* `ACTIVE_SUBSCRIPTION_EXISTS`, the PENDING Steam row on `STEAM_AUTHORIZATION_PENDING`,
|
|
487
|
+
* or the abandoned (now `expired`) row when a Steam-side failure abandoned it after creation.
|
|
488
|
+
*/
|
|
489
|
+
get existingSubscriptionId() {
|
|
490
|
+
const v = this.bodyObject()["subscription_id"];
|
|
491
|
+
return typeof v === "string" && v ? v : void 0;
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* True when the same `clientRequestId` was replayed for the same player and item but
|
|
495
|
+
* with DIFFERENT material terms (`IDEMPOTENT_REPLAY_MISMATCH`, 409). See
|
|
496
|
+
* `mismatchedFields` (any of `amount_usd`, `interval`, `interval_count`, `wallet_only`,
|
|
497
|
+
* `funding_rail`). To change terms use `changeAmount` / `setPaymentMethod`; to create a
|
|
498
|
+
* new subscription use a new key.
|
|
499
|
+
*/
|
|
500
|
+
get isIdempotentReplayMismatch() {
|
|
501
|
+
return this.code === "IDEMPOTENT_REPLAY_MISMATCH";
|
|
502
|
+
}
|
|
503
|
+
/** The `mismatched_fields` on an `IDEMPOTENT_REPLAY_MISMATCH` 409. */
|
|
504
|
+
get mismatchedFields() {
|
|
505
|
+
const v = this.bodyObject()["mismatched_fields"];
|
|
506
|
+
return Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* True when `changeAmount` tried to RAISE the price of a Steam subscription
|
|
510
|
+
* (`STEAM_REAUTHORIZATION_REQUIRED`, 409). The member consented to a ceiling; start a
|
|
511
|
+
* new Steam subscription at the new price and cancel this one. Decreases stage normally.
|
|
512
|
+
* The body carries `current_amount_usd` and `requested_amount_usd`.
|
|
513
|
+
*/
|
|
514
|
+
get isSteamReauthorizationRequired() {
|
|
515
|
+
return this.code === "STEAM_REAUTHORIZATION_REQUIRED";
|
|
516
|
+
}
|
|
517
|
+
/** True when `setPaymentMethod` was called on a Steam subscription (`NOT_A_CARD_SUBSCRIPTION`, 409). A rail is fixed at creation. */
|
|
518
|
+
get isNotACardSubscription() {
|
|
519
|
+
return this.code === "NOT_A_CARD_SUBSCRIPTION";
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* True when a Steam subscription was started with a key for a non-Steam channel
|
|
523
|
+
* (`STEAM_CHANNEL_REQUIRED`, 409). Use the primary game key or the `steam` channel key.
|
|
524
|
+
*/
|
|
525
|
+
get isSteamChannelRequired() {
|
|
526
|
+
return this.code === "STEAM_CHANNEL_REQUIRED";
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* True when `subscriptions.refund` targeted a period that was charged through Steam
|
|
530
|
+
* (`STEAM_REFUND_NOT_SUPPORTED`, 409). Refunds of Steam-charged periods are not
|
|
531
|
+
* supported yet; periods of a Steam subscription that the wallet covered entirely
|
|
532
|
+
* remain refundable in coins.
|
|
533
|
+
*/
|
|
534
|
+
get isSteamRefundNotSupported() {
|
|
535
|
+
return this.code === "STEAM_REFUND_NOT_SUPPORTED";
|
|
536
|
+
}
|
|
537
|
+
/** True when the subscription is `canceled` or `expired` and the call cannot apply (`SUBSCRIPTION_TERMINAL`, 409). Start a new one. */
|
|
538
|
+
get isSubscriptionTerminal() {
|
|
539
|
+
return this.code === "SUBSCRIPTION_TERMINAL";
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* True when `subscriptions.steamFinalize` was called before the member completed the
|
|
543
|
+
* Steam authorisation (409, body `status: "not_authorized"`, with `steam_status`).
|
|
544
|
+
* THE NORMAL WAIT STATE: call finalize again after the overlay or checkout closes.
|
|
545
|
+
* The member has 24 hours; after that the row expires.
|
|
546
|
+
*/
|
|
547
|
+
get isNotAuthorized() {
|
|
548
|
+
return this.bodyObject()["status"] === "not_authorized";
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* True when a sandbox clock call was refused for a missing, wrong or never-issued
|
|
552
|
+
* `X-Sandbox-Clock-Key` (`SANDBOX_CLOCK_UNAUTHORIZED`, 401). Reveal or rotate the key on
|
|
553
|
+
* the game's Game Settings page in the sandbox console.
|
|
554
|
+
*/
|
|
555
|
+
get isSandboxClockUnauthorized() {
|
|
556
|
+
return this.code === "SANDBOX_CLOCK_UNAUTHORIZED";
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* True when INVO has paused this flow for maintenance (503): `flow_paused` on create /
|
|
560
|
+
* amount / payment-method / Steam init / card setup, `FLOW_PAUSED` on refund and the
|
|
561
|
+
* sandbox clock. Retry later WITH THE SAME idempotency key.
|
|
562
|
+
*/
|
|
563
|
+
get isFlowPaused() {
|
|
564
|
+
return this.code === "flow_paused" || this.code === "FLOW_PAUSED";
|
|
565
|
+
}
|
|
566
|
+
/** True when a create was refused because the game is not `live` (`GAME_NOT_LIVE`, 403). Make it live in the console. */
|
|
567
|
+
get isGameNotLive() {
|
|
568
|
+
return this.code === "GAME_NOT_LIVE";
|
|
569
|
+
}
|
|
386
570
|
/** Seconds to wait before retrying, when the backend throttled the call (429 `retry_after`). */
|
|
387
571
|
get retryAfter() {
|
|
388
572
|
const v = this.bodyObject()["retry_after"];
|
|
@@ -406,7 +590,7 @@ function errorFromResponse(status, body, requestId) {
|
|
|
406
590
|
code = typeof b["error_code_public"] === "string" ? b["error_code_public"] : rawCode;
|
|
407
591
|
if (typeof b["error"] === "string") message = b["error"];
|
|
408
592
|
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(
|
|
593
|
+
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
594
|
b["error"]
|
|
411
595
|
)) {
|
|
412
596
|
code = b["error"];
|
|
@@ -456,11 +640,11 @@ var _Http = class _Http {
|
|
|
456
640
|
* (e.g. single-use WebAuthn assertions) are NEVER auto-retried.
|
|
457
641
|
*/
|
|
458
642
|
async post(path, body, auth, opts) {
|
|
459
|
-
return this.request("POST", path, body, auth, opts?.idempotent ?? false, opts?.signal);
|
|
643
|
+
return this.request("POST", path, body, auth, opts?.idempotent ?? false, opts?.signal, opts?.headers);
|
|
460
644
|
}
|
|
461
645
|
// GET is always idempotent → safe to retry.
|
|
462
646
|
async get(path, auth, opts) {
|
|
463
|
-
return this.request("GET", path, void 0, auth, true, opts?.signal);
|
|
647
|
+
return this.request("GET", path, void 0, auth, true, opts?.signal, opts?.headers);
|
|
464
648
|
}
|
|
465
649
|
authHeaders(auth) {
|
|
466
650
|
switch (auth.kind) {
|
|
@@ -472,10 +656,13 @@ var _Http = class _Http {
|
|
|
472
656
|
return {};
|
|
473
657
|
}
|
|
474
658
|
}
|
|
475
|
-
async request(method, path, body, auth, idempotent, signal) {
|
|
659
|
+
async request(method, path, body, auth, idempotent, signal, extraHeaders) {
|
|
476
660
|
const url = `${this.baseUrl}${path}`;
|
|
477
661
|
const headers = {
|
|
478
662
|
Accept: "application/json",
|
|
663
|
+
...this.authHeaders(auth),
|
|
664
|
+
// Per-call extras (e.g. the sandbox clock key) — never able to override the auth header.
|
|
665
|
+
...extraHeaders ?? {},
|
|
479
666
|
...this.authHeaders(auth)
|
|
480
667
|
};
|
|
481
668
|
if (this.userAgent) headers["User-Agent"] = this.userAgent;
|
|
@@ -661,6 +848,9 @@ function toDestinationsResult(raw, direction) {
|
|
|
661
848
|
raw
|
|
662
849
|
};
|
|
663
850
|
}
|
|
851
|
+
|
|
852
|
+
// src/version.ts
|
|
853
|
+
var SDK_VERSION = "3.8.0";
|
|
664
854
|
var DEFAULT_TOLERANCE_SEC = 300;
|
|
665
855
|
var ENCODER = new TextEncoder();
|
|
666
856
|
function toBytes(body) {
|
|
@@ -826,7 +1016,7 @@ async function hmacHexSubtle(secret, message) {
|
|
|
826
1016
|
}
|
|
827
1017
|
|
|
828
1018
|
// src/server.ts
|
|
829
|
-
var DEFAULT_UA =
|
|
1019
|
+
var DEFAULT_UA = `invonetwork-web-sdk/${SDK_VERSION} (+https://invo.network)`;
|
|
830
1020
|
var MAX_USD_AMOUNT = 999.99;
|
|
831
1021
|
var MAX_ITEM_PRICE = 999999.99;
|
|
832
1022
|
function invalidInput(label, value, why) {
|
|
@@ -963,6 +1153,133 @@ function toPhoneShareApproveResult(raw) {
|
|
|
963
1153
|
raw
|
|
964
1154
|
};
|
|
965
1155
|
}
|
|
1156
|
+
var DEVICE_APPROVAL_FLOWS = /* @__PURE__ */ new Set([
|
|
1157
|
+
"transfer",
|
|
1158
|
+
"send",
|
|
1159
|
+
"send_receipt",
|
|
1160
|
+
"transfer_receipt"
|
|
1161
|
+
]);
|
|
1162
|
+
var DEVICE_APPROVAL_CHANNELS = /* @__PURE__ */ new Set([
|
|
1163
|
+
"qr",
|
|
1164
|
+
"app_browser",
|
|
1165
|
+
"popup"
|
|
1166
|
+
]);
|
|
1167
|
+
var DEVICE_POLL_OUTCOME_TOKENS = /* @__PURE__ */ new Set([
|
|
1168
|
+
"authorization_pending",
|
|
1169
|
+
"slow_down",
|
|
1170
|
+
"expired_token",
|
|
1171
|
+
"access_denied"
|
|
1172
|
+
]);
|
|
1173
|
+
function deviceApprovalSettlePath(flow, transactionId) {
|
|
1174
|
+
const id = encodeURIComponent(transactionId);
|
|
1175
|
+
switch (flow) {
|
|
1176
|
+
case "transfer":
|
|
1177
|
+
return `/api/sdk/transfers/${id}/approve`;
|
|
1178
|
+
case "send":
|
|
1179
|
+
return `/api/sdk/send/${id}/approve`;
|
|
1180
|
+
case "send_receipt":
|
|
1181
|
+
return `/api/sdk/send/${id}/confirm-receipt`;
|
|
1182
|
+
case "transfer_receipt":
|
|
1183
|
+
return `/api/sdk/transfers/${id}/confirm-receipt`;
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
var DEVICE_SETTLED_STATUSES = {
|
|
1187
|
+
// Sender's approve: anything from "approved, awaiting the claim" onwards.
|
|
1188
|
+
transfer: /* @__PURE__ */ new Set([
|
|
1189
|
+
"pending_claim",
|
|
1190
|
+
"verified",
|
|
1191
|
+
"pin_verified_awaiting_claim",
|
|
1192
|
+
"completed",
|
|
1193
|
+
"distributed"
|
|
1194
|
+
]),
|
|
1195
|
+
send: /* @__PURE__ */ new Set([
|
|
1196
|
+
"pending_claim",
|
|
1197
|
+
"verified",
|
|
1198
|
+
"pin_verified_awaiting_claim",
|
|
1199
|
+
"completed",
|
|
1200
|
+
"distributed"
|
|
1201
|
+
]),
|
|
1202
|
+
// Recipient's collect: only a finished transaction is past it. `pending_claim` and
|
|
1203
|
+
// `verified` are this step's own gate statuses, not states beyond it.
|
|
1204
|
+
send_receipt: /* @__PURE__ */ new Set(["completed", "distributed"]),
|
|
1205
|
+
transfer_receipt: /* @__PURE__ */ new Set(["completed", "distributed"])
|
|
1206
|
+
};
|
|
1207
|
+
function isPastThisStep(flow, currentStatus) {
|
|
1208
|
+
return DEVICE_SETTLED_STATUSES[flow].has(currentStatus.trim().toLowerCase());
|
|
1209
|
+
}
|
|
1210
|
+
function assertPlayerToken(playerToken) {
|
|
1211
|
+
if (typeof playerToken !== "string" || !playerToken.trim()) {
|
|
1212
|
+
throw invalidInput("playerToken", playerToken, "is required (the player's session token, not the game secret)");
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
function assertDeviceApprovalFlow(flow) {
|
|
1216
|
+
if (typeof flow !== "string" || !DEVICE_APPROVAL_FLOWS.has(flow)) {
|
|
1217
|
+
throw invalidInput("flow", flow, 'must be "transfer" | "send" | "send_receipt" | "transfer_receipt"');
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
function toDeviceApprovalGrant(raw) {
|
|
1221
|
+
return {
|
|
1222
|
+
deviceCode: requireField(raw["device_code"], "device_code", raw),
|
|
1223
|
+
userCode: String(raw["user_code"] ?? ""),
|
|
1224
|
+
verificationUri: String(raw["verification_uri"] ?? ""),
|
|
1225
|
+
verificationUriComplete: requireField(raw["verification_uri_complete"], "verification_uri_complete", raw),
|
|
1226
|
+
expiresIn: Number(raw["expires_in"] ?? 0) || 0,
|
|
1227
|
+
interval: Math.max(1, Number(raw["interval"] ?? 5) || 5),
|
|
1228
|
+
channel: String(raw["channel"] ?? "qr"),
|
|
1229
|
+
raw
|
|
1230
|
+
};
|
|
1231
|
+
}
|
|
1232
|
+
function toDeviceApprovalEnrollment(raw) {
|
|
1233
|
+
return {
|
|
1234
|
+
state: String(raw["state"] ?? ""),
|
|
1235
|
+
deviceLabel: String(raw["device_label"] ?? ""),
|
|
1236
|
+
matchCode: String(raw["match_code"] ?? ""),
|
|
1237
|
+
recovery: raw["recovery"] === true,
|
|
1238
|
+
requestedAt: raw["requested_at"] ?? null,
|
|
1239
|
+
raw
|
|
1240
|
+
};
|
|
1241
|
+
}
|
|
1242
|
+
function toDevicePollOutcome(token, body) {
|
|
1243
|
+
const interval = Number(body["interval"]);
|
|
1244
|
+
const enrollment = body["enrollment"];
|
|
1245
|
+
return {
|
|
1246
|
+
status: token,
|
|
1247
|
+
interval: Number.isFinite(interval) && interval > 0 ? interval : void 0,
|
|
1248
|
+
enrollment: enrollment && typeof enrollment === "object" ? toDeviceApprovalEnrollment(enrollment) : void 0,
|
|
1249
|
+
raw: body
|
|
1250
|
+
};
|
|
1251
|
+
}
|
|
1252
|
+
function toDeviceApprovalSettleResult(raw, input) {
|
|
1253
|
+
const holdReason = raw["error_code"] ?? raw["code"];
|
|
1254
|
+
return {
|
|
1255
|
+
status: String(raw["status"] ?? ""),
|
|
1256
|
+
transactionId: String(raw["transaction_id"] ?? input.transactionId),
|
|
1257
|
+
flow: input.flow,
|
|
1258
|
+
alreadySettled: false,
|
|
1259
|
+
next: raw["next"],
|
|
1260
|
+
claimCode: raw["claim_code"],
|
|
1261
|
+
claimCodeExpiresAt: raw["claim_code_expires_at"],
|
|
1262
|
+
amountReceived: raw["amount_received"] == null ? void 0 : String(raw["amount_received"]),
|
|
1263
|
+
holdReason: typeof holdReason === "string" ? holdReason : void 0,
|
|
1264
|
+
risk: raw["risk"],
|
|
1265
|
+
guardianApproval: raw["guardian_approval"] ?? void 0,
|
|
1266
|
+
pollEndpoint: raw["poll_endpoint"],
|
|
1267
|
+
raw
|
|
1268
|
+
};
|
|
1269
|
+
}
|
|
1270
|
+
function sleepFor(ms, signal) {
|
|
1271
|
+
return new Promise((resolve) => {
|
|
1272
|
+
if (signal?.aborted) return resolve();
|
|
1273
|
+
const timer = setTimeout(done, ms);
|
|
1274
|
+
const onAbort = () => done();
|
|
1275
|
+
function done() {
|
|
1276
|
+
clearTimeout(timer);
|
|
1277
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1278
|
+
resolve();
|
|
1279
|
+
}
|
|
1280
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1281
|
+
});
|
|
1282
|
+
}
|
|
966
1283
|
function toCurrencyBalance(row) {
|
|
967
1284
|
return {
|
|
968
1285
|
currencyId: row["currency_id"] ?? "",
|
|
@@ -1179,6 +1496,855 @@ var PlatformCommerceServer = class {
|
|
|
1179
1496
|
};
|
|
1180
1497
|
}
|
|
1181
1498
|
};
|
|
1499
|
+
var SUBSCRIPTION_MAX_USD = 999999.99;
|
|
1500
|
+
var SUBSCRIPTION_INTERVALS = /* @__PURE__ */ new Set(["month", "year"]);
|
|
1501
|
+
var SANDBOX_FAILURE_OUTCOMES = /* @__PURE__ */ new Set([
|
|
1502
|
+
"card_declined",
|
|
1503
|
+
"insufficient_funds",
|
|
1504
|
+
"error"
|
|
1505
|
+
]);
|
|
1506
|
+
function assertClientRequestId(value, label) {
|
|
1507
|
+
if (typeof value !== "string" || !value.trim()) throw invalidInput(label, value, "is required");
|
|
1508
|
+
if (value.length > 255) throw invalidInput(label, value, "must be at most 255 characters");
|
|
1509
|
+
if (/^sub_/i.test(value)) throw invalidInput(label, value, 'must not begin with "sub_" (reserved)');
|
|
1510
|
+
}
|
|
1511
|
+
function assertSubscriptionId(value) {
|
|
1512
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
1513
|
+
throw invalidInput("subscriptionId", value, "is required");
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
function subscriptionMoney(value, label) {
|
|
1517
|
+
const n = parseMoney(value, SUBSCRIPTION_MAX_USD, label);
|
|
1518
|
+
return typeof value === "number" ? n.toFixed(2) : value;
|
|
1519
|
+
}
|
|
1520
|
+
function toSavedCard(row) {
|
|
1521
|
+
if (!row || typeof row !== "object") return null;
|
|
1522
|
+
const r = row;
|
|
1523
|
+
return {
|
|
1524
|
+
id: Number(r["id"]),
|
|
1525
|
+
lastFour: String(r["last_four"] ?? ""),
|
|
1526
|
+
brand: String(r["brand"] ?? ""),
|
|
1527
|
+
expMonth: Number(r["exp_month"] ?? 0),
|
|
1528
|
+
expYear: Number(r["exp_year"] ?? 0),
|
|
1529
|
+
createdAt: String(r["created_at"] ?? ""),
|
|
1530
|
+
raw: r
|
|
1531
|
+
};
|
|
1532
|
+
}
|
|
1533
|
+
function nullableString(v) {
|
|
1534
|
+
return v == null ? null : String(v);
|
|
1535
|
+
}
|
|
1536
|
+
function toSubscription(row) {
|
|
1537
|
+
const r = row && typeof row === "object" ? row : {};
|
|
1538
|
+
const share = r["revenue_share"];
|
|
1539
|
+
const consent = r["consent"] ?? {};
|
|
1540
|
+
return {
|
|
1541
|
+
subscriptionId: String(r["subscription_id"] ?? ""),
|
|
1542
|
+
gameId: String(r["game_id"] ?? ""),
|
|
1543
|
+
playerId: Number(r["player_id"] ?? 0),
|
|
1544
|
+
clientRequestId: String(r["client_request_id"] ?? ""),
|
|
1545
|
+
status: String(r["status"] ?? ""),
|
|
1546
|
+
amountUsd: String(r["amount_usd"] ?? ""),
|
|
1547
|
+
pendingAmountUsd: nullableString(r["pending_amount_usd"]),
|
|
1548
|
+
interval: String(r["interval"] ?? "month"),
|
|
1549
|
+
intervalCount: Number(r["interval_count"] ?? 1),
|
|
1550
|
+
itemId: String(r["item_id"] ?? ""),
|
|
1551
|
+
itemName: nullableString(r["item_name"]),
|
|
1552
|
+
currentPeriodStart: String(r["current_period_start"] ?? ""),
|
|
1553
|
+
currentPeriodEnd: String(r["current_period_end"] ?? ""),
|
|
1554
|
+
periodSeq: Number(r["period_seq"] ?? 0),
|
|
1555
|
+
nextChargeAt: nullableString(r["next_charge_at"]),
|
|
1556
|
+
cancelAtPeriodEnd: r["cancel_at_period_end"] === true,
|
|
1557
|
+
trialEnd: nullableString(r["trial_end"]),
|
|
1558
|
+
canceledAt: nullableString(r["canceled_at"]),
|
|
1559
|
+
endedAt: nullableString(r["ended_at"]),
|
|
1560
|
+
walletOnly: r["wallet_only"] === true,
|
|
1561
|
+
hasPaymentMethod: r["has_payment_method"] === true,
|
|
1562
|
+
fundingRail: String(r["funding_rail"] ?? "card"),
|
|
1563
|
+
steamAgreementStatus: nullableString(r["steam_agreement_status"]),
|
|
1564
|
+
metadata: r["metadata"] && typeof r["metadata"] === "object" ? r["metadata"] : null,
|
|
1565
|
+
consent: {
|
|
1566
|
+
consent_at: nullableString(consent["consent_at"]),
|
|
1567
|
+
consent_ip: nullableString(consent["consent_ip"]),
|
|
1568
|
+
consent_user_agent: nullableString(consent["consent_user_agent"]),
|
|
1569
|
+
disclosed_amount_usd: nullableString(consent["disclosed_amount_usd"]),
|
|
1570
|
+
disclosed_interval: nullableString(consent["disclosed_interval"]),
|
|
1571
|
+
terms_version: nullableString(consent["terms_version"])
|
|
1572
|
+
},
|
|
1573
|
+
createdAt: String(r["created_at"] ?? ""),
|
|
1574
|
+
updatedAt: String(r["updated_at"] ?? ""),
|
|
1575
|
+
revenueShare: share && typeof share === "object" ? {
|
|
1576
|
+
recipientPlayerId: Number(share["recipient_player_id"] ?? 0),
|
|
1577
|
+
percent: String(share["percent"] ?? ""),
|
|
1578
|
+
// Attribution only: INVO never pays the recipient. Read the wire value, never assume.
|
|
1579
|
+
settledByInvo: share["settled_by_invo"] === true
|
|
1580
|
+
} : null,
|
|
1581
|
+
paidThrough: nullableString(r["paid_through"]),
|
|
1582
|
+
amountCoinsEstimate: r["amount_coins_estimate"] == null ? void 0 : String(r["amount_coins_estimate"]),
|
|
1583
|
+
raw: r
|
|
1584
|
+
};
|
|
1585
|
+
}
|
|
1586
|
+
function toFirstCharge(row) {
|
|
1587
|
+
const r = row && typeof row === "object" ? row : {};
|
|
1588
|
+
return {
|
|
1589
|
+
status: String(r["status"] ?? "pending"),
|
|
1590
|
+
amountUsd: nullableString(r["amount_usd"]),
|
|
1591
|
+
paidPeriodSeq: typeof r["paid_period_seq"] === "number" ? r["paid_period_seq"] : null,
|
|
1592
|
+
paidThrough: nullableString(r["paid_through"]),
|
|
1593
|
+
failureCode: nullableString(r["failure_code"]),
|
|
1594
|
+
nextRetryAt: nullableString(r["next_retry_at"]),
|
|
1595
|
+
confirmationUrl: nullableString(r["confirmation_url"]),
|
|
1596
|
+
expiresAt: nullableString(r["expires_at"]),
|
|
1597
|
+
message: nullableString(r["message"]),
|
|
1598
|
+
raw: r
|
|
1599
|
+
};
|
|
1600
|
+
}
|
|
1601
|
+
function toSubscriptionResult(raw) {
|
|
1602
|
+
return {
|
|
1603
|
+
status: String(raw["status"] ?? ""),
|
|
1604
|
+
idempotentReplay: raw["idempotent_replay"] === true,
|
|
1605
|
+
subscription: toSubscription(raw["subscription"]),
|
|
1606
|
+
card: toSavedCard(raw["card"]),
|
|
1607
|
+
firstCharge: toFirstCharge(raw["first_charge"]),
|
|
1608
|
+
warning: typeof raw["warning"] === "string" ? raw["warning"] : void 0,
|
|
1609
|
+
raw
|
|
1610
|
+
};
|
|
1611
|
+
}
|
|
1612
|
+
function toSandboxClockState(row) {
|
|
1613
|
+
if (!row || typeof row !== "object") return null;
|
|
1614
|
+
const r = row;
|
|
1615
|
+
return {
|
|
1616
|
+
status: String(r["status"] ?? ""),
|
|
1617
|
+
periodSeq: Number(r["period_seq"] ?? 0),
|
|
1618
|
+
currentPeriodStart: nullableString(r["current_period_start"]),
|
|
1619
|
+
currentPeriodEnd: nullableString(r["current_period_end"]),
|
|
1620
|
+
nextChargeAt: nullableString(r["next_charge_at"]),
|
|
1621
|
+
trialEnd: nullableString(r["trial_end"]),
|
|
1622
|
+
cancelAtPeriodEnd: r["cancel_at_period_end"] === true,
|
|
1623
|
+
walletOnly: r["wallet_only"] === true,
|
|
1624
|
+
hasPaymentMethod: r["has_payment_method"] === true,
|
|
1625
|
+
amountUsd: String(r["amount_usd"] ?? ""),
|
|
1626
|
+
raw: r
|
|
1627
|
+
};
|
|
1628
|
+
}
|
|
1629
|
+
function optNumber(v) {
|
|
1630
|
+
return typeof v === "number" && Number.isFinite(v) ? v : void 0;
|
|
1631
|
+
}
|
|
1632
|
+
function toSandboxClockResult(raw) {
|
|
1633
|
+
const before = toSandboxClockState(raw["before"]);
|
|
1634
|
+
const after = toSandboxClockState(raw["after"]);
|
|
1635
|
+
const stats = raw["engine_stats"];
|
|
1636
|
+
return {
|
|
1637
|
+
status: String(raw["status"] ?? ""),
|
|
1638
|
+
action: String(raw["action"] ?? ""),
|
|
1639
|
+
// advance-clock reports before/after rather than a `subscription` block; surface
|
|
1640
|
+
// `after` there so every tool answers "where is the clock now" in one place.
|
|
1641
|
+
subscription: toSandboxClockState(raw["subscription"]) ?? after,
|
|
1642
|
+
before: before ?? void 0,
|
|
1643
|
+
after: after ?? void 0,
|
|
1644
|
+
intervals: optNumber(raw["intervals"]),
|
|
1645
|
+
intervalsAppliedToWindow: optNumber(raw["intervals_applied_to_window"]),
|
|
1646
|
+
windowMoved: typeof raw["window_moved"] === "boolean" ? raw["window_moved"] : void 0,
|
|
1647
|
+
windowAlreadyElapsed: typeof raw["window_already_elapsed"] === "boolean" ? raw["window_already_elapsed"] : void 0,
|
|
1648
|
+
engineStats: stats && typeof stats === "object" ? stats : void 0,
|
|
1649
|
+
periodSeq: optNumber(raw["period_seq"]),
|
|
1650
|
+
attemptNo: optNumber(raw["attempt_no"]),
|
|
1651
|
+
amountUsd: raw["amount_usd"] == null ? void 0 : String(raw["amount_usd"]),
|
|
1652
|
+
amountCoins: raw["amount_coins"] == null ? void 0 : String(raw["amount_coins"]),
|
|
1653
|
+
retired: typeof raw["retired"] === "boolean" ? raw["retired"] : void 0,
|
|
1654
|
+
retryBudgetUsed: optNumber(raw["retry_budget_used"]),
|
|
1655
|
+
retryScheduleDays: Array.isArray(raw["retry_schedule_days"]) ? raw["retry_schedule_days"].map(Number) : void 0,
|
|
1656
|
+
retriesRemaining: optNumber(raw["retries_remaining"]),
|
|
1657
|
+
authChallengesUsed: optNumber(raw["auth_challenges_used"]),
|
|
1658
|
+
maxAuthChallenges: optNumber(raw["max_auth_challenges"]),
|
|
1659
|
+
downgradedToDecline: typeof raw["downgraded_to_decline"] === "boolean" ? raw["downgraded_to_decline"] : void 0,
|
|
1660
|
+
note: typeof raw["note"] === "string" ? raw["note"] : void 0,
|
|
1661
|
+
raw
|
|
1662
|
+
};
|
|
1663
|
+
}
|
|
1664
|
+
function subscriptionBaseBody(input) {
|
|
1665
|
+
assertClientRequestId(input.clientRequestId, "clientRequestId");
|
|
1666
|
+
for (const [k, v] of [
|
|
1667
|
+
["playerEmail", input.playerEmail],
|
|
1668
|
+
["playerName", input.playerName],
|
|
1669
|
+
["itemId", input.itemId]
|
|
1670
|
+
]) {
|
|
1671
|
+
if (typeof v !== "string" || !v.trim()) throw invalidInput(k, v, "is required");
|
|
1672
|
+
}
|
|
1673
|
+
if (input.interval !== void 0 && !SUBSCRIPTION_INTERVALS.has(input.interval)) {
|
|
1674
|
+
throw invalidInput("interval", input.interval, 'must be "month" or "year"');
|
|
1675
|
+
}
|
|
1676
|
+
if (input.playerPhone !== void 0) assertE164(input.playerPhone, "playerPhone");
|
|
1677
|
+
const body = {
|
|
1678
|
+
client_request_id: input.clientRequestId,
|
|
1679
|
+
player_email: input.playerEmail,
|
|
1680
|
+
player_name: input.playerName,
|
|
1681
|
+
item_id: input.itemId,
|
|
1682
|
+
amount_usd: subscriptionMoney(input.amountUsd, "amountUsd")
|
|
1683
|
+
};
|
|
1684
|
+
if (input.playerPhone) body["player_phone"] = input.playerPhone;
|
|
1685
|
+
if (input.itemName) body["item_name"] = input.itemName;
|
|
1686
|
+
if (input.interval) body["interval"] = input.interval;
|
|
1687
|
+
if (input.metadata) body["metadata"] = input.metadata;
|
|
1688
|
+
if (input.consent) {
|
|
1689
|
+
const c = input.consent;
|
|
1690
|
+
const consent = {};
|
|
1691
|
+
if (c.consentAt !== void 0) consent["consent_at"] = c.consentAt;
|
|
1692
|
+
if (c.consentIp !== void 0) consent["consent_ip"] = c.consentIp;
|
|
1693
|
+
if (c.consentUserAgent !== void 0) consent["consent_user_agent"] = c.consentUserAgent;
|
|
1694
|
+
if (c.disclosedAmountUsd !== void 0) consent["disclosed_amount_usd"] = c.disclosedAmountUsd;
|
|
1695
|
+
if (c.disclosedInterval !== void 0) consent["disclosed_interval"] = c.disclosedInterval;
|
|
1696
|
+
if (c.termsVersion !== void 0) consent["terms_version"] = c.termsVersion;
|
|
1697
|
+
body["consent"] = consent;
|
|
1698
|
+
}
|
|
1699
|
+
if (input.revenueShare) {
|
|
1700
|
+
const s = input.revenueShare;
|
|
1701
|
+
const hasEmail = typeof s.recipientPlayerEmail === "string" && s.recipientPlayerEmail.trim() !== "";
|
|
1702
|
+
const hasId = s.recipientPlayerId != null;
|
|
1703
|
+
if (hasEmail === hasId) {
|
|
1704
|
+
throw invalidInput(
|
|
1705
|
+
"revenueShare",
|
|
1706
|
+
s,
|
|
1707
|
+
"requires EXACTLY ONE of recipientPlayerEmail or recipientPlayerId"
|
|
1708
|
+
);
|
|
1709
|
+
}
|
|
1710
|
+
const share = {
|
|
1711
|
+
percent: typeof s.percent === "number" ? s.percent.toFixed(2) : s.percent
|
|
1712
|
+
};
|
|
1713
|
+
if (hasEmail) share["recipient_player_email"] = s.recipientPlayerEmail;
|
|
1714
|
+
else share["recipient_player_id"] = s.recipientPlayerId;
|
|
1715
|
+
body["revenue_share"] = share;
|
|
1716
|
+
}
|
|
1717
|
+
return body;
|
|
1718
|
+
}
|
|
1719
|
+
var SubscriptionsServer = class {
|
|
1720
|
+
constructor(http, auth) {
|
|
1721
|
+
this.http = http;
|
|
1722
|
+
this.auth = auth;
|
|
1723
|
+
}
|
|
1724
|
+
/**
|
|
1725
|
+
* Create a CARD-rail subscription. **Charges the first period before responding**
|
|
1726
|
+
* (unless it is a trial), so expect the call to take as long as a card charge.
|
|
1727
|
+
*
|
|
1728
|
+
* Branch on `result.firstCharge.status`: `paid` (grant until `paidThrough`),
|
|
1729
|
+
* `requires_action` (NOTHING charged; send the member to `confirmationUrl`),
|
|
1730
|
+
* `skipped_trial` (grant trial access until `subscription.trialEnd`), `failed` (in
|
|
1731
|
+
* dunning; INVO retries at `nextRetryAt`), `pending` (wait for the event).
|
|
1732
|
+
*
|
|
1733
|
+
* Idempotent on `clientRequestId`: a repeat returns HTTP 200 with the identical shape
|
|
1734
|
+
* and `idempotentReplay: true`, and NOTHING is charged again. **On any timeout or 5xx,
|
|
1735
|
+
* replay the same key before you do anything else**; a fresh key inside a retry loop
|
|
1736
|
+
* lands on `409 ACTIVE_SUBSCRIPTION_EXISTS` (`err.isActiveSubscriptionExists`,
|
|
1737
|
+
* `err.existingSubscriptionId`) at best and a second subscription at worst. Same key
|
|
1738
|
+
* with different terms is `err.isIdempotentReplayMismatch` (`err.mismatchedFields`).
|
|
1739
|
+
*
|
|
1740
|
+
* Card selection: `playerCardId` names one (from `cards.list`); omitted, INVO attaches
|
|
1741
|
+
* the member's newest unexpired saved card; `walletOnly: true` never charges a card.
|
|
1742
|
+
* Requires the game to be `live` (`err.isGameNotLive`).
|
|
1743
|
+
*/
|
|
1744
|
+
async create(input, opts) {
|
|
1745
|
+
const body = subscriptionBaseBody(input);
|
|
1746
|
+
if (input.intervalCount !== void 0) {
|
|
1747
|
+
if (!Number.isInteger(input.intervalCount) || input.intervalCount < 1 || input.intervalCount > 36) {
|
|
1748
|
+
throw invalidInput("intervalCount", input.intervalCount, "must be an integer 1..36");
|
|
1749
|
+
}
|
|
1750
|
+
body["interval_count"] = input.intervalCount;
|
|
1751
|
+
}
|
|
1752
|
+
if (input.trialDays !== void 0) {
|
|
1753
|
+
if (!Number.isInteger(input.trialDays) || input.trialDays < 1 || input.trialDays > 365) {
|
|
1754
|
+
throw invalidInput("trialDays", input.trialDays, "must be an integer 1..365");
|
|
1755
|
+
}
|
|
1756
|
+
body["trial_days"] = input.trialDays;
|
|
1757
|
+
}
|
|
1758
|
+
if (input.trialEnd !== void 0) {
|
|
1759
|
+
if (typeof input.trialEnd !== "string" || Number.isNaN(Date.parse(input.trialEnd))) {
|
|
1760
|
+
throw invalidInput("trialEnd", input.trialEnd, "must be an ISO 8601 timestamp");
|
|
1761
|
+
}
|
|
1762
|
+
body["trial_end"] = input.trialEnd;
|
|
1763
|
+
}
|
|
1764
|
+
if (input.walletOnly !== void 0) {
|
|
1765
|
+
if (typeof input.walletOnly !== "boolean") {
|
|
1766
|
+
throw invalidInput("walletOnly", input.walletOnly, "must be a boolean");
|
|
1767
|
+
}
|
|
1768
|
+
body["wallet_only"] = input.walletOnly;
|
|
1769
|
+
}
|
|
1770
|
+
if (input.playerCardId !== void 0) {
|
|
1771
|
+
if (!Number.isInteger(input.playerCardId) || input.playerCardId < 1) {
|
|
1772
|
+
throw invalidInput("playerCardId", input.playerCardId, "must be a positive integer card id (from cards.list)");
|
|
1773
|
+
}
|
|
1774
|
+
if (input.walletOnly === true) {
|
|
1775
|
+
throw invalidInput("playerCardId", input.playerCardId, "cannot be combined with walletOnly: true");
|
|
1776
|
+
}
|
|
1777
|
+
body["player_card_id"] = input.playerCardId;
|
|
1778
|
+
}
|
|
1779
|
+
const raw = await this.http.post(
|
|
1780
|
+
"/api/subscriptions/subscribe",
|
|
1781
|
+
body,
|
|
1782
|
+
this.auth,
|
|
1783
|
+
// Idempotent on client_request_id: a lost-response retry REPLAYS the row (200,
|
|
1784
|
+
// idempotent_replay: true) and never charges twice. Replay before retry.
|
|
1785
|
+
{ idempotent: true, signal: opts?.signal }
|
|
1786
|
+
);
|
|
1787
|
+
return toSubscriptionResult(raw);
|
|
1788
|
+
}
|
|
1789
|
+
/** Read one subscription. `404 SUBSCRIPTION_NOT_FOUND` for an id that is not your game's. */
|
|
1790
|
+
async get(subscriptionId, options, opts) {
|
|
1791
|
+
assertSubscriptionId(subscriptionId);
|
|
1792
|
+
const qs = options?.includePlayer ? "?include_player=true" : "";
|
|
1793
|
+
const raw = await this.http.get(
|
|
1794
|
+
`/api/subscriptions/${encodeURIComponent(subscriptionId)}${qs}`,
|
|
1795
|
+
this.auth,
|
|
1796
|
+
{ signal: opts?.signal }
|
|
1797
|
+
);
|
|
1798
|
+
return {
|
|
1799
|
+
subscription: toSubscription(raw["subscription"]),
|
|
1800
|
+
player: raw["player"] && typeof raw["player"] === "object" ? raw["player"] : void 0,
|
|
1801
|
+
raw
|
|
1802
|
+
};
|
|
1803
|
+
}
|
|
1804
|
+
/**
|
|
1805
|
+
* List a member's subscriptions, newest first, paged (`limit` 1..100, `offset`
|
|
1806
|
+
* 0..100000). `status` filters; `"live"` expands to the four live statuses and may be
|
|
1807
|
+
* mixed in (`["live", "canceled"]`). A player who does not exist yet is an empty list
|
|
1808
|
+
* with `totalCount: 0`, not a 404.
|
|
1809
|
+
*/
|
|
1810
|
+
async listForPlayer(playerEmail, options, opts) {
|
|
1811
|
+
if (typeof playerEmail !== "string" || !playerEmail.trim()) {
|
|
1812
|
+
throw invalidInput("playerEmail", playerEmail, "is required");
|
|
1813
|
+
}
|
|
1814
|
+
const q = new URLSearchParams();
|
|
1815
|
+
q.set("player_email", playerEmail);
|
|
1816
|
+
if (options?.status !== void 0) {
|
|
1817
|
+
const list = Array.isArray(options.status) ? options.status : [options.status];
|
|
1818
|
+
if (list.length) q.set("status", list.join(","));
|
|
1819
|
+
}
|
|
1820
|
+
if (options?.includePlayer) q.set("include_player", "true");
|
|
1821
|
+
if (options?.limit != null) {
|
|
1822
|
+
if (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > 100) {
|
|
1823
|
+
throw invalidInput("limit", options.limit, "must be an integer 1..100");
|
|
1824
|
+
}
|
|
1825
|
+
q.set("limit", String(options.limit));
|
|
1826
|
+
}
|
|
1827
|
+
if (options?.offset != null) {
|
|
1828
|
+
if (!Number.isInteger(options.offset) || options.offset < 0 || options.offset > 1e5) {
|
|
1829
|
+
throw invalidInput("offset", options.offset, "must be an integer 0..100000");
|
|
1830
|
+
}
|
|
1831
|
+
q.set("offset", String(options.offset));
|
|
1832
|
+
}
|
|
1833
|
+
const raw = await this.http.get(
|
|
1834
|
+
`/api/subscriptions/player?${q.toString()}`,
|
|
1835
|
+
this.auth,
|
|
1836
|
+
{ signal: opts?.signal }
|
|
1837
|
+
);
|
|
1838
|
+
const rows = Array.isArray(raw["subscriptions"]) ? raw["subscriptions"] : [];
|
|
1839
|
+
const p = raw["pagination"] ?? {};
|
|
1840
|
+
return {
|
|
1841
|
+
playerEmail: String(raw["player_email"] ?? playerEmail),
|
|
1842
|
+
subscriptions: rows.map(toSubscription),
|
|
1843
|
+
pagination: {
|
|
1844
|
+
totalCount: Number(p["total_count"] ?? rows.length),
|
|
1845
|
+
limit: Number(p["limit"] ?? 50),
|
|
1846
|
+
offset: Number(p["offset"] ?? 0),
|
|
1847
|
+
hasMore: p["has_more"] === true
|
|
1848
|
+
},
|
|
1849
|
+
raw
|
|
1850
|
+
};
|
|
1851
|
+
}
|
|
1852
|
+
/**
|
|
1853
|
+
* Cancel. `atPeriodEnd` defaults to `true`: the subscription stays live with
|
|
1854
|
+
* `cancelAtPeriodEnd: true` and is retired at `paidThrough` without another charge.
|
|
1855
|
+
* If nothing has been paid (or the paid window has elapsed) an at-period-end cancel is
|
|
1856
|
+
* **downgraded to immediate**: read `terminatedImmediately`. `atPeriodEnd: false` ends
|
|
1857
|
+
* it now. Revoke access at `accessUntil`.
|
|
1858
|
+
*
|
|
1859
|
+
* Cancelling an already-terminal subscription is a 200 with `alreadyCanceled: true`
|
|
1860
|
+
* (never thrown), so a batch reconciler needs no special case; that is also what makes
|
|
1861
|
+
* a lost-response retry safe. One `subscription.canceled` event fires at request time.
|
|
1862
|
+
* Never blocked by a maintenance pause.
|
|
1863
|
+
*/
|
|
1864
|
+
async cancel(subscriptionId, options, opts) {
|
|
1865
|
+
assertSubscriptionId(subscriptionId);
|
|
1866
|
+
const body = {};
|
|
1867
|
+
if (options?.atPeriodEnd !== void 0) {
|
|
1868
|
+
if (typeof options.atPeriodEnd !== "boolean") {
|
|
1869
|
+
throw invalidInput("atPeriodEnd", options.atPeriodEnd, "must be a boolean");
|
|
1870
|
+
}
|
|
1871
|
+
body["at_period_end"] = options.atPeriodEnd;
|
|
1872
|
+
}
|
|
1873
|
+
if (options?.reason !== void 0) {
|
|
1874
|
+
if (typeof options.reason !== "string" || options.reason.length > 500) {
|
|
1875
|
+
throw invalidInput("reason", options.reason, "must be a string of at most 500 characters");
|
|
1876
|
+
}
|
|
1877
|
+
body["reason"] = options.reason;
|
|
1878
|
+
}
|
|
1879
|
+
const raw = await this.http.post(
|
|
1880
|
+
`/api/subscriptions/${encodeURIComponent(subscriptionId)}/cancel`,
|
|
1881
|
+
body,
|
|
1882
|
+
this.auth,
|
|
1883
|
+
// Safe to retry: a repeat on an already-canceled row is a 200 (already_canceled: true).
|
|
1884
|
+
{ idempotent: true, signal: opts?.signal }
|
|
1885
|
+
);
|
|
1886
|
+
return {
|
|
1887
|
+
status: String(raw["status"] ?? ""),
|
|
1888
|
+
alreadyCanceled: raw["already_canceled"] === true,
|
|
1889
|
+
finalStatus: typeof raw["final_status"] === "string" ? raw["final_status"] : void 0,
|
|
1890
|
+
cancelAtPeriodEnd: raw["cancel_at_period_end"] === true,
|
|
1891
|
+
effectiveAt: nullableString(raw["effective_at"]),
|
|
1892
|
+
currentPeriodEnd: nullableString(raw["current_period_end"]),
|
|
1893
|
+
accessUntil: nullableString(raw["access_until"]),
|
|
1894
|
+
paidThrough: nullableString(raw["paid_through"]),
|
|
1895
|
+
terminatedImmediately: raw["terminated_immediately"] === true,
|
|
1896
|
+
downgradeReason: typeof raw["downgrade_reason"] === "string" ? raw["downgrade_reason"] : void 0,
|
|
1897
|
+
message: typeof raw["message"] === "string" ? raw["message"] : void 0,
|
|
1898
|
+
steamAgreementStatus: "steam_agreement_status" in raw ? nullableString(raw["steam_agreement_status"]) : void 0,
|
|
1899
|
+
steamAgreementCanceled: typeof raw["steam_agreement_canceled"] === "boolean" ? raw["steam_agreement_canceled"] : void 0,
|
|
1900
|
+
subscription: raw["subscription"] ? toSubscription(raw["subscription"]) : null,
|
|
1901
|
+
raw
|
|
1902
|
+
};
|
|
1903
|
+
}
|
|
1904
|
+
/**
|
|
1905
|
+
* Stage a price change. Applied on the NEXT successful renewal (the current window is
|
|
1906
|
+
* billed at the old price first; no proration). Sending the current price clears a
|
|
1907
|
+
* staged change (`changeQueued: false`). The billed price appears on that period's
|
|
1908
|
+
* `subscription.renewed`; there is no `amount_changed` event.
|
|
1909
|
+
*
|
|
1910
|
+
* Steam: an increase is refused (`err.isSteamReauthorizationRequired`; start a new
|
|
1911
|
+
* Steam subscription at the new price), a decrease stages. An increase to more than
|
|
1912
|
+
* double the last agreed price, or above 500.00, is staged but never applied: raise
|
|
1913
|
+
* prices in steps. `err.isSubscriptionTerminal` on a canceled/expired row.
|
|
1914
|
+
*/
|
|
1915
|
+
async changeAmount(subscriptionId, amountUsd, opts) {
|
|
1916
|
+
assertSubscriptionId(subscriptionId);
|
|
1917
|
+
const amount = subscriptionMoney(amountUsd, "amountUsd");
|
|
1918
|
+
const raw = await this.http.post(
|
|
1919
|
+
`/api/subscriptions/${encodeURIComponent(subscriptionId)}/amount`,
|
|
1920
|
+
{ amount_usd: amount },
|
|
1921
|
+
this.auth,
|
|
1922
|
+
// Setting a price is naturally idempotent: the same value again is the same state.
|
|
1923
|
+
{ idempotent: true, signal: opts?.signal }
|
|
1924
|
+
);
|
|
1925
|
+
return {
|
|
1926
|
+
status: String(raw["status"] ?? ""),
|
|
1927
|
+
oldAmountUsd: String(raw["old_amount_usd"] ?? ""),
|
|
1928
|
+
newAmountUsd: String(raw["new_amount_usd"] ?? amount),
|
|
1929
|
+
pendingAmountUsd: nullableString(raw["pending_amount_usd"]),
|
|
1930
|
+
changeQueued: raw["change_queued"] === true,
|
|
1931
|
+
appliesFrom: nullableString(raw["applies_from"]),
|
|
1932
|
+
appliesFromPeriodSeq: Number(raw["applies_from_period_seq"] ?? 0),
|
|
1933
|
+
paidThrough: nullableString(raw["paid_through"]),
|
|
1934
|
+
currentPeriodEnd: nullableString(raw["current_period_end"]),
|
|
1935
|
+
prorated: raw["prorated"] === true,
|
|
1936
|
+
subscription: raw["subscription"] ? toSubscription(raw["subscription"]) : null,
|
|
1937
|
+
raw
|
|
1938
|
+
};
|
|
1939
|
+
}
|
|
1940
|
+
/**
|
|
1941
|
+
* Card subscriptions only. Attach a card (`{ playerCardId }`, an `id` from
|
|
1942
|
+
* `cards.list` belonging to this player, unexpired) or make the subscription wallet-only
|
|
1943
|
+
* (`{ walletOnly: true }`). On a wallet-only subscription pass `walletOnly: false`
|
|
1944
|
+
* beside the card to convert it back. The new card is used from the next charge,
|
|
1945
|
+
* including a pending retry in dunning.
|
|
1946
|
+
*
|
|
1947
|
+
* `err.isNotACardSubscription` on Steam; `err.isSubscriptionTerminal` on a terminal row.
|
|
1948
|
+
*/
|
|
1949
|
+
async setPaymentMethod(subscriptionId, input, opts) {
|
|
1950
|
+
assertSubscriptionId(subscriptionId);
|
|
1951
|
+
const body = {};
|
|
1952
|
+
if ("playerCardId" in input && input.playerCardId !== void 0) {
|
|
1953
|
+
if (!Number.isInteger(input.playerCardId) || input.playerCardId < 1) {
|
|
1954
|
+
throw invalidInput("playerCardId", input.playerCardId, "must be a positive integer card id (from cards.list)");
|
|
1955
|
+
}
|
|
1956
|
+
body["player_card_id"] = input.playerCardId;
|
|
1957
|
+
if (input.walletOnly !== void 0) body["wallet_only"] = input.walletOnly;
|
|
1958
|
+
} else if (input.walletOnly === true) {
|
|
1959
|
+
body["wallet_only"] = true;
|
|
1960
|
+
} else {
|
|
1961
|
+
throw invalidInput("input", input, "requires { playerCardId } or { walletOnly: true }");
|
|
1962
|
+
}
|
|
1963
|
+
const raw = await this.http.post(
|
|
1964
|
+
`/api/subscriptions/${encodeURIComponent(subscriptionId)}/payment-method`,
|
|
1965
|
+
body,
|
|
1966
|
+
this.auth,
|
|
1967
|
+
// Attaching the same card twice is the same state: safe to retry.
|
|
1968
|
+
{ idempotent: true, signal: opts?.signal }
|
|
1969
|
+
);
|
|
1970
|
+
return {
|
|
1971
|
+
status: String(raw["status"] ?? ""),
|
|
1972
|
+
replaced: raw["replaced"] === true,
|
|
1973
|
+
walletOnly: raw["wallet_only"] === true,
|
|
1974
|
+
card: toSavedCard(raw["card"]),
|
|
1975
|
+
subscription: raw["subscription"] ? toSubscription(raw["subscription"]) : null,
|
|
1976
|
+
raw
|
|
1977
|
+
};
|
|
1978
|
+
}
|
|
1979
|
+
/**
|
|
1980
|
+
* Refund a billed period (card rail). Idempotent on `clientRequestId`: a repeat returns
|
|
1981
|
+
* the stored receipt with `idempotentReplay: true` and moves nothing.
|
|
1982
|
+
*
|
|
1983
|
+
* A full refund returns the card charge and reclaims the coins that charge minted
|
|
1984
|
+
* (`balanceDeltaCoins` is signed and can be negative); a partial refund credits the
|
|
1985
|
+
* wallet in coins at the 10:1 peg. Your revenue is reversed for the refunded portion
|
|
1986
|
+
* (`partnerRevenueReversedUsd`); INVO's fee is retained. The subscription is NOT
|
|
1987
|
+
* cancelled by a refund. Refunds of Steam-CHARGED periods are not supported yet; do not
|
|
1988
|
+
* call this on them.
|
|
1989
|
+
*
|
|
1990
|
+
* Refusals: `NO_PAID_PERIOD` (409, nothing collected yet), `PERIOD_NOT_REFUNDABLE`,
|
|
1991
|
+
* `ALREADY_REFUNDED` (`err.isAlreadyRefunded`), `AMOUNT_EXCEEDS_REMAINING` (body carries
|
|
1992
|
+
* `remaining_refundable_usd`), `err.isFlowPaused`.
|
|
1993
|
+
*/
|
|
1994
|
+
async refund(subscriptionId, input, opts) {
|
|
1995
|
+
assertSubscriptionId(subscriptionId);
|
|
1996
|
+
assertClientRequestId(input.clientRequestId, "clientRequestId");
|
|
1997
|
+
const body = { client_request_id: input.clientRequestId };
|
|
1998
|
+
if (input.periodSeq !== void 0) {
|
|
1999
|
+
if (!Number.isInteger(input.periodSeq) || input.periodSeq < 1) {
|
|
2000
|
+
throw invalidInput("periodSeq", input.periodSeq, "must be an integer >= 1");
|
|
2001
|
+
}
|
|
2002
|
+
body["period_seq"] = input.periodSeq;
|
|
2003
|
+
}
|
|
2004
|
+
if (input.amountUsd !== void 0) body["amount_usd"] = subscriptionMoney(input.amountUsd, "amountUsd");
|
|
2005
|
+
if (input.reason !== void 0) {
|
|
2006
|
+
if (typeof input.reason !== "string" || input.reason.length > 500) {
|
|
2007
|
+
throw invalidInput("reason", input.reason, "must be a string of at most 500 characters");
|
|
2008
|
+
}
|
|
2009
|
+
body["reason"] = input.reason;
|
|
2010
|
+
}
|
|
2011
|
+
const raw = await this.http.post(
|
|
2012
|
+
`/api/subscriptions/${encodeURIComponent(subscriptionId)}/refund`,
|
|
2013
|
+
body,
|
|
2014
|
+
this.auth,
|
|
2015
|
+
// Idempotent on client_request_id: a lost-response retry returns the stored receipt.
|
|
2016
|
+
{ idempotent: true, signal: opts?.signal }
|
|
2017
|
+
);
|
|
2018
|
+
const attr = raw["revenue_share_attribution"];
|
|
2019
|
+
const a = attr && typeof attr === "object" ? attr : null;
|
|
2020
|
+
return {
|
|
2021
|
+
status: String(raw["status"] ?? ""),
|
|
2022
|
+
idempotentReplay: raw["idempotent_replay"] === true,
|
|
2023
|
+
refundKey: nullableString(raw["refund_key"]),
|
|
2024
|
+
clientRequestId: nullableString(raw["client_request_id"]) ?? input.clientRequestId,
|
|
2025
|
+
subscriptionId: String(raw["subscription_id"] ?? subscriptionId),
|
|
2026
|
+
periodSeq: raw["period_seq"] == null ? null : Number(raw["period_seq"]),
|
|
2027
|
+
transactionId: nullableString(raw["transaction_id"]),
|
|
2028
|
+
refundedAmountUsd: nullableString(raw["refunded_amount_usd"]),
|
|
2029
|
+
totalRefundedAmountUsd: nullableString(raw["total_refunded_amount_usd"]),
|
|
2030
|
+
remainingRefundableUsd: nullableString(raw["remaining_refundable_usd"]),
|
|
2031
|
+
isFullRefund: raw["is_full_refund"] === true,
|
|
2032
|
+
fundingShape: nullableString(raw["funding_shape"]),
|
|
2033
|
+
balanceDeltaCoins: nullableString(raw["balance_delta_coins"]),
|
|
2034
|
+
cardRefundedUsd: nullableString(raw["card_refunded_usd"]),
|
|
2035
|
+
// Neutral field only; the vendor-named sibling is deliberately not read.
|
|
2036
|
+
processorRefundReference: nullableString(raw["processor_refund_reference"]),
|
|
2037
|
+
processorRefundAdopted: raw["processor_refund_adopted"] === true,
|
|
2038
|
+
invoFeeRetained: raw["invo_fee_retained"] === true,
|
|
2039
|
+
partnerRevenueReversedUsd: nullableString(raw["partner_revenue_reversed_usd"]),
|
|
2040
|
+
partnerRevenueReversalMode: nullableString(raw["partner_revenue_reversal_mode"]),
|
|
2041
|
+
reason: nullableString(raw["reason"]),
|
|
2042
|
+
refundedAt: nullableString(raw["refunded_at"]),
|
|
2043
|
+
newBalance: nullableString(raw["new_balance"]),
|
|
2044
|
+
revenueShareAttribution: a ? {
|
|
2045
|
+
recipientPlayerId: Number(a["recipient_player_id"] ?? 0),
|
|
2046
|
+
percent: String(a["percent"] ?? ""),
|
|
2047
|
+
originalAttributedAmountUsd: String(a["original_attributed_amount_usd"] ?? ""),
|
|
2048
|
+
refundedAttributedAmountUsd: String(a["refunded_attributed_amount_usd"] ?? ""),
|
|
2049
|
+
netAttributedAmountUsd: String(a["net_attributed_amount_usd"] ?? ""),
|
|
2050
|
+
settledByInvo: a["settled_by_invo"] === true,
|
|
2051
|
+
raw: a
|
|
2052
|
+
} : null,
|
|
2053
|
+
note: typeof raw["note"] === "string" ? raw["note"] : void 0,
|
|
2054
|
+
raw
|
|
2055
|
+
};
|
|
2056
|
+
}
|
|
2057
|
+
/**
|
|
2058
|
+
* Start a STEAM-rail subscription: creates it in `pending_steam_authorization`, opens
|
|
2059
|
+
* period 1 for the full price and starts the Steam authorisation. Nothing is charged
|
|
2060
|
+
* until the member authorises and you call {@link steamFinalize}. Idempotent on
|
|
2061
|
+
* `clientRequestId`; a replay answers with the row's CURRENT status (which may already
|
|
2062
|
+
* be `active`, `canceled` or `expired`).
|
|
2063
|
+
*
|
|
2064
|
+
* `userSession: "client"` (default): the Steam overlay presents the authorisation inside
|
|
2065
|
+
* the game; match the Steam client callback's `order_id` against `steamOrderId` (never
|
|
2066
|
+
* `steamTransid`). `"web"`: open `steamCheckoutUrl` as a TOP-LEVEL window (it cannot be
|
|
2067
|
+
* framed); requires `playerIp`, the MEMBER's address. Show `amountCoins`: what one
|
|
2068
|
+
* period is worth for THIS member depends on their country and is fixed at init.
|
|
2069
|
+
*
|
|
2070
|
+
* A pending authorisation for the same player and item with the SAME terms is handed
|
|
2071
|
+
* back (`pendingReuse: true`, no new agreement): finalize that one. With DIFFERENT
|
|
2072
|
+
* terms the call throws `409 STEAM_AUTHORIZATION_PENDING` (`err.isSteamAuthorizationPending`,
|
|
2073
|
+
* `err.existingSubscriptionId`): finalize or cancel the pending one first.
|
|
2074
|
+
*
|
|
2075
|
+
* Not available on Steam, refused before the network: trials, `walletOnly`, card
|
|
2076
|
+
* fields, `intervalCount` other than 1. Backend refusals worth branching on:
|
|
2077
|
+
* `err.isSteamChannelRequired` (409, wrong channel key), `err.isActiveSubscriptionExists`,
|
|
2078
|
+
* `err.isSteamRailNotEntitled` (403), `err.isSteamNotConfigured` (503),
|
|
2079
|
+
* `err.isPartnerBillingNotSetUp` / `isPartnerSettlementUnavailable` (409),
|
|
2080
|
+
* `AMOUNT_TOO_SMALL_FOR_STEAM` (400). When a Steam-side failure abandons the row after
|
|
2081
|
+
* creation the body carries the abandoned `subscription_id`; retry with a NEW key.
|
|
2082
|
+
*/
|
|
2083
|
+
async steamInit(input, opts) {
|
|
2084
|
+
const body = subscriptionBaseBody(input);
|
|
2085
|
+
if (!/^[0-9]+$/.test(String(input.steamId ?? ""))) {
|
|
2086
|
+
throw invalidInput("steamId", input.steamId, "must be the member's numeric 64-bit Steam id");
|
|
2087
|
+
}
|
|
2088
|
+
if (input.userSession !== void 0 && input.userSession !== "client" && input.userSession !== "web") {
|
|
2089
|
+
throw invalidInput("userSession", input.userSession, 'must be "client" or "web"');
|
|
2090
|
+
}
|
|
2091
|
+
if (input.userSession === "web" && !input.playerIp) {
|
|
2092
|
+
throw new InvoError({
|
|
2093
|
+
message: `playerIp is required when userSession is "web" \u2014 the MEMBER's IP, not your server's.`,
|
|
2094
|
+
code: "MISSING_PLAYER_IP",
|
|
2095
|
+
status: 0
|
|
2096
|
+
});
|
|
2097
|
+
}
|
|
2098
|
+
if (input.intervalCount !== void 0 && input.intervalCount !== 1) {
|
|
2099
|
+
throw invalidInput("intervalCount", input.intervalCount, "must be 1 on the Steam rail (monthly and yearly only)");
|
|
2100
|
+
}
|
|
2101
|
+
const forbidden = input;
|
|
2102
|
+
for (const k of ["trialDays", "trialEnd", "walletOnly", "playerCardId"]) {
|
|
2103
|
+
if (forbidden[k] !== void 0) {
|
|
2104
|
+
throw invalidInput(k, forbidden[k], "is not available on the Steam rail");
|
|
2105
|
+
}
|
|
2106
|
+
}
|
|
2107
|
+
body["steamid"] = String(input.steamId);
|
|
2108
|
+
if (input.userSession) body["usersession"] = input.userSession;
|
|
2109
|
+
if (input.playerIp) body["player_ip"] = input.playerIp;
|
|
2110
|
+
if (input.intervalCount !== void 0) body["interval_count"] = input.intervalCount;
|
|
2111
|
+
const raw = await this.http.post(
|
|
2112
|
+
"/api/subscriptions/steam/init",
|
|
2113
|
+
body,
|
|
2114
|
+
this.auth,
|
|
2115
|
+
// Idempotent on client_request_id: a replay returns the row's current status.
|
|
2116
|
+
{ idempotent: true, signal: opts?.signal }
|
|
2117
|
+
);
|
|
2118
|
+
return {
|
|
2119
|
+
status: String(raw["status"] ?? ""),
|
|
2120
|
+
subscriptionStatus: String(raw["subscription_status"] ?? raw["status"] ?? ""),
|
|
2121
|
+
idempotentReplay: raw["idempotent_replay"] === true,
|
|
2122
|
+
pendingReuse: raw["pending_reuse"] === true,
|
|
2123
|
+
subscription: toSubscription(raw["subscription"]),
|
|
2124
|
+
subscriptionId: String(raw["subscription_id"] ?? ""),
|
|
2125
|
+
orderId: String(raw["order_id"] ?? ""),
|
|
2126
|
+
steamOrderId: String(raw["steam_order_id"] ?? ""),
|
|
2127
|
+
steamTransid: String(raw["steam_transid"] ?? ""),
|
|
2128
|
+
steamCheckoutUrl: nullableString(raw["steam_checkout_url"]),
|
|
2129
|
+
amountUsd: String(raw["amount_usd"] ?? ""),
|
|
2130
|
+
amountCoins: String(raw["amount_coins"] ?? ""),
|
|
2131
|
+
steamChargeUsd: String(raw["steam_charge_usd"] ?? ""),
|
|
2132
|
+
recurringAmountUsd: String(raw["recurring_amount_usd"] ?? ""),
|
|
2133
|
+
firstCharge: toFirstCharge(raw["first_charge"]),
|
|
2134
|
+
message: String(raw["message"] ?? ""),
|
|
2135
|
+
raw
|
|
2136
|
+
};
|
|
2137
|
+
}
|
|
2138
|
+
/**
|
|
2139
|
+
* Finalize a Steam subscription after the member has authorised: INVO verifies with
|
|
2140
|
+
* Steam, captures period 1, records the agreement and settles period 1 exactly as a
|
|
2141
|
+
* renewal. Idempotent: a repeat returns `alreadyProcessed: true` with
|
|
2142
|
+
* `idempotentReplay: true` (treat as success; never thrown).
|
|
2143
|
+
*
|
|
2144
|
+
* **Finalize is your call.** Steam does not tell INVO the member authorised; call this
|
|
2145
|
+
* after the overlay or checkout closes, and again if it threw `err.isNotAuthorized`
|
|
2146
|
+
* (409 `status: "not_authorized"`: the normal wait state). The member has 24 hours.
|
|
2147
|
+
* A 200 with `warning` means Steam charged but period 1 could not settle in one step:
|
|
2148
|
+
* the money is taken, do not retry the charge, watch for `subscription.renewed`.
|
|
2149
|
+
* In sandbox this does not call Steam (`sandboxAutoApproved: true`).
|
|
2150
|
+
*
|
|
2151
|
+
* Other refusals: `err.isSubscriptionTerminal`, `NOT_A_STEAM_SUBSCRIPTION`,
|
|
2152
|
+
* `NO_STEAM_AUTHORIZATION`, `err.isSteamAppChanged` (409); 502/503 are transient.
|
|
2153
|
+
*/
|
|
2154
|
+
async steamFinalize(subscriptionId, opts) {
|
|
2155
|
+
assertSubscriptionId(subscriptionId);
|
|
2156
|
+
const raw = await this.http.post(
|
|
2157
|
+
"/api/subscriptions/steam/finalize",
|
|
2158
|
+
{ subscription_id: subscriptionId },
|
|
2159
|
+
this.auth,
|
|
2160
|
+
// Idempotent: a repeat replays the finalised row (already_processed: true).
|
|
2161
|
+
{ idempotent: true, signal: opts?.signal }
|
|
2162
|
+
);
|
|
2163
|
+
return {
|
|
2164
|
+
...toSubscriptionResult(raw),
|
|
2165
|
+
alreadyProcessed: raw["already_processed"] === true,
|
|
2166
|
+
steamAgreementStatus: nullableString(raw["steam_agreement_status"]),
|
|
2167
|
+
sandboxAutoApproved: raw["sandbox_auto_approved"] === true
|
|
2168
|
+
};
|
|
2169
|
+
}
|
|
2170
|
+
};
|
|
2171
|
+
var CardsServer = class {
|
|
2172
|
+
constructor(http, auth) {
|
|
2173
|
+
this.http = http;
|
|
2174
|
+
this.auth = auth;
|
|
2175
|
+
}
|
|
2176
|
+
/**
|
|
2177
|
+
* Begin saving a card (charges nothing). The player must already exist in this game
|
|
2178
|
+
* (`404 PLAYER_NOT_FOUND`). Idempotent on `setupReference`: resend the same value on a
|
|
2179
|
+
* retry and you get the same setup back (`409 SETUP_REFERENCE_REUSED` if you reuse it
|
|
2180
|
+
* with different parameters).
|
|
2181
|
+
*
|
|
2182
|
+
* With `paymentMethodId` (a card tokenised on the client) INVO confirms server-side
|
|
2183
|
+
* and answers `succeeded` with the `card`, or `requires_action` with a `clientSecret`
|
|
2184
|
+
* for the card form to run the cardholder authentication. Without it, INVO answers
|
|
2185
|
+
* `requires_confirmation` / `requires_payment_method` with a `clientSecret`: confirm on
|
|
2186
|
+
* the client, then call {@link confirmSetup}. Send tokens only, never raw card numbers
|
|
2187
|
+
* (`RAW_CARD_NOT_SUPPORTED`).
|
|
2188
|
+
*/
|
|
2189
|
+
async beginSetup(input, opts) {
|
|
2190
|
+
if (typeof input.playerEmail !== "string" || !input.playerEmail.trim()) {
|
|
2191
|
+
throw invalidInput("playerEmail", input.playerEmail, "is required");
|
|
2192
|
+
}
|
|
2193
|
+
if (typeof input.setupReference !== "string" || !/^[A-Za-z0-9._:-]{1,200}$/.test(input.setupReference)) {
|
|
2194
|
+
throw invalidInput("setupReference", input.setupReference, "must be 1-200 characters of A-Z a-z 0-9 . _ : -");
|
|
2195
|
+
}
|
|
2196
|
+
const body = {
|
|
2197
|
+
player_email: input.playerEmail,
|
|
2198
|
+
setup_reference: input.setupReference
|
|
2199
|
+
};
|
|
2200
|
+
if (input.paymentMethodId) body["payment_method_id"] = input.paymentMethodId;
|
|
2201
|
+
const raw = await this.http.post(
|
|
2202
|
+
"/api/currency-purchases/setup-intent",
|
|
2203
|
+
body,
|
|
2204
|
+
this.auth,
|
|
2205
|
+
// Idempotent on setup_reference: a retry returns the same setup, never a second one.
|
|
2206
|
+
{ idempotent: true, signal: opts?.signal }
|
|
2207
|
+
);
|
|
2208
|
+
return {
|
|
2209
|
+
status: String(raw["status"] ?? ""),
|
|
2210
|
+
setupIntentId: requireField(raw["setup_intent_id"], "setup_intent_id", raw),
|
|
2211
|
+
clientSecret: typeof raw["client_secret"] === "string" ? raw["client_secret"] : void 0,
|
|
2212
|
+
publishableKey: typeof raw["publishable_key"] === "string" ? raw["publishable_key"] : void 0,
|
|
2213
|
+
card: toSavedCard(raw["card"]),
|
|
2214
|
+
alreadySaved: raw["already_saved"] === true,
|
|
2215
|
+
message: typeof raw["message"] === "string" ? raw["message"] : void 0,
|
|
2216
|
+
raw
|
|
2217
|
+
};
|
|
2218
|
+
}
|
|
2219
|
+
/**
|
|
2220
|
+
* Finish a client-confirmed setup and save the card. Idempotent on `setupIntentId`.
|
|
2221
|
+
* While the client has not finished, this throws a 400 with body
|
|
2222
|
+
* `status: "still_requires_action"`. On `500 CARD_PERSIST_FAILED` (authorised but not
|
|
2223
|
+
* recorded) retry this call with the same `setupIntentId`.
|
|
2224
|
+
*/
|
|
2225
|
+
async confirmSetup(input, opts) {
|
|
2226
|
+
if (typeof input.setupIntentId !== "string" || !input.setupIntentId.trim()) {
|
|
2227
|
+
throw invalidInput("setupIntentId", input.setupIntentId, "is required (from beginSetup)");
|
|
2228
|
+
}
|
|
2229
|
+
const raw = await this.http.post(
|
|
2230
|
+
"/api/currency-purchases/setup-intent/confirm",
|
|
2231
|
+
{ setup_intent_id: input.setupIntentId },
|
|
2232
|
+
this.auth,
|
|
2233
|
+
{ idempotent: true, signal: opts?.signal }
|
|
2234
|
+
// keyed by setup_intent_id: safe to retry
|
|
2235
|
+
);
|
|
2236
|
+
return {
|
|
2237
|
+
status: String(raw["status"] ?? ""),
|
|
2238
|
+
setupIntentId: String(raw["setup_intent_id"] ?? input.setupIntentId),
|
|
2239
|
+
card: toSavedCard(raw["card"]),
|
|
2240
|
+
alreadySaved: raw["already_saved"] === true,
|
|
2241
|
+
raw
|
|
2242
|
+
};
|
|
2243
|
+
}
|
|
2244
|
+
/**
|
|
2245
|
+
* A member's unexpired saved cards, newest first. An unknown player is `{ cards: [] }`.
|
|
2246
|
+
* The `id` is the value you pass as `playerCardId`; INVO never returns processor
|
|
2247
|
+
* identifiers for a card. Served from a short cache (about 60 s); a card saved through
|
|
2248
|
+
* `beginSetup` / `confirmSetup` appears immediately.
|
|
2249
|
+
*/
|
|
2250
|
+
async list(playerEmail, opts) {
|
|
2251
|
+
if (typeof playerEmail !== "string" || !playerEmail.trim()) {
|
|
2252
|
+
throw invalidInput("playerEmail", playerEmail, "is required");
|
|
2253
|
+
}
|
|
2254
|
+
const raw = await this.http.get(
|
|
2255
|
+
`/api/currency-purchases/player-cards?player_email=${encodeURIComponent(playerEmail)}`,
|
|
2256
|
+
this.auth,
|
|
2257
|
+
{ signal: opts?.signal }
|
|
2258
|
+
);
|
|
2259
|
+
const rows = Array.isArray(raw["cards"]) ? raw["cards"] : [];
|
|
2260
|
+
return {
|
|
2261
|
+
cards: rows.map(toSavedCard).filter((c) => c !== null),
|
|
2262
|
+
raw
|
|
2263
|
+
};
|
|
2264
|
+
}
|
|
2265
|
+
};
|
|
2266
|
+
var SandboxSubscriptionsServer = class {
|
|
2267
|
+
constructor(http, auth, clockKey) {
|
|
2268
|
+
this.http = http;
|
|
2269
|
+
this.auth = auth;
|
|
2270
|
+
this.clockKey = clockKey;
|
|
2271
|
+
}
|
|
2272
|
+
async call(subscriptionId, tool, body, opts) {
|
|
2273
|
+
assertSubscriptionId(subscriptionId);
|
|
2274
|
+
if (typeof this.clockKey !== "string" || !this.clockKey.trim()) {
|
|
2275
|
+
throw invalidInput(
|
|
2276
|
+
"sandboxClockKey",
|
|
2277
|
+
this.clockKey,
|
|
2278
|
+
'is required for invo.sandbox.subscriptions.* \u2014 pass it to new InvoServer({ sandboxClockKey }) from the sandbox console (Game Settings, "Sandbox clock key")'
|
|
2279
|
+
);
|
|
2280
|
+
}
|
|
2281
|
+
const raw = await this.http.post(
|
|
2282
|
+
// Relative to baseUrl, which already ends in /sandbox. NOT under /api.
|
|
2283
|
+
`/subscriptions/${encodeURIComponent(subscriptionId)}/${tool}`,
|
|
2284
|
+
body,
|
|
2285
|
+
this.auth,
|
|
2286
|
+
{ signal: opts?.signal, headers: { "X-Sandbox-Clock-Key": this.clockKey } }
|
|
2287
|
+
// never auto-retried
|
|
2288
|
+
);
|
|
2289
|
+
return toSandboxClockResult(raw);
|
|
2290
|
+
}
|
|
2291
|
+
/**
|
|
2292
|
+
* Make the next period due now. `intervals` 0..60, default 1. `0` makes it due without
|
|
2293
|
+
* moving the window (use it to trigger a retry). `N` on a never-paid subscription
|
|
2294
|
+
* (a trial, a fresh row) also moves the window back by up to N intervals; once anything
|
|
2295
|
+
* has been paid the window stays put (`intervalsAppliedToWindow: 0`). No window is ever
|
|
2296
|
+
* billed twice. Then `forceRenewal`, or wait for the next sweep (within a minute or two).
|
|
2297
|
+
* `409 SUBSCRIPTION_NOT_LIVE` on a terminal or pending row.
|
|
2298
|
+
*/
|
|
2299
|
+
async advanceClock(subscriptionId, intervals = 1, opts) {
|
|
2300
|
+
if (!Number.isInteger(intervals) || intervals < 0 || intervals > 60) {
|
|
2301
|
+
throw invalidInput("intervals", intervals, "must be an integer 0..60");
|
|
2302
|
+
}
|
|
2303
|
+
return this.call(subscriptionId, "advance-clock", { intervals }, opts);
|
|
2304
|
+
}
|
|
2305
|
+
/**
|
|
2306
|
+
* Run the renewal immediately. **Charges the test card** (or the Steam stand-in): the
|
|
2307
|
+
* real money path, wallet read, shortfall, mint, spend, split, `subscription.renewed`,
|
|
2308
|
+
* and on failure the real dunning. Read `engineStats` (`renewed: 1` on success). A
|
|
2309
|
+
* cancel-at-period-end row answers `action: "retired-at-period-end"`, `retired: true`.
|
|
2310
|
+
* `409 PERIOD_TOO_FAR_AHEAD` means you forced twice without advancing the clock.
|
|
2311
|
+
*/
|
|
2312
|
+
async forceRenewal(subscriptionId, opts) {
|
|
2313
|
+
return this.call(subscriptionId, "force-renewal", {}, opts);
|
|
2314
|
+
}
|
|
2315
|
+
/**
|
|
2316
|
+
* Synthesise a failed attempt and run real dunning. No charge. `outcome` defaults to
|
|
2317
|
+
* `card_declined`. Returns `retryBudgetUsed`, `retryScheduleDays` (e.g. `[2, 3, 2]`),
|
|
2318
|
+
* `retriesRemaining`. Call it four times to walk `active` through `past_due` to `expired`
|
|
2319
|
+
* and watch the events. Does not model a Steam refusal.
|
|
2320
|
+
*/
|
|
2321
|
+
async forceFailure(subscriptionId, outcome = "card_declined", options, opts) {
|
|
2322
|
+
if (!SANDBOX_FAILURE_OUTCOMES.has(outcome)) {
|
|
2323
|
+
throw invalidInput("outcome", outcome, 'must be "card_declined" | "insufficient_funds" | "error"');
|
|
2324
|
+
}
|
|
2325
|
+
const body = { outcome };
|
|
2326
|
+
if (options?.failureCode !== void 0) body["failure_code"] = options.failureCode;
|
|
2327
|
+
if (options?.failureMessage !== void 0) body["failure_message"] = options.failureMessage;
|
|
2328
|
+
return this.call(subscriptionId, "force-failure", body, opts);
|
|
2329
|
+
}
|
|
2330
|
+
/**
|
|
2331
|
+
* Synthesise a cardholder authentication challenge: moves the subscription to
|
|
2332
|
+
* `awaiting_authentication` (no charge). Returns `authChallengesUsed`,
|
|
2333
|
+
* `maxAuthChallenges` (2) and `downgradedToDecline`. It does NOT mint a confirmation
|
|
2334
|
+
* link; to exercise the link and the `subscription.authentication_required` event use a
|
|
2335
|
+
* test card that requires authentication, then `forceRenewal`.
|
|
2336
|
+
*/
|
|
2337
|
+
async forceAuthChallenge(subscriptionId, options, opts) {
|
|
2338
|
+
const body = {};
|
|
2339
|
+
if (options?.failureMessage !== void 0) body["failure_message"] = options.failureMessage;
|
|
2340
|
+
return this.call(subscriptionId, "force-auth-challenge", body, opts);
|
|
2341
|
+
}
|
|
2342
|
+
};
|
|
2343
|
+
var SandboxServer = class {
|
|
2344
|
+
constructor(http, auth, clockKey) {
|
|
2345
|
+
this.subscriptions = new SandboxSubscriptionsServer(http, auth, clockKey);
|
|
2346
|
+
}
|
|
2347
|
+
};
|
|
1182
2348
|
var InvoServer = class {
|
|
1183
2349
|
constructor(config) {
|
|
1184
2350
|
if (!config.gameSecret) throw new Error("InvoServer requires a `gameSecret`.");
|
|
@@ -1196,6 +2362,9 @@ var InvoServer = class {
|
|
|
1196
2362
|
});
|
|
1197
2363
|
this.auth = { kind: "game-secret", secret: config.gameSecret };
|
|
1198
2364
|
this.platformCommerce = new PlatformCommerceServer(this.http, this.auth);
|
|
2365
|
+
this.subscriptions = new SubscriptionsServer(this.http, this.auth);
|
|
2366
|
+
this.cards = new CardsServer(this.http, this.auth);
|
|
2367
|
+
this.sandbox = new SandboxServer(this.http, this.auth, config.sandboxClockKey);
|
|
1199
2368
|
}
|
|
1200
2369
|
/**
|
|
1201
2370
|
* Mint a short-lived, game-scoped player token to hand to the browser InvoClient.
|
|
@@ -2027,6 +3196,299 @@ var InvoServer = class {
|
|
|
2027
3196
|
);
|
|
2028
3197
|
return { approved: raw["approved"] === true, raw };
|
|
2029
3198
|
}
|
|
3199
|
+
// ---- Device approval grant (RFC 8628) — consoles, TVs, native Steam / desktop ----
|
|
3200
|
+
//
|
|
3201
|
+
// These take the PLAYER TOKEN explicitly: on a console the game server minted it and
|
|
3202
|
+
// holds it, and every call below authenticates with it — the game secret is never
|
|
3203
|
+
// sent. The grant is a FACTOR. `beginDeviceApproval` + `pollDeviceApproval` reaching
|
|
3204
|
+
// `approved` settles NOTHING; `approveWithDeviceCode` is the step that moves the money.
|
|
3205
|
+
/**
|
|
3206
|
+
* Stage 1 — start a device approval for ONE transaction (RFC 8628 §3.1/§3.2).
|
|
3207
|
+
*
|
|
3208
|
+
* Returns the grant: render `verificationUriComplete` as the QR (print `userCode`
|
|
3209
|
+
* under it for a TV with no camera), keep `deviceCode` on your server, then poll.
|
|
3210
|
+
* A repeat `begin` while an earlier grant is merely PENDING supersedes it (fresh code;
|
|
3211
|
+
* a page still open on the old one is told to scan again). A grant the player already
|
|
3212
|
+
* APPROVED blocks a new `begin` for its window with `409 DEVICE_APPROVAL_ALREADY_PENDING`
|
|
3213
|
+
* (`err.isDeviceApprovalAlreadyPending`, `err.deviceApprovalExpiresAt`) — the missing
|
|
3214
|
+
* step there is `approveWithDeviceCode`, not a new code.
|
|
3215
|
+
*
|
|
3216
|
+
* For `transfer` / `send` the backend also pushes the transaction's own approval
|
|
3217
|
+
* window past the grant's expiry, so an approval at minute nine cannot land on a
|
|
3218
|
+
* transfer that has already been refunded. Auth: the player token. `channel: "popup"`
|
|
3219
|
+
* is browser-only (`InvoClient.approveHosted`) and is refused before the network.
|
|
3220
|
+
*/
|
|
3221
|
+
async beginDeviceApproval(input, opts) {
|
|
3222
|
+
assertPlayerToken(input.playerToken);
|
|
3223
|
+
if (typeof input.transactionId !== "string" || !input.transactionId.trim()) {
|
|
3224
|
+
throw invalidInput("transactionId", input.transactionId, "is required");
|
|
3225
|
+
}
|
|
3226
|
+
assertDeviceApprovalFlow(input.flow);
|
|
3227
|
+
const channel = input.channel ?? "qr";
|
|
3228
|
+
if (!DEVICE_APPROVAL_CHANNELS.has(channel)) {
|
|
3229
|
+
throw invalidInput("channel", channel, 'must be "qr" | "app_browser" ("popup" is browser-only)');
|
|
3230
|
+
}
|
|
3231
|
+
if (channel === "popup") {
|
|
3232
|
+
throw new InvoError({
|
|
3233
|
+
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".`,
|
|
3234
|
+
code: "INVALID_INPUT",
|
|
3235
|
+
status: 0
|
|
3236
|
+
});
|
|
3237
|
+
}
|
|
3238
|
+
const raw = await this.http.post(
|
|
3239
|
+
"/api/sdk/approvals/device/begin",
|
|
3240
|
+
{ transaction_id: input.transactionId, flow: input.flow, channel },
|
|
3241
|
+
{ kind: "bearer", token: input.playerToken },
|
|
3242
|
+
// PLAYER token — never the game secret
|
|
3243
|
+
// Safe to retry: a lost-response retry supersedes the unseen pending grant with a
|
|
3244
|
+
// fresh code (one live grant per transaction + flow either way).
|
|
3245
|
+
{ idempotent: true, signal: opts?.signal }
|
|
3246
|
+
);
|
|
3247
|
+
return toDeviceApprovalGrant(raw);
|
|
3248
|
+
}
|
|
3249
|
+
/**
|
|
3250
|
+
* Stage 3 — one poll (RFC 8628 §3.4/§3.5). Call it no faster than `interval` seconds.
|
|
3251
|
+
*
|
|
3252
|
+
* Returns `status`:
|
|
3253
|
+
* - `authorization_pending` — keep polling. While a first-time phone waits on your
|
|
3254
|
+
* screen, `enrollment` is present: show "Set up INVO on <deviceLabel>? Code
|
|
3255
|
+
* <matchCode>" and answer with `confirmDeviceEnrollment`.
|
|
3256
|
+
* - `slow_down` — add 5 s to your interval, then resume.
|
|
3257
|
+
* - `approved` — **now call `approveWithDeviceCode`**. Nothing has moved yet.
|
|
3258
|
+
* - `access_denied` — the player declined; do not retry silently.
|
|
3259
|
+
* - `expired_token` — the grant lapsed; `beginDeviceApproval` again.
|
|
3260
|
+
* Throws `InvoError` for `invalid_grant` (`err.code === "invalid_grant"`: unknown code,
|
|
3261
|
+
* or not this player's — one answer for both, deliberately) and for transport failures
|
|
3262
|
+
* after the retry budget (429 / 5xx are retried: this is an idempotent read).
|
|
3263
|
+
*/
|
|
3264
|
+
async pollDeviceApproval(input, opts) {
|
|
3265
|
+
assertPlayerToken(input.playerToken);
|
|
3266
|
+
if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
|
|
3267
|
+
throw invalidInput("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
|
|
3268
|
+
}
|
|
3269
|
+
let raw;
|
|
3270
|
+
try {
|
|
3271
|
+
raw = await this.http.post(
|
|
3272
|
+
"/api/sdk/approvals/device/poll",
|
|
3273
|
+
{ device_code: input.deviceCode },
|
|
3274
|
+
{ kind: "bearer", token: input.playerToken },
|
|
3275
|
+
{ idempotent: true, signal: opts?.signal }
|
|
3276
|
+
// a read; safe to retry
|
|
3277
|
+
);
|
|
3278
|
+
} catch (err) {
|
|
3279
|
+
if (err instanceof InvoError && err.status === 400 && typeof err.code === "string" && DEVICE_POLL_OUTCOME_TOKENS.has(err.code)) {
|
|
3280
|
+
const body = err.body && typeof err.body === "object" ? err.body : {};
|
|
3281
|
+
return toDevicePollOutcome(err.code, body);
|
|
3282
|
+
}
|
|
3283
|
+
throw err;
|
|
3284
|
+
}
|
|
3285
|
+
return {
|
|
3286
|
+
status: "approved",
|
|
3287
|
+
transactionId: raw["transaction_id"],
|
|
3288
|
+
flow: raw["flow"],
|
|
3289
|
+
approvedAt: raw["approved_at"] ?? null,
|
|
3290
|
+
raw
|
|
3291
|
+
};
|
|
3292
|
+
}
|
|
3293
|
+
/**
|
|
3294
|
+
* Stage 3b — answer the on-screen match-code prompt for a first-time phone.
|
|
3295
|
+
*
|
|
3296
|
+
* `approve` = "yes, the phone I just scanned with shows this code" (the phone then
|
|
3297
|
+
* creates its INVO passkey and approves); `deny` ends the whole grant — the next poll
|
|
3298
|
+
* answers `access_denied`. Answered once: `409 DEVICE_APPROVAL_ENROLLMENT_ALREADY_DECIDED`
|
|
3299
|
+
* means the backup email got there first — take the prompt down quietly.
|
|
3300
|
+
* `409 DEVICE_APPROVAL_NO_ENROLLMENT_PENDING`: no phone has asked. Not auto-retried.
|
|
3301
|
+
*/
|
|
3302
|
+
async confirmDeviceEnrollment(input, opts) {
|
|
3303
|
+
assertPlayerToken(input.playerToken);
|
|
3304
|
+
if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
|
|
3305
|
+
throw invalidInput("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
|
|
3306
|
+
}
|
|
3307
|
+
if (input.decision !== "approve" && input.decision !== "deny") {
|
|
3308
|
+
throw invalidInput("decision", input.decision, 'must be "approve" or "deny"');
|
|
3309
|
+
}
|
|
3310
|
+
const raw = await this.http.post(
|
|
3311
|
+
"/api/sdk/approvals/device/confirm-enrollment",
|
|
3312
|
+
{ device_code: input.deviceCode, decision: input.decision },
|
|
3313
|
+
{ kind: "bearer", token: input.playerToken },
|
|
3314
|
+
{ signal: opts?.signal }
|
|
3315
|
+
// a decision — never auto-retried
|
|
3316
|
+
);
|
|
3317
|
+
return { status: String(raw["status"] ?? ""), raw };
|
|
3318
|
+
}
|
|
3319
|
+
/**
|
|
3320
|
+
* Stage 4 — THE MONEY STEP. Once the poll says `approved`, call this with the same
|
|
3321
|
+
* player token and the grant's `deviceCode`. Routes by `flow`:
|
|
3322
|
+
*
|
|
3323
|
+
* transfer → POST /api/sdk/transfers/{id}/approve
|
|
3324
|
+
* send → POST /api/sdk/send/{id}/approve
|
|
3325
|
+
* send_receipt → POST /api/sdk/send/{id}/confirm-receipt
|
|
3326
|
+
* transfer_receipt → POST /api/sdk/transfers/{id}/confirm-receipt
|
|
3327
|
+
*
|
|
3328
|
+
* The grant proves WHO approved; this call runs every gate the in-app passkey approve
|
|
3329
|
+
* runs (guardian, risk, recovery cooldown) and moves the money. A grant that is never
|
|
3330
|
+
* followed by this call moves nothing, and is consumed by nothing.
|
|
3331
|
+
*
|
|
3332
|
+
* Result: `status: "approved"` + `next: "pending_claim"` (transfer/send; `claimCode`
|
|
3333
|
+
* on a transfer) or `status: "completed"` + `amountReceived` (receipt flows). A 202
|
|
3334
|
+
* hold returns `holdReason` (money held, not refused). A repeat call after the code was
|
|
3335
|
+
* consumed returns `status: "not_pending"` with `currentStatus` and `alreadySettled`
|
|
3336
|
+
* — the backend's `TRANSACTION_NOT_PENDING` mapped into a result rather than thrown,
|
|
3337
|
+
* because for this call it is the normal answer to "did my earlier attempt land?".
|
|
3338
|
+
*
|
|
3339
|
+
* Throws `InvoError`: `err.isDeviceApprovalNotApproved` (400 — wrong/foreign code,
|
|
3340
|
+
* wrong flow, or the poll never said approved), `err.isPasskeyRecoveryCooldown` (403,
|
|
3341
|
+
* money-out after a passkey recovery — `err.retryAfterAt`), guardian terminal states
|
|
3342
|
+
* (410). Never auto-retried: the device_code is a single-use factor.
|
|
3343
|
+
*
|
|
3344
|
+
* **A FAILURE HERE IS AMBIGUOUS ABOUT THE MONEY.** The backend commits the transfer and
|
|
3345
|
+
* *then* builds its 200 by reading the transaction back, so a fault raised after that
|
|
3346
|
+
* commit answers `SEND_APPROVE_FAILED` / `TRANSFER_APPROVE_FAILED` /
|
|
3347
|
+
* `CONFIRM_RECEIPT_FAILED` (`err.isSettleFault`, `err.errorRef`) for money that already
|
|
3348
|
+
* moved. A `status === 0` (timeout, connection dropped) is ambiguous for the same
|
|
3349
|
+
* reason, and this call is deliberately not auto-retried. So on either: read
|
|
3350
|
+
* `getTransferStatus` / `getSendStatus`, or wait for the `transfer.claim_pending`
|
|
3351
|
+
* webhook, BEFORE you tell the player it failed — and never auto-start a replacement
|
|
3352
|
+
* transaction.
|
|
3353
|
+
*/
|
|
3354
|
+
async approveWithDeviceCode(input, opts) {
|
|
3355
|
+
assertPlayerToken(input.playerToken);
|
|
3356
|
+
if (typeof input.transactionId !== "string" || !input.transactionId.trim()) {
|
|
3357
|
+
throw invalidInput("transactionId", input.transactionId, "is required");
|
|
3358
|
+
}
|
|
3359
|
+
assertDeviceApprovalFlow(input.flow);
|
|
3360
|
+
if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
|
|
3361
|
+
throw invalidInput("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
|
|
3362
|
+
}
|
|
3363
|
+
let raw;
|
|
3364
|
+
try {
|
|
3365
|
+
raw = await this.http.post(
|
|
3366
|
+
deviceApprovalSettlePath(input.flow, input.transactionId),
|
|
3367
|
+
{ device_code: input.deviceCode },
|
|
3368
|
+
{ kind: "bearer", token: input.playerToken },
|
|
3369
|
+
// PLAYER token — never the game secret
|
|
3370
|
+
{ signal: opts?.signal }
|
|
3371
|
+
// NOT idempotent — the device_code is single-use; never auto-retried
|
|
3372
|
+
);
|
|
3373
|
+
} catch (err) {
|
|
3374
|
+
if (err instanceof InvoError && err.isTransactionNotPending) {
|
|
3375
|
+
const body = err.body && typeof err.body === "object" ? err.body : {};
|
|
3376
|
+
const currentStatus = err.currentTransactionStatus ?? "";
|
|
3377
|
+
return {
|
|
3378
|
+
status: "not_pending",
|
|
3379
|
+
transactionId: input.transactionId,
|
|
3380
|
+
flow: input.flow,
|
|
3381
|
+
alreadySettled: currentStatus !== "" && isPastThisStep(input.flow, currentStatus),
|
|
3382
|
+
currentStatus: currentStatus || void 0,
|
|
3383
|
+
raw: body
|
|
3384
|
+
};
|
|
3385
|
+
}
|
|
3386
|
+
throw err;
|
|
3387
|
+
}
|
|
3388
|
+
return toDeviceApprovalSettleResult(raw, input);
|
|
3389
|
+
}
|
|
3390
|
+
/**
|
|
3391
|
+
* Convenience only — stages 3 and 4 in one call, for a server that can hold the loop
|
|
3392
|
+
* open (a per-request worker, a job). Polls `pollDeviceApproval` on `interval`, adds
|
|
3393
|
+
* 5 s on `slow_down`, forwards the poll's `enrollment` to `onEnrollment` (answer with
|
|
3394
|
+
* `respond`), and on `approved` calls `approveWithDeviceCode` — THEN resolves.
|
|
3395
|
+
* `respond` is best-effort: a prompt the grant has outlived (`expired_token`,
|
|
3396
|
+
* `invalid_grant`) or that was already answered elsewhere resolves quietly rather than
|
|
3397
|
+
* rejecting, because callers fire it from UI code without awaiting it.
|
|
3398
|
+
* You still call `beginDeviceApproval` yourself first, because your game has to draw
|
|
3399
|
+
* the QR between begin and the first poll.
|
|
3400
|
+
*
|
|
3401
|
+
* Resolves `{ status: "approved", settlement }` | `denied` | `expired` | `aborted`.
|
|
3402
|
+
* Rejects on `invalid_grant`, on a refused approve (e.g. `PASSKEY_RECOVERY_COOLDOWN`),
|
|
3403
|
+
* and after 5 consecutive transport failures on the poll.
|
|
3404
|
+
*
|
|
3405
|
+
* **Record the attempt in your own store BEFORE you call this.** It blocks for as long
|
|
3406
|
+
* as the player takes and then moves money from inside the loop, so if your process
|
|
3407
|
+
* dies between the approve call and its response, a row you wrote first — plus
|
|
3408
|
+
* `getTransferStatus` / `getSendStatus` — is the only way to learn whether the money
|
|
3409
|
+
* moved. Servers that must not block a request use the three calls directly and keep
|
|
3410
|
+
* `deviceCode` in their own store.
|
|
3411
|
+
*
|
|
3412
|
+
* `respond` (handed to `onEnrollment`) is best-effort: a prompt the grant has outlived
|
|
3413
|
+
* resolves quietly rather than rejecting. Any other confirm-enrollment refusal
|
|
3414
|
+
* propagates, so `await` it if you want to see one.
|
|
3415
|
+
*/
|
|
3416
|
+
async completeDeviceApproval(input, opts) {
|
|
3417
|
+
assertPlayerToken(input.playerToken);
|
|
3418
|
+
if (typeof input.transactionId !== "string" || !input.transactionId.trim()) {
|
|
3419
|
+
throw invalidInput("transactionId", input.transactionId, "is required");
|
|
3420
|
+
}
|
|
3421
|
+
assertDeviceApprovalFlow(input.flow);
|
|
3422
|
+
if (typeof input.deviceCode !== "string" || !input.deviceCode.trim()) {
|
|
3423
|
+
throw invalidInput("deviceCode", input.deviceCode, "is required (from beginDeviceApproval)");
|
|
3424
|
+
}
|
|
3425
|
+
const signal = input.signal ?? opts?.signal;
|
|
3426
|
+
const { playerToken, deviceCode } = input;
|
|
3427
|
+
let interval = Math.max(1, Number(input.interval) || 5);
|
|
3428
|
+
let lastPoll;
|
|
3429
|
+
let lastEnrollmentKey = null;
|
|
3430
|
+
let transientFailures = 0;
|
|
3431
|
+
const MAX_TRANSIENT = 5;
|
|
3432
|
+
const respond = async (decision) => {
|
|
3433
|
+
try {
|
|
3434
|
+
await this.confirmDeviceEnrollment({ playerToken, deviceCode, decision }, { signal });
|
|
3435
|
+
} catch (err) {
|
|
3436
|
+
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")) {
|
|
3437
|
+
return;
|
|
3438
|
+
}
|
|
3439
|
+
throw err;
|
|
3440
|
+
}
|
|
3441
|
+
};
|
|
3442
|
+
const publishEnrollment = (e) => {
|
|
3443
|
+
if (!input.onEnrollment) return;
|
|
3444
|
+
const key = e ? `${e.state}|${e.matchCode}|${e.deviceLabel}|${e.recovery}` : null;
|
|
3445
|
+
if (key === lastEnrollmentKey) return;
|
|
3446
|
+
lastEnrollmentKey = key;
|
|
3447
|
+
input.onEnrollment(e ?? null, respond);
|
|
3448
|
+
};
|
|
3449
|
+
for (; ; ) {
|
|
3450
|
+
await sleepFor(interval * 1e3, signal);
|
|
3451
|
+
if (signal?.aborted) return { status: "aborted", lastPoll };
|
|
3452
|
+
let poll;
|
|
3453
|
+
try {
|
|
3454
|
+
poll = await this.pollDeviceApproval({ playerToken, deviceCode }, { signal });
|
|
3455
|
+
} catch (err) {
|
|
3456
|
+
if (signal?.aborted) return { status: "aborted", lastPoll };
|
|
3457
|
+
const transient = err instanceof InvoError && (err.status === 0 || err.status === 429 || err.status >= 500);
|
|
3458
|
+
if (transient && ++transientFailures < MAX_TRANSIENT) {
|
|
3459
|
+
const ra = err instanceof InvoError && err.status === 429 ? err.retryAfter : void 0;
|
|
3460
|
+
if (typeof ra === "number" && ra > interval) interval = ra;
|
|
3461
|
+
continue;
|
|
3462
|
+
}
|
|
3463
|
+
throw err;
|
|
3464
|
+
}
|
|
3465
|
+
transientFailures = 0;
|
|
3466
|
+
lastPoll = poll;
|
|
3467
|
+
switch (poll.status) {
|
|
3468
|
+
case "authorization_pending":
|
|
3469
|
+
if (poll.interval) interval = poll.interval;
|
|
3470
|
+
publishEnrollment(poll.enrollment);
|
|
3471
|
+
continue;
|
|
3472
|
+
case "slow_down":
|
|
3473
|
+
interval = Math.max(interval + 5, poll.interval ?? 0);
|
|
3474
|
+
continue;
|
|
3475
|
+
case "expired_token":
|
|
3476
|
+
publishEnrollment(void 0);
|
|
3477
|
+
return { status: "expired", lastPoll };
|
|
3478
|
+
case "access_denied":
|
|
3479
|
+
publishEnrollment(void 0);
|
|
3480
|
+
return { status: "denied", lastPoll };
|
|
3481
|
+
case "approved": {
|
|
3482
|
+
publishEnrollment(void 0);
|
|
3483
|
+
const settlement = await this.approveWithDeviceCode(
|
|
3484
|
+
{ playerToken, transactionId: input.transactionId, flow: input.flow, deviceCode },
|
|
3485
|
+
{ signal }
|
|
3486
|
+
);
|
|
3487
|
+
return { status: "approved", settlement, lastPoll };
|
|
3488
|
+
}
|
|
3489
|
+
}
|
|
3490
|
+
}
|
|
3491
|
+
}
|
|
2030
3492
|
toInitiateResult(raw) {
|
|
2031
3493
|
const vm = raw["verification_method"];
|
|
2032
3494
|
const guardian = raw["guardian_approval"];
|
|
@@ -2039,9 +3501,14 @@ var InvoServer = class {
|
|
|
2039
3501
|
}
|
|
2040
3502
|
};
|
|
2041
3503
|
|
|
3504
|
+
exports.CardsServer = CardsServer;
|
|
2042
3505
|
exports.InvoError = InvoError;
|
|
2043
3506
|
exports.InvoServer = InvoServer;
|
|
2044
3507
|
exports.PlatformCommerceServer = PlatformCommerceServer;
|
|
3508
|
+
exports.SDK_VERSION = SDK_VERSION;
|
|
3509
|
+
exports.SandboxServer = SandboxServer;
|
|
3510
|
+
exports.SandboxSubscriptionsServer = SandboxSubscriptionsServer;
|
|
3511
|
+
exports.SubscriptionsServer = SubscriptionsServer;
|
|
2045
3512
|
exports.createWebhookHandler = createWebhookHandler;
|
|
2046
3513
|
exports.verifyWebhook = verifyWebhook;
|
|
2047
3514
|
exports.verifyWebhookAsync = verifyWebhookAsync;
|