@openfort/openfort-js 0.10.4 → 0.10.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/sdk/src/api/embeddedWallet.js +1 -1
- package/dist/cjs/sdk/src/core/openfortInternal.js +1 -1
- package/dist/cjs/sdk/src/types/types.js +1 -1
- package/dist/cjs/sdk/src/version.js +1 -1
- package/dist/cjs/sdk/src/wallets/embedded.js +1 -1
- package/dist/cjs/sdk/src/wallets/evm/evmProvider.js +1 -1
- package/dist/cjs/sdk/src/wallets/iframeManager.js +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/sdk/src/api/embeddedWallet.js +1 -1
- package/dist/sdk/src/core/openfortInternal.js +1 -1
- package/dist/sdk/src/types/types.js +1 -1
- package/dist/sdk/src/version.js +1 -1
- package/dist/sdk/src/wallets/embedded.js +1 -1
- package/dist/sdk/src/wallets/evm/evmProvider.js +1 -1
- package/dist/sdk/src/wallets/iframeManager.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.js"),r=require("../core/config/config.js"),t=require("../core/configuration/account.js"),n=require("../core/configuration/authentication.js"),a=require("../core/errors/openfortError.js"),i=require("../types/types.js"),s=require("../utils/debug.js"),o=require("../wallets/embedded.js"),d=require("../wallets/evm/evmProvider.js");require("../wallets/evm/types.js");var c=require("../wallets/evm/provider/eip6963.js"),g=require("../wallets/evm/walletHelpers.js"),h=require("../wallets/iframeManager.js"),u=require("../wallets/messaging/ReactNativeMessenger.js");require("../wallets/messaging/browserMessenger/backwardCompatibility.js");var p=require("../wallets/messaging/browserMessenger/messengers/WindowMessenger.js");exports.EmbeddedWalletApi=class{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,r,t,n){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=n,this.eventEmitter.on(i.OpenfortEvents.TOKEN_REFRESHED,()=>{s.debugLog("Handling token refresh event in EmbeddedWalletApi"),this.handleTokenRefreshed()}),this.eventEmitter.on(i.OpenfortEvents.LOGGED_OUT,()=>{s.debugLog("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=r.SDKConfiguration.getInstance();if(!t)throw new a.OpenfortError("Configuration not found",a.OpenfortErrorType.INVALID_CONFIGURATION);return new e.BackendApiClients({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey})}async getIframeManager(){if(s.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager)return s.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return s.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;s.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return s.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,s.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw s.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,e}}async createIframeManager(){s.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=r.SDKConfiguration.getInstance();if(!e)throw s.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new a.OpenfortError("Configuration not found",a.OpenfortErrorType.INVALID_CONFIGURATION);let t;if(s.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)s.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger=new u.ReactNativeMessenger(this.messagePoster),s.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{s.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),n=new URL(e.iframeUrl).origin;t=new p({remoteWindow:r.contentWindow,allowedOrigins:[n]}),s.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return s.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new h.IframeManager(e,this.storage,t)}async ensureSigner(){if(this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();return new o.EmbeddedSigner(e,this.storage,this.backendApiClients,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new a.OpenfortError("Document is not available. Please provide a message poster for non-browser environments.",a.OpenfortErrorType.INVALID_CONFIGURATION);const r=document.getElementById("openfort-iframe");r&&r.remove();const t=document.createElement("iframe");return t.style.display="none",t.id="openfort-iframe",t.src=e,document.body.appendChild(t),s.debugLog("Iframe created and appended to document"),t}getEntropy(e){switch(e.recoveryMethod){case i.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case i.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};default:throw new a.OpenfortError("Invalid recovery method",a.OpenfortErrorType.INVALID_CONFIGURATION)}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:i.RecoveryMethod.AUTOMATIC},t=this.getEntropy(r),a=await this.ensureSigner(),s=await a.configure({chainId:e.chainId,entropy:t}),o=await n.Authentication.fromStorage(this.storage);return{id:s.id,chainId:s.chainId,user:o.player,address:s.address,ownerAddress:s.ownerAddress,chainType:s.chainType,accountType:s.accountType,implementationType:s.implementationType}}async create(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:i.RecoveryMethod.AUTOMATIC},t=this.getEntropy(r),a=await this.ensureSigner(),s=await a.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:t}),o=await n.Authentication.fromStorage(this.storage);return{id:s.id,chainId:s.chainId,user:o.player,address:s.address,ownerAddress:s.ownerAddress,chainType:s.chainType,accountType:s.accountType,implementationType:s.implementationType}}async recover(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:i.RecoveryMethod.AUTOMATIC},t=this.getEntropy(r),a=await this.ensureSigner(),s=await a.recover({account:e.account,entropy:t}),o=await n.Authentication.fromStorage(this.storage);return{id:s.id,chainId:s.chainId,user:o.player,address:s.address,ownerAddress:s.ownerAddress,chainType:s.chainType,accountType:s.accountType,implementationType:s.implementationType}}async signMessage(e,r){await this.validateAndRefreshToken();const n=await this.ensureSigner(),{hashMessage:a=!0,arrayifyMessage:i=!1}=r||{},s=await t.Account.fromStorage(this.storage);return await n.sign(e,i,a,s?.chainType)}async signTypedData(e,r,n){await this.validateAndRefreshToken();const i=await this.ensureSigner(),s=await t.Account.fromStorage(this.storage);if(!s)throw new a.OpenfortError("No account found",a.OpenfortErrorType.MISSING_SIGNER_ERROR);const o={...r};delete o.EIP712Domain;const{_TypedDataEncoder:d}=await import("@ethersproject/hash"),c=d.hash(e,o,n);return await g.signMessage({hash:c,implementationType:s.implementationType||s.type,chainId:Number(s.chainId),signer:i,address:s.address,ownerAddress:s.ownerAddress,factoryAddress:s.factoryAddress,salt:s.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner();let n,s;if(e.recoveryMethod===i.RecoveryMethod.PASSWORD?n=e.password:r.recoveryMethod===i.RecoveryMethod.PASSWORD&&(n=r.password),e.recoveryMethod===i.RecoveryMethod.AUTOMATIC?s=e.encryptionSession:r.recoveryMethod===i.RecoveryMethod.AUTOMATIC&&(s=r.encryptionSession),!n&&!s)throw new a.OpenfortError("Password or encryption session is not provided",a.OpenfortErrorType.INVALID_CONFIGURATION);await t.setRecoveryMethod({recoveryMethod:r.recoveryMethod,recoveryPassword:n,encryptionSession:s})}async get(){const e=await t.Account.fromStorage(this.storage);if(!e)throw new a.OpenfortError("No signer configured",a.OpenfortErrorType.MISSING_SIGNER_ERROR);const r=await n.Authentication.fromStorage(this.storage);if(!r)throw new a.OpenfortError("No access token found",a.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return{id:e.id,chainId:e.chainId,user:r.player,address:e.address,ownerAddress:e.ownerAddress,chainType:e.chainType,accountType:e.accountType,implementationType:e.implementationType}}async list(e){const t={accountType:i.AccountTypeEnum.SMART_ACCOUNT,...e},s=r.SDKConfiguration.getInstance();if(!s)throw new a.OpenfortError("Configuration not found",a.OpenfortErrorType.INVALID_CONFIGURATION);await this.validateAndRefreshToken();const o=await n.Authentication.fromStorage(this.storage);if(!o)throw new a.OpenfortError("No access token found",a.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return a.withOpenfortError(async()=>(await this.backendApiClients.accountsApi.getAccountsV2(t,{headers:{authorization:`Bearer ${s.baseConfiguration.publishableKey}`,"x-player-token":o.token,"x-auth-provider":o.thirdPartyProvider,"x-token-type":o.thirdPartyTokenType}})).data.data.map(e=>({user:e.user,chainType:e.chainType,id:e.id,address:e.address,ownerAddress:e.ownerAddress,accountType:e.accountType,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId})),{default:a.OpenfortErrorType.AUTHENTICATION_ERROR})}async getEmbeddedState(){try{if(!await n.Authentication.fromStorage(this.storage))return i.EmbeddedState.UNAUTHENTICATED;return await t.Account.fromStorage(this.storage)?i.EmbeddedState.READY:i.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return s.debugLog("Failed to get embedded state:",e),i.EmbeddedState.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},a=await n.Authentication.fromStorage(this.storage),i=await t.Account.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new d.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:i||void 0,authentication:a||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&c.announceProvider({info:{...c.openfortProviderInfo,...r.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(r=>{setTimeout(r,e)});const r=await this.getIframeManager();if(!r.isLoaded())return!1;const t=await n.Authentication.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.player),!0}catch(e){return!1}return r.isLoaded()}catch(e){return s.debugLog("Ping failed:",e),!1}}getURL(){const e=r.SDKConfiguration.getInstance();if(!e)throw new a.OpenfortError("Configuration not found",a.OpenfortErrorType.INVALID_CONFIGURATION);return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new a.OpenfortError("Invalid message poster",a.OpenfortErrorType.INVALID_CONFIGURATION);this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleTokenRefreshed(){if(this.iframeManager)try{await this.iframeManager.updateAuthentication(),s.debugLog("Updated IframeManager authentication after token refresh")}catch(e){s.debugLog("Failed to update IframeManager authentication:",e)}else s.debugLog("IframeManager not initialized, skipping authentication update")}async handleLogout(){const e=await this.ensureSigner();await e.disconnect(),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void s.debugLog("Invalid message received:",e);s.debugLog("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const r="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(r&&this.messenger&&this.messagePoster)return s.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();s.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&s.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),s.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),s.debugLog("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}};
|
|
1
|
+
"use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.js"),r=require("../core/config/config.js"),t=require("../core/configuration/account.js"),n=require("../core/configuration/authentication.js"),a=require("../core/errors/openfortError.js"),i=require("../types/types.js"),s=require("../utils/debug.js"),o=require("../wallets/embedded.js"),d=require("../wallets/evm/evmProvider.js");require("../wallets/evm/types.js");var c=require("../wallets/evm/provider/eip6963.js"),g=require("../wallets/evm/walletHelpers.js"),h=require("../wallets/iframeManager.js"),u=require("../wallets/messaging/ReactNativeMessenger.js");require("../wallets/messaging/browserMessenger/backwardCompatibility.js");var p=require("../wallets/messaging/browserMessenger/messengers/WindowMessenger.js");exports.EmbeddedWalletApi=class{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,r,t,n){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=n,this.eventEmitter.on(i.OpenfortEvents.LOGGED_OUT,()=>{s.debugLog("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=r.SDKConfiguration.getInstance();if(!t)throw new a.OpenfortError("Configuration not found",a.OpenfortErrorType.INVALID_CONFIGURATION);return new e.BackendApiClients({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey})}async getIframeManager(){if(s.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager)return s.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return s.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;s.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return s.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,s.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw s.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,e}}async createIframeManager(){s.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=r.SDKConfiguration.getInstance();if(!e)throw s.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new a.OpenfortError("Configuration not found",a.OpenfortErrorType.INVALID_CONFIGURATION);let t;if(s.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)s.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger=new u.ReactNativeMessenger(this.messagePoster),s.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{s.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),n=new URL(e.iframeUrl).origin;t=new p({remoteWindow:r.contentWindow,allowedOrigins:[n]}),s.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return s.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new h.IframeManager(e,this.storage,t)}async ensureSigner(){if(this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();return new o.EmbeddedSigner(e,this.storage,this.backendApiClients,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new a.OpenfortError("Document is not available. Please provide a message poster for non-browser environments.",a.OpenfortErrorType.INVALID_CONFIGURATION);const r=document.getElementById("openfort-iframe");r&&r.remove();const t=document.createElement("iframe");return t.style.display="none",t.id="openfort-iframe",t.src=e,document.body.appendChild(t),s.debugLog("Iframe created and appended to document"),t}getEntropy(e){switch(e.recoveryMethod){case i.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case i.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};default:throw new a.OpenfortError("Invalid recovery method",a.OpenfortErrorType.INVALID_CONFIGURATION)}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:i.RecoveryMethod.AUTOMATIC},t=this.getEntropy(r),a={chainId:e.chainId,entropy:t,accountType:e.accountType??i.AccountTypeEnum.SMART_ACCOUNT,chainType:e.chainType??i.ChainTypeEnum.EVM},s=await this.ensureSigner(),o=await s.configure(a),d=await n.Authentication.fromStorage(this.storage);return{id:o.id,chainId:o.chainId,user:d.player,address:o.address,ownerAddress:o.ownerAddress,chainType:o.chainType,accountType:o.accountType,implementationType:o.implementationType}}async create(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:i.RecoveryMethod.AUTOMATIC},t=this.getEntropy(r),a=await this.ensureSigner(),s=await a.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:t}),o=await n.Authentication.fromStorage(this.storage);return{id:s.id,chainId:s.chainId,user:o.player,address:s.address,ownerAddress:s.ownerAddress,chainType:s.chainType,accountType:s.accountType,implementationType:s.implementationType}}async recover(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:i.RecoveryMethod.AUTOMATIC},t=this.getEntropy(r),a=await this.ensureSigner(),s=await a.recover({account:e.account,entropy:t}),o=await n.Authentication.fromStorage(this.storage);return{id:s.id,chainId:s.chainId,user:o.player,address:s.address,ownerAddress:s.ownerAddress,chainType:s.chainType,accountType:s.accountType,implementationType:s.implementationType}}async signMessage(e,r){await this.validateAndRefreshToken();const n=await this.ensureSigner(),{hashMessage:a=!0,arrayifyMessage:i=!1}=r||{},s=await t.Account.fromStorage(this.storage);return await n.sign(e,i,a,s?.chainType)}async signTypedData(e,r,n){await this.validateAndRefreshToken();const i=await this.ensureSigner(),s=await t.Account.fromStorage(this.storage);if(!s)throw new a.OpenfortError("No account found",a.OpenfortErrorType.MISSING_SIGNER_ERROR);const o={...r};delete o.EIP712Domain;const{_TypedDataEncoder:d}=await import("@ethersproject/hash"),c=d.hash(e,o,n);return await g.signMessage({hash:c,implementationType:s.implementationType||s.type,chainId:Number(s.chainId),signer:i,address:s.address,ownerAddress:s.ownerAddress,factoryAddress:s.factoryAddress,salt:s.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner();let n,s;if(e.recoveryMethod===i.RecoveryMethod.PASSWORD?n=e.password:r.recoveryMethod===i.RecoveryMethod.PASSWORD&&(n=r.password),e.recoveryMethod===i.RecoveryMethod.AUTOMATIC?s=e.encryptionSession:r.recoveryMethod===i.RecoveryMethod.AUTOMATIC&&(s=r.encryptionSession),!n&&!s)throw new a.OpenfortError("Password or encryption session is not provided",a.OpenfortErrorType.INVALID_CONFIGURATION);await t.setRecoveryMethod({recoveryMethod:r.recoveryMethod,recoveryPassword:n,encryptionSession:s})}async get(){const e=await t.Account.fromStorage(this.storage);if(!e)throw new a.OpenfortError("No signer configured",a.OpenfortErrorType.MISSING_SIGNER_ERROR);const r=await n.Authentication.fromStorage(this.storage);if(!r)throw new a.OpenfortError("No access token found",a.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return{id:e.id,chainId:e.chainId,user:r.player,address:e.address,ownerAddress:e.ownerAddress,chainType:e.chainType,accountType:e.accountType,implementationType:e.implementationType}}async list(e){const t={accountType:i.AccountTypeEnum.SMART_ACCOUNT,...e},s=r.SDKConfiguration.getInstance();if(!s)throw new a.OpenfortError("Configuration not found",a.OpenfortErrorType.INVALID_CONFIGURATION);await this.validateAndRefreshToken();const o=await n.Authentication.fromStorage(this.storage);if(!o)throw new a.OpenfortError("No access token found",a.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return a.withOpenfortError(async()=>(await this.backendApiClients.accountsApi.getAccountsV2(t,{headers:{authorization:`Bearer ${s.baseConfiguration.publishableKey}`,"x-player-token":o.token,"x-auth-provider":o.thirdPartyProvider,"x-token-type":o.thirdPartyTokenType}})).data.data.map(e=>({user:e.user,chainType:e.chainType,id:e.id,address:e.address,ownerAddress:e.ownerAddress,accountType:e.accountType,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId})),{default:a.OpenfortErrorType.AUTHENTICATION_ERROR})}async getEmbeddedState(){try{if(!await n.Authentication.fromStorage(this.storage))return i.EmbeddedState.UNAUTHENTICATED;return await t.Account.fromStorage(this.storage)?i.EmbeddedState.READY:i.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return s.debugLog("Failed to get embedded state:",e),i.EmbeddedState.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},a=await n.Authentication.fromStorage(this.storage),i=await t.Account.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new d.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:i||void 0,authentication:a||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&c.announceProvider({info:{...c.openfortProviderInfo,...r.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(r=>{setTimeout(r,e)});const r=await this.getIframeManager();if(!r.isLoaded())return!1;const t=await n.Authentication.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.player),!0}catch(e){return!1}return r.isLoaded()}catch(e){return s.debugLog("Ping failed:",e),!1}}getURL(){const e=r.SDKConfiguration.getInstance();if(!e)throw new a.OpenfortError("Configuration not found",a.OpenfortErrorType.INVALID_CONFIGURATION);return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new a.OpenfortError("Invalid message poster",a.OpenfortErrorType.INVALID_CONFIGURATION);this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleTokenRefreshed(){if(this.iframeManager)try{await this.iframeManager.updateAuthentication(),s.debugLog("Updated IframeManager authentication after token refresh")}catch(e){s.debugLog("Failed to update IframeManager authentication:",e)}else s.debugLog("IframeManager not initialized, skipping authentication update")}async handleLogout(){const e=await this.ensureSigner();await e.disconnect(),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void s.debugLog("Invalid message received:",e);s.debugLog("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const r="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(r&&this.messenger&&this.messagePoster)return s.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();s.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&s.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),s.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),s.debugLog("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./errors/openfortError.js"),t=require("../types/types.js");require("../storage/istorage.js"),require("../wallets/messaging/browserMessenger/backwardCompatibility.js");var r=require("../utils/debug.js"),n=require("./configuration/authentication.js");require("../wallets/types.js"),require("./errors/sentry.js");var
|
|
1
|
+
"use strict";var e=require("./errors/openfortError.js"),t=require("../types/types.js");require("../storage/istorage.js"),require("../wallets/messaging/browserMessenger/backwardCompatibility.js");var r=require("../utils/debug.js"),n=require("./configuration/authentication.js");require("../wallets/types.js"),require("./errors/sentry.js");var o=require("./config/config.js");require("jose"),require("../wallets/evm/types.js"),require("../wallets/evm/JsonRpcError.js"),require("eventemitter3"),require("../wallets/evm/provider/eip6963.js");exports.OpenfortInternal=class{storage;authManager;eventEmitter;constructor(e,t,r){this.storage=e,this.authManager=t,this.eventEmitter=r}async getThirdPartyAuthToken(){const r=o.SDKConfiguration.getInstance();if(!r?.thirdPartyAuth)throw new e.OpenfortError("No third party configuration found",e.OpenfortErrorType.INTERNAL_ERROR);const{getAccessToken:i,provider:a}=r.thirdPartyAuth;if(!i||!a)throw new e.OpenfortError("Third party is not configured. Please configure getAccessToken and thirdPartyAuthProvider in your Openfort instance",e.OpenfortErrorType.INVALID_CONFIGURATION);const s=await i();if(!s)throw new e.OpenfortError("Could not get access token",e.OpenfortErrorType.AUTHENTICATION_ERROR);let u=(await n.Authentication.fromStorage(this.storage))?.player;if(!u){const e=await this.authManager.authenticateThirdParty(a,s,t.TokenType.ID_TOKEN);u=e?.id}return new n.Authentication("third_party",s,u,null,a,t.TokenType.ID_TOKEN).save(this.storage),s}async getAccessToken(){if(o.SDKConfiguration.getInstance()?.thirdPartyAuth)return this.getThirdPartyAuthToken();return(await n.Authentication.fromStorage(this.storage))?.token??null}async validateAndRefreshToken(i){if(o.SDKConfiguration.getInstance()?.thirdPartyAuth)return void await this.getThirdPartyAuthToken();const a=await n.Authentication.fromStorage(this.storage);if(!a)throw new e.OpenfortError("Must be logged in to validate and refresh token",e.OpenfortErrorType.NOT_LOGGED_IN_ERROR);let s;r.debugLog("validating credentials...");try{s=await this.authManager.validateCredentials(a,i)}catch(e){throw n.Authentication.clear(this.storage),this.eventEmitter.emit(t.OpenfortEvents.LOGGED_OUT),e}if(!s.player)throw new e.OpenfortError("No user found in credentials",e.OpenfortErrorType.INTERNAL_ERROR);s.accessToken!==a.token&&(r.debugLog("tokens refreshed"),new n.Authentication("jwt",s.accessToken,s.player,s.refreshToken).save(this.storage))}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e,o,t,r,E,A,p,s,d,i,T,n,a;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={})).LOGGED_OUT="loggedOut",o.SWITCH_ACCOUNT="switchAccount",
|
|
1
|
+
"use strict";var e,o,t,r,E,A,p,s,d,i,T,n,a;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={})).LOGGED_OUT="loggedOut",o.SWITCH_ACCOUNT="switchAccount",exports.RecoveryMethod=void 0,(t=exports.RecoveryMethod||(exports.RecoveryMethod={})).PASSWORD="password",t.AUTOMATIC="automatic",exports.AccountType=void 0,(r=exports.AccountType||(exports.AccountType={})).UPGRADEABLE_V4="Upgradeable_v04",r.MANAGED_V4="Managed_v04",r.ERC6551_V4="ERC6551_v04",r.ERC6551_V5="ERC6551_v05",r.RECOVERABLE_V4="Recoverable_v04",r.MANAGED_V5="Managed_v05",r.UPGRADEABLE_V5="Upgradeable_v05",r.UPGRADEABLE_V6="Upgradeable_v06",r.ZKSYNC_UPGRADEABLE_V1="zksync_upgradeable_v1",r.ZKSYNC_UPGRADEABLE_V2="zksync_upgradeable_v2",exports.AuthType=void 0,(E=exports.AuthType||(exports.AuthType={})).OPENFORT="openfort",E.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.LOOTLOCKER="lootlocker",p.PLAYFAB="playfab",p.SUPABASE="supabase",p.CUSTOM="custom",p.OIDC="oidc",exports.BasicAuthProvider=void 0,(s=exports.BasicAuthProvider||(exports.BasicAuthProvider={})).EMAIL="email",s.WALLET="wallet",exports.OAuthProvider=void 0,(d=exports.OAuthProvider||(exports.OAuthProvider={})).GOOGLE="google",d.TWITTER="twitter",d.APPLE="apple",d.FACEBOOK="facebook",d.DISCORD="discord",d.EPIC_GAMES="epic_games",d.LINE="line",exports.AuthActionRequiredActions=void 0,(exports.AuthActionRequiredActions||(exports.AuthActionRequiredActions={})).ACTION_VERIFY_EMAIL="verify_email",exports.CodeChallengeMethodEnum=void 0,(i=exports.CodeChallengeMethodEnum||(exports.CodeChallengeMethodEnum={})).PLAIN="plain",i.S256="S256",exports.AccountTypeEnum=void 0,(T=exports.AccountTypeEnum||(exports.AccountTypeEnum={})).EOA="Externally Owned Account",T.SMART_ACCOUNT="Smart Account",exports.ChainTypeEnum=void 0,(n=exports.ChainTypeEnum||(exports.ChainTypeEnum={})).EVM="EVM",n.SVM="SVM",exports.SortOrdering=void 0,(a=exports.SortOrdering||(exports.SortOrdering={})).ASC="asc",a.DESC="desc";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="0.10.
|
|
1
|
+
"use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="0.10.6";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var e=require("../core/configuration/authentication.js"),t=require("../core/errors/openfortError.js"),r=require("../types/types.js"),a=require("../core/configuration/account.js");require("./messaging/browserMessenger/backwardCompatibility.js");var n=require("../storage/istorage.js"),o=require("../core/config/config.js");require("./types.js"),require("../core/errors/sentry.js"),require("jose"),require("./evm/types.js"),require("./evm/JsonRpcError.js"),require("eventemitter3"),require("./evm/provider/eip6963.js");exports.EmbeddedSigner=class{iframeManager;storage;backendApiClients;eventEmitter;constructor(e,t,r,a){this.iframeManager=e,this.storage=t,this.backendApiClients=r,this.eventEmitter=a}async configure(n){const s=await e.Authentication.fromStorage(this.storage);if(!s)throw new t.OpenfortError("No access token found",t.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const i=o.SDKConfiguration.getInstance();if(!i)throw new t.OpenfortError("Configuration not found",t.OpenfortErrorType.INVALID_CONFIGURATION);const c=await a.Account.fromStorage(this.storage);let d;if(c){const e={account:c.id,...n.entropy&&{entropy:{...n.entropy.recoveryPassword&&{recoveryPassword:n.entropy.recoveryPassword},...n.entropy.encryptionSession&&{encryptionSession:n.entropy.encryptionSession}}}},t=await this.iframeManager.recover(e);d=t.account}else{const e=await this.backendApiClients.accountsApi.getAccountsV2({user:s.player,accountType:n.accountType,chainType:n.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={accountType:n.accountType,chainType:n.chainType,chainId:n.chainId,...n.entropy&&{entropy:{...n.entropy.recoveryPassword&&{recoveryPassword:n.entropy.recoveryPassword},...n.entropy.encryptionSession&&{encryptionSession:n.entropy.encryptionSession}}}},t=await this.iframeManager.create(e);d=t.account}else{const t={account:e.data.data[0].id,...n.entropy&&{entropy:{...n.entropy.recoveryPassword&&{recoveryPassword:n.entropy.recoveryPassword},...n.entropy.encryptionSession&&{encryptionSession:n.entropy.encryptionSession}}}},r=await this.iframeManager.recover(t);d=r.account}}return t.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 a.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,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress});return t.save(this.storage),this.eventEmitter.emit(r.OpenfortEvents.SWITCH_ACCOUNT,e.data.address),t},{default:t.OpenfortErrorType.AUTHENTICATION_ERROR})}async sign(e,t,r,a){return await this.iframeManager.sign(e,t,r,a)}async export(){return await this.iframeManager.export()}async switchChain({chainId:e}){const t=await this.iframeManager.switchChain(e),r=await a.Account.fromStorage(this.storage);new a.Account({...r,id:t.account,chainId:e}).save(this.storage)}async create(n){const s=await this.iframeManager.create(n),i=await e.Authentication.fromStorage(this.storage);if(!i)throw new t.OpenfortError("No access token found",t.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const c=o.SDKConfiguration.getInstance();if(!c)throw new t.OpenfortError("Configuration not found",t.OpenfortErrorType.INVALID_CONFIGURATION);return t.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 a.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,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress});return t.save(this.storage),this.eventEmitter.emit(r.OpenfortEvents.SWITCH_ACCOUNT,e.data.address),t},{default:t.OpenfortErrorType.AUTHENTICATION_ERROR})}async recover(n){const s=await this.iframeManager.recover(n),i=await e.Authentication.fromStorage(this.storage);if(!i)throw new t.OpenfortError("No access token found",t.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const c=o.SDKConfiguration.getInstance();if(!c)throw new t.OpenfortError("Configuration not found",t.OpenfortErrorType.INVALID_CONFIGURATION);return t.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 a.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,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress});return t.save(this.storage),this.eventEmitter.emit(r.OpenfortEvents.SWITCH_ACCOUNT,e.data.address),t},{default:t.OpenfortErrorType.AUTHENTICATION_ERROR})}async setRecoveryMethod({recoveryMethod:e,recoveryPassword:t,encryptionSession:r}){await this.iframeManager.setRecoveryMethod(e,t,r)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(n.StorageKeys.ACCOUNT)}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../
|
|
1
|
+
"use strict";var e=require("../../core/configuration/authentication.js"),t=require("./types.js"),r=require("./JsonRpcError.js"),i=require("./signTypedDataV4.js"),s=require("../../types/types.js"),a=require("../../utils/typedEventEmitter.js"),n=require("../../utils/chains/index.js"),o=require("../../core/configuration/account.js"),c=require("./addEthereumChain.js"),h=require("./registerSession.js"),d=require("./revokeSession.js"),u=require("./sendCalls.js"),p=require("./getCallsStatus.js"),l=require("./personalSign.js"),w=require("./estimateGas.js"),g=require("../../utils/crypto.js");exports.EvmProvider=class{#e;#t;#r;#i;updatePolicy(e){this.#t=e}#s;#a;#n=null;#o;isOpenfort=!0;#c;constructor({storage:e,backendApiClients:t,openfortEventEmitter:r,policyId:i,ensureSigner:n,chains:o,validateAndRefreshSession:c}){this.#c=n,this.#e=e,this.#r=o,this.#t=i,this.#s=c,this.#o=t,this.#o=t,this.#a=new a,r.on(s.OpenfortEvents.LOGGED_OUT,this.#h),r.on(s.OpenfortEvents.SWITCH_ACCOUNT,this.#d)}#u=async()=>(this.#i||(this.#i=await this.#c()),this.#i);#h=async()=>{this.#i=void 0,this.#a.emit(t.ProviderEvent.ACCOUNTS_CHANGED,[])};#d=async e=>{this.#a.emit(t.ProviderEvent.ACCOUNTS_CHANGED,[e])};async getRpcProvider(){if(!this.#n){const e=await o.Account.fromStorage(this.#e),t=e?.chainId||8453;await import("@ethersproject/providers").then(e=>{const r=this.#r?this.#r[t]:void 0;this.#n=new e.StaticJsonRpcProvider(r??n.defaultChainRpcs[t])})}if(!this.#n)throw new Error("RPC provider not initialized");return this.#n}async#p(s){switch(s.method){case"eth_accounts":{const e=await o.Account.fromStorage(this.#e);return e?[e.address]:[]}case"eth_requestAccounts":{const e=await o.Account.fromStorage(this.#e);if(e)return this.#a.emit(t.ProviderEvent.ACCOUNTS_CONNECT,{chainId:String(e.chainId)}),[e.address];throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer.")}case"eth_sendTransaction":{const t=await o.Account.fromStorage(this.#e),i=await this.#u(),a=await e.Authentication.fromStorage(this.#e);if(!t||!a)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await u.sendCalls({params:s.params||[],signer:i,account:t,authentication:a,backendClient:this.#o,policyId:this.#t})}case"eth_estimateGas":{const t=await o.Account.fromStorage(this.#e),i=await e.Authentication.fromStorage(this.#e);if(!t||!i)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await w.estimateGas({params:s.params||[],account:t,authentication:i,backendClient:this.#o,policyId:this.#t})}case"eth_signTypedData":case"eth_signTypedData_v4":{const e=await o.Account.fromStorage(this.#e),t=await this.#u();if(!e)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#s();const a=await this.getRpcProvider();return await i.signTypedDataV4({method:s.method,params:s.params||[],signer:t,implementationType:e.implementationType||e.type,rpcProvider:a,account:e})}case"personal_sign":{const e=await o.Account.fromStorage(this.#e);if(!e)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const t=await this.#u();return await this.#s(),await l.personalSign({params:s.params||[],signer:t,account:e})}case"eth_chainId":{const e=await this.getRpcProvider(),{chainId:t}=await e.detectNetwork();return g.numberToHex(t)}case"wallet_switchEthereumChain":{const e=await this.#u();if(!s.params||!Array.isArray(s.params)||0===s.params.length)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#s();try{const t=parseInt(s.params[0].chainId,16);await e.switchChain({chainId:t}),await import("@ethersproject/providers").then(e=>{const r=this.#r?this.#r[t]:void 0;this.#n=new e.StaticJsonRpcProvider(r??n.defaultChainRpcs[t])})}catch(e){const t=e;throw new r.JsonRpcError(r.RpcErrorCode.INTERNAL_ERROR,`Failed to switch chain: ${t.message}`)}return null}case"wallet_addEthereumChain":{await this.#u();const e=await this.getRpcProvider();return await c.addEthereumChain({params:s.params||[],rpcProvider:e,storage:this.#e})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const t=await o.Account.fromStorage(this.#e);await this.#u();const i=await e.Authentication.fromStorage(this.#e);if(!t||!i)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await p.getCallStatus({params:s.params||{},authentication:i,backendClient:this.#o,account:t})}case"wallet_sendCalls":{const t=await o.Account.fromStorage(this.#e),i=await this.#u(),a=await e.Authentication.fromStorage(this.#e);if(!t||!a)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await u.sendCalls({params:s.params?s.params[0].calls:[],signer:i,account:t,authentication:a,backendClient:this.#o,policyId:this.#t})}case"wallet_grantPermissions":{const t=await o.Account.fromStorage(this.#e),i=await this.#u(),a=await e.Authentication.fromStorage(this.#e);if(!t||!a)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await h.registerSession({params:s.params||[],signer:i,account:t,authentication:a,backendClient:this.#o,policyId:this.#t})}case"wallet_revokePermissions":{const t=await o.Account.fromStorage(this.#e),i=await this.#u(),a=await e.Authentication.fromStorage(this.#e);if(!t||!a)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await d.revokeSession({params:s.params||[],signer:i,account:t,authentication:a,backendClient:this.#o})}case"wallet_getCapabilities":{const e=await this.getRpcProvider(),{chainId:t}=await e.detectNetwork();return{[g.numberToHex(t)]:{permissions:{supported:!0,signerTypes:["account","key"],keyTypes:["secp256k1"],permissionTypes:["contract-calls"]},paymasterService:{supported:!0},atomicBatch:{supported:!0}}}}case"eth_gasPrice":case"eth_getBalance":case"eth_getCode":case"eth_getStorageAt":case"eth_call":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":case"eth_getTransactionCount":return(await this.getRpcProvider()).send(s.method,s.params||[]);default:throw new r.JsonRpcError(r.ProviderErrorCode.UNSUPPORTED_METHOD,`${s.method}: Method not supported`)}}async request(e){try{return this.#p(e)}catch(e){if(e instanceof r.JsonRpcError)throw e;if(e instanceof Error)throw new r.JsonRpcError(r.RpcErrorCode.INTERNAL_ERROR,e.message);throw new r.JsonRpcError(r.RpcErrorCode.INTERNAL_ERROR,"Internal error")}}on(e,t){this.#a.on(e,t)}removeListener(e,t){this.#a.off(e,t)}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../core/configuration/account.js"),i=require("./messaging/browserMessenger/connect.js");require("./messaging/browserMessenger/backwardCompatibility.js");var r=require("../storage/istorage.js"),t=require("../core/errors/openfortError.js"),n=require("../utils/debug.js"),o=require("../utils/crypto.js"),s=require("../core/configuration/authentication.js"),a=require("./messaging/ReactNativeMessenger.js"),c=require("./types.js"),d=require("../core/errors/sentry.js");class h extends Error{constructor(){super("This embedded signer requires a password to be recovered")}}class u extends Error{constructor(){super("MissingProjectEntropyError")}}class g extends Error{constructor(){super("Wrong recovery password for this embedded signer")}}class l extends Error{constructor(){super("Not configured")}}exports.IframeManager=class{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;constructor(e,i,r){if(!e)throw new t.OpenfortError("Configuration is required for IframeManager",t.OpenfortErrorType.INVALID_CONFIGURATION);if(!i)throw new t.OpenfortError("Storage is required for IframeManager",t.OpenfortErrorType.INVALID_CONFIGURATION);if(!r)throw new t.OpenfortError("Messenger is required for IframeManager",t.OpenfortErrorType.INVALID_CONFIGURATION);this.sdkConfiguration=e,this.storage=i,this.messenger=r}async initialize(){if(!this.isInitialized)if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.initializationPromise=null,e}}}async doInitialize(){n.debugLog("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:n.debugLog}),this.connection=i({messenger:this.messenger,timeout:1e4,log:n.debugLog});try{this.remote=await this.connection.promise,n.debugLog("IframeManager connection established")}catch(e){const i=e;throw d.sentry.captureException(i),this.destroy(),n.debugLog("Failed to establish connection:",i),new t.OpenfortError(`Failed to establish iFrame connection: ${i.cause||i.message}`,t.OpenfortErrorType.INTERNAL_ERROR,e)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new t.OpenfortError("Failed to establish connection",t.OpenfortErrorType.INTERNAL_ERROR);return this.remote}handleError(e){if(c.isErrorResponse(e)){if(e.error===c.NOT_CONFIGURED_ERROR)throw new l;if(e.error===c.MISSING_USER_ENTROPY_ERROR)throw this.storage.remove(r.StorageKeys.ACCOUNT),new h;if(e.error===c.MISSING_PROJECT_ENTROPY_ERROR)throw this.storage.remove(r.StorageKeys.ACCOUNT),new u;if(e.error===c.INCORRECT_USER_ENTROPY_ERROR)throw new g;throw new t.OpenfortError(`Unknown error: ${e.error}`,t.OpenfortErrorType.INTERNAL_ERROR)}throw e}async buildRequestConfiguration(){const e=await s.Authentication.fromStorage(this.storage);if(!e)throw new t.OpenfortError("Must be authenticated to create a signer",t.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl}}async buildIFrameRequestConfiguration(){const e=await s.Authentication.fromStorage(this.storage);if(!e)throw new t.OpenfortError("Must be authenticated to create a signer",t.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const i={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:i,chainId:null,password:null}}async configure(i){if(!this.sdkConfiguration.shieldConfiguration)throw new t.OpenfortError("shieldConfiguration is required",t.OpenfortErrorType.INVALID_CONFIGURATION);const r=await e.Account.fromStorage(this.storage),n=await this.ensureConnection(),s=await this.buildIFrameRequestConfiguration();s.chainId=i?.chainId??r?.chainId??null,s.password=i?.entropy?.recoveryPassword??null,s.recovery={...s.recovery,encryptionSession:i?.entropy?.encryptionSession};const a={uuid:o.randomUUID(),action:c.Event.CONFIGURE,chainId:s.chainId,recovery:s.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:s.accessToken,playerID:s.playerID,thirdPartyProvider:s.thirdPartyProvider,thirdPartyTokenType:s.thirdPartyTokenType,encryptionKey:s.password,encryptionPart:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??null,encryptionSession:s.recovery?.encryptionSession??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl},d=await n.configure(a);return c.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined"),d}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};const t={uuid:o.randomUUID(),action:c.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,encryptionPart:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??null,encryptionSession:r.recovery?.encryptionSession??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType},n=await i.create(t);return c.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};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,encryptionPart:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??null,encryptionSession:n.recovery?.encryptionSession??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account},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,i,r,t){n.debugLog("[iframe] ensureConnection");const s=await this.ensureConnection(),a=new c.SignRequest(o.randomUUID(),e,await this.buildRequestConfiguration(),i,r,t);n.debugLog("[iframe] done ensureConnection");try{const e=await s.sign(a);return n.debugLog("[iframe] response",e),c.isErrorResponse(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e.signature}catch(t){if(t instanceof l)return await this.configure(),this.sign(e,i,r);throw t}}async switchChain(e){const i=await this.ensureConnection(),r=new c.SwitchChainRequest(o.randomUUID(),e,await this.buildRequestConfiguration());try{const e=await i.switchChain(r);return c.isErrorResponse(e)&&this.handleError(e),e}catch(i){if(i instanceof l)return await this.configure(),this.switchChain(e);throw i}}async export(){const e=await this.ensureConnection(),i=new c.ExportPrivateKeyRequest(o.randomUUID(),await this.buildRequestConfiguration());try{const r=await e.export(i);return c.isErrorResponse(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r.key}catch(e){if(e instanceof l)return await this.configure(),this.export();throw e}}async setRecoveryMethod(e,i,r){const t=await this.ensureConnection(),n=new c.SetRecoveryMethodRequest(o.randomUUID(),e,i,r,await this.buildRequestConfiguration());try{const e=await t.setRecoveryMethod(n);c.isErrorResponse(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined")}catch(t){if(t instanceof l)return await this.configure(),this.setRecoveryMethod(e,i,r);throw t}}async getCurrentDevice(e){const i=await this.ensureConnection(),r=new c.GetCurrentDeviceRequest(o.randomUUID(),e);try{const e=await i.getCurrentDevice(r);return c.isErrorResponse(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof l)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void n.debugLog("IframeManager not loaded, skipping authentication update");const e=await s.Authentication.fromStorage(this.storage);if(!e)return void n.debugLog("No authentication found, skipping update");const i=new c.UpdateAuthenticationRequest(o.randomUUID(),e.token);try{n.debugLog("Updating authentication in iframe with token:",e.token);const r=await this.remote.updateAuthentication(i);c.isErrorResponse(r)&&this.handleError(r)}catch(e){if(e instanceof l)return await this.configure(),void await this.updateAuthentication();throw e}}async disconnect(){const e=await this.ensureConnection(),i={uuid:o.randomUUID()};await e.logout(i)}async onMessage(e){n.debugLog("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof a.ReactNativeMessenger?(this.isInitialized||this.connection?n.debugLog(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(n.debugLog("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{n.debugLog("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),n.debugLog("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):n.debugLog("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.messenger.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}},exports.MissingProjectEntropyError=u,exports.MissingRecoveryPasswordError=h,exports.NotConfiguredError=l,exports.WrongRecoveryPasswordError=g;
|
|
1
|
+
"use strict";var e=require("../core/configuration/account.js"),r=require("./messaging/browserMessenger/connect.js");require("./messaging/browserMessenger/backwardCompatibility.js");var i=require("../storage/istorage.js"),t=require("../core/errors/openfortError.js"),n=require("../utils/debug.js"),o=require("../utils/crypto.js"),s=require("../core/configuration/authentication.js"),a=require("./messaging/ReactNativeMessenger.js"),d=require("./types.js"),c=require("../core/errors/sentry.js");class u extends Error{constructor(){super("This embedded signer requires a password to be recovered")}}class h extends Error{constructor(){super("MissingProjectEntropyError")}}class g extends Error{constructor(){super("Wrong recovery password for this embedded signer")}}class l extends Error{constructor(){super("Not configured")}}exports.IframeManager=class{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;constructor(e,r,i){if(!e)throw new t.OpenfortError("Configuration is required for IframeManager",t.OpenfortErrorType.INVALID_CONFIGURATION);if(!r)throw new t.OpenfortError("Storage is required for IframeManager",t.OpenfortErrorType.INVALID_CONFIGURATION);if(!i)throw new t.OpenfortError("Messenger is required for IframeManager",t.OpenfortErrorType.INVALID_CONFIGURATION);this.sdkConfiguration=e,this.storage=r,this.messenger=i}async initialize(){if(!this.isInitialized)if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.initializationPromise=null,e}}}async doInitialize(){n.debugLog("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:n.debugLog}),this.connection=r({messenger:this.messenger,timeout:1e4,log:n.debugLog});try{this.remote=await this.connection.promise,n.debugLog("IframeManager connection established")}catch(e){const r=e;throw c.sentry.captureException(r),this.destroy(),n.debugLog("Failed to establish connection:",r),new t.OpenfortError(`Failed to establish iFrame connection: ${r.cause||r.message}`,t.OpenfortErrorType.INTERNAL_ERROR,e)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new t.OpenfortError("Failed to establish connection",t.OpenfortErrorType.INTERNAL_ERROR);return this.remote}handleError(e){if(d.isErrorResponse(e)){if(e.error===d.NOT_CONFIGURED_ERROR)throw this.storage.remove(i.StorageKeys.ACCOUNT),new l;if(e.error===d.MISSING_USER_ENTROPY_ERROR)throw this.storage.remove(i.StorageKeys.ACCOUNT),new u;if(e.error===d.MISSING_PROJECT_ENTROPY_ERROR)throw this.storage.remove(i.StorageKeys.ACCOUNT),new h;if(e.error===d.INCORRECT_USER_ENTROPY_ERROR)throw new g;throw new t.OpenfortError(`Unknown error: ${e.error}`,t.OpenfortErrorType.INTERNAL_ERROR)}throw e}async buildRequestConfiguration(){const e=await s.Authentication.fromStorage(this.storage);if(!e)throw new t.OpenfortError("Must be authenticated to create a signer",t.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl}}async buildIFrameRequestConfiguration(){const e=await s.Authentication.fromStorage(this.storage);if(!e)throw new t.OpenfortError("Must be authenticated to create a signer",t.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const r={auth:d.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:r,chainId:null,password: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};const t={uuid:o.randomUUID(),action:d.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,encryptionPart:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??null,encryptionSession:i.recovery?.encryptionSession??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType},n=await r.create(t);return d.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};const s={uuid:o.randomUUID(),action:d.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,encryptionPart:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??null,encryptionSession:n.recovery?.encryptionSession??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:r.account},a=await t.recover(s);return d.isErrorResponse(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,r,i,t){n.debugLog("[iframe] ensureConnection");const s=await this.ensureConnection(),a=new d.SignRequest(o.randomUUID(),e,await this.buildRequestConfiguration(),r,i,t);n.debugLog("[iframe] done ensureConnection");const c=await s.sign(a);return n.debugLog("[iframe] response",c),d.isErrorResponse(c)&&this.handleError(c),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",c.version??"undefined"),c.signature}async switchChain(e){const r=await this.ensureConnection(),i=new d.SwitchChainRequest(o.randomUUID(),e,await this.buildRequestConfiguration()),t=await r.switchChain(i);return d.isErrorResponse(t)&&this.handleError(t),t}async export(){const e=await this.ensureConnection(),r=new d.ExportPrivateKeyRequest(o.randomUUID(),await this.buildRequestConfiguration()),i=await e.export(r);return d.isErrorResponse(i)&&this.handleError(i),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",i.version??"undefined"),i.key}async setRecoveryMethod(e,r,i){const t=await this.ensureConnection(),n=new d.SetRecoveryMethodRequest(o.randomUUID(),e,r,i,await this.buildRequestConfiguration()),s=await t.setRecoveryMethod(n);d.isErrorResponse(s)&&this.handleError(s),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",s.version??"undefined")}async getCurrentDevice(e){const r=await this.ensureConnection(),i=new d.GetCurrentDeviceRequest(o.randomUUID(),e);try{const e=await r.getCurrentDevice(i);return d.isErrorResponse(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof l)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void n.debugLog("IframeManager not loaded, skipping authentication update");const e=await s.Authentication.fromStorage(this.storage);if(!e)return void n.debugLog("No authentication found, skipping update");const r=new d.UpdateAuthenticationRequest(o.randomUUID(),e.token);n.debugLog("Updating authentication in iframe with token");const i=await this.remote.updateAuthentication(r);d.isErrorResponse(i)&&this.handleError(i)}async disconnect(){const e=await this.ensureConnection(),r={uuid:o.randomUUID()};await e.logout(r)}async onMessage(e){n.debugLog("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof a.ReactNativeMessenger?(this.isInitialized||this.connection?n.debugLog(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(n.debugLog("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{n.debugLog("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),n.debugLog("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):n.debugLog("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.messenger.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}},exports.MissingProjectEntropyError=h,exports.MissingRecoveryPasswordError=u,exports.NotConfiguredError=l,exports.WrongRecoveryPasswordError=g;
|
package/dist/index.d.ts
CHANGED
|
@@ -50,12 +50,10 @@ declare enum EmbeddedState {
|
|
|
50
50
|
}
|
|
51
51
|
declare enum OpenfortEvents {
|
|
52
52
|
LOGGED_OUT = "loggedOut",
|
|
53
|
-
SWITCH_ACCOUNT = "switchAccount"
|
|
54
|
-
TOKEN_REFRESHED = "tokenRefreshed"
|
|
53
|
+
SWITCH_ACCOUNT = "switchAccount"
|
|
55
54
|
}
|
|
56
55
|
interface OpenfortEventMap extends Record<string, any> {
|
|
57
56
|
[OpenfortEvents.LOGGED_OUT]: [];
|
|
58
|
-
[OpenfortEvents.TOKEN_REFRESHED]: [];
|
|
59
57
|
[OpenfortEvents.SWITCH_ACCOUNT]: [string];
|
|
60
58
|
}
|
|
61
59
|
declare enum RecoveryMethod {
|
|
@@ -392,6 +390,8 @@ type EmbeddedAccount = {
|
|
|
392
390
|
type EmbeddedAccountConfigureParams = {
|
|
393
391
|
chainId?: number;
|
|
394
392
|
recoveryParams: RecoveryParams;
|
|
393
|
+
chainType?: ChainTypeEnum;
|
|
394
|
+
accountType?: AccountTypeEnum;
|
|
395
395
|
};
|
|
396
396
|
type EmbeddedAccountRecoverParams = {
|
|
397
397
|
account: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{SDKConfiguration as t}from"../core/config/config.js";import{Account as r}from"../core/configuration/account.js";import{Authentication as a}from"../core/configuration/authentication.js";import{OpenfortError as n,OpenfortErrorType as i,withOpenfortError as s}from"../core/errors/openfortError.js";import{OpenfortEvents as o,RecoveryMethod as d,AccountTypeEnum as c,EmbeddedState as h}from"../types/types.js";import{debugLog as g}from"../utils/debug.js";import{EmbeddedSigner as m}from"../wallets/embedded.js";import{EvmProvider as l}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as p,openfortProviderInfo as f}from"../wallets/evm/provider/eip6963.js";import{signMessage as u}from"../wallets/evm/walletHelpers.js";import{IframeManager as y}from"../wallets/iframeManager.js";import{ReactNativeMessenger as w}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import A from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class I{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,t,r,a){this.storage=e,this.validateAndRefreshToken=t,this.ensureInitialized=r,this.eventEmitter=a,this.eventEmitter.on(o.TOKEN_REFRESHED,()=>{g("Handling token refresh event in EmbeddedWalletApi"),this.handleTokenRefreshed()}),this.eventEmitter.on(o.LOGGED_OUT,()=>{g("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const r=t.getInstance();if(!r)throw new n("Configuration not found",i.INVALID_CONFIGURATION);return new e({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey})}async getIframeManager(){if(g("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager)return g("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return g("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;g("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return g("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,g("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw g("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,e}}async createIframeManager(){g("[HANDSHAKE DEBUG] createIframeManager starting");const e=t.getInstance();if(!e)throw g("[HANDSHAKE DEBUG] Configuration not found"),new n("Configuration not found",i.INVALID_CONFIGURATION);let r;if(g("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)g("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger=new w(this.messagePoster),g("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{g("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),a=new URL(e.iframeUrl).origin;r=new A({remoteWindow:t.contentWindow,allowedOrigins:[a]}),g("[HANDSHAKE DEBUG] Created WindowMessenger")}return g("[HANDSHAKE DEBUG] Creating IframeManager instance"),new y(e,this.storage,r)}async ensureSigner(){if(this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();return new m(e,this.storage,this.backendApiClients,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new n("Document is not available. Please provide a message poster for non-browser environments.",i.INVALID_CONFIGURATION);const t=document.getElementById("openfort-iframe");t&&t.remove();const r=document.createElement("iframe");return r.style.display="none",r.id="openfort-iframe",r.src=e,document.body.appendChild(r),g("Iframe created and appended to document"),r}getEntropy(e){switch(e.recoveryMethod){case d.PASSWORD:return{recoveryPassword:e.password};case d.AUTOMATIC:return{encryptionSession:e.encryptionSession};default:throw new n("Invalid recovery method",i.INVALID_CONFIGURATION)}}async configure(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:d.AUTOMATIC},r=this.getEntropy(t),n=await this.ensureSigner(),i=await n.configure({chainId:e.chainId,entropy:r}),s=await a.fromStorage(this.storage);return{id:i.id,chainId:i.chainId,user:s.player,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType}}async create(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:d.AUTOMATIC},r=this.getEntropy(t),n=await this.ensureSigner(),i=await n.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:r}),s=await a.fromStorage(this.storage);return{id:i.id,chainId:i.chainId,user:s.player,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType}}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:d.AUTOMATIC},r=this.getEntropy(t),n=await this.ensureSigner(),i=await n.recover({account:e.account,entropy:r}),s=await a.fromStorage(this.storage);return{id:i.id,chainId:i.chainId,user:s.player,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType}}async signMessage(e,t){await this.validateAndRefreshToken();const a=await this.ensureSigner(),{hashMessage:n=!0,arrayifyMessage:i=!1}=t||{},s=await r.fromStorage(this.storage);return await a.sign(e,i,n,s?.chainType)}async signTypedData(e,t,a){await this.validateAndRefreshToken();const s=await this.ensureSigner(),o=await r.fromStorage(this.storage);if(!o)throw new n("No account found",i.MISSING_SIGNER_ERROR);const d={...t};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),h=c.hash(e,d,a);return await u({hash:h,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:s,address:o.address,ownerAddress:o.ownerAddress,factoryAddress:o.factoryAddress,salt:o.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,t){await this.validateAndRefreshToken();const r=await this.ensureSigner();let a,s;if(e.recoveryMethod===d.PASSWORD?a=e.password:t.recoveryMethod===d.PASSWORD&&(a=t.password),e.recoveryMethod===d.AUTOMATIC?s=e.encryptionSession:t.recoveryMethod===d.AUTOMATIC&&(s=t.encryptionSession),!a&&!s)throw new n("Password or encryption session is not provided",i.INVALID_CONFIGURATION);await r.setRecoveryMethod({recoveryMethod:t.recoveryMethod,recoveryPassword:a,encryptionSession:s})}async get(){const e=await r.fromStorage(this.storage);if(!e)throw new n("No signer configured",i.MISSING_SIGNER_ERROR);const t=await a.fromStorage(this.storage);if(!t)throw new n("No access token found",i.NOT_LOGGED_IN_ERROR);return{id:e.id,chainId:e.chainId,user:t.player,address:e.address,ownerAddress:e.ownerAddress,chainType:e.chainType,accountType:e.accountType,implementationType:e.implementationType}}async list(e){const r={accountType:c.SMART_ACCOUNT,...e},o=t.getInstance();if(!o)throw new n("Configuration not found",i.INVALID_CONFIGURATION);await this.validateAndRefreshToken();const d=await a.fromStorage(this.storage);if(!d)throw new n("No access token found",i.NOT_LOGGED_IN_ERROR);return s(async()=>(await this.backendApiClients.accountsApi.getAccountsV2(r,{headers:{authorization:`Bearer ${o.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}})).data.data.map(e=>({user:e.user,chainType:e.chainType,id:e.id,address:e.address,ownerAddress:e.ownerAddress,accountType:e.accountType,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId})),{default:i.AUTHENTICATION_ERROR})}async getEmbeddedState(){try{if(!await a.fromStorage(this.storage))return h.UNAUTHENTICATED;return await r.fromStorage(this.storage)?h.READY:h.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return g("Failed to get embedded state:",e),h.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const t={announceProvider:!0,...e},n=await a.fromStorage(this.storage),i=await r.fromStorage(this.storage);return this.provider?this.provider&&t.policy&&this.provider.updatePolicy(t.policy):(this.provider=new l({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:i||void 0,authentication:n||void 0,backendApiClients:this.backendApiClients,policyId:t.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:t.chains}),t.announceProvider&&p({info:{...f,...t.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(t=>{setTimeout(t,e)});const t=await this.getIframeManager();if(!t.isLoaded())return!1;const r=await a.fromStorage(this.storage);if(r)try{return await t.getCurrentDevice(r.player),!0}catch(e){return!1}return t.isLoaded()}catch(e){return g("Ping failed:",e),!1}}getURL(){const e=t.getInstance();if(!e)throw new n("Configuration not found",i.INVALID_CONFIGURATION);return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new n("Invalid message poster",i.INVALID_CONFIGURATION);this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleTokenRefreshed(){if(this.iframeManager)try{await this.iframeManager.updateAuthentication(),g("Updated IframeManager authentication after token refresh")}catch(e){g("Failed to update IframeManager authentication:",e)}else g("IframeManager not initialized, skipping authentication update")}async handleLogout(){const e=await this.ensureSigner();await e.disconnect(),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void g("Invalid message received:",e);g("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const t="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(t&&this.messenger&&this.messagePoster)return g("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const r=await this.getIframeManager();g(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${r.isLoaded()}`),t&&!r.isLoaded()&&g("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),g("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await r.onMessage(e),g("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{I as EmbeddedWalletApi};
|
|
1
|
+
import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{SDKConfiguration as t}from"../core/config/config.js";import{Account as r}from"../core/configuration/account.js";import{Authentication as a}from"../core/configuration/authentication.js";import{OpenfortError as n,OpenfortErrorType as i,withOpenfortError as s}from"../core/errors/openfortError.js";import{OpenfortEvents as o,RecoveryMethod as d,AccountTypeEnum as c,ChainTypeEnum as g,EmbeddedState as h}from"../types/types.js";import{debugLog as m}from"../utils/debug.js";import{EmbeddedSigner as p}from"../wallets/embedded.js";import{EvmProvider as l}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as f,openfortProviderInfo as u}from"../wallets/evm/provider/eip6963.js";import{signMessage as y}from"../wallets/evm/walletHelpers.js";import{IframeManager as w}from"../wallets/iframeManager.js";import{ReactNativeMessenger as A}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import I from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class T{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,t,r,a){this.storage=e,this.validateAndRefreshToken=t,this.ensureInitialized=r,this.eventEmitter=a,this.eventEmitter.on(o.LOGGED_OUT,()=>{m("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const r=t.getInstance();if(!r)throw new n("Configuration not found",i.INVALID_CONFIGURATION);return new e({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey})}async getIframeManager(){if(m("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager)return m("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return m("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;m("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return m("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,m("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw m("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,e}}async createIframeManager(){m("[HANDSHAKE DEBUG] createIframeManager starting");const e=t.getInstance();if(!e)throw m("[HANDSHAKE DEBUG] Configuration not found"),new n("Configuration not found",i.INVALID_CONFIGURATION);let r;if(m("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)m("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger=new A(this.messagePoster),m("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{m("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),a=new URL(e.iframeUrl).origin;r=new I({remoteWindow:t.contentWindow,allowedOrigins:[a]}),m("[HANDSHAKE DEBUG] Created WindowMessenger")}return m("[HANDSHAKE DEBUG] Creating IframeManager instance"),new w(e,this.storage,r)}async ensureSigner(){if(this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();return new p(e,this.storage,this.backendApiClients,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new n("Document is not available. Please provide a message poster for non-browser environments.",i.INVALID_CONFIGURATION);const t=document.getElementById("openfort-iframe");t&&t.remove();const r=document.createElement("iframe");return r.style.display="none",r.id="openfort-iframe",r.src=e,document.body.appendChild(r),m("Iframe created and appended to document"),r}getEntropy(e){switch(e.recoveryMethod){case d.PASSWORD:return{recoveryPassword:e.password};case d.AUTOMATIC:return{encryptionSession:e.encryptionSession};default:throw new n("Invalid recovery method",i.INVALID_CONFIGURATION)}}async configure(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:d.AUTOMATIC},r=this.getEntropy(t),n={chainId:e.chainId,entropy:r,accountType:e.accountType??c.SMART_ACCOUNT,chainType:e.chainType??g.EVM},i=await this.ensureSigner(),s=await i.configure(n),o=await a.fromStorage(this.storage);return{id:s.id,chainId:s.chainId,user:o.player,address:s.address,ownerAddress:s.ownerAddress,chainType:s.chainType,accountType:s.accountType,implementationType:s.implementationType}}async create(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:d.AUTOMATIC},r=this.getEntropy(t),n=await this.ensureSigner(),i=await n.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:r}),s=await a.fromStorage(this.storage);return{id:i.id,chainId:i.chainId,user:s.player,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType}}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:d.AUTOMATIC},r=this.getEntropy(t),n=await this.ensureSigner(),i=await n.recover({account:e.account,entropy:r}),s=await a.fromStorage(this.storage);return{id:i.id,chainId:i.chainId,user:s.player,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType}}async signMessage(e,t){await this.validateAndRefreshToken();const a=await this.ensureSigner(),{hashMessage:n=!0,arrayifyMessage:i=!1}=t||{},s=await r.fromStorage(this.storage);return await a.sign(e,i,n,s?.chainType)}async signTypedData(e,t,a){await this.validateAndRefreshToken();const s=await this.ensureSigner(),o=await r.fromStorage(this.storage);if(!o)throw new n("No account found",i.MISSING_SIGNER_ERROR);const d={...t};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),g=c.hash(e,d,a);return await y({hash:g,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:s,address:o.address,ownerAddress:o.ownerAddress,factoryAddress:o.factoryAddress,salt:o.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,t){await this.validateAndRefreshToken();const r=await this.ensureSigner();let a,s;if(e.recoveryMethod===d.PASSWORD?a=e.password:t.recoveryMethod===d.PASSWORD&&(a=t.password),e.recoveryMethod===d.AUTOMATIC?s=e.encryptionSession:t.recoveryMethod===d.AUTOMATIC&&(s=t.encryptionSession),!a&&!s)throw new n("Password or encryption session is not provided",i.INVALID_CONFIGURATION);await r.setRecoveryMethod({recoveryMethod:t.recoveryMethod,recoveryPassword:a,encryptionSession:s})}async get(){const e=await r.fromStorage(this.storage);if(!e)throw new n("No signer configured",i.MISSING_SIGNER_ERROR);const t=await a.fromStorage(this.storage);if(!t)throw new n("No access token found",i.NOT_LOGGED_IN_ERROR);return{id:e.id,chainId:e.chainId,user:t.player,address:e.address,ownerAddress:e.ownerAddress,chainType:e.chainType,accountType:e.accountType,implementationType:e.implementationType}}async list(e){const r={accountType:c.SMART_ACCOUNT,...e},o=t.getInstance();if(!o)throw new n("Configuration not found",i.INVALID_CONFIGURATION);await this.validateAndRefreshToken();const d=await a.fromStorage(this.storage);if(!d)throw new n("No access token found",i.NOT_LOGGED_IN_ERROR);return s(async()=>(await this.backendApiClients.accountsApi.getAccountsV2(r,{headers:{authorization:`Bearer ${o.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}})).data.data.map(e=>({user:e.user,chainType:e.chainType,id:e.id,address:e.address,ownerAddress:e.ownerAddress,accountType:e.accountType,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId})),{default:i.AUTHENTICATION_ERROR})}async getEmbeddedState(){try{if(!await a.fromStorage(this.storage))return h.UNAUTHENTICATED;return await r.fromStorage(this.storage)?h.READY:h.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return m("Failed to get embedded state:",e),h.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const t={announceProvider:!0,...e},n=await a.fromStorage(this.storage),i=await r.fromStorage(this.storage);return this.provider?this.provider&&t.policy&&this.provider.updatePolicy(t.policy):(this.provider=new l({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:i||void 0,authentication:n||void 0,backendApiClients:this.backendApiClients,policyId:t.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:t.chains}),t.announceProvider&&f({info:{...u,...t.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(t=>{setTimeout(t,e)});const t=await this.getIframeManager();if(!t.isLoaded())return!1;const r=await a.fromStorage(this.storage);if(r)try{return await t.getCurrentDevice(r.player),!0}catch(e){return!1}return t.isLoaded()}catch(e){return m("Ping failed:",e),!1}}getURL(){const e=t.getInstance();if(!e)throw new n("Configuration not found",i.INVALID_CONFIGURATION);return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new n("Invalid message poster",i.INVALID_CONFIGURATION);this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleTokenRefreshed(){if(this.iframeManager)try{await this.iframeManager.updateAuthentication(),m("Updated IframeManager authentication after token refresh")}catch(e){m("Failed to update IframeManager authentication:",e)}else m("IframeManager not initialized, skipping authentication update")}async handleLogout(){const e=await this.ensureSigner();await e.disconnect(),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void m("Invalid message received:",e);m("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const t="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(t&&this.messenger&&this.messagePoster)return m("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const r=await this.getIframeManager();m(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${r.isLoaded()}`),t&&!r.isLoaded()&&m("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),m("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await r.onMessage(e),m("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{T as EmbeddedWalletApi};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{OpenfortError as t,OpenfortErrorType as e}from"./errors/openfortError.js";import{TokenType as r,OpenfortEvents as
|
|
1
|
+
import{OpenfortError as t,OpenfortErrorType as e}from"./errors/openfortError.js";import{TokenType as r,OpenfortEvents as a}from"../types/types.js";import"../storage/istorage.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import{debugLog as o}from"../utils/debug.js";import{Authentication as s}from"./configuration/authentication.js";import"../wallets/types.js";import"./errors/sentry.js";import{SDKConfiguration as i}from"./config/config.js";import"jose";import"../wallets/evm/types.js";import"../wallets/evm/JsonRpcError.js";import"eventemitter3";import"../wallets/evm/provider/eip6963.js";class n{storage;authManager;eventEmitter;constructor(t,e,r){this.storage=t,this.authManager=e,this.eventEmitter=r}async getThirdPartyAuthToken(){const a=i.getInstance();if(!a?.thirdPartyAuth)throw new t("No third party configuration found",e.INTERNAL_ERROR);const{getAccessToken:o,provider:n}=a.thirdPartyAuth;if(!o||!n)throw new t("Third party is not configured. Please configure getAccessToken and thirdPartyAuthProvider in your Openfort instance",e.INVALID_CONFIGURATION);const h=await o();if(!h)throw new t("Could not get access token",e.AUTHENTICATION_ERROR);let c=(await s.fromStorage(this.storage))?.player;if(!c){const t=await this.authManager.authenticateThirdParty(n,h,r.ID_TOKEN);c=t?.id}return new s("third_party",h,c,null,n,r.ID_TOKEN).save(this.storage),h}async getAccessToken(){if(i.getInstance()?.thirdPartyAuth)return this.getThirdPartyAuthToken();return(await s.fromStorage(this.storage))?.token??null}async validateAndRefreshToken(r){if(i.getInstance()?.thirdPartyAuth)return void await this.getThirdPartyAuthToken();const n=await s.fromStorage(this.storage);if(!n)throw new t("Must be logged in to validate and refresh token",e.NOT_LOGGED_IN_ERROR);let h;o("validating credentials...");try{h=await this.authManager.validateCredentials(n,r)}catch(t){throw s.clear(this.storage),this.eventEmitter.emit(a.LOGGED_OUT),t}if(!h.player)throw new t("No user found in credentials",e.INTERNAL_ERROR);h.accessToken!==n.token&&(o("tokens refreshed"),new s("jwt",h.accessToken,h.player,h.refreshToken).save(this.storage))}}export{n as OpenfortInternal};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var E,A,
|
|
1
|
+
var E,A,_,n,e,o,a,c,t,C,T,O,N,R;!function(E){E[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"}(E||(E={})),function(E){E.LOGGED_OUT="loggedOut",E.SWITCH_ACCOUNT="switchAccount"}(A||(A={})),function(E){E.PASSWORD="password",E.AUTOMATIC="automatic"}(_||(_={})),function(E){E.UPGRADEABLE_V4="Upgradeable_v04",E.MANAGED_V4="Managed_v04",E.ERC6551_V4="ERC6551_v04",E.ERC6551_V5="ERC6551_v05",E.RECOVERABLE_V4="Recoverable_v04",E.MANAGED_V5="Managed_v05",E.UPGRADEABLE_V5="Upgradeable_v05",E.UPGRADEABLE_V6="Upgradeable_v06",E.ZKSYNC_UPGRADEABLE_V1="zksync_upgradeable_v1",E.ZKSYNC_UPGRADEABLE_V2="zksync_upgradeable_v2"}(n||(n={})),function(E){E.OPENFORT="openfort",E.THIRD_PARTY="thirdParty"}(e||(e={})),function(E){E.ID_TOKEN="idToken",E.CUSTOM_TOKEN="customToken"}(o||(o={})),function(E){E.ACCELBYTE="accelbyte",E.FIREBASE="firebase",E.LOOTLOCKER="lootlocker",E.PLAYFAB="playfab",E.SUPABASE="supabase",E.CUSTOM="custom",E.OIDC="oidc"}(a||(a={})),function(E){E.EMAIL="email",E.WALLET="wallet"}(c||(c={})),function(E){E.GOOGLE="google",E.TWITTER="twitter",E.APPLE="apple",E.FACEBOOK="facebook",E.DISCORD="discord",E.EPIC_GAMES="epic_games",E.LINE="line"}(t||(t={})),function(E){E.ACTION_VERIFY_EMAIL="verify_email"}(C||(C={})),function(E){E.PLAIN="plain",E.S256="S256"}(T||(T={})),function(E){E.EOA="Externally Owned Account",E.SMART_ACCOUNT="Smart Account"}(O||(O={})),function(E){E.EVM="EVM",E.SVM="SVM"}(N||(N={})),function(E){E.ASC="asc",E.DESC="desc"}(R||(R={}));export{n as AccountType,O as AccountTypeEnum,C as AuthActionRequiredActions,e as AuthType,c as BasicAuthProvider,N as ChainTypeEnum,T as CodeChallengeMethodEnum,E as EmbeddedState,t as OAuthProvider,A as OpenfortEvents,_ as RecoveryMethod,R as SortOrdering,a as ThirdPartyAuthProvider,o as TokenType};
|
package/dist/sdk/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.10.
|
|
1
|
+
const o="0.10.6",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Authentication as t}from"../core/configuration/authentication.js";import{OpenfortError as
|
|
1
|
+
import{Authentication as t}from"../core/configuration/authentication.js";import{OpenfortError as e,OpenfortErrorType as a,withOpenfortError as r}from"../core/errors/openfortError.js";import{OpenfortEvents as o}from"../types/types.js";import{Account as n}from"../core/configuration/account.js";import"./messaging/browserMessenger/backwardCompatibility.js";import{StorageKeys as s}from"../storage/istorage.js";import{SDKConfiguration as i}from"../core/config/config.js";import"./types.js";import"../core/errors/sentry.js";import"jose";import"./evm/types.js";import"./evm/JsonRpcError.js";import"eventemitter3";import"./evm/provider/eip6963.js";class c{iframeManager;storage;backendApiClients;eventEmitter;constructor(t,e,a,r){this.iframeManager=t,this.storage=e,this.backendApiClients=a,this.eventEmitter=r}async configure(s){const c=await t.fromStorage(this.storage);if(!c)throw new e("No access token found",a.NOT_LOGGED_IN_ERROR);const d=i.getInstance();if(!d)throw new e("Configuration not found",a.INVALID_CONFIGURATION);const p=await n.fromStorage(this.storage);let y;if(p){const t={account:p.id,...s.entropy&&{entropy:{...s.entropy.recoveryPassword&&{recoveryPassword:s.entropy.recoveryPassword},...s.entropy.encryptionSession&&{encryptionSession:s.entropy.encryptionSession}}}},e=await this.iframeManager.recover(t);y=e.account}else{const t=await this.backendApiClients.accountsApi.getAccountsV2({user:c.player,accountType:s.accountType,chainType:s.chainType},{headers:{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}});if(0===t.data.data.length){const t={accountType:s.accountType,chainType:s.chainType,chainId:s.chainId,...s.entropy&&{entropy:{...s.entropy.recoveryPassword&&{recoveryPassword:s.entropy.recoveryPassword},...s.entropy.encryptionSession&&{encryptionSession:s.entropy.encryptionSession}}}},e=await this.iframeManager.create(t);y=e.account}else{const e={account:t.data.data[0].id,...s.entropy&&{entropy:{...s.entropy.recoveryPassword&&{recoveryPassword:s.entropy.recoveryPassword},...s.entropy.encryptionSession&&{encryptionSession:s.entropy.encryptionSession}}}},a=await this.iframeManager.recover(e);y=a.account}}return r(async()=>{const t=await this.backendApiClients.accountsApi.getAccountV2({id:y},{headers:{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}}),e=new n({user:t.data.user,chainType:t.data.chainType,id:t.data.id,address:t.data.address,ownerAddress:t.data.ownerAddress,accountType:t.data.accountType,createdAt:t.data.createdAt,implementationType:t.data.smartAccount?.implementationType,chainId:t.data.chainId,salt:t.data.smartAccount?.salt,factoryAddress:t.data.smartAccount?.factoryAddress});return e.save(this.storage),this.eventEmitter.emit(o.SWITCH_ACCOUNT,t.data.address),e},{default:a.AUTHENTICATION_ERROR})}async sign(t,e,a,r){return await this.iframeManager.sign(t,e,a,r)}async export(){return await this.iframeManager.export()}async switchChain({chainId:t}){const e=await this.iframeManager.switchChain(t),a=await n.fromStorage(this.storage);new n({...a,id:e.account,chainId:t}).save(this.storage)}async create(s){const c=await this.iframeManager.create(s),d=await t.fromStorage(this.storage);if(!d)throw new e("No access token found",a.NOT_LOGGED_IN_ERROR);const p=i.getInstance();if(!p)throw new e("Configuration not found",a.INVALID_CONFIGURATION);return r(async()=>{const t=await this.backendApiClients.accountsApi.getAccountV2({id:c.account},{headers:{authorization:`Bearer ${p.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}}),e=new n({user:t.data.user,chainType:t.data.chainType,id:t.data.id,address:t.data.address,ownerAddress:t.data.ownerAddress,accountType:t.data.accountType,createdAt:t.data.createdAt,implementationType:t.data.smartAccount?.implementationType,chainId:t.data.chainId,salt:t.data.smartAccount?.salt,factoryAddress:t.data.smartAccount?.factoryAddress});return e.save(this.storage),this.eventEmitter.emit(o.SWITCH_ACCOUNT,t.data.address),e},{default:a.AUTHENTICATION_ERROR})}async recover(s){const c=await this.iframeManager.recover(s),d=await t.fromStorage(this.storage);if(!d)throw new e("No access token found",a.NOT_LOGGED_IN_ERROR);const p=i.getInstance();if(!p)throw new e("Configuration not found",a.INVALID_CONFIGURATION);return r(async()=>{const t=await this.backendApiClients.accountsApi.getAccountV2({id:c.account},{headers:{authorization:`Bearer ${p.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}}),e=new n({user:t.data.user,chainType:t.data.chainType,id:t.data.id,address:t.data.address,ownerAddress:t.data.ownerAddress,accountType:t.data.accountType,createdAt:t.data.createdAt,implementationType:t.data.smartAccount?.implementationType,chainId:t.data.chainId,salt:t.data.smartAccount?.salt,factoryAddress:t.data.smartAccount?.factoryAddress});return e.save(this.storage),this.eventEmitter.emit(o.SWITCH_ACCOUNT,t.data.address),e},{default:a.AUTHENTICATION_ERROR})}async setRecoveryMethod({recoveryMethod:t,recoveryPassword:e,encryptionSession:a}){await this.iframeManager.setRecoveryMethod(t,e,a)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(s.ACCOUNT)}}export{c as EmbeddedSigner};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Authentication as t}from"../../core/configuration/authentication.js";import{ProviderEvent as e}from"./types.js";import{JsonRpcError as a,ProviderErrorCode as i,RpcErrorCode as s}from"./JsonRpcError.js";import{signTypedDataV4 as r}from"./signTypedDataV4.js";import{OpenfortEvents as n}from"../../types/types.js";import o from"../../utils/typedEventEmitter.js";import{defaultChainRpcs as c}from"../../utils/chains/index.js";import{Account as h}from"../../core/configuration/account.js";import{addEthereumChain as d}from"./addEthereumChain.js";import{registerSession as p}from"./registerSession.js";import{revokeSession as m}from"./revokeSession.js";import{sendCalls as l}from"./sendCalls.js";import{getCallStatus as u}from"./getCallsStatus.js";import{personalSign as w}from"./personalSign.js";import{estimateGas as g}from"./estimateGas.js";import{numberToHex as f}from"../../utils/crypto.js";class S{#t;#e;#a;#i;updatePolicy(t){this.#e=t}#s;#r;#n=null;#o;isOpenfort=!0;#c;constructor({storage:t,backendApiClients:e,openfortEventEmitter:a,policyId:i,ensureSigner:s,chains:r,validateAndRefreshSession:c}){this.#c=s,this.#t=t,this.#a=r,this.#e=i,this.#s=c,this.#o=e,this.#o=e,this.#r=new o,a.on(n.LOGGED_OUT,this.#h),a.on(n.SWITCH_ACCOUNT,this.#d)}#p=async()=>(this.#i||(this.#i=await this.#c()),this.#i);#h=async()=>{this.#i=void 0,this.#r.emit(e.ACCOUNTS_CHANGED,[])};#d=async t=>{this.#r.emit(e.ACCOUNTS_CHANGED,[t])};async getRpcProvider(){if(!this.#n){const t=await h.fromStorage(this.#t),e=t?.chainId||8453;await import("@ethersproject/providers").then(t=>{const a=this.#a?this.#a[e]:void 0;this.#n=new t.StaticJsonRpcProvider(a??c[e])})}if(!this.#n)throw new Error("RPC provider not initialized");return this.#n}async#m(n){switch(n.method){case"eth_accounts":{const t=await h.fromStorage(this.#t);return t?[t.address]:[]}case"eth_requestAccounts":{const t=await h.fromStorage(this.#t);if(t)return this.#r.emit(e.ACCOUNTS_CONNECT,{chainId:String(t.chainId)}),[t.address];throw new a(i.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer.")}case"eth_sendTransaction":{const e=await h.fromStorage(this.#t),s=await this.#p(),r=await t.fromStorage(this.#t);if(!e||!r)throw new a(i.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await l({params:n.params||[],signer:s,account:e,authentication:r,backendClient:this.#o,policyId:this.#e})}case"eth_estimateGas":{const e=await h.fromStorage(this.#t),s=await t.fromStorage(this.#t);if(!e||!s)throw new a(i.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await g({params:n.params||[],account:e,authentication:s,backendClient:this.#o,policyId:this.#e})}case"eth_signTypedData":case"eth_signTypedData_v4":{const t=await h.fromStorage(this.#t),e=await this.#p();if(!t)throw new a(i.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#s();const s=await this.getRpcProvider();return await r({method:n.method,params:n.params||[],signer:e,implementationType:t.implementationType||t.type,rpcProvider:s,account:t})}case"personal_sign":{const t=await h.fromStorage(this.#t);if(!t)throw new a(i.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const e=await this.#p();return await this.#s(),await w({params:n.params||[],signer:e,account:t})}case"eth_chainId":{const t=await this.getRpcProvider(),{chainId:e}=await t.detectNetwork();return f(e)}case"wallet_switchEthereumChain":{const t=await this.#p();if(!n.params||!Array.isArray(n.params)||0===n.params.length)throw new a(s.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#s();try{const e=parseInt(n.params[0].chainId,16);await t.switchChain({chainId:e}),await import("@ethersproject/providers").then(t=>{const a=this.#a?this.#a[e]:void 0;this.#n=new t.StaticJsonRpcProvider(a??c[e])})}catch(t){const e=t;throw new a(s.INTERNAL_ERROR,`Failed to switch chain: ${e.message}`)}return null}case"wallet_addEthereumChain":{await this.#p();const t=await this.getRpcProvider();return await d({params:n.params||[],rpcProvider:t,storage:this.#t})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const e=await h.fromStorage(this.#t);await this.#p();const s=await t.fromStorage(this.#t);if(!e||!s)throw new a(i.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await u({params:n.params||{},authentication:s,backendClient:this.#o,account:e})}case"wallet_sendCalls":{const e=await h.fromStorage(this.#t),s=await this.#p(),r=await t.fromStorage(this.#t);if(!e||!r)throw new a(i.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await l({params:n.params?n.params[0].calls:[],signer:s,account:e,authentication:r,backendClient:this.#o,policyId:this.#e})}case"wallet_grantPermissions":{const e=await h.fromStorage(this.#t),s=await this.#p(),r=await t.fromStorage(this.#t);if(!e||!r)throw new a(i.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await p({params:n.params||[],signer:s,account:e,authentication:r,backendClient:this.#o,policyId:this.#e})}case"wallet_revokePermissions":{const e=await h.fromStorage(this.#t),s=await this.#p(),r=await t.fromStorage(this.#t);if(!e||!r)throw new a(i.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await m({params:n.params||[],signer:s,account:e,authentication:r,backendClient:this.#o})}case"wallet_getCapabilities":{const t=await this.getRpcProvider(),{chainId:e}=await t.detectNetwork();return{[f(e)]:{permissions:{supported:!0,signerTypes:["account","key"],keyTypes:["secp256k1"],permissionTypes:["contract-calls"]},paymasterService:{supported:!0},atomicBatch:{supported:!0}}}}case"eth_gasPrice":case"eth_getBalance":case"eth_getCode":case"eth_getStorageAt":case"eth_call":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":case"eth_getTransactionCount":return(await this.getRpcProvider()).send(n.method,n.params||[]);default:throw new a(i.UNSUPPORTED_METHOD,`${n.method}: Method not supported`)}}async request(t){try{return this.#m(t)}catch(t){if(t instanceof a)throw t;if(t instanceof Error)throw new a(s.INTERNAL_ERROR,t.message);throw new a(s.INTERNAL_ERROR,"Internal error")}}on(t,e){this.#r.on(t,e)}removeListener(t,e){this.#r.off(t,e)}}export{S as EvmProvider};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Account as e}from"../core/configuration/account.js";import i from"./messaging/browserMessenger/connect.js";import"./messaging/browserMessenger/backwardCompatibility.js";import{StorageKeys as t}from"../storage/istorage.js";import{OpenfortError as n,OpenfortErrorType as r}from"../core/errors/openfortError.js";import{debugLog as o}from"../utils/debug.js";import{randomUUID as s}from"../utils/crypto.js";import{Authentication as a}from"../core/configuration/authentication.js";import{ReactNativeMessenger as c}from"./messaging/ReactNativeMessenger.js";import{isErrorResponse as h,NOT_CONFIGURED_ERROR as d,MISSING_USER_ENTROPY_ERROR as u,MISSING_PROJECT_ENTROPY_ERROR as l,INCORRECT_USER_ENTROPY_ERROR as y,ShieldAuthType as f,Event as g,SignRequest as p,SwitchChainRequest as w,ExportPrivateKeyRequest as m,SetRecoveryMethodRequest as C,GetCurrentDeviceRequest as I,UpdateAuthenticationRequest as v}from"./types.js";import{sentry as k}from"../core/errors/sentry.js";class P extends Error{constructor(){super("This embedded signer requires a password to be recovered")}}class b extends Error{constructor(){super("MissingProjectEntropyError")}}class E extends Error{constructor(){super("Wrong recovery password for this embedded signer")}}class R extends Error{constructor(){super("Not configured")}}class T{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;constructor(e,i,t){if(!e)throw new n("Configuration is required for IframeManager",r.INVALID_CONFIGURATION);if(!i)throw new n("Storage is required for IframeManager",r.INVALID_CONFIGURATION);if(!t)throw new n("Messenger is required for IframeManager",r.INVALID_CONFIGURATION);this.sdkConfiguration=e,this.storage=i,this.messenger=t}async initialize(){if(!this.isInitialized)if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.initializationPromise=null,e}}}async doInitialize(){o("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:o}),this.connection=i({messenger:this.messenger,timeout:1e4,log:o});try{this.remote=await this.connection.promise,o("IframeManager connection established")}catch(e){const i=e;throw k.captureException(i),this.destroy(),o("Failed to establish connection:",i),new n(`Failed to establish iFrame connection: ${i.cause||i.message}`,r.INTERNAL_ERROR,e)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new n("Failed to establish connection",r.INTERNAL_ERROR);return this.remote}handleError(e){if(h(e)){if(e.error===d)throw new R;if(e.error===u)throw this.storage.remove(t.ACCOUNT),new P;if(e.error===l)throw this.storage.remove(t.ACCOUNT),new b;if(e.error===y)throw new E;throw new n(`Unknown error: ${e.error}`,r.INTERNAL_ERROR)}throw e}async buildRequestConfiguration(){const e=await a.fromStorage(this.storage);if(!e)throw new n("Must be authenticated to create a signer",r.NOT_LOGGED_IN_ERROR);return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl}}async buildIFrameRequestConfiguration(){const e=await a.fromStorage(this.storage);if(!e)throw new n("Must be authenticated to create a signer",r.NOT_LOGGED_IN_ERROR);const i={auth:f.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:i,chainId:null,password:null}}async configure(i){if(!this.sdkConfiguration.shieldConfiguration)throw new n("shieldConfiguration is required",r.INVALID_CONFIGURATION);const t=await e.fromStorage(this.storage),o=await this.ensureConnection(),a=await this.buildIFrameRequestConfiguration();a.chainId=i?.chainId??t?.chainId??null,a.password=i?.entropy?.recoveryPassword??null,a.recovery={...a.recovery,encryptionSession:i?.entropy?.encryptionSession};const c={uuid:s(),action:g.CONFIGURE,chainId:a.chainId,recovery:a.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:a.accessToken,playerID:a.playerID,thirdPartyProvider:a.thirdPartyProvider,thirdPartyTokenType:a.thirdPartyTokenType,encryptionKey:a.password,encryptionPart:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??null,encryptionSession:a.recovery?.encryptionSession??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl},d=await o.configure(c);return h(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined"),d}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),t=await this.buildIFrameRequestConfiguration();t.chainId=e.chainId??null,t.password=e?.entropy?.recoveryPassword??null,t.recovery={...t.recovery,encryptionSession:e?.entropy?.encryptionSession};const n={uuid:s(),action:g.CREATE,recovery:t.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:t.accessToken,playerID:t.playerID,thirdPartyProvider:t.thirdPartyProvider,thirdPartyTokenType:t.thirdPartyTokenType,encryptionKey:t.password,encryptionPart:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??null,encryptionSession:t.recovery?.encryptionSession??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType},r=await i.create(n);return h(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const t=await e.fromStorage(this.storage),n=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=t?.chainId??null,r.password=i?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:i?.entropy?.encryptionSession};const o={uuid:s(),action:g.RECOVER,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,encryptionPart:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??null,encryptionSession:r.recovery?.encryptionSession??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account},a=await n.recover(o);return h(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,i,t,n){o("[iframe] ensureConnection");const r=await this.ensureConnection(),a=new p(s(),e,await this.buildRequestConfiguration(),i,t,n);o("[iframe] done ensureConnection");try{const e=await r.sign(a);return o("[iframe] response",e),h(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e.signature}catch(n){if(n instanceof R)return await this.configure(),this.sign(e,i,t);throw n}}async switchChain(e){const i=await this.ensureConnection(),t=new w(s(),e,await this.buildRequestConfiguration());try{const e=await i.switchChain(t);return h(e)&&this.handleError(e),e}catch(i){if(i instanceof R)return await this.configure(),this.switchChain(e);throw i}}async export(){const e=await this.ensureConnection(),i=new m(s(),await this.buildRequestConfiguration());try{const t=await e.export(i);return h(t)&&this.handleError(t),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",t.version??"undefined"),t.key}catch(e){if(e instanceof R)return await this.configure(),this.export();throw e}}async setRecoveryMethod(e,i,t){const n=await this.ensureConnection(),r=new C(s(),e,i,t,await this.buildRequestConfiguration());try{const e=await n.setRecoveryMethod(r);h(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined")}catch(n){if(n instanceof R)return await this.configure(),this.setRecoveryMethod(e,i,t);throw n}}async getCurrentDevice(e){const i=await this.ensureConnection(),t=new I(s(),e);try{const e=await i.getCurrentDevice(t);return h(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof R)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void o("IframeManager not loaded, skipping authentication update");const e=await a.fromStorage(this.storage);if(!e)return void o("No authentication found, skipping update");const i=new v(s(),e.token);try{o("Updating authentication in iframe with token:",e.token);const t=await this.remote.updateAuthentication(i);h(t)&&this.handleError(t)}catch(e){if(e instanceof R)return await this.configure(),void await this.updateAuthentication();throw e}}async disconnect(){const e=await this.ensureConnection(),i={uuid:s()};await e.logout(i)}async onMessage(e){o("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof c?(this.isInitialized||this.connection?o(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(o("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{o("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),o("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):o("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.messenger.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}}export{T as IframeManager,b as MissingProjectEntropyError,P as MissingRecoveryPasswordError,R as NotConfiguredError,E as WrongRecoveryPasswordError};
|
|
1
|
+
import{Account as e}from"../core/configuration/account.js";import i from"./messaging/browserMessenger/connect.js";import"./messaging/browserMessenger/backwardCompatibility.js";import{StorageKeys as t}from"../storage/istorage.js";import{OpenfortError as n,OpenfortErrorType as r}from"../core/errors/openfortError.js";import{debugLog as o}from"../utils/debug.js";import{randomUUID as s}from"../utils/crypto.js";import{Authentication as a}from"../core/configuration/authentication.js";import{ReactNativeMessenger as c}from"./messaging/ReactNativeMessenger.js";import{isErrorResponse as d,NOT_CONFIGURED_ERROR as h,MISSING_USER_ENTROPY_ERROR as u,MISSING_PROJECT_ENTROPY_ERROR as l,INCORRECT_USER_ENTROPY_ERROR as g,ShieldAuthType as y,Event as f,SignRequest as p,SwitchChainRequest as m,ExportPrivateKeyRequest as w,SetRecoveryMethodRequest as C,GetCurrentDeviceRequest as I,UpdateAuthenticationRequest as v}from"./types.js";import{sentry as E}from"../core/errors/sentry.js";class k extends Error{constructor(){super("This embedded signer requires a password to be recovered")}}class P extends Error{constructor(){super("MissingProjectEntropyError")}}class b extends Error{constructor(){super("Wrong recovery password for this embedded signer")}}class R extends Error{constructor(){super("Not configured")}}class T{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;constructor(e,i,t){if(!e)throw new n("Configuration is required for IframeManager",r.INVALID_CONFIGURATION);if(!i)throw new n("Storage is required for IframeManager",r.INVALID_CONFIGURATION);if(!t)throw new n("Messenger is required for IframeManager",r.INVALID_CONFIGURATION);this.sdkConfiguration=e,this.storage=i,this.messenger=t}async initialize(){if(!this.isInitialized)if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.initializationPromise=null,e}}}async doInitialize(){o("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:o}),this.connection=i({messenger:this.messenger,timeout:1e4,log:o});try{this.remote=await this.connection.promise,o("IframeManager connection established")}catch(e){const i=e;throw E.captureException(i),this.destroy(),o("Failed to establish connection:",i),new n(`Failed to establish iFrame connection: ${i.cause||i.message}`,r.INTERNAL_ERROR,e)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new n("Failed to establish connection",r.INTERNAL_ERROR);return this.remote}handleError(e){if(d(e)){if(e.error===h)throw this.storage.remove(t.ACCOUNT),new R;if(e.error===u)throw this.storage.remove(t.ACCOUNT),new k;if(e.error===l)throw this.storage.remove(t.ACCOUNT),new P;if(e.error===g)throw new b;throw new n(`Unknown error: ${e.error}`,r.INTERNAL_ERROR)}throw e}async buildRequestConfiguration(){const e=await a.fromStorage(this.storage);if(!e)throw new n("Must be authenticated to create a signer",r.NOT_LOGGED_IN_ERROR);return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl}}async buildIFrameRequestConfiguration(){const e=await a.fromStorage(this.storage);if(!e)throw new n("Must be authenticated to create a signer",r.NOT_LOGGED_IN_ERROR);const i={auth:y.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:i,chainId:null,password:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),t=await this.buildIFrameRequestConfiguration();t.chainId=e.chainId??null,t.password=e?.entropy?.recoveryPassword??null,t.recovery={...t.recovery,encryptionSession:e?.entropy?.encryptionSession};const n={uuid:s(),action:f.CREATE,recovery:t.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:t.accessToken,playerID:t.playerID,thirdPartyProvider:t.thirdPartyProvider,thirdPartyTokenType:t.thirdPartyTokenType,encryptionKey:t.password,encryptionPart:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??null,encryptionSession:t.recovery?.encryptionSession??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType},r=await i.create(n);return d(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const t=await e.fromStorage(this.storage),n=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=t?.chainId??null,r.password=i?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:i?.entropy?.encryptionSession};const o={uuid:s(),action:f.RECOVER,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,encryptionPart:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??null,encryptionSession:r.recovery?.encryptionSession??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account},a=await n.recover(o);return d(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,i,t,n){o("[iframe] ensureConnection");const r=await this.ensureConnection(),a=new p(s(),e,await this.buildRequestConfiguration(),i,t,n);o("[iframe] done ensureConnection");const c=await r.sign(a);return o("[iframe] response",c),d(c)&&this.handleError(c),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",c.version??"undefined"),c.signature}async switchChain(e){const i=await this.ensureConnection(),t=new m(s(),e,await this.buildRequestConfiguration()),n=await i.switchChain(t);return d(n)&&this.handleError(n),n}async export(){const e=await this.ensureConnection(),i=new w(s(),await this.buildRequestConfiguration()),t=await e.export(i);return d(t)&&this.handleError(t),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",t.version??"undefined"),t.key}async setRecoveryMethod(e,i,t){const n=await this.ensureConnection(),r=new C(s(),e,i,t,await this.buildRequestConfiguration()),o=await n.setRecoveryMethod(r);d(o)&&this.handleError(o),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",o.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),t=new I(s(),e);try{const e=await i.getCurrentDevice(t);return d(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof R)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void o("IframeManager not loaded, skipping authentication update");const e=await a.fromStorage(this.storage);if(!e)return void o("No authentication found, skipping update");const i=new v(s(),e.token);o("Updating authentication in iframe with token");const t=await this.remote.updateAuthentication(i);d(t)&&this.handleError(t)}async disconnect(){const e=await this.ensureConnection(),i={uuid:s()};await e.logout(i)}async onMessage(e){o("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof c?(this.isInitialized||this.connection?o(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(o("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{o("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),o("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):o("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.messenger.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}}export{T as IframeManager,P as MissingProjectEntropyError,k as MissingRecoveryPasswordError,R as NotConfiguredError,b as WrongRecoveryPasswordError};
|
package/package.json
CHANGED