@invonetwork/web-sdk 3.29.1 → 3.30.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.
Files changed (36) hide show
  1. package/CHANGELOG.md +1432 -1397
  2. package/README.md +2954 -2923
  3. package/dist/{chunk-YONO4JE5.js → chunk-664RAO2T.js} +25 -5
  4. package/dist/chunk-BIK6UXY7.js +6 -0
  5. package/dist/chunk-QDHOPJFL.js +1634 -0
  6. package/dist/{chunk-VP3OK4J4.js → chunk-TSTP2CWA.js} +471 -3
  7. package/dist/game-server.cjs +269 -2
  8. package/dist/game-server.d.cts +40 -6
  9. package/dist/game-server.d.ts +40 -6
  10. package/dist/game-server.js +252 -7
  11. package/dist/game.cjs +2677 -9
  12. package/dist/game.d.cts +78 -4
  13. package/dist/game.d.ts +78 -4
  14. package/dist/game.js +558 -3
  15. package/dist/hosted-approval-DcY4U2RN.d.cts +96 -0
  16. package/dist/hosted-approval-DiKmtjEh.d.ts +96 -0
  17. package/dist/index.d.cts +7 -96
  18. package/dist/index.d.ts +7 -96
  19. package/dist/index.js +2 -1635
  20. package/dist/loyalty-events-CmDw2ZoR.d.cts +40 -0
  21. package/dist/loyalty-events-CmDw2ZoR.d.ts +40 -0
  22. package/dist/{server-BYY6tM6X.d.ts → server-B0mvlGFY.d.ts} +17 -2
  23. package/dist/{server-Bxo_wgHx.d.cts → server-DEh9wjF2.d.cts} +17 -2
  24. package/dist/server.cjs +22 -1
  25. package/dist/server.d.cts +4 -3
  26. package/dist/server.d.ts +4 -3
  27. package/dist/server.js +3 -4
  28. package/dist/{types-_lIm74kd.d.cts → types-BTbZicgj.d.cts} +1 -40
  29. package/dist/{types-_lIm74kd.d.ts → types-BTbZicgj.d.ts} +1 -40
  30. package/dist/{types-CLyJDuXd.d.cts → types-jUxfYjiD.d.cts} +64 -1
  31. package/dist/{types-CLyJDuXd.d.ts → types-jUxfYjiD.d.ts} +64 -1
  32. package/dist/{version-DOaYbHu7.d.cts → version-DfVkILOj.d.cts} +1 -1
  33. package/dist/{version-DOaYbHu7.d.ts → version-DfVkILOj.d.ts} +1 -1
  34. package/package.json +91 -91
  35. package/dist/chunk-6CN236QH.js +0 -473
  36. package/dist/chunk-VOGZZ6QS.js +0 -6
@@ -1,9 +1,8 @@
1
- import { isDemoKey, SANDBOX_BASE_URL, PRODUCTION_BASE_URL, InvoServer, resolveEnvironment, verifyWebhook } from './chunk-YONO4JE5.js';
2
- export { DEMO_KEY_PREFIX, EnvironmentUnknownError, InvoServer, PRODUCTION_BASE_URL, SANDBOX_BASE_URL, baseUrlForKey, isDemoKey, resolveEnvironment, verifyInvoSignature } from './chunk-YONO4JE5.js';
3
- import './chunk-6CN236QH.js';
4
- export { SDK_VERSION } from './chunk-VOGZZ6QS.js';
5
- import { InvoError } from './chunk-VP3OK4J4.js';
6
- export { InvoError } from './chunk-VP3OK4J4.js';
1
+ import { isDemoKey, SANDBOX_BASE_URL, PRODUCTION_BASE_URL, InvoServer, resolveEnvironment, verifyWebhook } from './chunk-664RAO2T.js';
2
+ export { DEMO_KEY_PREFIX, EnvironmentUnknownError, InvoServer, PRODUCTION_BASE_URL, SANDBOX_BASE_URL, baseUrlForKey, isDemoKey, resolveEnvironment, verifyInvoSignature } from './chunk-664RAO2T.js';
3
+ export { SDK_VERSION } from './chunk-BIK6UXY7.js';
4
+ import { InvoError } from './chunk-TSTP2CWA.js';
5
+ export { InvoError } from './chunk-TSTP2CWA.js';
7
6
  import { createHash, randomBytes } from 'crypto';
