@getpara/core-sdk 2.0.0-alpha.63 → 2.0.0-alpha.65

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.
@@ -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
+ this.isSwitchingWallets = false;
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,28 @@ 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
+ isExportPrivateKey
747
+ ] = [
729
748
  ["createAuth", "createPassword", "createPIN"].includes(type),
730
- ["loginAuth", "loginPassword", "loginPIN", "loginOTP"].includes(type),
749
+ ["loginAuth", "loginPassword", "loginPIN", "loginOTP", "switchWallets"].includes(type),
731
750
  type === "onRamp",
732
751
  type === "oAuth",
733
752
  type === "oAuthCallback",
734
753
  ["telegramLogin", "telegramLoginVerify"].includes(type),
735
- type === "loginFarcaster"
754
+ type === "loginFarcaster",
755
+ type === "addNewCredential",
756
+ type === "switchWallets",
757
+ type === "exportPrivateKey"
736
758
  ];
737
759
  if (isOAuth && !opts.oAuthMethod) {
738
760
  throw new Error("oAuthMethod is required for oAuth portal URLs");
@@ -741,7 +763,7 @@ const _ParaCore = class _ParaCore {
741
763
  this.assertIsAuthSet();
742
764
  }
743
765
  let sessionId = opts.sessionId;
744
- if ((isLogin || isOnRamp || isTelegramLogin || isFarcasterLogin) && !sessionId) {
766
+ if ((isLogin || isOnRamp || isTelegramLogin || isFarcasterLogin || isExportPrivateKey) && !sessionId) {
745
767
  const session = yield this.touchSession(true);
746
768
  sessionId = session.sessionId;
747
769
  }
@@ -807,6 +829,18 @@ const _ParaCore = class _ParaCore {
807
829
  path = "/auth/farcaster";
808
830
  break;
809
831
  }
832
+ case "switchWallets": {
833
+ path = `/auth/wallets`;
834
+ break;
835
+ }
836
+ case "addNewCredential": {
837
+ path = "/auth/add-new-credential";
838
+ break;
839
+ }
840
+ case "exportPrivateKey": {
841
+ path = `/web/users/${this.userId}/private-key/${opts.pathId}`;
842
+ break;
843
+ }
810
844
  default: {
811
845
  throw new Error(`invalid URL type ${type}`);
812
846
  }
@@ -825,8 +859,9 @@ const _ParaCore = class _ParaCore {
825
859
  encryptionKey: getPublicKeyHex(this.loginEncryptionKeyPair),
826
860
  sessionId
827
861
  };
828
- const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
862
+ const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
829
863
  apiKey: this.ctx.apiKey,
864
+ origin: typeof window !== "undefined" ? window.location.origin : void 0,
830
865
  partnerId: partner == null ? void 0 : partner.id,
831
866
  portalFont: ((_b = opts.portalTheme) == null ? void 0 : _b.font) || ((_c = this.portalTheme) == null ? void 0 : _c.font) || (partner == null ? void 0 : partner.font),
832
867
  portalBorderRadius: ((_d = opts.portalTheme) == null ? void 0 : _d.borderRadius) || ((_e = this.portalTheme) == null ? void 0 : _e.borderRadius),
@@ -838,12 +873,12 @@ const _ParaCore = class _ParaCore {
838
873
  portalTextColor: this.portalTextColor,
839
874
  portalPrimaryButtonTextColor: this.portalPrimaryButtonTextColor,
840
875
  isForNewDevice: opts.isForNewDevice ? opts.isForNewDevice.toString() : void 0
841
- }, isCreate || isLogin ? __spreadProps(__spreadValues({
876
+ }, this.authInfo && (isCreate || isLogin || isAddNewCredential || isOAuthCallback || isSwitchWallets || isExportPrivateKey) ? __spreadProps(__spreadValues({
842
877
  authInfo: JSON.stringify(this.authInfo)
843
878
  }, isPhone(this.authInfo.auth) ? splitPhoneNumber(this.authInfo.auth.phone) : this.authInfo.auth), {
844
879
  pfpUrl: this.authInfo.pfpUrl,
845
880
  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({
881
+ }) : {}), isOnRamp ? { email: this.email } : {}), isLogin || isOAuth || isOAuthCallback || isTelegramLogin || isFarcasterLogin || isAddNewCredential || isExportPrivateKey ? __spreadProps(__spreadValues({
847
882
  sessionId: thisDevice.sessionId,
848
883
  encryptionKey: thisDevice.encryptionKey
849
884
  }, opts.newDevice ? {
@@ -853,7 +888,10 @@ const _ParaCore = class _ParaCore {
853
888
  pregenIds: JSON.stringify(this.pregenIds)
854
889
  }) : {}), isOAuth || isOAuthCallback || isFarcasterLogin ? {
855
890
  appScheme: opts.appScheme
856
- } : {}), isTelegramLogin ? { isEmbed: "true" } : {}), opts.params || {});
891
+ } : {}), 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() }), {
892
+ addNewCredentialPasskeyId: opts.addNewCredentialPasskeyId,
893
+ addNewCredentialPasswordId: opts.addNewCredentialPasswordId
894
+ }) : {});
857
895
  const url = constructUrl({ base, path, params });
