@openfort/openfort-js 1.0.1 → 1.0.3

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/configuration/passkey.cjs"),t=require("../core/config/config.cjs"),s=require("../core/configuration/account.cjs"),a=require("../core/configuration/authentication.cjs"),i=require("../core/errors/authErrorCodes.cjs"),n=require("../core/errors/openfortError.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"),m=require("../wallets/iframeManager.cjs"),l=require("../wallets/messaging/ReactNativeMessenger.cjs");require("../wallets/messaging/browserMessenger/backwardCompatibility.cjs");var p=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 r=t.SDKConfiguration.getInstance();if(!r)throw new n.ConfigurationError("Configuration not found");return new e.BackendApiClients({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey,nativeAppIdentifier:r.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=t.SDKConfiguration.getInstance();if(!e)throw c.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new n.ConfigurationError("Configuration not found");let r;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 l.ReactNativeMessenger(this.messagePoster),c.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{c.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;r=new p({remoteWindow:t.contentWindow,allowedOrigins:[s]}),c.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return c.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new m.IframeManager(e,this.storage,r)}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();return new g.EmbeddedSigner(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new n.ConfigurationError("Document is not available. Please provide a message poster for non-browser environments.");const r=document.getElementById("openfort-iframe");r&&r.remove();const t=document.createElement("iframe");return t.style.display="none",t.id="openfort-iframe",t.src=e,document.body.appendChild(t),t}async getPasskeyKey(e){const r=await a.Authentication.fromStorage(this.storage);return await this.passkeyHandler.deriveAndExportKey({id:e,seed:r?.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 n.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,user:n.user,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 t=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC},o=await a.Authentication.fromStorage(this.storage);if(!o)throw new n.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(t.recoveryMethod===d.RecoveryMethod.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:o?.userId});t.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[c,g]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),h=await c.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:g}),u={id:h.id,chainId:h.chainId,user:o?.userId,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:s.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 r=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC};if(r.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!r.passkeyInfo?.passkeyId)throw new n.ConfigurationError("Passkey ID must be provided for passkey recovery");r.passkeyInfo={passkeyId:r.passkeyInfo.passkeyId}}const[t,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i=await t.recover({account:e.account,entropy:a}),o={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,user:i.user,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:s.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.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,r,t){await this.validateAndRefreshToken();const a=await this.ensureSigner(),o=await s.Account.fromStorage(this.storage);if(!o)throw new n.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No account found");const d={...r};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),g=c.hash(e,d,t);return await y.signMessage({hash:g,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:a,address:o.address,ownerAddress:o.ownerAddress,factoryAddress:o.factoryAddress,salt:o.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,t){await this.validateAndRefreshToken();const o=await this.ensureSigner(),c=await a.Authentication.fromStorage(this.storage);if(!c)throw new n.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");let g,h,u,y;if(e.recoveryMethod===d.RecoveryMethod.PASSKEY){const e=await s.Account.fromStorage(this.storage);if(!e)throw new n.ConfigurationError("missing account");const r=e?.recoveryMethodDetails?.passkeyId;if(!r)throw new n.ConfigurationError("missing passkey id for account");u={passkeyId:r,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:r,seed:c.userId})}}else if(t.recoveryMethod===d.RecoveryMethod.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:c.userId});u={passkeyId:e.id,passkeyKey:e.key},y={passkeyId:e.id}}if(e.recoveryMethod===d.RecoveryMethod.PASSWORD?g=e.password:t.recoveryMethod===d.RecoveryMethod.PASSWORD&&(g=t.password),e.recoveryMethod===d.RecoveryMethod.AUTOMATIC?h=e.encryptionSession:t.recoveryMethod===d.RecoveryMethod.AUTOMATIC&&(h=t.encryptionSession),!g&&!h)throw new n.ConfigurationError("Password or encryption session is not provided");await o.setRecoveryMethod({recoveryMethod:t.recoveryMethod,recoveryPassword:g,encryptionSession:h,passkeyInfo:u});const m=await s.Account.fromStorage(this.storage);m&&new s.Account({...m,recoveryMethod:t.recoveryMethod,recoveryMethodDetails:y}).save(this.storage)}async get(){const e=await s.Account.fromStorage(this.storage);if(!e)throw new n.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No signer configured");const r=await a.Authentication.fromStorage(this.storage);if(!r)throw new n.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,user:r.userId,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){const r={accountType:d.AccountTypeEnum.SMART_ACCOUNT,...e},c=t.SDKConfiguration.getInstance();if(!c)throw new n.ConfigurationError("Configuration not found");const g=await a.Authentication.fromStorage(this.storage);if(!g)throw new n.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),o.withApiError(async()=>(await this.backendApiClients.accountsApi.getAccountsV2(r,{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=>({user:e.user,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 a.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 a.Authentication.fromStorage(this.storage),i=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:i||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 a.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=t.SDKConfiguration.getInstance();if(!e)throw new n.ConfigurationError("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new n.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(){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/configuration/passkey.cjs"),t=require("../core/config/config.cjs"),s=require("../core/configuration/account.cjs"),a=require("../core/configuration/authentication.cjs"),i=require("../core/errors/authErrorCodes.cjs"),n=require("../core/errors/openfortError.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 p=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 r=t.SDKConfiguration.getInstance();if(!r)throw new n.ConfigurationError("Configuration not found");return new e.BackendApiClients({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey,nativeAppIdentifier:r.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=t.SDKConfiguration.getInstance();if(!e)throw c.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new n.ConfigurationError("Configuration not found");let r;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"),r=this.messenger;else{c.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;r=new p({remoteWindow:t.contentWindow,allowedOrigins:[s]}),c.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return c.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new l.IframeManager(e,this.storage,r)}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();return new g.EmbeddedSigner(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new n.ConfigurationError("Document is not available. Please provide a message poster for non-browser environments.");const r=document.getElementById("openfort-iframe");r&&r.remove();const t=document.createElement("iframe");return t.style.display="none",t.id="openfort-iframe",t.src=e,document.body.appendChild(t),t}async getPasskeyKey(e){const r=await a.Authentication.fromStorage(this.storage);return await this.passkeyHandler.deriveAndExportKey({id:e,seed:r?.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 n.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,user:n.user,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 t=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC},o=await a.Authentication.fromStorage(this.storage);if(!o)throw new n.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(t.recoveryMethod===d.RecoveryMethod.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:o?.userId});t.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[c,g]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),h=await c.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:g}),u={id:h.id,chainId:h.chainId,user:o?.userId,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:s.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 r=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC};if(r.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!r.passkeyInfo?.passkeyId)throw new n.ConfigurationError("Passkey ID must be provided for passkey recovery");r.passkeyInfo={passkeyId:r.passkeyInfo.passkeyId}}const[t,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i=await t.recover({account:e.account,entropy:a}),o={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,user:i.user,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:s.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.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,r,t){await this.validateAndRefreshToken();const a=await this.ensureSigner(),o=await s.Account.fromStorage(this.storage);if(!o)throw new n.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No account found");const d={...r};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),g=c.hash(e,d,t);return await y.signMessage({hash:g,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:a,address:o.address,ownerAddress:o.ownerAddress,factoryAddress:o.factoryAddress,salt:o.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,t){await this.validateAndRefreshToken();const o=await this.ensureSigner(),c=await a.Authentication.fromStorage(this.storage);if(!c)throw new n.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");let g,h,u,y;if(e.recoveryMethod===d.RecoveryMethod.PASSKEY){const e=await s.Account.fromStorage(this.storage);if(!e)throw new n.ConfigurationError("missing account");const r=e?.recoveryMethodDetails?.passkeyId;if(!r)throw new n.ConfigurationError("missing passkey id for account");u={passkeyId:r,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:r,seed:c.userId})}}else if(t.recoveryMethod===d.RecoveryMethod.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:c.userId});u={passkeyId:e.id,passkeyKey:e.key},y={passkeyId:e.id}}if(e.recoveryMethod===d.RecoveryMethod.PASSWORD?g=e.password:t.recoveryMethod===d.RecoveryMethod.PASSWORD&&(g=t.password),e.recoveryMethod===d.RecoveryMethod.AUTOMATIC?h=e.encryptionSession:t.recoveryMethod===d.RecoveryMethod.AUTOMATIC&&(h=t.encryptionSession),!g&&!h)throw new n.ConfigurationError("Password or encryption session is not provided");await o.setRecoveryMethod({recoveryMethod:t.recoveryMethod,recoveryPassword:g,encryptionSession:h,passkeyInfo:u});const l=await s.Account.fromStorage(this.storage);l&&new s.Account({...l,recoveryMethod:t.recoveryMethod,recoveryMethodDetails:y}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await s.Account.fromStorage(this.storage);if(!e)throw new n.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No signer configured");const r=await a.Authentication.fromStorage(this.storage);if(!r)throw new n.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,user:r.userId,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 r={accountType:d.AccountTypeEnum.SMART_ACCOUNT,...e},c=t.SDKConfiguration.getInstance();if(!c)throw new n.ConfigurationError("Configuration not found");const g=await a.Authentication.fromStorage(this.storage);if(!g)throw new n.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),o.withApiError(async()=>(await this.backendApiClients.accountsApi.getAccountsV2(r,{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=>({user:e.user,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 a.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 a.Authentication.fromStorage(this.storage),i=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:i||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 a.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=t.SDKConfiguration.getInstance();if(!e)throw new n.ConfigurationError("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new n.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(){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 +1 @@
1
- "use strict";var t=require("../core/configuration/authentication.cjs"),e=require("../core/errors/authErrorCodes.cjs"),r=require("../core/errors/openfortError.cjs");exports.UserApi=class{storage;authManager;validateAndRefreshToken;constructor(t,e,r){this.storage=t,this.authManager=e,this.validateAndRefreshToken=r}async get(){await this.validateAndRefreshToken();const a=await t.Authentication.fromStorage(this.storage);if(!a)throw new r.SessionError(e.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return await this.authManager.getUser(a)}async list(){await this.validateAndRefreshToken();const a=await t.Authentication.fromStorage(this.storage);if(!a)throw new r.SessionError(e.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return await this.authManager.listAccounts(a)}};
1
+ "use strict";var r=require("../core/configuration/authentication.cjs"),e=require("../core/errors/authErrorCodes.cjs"),t=require("../core/errors/openfortError.cjs");exports.UserApi=class{storage;authManager;validateAndRefreshToken;constructor(r,e,t){this.storage=r,this.authManager=e,this.validateAndRefreshToken=t}async get(){await this.validateAndRefreshToken();const a=await r.Authentication.fromStorage(this.storage);if(!a)throw new t.SessionError(e.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return await this.authManager.getUser(a)}};
@@ -1 +1 @@
1
- "use strict";var e=require("../utils/debug.cjs"),t=require("../core/errors/authErrorCodes.cjs"),i=require("../core/errors/openfortError.cjs"),a=require("../core/errors/withApiError.cjs"),r=require("../types/types.cjs");function n(e){if(!e)throw new i.OpenfortError(t.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"User data is missing");return{id:e.id||"",email:e.email,name:e.name??void 0,image:e.image??void 0,emailVerified:e.emailVerified,isAnonymous:e.isAnonymous,createdAt:e.createdAt,updatedAt:e.updatedAt,phoneNumber:e.phoneNumber,phoneNumberVerified:e.phoneNumberVerified}}function s(e){if(e)return{id:e.id,token:e.token,userId:e.userId,expiresAt:e.expiresAt,createdAt:e.createdAt,updatedAt:e.updatedAt}}exports.AuthManager=class{backendApiClientsInstance;publishableKeyInstance;setBackendApiClients(e,t){this.backendApiClientsInstance=e,this.publishableKeyInstance=t}get backendApiClients(){if(!this.backendApiClientsInstance)throw new i.ConfigurationError("Backend API clients not initialized");return this.backendApiClientsInstance}get publishableKey(){if(!this.publishableKeyInstance)throw new i.ConfigurationError("Publishable key not initialized");return this.publishableKeyInstance}buildAuthHeaders(e){return{"x-project-key":this.publishableKey,...e&&{authorization:`Bearer ${e}`}}}async initOAuth(e,t,i){return await a.withApiError(async()=>(await this.backendApiClients.authenticationV2Api.socialSignIn({socialSignInRequest:{provider:e,callbackURL:t,scopes:i?.scopes?.split(" "),disableRedirect:i?.skipBrowserRedirect??!1}},{headers:{"x-project-key":`${this.publishableKey}`}})).data.url||"",{context:"initOAuth"})}async linkOAuthToAnonymous(e,t,i){return await a.withApiError(async()=>(await this.backendApiClients.authenticationV2Api.socialSignIn({socialSignInRequest:{provider:t,callbackURL:i}},{headers:{authorization:`Bearer ${e.token}`,"x-project-key":`${this.publishableKey}`}})).data.url||"",{context:"initOAuth"})}async registerGuest(){return a.withApiError(async()=>{const e=await this.backendApiClients.anonymousApi.signInAnonymousPost({headers:{"x-project-key":`${this.publishableKey}`}});return{token:e.data.token,user:n(e.data.user)}},{context:"registerGuest"})}async loginWithIdToken(e,t){const i={socialSignInRequest:{provider:e,idToken:{token:t}}};return await a.withApiError(async()=>{const e=await this.backendApiClients.authenticationV2Api.socialSignIn(i,{headers:{"x-project-key":`${this.publishableKey}`}});return{token:e.data.token,user:n(e.data.user)}},{context:"loginWithIdToken"})}async authenticateThirdParty(e,t){const i={thirdPartyOAuthRequest:{provider:e,token:t}};return a.withApiError(async()=>({userId:(await this.backendApiClients.userApi.thirdPartyV2(i,{headers:{"x-project-key":`${this.publishableKey}`}})).data.id}),{context:"authenticateThirdParty"})}async initSIWE(e){const t={siweNoncePostRequest:{walletAddress:e}};return{address:e,nonce:(await a.withApiError(async()=>this.backendApiClients.siweApi.siweNoncePost(t,{headers:{"x-project-key":`${this.publishableKey}`}}),{context:"initSIWE"})).data.nonce}}async linkSIWE(e,t){const i={siweNoncePostRequest:{walletAddress:e}};return{address:e,nonce:(await a.withApiError(async()=>this.backendApiClients.siweApi.linkSiweNoncePost(i,{headers:{authorization:`Bearer ${t.token}`,"x-project-key":`${this.publishableKey}`}}),{context:"linkSIWE"})).data.nonce}}async authenticateSIWE(e,t,i,r,s){const o={siweVerifyPostRequest:{signature:e,walletAddress:s,message:t,walletClientType:i,connectorType:r}};return a.withApiError(async()=>{const e=await this.backendApiClients.siweApi.siweVerifyPost(o,{headers:{"x-project-key":`${this.publishableKey}`}}),t=e.data.user;return{token:e.data.token,user:n(t)}},{context:"authenticateSIWE"})}async loginEmailPassword(e,t){return a.withApiError(async()=>{const i=(await this.backendApiClients.authenticationV2Api.signInEmailPost({signInEmailPostRequest:{email:e,password:t}},{headers:{"x-project-key":`${this.publishableKey}`}})).data;return{token:i.token,user:n(i.user)}},{context:"loginEmailPassword"})}async requestResetPassword(e,t){await a.withApiError(async()=>{await this.backendApiClients.authenticationV2Api.requestPasswordResetPost({forgetPasswordPostRequest:{email:e,redirectTo:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"requestResetPassword"})}async resetPassword(e,t){return a.withApiError(async()=>{await this.backendApiClients.authenticationV2Api.resetPasswordPost({resetPasswordPostRequest:{newPassword:e,token:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"resetPassword"})}async requestEmailVerification(e,t){await a.withApiError(async()=>{await this.backendApiClients.authenticationV2Api.sendVerificationEmailPost({sendVerificationEmailPostRequest:{email:e,callbackURL:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"requestEmailVerification"})}async verifyEmail(e,t){return a.withApiError(async()=>{await this.backendApiClients.authenticationV2Api.verifyEmailGet({token:e,callbackURL:t})},{context:"verifyEmail"})}async signupEmailPassword(e,t,i,s,o){return a.withApiError(async()=>{const a=(await this.backendApiClients.authenticationV2Api.signUpEmailPost({signUpEmailPostRequest:{email:e,password:t,name:i,callbackURL:s}},{headers:this.buildAuthHeaders(o)})).data;return null===a.token?{action:r.AuthActionRequiredActions.ACTION_VERIFY_EMAIL}:{token:a.token,user:n(a.user)}},{context:"signupEmailPassword"})}async validateCredentials(t,i){e.debugLog("Validating credentials with token:",t.token);const a=await this.getSessionWithToken(t,i);return{token:a.session.token,user:n(a.user),session:s(a.session)}}async logout(e){return a.withApiError(async()=>{await this.backendApiClients.authenticationV2Api.signOutPost(void 0,{headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)})},{context:"logout"})}async getUser(e){return a.withApiError(async()=>n((await this.backendApiClients.userApi.meV2({headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)})).data),{context:"getUser"})}async listAccounts(e){return a.withApiError(async()=>(await this.backendApiClients.authenticationV2Api.listAccountsGet({headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)})).data,{context:"listAccounts"})}async linkOAuth(e,t,i,r){const n=r?.skipBrowserRedirect??!1,s={linkSocialPostRequest:{provider:t,callbackURL:i,scopes:r?.scopes?.split(" "),disableRedirect:n}},o=await a.withApiError(async()=>this.backendApiClients.authenticationV2Api.linkSocialPost(s,{headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)}),{context:"linkOAuth"});return"undefined"!=typeof window&&!n&&o.data.url&&window.location.assign(o.data.url),o.data.url||""}async unlinkOAuth(e,t){const i={unlinkAccountPostRequest:{providerId:e}};return a.withApiError(async()=>(await this.backendApiClients.authenticationV2Api.unlinkAccountPost(i,{headers:t.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t.token,"x-auth-provider":t.thirdPartyProvider,"x-token-type":t.thirdPartyTokenType}:this.buildAuthHeaders(t.token)})).data,{context:"unlinkOAuth"})}async addEmail(e,t,i){return a.withApiError(async()=>(await this.backendApiClients.authenticationV2Api.changeEmailPost({changeEmailPostRequest:{newEmail:e,callbackURL:t}},{headers:i.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:this.buildAuthHeaders(i.token)})).data,{context:"addEmail"})}async unlinkWallet(e,t,i){const r={linkSiweUnlinkPostRequest:{walletAddress:e,chaindId:t}};return a.withApiError(async()=>(await this.backendApiClients.siweApi.linkSiweUnlinkPost(r,{headers:i.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:this.buildAuthHeaders(i.token)})).data,{context:"unlinkWallet"})}async linkWallet(e,t,i,r,n,s,o){const h={siweVerifyPostRequest:{signature:e,message:t,walletAddress:n,chainId:s,walletClientType:i,connectorType:r}};return a.withApiError(async()=>(await this.backendApiClients.siweApi.linkSiweVerifyPost(h,{headers:o.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":o.token,"x-auth-provider":o.thirdPartyProvider,"x-token-type":o.thirdPartyTokenType}:this.buildAuthHeaders(o.token)})).data,{context:"linkWallet"})}async requestEmailOTP(e,t){const i={emailOtpSendVerificationOtpPostRequest:{email:e,type:t}};await a.withApiError(async()=>(await this.backendApiClients.emailOTPApi.emailOtpSendVerificationOtpPost(i,{headers:{"x-project-key":`${this.publishableKey}`}})).data,{context:"requestEmailOTP"})}async verifyEmailOtp(e,t,i){await a.withApiError(async()=>(await this.backendApiClients.emailOTPApi.emailOtpVerifyEmailPost({emailOtpVerifyEmailPostRequest:{email:e,otp:t}},{headers:this.buildAuthHeaders(i)})).data,{context:"verifyEmailOtp"})}async loginWithEmailOTP(e,t,i){return await a.withApiError(async()=>{const a=(await this.backendApiClients.emailOTPApi.signInEmailOtpPost({signInEmailOtpPostRequest:{email:e,otp:t}},{headers:this.buildAuthHeaders(i)})).data;return{token:a.token,user:n(a.user)}},{context:"loginWithEmailOTP"})}async requestPhoneOtp(e){const t={phoneNumberSendOtpPostRequest:{phoneNumber:e}};await a.withApiError(async()=>(await this.backendApiClients.smsOTPApi.phoneNumberSendOtpPost(t,{headers:{"x-project-key":`${this.publishableKey}`}})).data,{context:"requestPhoneOtp"})}async loginWithSMSOTP(e,t){return await a.withApiError(async()=>{const i=(await this.backendApiClients.smsOTPApi.phoneNumberVerifyPost({phoneNumberVerifyPostRequest:{code:t,phoneNumber:e}},{headers:{"x-project-key":`${this.publishableKey}`}})).data;return{token:i.token,user:n(i.user)}},{context:"loginWithSMSOTP"})}async linkSMSOTP(e,t,i){return await a.withApiError(async()=>{const a=(await this.backendApiClients.smsOTPApi.phoneNumberVerifyPost({phoneNumberVerifyPostRequest:{code:t,phoneNumber:e,updatePhoneNumber:!0}},{headers:{authorization:`Bearer ${i.token}`,"x-project-key":`${this.publishableKey}`}})).data;return{token:a.token,user:n(a.user)}},{context:"linkSMSOTP"})}async getSessionWithToken(e,t){return await a.withApiError(async()=>(await this.backendApiClients.authenticationV2Api.getSessionGet({disableCookieCache:t},{headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)})).data,{context:"getSessionWithToken"})}};
1
+ "use strict";var e=require("../utils/debug.cjs"),t=require("../core/errors/authErrorCodes.cjs"),i=require("../core/errors/openfortError.cjs"),a=require("../core/errors/withApiError.cjs"),r=require("../types/types.cjs");function n(e){if(!e)throw new i.OpenfortError(t.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"User data is missing");return{id:e.id||"",email:e.email,name:e.name??void 0,image:e.image??void 0,emailVerified:e.emailVerified,isAnonymous:e.isAnonymous,createdAt:e.createdAt,updatedAt:e.updatedAt,phoneNumber:e.phoneNumber,phoneNumberVerified:e.phoneNumberVerified,linkedAccounts:e.linkedAccounts}}function s(e){if(e)return{id:e.id,token:e.token,userId:e.userId,expiresAt:e.expiresAt,createdAt:e.createdAt,updatedAt:e.updatedAt}}exports.AuthManager=class{backendApiClientsInstance;publishableKeyInstance;setBackendApiClients(e,t){this.backendApiClientsInstance=e,this.publishableKeyInstance=t}get backendApiClients(){if(!this.backendApiClientsInstance)throw new i.ConfigurationError("Backend API clients not initialized");return this.backendApiClientsInstance}get publishableKey(){if(!this.publishableKeyInstance)throw new i.ConfigurationError("Publishable key not initialized");return this.publishableKeyInstance}buildAuthHeaders(e){return{"x-project-key":this.publishableKey,...e&&{authorization:`Bearer ${e}`}}}async initOAuth(e,t,i){return await a.withApiError(async()=>(await this.backendApiClients.authenticationV2Api.socialSignIn({socialSignInRequest:{provider:e,callbackURL:t,scopes:i?.scopes?.split(" "),disableRedirect:i?.skipBrowserRedirect??!1}},{headers:{"x-project-key":`${this.publishableKey}`}})).data.url||"",{context:"initOAuth"})}async linkOAuthToAnonymous(e,t,i){return await a.withApiError(async()=>(await this.backendApiClients.authenticationV2Api.socialSignIn({socialSignInRequest:{provider:t,callbackURL:i}},{headers:{authorization:`Bearer ${e.token}`,"x-project-key":`${this.publishableKey}`}})).data.url||"",{context:"initOAuth"})}async registerGuest(){return a.withApiError(async()=>{const e=await this.backendApiClients.anonymousApi.signInAnonymousPost({headers:{"x-project-key":`${this.publishableKey}`}});return{token:e.data.token,user:n(e.data.user)}},{context:"registerGuest"})}async loginWithIdToken(e,t){const i={socialSignInRequest:{provider:e,idToken:{token:t}}};return await a.withApiError(async()=>{const e=await this.backendApiClients.authenticationV2Api.socialSignIn(i,{headers:{"x-project-key":`${this.publishableKey}`}});return{token:e.data.token,user:n(e.data.user)}},{context:"loginWithIdToken"})}async authenticateThirdParty(e,t){const i={thirdPartyOAuthRequest:{provider:e,token:t}};return a.withApiError(async()=>({userId:(await this.backendApiClients.userApi.thirdPartyV2(i,{headers:{"x-project-key":`${this.publishableKey}`}})).data.id}),{context:"authenticateThirdParty"})}async initSIWE(e){const t={siweNoncePostRequest:{walletAddress:e}};return{address:e,nonce:(await a.withApiError(async()=>this.backendApiClients.siweApi.siweNoncePost(t,{headers:{"x-project-key":`${this.publishableKey}`}}),{context:"initSIWE"})).data.nonce}}async linkSIWE(e,t){const i={siweNoncePostRequest:{walletAddress:e}};return{address:e,nonce:(await a.withApiError(async()=>this.backendApiClients.siweApi.linkSiweNoncePost(i,{headers:{authorization:`Bearer ${t.token}`,"x-project-key":`${this.publishableKey}`}}),{context:"linkSIWE"})).data.nonce}}async authenticateSIWE(e,t,i,r,s){const o={siweVerifyPostRequest:{signature:e,walletAddress:s,message:t,walletClientType:i,connectorType:r}};return a.withApiError(async()=>{const e=await this.backendApiClients.siweApi.siweVerifyPost(o,{headers:{"x-project-key":`${this.publishableKey}`}}),t=e.data.user;return{token:e.data.token,user:n(t)}},{context:"authenticateSIWE"})}async loginEmailPassword(e,t){return a.withApiError(async()=>{const i=(await this.backendApiClients.authenticationV2Api.signInEmailPost({signInEmailPostRequest:{email:e,password:t}},{headers:{"x-project-key":`${this.publishableKey}`}})).data;return{token:i.token,user:n(i.user)}},{context:"loginEmailPassword"})}async requestResetPassword(e,t){await a.withApiError(async()=>{await this.backendApiClients.authenticationV2Api.requestPasswordResetPost({forgetPasswordPostRequest:{email:e,redirectTo:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"requestResetPassword"})}async resetPassword(e,t){return a.withApiError(async()=>{await this.backendApiClients.authenticationV2Api.resetPasswordPost({resetPasswordPostRequest:{newPassword:e,token:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"resetPassword"})}async requestEmailVerification(e,t){await a.withApiError(async()=>{await this.backendApiClients.authenticationV2Api.sendVerificationEmailPost({sendVerificationEmailPostRequest:{email:e,callbackURL:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"requestEmailVerification"})}async verifyEmail(e,t){return a.withApiError(async()=>{await this.backendApiClients.authenticationV2Api.verifyEmailGet({token:e,callbackURL:t})},{context:"verifyEmail"})}async signupEmailPassword(e,t,i,s,o){return a.withApiError(async()=>{const a=(await this.backendApiClients.authenticationV2Api.signUpEmailPost({signUpEmailPostRequest:{email:e,password:t,name:i,callbackURL:s}},{headers:this.buildAuthHeaders(o)})).data;return null===a.token?{action:r.AuthActionRequiredActions.ACTION_VERIFY_EMAIL}:{token:a.token,user:n(a.user)}},{context:"signupEmailPassword"})}async validateCredentials(t,i){e.debugLog("Validating credentials with token:",t.token);const a=await this.getSessionWithToken(t,i);return{token:a.session.token,user:n(a.user),session:s(a.session)}}async logout(e){return a.withApiError(async()=>{await this.backendApiClients.authenticationV2Api.signOutPost(void 0,{headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)})},{context:"logout"})}async getUser(e){return a.withApiError(async()=>n((await this.backendApiClients.userApi.meV2({headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)})).data),{context:"getUser"})}async linkOAuth(e,t,i,r){const n=r?.skipBrowserRedirect??!1,s={linkSocialPostRequest:{provider:t,callbackURL:i,scopes:r?.scopes?.split(" "),disableRedirect:n}},o=await a.withApiError(async()=>this.backendApiClients.authenticationV2Api.linkSocialPost(s,{headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)}),{context:"linkOAuth"});return"undefined"!=typeof window&&!n&&o.data.url&&window.location.assign(o.data.url),o.data.url||""}async unlinkOAuth(e,t){const i={unlinkAccountPostRequest:{providerId:e}};return a.withApiError(async()=>(await this.backendApiClients.authenticationV2Api.unlinkAccountPost(i,{headers:t.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t.token,"x-auth-provider":t.thirdPartyProvider,"x-token-type":t.thirdPartyTokenType}:this.buildAuthHeaders(t.token)})).data,{context:"unlinkOAuth"})}async addEmail(e,t,i){return a.withApiError(async()=>(await this.backendApiClients.authenticationV2Api.changeEmailPost({changeEmailPostRequest:{newEmail:e,callbackURL:t}},{headers:i.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:this.buildAuthHeaders(i.token)})).data,{context:"addEmail"})}async unlinkWallet(e,t,i){const r={linkSiweUnlinkPostRequest:{walletAddress:e,chaindId:t}};return a.withApiError(async()=>(await this.backendApiClients.siweApi.linkSiweUnlinkPost(r,{headers:i.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:this.buildAuthHeaders(i.token)})).data,{context:"unlinkWallet"})}async linkWallet(e,t,i,r,n,s,o){const h={siweVerifyPostRequest:{signature:e,message:t,walletAddress:n,chainId:s,walletClientType:i,connectorType:r}};return a.withApiError(async()=>(await this.backendApiClients.siweApi.linkSiweVerifyPost(h,{headers:o.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":o.token,"x-auth-provider":o.thirdPartyProvider,"x-token-type":o.thirdPartyTokenType}:this.buildAuthHeaders(o.token)})).data,{context:"linkWallet"})}async requestEmailOTP(e,t){const i={emailOtpSendVerificationOtpPostRequest:{email:e,type:t}};await a.withApiError(async()=>(await this.backendApiClients.emailOTPApi.emailOtpSendVerificationOtpPost(i,{headers:{"x-project-key":`${this.publishableKey}`}})).data,{context:"requestEmailOTP"})}async verifyEmailOtp(e,t,i){await a.withApiError(async()=>(await this.backendApiClients.emailOTPApi.emailOtpVerifyEmailPost({emailOtpVerifyEmailPostRequest:{email:e,otp:t}},{headers:this.buildAuthHeaders(i)})).data,{context:"verifyEmailOtp"})}async loginWithEmailOTP(e,t,i){return await a.withApiError(async()=>{const a=(await this.backendApiClients.emailOTPApi.signInEmailOtpPost({signInEmailOtpPostRequest:{email:e,otp:t}},{headers:this.buildAuthHeaders(i)})).data;return{token:a.token,user:n(a.user)}},{context:"loginWithEmailOTP"})}async requestPhoneOtp(e){const t={phoneNumberSendOtpPostRequest:{phoneNumber:e}};await a.withApiError(async()=>(await this.backendApiClients.smsOTPApi.phoneNumberSendOtpPost(t,{headers:{"x-project-key":`${this.publishableKey}`}})).data,{context:"requestPhoneOtp"})}async loginWithSMSOTP(e,t){return await a.withApiError(async()=>{const i=(await this.backendApiClients.smsOTPApi.phoneNumberVerifyPost({phoneNumberVerifyPostRequest:{code:t,phoneNumber:e}},{headers:{"x-project-key":`${this.publishableKey}`}})).data;return{token:i.token,user:n(i.user)}},{context:"loginWithSMSOTP"})}async linkSMSOTP(e,t,i){return await a.withApiError(async()=>{const a=(await this.backendApiClients.smsOTPApi.phoneNumberVerifyPost({phoneNumberVerifyPostRequest:{code:t,phoneNumber:e,updatePhoneNumber:!0}},{headers:{authorization:`Bearer ${i.token}`,"x-project-key":`${this.publishableKey}`}})).data;return{token:a.token,user:n(a.user)}},{context:"linkSMSOTP"})}async getSessionWithToken(e,t){return await a.withApiError(async()=>(await this.backendApiClients.authenticationV2Api.getSessionGet({disableCookieCache:t},{headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)})).data,{context:"getSessionWithToken"})}};
@@ -1 +1 @@
1
- "use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.0.1";
1
+ "use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.0.3";
@@ -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 E extends t.OpenfortError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.OTP_REQUIRED,"OTP verification required")}}exports.IframeManager=class{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;hasFailed=!1;constructor(e,i,r){if(!e)throw new t.ConfigurationError("Configuration is required for IframeManager");if(!i)throw new t.ConfigurationError("Storage is required for IframeManager");if(!r)throw new t.ConfigurationError("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=r}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){a.debugLog("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:a.debugLog}),this.connection=c({messenger:this.messenger,timeout:1e4,log:a.debugLog});try{this.remote=await this.connection.promise,a.debugLog("IframeManager connection established")}catch(e){const i=e;throw n.sentry.captureException(i),this.destroy(),a.debugLog("Failed to establish connection:",i),new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}`)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(u.isErrorResponse(e)){if(e.error===u.NOT_CONFIGURED_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new y;if(e.error===u.MISSING_USER_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.MISSING_PROJECT_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new l;if(e.error===u.INCORRECT_USER_ENTROPY_ERROR)throw new R;if(e.error===u.MISSING_PASSKEY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.INCORRECT_PASSKEY_ERROR)throw new g;if(e.error===u.OTP_REQUIRED_ERROR)throw new E;throw this.storage.remove(o.StorageKeys.ACCOUNT),new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=e.chainId??null,r.password=e?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:e?.entropy?.encryptionSession},r.passkey=e?.entropy?.passkey??null;const t={uuid:s.randomUUID(),action:u.Event.CREATE,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},n=await i.create(t);return u.isErrorResponse(n)&&this.handleError(n),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",n.version??"undefined"),n}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await e.Account.fromStorage(this.storage),t=await this.ensureConnection(),n=await this.buildIFrameRequestConfiguration();n.chainId=r?.chainId??null,n.password=i?.entropy?.recoveryPassword??null,n.recovery={...n.recovery,encryptionSession:i?.entropy?.encryptionSession},n.passkey=i?.entropy?.passkey??null;const o={uuid:s.randomUUID(),action:u.Event.RECOVER,recovery:n.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:n.accessToken,playerID:n.playerID,thirdPartyProvider:n.thirdPartyProvider,thirdPartyTokenType:n.thirdPartyTokenType,encryptionKey:n.password,encryptionSession:n.recovery?.encryptionSession??null,passkey:n.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},a=await t.recover(o);return u.isErrorResponse(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,i,r,t){a.debugLog("[iframe] ensureConnection");const n=await this.ensureConnection(),o=new u.SignRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,t);a.debugLog("[iframe] done ensureConnection");const d=await n.sign(o);return a.debugLog("[iframe] response",d),u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined"),d.signature}async switchChain(e){const i=await this.ensureConnection(),r=new u.SwitchChainRequest(s.randomUUID(),e,await this.buildRequestConfiguration()),t=await i.switchChain(r);return u.isErrorResponse(t)&&this.handleError(t),t}async export(){const e=await this.ensureConnection(),i=new u.ExportPrivateKeyRequest(s.randomUUID(),await this.buildRequestConfiguration()),r=await e.export(i);return u.isErrorResponse(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r.key}async setRecoveryMethod(e,i,r,t,n){const o=await this.ensureConnection(),a=new u.SetRecoveryMethodRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,t,n),d=await o.setRecoveryMethod(a);u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),r=new u.GetCurrentDeviceRequest(s.randomUUID(),e);try{const e=await i.getCurrentDevice(r);return u.isErrorResponse(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof y)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void a.debugLog("IframeManager not loaded, skipping authentication update");const e=await i.Authentication.fromStorage(this.storage);if(!e)return void a.debugLog("No authentication found, skipping update");const r=new u.UpdateAuthenticationRequest(s.randomUUID(),e.token);a.debugLog("Updating authentication in iframe with token");const t=await this.remote.updateAuthentication(r);u.isErrorResponse(t)&&this.handleError(t)}async disconnect(){const e=await this.ensureConnection(),i={uuid:s.randomUUID()};await e.logout(i)}async onMessage(e){a.debugLog("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof d.ReactNativeMessenger?(this.isInitialized||this.connection?a.debugLog(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(a.debugLog("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{a.debugLog("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),a.debugLog("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):a.debugLog("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}},exports.MissingProjectEntropyError=l,exports.MissingRecoveryPasswordError=h,exports.NotConfiguredError=y,exports.OTPRequiredError=E,exports.WrongPasskeyError=g,exports.WrongRecoveryPasswordError=R;
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;
package/dist/index.d.cts CHANGED
@@ -1,7 +1,6 @@
1
1
  import { PasskeyDetails } from 'wallets/types';
2
2
  import { PasskeyHandler as PasskeyHandler$1 } from 'core/configuration/passkey';
3
3
  import { User as User$2, ThirdPartyOAuthProvider as ThirdPartyOAuthProvider$1 } from 'types';
4
- import { UserAccount } from 'types/types';
5
4
  import { Account } from 'core/configuration/account';
6
5
  import { Hex } from 'wallets/evm/types';
7
6
 
@@ -11276,6 +11275,8 @@ interface User {
11276
11275
  phoneNumber?: string;
11277
11276
  /** Whether the user's phone number has been verified */
11278
11277
  phoneNumberVerified?: boolean;
11278
+ /** List of user linked accounts */
11279
+ linkedAccounts?: ListAccountsGet200ResponseInner[];
11279
11280
  }
11280
11281
  /**
11281
11282
  * Session information
@@ -11496,7 +11497,6 @@ declare class AuthManager {
11496
11497
  validateCredentials(authentication: Authentication, _forceRefresh?: boolean): Promise<AuthResponse>;
11497
11498
  logout(auth: Authentication): Promise<void>;
11498
11499
  getUser(auth: Authentication): Promise<User>;
11499
- listAccounts(auth: Authentication): Promise<ListAccountsGet200ResponseInner[]>;
11500
11500
  linkOAuth(auth: Authentication, provider: OAuthProvider, redirectTo: string, options?: InitializeOAuthOptions): Promise<string>;
11501
11501
  unlinkOAuth(provider: OAuthProvider, auth: Authentication): Promise<UnlinkAccountResponse>;
11502
11502
  addEmail(email: string, callbackURL: string, auth: Authentication): Promise<ChangeEmailPost200Response>;
@@ -11725,7 +11725,6 @@ declare class UserApi {
11725
11725
  private validateAndRefreshToken;
11726
11726
  constructor(storage: IStorage, authManager: AuthManager, validateAndRefreshToken: () => Promise<void>);
11727
11727
  get(): Promise<User$2>;
11728
- list(): Promise<UserAccount[]>;
11729
11728
  }
11730
11729
 
11731
11730
  interface SDKOverrides {
package/dist/index.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import { PasskeyDetails } from 'wallets/types';
2
2
  import { PasskeyHandler as PasskeyHandler$1 } from 'core/configuration/passkey';
3
3
  import { User as User$2, ThirdPartyOAuthProvider as ThirdPartyOAuthProvider$1 } from 'types';
4
- import { UserAccount } from 'types/types';
5
4
  import { Account } from 'core/configuration/account';
6
5
  import { Hex } from 'wallets/evm/types';
7
6
 
@@ -11276,6 +11275,8 @@ interface User {
11276
11275
  phoneNumber?: string;
11277
11276
  /** Whether the user's phone number has been verified */
11278
11277
  phoneNumberVerified?: boolean;
11278
+ /** List of user linked accounts */
11279
+ linkedAccounts?: ListAccountsGet200ResponseInner[];
11279
11280
  }
11280
11281
  /**
11281
11282
  * Session information
@@ -11496,7 +11497,6 @@ declare class AuthManager {
11496
11497
  validateCredentials(authentication: Authentication, _forceRefresh?: boolean): Promise<AuthResponse>;
11497
11498
  logout(auth: Authentication): Promise<void>;
11498
11499
  getUser(auth: Authentication): Promise<User>;
11499
- listAccounts(auth: Authentication): Promise<ListAccountsGet200ResponseInner[]>;
11500
11500
  linkOAuth(auth: Authentication, provider: OAuthProvider, redirectTo: string, options?: InitializeOAuthOptions): Promise<string>;
11501
11501
  unlinkOAuth(provider: OAuthProvider, auth: Authentication): Promise<UnlinkAccountResponse>;
11502
11502
  addEmail(email: string, callbackURL: string, auth: Authentication): Promise<ChangeEmailPost200Response>;
@@ -11725,7 +11725,6 @@ declare class UserApi {
11725
11725
  private validateAndRefreshToken;
11726
11726
  constructor(storage: IStorage, authManager: AuthManager, validateAndRefreshToken: () => Promise<void>);
11727
11727
  get(): Promise<User$2>;
11728
- list(): Promise<UserAccount[]>;
11729
11728
  }
11730
11729
 
11731
11730
  interface SDKOverrides {
@@ -1 +1 @@
1
- import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{PasskeyHandler as r}from"../core/configuration/passkey.js";import{SDKConfiguration as t}from"../core/config/config.js";import{Account as s}from"../core/configuration/account.js";import{Authentication as a}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as i}from"../core/errors/authErrorCodes.js";import{ConfigurationError as n,SessionError as o,SignerError as d}from"../core/errors/openfortError.js";import{withApiError as c}from"../core/errors/withApiError.js";import{OpenfortEvents as h,RecoveryMethod as m,ChainTypeEnum as g,AccountTypeEnum as y,EmbeddedState as l}from"../types/types.js";import{debugLog as p}from"../utils/debug.js";import{EmbeddedSigner as f}from"../wallets/embedded.js";import{EvmProvider as u}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as A,openfortProviderInfo as w}from"../wallets/evm/provider/eip6963.js";import{signMessage as v}from"../wallets/evm/walletHelpers.js";import{IframeManager as M}from"../wallets/iframeManager.js";import{ReactNativeMessenger as E}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import I from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class T{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;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(h.ON_LOGOUT,()=>{p("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const r=t.getInstance();if(!r)throw new n("Configuration not found");return new e({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey,nativeAppIdentifier:r.nativeAppIdentifier})}async getIframeManager(){if(p("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager&&this.iframeManager.hasFailed&&(p("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return p("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return p("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;p("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return p("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,p("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw p("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){p("[HANDSHAKE DEBUG] createIframeManager starting");const e=t.getInstance();if(!e)throw p("[HANDSHAKE DEBUG] Configuration not found"),new n("Configuration not found");let r;if(p("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)p("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(p("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new E(this.messagePoster),p("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{p("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;r=new I({remoteWindow:t.contentWindow,allowedOrigins:[s]}),p("[HANDSHAKE DEBUG] Created WindowMessenger")}return p("[HANDSHAKE DEBUG] Creating IframeManager instance"),new M(e,this.storage,r)}async ensureSigner(){if(this.iframeManager&&this.iframeManager.hasFailed&&(p("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();return new f(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new n("Document is not available. Please provide a message poster for non-browser environments.");const r=document.getElementById("openfort-iframe");r&&r.remove();const t=document.createElement("iframe");return t.style.display="none",t.id="openfort-iframe",t.src=e,document.body.appendChild(t),t}async getPasskeyKey(e){const r=await a.fromStorage(this.storage);return await this.passkeyHandler.deriveAndExportKey({id:e,seed:r?.userId??""})}async getEntropy(e){switch(e.recoveryMethod){case m.PASSWORD:return{recoveryPassword:e.password};case m.AUTOMATIC:return{encryptionSession:e.encryptionSession};case m.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new n("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:m.AUTOMATIC},[t,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i={chainId:e.chainId,entropy:a,accountType:e.accountType??y.SMART_ACCOUNT,chainType:e.chainType??g.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},n=await t.configure(i);return{id:n.id,chainId:n.chainId,user:n.user,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.parseRecoveryMethod(n.recoveryMethod),recoveryMethodDetails:n.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:m.AUTOMATIC},n=await a.fromStorage(this.storage);if(!n)throw new o(i.NOT_LOGGED_IN,"missing authentication");if(t.recoveryMethod===m.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:n?.userId});t.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[d,c]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),g=await d.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:c}),y={id:g.id,chainId:g.chainId,user:n?.userId,address:g.address,ownerAddress:g.ownerAddress,chainType:g.chainType,accountType:g.accountType,implementationType:g.implementationType,factoryAddress:g.factoryAddress,salt:g.salt,createdAt:g.createdAt,implementationAddress:g.implementationAddress,recoveryMethod:s.parseRecoveryMethod(g.recoveryMethod),recoveryMethodDetails:g.recoveryMethodDetails};return this.eventEmitter.emit(h.ON_EMBEDDED_WALLET_CREATED,y),y}async recover(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:m.AUTOMATIC};if(r.recoveryMethod===m.PASSKEY){if(!r.passkeyInfo?.passkeyId)throw new n("Passkey ID must be provided for passkey recovery");r.passkeyInfo={passkeyId:r.passkeyInfo.passkeyId}}const[t,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i=await t.recover({account:e.account,entropy:a}),o={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,user:i.user,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:s.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(h.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.fromStorage(this.storage);return await t.sign(e,i,a,n?.chainType)}async signTypedData(e,r,t){await this.validateAndRefreshToken();const a=await this.ensureSigner(),n=await s.fromStorage(this.storage);if(!n)throw new d(i.MISSING_SIGNER,"No account found");const o={...r};delete o.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),h=c.hash(e,o,t);return await v({hash:h,implementationType:n.implementationType||n.type,chainId:Number(n.chainId),signer:a,address:n.address,ownerAddress:n.ownerAddress,factoryAddress:n.factoryAddress,salt:n.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,t){await this.validateAndRefreshToken();const d=await this.ensureSigner(),c=await a.fromStorage(this.storage);if(!c)throw new o(i.NOT_LOGGED_IN,"missing authentication");let h,g,y,l;if(e.recoveryMethod===m.PASSKEY){const e=await s.fromStorage(this.storage);if(!e)throw new n("missing account");const r=e?.recoveryMethodDetails?.passkeyId;if(!r)throw new n("missing passkey id for account");y={passkeyId:r,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:r,seed:c.userId})}}else if(t.recoveryMethod===m.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:c.userId});y={passkeyId:e.id,passkeyKey:e.key},l={passkeyId:e.id}}if(e.recoveryMethod===m.PASSWORD?h=e.password:t.recoveryMethod===m.PASSWORD&&(h=t.password),e.recoveryMethod===m.AUTOMATIC?g=e.encryptionSession:t.recoveryMethod===m.AUTOMATIC&&(g=t.encryptionSession),!h&&!g)throw new n("Password or encryption session is not provided");await d.setRecoveryMethod({recoveryMethod:t.recoveryMethod,recoveryPassword:h,encryptionSession:g,passkeyInfo:y});const p=await s.fromStorage(this.storage);p&&new s({...p,recoveryMethod:t.recoveryMethod,recoveryMethodDetails:l}).save(this.storage)}async get(){const e=await s.fromStorage(this.storage);if(!e)throw new d(i.MISSING_SIGNER,"No signer configured");const r=await a.fromStorage(this.storage);if(!r)throw new o(i.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,user:r.userId,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.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){const r={accountType:y.SMART_ACCOUNT,...e},d=t.getInstance();if(!d)throw new n("Configuration not found");const h=await a.fromStorage(this.storage);if(!h)throw new o(i.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),c(async()=>(await this.backendApiClients.accountsApi.getAccountsV2(r,{headers:h.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":h.token,"x-auth-provider":h.thirdPartyProvider,"x-token-type":h.thirdPartyTokenType}:{authorization:`Bearer ${h.token}`,"x-project-key":d.baseConfiguration.publishableKey}})).data.data.map(e=>({user:e.user,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.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await a.fromStorage(this.storage))return l.UNAUTHENTICATED;return await s.fromStorage(this.storage)?l.READY:l.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return p("Failed to get embedded state:",e),l.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await a.fromStorage(this.storage),i=await s.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new u({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:i||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&A({info:{...w,...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 a.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return p("Ping failed:",e),!1}}getURL(){const e=t.getInstance();if(!e)throw new n("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new n("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(){const e=await this.ensureSigner();await e.disconnect(),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void p("Invalid message received:",e);p("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const r="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(r&&this.messenger&&this.messagePoster)return p("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();p(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&p("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),p("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),p("[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{PasskeyHandler as r}from"../core/configuration/passkey.js";import{SDKConfiguration as t}from"../core/config/config.js";import{Account as s}from"../core/configuration/account.js";import{Authentication as a}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as i}from"../core/errors/authErrorCodes.js";import{ConfigurationError as n,SessionError as o,SignerError as d}from"../core/errors/openfortError.js";import{withApiError as c}from"../core/errors/withApiError.js";import{OpenfortEvents as h,RecoveryMethod as m,ChainTypeEnum as g,AccountTypeEnum as y,EmbeddedState as l}from"../types/types.js";import{debugLog as p}from"../utils/debug.js";import{EmbeddedSigner as f}from"../wallets/embedded.js";import{EvmProvider as u}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as A,openfortProviderInfo as w}from"../wallets/evm/provider/eip6963.js";import{signMessage as v}from"../wallets/evm/walletHelpers.js";import{IframeManager as M}from"../wallets/iframeManager.js";import{ReactNativeMessenger as E}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import I from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class T{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;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(h.ON_LOGOUT,()=>{p("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const r=t.getInstance();if(!r)throw new n("Configuration not found");return new e({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey,nativeAppIdentifier:r.nativeAppIdentifier})}async getIframeManager(){if(p("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager&&this.iframeManager.hasFailed&&(p("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return p("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return p("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;p("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return p("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,p("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw p("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){p("[HANDSHAKE DEBUG] createIframeManager starting");const e=t.getInstance();if(!e)throw p("[HANDSHAKE DEBUG] Configuration not found"),new n("Configuration not found");let r;if(p("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)p("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(p("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new E(this.messagePoster),p("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{p("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;r=new I({remoteWindow:t.contentWindow,allowedOrigins:[s]}),p("[HANDSHAKE DEBUG] Created WindowMessenger")}return p("[HANDSHAKE DEBUG] Creating IframeManager instance"),new M(e,this.storage,r)}async ensureSigner(){if(this.iframeManager&&this.iframeManager.hasFailed&&(p("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();return new f(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new n("Document is not available. Please provide a message poster for non-browser environments.");const r=document.getElementById("openfort-iframe");r&&r.remove();const t=document.createElement("iframe");return t.style.display="none",t.id="openfort-iframe",t.src=e,document.body.appendChild(t),t}async getPasskeyKey(e){const r=await a.fromStorage(this.storage);return await this.passkeyHandler.deriveAndExportKey({id:e,seed:r?.userId??""})}async getEntropy(e){switch(e.recoveryMethod){case m.PASSWORD:return{recoveryPassword:e.password};case m.AUTOMATIC:return{encryptionSession:e.encryptionSession};case m.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new n("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:m.AUTOMATIC},[t,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i={chainId:e.chainId,entropy:a,accountType:e.accountType??y.SMART_ACCOUNT,chainType:e.chainType??g.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},n=await t.configure(i);return{id:n.id,chainId:n.chainId,user:n.user,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.parseRecoveryMethod(n.recoveryMethod),recoveryMethodDetails:n.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:m.AUTOMATIC},n=await a.fromStorage(this.storage);if(!n)throw new o(i.NOT_LOGGED_IN,"missing authentication");if(t.recoveryMethod===m.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:n?.userId});t.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[d,c]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),g=await d.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:c}),y={id:g.id,chainId:g.chainId,user:n?.userId,address:g.address,ownerAddress:g.ownerAddress,chainType:g.chainType,accountType:g.accountType,implementationType:g.implementationType,factoryAddress:g.factoryAddress,salt:g.salt,createdAt:g.createdAt,implementationAddress:g.implementationAddress,recoveryMethod:s.parseRecoveryMethod(g.recoveryMethod),recoveryMethodDetails:g.recoveryMethodDetails};return this.eventEmitter.emit(h.ON_EMBEDDED_WALLET_CREATED,y),y}async recover(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:m.AUTOMATIC};if(r.recoveryMethod===m.PASSKEY){if(!r.passkeyInfo?.passkeyId)throw new n("Passkey ID must be provided for passkey recovery");r.passkeyInfo={passkeyId:r.passkeyInfo.passkeyId}}const[t,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i=await t.recover({account:e.account,entropy:a}),o={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,user:i.user,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:s.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(h.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.fromStorage(this.storage);return await t.sign(e,i,a,n?.chainType)}async signTypedData(e,r,t){await this.validateAndRefreshToken();const a=await this.ensureSigner(),n=await s.fromStorage(this.storage);if(!n)throw new d(i.MISSING_SIGNER,"No account found");const o={...r};delete o.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),h=c.hash(e,o,t);return await v({hash:h,implementationType:n.implementationType||n.type,chainId:Number(n.chainId),signer:a,address:n.address,ownerAddress:n.ownerAddress,factoryAddress:n.factoryAddress,salt:n.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,t){await this.validateAndRefreshToken();const d=await this.ensureSigner(),c=await a.fromStorage(this.storage);if(!c)throw new o(i.NOT_LOGGED_IN,"missing authentication");let h,g,y,l;if(e.recoveryMethod===m.PASSKEY){const e=await s.fromStorage(this.storage);if(!e)throw new n("missing account");const r=e?.recoveryMethodDetails?.passkeyId;if(!r)throw new n("missing passkey id for account");y={passkeyId:r,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:r,seed:c.userId})}}else if(t.recoveryMethod===m.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:c.userId});y={passkeyId:e.id,passkeyKey:e.key},l={passkeyId:e.id}}if(e.recoveryMethod===m.PASSWORD?h=e.password:t.recoveryMethod===m.PASSWORD&&(h=t.password),e.recoveryMethod===m.AUTOMATIC?g=e.encryptionSession:t.recoveryMethod===m.AUTOMATIC&&(g=t.encryptionSession),!h&&!g)throw new n("Password or encryption session is not provided");await d.setRecoveryMethod({recoveryMethod:t.recoveryMethod,recoveryPassword:h,encryptionSession:g,passkeyInfo:y});const p=await s.fromStorage(this.storage);p&&new s({...p,recoveryMethod:t.recoveryMethod,recoveryMethodDetails:l}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await s.fromStorage(this.storage);if(!e)throw new d(i.MISSING_SIGNER,"No signer configured");const r=await a.fromStorage(this.storage);if(!r)throw new o(i.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,user:r.userId,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.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const r={accountType:y.SMART_ACCOUNT,...e},d=t.getInstance();if(!d)throw new n("Configuration not found");const h=await a.fromStorage(this.storage);if(!h)throw new o(i.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),c(async()=>(await this.backendApiClients.accountsApi.getAccountsV2(r,{headers:h.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":h.token,"x-auth-provider":h.thirdPartyProvider,"x-token-type":h.thirdPartyTokenType}:{authorization:`Bearer ${h.token}`,"x-project-key":d.baseConfiguration.publishableKey}})).data.data.map(e=>({user:e.user,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.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await a.fromStorage(this.storage))return l.UNAUTHENTICATED;return await s.fromStorage(this.storage)?l.READY:l.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return p("Failed to get embedded state:",e),l.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await a.fromStorage(this.storage),i=await s.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new u({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:i||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&A({info:{...w,...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 a.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return p("Ping failed:",e),!1}}getURL(){const e=t.getInstance();if(!e)throw new n("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new n("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(){const e=await this.ensureSigner();await e.disconnect(),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void p("Invalid message received:",e);p("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const r="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(r&&this.messenger&&this.messagePoster)return p("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();p(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&p("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),p("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),p("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{T as EmbeddedWalletApi};
@@ -1 +1 @@
1
- import{Authentication as t}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as r}from"../core/errors/authErrorCodes.js";import{SessionError as a}from"../core/errors/openfortError.js";class e{storage;authManager;validateAndRefreshToken;constructor(t,r,a){this.storage=t,this.authManager=r,this.validateAndRefreshToken=a}async get(){await this.validateAndRefreshToken();const e=await t.fromStorage(this.storage);if(!e)throw new a(r.NOT_LOGGED_IN,"No access token found");return await this.authManager.getUser(e)}async list(){await this.validateAndRefreshToken();const e=await t.fromStorage(this.storage);if(!e)throw new a(r.NOT_LOGGED_IN,"No access token found");return await this.authManager.listAccounts(e)}}export{e as UserApi};
1
+ import{Authentication as r}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as t}from"../core/errors/authErrorCodes.js";import{SessionError as e}from"../core/errors/openfortError.js";class o{storage;authManager;validateAndRefreshToken;constructor(r,t,e){this.storage=r,this.authManager=t,this.validateAndRefreshToken=e}async get(){await this.validateAndRefreshToken();const o=await r.fromStorage(this.storage);if(!o)throw new e(t.NOT_LOGGED_IN,"No access token found");return await this.authManager.getUser(o)}}export{o as UserApi};
@@ -1 +1 @@
1
- import{debugLog as e}from"../utils/debug.js";import{OPENFORT_AUTH_ERROR_CODES as t}from"../core/errors/authErrorCodes.js";import{ConfigurationError as i,OpenfortError as a}from"../core/errors/openfortError.js";import{withApiError as n}from"../core/errors/withApiError.js";import{AuthActionRequiredActions as s}from"../types/types.js";function r(e){if(!e)throw new a(t.INTERNAL_ERROR,"User data is missing");return{id:e.id||"",email:e.email,name:e.name??void 0,image:e.image??void 0,emailVerified:e.emailVerified,isAnonymous:e.isAnonymous,createdAt:e.createdAt,updatedAt:e.updatedAt,phoneNumber:e.phoneNumber,phoneNumberVerified:e.phoneNumberVerified}}function o(e){if(e)return{id:e.id,token:e.token,userId:e.userId,expiresAt:e.expiresAt,createdAt:e.createdAt,updatedAt:e.updatedAt}}class d{backendApiClientsInstance;publishableKeyInstance;setBackendApiClients(e,t){this.backendApiClientsInstance=e,this.publishableKeyInstance=t}get backendApiClients(){if(!this.backendApiClientsInstance)throw new i("Backend API clients not initialized");return this.backendApiClientsInstance}get publishableKey(){if(!this.publishableKeyInstance)throw new i("Publishable key not initialized");return this.publishableKeyInstance}buildAuthHeaders(e){return{"x-project-key":this.publishableKey,...e&&{authorization:`Bearer ${e}`}}}async initOAuth(e,t,i){return await n(async()=>(await this.backendApiClients.authenticationV2Api.socialSignIn({socialSignInRequest:{provider:e,callbackURL:t,scopes:i?.scopes?.split(" "),disableRedirect:i?.skipBrowserRedirect??!1}},{headers:{"x-project-key":`${this.publishableKey}`}})).data.url||"",{context:"initOAuth"})}async linkOAuthToAnonymous(e,t,i){return await n(async()=>(await this.backendApiClients.authenticationV2Api.socialSignIn({socialSignInRequest:{provider:t,callbackURL:i}},{headers:{authorization:`Bearer ${e.token}`,"x-project-key":`${this.publishableKey}`}})).data.url||"",{context:"initOAuth"})}async registerGuest(){return n(async()=>{const e=await this.backendApiClients.anonymousApi.signInAnonymousPost({headers:{"x-project-key":`${this.publishableKey}`}});return{token:e.data.token,user:r(e.data.user)}},{context:"registerGuest"})}async loginWithIdToken(e,t){const i={socialSignInRequest:{provider:e,idToken:{token:t}}};return await n(async()=>{const e=await this.backendApiClients.authenticationV2Api.socialSignIn(i,{headers:{"x-project-key":`${this.publishableKey}`}});return{token:e.data.token,user:r(e.data.user)}},{context:"loginWithIdToken"})}async authenticateThirdParty(e,t){const i={thirdPartyOAuthRequest:{provider:e,token:t}};return n(async()=>({userId:(await this.backendApiClients.userApi.thirdPartyV2(i,{headers:{"x-project-key":`${this.publishableKey}`}})).data.id}),{context:"authenticateThirdParty"})}async initSIWE(e){const t={siweNoncePostRequest:{walletAddress:e}};return{address:e,nonce:(await n(async()=>this.backendApiClients.siweApi.siweNoncePost(t,{headers:{"x-project-key":`${this.publishableKey}`}}),{context:"initSIWE"})).data.nonce}}async linkSIWE(e,t){const i={siweNoncePostRequest:{walletAddress:e}};return{address:e,nonce:(await n(async()=>this.backendApiClients.siweApi.linkSiweNoncePost(i,{headers:{authorization:`Bearer ${t.token}`,"x-project-key":`${this.publishableKey}`}}),{context:"linkSIWE"})).data.nonce}}async authenticateSIWE(e,t,i,a,s){const o={siweVerifyPostRequest:{signature:e,walletAddress:s,message:t,walletClientType:i,connectorType:a}};return n(async()=>{const e=await this.backendApiClients.siweApi.siweVerifyPost(o,{headers:{"x-project-key":`${this.publishableKey}`}}),t=e.data.user;return{token:e.data.token,user:r(t)}},{context:"authenticateSIWE"})}async loginEmailPassword(e,t){return n(async()=>{const i=(await this.backendApiClients.authenticationV2Api.signInEmailPost({signInEmailPostRequest:{email:e,password:t}},{headers:{"x-project-key":`${this.publishableKey}`}})).data;return{token:i.token,user:r(i.user)}},{context:"loginEmailPassword"})}async requestResetPassword(e,t){await n(async()=>{await this.backendApiClients.authenticationV2Api.requestPasswordResetPost({forgetPasswordPostRequest:{email:e,redirectTo:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"requestResetPassword"})}async resetPassword(e,t){return n(async()=>{await this.backendApiClients.authenticationV2Api.resetPasswordPost({resetPasswordPostRequest:{newPassword:e,token:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"resetPassword"})}async requestEmailVerification(e,t){await n(async()=>{await this.backendApiClients.authenticationV2Api.sendVerificationEmailPost({sendVerificationEmailPostRequest:{email:e,callbackURL:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"requestEmailVerification"})}async verifyEmail(e,t){return n(async()=>{await this.backendApiClients.authenticationV2Api.verifyEmailGet({token:e,callbackURL:t})},{context:"verifyEmail"})}async signupEmailPassword(e,t,i,a,o){return n(async()=>{const n=(await this.backendApiClients.authenticationV2Api.signUpEmailPost({signUpEmailPostRequest:{email:e,password:t,name:i,callbackURL:a}},{headers:this.buildAuthHeaders(o)})).data;return null===n.token?{action:s.ACTION_VERIFY_EMAIL}:{token:n.token,user:r(n.user)}},{context:"signupEmailPassword"})}async validateCredentials(t,i){e("Validating credentials with token:",t.token);const a=await this.getSessionWithToken(t,i);return{token:a.session.token,user:r(a.user),session:o(a.session)}}async logout(e){return n(async()=>{await this.backendApiClients.authenticationV2Api.signOutPost(void 0,{headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)})},{context:"logout"})}async getUser(e){return n(async()=>r((await this.backendApiClients.userApi.meV2({headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)})).data),{context:"getUser"})}async listAccounts(e){return n(async()=>(await this.backendApiClients.authenticationV2Api.listAccountsGet({headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)})).data,{context:"listAccounts"})}async linkOAuth(e,t,i,a){const s=a?.skipBrowserRedirect??!1,r={linkSocialPostRequest:{provider:t,callbackURL:i,scopes:a?.scopes?.split(" "),disableRedirect:s}},o=await n(async()=>this.backendApiClients.authenticationV2Api.linkSocialPost(r,{headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)}),{context:"linkOAuth"});return"undefined"!=typeof window&&!s&&o.data.url&&window.location.assign(o.data.url),o.data.url||""}async unlinkOAuth(e,t){const i={unlinkAccountPostRequest:{providerId:e}};return n(async()=>(await this.backendApiClients.authenticationV2Api.unlinkAccountPost(i,{headers:t.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t.token,"x-auth-provider":t.thirdPartyProvider,"x-token-type":t.thirdPartyTokenType}:this.buildAuthHeaders(t.token)})).data,{context:"unlinkOAuth"})}async addEmail(e,t,i){return n(async()=>(await this.backendApiClients.authenticationV2Api.changeEmailPost({changeEmailPostRequest:{newEmail:e,callbackURL:t}},{headers:i.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:this.buildAuthHeaders(i.token)})).data,{context:"addEmail"})}async unlinkWallet(e,t,i){const a={linkSiweUnlinkPostRequest:{walletAddress:e,chaindId:t}};return n(async()=>(await this.backendApiClients.siweApi.linkSiweUnlinkPost(a,{headers:i.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:this.buildAuthHeaders(i.token)})).data,{context:"unlinkWallet"})}async linkWallet(e,t,i,a,s,r,o){const d={siweVerifyPostRequest:{signature:e,message:t,walletAddress:s,chainId:r,walletClientType:i,connectorType:a}};return n(async()=>(await this.backendApiClients.siweApi.linkSiweVerifyPost(d,{headers:o.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":o.token,"x-auth-provider":o.thirdPartyProvider,"x-token-type":o.thirdPartyTokenType}:this.buildAuthHeaders(o.token)})).data,{context:"linkWallet"})}async requestEmailOTP(e,t){const i={emailOtpSendVerificationOtpPostRequest:{email:e,type:t}};await n(async()=>(await this.backendApiClients.emailOTPApi.emailOtpSendVerificationOtpPost(i,{headers:{"x-project-key":`${this.publishableKey}`}})).data,{context:"requestEmailOTP"})}async verifyEmailOtp(e,t,i){await n(async()=>(await this.backendApiClients.emailOTPApi.emailOtpVerifyEmailPost({emailOtpVerifyEmailPostRequest:{email:e,otp:t}},{headers:this.buildAuthHeaders(i)})).data,{context:"verifyEmailOtp"})}async loginWithEmailOTP(e,t,i){return await n(async()=>{const a=(await this.backendApiClients.emailOTPApi.signInEmailOtpPost({signInEmailOtpPostRequest:{email:e,otp:t}},{headers:this.buildAuthHeaders(i)})).data;return{token:a.token,user:r(a.user)}},{context:"loginWithEmailOTP"})}async requestPhoneOtp(e){const t={phoneNumberSendOtpPostRequest:{phoneNumber:e}};await n(async()=>(await this.backendApiClients.smsOTPApi.phoneNumberSendOtpPost(t,{headers:{"x-project-key":`${this.publishableKey}`}})).data,{context:"requestPhoneOtp"})}async loginWithSMSOTP(e,t){return await n(async()=>{const i=(await this.backendApiClients.smsOTPApi.phoneNumberVerifyPost({phoneNumberVerifyPostRequest:{code:t,phoneNumber:e}},{headers:{"x-project-key":`${this.publishableKey}`}})).data;return{token:i.token,user:r(i.user)}},{context:"loginWithSMSOTP"})}async linkSMSOTP(e,t,i){return await n(async()=>{const a=(await this.backendApiClients.smsOTPApi.phoneNumberVerifyPost({phoneNumberVerifyPostRequest:{code:t,phoneNumber:e,updatePhoneNumber:!0}},{headers:{authorization:`Bearer ${i.token}`,"x-project-key":`${this.publishableKey}`}})).data;return{token:a.token,user:r(a.user)}},{context:"linkSMSOTP"})}async getSessionWithToken(e,t){return await n(async()=>(await this.backendApiClients.authenticationV2Api.getSessionGet({disableCookieCache:t},{headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)})).data,{context:"getSessionWithToken"})}}export{d as AuthManager};
1
+ import{debugLog as e}from"../utils/debug.js";import{OPENFORT_AUTH_ERROR_CODES as t}from"../core/errors/authErrorCodes.js";import{ConfigurationError as i,OpenfortError as a}from"../core/errors/openfortError.js";import{withApiError as n}from"../core/errors/withApiError.js";import{AuthActionRequiredActions as s}from"../types/types.js";function r(e){if(!e)throw new a(t.INTERNAL_ERROR,"User data is missing");return{id:e.id||"",email:e.email,name:e.name??void 0,image:e.image??void 0,emailVerified:e.emailVerified,isAnonymous:e.isAnonymous,createdAt:e.createdAt,updatedAt:e.updatedAt,phoneNumber:e.phoneNumber,phoneNumberVerified:e.phoneNumberVerified,linkedAccounts:e.linkedAccounts}}function o(e){if(e)return{id:e.id,token:e.token,userId:e.userId,expiresAt:e.expiresAt,createdAt:e.createdAt,updatedAt:e.updatedAt}}class d{backendApiClientsInstance;publishableKeyInstance;setBackendApiClients(e,t){this.backendApiClientsInstance=e,this.publishableKeyInstance=t}get backendApiClients(){if(!this.backendApiClientsInstance)throw new i("Backend API clients not initialized");return this.backendApiClientsInstance}get publishableKey(){if(!this.publishableKeyInstance)throw new i("Publishable key not initialized");return this.publishableKeyInstance}buildAuthHeaders(e){return{"x-project-key":this.publishableKey,...e&&{authorization:`Bearer ${e}`}}}async initOAuth(e,t,i){return await n(async()=>(await this.backendApiClients.authenticationV2Api.socialSignIn({socialSignInRequest:{provider:e,callbackURL:t,scopes:i?.scopes?.split(" "),disableRedirect:i?.skipBrowserRedirect??!1}},{headers:{"x-project-key":`${this.publishableKey}`}})).data.url||"",{context:"initOAuth"})}async linkOAuthToAnonymous(e,t,i){return await n(async()=>(await this.backendApiClients.authenticationV2Api.socialSignIn({socialSignInRequest:{provider:t,callbackURL:i}},{headers:{authorization:`Bearer ${e.token}`,"x-project-key":`${this.publishableKey}`}})).data.url||"",{context:"initOAuth"})}async registerGuest(){return n(async()=>{const e=await this.backendApiClients.anonymousApi.signInAnonymousPost({headers:{"x-project-key":`${this.publishableKey}`}});return{token:e.data.token,user:r(e.data.user)}},{context:"registerGuest"})}async loginWithIdToken(e,t){const i={socialSignInRequest:{provider:e,idToken:{token:t}}};return await n(async()=>{const e=await this.backendApiClients.authenticationV2Api.socialSignIn(i,{headers:{"x-project-key":`${this.publishableKey}`}});return{token:e.data.token,user:r(e.data.user)}},{context:"loginWithIdToken"})}async authenticateThirdParty(e,t){const i={thirdPartyOAuthRequest:{provider:e,token:t}};return n(async()=>({userId:(await this.backendApiClients.userApi.thirdPartyV2(i,{headers:{"x-project-key":`${this.publishableKey}`}})).data.id}),{context:"authenticateThirdParty"})}async initSIWE(e){const t={siweNoncePostRequest:{walletAddress:e}};return{address:e,nonce:(await n(async()=>this.backendApiClients.siweApi.siweNoncePost(t,{headers:{"x-project-key":`${this.publishableKey}`}}),{context:"initSIWE"})).data.nonce}}async linkSIWE(e,t){const i={siweNoncePostRequest:{walletAddress:e}};return{address:e,nonce:(await n(async()=>this.backendApiClients.siweApi.linkSiweNoncePost(i,{headers:{authorization:`Bearer ${t.token}`,"x-project-key":`${this.publishableKey}`}}),{context:"linkSIWE"})).data.nonce}}async authenticateSIWE(e,t,i,a,s){const o={siweVerifyPostRequest:{signature:e,walletAddress:s,message:t,walletClientType:i,connectorType:a}};return n(async()=>{const e=await this.backendApiClients.siweApi.siweVerifyPost(o,{headers:{"x-project-key":`${this.publishableKey}`}}),t=e.data.user;return{token:e.data.token,user:r(t)}},{context:"authenticateSIWE"})}async loginEmailPassword(e,t){return n(async()=>{const i=(await this.backendApiClients.authenticationV2Api.signInEmailPost({signInEmailPostRequest:{email:e,password:t}},{headers:{"x-project-key":`${this.publishableKey}`}})).data;return{token:i.token,user:r(i.user)}},{context:"loginEmailPassword"})}async requestResetPassword(e,t){await n(async()=>{await this.backendApiClients.authenticationV2Api.requestPasswordResetPost({forgetPasswordPostRequest:{email:e,redirectTo:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"requestResetPassword"})}async resetPassword(e,t){return n(async()=>{await this.backendApiClients.authenticationV2Api.resetPasswordPost({resetPasswordPostRequest:{newPassword:e,token:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"resetPassword"})}async requestEmailVerification(e,t){await n(async()=>{await this.backendApiClients.authenticationV2Api.sendVerificationEmailPost({sendVerificationEmailPostRequest:{email:e,callbackURL:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"requestEmailVerification"})}async verifyEmail(e,t){return n(async()=>{await this.backendApiClients.authenticationV2Api.verifyEmailGet({token:e,callbackURL:t})},{context:"verifyEmail"})}async signupEmailPassword(e,t,i,a,o){return n(async()=>{const n=(await this.backendApiClients.authenticationV2Api.signUpEmailPost({signUpEmailPostRequest:{email:e,password:t,name:i,callbackURL:a}},{headers:this.buildAuthHeaders(o)})).data;return null===n.token?{action:s.ACTION_VERIFY_EMAIL}:{token:n.token,user:r(n.user)}},{context:"signupEmailPassword"})}async validateCredentials(t,i){e("Validating credentials with token:",t.token);const a=await this.getSessionWithToken(t,i);return{token:a.session.token,user:r(a.user),session:o(a.session)}}async logout(e){return n(async()=>{await this.backendApiClients.authenticationV2Api.signOutPost(void 0,{headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)})},{context:"logout"})}async getUser(e){return n(async()=>r((await this.backendApiClients.userApi.meV2({headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)})).data),{context:"getUser"})}async linkOAuth(e,t,i,a){const s=a?.skipBrowserRedirect??!1,r={linkSocialPostRequest:{provider:t,callbackURL:i,scopes:a?.scopes?.split(" "),disableRedirect:s}},o=await n(async()=>this.backendApiClients.authenticationV2Api.linkSocialPost(r,{headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)}),{context:"linkOAuth"});return"undefined"!=typeof window&&!s&&o.data.url&&window.location.assign(o.data.url),o.data.url||""}async unlinkOAuth(e,t){const i={unlinkAccountPostRequest:{providerId:e}};return n(async()=>(await this.backendApiClients.authenticationV2Api.unlinkAccountPost(i,{headers:t.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t.token,"x-auth-provider":t.thirdPartyProvider,"x-token-type":t.thirdPartyTokenType}:this.buildAuthHeaders(t.token)})).data,{context:"unlinkOAuth"})}async addEmail(e,t,i){return n(async()=>(await this.backendApiClients.authenticationV2Api.changeEmailPost({changeEmailPostRequest:{newEmail:e,callbackURL:t}},{headers:i.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:this.buildAuthHeaders(i.token)})).data,{context:"addEmail"})}async unlinkWallet(e,t,i){const a={linkSiweUnlinkPostRequest:{walletAddress:e,chaindId:t}};return n(async()=>(await this.backendApiClients.siweApi.linkSiweUnlinkPost(a,{headers:i.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:this.buildAuthHeaders(i.token)})).data,{context:"unlinkWallet"})}async linkWallet(e,t,i,a,s,r,o){const d={siweVerifyPostRequest:{signature:e,message:t,walletAddress:s,chainId:r,walletClientType:i,connectorType:a}};return n(async()=>(await this.backendApiClients.siweApi.linkSiweVerifyPost(d,{headers:o.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":o.token,"x-auth-provider":o.thirdPartyProvider,"x-token-type":o.thirdPartyTokenType}:this.buildAuthHeaders(o.token)})).data,{context:"linkWallet"})}async requestEmailOTP(e,t){const i={emailOtpSendVerificationOtpPostRequest:{email:e,type:t}};await n(async()=>(await this.backendApiClients.emailOTPApi.emailOtpSendVerificationOtpPost(i,{headers:{"x-project-key":`${this.publishableKey}`}})).data,{context:"requestEmailOTP"})}async verifyEmailOtp(e,t,i){await n(async()=>(await this.backendApiClients.emailOTPApi.emailOtpVerifyEmailPost({emailOtpVerifyEmailPostRequest:{email:e,otp:t}},{headers:this.buildAuthHeaders(i)})).data,{context:"verifyEmailOtp"})}async loginWithEmailOTP(e,t,i){return await n(async()=>{const a=(await this.backendApiClients.emailOTPApi.signInEmailOtpPost({signInEmailOtpPostRequest:{email:e,otp:t}},{headers:this.buildAuthHeaders(i)})).data;return{token:a.token,user:r(a.user)}},{context:"loginWithEmailOTP"})}async requestPhoneOtp(e){const t={phoneNumberSendOtpPostRequest:{phoneNumber:e}};await n(async()=>(await this.backendApiClients.smsOTPApi.phoneNumberSendOtpPost(t,{headers:{"x-project-key":`${this.publishableKey}`}})).data,{context:"requestPhoneOtp"})}async loginWithSMSOTP(e,t){return await n(async()=>{const i=(await this.backendApiClients.smsOTPApi.phoneNumberVerifyPost({phoneNumberVerifyPostRequest:{code:t,phoneNumber:e}},{headers:{"x-project-key":`${this.publishableKey}`}})).data;return{token:i.token,user:r(i.user)}},{context:"loginWithSMSOTP"})}async linkSMSOTP(e,t,i){return await n(async()=>{const a=(await this.backendApiClients.smsOTPApi.phoneNumberVerifyPost({phoneNumberVerifyPostRequest:{code:t,phoneNumber:e,updatePhoneNumber:!0}},{headers:{authorization:`Bearer ${i.token}`,"x-project-key":`${this.publishableKey}`}})).data;return{token:a.token,user:r(a.user)}},{context:"linkSMSOTP"})}async getSessionWithToken(e,t){return await n(async()=>(await this.backendApiClients.authenticationV2Api.getSessionGet({disableCookieCache:t},{headers:e.thirdPartyProvider?{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}:this.buildAuthHeaders(e.token)})).data,{context:"getSessionWithToken"})}}export{d as AuthManager};
@@ -1 +1 @@
1
- const o="1.0.1",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
1
+ const o="1.0.3",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
@@ -1 +1 @@
1
- import{Account as e}from"../core/configuration/account.js";import{Authentication as i}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as t}from"../core/errors/authErrorCodes.js";import{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 y from"./messaging/browserMessenger/connect.js";import"./messaging/browserMessenger/backwardCompatibility.js";import{isErrorResponse as f,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 E,ExportPrivateKeyRequest as T,SetRecoveryMethodRequest as b,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=y({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}`)}}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(f(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 f(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 f(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),f(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 E(h(),e,await this.buildRequestConfiguration()),n=await i.switchChain(t);return f(n)&&this.handleError(n),n}async export(){const e=await this.ensureConnection(),i=new T(h(),await this.buildRequestConfiguration()),t=await e.export(i);return f(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 b(h(),e,await this.buildRequestConfiguration(),i,t,n,r),a=await o.setRecoveryMethod(s);f(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 f(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);f(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 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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfort/openfort-js",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
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",