8
7
  import { promises, readFileSync, mkdirSync, writeFileSync } from 'fs';
9
8
  import * as path from 'path';
@@ -150,6 +149,19 @@ var GameServerError = class extends Error {
150
149
  this.requestId = requestId;
151
150
  }
152
151
  };
152
+ function moveDetails(raw) {
153
+ const d = (raw?.["send_details"] ?? raw?.["transfer_details"] ?? {}) || {};
154
+ const pick = (...keys) => {
155
+ for (const k of keys) if (d[k] !== void 0 && d[k] !== null && d[k] !== "") return String(d[k]);
156
+ return null;
157
+ };
158
+ const toId = pick("receiving_game_id", "target_game_id");
159
+ const fromId = pick("sending_game_id", "source_game_id");
160
+ const toName = pick("receiving_game", "target_game", "target_game_name");
161
+ const fromName = pick("sending_game", "source_game", "source_game_name");
162
+ const sameGame = fromId !== null && toId !== null ? fromId === toId : toName !== null && toName === fromName;
163
+ return { sameGame, destinationName: toName, currencyName: pick("currency", "currency_name") ?? (typeof raw?.["currency_name"] === "string" ? raw["currency_name"] : null) };
164
+ }
153
165
  function validateEconomy(economy) {
154
166
  const problems = [];
155
167
  if (!economy?.premium?.name) problems.push("premium.name is required");
@@ -255,6 +267,7 @@ function createInvoGameServer(options) {
255
267
  maxPerMinute: economy.soft.maxEarnPerMinute ?? 1e4
256
268
  };
257
269
  const iso = () => now().toISOString();
270
+ const environmentNow = options.environment ?? (() => options.sandbox ? "sandbox" : "production");
258
271
  function toPlayer(p) {
259
272
  return { id: p.id, email: p.email, name: p.name, phoneMasked: maskPhone(p.phone) };
260
273
  }
@@ -642,6 +655,223 @@ function createInvoGameServer(options) {
642
655
  throw err;
643
656
  }
644
657
  }
