@openfort/openfort-js 1.3.1 → 1.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/sdk/src/api/embeddedWallet.cjs +1 -1
- package/dist/cjs/sdk/src/auth/authManager.cjs +1 -1
- package/dist/cjs/sdk/src/utils/debug.cjs +1 -1
- package/dist/cjs/sdk/src/version.cjs +1 -1
- package/dist/sdk/src/api/embeddedWallet.js +1 -1
- package/dist/sdk/src/auth/authManager.js +1 -1
- package/dist/sdk/src/utils/debug.js +1 -1
- package/dist/sdk/src/version.js +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.cjs"),r=require("../core/errors/openfortError.cjs"),t=require("../core/passkey/handler.cjs"),s=require("../core/config/config.cjs"),n=require("../core/configuration/account.cjs"),a=require("../core/configuration/authentication.cjs"),i=require("../core/errors/authErrorCodes.cjs"),o=require("../core/errors/withApiError.cjs"),d=require("../types/types.cjs"),c=require("../utils/debug.cjs"),g=require("../utils/observe.cjs"),h=require("../wallets/embedded.cjs"),u=require("../wallets/evm/evmProvider.cjs");require("../wallets/evm/types.cjs");var y=require("../wallets/evm/provider/eip6963.cjs"),l=require("../wallets/evm/walletHelpers.cjs"),m=require("../wallets/iframeManager.cjs"),f=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,n){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=s,this.passkeyHandler=n,this.eventEmitter.on(d.OpenfortEvents.ON_LOGOUT,()=>{c.debugLog("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=s.SDKConfiguration.getInstance();if(!t)throw new r.ConfigurationError("Configuration not found");return new e.BackendApiClients({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey,nativeAppIdentifier:t.nativeAppIdentifier})}async getIframeManager(){if(c.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(c.debugLog("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;c.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return c.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,c.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw c.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){c.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=s.SDKConfiguration.getInstance();if(!e)throw c.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new r.ConfigurationError("Configuration not found");let t;if(c.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)c.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(c.debugLog("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new f.ReactNativeMessenger(this.messagePoster),c.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{c.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new p({remoteWindow:r.contentWindow,allowedOrigins:[s]}),c.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return c.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new m.IframeManager(e,this.storage,t)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(c.debugLog("IframeManager has failed, clearing signer for recreation"),this.signer=null),this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();await e.initialize();return new h.EmbeddedSigner(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new r.ConfigurationError("Document is not available. Please provide a message poster for non-browser environments.");const t=document.getElementById("openfort-iframe");t&&t.remove();const s=document.createElement("iframe");return s.style.display="none",s.id="openfort-iframe",s.src=e,document.body.appendChild(s),s}async getPasskeyKey(e){const t=await a.Authentication.fromStorage(this.storage);if(!t?.userId)throw new r.AuthenticationError("auth","User is required for passkey key derivation. Logout and login again.",401);return this.passkeyHandler.deriveAndExportKey({id:e,seed:t.userId})}async getEntropy(e){switch(e.recoveryMethod){case d.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case d.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};case d.RecoveryMethod.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new r.ConfigurationError("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC},[t,s]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),a={chainId:e.chainId,entropy:s,accountType:e.accountType??d.AccountTypeEnum.SMART_ACCOUNT,chainType:e.chainType??d.ChainTypeEnum.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},i=await t.configure(a);return{id:i.id,chainId:i.chainId,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,factoryAddress:i.factoryAddress,salt:i.salt,createdAt:i.createdAt,implementationAddress:i.implementationAddress,recoveryMethod:n.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const s=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC},o=await a.Authentication.fromStorage(this.storage);if(!o)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(s.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!o.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:o.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");s.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[c,g]=await Promise.all([this.ensureSigner(),this.getEntropy(s)]),h=await c.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:g}),u={id:h.id,chainId:h.chainId,address:h.address,ownerAddress:h.ownerAddress,chainType:h.chainType,accountType:h.accountType,implementationType:h.implementationType,factoryAddress:h.factoryAddress,salt:h.salt,createdAt:h.createdAt,implementationAddress:h.implementationAddress,recoveryMethod:n.Account.parseRecoveryMethod(h.recoveryMethod),recoveryMethodDetails:h.recoveryMethodDetails};return this.eventEmitter.emit(d.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,u),u}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC};if(t.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!t.passkeyInfo?.passkeyId)throw new r.ConfigurationError("Passkey ID must be provided for passkey recovery");t.passkeyInfo={passkeyId:t.passkeyInfo.passkeyId}}const[s,a]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),i=await s.recover({account:e.account,entropy:a}),o={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:n.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:s=!0,arrayifyMessage:a=!1}=r||{},i=await n.Account.fromStorage(this.storage);return await t.sign(e,a,s,i?.chainType)}async signTypedData(e,t,s){await this.validateAndRefreshToken();const a=await this.ensureSigner(),o=await n.Account.fromStorage(this.storage);if(!o)throw new r.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No account found");const d={...t};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),g=c.hash(e,d,s);return await l.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,s){await this.validateAndRefreshToken();const o=await this.ensureSigner(),c=await a.Authentication.fromStorage(this.storage);if(!c)throw new r.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 n.Account.fromStorage(this.storage);if(!e)throw new r.ConfigurationError("missing account");const t=e?.recoveryMethodDetails?.passkeyId;if(!t)throw new r.ConfigurationError("missing passkey id for account");if(!c.userId)throw new r.ConfigurationError("User ID is required for passkey key derivation");u={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:c.userId})}}else if(s.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!c.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:c.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");u={passkeyId:e.id,passkeyKey:e.key},y={passkeyId:e.id}}if(e.recoveryMethod===d.RecoveryMethod.PASSWORD?g=e.password:s.recoveryMethod===d.RecoveryMethod.PASSWORD&&(g=s.password),e.recoveryMethod===d.RecoveryMethod.AUTOMATIC?h=e.encryptionSession:s.recoveryMethod===d.RecoveryMethod.AUTOMATIC&&(h=s.encryptionSession),!g&&!h)throw new r.ConfigurationError("Password or encryption session is not provided");await o.setRecoveryMethod({recoveryMethod:s.recoveryMethod,recoveryPassword:g,encryptionSession:h,passkeyInfo:u});const l=await n.Account.fromStorage(this.storage);l&&new n.Account({...l,recoveryMethod:s.recoveryMethod,recoveryMethodDetails:y}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await n.Account.fromStorage(this.storage);if(!e)throw new r.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No signer configured");if(!await a.Authentication.fromStorage(this.storage))throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:n.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const t={...e},d=s.SDKConfiguration.getInstance();if(!d)throw new r.ConfigurationError("Configuration not found");const c=await a.Authentication.fromStorage(this.storage);if(!c)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),o.withApiError(async()=>(await this.backendApiClients.accountsV2Api.getAccountsV2(t,{headers:c.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}:{authorization:`Bearer ${c.token}`,"x-project-key":d.baseConfiguration.publishableKey}})).data.data.map(e=>({chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:n.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 n.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}}watchEmbeddedState(e){return g.observe("watchEmbeddedState",{onChange:e.onChange,onError:e.onError},r=>{let t;const s=async()=>{try{const e=await this.getEmbeddedState();t!==e&&(r.onChange?.(e,t),t=e)}catch(e){r.onError?.(e instanceof Error?e:new Error(String(e)))}};s();const n=()=>s(),a=()=>s(),i=()=>s(),o=()=>s();this.eventEmitter.on(d.OpenfortEvents.ON_AUTH_SUCCESS,n),this.eventEmitter.on(d.OpenfortEvents.ON_LOGOUT,a),this.eventEmitter.on(d.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,i),this.eventEmitter.on(d.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o);const c=setInterval(s,e.pollingInterval??2e3);return()=>{clearInterval(c),this.eventEmitter.off(d.OpenfortEvents.ON_AUTH_SUCCESS,n),this.eventEmitter.off(d.OpenfortEvents.ON_LOGOUT,a),this.eventEmitter.off(d.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,i),this.eventEmitter.off(d.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o)}})}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await a.Authentication.fromStorage(this.storage),s=await n.Account.fromStorage(this.storage);return this.provider?this.provider&&r.feeSponsorship&&this.provider.updateFeeSponsorship(r.feeSponsorship):(this.provider=new u.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,feeSponsorshipId:r.feeSponsorship,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&y.announceProvider({info:{...y.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=s.SDKConfiguration.getInstance();if(!e)throw new r.ConfigurationError("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new r.ConfigurationError("Invalid message poster");this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleLogout(){if("undefined"==typeof document&&!this.messagePoster)return c.debugLog("Skipping signer disconnect: no messagePoster available in non-browser environment"),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,void(this.signerPromise=null);try{const e=await this.ensureSigner();await e.disconnect()}catch{}this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void c.debugLog("Invalid message received:",e);c.debugLog("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const r="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(r&&this.messenger&&this.messagePoster)return c.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();c.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&c.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),c.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),c.debugLog("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}};
|
|
1
|
+
"use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.cjs"),r=require("../core/errors/openfortError.cjs"),t=require("../core/passkey/handler.cjs"),s=require("../core/config/config.cjs"),n=require("../core/configuration/account.cjs"),a=require("../core/configuration/authentication.cjs"),i=require("../core/errors/authErrorCodes.cjs"),o=require("../core/errors/withApiError.cjs"),d=require("../storage/istorage.cjs"),c=require("../types/types.cjs"),g=require("../utils/debug.cjs"),h=require("../utils/observe.cjs"),u=require("../wallets/embedded.cjs"),y=require("../wallets/evm/evmProvider.cjs");require("../wallets/evm/types.cjs");var l=require("../wallets/evm/provider/eip6963.cjs"),m=require("../wallets/evm/walletHelpers.cjs"),f=require("../wallets/iframeManager.cjs"),p=require("../wallets/messaging/ReactNativeMessenger.cjs");require("../wallets/messaging/browserMessenger/backwardCompatibility.cjs");var E=require("../wallets/messaging/browserMessenger/messengers/WindowMessenger.cjs");exports.EmbeddedWalletApi=class{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,r,t,s,n){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=s,this.passkeyHandler=n,this.eventEmitter.on(c.OpenfortEvents.ON_LOGOUT,()=>{g.debugLog("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=s.SDKConfiguration.getInstance();if(!t)throw new r.ConfigurationError("Configuration not found");return new e.BackendApiClients({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey,nativeAppIdentifier:t.nativeAppIdentifier})}async getIframeManager(){if(g.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(g.debugLog("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return g.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return g.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;g.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return g.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,g.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw g.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){g.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=s.SDKConfiguration.getInstance();if(!e)throw g.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new r.ConfigurationError("Configuration not found");let t;if(g.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)g.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(g.debugLog("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new p.ReactNativeMessenger(this.messagePoster),g.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{g.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new E({remoteWindow:r.contentWindow,allowedOrigins:[s]}),g.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return g.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new f.IframeManager(e,this.storage,t)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(g.debugLog("IframeManager has failed, clearing signer for recreation"),this.signer=null),this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();await e.initialize();return new u.EmbeddedSigner(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new r.ConfigurationError("Document is not available. Please provide a message poster for non-browser environments.");const t=document.getElementById("openfort-iframe");t&&t.remove();const s=document.createElement("iframe");return s.style.display="none",s.id="openfort-iframe",s.src=e,document.body.appendChild(s),s}async getPasskeyKey(e){const t=await a.Authentication.fromStorage(this.storage);if(!t?.userId)throw new r.AuthenticationError("auth","User is required for passkey key derivation. Logout and login again.",401);return this.passkeyHandler.deriveAndExportKey({id:e,seed:t.userId})}async getEntropy(e){switch(e.recoveryMethod){case c.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case c.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};case c.RecoveryMethod.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new r.ConfigurationError("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC},[t,s]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),a={chainId:e.chainId,entropy:s,accountType:e.accountType??c.AccountTypeEnum.SMART_ACCOUNT,chainType:e.chainType??c.ChainTypeEnum.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},i=await t.configure(a);return{id:i.id,chainId:i.chainId,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,factoryAddress:i.factoryAddress,salt:i.salt,createdAt:i.createdAt,implementationAddress:i.implementationAddress,recoveryMethod:n.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const s=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC},o=await a.Authentication.fromStorage(this.storage);if(!o)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(s.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!o.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:o.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");s.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[d,g]=await Promise.all([this.ensureSigner(),this.getEntropy(s)]),h=await d.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:g}),u={id:h.id,chainId:h.chainId,address:h.address,ownerAddress:h.ownerAddress,chainType:h.chainType,accountType:h.accountType,implementationType:h.implementationType,factoryAddress:h.factoryAddress,salt:h.salt,createdAt:h.createdAt,implementationAddress:h.implementationAddress,recoveryMethod:n.Account.parseRecoveryMethod(h.recoveryMethod),recoveryMethodDetails:h.recoveryMethodDetails};return this.eventEmitter.emit(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,u),u}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:c.RecoveryMethod.AUTOMATIC};if(t.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!t.passkeyInfo?.passkeyId)throw new r.ConfigurationError("Passkey ID must be provided for passkey recovery");t.passkeyInfo={passkeyId:t.passkeyInfo.passkeyId}}const[s,a]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),i=await s.recover({account:e.account,entropy:a}),o={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:n.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(c.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o),o}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:s=!0,arrayifyMessage:a=!1}=r||{},i=await n.Account.fromStorage(this.storage);return await t.sign(e,a,s,i?.chainType)}async signTypedData(e,t,s){await this.validateAndRefreshToken();const a=await this.ensureSigner(),o=await n.Account.fromStorage(this.storage);if(!o)throw new r.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No account found");const d={...t};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),g=c.hash(e,d,s);return await m.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,s){await this.validateAndRefreshToken();const o=await this.ensureSigner(),d=await a.Authentication.fromStorage(this.storage);if(!d)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");let g,h,u,y;if(e.recoveryMethod===c.RecoveryMethod.PASSKEY){const e=await n.Account.fromStorage(this.storage);if(!e)throw new r.ConfigurationError("missing account");const t=e?.recoveryMethodDetails?.passkeyId;if(!t)throw new r.ConfigurationError("missing passkey id for account");if(!d.userId)throw new r.ConfigurationError("User ID is required for passkey key derivation");u={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:d.userId})}}else if(s.recoveryMethod===c.RecoveryMethod.PASSKEY){if(!d.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:d.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");u={passkeyId:e.id,passkeyKey:e.key},y={passkeyId:e.id}}if(e.recoveryMethod===c.RecoveryMethod.PASSWORD?g=e.password:s.recoveryMethod===c.RecoveryMethod.PASSWORD&&(g=s.password),e.recoveryMethod===c.RecoveryMethod.AUTOMATIC?h=e.encryptionSession:s.recoveryMethod===c.RecoveryMethod.AUTOMATIC&&(h=s.encryptionSession),!g&&!h)throw new r.ConfigurationError("Password or encryption session is not provided");await o.setRecoveryMethod({recoveryMethod:s.recoveryMethod,recoveryPassword:g,encryptionSession:h,passkeyInfo:u});const l=await n.Account.fromStorage(this.storage);l&&new n.Account({...l,recoveryMethod:s.recoveryMethod,recoveryMethodDetails:y}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await n.Account.fromStorage(this.storage);if(!e)throw new r.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No signer configured");if(!await a.Authentication.fromStorage(this.storage))throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:n.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const t={...e},d=s.SDKConfiguration.getInstance();if(!d)throw new r.ConfigurationError("Configuration not found");const c=await a.Authentication.fromStorage(this.storage);if(!c)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),o.withApiError(async()=>(await this.backendApiClients.accountsV2Api.getAccountsV2(t,{headers:c.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}:{authorization:`Bearer ${c.token}`,"x-project-key":d.baseConfiguration.publishableKey}})).data.data.map(e=>({chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:n.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await a.Authentication.fromStorage(this.storage))return c.EmbeddedState.UNAUTHENTICATED;return await n.Account.fromStorage(this.storage)?c.EmbeddedState.READY:c.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return g.debugLog("Failed to get embedded state:",e),c.EmbeddedState.UNAUTHENTICATED}}watchEmbeddedState(e){return h.observe("watchEmbeddedState",{onChange:e.onChange,onError:e.onError},r=>{let t;const s=async()=>{try{const e=await this.getEmbeddedState();t!==e&&(r.onChange?.(e,t),t=e)}catch(e){r.onError?.(e instanceof Error?e:new Error(String(e)))}};s();const n=()=>s(),a=()=>s(),i=()=>s(),o=()=>s();this.eventEmitter.on(c.OpenfortEvents.ON_AUTH_SUCCESS,n),this.eventEmitter.on(c.OpenfortEvents.ON_LOGOUT,a),this.eventEmitter.on(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,i),this.eventEmitter.on(c.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o);const d=setInterval(s,e.pollingInterval??2e3);return()=>{clearInterval(d),this.eventEmitter.off(c.OpenfortEvents.ON_AUTH_SUCCESS,n),this.eventEmitter.off(c.OpenfortEvents.ON_LOGOUT,a),this.eventEmitter.off(c.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,i),this.eventEmitter.off(c.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o)}})}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await a.Authentication.fromStorage(this.storage),s=await n.Account.fromStorage(this.storage);return this.provider?this.provider&&r.feeSponsorship&&this.provider.updateFeeSponsorship(r.feeSponsorship):(this.provider=new y.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,feeSponsorshipId:r.feeSponsorship,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&l.announceProvider({info:{...l.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 g.debugLog("Ping failed:",e),!1}}getURL(){const e=s.SDKConfiguration.getInstance();if(!e)throw new r.ConfigurationError("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new r.ConfigurationError("Invalid message poster");this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleLogout(){if(this.storage.remove(d.StorageKeys.ACCOUNT),"undefined"==typeof document&&!this.messagePoster)return g.debugLog("Skipping signer disconnect: no messagePoster available in non-browser environment"),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,void(this.signerPromise=null);try{const e=await this.ensureSigner();await e.disconnect()}catch{}this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void g.debugLog("Invalid message received:",e);g.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 g.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();g.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&g.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),g.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),g.debugLog("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}};
|
|
@@ -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 s(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 n(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.authApi.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.authApi.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.authApi.signInAnonymousPost({headers:{"x-project-key":`${this.publishableKey}`}});return{token:e.data.token,user:s(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.authApi.socialSignIn(i,{headers:{"x-project-key":`${this.publishableKey}`}});return{token:e.data.token,user:s(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.authApi.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.authApi.linkSiweNoncePost(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)}),{context:"linkSIWE"})).data.nonce}}async authenticateSIWE(e,t,i,r,n){const o={siweVerifyPostRequest:{signature:e,walletAddress:n,message:t,walletClientType:i,connectorType:r}};return a.withApiError(async()=>{const e=await this.backendApiClients.authApi.siweVerifyPost(o,{headers:{"x-project-key":`${this.publishableKey}`}}),t=e.data.user;return{token:e.data.token,user:s(t)}},{context:"authenticateSIWE"})}async loginEmailPassword(e,t){return a.withApiError(async()=>{const i=(await this.backendApiClients.authApi.signInEmailPost({signInEmailPostRequest:{email:e,password:t}},{headers:{"x-project-key":`${this.publishableKey}`}})).data;return{token:i.token,user:s(i.user)}},{context:"loginEmailPassword"})}async requestResetPassword(e,t){await a.withApiError(async()=>{await this.backendApiClients.authApi.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.authApi.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.authApi.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.authApi.verifyEmailGet({token:e,callbackURL:t})},{context:"verifyEmail"})}async signupEmailPassword(e,t,i,n,o){return a.withApiError(async()=>{const a=(await this.backendApiClients.authApi.signUpEmailPost({signUpEmailPostRequest:{email:e,password:t,name:i,callbackURL:n}},{headers:this.buildAuthHeaders(o)})).data;return null===a.token?{action:r.AuthActionRequiredActions.ACTION_VERIFY_EMAIL}:{token:a.token,user:s(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:s(a.user),session:n(a.session)}}async logout(e){return a.withApiError(async()=>{await this.backendApiClients.authApi.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()=>s((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 s=r?.skipBrowserRedirect??!1,n={linkSocialPostRequest:{provider:t,callbackURL:i,scopes:r?.scopes?.split(" "),disableRedirect:s}},o=await a.withApiError(async()=>this.backendApiClients.authApi.linkSocialPost(n,{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 a.withApiError(async()=>(await this.backendApiClients.authApi.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.authApi.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.authApi.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,s,n,o){const h={siweVerifyPostRequest:{signature:e,message:t,walletAddress:s,chainId:n,walletClientType:i,connectorType:r}};return a.withApiError(async()=>(await this.backendApiClients.authApi.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.authApi.emailOtpSendVerificationOtpPost(i,{headers:{"x-project-key":`${this.publishableKey}`}})).data,{context:"requestEmailOTP"})}async verifyEmailOtp(e,t,i){await a.withApiError(async()=>(await this.backendApiClients.authApi.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.authApi.signInEmailOtpPost({signInEmailOtpPostRequest:{email:e,otp:t}},{headers:this.buildAuthHeaders(i)})).data;return{token:a.token,user:s(a.user)}},{context:"loginWithEmailOTP"})}async requestPhoneOtp(e){const t={phoneNumberSendOtpPostRequest:{phoneNumber:e}};await a.withApiError(async()=>(await this.backendApiClients.authApi.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.authApi.phoneNumberVerifyPost({phoneNumberVerifyPostRequest:{code:t,phoneNumber:e}},{headers:{"x-project-key":`${this.publishableKey}`}})).data;return{token:i.token,user:s(i.user)}},{context:"loginWithSMSOTP"})}async linkSMSOTP(e,t,i){return await a.withApiError(async()=>{const a=(await this.backendApiClients.authApi.phoneNumberVerifyPost({phoneNumberVerifyPostRequest:{code:t,phoneNumber:e,updatePhoneNumber:!0}},{headers:{authorization:`Bearer ${i.token}`,"x-project-key":`${this.publishableKey}`}})).data;return{token:a.token,user:s(a.user)}},{context:"linkSMSOTP"})}async getSessionWithToken(e,t){return await a.withApiError(async()=>(await this.backendApiClients.authApi.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 s(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 n(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.authApi.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.authApi.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.authApi.signInAnonymousPost({headers:{"x-project-key":`${this.publishableKey}`}});return{token:e.data.token,user:s(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.authApi.socialSignIn(i,{headers:{"x-project-key":`${this.publishableKey}`}});return{token:e.data.token,user:s(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.authApi.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.authApi.linkSiweNoncePost(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)}),{context:"linkSIWE"})).data.nonce}}async authenticateSIWE(e,t,i,r,n){const o={siweVerifyPostRequest:{signature:e,walletAddress:n,message:t,walletClientType:i,connectorType:r}};return a.withApiError(async()=>{const e=await this.backendApiClients.authApi.siweVerifyPost(o,{headers:{"x-project-key":`${this.publishableKey}`}}),t=e.data.user;return{token:e.data.token,user:s(t)}},{context:"authenticateSIWE"})}async loginEmailPassword(e,t){return a.withApiError(async()=>{const i=(await this.backendApiClients.authApi.signInEmailPost({signInEmailPostRequest:{email:e,password:t}},{headers:{"x-project-key":`${this.publishableKey}`}})).data;return{token:i.token,user:s(i.user)}},{context:"loginEmailPassword"})}async requestResetPassword(e,t){await a.withApiError(async()=>{await this.backendApiClients.authApi.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.authApi.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.authApi.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.authApi.verifyEmailGet({token:e,callbackURL:t})},{context:"verifyEmail"})}async signupEmailPassword(e,t,i,n,o){return a.withApiError(async()=>{const a=(await this.backendApiClients.authApi.signUpEmailPost({signUpEmailPostRequest:{email:e,password:t,name:i,callbackURL:n}},{headers:this.buildAuthHeaders(o)})).data;return null===a.token?{action:r.AuthActionRequiredActions.ACTION_VERIFY_EMAIL}:{token:a.token,user:s(a.user)}},{context:"signupEmailPassword"})}async validateCredentials(t,i){e.debugLog("Validating credentials...");const a=await this.getSessionWithToken(t,i);return{token:a.session.token,user:s(a.user),session:n(a.session)}}async logout(e){return a.withApiError(async()=>{await this.backendApiClients.authApi.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()=>s((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 s=r?.skipBrowserRedirect??!1,n={linkSocialPostRequest:{provider:t,callbackURL:i,scopes:r?.scopes?.split(" "),disableRedirect:s}},o=await a.withApiError(async()=>this.backendApiClients.authApi.linkSocialPost(n,{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 a.withApiError(async()=>(await this.backendApiClients.authApi.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.authApi.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.authApi.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,s,n,o){const h={siweVerifyPostRequest:{signature:e,message:t,walletAddress:s,chainId:n,walletClientType:i,connectorType:r}};return a.withApiError(async()=>(await this.backendApiClients.authApi.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.authApi.emailOtpSendVerificationOtpPost(i,{headers:{"x-project-key":`${this.publishableKey}`}})).data,{context:"requestEmailOTP"})}async verifyEmailOtp(e,t,i){await a.withApiError(async()=>(await this.backendApiClients.authApi.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.authApi.signInEmailOtpPost({signInEmailOtpPostRequest:{email:e,otp:t}},{headers:this.buildAuthHeaders(i)})).data;return{token:a.token,user:s(a.user)}},{context:"loginWithEmailOTP"})}async requestPhoneOtp(e){const t={phoneNumberSendOtpPostRequest:{phoneNumber:e}};await a.withApiError(async()=>(await this.backendApiClients.authApi.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.authApi.phoneNumberVerifyPost({phoneNumberVerifyPostRequest:{code:t,phoneNumber:e}},{headers:{"x-project-key":`${this.publishableKey}`}})).data;return{token:i.token,user:s(i.user)}},{context:"loginWithSMSOTP"})}async linkSMSOTP(e,t,i){return await a.withApiError(async()=>{const a=(await this.backendApiClients.authApi.phoneNumberVerifyPost({phoneNumberVerifyPostRequest:{code:t,phoneNumber:e,updatePhoneNumber:!0}},{headers:{authorization:`Bearer ${i.token}`,"x-project-key":`${this.publishableKey}`}})).data;return{token:a.token,user:s(a.user)}},{context:"linkSMSOTP"})}async getSessionWithToken(e,t){return await a.withApiError(async()=>(await this.backendApiClients.authApi.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";var
|
|
1
|
+
"use strict";var n=require("../core/config/config.cjs");function e(n){return("object"==typeof n&&null!==n?JSON.stringify(n):String(n)).replace(/[\r\n]/g,"\\n")}exports.debugLog=function(...t){const o=n.SDKConfiguration.getInstance();o?.debug&&console.log(`${(new Date).toISOString()} [SDK]`,...t.map(e))};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.3.
|
|
1
|
+
"use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.3.2";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{ConfigurationError as t,AuthenticationError as r,SessionError as s,SignerError as a}from"../core/errors/openfortError.js";import{PasskeyHandler as i}from"../core/passkey/handler.js";import{SDKConfiguration as n}from"../core/config/config.js";import{Account as o}from"../core/configuration/account.js";import{Authentication as d}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as c}from"../core/errors/authErrorCodes.js";import{withApiError as h}from"../core/errors/withApiError.js";import{OpenfortEvents as m,RecoveryMethod as g,ChainTypeEnum as y,AccountTypeEnum as l,EmbeddedState as p}from"../types/types.js";import{debugLog as f}from"../utils/debug.js";import{observe as u}from"../utils/observe.js";import{EmbeddedSigner as w}from"../wallets/embedded.js";import{EvmProvider as A}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as E,openfortProviderInfo as v}from"../wallets/evm/provider/eip6963.js";import{signMessage as M}from"../wallets/evm/walletHelpers.js";import{IframeManager as D}from"../wallets/iframeManager.js";import{ReactNativeMessenger as I}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import S from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class T{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,t,r,s,a){this.storage=e,this.validateAndRefreshToken=t,this.ensureInitialized=r,this.eventEmitter=s,this.passkeyHandler=a,this.eventEmitter.on(m.ON_LOGOUT,()=>{f("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const r=n.getInstance();if(!r)throw new t("Configuration not found");return new e({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey,nativeAppIdentifier:r.nativeAppIdentifier})}async getIframeManager(){if(f("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(f("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return f("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return f("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;f("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return f("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,f("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw f("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){f("[HANDSHAKE DEBUG] createIframeManager starting");const e=n.getInstance();if(!e)throw f("[HANDSHAKE DEBUG] Configuration not found"),new t("Configuration not found");let r;if(f("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)f("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(f("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new I(this.messagePoster),f("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{f("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;r=new S({remoteWindow:t.contentWindow,allowedOrigins:[s]}),f("[HANDSHAKE DEBUG] Created WindowMessenger")}return f("[HANDSHAKE DEBUG] Creating IframeManager instance"),new D(e,this.storage,r)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(f("IframeManager has failed, clearing signer for recreation"),this.signer=null),this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();await e.initialize();return new w(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new t("Document is not available. Please provide a message poster for non-browser environments.");const r=document.getElementById("openfort-iframe");r&&r.remove();const s=document.createElement("iframe");return s.style.display="none",s.id="openfort-iframe",s.src=e,document.body.appendChild(s),s}async getPasskeyKey(e){const t=await d.fromStorage(this.storage);if(!t?.userId)throw new r("auth","User is required for passkey key derivation. Logout and login again.",401);return this.passkeyHandler.deriveAndExportKey({id:e,seed:t.userId})}async getEntropy(e){switch(e.recoveryMethod){case g.PASSWORD:return{recoveryPassword:e.password};case g.AUTOMATIC:return{encryptionSession:e.encryptionSession};case g.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new t("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:g.AUTOMATIC},[r,s]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),a={chainId:e.chainId,entropy:s,accountType:e.accountType??l.SMART_ACCOUNT,chainType:e.chainType??y.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},i=await r.configure(a);return{id:i.id,chainId:i.chainId,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,factoryAddress:i.factoryAddress,salt:i.salt,createdAt:i.createdAt,implementationAddress:i.implementationAddress,recoveryMethod:o.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:g.AUTOMATIC},a=await d.fromStorage(this.storage);if(!a)throw new s(c.NOT_LOGGED_IN,"missing authentication");if(r.recoveryMethod===g.PASSKEY){if(!a.userId)throw new t("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:a.userId});if(!e.key)throw new t("Passkey creation failed: no key material returned");r.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[n,h]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),y=await n.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),l={id:y.id,chainId:y.chainId,address:y.address,ownerAddress:y.ownerAddress,chainType:y.chainType,accountType:y.accountType,implementationType:y.implementationType,factoryAddress:y.factoryAddress,salt:y.salt,createdAt:y.createdAt,implementationAddress:y.implementationAddress,recoveryMethod:o.parseRecoveryMethod(y.recoveryMethod),recoveryMethodDetails:y.recoveryMethodDetails};return this.eventEmitter.emit(m.ON_EMBEDDED_WALLET_CREATED,l),l}async recover(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:g.AUTOMATIC};if(r.recoveryMethod===g.PASSKEY){if(!r.passkeyInfo?.passkeyId)throw new t("Passkey ID must be provided for passkey recovery");r.passkeyInfo={passkeyId:r.passkeyInfo.passkeyId}}const[s,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i=await s.recover({account:e.account,entropy:a}),n={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:o.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(m.ON_EMBEDDED_WALLET_RECOVERED,n),n}async signMessage(e,t){await this.validateAndRefreshToken();const r=await this.ensureSigner(),{hashMessage:s=!0,arrayifyMessage:a=!1}=t||{},i=await o.fromStorage(this.storage);return await r.sign(e,a,s,i?.chainType)}async signTypedData(e,t,r){await this.validateAndRefreshToken();const s=await this.ensureSigner(),i=await o.fromStorage(this.storage);if(!i)throw new a(c.MISSING_SIGNER,"No account found");const n={...t};delete n.EIP712Domain;const{_TypedDataEncoder:d}=await import("@ethersproject/hash"),h=d.hash(e,n,r);return await M({hash:h,implementationType:i.implementationType||i.type,chainId:Number(i.chainId),signer:s,address:i.address,ownerAddress:i.ownerAddress,factoryAddress:i.factoryAddress,salt:i.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,r){await this.validateAndRefreshToken();const a=await this.ensureSigner(),n=await d.fromStorage(this.storage);if(!n)throw new s(c.NOT_LOGGED_IN,"missing authentication");let h,m,y,l;if(e.recoveryMethod===g.PASSKEY){const e=await o.fromStorage(this.storage);if(!e)throw new t("missing account");const r=e?.recoveryMethodDetails?.passkeyId;if(!r)throw new t("missing passkey id for account");if(!n.userId)throw new t("User ID is required for passkey key derivation");y={passkeyId:r,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:r,seed:n.userId})}}else if(r.recoveryMethod===g.PASSKEY){if(!n.userId)throw new t("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:n.userId});if(!e.key)throw new t("Passkey creation failed: no key material returned");y={passkeyId:e.id,passkeyKey:e.key},l={passkeyId:e.id}}if(e.recoveryMethod===g.PASSWORD?h=e.password:r.recoveryMethod===g.PASSWORD&&(h=r.password),e.recoveryMethod===g.AUTOMATIC?m=e.encryptionSession:r.recoveryMethod===g.AUTOMATIC&&(m=r.encryptionSession),!h&&!m)throw new t("Password or encryption session is not provided");await a.setRecoveryMethod({recoveryMethod:r.recoveryMethod,recoveryPassword:h,encryptionSession:m,passkeyInfo:y});const p=await o.fromStorage(this.storage);p&&new o({...p,recoveryMethod:r.recoveryMethod,recoveryMethodDetails:l}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await o.fromStorage(this.storage);if(!e)throw new a(c.MISSING_SIGNER,"No signer configured");if(!await d.fromStorage(this.storage))throw new s(c.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:o.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const r={...e},a=n.getInstance();if(!a)throw new t("Configuration not found");const i=await d.fromStorage(this.storage);if(!i)throw new s(c.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),h(async()=>(await this.backendApiClients.accountsV2Api.getAccountsV2(r,{headers:i.thirdPartyProvider?{authorization:`Bearer ${a.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":a.baseConfiguration.publishableKey}})).data.data.map(e=>({chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:o.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await d.fromStorage(this.storage))return p.UNAUTHENTICATED;return await o.fromStorage(this.storage)?p.READY:p.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return f("Failed to get embedded state:",e),p.UNAUTHENTICATED}}watchEmbeddedState(e){return u("watchEmbeddedState",{onChange:e.onChange,onError:e.onError},t=>{let r;const s=async()=>{try{const e=await this.getEmbeddedState();r!==e&&(t.onChange?.(e,r),r=e)}catch(e){t.onError?.(e instanceof Error?e:new Error(String(e)))}};s();const a=()=>s(),i=()=>s(),n=()=>s(),o=()=>s();this.eventEmitter.on(m.ON_AUTH_SUCCESS,a),this.eventEmitter.on(m.ON_LOGOUT,i),this.eventEmitter.on(m.ON_EMBEDDED_WALLET_CREATED,n),this.eventEmitter.on(m.ON_EMBEDDED_WALLET_RECOVERED,o);const d=setInterval(s,e.pollingInterval??2e3);return()=>{clearInterval(d),this.eventEmitter.off(m.ON_AUTH_SUCCESS,a),this.eventEmitter.off(m.ON_LOGOUT,i),this.eventEmitter.off(m.ON_EMBEDDED_WALLET_CREATED,n),this.eventEmitter.off(m.ON_EMBEDDED_WALLET_RECOVERED,o)}})}async getEthereumProvider(e){await this.ensureInitialized();const t={announceProvider:!0,...e},r=await d.fromStorage(this.storage),s=await o.fromStorage(this.storage);return this.provider?this.provider&&t.feeSponsorship&&this.provider.updateFeeSponsorship(t.feeSponsorship):(this.provider=new A({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:r||void 0,backendApiClients:this.backendApiClients,feeSponsorshipId:t.feeSponsorship,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:t.chains}),t.announceProvider&&E({info:{...v,...t.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(t=>{setTimeout(t,e)});const t=await this.getIframeManager();if(!t.isLoaded())return!1;const r=await d.fromStorage(this.storage);if(r)try{return await t.getCurrentDevice(r.userId),!0}catch(e){return!1}return t.isLoaded()}catch(e){return f("Ping failed:",e),!1}}getURL(){const e=n.getInstance();if(!e)throw new t("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new t("Invalid message poster");this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleLogout(){if("undefined"==typeof document&&!this.messagePoster)return f("Skipping signer disconnect: no messagePoster available in non-browser environment"),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,void(this.signerPromise=null);try{const e=await this.ensureSigner();await e.disconnect()}catch{}this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void f("Invalid message received:",e);f("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const t="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(t&&this.messenger&&this.messagePoster)return f("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const r=await this.getIframeManager();f(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${r.isLoaded()}`),t&&!r.isLoaded()&&f("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),f("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await r.onMessage(e),f("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{T as EmbeddedWalletApi};
|
|
1
|
+
import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{ConfigurationError as r,AuthenticationError as t,SessionError as s,SignerError as a}from"../core/errors/openfortError.js";import{PasskeyHandler as i}from"../core/passkey/handler.js";import{SDKConfiguration as n}from"../core/config/config.js";import{Account as o}from"../core/configuration/account.js";import{Authentication as d}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as c}from"../core/errors/authErrorCodes.js";import{withApiError as h}from"../core/errors/withApiError.js";import{StorageKeys as m}from"../storage/istorage.js";import{OpenfortEvents as g,RecoveryMethod as y,ChainTypeEnum as l,AccountTypeEnum as p,EmbeddedState as f}from"../types/types.js";import{debugLog as u}from"../utils/debug.js";import{observe as w}from"../utils/observe.js";import{EmbeddedSigner as A}from"../wallets/embedded.js";import{EvmProvider as E}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as v,openfortProviderInfo as M}from"../wallets/evm/provider/eip6963.js";import{signMessage as D}from"../wallets/evm/walletHelpers.js";import{IframeManager as I}from"../wallets/iframeManager.js";import{ReactNativeMessenger as T}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import S from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class k{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,r,t,s,a){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=s,this.passkeyHandler=a,this.eventEmitter.on(g.ON_LOGOUT,()=>{u("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=n.getInstance();if(!t)throw new r("Configuration not found");return new e({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey,nativeAppIdentifier:t.nativeAppIdentifier})}async getIframeManager(){if(u("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(u("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return u("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return u("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;u("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return u("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,u("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw u("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){u("[HANDSHAKE DEBUG] createIframeManager starting");const e=n.getInstance();if(!e)throw u("[HANDSHAKE DEBUG] Configuration not found"),new r("Configuration not found");let t;if(u("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)u("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(u("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new T(this.messagePoster),u("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{u("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new S({remoteWindow:r.contentWindow,allowedOrigins:[s]}),u("[HANDSHAKE DEBUG] Created WindowMessenger")}return u("[HANDSHAKE DEBUG] Creating IframeManager instance"),new I(e,this.storage,t)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(u("IframeManager has failed, clearing signer for recreation"),this.signer=null),this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();await e.initialize();return new A(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new r("Document is not available. Please provide a message poster for non-browser environments.");const t=document.getElementById("openfort-iframe");t&&t.remove();const s=document.createElement("iframe");return s.style.display="none",s.id="openfort-iframe",s.src=e,document.body.appendChild(s),s}async getPasskeyKey(e){const r=await d.fromStorage(this.storage);if(!r?.userId)throw new t("auth","User is required for passkey key derivation. Logout and login again.",401);return this.passkeyHandler.deriveAndExportKey({id:e,seed:r.userId})}async getEntropy(e){switch(e.recoveryMethod){case y.PASSWORD:return{recoveryPassword:e.password};case y.AUTOMATIC:return{encryptionSession:e.encryptionSession};case y.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new r("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:y.AUTOMATIC},[t,s]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),a={chainId:e.chainId,entropy:s,accountType:e.accountType??p.SMART_ACCOUNT,chainType:e.chainType??l.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},i=await t.configure(a);return{id:i.id,chainId:i.chainId,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,factoryAddress:i.factoryAddress,salt:i.salt,createdAt:i.createdAt,implementationAddress:i.implementationAddress,recoveryMethod:o.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:y.AUTOMATIC},a=await d.fromStorage(this.storage);if(!a)throw new s(c.NOT_LOGGED_IN,"missing authentication");if(t.recoveryMethod===y.PASSKEY){if(!a.userId)throw new r("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:a.userId});if(!e.key)throw new r("Passkey creation failed: no key material returned");t.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[n,h]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),m=await n.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),l={id:m.id,chainId:m.chainId,address:m.address,ownerAddress:m.ownerAddress,chainType:m.chainType,accountType:m.accountType,implementationType:m.implementationType,factoryAddress:m.factoryAddress,salt:m.salt,createdAt:m.createdAt,implementationAddress:m.implementationAddress,recoveryMethod:o.parseRecoveryMethod(m.recoveryMethod),recoveryMethodDetails:m.recoveryMethodDetails};return this.eventEmitter.emit(g.ON_EMBEDDED_WALLET_CREATED,l),l}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:y.AUTOMATIC};if(t.recoveryMethod===y.PASSKEY){if(!t.passkeyInfo?.passkeyId)throw new r("Passkey ID must be provided for passkey recovery");t.passkeyInfo={passkeyId:t.passkeyInfo.passkeyId}}const[s,a]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),i=await s.recover({account:e.account,entropy:a}),n={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:o.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(g.ON_EMBEDDED_WALLET_RECOVERED,n),n}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:s=!0,arrayifyMessage:a=!1}=r||{},i=await o.fromStorage(this.storage);return await t.sign(e,a,s,i?.chainType)}async signTypedData(e,r,t){await this.validateAndRefreshToken();const s=await this.ensureSigner(),i=await o.fromStorage(this.storage);if(!i)throw new a(c.MISSING_SIGNER,"No account found");const n={...r};delete n.EIP712Domain;const{_TypedDataEncoder:d}=await import("@ethersproject/hash"),h=d.hash(e,n,t);return await D({hash:h,implementationType:i.implementationType||i.type,chainId:Number(i.chainId),signer:s,address:i.address,ownerAddress:i.ownerAddress,factoryAddress:i.factoryAddress,salt:i.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,t){await this.validateAndRefreshToken();const a=await this.ensureSigner(),n=await d.fromStorage(this.storage);if(!n)throw new s(c.NOT_LOGGED_IN,"missing authentication");let h,m,g,l;if(e.recoveryMethod===y.PASSKEY){const e=await o.fromStorage(this.storage);if(!e)throw new r("missing account");const t=e?.recoveryMethodDetails?.passkeyId;if(!t)throw new r("missing passkey id for account");if(!n.userId)throw new r("User ID is required for passkey key derivation");g={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:n.userId})}}else if(t.recoveryMethod===y.PASSKEY){if(!n.userId)throw new r("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:n.userId});if(!e.key)throw new r("Passkey creation failed: no key material returned");g={passkeyId:e.id,passkeyKey:e.key},l={passkeyId:e.id}}if(e.recoveryMethod===y.PASSWORD?h=e.password:t.recoveryMethod===y.PASSWORD&&(h=t.password),e.recoveryMethod===y.AUTOMATIC?m=e.encryptionSession:t.recoveryMethod===y.AUTOMATIC&&(m=t.encryptionSession),!h&&!m)throw new r("Password or encryption session is not provided");await a.setRecoveryMethod({recoveryMethod:t.recoveryMethod,recoveryPassword:h,encryptionSession:m,passkeyInfo:g});const p=await o.fromStorage(this.storage);p&&new o({...p,recoveryMethod:t.recoveryMethod,recoveryMethodDetails:l}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await o.fromStorage(this.storage);if(!e)throw new a(c.MISSING_SIGNER,"No signer configured");if(!await d.fromStorage(this.storage))throw new s(c.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:o.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const t={...e},a=n.getInstance();if(!a)throw new r("Configuration not found");const i=await d.fromStorage(this.storage);if(!i)throw new s(c.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),h(async()=>(await this.backendApiClients.accountsV2Api.getAccountsV2(t,{headers:i.thirdPartyProvider?{authorization:`Bearer ${a.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":a.baseConfiguration.publishableKey}})).data.data.map(e=>({chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:o.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await d.fromStorage(this.storage))return f.UNAUTHENTICATED;return await o.fromStorage(this.storage)?f.READY:f.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return u("Failed to get embedded state:",e),f.UNAUTHENTICATED}}watchEmbeddedState(e){return w("watchEmbeddedState",{onChange:e.onChange,onError:e.onError},r=>{let t;const s=async()=>{try{const e=await this.getEmbeddedState();t!==e&&(r.onChange?.(e,t),t=e)}catch(e){r.onError?.(e instanceof Error?e:new Error(String(e)))}};s();const a=()=>s(),i=()=>s(),n=()=>s(),o=()=>s();this.eventEmitter.on(g.ON_AUTH_SUCCESS,a),this.eventEmitter.on(g.ON_LOGOUT,i),this.eventEmitter.on(g.ON_EMBEDDED_WALLET_CREATED,n),this.eventEmitter.on(g.ON_EMBEDDED_WALLET_RECOVERED,o);const d=setInterval(s,e.pollingInterval??2e3);return()=>{clearInterval(d),this.eventEmitter.off(g.ON_AUTH_SUCCESS,a),this.eventEmitter.off(g.ON_LOGOUT,i),this.eventEmitter.off(g.ON_EMBEDDED_WALLET_CREATED,n),this.eventEmitter.off(g.ON_EMBEDDED_WALLET_RECOVERED,o)}})}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await d.fromStorage(this.storage),s=await o.fromStorage(this.storage);return this.provider?this.provider&&r.feeSponsorship&&this.provider.updateFeeSponsorship(r.feeSponsorship):(this.provider=new E({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,feeSponsorshipId:r.feeSponsorship,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&v({info:{...M,...r.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(r=>{setTimeout(r,e)});const r=await this.getIframeManager();if(!r.isLoaded())return!1;const t=await d.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return u("Ping failed:",e),!1}}getURL(){const e=n.getInstance();if(!e)throw new r("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new r("Invalid message poster");this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleLogout(){if(this.storage.remove(m.ACCOUNT),"undefined"==typeof document&&!this.messagePoster)return u("Skipping signer disconnect: no messagePoster available in non-browser environment"),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,void(this.signerPromise=null);try{const e=await this.ensureSigner();await e.disconnect()}catch{}this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void u("Invalid message received:",e);u("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const r="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(r&&this.messenger&&this.messagePoster)return u("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();u(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&u("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),u("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),u("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{k as EmbeddedWalletApi};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{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 s}from"../core/errors/withApiError.js";import{AuthActionRequiredActions as n}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 s(async()=>(await this.backendApiClients.authApi.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 s(async()=>(await this.backendApiClients.authApi.socialSignIn({socialSignInRequest:{provider:t,callbackURL:i}},{headers:{authorization:`Bearer ${e.token}`,"x-project-key":`${this.publishableKey}`}})).data.url||"",{context:"initOAuth"})}async registerGuest(){return s(async()=>{const e=await this.backendApiClients.authApi.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 s(async()=>{const e=await this.backendApiClients.authApi.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 s(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 s(async()=>this.backendApiClients.authApi.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 s(async()=>this.backendApiClients.authApi.linkSiweNoncePost(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)}),{context:"linkSIWE"})).data.nonce}}async authenticateSIWE(e,t,i,a,n){const o={siweVerifyPostRequest:{signature:e,walletAddress:n,message:t,walletClientType:i,connectorType:a}};return s(async()=>{const e=await this.backendApiClients.authApi.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 s(async()=>{const i=(await this.backendApiClients.authApi.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 s(async()=>{await this.backendApiClients.authApi.requestPasswordResetPost({forgetPasswordPostRequest:{email:e,redirectTo:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"requestResetPassword"})}async resetPassword(e,t){return s(async()=>{await this.backendApiClients.authApi.resetPasswordPost({resetPasswordPostRequest:{newPassword:e,token:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"resetPassword"})}async requestEmailVerification(e,t){await s(async()=>{await this.backendApiClients.authApi.sendVerificationEmailPost({sendVerificationEmailPostRequest:{email:e,callbackURL:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"requestEmailVerification"})}async verifyEmail(e,t){return s(async()=>{await this.backendApiClients.authApi.verifyEmailGet({token:e,callbackURL:t})},{context:"verifyEmail"})}async signupEmailPassword(e,t,i,a,o){return s(async()=>{const s=(await this.backendApiClients.authApi.signUpEmailPost({signUpEmailPostRequest:{email:e,password:t,name:i,callbackURL:a}},{headers:this.buildAuthHeaders(o)})).data;return null===s.token?{action:n.ACTION_VERIFY_EMAIL}:{token:s.token,user:r(s.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 s(async()=>{await this.backendApiClients.authApi.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 s(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 n=a?.skipBrowserRedirect??!1,r={linkSocialPostRequest:{provider:t,callbackURL:i,scopes:a?.scopes?.split(" "),disableRedirect:n}},o=await s(async()=>this.backendApiClients.authApi.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&&!n&&o.data.url&&window.location.assign(o.data.url),o.data.url||""}async unlinkOAuth(e,t){const i={unlinkAccountPostRequest:{providerId:e}};return s(async()=>(await this.backendApiClients.authApi.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 s(async()=>(await this.backendApiClients.authApi.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 s(async()=>(await this.backendApiClients.authApi.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,n,r,o){const d={siweVerifyPostRequest:{signature:e,message:t,walletAddress:n,chainId:r,walletClientType:i,connectorType:a}};return s(async()=>(await this.backendApiClients.authApi.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 s(async()=>(await this.backendApiClients.authApi.emailOtpSendVerificationOtpPost(i,{headers:{"x-project-key":`${this.publishableKey}`}})).data,{context:"requestEmailOTP"})}async verifyEmailOtp(e,t,i){await s(async()=>(await this.backendApiClients.authApi.emailOtpVerifyEmailPost({emailOtpVerifyEmailPostRequest:{email:e,otp:t}},{headers:this.buildAuthHeaders(i)})).data,{context:"verifyEmailOtp"})}async loginWithEmailOTP(e,t,i){return await s(async()=>{const a=(await this.backendApiClients.authApi.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 s(async()=>(await this.backendApiClients.authApi.phoneNumberSendOtpPost(t,{headers:{"x-project-key":`${this.publishableKey}`}})).data,{context:"requestPhoneOtp"})}async loginWithSMSOTP(e,t){return await s(async()=>{const i=(await this.backendApiClients.authApi.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 s(async()=>{const a=(await this.backendApiClients.authApi.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 s(async()=>(await this.backendApiClients.authApi.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 s}from"../core/errors/withApiError.js";import{AuthActionRequiredActions as n}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 s(async()=>(await this.backendApiClients.authApi.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 s(async()=>(await this.backendApiClients.authApi.socialSignIn({socialSignInRequest:{provider:t,callbackURL:i}},{headers:{authorization:`Bearer ${e.token}`,"x-project-key":`${this.publishableKey}`}})).data.url||"",{context:"initOAuth"})}async registerGuest(){return s(async()=>{const e=await this.backendApiClients.authApi.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 s(async()=>{const e=await this.backendApiClients.authApi.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 s(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 s(async()=>this.backendApiClients.authApi.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 s(async()=>this.backendApiClients.authApi.linkSiweNoncePost(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)}),{context:"linkSIWE"})).data.nonce}}async authenticateSIWE(e,t,i,a,n){const o={siweVerifyPostRequest:{signature:e,walletAddress:n,message:t,walletClientType:i,connectorType:a}};return s(async()=>{const e=await this.backendApiClients.authApi.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 s(async()=>{const i=(await this.backendApiClients.authApi.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 s(async()=>{await this.backendApiClients.authApi.requestPasswordResetPost({forgetPasswordPostRequest:{email:e,redirectTo:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"requestResetPassword"})}async resetPassword(e,t){return s(async()=>{await this.backendApiClients.authApi.resetPasswordPost({resetPasswordPostRequest:{newPassword:e,token:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"resetPassword"})}async requestEmailVerification(e,t){await s(async()=>{await this.backendApiClients.authApi.sendVerificationEmailPost({sendVerificationEmailPostRequest:{email:e,callbackURL:t}},{headers:{"x-project-key":`${this.publishableKey}`}})},{context:"requestEmailVerification"})}async verifyEmail(e,t){return s(async()=>{await this.backendApiClients.authApi.verifyEmailGet({token:e,callbackURL:t})},{context:"verifyEmail"})}async signupEmailPassword(e,t,i,a,o){return s(async()=>{const s=(await this.backendApiClients.authApi.signUpEmailPost({signUpEmailPostRequest:{email:e,password:t,name:i,callbackURL:a}},{headers:this.buildAuthHeaders(o)})).data;return null===s.token?{action:n.ACTION_VERIFY_EMAIL}:{token:s.token,user:r(s.user)}},{context:"signupEmailPassword"})}async validateCredentials(t,i){e("Validating credentials...");const a=await this.getSessionWithToken(t,i);return{token:a.session.token,user:r(a.user),session:o(a.session)}}async logout(e){return s(async()=>{await this.backendApiClients.authApi.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 s(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 n=a?.skipBrowserRedirect??!1,r={linkSocialPostRequest:{provider:t,callbackURL:i,scopes:a?.scopes?.split(" "),disableRedirect:n}},o=await s(async()=>this.backendApiClients.authApi.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&&!n&&o.data.url&&window.location.assign(o.data.url),o.data.url||""}async unlinkOAuth(e,t){const i={unlinkAccountPostRequest:{providerId:e}};return s(async()=>(await this.backendApiClients.authApi.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 s(async()=>(await this.backendApiClients.authApi.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 s(async()=>(await this.backendApiClients.authApi.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,n,r,o){const d={siweVerifyPostRequest:{signature:e,message:t,walletAddress:n,chainId:r,walletClientType:i,connectorType:a}};return s(async()=>(await this.backendApiClients.authApi.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 s(async()=>(await this.backendApiClients.authApi.emailOtpSendVerificationOtpPost(i,{headers:{"x-project-key":`${this.publishableKey}`}})).data,{context:"requestEmailOTP"})}async verifyEmailOtp(e,t,i){await s(async()=>(await this.backendApiClients.authApi.emailOtpVerifyEmailPost({emailOtpVerifyEmailPostRequest:{email:e,otp:t}},{headers:this.buildAuthHeaders(i)})).data,{context:"verifyEmailOtp"})}async loginWithEmailOTP(e,t,i){return await s(async()=>{const a=(await this.backendApiClients.authApi.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 s(async()=>(await this.backendApiClients.authApi.phoneNumberSendOtpPost(t,{headers:{"x-project-key":`${this.publishableKey}`}})).data,{context:"requestPhoneOtp"})}async loginWithSMSOTP(e,t){return await s(async()=>{const i=(await this.backendApiClients.authApi.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 s(async()=>{const a=(await this.backendApiClients.authApi.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 s(async()=>(await this.backendApiClients.authApi.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
|
-
import{SDKConfiguration as
|
|
1
|
+
import{SDKConfiguration as n}from"../core/config/config.js";function o(n){return("object"==typeof n&&null!==n?JSON.stringify(n):String(n)).replace(/[\r\n]/g,"\\n")}function t(...t){const e=n.getInstance();e?.debug&&console.log(`${(new Date).toISOString()} [SDK]`,...t.map(o))}export{t as debugLog};
|
package/dist/sdk/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="1.3.
|
|
1
|
+
const o="1.3.2",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openfort/openfort-js",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.2",
|
|
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",
|
|
@@ -24,10 +24,10 @@
|
|
|
24
24
|
"@ethersproject/providers": "^5.8.0",
|
|
25
25
|
"@ethersproject/transactions": "^5.8.0",
|
|
26
26
|
"@ethersproject/keccak256": "^5.8.0",
|
|
27
|
-
"@openfort/shield-js": "^0.1.
|
|
27
|
+
"@openfort/shield-js": "^0.1.36",
|
|
28
28
|
"@sentry/browser": "^9.15.0",
|
|
29
29
|
"@sentry/core": "^9.15.0",
|
|
30
|
-
"axios": "^1.
|
|
30
|
+
"axios": "^1.15.0",
|
|
31
31
|
"axios-retry": "^4.5.0",
|
|
32
32
|
"eventemitter3": "5.0.1",
|
|
33
33
|
"human-id": "^4.1.1"
|