@openfort/openfort-js 1.3.7 → 1.3.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.
@@ -1 +1 @@
1
- "use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.cjs"),r=require("../core/errors/openfortError.cjs"),t=require("../core/passkey/handler.cjs"),s=require("../core/config/config.cjs"),a=require("../core/configuration/account.cjs"),n=require("../core/configuration/authentication.cjs"),i=require("../core/errors/authErrorCodes.cjs"),o=require("../core/errors/withApiError.cjs"),d=require("../storage/istorage.cjs"),c=require("../types/types.cjs"),h=require("../utils/debug.cjs"),g=require("../utils/observe.cjs"),y=require("../wallets/embedded.cjs"),u=require("../wallets/evm/evmProvider.cjs");require("../wallets/evm/types.cjs");var m=require("../wallets/evm/provider/eip6963.cjs"),l=require("../wallets/evm/walletHelpers.cjs"),f=require("../wallets/iframeManager.cjs"),p=require("../wallets/messaging/ReactNativeMessenger.cjs");require("../wallets/messaging/browserMessenger/backwardCompatibility.cjs");var E=require("../wallets/messaging/browserMessenger/messengers/WindowMessenger.cjs");exports.EmbeddedWalletApi=class{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,r,t,s,a){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=s,this.passkeyHandler=a,this.eventEmitter.on(c.OpenfortEvents.ON_LOGOUT,()=>{h.debugLog("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=s.SDKConfiguration.getInstance();if(!t)throw new r.ConfigurationError("Configuration not found");return new e.BackendApiClients({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey,nativeAppIdentifier:t.nativeAppIdentifier})}async getIframeManager(){if(h.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(h.debugLog("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return h.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return h.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;h.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return h.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,h.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw h.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){h.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=s.SDKConfiguration.getInstance();if(!e)throw h.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new r.ConfigurationError("Configuration not found");let t;if(h.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)h.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(h.debugLog("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new p.ReactNativeMessenger(this.messagePoster),h.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{h.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new E({remoteWindow:r.contentWindow,allowedOrigins:[s]}),h.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return h.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new f.IframeManager(e,this.storage,t)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(h.debugLog("IframeManager has failed, clearing signer for recreation"),this.signer=null),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();await e.initialize();return new y.EmbeddedSigner(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new r.ConfigurationError("Document is not available. Please provide a message poster for non-browser environments.");const t=document.getElementById("openfort-iframe");t&&t.remove();const s=document.createElement("iframe");return s.style.display="none",s.id="openfort-iframe",s.src=e,document.body.appendChild(s),s}async getPasskeyKey(e){const t=await n.Authentication.fromStorage(this.storage);if(!t?.userId)throw new r.AuthenticationError("auth","User is required for passkey key derivation. Logout and login again.",401);return this.passkeyHandler.deriveAndExportKey({id:e,seed:t.userId})}async getEntropy(e){switch(e.recoveryMethod){case c.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case c.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};case c.RecoveryMethod.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new r.ConfigurationError("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC},[t,s]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),n={chainId:e.chainId,entropy:s,accountType:e.accountType??c.AccountTypeEnum.SMART_ACCOUNT,chainType:e.chainType??c.ChainTypeEnum.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},i=await t.configure(n);return{id:i.id,chainId:i.chainId,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,factoryAddress:i.factoryAddress,salt:i.salt,createdAt:i.createdAt,implementationAddress:i.implementationAddress,recoveryMethod:a.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const s=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC},o=await n.Authentication.fromStorage(this.storage);if(!o)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(s.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!o.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:o.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");s.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[d,h]=await Promise.all([this.ensureSigner(),this.getEntropy(s)]),g=await d.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),y={id:g.id,chainId:g.chainId,address:g.address,ownerAddress:g.ownerAddress,chainType:g.chainType,accountType:g.accountType,implementationType:g.implementationType,factoryAddress:g.factoryAddress,salt:g.salt,createdAt:g.createdAt,implementationAddress:g.implementationAddress,recoveryMethod:a.Account.parseRecoveryMethod(g.recoveryMethod),recoveryMethodDetails:g.recoveryMethodDetails};return this.eventEmitter.emit(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,y),y}async import(e){await this.validateAndRefreshToken();const s=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC},o=await n.Authentication.fromStorage(this.storage);if(!o)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(s.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!o.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:o.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");s.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[d,h]=await Promise.all([this.ensureSigner(),this.getEntropy(s)]),g=await d.import({privateKey:e.privateKey,accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),y={id:g.id,chainId:g.chainId,address:g.address,ownerAddress:g.ownerAddress,chainType:g.chainType,accountType:g.accountType,implementationType:g.implementationType,factoryAddress:g.factoryAddress,salt:g.salt,createdAt:g.createdAt,implementationAddress:g.implementationAddress,recoveryMethod:a.Account.parseRecoveryMethod(g.recoveryMethod),recoveryMethodDetails:g.recoveryMethodDetails};return this.eventEmitter.emit(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,y),y}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC};if(t.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!t.passkeyInfo?.passkeyId)throw new r.ConfigurationError("Passkey ID must be provided for passkey recovery");t.passkeyInfo={passkeyId:t.passkeyInfo.passkeyId}}const[s,n]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),i=await s.recover({account:e.account,entropy:n}),o={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:a.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(c.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o),o}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:s=!0,arrayifyMessage:n=!1}=r||{},i=await a.Account.fromStorage(this.storage);return await t.sign(e,n,s,i?.chainType)}async signTypedData(e,t,s){await this.validateAndRefreshToken();const n=await this.ensureSigner(),o=await a.Account.fromStorage(this.storage);if(!o)throw new r.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No account found");const d={...t};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),h=c.hash(e,d,s);return await l.signMessage({hash:h,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:n,address:o.address,ownerAddress:o.ownerAddress,factoryAddress:o.factoryAddress,salt:o.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,s){await this.validateAndRefreshToken();const o=await this.ensureSigner(),d=await n.Authentication.fromStorage(this.storage);if(!d)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");let h,g,y,u;if(e.recoveryMethod===c.RecoveryMethod.PASSKEY){const e=await a.Account.fromStorage(this.storage);if(!e)throw new r.ConfigurationError("missing account");const t=e?.recoveryMethodDetails?.passkeyId;if(!t)throw new r.ConfigurationError("missing passkey id for account");if(!d.userId)throw new r.ConfigurationError("User ID is required for passkey key derivation");y={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:d.userId})}}else if(s.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!d.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:d.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");y={passkeyId:e.id,passkeyKey:e.key},u={passkeyId:e.id}}if(e.recoveryMethod===c.RecoveryMethod.PASSWORD?h=e.password:s.recoveryMethod===c.RecoveryMethod.PASSWORD&&(h=s.password),e.recoveryMethod===c.RecoveryMethod.AUTOMATIC?g=e.encryptionSession:s.recoveryMethod===c.RecoveryMethod.AUTOMATIC&&(g=s.encryptionSession),!h&&!g)throw new r.ConfigurationError("Password or encryption session is not provided");await o.setRecoveryMethod({recoveryMethod:s.recoveryMethod,recoveryPassword:h,encryptionSession:g,passkeyInfo:y});const m=await a.Account.fromStorage(this.storage);m&&new a.Account({...m,recoveryMethod:s.recoveryMethod,recoveryMethodDetails:u}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await a.Account.fromStorage(this.storage);if(!e)throw new r.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No signer configured");if(!await n.Authentication.fromStorage(this.storage))throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:a.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const t={...e},d=s.SDKConfiguration.getInstance();if(!d)throw new r.ConfigurationError("Configuration not found");const c=await n.Authentication.fromStorage(this.storage);if(!c)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),o.withApiError(async()=>(await this.backendApiClients.accountsV2Api.getAccountsV2(t,{headers:c.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}:{authorization:`Bearer ${c.token}`,"x-project-key":d.baseConfiguration.publishableKey}})).data.data.map(e=>({chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:a.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await n.Authentication.fromStorage(this.storage))return c.EmbeddedState.UNAUTHENTICATED;return await a.Account.fromStorage(this.storage)?c.EmbeddedState.READY:c.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return h.debugLog("Failed to get embedded state:",e),c.EmbeddedState.UNAUTHENTICATED}}watchEmbeddedState(e){return g.observe("watchEmbeddedState",{onChange:e.onChange,onError:e.onError},r=>{let t;const s=async()=>{try{const e=await this.getEmbeddedState();t!==e&&(r.onChange?.(e,t),t=e)}catch(e){r.onError?.(e instanceof Error?e:new Error(String(e)))}};s();const a=()=>s(),n=()=>s(),i=()=>s(),o=()=>s();this.eventEmitter.on(c.OpenfortEvents.ON_AUTH_SUCCESS,a),this.eventEmitter.on(c.OpenfortEvents.ON_LOGOUT,n),this.eventEmitter.on(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,i),this.eventEmitter.on(c.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o);const d=setInterval(s,e.pollingInterval??2e3);return()=>{clearInterval(d),this.eventEmitter.off(c.OpenfortEvents.ON_AUTH_SUCCESS,a),this.eventEmitter.off(c.OpenfortEvents.ON_LOGOUT,n),this.eventEmitter.off(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,i),this.eventEmitter.off(c.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o)}})}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await n.Authentication.fromStorage(this.storage),s=await a.Account.fromStorage(this.storage);return this.provider?this.provider&&r.feeSponsorship&&this.provider.updateFeeSponsorship(r.feeSponsorship):(this.provider=new u.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,feeSponsorshipId:r.feeSponsorship,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&m.announceProvider({info:{...m.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.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return h.debugLog("Ping failed:",e),!1}}getURL(){const e=s.SDKConfiguration.getInstance();if(!e)throw new r.ConfigurationError("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new r.ConfigurationError("Invalid message poster");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 handleLogout(){if(this.storage.remove(d.StorageKeys.ACCOUNT),"undefined"==typeof document&&!this.messagePoster)return h.debugLog("Skipping signer disconnect: no messagePoster available in non-browser environment"),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,void(this.signerPromise=null);try{const e=await this.ensureSigner();await e.disconnect()}catch{}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 h.debugLog("Invalid message received:",e);h.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 h.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();h.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&h.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),h.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),h.debugLog("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}};
1
+ "use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.cjs"),r=require("../core/errors/openfortError.cjs"),t=require("../core/passkey/handler.cjs"),s=require("../core/config/config.cjs"),a=require("../core/configuration/account.cjs"),n=require("../core/configuration/authentication.cjs"),i=require("../core/errors/authErrorCodes.cjs"),o=require("../core/errors/withApiError.cjs"),d=require("../storage/istorage.cjs"),c=require("../types/types.cjs"),h=require("../utils/debug.cjs"),g=require("../utils/observe.cjs"),y=require("../wallets/embedded.cjs"),u=require("../wallets/evm/evmProvider.cjs");require("../wallets/evm/types.cjs");var m=require("../wallets/evm/provider/eip6963.cjs"),l=require("../wallets/evm/walletHelpers.cjs"),f=require("../wallets/iframeManager.cjs"),p=require("../wallets/messaging/ReactNativeMessenger.cjs");require("../wallets/messaging/browserMessenger/backwardCompatibility.cjs");var E=require("../wallets/messaging/browserMessenger/messengers/WindowMessenger.cjs");exports.EmbeddedWalletApi=class{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,r,t,s,a){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=s,this.passkeyHandler=a,this.eventEmitter.on(c.OpenfortEvents.ON_LOGOUT,()=>{h.debugLog("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=s.SDKConfiguration.getInstance();if(!t)throw new r.ConfigurationError("Configuration not found");return new e.BackendApiClients({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey,nativeAppIdentifier:t.nativeAppIdentifier})}async getIframeManager(){if(h.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(h.debugLog("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return h.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return h.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;h.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return h.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,h.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw h.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){h.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=s.SDKConfiguration.getInstance();if(!e)throw h.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new r.ConfigurationError("Configuration not found");let t;if(h.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)h.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(h.debugLog("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new p.ReactNativeMessenger(this.messagePoster),h.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{h.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new E({remoteWindow:r.contentWindow,allowedOrigins:[s]}),h.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return h.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new f.IframeManager(e,this.storage,t)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(h.debugLog("IframeManager has failed, clearing signer for recreation"),this.signer=null),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();await e.initialize();return new y.EmbeddedSigner(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new r.ConfigurationError("Document is not available. Please provide a message poster for non-browser environments.");const t=document.getElementById("openfort-iframe");t&&t.remove();const s=document.createElement("iframe");return s.style.display="none",s.id="openfort-iframe",s.referrerPolicy="strict-origin-when-cross-origin",s.src=e,document.body.appendChild(s),s}async getPasskeyKey(e){const t=await n.Authentication.fromStorage(this.storage);if(!t?.userId)throw new r.AuthenticationError("auth","User is required for passkey key derivation. Logout and login again.",401);return this.passkeyHandler.deriveAndExportKey({id:e,seed:t.userId})}async getEntropy(e){switch(e.recoveryMethod){case c.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case c.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};case c.RecoveryMethod.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new r.ConfigurationError("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC},[t,s]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),n={chainId:e.chainId,entropy:s,accountType:e.accountType??c.AccountTypeEnum.SMART_ACCOUNT,chainType:e.chainType??c.ChainTypeEnum.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},i=await t.configure(n);return{id:i.id,chainId:i.chainId,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,factoryAddress:i.factoryAddress,salt:i.salt,createdAt:i.createdAt,implementationAddress:i.implementationAddress,recoveryMethod:a.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const s=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC},o=await n.Authentication.fromStorage(this.storage);if(!o)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(s.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!o.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:o.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");s.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[d,h]=await Promise.all([this.ensureSigner(),this.getEntropy(s)]),g=await d.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),y={id:g.id,chainId:g.chainId,address:g.address,ownerAddress:g.ownerAddress,chainType:g.chainType,accountType:g.accountType,implementationType:g.implementationType,factoryAddress:g.factoryAddress,salt:g.salt,createdAt:g.createdAt,implementationAddress:g.implementationAddress,recoveryMethod:a.Account.parseRecoveryMethod(g.recoveryMethod),recoveryMethodDetails:g.recoveryMethodDetails};return this.eventEmitter.emit(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,y),y}async import(e){await this.validateAndRefreshToken();const s=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC},o=await n.Authentication.fromStorage(this.storage);if(!o)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(s.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!o.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:o.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");s.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[d,h]=await Promise.all([this.ensureSigner(),this.getEntropy(s)]),g=await d.import({privateKey:e.privateKey,accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),y={id:g.id,chainId:g.chainId,address:g.address,ownerAddress:g.ownerAddress,chainType:g.chainType,accountType:g.accountType,implementationType:g.implementationType,factoryAddress:g.factoryAddress,salt:g.salt,createdAt:g.createdAt,implementationAddress:g.implementationAddress,recoveryMethod:a.Account.parseRecoveryMethod(g.recoveryMethod),recoveryMethodDetails:g.recoveryMethodDetails};return this.eventEmitter.emit(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,y),y}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC};if(t.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!t.passkeyInfo?.passkeyId)throw new r.ConfigurationError("Passkey ID must be provided for passkey recovery");t.passkeyInfo={passkeyId:t.passkeyInfo.passkeyId}}const[s,n]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),i=await s.recover({account:e.account,entropy:n}),o={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:a.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(c.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o),o}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:s=!0,arrayifyMessage:n=!1}=r||{},i=await a.Account.fromStorage(this.storage);return await t.sign(e,n,s,i?.chainType)}async signTypedData(e,t,s){await this.validateAndRefreshToken();const n=await this.ensureSigner(),o=await a.Account.fromStorage(this.storage);if(!o)throw new r.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No account found");const d={...t};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),h=c.hash(e,d,s);return await l.signMessage({hash:h,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:n,address:o.address,ownerAddress:o.ownerAddress,factoryAddress:o.factoryAddress,salt:o.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,s){await this.validateAndRefreshToken();const o=await this.ensureSigner(),d=await n.Authentication.fromStorage(this.storage);if(!d)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");let h,g,y,u;if(e.recoveryMethod===c.RecoveryMethod.PASSKEY){const e=await a.Account.fromStorage(this.storage);if(!e)throw new r.ConfigurationError("missing account");const t=e?.recoveryMethodDetails?.passkeyId;if(!t)throw new r.ConfigurationError("missing passkey id for account");if(!d.userId)throw new r.ConfigurationError("User ID is required for passkey key derivation");y={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:d.userId})}}else if(s.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!d.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:d.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");y={passkeyId:e.id,passkeyKey:e.key},u={passkeyId:e.id}}if(e.recoveryMethod===c.RecoveryMethod.PASSWORD?h=e.password:s.recoveryMethod===c.RecoveryMethod.PASSWORD&&(h=s.password),e.recoveryMethod===c.RecoveryMethod.AUTOMATIC?g=e.encryptionSession:s.recoveryMethod===c.RecoveryMethod.AUTOMATIC&&(g=s.encryptionSession),!h&&!g)throw new r.ConfigurationError("Password or encryption session is not provided");await o.setRecoveryMethod({recoveryMethod:s.recoveryMethod,recoveryPassword:h,encryptionSession:g,passkeyInfo:y});const m=await a.Account.fromStorage(this.storage);m&&new a.Account({...m,recoveryMethod:s.recoveryMethod,recoveryMethodDetails:u}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await a.Account.fromStorage(this.storage);if(!e)throw new r.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No signer configured");if(!await n.Authentication.fromStorage(this.storage))throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:a.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const t={...e},d=s.SDKConfiguration.getInstance();if(!d)throw new r.ConfigurationError("Configuration not found");const c=await n.Authentication.fromStorage(this.storage);if(!c)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),o.withApiError(async()=>(await this.backendApiClients.accountsV2Api.getAccountsV2(t,{headers:c.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}:{authorization:`Bearer ${c.token}`,"x-project-key":d.baseConfiguration.publishableKey}})).data.data.map(e=>({chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:a.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await n.Authentication.fromStorage(this.storage))return c.EmbeddedState.UNAUTHENTICATED;return await a.Account.fromStorage(this.storage)?c.EmbeddedState.READY:c.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return h.debugLog("Failed to get embedded state:",e),c.EmbeddedState.UNAUTHENTICATED}}watchEmbeddedState(e){return g.observe("watchEmbeddedState",{onChange:e.onChange,onError:e.onError},r=>{let t;const s=async()=>{try{const e=await this.getEmbeddedState();t!==e&&(r.onChange?.(e,t),t=e)}catch(e){r.onError?.(e instanceof Error?e:new Error(String(e)))}};s();const a=()=>s(),n=()=>s(),i=()=>s(),o=()=>s();this.eventEmitter.on(c.OpenfortEvents.ON_AUTH_SUCCESS,a),this.eventEmitter.on(c.OpenfortEvents.ON_LOGOUT,n),this.eventEmitter.on(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,i),this.eventEmitter.on(c.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o);const d=setInterval(s,e.pollingInterval??2e3);return()=>{clearInterval(d),this.eventEmitter.off(c.OpenfortEvents.ON_AUTH_SUCCESS,a),this.eventEmitter.off(c.OpenfortEvents.ON_LOGOUT,n),this.eventEmitter.off(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,i),this.eventEmitter.off(c.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o)}})}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await n.Authentication.fromStorage(this.storage),s=await a.Account.fromStorage(this.storage);return this.provider?this.provider&&r.feeSponsorship&&this.provider.updateFeeSponsorship(r.feeSponsorship):(this.provider=new u.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,feeSponsorshipId:r.feeSponsorship,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&m.announceProvider({info:{...m.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.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return h.debugLog("Ping failed:",e),!1}}getURL(){const e=s.SDKConfiguration.getInstance();if(!e)throw new r.ConfigurationError("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new r.ConfigurationError("Invalid message poster");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 handleLogout(){if(this.storage.remove(d.StorageKeys.ACCOUNT),"undefined"==typeof document&&!this.messagePoster)return h.debugLog("Skipping signer disconnect: no messagePoster available in non-browser environment"),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,void(this.signerPromise=null);try{const e=await this.ensureSigner();await e.disconnect()}catch{}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 h.debugLog("Invalid message received:",e);h.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 h.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();h.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&h.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),h.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),h.debugLog("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}};
@@ -1 +1 @@
1
- "use strict";var e=require("axios"),t=require("../../version.cjs");const r="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class s{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(t){const n=t.getDsn();if(!n)throw new Error("Sentry DSN is not set");if(n.projectId!==r.split("https://")[1].split("/")[1]||n.host!==r.split("@")[1].split("/")[0]||n.publicKey!==r.split("@")[0].split("https://")[1])throw new Error("Sentry DSN is not valid");t.captureAxiosError=(r,n,o,a)=>{if(n instanceof e.AxiosError){if(400===n.response?.status||401===n.response?.status)return;n.name=r,t.captureException(n,{...o,captureContext:{...o?.captureContext,extra:{errorResponseData:n.response?.data,errorStatus:n.response?.status,errorHeaders:n.response?.headers,errorRequest:n.request},tags:{...s.baseTags,method:r}}})}else t.captureException(n,o,a)},t.captureError=(e,r,n,o)=>{const a=r.statusCode;if(400===a||401===a)return;const c=r,i=c.error,u=c.error_description,p=n?.captureContext;t.captureException(r,{...n,captureContext:{...p,extra:{...p?.extra,errorCode:i,errorDescription:u,errorClass:r.constructor.name,...c.statusCode&&{statusCode:c.statusCode},...c.audience&&{audience:c.audience},...c.scope&&{scope:c.scope},...c.accountId&&{accountId:c.accountId},...c.userId&&{userId:c.userId},...c.provider&&{provider:c.provider},...c.recoveryMethod&&{recoveryMethod:c.recoveryMethod}},tags:{...s.baseTags,context:e,errorClass:r.constructor.name}}})},s.sentryInstance=t}static get sentry(){return s.proxy}static async init({sentry:e,configuration:n}){if(e)return void(s.sentry=e);const o=await import("@sentry/browser");s.sentry=new o.BrowserClient({dsn:r,integrations:[],stackParser:o.defaultStackParser,transport:o.makeFetchTransport}),s.baseTags={projectId:n?.baseConfiguration.publishableKey??"",sdk:t.PACKAGE,sdkVersion:t.VERSION},s.processQueuedCalls()}static proxy=new Proxy({},{get:(e,t)=>s.sentryInstance&&"function"==typeof s.sentryInstance[t]?(...e)=>s.sentryInstance[t](...e):(...e)=>{s.queuedCalls.push({fn:t,args:e})}});static processQueuedCalls(){s.sentryInstance&&(s.queuedCalls.forEach(({fn:e,args:t})=>{"function"==typeof s.sentryInstance[e]&&s.sentryInstance[e](...t)}),s.queuedCalls=[])}}const{sentry:n}=s;exports.InternalSentry=s,exports.sentry=n;
1
+ "use strict";var e=require("axios"),t=require("../../version.cjs");const r="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class s{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(t){const n=t.getDsn();if(!n)throw new Error("Sentry DSN is not set");if(n.projectId!==r.split("https://")[1].split("/")[1]||n.host!==r.split("@")[1].split("/")[0]||n.publicKey!==r.split("@")[0].split("https://")[1])throw new Error("Sentry DSN is not valid");t.captureAxiosError=(r,n,o,a)=>{if(n instanceof e.AxiosError){if(400===n.response?.status||401===n.response?.status)return;n.name=r,t.captureException(n,{...o,captureContext:{...o?.captureContext,extra:{errorResponseData:n.response?.data,errorStatus:n.response?.status,errorHeaders:n.response?.headers,errorRequest:n.request},tags:{...s.baseTags,method:r}}})}else t.captureException(n,o,a)},t.captureError=(e,r,n,o)=>{const a=r.statusCode;if(400===a||401===a)return;const c=r,i=c.error,u=c.error_description,p=n?.captureContext;t.captureException(r,{...n,captureContext:{...p,extra:{...p?.extra,errorCode:i,errorDescription:u,errorClass:r.constructor.name,...c.statusCode&&{statusCode:c.statusCode},...c.audience&&{audience:c.audience},...c.scope&&{scope:c.scope},...c.accountId&&{accountId:c.accountId},...c.userId&&{userId:c.userId},...c.provider&&{provider:c.provider},...c.recoveryMethod&&{recoveryMethod:c.recoveryMethod}},tags:{...s.baseTags,context:e,errorClass:r.constructor.name}}})},s.sentryInstance=t}static get sentry(){return s.proxy}static async init({sentry:e,configuration:n}){if(e)return void(s.sentry=e);const o=await import("@sentry/browser");s.sentry=new o.BrowserClient({dsn:r,release:`${t.PACKAGE}@${t.VERSION}`,integrations:[],stackParser:o.defaultStackParser,transport:o.makeFetchTransport}),s.baseTags={projectId:n?.baseConfiguration.publishableKey??"",sdk:t.PACKAGE,sdkVersion:t.VERSION},s.processQueuedCalls()}static proxy=new Proxy({},{get:(e,t)=>s.sentryInstance&&"function"==typeof s.sentryInstance[t]?(...e)=>s.sentryInstance[t](...e):(...e)=>{s.queuedCalls.push({fn:t,args:e})}});static processQueuedCalls(){s.sentryInstance&&(s.queuedCalls.forEach(({fn:e,args:t})=>{"function"==typeof s.sentryInstance[e]&&s.sentryInstance[e](...t)}),s.queuedCalls=[])}}const{sentry:n}=s;exports.InternalSentry=s,exports.sentry=n;
@@ -1 +1 @@
1
- "use strict";var r=require("./core/openfort.cjs"),e=require("./api/auth.cjs"),o=require("./api/embeddedWallet.cjs"),t=require("./api/proxy.cjs"),s=require("./api/user.cjs"),n=require("./core/errors/authErrorCodes.cjs"),i=require("./core/errors/openfortError.cjs"),p=require("./core/passkey/errors.cjs"),u=require("./core/passkey/handler.cjs"),a=require("./core/passkey/utils.cjs"),E=require("./core/config/config.cjs"),c=require("./core/openfortInternal.cjs"),d=require("./utils/authorization.cjs"),f=require("./wallets/iframeManager.cjs"),y=require("./types/types.cjs"),x=require("./utils/crypto.cjs");const P=r.Openfort.getEventEmitter();exports.Openfort=r.Openfort,exports.AuthApi=e.AuthApi,exports.EmbeddedWalletApi=o.EmbeddedWalletApi,exports.ProxyApi=t.ProxyApi,exports.UserApi=s.UserApi,exports.OPENFORT_AUTH_ERROR_CODES=n.OPENFORT_AUTH_ERROR_CODES,exports.OPENFORT_ERROR_CODES=n.OPENFORT_ERROR_CODES,exports.AuthenticationError=i.AuthenticationError,exports.AuthorizationError=i.AuthorizationError,exports.ConfigurationError=i.ConfigurationError,exports.OAuthError=i.OAuthError,exports.OTPError=i.OTPError,exports.OpenfortError=i.OpenfortError,exports.RecoveryError=i.RecoveryError,exports.RequestError=i.RequestError,exports.SessionError=i.SessionError,exports.SignerError=i.SignerError,exports.UserError=i.UserError,exports.PASSKEY_ERROR_CODES=p.PASSKEY_ERROR_CODES,exports.PasskeyAssertionFailedError=p.PasskeyAssertionFailedError,exports.PasskeyCreationFailedError=p.PasskeyCreationFailedError,exports.PasskeyPRFNotSupportedError=p.PasskeyPRFNotSupportedError,exports.PasskeySeedInvalidError=p.PasskeySeedInvalidError,exports.PasskeyUserCancelledError=p.PasskeyUserCancelledError,exports.PasskeyHandler=u.PasskeyHandler,exports.arrayBufferToBase64URL=a.arrayBufferToBase64URL,exports.base64ToArrayBuffer=a.base64ToArrayBuffer,exports.OpenfortConfiguration=E.OpenfortConfiguration,exports.SDKConfiguration=E.SDKConfiguration,exports.ShieldConfiguration=E.ShieldConfiguration,exports.OpenfortInternal=c.OpenfortInternal,exports.prepareAndSignAuthorization=d.prepareAndSignAuthorization,exports.serializeSignedAuthorization=d.serializeSignedAuthorization,exports.signAuthorization=d.signAuthorization,exports.IframeSignEmptyResponseError=f.IframeSignEmptyResponseError,exports.IframeSignTimeoutError=f.IframeSignTimeoutError,exports.MissingProjectEntropyError=f.MissingProjectEntropyError,exports.MissingRecoveryPasswordError=f.MissingRecoveryPasswordError,exports.NotConfiguredError=f.NotConfiguredError,exports.OTPRequiredError=f.OTPRequiredError,exports.SessionEndedBeforeSetupError=f.SessionEndedBeforeSetupError,exports.WrongPasskeyError=f.WrongPasskeyError,exports.WrongRecoveryPasswordError=f.WrongRecoveryPasswordError,Object.defineProperty(exports,"AccountTypeEnum",{enumerable:!0,get:function(){return y.AccountTypeEnum}}),Object.defineProperty(exports,"AuthActionRequiredActions",{enumerable:!0,get:function(){return y.AuthActionRequiredActions}}),Object.defineProperty(exports,"AuthType",{enumerable:!0,get:function(){return y.AuthType}}),Object.defineProperty(exports,"BasicAuthProvider",{enumerable:!0,get:function(){return y.BasicAuthProvider}}),Object.defineProperty(exports,"ChainTypeEnum",{enumerable:!0,get:function(){return y.ChainTypeEnum}}),Object.defineProperty(exports,"EmbeddedState",{enumerable:!0,get:function(){return y.EmbeddedState}}),Object.defineProperty(exports,"OAuthProvider",{enumerable:!0,get:function(){return y.OAuthProvider}}),Object.defineProperty(exports,"OpenfortEvents",{enumerable:!0,get:function(){return y.OpenfortEvents}}),Object.defineProperty(exports,"RecoveryMethod",{enumerable:!0,get:function(){return y.RecoveryMethod}}),Object.defineProperty(exports,"ThirdPartyOAuthProvider",{enumerable:!0,get:function(){return y.ThirdPartyAuthProvider}}),Object.defineProperty(exports,"TokenType",{enumerable:!0,get:function(){return y.TokenType}}),exports.cryptoDigest=x.cryptoDigest,exports.openfortEvents=P;
1
+ "use strict";var r=require("./core/openfort.cjs"),e=require("./api/auth.cjs"),o=require("./api/embeddedWallet.cjs"),t=require("./api/proxy.cjs"),s=require("./api/user.cjs"),n=require("./core/errors/authErrorCodes.cjs"),i=require("./core/errors/openfortError.cjs"),p=require("./core/passkey/errors.cjs"),u=require("./core/passkey/handler.cjs"),a=require("./core/passkey/utils.cjs"),E=require("./core/config/config.cjs"),c=require("./core/openfortInternal.cjs"),d=require("./utils/authorization.cjs"),f=require("./wallets/iframeManager.cjs"),y=require("./types/types.cjs"),x=require("./utils/crypto.cjs");const P=r.Openfort.getEventEmitter();exports.Openfort=r.Openfort,exports.AuthApi=e.AuthApi,exports.EmbeddedWalletApi=o.EmbeddedWalletApi,exports.ProxyApi=t.ProxyApi,exports.UserApi=s.UserApi,exports.OPENFORT_AUTH_ERROR_CODES=n.OPENFORT_AUTH_ERROR_CODES,exports.OPENFORT_ERROR_CODES=n.OPENFORT_ERROR_CODES,exports.AuthenticationError=i.AuthenticationError,exports.AuthorizationError=i.AuthorizationError,exports.ConfigurationError=i.ConfigurationError,exports.OAuthError=i.OAuthError,exports.OTPError=i.OTPError,exports.OpenfortError=i.OpenfortError,exports.RecoveryError=i.RecoveryError,exports.RequestError=i.RequestError,exports.SessionError=i.SessionError,exports.SignerError=i.SignerError,exports.UserError=i.UserError,exports.PASSKEY_ERROR_CODES=p.PASSKEY_ERROR_CODES,exports.PasskeyAssertionFailedError=p.PasskeyAssertionFailedError,exports.PasskeyCreationFailedError=p.PasskeyCreationFailedError,exports.PasskeyPRFNotSupportedError=p.PasskeyPRFNotSupportedError,exports.PasskeySeedInvalidError=p.PasskeySeedInvalidError,exports.PasskeyUserCancelledError=p.PasskeyUserCancelledError,exports.PasskeyHandler=u.PasskeyHandler,exports.arrayBufferToBase64URL=a.arrayBufferToBase64URL,exports.base64ToArrayBuffer=a.base64ToArrayBuffer,exports.OpenfortConfiguration=E.OpenfortConfiguration,exports.SDKConfiguration=E.SDKConfiguration,exports.ShieldConfiguration=E.ShieldConfiguration,exports.OpenfortInternal=c.OpenfortInternal,exports.prepareAndSignAuthorization=d.prepareAndSignAuthorization,exports.serializeSignedAuthorization=d.serializeSignedAuthorization,exports.signAuthorization=d.signAuthorization,exports.IframeHandshakeTimeoutError=f.IframeHandshakeTimeoutError,exports.IframeSignEmptyResponseError=f.IframeSignEmptyResponseError,exports.IframeSignTimeoutError=f.IframeSignTimeoutError,exports.MissingProjectEntropyError=f.MissingProjectEntropyError,exports.MissingRecoveryPasswordError=f.MissingRecoveryPasswordError,exports.NotConfiguredError=f.NotConfiguredError,exports.OTPRequiredError=f.OTPRequiredError,exports.SessionEndedBeforeSetupError=f.SessionEndedBeforeSetupError,exports.WrongPasskeyError=f.WrongPasskeyError,exports.WrongRecoveryPasswordError=f.WrongRecoveryPasswordError,Object.defineProperty(exports,"AccountTypeEnum",{enumerable:!0,get:function(){return y.AccountTypeEnum}}),Object.defineProperty(exports,"AuthActionRequiredActions",{enumerable:!0,get:function(){return y.AuthActionRequiredActions}}),Object.defineProperty(exports,"AuthType",{enumerable:!0,get:function(){return y.AuthType}}),Object.defineProperty(exports,"BasicAuthProvider",{enumerable:!0,get:function(){return y.BasicAuthProvider}}),Object.defineProperty(exports,"ChainTypeEnum",{enumerable:!0,get:function(){return y.ChainTypeEnum}}),Object.defineProperty(exports,"EmbeddedState",{enumerable:!0,get:function(){return y.EmbeddedState}}),Object.defineProperty(exports,"OAuthProvider",{enumerable:!0,get:function(){return y.OAuthProvider}}),Object.defineProperty(exports,"OpenfortEvents",{enumerable:!0,get:function(){return y.OpenfortEvents}}),Object.defineProperty(exports,"RecoveryMethod",{enumerable:!0,get:function(){return y.RecoveryMethod}}),Object.defineProperty(exports,"ThirdPartyOAuthProvider",{enumerable:!0,get:function(){return y.ThirdPartyAuthProvider}}),Object.defineProperty(exports,"TokenType",{enumerable:!0,get:function(){return y.TokenType}}),exports.cryptoDigest=x.cryptoDigest,exports.openfortEvents=P;
@@ -1 +1 @@
1
- "use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.3.7";
1
+ "use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.3.9";
@@ -1 +1 @@
1
- "use strict";var e=require("../core/configuration/account.cjs"),r=require("../core/configuration/authentication.cjs"),i=require("../core/errors/authErrorCodes.cjs"),t=require("../core/errors/openfortError.cjs"),n=require("../core/errors/sentry.cjs"),o=require("../storage/istorage.cjs"),s=require("../utils/crypto.cjs"),a=require("../utils/debug.cjs"),d=require("./messaging/ReactNativeMessenger.cjs"),c=require("./messaging/browserMessenger/CallOptions.cjs"),u=require("./messaging/browserMessenger/connect.cjs");require("./messaging/browserMessenger/backwardCompatibility.cjs");var h=require("./messaging/browserMessenger/PenpalError.cjs"),l=require("./types.cjs");class g extends t.RecoveryError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class y extends t.RecoveryError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class p extends t.RecoveryError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class R extends t.RecoveryError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class f extends t.SignerError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.NOT_CONFIGURED,"Signer is not configured")}}class E extends t.OpenfortError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.OTP_REQUIRED,"OTP verification required")}}class w extends t.SignerError{constructor(e){super(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Iframe signer did not respond within ${e}ms. The signing prompt may have been dismissed or the iframe is unresponsive.`),this.name="IframeSignTimeoutError",Object.setPrototypeOf(this,w.prototype)}}class O extends t.SignerError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Iframe signer returned an empty signature."),this.name="IframeSignEmptyResponseError",Object.setPrototypeOf(this,O.prototype)}}class C extends t.OpenfortError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Wallet session ended before setup completed."),Object.setPrototypeOf(this,C.prototype)}}exports.IframeManager=class{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;isDestroyed=!1;hasFailed=!1;constructor(e,r,i){if(!e)throw new t.ConfigurationError("Configuration is required for IframeManager");if(!r)throw new t.ConfigurationError("Storage is required for IframeManager");if(!i)throw new t.ConfigurationError("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=r,this.messenger=i}assertAlive(){if(this.isDestroyed)throw new C}async initialize(){if(this.assertAlive(),!this.isInitialized){if(this.hasFailed)throw new t.OpenfortError(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)return await this.initializationPromise,void this.assertAlive();this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.assertAlive(),this.isInitialized=!0}catch(e){if(this.initializationPromise=null,e instanceof C)throw e;throw this.hasFailed=!0,e}}}async doInitialize(){a.debugLog("Initializing IframeManager connection..."),this.assertAlive(),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:a.debugLog}),this.connection=u({messenger:this.messenger,timeout:1e4,log:a.debugLog});try{this.remote=await this.connection.promise,this.assertAlive(),a.debugLog("IframeManager connection established")}catch(e){this.isDestroyed&&a.debugLog("Connection rejected after destroy() — surfacing teardown error"),this.assertAlive();const r=e;throw n.sentry.captureException(r),this.clearConnection(),a.debugLog("Failed to establish connection:",r),new t.OpenfortError(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Failed to establish iFrame connection: ${r.cause||r.message}\n\n In apps built with:\n - react native\n - swift\n - unity (non-webgl)\n\n You must configure your origin in the openfort dashboard before using the embedded wallet.\n\n For more information, see: https://www.openfort.io/docs/configuration/native-apps\n `)}}clearConnection(){if(this.connection)try{this.connection.destroy()}catch(e){a.debugLog("clearConnection: connection.destroy() threw, swallowing:",e)}this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new t.OpenfortError(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(l.isErrorResponse(e)){if(e.error===l.NOT_CONFIGURED_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new f;if(e.error===l.MISSING_USER_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new g;if(e.error===l.MISSING_PROJECT_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new p;if(e.error===l.INCORRECT_USER_ENTROPY_ERROR)throw new R;if(e.error===l.MISSING_PASSKEY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new g;if(e.error===l.INCORRECT_PASSKEY_ERROR)throw new y;if(e.error===l.OTP_REQUIRED_ERROR)throw new E;throw this.storage.remove(o.StorageKeys.ACCOUNT),new t.OpenfortError(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await r.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:l.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await r.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:l.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await this.ensureConnection(),i=await this.buildIFrameRequestConfiguration();i.chainId=e.chainId??null,i.password=e?.entropy?.recoveryPassword??null,i.recovery={...i.recovery,encryptionSession:e?.entropy?.encryptionSession},i.passkey=e?.entropy?.passkey??null;const t={uuid:s.randomUUID(),action:l.Event.CREATE,recovery:i.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:i.accessToken,playerID:i.playerID,thirdPartyProvider:i.thirdPartyProvider,thirdPartyTokenType:i.thirdPartyTokenType,encryptionKey:i.password,encryptionSession:i.recovery?.encryptionSession??null,passkey:i.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},n=await r.create(t);return l.isErrorResponse(n)&&this.handleError(n),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",n.version??"undefined"),n}async import(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await this.ensureConnection(),i=await this.buildIFrameRequestConfiguration();i.chainId=e.chainId??null,i.password=e?.entropy?.recoveryPassword??null,i.recovery={...i.recovery,encryptionSession:e?.entropy?.encryptionSession},i.passkey=e?.entropy?.passkey??null;const t={uuid:s.randomUUID(),action:l.Event.IMPORT,privateKey:e.privateKey,recovery:i.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:i.accessToken,playerID:i.playerID,thirdPartyProvider:i.thirdPartyProvider,thirdPartyTokenType:i.thirdPartyTokenType,encryptionKey:i.password,encryptionSession:i.recovery?.encryptionSession??null,passkey:i.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},n=await r.import(t);return l.isErrorResponse(n)&&this.handleError(n),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",n.version??"undefined"),n}async recover(r){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await e.Account.fromStorage(this.storage),t=await this.ensureConnection(),n=await this.buildIFrameRequestConfiguration();n.chainId=i?.chainId??null,n.password=r?.entropy?.recoveryPassword??null,n.recovery={...n.recovery,encryptionSession:r?.entropy?.encryptionSession},n.passkey=r?.entropy?.passkey??null;const o={uuid:s.randomUUID(),action:l.Event.RECOVER,recovery:n.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:n.accessToken,playerID:n.playerID,thirdPartyProvider:n.thirdPartyProvider,thirdPartyTokenType:n.thirdPartyTokenType,encryptionKey:n.password,encryptionSession:n.recovery?.encryptionSession??null,passkey:n.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:r.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},a=await t.recover(o);return l.isErrorResponse(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,r,i,t){a.debugLog("[iframe] ensureConnection");const n=await this.ensureConnection(),o=new l.SignRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),r,i,t);let d;a.debugLog("[iframe] done ensureConnection"),this.assertAlive();try{d=await n.sign(o,new c({timeout:9e4}))}catch(e){if(e instanceof h&&"METHOD_CALL_TIMEOUT"===e.code)throw this.hasFailed=!0,new w(9e4);throw e}if(a.debugLog("[iframe] response",d),l.isErrorResponse(d)&&this.handleError(d),!d.signature)throw new O;return"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined"),d.signature}async switchChain(e){const r=await this.ensureConnection(),i=new l.SwitchChainRequest(s.randomUUID(),e,await this.buildRequestConfiguration()),t=await r.switchChain(i);return l.isErrorResponse(t)&&this.handleError(t),t}async export(){const e=await this.ensureConnection(),r=new l.ExportPrivateKeyRequest(s.randomUUID(),await this.buildRequestConfiguration()),i=await e.export(r);return l.isErrorResponse(i)&&this.handleError(i),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",i.version??"undefined"),i.key}async setRecoveryMethod(e,r,i,t,n){const o=await this.ensureConnection(),a=new l.SetRecoveryMethodRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),r,i,t,n),d=await o.setRecoveryMethod(a);l.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined")}async getCurrentDevice(e){const r=await this.ensureConnection(),i=new l.GetCurrentDeviceRequest(s.randomUUID(),e);try{const e=await r.getCurrentDevice(i);return l.isErrorResponse(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof f)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void a.debugLog("IframeManager not loaded, skipping authentication update");const e=await r.Authentication.fromStorage(this.storage);if(!e)return void a.debugLog("No authentication found, skipping update");const i=new l.UpdateAuthenticationRequest(s.randomUUID(),e.token);a.debugLog("Updating authentication in iframe with token");const t=await this.remote.updateAuthentication(i);l.isErrorResponse(t)&&this.handleError(t)}async disconnect(){const e=await this.ensureConnection(),r={uuid:s.randomUUID()};await e.logout(r)}async onMessage(e){a.debugLog("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof d.ReactNativeMessenger?(this.isInitialized||this.connection?a.debugLog(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(a.debugLog("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{a.debugLog("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),a.debugLog("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):a.debugLog("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.clearConnection())}},exports.IframeSignEmptyResponseError=O,exports.IframeSignTimeoutError=w,exports.MissingProjectEntropyError=p,exports.MissingRecoveryPasswordError=g,exports.NotConfiguredError=f,exports.OTPRequiredError=E,exports.SessionEndedBeforeSetupError=C,exports.WrongPasskeyError=y,exports.WrongRecoveryPasswordError=R;
1
+ "use strict";var e=require("../core/configuration/account.cjs"),r=require("../core/configuration/authentication.cjs"),i=require("../core/errors/authErrorCodes.cjs"),t=require("../core/errors/openfortError.cjs"),n=require("../core/errors/sentry.cjs"),o=require("../storage/istorage.cjs"),s=require("../utils/crypto.cjs"),a=require("../utils/debug.cjs"),d=require("./messaging/ReactNativeMessenger.cjs"),c=require("./messaging/browserMessenger/CallOptions.cjs"),h=require("./messaging/browserMessenger/connect.cjs");require("./messaging/browserMessenger/backwardCompatibility.cjs");var u=require("./messaging/browserMessenger/PenpalError.cjs"),l=require("./types.cjs");class g extends t.RecoveryError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class p extends t.RecoveryError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class y extends t.RecoveryError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class R extends t.RecoveryError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class f extends t.SignerError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.NOT_CONFIGURED,"Signer is not configured")}}class E extends t.OpenfortError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.OTP_REQUIRED,"OTP verification required")}}class O extends t.SignerError{constructor(e){super(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Iframe signer did not respond within ${e}ms. The signing prompt may have been dismissed or the iframe is unresponsive.`),this.name="IframeSignTimeoutError",Object.setPrototypeOf(this,O.prototype)}}class w extends t.SignerError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Iframe signer returned an empty signature."),this.name="IframeSignEmptyResponseError",Object.setPrototypeOf(this,w.prototype)}}class m extends t.OpenfortError{constructor(){super(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Wallet session ended before setup completed."),Object.setPrototypeOf(this,m.prototype)}}class C extends t.OpenfortError{constructor(e,r){super(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Failed to establish iframe connection within ${e}ms. The embedded wallet page did not respond — it may be unreachable or blocked by CSP/network.`),this.name="IframeHandshakeTimeoutError",this.cause=r,Object.setPrototypeOf(this,C.prototype)}}exports.IframeHandshakeTimeoutError=C,exports.IframeManager=class{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;isDestroyed=!1;hasFailed=!1;constructor(e,r,i){if(!e)throw new t.ConfigurationError("Configuration is required for IframeManager");if(!r)throw new t.ConfigurationError("Storage is required for IframeManager");if(!i)throw new t.ConfigurationError("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=r,this.messenger=i}assertAlive(){if(this.isDestroyed)throw new m}async initialize(){if(this.assertAlive(),!this.isInitialized){if(this.hasFailed)throw new t.OpenfortError(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)return await this.initializationPromise,void this.assertAlive();this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.assertAlive(),this.isInitialized=!0}catch(e){if(this.initializationPromise=null,e instanceof m)throw e;throw this.hasFailed=!0,e}}}async doInitialize(){a.debugLog("Initializing IframeManager connection..."),this.assertAlive(),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:a.debugLog}),this.connection=h({messenger:this.messenger,timeout:1e4,log:a.debugLog});try{this.remote=await this.connection.promise,this.assertAlive(),a.debugLog("IframeManager connection established")}catch(e){if(this.isDestroyed&&a.debugLog("Connection rejected after destroy() — surfacing teardown error"),this.assertAlive(),n.sentry.captureException(e),this.clearConnection(),a.debugLog("Failed to establish connection:",e),e instanceof u&&"CONNECTION_TIMEOUT"===e.code)throw new C(1e4,e);const r=e;throw new t.OpenfortError(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Failed to establish iFrame connection: ${r.cause||r.message}\n\n In apps built with:\n - react native\n - swift\n - unity (non-webgl)\n\n You must configure your origin in the openfort dashboard before using the embedded wallet.\n\n For more information, see: https://www.openfort.io/docs/configuration/native-apps\n `)}}clearConnection(){if(this.connection)try{this.connection.destroy()}catch(e){a.debugLog("clearConnection: connection.destroy() threw, swallowing:",e)}this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new t.OpenfortError(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(l.isErrorResponse(e)){if(e.error===l.NOT_CONFIGURED_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new f;if(e.error===l.MISSING_USER_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new g;if(e.error===l.MISSING_PROJECT_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new y;if(e.error===l.INCORRECT_USER_ENTROPY_ERROR)throw new R;if(e.error===l.MISSING_PASSKEY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new g;if(e.error===l.INCORRECT_PASSKEY_ERROR)throw new p;if(e.error===l.OTP_REQUIRED_ERROR)throw new E;throw this.storage.remove(o.StorageKeys.ACCOUNT),new t.OpenfortError(i.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await r.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:l.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await r.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:l.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await this.ensureConnection(),i=await this.buildIFrameRequestConfiguration();i.chainId=e.chainId??null,i.password=e?.entropy?.recoveryPassword??null,i.recovery={...i.recovery,encryptionSession:e?.entropy?.encryptionSession},i.passkey=e?.entropy?.passkey??null;const t={uuid:s.randomUUID(),action:l.Event.CREATE,recovery:i.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:i.accessToken,playerID:i.playerID,thirdPartyProvider:i.thirdPartyProvider,thirdPartyTokenType:i.thirdPartyTokenType,encryptionKey:i.password,encryptionSession:i.recovery?.encryptionSession??null,passkey:i.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},n=await r.create(t);return l.isErrorResponse(n)&&this.handleError(n),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",n.version??"undefined"),n}async import(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await this.ensureConnection(),i=await this.buildIFrameRequestConfiguration();i.chainId=e.chainId??null,i.password=e?.entropy?.recoveryPassword??null,i.recovery={...i.recovery,encryptionSession:e?.entropy?.encryptionSession},i.passkey=e?.entropy?.passkey??null;const t={uuid:s.randomUUID(),action:l.Event.IMPORT,privateKey:e.privateKey,recovery:i.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:i.accessToken,playerID:i.playerID,thirdPartyProvider:i.thirdPartyProvider,thirdPartyTokenType:i.thirdPartyTokenType,encryptionKey:i.password,encryptionSession:i.recovery?.encryptionSession??null,passkey:i.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},n=await r.import(t);return l.isErrorResponse(n)&&this.handleError(n),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",n.version??"undefined"),n}async recover(r){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await e.Account.fromStorage(this.storage),t=await this.ensureConnection(),n=await this.buildIFrameRequestConfiguration();n.chainId=i?.chainId??null,n.password=r?.entropy?.recoveryPassword??null,n.recovery={...n.recovery,encryptionSession:r?.entropy?.encryptionSession},n.passkey=r?.entropy?.passkey??null;const o={uuid:s.randomUUID(),action:l.Event.RECOVER,recovery:n.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:n.accessToken,playerID:n.playerID,thirdPartyProvider:n.thirdPartyProvider,thirdPartyTokenType:n.thirdPartyTokenType,encryptionKey:n.password,encryptionSession:n.recovery?.encryptionSession??null,passkey:n.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:r.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},a=await t.recover(o);return l.isErrorResponse(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,r,i,t){a.debugLog("[iframe] ensureConnection");const n=await this.ensureConnection(),o=new l.SignRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),r,i,t);let d;a.debugLog("[iframe] done ensureConnection"),this.assertAlive();try{d=await n.sign(o,new c({timeout:9e4}))}catch(e){if(e instanceof u&&"METHOD_CALL_TIMEOUT"===e.code)throw this.hasFailed=!0,new O(9e4);throw e}if(a.debugLog("[iframe] response",d),l.isErrorResponse(d)&&this.handleError(d),!d.signature)throw new w;return"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined"),d.signature}async switchChain(e){const r=await this.ensureConnection(),i=new l.SwitchChainRequest(s.randomUUID(),e,await this.buildRequestConfiguration()),t=await r.switchChain(i);return l.isErrorResponse(t)&&this.handleError(t),t}async export(){const e=await this.ensureConnection(),r=new l.ExportPrivateKeyRequest(s.randomUUID(),await this.buildRequestConfiguration()),i=await e.export(r);return l.isErrorResponse(i)&&this.handleError(i),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",i.version??"undefined"),i.key}async setRecoveryMethod(e,r,i,t,n){const o=await this.ensureConnection(),a=new l.SetRecoveryMethodRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),r,i,t,n),d=await o.setRecoveryMethod(a);l.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined")}async getCurrentDevice(e){const r=await this.ensureConnection(),i=new l.GetCurrentDeviceRequest(s.randomUUID(),e);try{const e=await r.getCurrentDevice(i);return l.isErrorResponse(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof f)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void a.debugLog("IframeManager not loaded, skipping authentication update");const e=await r.Authentication.fromStorage(this.storage);if(!e)return void a.debugLog("No authentication found, skipping update");const i=new l.UpdateAuthenticationRequest(s.randomUUID(),e.token);a.debugLog("Updating authentication in iframe with token");const t=await this.remote.updateAuthentication(i);l.isErrorResponse(t)&&this.handleError(t)}async disconnect(){const e=await this.ensureConnection(),r={uuid:s.randomUUID()};await e.logout(r)}async onMessage(e){a.debugLog("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof d.ReactNativeMessenger?(this.isInitialized||this.connection?a.debugLog(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(a.debugLog("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{a.debugLog("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),a.debugLog("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):a.debugLog("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.clearConnection())}},exports.IframeSignEmptyResponseError=w,exports.IframeSignTimeoutError=O,exports.MissingProjectEntropyError=y,exports.MissingRecoveryPasswordError=g,exports.NotConfiguredError=f,exports.OTPRequiredError=E,exports.SessionEndedBeforeSetupError=m,exports.WrongPasskeyError=p,exports.WrongRecoveryPasswordError=R;
package/dist/index.d.cts CHANGED
@@ -12988,6 +12988,19 @@ declare class IframeSignEmptyResponseError extends SignerError {
12988
12988
  declare class SessionEndedBeforeSetupError extends OpenfortError {
12989
12989
  constructor();
12990
12990
  }
12991
+ /**
12992
+ * Thrown when the penpal handshake does not complete within the connection
12993
+ * window — the iframe never replied to SYN/ACK. Distinct from a dashboard
12994
+ * origin misconfiguration: a timeout usually means the embed page is
12995
+ * unreachable, blocked by CSP, or the network dropped the load. Collapsing it
12996
+ * into the native-app "configure your origin" copy misled web users whose
12997
+ * origin was fine (Sentry OPENFORT-JS-D0, seen on playground.openfort.io). The
12998
+ * original PenpalError is kept as `cause` so callers can still inspect
12999
+ * `code === 'CONNECTION_TIMEOUT'`.
13000
+ */
13001
+ declare class IframeHandshakeTimeoutError extends OpenfortError {
13002
+ constructor(timeoutMs: number, cause: unknown);
13003
+ }
12991
13004
 
12992
13005
  interface Signer$1 {
12993
13006
  sign(message: Uint8Array | string, requireArrayify?: boolean, requireHash?: boolean): Promise<string>;
@@ -13285,4 +13298,4 @@ declare function cryptoDigest(algorithm: string, data: BufferSource): Promise<Ar
13285
13298
  */
13286
13299
  declare const openfortEvents: TypedEventEmitter<OpenfortEventMap>;
13287
13300
 
13288
- export { AccountTypeEnum, AuthActionRequiredActions, AuthActionRequiredResponse, AuthApi, AuthInitPayload, AuthResponse, AuthType, AuthenticationError, Authorization, AuthorizationError, BasicAuthProvider, ChainTypeEnum, ConfigurationError, EmbeddedAccount, EmbeddedState, EmbeddedWalletApi, GrantPermissionsParameters, GrantPermissionsReturnType, IPasskeyHandler, IframeSignEmptyResponseError, IframeSignTimeoutError, InitializeOAuthOptions, MissingProjectEntropyError, MissingRecoveryPasswordError, NotConfiguredError, OAuthError, OAuthProvider, OPENFORT_AUTH_ERROR_CODES, OPENFORT_ERROR_CODES, OTPError, OTPRequiredError, Openfort, OpenfortAuthErrorCode, OpenfortConfiguration, OpenfortError, OpenfortErrorCode, OpenfortEventMap, OpenfortEvents, OpenfortInternal, OpenfortSDKConfiguration, PASSKEY_ERROR_CODES, PasskeyAssertionFailedError, PasskeyCreateConfig, PasskeyCreationFailedError, PasskeyDeriveConfig, PasskeyDetails, PasskeyEnv, PasskeyErrorCode, PasskeyHandler, PasskeyPRFNotSupportedError, PasskeySeedInvalidError, PasskeyUserCancelledError, Permission, Policy, PrepareAuthorizationParams, Provider, ProxyApi, RecoveryError, RecoveryMethod, RecoveryMethodDetails, RecoveryParams, RequestError, RevokePermissionsRequestParams, SDKConfiguration, SDKOverrides, SessionEndedBeforeSetupError, SessionError, SessionResponse, ShieldAuthOptions, ShieldConfiguration, ShieldOptions, SignAuthorizationParams, SignedAuthorization, SignedMessagePayload, Signer, SignerError, IStorage as Storage, ThirdPartyAuthConfiguration, ThirdPartyAuthProvider as ThirdPartyOAuthProvider, TokenType, TransactionIntentResponse, TypedDataPayload, User, ListAccountsGet200ResponseInner as UserAccount, UserApi, UserError, WrongPasskeyError, WrongRecoveryPasswordError, arrayBufferToBase64URL, base64ToArrayBuffer, cryptoDigest, openfortEvents, prepareAndSignAuthorization, serializeSignedAuthorization, signAuthorization };
13301
+ export { AccountTypeEnum, AuthActionRequiredActions, AuthActionRequiredResponse, AuthApi, AuthInitPayload, AuthResponse, AuthType, AuthenticationError, Authorization, AuthorizationError, BasicAuthProvider, ChainTypeEnum, ConfigurationError, EmbeddedAccount, EmbeddedState, EmbeddedWalletApi, GrantPermissionsParameters, GrantPermissionsReturnType, IPasskeyHandler, IframeHandshakeTimeoutError, IframeSignEmptyResponseError, IframeSignTimeoutError, InitializeOAuthOptions, MissingProjectEntropyError, MissingRecoveryPasswordError, NotConfiguredError, OAuthError, OAuthProvider, OPENFORT_AUTH_ERROR_CODES, OPENFORT_ERROR_CODES, OTPError, OTPRequiredError, Openfort, OpenfortAuthErrorCode, OpenfortConfiguration, OpenfortError, OpenfortErrorCode, OpenfortEventMap, OpenfortEvents, OpenfortInternal, OpenfortSDKConfiguration, PASSKEY_ERROR_CODES, PasskeyAssertionFailedError, PasskeyCreateConfig, PasskeyCreationFailedError, PasskeyDeriveConfig, PasskeyDetails, PasskeyEnv, PasskeyErrorCode, PasskeyHandler, PasskeyPRFNotSupportedError, PasskeySeedInvalidError, PasskeyUserCancelledError, Permission, Policy, PrepareAuthorizationParams, Provider, ProxyApi, RecoveryError, RecoveryMethod, RecoveryMethodDetails, RecoveryParams, RequestError, RevokePermissionsRequestParams, SDKConfiguration, SDKOverrides, SessionEndedBeforeSetupError, SessionError, SessionResponse, ShieldAuthOptions, ShieldConfiguration, ShieldOptions, SignAuthorizationParams, SignedAuthorization, SignedMessagePayload, Signer, SignerError, IStorage as Storage, ThirdPartyAuthConfiguration, ThirdPartyAuthProvider as ThirdPartyOAuthProvider, TokenType, TransactionIntentResponse, TypedDataPayload, User, ListAccountsGet200ResponseInner as UserAccount, UserApi, UserError, WrongPasskeyError, WrongRecoveryPasswordError, arrayBufferToBase64URL, base64ToArrayBuffer, cryptoDigest, openfortEvents, prepareAndSignAuthorization, serializeSignedAuthorization, signAuthorization };
package/dist/index.d.ts CHANGED
@@ -12988,6 +12988,19 @@ declare class IframeSignEmptyResponseError extends SignerError {
12988
12988
  declare class SessionEndedBeforeSetupError extends OpenfortError {
12989
12989
  constructor();
12990
12990
  }
12991
+ /**
12992
+ * Thrown when the penpal handshake does not complete within the connection
12993
+ * window — the iframe never replied to SYN/ACK. Distinct from a dashboard
12994
+ * origin misconfiguration: a timeout usually means the embed page is
12995
+ * unreachable, blocked by CSP, or the network dropped the load. Collapsing it
12996
+ * into the native-app "configure your origin" copy misled web users whose
12997
+ * origin was fine (Sentry OPENFORT-JS-D0, seen on playground.openfort.io). The
12998
+ * original PenpalError is kept as `cause` so callers can still inspect
12999
+ * `code === 'CONNECTION_TIMEOUT'`.
13000
+ */
13001
+ declare class IframeHandshakeTimeoutError extends OpenfortError {
13002
+ constructor(timeoutMs: number, cause: unknown);
13003
+ }
12991
13004
 
12992
13005
  interface Signer$1 {
12993
13006
  sign(message: Uint8Array | string, requireArrayify?: boolean, requireHash?: boolean): Promise<string>;
@@ -13285,4 +13298,4 @@ declare function cryptoDigest(algorithm: string, data: BufferSource): Promise<Ar
13285
13298
  */
13286
13299
  declare const openfortEvents: TypedEventEmitter<OpenfortEventMap>;
13287
13300
 
13288
- export { AccountTypeEnum, AuthActionRequiredActions, AuthActionRequiredResponse, AuthApi, AuthInitPayload, AuthResponse, AuthType, AuthenticationError, Authorization, AuthorizationError, BasicAuthProvider, ChainTypeEnum, ConfigurationError, EmbeddedAccount, EmbeddedState, EmbeddedWalletApi, GrantPermissionsParameters, GrantPermissionsReturnType, IPasskeyHandler, IframeSignEmptyResponseError, IframeSignTimeoutError, InitializeOAuthOptions, MissingProjectEntropyError, MissingRecoveryPasswordError, NotConfiguredError, OAuthError, OAuthProvider, OPENFORT_AUTH_ERROR_CODES, OPENFORT_ERROR_CODES, OTPError, OTPRequiredError, Openfort, OpenfortAuthErrorCode, OpenfortConfiguration, OpenfortError, OpenfortErrorCode, OpenfortEventMap, OpenfortEvents, OpenfortInternal, OpenfortSDKConfiguration, PASSKEY_ERROR_CODES, PasskeyAssertionFailedError, PasskeyCreateConfig, PasskeyCreationFailedError, PasskeyDeriveConfig, PasskeyDetails, PasskeyEnv, PasskeyErrorCode, PasskeyHandler, PasskeyPRFNotSupportedError, PasskeySeedInvalidError, PasskeyUserCancelledError, Permission, Policy, PrepareAuthorizationParams, Provider, ProxyApi, RecoveryError, RecoveryMethod, RecoveryMethodDetails, RecoveryParams, RequestError, RevokePermissionsRequestParams, SDKConfiguration, SDKOverrides, SessionEndedBeforeSetupError, SessionError, SessionResponse, ShieldAuthOptions, ShieldConfiguration, ShieldOptions, SignAuthorizationParams, SignedAuthorization, SignedMessagePayload, Signer, SignerError, IStorage as Storage, ThirdPartyAuthConfiguration, ThirdPartyAuthProvider as ThirdPartyOAuthProvider, TokenType, TransactionIntentResponse, TypedDataPayload, User, ListAccountsGet200ResponseInner as UserAccount, UserApi, UserError, WrongPasskeyError, WrongRecoveryPasswordError, arrayBufferToBase64URL, base64ToArrayBuffer, cryptoDigest, openfortEvents, prepareAndSignAuthorization, serializeSignedAuthorization, signAuthorization };
13301
+ export { AccountTypeEnum, AuthActionRequiredActions, AuthActionRequiredResponse, AuthApi, AuthInitPayload, AuthResponse, AuthType, AuthenticationError, Authorization, AuthorizationError, BasicAuthProvider, ChainTypeEnum, ConfigurationError, EmbeddedAccount, EmbeddedState, EmbeddedWalletApi, GrantPermissionsParameters, GrantPermissionsReturnType, IPasskeyHandler, IframeHandshakeTimeoutError, IframeSignEmptyResponseError, IframeSignTimeoutError, InitializeOAuthOptions, MissingProjectEntropyError, MissingRecoveryPasswordError, NotConfiguredError, OAuthError, OAuthProvider, OPENFORT_AUTH_ERROR_CODES, OPENFORT_ERROR_CODES, OTPError, OTPRequiredError, Openfort, OpenfortAuthErrorCode, OpenfortConfiguration, OpenfortError, OpenfortErrorCode, OpenfortEventMap, OpenfortEvents, OpenfortInternal, OpenfortSDKConfiguration, PASSKEY_ERROR_CODES, PasskeyAssertionFailedError, PasskeyCreateConfig, PasskeyCreationFailedError, PasskeyDeriveConfig, PasskeyDetails, PasskeyEnv, PasskeyErrorCode, PasskeyHandler, PasskeyPRFNotSupportedError, PasskeySeedInvalidError, PasskeyUserCancelledError, Permission, Policy, PrepareAuthorizationParams, Provider, ProxyApi, RecoveryError, RecoveryMethod, RecoveryMethodDetails, RecoveryParams, RequestError, RevokePermissionsRequestParams, SDKConfiguration, SDKOverrides, SessionEndedBeforeSetupError, SessionError, SessionResponse, ShieldAuthOptions, ShieldConfiguration, ShieldOptions, SignAuthorizationParams, SignedAuthorization, SignedMessagePayload, Signer, SignerError, IStorage as Storage, ThirdPartyAuthConfiguration, ThirdPartyAuthProvider as ThirdPartyOAuthProvider, TokenType, TransactionIntentResponse, TypedDataPayload, User, ListAccountsGet200ResponseInner as UserAccount, UserApi, UserError, WrongPasskeyError, WrongRecoveryPasswordError, arrayBufferToBase64URL, base64ToArrayBuffer, cryptoDigest, openfortEvents, prepareAndSignAuthorization, serializeSignedAuthorization, signAuthorization };
@@ -1 +1 @@
1
- import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{ConfigurationError as t,AuthenticationError as r,SessionError as s,SignerError as a}from"../core/errors/openfortError.js";import{PasskeyHandler as i}from"../core/passkey/handler.js";import{SDKConfiguration as n}from"../core/config/config.js";import{Account as o}from"../core/configuration/account.js";import{Authentication as d}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as c}from"../core/errors/authErrorCodes.js";import{withApiError as h}from"../core/errors/withApiError.js";import{StorageKeys as m}from"../storage/istorage.js";import{OpenfortEvents as y,RecoveryMethod as g,ChainTypeEnum as l,AccountTypeEnum as p,EmbeddedState as f}from"../types/types.js";import{debugLog as u}from"../utils/debug.js";import{observe as w}from"../utils/observe.js";import{EmbeddedSigner as A}from"../wallets/embedded.js";import{EvmProvider as E}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as v,openfortProviderInfo as M}from"../wallets/evm/provider/eip6963.js";import{signMessage as T}from"../wallets/evm/walletHelpers.js";import{IframeManager as D}from"../wallets/iframeManager.js";import{ReactNativeMessenger as I}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import S from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class k{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,t,r,s,a){this.storage=e,this.validateAndRefreshToken=t,this.ensureInitialized=r,this.eventEmitter=s,this.passkeyHandler=a,this.eventEmitter.on(y.ON_LOGOUT,()=>{u("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const r=n.getInstance();if(!r)throw new t("Configuration not found");return new e({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey,nativeAppIdentifier:r.nativeAppIdentifier})}async getIframeManager(){if(u("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(u("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return u("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return u("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;u("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return u("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,u("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw u("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){u("[HANDSHAKE DEBUG] createIframeManager starting");const e=n.getInstance();if(!e)throw u("[HANDSHAKE DEBUG] Configuration not found"),new t("Configuration not found");let r;if(u("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)u("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(u("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new I(this.messagePoster),u("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{u("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;r=new S({remoteWindow:t.contentWindow,allowedOrigins:[s]}),u("[HANDSHAKE DEBUG] Created WindowMessenger")}return u("[HANDSHAKE DEBUG] Creating IframeManager instance"),new D(e,this.storage,r)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(u("IframeManager has failed, clearing signer for recreation"),this.signer=null),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();await e.initialize();return new A(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new t("Document is not available. Please provide a message poster for non-browser environments.");const r=document.getElementById("openfort-iframe");r&&r.remove();const s=document.createElement("iframe");return s.style.display="none",s.id="openfort-iframe",s.src=e,document.body.appendChild(s),s}async getPasskeyKey(e){const t=await d.fromStorage(this.storage);if(!t?.userId)throw new r("auth","User is required for passkey key derivation. Logout and login again.",401);return this.passkeyHandler.deriveAndExportKey({id:e,seed:t.userId})}async getEntropy(e){switch(e.recoveryMethod){case g.PASSWORD:return{recoveryPassword:e.password};case g.AUTOMATIC:return{encryptionSession:e.encryptionSession};case g.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new t("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:g.AUTOMATIC},[r,s]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),a={chainId:e.chainId,entropy:s,accountType:e.accountType??p.SMART_ACCOUNT,chainType:e.chainType??l.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},i=await r.configure(a);return{id:i.id,chainId:i.chainId,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,factoryAddress:i.factoryAddress,salt:i.salt,createdAt:i.createdAt,implementationAddress:i.implementationAddress,recoveryMethod:o.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:g.AUTOMATIC},a=await d.fromStorage(this.storage);if(!a)throw new s(c.NOT_LOGGED_IN,"missing authentication");if(r.recoveryMethod===g.PASSKEY){if(!a.userId)throw new t("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:a.userId});if(!e.key)throw new t("Passkey creation failed: no key material returned");r.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[n,h]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),m=await n.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),l={id:m.id,chainId:m.chainId,address:m.address,ownerAddress:m.ownerAddress,chainType:m.chainType,accountType:m.accountType,implementationType:m.implementationType,factoryAddress:m.factoryAddress,salt:m.salt,createdAt:m.createdAt,implementationAddress:m.implementationAddress,recoveryMethod:o.parseRecoveryMethod(m.recoveryMethod),recoveryMethodDetails:m.recoveryMethodDetails};return this.eventEmitter.emit(y.ON_EMBEDDED_WALLET_CREATED,l),l}async import(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:g.AUTOMATIC},a=await d.fromStorage(this.storage);if(!a)throw new s(c.NOT_LOGGED_IN,"missing authentication");if(r.recoveryMethod===g.PASSKEY){if(!a.userId)throw new t("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:a.userId});if(!e.key)throw new t("Passkey creation failed: no key material returned");r.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[n,h]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),m=await n.import({privateKey:e.privateKey,accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),l={id:m.id,chainId:m.chainId,address:m.address,ownerAddress:m.ownerAddress,chainType:m.chainType,accountType:m.accountType,implementationType:m.implementationType,factoryAddress:m.factoryAddress,salt:m.salt,createdAt:m.createdAt,implementationAddress:m.implementationAddress,recoveryMethod:o.parseRecoveryMethod(m.recoveryMethod),recoveryMethodDetails:m.recoveryMethodDetails};return this.eventEmitter.emit(y.ON_EMBEDDED_WALLET_CREATED,l),l}async recover(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:g.AUTOMATIC};if(r.recoveryMethod===g.PASSKEY){if(!r.passkeyInfo?.passkeyId)throw new t("Passkey ID must be provided for passkey recovery");r.passkeyInfo={passkeyId:r.passkeyInfo.passkeyId}}const[s,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i=await s.recover({account:e.account,entropy:a}),n={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:o.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(y.ON_EMBEDDED_WALLET_RECOVERED,n),n}async signMessage(e,t){await this.validateAndRefreshToken();const r=await this.ensureSigner(),{hashMessage:s=!0,arrayifyMessage:a=!1}=t||{},i=await o.fromStorage(this.storage);return await r.sign(e,a,s,i?.chainType)}async signTypedData(e,t,r){await this.validateAndRefreshToken();const s=await this.ensureSigner(),i=await o.fromStorage(this.storage);if(!i)throw new a(c.MISSING_SIGNER,"No account found");const n={...t};delete n.EIP712Domain;const{_TypedDataEncoder:d}=await import("@ethersproject/hash"),h=d.hash(e,n,r);return await T({hash:h,implementationType:i.implementationType||i.type,chainId:Number(i.chainId),signer:s,address:i.address,ownerAddress:i.ownerAddress,factoryAddress:i.factoryAddress,salt:i.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,r){await this.validateAndRefreshToken();const a=await this.ensureSigner(),n=await d.fromStorage(this.storage);if(!n)throw new s(c.NOT_LOGGED_IN,"missing authentication");let h,m,y,l;if(e.recoveryMethod===g.PASSKEY){const e=await o.fromStorage(this.storage);if(!e)throw new t("missing account");const r=e?.recoveryMethodDetails?.passkeyId;if(!r)throw new t("missing passkey id for account");if(!n.userId)throw new t("User ID is required for passkey key derivation");y={passkeyId:r,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:r,seed:n.userId})}}else if(r.recoveryMethod===g.PASSKEY){if(!n.userId)throw new t("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:n.userId});if(!e.key)throw new t("Passkey creation failed: no key material returned");y={passkeyId:e.id,passkeyKey:e.key},l={passkeyId:e.id}}if(e.recoveryMethod===g.PASSWORD?h=e.password:r.recoveryMethod===g.PASSWORD&&(h=r.password),e.recoveryMethod===g.AUTOMATIC?m=e.encryptionSession:r.recoveryMethod===g.AUTOMATIC&&(m=r.encryptionSession),!h&&!m)throw new t("Password or encryption session is not provided");await a.setRecoveryMethod({recoveryMethod:r.recoveryMethod,recoveryPassword:h,encryptionSession:m,passkeyInfo:y});const p=await o.fromStorage(this.storage);p&&new o({...p,recoveryMethod:r.recoveryMethod,recoveryMethodDetails:l}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await o.fromStorage(this.storage);if(!e)throw new a(c.MISSING_SIGNER,"No signer configured");if(!await d.fromStorage(this.storage))throw new s(c.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:o.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const r={...e},a=n.getInstance();if(!a)throw new t("Configuration not found");const i=await d.fromStorage(this.storage);if(!i)throw new s(c.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),h(async()=>(await this.backendApiClients.accountsV2Api.getAccountsV2(r,{headers:i.thirdPartyProvider?{authorization:`Bearer ${a.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":a.baseConfiguration.publishableKey}})).data.data.map(e=>({chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:o.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await d.fromStorage(this.storage))return f.UNAUTHENTICATED;return await o.fromStorage(this.storage)?f.READY:f.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return u("Failed to get embedded state:",e),f.UNAUTHENTICATED}}watchEmbeddedState(e){return w("watchEmbeddedState",{onChange:e.onChange,onError:e.onError},t=>{let r;const s=async()=>{try{const e=await this.getEmbeddedState();r!==e&&(t.onChange?.(e,r),r=e)}catch(e){t.onError?.(e instanceof Error?e:new Error(String(e)))}};s();const a=()=>s(),i=()=>s(),n=()=>s(),o=()=>s();this.eventEmitter.on(y.ON_AUTH_SUCCESS,a),this.eventEmitter.on(y.ON_LOGOUT,i),this.eventEmitter.on(y.ON_EMBEDDED_WALLET_CREATED,n),this.eventEmitter.on(y.ON_EMBEDDED_WALLET_RECOVERED,o);const d=setInterval(s,e.pollingInterval??2e3);return()=>{clearInterval(d),this.eventEmitter.off(y.ON_AUTH_SUCCESS,a),this.eventEmitter.off(y.ON_LOGOUT,i),this.eventEmitter.off(y.ON_EMBEDDED_WALLET_CREATED,n),this.eventEmitter.off(y.ON_EMBEDDED_WALLET_RECOVERED,o)}})}async getEthereumProvider(e){await this.ensureInitialized();const t={announceProvider:!0,...e},r=await d.fromStorage(this.storage),s=await o.fromStorage(this.storage);return this.provider?this.provider&&t.feeSponsorship&&this.provider.updateFeeSponsorship(t.feeSponsorship):(this.provider=new E({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:r||void 0,backendApiClients:this.backendApiClients,feeSponsorshipId:t.feeSponsorship,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:t.chains}),t.announceProvider&&v({info:{...M,...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 d.fromStorage(this.storage);if(r)try{return await t.getCurrentDevice(r.userId),!0}catch(e){return!1}return t.isLoaded()}catch(e){return u("Ping failed:",e),!1}}getURL(){const e=n.getInstance();if(!e)throw new t("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new t("Invalid message poster");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 handleLogout(){if(this.storage.remove(m.ACCOUNT),"undefined"==typeof document&&!this.messagePoster)return u("Skipping signer disconnect: no messagePoster available in non-browser environment"),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,void(this.signerPromise=null);try{const e=await this.ensureSigner();await e.disconnect()}catch{}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 u("Invalid message received:",e);u("[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 u("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const r=await this.getIframeManager();u(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${r.isLoaded()}`),t&&!r.isLoaded()&&u("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),u("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await r.onMessage(e),u("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{k as EmbeddedWalletApi};
1
+ import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{ConfigurationError as r,AuthenticationError as t,SessionError as s,SignerError as a}from"../core/errors/openfortError.js";import{PasskeyHandler as i}from"../core/passkey/handler.js";import{SDKConfiguration as n}from"../core/config/config.js";import{Account as o}from"../core/configuration/account.js";import{Authentication as d}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as c}from"../core/errors/authErrorCodes.js";import{withApiError as h}from"../core/errors/withApiError.js";import{StorageKeys as m}from"../storage/istorage.js";import{OpenfortEvents as y,RecoveryMethod as g,ChainTypeEnum as l,AccountTypeEnum as p,EmbeddedState as f}from"../types/types.js";import{debugLog as u}from"../utils/debug.js";import{observe as w}from"../utils/observe.js";import{EmbeddedSigner as A}from"../wallets/embedded.js";import{EvmProvider as E}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as v,openfortProviderInfo as M}from"../wallets/evm/provider/eip6963.js";import{signMessage as T}from"../wallets/evm/walletHelpers.js";import{IframeManager as D}from"../wallets/iframeManager.js";import{ReactNativeMessenger as I}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import S from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class k{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,r,t,s,a){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=s,this.passkeyHandler=a,this.eventEmitter.on(y.ON_LOGOUT,()=>{u("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=n.getInstance();if(!t)throw new r("Configuration not found");return new e({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey,nativeAppIdentifier:t.nativeAppIdentifier})}async getIframeManager(){if(u("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(u("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return u("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return u("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;u("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return u("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,u("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw u("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){u("[HANDSHAKE DEBUG] createIframeManager starting");const e=n.getInstance();if(!e)throw u("[HANDSHAKE DEBUG] Configuration not found"),new r("Configuration not found");let t;if(u("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)u("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(u("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new I(this.messagePoster),u("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{u("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new S({remoteWindow:r.contentWindow,allowedOrigins:[s]}),u("[HANDSHAKE DEBUG] Created WindowMessenger")}return u("[HANDSHAKE DEBUG] Creating IframeManager instance"),new D(e,this.storage,t)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(u("IframeManager has failed, clearing signer for recreation"),this.signer=null),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();await e.initialize();return new A(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new r("Document is not available. Please provide a message poster for non-browser environments.");const t=document.getElementById("openfort-iframe");t&&t.remove();const s=document.createElement("iframe");return s.style.display="none",s.id="openfort-iframe",s.referrerPolicy="strict-origin-when-cross-origin",s.src=e,document.body.appendChild(s),s}async getPasskeyKey(e){const r=await d.fromStorage(this.storage);if(!r?.userId)throw new t("auth","User is required for passkey key derivation. Logout and login again.",401);return this.passkeyHandler.deriveAndExportKey({id:e,seed:r.userId})}async getEntropy(e){switch(e.recoveryMethod){case g.PASSWORD:return{recoveryPassword:e.password};case g.AUTOMATIC:return{encryptionSession:e.encryptionSession};case g.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new r("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:g.AUTOMATIC},[t,s]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),a={chainId:e.chainId,entropy:s,accountType:e.accountType??p.SMART_ACCOUNT,chainType:e.chainType??l.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},i=await t.configure(a);return{id:i.id,chainId:i.chainId,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,factoryAddress:i.factoryAddress,salt:i.salt,createdAt:i.createdAt,implementationAddress:i.implementationAddress,recoveryMethod:o.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:g.AUTOMATIC},a=await d.fromStorage(this.storage);if(!a)throw new s(c.NOT_LOGGED_IN,"missing authentication");if(t.recoveryMethod===g.PASSKEY){if(!a.userId)throw new r("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:a.userId});if(!e.key)throw new r("Passkey creation failed: no key material returned");t.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[n,h]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),m=await n.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),l={id:m.id,chainId:m.chainId,address:m.address,ownerAddress:m.ownerAddress,chainType:m.chainType,accountType:m.accountType,implementationType:m.implementationType,factoryAddress:m.factoryAddress,salt:m.salt,createdAt:m.createdAt,implementationAddress:m.implementationAddress,recoveryMethod:o.parseRecoveryMethod(m.recoveryMethod),recoveryMethodDetails:m.recoveryMethodDetails};return this.eventEmitter.emit(y.ON_EMBEDDED_WALLET_CREATED,l),l}async import(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:g.AUTOMATIC},a=await d.fromStorage(this.storage);if(!a)throw new s(c.NOT_LOGGED_IN,"missing authentication");if(t.recoveryMethod===g.PASSKEY){if(!a.userId)throw new r("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:a.userId});if(!e.key)throw new r("Passkey creation failed: no key material returned");t.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[n,h]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),m=await n.import({privateKey:e.privateKey,accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),l={id:m.id,chainId:m.chainId,address:m.address,ownerAddress:m.ownerAddress,chainType:m.chainType,accountType:m.accountType,implementationType:m.implementationType,factoryAddress:m.factoryAddress,salt:m.salt,createdAt:m.createdAt,implementationAddress:m.implementationAddress,recoveryMethod:o.parseRecoveryMethod(m.recoveryMethod),recoveryMethodDetails:m.recoveryMethodDetails};return this.eventEmitter.emit(y.ON_EMBEDDED_WALLET_CREATED,l),l}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:g.AUTOMATIC};if(t.recoveryMethod===g.PASSKEY){if(!t.passkeyInfo?.passkeyId)throw new r("Passkey ID must be provided for passkey recovery");t.passkeyInfo={passkeyId:t.passkeyInfo.passkeyId}}const[s,a]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),i=await s.recover({account:e.account,entropy:a}),n={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:o.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(y.ON_EMBEDDED_WALLET_RECOVERED,n),n}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:s=!0,arrayifyMessage:a=!1}=r||{},i=await o.fromStorage(this.storage);return await t.sign(e,a,s,i?.chainType)}async signTypedData(e,r,t){await this.validateAndRefreshToken();const s=await this.ensureSigner(),i=await o.fromStorage(this.storage);if(!i)throw new a(c.MISSING_SIGNER,"No account found");const n={...r};delete n.EIP712Domain;const{_TypedDataEncoder:d}=await import("@ethersproject/hash"),h=d.hash(e,n,t);return await T({hash:h,implementationType:i.implementationType||i.type,chainId:Number(i.chainId),signer:s,address:i.address,ownerAddress:i.ownerAddress,factoryAddress:i.factoryAddress,salt:i.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,t){await this.validateAndRefreshToken();const a=await this.ensureSigner(),n=await d.fromStorage(this.storage);if(!n)throw new s(c.NOT_LOGGED_IN,"missing authentication");let h,m,y,l;if(e.recoveryMethod===g.PASSKEY){const e=await o.fromStorage(this.storage);if(!e)throw new r("missing account");const t=e?.recoveryMethodDetails?.passkeyId;if(!t)throw new r("missing passkey id for account");if(!n.userId)throw new r("User ID is required for passkey key derivation");y={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:n.userId})}}else if(t.recoveryMethod===g.PASSKEY){if(!n.userId)throw new r("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:n.userId});if(!e.key)throw new r("Passkey creation failed: no key material returned");y={passkeyId:e.id,passkeyKey:e.key},l={passkeyId:e.id}}if(e.recoveryMethod===g.PASSWORD?h=e.password:t.recoveryMethod===g.PASSWORD&&(h=t.password),e.recoveryMethod===g.AUTOMATIC?m=e.encryptionSession:t.recoveryMethod===g.AUTOMATIC&&(m=t.encryptionSession),!h&&!m)throw new r("Password or encryption session is not provided");await a.setRecoveryMethod({recoveryMethod:t.recoveryMethod,recoveryPassword:h,encryptionSession:m,passkeyInfo:y});const p=await o.fromStorage(this.storage);p&&new o({...p,recoveryMethod:t.recoveryMethod,recoveryMethodDetails:l}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await o.fromStorage(this.storage);if(!e)throw new a(c.MISSING_SIGNER,"No signer configured");if(!await d.fromStorage(this.storage))throw new s(c.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:o.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const t={...e},a=n.getInstance();if(!a)throw new r("Configuration not found");const i=await d.fromStorage(this.storage);if(!i)throw new s(c.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),h(async()=>(await this.backendApiClients.accountsV2Api.getAccountsV2(t,{headers:i.thirdPartyProvider?{authorization:`Bearer ${a.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":a.baseConfiguration.publishableKey}})).data.data.map(e=>({chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:o.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await d.fromStorage(this.storage))return f.UNAUTHENTICATED;return await o.fromStorage(this.storage)?f.READY:f.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return u("Failed to get embedded state:",e),f.UNAUTHENTICATED}}watchEmbeddedState(e){return w("watchEmbeddedState",{onChange:e.onChange,onError:e.onError},r=>{let t;const s=async()=>{try{const e=await this.getEmbeddedState();t!==e&&(r.onChange?.(e,t),t=e)}catch(e){r.onError?.(e instanceof Error?e:new Error(String(e)))}};s();const a=()=>s(),i=()=>s(),n=()=>s(),o=()=>s();this.eventEmitter.on(y.ON_AUTH_SUCCESS,a),this.eventEmitter.on(y.ON_LOGOUT,i),this.eventEmitter.on(y.ON_EMBEDDED_WALLET_CREATED,n),this.eventEmitter.on(y.ON_EMBEDDED_WALLET_RECOVERED,o);const d=setInterval(s,e.pollingInterval??2e3);return()=>{clearInterval(d),this.eventEmitter.off(y.ON_AUTH_SUCCESS,a),this.eventEmitter.off(y.ON_LOGOUT,i),this.eventEmitter.off(y.ON_EMBEDDED_WALLET_CREATED,n),this.eventEmitter.off(y.ON_EMBEDDED_WALLET_RECOVERED,o)}})}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await d.fromStorage(this.storage),s=await o.fromStorage(this.storage);return this.provider?this.provider&&r.feeSponsorship&&this.provider.updateFeeSponsorship(r.feeSponsorship):(this.provider=new E({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,feeSponsorshipId:r.feeSponsorship,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&v({info:{...M,...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 d.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return u("Ping failed:",e),!1}}getURL(){const e=n.getInstance();if(!e)throw new r("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new r("Invalid message poster");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 handleLogout(){if(this.storage.remove(m.ACCOUNT),"undefined"==typeof document&&!this.messagePoster)return u("Skipping signer disconnect: no messagePoster available in non-browser environment"),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,void(this.signerPromise=null);try{const e=await this.ensureSigner();await e.disconnect()}catch{}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 u("Invalid message received:",e);u("[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 u("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();u(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&u("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),u("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),u("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{k as EmbeddedWalletApi};
@@ -1 +1 @@
1
- import{AxiosError as e}from"axios";import{VERSION as t,PACKAGE as s}from"../../version.js";const r="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class n{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(t){const s=t.getDsn();if(!s)throw new Error("Sentry DSN is not set");if(s.projectId!==r.split("https://")[1].split("/")[1]||s.host!==r.split("@")[1].split("/")[0]||s.publicKey!==r.split("@")[0].split("https://")[1])throw new Error("Sentry DSN is not valid");t.captureAxiosError=(s,r,o,a)=>{if(r instanceof e){if(400===r.response?.status||401===r.response?.status)return;r.name=s,t.captureException(r,{...o,captureContext:{...o?.captureContext,extra:{errorResponseData:r.response?.data,errorStatus:r.response?.status,errorHeaders:r.response?.headers,errorRequest:r.request},tags:{...n.baseTags,method:s}}})}else t.captureException(r,o,a)},t.captureError=(e,s,r,o)=>{const a=s.statusCode;if(400===a||401===a)return;const c=s,i=c.error,u=c.error_description,p=r?.captureContext;t.captureException(s,{...r,captureContext:{...p,extra:{...p?.extra,errorCode:i,errorDescription:u,errorClass:s.constructor.name,...c.statusCode&&{statusCode:c.statusCode},...c.audience&&{audience:c.audience},...c.scope&&{scope:c.scope},...c.accountId&&{accountId:c.accountId},...c.userId&&{userId:c.userId},...c.provider&&{provider:c.provider},...c.recoveryMethod&&{recoveryMethod:c.recoveryMethod}},tags:{...n.baseTags,context:e,errorClass:s.constructor.name}}})},n.sentryInstance=t}static get sentry(){return n.proxy}static async init({sentry:e,configuration:o}){if(e)return void(n.sentry=e);const a=await import("@sentry/browser");n.sentry=new a.BrowserClient({dsn:r,integrations:[],stackParser:a.defaultStackParser,transport:a.makeFetchTransport}),n.baseTags={projectId:o?.baseConfiguration.publishableKey??"",sdk:s,sdkVersion:t},n.processQueuedCalls()}static proxy=new Proxy({},{get:(e,t)=>n.sentryInstance&&"function"==typeof n.sentryInstance[t]?(...e)=>n.sentryInstance[t](...e):(...e)=>{n.queuedCalls.push({fn:t,args:e})}});static processQueuedCalls(){n.sentryInstance&&(n.queuedCalls.forEach(({fn:e,args:t})=>{"function"==typeof n.sentryInstance[e]&&n.sentryInstance[e](...t)}),n.queuedCalls=[])}}const{sentry:o}=n;export{n as InternalSentry,o as sentry};
1
+ import{AxiosError as e}from"axios";import{PACKAGE as t,VERSION as s}from"../../version.js";const r="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class n{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(t){const s=t.getDsn();if(!s)throw new Error("Sentry DSN is not set");if(s.projectId!==r.split("https://")[1].split("/")[1]||s.host!==r.split("@")[1].split("/")[0]||s.publicKey!==r.split("@")[0].split("https://")[1])throw new Error("Sentry DSN is not valid");t.captureAxiosError=(s,r,o,a)=>{if(r instanceof e){if(400===r.response?.status||401===r.response?.status)return;r.name=s,t.captureException(r,{...o,captureContext:{...o?.captureContext,extra:{errorResponseData:r.response?.data,errorStatus:r.response?.status,errorHeaders:r.response?.headers,errorRequest:r.request},tags:{...n.baseTags,method:s}}})}else t.captureException(r,o,a)},t.captureError=(e,s,r,o)=>{const a=s.statusCode;if(400===a||401===a)return;const c=s,i=c.error,u=c.error_description,p=r?.captureContext;t.captureException(s,{...r,captureContext:{...p,extra:{...p?.extra,errorCode:i,errorDescription:u,errorClass:s.constructor.name,...c.statusCode&&{statusCode:c.statusCode},...c.audience&&{audience:c.audience},...c.scope&&{scope:c.scope},...c.accountId&&{accountId:c.accountId},...c.userId&&{userId:c.userId},...c.provider&&{provider:c.provider},...c.recoveryMethod&&{recoveryMethod:c.recoveryMethod}},tags:{...n.baseTags,context:e,errorClass:s.constructor.name}}})},n.sentryInstance=t}static get sentry(){return n.proxy}static async init({sentry:e,configuration:o}){if(e)return void(n.sentry=e);const a=await import("@sentry/browser");n.sentry=new a.BrowserClient({dsn:r,release:`${t}@${s}`,integrations:[],stackParser:a.defaultStackParser,transport:a.makeFetchTransport}),n.baseTags={projectId:o?.baseConfiguration.publishableKey??"",sdk:t,sdkVersion:s},n.processQueuedCalls()}static proxy=new Proxy({},{get:(e,t)=>n.sentryInstance&&"function"==typeof n.sentryInstance[t]?(...e)=>n.sentryInstance[t](...e):(...e)=>{n.queuedCalls.push({fn:t,args:e})}});static processQueuedCalls(){n.sentryInstance&&(n.queuedCalls.forEach(({fn:e,args:t})=>{"function"==typeof n.sentryInstance[e]&&n.sentryInstance[e](...t)}),n.queuedCalls=[])}}const{sentry:o}=n;export{n as InternalSentry,o as sentry};
@@ -1 +1 @@
1
- import{Openfort as r}from"./core/openfort.js";export{AuthApi}from"./api/auth.js";export{EmbeddedWalletApi}from"./api/embeddedWallet.js";export{ProxyApi}from"./api/proxy.js";export{UserApi}from"./api/user.js";export{OPENFORT_AUTH_ERROR_CODES,OPENFORT_ERROR_CODES}from"./core/errors/authErrorCodes.js";export{AuthenticationError,AuthorizationError,ConfigurationError,OAuthError,OTPError,OpenfortError,RecoveryError,RequestError,SessionError,SignerError,UserError}from"./core/errors/openfortError.js";export{PASSKEY_ERROR_CODES,PasskeyAssertionFailedError,PasskeyCreationFailedError,PasskeyPRFNotSupportedError,PasskeySeedInvalidError,PasskeyUserCancelledError}from"./core/passkey/errors.js";export{PasskeyHandler}from"./core/passkey/handler.js";export{arrayBufferToBase64URL,base64ToArrayBuffer}from"./core/passkey/utils.js";export{OpenfortConfiguration,SDKConfiguration,ShieldConfiguration}from"./core/config/config.js";export{OpenfortInternal}from"./core/openfortInternal.js";export{prepareAndSignAuthorization,serializeSignedAuthorization,signAuthorization}from"./utils/authorization.js";export{IframeSignEmptyResponseError,IframeSignTimeoutError,MissingProjectEntropyError,MissingRecoveryPasswordError,NotConfiguredError,OTPRequiredError,SessionEndedBeforeSetupError,WrongPasskeyError,WrongRecoveryPasswordError}from"./wallets/iframeManager.js";export{AccountTypeEnum,AuthActionRequiredActions,AuthType,BasicAuthProvider,ChainTypeEnum,EmbeddedState,OAuthProvider,OpenfortEvents,RecoveryMethod,ThirdPartyAuthProvider as ThirdPartyOAuthProvider,TokenType}from"./types/types.js";export{cryptoDigest}from"./utils/crypto.js";const o=r.getEventEmitter();export{r as Openfort,o as openfortEvents};
1
+ import{Openfort as r}from"./core/openfort.js";export{AuthApi}from"./api/auth.js";export{EmbeddedWalletApi}from"./api/embeddedWallet.js";export{ProxyApi}from"./api/proxy.js";export{UserApi}from"./api/user.js";export{OPENFORT_AUTH_ERROR_CODES,OPENFORT_ERROR_CODES}from"./core/errors/authErrorCodes.js";export{AuthenticationError,AuthorizationError,ConfigurationError,OAuthError,OTPError,OpenfortError,RecoveryError,RequestError,SessionError,SignerError,UserError}from"./core/errors/openfortError.js";export{PASSKEY_ERROR_CODES,PasskeyAssertionFailedError,PasskeyCreationFailedError,PasskeyPRFNotSupportedError,PasskeySeedInvalidError,PasskeyUserCancelledError}from"./core/passkey/errors.js";export{PasskeyHandler}from"./core/passkey/handler.js";export{arrayBufferToBase64URL,base64ToArrayBuffer}from"./core/passkey/utils.js";export{OpenfortConfiguration,SDKConfiguration,ShieldConfiguration}from"./core/config/config.js";export{OpenfortInternal}from"./core/openfortInternal.js";export{prepareAndSignAuthorization,serializeSignedAuthorization,signAuthorization}from"./utils/authorization.js";export{IframeHandshakeTimeoutError,IframeSignEmptyResponseError,IframeSignTimeoutError,MissingProjectEntropyError,MissingRecoveryPasswordError,NotConfiguredError,OTPRequiredError,SessionEndedBeforeSetupError,WrongPasskeyError,WrongRecoveryPasswordError}from"./wallets/iframeManager.js";export{AccountTypeEnum,AuthActionRequiredActions,AuthType,BasicAuthProvider,ChainTypeEnum,EmbeddedState,OAuthProvider,OpenfortEvents,RecoveryMethod,ThirdPartyAuthProvider as ThirdPartyOAuthProvider,TokenType}from"./types/types.js";export{cryptoDigest}from"./utils/crypto.js";const o=r.getEventEmitter();export{r as Openfort,o as openfortEvents};
@@ -1 +1 @@
1
- const o="1.3.7",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
1
+ const o="1.3.9",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
@@ -1 +1 @@
1
- import{Account as e}from"../core/configuration/account.js";import{Authentication as i}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as t}from"../core/errors/authErrorCodes.js";import{SignerError as n,RecoveryError as r,OpenfortError as s,ConfigurationError as o,SessionError as a}from"../core/errors/openfortError.js";import{sentry as d}from"../core/errors/sentry.js";import{StorageKeys as c}from"../storage/istorage.js";import{randomUUID as h}from"../utils/crypto.js";import{debugLog as u}from"../utils/debug.js";import{ReactNativeMessenger as l}from"./messaging/ReactNativeMessenger.js";import y from"./messaging/browserMessenger/CallOptions.js";import p from"./messaging/browserMessenger/connect.js";import"./messaging/browserMessenger/backwardCompatibility.js";import f from"./messaging/browserMessenger/PenpalError.js";import{isErrorResponse as g,NOT_CONFIGURED_ERROR as m,MISSING_USER_ENTROPY_ERROR as w,MISSING_PROJECT_ENTROPY_ERROR as v,INCORRECT_USER_ENTROPY_ERROR as C,MISSING_PASSKEY_ERROR as I,INCORRECT_PASSKEY_ERROR as k,OTP_REQUIRED_ERROR as P,ShieldAuthType as R,Event as T,SignRequest as b,SwitchChainRequest as E,ExportPrivateKeyRequest as A,SetRecoveryMethodRequest as S,GetCurrentDeviceRequest as N,UpdateAuthenticationRequest as O}from"./types.js";class D extends r{constructor(){super(t.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class U extends r{constructor(){super(t.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class K extends r{constructor(){super(t.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class M extends r{constructor(){super(t.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class z extends n{constructor(){super(t.NOT_CONFIGURED,"Signer is not configured")}}class _ extends s{constructor(){super(t.OTP_REQUIRED,"OTP verification required")}}class L extends n{constructor(e){super(t.INTERNAL_ERROR,`Iframe signer did not respond within ${e}ms. The signing prompt may have been dismissed or the iframe is unresponsive.`),this.name="IframeSignTimeoutError",Object.setPrototypeOf(this,L.prototype)}}class j extends n{constructor(){super(t.INTERNAL_ERROR,"Iframe signer returned an empty signature."),this.name="IframeSignEmptyResponseError",Object.setPrototypeOf(this,j.prototype)}}class F extends s{constructor(){super(t.INTERNAL_ERROR,"Wallet session ended before setup completed."),Object.setPrototypeOf(this,F.prototype)}}class q{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;isDestroyed=!1;hasFailed=!1;constructor(e,i,t){if(!e)throw new o("Configuration is required for IframeManager");if(!i)throw new o("Storage is required for IframeManager");if(!t)throw new o("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=t}assertAlive(){if(this.isDestroyed)throw new F}async initialize(){if(this.assertAlive(),!this.isInitialized){if(this.hasFailed)throw new s(t.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)return await this.initializationPromise,void this.assertAlive();this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.assertAlive(),this.isInitialized=!0}catch(e){if(this.initializationPromise=null,e instanceof F)throw e;throw this.hasFailed=!0,e}}}async doInitialize(){u("Initializing IframeManager connection..."),this.assertAlive(),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:u}),this.connection=p({messenger:this.messenger,timeout:1e4,log:u});try{this.remote=await this.connection.promise,this.assertAlive(),u("IframeManager connection established")}catch(e){this.isDestroyed&&u("Connection rejected after destroy() — surfacing teardown error"),this.assertAlive();const i=e;throw d.captureException(i),this.clearConnection(),u("Failed to establish connection:",i),new s(t.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}\n\n In apps built with:\n - react native\n - swift\n - unity (non-webgl)\n\n You must configure your origin in the openfort dashboard before using the embedded wallet.\n\n For more information, see: https://www.openfort.io/docs/configuration/native-apps\n `)}}clearConnection(){if(this.connection)try{this.connection.destroy()}catch(e){u("clearConnection: connection.destroy() threw, swallowing:",e)}this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new s(t.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(g(e)){if(e.error===m)throw this.storage.remove(c.ACCOUNT),new z;if(e.error===w)throw this.storage.remove(c.ACCOUNT),new D;if(e.error===v)throw this.storage.remove(c.ACCOUNT),new K;if(e.error===C)throw new M;if(e.error===I)throw this.storage.remove(c.ACCOUNT),new D;if(e.error===k)throw new U;if(e.error===P)throw new _;throw this.storage.remove(c.ACCOUNT),new s(t.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(t.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:R.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(t.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:R.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),t=await this.buildIFrameRequestConfiguration();t.chainId=e.chainId??null,t.password=e?.entropy?.recoveryPassword??null,t.recovery={...t.recovery,encryptionSession:e?.entropy?.encryptionSession},t.passkey=e?.entropy?.passkey??null;const n={uuid:h(),action:T.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,encryptionSession:t.recovery?.encryptionSession??null,passkey:t.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},r=await i.create(n);return g(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r}async import(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),t=await this.buildIFrameRequestConfiguration();t.chainId=e.chainId??null,t.password=e?.entropy?.recoveryPassword??null,t.recovery={...t.recovery,encryptionSession:e?.entropy?.encryptionSession},t.passkey=e?.entropy?.passkey??null;const n={uuid:h(),action:T.IMPORT,privateKey:e.privateKey,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,encryptionSession:t.recovery?.encryptionSession??null,passkey:t.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},r=await i.import(n);return g(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},r.passkey=i?.entropy?.passkey??null;const s={uuid:h(),action:T.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,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},o=await n.recover(s);return g(o)&&this.handleError(o),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",o.version??"undefined"),o}async sign(e,i,t,n){u("[iframe] ensureConnection");const r=await this.ensureConnection(),s=new b(h(),e,await this.buildRequestConfiguration(),i,t,n);let o;u("[iframe] done ensureConnection"),this.assertAlive();try{o=await r.sign(s,new y({timeout:9e4}))}catch(e){if(e instanceof f&&"METHOD_CALL_TIMEOUT"===e.code)throw this.hasFailed=!0,new L(9e4);throw e}if(u("[iframe] response",o),g(o)&&this.handleError(o),!o.signature)throw new j;return"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",o.version??"undefined"),o.signature}async switchChain(e){const i=await this.ensureConnection(),t=new E(h(),e,await this.buildRequestConfiguration()),n=await i.switchChain(t);return g(n)&&this.handleError(n),n}async export(){const e=await this.ensureConnection(),i=new A(h(),await this.buildRequestConfiguration()),t=await e.export(i);return g(t)&&this.handleError(t),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",t.version??"undefined"),t.key}async setRecoveryMethod(e,i,t,n,r){const s=await this.ensureConnection(),o=new S(h(),e,await this.buildRequestConfiguration(),i,t,n,r),a=await s.setRecoveryMethod(o);g(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),t=new N(h(),e);try{const e=await i.getCurrentDevice(t);return g(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof z)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void u("IframeManager not loaded, skipping authentication update");const e=await i.fromStorage(this.storage);if(!e)return void u("No authentication found, skipping update");const t=new O(h(),e.token);u("Updating authentication in iframe with token");const n=await this.remote.updateAuthentication(t);g(n)&&this.handleError(n)}async disconnect(){const e=await this.ensureConnection(),i={uuid:h()};await e.logout(i)}async onMessage(e){u("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof l?(this.isInitialized||this.connection?u(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(u("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{u("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),u("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):u("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.clearConnection())}}export{q as IframeManager,j as IframeSignEmptyResponseError,L as IframeSignTimeoutError,K as MissingProjectEntropyError,D as MissingRecoveryPasswordError,z as NotConfiguredError,_ as OTPRequiredError,F as SessionEndedBeforeSetupError,U as WrongPasskeyError,M as WrongRecoveryPasswordError};
1
+ import{Account as e}from"../core/configuration/account.js";import{Authentication as i}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as t}from"../core/errors/authErrorCodes.js";import{OpenfortError as n,SignerError as r,RecoveryError as o,ConfigurationError as s,SessionError as a}from"../core/errors/openfortError.js";import{sentry as d}from"../core/errors/sentry.js";import{StorageKeys as c}from"../storage/istorage.js";import{randomUUID as h}from"../utils/crypto.js";import{debugLog as u}from"../utils/debug.js";import{ReactNativeMessenger as l}from"./messaging/ReactNativeMessenger.js";import p from"./messaging/browserMessenger/CallOptions.js";import y from"./messaging/browserMessenger/connect.js";import"./messaging/browserMessenger/backwardCompatibility.js";import f from"./messaging/browserMessenger/PenpalError.js";import{isErrorResponse as g,NOT_CONFIGURED_ERROR as m,MISSING_USER_ENTROPY_ERROR as w,MISSING_PROJECT_ENTROPY_ERROR as v,INCORRECT_USER_ENTROPY_ERROR as C,MISSING_PASSKEY_ERROR as I,INCORRECT_PASSKEY_ERROR as k,OTP_REQUIRED_ERROR as b,ShieldAuthType as T,Event as R,SignRequest as P,SwitchChainRequest as E,ExportPrivateKeyRequest as A,SetRecoveryMethodRequest as S,GetCurrentDeviceRequest as N,UpdateAuthenticationRequest as O}from"./types.js";class D extends o{constructor(){super(t.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class U extends o{constructor(){super(t.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class K extends o{constructor(){super(t.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class M extends o{constructor(){super(t.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class z extends r{constructor(){super(t.NOT_CONFIGURED,"Signer is not configured")}}class _ extends n{constructor(){super(t.OTP_REQUIRED,"OTP verification required")}}class L extends r{constructor(e){super(t.INTERNAL_ERROR,`Iframe signer did not respond within ${e}ms. The signing prompt may have been dismissed or the iframe is unresponsive.`),this.name="IframeSignTimeoutError",Object.setPrototypeOf(this,L.prototype)}}class j extends r{constructor(){super(t.INTERNAL_ERROR,"Iframe signer returned an empty signature."),this.name="IframeSignEmptyResponseError",Object.setPrototypeOf(this,j.prototype)}}class F extends n{constructor(){super(t.INTERNAL_ERROR,"Wallet session ended before setup completed."),Object.setPrototypeOf(this,F.prototype)}}class q extends n{constructor(e,i){super(t.INTERNAL_ERROR,`Failed to establish iframe connection within ${e}ms. The embedded wallet page did not respond — it may be unreachable or blocked by CSP/network.`),this.name="IframeHandshakeTimeoutError",this.cause=i,Object.setPrototypeOf(this,q.prototype)}}class x{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;isDestroyed=!1;hasFailed=!1;constructor(e,i,t){if(!e)throw new s("Configuration is required for IframeManager");if(!i)throw new s("Storage is required for IframeManager");if(!t)throw new s("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=t}assertAlive(){if(this.isDestroyed)throw new F}async initialize(){if(this.assertAlive(),!this.isInitialized){if(this.hasFailed)throw new n(t.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)return await this.initializationPromise,void this.assertAlive();this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.assertAlive(),this.isInitialized=!0}catch(e){if(this.initializationPromise=null,e instanceof F)throw e;throw this.hasFailed=!0,e}}}async doInitialize(){u("Initializing IframeManager connection..."),this.assertAlive(),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:u}),this.connection=y({messenger:this.messenger,timeout:1e4,log:u});try{this.remote=await this.connection.promise,this.assertAlive(),u("IframeManager connection established")}catch(e){if(this.isDestroyed&&u("Connection rejected after destroy() — surfacing teardown error"),this.assertAlive(),d.captureException(e),this.clearConnection(),u("Failed to establish connection:",e),e instanceof f&&"CONNECTION_TIMEOUT"===e.code)throw new q(1e4,e);const i=e;throw new n(t.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}\n\n In apps built with:\n - react native\n - swift\n - unity (non-webgl)\n\n You must configure your origin in the openfort dashboard before using the embedded wallet.\n\n For more information, see: https://www.openfort.io/docs/configuration/native-apps\n `)}}clearConnection(){if(this.connection)try{this.connection.destroy()}catch(e){u("clearConnection: connection.destroy() threw, swallowing:",e)}this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new n(t.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(g(e)){if(e.error===m)throw this.storage.remove(c.ACCOUNT),new z;if(e.error===w)throw this.storage.remove(c.ACCOUNT),new D;if(e.error===v)throw this.storage.remove(c.ACCOUNT),new K;if(e.error===C)throw new M;if(e.error===I)throw this.storage.remove(c.ACCOUNT),new D;if(e.error===k)throw new U;if(e.error===b)throw new _;throw this.storage.remove(c.ACCOUNT),new n(t.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(t.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:T.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(t.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:T.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),t=await this.buildIFrameRequestConfiguration();t.chainId=e.chainId??null,t.password=e?.entropy?.recoveryPassword??null,t.recovery={...t.recovery,encryptionSession:e?.entropy?.encryptionSession},t.passkey=e?.entropy?.passkey??null;const n={uuid:h(),action:R.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,encryptionSession:t.recovery?.encryptionSession??null,passkey:t.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},r=await i.create(n);return g(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r}async import(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),t=await this.buildIFrameRequestConfiguration();t.chainId=e.chainId??null,t.password=e?.entropy?.recoveryPassword??null,t.recovery={...t.recovery,encryptionSession:e?.entropy?.encryptionSession},t.passkey=e?.entropy?.passkey??null;const n={uuid:h(),action:R.IMPORT,privateKey:e.privateKey,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,encryptionSession:t.recovery?.encryptionSession??null,passkey:t.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},r=await i.import(n);return g(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},r.passkey=i?.entropy?.passkey??null;const o={uuid:h(),action:R.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,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},s=await n.recover(o);return g(s)&&this.handleError(s),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",s.version??"undefined"),s}async sign(e,i,t,n){u("[iframe] ensureConnection");const r=await this.ensureConnection(),o=new P(h(),e,await this.buildRequestConfiguration(),i,t,n);let s;u("[iframe] done ensureConnection"),this.assertAlive();try{s=await r.sign(o,new p({timeout:9e4}))}catch(e){if(e instanceof f&&"METHOD_CALL_TIMEOUT"===e.code)throw this.hasFailed=!0,new L(9e4);throw e}if(u("[iframe] response",s),g(s)&&this.handleError(s),!s.signature)throw new j;return"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",s.version??"undefined"),s.signature}async switchChain(e){const i=await this.ensureConnection(),t=new E(h(),e,await this.buildRequestConfiguration()),n=await i.switchChain(t);return g(n)&&this.handleError(n),n}async export(){const e=await this.ensureConnection(),i=new A(h(),await this.buildRequestConfiguration()),t=await e.export(i);return g(t)&&this.handleError(t),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",t.version??"undefined"),t.key}async setRecoveryMethod(e,i,t,n,r){const o=await this.ensureConnection(),s=new S(h(),e,await this.buildRequestConfiguration(),i,t,n,r),a=await o.setRecoveryMethod(s);g(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),t=new N(h(),e);try{const e=await i.getCurrentDevice(t);return g(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof z)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void u("IframeManager not loaded, skipping authentication update");const e=await i.fromStorage(this.storage);if(!e)return void u("No authentication found, skipping update");const t=new O(h(),e.token);u("Updating authentication in iframe with token");const n=await this.remote.updateAuthentication(t);g(n)&&this.handleError(n)}async disconnect(){const e=await this.ensureConnection(),i={uuid:h()};await e.logout(i)}async onMessage(e){u("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof l?(this.isInitialized||this.connection?u(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(u("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{u("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),u("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):u("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.clearConnection())}}export{q as IframeHandshakeTimeoutError,x as IframeManager,j as IframeSignEmptyResponseError,L as IframeSignTimeoutError,K as MissingProjectEntropyError,D as MissingRecoveryPasswordError,z as NotConfiguredError,_ as OTPRequiredError,F as SessionEndedBeforeSetupError,U as WrongPasskeyError,M as WrongRecoveryPasswordError};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfort/openfort-js",
3
- "version": "1.3.7",
3
+ "version": "1.3.9",
4
4
  "author": "Openfort (https://www.openfort.io)",
5
5
  "bugs": "https://github.com/openfort-xyz/openfort-js/issues",
6
6
  "repository": "openfort-xyz/openfort-js.git",