658
+ function transferStatus() {
659
+ const demo = !!options.demoProjectId;
660
+ const environment = environmentNow();
661
+ const setting = options.transfers ?? "auto";
662
+ let reason = null;
663
+ if (setting === false) reason = "off";
664
+ else if (setting === "auto" && !demo) {
665
+ if (environment === "resolving") reason = "checking";
666
+ else if (environment === "sandbox") reason = "sandbox";
667
+ }
668
+ return {
669
+ enabled: reason === null,
670
+ reason,
671
+ demo,
672
+ scope: demo ? "project" : "network",
673
+ recipientFields: demo ? { email: "required", phone: "hidden" } : { email: "optional", phone: "required" },
674
+ apiBaseUrl: reason === null ? options.playerApiBaseUrl?.() ?? null : null,
675
+ approval: demo ? "sandbox" : "passkey"
676
+ };
677
+ }
678
+ function requireTransfers() {
679
+ const status = transferStatus();
680
+ if (!status.enabled) {
681
+ throw new GameServerError(
682
+ 403,
683
+ "TRANSFERS_DISABLED",
684
+ status.reason === "sandbox" ? "Transfers are off on this sandbox key. Set INVO_TRANSFERS=on to try them, or use your production key." : status.reason === "checking" ? "Checking this game's INVO key. Try again in a moment." : "Transfers are switched off for this game."
685
+ );
686
+ }
687
+ return status;
688
+ }
689
+ async function transferToken(request) {
690
+ const status = requireTransfers();
691
+ const { player } = await sessionPlayer(request);
692
+ try {
693
+ const minted = await invo.mintPlayerToken({ playerEmail: player.email });
694
+ return json(200, { token: minted.token, expiresAt: minted.expiresAt, apiBaseUrl: status.apiBaseUrl }, { "cache-control": "no-store" });
695
+ } catch (err) {
696
+ if (err instanceof InvoError) throw fromInvoError(err);
697
+ throw err;
698
+ }
699
+ }
700
+ async function startTransfer(request) {
701
+ requireTransfers();
702
+ const { player } = await sessionPlayer(request);
703
+ const body = await readJson(request);
704
+ const kind = body["kind"] === "send" ? "send" : "transfer";
705
+ const amount = String(body["amount"] ?? "").trim();
706
+ if (!/^\d{1,9}(\.\d{1,2})?$/.test(amount) || Number(amount) <= 0) {
707
+ throw new GameServerError(400, "INVALID_AMOUNT", "Enter an amount greater than zero.");
708
+ }
709
+ const targetGameId = body["targetGameId"];
710
+ if ((typeof targetGameId !== "string" || !targetGameId.trim()) && typeof targetGameId !== "number") {
711
+ throw new GameServerError(400, "INVALID_GAME", "Pick a game to send to.");
712
+ }
713
+ const requestId = typeof body["clientRequestId"] === "string" ? body["clientRequestId"] : "";
714
+ if (requestId && !REQUEST_ID.test(requestId)) {
715
+ throw new GameServerError(400, "INVALID_REQUEST_ID", "clientRequestId must be 8 to 64 letters, digits, - or _.");
716
+ }
717
+ const clientRequestId = requestId || randomBytes(16).toString("hex");
718
+ const typedEmail = typeof body["recipientEmail"] === "string" ? body["recipientEmail"].trim().toLowerCase() : "";
719
+ if (typedEmail && !EMAIL.test(typedEmail)) throw new GameServerError(400, "INVALID_EMAIL", "Check the recipient's email address.");
720
+ let senderPhone;
721
+ let recipientEmail;
722
+ let recipientPhone;
723
+ const demoPid = options.demoProjectId;
724
+ if (demoPid) {
725
+ if (!typedEmail) {
726
+ throw new GameServerError(400, "RECIPIENT_EMAIL_REQUIRED", "Enter your friend's email: the one they sign in to this game with.");
727
+ }
728
+ recipientEmail = toDemoEmail(typedEmail, demoPid);
729
+ if (recipientEmail === player.email) throw new GameServerError(400, "RECIPIENT_IS_SENDER", "Pick someone other than yourself.");
730
+ recipientPhone = demoPhoneFor(recipientEmail);
731
+ senderPhone = demoPhoneFor(player.email);
732
+ } else {
733
+ recipientPhone = typeof body["recipientPhone"] === "string" ? body["recipientPhone"].replace(/[\s()-]/g, "") : "";
734
+ if (!E164.test(recipientPhone)) {
735
+ throw new GameServerError(400, "INVALID_PHONE", "Enter the recipient's phone in international format, e.g. +15555550111.");
736
+ }
737
+ recipientEmail = typedEmail || void 0;
738
+ const typedSender = typeof body["senderPhone"] === "string" ? body["senderPhone"].replace(/[\s()-]/g, "") : "";
739
+ senderPhone = typedSender || player.phone || "";
740
+ if (!E164.test(senderPhone)) throw new GameServerError(400, "SENDER_PHONE_REQUIRED", "Add the phone number on your INVO account to send.");
741
+ }
742
+ try {
743
+ const started = kind === "send" ? await invo.initiateSend({
744
+ clientRequestId,
745
+ senderPlayerName: player.name,
746
+ senderPlayerEmail: player.email,
747
+ senderPlayerPhone: senderPhone,
748
+ receiverPlayerPhone: recipientPhone,
749
+ ...recipientEmail ? { receiverPlayerEmail: recipientEmail } : {},
750
+ receivingGameId: targetGameId,
751
+ amount
752
+ }) : await invo.initiateTransfer({
753
+ clientRequestId,
754
+ sourcePlayerName: player.name,
755
+ sourcePlayerEmail: player.email,
756
+ sourcePlayerPhone: senderPhone,
757
+ targetPlayerPhone: recipientPhone,
758
+ ...recipientEmail ? { targetPlayerEmail: recipientEmail } : {},
759
+ targetGameId,
760
+ amount
761
+ });
762
+ log("info", "transfer started", { kind, playerId: player.id, transactionId: started.transactionId });
763
+ if (demoPid && recipientEmail) {
764
+ const details = moveDetails(started.raw);
765
+ const move = {
766
+ transactionId: started.transactionId,
767
+ kind,
768
+ fromPlayerId: player.id,
769
+ fromName: player.name,
770
+ toEmail: recipientEmail,
771
+ amount,
772
+ currencyName: details.currencyName ?? economy.premium.name,
773
+ sameGame: details.sameGame,
774
+ destinationName: details.destinationName ?? "",
775
+ status: "started",
776
+ claimCode: null,
777
+ claimCodeExpiresAt: null,
778
+ createdAt: iso()
779
+ };
780
+ await store.transact((s) => void ((s.demoMoves ?? (s.demoMoves = {}))[move.transactionId] = move));
781
+ }
782
+ const answer = {
783
+ transactionId: started.transactionId,
784
+ kind,
785
+ guardianPending: Boolean(started.guardianApproval),
786
+ playerToken: started.playerToken ?? null,
787
+ approval: demoPid ? "sandbox" : "passkey"
788
+ };
789
+ return json(200, answer, { "cache-control": "no-store" });
790
+ } catch (err) {
791
+ if (err instanceof InvoError) throw fromInvoError(err);
792
+ throw err;
793
+ }
794
+ }
795
+ function requireDemo() {
796
+ requireTransfers();
797
+ if (!options.demoProjectId) {
798
+ throw new GameServerError(409, "PASSKEY_REQUIRED", "Approve and collect on INVO's page with your passkey.");
799
+ }
800
+ return options.demoProjectId;
801
+ }
802
+ async function approveMove(request, id) {
803
+ requireDemo();
804
+ const { player } = await sessionPlayer(request);
805
+ const move = await store.read((s) => s.demoMoves?.[id] ?? null);
806
+ if (!move || move.fromPlayerId !== player.id) throw new GameServerError(404, "TRANSFER_NOT_FOUND", "That transfer isn't yours to approve.");
807
+ if (move.status !== "started") return json(200, { status: "approved", claimCode: move.claimCode, replayed: true });
808
+ try {
809
+ const approved = await invo.sandbox.approveDemoMove(id, move.kind);
810
+ await store.transact((s) => {
811
+ const m = s.demoMoves?.[id];
812
+ if (m && m.status === "started") {
813
+ m.status = "approved";
814
+ m.claimCode = approved.claimCode;
815
+ m.claimCodeExpiresAt = approved.claimCodeExpiresAt;
816
+ }
817
+ });
818
+ log("info", "demo transfer approved", { kind: move.kind, playerId: player.id, transactionId: id });
819
+ return json(200, { status: "approved", claimCode: approved.claimCode, replayed: false });
820
+ } catch (err) {
821
+ if (err instanceof InvoError) throw fromInvoError(err);
822
+ throw err;
823
+ }
824
+ }
825
+ async function pendingMoves(request) {
826
+ requireDemo();
827
+ const { player } = await sessionPlayer(request);
828
+ const nowMs = now().getTime();
829
+ const moves = await store.read((s) => Object.values(s.demoMoves ?? {}));
830
+ const pending = moves.filter(
831
+ (m) => m.toEmail === player.email && m.status === "approved" && m.sameGame && (!m.claimCodeExpiresAt || Date.parse(m.claimCodeExpiresAt) > nowMs) || m.fromPlayerId === player.id && m.status === "started"
832
+ ).sort((a, b) => b.createdAt.localeCompare(a.createdAt)).map((m) => {
833
+ const incoming = m.toEmail === player.email;
834
+ return {
835
+ transferId: m.transactionId,
836
+ kind: incoming ? "receiving_confirm" : "identity_gate",
837
+ flow: m.kind,
838
+ amount: m.amount,
839
+ currency: m.currencyName,
840
+ counterpartyGame: incoming ? `${m.fromName}, in this game` : m.destinationName || "another game",
841
+ expiresAt: m.claimCodeExpiresAt,
842
+ stepUpRequired: false,
843
+ held: false,
844
+ holdReason: null,
845
+ raw: {}
846
+ };
847
+ });
848
+ return json(200, { pending }, { "cache-control": "no-store" });
849
+ }
850
+ async function collectMove(request, id) {
851
+ requireDemo();
852
+ const { player } = await sessionPlayer(request);
853
+ const move = await store.read((s) => s.demoMoves?.[id] ?? null);
854
+ if (!move || move.toEmail !== player.email) throw new GameServerError(404, "TRANSFER_NOT_FOUND", "There's nothing to collect with that id.");
855
+ if (move.status === "collected") return json(200, { status: "collected", replayed: true, wallet: await readWallet(player) });
856
+ if (move.status !== "approved" || !move.claimCode) throw new GameServerError(409, "NOT_APPROVED_YET", "The sender hasn't approved this one yet.");
857
+ if (!move.sameGame) throw new GameServerError(409, "OTHER_GAME", `This one is waiting in ${move.destinationName || "another game"}; collect it there.`);
858
+ try {
859
+ if (move.kind === "send") {
860
+ await invo.claimCurrency({ claimCode: move.claimCode, receiverPlayerName: player.name, receiverPlayerEmail: player.email, receiverPlayerPhone: demoPhoneFor(player.email) });
861
+ } else {
862
+ throw new GameServerError(409, "OTHER_GAME", "Collect this transfer in the game it was sent to.");
863
+ }
864
+ } catch (err) {
865
+ if (err instanceof InvoError) throw fromInvoError(err);
866
+ throw err;
867
+ }
868
+ await store.transact((s) => {
869
+ const m = s.demoMoves?.[id];
870
+ if (m) m.status = "collected";
871
+ });
872
+ log("info", "demo transfer collected", { kind: move.kind, playerId: player.id, transactionId: id });
873
+ return json(200, { status: "collected", replayed: false, wallet: await readWallet(player) });
874
+ }
645
875
  async function route(request, sub, method) {
646
876
  if (method === "GET" && sub === "/health") return json(200, { ok: true, setupRequired: false, sandbox: options.sandbox, demo: !!options.demoProjectId });
647
877
  if (method === "GET" && sub === "/catalog") return catalog();
@@ -659,6 +889,15 @@ function createInvoGameServer(options) {
659
889
  if (method === "POST" && sub === "/earn") return earn(request);
660
890
  if (method === "POST" && sub === "/events") return events(request);
661
891
  if (method === "GET" && sub === "/rewards") return rewards(request);
892
+ if (method === "GET" && sub === "/transfers/status") return json(200, transferStatus());
893
+ if (method === "POST" && sub === "/transfers/token") return transferToken(request);
894
+ if (method === "POST" && sub === "/transfers") return startTransfer(request);
895
+ if (method === "GET" && sub === "/transfers/pending") return pendingMoves(request);
896
+ const move = /^\/transfers\/([^/]+)\/(approve|collect)$/.exec(sub);
897
+ if (method === "POST" && move) {
898
+ const id = decodeURIComponent(move[1]);
899
+ return move[2] === "approve" ? approveMove(request, id) : collectMove(request, id);
900
+ }
662
901
  return json(404, { error: { code: "NOT_FOUND", message: "No such route." } });
663
902
  }
664
903
  return {
@@ -729,7 +968,13 @@ function invoGameServerFromEnv(options) {
729
968
  },
730
969
  basePath: options.basePath,
731
970
  publicUrl: env["PUBLIC_URL"] || void 0,
732
- log: options.log
971
+ log: options.log,
972
+ transfers: (() => {
973
+ const t = env["INVO_TRANSFERS"]?.trim().toLowerCase();
974
+ return t === "on" ? true : t === "off" ? false : "auto";
975
+ })(),
976
+ environment: envNow,
977
+ playerApiBaseUrl: () => explicitBase || (state.environment === "production" ? PRODUCTION_BASE_URL : state.environment === "sandbox" ? SANDBOX_BASE_URL : null)
733
978
  };
734
979
  const server = createInvoGameServer(serverOptions);
735
980
  return { server, missing, sandbox: sandboxNow(), environment: envNow(), demo };