@openfort/openfort-js 0.10.35 → 0.10.36-beta.1

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 (62) hide show
  1. package/dist/cjs/packages/internal/openapi-clients/dist/index.js +1 -1
  2. package/dist/cjs/sdk/src/api/auth.js +1 -1
  3. package/dist/cjs/sdk/src/api/embeddedWallet.js +1 -1
  4. package/dist/cjs/sdk/src/api/proxy.js +1 -1
  5. package/dist/cjs/sdk/src/api/user.js +1 -1
  6. package/dist/cjs/sdk/src/auth/authManager.js +1 -1
  7. package/dist/cjs/sdk/src/core/configuration/account.js +1 -1
  8. package/dist/cjs/sdk/src/core/configuration/authentication.js +1 -1
  9. package/dist/cjs/sdk/src/core/errors/authErrorCodes.js +1 -0
  10. package/dist/cjs/sdk/src/core/errors/internal/extractApiError.js +1 -0
  11. package/dist/cjs/sdk/src/core/errors/internal/extractAuthError.js +1 -0
  12. package/dist/cjs/sdk/src/core/errors/openfortError.js +1 -1
  13. package/dist/cjs/sdk/src/core/errors/sentry.js +1 -1
  14. package/dist/cjs/sdk/src/core/errors/withApiError.js +1 -0
  15. package/dist/cjs/sdk/src/core/openfort.js +1 -1
  16. package/dist/cjs/sdk/src/core/openfortInternal.js +1 -1
  17. package/dist/cjs/sdk/src/index.js +1 -1
  18. package/dist/cjs/sdk/src/storage/istorage.js +1 -1
  19. package/dist/cjs/sdk/src/storage/lazyStorage.js +1 -1
  20. package/dist/cjs/sdk/src/types/types.js +1 -1
  21. package/dist/cjs/sdk/src/utils/crypto.js +1 -1
  22. package/dist/cjs/sdk/src/version.js +1 -1
  23. package/dist/cjs/sdk/src/wallets/embedded.js +1 -1
  24. package/dist/cjs/sdk/src/wallets/evm/estimateGas.js +1 -1
  25. package/dist/cjs/sdk/src/wallets/evm/getAssets.js +1 -1
  26. package/dist/cjs/sdk/src/wallets/evm/getCallsStatus.js +1 -1
  27. package/dist/cjs/sdk/src/wallets/evm/registerSession.js +1 -1
  28. package/dist/cjs/sdk/src/wallets/evm/revokeSession.js +1 -1
  29. package/dist/cjs/sdk/src/wallets/evm/sendCallSync.js +1 -1
  30. package/dist/cjs/sdk/src/wallets/iframeManager.js +1 -1
  31. package/dist/index.d.ts +7323 -2893
  32. package/dist/packages/internal/openapi-clients/dist/index.js +1 -1
  33. package/dist/sdk/src/api/auth.js +1 -1
  34. package/dist/sdk/src/api/embeddedWallet.js +1 -1
  35. package/dist/sdk/src/api/proxy.js +1 -1
  36. package/dist/sdk/src/api/user.js +1 -1
  37. package/dist/sdk/src/auth/authManager.js +1 -1
  38. package/dist/sdk/src/core/configuration/account.js +1 -1
  39. package/dist/sdk/src/core/configuration/authentication.js +1 -1
  40. package/dist/sdk/src/core/errors/authErrorCodes.js +1 -0
  41. package/dist/sdk/src/core/errors/internal/extractApiError.js +1 -0
  42. package/dist/sdk/src/core/errors/internal/extractAuthError.js +1 -0
  43. package/dist/sdk/src/core/errors/openfortError.js +1 -1
  44. package/dist/sdk/src/core/errors/sentry.js +1 -1
  45. package/dist/sdk/src/core/errors/withApiError.js +1 -0
  46. package/dist/sdk/src/core/openfort.js +1 -1
  47. package/dist/sdk/src/core/openfortInternal.js +1 -1
  48. package/dist/sdk/src/index.js +1 -1
  49. package/dist/sdk/src/storage/istorage.js +1 -1
  50. package/dist/sdk/src/storage/lazyStorage.js +1 -1
  51. package/dist/sdk/src/types/types.js +1 -1
  52. package/dist/sdk/src/utils/crypto.js +1 -1
  53. package/dist/sdk/src/version.js +1 -1
  54. package/dist/sdk/src/wallets/embedded.js +1 -1
  55. package/dist/sdk/src/wallets/evm/estimateGas.js +1 -1
  56. package/dist/sdk/src/wallets/evm/getAssets.js +1 -1
  57. package/dist/sdk/src/wallets/evm/getCallsStatus.js +1 -1
  58. package/dist/sdk/src/wallets/evm/registerSession.js +1 -1
  59. package/dist/sdk/src/wallets/evm/revokeSession.js +1 -1
  60. package/dist/sdk/src/wallets/evm/sendCallSync.js +1 -1
  61. package/dist/sdk/src/wallets/iframeManager.js +1 -1
  62. package/package.json +8 -5
