@openfort/openfort-js 1.0.2 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/sdk/src/api/embeddedWallet.cjs +1 -1
- package/dist/cjs/sdk/src/version.cjs +1 -1
- package/dist/cjs/sdk/src/wallets/iframeManager.cjs +1 -1
- package/dist/sdk/src/api/embeddedWallet.js +1 -1
- package/dist/sdk/src/version.js +1 -1
- package/dist/sdk/src/wallets/iframeManager.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.cjs"),r=require("../core/configuration/passkey.cjs"),t=require("../core/config/config.cjs"),s=require("../core/configuration/account.cjs"),a=require("../core/configuration/authentication.cjs"),i=require("../core/errors/authErrorCodes.cjs"),n=require("../core/errors/openfortError.cjs"),o=require("../core/errors/withApiError.cjs"),d=require("../types/types.cjs"),c=require("../utils/debug.cjs"),g=require("../wallets/embedded.cjs"),h=require("../wallets/evm/evmProvider.cjs");require("../wallets/evm/types.cjs");var u=require("../wallets/evm/provider/eip6963.cjs"),y=require("../wallets/evm/walletHelpers.cjs"),m=require("../wallets/iframeManager.cjs"),l=require("../wallets/messaging/ReactNativeMessenger.cjs");require("../wallets/messaging/browserMessenger/backwardCompatibility.cjs");var p=require("../wallets/messaging/browserMessenger/messengers/WindowMessenger.cjs");exports.EmbeddedWalletApi=class{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,r,t,s,a){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=s,this.passkeyHandler=a,this.eventEmitter.on(d.OpenfortEvents.ON_LOGOUT,()=>{c.debugLog("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const r=t.SDKConfiguration.getInstance();if(!r)throw new n.ConfigurationError("Configuration not found");return new e.BackendApiClients({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey,nativeAppIdentifier:r.nativeAppIdentifier})}async getIframeManager(){if(c.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager&&this.iframeManager.hasFailed&&(c.debugLog("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;c.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return c.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,c.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw c.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){c.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=t.SDKConfiguration.getInstance();if(!e)throw c.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new n.ConfigurationError("Configuration not found");let r;if(c.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)c.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(c.debugLog("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new l.ReactNativeMessenger(this.messagePoster),c.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{c.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;r=new p({remoteWindow:t.contentWindow,allowedOrigins:[s]}),c.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return c.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new m.IframeManager(e,this.storage,r)}async ensureSigner(){if(this.iframeManager&&this.iframeManager.hasFailed&&(c.debugLog("IframeManager has failed, clearing signer for recreation"),this.signer=null),this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();return new g.EmbeddedSigner(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new n.ConfigurationError("Document is not available. Please provide a message poster for non-browser environments.");const r=document.getElementById("openfort-iframe");r&&r.remove();const t=document.createElement("iframe");return t.style.display="none",t.id="openfort-iframe",t.src=e,document.body.appendChild(t),t}async getPasskeyKey(e){const r=await a.Authentication.fromStorage(this.storage);return await this.passkeyHandler.deriveAndExportKey({id:e,seed:r?.userId??""})}async getEntropy(e){switch(e.recoveryMethod){case d.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case d.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};case d.RecoveryMethod.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new n.ConfigurationError("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC},[t,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i={chainId:e.chainId,entropy:a,accountType:e.accountType??d.AccountTypeEnum.SMART_ACCOUNT,chainType:e.chainType??d.ChainTypeEnum.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},n=await t.configure(i);return{id:n.id,chainId:n.chainId,user:n.user,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType,factoryAddress:n.factoryAddress,salt:n.salt,createdAt:n.createdAt,implementationAddress:n.implementationAddress,recoveryMethod:s.Account.parseRecoveryMethod(n.recoveryMethod),recoveryMethodDetails:n.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC},o=await a.Authentication.fromStorage(this.storage);if(!o)throw new n.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(t.recoveryMethod===d.RecoveryMethod.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:o?.userId});t.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[c,g]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),h=await c.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:g}),u={id:h.id,chainId:h.chainId,user:o?.userId,address:h.address,ownerAddress:h.ownerAddress,chainType:h.chainType,accountType:h.accountType,implementationType:h.implementationType,factoryAddress:h.factoryAddress,salt:h.salt,createdAt:h.createdAt,implementationAddress:h.implementationAddress,recoveryMethod:s.Account.parseRecoveryMethod(h.recoveryMethod),recoveryMethodDetails:h.recoveryMethodDetails};return this.eventEmitter.emit(d.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,u),u}async recover(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC};if(r.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!r.passkeyInfo?.passkeyId)throw new n.ConfigurationError("Passkey ID must be provided for passkey recovery");r.passkeyInfo={passkeyId:r.passkeyInfo.passkeyId}}const[t,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i=await t.recover({account:e.account,entropy:a}),o={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,user:i.user,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:s.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(d.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o),o}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:a=!0,arrayifyMessage:i=!1}=r||{},n=await s.Account.fromStorage(this.storage);return await t.sign(e,i,a,n?.chainType)}async signTypedData(e,r,t){await this.validateAndRefreshToken();const a=await this.ensureSigner(),o=await s.Account.fromStorage(this.storage);if(!o)throw new n.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No account found");const d={...r};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),g=c.hash(e,d,t);return await y.signMessage({hash:g,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:a,address:o.address,ownerAddress:o.ownerAddress,factoryAddress:o.factoryAddress,salt:o.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,t){await this.validateAndRefreshToken();const o=await this.ensureSigner(),c=await a.Authentication.fromStorage(this.storage);if(!c)throw new n.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");let g,h,u,y;if(e.recoveryMethod===d.RecoveryMethod.PASSKEY){const e=await s.Account.fromStorage(this.storage);if(!e)throw new n.ConfigurationError("missing account");const r=e?.recoveryMethodDetails?.passkeyId;if(!r)throw new n.ConfigurationError("missing passkey id for account");u={passkeyId:r,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:r,seed:c.userId})}}else if(t.recoveryMethod===d.RecoveryMethod.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:c.userId});u={passkeyId:e.id,passkeyKey:e.key},y={passkeyId:e.id}}if(e.recoveryMethod===d.RecoveryMethod.PASSWORD?g=e.password:t.recoveryMethod===d.RecoveryMethod.PASSWORD&&(g=t.password),e.recoveryMethod===d.RecoveryMethod.AUTOMATIC?h=e.encryptionSession:t.recoveryMethod===d.RecoveryMethod.AUTOMATIC&&(h=t.encryptionSession),!g&&!h)throw new n.ConfigurationError("Password or encryption session is not provided");await o.setRecoveryMethod({recoveryMethod:t.recoveryMethod,recoveryPassword:g,encryptionSession:h,passkeyInfo:u});const m=await s.Account.fromStorage(this.storage);m&&new s.Account({...m,recoveryMethod:t.recoveryMethod,recoveryMethodDetails:y}).save(this.storage)}async get(){const e=await s.Account.fromStorage(this.storage);if(!e)throw new n.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No signer configured");const r=await a.Authentication.fromStorage(this.storage);if(!r)throw new n.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,user:r.userId,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:s.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){const r={accountType:d.AccountTypeEnum.SMART_ACCOUNT,...e},c=t.SDKConfiguration.getInstance();if(!c)throw new n.ConfigurationError("Configuration not found");const g=await a.Authentication.fromStorage(this.storage);if(!g)throw new n.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),o.withApiError(async()=>(await this.backendApiClients.accountsApi.getAccountsV2(r,{headers:g.thirdPartyProvider?{authorization:`Bearer ${c.baseConfiguration.publishableKey}`,"x-player-token":g.token,"x-auth-provider":g.thirdPartyProvider,"x-token-type":g.thirdPartyTokenType}:{authorization:`Bearer ${g.token}`,"x-project-key":c.baseConfiguration.publishableKey}})).data.data.map(e=>({user:e.user,chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:s.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await a.Authentication.fromStorage(this.storage))return d.EmbeddedState.UNAUTHENTICATED;return await s.Account.fromStorage(this.storage)?d.EmbeddedState.READY:d.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return c.debugLog("Failed to get embedded state:",e),d.EmbeddedState.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await a.Authentication.fromStorage(this.storage),i=await s.Account.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new h.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:i||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&u.announceProvider({info:{...u.openfortProviderInfo,...r.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(r=>{setTimeout(r,e)});const r=await this.getIframeManager();if(!r.isLoaded())return!1;const t=await a.Authentication.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return c.debugLog("Ping failed:",e),!1}}getURL(){const e=t.SDKConfiguration.getInstance();if(!e)throw new n.ConfigurationError("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new n.ConfigurationError("Invalid message poster");this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleLogout(){const e=await this.ensureSigner();await e.disconnect(),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void c.debugLog("Invalid message received:",e);c.debugLog("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const r="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(r&&this.messenger&&this.messagePoster)return c.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();c.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&c.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),c.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),c.debugLog("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}};
|
|
1
|
+
"use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.cjs"),r=require("../core/configuration/passkey.cjs"),t=require("../core/config/config.cjs"),s=require("../core/configuration/account.cjs"),a=require("../core/configuration/authentication.cjs"),i=require("../core/errors/authErrorCodes.cjs"),n=require("../core/errors/openfortError.cjs"),o=require("../core/errors/withApiError.cjs"),d=require("../types/types.cjs"),c=require("../utils/debug.cjs"),g=require("../wallets/embedded.cjs"),h=require("../wallets/evm/evmProvider.cjs");require("../wallets/evm/types.cjs");var u=require("../wallets/evm/provider/eip6963.cjs"),y=require("../wallets/evm/walletHelpers.cjs"),l=require("../wallets/iframeManager.cjs"),m=require("../wallets/messaging/ReactNativeMessenger.cjs");require("../wallets/messaging/browserMessenger/backwardCompatibility.cjs");var p=require("../wallets/messaging/browserMessenger/messengers/WindowMessenger.cjs");exports.EmbeddedWalletApi=class{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,r,t,s,a){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=s,this.passkeyHandler=a,this.eventEmitter.on(d.OpenfortEvents.ON_LOGOUT,()=>{c.debugLog("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const r=t.SDKConfiguration.getInstance();if(!r)throw new n.ConfigurationError("Configuration not found");return new e.BackendApiClients({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey,nativeAppIdentifier:r.nativeAppIdentifier})}async getIframeManager(){if(c.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager&&this.iframeManager.hasFailed&&(c.debugLog("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;c.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return c.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,c.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw c.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){c.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=t.SDKConfiguration.getInstance();if(!e)throw c.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new n.ConfigurationError("Configuration not found");let r;if(c.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)c.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(c.debugLog("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new m.ReactNativeMessenger(this.messagePoster),c.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{c.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;r=new p({remoteWindow:t.contentWindow,allowedOrigins:[s]}),c.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return c.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new l.IframeManager(e,this.storage,r)}async ensureSigner(){if(this.iframeManager&&this.iframeManager.hasFailed&&(c.debugLog("IframeManager has failed, clearing signer for recreation"),this.signer=null),this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();return new g.EmbeddedSigner(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new n.ConfigurationError("Document is not available. Please provide a message poster for non-browser environments.");const r=document.getElementById("openfort-iframe");r&&r.remove();const t=document.createElement("iframe");return t.style.display="none",t.id="openfort-iframe",t.src=e,document.body.appendChild(t),t}async getPasskeyKey(e){const r=await a.Authentication.fromStorage(this.storage);return await this.passkeyHandler.deriveAndExportKey({id:e,seed:r?.userId??""})}async getEntropy(e){switch(e.recoveryMethod){case d.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case d.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};case d.RecoveryMethod.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new n.ConfigurationError("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC},[t,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i={chainId:e.chainId,entropy:a,accountType:e.accountType??d.AccountTypeEnum.SMART_ACCOUNT,chainType:e.chainType??d.ChainTypeEnum.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},n=await t.configure(i);return{id:n.id,chainId:n.chainId,user:n.user,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType,factoryAddress:n.factoryAddress,salt:n.salt,createdAt:n.createdAt,implementationAddress:n.implementationAddress,recoveryMethod:s.Account.parseRecoveryMethod(n.recoveryMethod),recoveryMethodDetails:n.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC},o=await a.Authentication.fromStorage(this.storage);if(!o)throw new n.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(t.recoveryMethod===d.RecoveryMethod.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:o?.userId});t.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[c,g]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),h=await c.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:g}),u={id:h.id,chainId:h.chainId,user:o?.userId,address:h.address,ownerAddress:h.ownerAddress,chainType:h.chainType,accountType:h.accountType,implementationType:h.implementationType,factoryAddress:h.factoryAddress,salt:h.salt,createdAt:h.createdAt,implementationAddress:h.implementationAddress,recoveryMethod:s.Account.parseRecoveryMethod(h.recoveryMethod),recoveryMethodDetails:h.recoveryMethodDetails};return this.eventEmitter.emit(d.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,u),u}async recover(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC};if(r.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!r.passkeyInfo?.passkeyId)throw new n.ConfigurationError("Passkey ID must be provided for passkey recovery");r.passkeyInfo={passkeyId:r.passkeyInfo.passkeyId}}const[t,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i=await t.recover({account:e.account,entropy:a}),o={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,user:i.user,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:s.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(d.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o),o}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:a=!0,arrayifyMessage:i=!1}=r||{},n=await s.Account.fromStorage(this.storage);return await t.sign(e,i,a,n?.chainType)}async signTypedData(e,r,t){await this.validateAndRefreshToken();const a=await this.ensureSigner(),o=await s.Account.fromStorage(this.storage);if(!o)throw new n.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No account found");const d={...r};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),g=c.hash(e,d,t);return await y.signMessage({hash:g,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:a,address:o.address,ownerAddress:o.ownerAddress,factoryAddress:o.factoryAddress,salt:o.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,t){await this.validateAndRefreshToken();const o=await this.ensureSigner(),c=await a.Authentication.fromStorage(this.storage);if(!c)throw new n.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");let g,h,u,y;if(e.recoveryMethod===d.RecoveryMethod.PASSKEY){const e=await s.Account.fromStorage(this.storage);if(!e)throw new n.ConfigurationError("missing account");const r=e?.recoveryMethodDetails?.passkeyId;if(!r)throw new n.ConfigurationError("missing passkey id for account");u={passkeyId:r,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:r,seed:c.userId})}}else if(t.recoveryMethod===d.RecoveryMethod.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:c.userId});u={passkeyId:e.id,passkeyKey:e.key},y={passkeyId:e.id}}if(e.recoveryMethod===d.RecoveryMethod.PASSWORD?g=e.password:t.recoveryMethod===d.RecoveryMethod.PASSWORD&&(g=t.password),e.recoveryMethod===d.RecoveryMethod.AUTOMATIC?h=e.encryptionSession:t.recoveryMethod===d.RecoveryMethod.AUTOMATIC&&(h=t.encryptionSession),!g&&!h)throw new n.ConfigurationError("Password or encryption session is not provided");await o.setRecoveryMethod({recoveryMethod:t.recoveryMethod,recoveryPassword:g,encryptionSession:h,passkeyInfo:u});const l=await s.Account.fromStorage(this.storage);l&&new s.Account({...l,recoveryMethod:t.recoveryMethod,recoveryMethodDetails:y}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await s.Account.fromStorage(this.storage);if(!e)throw new n.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No signer configured");const r=await a.Authentication.fromStorage(this.storage);if(!r)throw new n.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,user:r.userId,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:s.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const r={accountType:d.AccountTypeEnum.SMART_ACCOUNT,...e},c=t.SDKConfiguration.getInstance();if(!c)throw new n.ConfigurationError("Configuration not found");const g=await a.Authentication.fromStorage(this.storage);if(!g)throw new n.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),o.withApiError(async()=>(await this.backendApiClients.accountsApi.getAccountsV2(r,{headers:g.thirdPartyProvider?{authorization:`Bearer ${c.baseConfiguration.publishableKey}`,"x-player-token":g.token,"x-auth-provider":g.thirdPartyProvider,"x-token-type":g.thirdPartyTokenType}:{authorization:`Bearer ${g.token}`,"x-project-key":c.baseConfiguration.publishableKey}})).data.data.map(e=>({user:e.user,chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:s.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await a.Authentication.fromStorage(this.storage))return d.EmbeddedState.UNAUTHENTICATED;return await s.Account.fromStorage(this.storage)?d.EmbeddedState.READY:d.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return c.debugLog("Failed to get embedded state:",e),d.EmbeddedState.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await a.Authentication.fromStorage(this.storage),i=await s.Account.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new h.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:i||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&u.announceProvider({info:{...u.openfortProviderInfo,...r.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(r=>{setTimeout(r,e)});const r=await this.getIframeManager();if(!r.isLoaded())return!1;const t=await a.Authentication.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return c.debugLog("Ping failed:",e),!1}}getURL(){const e=t.SDKConfiguration.getInstance();if(!e)throw new n.ConfigurationError("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new n.ConfigurationError("Invalid message poster");this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleLogout(){const e=await this.ensureSigner();await e.disconnect(),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void c.debugLog("Invalid message received:",e);c.debugLog("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const r="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(r&&this.messenger&&this.messagePoster)return c.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();c.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&c.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),c.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),c.debugLog("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.0.
|
|
1
|
+
"use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.0.3";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../core/configuration/account.cjs"),i=require("../core/configuration/authentication.cjs"),r=require("../core/errors/authErrorCodes.cjs"),t=require("../core/errors/openfortError.cjs"),n=require("../core/errors/sentry.cjs"),o=require("../storage/istorage.cjs"),s=require("../utils/crypto.cjs"),a=require("../utils/debug.cjs"),d=require("./messaging/ReactNativeMessenger.cjs"),c=require("./messaging/browserMessenger/connect.cjs");require("./messaging/browserMessenger/backwardCompatibility.cjs");var u=require("./types.cjs");class h extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class g extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class l extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class R extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class y extends t.SignerError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.NOT_CONFIGURED,"Signer is not configured")}}class E extends t.OpenfortError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.OTP_REQUIRED,"OTP verification required")}}exports.IframeManager=class{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;hasFailed=!1;constructor(e,i,r){if(!e)throw new t.ConfigurationError("Configuration is required for IframeManager");if(!i)throw new t.ConfigurationError("Storage is required for IframeManager");if(!r)throw new t.ConfigurationError("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=r}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){a.debugLog("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:a.debugLog}),this.connection=c({messenger:this.messenger,timeout:1e4,log:a.debugLog});try{this.remote=await this.connection.promise,a.debugLog("IframeManager connection established")}catch(e){const i=e;throw n.sentry.captureException(i),this.destroy(),a.debugLog("Failed to establish connection:",i),new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}`)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(u.isErrorResponse(e)){if(e.error===u.NOT_CONFIGURED_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new y;if(e.error===u.MISSING_USER_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.MISSING_PROJECT_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new l;if(e.error===u.INCORRECT_USER_ENTROPY_ERROR)throw new R;if(e.error===u.MISSING_PASSKEY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.INCORRECT_PASSKEY_ERROR)throw new g;if(e.error===u.OTP_REQUIRED_ERROR)throw new E;throw this.storage.remove(o.StorageKeys.ACCOUNT),new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=e.chainId??null,r.password=e?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:e?.entropy?.encryptionSession},r.passkey=e?.entropy?.passkey??null;const t={uuid:s.randomUUID(),action:u.Event.CREATE,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},n=await i.create(t);return u.isErrorResponse(n)&&this.handleError(n),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",n.version??"undefined"),n}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await e.Account.fromStorage(this.storage),t=await this.ensureConnection(),n=await this.buildIFrameRequestConfiguration();n.chainId=r?.chainId??null,n.password=i?.entropy?.recoveryPassword??null,n.recovery={...n.recovery,encryptionSession:i?.entropy?.encryptionSession},n.passkey=i?.entropy?.passkey??null;const o={uuid:s.randomUUID(),action:u.Event.RECOVER,recovery:n.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:n.accessToken,playerID:n.playerID,thirdPartyProvider:n.thirdPartyProvider,thirdPartyTokenType:n.thirdPartyTokenType,encryptionKey:n.password,encryptionSession:n.recovery?.encryptionSession??null,passkey:n.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},a=await t.recover(o);return u.isErrorResponse(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,i,r,t){a.debugLog("[iframe] ensureConnection");const n=await this.ensureConnection(),o=new u.SignRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,t);a.debugLog("[iframe] done ensureConnection");const d=await n.sign(o);return a.debugLog("[iframe] response",d),u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined"),d.signature}async switchChain(e){const i=await this.ensureConnection(),r=new u.SwitchChainRequest(s.randomUUID(),e,await this.buildRequestConfiguration()),t=await i.switchChain(r);return u.isErrorResponse(t)&&this.handleError(t),t}async export(){const e=await this.ensureConnection(),i=new u.ExportPrivateKeyRequest(s.randomUUID(),await this.buildRequestConfiguration()),r=await e.export(i);return u.isErrorResponse(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r.key}async setRecoveryMethod(e,i,r,t,n){const o=await this.ensureConnection(),a=new u.SetRecoveryMethodRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,t,n),d=await o.setRecoveryMethod(a);u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),r=new u.GetCurrentDeviceRequest(s.randomUUID(),e);try{const e=await i.getCurrentDevice(r);return u.isErrorResponse(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof y)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void a.debugLog("IframeManager not loaded, skipping authentication update");const e=await i.Authentication.fromStorage(this.storage);if(!e)return void a.debugLog("No authentication found, skipping update");const r=new u.UpdateAuthenticationRequest(s.randomUUID(),e.token);a.debugLog("Updating authentication in iframe with token");const t=await this.remote.updateAuthentication(r);u.isErrorResponse(t)&&this.handleError(t)}async disconnect(){const e=await this.ensureConnection(),i={uuid:s.randomUUID()};await e.logout(i)}async onMessage(e){a.debugLog("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof d.ReactNativeMessenger?(this.isInitialized||this.connection?a.debugLog(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(a.debugLog("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{a.debugLog("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),a.debugLog("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):a.debugLog("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}},exports.MissingProjectEntropyError=l,exports.MissingRecoveryPasswordError=h,exports.NotConfiguredError=y,exports.OTPRequiredError=E,exports.WrongPasskeyError=g,exports.WrongRecoveryPasswordError=R;
|
|
1
|
+
"use strict";var e=require("../core/configuration/account.cjs"),i=require("../core/configuration/authentication.cjs"),r=require("../core/errors/authErrorCodes.cjs"),t=require("../core/errors/openfortError.cjs"),n=require("../core/errors/sentry.cjs"),o=require("../storage/istorage.cjs"),s=require("../utils/crypto.cjs"),a=require("../utils/debug.cjs"),d=require("./messaging/ReactNativeMessenger.cjs"),c=require("./messaging/browserMessenger/connect.cjs");require("./messaging/browserMessenger/backwardCompatibility.cjs");var u=require("./types.cjs");class h extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class g extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class l extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class R extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class y extends t.SignerError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.NOT_CONFIGURED,"Signer is not configured")}}class p extends t.OpenfortError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.OTP_REQUIRED,"OTP verification required")}}exports.IframeManager=class{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;hasFailed=!1;constructor(e,i,r){if(!e)throw new t.ConfigurationError("Configuration is required for IframeManager");if(!i)throw new t.ConfigurationError("Storage is required for IframeManager");if(!r)throw new t.ConfigurationError("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=r}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){a.debugLog("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:a.debugLog}),this.connection=c({messenger:this.messenger,timeout:1e4,log:a.debugLog});try{this.remote=await this.connection.promise,a.debugLog("IframeManager connection established")}catch(e){const i=e;throw n.sentry.captureException(i),this.destroy(),a.debugLog("Failed to establish connection:",i),new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}\n \n In apps built with:\n - react native\n - swift\n - unity (non-webgl) \n \n You must configure your origin in the openfort dashboard before using the embedded wallet.\n\n For more information, see: https://www.openfort.io/docs/configuration/native-apps\n `)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(u.isErrorResponse(e)){if(e.error===u.NOT_CONFIGURED_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new y;if(e.error===u.MISSING_USER_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.MISSING_PROJECT_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new l;if(e.error===u.INCORRECT_USER_ENTROPY_ERROR)throw new R;if(e.error===u.MISSING_PASSKEY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.INCORRECT_PASSKEY_ERROR)throw new g;if(e.error===u.OTP_REQUIRED_ERROR)throw new p;throw this.storage.remove(o.StorageKeys.ACCOUNT),new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=e.chainId??null,r.password=e?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:e?.entropy?.encryptionSession},r.passkey=e?.entropy?.passkey??null;const t={uuid:s.randomUUID(),action:u.Event.CREATE,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},n=await i.create(t);return u.isErrorResponse(n)&&this.handleError(n),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",n.version??"undefined"),n}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await e.Account.fromStorage(this.storage),t=await this.ensureConnection(),n=await this.buildIFrameRequestConfiguration();n.chainId=r?.chainId??null,n.password=i?.entropy?.recoveryPassword??null,n.recovery={...n.recovery,encryptionSession:i?.entropy?.encryptionSession},n.passkey=i?.entropy?.passkey??null;const o={uuid:s.randomUUID(),action:u.Event.RECOVER,recovery:n.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:n.accessToken,playerID:n.playerID,thirdPartyProvider:n.thirdPartyProvider,thirdPartyTokenType:n.thirdPartyTokenType,encryptionKey:n.password,encryptionSession:n.recovery?.encryptionSession??null,passkey:n.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},a=await t.recover(o);return u.isErrorResponse(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,i,r,t){a.debugLog("[iframe] ensureConnection");const n=await this.ensureConnection(),o=new u.SignRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,t);a.debugLog("[iframe] done ensureConnection");const d=await n.sign(o);return a.debugLog("[iframe] response",d),u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined"),d.signature}async switchChain(e){const i=await this.ensureConnection(),r=new u.SwitchChainRequest(s.randomUUID(),e,await this.buildRequestConfiguration()),t=await i.switchChain(r);return u.isErrorResponse(t)&&this.handleError(t),t}async export(){const e=await this.ensureConnection(),i=new u.ExportPrivateKeyRequest(s.randomUUID(),await this.buildRequestConfiguration()),r=await e.export(i);return u.isErrorResponse(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r.key}async setRecoveryMethod(e,i,r,t,n){const o=await this.ensureConnection(),a=new u.SetRecoveryMethodRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,t,n),d=await o.setRecoveryMethod(a);u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),r=new u.GetCurrentDeviceRequest(s.randomUUID(),e);try{const e=await i.getCurrentDevice(r);return u.isErrorResponse(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof y)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void a.debugLog("IframeManager not loaded, skipping authentication update");const e=await i.Authentication.fromStorage(this.storage);if(!e)return void a.debugLog("No authentication found, skipping update");const r=new u.UpdateAuthenticationRequest(s.randomUUID(),e.token);a.debugLog("Updating authentication in iframe with token");const t=await this.remote.updateAuthentication(r);u.isErrorResponse(t)&&this.handleError(t)}async disconnect(){const e=await this.ensureConnection(),i={uuid:s.randomUUID()};await e.logout(i)}async onMessage(e){a.debugLog("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof d.ReactNativeMessenger?(this.isInitialized||this.connection?a.debugLog(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(a.debugLog("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{a.debugLog("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),a.debugLog("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):a.debugLog("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}},exports.MissingProjectEntropyError=l,exports.MissingRecoveryPasswordError=h,exports.NotConfiguredError=y,exports.OTPRequiredError=p,exports.WrongPasskeyError=g,exports.WrongRecoveryPasswordError=R;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{PasskeyHandler as r}from"../core/configuration/passkey.js";import{SDKConfiguration as t}from"../core/config/config.js";import{Account as s}from"../core/configuration/account.js";import{Authentication as a}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as i}from"../core/errors/authErrorCodes.js";import{ConfigurationError as n,SessionError as o,SignerError as d}from"../core/errors/openfortError.js";import{withApiError as c}from"../core/errors/withApiError.js";import{OpenfortEvents as h,RecoveryMethod as m,ChainTypeEnum as g,AccountTypeEnum as y,EmbeddedState as l}from"../types/types.js";import{debugLog as p}from"../utils/debug.js";import{EmbeddedSigner as f}from"../wallets/embedded.js";import{EvmProvider as u}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as A,openfortProviderInfo as w}from"../wallets/evm/provider/eip6963.js";import{signMessage as v}from"../wallets/evm/walletHelpers.js";import{IframeManager as M}from"../wallets/iframeManager.js";import{ReactNativeMessenger as E}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import I from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class T{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,r,t,s,a){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=s,this.passkeyHandler=a,this.eventEmitter.on(h.ON_LOGOUT,()=>{p("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const r=t.getInstance();if(!r)throw new n("Configuration not found");return new e({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey,nativeAppIdentifier:r.nativeAppIdentifier})}async getIframeManager(){if(p("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager&&this.iframeManager.hasFailed&&(p("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return p("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return p("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;p("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return p("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,p("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw p("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){p("[HANDSHAKE DEBUG] createIframeManager starting");const e=t.getInstance();if(!e)throw p("[HANDSHAKE DEBUG] Configuration not found"),new n("Configuration not found");let r;if(p("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)p("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(p("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new E(this.messagePoster),p("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{p("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;r=new I({remoteWindow:t.contentWindow,allowedOrigins:[s]}),p("[HANDSHAKE DEBUG] Created WindowMessenger")}return p("[HANDSHAKE DEBUG] Creating IframeManager instance"),new M(e,this.storage,r)}async ensureSigner(){if(this.iframeManager&&this.iframeManager.hasFailed&&(p("IframeManager has failed, clearing signer for recreation"),this.signer=null),this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();return new f(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new n("Document is not available. Please provide a message poster for non-browser environments.");const r=document.getElementById("openfort-iframe");r&&r.remove();const t=document.createElement("iframe");return t.style.display="none",t.id="openfort-iframe",t.src=e,document.body.appendChild(t),t}async getPasskeyKey(e){const r=await a.fromStorage(this.storage);return await this.passkeyHandler.deriveAndExportKey({id:e,seed:r?.userId??""})}async getEntropy(e){switch(e.recoveryMethod){case m.PASSWORD:return{recoveryPassword:e.password};case m.AUTOMATIC:return{encryptionSession:e.encryptionSession};case m.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new n("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:m.AUTOMATIC},[t,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i={chainId:e.chainId,entropy:a,accountType:e.accountType??y.SMART_ACCOUNT,chainType:e.chainType??g.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},n=await t.configure(i);return{id:n.id,chainId:n.chainId,user:n.user,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType,factoryAddress:n.factoryAddress,salt:n.salt,createdAt:n.createdAt,implementationAddress:n.implementationAddress,recoveryMethod:s.parseRecoveryMethod(n.recoveryMethod),recoveryMethodDetails:n.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:m.AUTOMATIC},n=await a.fromStorage(this.storage);if(!n)throw new o(i.NOT_LOGGED_IN,"missing authentication");if(t.recoveryMethod===m.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:n?.userId});t.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[d,c]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),g=await d.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:c}),y={id:g.id,chainId:g.chainId,user:n?.userId,address:g.address,ownerAddress:g.ownerAddress,chainType:g.chainType,accountType:g.accountType,implementationType:g.implementationType,factoryAddress:g.factoryAddress,salt:g.salt,createdAt:g.createdAt,implementationAddress:g.implementationAddress,recoveryMethod:s.parseRecoveryMethod(g.recoveryMethod),recoveryMethodDetails:g.recoveryMethodDetails};return this.eventEmitter.emit(h.ON_EMBEDDED_WALLET_CREATED,y),y}async recover(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:m.AUTOMATIC};if(r.recoveryMethod===m.PASSKEY){if(!r.passkeyInfo?.passkeyId)throw new n("Passkey ID must be provided for passkey recovery");r.passkeyInfo={passkeyId:r.passkeyInfo.passkeyId}}const[t,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i=await t.recover({account:e.account,entropy:a}),o={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,user:i.user,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:s.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(h.ON_EMBEDDED_WALLET_RECOVERED,o),o}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:a=!0,arrayifyMessage:i=!1}=r||{},n=await s.fromStorage(this.storage);return await t.sign(e,i,a,n?.chainType)}async signTypedData(e,r,t){await this.validateAndRefreshToken();const a=await this.ensureSigner(),n=await s.fromStorage(this.storage);if(!n)throw new d(i.MISSING_SIGNER,"No account found");const o={...r};delete o.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),h=c.hash(e,o,t);return await v({hash:h,implementationType:n.implementationType||n.type,chainId:Number(n.chainId),signer:a,address:n.address,ownerAddress:n.ownerAddress,factoryAddress:n.factoryAddress,salt:n.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,t){await this.validateAndRefreshToken();const d=await this.ensureSigner(),c=await a.fromStorage(this.storage);if(!c)throw new o(i.NOT_LOGGED_IN,"missing authentication");let h,g,y,l;if(e.recoveryMethod===m.PASSKEY){const e=await s.fromStorage(this.storage);if(!e)throw new n("missing account");const r=e?.recoveryMethodDetails?.passkeyId;if(!r)throw new n("missing passkey id for account");y={passkeyId:r,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:r,seed:c.userId})}}else if(t.recoveryMethod===m.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:c.userId});y={passkeyId:e.id,passkeyKey:e.key},l={passkeyId:e.id}}if(e.recoveryMethod===m.PASSWORD?h=e.password:t.recoveryMethod===m.PASSWORD&&(h=t.password),e.recoveryMethod===m.AUTOMATIC?g=e.encryptionSession:t.recoveryMethod===m.AUTOMATIC&&(g=t.encryptionSession),!h&&!g)throw new n("Password or encryption session is not provided");await d.setRecoveryMethod({recoveryMethod:t.recoveryMethod,recoveryPassword:h,encryptionSession:g,passkeyInfo:y});const p=await s.fromStorage(this.storage);p&&new s({...p,recoveryMethod:t.recoveryMethod,recoveryMethodDetails:l}).save(this.storage)}async get(){const e=await s.fromStorage(this.storage);if(!e)throw new d(i.MISSING_SIGNER,"No signer configured");const r=await a.fromStorage(this.storage);if(!r)throw new o(i.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,user:r.userId,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:s.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){const r={accountType:y.SMART_ACCOUNT,...e},d=t.getInstance();if(!d)throw new n("Configuration not found");const h=await a.fromStorage(this.storage);if(!h)throw new o(i.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),c(async()=>(await this.backendApiClients.accountsApi.getAccountsV2(r,{headers:h.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":h.token,"x-auth-provider":h.thirdPartyProvider,"x-token-type":h.thirdPartyTokenType}:{authorization:`Bearer ${h.token}`,"x-project-key":d.baseConfiguration.publishableKey}})).data.data.map(e=>({user:e.user,chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:s.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await a.fromStorage(this.storage))return l.UNAUTHENTICATED;return await s.fromStorage(this.storage)?l.READY:l.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return p("Failed to get embedded state:",e),l.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await a.fromStorage(this.storage),i=await s.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new u({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:i||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&A({info:{...w,...r.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(r=>{setTimeout(r,e)});const r=await this.getIframeManager();if(!r.isLoaded())return!1;const t=await a.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return p("Ping failed:",e),!1}}getURL(){const e=t.getInstance();if(!e)throw new n("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new n("Invalid message poster");this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleLogout(){const e=await this.ensureSigner();await e.disconnect(),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void p("Invalid message received:",e);p("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const r="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(r&&this.messenger&&this.messagePoster)return p("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();p(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&p("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),p("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),p("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{T as EmbeddedWalletApi};
|
|
1
|
+
import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{PasskeyHandler as r}from"../core/configuration/passkey.js";import{SDKConfiguration as t}from"../core/config/config.js";import{Account as s}from"../core/configuration/account.js";import{Authentication as a}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as i}from"../core/errors/authErrorCodes.js";import{ConfigurationError as n,SessionError as o,SignerError as d}from"../core/errors/openfortError.js";import{withApiError as c}from"../core/errors/withApiError.js";import{OpenfortEvents as h,RecoveryMethod as m,ChainTypeEnum as g,AccountTypeEnum as y,EmbeddedState as l}from"../types/types.js";import{debugLog as p}from"../utils/debug.js";import{EmbeddedSigner as f}from"../wallets/embedded.js";import{EvmProvider as u}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as A,openfortProviderInfo as w}from"../wallets/evm/provider/eip6963.js";import{signMessage as v}from"../wallets/evm/walletHelpers.js";import{IframeManager as M}from"../wallets/iframeManager.js";import{ReactNativeMessenger as E}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import I from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class T{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,r,t,s,a){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=s,this.passkeyHandler=a,this.eventEmitter.on(h.ON_LOGOUT,()=>{p("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const r=t.getInstance();if(!r)throw new n("Configuration not found");return new e({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey,nativeAppIdentifier:r.nativeAppIdentifier})}async getIframeManager(){if(p("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager&&this.iframeManager.hasFailed&&(p("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return p("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return p("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;p("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return p("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,p("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw p("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){p("[HANDSHAKE DEBUG] createIframeManager starting");const e=t.getInstance();if(!e)throw p("[HANDSHAKE DEBUG] Configuration not found"),new n("Configuration not found");let r;if(p("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)p("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(p("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new E(this.messagePoster),p("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{p("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;r=new I({remoteWindow:t.contentWindow,allowedOrigins:[s]}),p("[HANDSHAKE DEBUG] Created WindowMessenger")}return p("[HANDSHAKE DEBUG] Creating IframeManager instance"),new M(e,this.storage,r)}async ensureSigner(){if(this.iframeManager&&this.iframeManager.hasFailed&&(p("IframeManager has failed, clearing signer for recreation"),this.signer=null),this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();return new f(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new n("Document is not available. Please provide a message poster for non-browser environments.");const r=document.getElementById("openfort-iframe");r&&r.remove();const t=document.createElement("iframe");return t.style.display="none",t.id="openfort-iframe",t.src=e,document.body.appendChild(t),t}async getPasskeyKey(e){const r=await a.fromStorage(this.storage);return await this.passkeyHandler.deriveAndExportKey({id:e,seed:r?.userId??""})}async getEntropy(e){switch(e.recoveryMethod){case m.PASSWORD:return{recoveryPassword:e.password};case m.AUTOMATIC:return{encryptionSession:e.encryptionSession};case m.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new n("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:m.AUTOMATIC},[t,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i={chainId:e.chainId,entropy:a,accountType:e.accountType??y.SMART_ACCOUNT,chainType:e.chainType??g.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},n=await t.configure(i);return{id:n.id,chainId:n.chainId,user:n.user,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType,factoryAddress:n.factoryAddress,salt:n.salt,createdAt:n.createdAt,implementationAddress:n.implementationAddress,recoveryMethod:s.parseRecoveryMethod(n.recoveryMethod),recoveryMethodDetails:n.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:m.AUTOMATIC},n=await a.fromStorage(this.storage);if(!n)throw new o(i.NOT_LOGGED_IN,"missing authentication");if(t.recoveryMethod===m.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:n?.userId});t.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[d,c]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),g=await d.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:c}),y={id:g.id,chainId:g.chainId,user:n?.userId,address:g.address,ownerAddress:g.ownerAddress,chainType:g.chainType,accountType:g.accountType,implementationType:g.implementationType,factoryAddress:g.factoryAddress,salt:g.salt,createdAt:g.createdAt,implementationAddress:g.implementationAddress,recoveryMethod:s.parseRecoveryMethod(g.recoveryMethod),recoveryMethodDetails:g.recoveryMethodDetails};return this.eventEmitter.emit(h.ON_EMBEDDED_WALLET_CREATED,y),y}async recover(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:m.AUTOMATIC};if(r.recoveryMethod===m.PASSKEY){if(!r.passkeyInfo?.passkeyId)throw new n("Passkey ID must be provided for passkey recovery");r.passkeyInfo={passkeyId:r.passkeyInfo.passkeyId}}const[t,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i=await t.recover({account:e.account,entropy:a}),o={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,user:i.user,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:s.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(h.ON_EMBEDDED_WALLET_RECOVERED,o),o}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:a=!0,arrayifyMessage:i=!1}=r||{},n=await s.fromStorage(this.storage);return await t.sign(e,i,a,n?.chainType)}async signTypedData(e,r,t){await this.validateAndRefreshToken();const a=await this.ensureSigner(),n=await s.fromStorage(this.storage);if(!n)throw new d(i.MISSING_SIGNER,"No account found");const o={...r};delete o.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),h=c.hash(e,o,t);return await v({hash:h,implementationType:n.implementationType||n.type,chainId:Number(n.chainId),signer:a,address:n.address,ownerAddress:n.ownerAddress,factoryAddress:n.factoryAddress,salt:n.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,t){await this.validateAndRefreshToken();const d=await this.ensureSigner(),c=await a.fromStorage(this.storage);if(!c)throw new o(i.NOT_LOGGED_IN,"missing authentication");let h,g,y,l;if(e.recoveryMethod===m.PASSKEY){const e=await s.fromStorage(this.storage);if(!e)throw new n("missing account");const r=e?.recoveryMethodDetails?.passkeyId;if(!r)throw new n("missing passkey id for account");y={passkeyId:r,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:r,seed:c.userId})}}else if(t.recoveryMethod===m.PASSKEY){const e=await this.passkeyHandler.createPasskey({id:r.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:c.userId});y={passkeyId:e.id,passkeyKey:e.key},l={passkeyId:e.id}}if(e.recoveryMethod===m.PASSWORD?h=e.password:t.recoveryMethod===m.PASSWORD&&(h=t.password),e.recoveryMethod===m.AUTOMATIC?g=e.encryptionSession:t.recoveryMethod===m.AUTOMATIC&&(g=t.encryptionSession),!h&&!g)throw new n("Password or encryption session is not provided");await d.setRecoveryMethod({recoveryMethod:t.recoveryMethod,recoveryPassword:h,encryptionSession:g,passkeyInfo:y});const p=await s.fromStorage(this.storage);p&&new s({...p,recoveryMethod:t.recoveryMethod,recoveryMethodDetails:l}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await s.fromStorage(this.storage);if(!e)throw new d(i.MISSING_SIGNER,"No signer configured");const r=await a.fromStorage(this.storage);if(!r)throw new o(i.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,user:r.userId,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:s.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const r={accountType:y.SMART_ACCOUNT,...e},d=t.getInstance();if(!d)throw new n("Configuration not found");const h=await a.fromStorage(this.storage);if(!h)throw new o(i.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),c(async()=>(await this.backendApiClients.accountsApi.getAccountsV2(r,{headers:h.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":h.token,"x-auth-provider":h.thirdPartyProvider,"x-token-type":h.thirdPartyTokenType}:{authorization:`Bearer ${h.token}`,"x-project-key":d.baseConfiguration.publishableKey}})).data.data.map(e=>({user:e.user,chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:s.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await a.fromStorage(this.storage))return l.UNAUTHENTICATED;return await s.fromStorage(this.storage)?l.READY:l.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return p("Failed to get embedded state:",e),l.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await a.fromStorage(this.storage),i=await s.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new u({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:i||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&A({info:{...w,...r.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(r=>{setTimeout(r,e)});const r=await this.getIframeManager();if(!r.isLoaded())return!1;const t=await a.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return p("Ping failed:",e),!1}}getURL(){const e=t.getInstance();if(!e)throw new n("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new n("Invalid message poster");this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleLogout(){const e=await this.ensureSigner();await e.disconnect(),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void p("Invalid message received:",e);p("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const r="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(r&&this.messenger&&this.messagePoster)return p("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();p(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&p("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),p("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),p("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{T as EmbeddedWalletApi};
|
package/dist/sdk/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="1.0.
|
|
1
|
+
const o="1.0.3",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Account as e}from"../core/configuration/account.js";import{Authentication as i}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as t}from"../core/errors/authErrorCodes.js";import{RecoveryError as n,SignerError as r,OpenfortError as o,ConfigurationError as s,SessionError as a}from"../core/errors/openfortError.js";import{sentry as d}from"../core/errors/sentry.js";import{StorageKeys as c}from"../storage/istorage.js";import{randomUUID as h}from"../utils/crypto.js";import{debugLog as u}from"../utils/debug.js";import{ReactNativeMessenger as l}from"./messaging/ReactNativeMessenger.js";import y from"./messaging/browserMessenger/connect.js";import"./messaging/browserMessenger/backwardCompatibility.js";import{isErrorResponse as f,NOT_CONFIGURED_ERROR as g,MISSING_USER_ENTROPY_ERROR as p,MISSING_PROJECT_ENTROPY_ERROR as m,INCORRECT_USER_ENTROPY_ERROR as w,MISSING_PASSKEY_ERROR as C,INCORRECT_PASSKEY_ERROR as v,OTP_REQUIRED_ERROR as k,ShieldAuthType as I,Event as P,SignRequest as R,SwitchChainRequest as E,ExportPrivateKeyRequest as T,SetRecoveryMethodRequest as b,GetCurrentDeviceRequest as S,UpdateAuthenticationRequest as N}from"./types.js";class A extends n{constructor(){super(t.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class O extends n{constructor(){super(t.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class U extends n{constructor(){super(t.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class z extends n{constructor(){super(t.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class D extends r{constructor(){super(t.NOT_CONFIGURED,"Signer is not configured")}}class K extends o{constructor(){super(t.OTP_REQUIRED,"OTP verification required")}}class M{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;hasFailed=!1;constructor(e,i,t){if(!e)throw new s("Configuration is required for IframeManager");if(!i)throw new s("Storage is required for IframeManager");if(!t)throw new s("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=t}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new o(t.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){u("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:u}),this.connection=y({messenger:this.messenger,timeout:1e4,log:u});try{this.remote=await this.connection.promise,u("IframeManager connection established")}catch(e){const i=e;throw d.captureException(i),this.destroy(),u("Failed to establish connection:",i),new o(t.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}`)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new o(t.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(f(e)){if(e.error===g)throw this.storage.remove(c.ACCOUNT),new D;if(e.error===p)throw this.storage.remove(c.ACCOUNT),new A;if(e.error===m)throw this.storage.remove(c.ACCOUNT),new U;if(e.error===w)throw new z;if(e.error===C)throw this.storage.remove(c.ACCOUNT),new A;if(e.error===v)throw new O;if(e.error===k)throw new K;throw this.storage.remove(c.ACCOUNT),new o(t.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(t.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:I.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(t.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:I.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),t=await this.buildIFrameRequestConfiguration();t.chainId=e.chainId??null,t.password=e?.entropy?.recoveryPassword??null,t.recovery={...t.recovery,encryptionSession:e?.entropy?.encryptionSession},t.passkey=e?.entropy?.passkey??null;const n={uuid:h(),action:P.CREATE,recovery:t.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:t.accessToken,playerID:t.playerID,thirdPartyProvider:t.thirdPartyProvider,thirdPartyTokenType:t.thirdPartyTokenType,encryptionKey:t.password,encryptionSession:t.recovery?.encryptionSession??null,passkey:t.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},r=await i.create(n);return f(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const t=await e.fromStorage(this.storage),n=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=t?.chainId??null,r.password=i?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:i?.entropy?.encryptionSession},r.passkey=i?.entropy?.passkey??null;const o={uuid:h(),action:P.RECOVER,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},s=await n.recover(o);return f(s)&&this.handleError(s),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",s.version??"undefined"),s}async sign(e,i,t,n){u("[iframe] ensureConnection");const r=await this.ensureConnection(),o=new R(h(),e,await this.buildRequestConfiguration(),i,t,n);u("[iframe] done ensureConnection");const s=await r.sign(o);return u("[iframe] response",s),f(s)&&this.handleError(s),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",s.version??"undefined"),s.signature}async switchChain(e){const i=await this.ensureConnection(),t=new E(h(),e,await this.buildRequestConfiguration()),n=await i.switchChain(t);return f(n)&&this.handleError(n),n}async export(){const e=await this.ensureConnection(),i=new T(h(),await this.buildRequestConfiguration()),t=await e.export(i);return f(t)&&this.handleError(t),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",t.version??"undefined"),t.key}async setRecoveryMethod(e,i,t,n,r){const o=await this.ensureConnection(),s=new b(h(),e,await this.buildRequestConfiguration(),i,t,n,r),a=await o.setRecoveryMethod(s);f(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),t=new S(h(),e);try{const e=await i.getCurrentDevice(t);return f(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof D)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void u("IframeManager not loaded, skipping authentication update");const e=await i.fromStorage(this.storage);if(!e)return void u("No authentication found, skipping update");const t=new N(h(),e.token);u("Updating authentication in iframe with token");const n=await this.remote.updateAuthentication(t);f(n)&&this.handleError(n)}async disconnect(){const e=await this.ensureConnection(),i={uuid:h()};await e.logout(i)}async onMessage(e){u("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof l?(this.isInitialized||this.connection?u(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(u("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{u("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),u("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):u("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}}export{M as IframeManager,U as MissingProjectEntropyError,A as MissingRecoveryPasswordError,D as NotConfiguredError,K as OTPRequiredError,O as WrongPasskeyError,z as WrongRecoveryPasswordError};
|
|
1
|
+
import{Account as e}from"../core/configuration/account.js";import{Authentication as i}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as t}from"../core/errors/authErrorCodes.js";import{RecoveryError as n,SignerError as r,OpenfortError as o,ConfigurationError as s,SessionError as a}from"../core/errors/openfortError.js";import{sentry as d}from"../core/errors/sentry.js";import{StorageKeys as c}from"../storage/istorage.js";import{randomUUID as h}from"../utils/crypto.js";import{debugLog as u}from"../utils/debug.js";import{ReactNativeMessenger as l}from"./messaging/ReactNativeMessenger.js";import f from"./messaging/browserMessenger/connect.js";import"./messaging/browserMessenger/backwardCompatibility.js";import{isErrorResponse as y,NOT_CONFIGURED_ERROR as g,MISSING_USER_ENTROPY_ERROR as p,MISSING_PROJECT_ENTROPY_ERROR as m,INCORRECT_USER_ENTROPY_ERROR as w,MISSING_PASSKEY_ERROR as C,INCORRECT_PASSKEY_ERROR as v,OTP_REQUIRED_ERROR as k,ShieldAuthType as I,Event as P,SignRequest as R,SwitchChainRequest as b,ExportPrivateKeyRequest as E,SetRecoveryMethodRequest as T,GetCurrentDeviceRequest as S,UpdateAuthenticationRequest as N}from"./types.js";class A extends n{constructor(){super(t.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class O extends n{constructor(){super(t.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class U extends n{constructor(){super(t.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class z extends n{constructor(){super(t.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class D extends r{constructor(){super(t.NOT_CONFIGURED,"Signer is not configured")}}class K extends o{constructor(){super(t.OTP_REQUIRED,"OTP verification required")}}class M{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;hasFailed=!1;constructor(e,i,t){if(!e)throw new s("Configuration is required for IframeManager");if(!i)throw new s("Storage is required for IframeManager");if(!t)throw new s("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=t}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new o(t.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){u("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:u}),this.connection=f({messenger:this.messenger,timeout:1e4,log:u});try{this.remote=await this.connection.promise,u("IframeManager connection established")}catch(e){const i=e;throw d.captureException(i),this.destroy(),u("Failed to establish connection:",i),new o(t.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}\n \n In apps built with:\n - react native\n - swift\n - unity (non-webgl) \n \n You must configure your origin in the openfort dashboard before using the embedded wallet.\n\n For more information, see: https://www.openfort.io/docs/configuration/native-apps\n `)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new o(t.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(y(e)){if(e.error===g)throw this.storage.remove(c.ACCOUNT),new D;if(e.error===p)throw this.storage.remove(c.ACCOUNT),new A;if(e.error===m)throw this.storage.remove(c.ACCOUNT),new U;if(e.error===w)throw new z;if(e.error===C)throw this.storage.remove(c.ACCOUNT),new A;if(e.error===v)throw new O;if(e.error===k)throw new K;throw this.storage.remove(c.ACCOUNT),new o(t.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(t.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:I.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(t.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:I.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),t=await this.buildIFrameRequestConfiguration();t.chainId=e.chainId??null,t.password=e?.entropy?.recoveryPassword??null,t.recovery={...t.recovery,encryptionSession:e?.entropy?.encryptionSession},t.passkey=e?.entropy?.passkey??null;const n={uuid:h(),action:P.CREATE,recovery:t.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:t.accessToken,playerID:t.playerID,thirdPartyProvider:t.thirdPartyProvider,thirdPartyTokenType:t.thirdPartyTokenType,encryptionKey:t.password,encryptionSession:t.recovery?.encryptionSession??null,passkey:t.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},r=await i.create(n);return y(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const t=await e.fromStorage(this.storage),n=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=t?.chainId??null,r.password=i?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:i?.entropy?.encryptionSession},r.passkey=i?.entropy?.passkey??null;const o={uuid:h(),action:P.RECOVER,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},s=await n.recover(o);return y(s)&&this.handleError(s),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",s.version??"undefined"),s}async sign(e,i,t,n){u("[iframe] ensureConnection");const r=await this.ensureConnection(),o=new R(h(),e,await this.buildRequestConfiguration(),i,t,n);u("[iframe] done ensureConnection");const s=await r.sign(o);return u("[iframe] response",s),y(s)&&this.handleError(s),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",s.version??"undefined"),s.signature}async switchChain(e){const i=await this.ensureConnection(),t=new b(h(),e,await this.buildRequestConfiguration()),n=await i.switchChain(t);return y(n)&&this.handleError(n),n}async export(){const e=await this.ensureConnection(),i=new E(h(),await this.buildRequestConfiguration()),t=await e.export(i);return y(t)&&this.handleError(t),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",t.version??"undefined"),t.key}async setRecoveryMethod(e,i,t,n,r){const o=await this.ensureConnection(),s=new T(h(),e,await this.buildRequestConfiguration(),i,t,n,r),a=await o.setRecoveryMethod(s);y(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),t=new S(h(),e);try{const e=await i.getCurrentDevice(t);return y(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof D)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void u("IframeManager not loaded, skipping authentication update");const e=await i.fromStorage(this.storage);if(!e)return void u("No authentication found, skipping update");const t=new N(h(),e.token);u("Updating authentication in iframe with token");const n=await this.remote.updateAuthentication(t);y(n)&&this.handleError(n)}async disconnect(){const e=await this.ensureConnection(),i={uuid:h()};await e.logout(i)}async onMessage(e){u("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof l?(this.isInitialized||this.connection?u(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(u("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{u("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),u("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):u("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}}export{M as IframeManager,U as MissingProjectEntropyError,A as MissingRecoveryPasswordError,D as NotConfiguredError,K as OTPRequiredError,O as WrongPasskeyError,z as WrongRecoveryPasswordError};
|
package/package.json
CHANGED