@openfort/openfort-js 1.1.7 → 1.2.1
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/core/config/config.cjs +1 -1
- package/dist/cjs/sdk/src/core/openfort.cjs +1 -1
- package/dist/cjs/sdk/src/core/passkey/handler.cjs +1 -1
- package/dist/cjs/sdk/src/core/passkey/types.cjs +1 -0
- package/dist/cjs/sdk/src/types/types.cjs +1 -1
- package/dist/cjs/sdk/src/utils/observe.cjs +1 -0
- package/dist/cjs/sdk/src/version.cjs +1 -1
- package/dist/cjs/sdk/src/wallets/embedded.cjs +1 -1
- package/dist/cjs/sdk/src/wallets/evm/evmProvider.cjs +1 -1
- package/dist/cjs/sdk/src/wallets/evm/types.cjs +1 -1
- package/dist/cjs/sdk/src/wallets/evm/walletHelpers.cjs +1 -1
- package/dist/cjs/sdk/src/wallets/iframeManager.cjs +1 -1
- package/dist/index.d.cts +32 -18
- package/dist/index.d.ts +32 -18
- package/dist/sdk/src/api/embeddedWallet.js +1 -1
- package/dist/sdk/src/core/config/config.js +1 -1
- package/dist/sdk/src/core/openfort.js +1 -1
- package/dist/sdk/src/core/passkey/handler.js +1 -1
- package/dist/sdk/src/core/passkey/types.js +1 -0
- package/dist/sdk/src/types/types.js +1 -1
- package/dist/sdk/src/utils/observe.js +1 -0
- package/dist/sdk/src/version.js +1 -1
- package/dist/sdk/src/wallets/embedded.js +1 -1
- package/dist/sdk/src/wallets/evm/evmProvider.js +1 -1
- package/dist/sdk/src/wallets/evm/types.js +1 -1
- package/dist/sdk/src/wallets/evm/walletHelpers.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/errors/openfortError.cjs"),t=require("../core/passkey/handler.cjs"),a=require("../core/config/config.cjs"),s=require("../core/configuration/account.cjs"),i=require("../core/configuration/authentication.cjs"),n=require("../core/errors/authErrorCodes.cjs"),o=require("../core/errors/withApiError.cjs"),d=require("../types/types.cjs"),c=require("../utils/debug.cjs"),g=require("../wallets/embedded.cjs"),h=require("../wallets/evm/evmProvider.cjs");require("../wallets/evm/types.cjs");var u=require("../wallets/evm/provider/eip6963.cjs"),y=require("../wallets/evm/walletHelpers.cjs"),l=require("../wallets/iframeManager.cjs"),m=require("../wallets/messaging/ReactNativeMessenger.cjs");require("../wallets/messaging/browserMessenger/backwardCompatibility.cjs");var f=require("../wallets/messaging/browserMessenger/messengers/WindowMessenger.cjs");exports.EmbeddedWalletApi=class{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,r,t,a,s){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=a,this.passkeyHandler=s,this.eventEmitter.on(d.OpenfortEvents.ON_LOGOUT,()=>{c.debugLog("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=a.SDKConfiguration.getInstance();if(!t)throw new r.ConfigurationError("Configuration not found");return new e.BackendApiClients({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey,nativeAppIdentifier:t.nativeAppIdentifier})}async getIframeManager(){if(c.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(c.debugLog("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;c.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return c.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,c.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw c.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){c.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=a.SDKConfiguration.getInstance();if(!e)throw c.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new r.ConfigurationError("Configuration not found");let t;if(c.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)c.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(c.debugLog("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new m.ReactNativeMessenger(this.messagePoster),c.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{c.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),a=new URL(e.iframeUrl).origin;t=new f({remoteWindow:r.contentWindow,allowedOrigins:[a]}),c.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return c.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new l.IframeManager(e,this.storage,t)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(c.debugLog("IframeManager has failed, clearing signer for recreation"),this.signer=null),this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();await e.initialize();return new g.EmbeddedSigner(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new r.ConfigurationError("Document is not available. Please provide a message poster for non-browser environments.");const t=document.getElementById("openfort-iframe");t&&t.remove();const a=document.createElement("iframe");return a.style.display="none",a.id="openfort-iframe",a.src=e,document.body.appendChild(a),a}async getPasskeyKey(e){const t=await i.Authentication.fromStorage(this.storage);if(!t?.userId)throw new r.AuthenticationError("auth","User is required for passkey key derivation. Logout and login again.",401);return this.passkeyHandler.deriveAndExportKey({id:e,seed:t.userId})}async getEntropy(e){switch(e.recoveryMethod){case d.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case d.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};case d.RecoveryMethod.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new r.ConfigurationError("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC},[t,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i={chainId:e.chainId,entropy:a,accountType:e.accountType??d.AccountTypeEnum.SMART_ACCOUNT,chainType:e.chainType??d.ChainTypeEnum.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},n=await t.configure(i);return{id:n.id,chainId:n.chainId,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType,factoryAddress:n.factoryAddress,salt:n.salt,createdAt:n.createdAt,implementationAddress:n.implementationAddress,recoveryMethod:s.Account.parseRecoveryMethod(n.recoveryMethod),recoveryMethodDetails:n.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const o=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC},c=await i.Authentication.fromStorage(this.storage);if(!c)throw new r.SessionError(n.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(o.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!c.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),displayName:a.SDKConfiguration.getInstance()?.passkeyDisplayName??"Openfort - Embedded Wallet",seed:c.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");o.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[g,h]=await Promise.all([this.ensureSigner(),this.getEntropy(o)]),u=await g.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),y={id:u.id,chainId:u.chainId,address:u.address,ownerAddress:u.ownerAddress,chainType:u.chainType,accountType:u.accountType,implementationType:u.implementationType,factoryAddress:u.factoryAddress,salt:u.salt,createdAt:u.createdAt,implementationAddress:u.implementationAddress,recoveryMethod:s.Account.parseRecoveryMethod(u.recoveryMethod),recoveryMethodDetails:u.recoveryMethodDetails};return this.eventEmitter.emit(d.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,y),y}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC};if(t.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!t.passkeyInfo?.passkeyId)throw new r.ConfigurationError("Passkey ID must be provided for passkey recovery");t.passkeyInfo={passkeyId:t.passkeyInfo.passkeyId}}const[a,i]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),n=await a.recover({account:e.account,entropy:i}),o={id:n.id,chainId:n.chainId,implementationAddress:n.implementationAddress,factoryAddress:n.factoryAddress,salt:n.salt,address:n.address,ownerAddress:n.ownerAddress,chainType:n.chainType,accountType:n.accountType,implementationType:n.implementationType,createdAt:n.createdAt,recoveryMethod:s.Account.parseRecoveryMethod(n.recoveryMethod),recoveryMethodDetails:n.recoveryMethodDetails};return this.eventEmitter.emit(d.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o),o}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:a=!0,arrayifyMessage:i=!1}=r||{},n=await s.Account.fromStorage(this.storage);return await t.sign(e,i,a,n?.chainType)}async signTypedData(e,t,a){await this.validateAndRefreshToken();const i=await this.ensureSigner(),o=await s.Account.fromStorage(this.storage);if(!o)throw new r.SignerError(n.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No account found");const d={...t};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),g=c.hash(e,d,a);return await y.signMessage({hash:g,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:i,address:o.address,ownerAddress:o.ownerAddress,factoryAddress:o.factoryAddress,salt:o.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,o){await this.validateAndRefreshToken();const c=await this.ensureSigner(),g=await i.Authentication.fromStorage(this.storage);if(!g)throw new r.SessionError(n.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");let h,u,y,l;if(e.recoveryMethod===d.RecoveryMethod.PASSKEY){const e=await s.Account.fromStorage(this.storage);if(!e)throw new r.ConfigurationError("missing account");const t=e?.recoveryMethodDetails?.passkeyId;if(!t)throw new r.ConfigurationError("missing passkey id for account");if(!g.userId)throw new r.ConfigurationError("User ID is required for passkey key derivation");y={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:g.userId})}}else if(o.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!g.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),displayName:a.SDKConfiguration.getInstance()?.passkeyDisplayName??"Openfort - Embedded Wallet",seed:g.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");y={passkeyId:e.id,passkeyKey:e.key},l={passkeyId:e.id}}if(e.recoveryMethod===d.RecoveryMethod.PASSWORD?h=e.password:o.recoveryMethod===d.RecoveryMethod.PASSWORD&&(h=o.password),e.recoveryMethod===d.RecoveryMethod.AUTOMATIC?u=e.encryptionSession:o.recoveryMethod===d.RecoveryMethod.AUTOMATIC&&(u=o.encryptionSession),!h&&!u)throw new r.ConfigurationError("Password or encryption session is not provided");await c.setRecoveryMethod({recoveryMethod:o.recoveryMethod,recoveryPassword:h,encryptionSession:u,passkeyInfo:y});const m=await s.Account.fromStorage(this.storage);m&&new s.Account({...m,recoveryMethod:o.recoveryMethod,recoveryMethodDetails:l}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await s.Account.fromStorage(this.storage);if(!e)throw new r.SignerError(n.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No signer configured");if(!await i.Authentication.fromStorage(this.storage))throw new r.SessionError(n.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:s.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const t={accountType:d.AccountTypeEnum.SMART_ACCOUNT,...e},c=a.SDKConfiguration.getInstance();if(!c)throw new r.ConfigurationError("Configuration not found");const g=await i.Authentication.fromStorage(this.storage);if(!g)throw new r.SessionError(n.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),o.withApiError(async()=>(await this.backendApiClients.accountsV2Api.getAccountsV2(t,{headers:g.thirdPartyProvider?{authorization:`Bearer ${c.baseConfiguration.publishableKey}`,"x-player-token":g.token,"x-auth-provider":g.thirdPartyProvider,"x-token-type":g.thirdPartyTokenType}:{authorization:`Bearer ${g.token}`,"x-project-key":c.baseConfiguration.publishableKey}})).data.data.map(e=>({chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:s.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await i.Authentication.fromStorage(this.storage))return d.EmbeddedState.UNAUTHENTICATED;return await s.Account.fromStorage(this.storage)?d.EmbeddedState.READY:d.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return c.debugLog("Failed to get embedded state:",e),d.EmbeddedState.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await i.Authentication.fromStorage(this.storage),a=await s.Account.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new h.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:a||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&u.announceProvider({info:{...u.openfortProviderInfo,...r.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(r=>{setTimeout(r,e)});const r=await this.getIframeManager();if(!r.isLoaded())return!1;const t=await i.Authentication.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return c.debugLog("Ping failed:",e),!1}}getURL(){const e=a.SDKConfiguration.getInstance();if(!e)throw new r.ConfigurationError("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new r.ConfigurationError("Invalid message poster");this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleLogout(){if("undefined"==typeof document&&!this.messagePoster)return c.debugLog("Skipping signer disconnect: no messagePoster available in non-browser environment"),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,void(this.signerPromise=null);try{const e=await this.ensureSigner();await e.disconnect()}catch{}this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void c.debugLog("Invalid message received:",e);c.debugLog("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const r="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(r&&this.messenger&&this.messagePoster)return c.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();c.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&c.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),c.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),c.debugLog("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}};
|
|
1
|
+
"use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.cjs"),r=require("../core/errors/openfortError.cjs"),t=require("../core/passkey/handler.cjs"),s=require("../core/config/config.cjs"),n=require("../core/configuration/account.cjs"),a=require("../core/configuration/authentication.cjs"),i=require("../core/errors/authErrorCodes.cjs"),o=require("../core/errors/withApiError.cjs"),d=require("../types/types.cjs"),c=require("../utils/debug.cjs"),g=require("../utils/observe.cjs"),h=require("../wallets/embedded.cjs"),u=require("../wallets/evm/evmProvider.cjs");require("../wallets/evm/types.cjs");var y=require("../wallets/evm/provider/eip6963.cjs"),l=require("../wallets/evm/walletHelpers.cjs"),m=require("../wallets/iframeManager.cjs"),f=require("../wallets/messaging/ReactNativeMessenger.cjs");require("../wallets/messaging/browserMessenger/backwardCompatibility.cjs");var p=require("../wallets/messaging/browserMessenger/messengers/WindowMessenger.cjs");exports.EmbeddedWalletApi=class{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,r,t,s,n){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=s,this.passkeyHandler=n,this.eventEmitter.on(d.OpenfortEvents.ON_LOGOUT,()=>{c.debugLog("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=s.SDKConfiguration.getInstance();if(!t)throw new r.ConfigurationError("Configuration not found");return new e.BackendApiClients({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey,nativeAppIdentifier:t.nativeAppIdentifier})}async getIframeManager(){if(c.debugLog("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(c.debugLog("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return c.debugLog("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;c.debugLog("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return c.debugLog("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,c.debugLog("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw c.debugLog("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){c.debugLog("[HANDSHAKE DEBUG] createIframeManager starting");const e=s.SDKConfiguration.getInstance();if(!e)throw c.debugLog("[HANDSHAKE DEBUG] Configuration not found"),new r.ConfigurationError("Configuration not found");let t;if(c.debugLog("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)c.debugLog("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(c.debugLog("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new f.ReactNativeMessenger(this.messagePoster),c.debugLog("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{c.debugLog("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new p({remoteWindow:r.contentWindow,allowedOrigins:[s]}),c.debugLog("[HANDSHAKE DEBUG] Created WindowMessenger")}return c.debugLog("[HANDSHAKE DEBUG] Creating IframeManager instance"),new m.IframeManager(e,this.storage,t)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(c.debugLog("IframeManager has failed, clearing signer for recreation"),this.signer=null),this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();await e.initialize();return new h.EmbeddedSigner(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new r.ConfigurationError("Document is not available. Please provide a message poster for non-browser environments.");const t=document.getElementById("openfort-iframe");t&&t.remove();const s=document.createElement("iframe");return s.style.display="none",s.id="openfort-iframe",s.src=e,document.body.appendChild(s),s}async getPasskeyKey(e){const t=await a.Authentication.fromStorage(this.storage);if(!t?.userId)throw new r.AuthenticationError("auth","User is required for passkey key derivation. Logout and login again.",401);return this.passkeyHandler.deriveAndExportKey({id:e,seed:t.userId})}async getEntropy(e){switch(e.recoveryMethod){case d.RecoveryMethod.PASSWORD:return{recoveryPassword:e.password};case d.RecoveryMethod.AUTOMATIC:return{encryptionSession:e.encryptionSession};case d.RecoveryMethod.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new r.ConfigurationError("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC},[t,s]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),a={chainId:e.chainId,entropy:s,accountType:e.accountType??d.AccountTypeEnum.SMART_ACCOUNT,chainType:e.chainType??d.ChainTypeEnum.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},i=await t.configure(a);return{id:i.id,chainId:i.chainId,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,factoryAddress:i.factoryAddress,salt:i.salt,createdAt:i.createdAt,implementationAddress:i.implementationAddress,recoveryMethod:n.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const s=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC},o=await a.Authentication.fromStorage(this.storage);if(!o)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");if(s.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!o.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:o.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");s.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[c,g]=await Promise.all([this.ensureSigner(),this.getEntropy(s)]),h=await c.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:g}),u={id:h.id,chainId:h.chainId,address:h.address,ownerAddress:h.ownerAddress,chainType:h.chainType,accountType:h.accountType,implementationType:h.implementationType,factoryAddress:h.factoryAddress,salt:h.salt,createdAt:h.createdAt,implementationAddress:h.implementationAddress,recoveryMethod:n.Account.parseRecoveryMethod(h.recoveryMethod),recoveryMethodDetails:h.recoveryMethodDetails};return this.eventEmitter.emit(d.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,u),u}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:d.RecoveryMethod.AUTOMATIC};if(t.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!t.passkeyInfo?.passkeyId)throw new r.ConfigurationError("Passkey ID must be provided for passkey recovery");t.passkeyInfo={passkeyId:t.passkeyInfo.passkeyId}}const[s,a]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),i=await s.recover({account:e.account,entropy:a}),o={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:n.Account.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(d.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o),o}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:s=!0,arrayifyMessage:a=!1}=r||{},i=await n.Account.fromStorage(this.storage);return await t.sign(e,a,s,i?.chainType)}async signTypedData(e,t,s){await this.validateAndRefreshToken();const a=await this.ensureSigner(),o=await n.Account.fromStorage(this.storage);if(!o)throw new r.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No account found");const d={...t};delete d.EIP712Domain;const{_TypedDataEncoder:c}=await import("@ethersproject/hash"),g=c.hash(e,d,s);return await l.signMessage({hash:g,implementationType:o.implementationType||o.type,chainId:Number(o.chainId),signer:a,address:o.address,ownerAddress:o.ownerAddress,factoryAddress:o.factoryAddress,salt:o.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,s){await this.validateAndRefreshToken();const o=await this.ensureSigner(),c=await a.Authentication.fromStorage(this.storage);if(!c)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"missing authentication");let g,h,u,y;if(e.recoveryMethod===d.RecoveryMethod.PASSKEY){const e=await n.Account.fromStorage(this.storage);if(!e)throw new r.ConfigurationError("missing account");const t=e?.recoveryMethodDetails?.passkeyId;if(!t)throw new r.ConfigurationError("missing passkey id for account");if(!c.userId)throw new r.ConfigurationError("User ID is required for passkey key derivation");u={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:c.userId})}}else if(s.recoveryMethod===d.RecoveryMethod.PASSKEY){if(!c.userId)throw new r.ConfigurationError("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),seed:c.userId});if(!e.key)throw new r.ConfigurationError("Passkey creation failed: no key material returned");u={passkeyId:e.id,passkeyKey:e.key},y={passkeyId:e.id}}if(e.recoveryMethod===d.RecoveryMethod.PASSWORD?g=e.password:s.recoveryMethod===d.RecoveryMethod.PASSWORD&&(g=s.password),e.recoveryMethod===d.RecoveryMethod.AUTOMATIC?h=e.encryptionSession:s.recoveryMethod===d.RecoveryMethod.AUTOMATIC&&(h=s.encryptionSession),!g&&!h)throw new r.ConfigurationError("Password or encryption session is not provided");await o.setRecoveryMethod({recoveryMethod:s.recoveryMethod,recoveryPassword:g,encryptionSession:h,passkeyInfo:u});const l=await n.Account.fromStorage(this.storage);l&&new n.Account({...l,recoveryMethod:s.recoveryMethod,recoveryMethodDetails:y}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await n.Account.fromStorage(this.storage);if(!e)throw new r.SignerError(i.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"No signer configured");if(!await a.Authentication.fromStorage(this.storage))throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:n.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const t={...e},d=s.SDKConfiguration.getInstance();if(!d)throw new r.ConfigurationError("Configuration not found");const c=await a.Authentication.fromStorage(this.storage);if(!c)throw new r.SessionError(i.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),o.withApiError(async()=>(await this.backendApiClients.accountsV2Api.getAccountsV2(t,{headers:c.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}:{authorization:`Bearer ${c.token}`,"x-project-key":d.baseConfiguration.publishableKey}})).data.data.map(e=>({chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:n.Account.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await a.Authentication.fromStorage(this.storage))return d.EmbeddedState.UNAUTHENTICATED;return await n.Account.fromStorage(this.storage)?d.EmbeddedState.READY:d.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return c.debugLog("Failed to get embedded state:",e),d.EmbeddedState.UNAUTHENTICATED}}watchEmbeddedState(e){return g.observe("watchEmbeddedState",{onChange:e.onChange,onError:e.onError},r=>{let t;const s=async()=>{try{const e=await this.getEmbeddedState();t!==e&&(r.onChange?.(e,t),t=e)}catch(e){r.onError?.(e instanceof Error?e:new Error(String(e)))}};s();const n=()=>s(),a=()=>s(),i=()=>s(),o=()=>s();this.eventEmitter.on(d.OpenfortEvents.ON_AUTH_SUCCESS,n),this.eventEmitter.on(d.OpenfortEvents.ON_LOGOUT,a),this.eventEmitter.on(d.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,i),this.eventEmitter.on(d.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o);const c=setInterval(s,e.pollingInterval??2e3);return()=>{clearInterval(c),this.eventEmitter.off(d.OpenfortEvents.ON_AUTH_SUCCESS,n),this.eventEmitter.off(d.OpenfortEvents.ON_LOGOUT,a),this.eventEmitter.off(d.OpenfortEvents.ON_EMBEDDED_WALLET_CREATED,i),this.eventEmitter.off(d.OpenfortEvents.ON_EMBEDDED_WALLET_RECOVERED,o)}})}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await a.Authentication.fromStorage(this.storage),s=await n.Account.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new u.EvmProvider({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&y.announceProvider({info:{...y.openfortProviderInfo,...r.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(r=>{setTimeout(r,e)});const r=await this.getIframeManager();if(!r.isLoaded())return!1;const t=await a.Authentication.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return c.debugLog("Ping failed:",e),!1}}getURL(){const e=s.SDKConfiguration.getInstance();if(!e)throw new r.ConfigurationError("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new r.ConfigurationError("Invalid message poster");this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleLogout(){if("undefined"==typeof document&&!this.messagePoster)return c.debugLog("Skipping signer disconnect: no messagePoster available in non-browser environment"),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,void(this.signerPromise=null);try{const e=await this.ensureSigner();await e.disconnect()}catch{}this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void c.debugLog("Invalid message received:",e);c.debugLog("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const r="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(r&&this.messenger&&this.messagePoster)return c.debugLog("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();c.debugLog(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&c.debugLog("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),c.debugLog("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),c.debugLog("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../utils/crypto.cjs");class
|
|
1
|
+
"use strict";var e=require("../../utils/crypto.cjs");class i{baseConfiguration;shieldConfiguration;thirdPartyAuth;shieldUrl;iframeUrl;backendUrl;storage;nativeAppIdentifier;debug;static instance=null;constructor({baseConfiguration:s,shieldConfiguration:t,overrides:r,thirdPartyAuth:a,debug:n}){this.shieldConfiguration=t,this.baseConfiguration=s,this.backendUrl=r?.backendUrl||"https://api.openfort.io",this.iframeUrl=r?.iframeUrl||"https://embed.openfort.io",this.iframeUrl=`${this.iframeUrl}/iframe/${this.baseConfiguration.publishableKey}`,this.debug=n,t?.debug&&(this.iframeUrl=`${this.iframeUrl}?debug=true`),this.shieldUrl=r?.shieldUrl||"https://shield.openfort.io",this.storage=r?.storage,this.thirdPartyAuth=a,this.nativeAppIdentifier=s.nativeAppIdentifier,r?.crypto?.digest&&e.setCryptoDigestOverride(r.crypto.digest),i.instance=this}static getInstance(){return i.instance}}exports.OpenfortConfiguration=class{publishableKey;nativeAppIdentifier;constructor(e){this.publishableKey=e.publishableKey,this.nativeAppIdentifier=e.nativeAppIdentifier}},exports.SDKConfiguration=i,exports.ShieldConfiguration=class{shieldPublishableKey;debug=!1;passkeyRpId;passkeyRpName;passkeyDisplayName;constructor(e){this.shieldPublishableKey=e.shieldPublishableKey,this.debug=e.shieldDebug||!1,this.passkeyRpId=e.passkeyRpId,this.passkeyRpName=e.passkeyRpName,this.passkeyDisplayName=e.passkeyDisplayName}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.cjs"),t=require("../api/auth.cjs"),i=require("../api/embeddedWallet.cjs"),n=require("../api/proxy.cjs"),a=require("../api/user.cjs"),
|
|
1
|
+
"use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.cjs"),t=require("../api/auth.cjs"),i=require("../api/embeddedWallet.cjs"),n=require("../api/proxy.cjs"),a=require("../api/user.cjs"),s=require("../auth/authManager.cjs"),r=require("../storage/istorage.cjs"),o=require("../storage/lazyStorage.cjs"),h=require("../utils/typedEventEmitter.cjs"),l=require("./config/config.cjs"),c=require("./errors/authErrorCodes.cjs"),u=require("./errors/openfortError.cjs"),d=require("./errors/sentry.cjs"),g=require("./openfortInternal.cjs"),f=require("./passkey/handler.cjs");class p{storage;iAuthManager=null;openfortInternal;initPromise;asyncInitPromise=null;authInstance;embeddedWalletInstance;userInstance;proxyInstance;configuration;eventEmitter;iPasskeyHandler;static globalEventEmitter=null;get auth(){if(!this.authInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.");return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.");return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.");return this.userInstance}get proxy(){if(!this.proxyInstance)throw new u.ConfigurationError("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.");return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new s.AuthManager,this.openfortInternal=new g.OpenfortInternal(this.storage,this.authManager,this.eventEmitter),this.authInstance=new t.AuthApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter),this.embeddedWalletInstance=new i.EmbeddedWalletApi(this.storage,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter,this.passkeyHandler),this.userInstance=new a.UserApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this)),this.proxyInstance=new n.ProxyApi(this.storage,this.backendApiClients,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),async()=>{if(!this.embeddedWalletInstance)throw new u.SignerError(c.OPENFORT_AUTH_ERROR_CODES.MISSING_SIGNER,"Embedded wallet not initialized");const e=this.embeddedWalletInstance;return t=>e.signMessage(t,{hashMessage:!0,arrayifyMessage:!0})})}catch(e){throw new u.ConfigurationError("Openfort SDK synchronous initialization failed")}}constructor(e){if(this.configuration=new l.SDKConfiguration(e),this.storage=new o.LazyStorage(this.configuration.baseConfiguration.publishableKey,this.configuration.storage),this.eventEmitter=new h,p.globalEventEmitter){["onAuthInit","onAuthSuccess","onAuthFailure","onLogout","onSwitchAccount","onSignedMessage","onEmbeddedWalletCreated","onEmbeddedWalletRecovered","onAuthFlowOpen","onAuthFlowClose","onAuthFlowCancel"].forEach(e=>{this.eventEmitter.on(e,(...t)=>{p.globalEventEmitter?.emit(e,...t)})})}else p.globalEventEmitter=this.eventEmitter;this.iPasskeyHandler=e.overrides?.passkeyHandler??new f.PasskeyHandler({rpId:e.shieldConfiguration?.passkeyRpId,rpName:e.shieldConfiguration?.passkeyRpName,displayName:e.shieldConfiguration?.passkeyDisplayName}),d.InternalSentry.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}static getEventEmitter(){return p.globalEventEmitter||(p.globalEventEmitter=new h),p.globalEventEmitter}async waitForInitialization(){await this.initPromise,await this.ensureAsyncInitialized()}async getAccessToken(){return await this.ensureInitialized(),this.openfortInternal.getAccessToken()}async validateAndRefreshToken(e){return await this.ensureInitialized(),await this.openfortInternal.validateAndRefreshToken(e)}get backendApiClients(){return new e.BackendApiClients({basePath:this.configuration.backendUrl,accessToken:this.configuration.baseConfiguration.publishableKey,nativeAppIdentifier:this.configuration.nativeAppIdentifier,storage:this.storage,onLogout:()=>{this.eventEmitter.emit("onLogout")}})}get authManager(){if(!this.iAuthManager)throw new u.RequestError("AuthManager not initialized");return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(e){try{const t=r.StorageKeys.TEST,i="openfort_storage_test";e.save(t,i);const n=await e.get(t);return e.remove(t),n===i}catch(e){return!1}}async initializeAsync(){if(!await p.isStorageAccessible(this.storage))throw new u.OpenfortError("Storage is not accessible",c.OPENFORT_ERROR_CODES.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}exports.Openfort=p;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("human-id"),r=require("./errors.cjs"),t=require("./utils.cjs");exports.PasskeyHandler=class{validByteLengths=[16,24,32];rpId;rpName;timeoutMs;derivedKeyLengthBytes;constructor({rpId:e,rpName:r,timeoutMs:
|
|
1
|
+
"use strict";var e=require("human-id"),r=require("./errors.cjs"),t=require("./types.cjs"),s=require("./utils.cjs");exports.PasskeyHandler=class{validByteLengths=[16,24,32];rpId;rpName;displayName;timeoutMs;derivedKeyLengthBytes;constructor({rpId:e,rpName:r,displayName:s,timeoutMs:a,derivedKeyLengthBytes:i}={}){if(this.rpId=e,this.rpName=r,this.displayName=s??t.DEFAULT_PASSKEY_DISPLAY_NAME,this.timeoutMs=a??6e4,this.derivedKeyLengthBytes=i??32,!this.validByteLengths.includes(this.derivedKeyLengthBytes))throw new Error(`Invalid key byte length ${this.derivedKeyLengthBytes}`)}static randomPasskeyName(){return e.humanId({capitalize:!0,separator:" "})}getChallengeBytes(){return crypto.getRandomValues(new Uint8Array(32))}async deriveKeyFromAssertion(e){const t=e.getClientExtensionResults();if(!t)throw new r.PasskeyPRFNotSupportedError("Passkey fetch failed: no client extension results");const s=t.prf;if(!s||!s.results)throw new r.PasskeyPRFNotSupportedError("PRF extension not supported or missing results");const a=s.results.first,i=await crypto.subtle.importKey("raw",a,{name:"AES-CBC",length:this.derivedKeyLengthBytes},!0,["encrypt","decrypt"]);return crypto.subtle.exportKey("raw",i)}async createPasskey({id:e,seed:t}){if(!t||0===t.trim().length)throw new r.PasskeySeedInvalidError;const a={challenge:this.getChallengeBytes(),rp:{id:this.rpId,name:this.rpName},user:{id:(new TextEncoder).encode(e),name:e,displayName:this.displayName},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{residentKey:"required",userVerification:"required"},extensions:{prf:{eval:{first:(new TextEncoder).encode(t)}}},timeout:this.timeoutMs,attestation:"direct"};let i,n;try{i=await navigator.credentials.create({publicKey:a})}catch(e){if(e instanceof Error&&"NotAllowedError"===e.name)throw new r.PasskeyUserCancelledError;throw new r.PasskeyCreationFailedError(e instanceof Error?e.message:"Unknown error",e instanceof Error?e:void 0)}if(!i)throw new r.PasskeyUserCancelledError;try{n=await this.deriveKeyFromAssertion(i)}catch(e){throw e instanceof r.PasskeyPRFNotSupportedError&&console.warn(`[Openfort] Passkey created but PRF extension failed. A passkey credential may exist on the device that cannot be used for wallet recovery. Credential ID: ${s.arrayBufferToBase64URL(i.rawId)}`),e}return{id:s.arrayBufferToBase64URL(i.rawId),displayName:this.displayName,key:s.arrayBufferToBase64URL(n)}}async deriveAndExportKey({id:e,seed:t}){if(!t||0===t.trim().length)throw new r.PasskeySeedInvalidError;let a;try{a=await navigator.credentials.get({publicKey:{challenge:this.getChallengeBytes(),rpId:this.rpId,allowCredentials:[{id:s.base64ToArrayBuffer(e),type:"public-key"}],userVerification:"required",extensions:{prf:{eval:{first:(new TextEncoder).encode(t)}}}}})}catch(e){if(e instanceof Error&&"NotAllowedError"===e.name)throw new r.PasskeyUserCancelledError;throw new r.PasskeyAssertionFailedError(e instanceof Error?e.message:"Unknown error",e instanceof Error?e:void 0)}if(!a)throw new r.PasskeyUserCancelledError;const i=await this.deriveKeyFromAssertion(a);return s.arrayBufferToBase64URL(i)}};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";exports.DEFAULT_PASSKEY_DISPLAY_NAME="Openfort - Embedded Wallet";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e,t,o,E,
|
|
1
|
+
"use strict";var e,t,o,r,E,A,T,p,s,i,d,n;exports.EmbeddedState=void 0,(e=exports.EmbeddedState||(exports.EmbeddedState={}))[e.NONE=0]="NONE",e[e.UNAUTHENTICATED=1]="UNAUTHENTICATED",e[e.EMBEDDED_SIGNER_NOT_CONFIGURED=2]="EMBEDDED_SIGNER_NOT_CONFIGURED",e[e.CREATING_ACCOUNT=3]="CREATING_ACCOUNT",e[e.READY=4]="READY",exports.OpenfortEvents=void 0,(t=exports.OpenfortEvents||(exports.OpenfortEvents={})).ON_AUTH_INIT="onAuthInit",t.ON_AUTH_SUCCESS="onAuthSuccess",t.ON_OTP_REQUEST="onOtpRequest",t.ON_OTP_FAILURE="onOtpFailure",t.ON_AUTH_FAILURE="onAuthFailure",t.ON_LOGOUT="onLogout",t.ON_SWITCH_ACCOUNT="onSwitchAccount",t.ON_SIGNED_MESSAGE="onSignedMessage",t.ON_EMBEDDED_WALLET_CREATED="onEmbeddedWalletCreated",t.ON_EMBEDDED_WALLET_RECOVERED="onEmbeddedWalletRecovered",exports.RecoveryMethod=void 0,(o=exports.RecoveryMethod||(exports.RecoveryMethod={})).PASSWORD="password",o.AUTOMATIC="automatic",o.PASSKEY="passkey",exports.AccountType=void 0,(r=exports.AccountType||(exports.AccountType={})).UPGRADEABLE_V5="UpgradeableV5",r.UPGRADEABLE_V6="UpgradeableV6",r.SIMPLE="Simple",r.CALIBUR="Calibur",r.CALIBUR_V9="CaliburV9",exports.AuthType=void 0,(E=exports.AuthType||(exports.AuthType={})).OPENFORT="openfort",E.THIRD_PARTY="thirdParty",exports.TokenType=void 0,(A=exports.TokenType||(exports.TokenType={})).ID_TOKEN="idToken",A.CUSTOM_TOKEN="customToken",exports.ThirdPartyAuthProvider=void 0,(T=exports.ThirdPartyAuthProvider||(exports.ThirdPartyAuthProvider={})).ACCELBYTE="accelbyte",T.FIREBASE="firebase",T.BETTER_AUTH="better-auth",T.LOOTLOCKER="lootlocker",T.PLAYFAB="playfab",T.SUPABASE="supabase",T.CUSTOM="custom",T.OIDC="oidc",exports.BasicAuthProvider=void 0,(p=exports.BasicAuthProvider||(exports.BasicAuthProvider={})).EMAIL="email",p.WALLET="wallet",exports.OAuthProvider=void 0,(s=exports.OAuthProvider||(exports.OAuthProvider={})).GOOGLE="google",s.TWITTER="twitter",s.APPLE="apple",s.FACEBOOK="facebook",s.DISCORD="discord",s.EPIC_GAMES="epic_games",s.LINE="line",exports.AuthActionRequiredActions=void 0,(exports.AuthActionRequiredActions||(exports.AuthActionRequiredActions={})).ACTION_VERIFY_EMAIL="verify_email",exports.AccountTypeEnum=void 0,(i=exports.AccountTypeEnum||(exports.AccountTypeEnum={})).EOA="Externally Owned Account",i.SMART_ACCOUNT="Smart Account",i.DELEGATED_ACCOUNT="Delegated Account",exports.ChainTypeEnum=void 0,(d=exports.ChainTypeEnum||(exports.ChainTypeEnum={})).EVM="EVM",d.SVM="SVM",function(e){e.ASC="asc",e.DESC="desc"}(n||(n={}));
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const t=new Map,n=new Map;let e=0;exports.observe=function(s,o,c){const f=++e,i=()=>t.get(s)||[],r=()=>{const e=i();if(!e.some(t=>t.id===f))return;const o=n.get(s);if(1===e.length&&o){const t=o();t instanceof Promise&&t.catch(()=>{})}(()=>{const n=i();t.set(s,n.filter(t=>t.id!==f))})()},u=i();if(t.set(s,[...u,{id:f,fns:o}]),u&&u.length>0)return r;const g={};for(const t in o)g[t]=(...n)=>{const e=i();if(0!==e.length)for(const s of e)s.fns[t]?.(...n)};const l=c(g);return"function"==typeof l&&n.set(s,l),r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.1
|
|
1
|
+
"use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="1.2.1";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../core/configuration/authentication.cjs"),t=require("../core/errors/authErrorCodes.cjs"),a=require("../core/errors/openfortError.cjs"),r=require("../core/errors/withApiError.cjs"),o=require("../core/passkey/handler.cjs"),n=require("../core/config/config.cjs"),s=require("../core/configuration/account.cjs"),i=require("../storage/istorage.cjs"),c=require("../types/types.cjs");exports.EmbeddedSigner=class{iframeManager;storage;backendApiClients;passkeyHandler;eventEmitter;constructor(e,t,a,r,o){this.iframeManager=e,this.storage=t,this.backendApiClients=a,this.passkeyHandler=r,this.eventEmitter=o}async createPasskey(e){const t=await this.passkeyHandler.createPasskey({id:o.PasskeyHandler.randomPasskeyName(),
|
|
1
|
+
"use strict";var e=require("../core/configuration/authentication.cjs"),t=require("../core/errors/authErrorCodes.cjs"),a=require("../core/errors/openfortError.cjs"),r=require("../core/errors/withApiError.cjs"),o=require("../core/passkey/handler.cjs"),n=require("../core/config/config.cjs"),s=require("../core/configuration/account.cjs"),i=require("../storage/istorage.cjs"),c=require("../types/types.cjs");exports.EmbeddedSigner=class{iframeManager;storage;backendApiClients;passkeyHandler;eventEmitter;constructor(e,t,a,r,o){this.iframeManager=e,this.storage=t,this.backendApiClients=a,this.passkeyHandler=r,this.eventEmitter=o}async createPasskey(e){const t=await this.passkeyHandler.createPasskey({id:o.PasskeyHandler.randomPasskeyName(),seed:e});return{id:t.id,key:t.key}}async configure(o){const i=await e.Authentication.fromStorage(this.storage);if(!i)throw new a.SessionError(t.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");const d=n.SDKConfiguration.getInstance();if(!d)throw new a.ConfigurationError("Configuration not found");const y=await s.Account.fromStorage(this.storage);let h;if(y){const e={account:y.id,...o.entropy&&{entropy:{...o.entropy.recoveryPassword&&{recoveryPassword:o.entropy.recoveryPassword},...o.entropy.encryptionSession&&{encryptionSession:o.entropy.encryptionSession},..."passkey"===y.recoveryMethod&&{passkey:{id:y.recoveryMethodDetails?.passkeyId,env:y.recoveryMethodDetails?.passkeyEnv,key:await o.getPasskeyKeyFn(y.recoveryMethodDetails?.passkeyId??"")}}}}},t=await this.iframeManager.recover(e);h=t.account}else{const e=await this.backendApiClients.accountsV2Api.getAccountsV2({accountType:o.accountType,chainType:o.chainType},{headers:i.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":d.baseConfiguration.publishableKey}});if(0===e.data.data.length){const e=o.entropy?.passkey?await this.createPasskey(i.userId):void 0,t={accountType:o.accountType,chainType:o.chainType,chainId:o.chainId,...o.entropy&&{entropy:{...o.entropy.recoveryPassword&&{recoveryPassword:o.entropy.recoveryPassword},...o.entropy.encryptionSession&&{encryptionSession:o.entropy.encryptionSession},...o.entropy.passkey&&{passkey:e}}}},a=await this.iframeManager.create(t);h=a.account}else{const t=e.data.data,a=t.find(e=>e.chainId===o.chainId),r=a||t[0],n={account:r.id,...o.entropy&&{entropy:{...o.entropy.recoveryPassword&&{recoveryPassword:o.entropy.recoveryPassword},...o.entropy.encryptionSession&&{encryptionSession:o.entropy.encryptionSession},..."passkey"===r.recoveryMethod&&{passkey:{id:r.recoveryMethodDetails?.passkeyId,env:r.recoveryMethodDetails?.passkeyEnv,key:await o.getPasskeyKeyFn(r.recoveryMethodDetails?.passkeyId??"")}}}}},s=await this.iframeManager.recover(n);if(h=s.account,!a){const e=await this.iframeManager.switchChain(o.chainId);h=e.account}}}return r.withApiError(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:h},{headers:i.thirdPartyProvider?{authorization:`Bearer ${d.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":d.baseConfiguration.publishableKey}}),t=new s.Account({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:s.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(c.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"configure"})}async sign(e,t,a,r){const o=await this.iframeManager.sign(e,t,a,r);return this.eventEmitter.emit(c.OpenfortEvents.ON_SIGNED_MESSAGE,{message:e,signature:o}),o}async export(){return await this.iframeManager.export()}async switchChain({chainId:e}){const t=await s.Account.fromStorage(this.storage);if(t?.accountType===c.AccountTypeEnum.EOA)new s.Account({...t,chainId:e}).save(this.storage);else{const a=await this.iframeManager.switchChain(e);new s.Account({...t,id:a.account,chainId:e}).save(this.storage)}}async create(o){const i=await this.iframeManager.create(o),d=await e.Authentication.fromStorage(this.storage);if(!d)throw new a.SessionError(t.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");const y=n.SDKConfiguration.getInstance();if(!y)throw new a.ConfigurationError("Configuration not found");return r.withApiError(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:i.account},{headers:d.thirdPartyProvider?{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}:{authorization:`Bearer ${d.token}`,"x-project-key":y.baseConfiguration.publishableKey}}),t=new s.Account({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,implementationAddress:e.data.smartAccount?.implementationAddress,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:s.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(c.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"create"})}async recover(o){const i=await this.iframeManager.recover(o),d=await e.Authentication.fromStorage(this.storage);if(!d)throw new a.SessionError(t.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"No access token found");const y=n.SDKConfiguration.getInstance();if(!y)throw new a.ConfigurationError("Configuration not found");return r.withApiError(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:i.account},{headers:d.thirdPartyProvider?{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":d.token,"x-auth-provider":d.thirdPartyProvider,"x-token-type":d.thirdPartyTokenType}:{authorization:`Bearer ${d.token}`,"x-project-key":y.baseConfiguration.publishableKey}}),t=new s.Account({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:s.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(c.OpenfortEvents.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"recover"})}async setRecoveryMethod({recoveryMethod:e,recoveryPassword:t,encryptionSession:a,passkeyInfo:r}){await this.iframeManager.setRecoveryMethod(e,t,a,r?.passkeyKey,r?.passkeyId)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(i.StorageKeys.ACCOUNT)}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../core/configuration/account.cjs"),t=require("../../core/configuration/authentication.cjs"),r=require("../../types/types.cjs"),a=require("../../utils/chains/index.cjs"),
|
|
1
|
+
"use strict";var e=require("../../core/configuration/account.cjs"),t=require("../../core/configuration/authentication.cjs"),r=require("../../types/types.cjs"),a=require("../../utils/chains/index.cjs"),i=require("../../utils/crypto.cjs"),s=require("../../utils/typedEventEmitter.cjs"),o=require("./addEthereumChain.cjs"),n=require("./estimateGas.cjs"),c=require("./getAssets.cjs"),h=require("./getCallsStatus.cjs"),d=require("./JsonRpcError.cjs"),u=require("./personalSign.cjs"),p=require("./registerSession.cjs"),l=require("./revokeSession.cjs"),w=require("./sendCallSync.cjs"),m=require("./sendCalls.cjs"),g=require("./signTypedDataV4.cjs"),E=require("./types.cjs"),A=require("./walletHelpers.cjs");exports.EvmProvider=class{#e;#t;#r;#a;updatePolicy(e){this.#t=e}#i;#s;#o=null;#n;isOpenfort=!0;#c;constructor({storage:e,backendApiClients:t,openfortEventEmitter:a,policyId:i,ensureSigner:o,chains:n,validateAndRefreshSession:c}){this.#c=o,this.#e=e,this.#r=n,this.#t=i,this.#i=c,this.#n=t,this.#s=new s,a.on(r.OpenfortEvents.ON_LOGOUT,this.#h),a.on(r.OpenfortEvents.ON_SWITCH_ACCOUNT,this.#d)}#u=async()=>(this.#a||(this.#a=await this.#c()),this.#a);#h=async()=>{this.#a=void 0,this.#s.emit(E.ProviderEvent.DISCONNECT,{code:4900,message:"Disconnected"}),this.#s.emit(E.ProviderEvent.ACCOUNTS_CHANGED,[])};#d=async e=>{this.#s.emit(E.ProviderEvent.ACCOUNTS_CHANGED,[e])};async getRpcProvider(){if(!this.#o){const t=await e.Account.fromStorage(this.#e),r=t?.chainId||8453;await import("@ethersproject/providers").then(e=>{const t=this.#r?this.#r[r]:void 0;this.#o=new e.StaticJsonRpcProvider(t??a.defaultChainRpcs[r])})}if(!this.#o)throw new Error("RPC provider not initialized");return this.#o}async#p(s){switch(s.method){case"eth_accounts":{const t=await e.Account.fromStorage(this.#e);return t?[t.address]:[]}case"eth_requestAccounts":{const t=await e.Account.fromStorage(this.#e);if(t){const e=await this.getRpcProvider(),{chainId:r}=await e.detectNetwork();return this.#s.emit(E.ProviderEvent.ACCOUNTS_CONNECT,{chainId:i.numberToHex(r)}),[t.address]}throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer.")}case"eth_signTransaction":{const r=await e.Account.fromStorage(this.#e),a=await this.#u(),i=await t.Authentication.fromStorage(this.#e);if(!r||!i)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const o=await this.getRpcProvider(),{chainId:n}=await o.detectNetwork(),[c]=s.params||[];c.chainId||(c.chainId=n.toString());const h=A.parseTransactionRequest(c),{serialize:u}=await import("@ethersproject/transactions"),p=e=>({legacy:0,eip2930:1,eip1559:2}[e]),{gas:l,...w}=h,m={...w,gasLimit:l,to:h.to??void 0,type:p(h.type)},g=u(m),{keccak256:E}=await import("@ethersproject/keccak256"),R=E(g);await this.#i();const v=await a.sign(R,!1,!1),{splitSignature:f}=await import("@ethersproject/bytes");return u(m,f(v))}case"eth_sendTransaction":{const[a,i,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#u(),t.Authentication.fromStorage(this.#e)]);if(!a||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(await this.#i(),a?.accountType===r.AccountTypeEnum.EOA){const[e]=s.params||[],t=await this.getRpcProvider(),r=await A.prepareEOATransaction(e,t,a.address),i=await this.#p({method:"eth_signTransaction",params:[r]});return this.#p({method:"eth_sendRawTransaction",params:[i]})}return(await w.sendCallsSync({params:s.params||[],signer:i,account:a,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),policyId:this.#t})).receipt.transactionHash}case"eth_sendRawTransactionSync":{const[a,i,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#u(),t.Authentication.fromStorage(this.#e)]);if(!a||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(a?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);return await this.#i(),await w.sendCallsSync({params:s.params||[],signer:i,account:a,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),policyId:this.#t})}case"eth_estimateGas":{const r=await e.Account.fromStorage(this.#e),a=await t.Authentication.fromStorage(this.#e);if(!r||!a)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await n.estimateGas({params:s.params||[],account:r,authentication:a,backendClient:this.#n,policyId:this.#t})}case"eth_signTypedData":case"eth_signTypedData_v4":{const t=await e.Account.fromStorage(this.#e),r=await this.#u();if(!t)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#i();const a=await this.getRpcProvider();return await g.signTypedDataV4({method:s.method,params:s.params||[],signer:r,implementationType:t.implementationType||t.type,rpcProvider:a,account:t})}case"personal_sign":{const t=await e.Account.fromStorage(this.#e);if(!t)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const r=await this.#u();return await this.#i(),await u.personalSign({params:s.params||[],signer:r,account:t})}case"eth_chainId":{const e=await this.getRpcProvider(),{chainId:t}=await e.detectNetwork();return i.numberToHex(t)}case"wallet_switchEthereumChain":{const e=await this.#u();if(!s.params||!Array.isArray(s.params)||0===s.params.length)throw new d.JsonRpcError(d.RpcErrorCode.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#i();try{const t=parseInt(s.params[0].chainId,16);await e.switchChain({chainId:t}),await import("@ethersproject/providers").then(e=>{const r=this.#r?this.#r[t]:void 0;this.#o=new e.StaticJsonRpcProvider(r??a.defaultChainRpcs[t])}),this.#s.emit(E.ProviderEvent.CHAIN_CHANGED,i.numberToHex(t))}catch(e){const t=e;throw new d.JsonRpcError(d.RpcErrorCode.INTERNAL_ERROR,`Failed to switch chain: ${t.message}`)}return null}case"wallet_addEthereumChain":{await this.#u();const e=await this.getRpcProvider();return await o.addEthereumChain({params:s.params||[],rpcProvider:e,storage:this.#e})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const a=await e.Account.fromStorage(this.#e);if(a?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);const i=await t.Authentication.fromStorage(this.#e);if(!a||!i)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await h.getCallStatus({params:s.params||{},authentication:i,backendClient:this.#n})}case"wallet_sendCalls":{const[a,i,o]=await Promise.all([e.Account.fromStorage(this.#e),this.#u(),t.Authentication.fromStorage(this.#e)]);if(a?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);if(!a||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#i();return await m.sendCalls({params:s.params?s.params[0].calls:[],signer:i,account:a,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),policyId:this.#t})}case"wallet_grantPermissions":{const a=await e.Account.fromStorage(this.#e);if(a?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);const i=await this.#u(),o=await t.Authentication.fromStorage(this.#e);if(!a||!o)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await p.registerSession({params:s.params||[],signer:i,account:a,authentication:o,backendClient:this.#n,policyId:this.#t})}case"wallet_revokePermissions":{const r=await e.Account.fromStorage(this.#e),a=await this.#u(),i=await t.Authentication.fromStorage(this.#e);if(!r||!i)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await l.revokeSession({params:s.params||[],signer:a,account:r,authentication:i,backendClient:this.#n,policyId:this.#t})}case"wallet_getCapabilities":{const t=await e.Account.fromStorage(this.#e);if(t?.accountType===r.AccountTypeEnum.EOA)throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${s.method}: Method not supported`);const a=await this.getRpcProvider(),{chainId:o}=await a.detectNetwork();return{[i.numberToHex(o)]:{permissions:{supported:!0,signerTypes:["account","key"],keyTypes:["secp256k1"],permissionTypes:["contract-calls"]},paymasterService:{supported:!0},atomicBatch:{supported:!0}}}}case"wallet_getAssets":{const r=await e.Account.fromStorage(this.#e),a=await t.Authentication.fromStorage(this.#e);if(!r||!a)throw new d.JsonRpcError(d.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#i(),await c.getAssets({params:s.params?.[0],account:r,authentication:a,backendClient:this.#n})}case"eth_gasPrice":case"eth_getBalance":case"eth_sendRawTransaction":case"eth_getCode":case"eth_getStorageAt":case"eth_call":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":case"eth_getTransactionCount":return(await this.getRpcProvider()).send(s.method,s.params||[]);default:throw new d.JsonRpcError(d.ProviderErrorCode.UNSUPPORTED_METHOD,`${s.method}: Method not supported`)}}async request(e){try{return this.#p(e)}catch(e){if(e instanceof d.JsonRpcError)throw e;if(e instanceof Error)throw new d.JsonRpcError(d.RpcErrorCode.INTERNAL_ERROR,e.message);throw new d.JsonRpcError(d.RpcErrorCode.INTERNAL_ERROR,"Internal error")}}on(e,t){this.#s.on(e,t)}removeListener(e,t){this.#s.off(e,t)}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e;exports.ProviderEvent=void 0,(e=exports.ProviderEvent||(exports.ProviderEvent={})).ACCOUNTS_CHANGED="accountsChanged",e.ACCOUNTS_CONNECT="connect";
|
|
1
|
+
"use strict";var e;exports.ProviderEvent=void 0,(e=exports.ProviderEvent||(exports.ProviderEvent={})).ACCOUNTS_CHANGED="accountsChanged",e.CHAIN_CHANGED="chainChanged",e.ACCOUNTS_CONNECT="connect",e.DISCONNECT="disconnect";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../types/types.cjs");exports.parseTransactionRequest=function({from:e,...t}){return{to:t.to,data:t.data,accessList:t.accessList,chainId:(i=t.chainId,i.startsWith("0x")?parseInt(i,16):parseInt(i,10)),type:t.type&&{"0x0":"legacy","0x1":"eip2930","0x2":"eip1559"}[t.type]||"eip1559",maxPriorityFeePerGas:t.maxPriorityFeePerGas?BigInt(t.maxPriorityFeePerGas):void 0,maxFeePerGas:t.maxFeePerGas?BigInt(t.maxFeePerGas):void 0,gasPrice:t.gasPrice?BigInt(t.gasPrice):void 0,value:(a=t.value,s=BigInt,r=0n,void 0!==a?s(a):r),nonce:t.nonce?parseInt(t.nonce.toString(),16):void 0,gas:t.gas?BigInt(t.gas):void 0};var a,s,r,i},exports.prepareEOATransaction=async function(e,t,a){const s={...e};if(!s.nonce){const e=await t.getTransactionCount(a,"pending");s.nonce=`0x${e.toString(16)}`}if(!s.gas)try{const e=await t.estimateGas({from:a,to:s.to,data:s.data,value:s.value});s.gas=e.toHexString()}catch{s.gas="0x5208"}const r=s.maxFeePerGas&&s.maxPriorityFeePerGas,i=s.gasPrice;if(!r&&!i){const e=await t.getBlock("latest");if(null!==e.baseFeePerGas&&void 0!==e.baseFeePerGas){const a=e.baseFeePerGas,r=a.mul(12).div(10),i=await t.getGasPrice();let n=i.sub(a);n.lt(0)&&(n=i.mul(0));const o=r.add(n);s.maxFeePerGas=o.toHexString(),s.maxPriorityFeePerGas=n.toHexString(),s.type="0x2",delete s.gasPrice}else{const e=(await t.getGasPrice()).mul(12).div(10);s.gasPrice=e.toHexString(),s.type="0x0",delete s.maxFeePerGas,delete s.maxPriorityFeePerGas}}return s},exports.signMessage=async t=>{const{hash:a,signer:s,ownerAddress:r,factoryAddress:i,salt:n,chainId:o,address:c,implementationType:d}=t;let p=a;if([e.AccountType.UPGRADEABLE_V5,e.AccountType.UPGRADEABLE_V6
|
|
1
|
+
"use strict";var e=require("../../types/types.cjs");exports.parseTransactionRequest=function({from:e,...t}){return{to:t.to,data:t.data,accessList:t.accessList,chainId:(i=t.chainId,i.startsWith("0x")?parseInt(i,16):parseInt(i,10)),type:t.type&&{"0x0":"legacy","0x1":"eip2930","0x2":"eip1559"}[t.type]||"eip1559",maxPriorityFeePerGas:t.maxPriorityFeePerGas?BigInt(t.maxPriorityFeePerGas):void 0,maxFeePerGas:t.maxFeePerGas?BigInt(t.maxFeePerGas):void 0,gasPrice:t.gasPrice?BigInt(t.gasPrice):void 0,value:(a=t.value,s=BigInt,r=0n,void 0!==a?s(a):r),nonce:t.nonce?parseInt(t.nonce.toString(),16):void 0,gas:t.gas?BigInt(t.gas):void 0};var a,s,r,i},exports.prepareEOATransaction=async function(e,t,a){const s={...e};if(!s.nonce){const e=await t.getTransactionCount(a,"pending");s.nonce=`0x${e.toString(16)}`}if(!s.gas)try{const e=await t.estimateGas({from:a,to:s.to,data:s.data,value:s.value});s.gas=e.toHexString()}catch{s.gas="0x5208"}const r=s.maxFeePerGas&&s.maxPriorityFeePerGas,i=s.gasPrice;if(!r&&!i){const e=await t.getBlock("latest");if(null!==e.baseFeePerGas&&void 0!==e.baseFeePerGas){const a=e.baseFeePerGas,r=a.mul(12).div(10),i=await t.getGasPrice();let n=i.sub(a);n.lt(0)&&(n=i.mul(0));const o=r.add(n);s.maxFeePerGas=o.toHexString(),s.maxPriorityFeePerGas=n.toHexString(),s.type="0x2",delete s.gasPrice}else{const e=(await t.getGasPrice()).mul(12).div(10);s.gasPrice=e.toHexString(),s.type="0x0",delete s.maxFeePerGas,delete s.maxPriorityFeePerGas}}return s},exports.signMessage=async t=>{const{hash:a,signer:s,ownerAddress:r,factoryAddress:i,salt:n,chainId:o,address:c,implementationType:d}=t;let p=a;if([e.AccountType.UPGRADEABLE_V5,e.AccountType.UPGRADEABLE_V6].includes(d)){const e={name:"Openfort",version:"0.5",chainId:Number(o),verifyingContract:c},t={OpenfortMessage:[{name:"hashedMessage",type:"bytes32"}]},a={hashedMessage:p},{_TypedDataEncoder:s}=await import("@ethersproject/hash");p=s.hash(e,t,a)}const g=await s.sign(p,!1,!1);if(i&&n&&[e.AccountType.UPGRADEABLE_V5,e.AccountType.UPGRADEABLE_V6].includes(d)){const{id:e}=await import("@ethersproject/hash"),{defaultAbiCoder:t}=await import("@ethersproject/abi"),{hexConcat:a}=await import("@ethersproject/bytes"),s=a([e("createAccountWithNonce(address,bytes32,bool)").slice(0,10),t.encode(["address","bytes32","bool"],[r,n,!1])]);return a([t.encode(["address","bytes","bytes"],[i,s,g]),"0x6492649264926492649264926492649264926492649264926492649264926492"])}return g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../core/configuration/account.cjs"),i=require("../core/configuration/authentication.cjs"),r=require("../core/errors/authErrorCodes.cjs"),t=require("../core/errors/openfortError.cjs"),n=require("../core/errors/sentry.cjs"),o=require("../storage/istorage.cjs"),s=require("../utils/crypto.cjs"),a=require("../utils/debug.cjs"),d=require("./messaging/ReactNativeMessenger.cjs"),c=require("./messaging/browserMessenger/connect.cjs");require("./messaging/browserMessenger/backwardCompatibility.cjs");var u=require("./types.cjs");class h extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class g extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class l extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class R extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class y extends t.SignerError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.NOT_CONFIGURED,"Signer is not configured")}}class p extends t.OpenfortError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.OTP_REQUIRED,"OTP verification required")}}exports.IframeManager=class{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;hasFailed=!1;constructor(e,i,r){if(!e)throw new t.ConfigurationError("Configuration is required for IframeManager");if(!i)throw new t.ConfigurationError("Storage is required for IframeManager");if(!r)throw new t.ConfigurationError("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=r}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){a.debugLog("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:a.debugLog}),this.connection=c({messenger:this.messenger,timeout:1e4,log:a.debugLog});try{this.remote=await this.connection.promise,a.debugLog("IframeManager connection established")}catch(e){const i=e;throw n.sentry.captureException(i),this.destroy(),a.debugLog("Failed to establish connection:",i),new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}\n \n In apps built with:\n - react native\n - swift\n - unity (non-webgl) \n \n You must configure your origin in the openfort dashboard before using the embedded wallet.\n\n For more information, see: https://www.openfort.io/docs/configuration/native-apps\n `)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(u.isErrorResponse(e)){if(e.error===u.NOT_CONFIGURED_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new y;if(e.error===u.MISSING_USER_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.MISSING_PROJECT_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new l;if(e.error===u.INCORRECT_USER_ENTROPY_ERROR)throw new R;if(e.error===u.MISSING_PASSKEY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.INCORRECT_PASSKEY_ERROR)throw new g;if(e.error===u.OTP_REQUIRED_ERROR)throw new p;throw this.storage.remove(o.StorageKeys.ACCOUNT),new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=e.chainId??null,r.password=e?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:e?.entropy?.encryptionSession},r.passkey=e?.entropy?.passkey??null;const t={uuid:s.randomUUID(),action:u.Event.CREATE,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},n=await i.create(t);return u.isErrorResponse(n)&&this.handleError(n),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",n.version??"undefined"),n}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await e.Account.fromStorage(this.storage),t=await this.ensureConnection(),n=await this.buildIFrameRequestConfiguration();n.chainId=r?.chainId??null,n.password=i?.entropy?.recoveryPassword??null,n.recovery={...n.recovery,encryptionSession:i?.entropy?.encryptionSession},n.passkey=i?.entropy?.passkey??null;const o={uuid:s.randomUUID(),action:u.Event.RECOVER,recovery:n.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:n.accessToken,playerID:n.playerID,thirdPartyProvider:n.thirdPartyProvider,thirdPartyTokenType:n.thirdPartyTokenType,encryptionKey:n.password,encryptionSession:n.recovery?.encryptionSession??null,passkey:n.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},a=await t.recover(o);return u.isErrorResponse(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,i,r,t){a.debugLog("[iframe] ensureConnection");const n=await this.ensureConnection(),o=new u.SignRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,t);a.debugLog("[iframe] done ensureConnection");const d=await n.sign(o);return a.debugLog("[iframe] response",d),u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined"),d.signature}async switchChain(e){const i=await this.ensureConnection(),r=new u.SwitchChainRequest(s.randomUUID(),e,await this.buildRequestConfiguration()),t=await i.switchChain(r);return u.isErrorResponse(t)&&this.handleError(t),t}async export(){const e=await this.ensureConnection(),i=new u.ExportPrivateKeyRequest(s.randomUUID(),await this.buildRequestConfiguration()),r=await e.export(i);return u.isErrorResponse(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r.key}async setRecoveryMethod(e,i,r,t,n){const o=await this.ensureConnection(),a=new u.SetRecoveryMethodRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,t,n),d=await o.setRecoveryMethod(a);u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),r=new u.GetCurrentDeviceRequest(s.randomUUID(),e);try{const e=await i.getCurrentDevice(r);return u.isErrorResponse(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof y)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void a.debugLog("IframeManager not loaded, skipping authentication update");const e=await i.Authentication.fromStorage(this.storage);if(!e)return void a.debugLog("No authentication found, skipping update");const r=new u.UpdateAuthenticationRequest(s.randomUUID(),e.token);a.debugLog("Updating authentication in iframe with token");const t=await this.remote.updateAuthentication(r);u.isErrorResponse(t)&&this.handleError(t)}async disconnect(){const e=await this.ensureConnection(),i={uuid:s.randomUUID()};await e.logout(i)}async onMessage(e){a.debugLog("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof d.ReactNativeMessenger?(this.isInitialized||this.connection?a.debugLog(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(a.debugLog("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{a.debugLog("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),a.debugLog("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):a.debugLog("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}},exports.MissingProjectEntropyError=l,exports.MissingRecoveryPasswordError=h,exports.NotConfiguredError=y,exports.OTPRequiredError=p,exports.WrongPasskeyError=g,exports.WrongRecoveryPasswordError=R;
|
|
1
|
+
"use strict";var e=require("../core/configuration/account.cjs"),i=require("../core/configuration/authentication.cjs"),r=require("../core/errors/authErrorCodes.cjs"),t=require("../core/errors/openfortError.cjs"),n=require("../core/errors/sentry.cjs"),o=require("../storage/istorage.cjs"),s=require("../utils/crypto.cjs"),a=require("../utils/debug.cjs"),d=require("./messaging/ReactNativeMessenger.cjs"),c=require("./messaging/browserMessenger/connect.cjs");require("./messaging/browserMessenger/backwardCompatibility.cjs");var u=require("./types.cjs");class h extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class g extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class l extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class R extends t.RecoveryError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class y extends t.SignerError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.NOT_CONFIGURED,"Signer is not configured")}}class p extends t.OpenfortError{constructor(){super(r.OPENFORT_AUTH_ERROR_CODES.OTP_REQUIRED,"OTP verification required")}}exports.IframeManager=class{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;hasFailed=!1;constructor(e,i,r){if(!e)throw new t.ConfigurationError("Configuration is required for IframeManager");if(!i)throw new t.ConfigurationError("Storage is required for IframeManager");if(!r)throw new t.ConfigurationError("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=r}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){a.debugLog("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:a.debugLog}),this.connection=c({messenger:this.messenger,timeout:1e4,log:a.debugLog});try{this.remote=await this.connection.promise,a.debugLog("IframeManager connection established")}catch(e){const i=e;throw n.sentry.captureException(i),this.destroy(),a.debugLog("Failed to establish connection:",i),new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}\n \n In apps built with:\n - react native\n - swift\n - unity (non-webgl) \n \n You must configure your origin in the openfort dashboard before using the embedded wallet.\n\n For more information, see: https://www.openfort.io/docs/configuration/native-apps\n `)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(u.isErrorResponse(e)){if(e.error===u.NOT_CONFIGURED_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new y;if(e.error===u.MISSING_USER_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.MISSING_PROJECT_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new l;if(e.error===u.INCORRECT_USER_ENTROPY_ERROR)throw new R;if(e.error===u.MISSING_PASSKEY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new h;if(e.error===u.INCORRECT_PASSKEY_ERROR)throw new g;if(e.error===u.OTP_REQUIRED_ERROR)throw new p;throw this.storage.remove(o.StorageKeys.ACCOUNT),new t.OpenfortError(r.OPENFORT_AUTH_ERROR_CODES.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.Authentication.fromStorage(this.storage);if(!e)throw new t.SessionError(r.OPENFORT_AUTH_ERROR_CODES.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:u.ShieldAuthType.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=e.chainId??null,r.password=e?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:e?.entropy?.encryptionSession},r.passkey=e?.entropy?.passkey??null;const t={uuid:s.randomUUID(),action:u.Event.CREATE,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},n=await i.create(t);return u.isErrorResponse(n)&&this.handleError(n),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",n.version??"undefined"),n}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await e.Account.fromStorage(this.storage),t=await this.ensureConnection(),n=await this.buildIFrameRequestConfiguration();n.chainId=r?.chainId??null,n.password=i?.entropy?.recoveryPassword??null,n.recovery={...n.recovery,encryptionSession:i?.entropy?.encryptionSession},n.passkey=i?.entropy?.passkey??null;const o={uuid:s.randomUUID(),action:u.Event.RECOVER,recovery:n.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:n.accessToken,playerID:n.playerID,thirdPartyProvider:n.thirdPartyProvider,thirdPartyTokenType:n.thirdPartyTokenType,encryptionKey:n.password,encryptionSession:n.recovery?.encryptionSession??null,passkey:n.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},a=await t.recover(o);return u.isErrorResponse(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,i,r,t){a.debugLog("[iframe] ensureConnection");const n=await this.ensureConnection(),o=new u.SignRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,t);a.debugLog("[iframe] done ensureConnection");const d=await n.sign(o);return a.debugLog("[iframe] response",d),u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined"),d.signature}async switchChain(e){const i=await this.ensureConnection(),r=new u.SwitchChainRequest(s.randomUUID(),e,await this.buildRequestConfiguration()),t=await i.switchChain(r);return u.isErrorResponse(t)&&this.handleError(t),t}async export(){const e=await this.ensureConnection(),i=new u.ExportPrivateKeyRequest(s.randomUUID(),await this.buildRequestConfiguration()),r=await e.export(i);return u.isErrorResponse(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r.key}async setRecoveryMethod(e,i,r,t,n){const o=await this.ensureConnection(),a=new u.SetRecoveryMethodRequest(s.randomUUID(),e,await this.buildRequestConfiguration(),i,r,t,n),d=await o.setRecoveryMethod(a);u.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),r=new u.GetCurrentDeviceRequest(s.randomUUID(),e);try{const e=await i.getCurrentDevice(r);return u.isErrorResponse(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof y)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void a.debugLog("IframeManager not loaded, skipping authentication update");const e=await i.Authentication.fromStorage(this.storage);if(!e)return void a.debugLog("No authentication found, skipping update");const r=new u.UpdateAuthenticationRequest(s.randomUUID(),e.token);a.debugLog("Updating authentication in iframe with token");const t=await this.remote.updateAuthentication(r);u.isErrorResponse(t)&&this.handleError(t)}async disconnect(){const e=await this.ensureConnection(),i={uuid:s.randomUUID()};await e.logout(i)}async onMessage(e){a.debugLog("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof d.ReactNativeMessenger?(this.isInitialized||this.connection?a.debugLog(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(a.debugLog("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{a.debugLog("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),a.debugLog("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):a.debugLog("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}},exports.MissingProjectEntropyError=l,exports.MissingRecoveryPasswordError=h,exports.NotConfiguredError=y,exports.OTPRequiredError=p,exports.WrongPasskeyError=g,exports.WrongRecoveryPasswordError=R;
|
package/dist/index.d.cts
CHANGED
|
@@ -12130,10 +12130,29 @@ interface RequestArguments {
|
|
|
12130
12130
|
method: string;
|
|
12131
12131
|
params?: any[];
|
|
12132
12132
|
}
|
|
12133
|
+
declare enum ProviderEvent {
|
|
12134
|
+
ACCOUNTS_CHANGED = "accountsChanged",
|
|
12135
|
+
CHAIN_CHANGED = "chainChanged",
|
|
12136
|
+
ACCOUNTS_CONNECT = "connect",
|
|
12137
|
+
DISCONNECT = "disconnect"
|
|
12138
|
+
}
|
|
12139
|
+
interface ProviderConnectInfo {
|
|
12140
|
+
chainId: string;
|
|
12141
|
+
}
|
|
12142
|
+
interface ProviderDisconnectError {
|
|
12143
|
+
code: number;
|
|
12144
|
+
message: string;
|
|
12145
|
+
}
|
|
12146
|
+
interface ProviderEventMap extends Record<string, any> {
|
|
12147
|
+
[ProviderEvent.ACCOUNTS_CHANGED]: [string[]];
|
|
12148
|
+
[ProviderEvent.CHAIN_CHANGED]: [string];
|
|
12149
|
+
[ProviderEvent.ACCOUNTS_CONNECT]: [ProviderConnectInfo];
|
|
12150
|
+
[ProviderEvent.DISCONNECT]: [ProviderDisconnectError];
|
|
12151
|
+
}
|
|
12133
12152
|
type Provider = {
|
|
12134
12153
|
request: (request: RequestArguments) => Promise<any>;
|
|
12135
|
-
on: (event:
|
|
12136
|
-
removeListener: (event:
|
|
12154
|
+
on: <E extends keyof ProviderEventMap>(event: E, listener: (...args: ProviderEventMap[E]) => void) => void;
|
|
12155
|
+
removeListener: <E extends keyof ProviderEventMap>(event: E, listener: (...args: ProviderEventMap[E]) => void) => void;
|
|
12137
12156
|
isOpenfort: boolean;
|
|
12138
12157
|
};
|
|
12139
12158
|
|
|
@@ -12185,6 +12204,11 @@ declare class EmbeddedWalletApi {
|
|
|
12185
12204
|
get(): Promise<EmbeddedAccount>;
|
|
12186
12205
|
list(requestParams?: ListAccountsParams): Promise<EmbeddedAccount[]>;
|
|
12187
12206
|
getEmbeddedState(): Promise<EmbeddedState>;
|
|
12207
|
+
watchEmbeddedState(params: {
|
|
12208
|
+
onChange: (state: EmbeddedState, prevState?: EmbeddedState) => void;
|
|
12209
|
+
onError?: (error: Error) => void;
|
|
12210
|
+
pollingInterval?: number;
|
|
12211
|
+
}): () => void;
|
|
12188
12212
|
getEthereumProvider(options?: {
|
|
12189
12213
|
policy?: string;
|
|
12190
12214
|
chains?: Record<number, string>;
|
|
@@ -12235,10 +12259,6 @@ declare class OpenfortConfiguration {
|
|
|
12235
12259
|
}
|
|
12236
12260
|
declare class ShieldConfiguration {
|
|
12237
12261
|
readonly shieldPublishableKey: string;
|
|
12238
|
-
/**
|
|
12239
|
-
* @deprecated This option is no longer used and will be removed in future versions.
|
|
12240
|
-
*/
|
|
12241
|
-
readonly shieldEncryptionKey?: string;
|
|
12242
12262
|
readonly debug?: boolean;
|
|
12243
12263
|
/**
|
|
12244
12264
|
* The relying party identifier for WebAuthn passkey operations.
|
|
@@ -12286,9 +12306,6 @@ declare class SDKConfiguration {
|
|
|
12286
12306
|
readonly iframeUrl: string;
|
|
12287
12307
|
readonly backendUrl: string;
|
|
12288
12308
|
readonly storage?: IStorage;
|
|
12289
|
-
readonly passkeyRpId?: string;
|
|
12290
|
-
readonly passkeyRpName?: string;
|
|
12291
|
-
readonly passkeyDisplayName?: string;
|
|
12292
12309
|
readonly nativeAppIdentifier?: string;
|
|
12293
12310
|
readonly debug?: boolean;
|
|
12294
12311
|
static instance: SDKConfiguration | null;
|
|
@@ -13147,17 +13164,12 @@ declare class PasskeySeedInvalidError extends OpenfortError {
|
|
|
13147
13164
|
constructor(message?: string);
|
|
13148
13165
|
}
|
|
13149
13166
|
|
|
13150
|
-
/**
|
|
13151
|
-
* Passkey types and interfaces.
|
|
13152
|
-
*/
|
|
13153
13167
|
/**
|
|
13154
13168
|
* Configuration for creating a new passkey.
|
|
13155
13169
|
*/
|
|
13156
13170
|
interface PasskeyCreateConfig {
|
|
13157
13171
|
/** Unique identifier for the passkey */
|
|
13158
13172
|
id: string;
|
|
13159
|
-
/** Human-readable display name shown in passkey dialogs */
|
|
13160
|
-
displayName: string;
|
|
13161
13173
|
/** Seed value used for PRF-based key derivation */
|
|
13162
13174
|
seed: string;
|
|
13163
13175
|
}
|
|
@@ -13201,24 +13213,24 @@ declare class PasskeyHandler implements IPasskeyHandler {
|
|
|
13201
13213
|
private readonly validByteLengths;
|
|
13202
13214
|
private readonly rpId?;
|
|
13203
13215
|
private readonly rpName?;
|
|
13216
|
+
private readonly displayName;
|
|
13204
13217
|
private readonly timeoutMs;
|
|
13205
13218
|
private readonly derivedKeyLengthBytes;
|
|
13206
13219
|
/**
|
|
13207
13220
|
* Creates a new passkey handler
|
|
13208
|
-
* The only fixed values from an issuer's point of view are rpId + rpName
|
|
13209
13221
|
* @param rpId The issuer's domain name
|
|
13210
13222
|
* @param rpName The issuer's display name
|
|
13223
|
+
* @param displayName Credential display name shown in passkey dialogs
|
|
13211
13224
|
* @param timeoutMs Timeout (in milliseconds) before a passkey dialog expires
|
|
13212
13225
|
* @param derivedKeyLengthBytes Byte length for target keys (16, 24, or 32)
|
|
13213
13226
|
*/
|
|
13214
|
-
constructor({ rpId, rpName, timeoutMs, derivedKeyLengthBytes }?: PasskeyHandlerConfig);
|
|
13227
|
+
constructor({ rpId, rpName, displayName, timeoutMs, derivedKeyLengthBytes }?: PasskeyHandlerConfig);
|
|
13215
13228
|
static randomPasskeyName(): string;
|
|
13216
13229
|
private getChallengeBytes;
|
|
13217
13230
|
private deriveKeyFromAssertion;
|
|
13218
13231
|
/**
|
|
13219
13232
|
* Prompts the user to create a passkey.
|
|
13220
13233
|
* @param id User identifier
|
|
13221
|
-
* @param displayName Display name (ideally it should hint about environment, chain id, etc)
|
|
13222
13234
|
* @param seed Seed phrase for PRF key derivation
|
|
13223
13235
|
* @returns PasskeyDetails with passkey details if passkey creation was successful
|
|
13224
13236
|
* @throws PasskeySeedInvalidError if seed is empty
|
|
@@ -13226,7 +13238,7 @@ declare class PasskeyHandler implements IPasskeyHandler {
|
|
|
13226
13238
|
* @throws PasskeyPRFNotSupportedError if PRF extension fails
|
|
13227
13239
|
* @throws PasskeyCreationFailedError for other failures
|
|
13228
13240
|
*/
|
|
13229
|
-
createPasskey({ id,
|
|
13241
|
+
createPasskey({ id, seed }: PasskeyCreateConfig): Promise<PasskeyDetails>;
|
|
13230
13242
|
/**
|
|
13231
13243
|
* Derive and export a key using local passkey
|
|
13232
13244
|
* @param id Internal ID of the passkey
|
|
@@ -13242,6 +13254,8 @@ declare class PasskeyHandler implements IPasskeyHandler {
|
|
|
13242
13254
|
interface PasskeyHandlerConfig {
|
|
13243
13255
|
rpId?: string;
|
|
13244
13256
|
rpName?: string;
|
|
13257
|
+
/** Credential display name shown in passkey dialogs */
|
|
13258
|
+
displayName?: string;
|
|
13245
13259
|
/** Timeout in milliseconds before passkey dialog expires (default: 60000) */
|
|
13246
13260
|
timeoutMs?: number;
|
|
13247
13261
|
/** Derived key length in bytes: 16, 24, or 32 (default: 32) */
|
package/dist/index.d.ts
CHANGED
|
@@ -12130,10 +12130,29 @@ interface RequestArguments {
|
|
|
12130
12130
|
method: string;
|
|
12131
12131
|
params?: any[];
|
|
12132
12132
|
}
|
|
12133
|
+
declare enum ProviderEvent {
|
|
12134
|
+
ACCOUNTS_CHANGED = "accountsChanged",
|
|
12135
|
+
CHAIN_CHANGED = "chainChanged",
|
|
12136
|
+
ACCOUNTS_CONNECT = "connect",
|
|
12137
|
+
DISCONNECT = "disconnect"
|
|
12138
|
+
}
|
|
12139
|
+
interface ProviderConnectInfo {
|
|
12140
|
+
chainId: string;
|
|
12141
|
+
}
|
|
12142
|
+
interface ProviderDisconnectError {
|
|
12143
|
+
code: number;
|
|
12144
|
+
message: string;
|
|
12145
|
+
}
|
|
12146
|
+
interface ProviderEventMap extends Record<string, any> {
|
|
12147
|
+
[ProviderEvent.ACCOUNTS_CHANGED]: [string[]];
|
|
12148
|
+
[ProviderEvent.CHAIN_CHANGED]: [string];
|
|
12149
|
+
[ProviderEvent.ACCOUNTS_CONNECT]: [ProviderConnectInfo];
|
|
12150
|
+
[ProviderEvent.DISCONNECT]: [ProviderDisconnectError];
|
|
12151
|
+
}
|
|
12133
12152
|
type Provider = {
|
|
12134
12153
|
request: (request: RequestArguments) => Promise<any>;
|
|
12135
|
-
on: (event:
|
|
12136
|
-
removeListener: (event:
|
|
12154
|
+
on: <E extends keyof ProviderEventMap>(event: E, listener: (...args: ProviderEventMap[E]) => void) => void;
|
|
12155
|
+
removeListener: <E extends keyof ProviderEventMap>(event: E, listener: (...args: ProviderEventMap[E]) => void) => void;
|
|
12137
12156
|
isOpenfort: boolean;
|
|
12138
12157
|
};
|
|
12139
12158
|
|
|
@@ -12185,6 +12204,11 @@ declare class EmbeddedWalletApi {
|
|
|
12185
12204
|
get(): Promise<EmbeddedAccount>;
|
|
12186
12205
|
list(requestParams?: ListAccountsParams): Promise<EmbeddedAccount[]>;
|
|
12187
12206
|
getEmbeddedState(): Promise<EmbeddedState>;
|
|
12207
|
+
watchEmbeddedState(params: {
|
|
12208
|
+
onChange: (state: EmbeddedState, prevState?: EmbeddedState) => void;
|
|
12209
|
+
onError?: (error: Error) => void;
|
|
12210
|
+
pollingInterval?: number;
|
|
12211
|
+
}): () => void;
|
|
12188
12212
|
getEthereumProvider(options?: {
|
|
12189
12213
|
policy?: string;
|
|
12190
12214
|
chains?: Record<number, string>;
|
|
@@ -12235,10 +12259,6 @@ declare class OpenfortConfiguration {
|
|
|
12235
12259
|
}
|
|
12236
12260
|
declare class ShieldConfiguration {
|
|
12237
12261
|
readonly shieldPublishableKey: string;
|
|
12238
|
-
/**
|
|
12239
|
-
* @deprecated This option is no longer used and will be removed in future versions.
|
|
12240
|
-
*/
|
|
12241
|
-
readonly shieldEncryptionKey?: string;
|
|
12242
12262
|
readonly debug?: boolean;
|
|
12243
12263
|
/**
|
|
12244
12264
|
* The relying party identifier for WebAuthn passkey operations.
|
|
@@ -12286,9 +12306,6 @@ declare class SDKConfiguration {
|
|
|
12286
12306
|
readonly iframeUrl: string;
|
|
12287
12307
|
readonly backendUrl: string;
|
|
12288
12308
|
readonly storage?: IStorage;
|
|
12289
|
-
readonly passkeyRpId?: string;
|
|
12290
|
-
readonly passkeyRpName?: string;
|
|
12291
|
-
readonly passkeyDisplayName?: string;
|
|
12292
12309
|
readonly nativeAppIdentifier?: string;
|
|
12293
12310
|
readonly debug?: boolean;
|
|
12294
12311
|
static instance: SDKConfiguration | null;
|
|
@@ -13147,17 +13164,12 @@ declare class PasskeySeedInvalidError extends OpenfortError {
|
|
|
13147
13164
|
constructor(message?: string);
|
|
13148
13165
|
}
|
|
13149
13166
|
|
|
13150
|
-
/**
|
|
13151
|
-
* Passkey types and interfaces.
|
|
13152
|
-
*/
|
|
13153
13167
|
/**
|
|
13154
13168
|
* Configuration for creating a new passkey.
|
|
13155
13169
|
*/
|
|
13156
13170
|
interface PasskeyCreateConfig {
|
|
13157
13171
|
/** Unique identifier for the passkey */
|
|
13158
13172
|
id: string;
|
|
13159
|
-
/** Human-readable display name shown in passkey dialogs */
|
|
13160
|
-
displayName: string;
|
|
13161
13173
|
/** Seed value used for PRF-based key derivation */
|
|
13162
13174
|
seed: string;
|
|
13163
13175
|
}
|
|
@@ -13201,24 +13213,24 @@ declare class PasskeyHandler implements IPasskeyHandler {
|
|
|
13201
13213
|
private readonly validByteLengths;
|
|
13202
13214
|
private readonly rpId?;
|
|
13203
13215
|
private readonly rpName?;
|
|
13216
|
+
private readonly displayName;
|
|
13204
13217
|
private readonly timeoutMs;
|
|
13205
13218
|
private readonly derivedKeyLengthBytes;
|
|
13206
13219
|
/**
|
|
13207
13220
|
* Creates a new passkey handler
|
|
13208
|
-
* The only fixed values from an issuer's point of view are rpId + rpName
|
|
13209
13221
|
* @param rpId The issuer's domain name
|
|
13210
13222
|
* @param rpName The issuer's display name
|
|
13223
|
+
* @param displayName Credential display name shown in passkey dialogs
|
|
13211
13224
|
* @param timeoutMs Timeout (in milliseconds) before a passkey dialog expires
|
|
13212
13225
|
* @param derivedKeyLengthBytes Byte length for target keys (16, 24, or 32)
|
|
13213
13226
|
*/
|
|
13214
|
-
constructor({ rpId, rpName, timeoutMs, derivedKeyLengthBytes }?: PasskeyHandlerConfig);
|
|
13227
|
+
constructor({ rpId, rpName, displayName, timeoutMs, derivedKeyLengthBytes }?: PasskeyHandlerConfig);
|
|
13215
13228
|
static randomPasskeyName(): string;
|
|
13216
13229
|
private getChallengeBytes;
|
|
13217
13230
|
private deriveKeyFromAssertion;
|
|
13218
13231
|
/**
|
|
13219
13232
|
* Prompts the user to create a passkey.
|
|
13220
13233
|
* @param id User identifier
|
|
13221
|
-
* @param displayName Display name (ideally it should hint about environment, chain id, etc)
|
|
13222
13234
|
* @param seed Seed phrase for PRF key derivation
|
|
13223
13235
|
* @returns PasskeyDetails with passkey details if passkey creation was successful
|
|
13224
13236
|
* @throws PasskeySeedInvalidError if seed is empty
|
|
@@ -13226,7 +13238,7 @@ declare class PasskeyHandler implements IPasskeyHandler {
|
|
|
13226
13238
|
* @throws PasskeyPRFNotSupportedError if PRF extension fails
|
|
13227
13239
|
* @throws PasskeyCreationFailedError for other failures
|
|
13228
13240
|
*/
|
|
13229
|
-
createPasskey({ id,
|
|
13241
|
+
createPasskey({ id, seed }: PasskeyCreateConfig): Promise<PasskeyDetails>;
|
|
13230
13242
|
/**
|
|
13231
13243
|
* Derive and export a key using local passkey
|
|
13232
13244
|
* @param id Internal ID of the passkey
|
|
@@ -13242,6 +13254,8 @@ declare class PasskeyHandler implements IPasskeyHandler {
|
|
|
13242
13254
|
interface PasskeyHandlerConfig {
|
|
13243
13255
|
rpId?: string;
|
|
13244
13256
|
rpName?: string;
|
|
13257
|
+
/** Credential display name shown in passkey dialogs */
|
|
13258
|
+
displayName?: string;
|
|
13245
13259
|
/** Timeout in milliseconds before passkey dialog expires (default: 60000) */
|
|
13246
13260
|
timeoutMs?: number;
|
|
13247
13261
|
/** Derived key length in bytes: 16, 24, or 32 (default: 32) */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{ConfigurationError as r,AuthenticationError as t,SessionError as s,SignerError as a}from"../core/errors/openfortError.js";import{PasskeyHandler as i}from"../core/passkey/handler.js";import{SDKConfiguration as n}from"../core/config/config.js";import{Account as o}from"../core/configuration/account.js";import{Authentication as d}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as c}from"../core/errors/authErrorCodes.js";import{withApiError as h}from"../core/errors/withApiError.js";import{OpenfortEvents as m,RecoveryMethod as y,ChainTypeEnum as g,AccountTypeEnum as l,EmbeddedState as p}from"../types/types.js";import{debugLog as f}from"../utils/debug.js";import{EmbeddedSigner as u}from"../wallets/embedded.js";import{EvmProvider as w}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as A,openfortProviderInfo as v}from"../wallets/evm/provider/eip6963.js";import{signMessage as M}from"../wallets/evm/walletHelpers.js";import{IframeManager as E}from"../wallets/iframeManager.js";import{ReactNativeMessenger as I}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import D from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class T{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,r,t,s,a){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t,this.eventEmitter=s,this.passkeyHandler=a,this.eventEmitter.on(m.ON_LOGOUT,()=>{f("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const t=n.getInstance();if(!t)throw new r("Configuration not found");return new e({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey,nativeAppIdentifier:t.nativeAppIdentifier})}async getIframeManager(){if(f("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(f("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return f("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return f("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;f("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return f("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,f("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw f("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){f("[HANDSHAKE DEBUG] createIframeManager starting");const e=n.getInstance();if(!e)throw f("[HANDSHAKE DEBUG] Configuration not found"),new r("Configuration not found");let t;if(f("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)f("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(f("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new I(this.messagePoster),f("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),t=this.messenger;else{f("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const r=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;t=new D({remoteWindow:r.contentWindow,allowedOrigins:[s]}),f("[HANDSHAKE DEBUG] Created WindowMessenger")}return f("[HANDSHAKE DEBUG] Creating IframeManager instance"),new E(e,this.storage,t)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(f("IframeManager has failed, clearing signer for recreation"),this.signer=null),this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();await e.initialize();return new u(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new r("Document is not available. Please provide a message poster for non-browser environments.");const t=document.getElementById("openfort-iframe");t&&t.remove();const s=document.createElement("iframe");return s.style.display="none",s.id="openfort-iframe",s.src=e,document.body.appendChild(s),s}async getPasskeyKey(e){const r=await d.fromStorage(this.storage);if(!r?.userId)throw new t("auth","User is required for passkey key derivation. Logout and login again.",401);return this.passkeyHandler.deriveAndExportKey({id:e,seed:r.userId})}async getEntropy(e){switch(e.recoveryMethod){case y.PASSWORD:return{recoveryPassword:e.password};case y.AUTOMATIC:return{encryptionSession:e.encryptionSession};case y.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new r("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:y.AUTOMATIC},[t,s]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),a={chainId:e.chainId,entropy:s,accountType:e.accountType??l.SMART_ACCOUNT,chainType:e.chainType??g.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},i=await t.configure(a);return{id:i.id,chainId:i.chainId,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,factoryAddress:i.factoryAddress,salt:i.salt,createdAt:i.createdAt,implementationAddress:i.implementationAddress,recoveryMethod:o.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:y.AUTOMATIC},a=await d.fromStorage(this.storage);if(!a)throw new s(c.NOT_LOGGED_IN,"missing authentication");if(t.recoveryMethod===y.PASSKEY){if(!a.userId)throw new r("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),displayName:n.getInstance()?.passkeyDisplayName??"Openfort - Embedded Wallet",seed:a.userId});if(!e.key)throw new r("Passkey creation failed: no key material returned");t.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[h,g]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),l=await h.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:g}),p={id:l.id,chainId:l.chainId,address:l.address,ownerAddress:l.ownerAddress,chainType:l.chainType,accountType:l.accountType,implementationType:l.implementationType,factoryAddress:l.factoryAddress,salt:l.salt,createdAt:l.createdAt,implementationAddress:l.implementationAddress,recoveryMethod:o.parseRecoveryMethod(l.recoveryMethod),recoveryMethodDetails:l.recoveryMethodDetails};return this.eventEmitter.emit(m.ON_EMBEDDED_WALLET_CREATED,p),p}async recover(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:y.AUTOMATIC};if(t.recoveryMethod===y.PASSKEY){if(!t.passkeyInfo?.passkeyId)throw new r("Passkey ID must be provided for passkey recovery");t.passkeyInfo={passkeyId:t.passkeyInfo.passkeyId}}const[s,a]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),i=await s.recover({account:e.account,entropy:a}),n={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:o.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(m.ON_EMBEDDED_WALLET_RECOVERED,n),n}async signMessage(e,r){await this.validateAndRefreshToken();const t=await this.ensureSigner(),{hashMessage:s=!0,arrayifyMessage:a=!1}=r||{},i=await o.fromStorage(this.storage);return await t.sign(e,a,s,i?.chainType)}async signTypedData(e,r,t){await this.validateAndRefreshToken();const s=await this.ensureSigner(),i=await o.fromStorage(this.storage);if(!i)throw new a(c.MISSING_SIGNER,"No account found");const n={...r};delete n.EIP712Domain;const{_TypedDataEncoder:d}=await import("@ethersproject/hash"),h=d.hash(e,n,t);return await M({hash:h,implementationType:i.implementationType||i.type,chainId:Number(i.chainId),signer:s,address:i.address,ownerAddress:i.ownerAddress,factoryAddress:i.factoryAddress,salt:i.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,t){await this.validateAndRefreshToken();const a=await this.ensureSigner(),h=await d.fromStorage(this.storage);if(!h)throw new s(c.NOT_LOGGED_IN,"missing authentication");let m,g,l,p;if(e.recoveryMethod===y.PASSKEY){const e=await o.fromStorage(this.storage);if(!e)throw new r("missing account");const t=e?.recoveryMethodDetails?.passkeyId;if(!t)throw new r("missing passkey id for account");if(!h.userId)throw new r("User ID is required for passkey key derivation");l={passkeyId:t,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:t,seed:h.userId})}}else if(t.recoveryMethod===y.PASSKEY){if(!h.userId)throw new r("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),displayName:n.getInstance()?.passkeyDisplayName??"Openfort - Embedded Wallet",seed:h.userId});if(!e.key)throw new r("Passkey creation failed: no key material returned");l={passkeyId:e.id,passkeyKey:e.key},p={passkeyId:e.id}}if(e.recoveryMethod===y.PASSWORD?m=e.password:t.recoveryMethod===y.PASSWORD&&(m=t.password),e.recoveryMethod===y.AUTOMATIC?g=e.encryptionSession:t.recoveryMethod===y.AUTOMATIC&&(g=t.encryptionSession),!m&&!g)throw new r("Password or encryption session is not provided");await a.setRecoveryMethod({recoveryMethod:t.recoveryMethod,recoveryPassword:m,encryptionSession:g,passkeyInfo:l});const f=await o.fromStorage(this.storage);f&&new o({...f,recoveryMethod:t.recoveryMethod,recoveryMethodDetails:p}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await o.fromStorage(this.storage);if(!e)throw new a(c.MISSING_SIGNER,"No signer configured");if(!await d.fromStorage(this.storage))throw new s(c.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:o.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const t={accountType:l.SMART_ACCOUNT,...e},a=n.getInstance();if(!a)throw new r("Configuration not found");const i=await d.fromStorage(this.storage);if(!i)throw new s(c.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),h(async()=>(await this.backendApiClients.accountsV2Api.getAccountsV2(t,{headers:i.thirdPartyProvider?{authorization:`Bearer ${a.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":a.baseConfiguration.publishableKey}})).data.data.map(e=>({chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:o.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await d.fromStorage(this.storage))return p.UNAUTHENTICATED;return await o.fromStorage(this.storage)?p.READY:p.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return f("Failed to get embedded state:",e),p.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const r={announceProvider:!0,...e},t=await d.fromStorage(this.storage),s=await o.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new w({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:r.chains}),r.announceProvider&&A({info:{...v,...r.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(r=>{setTimeout(r,e)});const r=await this.getIframeManager();if(!r.isLoaded())return!1;const t=await d.fromStorage(this.storage);if(t)try{return await r.getCurrentDevice(t.userId),!0}catch(e){return!1}return r.isLoaded()}catch(e){return f("Ping failed:",e),!1}}getURL(){const e=n.getInstance();if(!e)throw new r("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new r("Invalid message poster");this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleLogout(){if("undefined"==typeof document&&!this.messagePoster)return f("Skipping signer disconnect: no messagePoster available in non-browser environment"),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,void(this.signerPromise=null);try{const e=await this.ensureSigner();await e.disconnect()}catch{}this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void f("Invalid message received:",e);f("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const r="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(r&&this.messenger&&this.messagePoster)return f("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const t=await this.getIframeManager();f(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${t.isLoaded()}`),r&&!t.isLoaded()&&f("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),f("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await t.onMessage(e),f("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{T as EmbeddedWalletApi};
|
|
1
|
+
import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{ConfigurationError as t,AuthenticationError as r,SessionError as s,SignerError as a}from"../core/errors/openfortError.js";import{PasskeyHandler as i}from"../core/passkey/handler.js";import{SDKConfiguration as n}from"../core/config/config.js";import{Account as o}from"../core/configuration/account.js";import{Authentication as d}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as c}from"../core/errors/authErrorCodes.js";import{withApiError as h}from"../core/errors/withApiError.js";import{OpenfortEvents as m,RecoveryMethod as g,ChainTypeEnum as y,AccountTypeEnum as l,EmbeddedState as p}from"../types/types.js";import{debugLog as f}from"../utils/debug.js";import{observe as u}from"../utils/observe.js";import{EmbeddedSigner as w}from"../wallets/embedded.js";import{EvmProvider as A}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as E,openfortProviderInfo as v}from"../wallets/evm/provider/eip6963.js";import{signMessage as M}from"../wallets/evm/walletHelpers.js";import{IframeManager as D}from"../wallets/iframeManager.js";import{ReactNativeMessenger as I}from"../wallets/messaging/ReactNativeMessenger.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import T from"../wallets/messaging/browserMessenger/messengers/WindowMessenger.js";class S{storage;validateAndRefreshToken;ensureInitialized;eventEmitter;passkeyHandler;iframeManager=null;iframeManagerPromise=null;signer=null;signerPromise=null;provider=null;messagePoster=null;messenger=null;constructor(e,t,r,s,a){this.storage=e,this.validateAndRefreshToken=t,this.ensureInitialized=r,this.eventEmitter=s,this.passkeyHandler=a,this.eventEmitter.on(m.ON_LOGOUT,()=>{f("Handling logout event in EmbeddedWalletApi"),this.handleLogout()})}get backendApiClients(){const r=n.getInstance();if(!r)throw new t("Configuration not found");return new e({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey,nativeAppIdentifier:r.nativeAppIdentifier})}async getIframeManager(){if(f("[HANDSHAKE DEBUG] getIframeManager called"),this.iframeManager?.hasFailed&&(f("[HANDSHAKE DEBUG] Existing iframeManager has failed, clearing for recreation"),this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null),this.iframeManager)return f("[HANDSHAKE DEBUG] Returning existing iframeManager instance"),this.iframeManager;if(this.iframeManagerPromise)return f("[HANDSHAKE DEBUG] Returning existing iframeManagerPromise"),this.iframeManagerPromise;f("[HANDSHAKE DEBUG] Creating new iframeManager"),this.iframeManagerPromise=this.createIframeManager();try{return f("[HANDSHAKE DEBUG] Awaiting iframeManager creation"),this.iframeManager=await this.iframeManagerPromise,f("[HANDSHAKE DEBUG] IframeManager created successfully"),this.iframeManagerPromise=null,this.iframeManager}catch(e){throw f("[HANDSHAKE DEBUG] Error creating iframeManager:",e),this.iframeManagerPromise=null,this.messenger&&(this.messenger.destroy(),this.messenger=null),this.iframeManager=null,e}}async createIframeManager(){f("[HANDSHAKE DEBUG] createIframeManager starting");const e=n.getInstance();if(!e)throw f("[HANDSHAKE DEBUG] Configuration not found"),new t("Configuration not found");let r;if(f("[HANDSHAKE DEBUG] Configuration found"),this.messagePoster)f("[HANDSHAKE DEBUG] Creating ReactNativeMessenger with messagePoster"),this.messenger&&(f("[HANDSHAKE DEBUG] Destroying old messenger before creating new one"),this.messenger.destroy()),this.messenger=new I(this.messagePoster),f("[HANDSHAKE DEBUG] Created new ReactNativeMessenger instance"),r=this.messenger;else{f("[HANDSHAKE DEBUG] Creating WindowMessenger for browser mode");const t=this.createIframe(e.iframeUrl),s=new URL(e.iframeUrl).origin;r=new T({remoteWindow:t.contentWindow,allowedOrigins:[s]}),f("[HANDSHAKE DEBUG] Created WindowMessenger")}return f("[HANDSHAKE DEBUG] Creating IframeManager instance"),new D(e,this.storage,r)}async ensureSigner(){if(this.iframeManager?.hasFailed&&(f("IframeManager has failed, clearing signer for recreation"),this.signer=null),this.signer)return this.signer;if(this.signerPromise)return this.signerPromise;this.signerPromise=this.createSigner();try{return this.signer=await this.signerPromise,this.signer}catch(e){throw this.signerPromise=null,e}finally{this.signerPromise=null}}async createSigner(){const e=await this.getIframeManager();await e.initialize();return new w(e,this.storage,this.backendApiClients,this.passkeyHandler,this.eventEmitter)}createIframe(e){if("undefined"==typeof document)throw new t("Document is not available. Please provide a message poster for non-browser environments.");const r=document.getElementById("openfort-iframe");r&&r.remove();const s=document.createElement("iframe");return s.style.display="none",s.id="openfort-iframe",s.src=e,document.body.appendChild(s),s}async getPasskeyKey(e){const t=await d.fromStorage(this.storage);if(!t?.userId)throw new r("auth","User is required for passkey key derivation. Logout and login again.",401);return this.passkeyHandler.deriveAndExportKey({id:e,seed:t.userId})}async getEntropy(e){switch(e.recoveryMethod){case g.PASSWORD:return{recoveryPassword:e.password};case g.AUTOMATIC:return{encryptionSession:e.encryptionSession};case g.PASSKEY:return{passkey:e.passkeyInfo?{id:e.passkeyInfo.passkeyId,key:e.passkeyInfo.passkeyKey||await this.getPasskeyKey(e.passkeyInfo.passkeyId)}:{}};default:throw new t("Invalid recovery method")}}async configure(e){await this.validateAndRefreshToken();const t=e.recoveryParams??{recoveryMethod:g.AUTOMATIC},[r,s]=await Promise.all([this.ensureSigner(),this.getEntropy(t)]),a={chainId:e.chainId,entropy:s,accountType:e.accountType??l.SMART_ACCOUNT,chainType:e.chainType??y.EVM,getPasskeyKeyFn:async e=>this.getPasskeyKey(e)},i=await r.configure(a);return{id:i.id,chainId:i.chainId,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,factoryAddress:i.factoryAddress,salt:i.salt,createdAt:i.createdAt,implementationAddress:i.implementationAddress,recoveryMethod:o.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails}}async create(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:g.AUTOMATIC},a=await d.fromStorage(this.storage);if(!a)throw new s(c.NOT_LOGGED_IN,"missing authentication");if(r.recoveryMethod===g.PASSKEY){if(!a.userId)throw new t("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:a.userId});if(!e.key)throw new t("Passkey creation failed: no key material returned");r.passkeyInfo={passkeyId:e.id,passkeyKey:e.key}}const[n,h]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),y=await n.create({accountType:e.accountType,chainType:e.chainType,chainId:e.chainId,entropy:h}),l={id:y.id,chainId:y.chainId,address:y.address,ownerAddress:y.ownerAddress,chainType:y.chainType,accountType:y.accountType,implementationType:y.implementationType,factoryAddress:y.factoryAddress,salt:y.salt,createdAt:y.createdAt,implementationAddress:y.implementationAddress,recoveryMethod:o.parseRecoveryMethod(y.recoveryMethod),recoveryMethodDetails:y.recoveryMethodDetails};return this.eventEmitter.emit(m.ON_EMBEDDED_WALLET_CREATED,l),l}async recover(e){await this.validateAndRefreshToken();const r=e.recoveryParams??{recoveryMethod:g.AUTOMATIC};if(r.recoveryMethod===g.PASSKEY){if(!r.passkeyInfo?.passkeyId)throw new t("Passkey ID must be provided for passkey recovery");r.passkeyInfo={passkeyId:r.passkeyInfo.passkeyId}}const[s,a]=await Promise.all([this.ensureSigner(),this.getEntropy(r)]),i=await s.recover({account:e.account,entropy:a}),n={id:i.id,chainId:i.chainId,implementationAddress:i.implementationAddress,factoryAddress:i.factoryAddress,salt:i.salt,address:i.address,ownerAddress:i.ownerAddress,chainType:i.chainType,accountType:i.accountType,implementationType:i.implementationType,createdAt:i.createdAt,recoveryMethod:o.parseRecoveryMethod(i.recoveryMethod),recoveryMethodDetails:i.recoveryMethodDetails};return this.eventEmitter.emit(m.ON_EMBEDDED_WALLET_RECOVERED,n),n}async signMessage(e,t){await this.validateAndRefreshToken();const r=await this.ensureSigner(),{hashMessage:s=!0,arrayifyMessage:a=!1}=t||{},i=await o.fromStorage(this.storage);return await r.sign(e,a,s,i?.chainType)}async signTypedData(e,t,r){await this.validateAndRefreshToken();const s=await this.ensureSigner(),i=await o.fromStorage(this.storage);if(!i)throw new a(c.MISSING_SIGNER,"No account found");const n={...t};delete n.EIP712Domain;const{_TypedDataEncoder:d}=await import("@ethersproject/hash"),h=d.hash(e,n,r);return await M({hash:h,implementationType:i.implementationType||i.type,chainId:Number(i.chainId),signer:s,address:i.address,ownerAddress:i.ownerAddress,factoryAddress:i.factoryAddress,salt:i.salt})}async exportPrivateKey(){await this.validateAndRefreshToken();const e=await this.ensureSigner();return await e.export()}async setRecoveryMethod(e,r){await this.validateAndRefreshToken();const a=await this.ensureSigner(),n=await d.fromStorage(this.storage);if(!n)throw new s(c.NOT_LOGGED_IN,"missing authentication");let h,m,y,l;if(e.recoveryMethod===g.PASSKEY){const e=await o.fromStorage(this.storage);if(!e)throw new t("missing account");const r=e?.recoveryMethodDetails?.passkeyId;if(!r)throw new t("missing passkey id for account");if(!n.userId)throw new t("User ID is required for passkey key derivation");y={passkeyId:r,passkeyKey:await this.passkeyHandler.deriveAndExportKey({id:r,seed:n.userId})}}else if(r.recoveryMethod===g.PASSKEY){if(!n.userId)throw new t("User ID is required for passkey creation");const e=await this.passkeyHandler.createPasskey({id:i.randomPasskeyName(),seed:n.userId});if(!e.key)throw new t("Passkey creation failed: no key material returned");y={passkeyId:e.id,passkeyKey:e.key},l={passkeyId:e.id}}if(e.recoveryMethod===g.PASSWORD?h=e.password:r.recoveryMethod===g.PASSWORD&&(h=r.password),e.recoveryMethod===g.AUTOMATIC?m=e.encryptionSession:r.recoveryMethod===g.AUTOMATIC&&(m=r.encryptionSession),!h&&!m)throw new t("Password or encryption session is not provided");await a.setRecoveryMethod({recoveryMethod:r.recoveryMethod,recoveryPassword:h,encryptionSession:m,passkeyInfo:y});const p=await o.fromStorage(this.storage);p&&new o({...p,recoveryMethod:r.recoveryMethod,recoveryMethodDetails:l}).save(this.storage)}async get(){await this.validateAndRefreshToken();const e=await o.fromStorage(this.storage);if(!e)throw new a(c.MISSING_SIGNER,"No signer configured");if(!await d.fromStorage(this.storage))throw new s(c.NOT_LOGGED_IN,"No access token found");return{id:e.id,chainId:e.chainId,address:e.address,ownerAddress:e.ownerAddress,factoryAddress:e.factoryAddress,salt:e.salt,chainType:e.chainType,accountType:e.accountType,implementationAddress:e.implementationAddress,implementationType:e.implementationType,createdAt:e.createdAt,recoveryMethod:o.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails}}async list(e){await this.validateAndRefreshToken();const r={...e},a=n.getInstance();if(!a)throw new t("Configuration not found");const i=await d.fromStorage(this.storage);if(!i)throw new s(c.NOT_LOGGED_IN,"No access token found");return await this.validateAndRefreshToken(),h(async()=>(await this.backendApiClients.accountsV2Api.getAccountsV2(r,{headers:i.thirdPartyProvider?{authorization:`Bearer ${a.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":a.baseConfiguration.publishableKey}})).data.data.map(e=>({chainType:e.chainType,id:e.id,address:e.address,active:e.smartAccount?.active,ownerAddress:e.ownerAddress,factoryAddress:e.smartAccount?.factoryAddress,salt:e.smartAccount?.salt,accountType:e.accountType,implementationAddress:e.smartAccount?.implementationAddress,createdAt:e.createdAt,implementationType:e.smartAccount?.implementationType,chainId:e.chainId,recoveryMethod:o.parseRecoveryMethod(e.recoveryMethod),recoveryMethodDetails:e.recoveryMethodDetails})),{context:"list"})}async getEmbeddedState(){try{if(!await d.fromStorage(this.storage))return p.UNAUTHENTICATED;return await o.fromStorage(this.storage)?p.READY:p.EMBEDDED_SIGNER_NOT_CONFIGURED}catch(e){return f("Failed to get embedded state:",e),p.UNAUTHENTICATED}}watchEmbeddedState(e){return u("watchEmbeddedState",{onChange:e.onChange,onError:e.onError},t=>{let r;const s=async()=>{try{const e=await this.getEmbeddedState();r!==e&&(t.onChange?.(e,r),r=e)}catch(e){t.onError?.(e instanceof Error?e:new Error(String(e)))}};s();const a=()=>s(),i=()=>s(),n=()=>s(),o=()=>s();this.eventEmitter.on(m.ON_AUTH_SUCCESS,a),this.eventEmitter.on(m.ON_LOGOUT,i),this.eventEmitter.on(m.ON_EMBEDDED_WALLET_CREATED,n),this.eventEmitter.on(m.ON_EMBEDDED_WALLET_RECOVERED,o);const d=setInterval(s,e.pollingInterval??2e3);return()=>{clearInterval(d),this.eventEmitter.off(m.ON_AUTH_SUCCESS,a),this.eventEmitter.off(m.ON_LOGOUT,i),this.eventEmitter.off(m.ON_EMBEDDED_WALLET_CREATED,n),this.eventEmitter.off(m.ON_EMBEDDED_WALLET_RECOVERED,o)}})}async getEthereumProvider(e){await this.ensureInitialized();const t={announceProvider:!0,...e},r=await d.fromStorage(this.storage),s=await o.fromStorage(this.storage);return this.provider?this.provider&&t.policy&&this.provider.updatePolicy(t.policy):(this.provider=new A({storage:this.storage,openfortEventEmitter:this.eventEmitter,ensureSigner:this.ensureSigner.bind(this),account:s||void 0,authentication:r||void 0,backendApiClients:this.backendApiClients,policyId:t.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:t.chains}),t.announceProvider&&E({info:{...v,...t.providerInfo},provider:this.provider})),this.provider}async ping(e){try{e>0&&await new Promise(t=>{setTimeout(t,e)});const t=await this.getIframeManager();if(!t.isLoaded())return!1;const r=await d.fromStorage(this.storage);if(r)try{return await t.getCurrentDevice(r.userId),!0}catch(e){return!1}return t.isLoaded()}catch(e){return f("Ping failed:",e),!1}}getURL(){const e=n.getInstance();if(!e)throw new t("Configuration not found");return e.iframeUrl}async setMessagePoster(e){if(!e||"function"!=typeof e.postMessage)throw new t("Invalid message poster");this.messagePoster=e,this.messenger&&this.messenger.destroy(),this.iframeManager&&this.iframeManager.destroy(),this.signer=null,this.signerPromise=null,this.iframeManager=null,this.iframeManagerPromise=null,this.messenger=null}async handleLogout(){if("undefined"==typeof document&&!this.messagePoster)return f("Skipping signer disconnect: no messagePoster available in non-browser environment"),this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,void(this.signerPromise=null);try{const e=await this.ensureSigner();await e.disconnect()}catch{}this.provider=null,this.messenger=null,this.iframeManager=null,this.iframeManagerPromise=null,this.signer=null,this.signerPromise=null}async onMessage(e){if(!e||"object"!=typeof e)return void f("Invalid message received:",e);f("[HANDSHAKE DEBUG] EmbeddedWalletApi onMessage:",e);const t="penpal"===e.namespace&&"SYN"===e.type||e.penpal&&"string"==typeof e.penpal;if(t&&this.messenger&&this.messagePoster)return f("[HANDSHAKE DEBUG] Passing message directly to existing ReactNativeMessenger"),void this.messenger.handleMessage(e);const r=await this.getIframeManager();f(`[HANDSHAKE DEBUG] IframeManager obtained, isLoaded: ${r.isLoaded()}`),t&&!r.isLoaded()&&f("[HANDSHAKE DEBUG] Received penpal message before connection initialized, setting up connection..."),f("[HANDSHAKE DEBUG] Calling iframeManager.onMessage"),await r.onMessage(e),f("[HANDSHAKE DEBUG] iframeManager.onMessage completed")}isReady(){return this.iframeManager?.isLoaded()||!1}}export{S as EmbeddedWalletApi};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{setCryptoDigestOverride as e}from"../../utils/crypto.js";class
|
|
1
|
+
import{setCryptoDigestOverride as e}from"../../utils/crypto.js";class i{publishableKey;nativeAppIdentifier;constructor(e){this.publishableKey=e.publishableKey,this.nativeAppIdentifier=e.nativeAppIdentifier}}class s{shieldPublishableKey;debug=!1;passkeyRpId;passkeyRpName;passkeyDisplayName;constructor(e){this.shieldPublishableKey=e.shieldPublishableKey,this.debug=e.shieldDebug||!1,this.passkeyRpId=e.passkeyRpId,this.passkeyRpName=e.passkeyRpName,this.passkeyDisplayName=e.passkeyDisplayName}}class t{baseConfiguration;shieldConfiguration;thirdPartyAuth;shieldUrl;iframeUrl;backendUrl;storage;nativeAppIdentifier;debug;static instance=null;constructor({baseConfiguration:i,shieldConfiguration:s,overrides:a,thirdPartyAuth:r,debug:h}){this.shieldConfiguration=s,this.baseConfiguration=i,this.backendUrl=a?.backendUrl||"https://api.openfort.io",this.iframeUrl=a?.iframeUrl||"https://embed.openfort.io",this.iframeUrl=`${this.iframeUrl}/iframe/${this.baseConfiguration.publishableKey}`,this.debug=h,s?.debug&&(this.iframeUrl=`${this.iframeUrl}?debug=true`),this.shieldUrl=a?.shieldUrl||"https://shield.openfort.io",this.storage=a?.storage,this.thirdPartyAuth=r,this.nativeAppIdentifier=i.nativeAppIdentifier,a?.crypto?.digest&&e(a.crypto.digest),t.instance=this}static getInstance(){return t.instance}}export{i as OpenfortConfiguration,t as SDKConfiguration,s as ShieldConfiguration};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BackendApiClients as
|
|
1
|
+
import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{AuthApi as t}from"../api/auth.js";import{EmbeddedWalletApi as i}from"../api/embeddedWallet.js";import{ProxyApi as n}from"../api/proxy.js";import{UserApi as a}from"../api/user.js";import{AuthManager as s}from"../auth/authManager.js";import{StorageKeys as r}from"../storage/istorage.js";import{LazyStorage as o}from"../storage/lazyStorage.js";import h from"../utils/typedEventEmitter.js";import{SDKConfiguration as l}from"./config/config.js";import{OPENFORT_AUTH_ERROR_CODES as d,OPENFORT_ERROR_CODES as c}from"./errors/authErrorCodes.js";import{ConfigurationError as u,SignerError as g,RequestError as m,OpenfortError as f}from"./errors/openfortError.js";import{InternalSentry as p}from"./errors/sentry.js";import{OpenfortInternal as I}from"./openfortInternal.js";import{PasskeyHandler as w}from"./passkey/handler.js";class y{storage;iAuthManager=null;openfortInternal;initPromise;asyncInitPromise=null;authInstance;embeddedWalletInstance;userInstance;proxyInstance;configuration;eventEmitter;iPasskeyHandler;static globalEventEmitter=null;get auth(){if(!this.authInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.");return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.");return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.");return this.userInstance}get proxy(){if(!this.proxyInstance)throw new u("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.");return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new s,this.openfortInternal=new I(this.storage,this.authManager,this.eventEmitter),this.authInstance=new t(this.storage,this.authManager,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter),this.embeddedWalletInstance=new i(this.storage,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter,this.passkeyHandler),this.userInstance=new a(this.storage,this.authManager,this.validateAndRefreshToken.bind(this)),this.proxyInstance=new n(this.storage,this.backendApiClients,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),async()=>{if(!this.embeddedWalletInstance)throw new g(d.MISSING_SIGNER,"Embedded wallet not initialized");const e=this.embeddedWalletInstance;return t=>e.signMessage(t,{hashMessage:!0,arrayifyMessage:!0})})}catch(e){throw new u("Openfort SDK synchronous initialization failed")}}constructor(e){if(this.configuration=new l(e),this.storage=new o(this.configuration.baseConfiguration.publishableKey,this.configuration.storage),this.eventEmitter=new h,y.globalEventEmitter){["onAuthInit","onAuthSuccess","onAuthFailure","onLogout","onSwitchAccount","onSignedMessage","onEmbeddedWalletCreated","onEmbeddedWalletRecovered","onAuthFlowOpen","onAuthFlowClose","onAuthFlowCancel"].forEach(e=>{this.eventEmitter.on(e,(...t)=>{y.globalEventEmitter?.emit(e,...t)})})}else y.globalEventEmitter=this.eventEmitter;this.iPasskeyHandler=e.overrides?.passkeyHandler??new w({rpId:e.shieldConfiguration?.passkeyRpId,rpName:e.shieldConfiguration?.passkeyRpName,displayName:e.shieldConfiguration?.passkeyDisplayName}),p.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}static getEventEmitter(){return y.globalEventEmitter||(y.globalEventEmitter=new h),y.globalEventEmitter}async waitForInitialization(){await this.initPromise,await this.ensureAsyncInitialized()}async getAccessToken(){return await this.ensureInitialized(),this.openfortInternal.getAccessToken()}async validateAndRefreshToken(e){return await this.ensureInitialized(),await this.openfortInternal.validateAndRefreshToken(e)}get backendApiClients(){return new e({basePath:this.configuration.backendUrl,accessToken:this.configuration.baseConfiguration.publishableKey,nativeAppIdentifier:this.configuration.nativeAppIdentifier,storage:this.storage,onLogout:()=>{this.eventEmitter.emit("onLogout")}})}get authManager(){if(!this.iAuthManager)throw new m("AuthManager not initialized");return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(e){try{const t=r.TEST,i="openfort_storage_test";e.save(t,i);const n=await e.get(t);return e.remove(t),n===i}catch(e){return!1}}async initializeAsync(){if(!await y.isStorageAccessible(this.storage))throw new f("Storage is not accessible",c.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}export{y as Openfort};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{humanId as e}from"human-id";import{PasskeyPRFNotSupportedError as t,PasskeySeedInvalidError as r,PasskeyUserCancelledError as i,PasskeyCreationFailedError as
|
|
1
|
+
import{humanId as e}from"human-id";import{PasskeyPRFNotSupportedError as t,PasskeySeedInvalidError as r,PasskeyUserCancelledError as i,PasskeyCreationFailedError as s,PasskeyAssertionFailedError as n}from"./errors.js";import{DEFAULT_PASSKEY_DISPLAY_NAME as a}from"./types.js";import{arrayBufferToBase64URL as o,base64ToArrayBuffer as d}from"./utils.js";class l{validByteLengths=[16,24,32];rpId;rpName;displayName;timeoutMs;derivedKeyLengthBytes;constructor({rpId:e,rpName:t,displayName:r,timeoutMs:i,derivedKeyLengthBytes:s}={}){if(this.rpId=e,this.rpName=t,this.displayName=r??a,this.timeoutMs=i??6e4,this.derivedKeyLengthBytes=s??32,!this.validByteLengths.includes(this.derivedKeyLengthBytes))throw new Error(`Invalid key byte length ${this.derivedKeyLengthBytes}`)}static randomPasskeyName(){return e({capitalize:!0,separator:" "})}getChallengeBytes(){return crypto.getRandomValues(new Uint8Array(32))}async deriveKeyFromAssertion(e){const r=e.getClientExtensionResults();if(!r)throw new t("Passkey fetch failed: no client extension results");const i=r.prf;if(!i||!i.results)throw new t("PRF extension not supported or missing results");const s=i.results.first,n=await crypto.subtle.importKey("raw",s,{name:"AES-CBC",length:this.derivedKeyLengthBytes},!0,["encrypt","decrypt"]);return crypto.subtle.exportKey("raw",n)}async createPasskey({id:e,seed:n}){if(!n||0===n.trim().length)throw new r;const a={challenge:this.getChallengeBytes(),rp:{id:this.rpId,name:this.rpName},user:{id:(new TextEncoder).encode(e),name:e,displayName:this.displayName},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{residentKey:"required",userVerification:"required"},extensions:{prf:{eval:{first:(new TextEncoder).encode(n)}}},timeout:this.timeoutMs,attestation:"direct"};let d,l;try{d=await navigator.credentials.create({publicKey:a})}catch(e){if(e instanceof Error&&"NotAllowedError"===e.name)throw new i;throw new s(e instanceof Error?e.message:"Unknown error",e instanceof Error?e:void 0)}if(!d)throw new i;try{l=await this.deriveKeyFromAssertion(d)}catch(e){throw e instanceof t&&console.warn(`[Openfort] Passkey created but PRF extension failed. A passkey credential may exist on the device that cannot be used for wallet recovery. Credential ID: ${o(d.rawId)}`),e}return{id:o(d.rawId),displayName:this.displayName,key:o(l)}}async deriveAndExportKey({id:e,seed:t}){if(!t||0===t.trim().length)throw new r;let s;try{s=await navigator.credentials.get({publicKey:{challenge:this.getChallengeBytes(),rpId:this.rpId,allowCredentials:[{id:d(e),type:"public-key"}],userVerification:"required",extensions:{prf:{eval:{first:(new TextEncoder).encode(t)}}}}})}catch(e){if(e instanceof Error&&"NotAllowedError"===e.name)throw new i;throw new n(e instanceof Error?e.message:"Unknown error",e instanceof Error?e:void 0)}if(!s)throw new i;const a=await this.deriveKeyFromAssertion(s);return o(a)}}export{l as PasskeyHandler};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e="Openfort - Embedded Wallet";export{e as DEFAULT_PASSKEY_DISPLAY_NAME};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var E,A,e,
|
|
1
|
+
var E,A,e,T,t,n,o,O,_,C,N,c,a;!function(E){E[E.NONE=0]="NONE",E[E.UNAUTHENTICATED=1]="UNAUTHENTICATED",E[E.EMBEDDED_SIGNER_NOT_CONFIGURED=2]="EMBEDDED_SIGNER_NOT_CONFIGURED",E[E.CREATING_ACCOUNT=3]="CREATING_ACCOUNT",E[E.READY=4]="READY"}(E||(E={})),function(E){E.ON_AUTH_INIT="onAuthInit",E.ON_AUTH_SUCCESS="onAuthSuccess",E.ON_OTP_REQUEST="onOtpRequest",E.ON_OTP_FAILURE="onOtpFailure",E.ON_AUTH_FAILURE="onAuthFailure",E.ON_LOGOUT="onLogout",E.ON_SWITCH_ACCOUNT="onSwitchAccount",E.ON_SIGNED_MESSAGE="onSignedMessage",E.ON_EMBEDDED_WALLET_CREATED="onEmbeddedWalletCreated",E.ON_EMBEDDED_WALLET_RECOVERED="onEmbeddedWalletRecovered"}(A||(A={})),function(E){E.PASSWORD="password",E.AUTOMATIC="automatic",E.PASSKEY="passkey"}(e||(e={})),function(E){E.UPGRADEABLE_V5="UpgradeableV5",E.UPGRADEABLE_V6="UpgradeableV6",E.SIMPLE="Simple",E.CALIBUR="Calibur",E.CALIBUR_V9="CaliburV9"}(T||(T={})),function(E){E.OPENFORT="openfort",E.THIRD_PARTY="thirdParty"}(t||(t={})),function(E){E.ID_TOKEN="idToken",E.CUSTOM_TOKEN="customToken"}(n||(n={})),function(E){E.ACCELBYTE="accelbyte",E.FIREBASE="firebase",E.BETTER_AUTH="better-auth",E.LOOTLOCKER="lootlocker",E.PLAYFAB="playfab",E.SUPABASE="supabase",E.CUSTOM="custom",E.OIDC="oidc"}(o||(o={})),function(E){E.EMAIL="email",E.WALLET="wallet"}(O||(O={})),function(E){E.GOOGLE="google",E.TWITTER="twitter",E.APPLE="apple",E.FACEBOOK="facebook",E.DISCORD="discord",E.EPIC_GAMES="epic_games",E.LINE="line"}(_||(_={})),function(E){E.ACTION_VERIFY_EMAIL="verify_email"}(C||(C={})),function(E){E.EOA="Externally Owned Account",E.SMART_ACCOUNT="Smart Account",E.DELEGATED_ACCOUNT="Delegated Account"}(N||(N={})),function(E){E.EVM="EVM",E.SVM="SVM"}(c||(c={})),function(E){E.ASC="asc",E.DESC="desc"}(a||(a={}));export{T as AccountType,N as AccountTypeEnum,C as AuthActionRequiredActions,t as AuthType,O as BasicAuthProvider,c as ChainTypeEnum,E as EmbeddedState,_ as OAuthProvider,A as OpenfortEvents,e as RecoveryMethod,o as ThirdPartyAuthProvider,n as TokenType};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=new Map,n=new Map;let o=0;function e(e,s,c){const f=++o,i=()=>t.get(e)||[],r=()=>{const o=i();if(!o.some(t=>t.id===f))return;const s=n.get(e);if(1===o.length&&s){const t=s();t instanceof Promise&&t.catch(()=>{})}(()=>{const n=i();t.set(e,n.filter(t=>t.id!==f))})()},g=i();if(t.set(e,[...g,{id:f,fns:s}]),g&&g.length>0)return r;const l={};for(const t in s)l[t]=(...n)=>{const o=i();if(0!==o.length)for(const e of o)e.fns[t]?.(...n)};const u=c(l);return"function"==typeof u&&n.set(e,u),r}export{e as observe};
|
package/dist/sdk/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="1.1
|
|
1
|
+
const o="1.2.1",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Authentication as e}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as t}from"../core/errors/authErrorCodes.js";import{SessionError as a,ConfigurationError as r}from"../core/errors/openfortError.js";import{withApiError as o}from"../core/errors/withApiError.js";import{PasskeyHandler as s}from"../core/passkey/handler.js";import{SDKConfiguration as n}from"../core/config/config.js";import{Account as i}from"../core/configuration/account.js";import{StorageKeys as c}from"../storage/istorage.js";import{OpenfortEvents as d,AccountTypeEnum as y}from"../types/types.js";class p{iframeManager;storage;backendApiClients;passkeyHandler;eventEmitter;constructor(e,t,a,r,o){this.iframeManager=e,this.storage=t,this.backendApiClients=a,this.passkeyHandler=r,this.eventEmitter=o}async createPasskey(e){const t=await this.passkeyHandler.createPasskey({id:s.randomPasskeyName(),
|
|
1
|
+
import{Authentication as e}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as t}from"../core/errors/authErrorCodes.js";import{SessionError as a,ConfigurationError as r}from"../core/errors/openfortError.js";import{withApiError as o}from"../core/errors/withApiError.js";import{PasskeyHandler as s}from"../core/passkey/handler.js";import{SDKConfiguration as n}from"../core/config/config.js";import{Account as i}from"../core/configuration/account.js";import{StorageKeys as c}from"../storage/istorage.js";import{OpenfortEvents as d,AccountTypeEnum as y}from"../types/types.js";class p{iframeManager;storage;backendApiClients;passkeyHandler;eventEmitter;constructor(e,t,a,r,o){this.iframeManager=e,this.storage=t,this.backendApiClients=a,this.passkeyHandler=r,this.eventEmitter=o}async createPasskey(e){const t=await this.passkeyHandler.createPasskey({id:s.randomPasskeyName(),seed:e});return{id:t.id,key:t.key}}async configure(s){const c=await e.fromStorage(this.storage);if(!c)throw new a(t.NOT_LOGGED_IN,"No access token found");const y=n.getInstance();if(!y)throw new r("Configuration not found");const p=await i.fromStorage(this.storage);let h;if(p){const e={account:p.id,...s.entropy&&{entropy:{...s.entropy.recoveryPassword&&{recoveryPassword:s.entropy.recoveryPassword},...s.entropy.encryptionSession&&{encryptionSession:s.entropy.encryptionSession},..."passkey"===p.recoveryMethod&&{passkey:{id:p.recoveryMethodDetails?.passkeyId,env:p.recoveryMethodDetails?.passkeyEnv,key:await s.getPasskeyKeyFn(p.recoveryMethodDetails?.passkeyId??"")}}}}},t=await this.iframeManager.recover(e);h=t.account}else{const e=await this.backendApiClients.accountsV2Api.getAccountsV2({accountType:s.accountType,chainType:s.chainType},{headers:c.thirdPartyProvider?{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}:{authorization:`Bearer ${c.token}`,"x-project-key":y.baseConfiguration.publishableKey}});if(0===e.data.data.length){const e=s.entropy?.passkey?await this.createPasskey(c.userId):void 0,t={accountType:s.accountType,chainType:s.chainType,chainId:s.chainId,...s.entropy&&{entropy:{...s.entropy.recoveryPassword&&{recoveryPassword:s.entropy.recoveryPassword},...s.entropy.encryptionSession&&{encryptionSession:s.entropy.encryptionSession},...s.entropy.passkey&&{passkey:e}}}},a=await this.iframeManager.create(t);h=a.account}else{const t=e.data.data,a=t.find(e=>e.chainId===s.chainId),r=a||t[0],o={account:r.id,...s.entropy&&{entropy:{...s.entropy.recoveryPassword&&{recoveryPassword:s.entropy.recoveryPassword},...s.entropy.encryptionSession&&{encryptionSession:s.entropy.encryptionSession},..."passkey"===r.recoveryMethod&&{passkey:{id:r.recoveryMethodDetails?.passkeyId,env:r.recoveryMethodDetails?.passkeyEnv,key:await s.getPasskeyKeyFn(r.recoveryMethodDetails?.passkeyId??"")}}}}},n=await this.iframeManager.recover(o);if(h=n.account,!a){const e=await this.iframeManager.switchChain(s.chainId);h=e.account}}}return o(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:h},{headers:c.thirdPartyProvider?{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":c.token,"x-auth-provider":c.thirdPartyProvider,"x-token-type":c.thirdPartyTokenType}:{authorization:`Bearer ${c.token}`,"x-project-key":y.baseConfiguration.publishableKey}}),t=new i({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:i.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(d.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"configure"})}async sign(e,t,a,r){const o=await this.iframeManager.sign(e,t,a,r);return this.eventEmitter.emit(d.ON_SIGNED_MESSAGE,{message:e,signature:o}),o}async export(){return await this.iframeManager.export()}async switchChain({chainId:e}){const t=await i.fromStorage(this.storage);if(t?.accountType===y.EOA)new i({...t,chainId:e}).save(this.storage);else{const a=await this.iframeManager.switchChain(e);new i({...t,id:a.account,chainId:e}).save(this.storage)}}async create(s){const c=await this.iframeManager.create(s),y=await e.fromStorage(this.storage);if(!y)throw new a(t.NOT_LOGGED_IN,"No access token found");const p=n.getInstance();if(!p)throw new r("Configuration not found");return o(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:c.account},{headers:y.thirdPartyProvider?{authorization:`Bearer ${p.baseConfiguration.publishableKey}`,"x-player-token":y.token,"x-auth-provider":y.thirdPartyProvider,"x-token-type":y.thirdPartyTokenType}:{authorization:`Bearer ${y.token}`,"x-project-key":p.baseConfiguration.publishableKey}}),t=new i({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,implementationAddress:e.data.smartAccount?.implementationAddress,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:i.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(d.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"create"})}async recover(s){const c=await this.iframeManager.recover(s),y=await e.fromStorage(this.storage);if(!y)throw new a(t.NOT_LOGGED_IN,"No access token found");const p=n.getInstance();if(!p)throw new r("Configuration not found");return o(async()=>{const e=await this.backendApiClients.accountsV2Api.getAccountV2({id:c.account},{headers:y.thirdPartyProvider?{authorization:`Bearer ${p.baseConfiguration.publishableKey}`,"x-player-token":y.token,"x-auth-provider":y.thirdPartyProvider,"x-token-type":y.thirdPartyTokenType}:{authorization:`Bearer ${y.token}`,"x-project-key":p.baseConfiguration.publishableKey}}),t=new i({chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:i.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(d.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"recover"})}async setRecoveryMethod({recoveryMethod:e,recoveryPassword:t,encryptionSession:a,passkeyInfo:r}){await this.iframeManager.setRecoveryMethod(e,t,a,r?.passkeyKey,r?.passkeyId)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(c.ACCOUNT)}}export{p as EmbeddedSigner};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Account as t}from"../../core/configuration/account.js";import{Authentication as e}from"../../core/configuration/authentication.js";import{OpenfortEvents as a,AccountTypeEnum as i}from"../../types/types.js";import{defaultChainRpcs as s}from"../../utils/chains/index.js";import{numberToHex as r}from"../../utils/crypto.js";import o from"../../utils/typedEventEmitter.js";import{addEthereumChain as n}from"./addEthereumChain.js";import{estimateGas as c}from"./estimateGas.js";import{getAssets as h}from"./getAssets.js";import{getCallStatus as d}from"./getCallsStatus.js";import{JsonRpcError as p,ProviderErrorCode as m,RpcErrorCode as
|
|
1
|
+
import{Account as t}from"../../core/configuration/account.js";import{Authentication as e}from"../../core/configuration/authentication.js";import{OpenfortEvents as a,AccountTypeEnum as i}from"../../types/types.js";import{defaultChainRpcs as s}from"../../utils/chains/index.js";import{numberToHex as r}from"../../utils/crypto.js";import o from"../../utils/typedEventEmitter.js";import{addEthereumChain as n}from"./addEthereumChain.js";import{estimateGas as c}from"./estimateGas.js";import{getAssets as h}from"./getAssets.js";import{getCallStatus as d}from"./getCallsStatus.js";import{JsonRpcError as p,ProviderErrorCode as m,RpcErrorCode as w}from"./JsonRpcError.js";import{personalSign as l}from"./personalSign.js";import{registerSession as u}from"./registerSession.js";import{revokeSession as g}from"./revokeSession.js";import{sendCallsSync as f}from"./sendCallSync.js";import{sendCalls as S}from"./sendCalls.js";import{signTypedDataV4 as A}from"./signTypedDataV4.js";import{ProviderEvent as R}from"./types.js";import{prepareEOATransaction as v,parseTransactionRequest as _}from"./walletHelpers.js";class E{#t;#e;#a;#i;updatePolicy(t){this.#e=t}#s;#r;#o=null;#n;isOpenfort=!0;#c;constructor({storage:t,backendApiClients:e,openfortEventEmitter:i,policyId:s,ensureSigner:r,chains:n,validateAndRefreshSession:c}){this.#c=r,this.#t=t,this.#a=n,this.#e=s,this.#s=c,this.#n=e,this.#r=new o,i.on(a.ON_LOGOUT,this.#h),i.on(a.ON_SWITCH_ACCOUNT,this.#d)}#p=async()=>(this.#i||(this.#i=await this.#c()),this.#i);#h=async()=>{this.#i=void 0,this.#r.emit(R.DISCONNECT,{code:4900,message:"Disconnected"}),this.#r.emit(R.ACCOUNTS_CHANGED,[])};#d=async t=>{this.#r.emit(R.ACCOUNTS_CHANGED,[t])};async getRpcProvider(){if(!this.#o){const e=await t.fromStorage(this.#t),a=e?.chainId||8453;await import("@ethersproject/providers").then(t=>{const e=this.#a?this.#a[a]:void 0;this.#o=new t.StaticJsonRpcProvider(e??s[a])})}if(!this.#o)throw new Error("RPC provider not initialized");return this.#o}async#m(a){switch(a.method){case"eth_accounts":{const e=await t.fromStorage(this.#t);return e?[e.address]:[]}case"eth_requestAccounts":{const e=await t.fromStorage(this.#t);if(e){const t=await this.getRpcProvider(),{chainId:a}=await t.detectNetwork();return this.#r.emit(R.ACCOUNTS_CONNECT,{chainId:r(a)}),[e.address]}throw new p(m.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer.")}case"eth_signTransaction":{const i=await t.fromStorage(this.#t),s=await this.#p(),r=await e.fromStorage(this.#t);if(!i||!r)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const o=await this.getRpcProvider(),{chainId:n}=await o.detectNetwork(),[c]=a.params||[];c.chainId||(c.chainId=n.toString());const h=_(c),{serialize:d}=await import("@ethersproject/transactions"),w=t=>({legacy:0,eip2930:1,eip1559:2}[t]),{gas:l,...u}=h,g={...u,gasLimit:l,to:h.to??void 0,type:w(h.type)},f=d(g),{keccak256:S}=await import("@ethersproject/keccak256"),A=S(f);await this.#s();const R=await s.sign(A,!1,!1),{splitSignature:v}=await import("@ethersproject/bytes");return d(g,v(R))}case"eth_sendTransaction":{const[s,r,o]=await Promise.all([t.fromStorage(this.#t),this.#p(),e.fromStorage(this.#t)]);if(!s||!o)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(await this.#s(),s?.accountType===i.EOA){const[t]=a.params||[],e=await this.getRpcProvider(),i=await v(t,e,s.address),r=await this.#m({method:"eth_signTransaction",params:[i]});return this.#m({method:"eth_sendRawTransaction",params:[r]})}return(await f({params:a.params||[],signer:r,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),policyId:this.#e})).receipt.transactionHash}case"eth_sendRawTransactionSync":{const[s,r,o]=await Promise.all([t.fromStorage(this.#t),this.#p(),e.fromStorage(this.#t)]);if(!s||!o)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");if(s?.accountType===i.EOA)throw new p(m.UNSUPPORTED_METHOD,`${a.method}: Method not supported`);return await this.#s(),await f({params:a.params||[],signer:r,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),policyId:this.#e})}case"eth_estimateGas":{const i=await t.fromStorage(this.#t),s=await e.fromStorage(this.#t);if(!i||!s)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await c({params:a.params||[],account:i,authentication:s,backendClient:this.#n,policyId:this.#e})}case"eth_signTypedData":case"eth_signTypedData_v4":{const e=await t.fromStorage(this.#t),i=await this.#p();if(!e)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#s();const s=await this.getRpcProvider();return await A({method:a.method,params:a.params||[],signer:i,implementationType:e.implementationType||e.type,rpcProvider:s,account:e})}case"personal_sign":{const e=await t.fromStorage(this.#t);if(!e)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const i=await this.#p();return await this.#s(),await l({params:a.params||[],signer:i,account:e})}case"eth_chainId":{const t=await this.getRpcProvider(),{chainId:e}=await t.detectNetwork();return r(e)}case"wallet_switchEthereumChain":{const t=await this.#p();if(!a.params||!Array.isArray(a.params)||0===a.params.length)throw new p(w.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#s();try{const e=parseInt(a.params[0].chainId,16);await t.switchChain({chainId:e}),await import("@ethersproject/providers").then(t=>{const a=this.#a?this.#a[e]:void 0;this.#o=new t.StaticJsonRpcProvider(a??s[e])}),this.#r.emit(R.CHAIN_CHANGED,r(e))}catch(t){const e=t;throw new p(w.INTERNAL_ERROR,`Failed to switch chain: ${e.message}`)}return null}case"wallet_addEthereumChain":{await this.#p();const t=await this.getRpcProvider();return await n({params:a.params||[],rpcProvider:t,storage:this.#t})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const s=await t.fromStorage(this.#t);if(s?.accountType===i.EOA)throw new p(m.UNSUPPORTED_METHOD,`${a.method}: Method not supported`);const r=await e.fromStorage(this.#t);if(!s||!r)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await d({params:a.params||{},authentication:r,backendClient:this.#n})}case"wallet_sendCalls":{const[s,r,o]=await Promise.all([t.fromStorage(this.#t),this.#p(),e.fromStorage(this.#t)]);if(s?.accountType===i.EOA)throw new p(m.UNSUPPORTED_METHOD,`${a.method}: Method not supported`);if(!s||!o)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#s();return await S({params:a.params?a.params[0].calls:[],signer:r,account:s,authentication:o,backendClient:this.#n,rpcProvider:await this.getRpcProvider(),policyId:this.#e})}case"wallet_grantPermissions":{const s=await t.fromStorage(this.#t);if(s?.accountType===i.EOA)throw new p(m.UNSUPPORTED_METHOD,`${a.method}: Method not supported`);const r=await this.#p(),o=await e.fromStorage(this.#t);if(!s||!o)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await u({params:a.params||[],signer:r,account:s,authentication:o,backendClient:this.#n,policyId:this.#e})}case"wallet_revokePermissions":{const i=await t.fromStorage(this.#t),s=await this.#p(),r=await e.fromStorage(this.#t);if(!i||!r)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await g({params:a.params||[],signer:s,account:i,authentication:r,backendClient:this.#n,policyId:this.#e})}case"wallet_getCapabilities":{const e=await t.fromStorage(this.#t);if(e?.accountType===i.EOA)throw new p(m.UNSUPPORTED_METHOD,`${a.method}: Method not supported`);const s=await this.getRpcProvider(),{chainId:o}=await s.detectNetwork();return{[r(o)]:{permissions:{supported:!0,signerTypes:["account","key"],keyTypes:["secp256k1"],permissionTypes:["contract-calls"]},paymasterService:{supported:!0},atomicBatch:{supported:!0}}}}case"wallet_getAssets":{const i=await t.fromStorage(this.#t),s=await e.fromStorage(this.#t);if(!i||!s)throw new p(m.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await h({params:a.params?.[0],account:i,authentication:s,backendClient:this.#n})}case"eth_gasPrice":case"eth_getBalance":case"eth_sendRawTransaction":case"eth_getCode":case"eth_getStorageAt":case"eth_call":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":case"eth_getTransactionCount":return(await this.getRpcProvider()).send(a.method,a.params||[]);default:throw new p(m.UNSUPPORTED_METHOD,`${a.method}: Method not supported`)}}async request(t){try{return this.#m(t)}catch(t){if(t instanceof p)throw t;if(t instanceof Error)throw new p(w.INTERNAL_ERROR,t.message);throw new p(w.INTERNAL_ERROR,"Internal error")}}on(t,e){this.#r.on(t,e)}removeListener(t,e){this.#r.off(t,e)}}export{E as EvmProvider};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var C;!function(C){C.ACCOUNTS_CHANGED="accountsChanged",C.ACCOUNTS_CONNECT="connect"}(C||(C={}));export{C as ProviderEvent};
|
|
1
|
+
var C;!function(C){C.ACCOUNTS_CHANGED="accountsChanged",C.CHAIN_CHANGED="chainChanged",C.ACCOUNTS_CONNECT="connect",C.DISCONNECT="disconnect"}(C||(C={}));export{C as ProviderEvent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AccountType as e}from"../../types/types.js";const t=async t=>{const{hash:a,signer:s,ownerAddress:r,factoryAddress:i,salt:n,chainId:o,address:c,implementationType:d}=t;let g=a;if([e.UPGRADEABLE_V5,e.UPGRADEABLE_V6
|
|
1
|
+
import{AccountType as e}from"../../types/types.js";const t=async t=>{const{hash:a,signer:s,ownerAddress:r,factoryAddress:i,salt:n,chainId:o,address:c,implementationType:d}=t;let g=a;if([e.UPGRADEABLE_V5,e.UPGRADEABLE_V6].includes(d)){const e={name:"Openfort",version:"0.5",chainId:Number(o),verifyingContract:c},t={OpenfortMessage:[{name:"hashedMessage",type:"bytes32"}]},a={hashedMessage:g},{_TypedDataEncoder:s}=await import("@ethersproject/hash");g=s.hash(e,t,a)}const P=await s.sign(g,!1,!1);if(i&&n&&[e.UPGRADEABLE_V5,e.UPGRADEABLE_V6].includes(d)){const{id:e}=await import("@ethersproject/hash"),{defaultAbiCoder:t}=await import("@ethersproject/abi"),{hexConcat:a}=await import("@ethersproject/bytes"),s=a([e("createAccountWithNonce(address,bytes32,bool)").slice(0,10),t.encode(["address","bytes32","bool"],[r,n,!1])]);return a([t.encode(["address","bytes","bytes"],[i,s,P]),"0x6492649264926492649264926492649264926492649264926492649264926492"])}return P};async function a(e,t,a){const s={...e};if(!s.nonce){const e=await t.getTransactionCount(a,"pending");s.nonce=`0x${e.toString(16)}`}if(!s.gas)try{const e=await t.estimateGas({from:a,to:s.to,data:s.data,value:s.value});s.gas=e.toHexString()}catch{s.gas="0x5208"}const r=s.maxFeePerGas&&s.maxPriorityFeePerGas,i=s.gasPrice;if(!r&&!i){const e=await t.getBlock("latest");if(null!==e.baseFeePerGas&&void 0!==e.baseFeePerGas){const a=e.baseFeePerGas,r=a.mul(12).div(10),i=await t.getGasPrice();let n=i.sub(a);n.lt(0)&&(n=i.mul(0));const o=r.add(n);s.maxFeePerGas=o.toHexString(),s.maxPriorityFeePerGas=n.toHexString(),s.type="0x2",delete s.gasPrice}else{const e=(await t.getGasPrice()).mul(12).div(10);s.gasPrice=e.toHexString(),s.type="0x0",delete s.maxFeePerGas,delete s.maxPriorityFeePerGas}}return s}function s({from:e,...t}){return{to:t.to,data:t.data,accessList:t.accessList,chainId:(i=t.chainId,i.startsWith("0x")?parseInt(i,16):parseInt(i,10)),type:t.type&&{"0x0":"legacy","0x1":"eip2930","0x2":"eip1559"}[t.type]||"eip1559",maxPriorityFeePerGas:t.maxPriorityFeePerGas?BigInt(t.maxPriorityFeePerGas):void 0,maxFeePerGas:t.maxFeePerGas?BigInt(t.maxFeePerGas):void 0,gasPrice:t.gasPrice?BigInt(t.gasPrice):void 0,value:(a=t.value,s=BigInt,r=0n,void 0!==a?s(a):r),nonce:t.nonce?parseInt(t.nonce.toString(),16):void 0,gas:t.gas?BigInt(t.gas):void 0};var a,s,r,i}export{s as parseTransactionRequest,a as prepareEOATransaction,t as signMessage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Account as e}from"../core/configuration/account.js";import{Authentication as i}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as t}from"../core/errors/authErrorCodes.js";import{RecoveryError as n,SignerError as r,OpenfortError as o,ConfigurationError as s,SessionError as a}from"../core/errors/openfortError.js";import{sentry as d}from"../core/errors/sentry.js";import{StorageKeys as c}from"../storage/istorage.js";import{randomUUID as h}from"../utils/crypto.js";import{debugLog as u}from"../utils/debug.js";import{ReactNativeMessenger as l}from"./messaging/ReactNativeMessenger.js";import f from"./messaging/browserMessenger/connect.js";import"./messaging/browserMessenger/backwardCompatibility.js";import{isErrorResponse as y,NOT_CONFIGURED_ERROR as g,MISSING_USER_ENTROPY_ERROR as p,MISSING_PROJECT_ENTROPY_ERROR as m,INCORRECT_USER_ENTROPY_ERROR as w,MISSING_PASSKEY_ERROR as C,INCORRECT_PASSKEY_ERROR as v,OTP_REQUIRED_ERROR as k,ShieldAuthType as I,Event as P,SignRequest as R,SwitchChainRequest as b,ExportPrivateKeyRequest as E,SetRecoveryMethodRequest as T,GetCurrentDeviceRequest as S,UpdateAuthenticationRequest as N}from"./types.js";class A extends n{constructor(){super(t.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class O extends n{constructor(){super(t.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class U extends n{constructor(){super(t.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class z extends n{constructor(){super(t.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class D extends r{constructor(){super(t.NOT_CONFIGURED,"Signer is not configured")}}class K extends o{constructor(){super(t.OTP_REQUIRED,"OTP verification required")}}class M{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;hasFailed=!1;constructor(e,i,t){if(!e)throw new s("Configuration is required for IframeManager");if(!i)throw new s("Storage is required for IframeManager");if(!t)throw new s("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=t}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new o(t.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){u("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:u}),this.connection=f({messenger:this.messenger,timeout:1e4,log:u});try{this.remote=await this.connection.promise,u("IframeManager connection established")}catch(e){const i=e;throw d.captureException(i),this.destroy(),u("Failed to establish connection:",i),new o(t.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}\n \n In apps built with:\n - react native\n - swift\n - unity (non-webgl) \n \n You must configure your origin in the openfort dashboard before using the embedded wallet.\n\n For more information, see: https://www.openfort.io/docs/configuration/native-apps\n `)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new o(t.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(y(e)){if(e.error===g)throw this.storage.remove(c.ACCOUNT),new D;if(e.error===p)throw this.storage.remove(c.ACCOUNT),new A;if(e.error===m)throw this.storage.remove(c.ACCOUNT),new U;if(e.error===w)throw new z;if(e.error===C)throw this.storage.remove(c.ACCOUNT),new A;if(e.error===v)throw new O;if(e.error===k)throw new K;throw this.storage.remove(c.ACCOUNT),new o(t.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(t.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:I.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(t.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:I.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),t=await this.buildIFrameRequestConfiguration();t.chainId=e.chainId??null,t.password=e?.entropy?.recoveryPassword??null,t.recovery={...t.recovery,encryptionSession:e?.entropy?.encryptionSession},t.passkey=e?.entropy?.passkey??null;const n={uuid:h(),action:P.CREATE,recovery:t.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:t.accessToken,playerID:t.playerID,thirdPartyProvider:t.thirdPartyProvider,thirdPartyTokenType:t.thirdPartyTokenType,encryptionKey:t.password,encryptionSession:t.recovery?.encryptionSession??null,passkey:t.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},r=await i.create(n);return y(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const t=await e.fromStorage(this.storage),n=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=t?.chainId??null,r.password=i?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:i?.entropy?.encryptionSession},r.passkey=i?.entropy?.passkey??null;const o={uuid:h(),action:P.RECOVER,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},s=await n.recover(o);return y(s)&&this.handleError(s),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",s.version??"undefined"),s}async sign(e,i,t,n){u("[iframe] ensureConnection");const r=await this.ensureConnection(),o=new R(h(),e,await this.buildRequestConfiguration(),i,t,n);u("[iframe] done ensureConnection");const s=await r.sign(o);return u("[iframe] response",s),y(s)&&this.handleError(s),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",s.version??"undefined"),s.signature}async switchChain(e){const i=await this.ensureConnection(),t=new b(h(),e,await this.buildRequestConfiguration()),n=await i.switchChain(t);return y(n)&&this.handleError(n),n}async export(){const e=await this.ensureConnection(),i=new E(h(),await this.buildRequestConfiguration()),t=await e.export(i);return y(t)&&this.handleError(t),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",t.version??"undefined"),t.key}async setRecoveryMethod(e,i,t,n,r){const o=await this.ensureConnection(),s=new T(h(),e,await this.buildRequestConfiguration(),i,t,n,r),a=await o.setRecoveryMethod(s);y(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),t=new S(h(),e);try{const e=await i.getCurrentDevice(t);return y(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof D)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void u("IframeManager not loaded, skipping authentication update");const e=await i.fromStorage(this.storage);if(!e)return void u("No authentication found, skipping update");const t=new N(h(),e.token);u("Updating authentication in iframe with token");const n=await this.remote.updateAuthentication(t);y(n)&&this.handleError(n)}async disconnect(){const e=await this.ensureConnection(),i={uuid:h()};await e.logout(i)}async onMessage(e){u("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof l?(this.isInitialized||this.connection?u(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(u("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{u("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),u("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):u("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}}export{M as IframeManager,U as MissingProjectEntropyError,A as MissingRecoveryPasswordError,D as NotConfiguredError,K as OTPRequiredError,O as WrongPasskeyError,z as WrongRecoveryPasswordError};
|
|
1
|
+
import{Account as e}from"../core/configuration/account.js";import{Authentication as i}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as t}from"../core/errors/authErrorCodes.js";import{RecoveryError as n,SignerError as r,OpenfortError as o,ConfigurationError as s,SessionError as a}from"../core/errors/openfortError.js";import{sentry as d}from"../core/errors/sentry.js";import{StorageKeys as c}from"../storage/istorage.js";import{randomUUID as h}from"../utils/crypto.js";import{debugLog as u}from"../utils/debug.js";import{ReactNativeMessenger as l}from"./messaging/ReactNativeMessenger.js";import f from"./messaging/browserMessenger/connect.js";import"./messaging/browserMessenger/backwardCompatibility.js";import{isErrorResponse as y,NOT_CONFIGURED_ERROR as g,MISSING_USER_ENTROPY_ERROR as p,MISSING_PROJECT_ENTROPY_ERROR as m,INCORRECT_USER_ENTROPY_ERROR as w,MISSING_PASSKEY_ERROR as C,INCORRECT_PASSKEY_ERROR as v,OTP_REQUIRED_ERROR as k,ShieldAuthType as I,Event as P,SignRequest as R,SwitchChainRequest as b,ExportPrivateKeyRequest as E,SetRecoveryMethodRequest as T,GetCurrentDeviceRequest as S,UpdateAuthenticationRequest as N}from"./types.js";class A extends n{constructor(){super(t.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class O extends n{constructor(){super(t.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class U extends n{constructor(){super(t.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class z extends n{constructor(){super(t.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class D extends r{constructor(){super(t.NOT_CONFIGURED,"Signer is not configured")}}class M extends o{constructor(){super(t.OTP_REQUIRED,"OTP verification required")}}class K{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;hasFailed=!1;constructor(e,i,t){if(!e)throw new s("Configuration is required for IframeManager");if(!i)throw new s("Storage is required for IframeManager");if(!t)throw new s("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=t}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new o(t.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){u("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:u}),this.connection=f({messenger:this.messenger,timeout:1e4,log:u});try{this.remote=await this.connection.promise,u("IframeManager connection established")}catch(e){const i=e;throw d.captureException(i),this.destroy(),u("Failed to establish connection:",i),new o(t.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}\n \n In apps built with:\n - react native\n - swift\n - unity (non-webgl) \n \n You must configure your origin in the openfort dashboard before using the embedded wallet.\n\n For more information, see: https://www.openfort.io/docs/configuration/native-apps\n `)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new o(t.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(y(e)){if(e.error===g)throw this.storage.remove(c.ACCOUNT),new D;if(e.error===p)throw this.storage.remove(c.ACCOUNT),new A;if(e.error===m)throw this.storage.remove(c.ACCOUNT),new U;if(e.error===w)throw new z;if(e.error===C)throw this.storage.remove(c.ACCOUNT),new A;if(e.error===v)throw new O;if(e.error===k)throw new M;throw this.storage.remove(c.ACCOUNT),new o(t.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(t.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:I.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(t.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:I.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),t=await this.buildIFrameRequestConfiguration();t.chainId=e.chainId??null,t.password=e?.entropy?.recoveryPassword??null,t.recovery={...t.recovery,encryptionSession:e?.entropy?.encryptionSession},t.passkey=e?.entropy?.passkey??null;const n={uuid:h(),action:P.CREATE,recovery:t.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:t.accessToken,playerID:t.playerID,thirdPartyProvider:t.thirdPartyProvider,thirdPartyTokenType:t.thirdPartyTokenType,encryptionKey:t.password,encryptionSession:t.recovery?.encryptionSession??null,passkey:t.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},r=await i.create(n);return y(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const t=await e.fromStorage(this.storage),n=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=t?.chainId??null,r.password=i?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:i?.entropy?.encryptionSession},r.passkey=i?.entropy?.passkey??null;const o={uuid:h(),action:P.RECOVER,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},s=await n.recover(o);return y(s)&&this.handleError(s),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",s.version??"undefined"),s}async sign(e,i,t,n){u("[iframe] ensureConnection");const r=await this.ensureConnection(),o=new R(h(),e,await this.buildRequestConfiguration(),i,t,n);u("[iframe] done ensureConnection");const s=await r.sign(o);return u("[iframe] response",s),y(s)&&this.handleError(s),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",s.version??"undefined"),s.signature}async switchChain(e){const i=await this.ensureConnection(),t=new b(h(),e,await this.buildRequestConfiguration()),n=await i.switchChain(t);return y(n)&&this.handleError(n),n}async export(){const e=await this.ensureConnection(),i=new E(h(),await this.buildRequestConfiguration()),t=await e.export(i);return y(t)&&this.handleError(t),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",t.version??"undefined"),t.key}async setRecoveryMethod(e,i,t,n,r){const o=await this.ensureConnection(),s=new T(h(),e,await this.buildRequestConfiguration(),i,t,n,r),a=await o.setRecoveryMethod(s);y(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),t=new S(h(),e);try{const e=await i.getCurrentDevice(t);return y(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof D)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void u("IframeManager not loaded, skipping authentication update");const e=await i.fromStorage(this.storage);if(!e)return void u("No authentication found, skipping update");const t=new N(h(),e.token);u("Updating authentication in iframe with token");const n=await this.remote.updateAuthentication(t);y(n)&&this.handleError(n)}async disconnect(){const e=await this.ensureConnection(),i={uuid:h()};await e.logout(i)}async onMessage(e){u("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof l?(this.isInitialized||this.connection?u(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(u("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{u("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),u("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):u("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}}export{K as IframeManager,U as MissingProjectEntropyError,A as MissingRecoveryPasswordError,D as NotConfiguredError,M as OTPRequiredError,O as WrongPasskeyError,z as WrongRecoveryPasswordError};
|
package/package.json
CHANGED