@@ -1 +1 @@
1
- "use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.js"),t=require("../api/auth.js"),i=require("../api/embeddedWallet.js"),n=require("../api/proxy.js"),r=require("../api/user.js"),a=require("../auth/authManager.js"),s=require("../storage/istorage.js"),o=require("../storage/lazyStorage.js"),h=require("../utils/typedEventEmitter.js"),l=require("./config/config.js"),c=require("./configuration/passkey.js"),u=require("./errors/openfortError.js"),d=require("./errors/sentry.js"),g=require("./openfortInternal.js");class p{storage;iAuthManager=null;openfortInternal;initPromise;asyncInitPromise=null;authInstance;embeddedWalletInstance;userInstance;proxyInstance;configuration;eventEmitter;iPasskeyHandler;static globalEventEmitter=null;get auth(){if(!this.authInstance)throw new u.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.",u.OpenfortErrorType.INVALID_CONFIGURATION);return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new u.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.",u.OpenfortErrorType.INVALID_CONFIGURATION);return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new u.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.",u.OpenfortErrorType.INVALID_CONFIGURATION);return this.userInstance}get proxy(){if(!this.proxyInstance)throw new u.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.",u.OpenfortErrorType.INVALID_CONFIGURATION);return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new a.AuthManager(this.storage),this.openfortInternal=new g.OpenfortInternal(this.storage,this.authManager,this.eventEmitter),this.authInstance=new t.AuthApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter),this.embeddedWalletInstance=new i.EmbeddedWalletApi(this.storage,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter,this.passkeyHandler),this.userInstance=new r.UserApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this)),this.proxyInstance=new n.ProxyApi(this.storage,this.backendApiClients,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),async()=>{if(!this.embeddedWalletInstance)throw new u.OpenfortError("Embedded wallet not initialized",u.OpenfortErrorType.MISSING_SIGNER_ERROR);const e=this.embeddedWalletInstance;return t=>e.signMessage(t,{hashMessage:!0,arrayifyMessage:!0})})}catch(e){throw new u.OpenfortError("Openfort SDK synchronous initialization failed",u.OpenfortErrorType.INVALID_CONFIGURATION)}}constructor(e){if(this.configuration=new l.SDKConfiguration(e),this.storage=new o.LazyStorage(this.configuration.storage),this.eventEmitter=new h,p.globalEventEmitter){["onAuthInit","onAuthSuccess","onAuthFailure","onLogout","onSwitchAccount","onSignedMessage","onEmbeddedWalletCreated","onEmbeddedWalletRecovered","onAuthFlowOpen","onAuthFlowClose","onAuthFlowCancel"].forEach(e=>{this.eventEmitter.on(e,(...t)=>{p.globalEventEmitter?.emit(e,...t)})})}else p.globalEventEmitter=this.eventEmitter;this.iPasskeyHandler=new c.PasskeyHandler({rpId:this.configuration.passkeyRpId,rpName:this.configuration.passkeyRpName,extractableKey:!0}),d.InternalSentry.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}static getEventEmitter(){return p.globalEventEmitter||(p.globalEventEmitter=new h),p.globalEventEmitter}async waitForInitialization(){await this.initPromise,await this.ensureAsyncInitialized()}async getAccessToken(){return await this.ensureInitialized(),this.openfortInternal.getAccessToken()}async validateAndRefreshToken(e){return await this.ensureInitialized(),await this.openfortInternal.validateAndRefreshToken(e)}get backendApiClients(){return new e.BackendApiClients({basePath:this.configuration.backendUrl,accessToken:this.configuration.baseConfiguration.publishableKey,nativeAppIdentifier:this.configuration.nativeAppIdentifier,storage:this.storage,onLogout:()=>{this.eventEmitter.emit("onLogout")}})}get authManager(){if(!this.iAuthManager)throw new u.OpenfortError("AuthManager not initialized",u.OpenfortErrorType.INTERNAL_ERROR);return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(e){try{const t=s.StorageKeys.TEST,i="openfort_storage_test";e.save(t,i);const n=await e.get(t);return e.remove(t),n===i}catch(e){return!1}}async initializeAsync(){try{if(!await p.isStorageAccessible(this.storage))throw new u.OpenfortError("Storage is not accessible",u.OpenfortErrorType.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}catch(e){throw new u.OpenfortError("Openfort SDK async initialization failed",u.OpenfortErrorType.INTERNAL_ERROR)}}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}exports.Openfort=p;
1
+ "use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.js"),t=require("../api/auth.js"),i=require("../api/embeddedWallet.js"),n=require("../api/proxy.js"),a=require("../api/user.js"),r=require("../auth/authManager.js"),s=require("../storage/istorage.js"),o=require("../storage/lazyStorage.js"),h=require("../utils/typedEventEmitter.js"),l=require("./config/config.js"),u=require("./configuration/passkey.js"),c=require("./errors/authErrorCodes.js"),d=require("./errors/openfortError.js"),g=require("./errors/sentry.js"),f=require("./openfortInternal.js");class p{storage;iAuthManager=null;openfortInternal;initPromise;asyncInitPromise=null;authInstance;embeddedWalletInstance;userInstance;proxyInstance;configuration;eventEmitter;iPasskeyHandler;static globalEventEmitter=null;get auth(){if(!this.authInstance)throw new d.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.");return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new d.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.");return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new d.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.");return this.userInstance}get proxy(){if(!this.proxyInstance)throw new d.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.");return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new r.AuthManager,this.openfortInternal=new f.OpenfortInternal(this.storage,this.authManager,this.eventEmitter),this.authInstance=new t.AuthApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter),this.embeddedWalletInstance=new i.EmbeddedWalletApi(this.storage,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter,this.passkeyHandler),this.userInstance=new a.UserApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this)),this.proxyInstance=new n.ProxyApi(this.storage,this.backendApiClients,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),async()=>{if(!this.embeddedWalletInstance)throw new d.SignerError(c.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"Embedded wallet not initialized");const e=this.embeddedWalletInstance;return t=>e.signMessage(t,{hashMessage:!0,arrayifyMessage:!0})})}catch(e){throw new d.ConfigurationError("Openfort SDK synchronous initialization failed")}}constructor(e){if(this.configuration=new l.SDKConfiguration(e),this.storage=new o.LazyStorage(this.configuration.storage),this.eventEmitter=new h,p.globalEventEmitter){["onAuthInit","onAuthSuccess","onAuthFailure","onLogout","onSwitchAccount","onSignedMessage","onEmbeddedWalletCreated","onEmbeddedWalletRecovered","onAuthFlowOpen","onAuthFlowClose","onAuthFlowCancel"].forEach(e=>{this.eventEmitter.on(e,(...t)=>{p.globalEventEmitter?.emit(e,...t)})})}else p.globalEventEmitter=this.eventEmitter;this.iPasskeyHandler=new u.PasskeyHandler({rpId:this.configuration.passkeyRpId,rpName:this.configuration.passkeyRpName,extractableKey:!0}),g.InternalSentry.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}static getEventEmitter(){return p.globalEventEmitter||(p.globalEventEmitter=new h),p.globalEventEmitter}async waitForInitialization(){await this.initPromise,await this.ensureAsyncInitialized()}async getAccessToken(){return await this.ensureInitialized(),this.openfortInternal.getAccessToken()}async validateAndRefreshToken(e){return await this.ensureInitialized(),await this.openfortInternal.validateAndRefreshToken(e)}get backendApiClients(){return new e.BackendApiClients({basePath:this.configuration.backendUrl,accessToken:this.configuration.baseConfiguration.publishableKey,nativeAppIdentifier:this.configuration.nativeAppIdentifier,storage:this.storage,onLogout:()=>{this.eventEmitter.emit("onLogout")}})}get authManager(){if(!this.iAuthManager)throw new d.RequestError("AuthManager not initialized");return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(e){try{const t=s.StorageKeys.TEST,i="openfort_storage_test";e.save(t,i);const n=await e.get(t);return e.remove(t),n===i}catch(e){return!1}}async initializeAsync(){try{if(!await p.isStorageAccessible(this.storage))throw new d.ConfigurationError("Storage is not accessible");this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}catch(e){throw new d.RequestError("Openfort SDK async initialization failed")}}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}exports.Openfort=p;
@@ -1 +1 @@
1
- "use strict";var e=require("./configuration/authentication.js"),r=require("./errors/openfortError.js"),t=require("../types/types.js");require("human-id");var n=require("./config/config.js");require("../storage/istorage.js");var i=require("../utils/debug.js");require("eventemitter3"),require("../wallets/evm/JsonRpcError.js"),require("@ethersproject/keccak256"),require("../wallets/evm/types.js"),require("../wallets/evm/provider/eip6963.js"),require("./errors/sentry.js"),require("../wallets/messaging/browserMessenger/backwardCompatibility.js"),require("../wallets/types.js"),require("jose");var o=require("../utils/promiseUtils.js");exports.OpenfortInternal=class{storage;authManager;eventEmitter;constructor(e,r,t){this.storage=e,this.authManager=r,this.eventEmitter=t}async getThirdPartyAuthToken(){const i=n.SDKConfiguration.getInstance();if(!i?.thirdPartyAuth)throw new r.OpenfortError("No third party configuration found",r.OpenfortErrorType.INTERNAL_ERROR);const{getAccessToken:o,provider:a}=i.thirdPartyAuth;if(!o||!a)throw new r.OpenfortError("Third party is not configured. Please configure getAccessToken and thirdPartyAuthProvider in your Openfort instance",r.OpenfortErrorType.INVALID_CONFIGURATION);const s=await o();if(!s)throw new r.OpenfortError("Could not get access token",r.OpenfortErrorType.AUTHENTICATION_ERROR);let u=(await e.Authentication.fromStorage(this.storage))?.player;if(!u){const e=await this.authManager.authenticateThirdParty(a,s,t.TokenType.ID_TOKEN);u=e?.id}return new e.Authentication("third_party",s,u,null,a,t.TokenType.ID_TOKEN).save(this.storage),s}async getAccessToken(){if(n.SDKConfiguration.getInstance()?.thirdPartyAuth)return this.getThirdPartyAuthToken();return(await e.Authentication.fromStorage(this.storage))?.token??null}async validateAndRefreshToken(a){return o.singlePromise(async()=>{if(n.SDKConfiguration.getInstance()?.thirdPartyAuth)return void await this.getThirdPartyAuthToken();const o=await e.Authentication.fromStorage(this.storage);if(!o)throw new r.OpenfortError("Must be logged in to validate and refresh token",r.OpenfortErrorType.NOT_LOGGED_IN_ERROR);let s;i.debugLog("validating credentials...");try{s=await this.authManager.validateCredentials(o,a)}catch(r){throw e.Authentication.clear(this.storage),this.eventEmitter.emit(t.OpenfortEvents.ON_LOGOUT),r}if(!s.player)throw new r.OpenfortError("No user found in credentials",r.OpenfortErrorType.INTERNAL_ERROR);s.accessToken!==o.token&&(i.debugLog("tokens refreshed"),new e.Authentication("jwt",s.accessToken,s.player,s.refreshToken).save(this.storage))},"openfort.validateAndRefreshToken")}};
1
+ "use strict";var e=require("./configuration/authentication.js"),t=require("./errors/authErrorCodes.js"),r=require("./errors/openfortError.js"),i=require("../types/types.js");require("human-id");var n=require("./config/config.js");require("../storage/istorage.js"),require("axios"),require("./errors/sentry.js");var s=require("../utils/debug.js");require("eventemitter3"),require("../wallets/evm/JsonRpcError.js"),require("@ethersproject/keccak256"),require("../wallets/evm/types.js"),require("../wallets/evm/provider/eip6963.js"),require("../wallets/messaging/browserMessenger/backwardCompatibility.js"),require("../wallets/types.js");var a=require("../utils/promiseUtils.js");exports.OpenfortInternal=class{storage;authManager;eventEmitter;constructor(e,t,r){this.storage=e,this.authManager=t,this.eventEmitter=r}async getThirdPartyAuthToken(){const s=n.SDKConfiguration.getInstance();if(!s?.thirdPartyAuth)throw new r.RequestError("No third party configuration found");const{getAccessToken:a,provider:o}=s.thirdPartyAuth;if(!a||!o)throw new r.ConfigurationError("Third party is not configured. Please configure getAccessToken and thirdPartyAuthProvider in your Openfort instance");const u=await a();if(!u)throw new r.AuthenticationError(t.OPENFORT_AUTH_ERROR_CODES.INVALID_TOKEN,"Could not get access token");let h=(await e.Authentication.fromStorage(this.storage))?.userId;if(!h){h=(await this.authManager.authenticateThirdParty(o,u,i.TokenType.ID_TOKEN)).userId}return new e.Authentication("third_party",u,h,o,i.TokenType.ID_TOKEN).save(this.storage),u}async getAccessToken(){if(n.SDKConfiguration.getInstance()?.thirdPartyAuth)return this.getThirdPartyAuthToken();return(await e.Authentication.fromStorage(this.storage))?.token??null}async validateAndRefreshToken(o){return a.singlePromise(async()=>{if(n.SDKConfiguration.getInstance()?.thirdPartyAuth)return void await this.getThirdPartyAuthToken();const a=await e.Authentication.fromStorage(this.storage);if(!a)throw new r.SessionError(t.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be logged in to validate and refresh token");let u;s.debugLog("validating credentials...");try{u=await this.authManager.validateCredentials(a,o)}catch(t){throw e.Authentication.clear(this.storage),this.eventEmitter.emit(i.OpenfortEvents.ON_LOGOUT),t}if(!u.user?.id)throw new r.RequestError("No user found in credentials");u.token!==a.token&&(s.debugLog("tokens refreshed"),new e.Authentication("session",u.token,u.user.id).save(this.storage))},"openfort.validateAndRefreshToken")}};
@@ -1 +1 @@
1
- "use strict";var e=require("./core/openfort.js"),r=require("./api/auth.js"),t=require("./api/embeddedWallet.js"),o=require("./api/proxy.js"),n=require("./api/user.js"),i=require("./core/config/config.js"),p=require("./core/errors/openfortError.js"),u=require("./core/openfortInternal.js"),s=require("./utils/authorization.js"),a=require("./wallets/iframeManager.js"),d=require("./types/types.js");const f=e.Openfort.getEventEmitter();exports.Openfort=e.Openfort,exports.AuthApi=r.AuthApi,exports.EmbeddedWalletApi=t.EmbeddedWalletApi,exports.ProxyApi=o.ProxyApi,exports.UserApi=n.UserApi,exports.OpenfortConfiguration=i.OpenfortConfiguration,exports.SDKConfiguration=i.SDKConfiguration,exports.ShieldConfiguration=i.ShieldConfiguration,exports.OpenfortError=p.OpenfortError,Object.defineProperty(exports,"OpenfortErrorType",{enumerable:!0,get:function(){return p.OpenfortErrorType}}),exports.OpenfortInternal=u.OpenfortInternal,exports.prepareAndSignAuthorization=s.prepareAndSignAuthorization,exports.serializeSignedAuthorization=s.serializeSignedAuthorization,exports.signAuthorization=s.signAuthorization,exports.MissingProjectEntropyError=a.MissingProjectEntropyError,exports.MissingRecoveryPasswordError=a.MissingRecoveryPasswordError,exports.NotConfiguredError=a.NotConfiguredError,exports.OTPRequiredError=a.OTPRequiredError,exports.WrongRecoveryPasswordError=a.WrongRecoveryPasswordError,Object.defineProperty(exports,"AccountTypeEnum",{enumerable:!0,get:function(){return d.AccountTypeEnum}}),Object.defineProperty(exports,"AuthActionRequiredActions",{enumerable:!0,get:function(){return d.AuthActionRequiredActions}}),Object.defineProperty(exports,"AuthType",{enumerable:!0,get:function(){return d.AuthType}}),Object.defineProperty(exports,"BasicAuthProvider",{enumerable:!0,get:function(){return d.BasicAuthProvider}}),Object.defineProperty(exports,"ChainTypeEnum",{enumerable:!0,get:function(){return d.ChainTypeEnum}}),Object.defineProperty(exports,"EmbeddedState",{enumerable:!0,get:function(){return d.EmbeddedState}}),Object.defineProperty(exports,"OAuthProvider",{enumerable:!0,get:function(){return d.OAuthProvider}}),Object.defineProperty(exports,"OpenfortEvents",{enumerable:!0,get:function(){return d.OpenfortEvents}}),Object.defineProperty(exports,"RecoveryMethod",{enumerable:!0,get:function(){return d.RecoveryMethod}}),Object.defineProperty(exports,"ThirdPartyOAuthProvider",{enumerable:!0,get:function(){return d.ThirdPartyAuthProvider}}),Object.defineProperty(exports,"TokenType",{enumerable:!0,get:function(){return d.TokenType}}),exports.openfortEvents=f;
1
+ "use strict";var r=require("./core/openfort.js"),e=require("./api/auth.js"),o=require("./api/embeddedWallet.js"),t=require("./api/proxy.js"),n=require("./api/user.js"),i=require("./core/errors/authErrorCodes.js"),s=require("./core/errors/openfortError.js"),p=require("./core/config/config.js"),u=require("./core/openfortInternal.js"),a=require("./utils/authorization.js"),E=require("./wallets/iframeManager.js"),c=require("./types/types.js");const d=r.Openfort.getEventEmitter();exports.Openfort=r.Openfort,exports.AuthApi=e.AuthApi,exports.EmbeddedWalletApi=o.EmbeddedWalletApi,exports.ProxyApi=t.ProxyApi,exports.UserApi=n.UserApi,exports.OPENFORT_AUTH_ERROR_CODES=i.OPENFORT_AUTH_ERROR_CODES,exports.OPENFORT_ERROR_CODES=i.OPENFORT_ERROR_CODES,exports.AuthenticationError=s.AuthenticationError,exports.AuthorizationError=s.AuthorizationError,exports.ConfigurationError=s.ConfigurationError,exports.OAuthError=s.OAuthError,exports.OTPError=s.OTPError,exports.OpenfortError=s.OpenfortError,exports.RecoveryError=s.RecoveryError,exports.RequestError=s.RequestError,exports.SessionError=s.SessionError,exports.SignerError=s.SignerError,exports.UserError=s.UserError,exports.OpenfortConfiguration=p.OpenfortConfiguration,exports.SDKConfiguration=p.SDKConfiguration,exports.ShieldConfiguration=p.ShieldConfiguration,exports.OpenfortInternal=u.OpenfortInternal,exports.prepareAndSignAuthorization=a.prepareAndSignAuthorization,exports.serializeSignedAuthorization=a.serializeSignedAuthorization,exports.signAuthorization=a.signAuthorization,exports.MissingProjectEntropyError=E.MissingProjectEntropyError,exports.MissingRecoveryPasswordError=E.MissingRecoveryPasswordError,exports.NotConfiguredError=E.NotConfiguredError,exports.OTPRequiredError=E.OTPRequiredError,exports.WrongRecoveryPasswordError=E.WrongRecoveryPasswordError,Object.defineProperty(exports,"AccountTypeEnum",{enumerable:!0,get:function(){return c.AccountTypeEnum}}),Object.defineProperty(exports,"AuthActionRequiredActions",{enumerable:!0,get:function(){return c.AuthActionRequiredActions}}),Object.defineProperty(exports,"AuthType",{enumerable:!0,get:function(){return c.AuthType}}),Object.defineProperty(exports,"BasicAuthProvider",{enumerable:!0,get:function(){return c.BasicAuthProvider}}),Object.defineProperty(exports,"ChainTypeEnum",{enumerable:!0,get:function(){return c.ChainTypeEnum}}),Object.defineProperty(exports,"EmbeddedState",{enumerable:!0,get:function(){return c.EmbeddedState}}),Object.defineProperty(exports,"OAuthProvider",{enumerable:!0,get:function(){return c.OAuthProvider}}),Object.defineProperty(exports,"OpenfortEvents",{enumerable:!0,get:function(){return c.OpenfortEvents}}),Object.defineProperty(exports,"RecoveryMethod",{enumerable:!0,get:function(){return c.RecoveryMethod}}),Object.defineProperty(exports,"ThirdPartyOAuthProvider",{enumerable:!0,get:function(){return c.ThirdPartyAuthProvider}}),Object.defineProperty(exports,"TokenType",{enumerable:!0,get:function(){return c.TokenType}}),exports.openfortEvents=d;
@@ -1 +1 @@
1
- "use strict";var o;exports.StorageKeys=void 0,(o=exports.StorageKeys||(exports.StorageKeys={})).AUTHENTICATION="openfort.authentication",o.CONFIGURATION="openfort.configuration",o.ACCOUNT="openfort.account",o.TEST="openfort.test",o.SESSION="openfort.session",o.PKCE_STATE="openfort.pkce_state",o.PKCE_VERIFIER="openfort.pkce_verifier";
1
+ "use strict";var o;exports.StorageKeys=void 0,(o=exports.StorageKeys||(exports.StorageKeys={})).AUTHENTICATION="openfort.authentication",o.CONFIGURATION="openfort.configuration",o.ACCOUNT="openfort.account",o.TEST="openfort.test",o.SESSION="openfort.session";
@@ -1 +1 @@
1
- "use strict";var e=require("../core/errors/openfortError.js"),r=require("./storage.js");exports.LazyStorage=class{realStorage=null;customStorage;constructor(e){this.customStorage=e}getRealStorage(){if(!this.realStorage)if(this.customStorage)this.realStorage=this.customStorage;else{if("undefined"==typeof window||"undefined"==typeof localStorage)throw new e.OpenfortError("Storage not available. Please provide custom storage or use in browser environment.",e.OpenfortErrorType.INVALID_CONFIGURATION);this.realStorage=new r.StorageImplementation(localStorage)}return this.realStorage}async get(e){return this.getRealStorage().get(e)}save(e,r){this.getRealStorage().save(e,r)}remove(e){this.getRealStorage().remove(e)}flush(){this.getRealStorage().flush()}};
1
+ "use strict";var e=require("../core/errors/openfortError.js"),t=require("./storage.js");exports.LazyStorage=class{realStorage=null;customStorage;constructor(e){this.customStorage=e}getRealStorage(){if(!this.realStorage)if(this.customStorage)this.realStorage=this.customStorage;else{if("undefined"==typeof window||"undefined"==typeof localStorage)throw new e.ConfigurationError("Storage not available. Please provide custom storage or use in browser environment.");this.realStorage=new t.StorageImplementation(localStorage)}return this.realStorage}async get(e){return this.getRealStorage().get(e)}save(e,t){this.getRealStorage().save(e,t)}remove(e){this.getRealStorage().remove(e)}flush(){this.getRealStorage().flush()}};
@@ -1 +1 @@
1
- "use strict";var e,o,t,E,r,A,p,d,T,s,i,n;exports.EmbeddedState=void 0,(e=exports.EmbeddedState||(exports.EmbeddedState={}))[e.NONE=0]="NONE",e[e.UNAUTHENTICATED=1]="UNAUTHENTICATED",e[e.EMBEDDED_SIGNER_NOT_CONFIGURED=2]="EMBEDDED_SIGNER_NOT_CONFIGURED",e[e.CREATING_ACCOUNT=3]="CREATING_ACCOUNT",e[e.READY=4]="READY",exports.OpenfortEvents=void 0,(o=exports.OpenfortEvents||(exports.OpenfortEvents={})).ON_AUTH_INIT="onAuthInit",o.ON_AUTH_SUCCESS="onAuthSuccess",o.ON_AUTH_FAILURE="onAuthFailure",o.ON_LOGOUT="onLogout",o.ON_SWITCH_ACCOUNT="onSwitchAccount",o.ON_SIGNED_MESSAGE="onSignedMessage",o.ON_EMBEDDED_WALLET_CREATED="onEmbeddedWalletCreated",o.ON_EMBEDDED_WALLET_RECOVERED="onEmbeddedWalletRecovered",exports.RecoveryMethod=void 0,(t=exports.RecoveryMethod||(exports.RecoveryMethod={})).PASSWORD="password",t.AUTOMATIC="automatic",t.PASSKEY="passkey",exports.AccountType=void 0,(E=exports.AccountType||(exports.AccountType={})).ERC6551V1="ERC6551V1",E.UPGRADEABLE_V5="UpgradeableV5",E.UPGRADEABLE_V4="UpgradeableV4",E.UPGRADEABLE_V6="UpgradeableV6",E.ZKSYNC_UPGRADEABLE_V1="ZKSyncUpgradeableV1",E.ZKSYNC_UPGRADEABLE_V2="ZKSyncUpgradeableV2",E.SIMPLE="Simple",E.CALIBUR="Calibur",exports.AuthType=void 0,(r=exports.AuthType||(exports.AuthType={})).OPENFORT="openfort",r.THIRD_PARTY="thirdParty",exports.TokenType=void 0,(A=exports.TokenType||(exports.TokenType={})).ID_TOKEN="idToken",A.CUSTOM_TOKEN="customToken",exports.ThirdPartyAuthProvider=void 0,(p=exports.ThirdPartyAuthProvider||(exports.ThirdPartyAuthProvider={})).ACCELBYTE="accelbyte",p.FIREBASE="firebase",p.BETTER_AUTH="better-auth",p.LOOTLOCKER="lootlocker",p.PLAYFAB="playfab",p.SUPABASE="supabase",p.CUSTOM="custom",p.OIDC="oidc",exports.BasicAuthProvider=void 0,(d=exports.BasicAuthProvider||(exports.BasicAuthProvider={})).EMAIL="email",d.WALLET="wallet",exports.OAuthProvider=void 0,(T=exports.OAuthProvider||(exports.OAuthProvider={})).GOOGLE="google",T.TWITTER="twitter",T.APPLE="apple",T.FACEBOOK="facebook",T.DISCORD="discord",T.EPIC_GAMES="epic_games",T.LINE="line",exports.AuthActionRequiredActions=void 0,(exports.AuthActionRequiredActions||(exports.AuthActionRequiredActions={})).ACTION_VERIFY_EMAIL="verify_email",exports.CodeChallengeMethodEnum=void 0,(exports.CodeChallengeMethodEnum||(exports.CodeChallengeMethodEnum={})).S256="S256",exports.AccountTypeEnum=void 0,(s=exports.AccountTypeEnum||(exports.AccountTypeEnum={})).EOA="Externally Owned Account",s.SMART_ACCOUNT="Smart Account",s.DELEGATED_ACCOUNT="Delegated Account",exports.ChainTypeEnum=void 0,(i=exports.ChainTypeEnum||(exports.ChainTypeEnum={})).EVM="EVM",i.SVM="SVM",function(e){e.ASC="asc",e.DESC="desc"}(n||(n={}));
1
+ "use strict";var e,t,o,E,r,A,T,p,s,d,i,n;exports.EmbeddedState=void 0,(e=exports.EmbeddedState||(exports.EmbeddedState={}))[e.NONE=0]="NONE",e[e.UNAUTHENTICATED=1]="UNAUTHENTICATED",e[e.EMBEDDED_SIGNER_NOT_CONFIGURED=2]="EMBEDDED_SIGNER_NOT_CONFIGURED",e[e.CREATING_ACCOUNT=3]="CREATING_ACCOUNT",e[e.READY=4]="READY",exports.OpenfortEvents=void 0,(t=exports.OpenfortEvents||(exports.OpenfortEvents={})).ON_AUTH_INIT="onAuthInit",t.ON_AUTH_SUCCESS="onAuthSuccess",t.ON_OTP_REQUEST="onOtpRequest",t.ON_OTP_FAILURE="onOtpFailure",t.ON_AUTH_FAILURE="onAuthFailure",t.ON_LOGOUT="onLogout",t.ON_SWITCH_ACCOUNT="onSwitchAccount",t.ON_SIGNED_MESSAGE="onSignedMessage",t.ON_EMBEDDED_WALLET_CREATED="onEmbeddedWalletCreated",t.ON_EMBEDDED_WALLET_RECOVERED="onEmbeddedWalletRecovered",exports.RecoveryMethod=void 0,(o=exports.RecoveryMethod||(exports.RecoveryMethod={})).PASSWORD="password",o.AUTOMATIC="automatic",o.PASSKEY="passkey",exports.AccountType=void 0,(E=exports.AccountType||(exports.AccountType={})).ERC6551V1="ERC6551V1",E.UPGRADEABLE_V5="UpgradeableV5",E.UPGRADEABLE_V4="UpgradeableV4",E.UPGRADEABLE_V6="UpgradeableV6",E.ZKSYNC_UPGRADEABLE_V1="ZKSyncUpgradeableV1",E.ZKSYNC_UPGRADEABLE_V2="ZKSyncUpgradeableV2",E.SIMPLE="Simple",E.CALIBUR="Calibur",exports.AuthType=void 0,(r=exports.AuthType||(exports.AuthType={})).OPENFORT="openfort",r.THIRD_PARTY="thirdParty",exports.TokenType=void 0,(A=exports.TokenType||(exports.TokenType={})).ID_TOKEN="idToken",A.CUSTOM_TOKEN="customToken",exports.ThirdPartyAuthProvider=void 0,(T=exports.ThirdPartyAuthProvider||(exports.ThirdPartyAuthProvider={})).ACCELBYTE="accelbyte",T.FIREBASE="firebase",T.BETTER_AUTH="better-auth",T.LOOTLOCKER="lootlocker",T.PLAYFAB="playfab",T.SUPABASE="supabase",T.CUSTOM="custom",T.OIDC="oidc",exports.BasicAuthProvider=void 0,(p=exports.BasicAuthProvider||(exports.BasicAuthProvider={})).EMAIL="email",p.WALLET="wallet",exports.OAuthProvider=void 0,(s=exports.OAuthProvider||(exports.OAuthProvider={})).GOOGLE="google",s.TWITTER="twitter",s.APPLE="apple",s.FACEBOOK="facebook",s.DISCORD="discord",s.EPIC_GAMES="epic_games",s.LINE="line",exports.AuthActionRequiredActions=void 0,(exports.AuthActionRequiredActions||(exports.AuthActionRequiredActions={})).ACTION_VERIFY_EMAIL="verify_email",exports.AccountTypeEnum=void 0,(d=exports.AccountTypeEnum||(exports.AccountTypeEnum={})).EOA="Externally Owned Account",d.SMART_ACCOUNT="Smart Account",d.DELEGATED_ACCOUNT="Delegated Account",exports.ChainTypeEnum=void 0,(i=exports.ChainTypeEnum||(exports.ChainTypeEnum={})).EVM="EVM",i.SVM="SVM",function(e){e.ASC="asc",e.DESC="desc"}(n||(n={}));
@@ -1 +1 @@
1
- "use strict";let t;exports.cryptoDigest=async function(r,e){if(t)return t(r,e);if("undefined"!=typeof crypto&&crypto.subtle&&crypto.subtle.digest)return crypto.subtle.digest(r,e);throw new Error("No crypto digest function available. Please provide a crypto override for this environment.")},exports.hexToString=function(t){let r="";const e=t.startsWith("0x")?t.slice(2):t;for(let t=0;t<e.length;t+=2){const n=parseInt(e.substring(t,t+2),16);0!==n&&(r+=String.fromCharCode(n))}return r},exports.numberToHex=function(t){return`0x${t.toString(16)}`},exports.randomUUID=function(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(16);return crypto.getRandomValues(t),t[6]=15&t[6]|64,t[8]=63&t[8]|128,[...t].map((t,r)=>{const e=t.toString(16).padStart(2,"0");return[4,6,8,10].includes(r)?`-${e}`:e}).join("")},exports.setCryptoDigestOverride=function(r){t=r};
1
+ "use strict";exports.hexToString=function(t){let r="";const n=t.startsWith("0x")?t.slice(2):t;for(let t=0;t<n.length;t+=2){const e=parseInt(n.substring(t,t+2),16);0!==e&&(r+=String.fromCharCode(e))}return r},exports.numberToHex=function(t){return`0x${t.toString(16)}`},exports.randomUUID=function(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(16);return crypto.getRandomValues(t),t[6]=15&t[6]|64,t[8]=63&t[8]|128,[...t].map((t,r)=>{const n=t.toString(16).padStart(2,"0");return[4,6,8,10].includes(r)?`-${n}`:n}).join("")},exports.setCryptoDigestOverride=function(t){};
@@ -1 +1 @@
1
- "use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="0.10.35";
1
+ "use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="0.10.36-beta.1";
@@ -1 +1 @@
1
- "use strict";var e=require("../core/configuration/authentication.js"),t=require("../core/configuration/passkey.js"),r=require("../core/errors/openfortError.js"),a=require("../types/types.js"),o=require("../core/config/config.js"),n=require("../core/configuration/account.js"),s=require("../storage/istorage.js");require("eventemitter3"),require("./evm/JsonRpcError.js"),require("@ethersproject/keccak256"),require("./evm/types.js"),require("./evm/provider/eip6963.js"),require("../core/errors/sentry.js"),require("./messaging/browserMessenger/backwardCompatibility.js"),require("./types.js"),require("jose");exports.EmbeddedSigner=class{iframeManager;storage;backendApiClients;passkeyHandler;eventEmitter;constructor(e,t,r,a,o){this.iframeManager=e,this.storage=t,this.backendApiClients=r,this.passkeyHandler=a,this.eventEmitter=o}async createPasskey(e){const r=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:e});return{id:r.id,key:r.key}}async configure(t){const s=await e.Authentication.fromStorage(this.storage);if(!s)throw new r.OpenfortError("No access token found",r.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const i=o.SDKConfiguration.getInstance();if(!i)throw new r.OpenfortError("Configuration not found",r.OpenfortErrorType.INVALID_CONFIGURATION);const c=await n.Account.fromStorage(this.storage);let d;if(c){const e={account:c.id,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},..."passkey"===c.recoveryMethod&&{passkey:{id:c.recoveryMethodDetails?.passkeyId,env:c.recoveryMethodDetails?.passkeyEnv,key:await t.getPasskeyKeyFn(c.recoveryMethodDetails?.passkeyId)}}}}},r=await this.iframeManager.recover(e);d=r.account}else{const e=await this.backendApiClients.accountsApi.getAccountsV2({user:s.player,accountType:t.accountType,chainType:t.chainType},{headers:{authorization:`Bearer ${i.baseConfiguration.publishableKey}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}});if(0===e.data.data.length){const e=t.entropy?.passkey?await this.createPasskey(s.player):void 0,r={accountType:t.accountType,chainType:t.chainType,chainId:t.chainId,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},...t.entropy.passkey&&{passkey:e}}}},a=await this.iframeManager.create(r);d=a.account}else{const r=e.data.data,a=r.find(e=>e.chainId===t.chainId),o=a||r[0],n={account:o.id,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},..."passkey"===o.recoveryMethod&&{passkey:{id:o.recoveryMethodDetails?.passkeyId,env:o.recoveryMethodDetails?.passkeyEnv,key:await t.getPasskeyKeyFn(o.recoveryMethodDetails?.passkeyId)}}}}},s=await this.iframeManager.recover(n);if(d=s.account,!a){const e=await this.iframeManager.switchChain(t.chainId);d=e.account}}}return r.withOpenfortError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:d},{headers:{authorization:`Bearer ${i.baseConfiguration.publishableKey}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}}),t=new n.Account({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:n.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(a.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async sign(e,t,r,o){const n=await this.iframeManager.sign(e,t,r,o);return this.eventEmitter.emit(a.OpenfortEvents.ON_SIGNED_MESSAGE,{message:e,signature:n}),n}async export(){return await this.iframeManager.export()}async switchChain({chainId:e}){const t=await n.Account.fromStorage(this.storage);if(t?.accountType===a.AccountTypeEnum.EOA)new n.Account({...t,chainId:e}).save(this.storage);else{const r=await this.iframeManager.switchChain(e);new n.Account({...t,id:r.account,chainId:e}).save(this.storage)}}async create(t){const s=await this.iframeManager.create(t),i=await e.Authentication.fromStorage(this.storage);if(!i)throw new r.OpenfortError("No access token found",r.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const c=o.SDKConfiguration.getInstance();if(!c)throw new r.OpenfortError("Configuration not found",r.OpenfortErrorType.INVALID_CONFIGURATION);return r.withOpenfortError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:s.account},{headers:{authorization:`Bearer ${c.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}}),t=new n.Account({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,implementationAddress:e.data.smartAccount?.implementationAddress,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:n.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(a.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async recover(t){const s=await this.iframeManager.recover(t),i=await e.Authentication.fromStorage(this.storage);if(!i)throw new r.OpenfortError("No access token found",r.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const c=o.SDKConfiguration.getInstance();if(!c)throw new r.OpenfortError("Configuration not found",r.OpenfortErrorType.INVALID_CONFIGURATION);return r.withOpenfortError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:s.account},{headers:{authorization:`Bearer ${c.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}}),t=new n.Account({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:n.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(a.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async setRecoveryMethod({recoveryMethod:e,recoveryPassword:t,encryptionSession:r,passkeyInfo:a}){await this.iframeManager.setRecoveryMethod(e,t,r,a?.passkeyKey,a?.passkeyId)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(s.StorageKeys.ACCOUNT)}};
1
+ "use strict";var e=require("../core/configuration/authentication.js"),t=require("../core/configuration/passkey.js"),a=require("../core/errors/authErrorCodes.js"),r=require("../core/errors/openfortError.js"),o=require("../core/errors/withApiError.js"),n=require("../types/types.js"),s=require("../core/config/config.js"),i=require("../core/configuration/account.js"),c=require("../storage/istorage.js");require("eventemitter3"),require("./evm/JsonRpcError.js"),require("@ethersproject/keccak256"),require("./evm/types.js"),require("./evm/provider/eip6963.js"),require("../core/errors/sentry.js"),require("./messaging/browserMessenger/backwardCompatibility.js"),require("./types.js");exports.EmbeddedSigner=class{iframeManager;storage;backendApiClients;passkeyHandler;eventEmitter;constructor(e,t,a,r,o){this.iframeManager=e,this.storage=t,this.backendApiClients=a,this.passkeyHandler=r,this.eventEmitter=o}async createPasskey(e){const a=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:e});return{id:a.id,key:a.key}}async configure(t){const c=await e.Authentication.fromStorage(this.storage);if(!c)throw new r.SessionError(a.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");const d=s.SDKConfiguration.getInstance();if(!d)throw new r.ConfigurationError("Configuration not found");const y=await i.Account.fromStorage(this.storage);let p;if(y){const e={account:y.id,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},..."passkey"===y.recoveryMethod&&{passkey:{id:y.recoveryMethodDetails?.passkeyId,env:y.recoveryMethodDetails?.passkeyEnv,key:await t.getPasskeyKeyFn(y.recoveryMethodDetails?.passkeyId)}}}}},a=await this.iframeManager.recover(e);p=a.account}else{const e=await this.backendApiClients.accountsApi.getAccountsV2({user:c.userId,accountType:t.accountType,chainType:t.chainType},{headers:c.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}:{authorization:`Bearer ${c.token}`,"x-project-key":d.baseConfiguration.publishableKey}});if(0===e.data.data.length){const e=t.entropy?.passkey?await this.createPasskey(c.userId):void 0,a={accountType:t.accountType,chainType:t.chainType,chainId:t.chainId,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},...t.entropy.passkey&&{passkey:e}}}},r=await this.iframeManager.create(a);p=r.account}else{const a=e.data.data,r=a.find(e=>e.chainId===t.chainId),o=r||a[0],n={account:o.id,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},..."passkey"===o.recoveryMethod&&{passkey:{id:o.recoveryMethodDetails?.passkeyId,env:o.recoveryMethodDetails?.passkeyEnv,key:await t.getPasskeyKeyFn(o.recoveryMethodDetails?.passkeyId)}}}}},s=await this.iframeManager.recover(n);if(p=s.account,!r){const e=await this.iframeManager.switchChain(t.chainId);p=e.account}}}return o.withApiError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:p},{headers:c.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}:{authorization:`Bearer ${c.token}`,"x-project-key":d.baseConfiguration.publishableKey}}),t=new i.Account({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:i.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(n.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"configure"})}async sign(e,t,a,r){const o=await this.iframeManager.sign(e,t,a,r);return this.eventEmitter.emit(n.OpenfortEvents.ON_SIGNED_MESSAGE,{message:e,signature:o}),o}async export(){return await this.iframeManager.export()}async switchChain({chainId:e}){const t=await i.Account.fromStorage(this.storage);if(t?.accountType===n.AccountTypeEnum.EOA)new i.Account({...t,chainId:e}).save(this.storage);else{const a=await this.iframeManager.switchChain(e);new i.Account({...t,id:a.account,chainId:e}).save(this.storage)}}async create(t){const c=await this.iframeManager.create(t),d=await e.Authentication.fromStorage(this.storage);if(!d)throw new r.SessionError(a.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");const y=s.SDKConfiguration.getInstance();if(!y)throw new r.ConfigurationError("Configuration not found");return o.withApiError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:c.account},{headers:d.thirdPartyProvider?{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}:{authorization:`Bearer ${d.token}`,"x-project-key":y.baseConfiguration.publishableKey}}),t=new i.Account({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,implementationAddress:e.data.smartAccount?.implementationAddress,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:i.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(n.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"create"})}async recover(t){const c=await this.iframeManager.recover(t),d=await e.Authentication.fromStorage(this.storage);if(!d)throw new r.SessionError(a.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");const y=s.SDKConfiguration.getInstance();if(!y)throw new r.ConfigurationError("Configuration not found");return o.withApiError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:c.account},{headers:d.thirdPartyProvider?{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}:{authorization:`Bearer ${d.token}`,"x-project-key":y.baseConfiguration.publishableKey}}),t=new i.Account({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:i.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(n.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"recover"})}async setRecoveryMethod({recoveryMethod:e,recoveryPassword:t,encryptionSession:a,passkeyInfo:r}){await this.iframeManager.setRecoveryMethod(e,t,a,r?.passkeyKey,r?.passkeyId)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(c.StorageKeys.ACCOUNT)}};
@@ -1 +1 @@
1
- "use strict";var r=require("../../core/errors/openfortError.js"),t=require("./JsonRpcError.js");exports.estimateGas=async({params:e,account:a,authentication:o,backendClient:n,policyId:i})=>{const s=await(async(e,a,o,n,i)=>{const s=e.map(r=>{if(!r.to)throw new t.JsonRpcError(t.RpcErrorCode.INVALID_PARAMS,'eth_estimateGas requires a "to" field');return{to:String(r.to),data:r.data?String(r.data):void 0,value:r.value?String(r.value):void 0}});return r.withOpenfortError(async()=>(await a.transactionIntentsApi.estimateTransactionIntentCost({createTransactionIntentRequest:{policy:i,chainId:o.chainId,interactions:s}},{headers:{authorization:`Bearer ${a.config.backend.accessToken}`,"x-player-token":n.token,"x-auth-provider":n.thirdPartyProvider,"x-token-type":n.thirdPartyTokenType}})).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})})(e,n,a,o,i).catch(r=>{throw new t.JsonRpcError(t.RpcErrorCode.TRANSACTION_REJECTED,r.message)});return s.estimatedTXGas};
1
+ "use strict";var t=require("../../core/errors/withApiError.js"),r=require("./JsonRpcError.js");exports.estimateGas=async({params:e,account:a,authentication:o,backendClient:n,policyId:i})=>{const c=await(async(e,a,o,n,i)=>{const c=e.map(t=>{if(!t.to)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,'eth_estimateGas requires a "to" field');return{to:String(t.to),data:t.data?String(t.data):void 0,value:t.value?String(t.value):void 0}});return t.withApiError(async()=>(await a.transactionIntentsApi.estimateTransactionIntentCost({createTransactionIntentRequest:{policy:i,chainId:o.chainId,interactions:c}},{headers:n.thirdPartyProvider?{authorization:`Bearer ${a.config.backend.accessToken}`,"x-auth-provider":n.thirdPartyProvider,"x-token-type":n.thirdPartyTokenType}:{authorization:`Bearer ${n.token}`,"x-project-key":String(a.config.backend.accessToken)}})).data,{context:"operation"})})(e,n,a,o,i).catch(t=>{throw new r.JsonRpcError(r.RpcErrorCode.TRANSACTION_REJECTED,t.message)});return c.estimatedTXGas};
@@ -1 +1 @@
1
- "use strict";var e=require("../../core/errors/openfortError.js"),r=require("./JsonRpcError.js");exports.getAssets=async({params:t,account:a,authentication:s,backendClient:o})=>{const n=await(async(r,t,a,s)=>{const o=s?.chainFilter?.map(e=>Number.parseInt(e,16));return e.withOpenfortError(async()=>(await r.rpcApi.handleRpcRequest({jsonRpcRequest:{method:"wallet_getAssets",params:{account:t.address,chainFilter:o,assetFilter:s?.assetFilter,assetTypeFilter:s?.assetTypeFilter},id:1,jsonrpc:"2.0"}},{headers:{authorization:`Bearer ${r.config.backend.accessToken}`,"x-player-token":a.token,"x-auth-provider":a.thirdPartyProvider,"x-token-type":a.thirdPartyTokenType}})).data,{default:e.OpenfortErrorType.AUTHENTICATION_ERROR})})(o,a,s,t).catch(e=>{throw new r.JsonRpcError(r.RpcErrorCode.INTERNAL_ERROR,e.message)});return n.result};
1
+ "use strict";var e=require("../../core/errors/withApiError.js"),r=require("./JsonRpcError.js");exports.getAssets=async({params:t,account:a,authentication:s,backendClient:o})=>{const i=await(async(r,t,a,s)=>{const o=s?.chainFilter?.map(e=>Number.parseInt(e,16));return e.withApiError(async()=>(await r.rpcApi.handleRpcRequest({jsonRpcRequest:{method:"wallet_getAssets",params:{account:t.address,chainFilter:o,assetFilter:s?.assetFilter,assetTypeFilter:s?.assetTypeFilter},id:1,jsonrpc:"2.0"}},{headers:a.thirdPartyProvider?{authorization:`Bearer ${r.config.backend.accessToken}`,"x-auth-provider":a.thirdPartyProvider,"x-token-type":a.thirdPartyTokenType}:{authorization:`Bearer ${a.token}`,"x-project-key":String(r.config.backend.accessToken)}})).data,{context:"operation"})})(o,a,s,t).catch(e=>{throw new r.JsonRpcError(r.RpcErrorCode.INTERNAL_ERROR,e.message)});return i.result};
@@ -1 +1 @@
1
- "use strict";var e=require("../../core/errors/openfortError.js"),r=require("./JsonRpcError.js");exports.getCallStatus=async({params:s,authentication:t,backendClient:a})=>{const o=await(async(r,s,t)=>e.withOpenfortError(async()=>(await s.transactionIntentsApi.getTransactionIntent({id:r},{headers:{authorization:`Bearer ${s.config.backend.accessToken}`,"x-player-token":t.token,"x-auth-provider":t.thirdPartyProvider,"x-token-type":t.thirdPartyTokenType}})).data,{default:e.OpenfortErrorType.AUTHENTICATION_ERROR}))(s[0],a,t).catch(e=>{throw new r.JsonRpcError(r.RpcErrorCode.TRANSACTION_REJECTED,e.message)});return{status:o.response?"CONFIRMED":"PENDING",receipts:o.response?[{status:0===o.response.status?"reverted":"success",logs:o.response.logs?.map(e=>({address:e.address,data:e.data,topics:e.topics}))||[],blockHash:o.response.transactionHash||"",blockNumber:BigInt(o.response.blockNumber||0),gasUsed:BigInt(o.response.gasUsed||0),transactionHash:o.response.transactionHash||""}]:void 0}};
1
+ "use strict";var e=require("../../core/errors/withApiError.js"),r=require("./JsonRpcError.js");exports.getCallStatus=async({params:s,authentication:t,backendClient:a})=>{const o=await(async(r,s,t)=>e.withApiError(async()=>(await s.transactionIntentsApi.getTransactionIntent({id:r},{headers:t.thirdPartyProvider?{authorization:`Bearer ${s.config.backend.accessToken}`,"x-auth-provider":t.thirdPartyProvider,"x-token-type":t.thirdPartyTokenType}:{authorization:`Bearer ${t.token}`,"x-project-key":String(s.config.backend.accessToken)}})).data,{context:"operation"}))(s[0],a,t).catch(e=>{throw new r.JsonRpcError(r.RpcErrorCode.TRANSACTION_REJECTED,e.message)});return{status:o.response?"CONFIRMED":"PENDING",receipts:o.response?[{status:0===o.response.status?"reverted":"success",logs:o.response.logs?.map(e=>({address:e.address,data:e.data,topics:e.topics}))||[],blockHash:o.response.transactionHash||"",blockNumber:BigInt(o.response.blockNumber||0),gasUsed:BigInt(o.response.gasUsed||0),transactionHash:o.response.transactionHash||""}]:void 0}};
@@ -1 +1 @@
1
- "use strict";var e=require("../../core/errors/openfortError.js"),t=require("../../types/types.js"),r=require("./JsonRpcError.js");function i(e){return{data:(()=>{if("token-allowance"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"token-allowance policy is not supported with this account implementation.");if("gas-limit"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"gas-limit policy is not supported with this account implementation.");if("rate-limit"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"rate-limit policy is not supported with this account implementation.");return e.data})(),type:e.type.custom}}function o(e){if("native-token-transfer"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"native-token-transfer permission is not supported with this account implementation.");if("rate-limit"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"rate-limit permission is not supported with this account implementation.");if("gas-limit"===e.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"gas-limit permission is not supported with this account implementation.");return{...e,policies:e?.policies?.map(i),required:e.required??!1,type:"string"==typeof e.type?e.type:e.type.custom}}function n(e){return{expiry:e.validUntil?Number(e.validUntil):0,grantedPermissions:e.whitelist?e.whitelist.map(t=>({type:"contract-call",data:{address:t,calls:[]},policies:[{data:{limit:e.limit},type:{custom:"usage-limit"}}]})):[],permissionsContext:e.id}}exports.registerSession=async({params:i,signer:s,account:a,authentication:p,backendClient:c,policyId:l})=>{const d=await(async(t,i,n,s,a)=>{const p=t[0],c=Math.floor(Date.now()/1e3),l=Math.floor(new Date(Date.now()+1e3*p.expiry).getTime()/1e3),d=p.permissions.map(o),u=d.filter(e=>"contract-call"===e.type||"erc20-token-transfer"===e.type||"erc721-token-transfer"===e.type||"erc1155-token-transfer"===e.type).map(e=>e.data.address);let y,m=d.find(e=>"call-limit"===e.type)?.data;if(m=d[0]?.policies?.find(e=>"call-limit"===e.type)?.data?.limit,"signer"in p&&p.signer){if("keys"===p.signer.type)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"Multi-key signers are not supported for session creation");"key"!==p.signer.type&&"account"!==p.signer.type||(y=p.signer.data.id)}else"account"in p&&p.account&&(y=p.account);if(!y)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"Failed to request permissions - missing session address");const R=((e,t,r,i,o,n=!1,s,a,p,c)=>{const l={address:e,chainId:t,validAfter:r,validUntil:i,optimistic:n,whitelist:s,player:a,account:c};return o&&(l.policy=o),p&&(l.limit=p),l})(y,n.chainId,c,l,a,!1,u,s.player,m,n.id);return e.withOpenfortError(async()=>(await i.sessionsApi.createSession({createSessionRequest:R},{headers:{authorization:`Bearer ${i.config.backend.accessToken}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}})).data,{default:e.OpenfortErrorType.AUTHENTICATION_ERROR})})(i,c,a,p,l).catch(e=>{throw new r.JsonRpcError(r.RpcErrorCode.TRANSACTION_REJECTED,e.message)});if(d?.nextAction?.payload?.signableHash){let i;i=[300,531050104,324,50104,2741,11124].includes(a.chainId)||a.implementationType&&[t.AccountType.CALIBUR].includes(a.implementationType)?await s.sign(d.nextAction.payload.signableHash,!1,!1):await s.sign(d.nextAction.payload.signableHash);return n(await e.withOpenfortError(async()=>(await c.sessionsApi.signatureSession({id:d.id,signatureRequest:{signature:i}})).data,{default:e.OpenfortErrorType.AUTHENTICATION_ERROR}).catch(e=>{throw new r.JsonRpcError(r.RpcErrorCode.TRANSACTION_REJECTED,e.message)}))}if(!1===d.isActive)throw new r.JsonRpcError(r.RpcErrorCode.TRANSACTION_REJECTED,"Failed to grant permissions");return n(d)};
1
+ "use strict";var t=require("../../core/errors/withApiError.js"),e=require("../../types/types.js"),i=require("./JsonRpcError.js");function r(t){return{data:(()=>{if("token-allowance"===t.type)throw new i.JsonRpcError(i.RpcErrorCode.INVALID_PARAMS,"token-allowance policy is not supported with this account implementation.");if("gas-limit"===t.type)throw new i.JsonRpcError(i.RpcErrorCode.INVALID_PARAMS,"gas-limit policy is not supported with this account implementation.");if("rate-limit"===t.type)throw new i.JsonRpcError(i.RpcErrorCode.INVALID_PARAMS,"rate-limit policy is not supported with this account implementation.");return t.data})(),type:t.type.custom}}function o(t){if("native-token-transfer"===t.type)throw new i.JsonRpcError(i.RpcErrorCode.INVALID_PARAMS,"native-token-transfer permission is not supported with this account implementation.");if("rate-limit"===t.type)throw new i.JsonRpcError(i.RpcErrorCode.INVALID_PARAMS,"rate-limit permission is not supported with this account implementation.");if("gas-limit"===t.type)throw new i.JsonRpcError(i.RpcErrorCode.INVALID_PARAMS,"gas-limit permission is not supported with this account implementation.");return{...t,policies:t?.policies?.map(r),required:t.required??!1,type:"string"==typeof t.type?t.type:t.type.custom}}function n(t){return{expiry:t.validUntil?Number(t.validUntil):0,grantedPermissions:t.whitelist?t.whitelist.map(e=>({type:"contract-call",data:{address:e,calls:[]},policies:[{data:{limit:t.limit},type:{custom:"usage-limit"}}]})):[],permissionsContext:t.id}}exports.registerSession=async({params:r,signer:s,account:a,authentication:c,backendClient:p,policyId:l})=>{const d=await(async(e,r,n,s,a)=>{const c=e[0],p=Math.floor(Date.now()/1e3),l=Math.floor(new Date(Date.now()+1e3*c.expiry).getTime()/1e3),d=c.permissions.map(o),u=d.filter(t=>"contract-call"===t.type||"erc20-token-transfer"===t.type||"erc721-token-transfer"===t.type||"erc1155-token-transfer"===t.type).map(t=>t.data.address);let m,y=d.find(t=>"call-limit"===t.type)?.data;if(y=d[0]?.policies?.find(t=>"call-limit"===t.type)?.data?.limit,"signer"in c&&c.signer){if("keys"===c.signer.type)throw new i.JsonRpcError(i.RpcErrorCode.INVALID_PARAMS,"Multi-key signers are not supported for session creation");"key"!==c.signer.type&&"account"!==c.signer.type||(m=c.signer.data.id)}else"account"in c&&c.account&&(m=c.account);if(!m)throw new i.JsonRpcError(i.RpcErrorCode.INVALID_PARAMS,"Failed to request permissions - missing session address");const h=((t,e,i,r,o,n=!1,s,a,c,p)=>{const l={address:t,chainId:e,validAfter:i,validUntil:r,optimistic:n,whitelist:s,player:a,account:p};return o&&(l.policy=o),c&&(l.limit=c),l})(m,n.chainId,p,l,a,!1,u,s.userId,y,n.id);return t.withApiError(async()=>(await r.sessionsApi.createSession({createSessionRequest:h},{headers:s.thirdPartyProvider?{authorization:`Bearer ${r.config.backend.accessToken}`,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}:{authorization:`Bearer ${s.token}`,"x-project-key":String(r.config.backend.accessToken)}})).data,{context:"operation"})})(r,p,a,c,l).catch(t=>{throw new i.JsonRpcError(i.RpcErrorCode.TRANSACTION_REJECTED,t.message)});if(d?.nextAction?.payload?.signableHash){let r;r=[300,531050104,324,50104,2741,11124].includes(a.chainId)||a.implementationType&&[e.AccountType.CALIBUR].includes(a.implementationType)?await s.sign(d.nextAction.payload.signableHash,!1,!1):await s.sign(d.nextAction.payload.signableHash);return n(await t.withApiError(async()=>(await p.sessionsApi.signatureSession({id:d.id,signatureRequest:{signature:r}})).data,{context:"operation"}).catch(t=>{throw new i.JsonRpcError(i.RpcErrorCode.TRANSACTION_REJECTED,t.message)}))}if(!1===d.isActive)throw new i.JsonRpcError(i.RpcErrorCode.TRANSACTION_REJECTED,"Failed to grant permissions");return n(d)};
@@ -1 +1 @@
1
- "use strict";var e=require("../../core/errors/openfortError.js"),r=require("../../types/types.js"),n=require("./JsonRpcError.js");exports.revokeSession=async({params:t,signer:s,account:a,authentication:o,backendClient:i,policyId:c})=>{const p=t[0];if(!p.permissionContext)return await s.disconnect(),{};const d=await(async(r,n,t,s,a)=>{const o=((e,r,n,t,s)=>{const a={address:e,chainId:r,player:n,account:s};return t&&(a.policy=t),a})(r.permissionContext,t.chainId,s.player,a,t.id);return e.withOpenfortError(async()=>(await n.sessionsApi.revokeSession({revokeSessionRequest:o},{headers:{authorization:`Bearer ${n.config.backend.accessToken}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}})).data,{default:e.OpenfortErrorType.AUTHENTICATION_ERROR})})(p,i,a,o,c).catch(e=>{throw new n.JsonRpcError(n.RpcErrorCode.TRANSACTION_REJECTED,e.message)});if(d?.nextAction?.payload?.signableHash){let e;e=[300,531050104,324,50104,2741,11124].includes(a.chainId)||a.implementationType&&[r.AccountType.CALIBUR].includes(a.implementationType)?await s.sign(d.nextAction.payload.signableHash,!1,!1):await s.sign(d.nextAction.payload.signableHash);return(await i.sessionsApi.signatureSession({id:d.id,signatureRequest:{signature:e}}).catch(e=>{throw new n.JsonRpcError(n.RpcErrorCode.TRANSACTION_REJECTED,e.message)})).data}return d};
1
+ "use strict";var e=require("../../core/errors/withApiError.js"),r=require("../../types/types.js"),t=require("./JsonRpcError.js");exports.revokeSession=async({params:n,signer:i,account:a,authentication:s,backendClient:o,policyId:c})=>{const p=n[0];if(!p.permissionContext)return await i.disconnect(),{};const d=await(async(r,t,n,i,a)=>{const s=((e,r,t,n,i)=>{const a={address:e,chainId:r,player:t,account:i};return n&&(a.policy=n),a})(r.permissionContext,n.chainId,i.userId,a,n.id);return e.withApiError(async()=>(await t.sessionsApi.revokeSession({revokeSessionRequest:s},{headers:i.thirdPartyProvider?{authorization:`Bearer ${t.config.backend.accessToken}`,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":String(t.config.backend.accessToken)}})).data,{context:"operation"})})(p,o,a,s,c).catch(e=>{throw new t.JsonRpcError(t.RpcErrorCode.TRANSACTION_REJECTED,e.message)});if(d?.nextAction?.payload?.signableHash){let e;e=[300,531050104,324,50104,2741,11124].includes(a.chainId)||a.implementationType&&[r.AccountType.CALIBUR].includes(a.implementationType)?await i.sign(d.nextAction.payload.signableHash,!1,!1):await i.sign(d.nextAction.payload.signableHash);return(await o.sessionsApi.signatureSession({id:d.id,signatureRequest:{signature:e}}).catch(e=>{throw new t.JsonRpcError(t.RpcErrorCode.TRANSACTION_REJECTED,e.message)})).data}return d};
@@ -1 +1 @@
1
- "use strict";var e=require("../../core/errors/openfortError.js"),r=require("../../types/types.js"),t=require("../../utils/authorization.js"),o=require("./JsonRpcError.js");const a=e=>{const r=e?.logs?.[0];return{blockHash:r?.blockHash,blockNumber:e?.blockNumber?.toString(),contractAddress:void 0,cumulativeGasUsed:e?.gasUsed,effectiveGasPrice:e?.gasFee,from:void 0,gasUsed:e?.gasUsed,logs:e?.logs||[],logsBloom:void 0,status:1===e?.status?"success":0===e?.status?"reverted":void 0,to:e?.to,transactionHash:e?.transactionHash,transactionIndex:r?.transactionIndex,type:"eip1559",blobGasPrice:void 0,blobGasUsed:void 0,root:void 0}};async function n(e,r){try{const t=await e.getCode(r);return"0x"!==t&&t.length>2}catch{return!1}}exports.sendCallsSync=async({params:s,signer:i,account:c,authentication:d,backendClient:p,rpcProvider:u,policyId:l})=>{const E=s[0]?.capabilities?.paymasterService?.policy??l;let T;if(c.accountType===r.AccountTypeEnum.DELEGATED_ACCOUNT){const[e,r]=await Promise.all([n(u,c.address),u.getTransactionCount(c.address)]);if(!e){const e=await t.prepareAndSignAuthorization({signer:i,accountAddress:c.address,contractAddress:c.implementationAddress,chainId:c.chainId,nonce:r});T=t.serializeSignedAuthorization(e)}}const A=await(async(r,t,a,n,s,i)=>{const c=r.map(e=>{if(!e.to)throw new o.JsonRpcError(o.RpcErrorCode.INVALID_PARAMS,'wallet_sendCalls requires a "to" field');return{to:String(e.to),data:e.data?String(e.data):void 0,value:e.value?String(e.value):void 0}});return e.withOpenfortError(async()=>(await t.transactionIntentsApi.createTransactionIntent({createTransactionIntentRequest:{account:a.id,policy:s,signedAuthorization:i,chainId:a.chainId,interactions:c}},{headers:{authorization:`Bearer ${t.config.backend.accessToken}`,"x-player-token":n.token,"x-auth-provider":n.thirdPartyProvider,"x-token-type":n.thirdPartyTokenType}})).data,{default:e.OpenfortErrorType.AUTHENTICATION_ERROR})})(s,p,c,d,E,T).catch(e=>{throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,e.message)});if(A.response?.error.reason)throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,A.response?.error.reason);if(A?.nextAction?.payload?.signableHash){let t;t=[300,531050104,324,50104,2741,11124].includes(c.chainId)||c.implementationType&&[r.AccountType.CALIBUR].includes(c.implementationType)?await i.sign(A.nextAction.payload.signableHash,!1,!1):await i.sign(A.nextAction.payload.signableHash);const n=await e.withOpenfortError(async()=>await p.transactionIntentsApi.signature({id:A.id,signatureRequest:{signature:t}}),{default:e.OpenfortErrorType.AUTHENTICATION_ERROR}).catch(e=>{throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,e.message)});if(0===n.data.response?.status)throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,n.data.response?.error.reason);if(!n.data.response)throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,"No transaction response received");return{id:A.id,receipt:a(n.data.response)}}if(!A.response)throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,"No transaction response received");return{id:A.id,receipt:a(A.response)}};
1
+ "use strict";var e=require("../../core/errors/withApiError.js"),r=require("../../types/types.js"),t=require("../../utils/authorization.js"),o=require("./JsonRpcError.js");const a=e=>{const r=e?.logs?.[0];return{blockHash:r?.blockHash,blockNumber:e?.blockNumber?.toString(),contractAddress:void 0,cumulativeGasUsed:e?.gasUsed,effectiveGasPrice:e?.gasFee,from:void 0,gasUsed:e?.gasUsed,logs:e?.logs||[],logsBloom:void 0,status:1===e?.status?"success":0===e?.status?"reverted":void 0,to:e?.to,transactionHash:e?.transactionHash,transactionIndex:r?.transactionIndex,type:"eip1559",blobGasPrice:void 0,blobGasUsed:void 0,root:void 0}};async function n(e,r){try{const t=await e.getCode(r);return"0x"!==t&&t.length>2}catch{return!1}}exports.sendCallsSync=async({params:s,signer:i,account:c,authentication:d,backendClient:p,rpcProvider:u,policyId:l})=>{const E=s[0]?.capabilities?.paymasterService?.policy??l;let h;if(c.accountType===r.AccountTypeEnum.DELEGATED_ACCOUNT){const[e,r]=await Promise.all([n(u,c.address),u.getTransactionCount(c.address)]);if(!e){const e=await t.prepareAndSignAuthorization({signer:i,accountAddress:c.address,contractAddress:c.implementationAddress,chainId:c.chainId,nonce:r});h=t.serializeSignedAuthorization(e)}}const A=await(async(r,t,a,n,s,i)=>{const c=r.map(e=>{if(!e.to)throw new o.JsonRpcError(o.RpcErrorCode.INVALID_PARAMS,'wallet_sendCalls requires a "to" field');return{to:String(e.to),data:e.data?String(e.data):void 0,value:e.value?String(e.value):void 0}});return e.withApiError(async()=>(await t.transactionIntentsApi.createTransactionIntent({createTransactionIntentRequest:{account:a.id,policy:s,signedAuthorization:i,chainId:a.chainId,interactions:c}},{headers:n.thirdPartyProvider?{authorization:`Bearer ${t.config.backend.accessToken}`,"x-auth-provider":n.thirdPartyProvider,"x-token-type":n.thirdPartyTokenType}:{authorization:`Bearer ${n.token}`,"x-project-key":String(t.config.backend.accessToken)}})).data,{context:"operation"})})(s,p,c,d,E,h).catch(e=>{throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,e.message)});if(A.response?.error.reason)throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,A.response?.error.reason);if(A?.nextAction?.payload?.signableHash){let t;t=[300,531050104,324,50104,2741,11124].includes(c.chainId)||c.implementationType&&[r.AccountType.CALIBUR].includes(c.implementationType)?await i.sign(A.nextAction.payload.signableHash,!1,!1):await i.sign(A.nextAction.payload.signableHash);const n=await e.withApiError(async()=>await p.transactionIntentsApi.signature({id:A.id,signatureRequest:{signature:t}}),{context:"operation"}).catch(e=>{throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,e.message)});if(0===n.data.response?.status)throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,n.data.response?.error.reason);if(!n.data.response)throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,"No transaction response received");return{id:A.id,receipt:a(n.data.response)}}if(!A.response)throw new o.JsonRpcError(o.RpcErrorCode.TRANSACTION_REJECTED,"No transaction response received");return{id:A.id,receipt:a(A.response)}};
@@ -1 +1 @@
1
- "use strict";var e=require("../core/configuration/account.js"),r=require("../core/configuration/authentication.js"),i=require("../core/errors/openfortError.js"),t=require("../core/errors/sentry.js"),n=require("../storage/istorage.js"),o=require("../utils/crypto.js"),s=require("../utils/debug.js"),a=require("./messaging/ReactNativeMessenger.js"),d=require("./messaging/browserMessenger/connect.js");require("./messaging/browserMessenger/backwardCompatibility.js");var c=require("./types.js");class u extends Error{constructor(){super("This embedded signer requires a password to be recovered")}}class h extends Error{constructor(){super("Wrong recovery passkey for this embedded signer")}}class g extends Error{constructor(){super("MissingProjectEntropyError")}}class l extends Error{constructor(){super("Wrong recovery password for this embedded signer")}}class y extends Error{constructor(){super("Not configured")}}class p extends Error{constructor(){super("OTP required")}}exports.IframeManager=class{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;hasFailed=!1;constructor(e,r,t){if(!e)throw new i.OpenfortError("Configuration is required for IframeManager",i.OpenfortErrorType.INVALID_CONFIGURATION);if(!r)throw new i.OpenfortError("Storage is required for IframeManager",i.OpenfortErrorType.INVALID_CONFIGURATION);if(!t)throw new i.OpenfortError("Messenger is required for IframeManager",i.OpenfortErrorType.INVALID_CONFIGURATION);this.sdkConfiguration=e,this.storage=r,this.messenger=t}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new i.OpenfortError("Failed to establish iFrame connection: Previous connection attempt failed",i.OpenfortErrorType.INTERNAL_ERROR);if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){s.debugLog("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:s.debugLog}),this.connection=d({messenger:this.messenger,timeout:1e4,log:s.debugLog});try{this.remote=await this.connection.promise,s.debugLog("IframeManager connection established")}catch(e){const r=e;throw t.sentry.captureException(r),this.destroy(),s.debugLog("Failed to establish connection:",r),new i.OpenfortError(`Failed to establish iFrame connection: ${r.cause||r.message}`,i.OpenfortErrorType.INTERNAL_ERROR,e)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new i.OpenfortError("Failed to establish connection",i.OpenfortErrorType.INTERNAL_ERROR);return this.remote}handleError(e){if(c.isErrorResponse(e)){if(e.error===c.NOT_CONFIGURED_ERROR)throw this.storage.remove(n.StorageKeys.ACCOUNT),new y;if(e.error===c.MISSING_USER_ENTROPY_ERROR)throw this.storage.remove(n.StorageKeys.ACCOUNT),new u;if(e.error===c.MISSING_PROJECT_ENTROPY_ERROR)throw this.storage.remove(n.StorageKeys.ACCOUNT),new g;if(e.error===c.INCORRECT_USER_ENTROPY_ERROR)throw new l;if(e.error===c.MISSING_PASSKEY_ERROR)throw this.storage.remove(n.StorageKeys.ACCOUNT),new u;if(e.error===c.INCORRECT_PASSKEY_ERROR)throw new h;if(e.error===c.OTP_REQUIRED_ERROR)throw new p;throw this.storage.remove(n.StorageKeys.ACCOUNT),new i.OpenfortError(`Unknown error: ${e.error}`,i.OpenfortErrorType.INTERNAL_ERROR)}throw e}async buildRequestConfiguration(){const e=await r.Authentication.fromStorage(this.storage);if(!e)throw new i.OpenfortError("Must be authenticated to create a signer",i.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const t={auth:c.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:t,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await r.Authentication.fromStorage(this.storage);if(!e)throw new i.OpenfortError("Must be authenticated to create a signer",i.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const t={auth:c.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.player,recovery:t,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await this.ensureConnection(),i=await this.buildIFrameRequestConfiguration();i.chainId=e.chainId??null,i.password=e?.entropy?.recoveryPassword??null,i.recovery={...i.recovery,encryptionSession:e?.entropy?.encryptionSession},i.passkey=e?.entropy?.passkey??null;const t={uuid:o.randomUUID(),action:c.Event.CREATE,recovery:i.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:i.accessToken,playerID:i.playerID,thirdPartyProvider:i.thirdPartyProvider,thirdPartyTokenType:i.thirdPartyTokenType,encryptionKey:i.password,encryptionSession:i.recovery?.encryptionSession??null,passkey:i.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},n=await r.create(t);return c.isErrorResponse(n)&&this.handleError(n),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",n.version??"undefined"),n}async recover(r){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await e.Account.fromStorage(this.storage),t=await this.ensureConnection(),n=await this.buildIFrameRequestConfiguration();n.chainId=i?.chainId??null,n.password=r?.entropy?.recoveryPassword??null,n.recovery={...n.recovery,encryptionSession:r?.entropy?.encryptionSession},n.passkey=r?.entropy?.passkey??null;const s={uuid:o.randomUUID(),action:c.Event.RECOVER,recovery:n.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:n.accessToken,playerID:n.playerID,thirdPartyProvider:n.thirdPartyProvider,thirdPartyTokenType:n.thirdPartyTokenType,encryptionKey:n.password,encryptionSession:n.recovery?.encryptionSession??null,passkey:n.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:r.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},a=await t.recover(s);return c.isErrorResponse(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,r,i,t){s.debugLog("[iframe] ensureConnection");const n=await this.ensureConnection(),a=new c.SignRequest(o.randomUUID(),e,await this.buildRequestConfiguration(),r,i,t);s.debugLog("[iframe] done ensureConnection");const d=await n.sign(a);return s.debugLog("[iframe] response",d),c.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined"),d.signature}async switchChain(e){const r=await this.ensureConnection(),i=new c.SwitchChainRequest(o.randomUUID(),e,await this.buildRequestConfiguration()),t=await r.switchChain(i);return c.isErrorResponse(t)&&this.handleError(t),t}async export(){const e=await this.ensureConnection(),r=new c.ExportPrivateKeyRequest(o.randomUUID(),await this.buildRequestConfiguration()),i=await e.export(r);return c.isErrorResponse(i)&&this.handleError(i),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",i.version??"undefined"),i.key}async setRecoveryMethod(e,r,i,t,n){const s=await this.ensureConnection(),a=new c.SetRecoveryMethodRequest(o.randomUUID(),e,await this.buildRequestConfiguration(),r,i,t,n),d=await s.setRecoveryMethod(a);c.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined")}async getCurrentDevice(e){const r=await this.ensureConnection(),i=new c.GetCurrentDeviceRequest(o.randomUUID(),e);try{const e=await r.getCurrentDevice(i);return c.isErrorResponse(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof y)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void s.debugLog("IframeManager not loaded, skipping authentication update");const e=await r.Authentication.fromStorage(this.storage);if(!e)return void s.debugLog("No authentication found, skipping update");const i=new c.UpdateAuthenticationRequest(o.randomUUID(),e.token);s.debugLog("Updating authentication in iframe with token");const t=await this.remote.updateAuthentication(i);c.isErrorResponse(t)&&this.handleError(t)}async disconnect(){const e=await this.ensureConnection(),r={uuid:o.randomUUID()};await e.logout(r)}async onMessage(e){s.debugLog("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof a.ReactNativeMessenger?(this.isInitialized||this.connection?s.debugLog(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(s.debugLog("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{s.debugLog("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),s.debugLog("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):s.debugLog("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}},exports.MissingProjectEntropyError=g,exports.MissingRecoveryPasswordError=u,exports.NotConfiguredError=y,exports.OTPRequiredError=p,exports.WrongRecoveryPasswordError=l;
1
+ "use strict";var e=require("../core/configuration/account.js"),i=require("../core/configuration/authentication.js"),r=require("../core/errors/authErrorCodes.js"),t=require("../core/errors/openfortError.js"),n=require("../core/errors/sentry.js"),o=require("../storage/istorage.js"),s=require("../utils/crypto.js"),a=require("../utils/debug.js"),d=require("./messaging/ReactNativeMessenger.js"),c=require("./messaging/browserMessenger/connect.js");require("./messaging/browserMessenger/backwardCompatibility.js");var u=require("./types.js");class h extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class g extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class l extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class R extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class y extends t.SignerError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.NOT_CONFIGURED,"Signer is not configured")}}class E extends t.OpenfortError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.OTP_REQUIRED,"OTP verification required")}}exports.IframeManager=class{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;hasFailed=!1;constructor(e,i,r){if(!e)throw new t.ConfigurationError("Configuration is required for IframeManager");if(!i)throw new t.ConfigurationError("Storage is required for IframeManager");if(!r)throw new t.ConfigurationError("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=r}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){a.debugLog("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:a.debugLog}),this.connection=c({messenger:this.messenger,timeout:1e4,log:a.debugLog});try{this.remote=await this.connection.promise,a.debugLog("IframeManager connection established")}catch(e){const i=e;throw n.sentry.captureException(i),this.destroy(),a.debugLog("Failed to establish connection:",i),new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}`)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(u.isErrorResponse(e)){if(e.error===u.NOT_CONFIGURED_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new y;if(e.error===u.MISSING_USER_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.MISSING_PROJECT_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new l;if(e.error===u.INCORRECT_USER_ENTROPY_ERROR)throw new R;if(e.error===u.MISSING_PASSKEY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.INCORRECT_PASSKEY_ERROR)throw new g;if(e.error===u.OTP_REQUIRED_ERROR)throw new E;throw this.storage.remove(o.StorageKeys.ACCOUNT),new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=e.chainId??null,r.password=e?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:e?.entropy?.encryptionSession},r.passkey=e?.entropy?.passkey??null;const t={uuid:s.randomUUID(),action:u.Event.CREATE,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},n=await i.create(t);return u.isErrorResponse(n)&&this.handleError(n),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",n.version??"undefined"),n}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await e.Account.fromStorage(this.storage),t=await this.ensureConnection(),n=await this.buildIFrameRequestConfiguration();n.chainId=r?.chainId??null,n.password=i?.entropy?.recoveryPassword??null,n.recovery={...n.recovery,encryptionSession:i?.entropy?.encryptionSession},n.passkey=i?.entropy?.passkey??null;const o={uuid:s.randomUUID(),action:u.Event.RECOVER,recovery:n.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:n.accessToken,playerID:n.playerID,thirdPartyProvider:n.thirdPartyProvider,thirdPartyTokenType:n.thirdPartyTokenType,encryptionKey:n.password,encryptionSession:n.recovery?.encryptionSession??null,passkey:n.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},a=await t.recover(o);return u.isErrorResponse(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,i,r,t){a.debugLog("[iframe] ensureConnection");const n=await this.ensureConnection(),o=new u.SignRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,t);a.debugLog("[iframe] done ensureConnection");const d=await n.sign(o);return a.debugLog("[iframe] response",d),u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined"),d.signature}async switchChain(e){const i=await this.ensureConnection(),r=new u.SwitchChainRequest(s.randomUUID(),e,await this.buildRequestConfiguration()),t=await i.switchChain(r);return u.isErrorResponse(t)&&this.handleError(t),t}async export(){const e=await this.ensureConnection(),i=new u.ExportPrivateKeyRequest(s.randomUUID(),await this.buildRequestConfiguration()),r=await e.export(i);return u.isErrorResponse(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r.key}async setRecoveryMethod(e,i,r,t,n){const o=await this.ensureConnection(),a=new u.SetRecoveryMethodRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,t,n),d=await o.setRecoveryMethod(a);u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),r=new u.GetCurrentDeviceRequest(s.randomUUID(),e);try{const e=await i.getCurrentDevice(r);return u.isErrorResponse(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof y)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void a.debugLog("IframeManager not loaded, skipping authentication update");const e=await i.Authentication.fromStorage(this.storage);if(!e)return void a.debugLog("No authentication found, skipping update");const r=new u.UpdateAuthenticationRequest(s.randomUUID(),e.token);a.debugLog("Updating authentication in iframe with token");const t=await this.remote.updateAuthentication(r);u.isErrorResponse(t)&&this.handleError(t)}async disconnect(){const e=await this.ensureConnection(),i={uuid:s.randomUUID()};await e.logout(i)}async onMessage(e){a.debugLog("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof d.ReactNativeMessenger?(this.isInitialized||this.connection?a.debugLog(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(a.debugLog("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{a.debugLog("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),a.debugLog("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):a.debugLog("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}},exports.MissingProjectEntropyError=l,exports.MissingRecoveryPasswordError=h,exports.NotConfiguredError=y,exports.OTPRequiredError=E,exports.WrongPasskeyError=g,exports.WrongRecoveryPasswordError=R;