858
896
  if (opts.shorten) {
859
897
  return shortenUrl(this.ctx, url);
@@ -897,7 +935,7 @@ const _ParaCore = class _ParaCore {
897
935
  throw error;
898
936
  }
899
937
  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()) {
938
+ if (!session.partnerId && !this.isPortal()) {
901
939
  this.displayModalError(
902
940
  `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
941
  );
@@ -928,6 +966,9 @@ Need help? Visit: https://docs.getpara.com or contact support
928
966
  yield __privateMethod(this, _ParaCore_instances, getPartner_fn).call(this, session.partnerId);
929
967
  }
930
968
  }
969
+ if (session.currentWalletIds && !currentWalletIdsEq(session.currentWalletIds, this.currentWalletIds)) {
970
+ yield this.setCurrentWalletIds(session.currentWalletIds);
971
+ }
931
972
  return session;
932
973
  });
933
974
  }
@@ -1388,6 +1429,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1388
1429
  if (!wallet) return null;
1389
1430
  return {
1390
1431
  id: wallet.id,
1432
+ partner: wallet.partner,
1391
1433
  type,
1392
1434
  address: this.getDisplayAddress(id, { addressType: type }),
1393
1435
  name: wallet.name
@@ -1498,7 +1540,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1498
1540
  }
1499
1541
  populateWalletAddresses() {
1500
1542
  return __async(this, null, function* () {
1501
- const res = yield this.ctx.client.getWallets(this.userId, true);
1543
+ const res = yield (this.isPortal() ? this.ctx.client.getAllWallets : this.ctx.client.getWallets)(this.userId, true);
1502
1544
  const wallets = res.data.wallets;
1503
1545
  wallets.forEach((entity) => {
1504
1546
  if (this.wallets[entity.id]) {
@@ -1767,6 +1809,9 @@ Need help? Visit: https://docs.getpara.com or contact support
1767
1809
  if (this.externalWalletConnectionType === "VERIFICATION") {
1768
1810
  return isSessionActive;
1769
1811
  }
1812
+ if (this.isSwitchingWallets) {
1813
+ return isSessionActive;
1814
+ }
1770
1815
  return isSessionActive && (this.isNoWalletConfig || this.currentWalletIdsArray.length > 0 && this.currentWalletIdsArray.reduce((acc, [id]) => acc && !!this.wallets[id], true));
1771
1816
  });
1772
1817
  }
@@ -1780,6 +1825,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1780
1825
  }
1781
1826
  /**
1782
1827
  * Get the auth methods available to an existing user
1828
+ * @deprecated Use supportedUserAuthMethods instead
1783
1829
  */
1784
1830
  supportedAuthMethods(auth) {
1785
1831
  return __async(this, null, function* () {
@@ -1798,6 +1844,37 @@ Need help? Visit: https://docs.getpara.com or contact support
1798
1844
  return authMethods;
1799
1845
  });
1800
1846
  }
1847
+ /**
1848
+ * Get the auth methods available to an existing user
1849
+ */
1850
+ supportedUserAuthMethods() {
1851
+ return __async(this, null, function* () {
1852
+ yield this.assertIsAuthSet();
1853
+ const { supportedAuthMethods, hasPasswordWithoutPIN } = yield this.ctx.client.getSupportedAuthMethodsV2(
1854
+ this.authInfo.auth
1855
+ );
1856
+ const authMethods = /* @__PURE__ */ new Set();
1857
+ for (const type of supportedAuthMethods) {
1858
+ switch (type) {
1859
+ case "PASSWORD":
1860
+ if (hasPasswordWithoutPIN) {
1861
+ authMethods.add(AuthMethod.PASSWORD);
1862
+ }
1863
+ break;
1864
+ case "PASSKEY":
1865
+ authMethods.add(AuthMethod.PASSKEY);
1866
+ break;
1867
+ case "PIN":
1868
+ authMethods.add(AuthMethod.PIN);
1869
+ break;
1870
+ case "BASIC_LOGIN":
1871
+ authMethods.add(AuthMethod.BASIC_LOGIN);
1872
+ break;
1873
+ }
1874
+ }
1875
+ return authMethods;
1876
+ });
1877
+ }
1801
1878
  /**
1802
1879
  * Get hints associated with the users stored biometrics.
1803
1880
  * @deprecated
@@ -2091,61 +2168,26 @@ Need help? Visit: https://docs.getpara.com or contact support
2091
2168
  * @param {boolean} [opts.skipSessionRefresh] whether to skip refreshing the session.
2092
2169
  * @returns {Object} `{ isComplete: boolean; isError: boolean; needsWallet: boolean; partnerId: string; }` the result data
2093
2170
  **/
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
- });
2171
+ waitForLogin(args) {
2172
+ return __async(this, null, function* () {
2173
+ return yield __privateMethod(this, _ParaCore_instances, waitForLoginProcess_fn).call(this, args);
2174
+ });
2175
+ }
2176
+ waitForWalletSwitching(args) {
2177
+ return __async(this, null, function* () {
2178
+ return yield __privateMethod(this, _ParaCore_instances, waitForLoginProcess_fn).call(this, __spreadProps(__spreadValues({}, args), { isSwitchingWallets: true }));
2179
+ });
2180
+ }
2181
+ /**
2182
+ * Gets the switch wallets URL for wallet selection.
2183
+ * The authMethod is automatically included in the URL if available.
2184
+ *
2185
+ * @returns {Promise<{ url: string; authMethod: TAuthMethod }>} The switch wallets URL and authMethod
2186
+ */
2187
+ getSwitchWalletsUrl() {
2188
+ return __async(this, null, function* () {
2189
+ const url = yield this.constructPortalUrl("switchWallets");
2190
+ return url;
2149
2191
  });
2150
2192
  }
2151
2193
  /**
@@ -2275,7 +2317,7 @@ Need help? Visit: https://docs.getpara.com or contact support
2275
2317
  break;
2276
2318
  }
2277
2319
  ++maxPolls;
2278
- const res = yield this.ctx.client.getWallets(this.userId);
2320
+ const res = yield (this.isPortal() ? this.ctx.client.getAllWallets : this.ctx.client.getWallets)(this.userId);
2279
2321
  const wallet = res.data.wallets.find((w) => w.id === walletId);
2280
2322
  if (wallet && wallet.address) {
2281
2323
  return;
@@ -3142,49 +3184,80 @@ Need help? Visit: https://docs.getpara.com or contact support
3142
3184
  }
3143
3185
  getNewCredentialAndUrl() {
3144
3186
  return __async(this, arguments, function* ({
3145
- authMethod = "PASSKEY",
3187
+ authMethod: optsAuthMethod,
3146
3188
  isForNewDevice = false,
3147
3189
  portalTheme,
3148
3190
  shorten = false
3149
3191
  } = {}) {
3192
+ const userAuthMethods = yield this.supportedUserAuthMethods();
3193
+ const isEnclaveUser = userAuthMethods.has(AuthMethod.BASIC_LOGIN);
3194
+ if (isEnclaveUser) {
3195
+ isForNewDevice = true;
3196
+ }
3197
+ const authMethods = optsAuthMethod ? [optsAuthMethod] : isForNewDevice ? ["PASSKEY", "PIN", "PASSWORD"] : ["PASSKEY"];
3150
3198
  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":
3199
+ const canAddPasswordOrPIN = !userAuthMethods.has(AuthMethod.PASSWORD) && !userAuthMethods.has(AuthMethod.PIN);
3200
+ let passkeyId, passwordId, urlType;
3201
+ if (authMethods.includes("PASSKEY") && (yield this.isPasskeySupported())) {
3202
+ ({
3203
+ data: { id: passkeyId }
3204
+ } = yield this.ctx.client.addSessionPublicKey(this.userId, {
3205
+ status: AuthMethodStatus.PENDING,
3206
+ type: PublicKeyType.WEB
3207
+ }));
3208
+ urlType = "createAuth";
3209
+ }
3210
+ if (authMethods.includes("PASSWORD")) {
3211
+ if (!canAddPasswordOrPIN) {
3212
+ if (optsAuthMethod === "PASSWORD") throw new Error("A user cannot have more than one password or PIN.");
3213
+ } else {
3163
3214
  ({
3164
- data: { id: credentialId }
3215
+ data: { id: passwordId }
3165
3216
  } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
3166
3217
  status: AuthMethodStatus.PENDING
3167
3218
  }));
3168
3219
  urlType = "createPassword";
3169
- break;
3170
- case "PIN":
3220
+ }
3221
+ }
3222
+ if (authMethods.includes("PIN")) {
3223
+ if (!canAddPasswordOrPIN) {
3224
+ if (optsAuthMethod === "PIN") throw new Error("A user cannot have more than one password or PIN.");
3225
+ } else {
3171
3226
  ({
3172
- data: { id: credentialId }
3227
+ data: { id: passwordId }
3173
3228
  } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
3174
3229
  status: AuthMethodStatus.PENDING
3175
3230
  }));
3176
3231
  urlType = "createPIN";
3177
- break;
3232
+ }
3233
+ }
3234
+ const credentialId = passkeyId != null ? passkeyId : passwordId;
3235
+ if (this.isNativePasskey && authMethods.includes("PASSKEY")) {
3236
+ return { credentialId };
3178
3237
  }
3179
- const url = this.isNativePasskey && urlType === "createAuth" ? void 0 : yield this.constructPortalUrl(urlType, {
3238
+ const { sessionId } = yield this.touchSession();
3239
+ const url = yield this.constructPortalUrl(isForNewDevice ? "addNewCredential" : urlType, {
3180
3240
  isForNewDevice,
3181
3241
  pathId: credentialId,
3182
3242
  portalTheme,
3183
- shorten
3243
+ shorten,
3244
+ sessionId: isForNewDevice ? sessionId : void 0,
3245
+ addNewCredentialType: optsAuthMethod,
3246
+ addNewCredentialPasskeyId: passkeyId,
3247
+ addNewCredentialPasswordId: passwordId
3184
3248
  });
3185
3249
  return __spreadValues({ credentialId }, url ? { url } : {});
3186
3250
  });
3187
3251
  }
3252
+ addCredential(_0) {
3253
+ return __async(this, arguments, function* ({ authMethod }) {
3254
+ if (authMethod === "PASSKEY" && !(yield this.isPasskeySupported())) {
3255
+ throw new Error("Passkeys are not supported.");
3256
+ }
3257
+ const { url } = yield this.getNewCredentialAndUrl({ isForNewDevice: true, authMethod });
3258
+ return url;
3259
+ });
3260
+ }
3188
3261
  /**
3189
3262
  * Returns a Para Portal URL for logging in with a WebAuth passkey, password, PIN or OTP.
3190
3263
  * @param {Object} opts the options object
@@ -3412,6 +3485,40 @@ Need help? Visit: https://docs.getpara.com or contact support
3412
3485
  this.setUserId(userId);
3413
3486
  });
3414
3487
  }
3488
+ exportPrivateKey() {
3489
+ return __async(this, arguments, function* (args = {}) {
3490
+ let walletId = args == null ? void 0 : args.walletId;
3491
+ if (!(args == null ? void 0 : args.walletId)) {
3492
+ walletId = this.findWalletId(void 0, { forbidPregen: true, scheme: ["DKLS"] });
3493
+ }
3494
+ const wallet = this.wallets[walletId];
3495
+ if (this.externalWallets[walletId]) {
3496
+ throw new Error("Cannot export private key for an external wallet");
3497
+ }
3498
+ if (!wallet || !wallet.signer) {
3499
+ throw new Error("Wallet not found with id: " + walletId);
3500
+ }
3501
+ if (wallet.scheme !== "DKLS") {
3502
+ throw new Error("Cannot export private key for a Solana wallet");
3503
+ }
3504
+ if (wallet.isPregen && !!wallet.pregenIdentifier && wallet.pregenIdentifierType !== "GUEST_ID") {
3505
+ throw new Error("Cannot export private key for a pregenerated wallet");
3506
+ }
3507
+ if (args.shouldOpenPopup) {
3508
+ this.popupWindow = yield this.platformUtils.openPopup("about:blank", { type: PopupType.EXPORT_PRIVATE_KEY });
3509
+ }
3510
+ const exportPrivateKeyUrl = yield this.constructPortalUrl("exportPrivateKey", {
3511
+ pathId: walletId
3512
+ });
3513
+ if (args.shouldOpenPopup) {
3514
+ this.popupWindow.location.href = exportPrivateKeyUrl;
3515
+ }
3516
+ return {
3517
+ url: exportPrivateKeyUrl,
3518
+ popupWindow: this.popupWindow
3519
+ };
3520
+ });
3521
+ }
3415
3522
  };
3416
3523
  _authInfo = new WeakMap();
3417
3524
  _ParaCore_instances = new WeakSet();
@@ -3525,7 +3632,8 @@ getOAuthUrl_fn = function(_0) {
3525
3632
  appScheme,
3526
3633
  accountLinkInProgress,
3527
3634
  sessionLookupId,
3528
- encryptionKey
3635
+ encryptionKey,
3636
+ portalCallbackParams
3529
3637
  }) {
3530
3638
  if (!accountLinkInProgress && !this.isPortal()) {
3531
3639
  return yield this.constructPortalUrl("oAuth", { sessionId: sessionLookupId, oAuthMethod: method, appScheme });
@@ -3539,13 +3647,14 @@ getOAuthUrl_fn = function(_0) {
3539
3647
  path: `/auth/${method.toLowerCase()}`,
3540
3648
  params: __spreadProps(__spreadValues({
3541
3649
  apiKey: this.ctx.apiKey,
3650
+ origin: typeof window !== "undefined" ? window.location.origin : void 0,
3542
3651
  sessionLookupId,
3543
3652
  portalSessionLookupId,
3544
3653
  appScheme
3545
3654
  }, accountLinkInProgress ? {
3546
3655
  linkedAccountId: this.accountLinkInProgress.id
3547
3656
  } : {}), {
3548
- callback: !accountLinkInProgress && (yield this.constructPortalUrl("oAuthCallback", {
3657
+ callback: !accountLinkInProgress && (yield this.constructPortalUrl("oAuthCallback", __spreadValues({
3549
3658
  sessionId: sessionLookupId,
3550
3659
  oAuthMethod: method,
3551
3660
  appScheme,
@@ -3553,11 +3662,172 @@ getOAuthUrl_fn = function(_0) {
3553
3662
  sessionId: sessionLookupId,
3554
3663
  encryptionKey
3555
3664
  }
3556
- }))
3665
+ }, this.isPortal() && { params: portalCallbackParams })))
3557
3666
  })
3558
3667
  });
3559
3668
  });
3560
3669
  };
3670
+ waitForLoginProcess_fn = function() {
3671
+ return __async(this, arguments, function* ({
3672
+ isCanceled = () => false,
3673
+ onCancel,
3674
+ onPoll,
3675
+ skipSessionRefresh = false,
3676
+ isSwitchingWallets = false
3677
+ } = {}) {
3678
+ this.devLog("[waitForLoginProcess] Starting", {
3679
+ isSwitchingWallets,
3680
+ skipSessionRefresh,
3681
+ isExternalWalletAuth: this.isExternalWalletAuth
3682
+ });
3683
+ const startedAt = Date.now();
3684
+ let originalCurrentWalletIdsHash;
3685
+ if (isSwitchingWallets) {
3686
+ this.devLog("[waitForLoginProcess] Wallet switching mode enabled");
3687
+ this.isSwitchingWallets = true;
3688
+ const session = yield this.touchSession();
3689
+ originalCurrentWalletIdsHash = session.currentWalletIdsHash;
3690
+ this.devLog("[waitForLoginProcess] Original wallet IDs hash", { originalCurrentWalletIdsHash });
3691
+ }
3692
+ return new Promise((resolve, reject) => {
3693
+ (() => __async(this, null, function* () {
3694
+ var _a;
3695
+ if (!this.isExternalWalletAuth && !isSwitchingWallets) {
3696
+ this.devLog("[waitForLoginProcess] Clearing external wallets");
3697
+ this.externalWallets = {};
3698
+ }
3699
+ let pollCount = 0;
3700
+ while (true) {
3701
+ pollCount++;
3702
+ this.devLog("[waitForLoginProcess] Poll iteration", {
3703
+ pollCount,
3704
+ elapsedMs: Date.now() - startedAt
3705
+ });
3706
+ if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
3707
+ this.devLog("[waitForLoginProcess] Canceled or timed out", {
3708
+ wasCanceled: isCanceled(),
3709
+ timedOut: Date.now() - startedAt > constants.POLLING_TIMEOUT_MS,
3710
+ elapsedMs: Date.now() - startedAt
3711
+ });
3712
+ if (isSwitchingWallets) {
3713
+ this.isSwitchingWallets = false;
3714
+ } else {
3715
+ dispatchEvent(ParaEvent.LOGIN_EVENT, { isComplete: false }, "failed to setup user");
3716
+ }
3717
+ onCancel == null ? void 0 : onCancel();
3718
+ return reject("canceled");
3719
+ }
3720
+ yield new Promise((resolve2) => setTimeout(resolve2, constants.POLLING_INTERVAL_MS));
3721
+ try {
3722
+ this.devLog("[waitForLoginProcess] Touching session");
3723
+ let session = yield this.touchSession();
3724
+ this.devLog("[waitForLoginProcess] Session state", {
3725
+ isAuthenticated: session.isAuthenticated,
3726
+ currentWalletIdsHash: session.currentWalletIdsHash,
3727
+ needsWallet: session.needsWallet
3728
+ });
3729
+ const shouldContinuePolling = isSwitchingWallets ? originalCurrentWalletIdsHash === session.currentWalletIdsHash : !session.isAuthenticated;
3730
+ this.devLog("[waitForLoginProcess] Should continue polling", {
3731
+ shouldContinuePolling,
3732
+ isSwitchingWallets,
3733
+ originalCurrentWalletIdsHash,
3734
+ sessionCurrentWalletIdsHash: session.currentWalletIdsHash,
3735
+ isAuthenticated: session.isAuthenticated
3736
+ });
3737
+ if (shouldContinuePolling) {
3738
+ onPoll == null ? void 0 : onPoll();
3739
+ continue;
3740
+ }
3741
+ this.devLog("[waitForLoginProcess] Authentication check passed, setting up user");
3742
+ session = yield this.userSetupAfterLogin();
3743
+ const needsWallet = (_a = session.needsWallet) != null ? _a : false;
3744
+ this.devLog("[waitForLoginProcess] User setup complete", { needsWallet });
3745
+ if (isSwitchingWallets) {
3746
+ const isWalletSwitchingComplete = originalCurrentWalletIdsHash !== session.currentWalletIdsHash;
3747
+ this.devLog("[waitForLoginProcess] Wallet switching check", {
3748
+ isWalletSwitchingComplete,
3749
+ originalHash: originalCurrentWalletIdsHash,
3750
+ sessionHash: session.currentWalletIdsHash
3751
+ });
3752
+ if (!isWalletSwitchingComplete) {
3753
+ onPoll == null ? void 0 : onPoll();
3754
+ continue;
3755
+ }
3756
+ } else if (!needsWallet) {
3757
+ this.devLog("[waitForLoginProcess] Checking wallet IDs", {
3758
+ currentWalletIdsArrayLength: this.currentWalletIdsArray.length
3759
+ });
3760
+ if (this.currentWalletIdsArray.length === 0) {
3761
+ this.devLog("[waitForLoginProcess] No wallet IDs yet, continuing to poll");
3762
+ onPoll == null ? void 0 : onPoll();
3763
+ continue;
3764
+ }
3765
+ }
3766
+ this.devLog("[waitForLoginProcess] Getting transmission key shares");
3767
+ const tempSharesRes = yield this.getTransmissionKeyShares();
3768
+ this.devLog("[waitForLoginProcess] Transmission shares received", {
3769
+ shareCount: tempSharesRes.data.temporaryShares.length,
3770
+ shares: tempSharesRes.data.temporaryShares.map((s) => ({
3771
+ walletId: s.walletId,
3772
+ walletScheme: s.walletScheme
3773
+ }))
3774
+ });
3775
+ let hasSharesForCurrentWallets;
3776
+ if (!isSwitchingWallets) {
3777
+ this.devLog("[waitForLoginProcess] Fetching wallets");
3778
+ const fetchedWallets = yield this.fetchWallets();
3779
+ this.devLog("[waitForLoginProcess] Wallets fetched", {
3780
+ walletCount: fetchedWallets.length,
3781
+ wallets: fetchedWallets.map((w) => ({ id: w.id, type: w.type, scheme: w.scheme }))
3782
+ });
3783
+ hasSharesForCurrentWallets = tempSharesRes.data.temporaryShares.length === fetchedWallets.length;
3784
+ } else {
3785
+ hasSharesForCurrentWallets = this.currentWalletIdsArray.every(([walletId]) => {
3786
+ return tempSharesRes.data.temporaryShares.some((share) => share.walletId === walletId);
3787
+ });
3788
+ }
3789
+ this.devLog("[waitForLoginProcess] Checking shares for current wallets", {
3790
+ hasSharesForCurrentWallets,
3791
+ currentWalletIdsCount: this.currentWalletIdsArray.length,
3792
+ shareCount: tempSharesRes.data.temporaryShares.length
3793
+ });
3794
+ if (hasSharesForCurrentWallets) {
3795
+ this.devLog("[waitForLoginProcess] Setting up after login");
3796
+ yield this.setupAfterLogin({ temporaryShares: tempSharesRes.data.temporaryShares, skipSessionRefresh });
3797
+ this.devLog("[waitForLoginProcess] Setup after login complete");
3798
+ this.devLog("[waitForLoginProcess] Claiming pregen wallets");
3799
+ yield this.claimPregenWallets();
3800
+ this.devLog("[waitForLoginProcess] Pregen wallets claimed");
3801
+ const resp = {
3802
+ needsWallet: needsWallet || Object.values(this.wallets).length === 0,
3803
+ partnerId: session.partnerId
3804
+ };
3805
+ this.devLog("[waitForLoginProcess] Login process complete", {
3806
+ needsWallet: resp.needsWallet,
3807
+ partnerId: resp.partnerId,
3808
+ walletCount: Object.values(this.wallets).length,
3809
+ isSwitchingWallets
3810
+ });
3811
+ if (isSwitchingWallets) {
3812
+ this.devLog("[waitForLoginProcess] Clearing wallet switching state");
3813
+ this.isSwitchingWallets = false;
3814
+ } else {
3815
+ this.devLog("[waitForLoginProcess] Dispatching LOGIN_EVENT");
3816
+ dispatchEvent(ParaEvent.LOGIN_EVENT, resp);
3817
+ }
3818
+ return resolve(resp);
3819
+ }
3820
+ this.devLog("[waitForLoginProcess] Not all shares available yet, continuing to poll");
3821
+ onPoll == null ? void 0 : onPoll();
3822
+ } catch (err) {
3823
+ console.error("[waitForLoginProcess] Error during polling iteration", err);
3824
+ onPoll == null ? void 0 : onPoll();
3825
+ }
3826
+ }
3827
+ }))();
3828
+ });
3829
+ });
3830
+ };
3561
3831
  createPregenWallet_fn = function(opts) {
3562
3832
  return __async(this, null, function* () {
3563
3833
  var _a, _b;