@getpara/core-sdk 2.0.0-alpha.62 → 2.0.0-alpha.64

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.
@@ -45,6 +45,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
45
45
  var wallet_exports = {};
46
46
  __export(wallet_exports, {
47
47
  WalletSchemeTypeMap: () => WalletSchemeTypeMap,
48
+ currentWalletIdsEq: () => currentWalletIdsEq,
48
49
  entityToWallet: () => entityToWallet,
49
50
  getEquivalentTypes: () => getEquivalentTypes,
50
51
  getSchemes: () => getSchemes,
@@ -146,9 +147,23 @@ function mergeCurrentWalletIds(original, additional) {
146
147
  function newUuid() {
147
148
  return uuid.v4();
148
149
  }
150
+ function currentWalletIdsEq(a, b) {
151
+ if (!a && !b) return true;
152
+ if (!a || !b) return false;
153
+ const aKeys = Object.keys(a);
154
+ const bKeys = Object.keys(b);
155
+ if (aKeys.length !== bKeys.length) return false;
156
+ return aKeys.every((key) => {
157
+ var _a, _b;
158
+ const aIds = ((_a = a[key]) == null ? void 0 : _a.sort()) || [];
159
+ const bIds = ((_b = b[key]) == null ? void 0 : _b.sort()) || [];
160
+ return aIds.length === bIds.length && aIds.every((id, index) => id === bIds[index]);
161
+ });
162
+ }
149
163
  // Annotate the CommonJS export names for ESM import in node:
150
164
  0 && (module.exports = {
151
165
  WalletSchemeTypeMap,
166
+ currentWalletIdsEq,
152
167
  entityToWallet,
153
168
  getEquivalentTypes,
154
169
  getSchemes,
@@ -0,0 +1,38 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var window_exports = {};
19
+ __export(window_exports, {
20
+ isPortal: () => isPortal
21
+ });
22
+ module.exports = __toCommonJS(window_exports);
23
+ var import_url = require("./url.js");
24
+ function isPortal(ctx, env) {
25
+ var _a, _b;
26
+ if (typeof window === "undefined") return false;
27
+ const normalizedUrl = (_b = (_a = window.location) == null ? void 0 : _a.host) == null ? void 0 : _b.replace("getpara", "usecapsule");
28
+ const isOnPortalDomain = (0, import_url.getPortalBaseURL)(env ? { env } : ctx).includes(normalizedUrl);
29
+ if (!isOnPortalDomain) return false;
30
+ const isInIframe = window.parent !== window && !window.opener;
31
+ const isInPopup = window.opener && window.parent === window;
32
+ const isDirectAccess = !window.opener && !window.parent;
33
+ return isInIframe || isInPopup || isDirectAccess;
34
+ }
35
+ // Annotate the CommonJS export names for ESM import in node:
36
+ 0 && (module.exports = {
37
+ isPortal
38
+ });
@@ -8,7 +8,7 @@ import {
8
8
  __spreadProps,
9
9
  __spreadValues
10
10
  } from "./chunk-W5CT3TVS.js";
11
- var _authInfo, _ParaCore_instances, assertPartner_fn, guestWalletIds_get, guestWalletIdsArray_get, toAuthInfo_fn, setAuthInfo_fn, getPartner_fn, assertIsLinkingAccount_fn, assertIsLinkingAccountOrStart_fn, getOAuthUrl_fn, createPregenWallet_fn, _isCreateGuestWalletsPending, prepareAuthState_fn, prepareDoneState_fn, prepareVerificationState_fn, prepareLoginState_fn, prepareSignUpState_fn;
11
+ var _authInfo, _ParaCore_instances, assertPartner_fn, guestWalletIds_get, guestWalletIdsArray_get, toAuthInfo_fn, setAuthInfo_fn, getPartner_fn, assertIsLinkingAccount_fn, assertIsLinkingAccountOrStart_fn, getOAuthUrl_fn, waitForLoginProcess_fn, createPregenWallet_fn, _isCreateGuestWalletsPending, prepareAuthState_fn, prepareDoneState_fn, prepareVerificationState_fn, prepareLoginState_fn, prepareSignUpState_fn;
12
12
  import { Buffer as NodeBuffer } from "buffer";
13
13
  if (typeof global !== "undefined") {
14
14
  global.Buffer = global.Buffer || NodeBuffer;
@@ -70,7 +70,9 @@ import {
70
70
  WalletSchemeTypeMap,
71
71
  shortenUrl,
72
72
  isServerAuthState,
73
- splitPhoneNumber
73
+ splitPhoneNumber,
74
+ currentWalletIdsEq,
75
+ isPortal
74
76
  } from "./utils/index.js";
75
77
  import { TransactionReviewDenied, TransactionReviewTimeout } from "./errors.js";
76
78
  import * as constants from "./constants.js";
@@ -80,6 +82,7 @@ const _ParaCore = class _ParaCore {
80
82
  __privateAdd(this, _ParaCore_instances);
81
83
  this.popupWindow = null;
82
84
  __privateAdd(this, _authInfo);
85
+ // Track expected wallet IDs during wallet switching
83
86
  this.isNativePasskey = false;
84
87
  this.isReady = false;
85
88
  this.accountLinkInProgress = void 0;
@@ -98,20 +101,33 @@ const _ParaCore = class _ParaCore {
98
101
  */
99
102
  this.externalWallets = {};
100
103
  this.onRampPopup = void 0;
104
+ this.nonPersistedStorageKeys = [];
101
105
  this.localStorageGetItem = (key) => {
102
- return this.platformUtils.localStorage.get(key);
106
+ var _a;
107
+ if (!((_a = this.nonPersistedStorageKeys) != null ? _a : []).includes(key)) {
108
+ return this.platformUtils.localStorage.get(key);
109
+ }
103
110
  };
104
111
  this.localStorageSetItem = (key, value) => {
105
- return this.platformUtils.localStorage.set(key, value);
112
+ var _a;
113
+ if (!((_a = this.nonPersistedStorageKeys) != null ? _a : []).includes(key)) {
114
+ return this.platformUtils.localStorage.set(key, value);
115
+ }
106
116
  };
107
117
  this.localStorageRemoveItem = (key) => {
108
118
  return this.platformUtils.localStorage.removeItem(key);
109
119
  };
110
120
  this.sessionStorageGetItem = (key) => {
111
- return this.platformUtils.sessionStorage.get(key);
121
+ var _a;
122
+ if (!((_a = this.nonPersistedStorageKeys) != null ? _a : []).includes(key)) {
123
+ return this.platformUtils.sessionStorage.get(key);
124
+ }
112
125
  };
113
126
  this.sessionStorageSetItem = (key, value) => {
114
- return this.platformUtils.sessionStorage.set(key, value);
127
+ var _a;
128
+ if (!((_a = this.nonPersistedStorageKeys) != null ? _a : []).includes(key)) {
129
+ return this.platformUtils.sessionStorage.set(key, value);
130
+ }
115
131
  };
116
132
  this.sessionStorageRemoveItem = (key) => {
117
133
  return this.platformUtils.sessionStorage.removeItem(key);
@@ -268,7 +284,7 @@ const _ParaCore = class _ParaCore {
268
284
  this.setExternalWallets(_externalWallets);
269
285
  };
270
286
  this.initializeWorker = () => __async(this, null, function* () {
271
- if (!this.isWorkerInitialized && !this.ctx.disableWebSockets && !this.ctx.disableWorkers) {
287
+ if (!this.isWorkerInitialized && !this.ctx.disableWebSockets && !this.ctx.disableWorkers && !this.isPortal()) {
272
288
  try {
273
289
  this.isWorkerInitialized = true;
274
290
  yield this.platformUtils.initializeWorker(this.ctx);
@@ -592,15 +608,7 @@ const _ParaCore = class _ParaCore {
592
608
  };
593
609
  }
594
610
  isPortal(envOverride) {
595
- var _a;
596
- if (typeof window === "undefined") return false;
597
- return !!((_a = window.location) == null ? void 0 : _a.host) && getPortalBaseURL(envOverride ? { env: envOverride } : this.ctx).includes(window.location.host);
598
- }
599
- isRecoveryPortal(envOverride) {
600
- var _a, _b;
601
- if (typeof window === "undefined") return false;
602
- const normalizedUrl = (_b = (_a = window.location) == null ? void 0 : _a.host) == null ? void 0 : _b.replace("getpara", "usecapsule");
603
- return !!normalizedUrl && getPortalBaseURL(envOverride ? { env: envOverride } : this.ctx).includes(normalizedUrl);
611
+ return isPortal(this.ctx, envOverride);
604
612
  }
605
613
  isParaConnect() {
606
614
  var _a;
@@ -725,14 +733,26 @@ const _ParaCore = class _ParaCore {
725
733
  constructPortalUrl(_0) {
726
734
  return __async(this, arguments, function* (type, opts = {}) {
727
735
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
728
- const [isCreate, isLogin, isOnRamp, isOAuth, isOAuthCallback, isTelegramLogin, isFarcasterLogin] = [
736
+ const [
737
+ isCreate,
738
+ isLogin,
739
+ isOnRamp,
740
+ isOAuth,
741
+ isOAuthCallback,
742
+ isTelegramLogin,
743
+ isFarcasterLogin,
744
+ isAddNewCredential,
745
+ isSwitchWallets
746
+ ] = [
729
747
  ["createAuth", "createPassword", "createPIN"].includes(type),
730
- ["loginAuth", "loginPassword", "loginPIN", "loginOTP"].includes(type),
748
+ ["loginAuth", "loginPassword", "loginPIN", "loginOTP", "switchWallets"].includes(type),
731
749
  type === "onRamp",
732
750
  type === "oAuth",
733
751
  type === "oAuthCallback",
734
752
  ["telegramLogin", "telegramLoginVerify"].includes(type),
735
- type === "loginFarcaster"
753
+ type === "loginFarcaster",
754
+ type === "addNewCredential",
755
+ type === "switchWallets"
736
756
  ];
737
757
  if (isOAuth && !opts.oAuthMethod) {
738
758
  throw new Error("oAuthMethod is required for oAuth portal URLs");
@@ -807,6 +827,14 @@ const _ParaCore = class _ParaCore {
807
827
  path = "/auth/farcaster";
808
828
  break;
809
829
  }
830
+ case "switchWallets": {
831
+ path = `/auth/wallets`;
832
+ break;
833
+ }
834
+ case "addNewCredential": {
835
+ path = "/auth/add-new-credential";
836
+ break;
837
+ }
810
838
  default: {
811
839
  throw new Error(`invalid URL type ${type}`);
812
840
  }
@@ -825,8 +853,9 @@ const _ParaCore = class _ParaCore {
825
853
  encryptionKey: getPublicKeyHex(this.loginEncryptionKeyPair),
826
854
  sessionId
827
855
  };
828
- const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
856
+ const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
829
857
  apiKey: this.ctx.apiKey,
858
+ origin: typeof window !== "undefined" ? window.location.origin : void 0,
830
859
  partnerId: partner == null ? void 0 : partner.id,
831
860
  portalFont: ((_b = opts.portalTheme) == null ? void 0 : _b.font) || ((_c = this.portalTheme) == null ? void 0 : _c.font) || (partner == null ? void 0 : partner.font),
832
861
  portalBorderRadius: ((_d = opts.portalTheme) == null ? void 0 : _d.borderRadius) || ((_e = this.portalTheme) == null ? void 0 : _e.borderRadius),
@@ -838,12 +867,12 @@ const _ParaCore = class _ParaCore {
838
867
  portalTextColor: this.portalTextColor,
839
868
  portalPrimaryButtonTextColor: this.portalPrimaryButtonTextColor,
840
869
  isForNewDevice: opts.isForNewDevice ? opts.isForNewDevice.toString() : void 0
841
- }, isCreate || isLogin ? __spreadProps(__spreadValues({
870
+ }, this.authInfo && (isCreate || isLogin || isAddNewCredential || isOAuthCallback || isSwitchWallets) ? __spreadProps(__spreadValues({
842
871
  authInfo: JSON.stringify(this.authInfo)
843
872
  }, isPhone(this.authInfo.auth) ? splitPhoneNumber(this.authInfo.auth.phone) : this.authInfo.auth), {
844
873
  pfpUrl: this.authInfo.pfpUrl,
845
874
  displayName: this.authInfo.displayName
846
- }) : {}), isOnRamp ? { origin: typeof window !== "undefined" ? window.location.origin : void 0, email: this.email } : {}), isLogin || isOAuth || isOAuthCallback || isTelegramLogin || isFarcasterLogin ? __spreadProps(__spreadValues({
875
+ }) : {}), isOnRamp ? { email: this.email } : {}), isLogin || isOAuth || isOAuthCallback || isTelegramLogin || isFarcasterLogin || isAddNewCredential ? __spreadProps(__spreadValues({
847
876
  sessionId: thisDevice.sessionId,
848
877
  encryptionKey: thisDevice.encryptionKey
849
878
  }, opts.newDevice ? {
@@ -853,7 +882,10 @@ const _ParaCore = class _ParaCore {
853
882
  pregenIds: JSON.stringify(this.pregenIds)
854
883
  }) : {}), isOAuth || isOAuthCallback || isFarcasterLogin ? {
855
884
  appScheme: opts.appScheme
856
- } : {}), isTelegramLogin ? { isEmbed: "true" } : {}), opts.params || {});
885
+ } : {}), isTelegramLogin ? { isEmbed: "true" } : {}), isSwitchWallets ? __spreadValues(__spreadValues({}, this.currentWalletIds ? { currentWalletIds: JSON.stringify(this.currentWalletIds) } : {}), this.userId ? { userId: this.userId } : {}) : {}), opts.params || {}), isAddNewCredential ? __spreadProps(__spreadValues({}, opts.addNewCredentialType && { addNewCredentialType: opts.addNewCredentialType.toString() }), {
886
+ addNewCredentialPasskeyId: opts.addNewCredentialPasskeyId,
887
+ addNewCredentialPasswordId: opts.addNewCredentialPasswordId
888
+ }) : {});
857
889
  const url = constructUrl({ base, path, params });
858
890
  if (opts.shorten) {
859
891
  return shortenUrl(this.ctx, url);
@@ -897,7 +929,7 @@ const _ParaCore = class _ParaCore {
897
929
  throw error;
898
930
  }
899
931
  if (!this.partner || ((_a = this.partner) == null ? void 0 : _a.id) !== session.partnerId || !supportedWalletTypesEq(((_b = this.partner) == null ? void 0 : _b.supportedWalletTypes) || [], session.supportedWalletTypes) || (((_c = this.partner) == null ? void 0 : _c.cosmosPrefix) || "cosmos") !== session.cosmosPrefix) {
900
- if (!session.partnerId && !this.isRecoveryPortal()) {
932
+ if (!session.partnerId && !this.isPortal()) {
901
933
  this.displayModalError(
902
934
  `Invalid API Key. Please ensure you have a valid API key for the current environment: ${(_d = this.ctx.env) == null ? void 0 : _d.toUpperCase()}.`
903
935
  );
@@ -928,6 +960,9 @@ Need help? Visit: https://docs.getpara.com or contact support
928
960
  yield __privateMethod(this, _ParaCore_instances, getPartner_fn).call(this, session.partnerId);
929
961
  }
930
962
  }
963
+ if (session.currentWalletIds && !currentWalletIdsEq(session.currentWalletIds, this.currentWalletIds)) {
964
+ yield this.setCurrentWalletIds(session.currentWalletIds);
965
+ }
931
966
  return session;
932
967
  });
933
968
  }
@@ -1388,6 +1423,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1388
1423
  if (!wallet) return null;
1389
1424
  return {
1390
1425
  id: wallet.id,
1426
+ partner: wallet.partner,
1391
1427
  type,
1392
1428
  address: this.getDisplayAddress(id, { addressType: type }),
1393
1429
  name: wallet.name
@@ -1498,7 +1534,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1498
1534
  }
1499
1535
  populateWalletAddresses() {
1500
1536
  return __async(this, null, function* () {
1501
- const res = yield this.ctx.client.getWallets(this.userId, true);
1537
+ const res = yield (this.isPortal() ? this.ctx.client.getAllWallets : this.ctx.client.getWallets)(this.userId, true);
1502
1538
  const wallets = res.data.wallets;
1503
1539
  wallets.forEach((entity) => {
1504
1540
  if (this.wallets[entity.id]) {
@@ -1767,6 +1803,9 @@ Need help? Visit: https://docs.getpara.com or contact support
1767
1803
  if (this.externalWalletConnectionType === "VERIFICATION") {
1768
1804
  return isSessionActive;
1769
1805
  }
1806
+ if (this.walletSwitchIds) {
1807
+ return isSessionActive;
1808
+ }
1770
1809
  return isSessionActive && (this.isNoWalletConfig || this.currentWalletIdsArray.length > 0 && this.currentWalletIdsArray.reduce((acc, [id]) => acc && !!this.wallets[id], true));
1771
1810
  });
1772
1811
  }
@@ -1780,6 +1819,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1780
1819
  }
1781
1820
  /**
1782
1821
  * Get the auth methods available to an existing user
1822
+ * @deprecated Use supportedUserAuthMethods instead
1783
1823
  */
1784
1824
  supportedAuthMethods(auth) {
1785
1825
  return __async(this, null, function* () {
@@ -1798,6 +1838,37 @@ Need help? Visit: https://docs.getpara.com or contact support
1798
1838
  return authMethods;
1799
1839
  });
1800
1840
  }
1841
+ /**
1842
+ * Get the auth methods available to an existing user
1843
+ */
1844
+ supportedUserAuthMethods() {
1845
+ return __async(this, null, function* () {
1846
+ yield this.assertIsAuthSet();
1847
+ const { supportedAuthMethods, hasPasswordWithoutPIN } = yield this.ctx.client.getSupportedAuthMethodsV2(
1848
+ this.authInfo.auth
1849
+ );
1850
+ const authMethods = /* @__PURE__ */ new Set();
1851
+ for (const type of supportedAuthMethods) {
1852
+ switch (type) {
1853
+ case "PASSWORD":
1854
+ if (hasPasswordWithoutPIN) {
1855
+ authMethods.add(AuthMethod.PASSWORD);
1856
+ }
1857
+ break;
1858
+ case "PASSKEY":
1859
+ authMethods.add(AuthMethod.PASSKEY);
1860
+ break;
1861
+ case "PIN":
1862
+ authMethods.add(AuthMethod.PIN);
1863
+ break;
1864
+ case "BASIC_LOGIN":
1865
+ authMethods.add(AuthMethod.BASIC_LOGIN);
1866
+ break;
1867
+ }
1868
+ }
1869
+ return authMethods;
1870
+ });
1871
+ }
1801
1872
  /**
1802
1873
  * Get hints associated with the users stored biometrics.
1803
1874
  * @deprecated
@@ -2091,61 +2162,26 @@ Need help? Visit: https://docs.getpara.com or contact support
2091
2162
  * @param {boolean} [opts.skipSessionRefresh] whether to skip refreshing the session.
2092
2163
  * @returns {Object} `{ isComplete: boolean; isError: boolean; needsWallet: boolean; partnerId: string; }` the result data
2093
2164
  **/
2094
- waitForLogin() {
2095
- return __async(this, arguments, function* ({
2096
- isCanceled = () => false,
2097
- onCancel,
2098
- onPoll,
2099
- skipSessionRefresh = false
2100
- } = {}) {
2101
- const startedAt = Date.now();
2102
- return new Promise((resolve, reject) => {
2103
- (() => __async(this, null, function* () {
2104
- var _a;
2105
- if (!this.isExternalWalletAuth) {
2106
- this.externalWallets = {};
2107
- }
2108
- while (true) {
2109
- if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
2110
- dispatchEvent(ParaEvent.LOGIN_EVENT, { isComplete: false }, "failed to setup user");
2111
- onCancel == null ? void 0 : onCancel();
2112
- return reject("canceled");
2113
- }
2114
- yield new Promise((resolve2) => setTimeout(resolve2, constants.POLLING_INTERVAL_MS));
2115
- try {
2116
- let session = yield this.touchSession();
2117
- if (!session.isAuthenticated) {
2118
- onPoll == null ? void 0 : onPoll();
2119
- continue;
2120
- }
2121
- session = yield this.userSetupAfterLogin();
2122
- const needsWallet = (_a = session.needsWallet) != null ? _a : false;
2123
- if (!needsWallet) {
2124
- if (this.currentWalletIdsArray.length === 0) {
2125
- onPoll == null ? void 0 : onPoll();
2126
- continue;
2127
- }
2128
- }
2129
- const fetchedWallets = yield this.fetchWallets();
2130
- const tempSharesRes = yield this.getTransmissionKeyShares();
2131
- if (tempSharesRes.data.temporaryShares.length === fetchedWallets.length) {
2132
- yield this.setupAfterLogin({ temporaryShares: tempSharesRes.data.temporaryShares, skipSessionRefresh });
2133
- yield this.claimPregenWallets();
2134
- const resp = {
2135
- needsWallet: needsWallet || Object.values(this.wallets).length === 0,
2136
- partnerId: session.partnerId
2137
- };
2138
- dispatchEvent(ParaEvent.LOGIN_EVENT, resp);
2139
- return resolve(resp);
2140
- }
2141
- onPoll == null ? void 0 : onPoll();
2142
- } catch (err) {
2143
- console.error(err);
2144
- onPoll == null ? void 0 : onPoll();
2145
- }
2146
- }
2147
- }))();
2148
- });
2165
+ waitForLogin(args) {
2166
+ return __async(this, null, function* () {
2167
+ return yield __privateMethod(this, _ParaCore_instances, waitForLoginProcess_fn).call(this, args);
2168
+ });
2169
+ }
2170
+ waitForWalletSwitching(args) {
2171
+ return __async(this, null, function* () {
2172
+ return yield __privateMethod(this, _ParaCore_instances, waitForLoginProcess_fn).call(this, __spreadProps(__spreadValues({}, args), { isSwitchingWallets: true }));
2173
+ });
2174
+ }
2175
+ /**
2176
+ * Gets the switch wallets URL for wallet selection.
2177
+ * The authMethod is automatically included in the URL if available.
2178
+ *
2179
+ * @returns {Promise<{ url: string; authMethod: TAuthMethod }>} The switch wallets URL and authMethod
2180
+ */
2181
+ getSwitchWalletsUrl() {
2182
+ return __async(this, null, function* () {
2183
+ const url = yield this.constructPortalUrl("switchWallets");
2184
+ return url;
2149
2185
  });
2150
2186
  }
2151
2187
  /**
@@ -2275,7 +2311,7 @@ Need help? Visit: https://docs.getpara.com or contact support
2275
2311
  break;
2276
2312
  }
2277
2313
  ++maxPolls;
2278
- const res = yield this.ctx.client.getWallets(this.userId);
2314
+ const res = yield (this.isPortal() ? this.ctx.client.getAllWallets : this.ctx.client.getWallets)(this.userId);
2279
2315
  const wallet = res.data.wallets.find((w) => w.id === walletId);
2280
2316
  if (wallet && wallet.address) {
2281
2317
  return;
@@ -3142,49 +3178,80 @@ Need help? Visit: https://docs.getpara.com or contact support
3142
3178
  }
3143
3179
  getNewCredentialAndUrl() {
3144
3180
  return __async(this, arguments, function* ({
3145
- authMethod = "PASSKEY",
3181
+ authMethod: optsAuthMethod,
3146
3182
  isForNewDevice = false,
3147
3183
  portalTheme,
3148
3184
  shorten = false
3149
3185
  } = {}) {
3186
+ const userAuthMethods = yield this.supportedUserAuthMethods();
3187
+ const isEnclaveUser = userAuthMethods.has(AuthMethod.BASIC_LOGIN);
3188
+ if (isEnclaveUser) {
3189
+ isForNewDevice = true;
3190
+ }
3191
+ const authMethods = optsAuthMethod ? [optsAuthMethod] : isForNewDevice ? ["PASSKEY", "PIN", "PASSWORD"] : ["PASSKEY"];
3150
3192
  this.assertIsAuthSet();
3151
- let credentialId, urlType;
3152
- switch (authMethod) {
3153
- case "PASSKEY":
3154
- ({
3155
- data: { id: credentialId }
3156
- } = yield this.ctx.client.addSessionPublicKey(this.userId, {
3157
- status: AuthMethodStatus.PENDING,
3158
- type: PublicKeyType.WEB
3159
- }));
3160
- urlType = "createAuth";
3161
- break;
3162
- case "PASSWORD":
3193
+ const canAddPasswordOrPIN = !userAuthMethods.has(AuthMethod.PASSWORD) && !userAuthMethods.has(AuthMethod.PIN);
3194
+ let passkeyId, passwordId, urlType;
3195
+ if (authMethods.includes("PASSKEY") && (yield this.isPasskeySupported())) {
3196
+ ({
3197
+ data: { id: passkeyId }
3198
+ } = yield this.ctx.client.addSessionPublicKey(this.userId, {
3199
+ status: AuthMethodStatus.PENDING,
3200
+ type: PublicKeyType.WEB
3201
+ }));
3202
+ urlType = "createAuth";
3203
+ }
3204
+ if (authMethods.includes("PASSWORD")) {
3205
+ if (!canAddPasswordOrPIN) {
3206
+ if (optsAuthMethod === "PASSWORD") throw new Error("A user cannot have more than one password or PIN.");
3207
+ } else {
3163
3208
  ({
3164
- data: { id: credentialId }
3209
+ data: { id: passwordId }
3165
3210
  } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
3166
3211
  status: AuthMethodStatus.PENDING
3167
3212
  }));
3168
3213
  urlType = "createPassword";
3169
- break;
3170
- case "PIN":
3214
+ }
3215
+ }
3216
+ if (authMethods.includes("PIN")) {
3217
+ if (!canAddPasswordOrPIN) {
3218
+ if (optsAuthMethod === "PIN") throw new Error("A user cannot have more than one password or PIN.");
3219
+ } else {
3171
3220
  ({
3172
- data: { id: credentialId }
3221
+ data: { id: passwordId }
3173
3222
  } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
3174
3223
  status: AuthMethodStatus.PENDING
3175
3224
  }));
3176
3225
  urlType = "createPIN";
3177
- break;
3226
+ }
3227
+ }
3228
+ const credentialId = passkeyId != null ? passkeyId : passwordId;
3229
+ if (this.isNativePasskey && authMethods.includes("PASSKEY")) {
3230
+ return { credentialId };
3178
3231
  }
3179
- const url = this.isNativePasskey && urlType === "createAuth" ? void 0 : yield this.constructPortalUrl(urlType, {
3232
+ const { sessionId } = yield this.touchSession();
3233
+ const url = yield this.constructPortalUrl(isForNewDevice ? "addNewCredential" : urlType, {
3180
3234
  isForNewDevice,
3181
3235
  pathId: credentialId,
3182
3236
  portalTheme,
3183
- shorten
3237
+ shorten,
3238
+ sessionId: isForNewDevice ? sessionId : void 0,
3239
+ addNewCredentialType: optsAuthMethod,
3240
+ addNewCredentialPasskeyId: passkeyId,
3241
+ addNewCredentialPasswordId: passwordId
3184
3242
  });
3185
3243
  return __spreadValues({ credentialId }, url ? { url } : {});
3186
3244
  });
3187
3245
  }
3246
+ addCredential(_0) {
3247
+ return __async(this, arguments, function* ({ authMethod }) {
3248
+ if (authMethod === "PASSKEY" && !(yield this.isPasskeySupported())) {
3249
+ throw new Error("Passkeys are not supported.");
3250
+ }
3251
+ const { url } = yield this.getNewCredentialAndUrl({ isForNewDevice: true, authMethod });
3252
+ return url;
3253
+ });
3254
+ }
3188
3255
  /**
3189
3256
  * Returns a Para Portal URL for logging in with a WebAuth passkey, password, PIN or OTP.
3190
3257
  * @param {Object} opts the options object
@@ -3525,7 +3592,8 @@ getOAuthUrl_fn = function(_0) {
3525
3592
  appScheme,
3526
3593
  accountLinkInProgress,
3527
3594
  sessionLookupId,
3528
- encryptionKey
3595
+ encryptionKey,
3596
+ portalCallbackParams
3529
3597
  }) {
3530
3598
  if (!accountLinkInProgress && !this.isPortal()) {
3531
3599
  return yield this.constructPortalUrl("oAuth", { sessionId: sessionLookupId, oAuthMethod: method, appScheme });
@@ -3539,13 +3607,14 @@ getOAuthUrl_fn = function(_0) {
3539
3607
  path: `/auth/${method.toLowerCase()}`,
3540
3608
  params: __spreadProps(__spreadValues({
3541
3609
  apiKey: this.ctx.apiKey,
3610
+ origin: typeof window !== "undefined" ? window.location.origin : void 0,
3542
3611
  sessionLookupId,
3543
3612
  portalSessionLookupId,
3544
3613
  appScheme
3545
3614
  }, accountLinkInProgress ? {
3546
3615
  linkedAccountId: this.accountLinkInProgress.id
3547
3616
  } : {}), {
3548
- callback: !accountLinkInProgress && (yield this.constructPortalUrl("oAuthCallback", {
3617
+ callback: !accountLinkInProgress && (yield this.constructPortalUrl("oAuthCallback", __spreadValues({
3549
3618
  sessionId: sessionLookupId,
3550
3619
  oAuthMethod: method,
3551
3620
  appScheme,
@@ -3553,11 +3622,97 @@ getOAuthUrl_fn = function(_0) {
3553
3622
  sessionId: sessionLookupId,
3554
3623
  encryptionKey
3555
3624
  }
3556
- }))
3625
+ }, this.isPortal() && { params: portalCallbackParams })))
3557
3626
  })
3558
3627
  });
3559
3628
  });
3560
3629
  };
3630
+ waitForLoginProcess_fn = function() {
3631
+ return __async(this, arguments, function* ({
3632
+ isCanceled = () => false,
3633
+ onCancel,
3634
+ onPoll,
3635
+ skipSessionRefresh = false,
3636
+ isSwitchingWallets = false
3637
+ } = {}) {
3638
+ const startedAt = Date.now();
3639
+ return new Promise((resolve, reject) => {
3640
+ (() => __async(this, null, function* () {
3641
+ var _a;
3642
+ if (!this.isExternalWalletAuth && !isSwitchingWallets) {
3643
+ this.externalWallets = {};
3644
+ }
3645
+ while (true) {
3646
+ if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
3647
+ if (isSwitchingWallets) {
3648
+ this.walletSwitchIds = void 0;
3649
+ } else {
3650
+ dispatchEvent(ParaEvent.LOGIN_EVENT, { isComplete: false }, "failed to setup user");
3651
+ }
3652
+ onCancel == null ? void 0 : onCancel();
3653
+ return reject("canceled");
3654
+ }
3655
+ yield new Promise((resolve2) => setTimeout(resolve2, constants.POLLING_INTERVAL_MS));
3656
+ try {
3657
+ let session = yield this.touchSession();
3658
+ const shouldContinuePolling = !isSwitchingWallets && !session.isAuthenticated || isSwitchingWallets && !this.walletSwitchIds;
3659
+ if (shouldContinuePolling) {
3660
+ onPoll == null ? void 0 : onPoll();
3661
+ continue;
3662
+ }
3663
+ session = yield this.userSetupAfterLogin();
3664
+ const needsWallet = (_a = session.needsWallet) != null ? _a : false;
3665
+ if (isSwitchingWallets) {
3666
+ if (this.walletSwitchIds) {
3667
+ const walletIdsMatch = currentWalletIdsEq(session.currentWalletIds, this.walletSwitchIds);
3668
+ if (!walletIdsMatch) {
3669
+ onPoll == null ? void 0 : onPoll();
3670
+ continue;
3671
+ }
3672
+ } else {
3673
+ onPoll == null ? void 0 : onPoll();
3674
+ continue;
3675
+ }
3676
+ } else if (!needsWallet) {
3677
+ if (this.currentWalletIdsArray.length === 0) {
3678
+ onPoll == null ? void 0 : onPoll();
3679
+ continue;
3680
+ }
3681
+ }
3682
+ const tempSharesRes = yield this.getTransmissionKeyShares();
3683
+ let hasSharesForCurrentWallets;
3684
+ if (!isSwitchingWallets) {
3685
+ const fetchedWallets = yield this.fetchWallets();
3686
+ hasSharesForCurrentWallets = tempSharesRes.data.temporaryShares.length === fetchedWallets.length;
3687
+ } else {
3688
+ hasSharesForCurrentWallets = this.currentWalletIdsArray.every(([walletId]) => {
3689
+ return tempSharesRes.data.temporaryShares.some((share) => share.walletId === walletId);
3690
+ });
3691
+ }
3692
+ if (hasSharesForCurrentWallets) {
3693
+ yield this.setupAfterLogin({ temporaryShares: tempSharesRes.data.temporaryShares, skipSessionRefresh });
3694
+ yield this.claimPregenWallets();
3695
+ const resp = {
3696
+ needsWallet: needsWallet || Object.values(this.wallets).length === 0,
3697
+ partnerId: session.partnerId
3698
+ };
3699
+ if (isSwitchingWallets) {
3700
+ this.walletSwitchIds = void 0;
3701
+ } else {
3702
+ dispatchEvent(ParaEvent.LOGIN_EVENT, resp);
3703
+ }
3704
+ return resolve(resp);
3705
+ }
3706
+ onPoll == null ? void 0 : onPoll();
3707
+ } catch (err) {
3708
+ console.error(err);
3709
+ onPoll == null ? void 0 : onPoll();
3710
+ }
3711
+ }
3712
+ }))();
3713
+ });
3714
+ });
3715
+ };
3561
3716
  createPregenWallet_fn = function(opts) {
3562
3717
  return __async(this, null, function* () {
3563
3718
  var _a, _b;
@@ -1,5 +1,5 @@
1
1
  import "./chunk-W5CT3TVS.js";
2
- const PARA_CORE_VERSION = "2.0.0-alpha.62";
2
+ const PARA_CORE_VERSION = "2.0.0-alpha.64";
3
3
  const PREFIX = "@CAPSULE/";
4
4
  const PARA_PREFIX = "@PARA/";
5
5
  const LOCAL_STORAGE_AUTH_INFO = `${PREFIX}authInfo`;
@@ -17,6 +17,7 @@ const LOCAL_STORAGE_CURRENT_WALLET_IDS = `${PREFIX}currentWalletIds`;
17
17
  const LOCAL_STORAGE_SESSION_COOKIE = `${PREFIX}sessionCookie`;
18
18
  const LOCAL_STORAGE_ENCLAVE_JWT = `${PREFIX}enclaveJwt`;
19
19
  const LOCAL_STORAGE_ENCLAVE_REFRESH_JWT = `${PREFIX}enclaveRefreshJwt`;
20
+ const LOCAL_STORAGE_AUTH_METHOD = `${PREFIX}authMethod`;
20
21
  const SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR = `${PREFIX}loginEncryptionKeyPair`;
21
22
  const POLLING_INTERVAL_MS = 2e3;
22
23
  const SHORT_POLLING_INTERVAL_MS = 1e3;
@@ -27,6 +28,7 @@ export {
27
28
  ACCOUNT_LINK_CONFLICT,
28
29
  EXTERNAL_WALLET_CONNECTION_ONLY_USER_ID,
29
30
  LOCAL_STORAGE_AUTH_INFO,
31
+ LOCAL_STORAGE_AUTH_METHOD,
30
32
  LOCAL_STORAGE_COUNTRY_CODE,
31
33
  LOCAL_STORAGE_CURRENT_WALLET_IDS,
32
34
  LOCAL_STORAGE_ED25519_WALLETS,