@openfort/openfort-js 0.9.7 → 0.9.9
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/version.js +1 -1
- package/dist/cjs/sdk/src/wallets/embedded.js +1 -1
- package/dist/cjs/sdk/src/wallets/iframeManager.js +1 -1
- package/dist/sdk/src/api/embeddedWallet.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/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("../storage/istorage.js"),t=require("../core/configuration/account.js"),n=require("../core/configuration/authentication.js"),i=require("../core/config/config.js"),a=require("../core/errors/openfortError.js"),s=require("../wallets/evm/walletHelpers.js"),o=require("../wallets/evm/evmProvider.js");require("../wallets/evm/types.js");var d=require("../wallets/evm/provider/eip6963.js"),c=require("../types/types.js"),g=require("../wallets/iframeManager.js"),h=require("../wallets/embedded.js");require("../wallets/messaging/browserMessenger/backwardCompatibility.js");var u=require("../wallets/messaging/browserMessenger/messengers/WindowMessenger.js"),p=require("../wallets/messaging/ReactNativeMessenger.js"),l=require("../utils/debug.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(c.OpenfortEvents.TOKEN_REFRESHED,()=>{l.debugLog("Handling token refresh event in EmbeddedWalletApi"),this.handleTokenRefreshed()}),this.eventEmitter.on(c.OpenfortEvents.LOGGED_OUT,()=>{l.debugLog("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const r=i.SDKConfiguration.fromStorage();if(!r)throw new a.OpenfortError("Configuration not found",a.OpenfortErrorType.INVALID_CONFIGURATION);return new e.BackendApiClients({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey})}async getIframeManager(){if(l.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager)return l.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return l.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;l.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return l.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,l.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw l.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,e}}async createIframeManager(){l.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=i.SDKConfiguration.fromStorage();if(!e)throw l.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new a.OpenfortError("Configuration not found",a.OpenfortErrorType.INVALID_CONFIGURATION);let r;if(l.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)l.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger=new p.ReactNativeMessenger(this.messagePoster),l.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{l.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),n=new URL(e.iframeUrl).origin;r=new u({remoteWindow:t.contentWindow,allowedOrigins:[n]}),l.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return l.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new g.IframeManager(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 h.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),l.debugLog("Iframe created and appended to document"),t}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC};let t;(r.recoveryMethod===c.RecoveryMethod.PASSWORD||e.shieldAuthentication?.encryptionSession)&&(t={encryptionSession:e.shieldAuthentication?.encryptionSession,recoveryPassword:r.recoveryMethod===c.RecoveryMethod.PASSWORD?r.password:void 0});const i=await this.ensureSigner(),a=await i.configure({chainId:e.chainId,entropy:t}),s=await n.Authentication.fromStorage(this.storage);return{id:a.id,chainId:a.chainId,user:s.player,address:a.address,ownerAddress:a.ownerAddress,chainType:a.chainType,accountType:a.accountType,implementationType:a.implementationType}}async create(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC};let t;(r.recoveryMethod===c.RecoveryMethod.PASSWORD||e.shieldAuthentication?.encryptionSession)&&(t={encryptionSession:e.shieldAuthentication?.encryptionSession,recoveryPassword:r.recoveryMethod===c.RecoveryMethod.PASSWORD?r.password:void 0});const i=await this.ensureSigner(),a=await i.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:t});this.signer=null,this.signerPromise=null;const s=await n.Authentication.fromStorage(this.storage);return{id:a.id,chainId:a.chainId,user:s.player,address:a.address,ownerAddress:a.ownerAddress,chainType:a.chainType,accountType:a.accountType,implementationType:a.implementationType}}async recover(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC};let t;(r.recoveryMethod===c.RecoveryMethod.PASSWORD||e.shieldAuthentication?.encryptionSession)&&(t={encryptionSession:e.shieldAuthentication?.encryptionSession,recoveryPassword:r.recoveryMethod===c.RecoveryMethod.PASSWORD?r.password:void 0});const i=await this.ensureSigner(),a=await i.recover({account:e.account,entropy:t});this.signer=null,this.signerPromise=null;const s=await n.Authentication.fromStorage(this.storage);return{id:a.id,chainId:a.chainId,user:s.player,address:a.address,ownerAddress:a.ownerAddress,chainType:a.chainType,accountType:a.accountType,implementationType:a.implementationType}}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:n=!0,arrayifyMessage:i=!1}=r||{};return await t.sign(e,i,n)}async signTypedData(e,r,n){await this.validateAndRefreshToken();const i=await this.ensureSigner(),o=await t.Account.fromStorage(this.storage);if(!o)throw new a.OpenfortError("No account found",a.OpenfortErrorType.MISSING_SIGNER_ERROR);const d={...r};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),g=c.hash(e,d,n);return await s.signMessage({hash:g,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:i,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 setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:r,encryptionSession:t}){await this.validateAndRefreshToken();const n=await this.ensureSigner();if("password"===e&&!r)throw new a.OpenfortError("Recovery password is required",a.OpenfortErrorType.INVALID_CONFIGURATION);await n.setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:r,encryptionSession:t})}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(){const e=i.SDKConfiguration.fromStorage();if(!e)throw new a.OpenfortError("Configuration not found",a.OpenfortErrorType.INVALID_CONFIGURATION);await this.validateAndRefreshToken();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 a.withOpenfortError(async()=>(await this.backendApiClients.accountsApi.getAccountsV2({accountType:c.AccountTypeEnum.SMART_ACCOUNT},{headers:{authorization:`Bearer ${e.baseConfiguration.publishableKey}`,"x-player-token":r.token,"x-auth-provider":r.thirdPartyProvider,"x-token-type":r.thirdPartyTokenType}})).data.data.map(e=>({user:e.user,chainType:e.accountType,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 c.EmbeddedState.UNAUTHENTICATED;return await t.Account.fromStorage(this.storage)?c.EmbeddedState.READY:c.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return l.debugLog("Failed to get embedded state:",e),c.EmbeddedState.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},i=await n.Authentication.fromStorage(this.storage),a=await t.Account.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new o.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:a||void 0,authentication:i||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&d.announceProvider({info:{...d.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 l.debugLog("Ping failed:",e),!1}}getURL(){const e=i.SDKConfiguration.fromStorage();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(),l.debugLog("Updated IframeManager authentication after token refresh")}catch(e){l.debugLog("Failed to update IframeManager authentication:",e)}else l.debugLog("IframeManager not initialized, skipping authentication update")}async handleLogout(){this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null,this.storage.remove(r.StorageKeys.ACCOUNT)}async onMessage(e){if(!e||"object"!=typeof e)return void l.debugLog("Invalid message received:",e);l.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 l.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();l.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&l.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),l.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),l.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/configuration/account.js"),t=require("../core/configuration/authentication.js"),n=require("../core/config/config.js"),a=require("../core/errors/openfortError.js"),i=require("../wallets/evm/walletHelpers.js"),s=require("../wallets/evm/evmProvider.js");require("../wallets/evm/types.js");var o=require("../wallets/evm/provider/eip6963.js"),d=require("../types/types.js"),c=require("../wallets/iframeManager.js"),g=require("../wallets/embedded.js");require("../wallets/messaging/browserMessenger/backwardCompatibility.js");var h=require("../wallets/messaging/browserMessenger/messengers/WindowMessenger.js"),u=require("../wallets/messaging/ReactNativeMessenger.js"),p=require("../utils/debug.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(d.OpenfortEvents.TOKEN_REFRESHED,()=>{p.debugLog("Handling token refresh event in EmbeddedWalletApi"),this.handleTokenRefreshed()}),this.eventEmitter.on(d.OpenfortEvents.LOGGED_OUT,()=>{p.debugLog("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const r=n.SDKConfiguration.fromStorage();if(!r)throw new a.OpenfortError("Configuration not found",a.OpenfortErrorType.INVALID_CONFIGURATION);return new e.BackendApiClients({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey})}async getIframeManager(){if(p.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager)return p.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return p.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;p.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return p.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,p.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw p.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,e}}async createIframeManager(){p.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=n.SDKConfiguration.fromStorage();if(!e)throw p.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new a.OpenfortError("Configuration not found",a.OpenfortErrorType.INVALID_CONFIGURATION);let r;if(p.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)p.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger=new u.ReactNativeMessenger(this.messagePoster),p.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{p.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),n=new URL(e.iframeUrl).origin;r=new h({remoteWindow:t.contentWindow,allowedOrigins:[n]}),p.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return p.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new c.IframeManager(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 g.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),p.debugLog("Iframe created and appended to document"),t}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC};let n;(r.recoveryMethod===d.RecoveryMethod.PASSWORD||e.shieldAuthentication?.encryptionSession)&&(n={encryptionSession:e.shieldAuthentication?.encryptionSession,recoveryPassword:r.recoveryMethod===d.RecoveryMethod.PASSWORD?r.password:void 0});const a=await this.ensureSigner(),i=await a.configure({chainId:e.chainId,entropy:n}),s=await t.Authentication.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 r=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC};let n;(r.recoveryMethod===d.RecoveryMethod.PASSWORD||e.shieldAuthentication?.encryptionSession)&&(n={encryptionSession:e.shieldAuthentication?.encryptionSession,recoveryPassword:r.recoveryMethod===d.RecoveryMethod.PASSWORD?r.password:void 0});const a=await this.ensureSigner(),i=await a.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:n}),s=await t.Authentication.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 r=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC};let n;(r.recoveryMethod===d.RecoveryMethod.PASSWORD||e.shieldAuthentication?.encryptionSession)&&(n={encryptionSession:e.shieldAuthentication?.encryptionSession,recoveryPassword:r.recoveryMethod===d.RecoveryMethod.PASSWORD?r.password:void 0});const a=await this.ensureSigner(),i=await a.recover({account:e.account,entropy:n}),s=await t.Authentication.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,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:n=!0,arrayifyMessage:a=!1}=r||{};return await t.sign(e,a,n)}async signTypedData(e,t,n){await this.validateAndRefreshToken();const s=await this.ensureSigner(),o=await r.Account.fromStorage(this.storage);if(!o)throw new a.OpenfortError("No account found",a.OpenfortErrorType.MISSING_SIGNER_ERROR);const d={...t};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),g=c.hash(e,d,n);return await i.signMessage({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 setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:r,encryptionSession:t}){await this.validateAndRefreshToken();const n=await this.ensureSigner();if("password"===e&&!r)throw new a.OpenfortError("Recovery password is required",a.OpenfortErrorType.INVALID_CONFIGURATION);await n.setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:r,encryptionSession:t})}async get(){const e=await r.Account.fromStorage(this.storage);if(!e)throw new a.OpenfortError("No signer configured",a.OpenfortErrorType.MISSING_SIGNER_ERROR);const n=await t.Authentication.fromStorage(this.storage);if(!n)throw new a.OpenfortError("No access token found",a.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return{id:e.id,chainId:e.chainId,user:n.player,address:e.address,ownerAddress:e.ownerAddress,chainType:e.chainType,accountType:e.accountType,implementationType:e.implementationType}}async list(){const e=n.SDKConfiguration.fromStorage();if(!e)throw new a.OpenfortError("Configuration not found",a.OpenfortErrorType.INVALID_CONFIGURATION);await this.validateAndRefreshToken();const r=await t.Authentication.fromStorage(this.storage);if(!r)throw new a.OpenfortError("No access token found",a.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return a.withOpenfortError(async()=>(await this.backendApiClients.accountsApi.getAccountsV2({accountType:d.AccountTypeEnum.SMART_ACCOUNT},{headers:{authorization:`Bearer ${e.baseConfiguration.publishableKey}`,"x-player-token":r.token,"x-auth-provider":r.thirdPartyProvider,"x-token-type":r.thirdPartyTokenType}})).data.data.map(e=>({user:e.user,chainType:e.accountType,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 t.Authentication.fromStorage(this.storage))return d.EmbeddedState.UNAUTHENTICATED;return await r.Account.fromStorage(this.storage)?d.EmbeddedState.READY:d.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return p.debugLog("Failed to get embedded state:",e),d.EmbeddedState.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const n={announceProvider:!0,...e},a=await t.Authentication.fromStorage(this.storage),i=await r.Account.fromStorage(this.storage);return this.provider?this.provider&&n.policy&&this.provider.updatePolicy(n.policy):(this.provider=new s.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:i||void 0,authentication:a||void 0,backendApiClients:this.backendApiClients,policyId:n.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:n.chains}),n.announceProvider&&o.announceProvider({info:{...o.openfortProviderInfo,...n.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 n=await t.Authentication.fromStorage(this.storage);if(n)try{return await r.getCurrentDevice(n.player),!0}catch(e){return!1}return r.isLoaded()}catch(e){return p.debugLog("Ping failed:",e),!1}}getURL(){const e=n.SDKConfiguration.fromStorage();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(),p.debugLog("Updated IframeManager authentication after token refresh")}catch(e){p.debugLog("Failed to update IframeManager authentication:",e)}else p.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 p.debugLog("Invalid message received:",e);p.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 p.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();p.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&p.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),p.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),p.debugLog("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="0.9.
|
|
1
|
+
"use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="0.9.9";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var t=require("../core/configuration/authentication.js"),e=require("../core/errors/openfortError.js"),a=require("../types/types.js");require("./types.js");var r=require("../core/configuration/account.js");require("./messaging/browserMessenger/backwardCompatibility.js")
|
|
1
|
+
"use strict";var t=require("../core/configuration/authentication.js"),e=require("../core/errors/openfortError.js"),a=require("../types/types.js");require("./types.js");var r=require("../core/configuration/account.js");require("./messaging/browserMessenger/backwardCompatibility.js");var o=require("../storage/istorage.js"),n=require("../core/config/config.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(t,e,a,r){this.iframeManager=t,this.storage=e,this.backendApiClients=a,this.eventEmitter=r}async configure(o){const s=await this.iframeManager.configure(o),i=await t.Authentication.fromStorage(this.storage);if(!i)throw new e.OpenfortError("No access token found",e.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const d=n.SDKConfiguration.fromStorage();if(!d)throw new e.OpenfortError("Configuration not found",e.OpenfortErrorType.INVALID_CONFIGURATION);return s?.account||e.withOpenfortError(async()=>{const t=await this.backendApiClients.accountsApi.getAccountsV2({chainId:s.chainId,address:s.address},{headers:{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}});if(0===t.data.data.length)throw new e.OpenfortError("No account found",e.OpenfortErrorType.MISSING_SIGNER_ERROR);const o=new r.Account({user:t.data.data[0].user,chainType:t.data.data[0].accountType,id:t.data.data[0].id,address:t.data.data[0].address,ownerAddress:t.data.data[0].ownerAddress,accountType:t.data.data[0].accountType,createdAt:t.data.data[0].createdAt,implementationType:t.data.data[0].smartAccount?.implementationType,chainId:t.data.data[0].chainId,factoryAddress:t.data.data[0].smartAccount?.factoryAddress,salt:t.data.data[0].smartAccount?.salt});return o.save(this.storage),this.eventEmitter.emit(a.OpenfortEvents.SWITCH_ACCOUNT,t.data.data[0].address),o},{default:e.OpenfortErrorType.AUTHENTICATION_ERROR}),e.withOpenfortError(async()=>{const t=await this.backendApiClients.accountsApi.getAccountV2({id:s.account},{headers:{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}}),e=new r.Account({user:t.data.user,chainType:t.data.accountType,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(a.OpenfortEvents.SWITCH_ACCOUNT,t.data.address),e},{default:e.OpenfortErrorType.AUTHENTICATION_ERROR})}async sign(t,e,a){return await this.iframeManager.sign(t,e,a)}async export(){return await this.iframeManager.export()}async switchChain({chainId:t}){const e=await this.iframeManager.switchChain(t),a=await r.Account.fromStorage(this.storage);new r.Account({...a,id:e.account,chainId:t}).save(this.storage)}async create(o){const s=await this.iframeManager.create(o),i=await t.Authentication.fromStorage(this.storage);if(!i)throw new e.OpenfortError("No access token found",e.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const d=n.SDKConfiguration.fromStorage();if(!d)throw new e.OpenfortError("Configuration not found",e.OpenfortErrorType.INVALID_CONFIGURATION);return e.withOpenfortError(async()=>{const t=await this.backendApiClients.accountsApi.getAccountV2({id:s.account},{headers:{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}}),e=new r.Account({user:t.data.user,chainType:t.data.accountType,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(a.OpenfortEvents.SWITCH_ACCOUNT,t.data.address),e},{default:e.OpenfortErrorType.AUTHENTICATION_ERROR})}async recover(o){const s=await this.iframeManager.recover(o),i=await t.Authentication.fromStorage(this.storage);if(!i)throw new e.OpenfortError("No access token found",e.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const d=n.SDKConfiguration.fromStorage();if(!d)throw new e.OpenfortError("Configuration not found",e.OpenfortErrorType.INVALID_CONFIGURATION);return e.withOpenfortError(async()=>{const t=await this.backendApiClients.accountsApi.getAccountV2({id:s.account},{headers:{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}}),e=new r.Account({user:t.data.user,chainType:t.data.accountType,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(a.OpenfortEvents.SWITCH_ACCOUNT,t.data.address),e},{default:e.OpenfortErrorType.AUTHENTICATION_ERROR})}async setEmbeddedRecovery({recoveryMethod:t,recoveryPassword:e,encryptionSession:a}){await this.iframeManager.setEmbeddedRecovery(t,e,a)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(o.StorageKeys.ACCOUNT)}};
|
|
@@ -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(),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,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){n.debugLog("[iframe] ensureConnection");const t=await this.ensureConnection(),s=new c.SignRequest(o.randomUUID(),e,i,r,await this.buildRequestConfiguration());n.debugLog("[iframe] done ensureConnection");try{const e=await t.sign(s);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 setEmbeddedRecovery(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.setEmbeddedRecovery(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"),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 y 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 y;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,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,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){n.debugLog("[iframe] ensureConnection");const t=await this.ensureConnection(),s=new c.SignRequest(o.randomUUID(),e,i,r,await this.buildRequestConfiguration());n.debugLog("[iframe] done ensureConnection");try{const e=await t.sign(s);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 y)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 y)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 y)return await this.configure(),this.export();throw e}}async setEmbeddedRecovery(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 y)return await this.configure(),this.setEmbeddedRecovery(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 y)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 y)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=y,exports.WrongRecoveryPasswordError=g;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{StorageKeys as t}from"../storage/istorage.js";import{Account as r}from"../core/configuration/account.js";import{Authentication as a}from"../core/configuration/authentication.js";import{SDKConfiguration as i}from"../core/config/config.js";import{OpenfortError as n,OpenfortErrorType as s,withOpenfortError as o}from"../core/errors/openfortError.js";import{signMessage as d}from"../wallets/evm/walletHelpers.js";import{EvmProvider as c}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as h,openfortProviderInfo as g}from"../wallets/evm/provider/eip6963.js";import{OpenfortEvents as m,RecoveryMethod as l,AccountTypeEnum as p,EmbeddedState as f}from"../types/types.js";import{IframeManager as u}from"../wallets/iframeManager.js";import{EmbeddedSigner as y}from"../wallets/embedded.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import w from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";import{ReactNativeMessenger as A}from"../wallets/messaging/ReactNativeMessenger.js";import{debugLog as v}from"../utils/debug.js";class E{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(m.TOKEN_REFRESHED,()=>{v("Handling token refresh event in EmbeddedWalletApi"),this.handleTokenRefreshed()}),this.eventEmitter.on(m.LOGGED_OUT,()=>{v("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=i.fromStorage();if(!t)throw new n("Configuration not found",s.INVALID_CONFIGURATION);return new e({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey})}async getIframeManager(){if(v("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager)return v("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return v("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;v("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return v("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,v("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw v("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,e}}async createIframeManager(){v("[HANDSHAKE DEBUG] createIframeManager starting");const e=i.fromStorage();if(!e)throw v("[HANDSHAKE DEBUG] Configuration not found"),new n("Configuration not found",s.INVALID_CONFIGURATION);let t;if(v("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)v("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger=new A(this.messagePoster),v("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{v("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),a=new URL(e.iframeUrl).origin;t=new w({remoteWindow:r.contentWindow,allowedOrigins:[a]}),v("[HANDSHAKE DEBUG] Created WindowMessenger")}return v("[HANDSHAKE DEBUG] Creating IframeManager instance"),new u(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 y(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.",s.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),v("Iframe created and appended to document"),r}async configure(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:l.AUTOMATIC};let r;(t.recoveryMethod===l.PASSWORD||e.shieldAuthentication?.encryptionSession)&&(r={encryptionSession:e.shieldAuthentication?.encryptionSession,recoveryPassword:t.recoveryMethod===l.PASSWORD?t.password:void 0});const i=await this.ensureSigner(),n=await i.configure({chainId:e.chainId,entropy:r}),s=await a.fromStorage(this.storage);return{id:n.id,chainId:n.chainId,user:s.player,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType}}async create(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:l.AUTOMATIC};let r;(t.recoveryMethod===l.PASSWORD||e.shieldAuthentication?.encryptionSession)&&(r={encryptionSession:e.shieldAuthentication?.encryptionSession,recoveryPassword:t.recoveryMethod===l.PASSWORD?t.password:void 0});const i=await this.ensureSigner(),n=await i.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:r});this.signer=null,this.signerPromise=null;const s=await a.fromStorage(this.storage);return{id:n.id,chainId:n.chainId,user:s.player,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType}}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:l.AUTOMATIC};let r;(t.recoveryMethod===l.PASSWORD||e.shieldAuthentication?.encryptionSession)&&(r={encryptionSession:e.shieldAuthentication?.encryptionSession,recoveryPassword:t.recoveryMethod===l.PASSWORD?t.password:void 0});const i=await this.ensureSigner(),n=await i.recover({account:e.account,entropy:r});this.signer=null,this.signerPromise=null;const s=await a.fromStorage(this.storage);return{id:n.id,chainId:n.chainId,user:s.player,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType}}async signMessage(e,t){await this.validateAndRefreshToken();const r=await this.ensureSigner(),{hashMessage:a=!0,arrayifyMessage:i=!1}=t||{};return await r.sign(e,i,a)}async signTypedData(e,t,a){await this.validateAndRefreshToken();const i=await this.ensureSigner(),o=await r.fromStorage(this.storage);if(!o)throw new n("No account found",s.MISSING_SIGNER_ERROR);const c={...t};delete c.EIP712Domain;const{_TypedDataEncoder:h}=await import("@ethersproject/hash"),g=h.hash(e,c,a);return await d({hash:g,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:i,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 setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:t,encryptionSession:r}){await this.validateAndRefreshToken();const a=await this.ensureSigner();if("password"===e&&!t)throw new n("Recovery password is required",s.INVALID_CONFIGURATION);await a.setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:t,encryptionSession:r})}async get(){const e=await r.fromStorage(this.storage);if(!e)throw new n("No signer configured",s.MISSING_SIGNER_ERROR);const t=await a.fromStorage(this.storage);if(!t)throw new n("No access token found",s.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(){const e=i.fromStorage();if(!e)throw new n("Configuration not found",s.INVALID_CONFIGURATION);await this.validateAndRefreshToken();const t=await a.fromStorage(this.storage);if(!t)throw new n("No access token found",s.NOT_LOGGED_IN_ERROR);return o(async()=>(await this.backendApiClients.accountsApi.getAccountsV2({accountType:p.SMART_ACCOUNT},{headers:{authorization:`Bearer ${e.baseConfiguration.publishableKey}`,"x-player-token":t.token,"x-auth-provider":t.thirdPartyProvider,"x-token-type":t.thirdPartyTokenType}})).data.data.map(e=>({user:e.user,chainType:e.accountType,id:e.id,address:e.address,ownerAddress:e.ownerAddress,accountType:e.accountType,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId})),{default:s.AUTHENTICATION_ERROR})}async getEmbeddedState(){try{if(!await a.fromStorage(this.storage))return f.UNAUTHENTICATED;return await r.fromStorage(this.storage)?f.READY:f.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return v("Failed to get embedded state:",e),f.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const t={announceProvider:!0,...e},i=await a.fromStorage(this.storage),n=await r.fromStorage(this.storage);return this.provider?this.provider&&t.policy&&this.provider.updatePolicy(t.policy):(this.provider=new c({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:n||void 0,authentication:i||void 0,backendApiClients:this.backendApiClients,policyId:t.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:t.chains}),t.announceProvider&&h({info:{...g,...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 v("Ping failed:",e),!1}}getURL(){const e=i.fromStorage();if(!e)throw new n("Configuration not found",s.INVALID_CONFIGURATION);return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new n("Invalid message poster",s.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(),v("Updated IframeManager authentication after token refresh")}catch(e){v("Failed to update IframeManager authentication:",e)}else v("IframeManager not initialized, skipping authentication update")}async handleLogout(){this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null,this.storage.remove(t.ACCOUNT)}async onMessage(e){if(!e||"object"!=typeof e)return void v("Invalid message received:",e);v("[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 v("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const r=await this.getIframeManager();v(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${r.isLoaded()}`),t&&!r.isLoaded()&&v("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),v("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await r.onMessage(e),v("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{E as EmbeddedWalletApi};
|
|
1
|
+
import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{Account as t}from"../core/configuration/account.js";import{Authentication as r}from"../core/configuration/authentication.js";import{SDKConfiguration as a}from"../core/config/config.js";import{OpenfortError as i,OpenfortErrorType as n,withOpenfortError as s}from"../core/errors/openfortError.js";import{signMessage as o}from"../wallets/evm/walletHelpers.js";import{EvmProvider as d}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as c,openfortProviderInfo as h}from"../wallets/evm/provider/eip6963.js";import{OpenfortEvents as g,RecoveryMethod as m,AccountTypeEnum as l,EmbeddedState as p}from"../types/types.js";import{IframeManager as f}from"../wallets/iframeManager.js";import{EmbeddedSigner as u}from"../wallets/embedded.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import y from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";import{ReactNativeMessenger as w}from"../wallets/messaging/ReactNativeMessenger.js";import{debugLog as A}from"../utils/debug.js";class v{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(g.TOKEN_REFRESHED,()=>{A("Handling token refresh event in EmbeddedWalletApi"),this.handleTokenRefreshed()}),this.eventEmitter.on(g.LOGGED_OUT,()=>{A("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=a.fromStorage();if(!t)throw new i("Configuration not found",n.INVALID_CONFIGURATION);return new e({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey})}async getIframeManager(){if(A("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager)return A("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return A("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;A("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return A("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,A("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw A("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,e}}async createIframeManager(){A("[HANDSHAKE DEBUG] createIframeManager starting");const e=a.fromStorage();if(!e)throw A("[HANDSHAKE DEBUG] Configuration not found"),new i("Configuration not found",n.INVALID_CONFIGURATION);let t;if(A("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)A("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger=new w(this.messagePoster),A("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{A("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),a=new URL(e.iframeUrl).origin;t=new y({remoteWindow:r.contentWindow,allowedOrigins:[a]}),A("[HANDSHAKE DEBUG] Created WindowMessenger")}return A("[HANDSHAKE DEBUG] Creating IframeManager instance"),new f(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 u(e,this.storage,this.backendApiClients,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new i("Document is not available. Please provide a message poster for non-browser environments.",n.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),A("Iframe created and appended to document"),r}async configure(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:m.AUTOMATIC};let a;(t.recoveryMethod===m.PASSWORD||e.shieldAuthentication?.encryptionSession)&&(a={encryptionSession:e.shieldAuthentication?.encryptionSession,recoveryPassword:t.recoveryMethod===m.PASSWORD?t.password:void 0});const i=await this.ensureSigner(),n=await i.configure({chainId:e.chainId,entropy:a}),s=await r.fromStorage(this.storage);return{id:n.id,chainId:n.chainId,user:s.player,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType}}async create(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:m.AUTOMATIC};let a;(t.recoveryMethod===m.PASSWORD||e.shieldAuthentication?.encryptionSession)&&(a={encryptionSession:e.shieldAuthentication?.encryptionSession,recoveryPassword:t.recoveryMethod===m.PASSWORD?t.password:void 0});const i=await this.ensureSigner(),n=await i.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:a}),s=await r.fromStorage(this.storage);return{id:n.id,chainId:n.chainId,user:s.player,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType}}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:m.AUTOMATIC};let a;(t.recoveryMethod===m.PASSWORD||e.shieldAuthentication?.encryptionSession)&&(a={encryptionSession:e.shieldAuthentication?.encryptionSession,recoveryPassword:t.recoveryMethod===m.PASSWORD?t.password:void 0});const i=await this.ensureSigner(),n=await i.recover({account:e.account,entropy:a}),s=await r.fromStorage(this.storage);return{id:n.id,chainId:n.chainId,user:s.player,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType}}async signMessage(e,t){await this.validateAndRefreshToken();const r=await this.ensureSigner(),{hashMessage:a=!0,arrayifyMessage:i=!1}=t||{};return await r.sign(e,i,a)}async signTypedData(e,r,a){await this.validateAndRefreshToken();const s=await this.ensureSigner(),d=await t.fromStorage(this.storage);if(!d)throw new i("No account found",n.MISSING_SIGNER_ERROR);const c={...r};delete c.EIP712Domain;const{_TypedDataEncoder:h}=await import("@ethersproject/hash"),g=h.hash(e,c,a);return await o({hash:g,implementationType:d.implementationType||d.type,chainId:Number(d.chainId),signer:s,address:d.address,ownerAddress:d.ownerAddress,factoryAddress:d.factoryAddress,salt:d.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:t,encryptionSession:r}){await this.validateAndRefreshToken();const a=await this.ensureSigner();if("password"===e&&!t)throw new i("Recovery password is required",n.INVALID_CONFIGURATION);await a.setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:t,encryptionSession:r})}async get(){const e=await t.fromStorage(this.storage);if(!e)throw new i("No signer configured",n.MISSING_SIGNER_ERROR);const a=await r.fromStorage(this.storage);if(!a)throw new i("No access token found",n.NOT_LOGGED_IN_ERROR);return{id:e.id,chainId:e.chainId,user:a.player,address:e.address,ownerAddress:e.ownerAddress,chainType:e.chainType,accountType:e.accountType,implementationType:e.implementationType}}async list(){const e=a.fromStorage();if(!e)throw new i("Configuration not found",n.INVALID_CONFIGURATION);await this.validateAndRefreshToken();const t=await r.fromStorage(this.storage);if(!t)throw new i("No access token found",n.NOT_LOGGED_IN_ERROR);return s(async()=>(await this.backendApiClients.accountsApi.getAccountsV2({accountType:l.SMART_ACCOUNT},{headers:{authorization:`Bearer ${e.baseConfiguration.publishableKey}`,"x-player-token":t.token,"x-auth-provider":t.thirdPartyProvider,"x-token-type":t.thirdPartyTokenType}})).data.data.map(e=>({user:e.user,chainType:e.accountType,id:e.id,address:e.address,ownerAddress:e.ownerAddress,accountType:e.accountType,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId})),{default:n.AUTHENTICATION_ERROR})}async getEmbeddedState(){try{if(!await r.fromStorage(this.storage))return p.UNAUTHENTICATED;return await t.fromStorage(this.storage)?p.READY:p.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return A("Failed to get embedded state:",e),p.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const a={announceProvider:!0,...e},i=await r.fromStorage(this.storage),n=await t.fromStorage(this.storage);return this.provider?this.provider&&a.policy&&this.provider.updatePolicy(a.policy):(this.provider=new d({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:n||void 0,authentication:i||void 0,backendApiClients:this.backendApiClients,policyId:a.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:a.chains}),a.announceProvider&&c({info:{...h,...a.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 a=await r.fromStorage(this.storage);if(a)try{return await t.getCurrentDevice(a.player),!0}catch(e){return!1}return t.isLoaded()}catch(e){return A("Ping failed:",e),!1}}getURL(){const e=a.fromStorage();if(!e)throw new i("Configuration not found",n.INVALID_CONFIGURATION);return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new i("Invalid message poster",n.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(),A("Updated IframeManager authentication after token refresh")}catch(e){A("Failed to update IframeManager authentication:",e)}else A("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 A("Invalid message received:",e);A("[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 A("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const r=await this.getIframeManager();A(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${r.isLoaded()}`),t&&!r.isLoaded()&&A("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),A("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await r.onMessage(e),A("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{v as EmbeddedWalletApi};
|
package/dist/sdk/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.9.
|
|
1
|
+
const o="0.9.9",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Authentication as
|
|
1
|
+
import{Authentication as a}from"../core/configuration/authentication.js";import{OpenfortError as t,OpenfortErrorType as e,withOpenfortError as r}from"../core/errors/openfortError.js";import{OpenfortEvents as o}from"../types/types.js";import"./types.js";import{Account as s}from"../core/configuration/account.js";import"./messaging/browserMessenger/backwardCompatibility.js";import{StorageKeys as n}from"../storage/istorage.js";import{SDKConfiguration as i}from"../core/config/config.js";import"../core/errors/sentry.js";import"jose";import"./evm/types.js";import"./evm/JsonRpcError.js";import"eventemitter3";import"./evm/provider/eip6963.js";class d{iframeManager;storage;backendApiClients;eventEmitter;constructor(a,t,e,r){this.iframeManager=a,this.storage=t,this.backendApiClients=e,this.eventEmitter=r}async configure(n){const d=await this.iframeManager.configure(n),c=await a.fromStorage(this.storage);if(!c)throw new t("No access token found",e.NOT_LOGGED_IN_ERROR);const u=i.fromStorage();if(!u)throw new t("Configuration not found",e.INVALID_CONFIGURATION);return d?.account||r(async()=>{const a=await this.backendApiClients.accountsApi.getAccountsV2({chainId:d.chainId,address:d.address},{headers:{authorization:`Bearer ${u.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}});if(0===a.data.data.length)throw new t("No account found",e.MISSING_SIGNER_ERROR);const r=new s({user:a.data.data[0].user,chainType:a.data.data[0].accountType,id:a.data.data[0].id,address:a.data.data[0].address,ownerAddress:a.data.data[0].ownerAddress,accountType:a.data.data[0].accountType,createdAt:a.data.data[0].createdAt,implementationType:a.data.data[0].smartAccount?.implementationType,chainId:a.data.data[0].chainId,factoryAddress:a.data.data[0].smartAccount?.factoryAddress,salt:a.data.data[0].smartAccount?.salt});return r.save(this.storage),this.eventEmitter.emit(o.SWITCH_ACCOUNT,a.data.data[0].address),r},{default:e.AUTHENTICATION_ERROR}),r(async()=>{const a=await this.backendApiClients.accountsApi.getAccountV2({id:d.account},{headers:{authorization:`Bearer ${u.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}}),t=new s({user:a.data.user,chainType:a.data.accountType,id:a.data.id,address:a.data.address,ownerAddress:a.data.ownerAddress,accountType:a.data.accountType,createdAt:a.data.createdAt,implementationType:a.data.smartAccount?.implementationType,chainId:a.data.chainId,salt:a.data.smartAccount?.salt,factoryAddress:a.data.smartAccount?.factoryAddress});return t.save(this.storage),this.eventEmitter.emit(o.SWITCH_ACCOUNT,a.data.address),t},{default:e.AUTHENTICATION_ERROR})}async sign(a,t,e){return await this.iframeManager.sign(a,t,e)}async export(){return await this.iframeManager.export()}async switchChain({chainId:a}){const t=await this.iframeManager.switchChain(a),e=await s.fromStorage(this.storage);new s({...e,id:t.account,chainId:a}).save(this.storage)}async create(n){const d=await this.iframeManager.create(n),c=await a.fromStorage(this.storage);if(!c)throw new t("No access token found",e.NOT_LOGGED_IN_ERROR);const u=i.fromStorage();if(!u)throw new t("Configuration not found",e.INVALID_CONFIGURATION);return r(async()=>{const a=await this.backendApiClients.accountsApi.getAccountV2({id:d.account},{headers:{authorization:`Bearer ${u.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}}),t=new s({user:a.data.user,chainType:a.data.accountType,id:a.data.id,address:a.data.address,ownerAddress:a.data.ownerAddress,accountType:a.data.accountType,createdAt:a.data.createdAt,implementationType:a.data.smartAccount?.implementationType,chainId:a.data.chainId,salt:a.data.smartAccount?.salt,factoryAddress:a.data.smartAccount?.factoryAddress});return t.save(this.storage),this.eventEmitter.emit(o.SWITCH_ACCOUNT,a.data.address),t},{default:e.AUTHENTICATION_ERROR})}async recover(n){const d=await this.iframeManager.recover(n),c=await a.fromStorage(this.storage);if(!c)throw new t("No access token found",e.NOT_LOGGED_IN_ERROR);const u=i.fromStorage();if(!u)throw new t("Configuration not found",e.INVALID_CONFIGURATION);return r(async()=>{const a=await this.backendApiClients.accountsApi.getAccountV2({id:d.account},{headers:{authorization:`Bearer ${u.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}}),t=new s({user:a.data.user,chainType:a.data.accountType,id:a.data.id,address:a.data.address,ownerAddress:a.data.ownerAddress,accountType:a.data.accountType,createdAt:a.data.createdAt,implementationType:a.data.smartAccount?.implementationType,chainId:a.data.chainId,salt:a.data.smartAccount?.salt,factoryAddress:a.data.smartAccount?.factoryAddress});return t.save(this.storage),this.eventEmitter.emit(o.SWITCH_ACCOUNT,a.data.address),t},{default:e.AUTHENTICATION_ERROR})}async setEmbeddedRecovery({recoveryMethod:a,recoveryPassword:t,encryptionSession:e}){await this.iframeManager.setEmbeddedRecovery(a,t,e)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(n.ACCOUNT)}}export{d as EmbeddedSigner};
|
|
@@ -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 f,ShieldAuthType as y,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 b extends Error{constructor(){super("This embedded signer requires a password to be recovered")}}class P 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 b;if(e.error===l)throw this.storage.remove(t.ACCOUNT),new P;if(e.error===f)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: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 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(),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,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){o("[iframe] ensureConnection");const n=await this.ensureConnection(),r=new p(s(),e,i,t,await this.buildRequestConfiguration());o("[iframe] done ensureConnection");try{const e=await n.sign(r);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 setEmbeddedRecovery(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.setEmbeddedRecovery(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,P as MissingProjectEntropyError,b 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 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 b extends Error{constructor(){super("This embedded signer requires a password to be recovered")}}class P 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 b;if(e.error===l)throw this.storage.remove(t.ACCOUNT),new P;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,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,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){o("[iframe] ensureConnection");const n=await this.ensureConnection(),r=new p(s(),e,i,t,await this.buildRequestConfiguration());o("[iframe] done ensureConnection");try{const e=await n.sign(r);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 setEmbeddedRecovery(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.setEmbeddedRecovery(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,P as MissingProjectEntropyError,b as MissingRecoveryPasswordError,R as NotConfiguredError,E as WrongRecoveryPasswordError};
|
package/package.json
CHANGED