@openfort/openfort-js 1.1.6 → 1.2.0

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"),a=require("../core/config/config.cjs"),s=require("../core/configuration/account.cjs"),i=require("../core/configuration/authentication.cjs"),n=require("../core/errors/authErrorCodes.cjs"),o=require("../core/errors/withApiError.cjs"),d=require("../types/types.cjs"),c=require("../utils/debug.cjs"),g=require("../wallets/embedded.cjs"),h=require("../wallets/evm/evmProvider.cjs");require("../wallets/evm/types.cjs");var u=require("../wallets/evm/provider/eip6963.cjs"),y=require("../wallets/evm/walletHelpers.cjs"),l=require("../wallets/iframeManager.cjs"),m=require("../wallets/messaging/ReactNativeMessenger.cjs");require("../wallets/messaging/browserMessenger/backwardCompatibility.cjs");var f=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,a,s){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=a,this.passkeyHandler=s,this.eventEmitter.on(d.OpenfortEvents.ON_LOGOUT,()=>{c.debugLog("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=a.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(c.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager&&this.iframeManager.hasFailed&&(c.debugLog("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;c.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return c.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,c.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw c.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){c.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=a.SDKConfiguration.getInstance();if(!e)throw c.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new r.ConfigurationError("Configuration not found");let t;if(c.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)c.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(c.debugLog("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new m.ReactNativeMessenger(this.messagePoster),c.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{c.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),a=new URL(e.iframeUrl).origin;t=new f({remoteWindow:r.contentWindow,allowedOrigins:[a]}),c.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return c.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new l.IframeManager(e,this.storage,t)}async ensureSigner(){if(this.iframeManager&&this.iframeManager.hasFailed&&(c.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 g.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 a=document.createElement("iframe");return a.style.display="none",a.id="openfort-iframe",a.src=e,document.body.appendChild(a),a}async getPasskeyKey(e){const t=await i.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 d.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case d.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};case d.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:d.RecoveryMethod.AUTOMATIC},[t,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i={chainId:e.chainId,entropy:a,accountType:e.accountType??d.AccountTypeEnum.SMART_ACCOUNT,chainType:e.chainType??d.ChainTypeEnum.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},n=await t.configure(i);return{id:n.id,chainId:n.chainId,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType,factoryAddress:n.factoryAddress,salt:n.salt,createdAt:n.createdAt,implementationAddress:n.implementationAddress,recoveryMethod:s.Account.parseRecoveryMethod(n.recoveryMethod),recoveryMethodDetails:n.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const o=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC},c=await i.Authentication.fromStorage(this.storage);if(!c)throw new r.SessionError(n.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(o.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!c.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),displayName:a.SDKConfiguration.getInstance()?.passkeyDisplayName??"Openfort - Embedded Wallet",seed:c.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");o.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[g,h]=await Promise.all([this.ensureSigner(),this.getEntropy(o)]),u=await g.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),y={id:u.id,chainId:u.chainId,address:u.address,ownerAddress:u.ownerAddress,chainType:u.chainType,accountType:u.accountType,implementationType:u.implementationType,factoryAddress:u.factoryAddress,salt:u.salt,createdAt:u.createdAt,implementationAddress:u.implementationAddress,recoveryMethod:s.Account.parseRecoveryMethod(u.recoveryMethod),recoveryMethodDetails:u.recoveryMethodDetails};return this.eventEmitter.emit(d.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,y),y}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC};if(t.recoveryMethod===d.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[a,i]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),n=await a.recover({account:e.account,entropy:i}),o={id:n.id,chainId:n.chainId,implementationAddress:n.implementationAddress,factoryAddress:n.factoryAddress,salt:n.salt,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType,createdAt:n.createdAt,recoveryMethod:s.Account.parseRecoveryMethod(n.recoveryMethod),recoveryMethodDetails:n.recoveryMethodDetails};return this.eventEmitter.emit(d.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o),o}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:a=!0,arrayifyMessage:i=!1}=r||{},n=await s.Account.fromStorage(this.storage);return await t.sign(e,i,a,n?.chainType)}async signTypedData(e,t,a){await this.validateAndRefreshToken();const i=await this.ensureSigner(),o=await s.Account.fromStorage(this.storage);if(!o)throw new r.SignerError(n.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No account found");const d={...t};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),g=c.hash(e,d,a);return await y.signMessage({hash:g,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:i,address:o.address,ownerAddress:o.ownerAddress,factoryAddress:o.factoryAddress,salt:o.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,o){await this.validateAndRefreshToken();const c=await this.ensureSigner(),g=await i.Authentication.fromStorage(this.storage);if(!g)throw new r.SessionError(n.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");let h,u,y,l;if(e.recoveryMethod===d.RecoveryMethod.PASSKEY){const e=await s.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(!g.userId)throw new r.ConfigurationError("User ID is required for passkey key derivation");y={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:g.userId})}}else if(o.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!g.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),displayName:a.SDKConfiguration.getInstance()?.passkeyDisplayName??"Openfort - Embedded Wallet",seed:g.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");y={passkeyId:e.id,passkeyKey:e.key},l={passkeyId:e.id}}if(e.recoveryMethod===d.RecoveryMethod.PASSWORD?h=e.password:o.recoveryMethod===d.RecoveryMethod.PASSWORD&&(h=o.password),e.recoveryMethod===d.RecoveryMethod.AUTOMATIC?u=e.encryptionSession:o.recoveryMethod===d.RecoveryMethod.AUTOMATIC&&(u=o.encryptionSession),!h&&!u)throw new r.ConfigurationError("Password or encryption session is not provided");await c.setRecoveryMethod({recoveryMethod:o.recoveryMethod,recoveryPassword:h,encryptionSession:u,passkeyInfo:y});const m=await s.Account.fromStorage(this.storage);m&&new s.Account({...m,recoveryMethod:o.recoveryMethod,recoveryMethodDetails:l}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await s.Account.fromStorage(this.storage);if(!e)throw new r.SignerError(n.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No signer configured");if(!await i.Authentication.fromStorage(this.storage))throw new r.SessionError(n.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:s.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const t={accountType:d.AccountTypeEnum.SMART_ACCOUNT,...e},c=a.SDKConfiguration.getInstance();if(!c)throw new r.ConfigurationError("Configuration not found");const g=await i.Authentication.fromStorage(this.storage);if(!g)throw new r.SessionError(n.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:g.thirdPartyProvider?{authorization:`Bearer ${c.baseConfiguration.publishableKey}`,"x-player-token":g.token,"x-auth-provider":g.thirdPartyProvider,"x-token-type":g.thirdPartyTokenType}:{authorization:`Bearer ${g.token}`,"x-project-key":c.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:s.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await i.Authentication.fromStorage(this.storage))return d.EmbeddedState.UNAUTHENTICATED;return await s.Account.fromStorage(this.storage)?d.EmbeddedState.READY:d.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return c.debugLog("Failed to get embedded state:",e),d.EmbeddedState.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await i.Authentication.fromStorage(this.storage),a=await s.Account.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new h.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:a||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&u.announceProvider({info:{...u.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 i.Authentication.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return c.debugLog("Ping failed:",e),!1}}getURL(){const e=a.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("undefined"==typeof document&&!this.messagePoster)return c.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);const e=await this.ensureSigner();await e.disconnect(),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void c.debugLog("Invalid message received:",e);c.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 c.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();c.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&c.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),c.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),c.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"),i=require("../core/configuration/authentication.cjs"),n=require("../core/errors/authErrorCodes.cjs"),o=require("../core/errors/withApiError.cjs"),d=require("../types/types.cjs"),c=require("../utils/debug.cjs"),g=require("../wallets/embedded.cjs"),h=require("../wallets/evm/evmProvider.cjs");require("../wallets/evm/types.cjs");var u=require("../wallets/evm/provider/eip6963.cjs"),y=require("../wallets/evm/walletHelpers.cjs"),l=require("../wallets/iframeManager.cjs"),m=require("../wallets/messaging/ReactNativeMessenger.cjs");require("../wallets/messaging/browserMessenger/backwardCompatibility.cjs");var f=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(d.OpenfortEvents.ON_LOGOUT,()=>{c.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(c.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(c.debugLog("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;c.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return c.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,c.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw c.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){c.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=s.SDKConfiguration.getInstance();if(!e)throw c.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new r.ConfigurationError("Configuration not found");let t;if(c.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)c.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(c.debugLog("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new m.ReactNativeMessenger(this.messagePoster),c.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{c.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new f({remoteWindow:r.contentWindow,allowedOrigins:[s]}),c.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return c.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new l.IframeManager(e,this.storage,t)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(c.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 g.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 i.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 d.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case d.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};case d.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:d.RecoveryMethod.AUTOMATIC},[t,s]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i={chainId:e.chainId,entropy:s,accountType:e.accountType??d.AccountTypeEnum.SMART_ACCOUNT,chainType:e.chainType??d.ChainTypeEnum.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},n=await t.configure(i);return{id:n.id,chainId:n.chainId,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType,factoryAddress:n.factoryAddress,salt:n.salt,createdAt:n.createdAt,implementationAddress:n.implementationAddress,recoveryMethod:a.Account.parseRecoveryMethod(n.recoveryMethod),recoveryMethodDetails:n.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const s=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC},o=await i.Authentication.fromStorage(this.storage);if(!o)throw new r.SessionError(n.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(s.recoveryMethod===d.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[c,g]=await Promise.all([this.ensureSigner(),this.getEntropy(s)]),h=await c.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:g}),u={id:h.id,chainId:h.chainId,address:h.address,ownerAddress:h.ownerAddress,chainType:h.chainType,accountType:h.accountType,implementationType:h.implementationType,factoryAddress:h.factoryAddress,salt:h.salt,createdAt:h.createdAt,implementationAddress:h.implementationAddress,recoveryMethod:a.Account.parseRecoveryMethod(h.recoveryMethod),recoveryMethodDetails:h.recoveryMethodDetails};return this.eventEmitter.emit(d.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,u),u}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC};if(t.recoveryMethod===d.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,i]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),n=await s.recover({account:e.account,entropy:i}),o={id:n.id,chainId:n.chainId,implementationAddress:n.implementationAddress,factoryAddress:n.factoryAddress,salt:n.salt,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType,createdAt:n.createdAt,recoveryMethod:a.Account.parseRecoveryMethod(n.recoveryMethod),recoveryMethodDetails:n.recoveryMethodDetails};return this.eventEmitter.emit(d.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o),o}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:s=!0,arrayifyMessage:i=!1}=r||{},n=await a.Account.fromStorage(this.storage);return await t.sign(e,i,s,n?.chainType)}async signTypedData(e,t,s){await this.validateAndRefreshToken();const i=await this.ensureSigner(),o=await a.Account.fromStorage(this.storage);if(!o)throw new r.SignerError(n.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No account found");const d={...t};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),g=c.hash(e,d,s);return await y.signMessage({hash:g,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:i,address:o.address,ownerAddress:o.ownerAddress,factoryAddress:o.factoryAddress,salt:o.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,s){await this.validateAndRefreshToken();const o=await this.ensureSigner(),c=await i.Authentication.fromStorage(this.storage);if(!c)throw new r.SessionError(n.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");let g,h,u,y;if(e.recoveryMethod===d.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(!c.userId)throw new r.ConfigurationError("User ID is required for passkey key derivation");u={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:c.userId})}}else if(s.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!c.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:c.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");u={passkeyId:e.id,passkeyKey:e.key},y={passkeyId:e.id}}if(e.recoveryMethod===d.RecoveryMethod.PASSWORD?g=e.password:s.recoveryMethod===d.RecoveryMethod.PASSWORD&&(g=s.password),e.recoveryMethod===d.RecoveryMethod.AUTOMATIC?h=e.encryptionSession:s.recoveryMethod===d.RecoveryMethod.AUTOMATIC&&(h=s.encryptionSession),!g&&!h)throw new r.ConfigurationError("Password or encryption session is not provided");await o.setRecoveryMethod({recoveryMethod:s.recoveryMethod,recoveryPassword:g,encryptionSession:h,passkeyInfo:u});const l=await a.Account.fromStorage(this.storage);l&&new a.Account({...l,recoveryMethod:s.recoveryMethod,recoveryMethodDetails:y}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await a.Account.fromStorage(this.storage);if(!e)throw new r.SignerError(n.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No signer configured");if(!await i.Authentication.fromStorage(this.storage))throw new r.SessionError(n.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 i.Authentication.fromStorage(this.storage);if(!c)throw new r.SessionError(n.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 i.Authentication.fromStorage(this.storage))return d.EmbeddedState.UNAUTHENTICATED;return await a.Account.fromStorage(this.storage)?d.EmbeddedState.READY:d.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return c.debugLog("Failed to get embedded state:",e),d.EmbeddedState.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await i.Authentication.fromStorage(this.storage),s=await a.Account.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new h.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&u.announceProvider({info:{...u.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 i.Authentication.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return c.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("undefined"==typeof document&&!this.messagePoster)return c.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 c.debugLog("Invalid message received:",e);c.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 c.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();c.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&c.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),c.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),c.debugLog("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}};
@@ -1 +1 @@
1
- "use strict";var e=require("../../utils/crypto.cjs");class s{baseConfiguration;shieldConfiguration;thirdPartyAuth;shieldUrl;iframeUrl;backendUrl;storage;passkeyRpId;passkeyRpName;passkeyDisplayName;nativeAppIdentifier;debug;static instance=null;constructor({baseConfiguration:i,shieldConfiguration:t,overrides:a,thirdPartyAuth:r,debug:p}){this.shieldConfiguration=t,this.baseConfiguration=i,this.backendUrl=a?.backendUrl||"https://api.openfort.io",this.iframeUrl=a?.iframeUrl||"https://embed.openfort.io",this.iframeUrl=`${this.iframeUrl}/iframe/${this.baseConfiguration.publishableKey}`,this.debug=p,t?.debug&&(this.iframeUrl=`${this.iframeUrl}?debug=true`),this.shieldUrl=a?.shieldUrl||"https://shield.openfort.io",this.storage=a?.storage,this.thirdPartyAuth=r,this.passkeyRpId=t?.passkeyRpId,this.passkeyRpName=t?.passkeyRpName,this.passkeyDisplayName=t?.passkeyDisplayName,this.nativeAppIdentifier=i.nativeAppIdentifier,a?.crypto?.digest&&e.setCryptoDigestOverride(a.crypto.digest),s.instance=this}static getInstance(){return s.instance}}exports.OpenfortConfiguration=class{publishableKey;nativeAppIdentifier;constructor(e){this.publishableKey=e.publishableKey,this.nativeAppIdentifier=e.nativeAppIdentifier}},exports.SDKConfiguration=s,exports.ShieldConfiguration=class{shieldPublishableKey;shieldEncryptionKey;debug=!1;passkeyRpId;passkeyRpName;passkeyDisplayName;constructor(e){this.shieldPublishableKey=e.shieldPublishableKey,this.debug=e.shieldDebug||!1,this.passkeyRpId=e.passkeyRpId,this.passkeyRpName=e.passkeyRpName,this.passkeyDisplayName=e.passkeyDisplayName}};
1
+ "use strict";var e=require("../../utils/crypto.cjs");class i{baseConfiguration;shieldConfiguration;thirdPartyAuth;shieldUrl;iframeUrl;backendUrl;storage;nativeAppIdentifier;debug;static instance=null;constructor({baseConfiguration:s,shieldConfiguration:t,overrides:r,thirdPartyAuth:a,debug:n}){this.shieldConfiguration=t,this.baseConfiguration=s,this.backendUrl=r?.backendUrl||"https://api.openfort.io",this.iframeUrl=r?.iframeUrl||"https://embed.openfort.io",this.iframeUrl=`${this.iframeUrl}/iframe/${this.baseConfiguration.publishableKey}`,this.debug=n,t?.debug&&(this.iframeUrl=`${this.iframeUrl}?debug=true`),this.shieldUrl=r?.shieldUrl||"https://shield.openfort.io",this.storage=r?.storage,this.thirdPartyAuth=a,this.nativeAppIdentifier=s.nativeAppIdentifier,r?.crypto?.digest&&e.setCryptoDigestOverride(r.crypto.digest),i.instance=this}static getInstance(){return i.instance}}exports.OpenfortConfiguration=class{publishableKey;nativeAppIdentifier;constructor(e){this.publishableKey=e.publishableKey,this.nativeAppIdentifier=e.nativeAppIdentifier}},exports.SDKConfiguration=i,exports.ShieldConfiguration=class{shieldPublishableKey;debug=!1;passkeyRpId;passkeyRpName;passkeyDisplayName;constructor(e){this.shieldPublishableKey=e.shieldPublishableKey,this.debug=e.shieldDebug||!1,this.passkeyRpId=e.passkeyRpId,this.passkeyRpName=e.passkeyRpName,this.passkeyDisplayName=e.passkeyDisplayName}};
@@ -1 +1 @@
1
- "use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.cjs"),t=require("../api/auth.cjs"),i=require("../api/embeddedWallet.cjs"),n=require("../api/proxy.cjs"),a=require("../api/user.cjs"),r=require("../auth/authManager.cjs"),s=require("../storage/istorage.cjs"),o=require("../storage/lazyStorage.cjs"),h=require("../utils/typedEventEmitter.cjs"),l=require("./config/config.cjs"),c=require("./errors/authErrorCodes.cjs"),u=require("./errors/openfortError.cjs"),d=require("./errors/sentry.cjs"),g=require("./openfortInternal.cjs"),f=require("./passkey/handler.cjs");class p{storage;iAuthManager=null;openfortInternal;initPromise;asyncInitPromise=null;authInstance;embeddedWalletInstance;userInstance;proxyInstance;configuration;eventEmitter;iPasskeyHandler;static globalEventEmitter=null;get auth(){if(!this.authInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.");return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.");return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.");return this.userInstance}get proxy(){if(!this.proxyInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.");return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new r.AuthManager,this.openfortInternal=new g.OpenfortInternal(this.storage,this.authManager,this.eventEmitter),this.authInstance=new t.AuthApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter),this.embeddedWalletInstance=new i.EmbeddedWalletApi(this.storage,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter,this.passkeyHandler),this.userInstance=new a.UserApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this)),this.proxyInstance=new n.ProxyApi(this.storage,this.backendApiClients,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),async()=>{if(!this.embeddedWalletInstance)throw new u.SignerError(c.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"Embedded wallet not initialized");const e=this.embeddedWalletInstance;return t=>e.signMessage(t,{hashMessage:!0,arrayifyMessage:!0})})}catch(e){throw new u.ConfigurationError("Openfort SDK synchronous initialization failed")}}constructor(e){if(this.configuration=new l.SDKConfiguration(e),this.storage=new o.LazyStorage(this.configuration.baseConfiguration.publishableKey,this.configuration.storage),this.eventEmitter=new h,p.globalEventEmitter){["onAuthInit","onAuthSuccess","onAuthFailure","onLogout","onSwitchAccount","onSignedMessage","onEmbeddedWalletCreated","onEmbeddedWalletRecovered","onAuthFlowOpen","onAuthFlowClose","onAuthFlowCancel"].forEach(e=>{this.eventEmitter.on(e,(...t)=>{p.globalEventEmitter?.emit(e,...t)})})}else p.globalEventEmitter=this.eventEmitter;this.iPasskeyHandler=e.overrides?.passkeyHandler??new f.PasskeyHandler({rpId:this.configuration.passkeyRpId,rpName:this.configuration.passkeyRpName}),d.InternalSentry.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}static getEventEmitter(){return p.globalEventEmitter||(p.globalEventEmitter=new h),p.globalEventEmitter}async waitForInitialization(){await this.initPromise,await this.ensureAsyncInitialized()}async getAccessToken(){return await this.ensureInitialized(),this.openfortInternal.getAccessToken()}async validateAndRefreshToken(e){return await this.ensureInitialized(),await this.openfortInternal.validateAndRefreshToken(e)}get backendApiClients(){return new e.BackendApiClients({basePath:this.configuration.backendUrl,accessToken:this.configuration.baseConfiguration.publishableKey,nativeAppIdentifier:this.configuration.nativeAppIdentifier,storage:this.storage,onLogout:()=>{this.eventEmitter.emit("onLogout")}})}get authManager(){if(!this.iAuthManager)throw new u.RequestError("AuthManager not initialized");return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(e){try{const t=s.StorageKeys.TEST,i="openfort_storage_test";e.save(t,i);const n=await e.get(t);return e.remove(t),n===i}catch(e){return!1}}async initializeAsync(){if(!await p.isStorageAccessible(this.storage))throw new u.OpenfortError("Storage is not accessible",c.OPENFORT_ERROR_CODES.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}exports.Openfort=p;
1
+ "use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.cjs"),t=require("../api/auth.cjs"),i=require("../api/embeddedWallet.cjs"),n=require("../api/proxy.cjs"),a=require("../api/user.cjs"),s=require("../auth/authManager.cjs"),r=require("../storage/istorage.cjs"),o=require("../storage/lazyStorage.cjs"),h=require("../utils/typedEventEmitter.cjs"),l=require("./config/config.cjs"),c=require("./errors/authErrorCodes.cjs"),u=require("./errors/openfortError.cjs"),d=require("./errors/sentry.cjs"),g=require("./openfortInternal.cjs"),f=require("./passkey/handler.cjs");class p{storage;iAuthManager=null;openfortInternal;initPromise;asyncInitPromise=null;authInstance;embeddedWalletInstance;userInstance;proxyInstance;configuration;eventEmitter;iPasskeyHandler;static globalEventEmitter=null;get auth(){if(!this.authInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.");return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.");return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.");return this.userInstance}get proxy(){if(!this.proxyInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.");return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new s.AuthManager,this.openfortInternal=new g.OpenfortInternal(this.storage,this.authManager,this.eventEmitter),this.authInstance=new t.AuthApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter),this.embeddedWalletInstance=new i.EmbeddedWalletApi(this.storage,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter,this.passkeyHandler),this.userInstance=new a.UserApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this)),this.proxyInstance=new n.ProxyApi(this.storage,this.backendApiClients,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),async()=>{if(!this.embeddedWalletInstance)throw new u.SignerError(c.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"Embedded wallet not initialized");const e=this.embeddedWalletInstance;return t=>e.signMessage(t,{hashMessage:!0,arrayifyMessage:!0})})}catch(e){throw new u.ConfigurationError("Openfort SDK synchronous initialization failed")}}constructor(e){if(this.configuration=new l.SDKConfiguration(e),this.storage=new o.LazyStorage(this.configuration.baseConfiguration.publishableKey,this.configuration.storage),this.eventEmitter=new h,p.globalEventEmitter){["onAuthInit","onAuthSuccess","onAuthFailure","onLogout","onSwitchAccount","onSignedMessage","onEmbeddedWalletCreated","onEmbeddedWalletRecovered","onAuthFlowOpen","onAuthFlowClose","onAuthFlowCancel"].forEach(e=>{this.eventEmitter.on(e,(...t)=>{p.globalEventEmitter?.emit(e,...t)})})}else p.globalEventEmitter=this.eventEmitter;this.iPasskeyHandler=e.overrides?.passkeyHandler??new f.PasskeyHandler({rpId:e.shieldConfiguration?.passkeyRpId,rpName:e.shieldConfiguration?.passkeyRpName,displayName:e.shieldConfiguration?.passkeyDisplayName}),d.InternalSentry.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}static getEventEmitter(){return p.globalEventEmitter||(p.globalEventEmitter=new h),p.globalEventEmitter}async waitForInitialization(){await this.initPromise,await this.ensureAsyncInitialized()}async getAccessToken(){return await this.ensureInitialized(),this.openfortInternal.getAccessToken()}async validateAndRefreshToken(e){return await this.ensureInitialized(),await this.openfortInternal.validateAndRefreshToken(e)}get backendApiClients(){return new e.BackendApiClients({basePath:this.configuration.backendUrl,accessToken:this.configuration.baseConfiguration.publishableKey,nativeAppIdentifier:this.configuration.nativeAppIdentifier,storage:this.storage,onLogout:()=>{this.eventEmitter.emit("onLogout")}})}get authManager(){if(!this.iAuthManager)throw new u.RequestError("AuthManager not initialized");return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(e){try{const t=r.StorageKeys.TEST,i="openfort_storage_test";e.save(t,i);const n=await e.get(t);return e.remove(t),n===i}catch(e){return!1}}async initializeAsync(){if(!await p.isStorageAccessible(this.storage))throw new u.OpenfortError("Storage is not accessible",c.OPENFORT_ERROR_CODES.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}exports.Openfort=p;
@@ -1 +1 @@
1
- "use strict";var e=require("human-id"),r=require("./errors.cjs"),t=require("./utils.cjs");exports.PasskeyHandler=class{validByteLengths=[16,24,32];rpId;rpName;timeoutMs;derivedKeyLengthBytes;constructor({rpId:e,rpName:r,timeoutMs:t,derivedKeyLengthBytes:s}={}){if(this.rpId=e,this.rpName=r,this.timeoutMs=t??6e4,this.derivedKeyLengthBytes=s??32,!this.validByteLengths.includes(this.derivedKeyLengthBytes))throw new Error(`Invalid key byte length ${this.derivedKeyLengthBytes}`)}static randomPasskeyName(){return e.humanId({capitalize:!0,separator:" "})}getChallengeBytes(){return crypto.getRandomValues(new Uint8Array(32))}async deriveKeyFromAssertion(e){const t=e.getClientExtensionResults();if(!t)throw new r.PasskeyPRFNotSupportedError("Passkey fetch failed: no client extension results");const s=t.prf;if(!s||!s.results)throw new r.PasskeyPRFNotSupportedError("PRF extension not supported or missing results");const a=s.results.first,n=await crypto.subtle.importKey("raw",a,{name:"AES-CBC",length:this.derivedKeyLengthBytes},!0,["encrypt","decrypt"]);return crypto.subtle.exportKey("raw",n)}async createPasskey({id:e,displayName:s,seed:a}){if(!a||0===a.trim().length)throw new r.PasskeySeedInvalidError;const n={challenge:this.getChallengeBytes(),rp:{id:this.rpId,name:this.rpName},user:{id:(new TextEncoder).encode(e),name:e,displayName:s},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{residentKey:"required",userVerification:"required"},extensions:{prf:{eval:{first:(new TextEncoder).encode(a)}}},timeout:this.timeoutMs,attestation:"direct"};let i,o;try{i=await navigator.credentials.create({publicKey:n})}catch(e){if(e instanceof Error&&"NotAllowedError"===e.name)throw new r.PasskeyUserCancelledError;throw new r.PasskeyCreationFailedError(e instanceof Error?e.message:"Unknown error",e instanceof Error?e:void 0)}if(!i)throw new r.PasskeyUserCancelledError;try{o=await this.deriveKeyFromAssertion(i)}catch(e){throw e instanceof r.PasskeyPRFNotSupportedError&&console.warn(`[Openfort] Passkey created but PRF extension failed. A passkey credential may exist on the device that cannot be used for wallet recovery. Credential ID: ${t.arrayBufferToBase64URL(i.rawId)}`),e}return{id:t.arrayBufferToBase64URL(i.rawId),displayName:s,key:t.arrayBufferToBase64URL(o)}}async deriveAndExportKey({id:e,seed:s}){if(!s||0===s.trim().length)throw new r.PasskeySeedInvalidError;let a;try{a=await navigator.credentials.get({publicKey:{challenge:this.getChallengeBytes(),rpId:this.rpId,allowCredentials:[{id:t.base64ToArrayBuffer(e),type:"public-key"}],userVerification:"required",extensions:{prf:{eval:{first:(new TextEncoder).encode(s)}}}}})}catch(e){if(e instanceof Error&&"NotAllowedError"===e.name)throw new r.PasskeyUserCancelledError;throw new r.PasskeyAssertionFailedError(e instanceof Error?e.message:"Unknown error",e instanceof Error?e:void 0)}if(!a)throw new r.PasskeyUserCancelledError;const n=await this.deriveKeyFromAssertion(a);return t.arrayBufferToBase64URL(n)}};
1
+ "use strict";var e=require("human-id"),r=require("./errors.cjs"),t=require("./types.cjs"),s=require("./utils.cjs");exports.PasskeyHandler=class{validByteLengths=[16,24,32];rpId;rpName;displayName;timeoutMs;derivedKeyLengthBytes;constructor({rpId:e,rpName:r,displayName:s,timeoutMs:a,derivedKeyLengthBytes:i}={}){if(this.rpId=e,this.rpName=r,this.displayName=s??t.DEFAULT_PASSKEY_DISPLAY_NAME,this.timeoutMs=a??6e4,this.derivedKeyLengthBytes=i??32,!this.validByteLengths.includes(this.derivedKeyLengthBytes))throw new Error(`Invalid key byte length ${this.derivedKeyLengthBytes}`)}static randomPasskeyName(){return e.humanId({capitalize:!0,separator:" "})}getChallengeBytes(){return crypto.getRandomValues(new Uint8Array(32))}async deriveKeyFromAssertion(e){const t=e.getClientExtensionResults();if(!t)throw new r.PasskeyPRFNotSupportedError("Passkey fetch failed: no client extension results");const s=t.prf;if(!s||!s.results)throw new r.PasskeyPRFNotSupportedError("PRF extension not supported or missing results");const a=s.results.first,i=await crypto.subtle.importKey("raw",a,{name:"AES-CBC",length:this.derivedKeyLengthBytes},!0,["encrypt","decrypt"]);return crypto.subtle.exportKey("raw",i)}async createPasskey({id:e,seed:t}){if(!t||0===t.trim().length)throw new r.PasskeySeedInvalidError;const a={challenge:this.getChallengeBytes(),rp:{id:this.rpId,name:this.rpName},user:{id:(new TextEncoder).encode(e),name:e,displayName:this.displayName},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{residentKey:"required",userVerification:"required"},extensions:{prf:{eval:{first:(new TextEncoder).encode(t)}}},timeout:this.timeoutMs,attestation:"direct"};let i,n;try{i=await navigator.credentials.create({publicKey:a})}catch(e){if(e instanceof Error&&"NotAllowedError"===e.name)throw new r.PasskeyUserCancelledError;throw new r.PasskeyCreationFailedError(e instanceof Error?e.message:"Unknown error",e instanceof Error?e:void 0)}if(!i)throw new r.PasskeyUserCancelledError;try{n=await this.deriveKeyFromAssertion(i)}catch(e){throw e instanceof r.PasskeyPRFNotSupportedError&&console.warn(`[Openfort] Passkey created but PRF extension failed. A passkey credential may exist on the device that cannot be used for wallet recovery. Credential ID: ${s.arrayBufferToBase64URL(i.rawId)}`),e}return{id:s.arrayBufferToBase64URL(i.rawId),displayName:this.displayName,key:s.arrayBufferToBase64URL(n)}}async deriveAndExportKey({id:e,seed:t}){if(!t||0===t.trim().length)throw new r.PasskeySeedInvalidError;let a;try{a=await navigator.credentials.get({publicKey:{challenge:this.getChallengeBytes(),rpId:this.rpId,allowCredentials:[{id:s.base64ToArrayBuffer(e),type:"public-key"}],userVerification:"required",extensions:{prf:{eval:{first:(new TextEncoder).encode(t)}}}}})}catch(e){if(e instanceof Error&&"NotAllowedError"===e.name)throw new r.PasskeyUserCancelledError;throw new r.PasskeyAssertionFailedError(e instanceof Error?e.message:"Unknown error",e instanceof Error?e:void 0)}if(!a)throw new r.PasskeyUserCancelledError;const i=await this.deriveKeyFromAssertion(a);return s.arrayBufferToBase64URL(i)}};
@@ -0,0 +1 @@
1
+ "use strict";exports.DEFAULT_PASSKEY_DISPLAY_NAME="Openfort - Embedded Wallet";
@@ -1 +1 @@
1
- "use strict";exports.arrayBufferToBase64URL=function(r){const e=r instanceof Uint8Array?r:new Uint8Array(r);let t="";for(const r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},exports.base64ToArrayBuffer=function(r){const e=atob(r),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t.buffer};
1
+ "use strict";exports.arrayBufferToBase64URL=function(e){const r=e instanceof Uint8Array?e:new Uint8Array(e);let t="";for(const e of r)t+=String.fromCharCode(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},exports.base64ToArrayBuffer=function(e){const r=e.replace(/-/g,"+").replace(/_/g,"/"),t=r+"=".repeat((4-r.length%4)%4),n=atob(t),a=new Uint8Array(n.length);for(let e=0;e<n.length;e++)a[e]=n.charCodeAt(e);return a.buffer};
@@ -1 +1 @@
1
- "use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.1.6";
1
+ "use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.2.0";
@@ -1 +1 @@
1
- "use strict";var e=require("../core/configuration/authentication.cjs"),t=require("../core/errors/authErrorCodes.cjs"),a=require("../core/errors/openfortError.cjs"),r=require("../core/errors/withApiError.cjs"),o=require("../core/passkey/handler.cjs"),n=require("../core/config/config.cjs"),s=require("../core/configuration/account.cjs"),i=require("../storage/istorage.cjs"),c=require("../types/types.cjs");exports.EmbeddedSigner=class{iframeManager;storage;backendApiClients;passkeyHandler;eventEmitter;constructor(e,t,a,r,o){this.iframeManager=e,this.storage=t,this.backendApiClients=a,this.passkeyHandler=r,this.eventEmitter=o}async createPasskey(e){const t=await this.passkeyHandler.createPasskey({id:o.PasskeyHandler.randomPasskeyName(),displayName:n.SDKConfiguration.getInstance()?.passkeyDisplayName??"Openfort - Embedded Wallet",seed:e});return{id:t.id,key:t.key}}async configure(o){const i=await e.Authentication.fromStorage(this.storage);if(!i)throw new a.SessionError(t.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");const d=n.SDKConfiguration.getInstance();if(!d)throw new a.ConfigurationError("Configuration not found");const y=await s.Account.fromStorage(this.storage);let p;if(y){const e={account:y.id,...o.entropy&&{entropy:{...o.entropy.recoveryPassword&&{recoveryPassword:o.entropy.recoveryPassword},...o.entropy.encryptionSession&&{encryptionSession:o.entropy.encryptionSession},..."passkey"===y.recoveryMethod&&{passkey:{id:y.recoveryMethodDetails?.passkeyId,env:y.recoveryMethodDetails?.passkeyEnv,key:await o.getPasskeyKeyFn(y.recoveryMethodDetails?.passkeyId??"")}}}}},t=await this.iframeManager.recover(e);p=t.account}else{const e=await this.backendApiClients.accountsV2Api.getAccountsV2({accountType:o.accountType,chainType:o.chainType},{headers:i.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":d.baseConfiguration.publishableKey}});if(0===e.data.data.length){const e=o.entropy?.passkey?await this.createPasskey(i.userId):void 0,t={accountType:o.accountType,chainType:o.chainType,chainId:o.chainId,...o.entropy&&{entropy:{...o.entropy.recoveryPassword&&{recoveryPassword:o.entropy.recoveryPassword},...o.entropy.encryptionSession&&{encryptionSession:o.entropy.encryptionSession},...o.entropy.passkey&&{passkey:e}}}},a=await this.iframeManager.create(t);p=a.account}else{const t=e.data.data,a=t.find(e=>e.chainId===o.chainId),r=a||t[0],n={account:r.id,...o.entropy&&{entropy:{...o.entropy.recoveryPassword&&{recoveryPassword:o.entropy.recoveryPassword},...o.entropy.encryptionSession&&{encryptionSession:o.entropy.encryptionSession},..."passkey"===r.recoveryMethod&&{passkey:{id:r.recoveryMethodDetails?.passkeyId,env:r.recoveryMethodDetails?.passkeyEnv,key:await o.getPasskeyKeyFn(r.recoveryMethodDetails?.passkeyId??"")}}}}},s=await this.iframeManager.recover(n);if(p=s.account,!a){const e=await this.iframeManager.switchChain(o.chainId);p=e.account}}}return r.withApiError(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:p},{headers:i.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":d.baseConfiguration.publishableKey}}),t=new s.Account({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:s.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(c.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"configure"})}async sign(e,t,a,r){const o=await this.iframeManager.sign(e,t,a,r);return this.eventEmitter.emit(c.OpenfortEvents.ON_SIGNED_MESSAGE,{message:e,signature:o}),o}async export(){return await this.iframeManager.export()}async switchChain({chainId:e}){const t=await s.Account.fromStorage(this.storage);if(t?.accountType===c.AccountTypeEnum.EOA)new s.Account({...t,chainId:e}).save(this.storage);else{const a=await this.iframeManager.switchChain(e);new s.Account({...t,id:a.account,chainId:e}).save(this.storage)}}async create(o){const i=await this.iframeManager.create(o),d=await e.Authentication.fromStorage(this.storage);if(!d)throw new a.SessionError(t.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");const y=n.SDKConfiguration.getInstance();if(!y)throw new a.ConfigurationError("Configuration not found");return r.withApiError(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:i.account},{headers:d.thirdPartyProvider?{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}:{authorization:`Bearer ${d.token}`,"x-project-key":y.baseConfiguration.publishableKey}}),t=new s.Account({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,implementationAddress:e.data.smartAccount?.implementationAddress,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:s.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(c.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"create"})}async recover(o){const i=await this.iframeManager.recover(o),d=await e.Authentication.fromStorage(this.storage);if(!d)throw new a.SessionError(t.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");const y=n.SDKConfiguration.getInstance();if(!y)throw new a.ConfigurationError("Configuration not found");return r.withApiError(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:i.account},{headers:d.thirdPartyProvider?{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}:{authorization:`Bearer ${d.token}`,"x-project-key":y.baseConfiguration.publishableKey}}),t=new s.Account({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:s.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(c.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"recover"})}async setRecoveryMethod({recoveryMethod:e,recoveryPassword:t,encryptionSession:a,passkeyInfo:r}){await this.iframeManager.setRecoveryMethod(e,t,a,r?.passkeyKey,r?.passkeyId)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(i.StorageKeys.ACCOUNT)}};
1
+ "use strict";var e=require("../core/configuration/authentication.cjs"),t=require("../core/errors/authErrorCodes.cjs"),a=require("../core/errors/openfortError.cjs"),r=require("../core/errors/withApiError.cjs"),o=require("../core/passkey/handler.cjs"),n=require("../core/config/config.cjs"),s=require("../core/configuration/account.cjs"),i=require("../storage/istorage.cjs"),c=require("../types/types.cjs");exports.EmbeddedSigner=class{iframeManager;storage;backendApiClients;passkeyHandler;eventEmitter;constructor(e,t,a,r,o){this.iframeManager=e,this.storage=t,this.backendApiClients=a,this.passkeyHandler=r,this.eventEmitter=o}async createPasskey(e){const t=await this.passkeyHandler.createPasskey({id:o.PasskeyHandler.randomPasskeyName(),seed:e});return{id:t.id,key:t.key}}async configure(o){const i=await e.Authentication.fromStorage(this.storage);if(!i)throw new a.SessionError(t.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");const d=n.SDKConfiguration.getInstance();if(!d)throw new a.ConfigurationError("Configuration not found");const y=await s.Account.fromStorage(this.storage);let h;if(y){const e={account:y.id,...o.entropy&&{entropy:{...o.entropy.recoveryPassword&&{recoveryPassword:o.entropy.recoveryPassword},...o.entropy.encryptionSession&&{encryptionSession:o.entropy.encryptionSession},..."passkey"===y.recoveryMethod&&{passkey:{id:y.recoveryMethodDetails?.passkeyId,env:y.recoveryMethodDetails?.passkeyEnv,key:await o.getPasskeyKeyFn(y.recoveryMethodDetails?.passkeyId??"")}}}}},t=await this.iframeManager.recover(e);h=t.account}else{const e=await this.backendApiClients.accountsV2Api.getAccountsV2({accountType:o.accountType,chainType:o.chainType},{headers:i.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":d.baseConfiguration.publishableKey}});if(0===e.data.data.length){const e=o.entropy?.passkey?await this.createPasskey(i.userId):void 0,t={accountType:o.accountType,chainType:o.chainType,chainId:o.chainId,...o.entropy&&{entropy:{...o.entropy.recoveryPassword&&{recoveryPassword:o.entropy.recoveryPassword},...o.entropy.encryptionSession&&{encryptionSession:o.entropy.encryptionSession},...o.entropy.passkey&&{passkey:e}}}},a=await this.iframeManager.create(t);h=a.account}else{const t=e.data.data,a=t.find(e=>e.chainId===o.chainId),r=a||t[0],n={account:r.id,...o.entropy&&{entropy:{...o.entropy.recoveryPassword&&{recoveryPassword:o.entropy.recoveryPassword},...o.entropy.encryptionSession&&{encryptionSession:o.entropy.encryptionSession},..."passkey"===r.recoveryMethod&&{passkey:{id:r.recoveryMethodDetails?.passkeyId,env:r.recoveryMethodDetails?.passkeyEnv,key:await o.getPasskeyKeyFn(r.recoveryMethodDetails?.passkeyId??"")}}}}},s=await this.iframeManager.recover(n);if(h=s.account,!a){const e=await this.iframeManager.switchChain(o.chainId);h=e.account}}}return r.withApiError(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:h},{headers:i.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":d.baseConfiguration.publishableKey}}),t=new s.Account({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:s.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(c.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"configure"})}async sign(e,t,a,r){const o=await this.iframeManager.sign(e,t,a,r);return this.eventEmitter.emit(c.OpenfortEvents.ON_SIGNED_MESSAGE,{message:e,signature:o}),o}async export(){return await this.iframeManager.export()}async switchChain({chainId:e}){const t=await s.Account.fromStorage(this.storage);if(t?.accountType===c.AccountTypeEnum.EOA)new s.Account({...t,chainId:e}).save(this.storage);else{const a=await this.iframeManager.switchChain(e);new s.Account({...t,id:a.account,chainId:e}).save(this.storage)}}async create(o){const i=await this.iframeManager.create(o),d=await e.Authentication.fromStorage(this.storage);if(!d)throw new a.SessionError(t.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");const y=n.SDKConfiguration.getInstance();if(!y)throw new a.ConfigurationError("Configuration not found");return r.withApiError(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:i.account},{headers:d.thirdPartyProvider?{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}:{authorization:`Bearer ${d.token}`,"x-project-key":y.baseConfiguration.publishableKey}}),t=new s.Account({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,implementationAddress:e.data.smartAccount?.implementationAddress,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:s.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(c.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"create"})}async recover(o){const i=await this.iframeManager.recover(o),d=await e.Authentication.fromStorage(this.storage);if(!d)throw new a.SessionError(t.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");const y=n.SDKConfiguration.getInstance();if(!y)throw new a.ConfigurationError("Configuration not found");return r.withApiError(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:i.account},{headers:d.thirdPartyProvider?{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}:{authorization:`Bearer ${d.token}`,"x-project-key":y.baseConfiguration.publishableKey}}),t=new s.Account({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:s.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(c.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"recover"})}async setRecoveryMethod({recoveryMethod:e,recoveryPassword:t,encryptionSession:a,passkeyInfo:r}){await this.iframeManager.setRecoveryMethod(e,t,a,r?.passkeyKey,r?.passkeyId)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(i.StorageKeys.ACCOUNT)}};
@@ -1 +1 @@
1
- "use strict";var e=require("../core/configuration/account.cjs"),i=require("../core/configuration/authentication.cjs"),r=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/connect.cjs");require("./messaging/browserMessenger/backwardCompatibility.cjs");var u=require("./types.cjs");class h extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class g extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class l extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class R extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class y extends t.SignerError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.NOT_CONFIGURED,"Signer is not configured")}}class p extends t.OpenfortError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.OTP_REQUIRED,"OTP verification required")}}exports.IframeManager=class{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;hasFailed=!1;constructor(e,i,r){if(!e)throw new t.ConfigurationError("Configuration is required for IframeManager");if(!i)throw new t.ConfigurationError("Storage is required for IframeManager");if(!r)throw new t.ConfigurationError("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=r}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){a.debugLog("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:a.debugLog}),this.connection=c({messenger:this.messenger,timeout:1e4,log:a.debugLog});try{this.remote=await this.connection.promise,a.debugLog("IframeManager connection established")}catch(e){const i=e;throw n.sentry.captureException(i),this.destroy(),a.debugLog("Failed to establish connection:",i),new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}\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 `)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(u.isErrorResponse(e)){if(e.error===u.NOT_CONFIGURED_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new y;if(e.error===u.MISSING_USER_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.MISSING_PROJECT_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new l;if(e.error===u.INCORRECT_USER_ENTROPY_ERROR)throw new R;if(e.error===u.MISSING_PASSKEY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.INCORRECT_PASSKEY_ERROR)throw new g;if(e.error===u.OTP_REQUIRED_ERROR)throw new p;throw this.storage.remove(o.StorageKeys.ACCOUNT),new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=e.chainId??null,r.password=e?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:e?.entropy?.encryptionSession},r.passkey=e?.entropy?.passkey??null;const t={uuid:s.randomUUID(),action:u.Event.CREATE,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},n=await i.create(t);return u.isErrorResponse(n)&&this.handleError(n),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",n.version??"undefined"),n}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await e.Account.fromStorage(this.storage),t=await this.ensureConnection(),n=await this.buildIFrameRequestConfiguration();n.chainId=r?.chainId??null,n.password=i?.entropy?.recoveryPassword??null,n.recovery={...n.recovery,encryptionSession:i?.entropy?.encryptionSession},n.passkey=i?.entropy?.passkey??null;const o={uuid:s.randomUUID(),action:u.Event.RECOVER,recovery:n.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:n.accessToken,playerID:n.playerID,thirdPartyProvider:n.thirdPartyProvider,thirdPartyTokenType:n.thirdPartyTokenType,encryptionKey:n.password,encryptionSession:n.recovery?.encryptionSession??null,passkey:n.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},a=await t.recover(o);return u.isErrorResponse(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,i,r,t){a.debugLog("[iframe] ensureConnection");const n=await this.ensureConnection(),o=new u.SignRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,t);a.debugLog("[iframe] done ensureConnection");const d=await n.sign(o);return a.debugLog("[iframe] response",d),u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined"),d.signature}async switchChain(e){const i=await this.ensureConnection(),r=new u.SwitchChainRequest(s.randomUUID(),e,await this.buildRequestConfiguration()),t=await i.switchChain(r);return u.isErrorResponse(t)&&this.handleError(t),t}async export(){const e=await this.ensureConnection(),i=new u.ExportPrivateKeyRequest(s.randomUUID(),await this.buildRequestConfiguration()),r=await e.export(i);return u.isErrorResponse(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r.key}async setRecoveryMethod(e,i,r,t,n){const o=await this.ensureConnection(),a=new u.SetRecoveryMethodRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,t,n),d=await o.setRecoveryMethod(a);u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),r=new u.GetCurrentDeviceRequest(s.randomUUID(),e);try{const e=await i.getCurrentDevice(r);return u.isErrorResponse(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof y)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void a.debugLog("IframeManager not loaded, skipping authentication update");const e=await i.Authentication.fromStorage(this.storage);if(!e)return void a.debugLog("No authentication found, skipping update");const r=new u.UpdateAuthenticationRequest(s.randomUUID(),e.token);a.debugLog("Updating authentication in iframe with token");const t=await this.remote.updateAuthentication(r);u.isErrorResponse(t)&&this.handleError(t)}async disconnect(){const e=await this.ensureConnection(),i={uuid:s.randomUUID()};await e.logout(i)}async onMessage(e){a.debugLog("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof d.ReactNativeMessenger?(this.isInitialized||this.connection?a.debugLog(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(a.debugLog("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{a.debugLog("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),a.debugLog("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):a.debugLog("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}},exports.MissingProjectEntropyError=l,exports.MissingRecoveryPasswordError=h,exports.NotConfiguredError=y,exports.OTPRequiredError=p,exports.WrongPasskeyError=g,exports.WrongRecoveryPasswordError=R;
1
+ "use strict";var e=require("../core/configuration/account.cjs"),i=require("../core/configuration/authentication.cjs"),r=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/connect.cjs");require("./messaging/browserMessenger/backwardCompatibility.cjs");var u=require("./types.cjs");class h extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class g extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class l extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class R extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class y extends t.SignerError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.NOT_CONFIGURED,"Signer is not configured")}}class p extends t.OpenfortError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.OTP_REQUIRED,"OTP verification required")}}exports.IframeManager=class{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;hasFailed=!1;constructor(e,i,r){if(!e)throw new t.ConfigurationError("Configuration is required for IframeManager");if(!i)throw new t.ConfigurationError("Storage is required for IframeManager");if(!r)throw new t.ConfigurationError("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=r}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){a.debugLog("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:a.debugLog}),this.connection=c({messenger:this.messenger,timeout:1e4,log:a.debugLog});try{this.remote=await this.connection.promise,a.debugLog("IframeManager connection established")}catch(e){const i=e;throw n.sentry.captureException(i),this.destroy(),a.debugLog("Failed to establish connection:",i),new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}\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 `)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(u.isErrorResponse(e)){if(e.error===u.NOT_CONFIGURED_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new y;if(e.error===u.MISSING_USER_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.MISSING_PROJECT_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new l;if(e.error===u.INCORRECT_USER_ENTROPY_ERROR)throw new R;if(e.error===u.MISSING_PASSKEY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.INCORRECT_PASSKEY_ERROR)throw new g;if(e.error===u.OTP_REQUIRED_ERROR)throw new p;throw this.storage.remove(o.StorageKeys.ACCOUNT),new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=e.chainId??null,r.password=e?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:e?.entropy?.encryptionSession},r.passkey=e?.entropy?.passkey??null;const t={uuid:s.randomUUID(),action:u.Event.CREATE,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},n=await i.create(t);return u.isErrorResponse(n)&&this.handleError(n),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",n.version??"undefined"),n}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await e.Account.fromStorage(this.storage),t=await this.ensureConnection(),n=await this.buildIFrameRequestConfiguration();n.chainId=r?.chainId??null,n.password=i?.entropy?.recoveryPassword??null,n.recovery={...n.recovery,encryptionSession:i?.entropy?.encryptionSession},n.passkey=i?.entropy?.passkey??null;const o={uuid:s.randomUUID(),action:u.Event.RECOVER,recovery:n.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:n.accessToken,playerID:n.playerID,thirdPartyProvider:n.thirdPartyProvider,thirdPartyTokenType:n.thirdPartyTokenType,encryptionKey:n.password,encryptionSession:n.recovery?.encryptionSession??null,passkey:n.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},a=await t.recover(o);return u.isErrorResponse(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,i,r,t){a.debugLog("[iframe] ensureConnection");const n=await this.ensureConnection(),o=new u.SignRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,t);a.debugLog("[iframe] done ensureConnection");const d=await n.sign(o);return a.debugLog("[iframe] response",d),u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined"),d.signature}async switchChain(e){const i=await this.ensureConnection(),r=new u.SwitchChainRequest(s.randomUUID(),e,await this.buildRequestConfiguration()),t=await i.switchChain(r);return u.isErrorResponse(t)&&this.handleError(t),t}async export(){const e=await this.ensureConnection(),i=new u.ExportPrivateKeyRequest(s.randomUUID(),await this.buildRequestConfiguration()),r=await e.export(i);return u.isErrorResponse(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r.key}async setRecoveryMethod(e,i,r,t,n){const o=await this.ensureConnection(),a=new u.SetRecoveryMethodRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,t,n),d=await o.setRecoveryMethod(a);u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),r=new u.GetCurrentDeviceRequest(s.randomUUID(),e);try{const e=await i.getCurrentDevice(r);return u.isErrorResponse(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof y)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void a.debugLog("IframeManager not loaded, skipping authentication update");const e=await i.Authentication.fromStorage(this.storage);if(!e)return void a.debugLog("No authentication found, skipping update");const r=new u.UpdateAuthenticationRequest(s.randomUUID(),e.token);a.debugLog("Updating authentication in iframe with token");const t=await this.remote.updateAuthentication(r);u.isErrorResponse(t)&&this.handleError(t)}async disconnect(){const e=await this.ensureConnection(),i={uuid:s.randomUUID()};await e.logout(i)}async onMessage(e){a.debugLog("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof d.ReactNativeMessenger?(this.isInitialized||this.connection?a.debugLog(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(a.debugLog("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{a.debugLog("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),a.debugLog("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):a.debugLog("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}},exports.MissingProjectEntropyError=l,exports.MissingRecoveryPasswordError=h,exports.NotConfiguredError=y,exports.OTPRequiredError=p,exports.WrongPasskeyError=g,exports.WrongRecoveryPasswordError=R;
package/dist/index.d.cts CHANGED
@@ -12235,10 +12235,6 @@ declare class OpenfortConfiguration {
12235
12235
  }
12236
12236
  declare class ShieldConfiguration {
12237
12237
  readonly shieldPublishableKey: string;
12238
- /**
12239
- * @deprecated This option is no longer used and will be removed in future versions.
12240
- */
12241
- readonly shieldEncryptionKey?: string;
12242
12238
  readonly debug?: boolean;
12243
12239
  /**
12244
12240
  * The relying party identifier for WebAuthn passkey operations.
@@ -12286,9 +12282,6 @@ declare class SDKConfiguration {
12286
12282
  readonly iframeUrl: string;
12287
12283
  readonly backendUrl: string;
12288
12284
  readonly storage?: IStorage;
12289
- readonly passkeyRpId?: string;
12290
- readonly passkeyRpName?: string;
12291
- readonly passkeyDisplayName?: string;
12292
12285
  readonly nativeAppIdentifier?: string;
12293
12286
  readonly debug?: boolean;
12294
12287
  static instance: SDKConfiguration | null;
@@ -13147,17 +13140,12 @@ declare class PasskeySeedInvalidError extends OpenfortError {
13147
13140
  constructor(message?: string);
13148
13141
  }
13149
13142
 
13150
- /**
13151
- * Passkey types and interfaces.
13152
- */
13153
13143
  /**
13154
13144
  * Configuration for creating a new passkey.
13155
13145
  */
13156
13146
  interface PasskeyCreateConfig {
13157
13147
  /** Unique identifier for the passkey */
13158
13148
  id: string;
13159
- /** Human-readable display name shown in passkey dialogs */
13160
- displayName: string;
13161
13149
  /** Seed value used for PRF-based key derivation */
13162
13150
  seed: string;
13163
13151
  }
@@ -13201,24 +13189,24 @@ declare class PasskeyHandler implements IPasskeyHandler {
13201
13189
  private readonly validByteLengths;
13202
13190
  private readonly rpId?;
13203
13191
  private readonly rpName?;
13192
+ private readonly displayName;
13204
13193
  private readonly timeoutMs;
13205
13194
  private readonly derivedKeyLengthBytes;
13206
13195
  /**
13207
13196
  * Creates a new passkey handler
13208
- * The only fixed values from an issuer's point of view are rpId + rpName
13209
13197
  * @param rpId The issuer's domain name
13210
13198
  * @param rpName The issuer's display name
13199
+ * @param displayName Credential display name shown in passkey dialogs
13211
13200
  * @param timeoutMs Timeout (in milliseconds) before a passkey dialog expires
13212
13201
  * @param derivedKeyLengthBytes Byte length for target keys (16, 24, or 32)
13213
13202
  */
13214
- constructor({ rpId, rpName, timeoutMs, derivedKeyLengthBytes }?: PasskeyHandlerConfig);
13203
+ constructor({ rpId, rpName, displayName, timeoutMs, derivedKeyLengthBytes }?: PasskeyHandlerConfig);
13215
13204
  static randomPasskeyName(): string;
13216
13205
  private getChallengeBytes;
13217
13206
  private deriveKeyFromAssertion;
13218
13207
  /**
13219
13208
  * Prompts the user to create a passkey.
13220
13209
  * @param id User identifier
13221
- * @param displayName Display name (ideally it should hint about environment, chain id, etc)
13222
13210
  * @param seed Seed phrase for PRF key derivation
13223
13211
  * @returns PasskeyDetails with passkey details if passkey creation was successful
13224
13212
  * @throws PasskeySeedInvalidError if seed is empty
@@ -13226,7 +13214,7 @@ declare class PasskeyHandler implements IPasskeyHandler {
13226
13214
  * @throws PasskeyPRFNotSupportedError if PRF extension fails
13227
13215
  * @throws PasskeyCreationFailedError for other failures
13228
13216
  */
13229
- createPasskey({ id, displayName, seed }: PasskeyCreateConfig): Promise<PasskeyDetails>;
13217
+ createPasskey({ id, seed }: PasskeyCreateConfig): Promise<PasskeyDetails>;
13230
13218
  /**
13231
13219
  * Derive and export a key using local passkey
13232
13220
  * @param id Internal ID of the passkey
@@ -13242,6 +13230,8 @@ declare class PasskeyHandler implements IPasskeyHandler {
13242
13230
  interface PasskeyHandlerConfig {
13243
13231
  rpId?: string;
13244
13232
  rpName?: string;
13233
+ /** Credential display name shown in passkey dialogs */
13234
+ displayName?: string;
13245
13235
  /** Timeout in milliseconds before passkey dialog expires (default: 60000) */
13246
13236
  timeoutMs?: number;
13247
13237
  /** Derived key length in bytes: 16, 24, or 32 (default: 32) */
@@ -13257,7 +13247,7 @@ interface PasskeyHandlerConfig {
13257
13247
  */
13258
13248
  declare function arrayBufferToBase64URL(buffer: ArrayBuffer | Uint8Array): string;
13259
13249
  /**
13260
- * Converts base64 string to ArrayBuffer.
13250
+ * Converts base64 or base64url string to ArrayBuffer.
13261
13251
  */
13262
13252
  declare function base64ToArrayBuffer(base64: string): ArrayBuffer;
13263
13253
 
package/dist/index.d.ts CHANGED
@@ -12235,10 +12235,6 @@ declare class OpenfortConfiguration {
12235
12235
  }
12236
12236
  declare class ShieldConfiguration {
12237
12237
  readonly shieldPublishableKey: string;
12238
- /**
12239
- * @deprecated This option is no longer used and will be removed in future versions.
12240
- */
12241
- readonly shieldEncryptionKey?: string;
12242
12238
  readonly debug?: boolean;
12243
12239
  /**
12244
12240
  * The relying party identifier for WebAuthn passkey operations.
@@ -12286,9 +12282,6 @@ declare class SDKConfiguration {
12286
12282
  readonly iframeUrl: string;
12287
12283
  readonly backendUrl: string;
12288
12284
  readonly storage?: IStorage;
12289
- readonly passkeyRpId?: string;
12290
- readonly passkeyRpName?: string;
12291
- readonly passkeyDisplayName?: string;
12292
12285
  readonly nativeAppIdentifier?: string;
12293
12286
  readonly debug?: boolean;
12294
12287
  static instance: SDKConfiguration | null;
@@ -13147,17 +13140,12 @@ declare class PasskeySeedInvalidError extends OpenfortError {
13147
13140
  constructor(message?: string);
13148
13141
  }
13149
13142
 
13150
- /**
13151
- * Passkey types and interfaces.
13152
- */
13153
13143
  /**
13154
13144
  * Configuration for creating a new passkey.
13155
13145
  */
13156
13146
  interface PasskeyCreateConfig {
13157
13147
  /** Unique identifier for the passkey */
13158
13148
  id: string;
13159
- /** Human-readable display name shown in passkey dialogs */
13160
- displayName: string;
13161
13149
  /** Seed value used for PRF-based key derivation */
13162
13150
  seed: string;
13163
13151
  }
@@ -13201,24 +13189,24 @@ declare class PasskeyHandler implements IPasskeyHandler {
13201
13189
  private readonly validByteLengths;
13202
13190
  private readonly rpId?;
13203
13191
  private readonly rpName?;
13192
+ private readonly displayName;
13204
13193
  private readonly timeoutMs;
13205
13194
  private readonly derivedKeyLengthBytes;
13206
13195
  /**
13207
13196
  * Creates a new passkey handler
13208
- * The only fixed values from an issuer's point of view are rpId + rpName
13209
13197
  * @param rpId The issuer's domain name
13210
13198
  * @param rpName The issuer's display name
13199
+ * @param displayName Credential display name shown in passkey dialogs
13211
13200
  * @param timeoutMs Timeout (in milliseconds) before a passkey dialog expires
13212
13201
  * @param derivedKeyLengthBytes Byte length for target keys (16, 24, or 32)
13213
13202
  */
13214
- constructor({ rpId, rpName, timeoutMs, derivedKeyLengthBytes }?: PasskeyHandlerConfig);
13203
+ constructor({ rpId, rpName, displayName, timeoutMs, derivedKeyLengthBytes }?: PasskeyHandlerConfig);
13215
13204
  static randomPasskeyName(): string;
13216
13205
  private getChallengeBytes;
13217
13206
  private deriveKeyFromAssertion;
13218
13207
  /**
13219
13208
  * Prompts the user to create a passkey.
13220
13209
  * @param id User identifier
13221
- * @param displayName Display name (ideally it should hint about environment, chain id, etc)
13222
13210
  * @param seed Seed phrase for PRF key derivation
13223
13211
  * @returns PasskeyDetails with passkey details if passkey creation was successful
13224
13212
  * @throws PasskeySeedInvalidError if seed is empty
@@ -13226,7 +13214,7 @@ declare class PasskeyHandler implements IPasskeyHandler {
13226
13214
  * @throws PasskeyPRFNotSupportedError if PRF extension fails
13227
13215
  * @throws PasskeyCreationFailedError for other failures
13228
13216
  */
13229
- createPasskey({ id, displayName, seed }: PasskeyCreateConfig): Promise<PasskeyDetails>;
13217
+ createPasskey({ id, seed }: PasskeyCreateConfig): Promise<PasskeyDetails>;
13230
13218
  /**
13231
13219
  * Derive and export a key using local passkey
13232
13220
  * @param id Internal ID of the passkey
@@ -13242,6 +13230,8 @@ declare class PasskeyHandler implements IPasskeyHandler {
13242
13230
  interface PasskeyHandlerConfig {
13243
13231
  rpId?: string;
13244
13232
  rpName?: string;
13233
+ /** Credential display name shown in passkey dialogs */
13234
+ displayName?: string;
13245
13235
  /** Timeout in milliseconds before passkey dialog expires (default: 60000) */
13246
13236
  timeoutMs?: number;
13247
13237
  /** Derived key length in bytes: 16, 24, or 32 (default: 32) */
@@ -13257,7 +13247,7 @@ interface PasskeyHandlerConfig {
13257
13247
  */
13258
13248
  declare function arrayBufferToBase64URL(buffer: ArrayBuffer | Uint8Array): string;
13259
13249
  /**
13260
- * Converts base64 string to ArrayBuffer.
13250
+ * Converts base64 or base64url string to ArrayBuffer.
13261
13251
  */
13262
13252
  declare function base64ToArrayBuffer(base64: string): ArrayBuffer;
13263
13253
 
@@ -1 +1 @@
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{OpenfortEvents as m,RecoveryMethod as g,ChainTypeEnum as y,AccountTypeEnum as l,EmbeddedState as p}from"../types/types.js";import{debugLog as f}from"../utils/debug.js";import{EmbeddedSigner as u}from"../wallets/embedded.js";import{EvmProvider as w}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as A,openfortProviderInfo as v}from"../wallets/evm/provider/eip6963.js";import{signMessage as M}from"../wallets/evm/walletHelpers.js";import{IframeManager as E}from"../wallets/iframeManager.js";import{ReactNativeMessenger as I}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import D from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class T{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(m.ON_LOGOUT,()=>{f("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(f("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager&&this.iframeManager.hasFailed&&(f("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return f("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return f("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;f("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return f("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,f("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw f("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){f("[HANDSHAKE DEBUG] createIframeManager starting");const e=n.getInstance();if(!e)throw f("[HANDSHAKE DEBUG] Configuration not found"),new r("Configuration not found");let t;if(f("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)f("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(f("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new I(this.messagePoster),f("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{f("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new D({remoteWindow:r.contentWindow,allowedOrigins:[s]}),f("[HANDSHAKE DEBUG] Created WindowMessenger")}return f("[HANDSHAKE DEBUG] Creating IframeManager instance"),new E(e,this.storage,t)}async ensureSigner(){if(this.iframeManager&&this.iframeManager.hasFailed&&(f("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 u(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.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??l.SMART_ACCOUNT,chainType:e.chainType??y.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(),displayName:n.getInstance()?.passkeyDisplayName??"Openfort - Embedded Wallet",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[h,y]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),l=await h.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:y}),p={id:l.id,chainId:l.chainId,address:l.address,ownerAddress:l.ownerAddress,chainType:l.chainType,accountType:l.accountType,implementationType:l.implementationType,factoryAddress:l.factoryAddress,salt:l.salt,createdAt:l.createdAt,implementationAddress:l.implementationAddress,recoveryMethod:o.parseRecoveryMethod(l.recoveryMethod),recoveryMethodDetails:l.recoveryMethodDetails};return this.eventEmitter.emit(m.ON_EMBEDDED_WALLET_CREATED,p),p}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(m.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 M({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(),h=await d.fromStorage(this.storage);if(!h)throw new s(c.NOT_LOGGED_IN,"missing authentication");let m,y,l,p;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(!h.userId)throw new r("User ID is required for passkey key derivation");l={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:h.userId})}}else if(t.recoveryMethod===g.PASSKEY){if(!h.userId)throw new r("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),displayName:n.getInstance()?.passkeyDisplayName??"Openfort - Embedded Wallet",seed:h.userId});if(!e.key)throw new r("Passkey creation failed: no key material returned");l={passkeyId:e.id,passkeyKey:e.key},p={passkeyId:e.id}}if(e.recoveryMethod===g.PASSWORD?m=e.password:t.recoveryMethod===g.PASSWORD&&(m=t.password),e.recoveryMethod===g.AUTOMATIC?y=e.encryptionSession:t.recoveryMethod===g.AUTOMATIC&&(y=t.encryptionSession),!m&&!y)throw new r("Password or encryption session is not provided");await a.setRecoveryMethod({recoveryMethod:t.recoveryMethod,recoveryPassword:m,encryptionSession:y,passkeyInfo:l});const f=await o.fromStorage(this.storage);f&&new o({...f,recoveryMethod:t.recoveryMethod,recoveryMethodDetails:p}).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={accountType:l.SMART_ACCOUNT,...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 p.UNAUTHENTICATED;return await o.fromStorage(this.storage)?p.READY:p.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return f("Failed to get embedded state:",e),p.UNAUTHENTICATED}}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.policy&&this.provider.updatePolicy(r.policy):(this.provider=new w({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&A({info:{...v,...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 f("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("undefined"==typeof document&&!this.messagePoster)return f("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);const e=await this.ensureSigner();await e.disconnect(),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void f("Invalid message received:",e);f("[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 f("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();f(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&f("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),f("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),f("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{T 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{OpenfortEvents as m,RecoveryMethod as g,ChainTypeEnum as y,AccountTypeEnum as l,EmbeddedState as p}from"../types/types.js";import{debugLog as f}from"../utils/debug.js";import{EmbeddedSigner as u}from"../wallets/embedded.js";import{EvmProvider as w}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as A,openfortProviderInfo as v}from"../wallets/evm/provider/eip6963.js";import{signMessage as M}from"../wallets/evm/walletHelpers.js";import{IframeManager as E}from"../wallets/iframeManager.js";import{ReactNativeMessenger as I}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import D 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(m.ON_LOGOUT,()=>{f("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(f("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(f("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return f("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return f("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;f("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return f("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,f("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw f("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){f("[HANDSHAKE DEBUG] createIframeManager starting");const e=n.getInstance();if(!e)throw f("[HANDSHAKE DEBUG] Configuration not found"),new r("Configuration not found");let t;if(f("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)f("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(f("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new I(this.messagePoster),f("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{f("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new D({remoteWindow:r.contentWindow,allowedOrigins:[s]}),f("[HANDSHAKE DEBUG] Created WindowMessenger")}return f("[HANDSHAKE DEBUG] Creating IframeManager instance"),new E(e,this.storage,t)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(f("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 u(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.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??l.SMART_ACCOUNT,chainType:e.chainType??y.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)]),y=await n.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),l={id:y.id,chainId:y.chainId,address:y.address,ownerAddress:y.ownerAddress,chainType:y.chainType,accountType:y.accountType,implementationType:y.implementationType,factoryAddress:y.factoryAddress,salt:y.salt,createdAt:y.createdAt,implementationAddress:y.implementationAddress,recoveryMethod:o.parseRecoveryMethod(y.recoveryMethod),recoveryMethodDetails:y.recoveryMethodDetails};return this.eventEmitter.emit(m.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(m.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 M({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 p.UNAUTHENTICATED;return await o.fromStorage(this.storage)?p.READY:p.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return f("Failed to get embedded state:",e),p.UNAUTHENTICATED}}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.policy&&this.provider.updatePolicy(r.policy):(this.provider=new w({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&A({info:{...v,...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 f("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("undefined"==typeof document&&!this.messagePoster)return f("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 f("Invalid message received:",e);f("[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 f("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();f(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&f("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),f("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),f("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{k as EmbeddedWalletApi};
@@ -1 +1 @@
1
- import{setCryptoDigestOverride as e}from"../../utils/crypto.js";class s{publishableKey;nativeAppIdentifier;constructor(e){this.publishableKey=e.publishableKey,this.nativeAppIdentifier=e.nativeAppIdentifier}}class i{shieldPublishableKey;shieldEncryptionKey;debug=!1;passkeyRpId;passkeyRpName;passkeyDisplayName;constructor(e){this.shieldPublishableKey=e.shieldPublishableKey,this.debug=e.shieldDebug||!1,this.passkeyRpId=e.passkeyRpId,this.passkeyRpName=e.passkeyRpName,this.passkeyDisplayName=e.passkeyDisplayName}}class t{baseConfiguration;shieldConfiguration;thirdPartyAuth;shieldUrl;iframeUrl;backendUrl;storage;passkeyRpId;passkeyRpName;passkeyDisplayName;nativeAppIdentifier;debug;static instance=null;constructor({baseConfiguration:s,shieldConfiguration:i,overrides:a,thirdPartyAuth:p,debug:r}){this.shieldConfiguration=i,this.baseConfiguration=s,this.backendUrl=a?.backendUrl||"https://api.openfort.io",this.iframeUrl=a?.iframeUrl||"https://embed.openfort.io",this.iframeUrl=`${this.iframeUrl}/iframe/${this.baseConfiguration.publishableKey}`,this.debug=r,i?.debug&&(this.iframeUrl=`${this.iframeUrl}?debug=true`),this.shieldUrl=a?.shieldUrl||"https://shield.openfort.io",this.storage=a?.storage,this.thirdPartyAuth=p,this.passkeyRpId=i?.passkeyRpId,this.passkeyRpName=i?.passkeyRpName,this.passkeyDisplayName=i?.passkeyDisplayName,this.nativeAppIdentifier=s.nativeAppIdentifier,a?.crypto?.digest&&e(a.crypto.digest),t.instance=this}static getInstance(){return t.instance}}export{s as OpenfortConfiguration,t as SDKConfiguration,i as ShieldConfiguration};
1
+ import{setCryptoDigestOverride as e}from"../../utils/crypto.js";class i{publishableKey;nativeAppIdentifier;constructor(e){this.publishableKey=e.publishableKey,this.nativeAppIdentifier=e.nativeAppIdentifier}}class s{shieldPublishableKey;debug=!1;passkeyRpId;passkeyRpName;passkeyDisplayName;constructor(e){this.shieldPublishableKey=e.shieldPublishableKey,this.debug=e.shieldDebug||!1,this.passkeyRpId=e.passkeyRpId,this.passkeyRpName=e.passkeyRpName,this.passkeyDisplayName=e.passkeyDisplayName}}class t{baseConfiguration;shieldConfiguration;thirdPartyAuth;shieldUrl;iframeUrl;backendUrl;storage;nativeAppIdentifier;debug;static instance=null;constructor({baseConfiguration:i,shieldConfiguration:s,overrides:a,thirdPartyAuth:r,debug:h}){this.shieldConfiguration=s,this.baseConfiguration=i,this.backendUrl=a?.backendUrl||"https://api.openfort.io",this.iframeUrl=a?.iframeUrl||"https://embed.openfort.io",this.iframeUrl=`${this.iframeUrl}/iframe/${this.baseConfiguration.publishableKey}`,this.debug=h,s?.debug&&(this.iframeUrl=`${this.iframeUrl}?debug=true`),this.shieldUrl=a?.shieldUrl||"https://shield.openfort.io",this.storage=a?.storage,this.thirdPartyAuth=r,this.nativeAppIdentifier=i.nativeAppIdentifier,a?.crypto?.digest&&e(a.crypto.digest),t.instance=this}static getInstance(){return t.instance}}export{i as OpenfortConfiguration,t as SDKConfiguration,s as ShieldConfiguration};
@@ -1 +1 @@
1
- import{BackendApiClients as t}from"../../../packages/internal/openapi-clients/dist/index.js";import{AuthApi as e}from"../api/auth.js";import{EmbeddedWalletApi as i}from"../api/embeddedWallet.js";import{ProxyApi as n}from"../api/proxy.js";import{UserApi as s}from"../api/user.js";import{AuthManager as a}from"../auth/authManager.js";import{StorageKeys as r}from"../storage/istorage.js";import{LazyStorage as o}from"../storage/lazyStorage.js";import h from"../utils/typedEventEmitter.js";import{SDKConfiguration as l}from"./config/config.js";import{OPENFORT_AUTH_ERROR_CODES as c,OPENFORT_ERROR_CODES as d}from"./errors/authErrorCodes.js";import{ConfigurationError as u,SignerError as g,RequestError as m,OpenfortError as f}from"./errors/openfortError.js";import{InternalSentry as p}from"./errors/sentry.js";import{OpenfortInternal as I}from"./openfortInternal.js";import{PasskeyHandler as w}from"./passkey/handler.js";class y{storage;iAuthManager=null;openfortInternal;initPromise;asyncInitPromise=null;authInstance;embeddedWalletInstance;userInstance;proxyInstance;configuration;eventEmitter;iPasskeyHandler;static globalEventEmitter=null;get auth(){if(!this.authInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.");return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.");return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.");return this.userInstance}get proxy(){if(!this.proxyInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.");return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new a,this.openfortInternal=new I(this.storage,this.authManager,this.eventEmitter),this.authInstance=new e(this.storage,this.authManager,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter),this.embeddedWalletInstance=new i(this.storage,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter,this.passkeyHandler),this.userInstance=new s(this.storage,this.authManager,this.validateAndRefreshToken.bind(this)),this.proxyInstance=new n(this.storage,this.backendApiClients,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),async()=>{if(!this.embeddedWalletInstance)throw new g(c.MISSING_SIGNER,"Embedded wallet not initialized");const t=this.embeddedWalletInstance;return e=>t.signMessage(e,{hashMessage:!0,arrayifyMessage:!0})})}catch(t){throw new u("Openfort SDK synchronous initialization failed")}}constructor(t){if(this.configuration=new l(t),this.storage=new o(this.configuration.baseConfiguration.publishableKey,this.configuration.storage),this.eventEmitter=new h,y.globalEventEmitter){["onAuthInit","onAuthSuccess","onAuthFailure","onLogout","onSwitchAccount","onSignedMessage","onEmbeddedWalletCreated","onEmbeddedWalletRecovered","onAuthFlowOpen","onAuthFlowClose","onAuthFlowCancel"].forEach(t=>{this.eventEmitter.on(t,(...e)=>{y.globalEventEmitter?.emit(t,...e)})})}else y.globalEventEmitter=this.eventEmitter;this.iPasskeyHandler=t.overrides?.passkeyHandler??new w({rpId:this.configuration.passkeyRpId,rpName:this.configuration.passkeyRpName}),p.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}static getEventEmitter(){return y.globalEventEmitter||(y.globalEventEmitter=new h),y.globalEventEmitter}async waitForInitialization(){await this.initPromise,await this.ensureAsyncInitialized()}async getAccessToken(){return await this.ensureInitialized(),this.openfortInternal.getAccessToken()}async validateAndRefreshToken(t){return await this.ensureInitialized(),await this.openfortInternal.validateAndRefreshToken(t)}get backendApiClients(){return new t({basePath:this.configuration.backendUrl,accessToken:this.configuration.baseConfiguration.publishableKey,nativeAppIdentifier:this.configuration.nativeAppIdentifier,storage:this.storage,onLogout:()=>{this.eventEmitter.emit("onLogout")}})}get authManager(){if(!this.iAuthManager)throw new m("AuthManager not initialized");return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(t){try{const e=r.TEST,i="openfort_storage_test";t.save(e,i);const n=await t.get(e);return t.remove(e),n===i}catch(t){return!1}}async initializeAsync(){if(!await y.isStorageAccessible(this.storage))throw new f("Storage is not accessible",d.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}export{y as Openfort};
1
+ import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{AuthApi as t}from"../api/auth.js";import{EmbeddedWalletApi as i}from"../api/embeddedWallet.js";import{ProxyApi as n}from"../api/proxy.js";import{UserApi as a}from"../api/user.js";import{AuthManager as s}from"../auth/authManager.js";import{StorageKeys as r}from"../storage/istorage.js";import{LazyStorage as o}from"../storage/lazyStorage.js";import h from"../utils/typedEventEmitter.js";import{SDKConfiguration as l}from"./config/config.js";import{OPENFORT_AUTH_ERROR_CODES as d,OPENFORT_ERROR_CODES as c}from"./errors/authErrorCodes.js";import{ConfigurationError as u,SignerError as g,RequestError as m,OpenfortError as f}from"./errors/openfortError.js";import{InternalSentry as p}from"./errors/sentry.js";import{OpenfortInternal as I}from"./openfortInternal.js";import{PasskeyHandler as w}from"./passkey/handler.js";class y{storage;iAuthManager=null;openfortInternal;initPromise;asyncInitPromise=null;authInstance;embeddedWalletInstance;userInstance;proxyInstance;configuration;eventEmitter;iPasskeyHandler;static globalEventEmitter=null;get auth(){if(!this.authInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.");return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.");return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.");return this.userInstance}get proxy(){if(!this.proxyInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.");return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new s,this.openfortInternal=new I(this.storage,this.authManager,this.eventEmitter),this.authInstance=new t(this.storage,this.authManager,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter),this.embeddedWalletInstance=new i(this.storage,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter,this.passkeyHandler),this.userInstance=new a(this.storage,this.authManager,this.validateAndRefreshToken.bind(this)),this.proxyInstance=new n(this.storage,this.backendApiClients,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),async()=>{if(!this.embeddedWalletInstance)throw new g(d.MISSING_SIGNER,"Embedded wallet not initialized");const e=this.embeddedWalletInstance;return t=>e.signMessage(t,{hashMessage:!0,arrayifyMessage:!0})})}catch(e){throw new u("Openfort SDK synchronous initialization failed")}}constructor(e){if(this.configuration=new l(e),this.storage=new o(this.configuration.baseConfiguration.publishableKey,this.configuration.storage),this.eventEmitter=new h,y.globalEventEmitter){["onAuthInit","onAuthSuccess","onAuthFailure","onLogout","onSwitchAccount","onSignedMessage","onEmbeddedWalletCreated","onEmbeddedWalletRecovered","onAuthFlowOpen","onAuthFlowClose","onAuthFlowCancel"].forEach(e=>{this.eventEmitter.on(e,(...t)=>{y.globalEventEmitter?.emit(e,...t)})})}else y.globalEventEmitter=this.eventEmitter;this.iPasskeyHandler=e.overrides?.passkeyHandler??new w({rpId:e.shieldConfiguration?.passkeyRpId,rpName:e.shieldConfiguration?.passkeyRpName,displayName:e.shieldConfiguration?.passkeyDisplayName}),p.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}static getEventEmitter(){return y.globalEventEmitter||(y.globalEventEmitter=new h),y.globalEventEmitter}async waitForInitialization(){await this.initPromise,await this.ensureAsyncInitialized()}async getAccessToken(){return await this.ensureInitialized(),this.openfortInternal.getAccessToken()}async validateAndRefreshToken(e){return await this.ensureInitialized(),await this.openfortInternal.validateAndRefreshToken(e)}get backendApiClients(){return new e({basePath:this.configuration.backendUrl,accessToken:this.configuration.baseConfiguration.publishableKey,nativeAppIdentifier:this.configuration.nativeAppIdentifier,storage:this.storage,onLogout:()=>{this.eventEmitter.emit("onLogout")}})}get authManager(){if(!this.iAuthManager)throw new m("AuthManager not initialized");return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(e){try{const t=r.TEST,i="openfort_storage_test";e.save(t,i);const n=await e.get(t);return e.remove(t),n===i}catch(e){return!1}}async initializeAsync(){if(!await y.isStorageAccessible(this.storage))throw new f("Storage is not accessible",c.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}export{y as Openfort};
@@ -1 +1 @@
1
- import{humanId as e}from"human-id";import{PasskeyPRFNotSupportedError as t,PasskeySeedInvalidError as r,PasskeyUserCancelledError as i,PasskeyCreationFailedError as n,PasskeyAssertionFailedError as s}from"./errors.js";import{arrayBufferToBase64URL as o,base64ToArrayBuffer as a}from"./utils.js";class d{validByteLengths=[16,24,32];rpId;rpName;timeoutMs;derivedKeyLengthBytes;constructor({rpId:e,rpName:t,timeoutMs:r,derivedKeyLengthBytes:i}={}){if(this.rpId=e,this.rpName=t,this.timeoutMs=r??6e4,this.derivedKeyLengthBytes=i??32,!this.validByteLengths.includes(this.derivedKeyLengthBytes))throw new Error(`Invalid key byte length ${this.derivedKeyLengthBytes}`)}static randomPasskeyName(){return e({capitalize:!0,separator:" "})}getChallengeBytes(){return crypto.getRandomValues(new Uint8Array(32))}async deriveKeyFromAssertion(e){const r=e.getClientExtensionResults();if(!r)throw new t("Passkey fetch failed: no client extension results");const i=r.prf;if(!i||!i.results)throw new t("PRF extension not supported or missing results");const n=i.results.first,s=await crypto.subtle.importKey("raw",n,{name:"AES-CBC",length:this.derivedKeyLengthBytes},!0,["encrypt","decrypt"]);return crypto.subtle.exportKey("raw",s)}async createPasskey({id:e,displayName:s,seed:a}){if(!a||0===a.trim().length)throw new r;const d={challenge:this.getChallengeBytes(),rp:{id:this.rpId,name:this.rpName},user:{id:(new TextEncoder).encode(e),name:e,displayName:s},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{residentKey:"required",userVerification:"required"},extensions:{prf:{eval:{first:(new TextEncoder).encode(a)}}},timeout:this.timeoutMs,attestation:"direct"};let c,l;try{c=await navigator.credentials.create({publicKey:d})}catch(e){if(e instanceof Error&&"NotAllowedError"===e.name)throw new i;throw new n(e instanceof Error?e.message:"Unknown error",e instanceof Error?e:void 0)}if(!c)throw new i;try{l=await this.deriveKeyFromAssertion(c)}catch(e){throw e instanceof t&&console.warn(`[Openfort] Passkey created but PRF extension failed. A passkey credential may exist on the device that cannot be used for wallet recovery. Credential ID: ${o(c.rawId)}`),e}return{id:o(c.rawId),displayName:s,key:o(l)}}async deriveAndExportKey({id:e,seed:t}){if(!t||0===t.trim().length)throw new r;let n;try{n=await navigator.credentials.get({publicKey:{challenge:this.getChallengeBytes(),rpId:this.rpId,allowCredentials:[{id:a(e),type:"public-key"}],userVerification:"required",extensions:{prf:{eval:{first:(new TextEncoder).encode(t)}}}}})}catch(e){if(e instanceof Error&&"NotAllowedError"===e.name)throw new i;throw new s(e instanceof Error?e.message:"Unknown error",e instanceof Error?e:void 0)}if(!n)throw new i;const d=await this.deriveKeyFromAssertion(n);return o(d)}}export{d as PasskeyHandler};
1
+ import{humanId as e}from"human-id";import{PasskeyPRFNotSupportedError as t,PasskeySeedInvalidError as r,PasskeyUserCancelledError as i,PasskeyCreationFailedError as s,PasskeyAssertionFailedError as n}from"./errors.js";import{DEFAULT_PASSKEY_DISPLAY_NAME as a}from"./types.js";import{arrayBufferToBase64URL as o,base64ToArrayBuffer as d}from"./utils.js";class l{validByteLengths=[16,24,32];rpId;rpName;displayName;timeoutMs;derivedKeyLengthBytes;constructor({rpId:e,rpName:t,displayName:r,timeoutMs:i,derivedKeyLengthBytes:s}={}){if(this.rpId=e,this.rpName=t,this.displayName=r??a,this.timeoutMs=i??6e4,this.derivedKeyLengthBytes=s??32,!this.validByteLengths.includes(this.derivedKeyLengthBytes))throw new Error(`Invalid key byte length ${this.derivedKeyLengthBytes}`)}static randomPasskeyName(){return e({capitalize:!0,separator:" "})}getChallengeBytes(){return crypto.getRandomValues(new Uint8Array(32))}async deriveKeyFromAssertion(e){const r=e.getClientExtensionResults();if(!r)throw new t("Passkey fetch failed: no client extension results");const i=r.prf;if(!i||!i.results)throw new t("PRF extension not supported or missing results");const s=i.results.first,n=await crypto.subtle.importKey("raw",s,{name:"AES-CBC",length:this.derivedKeyLengthBytes},!0,["encrypt","decrypt"]);return crypto.subtle.exportKey("raw",n)}async createPasskey({id:e,seed:n}){if(!n||0===n.trim().length)throw new r;const a={challenge:this.getChallengeBytes(),rp:{id:this.rpId,name:this.rpName},user:{id:(new TextEncoder).encode(e),name:e,displayName:this.displayName},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{residentKey:"required",userVerification:"required"},extensions:{prf:{eval:{first:(new TextEncoder).encode(n)}}},timeout:this.timeoutMs,attestation:"direct"};let d,l;try{d=await navigator.credentials.create({publicKey:a})}catch(e){if(e instanceof Error&&"NotAllowedError"===e.name)throw new i;throw new s(e instanceof Error?e.message:"Unknown error",e instanceof Error?e:void 0)}if(!d)throw new i;try{l=await this.deriveKeyFromAssertion(d)}catch(e){throw e instanceof t&&console.warn(`[Openfort] Passkey created but PRF extension failed. A passkey credential may exist on the device that cannot be used for wallet recovery. Credential ID: ${o(d.rawId)}`),e}return{id:o(d.rawId),displayName:this.displayName,key:o(l)}}async deriveAndExportKey({id:e,seed:t}){if(!t||0===t.trim().length)throw new r;let s;try{s=await navigator.credentials.get({publicKey:{challenge:this.getChallengeBytes(),rpId:this.rpId,allowCredentials:[{id:d(e),type:"public-key"}],userVerification:"required",extensions:{prf:{eval:{first:(new TextEncoder).encode(t)}}}}})}catch(e){if(e instanceof Error&&"NotAllowedError"===e.name)throw new i;throw new n(e instanceof Error?e.message:"Unknown error",e instanceof Error?e:void 0)}if(!s)throw new i;const a=await this.deriveKeyFromAssertion(s);return o(a)}}export{l as PasskeyHandler};
@@ -0,0 +1 @@
1
+ const e="Openfort - Embedded Wallet";export{e as DEFAULT_PASSKEY_DISPLAY_NAME};
@@ -1 +1 @@
1
- function r(r){const t=r instanceof Uint8Array?r:new Uint8Array(r);let e="";for(const r of t)e+=String.fromCharCode(r);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function t(r){const t=atob(r),e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e.buffer}export{r as arrayBufferToBase64URL,t as base64ToArrayBuffer};
1
+ function e(e){const r=e instanceof Uint8Array?e:new Uint8Array(e);let t="";for(const e of r)t+=String.fromCharCode(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function r(e){const r=e.replace(/-/g,"+").replace(/_/g,"/"),t=r+"=".repeat((4-r.length%4)%4),n=atob(t),o=new Uint8Array(n.length);for(let e=0;e<n.length;e++)o[e]=n.charCodeAt(e);return o.buffer}export{e as arrayBufferToBase64URL,r as base64ToArrayBuffer};
@@ -1 +1 @@
1
- const o="1.1.6",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
1
+ const o="1.2.0",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
@@ -1 +1 @@
1
- import{Authentication as e}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as t}from"../core/errors/authErrorCodes.js";import{SessionError as a,ConfigurationError as r}from"../core/errors/openfortError.js";import{withApiError as o}from"../core/errors/withApiError.js";import{PasskeyHandler as s}from"../core/passkey/handler.js";import{SDKConfiguration as n}from"../core/config/config.js";import{Account as i}from"../core/configuration/account.js";import{StorageKeys as c}from"../storage/istorage.js";import{OpenfortEvents as d,AccountTypeEnum as y}from"../types/types.js";class p{iframeManager;storage;backendApiClients;passkeyHandler;eventEmitter;constructor(e,t,a,r,o){this.iframeManager=e,this.storage=t,this.backendApiClients=a,this.passkeyHandler=r,this.eventEmitter=o}async createPasskey(e){const t=await this.passkeyHandler.createPasskey({id:s.randomPasskeyName(),displayName:n.getInstance()?.passkeyDisplayName??"Openfort - Embedded Wallet",seed:e});return{id:t.id,key:t.key}}async configure(s){const c=await e.fromStorage(this.storage);if(!c)throw new a(t.NOT_LOGGED_IN,"No access token found");const y=n.getInstance();if(!y)throw new r("Configuration not found");const p=await i.fromStorage(this.storage);let h;if(p){const e={account:p.id,...s.entropy&&{entropy:{...s.entropy.recoveryPassword&&{recoveryPassword:s.entropy.recoveryPassword},...s.entropy.encryptionSession&&{encryptionSession:s.entropy.encryptionSession},..."passkey"===p.recoveryMethod&&{passkey:{id:p.recoveryMethodDetails?.passkeyId,env:p.recoveryMethodDetails?.passkeyEnv,key:await s.getPasskeyKeyFn(p.recoveryMethodDetails?.passkeyId??"")}}}}},t=await this.iframeManager.recover(e);h=t.account}else{const e=await this.backendApiClients.accountsV2Api.getAccountsV2({accountType:s.accountType,chainType:s.chainType},{headers:c.thirdPartyProvider?{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}:{authorization:`Bearer ${c.token}`,"x-project-key":y.baseConfiguration.publishableKey}});if(0===e.data.data.length){const e=s.entropy?.passkey?await this.createPasskey(c.userId):void 0,t={accountType:s.accountType,chainType:s.chainType,chainId:s.chainId,...s.entropy&&{entropy:{...s.entropy.recoveryPassword&&{recoveryPassword:s.entropy.recoveryPassword},...s.entropy.encryptionSession&&{encryptionSession:s.entropy.encryptionSession},...s.entropy.passkey&&{passkey:e}}}},a=await this.iframeManager.create(t);h=a.account}else{const t=e.data.data,a=t.find(e=>e.chainId===s.chainId),r=a||t[0],o={account:r.id,...s.entropy&&{entropy:{...s.entropy.recoveryPassword&&{recoveryPassword:s.entropy.recoveryPassword},...s.entropy.encryptionSession&&{encryptionSession:s.entropy.encryptionSession},..."passkey"===r.recoveryMethod&&{passkey:{id:r.recoveryMethodDetails?.passkeyId,env:r.recoveryMethodDetails?.passkeyEnv,key:await s.getPasskeyKeyFn(r.recoveryMethodDetails?.passkeyId??"")}}}}},n=await this.iframeManager.recover(o);if(h=n.account,!a){const e=await this.iframeManager.switchChain(s.chainId);h=e.account}}}return o(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:h},{headers:c.thirdPartyProvider?{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}:{authorization:`Bearer ${c.token}`,"x-project-key":y.baseConfiguration.publishableKey}}),t=new i({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:i.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(d.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"configure"})}async sign(e,t,a,r){const o=await this.iframeManager.sign(e,t,a,r);return this.eventEmitter.emit(d.ON_SIGNED_MESSAGE,{message:e,signature:o}),o}async export(){return await this.iframeManager.export()}async switchChain({chainId:e}){const t=await i.fromStorage(this.storage);if(t?.accountType===y.EOA)new i({...t,chainId:e}).save(this.storage);else{const a=await this.iframeManager.switchChain(e);new i({...t,id:a.account,chainId:e}).save(this.storage)}}async create(s){const c=await this.iframeManager.create(s),y=await e.fromStorage(this.storage);if(!y)throw new a(t.NOT_LOGGED_IN,"No access token found");const p=n.getInstance();if(!p)throw new r("Configuration not found");return o(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:c.account},{headers:y.thirdPartyProvider?{authorization:`Bearer ${p.baseConfiguration.publishableKey}`,"x-player-token":y.token,"x-auth-provider":y.thirdPartyProvider,"x-token-type":y.thirdPartyTokenType}:{authorization:`Bearer ${y.token}`,"x-project-key":p.baseConfiguration.publishableKey}}),t=new i({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,implementationAddress:e.data.smartAccount?.implementationAddress,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:i.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(d.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"create"})}async recover(s){const c=await this.iframeManager.recover(s),y=await e.fromStorage(this.storage);if(!y)throw new a(t.NOT_LOGGED_IN,"No access token found");const p=n.getInstance();if(!p)throw new r("Configuration not found");return o(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:c.account},{headers:y.thirdPartyProvider?{authorization:`Bearer ${p.baseConfiguration.publishableKey}`,"x-player-token":y.token,"x-auth-provider":y.thirdPartyProvider,"x-token-type":y.thirdPartyTokenType}:{authorization:`Bearer ${y.token}`,"x-project-key":p.baseConfiguration.publishableKey}}),t=new i({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:i.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(d.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"recover"})}async setRecoveryMethod({recoveryMethod:e,recoveryPassword:t,encryptionSession:a,passkeyInfo:r}){await this.iframeManager.setRecoveryMethod(e,t,a,r?.passkeyKey,r?.passkeyId)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(c.ACCOUNT)}}export{p as EmbeddedSigner};
1
+ import{Authentication as e}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as t}from"../core/errors/authErrorCodes.js";import{SessionError as a,ConfigurationError as r}from"../core/errors/openfortError.js";import{withApiError as o}from"../core/errors/withApiError.js";import{PasskeyHandler as s}from"../core/passkey/handler.js";import{SDKConfiguration as n}from"../core/config/config.js";import{Account as i}from"../core/configuration/account.js";import{StorageKeys as c}from"../storage/istorage.js";import{OpenfortEvents as d,AccountTypeEnum as y}from"../types/types.js";class p{iframeManager;storage;backendApiClients;passkeyHandler;eventEmitter;constructor(e,t,a,r,o){this.iframeManager=e,this.storage=t,this.backendApiClients=a,this.passkeyHandler=r,this.eventEmitter=o}async createPasskey(e){const t=await this.passkeyHandler.createPasskey({id:s.randomPasskeyName(),seed:e});return{id:t.id,key:t.key}}async configure(s){const c=await e.fromStorage(this.storage);if(!c)throw new a(t.NOT_LOGGED_IN,"No access token found");const y=n.getInstance();if(!y)throw new r("Configuration not found");const p=await i.fromStorage(this.storage);let h;if(p){const e={account:p.id,...s.entropy&&{entropy:{...s.entropy.recoveryPassword&&{recoveryPassword:s.entropy.recoveryPassword},...s.entropy.encryptionSession&&{encryptionSession:s.entropy.encryptionSession},..."passkey"===p.recoveryMethod&&{passkey:{id:p.recoveryMethodDetails?.passkeyId,env:p.recoveryMethodDetails?.passkeyEnv,key:await s.getPasskeyKeyFn(p.recoveryMethodDetails?.passkeyId??"")}}}}},t=await this.iframeManager.recover(e);h=t.account}else{const e=await this.backendApiClients.accountsV2Api.getAccountsV2({accountType:s.accountType,chainType:s.chainType},{headers:c.thirdPartyProvider?{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}:{authorization:`Bearer ${c.token}`,"x-project-key":y.baseConfiguration.publishableKey}});if(0===e.data.data.length){const e=s.entropy?.passkey?await this.createPasskey(c.userId):void 0,t={accountType:s.accountType,chainType:s.chainType,chainId:s.chainId,...s.entropy&&{entropy:{...s.entropy.recoveryPassword&&{recoveryPassword:s.entropy.recoveryPassword},...s.entropy.encryptionSession&&{encryptionSession:s.entropy.encryptionSession},...s.entropy.passkey&&{passkey:e}}}},a=await this.iframeManager.create(t);h=a.account}else{const t=e.data.data,a=t.find(e=>e.chainId===s.chainId),r=a||t[0],o={account:r.id,...s.entropy&&{entropy:{...s.entropy.recoveryPassword&&{recoveryPassword:s.entropy.recoveryPassword},...s.entropy.encryptionSession&&{encryptionSession:s.entropy.encryptionSession},..."passkey"===r.recoveryMethod&&{passkey:{id:r.recoveryMethodDetails?.passkeyId,env:r.recoveryMethodDetails?.passkeyEnv,key:await s.getPasskeyKeyFn(r.recoveryMethodDetails?.passkeyId??"")}}}}},n=await this.iframeManager.recover(o);if(h=n.account,!a){const e=await this.iframeManager.switchChain(s.chainId);h=e.account}}}return o(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:h},{headers:c.thirdPartyProvider?{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}:{authorization:`Bearer ${c.token}`,"x-project-key":y.baseConfiguration.publishableKey}}),t=new i({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:i.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(d.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"configure"})}async sign(e,t,a,r){const o=await this.iframeManager.sign(e,t,a,r);return this.eventEmitter.emit(d.ON_SIGNED_MESSAGE,{message:e,signature:o}),o}async export(){return await this.iframeManager.export()}async switchChain({chainId:e}){const t=await i.fromStorage(this.storage);if(t?.accountType===y.EOA)new i({...t,chainId:e}).save(this.storage);else{const a=await this.iframeManager.switchChain(e);new i({...t,id:a.account,chainId:e}).save(this.storage)}}async create(s){const c=await this.iframeManager.create(s),y=await e.fromStorage(this.storage);if(!y)throw new a(t.NOT_LOGGED_IN,"No access token found");const p=n.getInstance();if(!p)throw new r("Configuration not found");return o(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:c.account},{headers:y.thirdPartyProvider?{authorization:`Bearer ${p.baseConfiguration.publishableKey}`,"x-player-token":y.token,"x-auth-provider":y.thirdPartyProvider,"x-token-type":y.thirdPartyTokenType}:{authorization:`Bearer ${y.token}`,"x-project-key":p.baseConfiguration.publishableKey}}),t=new i({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,implementationAddress:e.data.smartAccount?.implementationAddress,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:i.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(d.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"create"})}async recover(s){const c=await this.iframeManager.recover(s),y=await e.fromStorage(this.storage);if(!y)throw new a(t.NOT_LOGGED_IN,"No access token found");const p=n.getInstance();if(!p)throw new r("Configuration not found");return o(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:c.account},{headers:y.thirdPartyProvider?{authorization:`Bearer ${p.baseConfiguration.publishableKey}`,"x-player-token":y.token,"x-auth-provider":y.thirdPartyProvider,"x-token-type":y.thirdPartyTokenType}:{authorization:`Bearer ${y.token}`,"x-project-key":p.baseConfiguration.publishableKey}}),t=new i({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:i.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(d.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"recover"})}async setRecoveryMethod({recoveryMethod:e,recoveryPassword:t,encryptionSession:a,passkeyInfo:r}){await this.iframeManager.setRecoveryMethod(e,t,a,r?.passkeyKey,r?.passkeyId)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(c.ACCOUNT)}}export{p as EmbeddedSigner};
@@ -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{RecoveryError as n,SignerError as r,OpenfortError 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 f from"./messaging/browserMessenger/connect.js";import"./messaging/browserMessenger/backwardCompatibility.js";import{isErrorResponse as y,NOT_CONFIGURED_ERROR as g,MISSING_USER_ENTROPY_ERROR as p,MISSING_PROJECT_ENTROPY_ERROR as m,INCORRECT_USER_ENTROPY_ERROR as w,MISSING_PASSKEY_ERROR as C,INCORRECT_PASSKEY_ERROR as v,OTP_REQUIRED_ERROR as k,ShieldAuthType as I,Event as P,SignRequest as R,SwitchChainRequest as b,ExportPrivateKeyRequest as E,SetRecoveryMethodRequest as T,GetCurrentDeviceRequest as S,UpdateAuthenticationRequest as N}from"./types.js";class A extends n{constructor(){super(t.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class O extends n{constructor(){super(t.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class U extends n{constructor(){super(t.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class z extends n{constructor(){super(t.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class D extends r{constructor(){super(t.NOT_CONFIGURED,"Signer is not configured")}}class K extends o{constructor(){super(t.OTP_REQUIRED,"OTP verification required")}}class M{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;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}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new o(t.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){u("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:u}),this.connection=f({messenger:this.messenger,timeout:1e4,log:u});try{this.remote=await this.connection.promise,u("IframeManager connection established")}catch(e){const i=e;throw d.captureException(i),this.destroy(),u("Failed to establish connection:",i),new o(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 `)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new o(t.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(y(e)){if(e.error===g)throw this.storage.remove(c.ACCOUNT),new D;if(e.error===p)throw this.storage.remove(c.ACCOUNT),new A;if(e.error===m)throw this.storage.remove(c.ACCOUNT),new U;if(e.error===w)throw new z;if(e.error===C)throw this.storage.remove(c.ACCOUNT),new A;if(e.error===v)throw new O;if(e.error===k)throw new K;throw this.storage.remove(c.ACCOUNT),new o(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:I.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(t.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:I.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:P.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 y(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:P.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 y(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 R(h(),e,await this.buildRequestConfiguration(),i,t,n);u("[iframe] done ensureConnection");const s=await r.sign(o);return u("[iframe] response",s),y(s)&&this.handleError(s),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",s.version??"undefined"),s.signature}async switchChain(e){const i=await this.ensureConnection(),t=new b(h(),e,await this.buildRequestConfiguration()),n=await i.switchChain(t);return y(n)&&this.handleError(n),n}async export(){const e=await this.ensureConnection(),i=new E(h(),await this.buildRequestConfiguration()),t=await e.export(i);return y(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 T(h(),e,await this.buildRequestConfiguration(),i,t,n,r),a=await o.setRecoveryMethod(s);y(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),t=new S(h(),e);try{const e=await i.getCurrentDevice(t);return y(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof D)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 N(h(),e.token);u("Updating authentication in iframe with token");const n=await this.remote.updateAuthentication(t);y(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.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}}export{M as IframeManager,U as MissingProjectEntropyError,A as MissingRecoveryPasswordError,D as NotConfiguredError,K as OTPRequiredError,O as WrongPasskeyError,z 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{RecoveryError as n,SignerError as r,OpenfortError 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 f from"./messaging/browserMessenger/connect.js";import"./messaging/browserMessenger/backwardCompatibility.js";import{isErrorResponse as y,NOT_CONFIGURED_ERROR as g,MISSING_USER_ENTROPY_ERROR as p,MISSING_PROJECT_ENTROPY_ERROR as m,INCORRECT_USER_ENTROPY_ERROR as w,MISSING_PASSKEY_ERROR as C,INCORRECT_PASSKEY_ERROR as v,OTP_REQUIRED_ERROR as k,ShieldAuthType as I,Event as P,SignRequest as R,SwitchChainRequest as b,ExportPrivateKeyRequest as E,SetRecoveryMethodRequest as T,GetCurrentDeviceRequest as S,UpdateAuthenticationRequest as N}from"./types.js";class A extends n{constructor(){super(t.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class O extends n{constructor(){super(t.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class U extends n{constructor(){super(t.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class z extends n{constructor(){super(t.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class D extends r{constructor(){super(t.NOT_CONFIGURED,"Signer is not configured")}}class M extends o{constructor(){super(t.OTP_REQUIRED,"OTP verification required")}}class K{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;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}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new o(t.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){u("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:u}),this.connection=f({messenger:this.messenger,timeout:1e4,log:u});try{this.remote=await this.connection.promise,u("IframeManager connection established")}catch(e){const i=e;throw d.captureException(i),this.destroy(),u("Failed to establish connection:",i),new o(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 `)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new o(t.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(y(e)){if(e.error===g)throw this.storage.remove(c.ACCOUNT),new D;if(e.error===p)throw this.storage.remove(c.ACCOUNT),new A;if(e.error===m)throw this.storage.remove(c.ACCOUNT),new U;if(e.error===w)throw new z;if(e.error===C)throw this.storage.remove(c.ACCOUNT),new A;if(e.error===v)throw new O;if(e.error===k)throw new M;throw this.storage.remove(c.ACCOUNT),new o(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:I.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:I.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:P.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 y(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:P.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 y(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 R(h(),e,await this.buildRequestConfiguration(),i,t,n);u("[iframe] done ensureConnection");const s=await r.sign(o);return u("[iframe] response",s),y(s)&&this.handleError(s),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",s.version??"undefined"),s.signature}async switchChain(e){const i=await this.ensureConnection(),t=new b(h(),e,await this.buildRequestConfiguration()),n=await i.switchChain(t);return y(n)&&this.handleError(n),n}async export(){const e=await this.ensureConnection(),i=new E(h(),await this.buildRequestConfiguration()),t=await e.export(i);return y(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 T(h(),e,await this.buildRequestConfiguration(),i,t,n,r),a=await o.setRecoveryMethod(s);y(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),t=new S(h(),e);try{const e=await i.getCurrentDevice(t);return y(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof D)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 N(h(),e.token);u("Updating authentication in iframe with token");const n=await this.remote.updateAuthentication(t);y(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.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}}export{K as IframeManager,U as MissingProjectEntropyError,A as MissingRecoveryPasswordError,D as NotConfiguredError,M as OTPRequiredError,O as WrongPasskeyError,z as WrongRecoveryPasswordError};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfort/openfort-js",
3
- "version": "1.1.6",
3
+ "version": "1.2.0",
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",