@openfort/openfort-js 0.10.21 → 0.10.22

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.
Files changed (48) hide show
  1. package/dist/cjs/sdk/src/api/proxy.js +1 -1
  2. package/dist/cjs/sdk/src/auth/authManager.js +1 -1
  3. package/dist/cjs/sdk/src/core/configuration/account.js +1 -1
  4. package/dist/cjs/sdk/src/core/errors/openfortError.js +1 -1
  5. package/dist/cjs/sdk/src/core/errors/sentry.js +1 -1
  6. package/dist/cjs/sdk/src/core/openfort.js +1 -1
  7. package/dist/cjs/sdk/src/core/openfortInternal.js +1 -1
  8. package/dist/cjs/sdk/src/index.js +1 -1
  9. package/dist/cjs/sdk/src/storage/lazyStorage.js +1 -1
  10. package/dist/cjs/sdk/src/version.js +1 -1
  11. package/dist/cjs/sdk/src/wallets/embedded.js +1 -1
  12. package/dist/cjs/sdk/src/wallets/evm/evmProvider.js +1 -1
  13. package/dist/cjs/sdk/src/wallets/evm/registerSession.js +1 -1
  14. package/dist/cjs/sdk/src/wallets/evm/signTypedDataV4.js +1 -1
  15. package/dist/cjs/sdk/src/wallets/iframeManager.js +1 -1
  16. package/dist/cjs/sdk/src/wallets/messaging/browserMessenger/CallOptions.js +1 -1
  17. package/dist/cjs/sdk/src/wallets/messaging/browserMessenger/Reply.js +1 -1
  18. package/dist/cjs/sdk/src/wallets/messaging/browserMessenger/backwardCompatibility.js +1 -1
  19. package/dist/cjs/sdk/src/wallets/messaging/browserMessenger/connect.js +1 -1
  20. package/dist/cjs/sdk/src/wallets/messaging/browserMessenger/connectCallHandler.js +1 -1
  21. package/dist/cjs/sdk/src/wallets/messaging/browserMessenger/connectRemoteProxy.js +1 -1
  22. package/dist/cjs/sdk/src/wallets/messaging/browserMessenger/messengers/WindowMessenger.js +1 -1
  23. package/dist/cjs/sdk/src/wallets/messaging/browserMessenger/shakeHands.js +1 -1
  24. package/dist/index.d.ts +1832 -1775
  25. package/dist/sdk/src/api/proxy.js +1 -1
  26. package/dist/sdk/src/auth/authManager.js +1 -1
  27. package/dist/sdk/src/core/configuration/account.js +1 -1
  28. package/dist/sdk/src/core/errors/openfortError.js +1 -1
  29. package/dist/sdk/src/core/errors/sentry.js +1 -1
  30. package/dist/sdk/src/core/openfort.js +1 -1
  31. package/dist/sdk/src/core/openfortInternal.js +1 -1
  32. package/dist/sdk/src/index.js +1 -1
  33. package/dist/sdk/src/storage/lazyStorage.js +1 -1
  34. package/dist/sdk/src/version.js +1 -1
  35. package/dist/sdk/src/wallets/embedded.js +1 -1
  36. package/dist/sdk/src/wallets/evm/evmProvider.js +1 -1
  37. package/dist/sdk/src/wallets/evm/registerSession.js +1 -1
  38. package/dist/sdk/src/wallets/evm/signTypedDataV4.js +1 -1
  39. package/dist/sdk/src/wallets/iframeManager.js +1 -1
  40. package/dist/sdk/src/wallets/messaging/browserMessenger/CallOptions.js +1 -1
  41. package/dist/sdk/src/wallets/messaging/browserMessenger/Reply.js +1 -1
  42. package/dist/sdk/src/wallets/messaging/browserMessenger/backwardCompatibility.js +1 -1
  43. package/dist/sdk/src/wallets/messaging/browserMessenger/connect.js +1 -1
  44. package/dist/sdk/src/wallets/messaging/browserMessenger/connectCallHandler.js +1 -1
  45. package/dist/sdk/src/wallets/messaging/browserMessenger/connectRemoteProxy.js +1 -1
  46. package/dist/sdk/src/wallets/messaging/browserMessenger/messengers/WindowMessenger.js +1 -1
  47. package/dist/sdk/src/wallets/messaging/browserMessenger/shakeHands.js +1 -1
  48. package/package.json +9 -18
@@ -1 +1 @@
1
- "use strict";var e=require("../core/config/config.js"),t=require("../core/errors/openfortError.js");exports.ProxyApi=class{storage;backendApiClients;validateAndRefreshToken;ensureInitialized;getSignerSignFunction;constructor(e,t,n,i,r){this.storage=e,this.backendApiClients=t,this.validateAndRefreshToken=n,this.ensureInitialized=i,this.getSignerSignFunction=r}async sendSignatureTransactionIntentRequest(n,i=null,r=null,s=!1){await this.ensureInitialized();if(!e.SDKConfiguration.getInstance())throw new t.OpenfortError("Configuration not found",t.OpenfortErrorType.INVALID_CONFIGURATION);await this.validateAndRefreshToken();let o=r;if(!o){if(!i)throw new t.OpenfortError("No signableHash or signature provided",t.OpenfortErrorType.OPERATION_NOT_SUPPORTED_ERROR);if(!this.getSignerSignFunction)throw new t.OpenfortError("In order to sign a transaction intent, a signer must be configured",t.OpenfortErrorType.MISSING_SIGNER_ERROR);const e=await this.getSignerSignFunction();o=await e(i)}const a={id:n,signatureRequest:{signature:o,optimistic:s}};return t.withOpenfortError(async()=>(await this.backendApiClients.transactionIntentsApi.signature(a)).data,{default:t.OpenfortErrorType.INTERNAL_ERROR})}async sendSignatureSessionRequest(e,n,i){await this.ensureInitialized();const r={id:e,signatureRequest:{signature:n,optimistic:i}};return t.withOpenfortError(async()=>(await this.backendApiClients.sessionsApi.signatureSession(r)).data,{default:t.OpenfortErrorType.INTERNAL_ERROR})}};
1
+ "use strict";var e=require("../core/config/config.js"),n=require("../core/errors/openfortError.js");exports.ProxyApi=class{backendApiClients;validateAndRefreshToken;ensureInitialized;getSignerSignFunction;constructor(e,n,t,i,r){this.backendApiClients=n,this.validateAndRefreshToken=t,this.ensureInitialized=i,this.getSignerSignFunction=r}async sendSignatureTransactionIntentRequest(t,i=null,r=null,s=!1){await this.ensureInitialized();if(!e.SDKConfiguration.getInstance())throw new n.OpenfortError("Configuration not found",n.OpenfortErrorType.INVALID_CONFIGURATION);await this.validateAndRefreshToken();let o=r;if(!o){if(!i)throw new n.OpenfortError("No signableHash or signature provided",n.OpenfortErrorType.OPERATION_NOT_SUPPORTED_ERROR);if(!this.getSignerSignFunction)throw new n.OpenfortError("In order to sign a transaction intent, a signer must be configured",n.OpenfortErrorType.MISSING_SIGNER_ERROR);const e=await this.getSignerSignFunction();o=await e(i)}const a={id:t,signatureRequest:{signature:o,optimistic:s}};return n.withOpenfortError(async()=>(await this.backendApiClients.transactionIntentsApi.signature(a)).data,{default:n.OpenfortErrorType.INTERNAL_ERROR})}async sendSignatureSessionRequest(e,t,i){await this.ensureInitialized();const r={id:e,signatureRequest:{signature:t,optimistic:i}};return n.withOpenfortError(async()=>(await this.backendApiClients.sessionsApi.signatureSession(r)).data,{default:n.OpenfortErrorType.INTERNAL_ERROR})}};
@@ -1 +1 @@
1
- "use strict";var e=require("jose"),t=require("../utils/debug.js"),r=require("../core/errors/openfortError.js"),a=require("../core/errors/sentry.js"),n=require("../types/types.js"),i=require("../storage/istorage.js"),o=require("../utils/crypto.js");async function s(e){const t=(new TextEncoder).encode(e),r=await o.cryptoDigest("SHA-256",t);return new Uint8Array(r)}function p(e){const t=new Uint8Array(e);return crypto.getRandomValues(t),t}class d{decodedPayload;value;constructor(t){this.value=t;try{this.decodedPayload=e.decodeJwt(t)}catch(e){throw new r.OpenfortError("Invalid token format",r.OpenfortErrorType.AUTHENTICATION_ERROR)}}get subject(){return this.decodedPayload.sub}get expiration(){return this.decodedPayload.exp}get issuer(){return this.decodedPayload.iss}isExpired(e=30){return!this.expiration||(t.debugLog("Token expiration:",1e3*(this.expiration-e),"Current time:",Date.now()),Date.now()>=1e3*(this.expiration-e))}static parse(e){try{return new d(e)}catch{return null}}}class c{storage;constructor(e){this.storage=e}async savePKCEData(e){this.storage.save(i.StorageKeys.PKCE_STATE,e.state),this.storage.save(i.StorageKeys.PKCE_VERIFIER,e.verifier)}async getPKCEData(){const e=await this.storage.get(i.StorageKeys.PKCE_STATE),t=await this.storage.get(i.StorageKeys.PKCE_VERIFIER);return e&&t?{state:e,verifier:t}:null}async clearPKCEData(){this.storage.remove(i.StorageKeys.PKCE_STATE),this.storage.remove(i.StorageKeys.PKCE_VERIFIER)}}class u{deviceCredentialsManager;backendApiClientsInstance;publishableKeyInstance;constructor(e){this.deviceCredentialsManager=new c(e)}setBackendApiClients(e,t){this.backendApiClientsInstance=e,this.publishableKeyInstance=t}get backendApiClients(){if(!this.backendApiClientsInstance)throw new r.OpenfortError("Backend API clients not initialized",r.OpenfortErrorType.INTERNAL_ERROR);return this.backendApiClientsInstance}get publishableKey(){if(!this.publishableKeyInstance)throw new r.OpenfortError("Publishable key not initialized",r.OpenfortErrorType.INTERNAL_ERROR);return this.publishableKeyInstance}async initOAuth(e,t,a){const n=t?.usePooling??!1,i=t?.skipBrowserRedirect??!1,{usePooling:o,skipBrowserRedirect:s,...p}=t||{},d={oAuthInitRequest:{provider:e,options:p,usePooling:n}},c=await r.withOpenfortError(async()=>this.backendApiClients.authenticationApi.initOAuth(d,u.getEcosystemGameOptsOrUndefined(a)),{default:r.OpenfortErrorType.AUTHENTICATION_ERROR});return"undefined"==typeof window||i||window.location.assign(c.data.url),{url:c.data.url,key:c.data.key}}async registerGuest(){const e={};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.registerGuest(e)).data,{default:r.OpenfortErrorType.USER_REGISTRATION_ERROR})}async poolOAuth(e){const t={key:e};for(let e=0;e<600;e++)try{const e=await r.withOpenfortError(async()=>this.backendApiClients.authenticationApi.poolOAuth(t),{default:r.OpenfortErrorType.AUTHENTICATION_ERROR});if(200===e.status)return e.data}catch(e){if(e.response&&404===e.response.status){await new Promise(e=>{setTimeout(e,500)});continue}throw e}throw new Error("Failed to pool OAuth, try again later")}async loginWithIdToken(e,t,n){const i={loginWithIdTokenRequest:{provider:e,token:t}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.loginWithIdToken(i,u.getEcosystemGameOptsOrUndefined(n))).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR,401:r.OpenfortErrorType.AUTHENTICATION_ERROR,403:r.OpenfortErrorType.USER_NOT_AUTHORIZED_ON_ECOSYSTEM},e=>{a.sentry.captureAxiosError("loginWithIdToken",e)})}async authenticateThirdParty(e,t,n,i){const o={thirdPartyOAuthRequest:{provider:e,token:t,tokenType:n}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.thirdParty(o,u.getEcosystemGameOptsOrUndefined(i))).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR,401:r.OpenfortErrorType.AUTHENTICATION_ERROR,403:r.OpenfortErrorType.USER_NOT_AUTHORIZED_ON_ECOSYSTEM},e=>{a.sentry.captureAxiosError("authenticateThirdParty",e)})}async initSIWE(e,t){const a={sIWERequest:{address:e}},n=await r.withOpenfortError(async()=>this.backendApiClients.authenticationApi.initSIWE(a,u.getEcosystemGameOptsOrUndefined(t)),{default:r.OpenfortErrorType.AUTHENTICATION_ERROR});return{address:n.data.address,nonce:n.data.nonce,expiresAt:n.data.expiresAt}}async authenticateSIWE(e,t,n,i){const o={sIWEAuthenticateRequest:{signature:e,message:t,walletClientType:n,connectorType:i}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.authenticateSIWE(o)).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR,401:r.OpenfortErrorType.AUTHENTICATION_ERROR,403:r.OpenfortErrorType.USER_NOT_AUTHORIZED_ON_ECOSYSTEM},e=>{a.sentry.captureAxiosError("authenticateSIWE",e)})}static getEcosystemGameOptsOrUndefined(e){if(e)return{headers:{"x-game":e}}}async loginEmailPassword(e,t,n){const i={loginRequest:{email:e,password:t}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.loginEmailPassword(i,u.getEcosystemGameOptsOrUndefined(n))).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR,401:r.OpenfortErrorType.AUTHENTICATION_ERROR,403:r.OpenfortErrorType.USER_NOT_AUTHORIZED_ON_ECOSYSTEM},e=>{a.sentry.captureAxiosError("loginEmailPassword",e)})}async requestResetPassword(t,a){const i=p(32),o=e.base64url.encode(i),d=await s(o),c=e.base64url.encode(d),u=p(32),l=e.base64url.encode(u);await this.deviceCredentialsManager.savePKCEData({state:l,verifier:o});const h={requestResetPasswordRequest:{email:t,redirectUrl:a,challenge:{codeChallenge:c,method:n.CodeChallengeMethodEnum.S256}}};await r.withOpenfortError(async()=>{await this.backendApiClients.authenticationApi.requestResetPassword(h)},{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async resetPassword(e,t,a){return r.withOpenfortError(async()=>{const r=await this.deviceCredentialsManager.getPKCEData();if(!r)throw new Error("No code verifier or state for PKCE");const n={resetPasswordRequest:{email:e,password:t,state:a,challenge:{codeVerifier:r.verifier}}};await this.backendApiClients.authenticationApi.resetPassword(n)},{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async requestEmailVerification(t,a){const i=p(32),o=e.base64url.encode(i),d=await s(o),c=e.base64url.encode(d),u=p(32),l=e.base64url.encode(u);await this.deviceCredentialsManager.savePKCEData({state:l,verifier:o});const h={requestVerifyEmailRequest:{email:t,redirectUrl:a,challenge:{codeChallenge:c,method:n.CodeChallengeMethodEnum.S256}}};await r.withOpenfortError(async()=>{await this.backendApiClients.authenticationApi.requestEmailVerification(h)},{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async verifyEmail(e,t){return r.withOpenfortError(async()=>{const r=await this.deviceCredentialsManager.getPKCEData();if(!r)throw new Error("No code verifier or state for PKCE");const a={verifyEmailRequest:{email:e,token:t,challenge:{codeVerifier:r.verifier}}};await this.backendApiClients.authenticationApi.verifyEmail(a)},{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async signupEmailPassword(e,t,n,i){const o={signupRequest:{email:e,password:t,name:n}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.signupEmailPassword(o,u.getEcosystemGameOptsOrUndefined(i))).data,{default:r.OpenfortErrorType.USER_REGISTRATION_ERROR,401:r.OpenfortErrorType.USER_REGISTRATION_ERROR,403:r.OpenfortErrorType.USER_NOT_AUTHORIZED_ON_ECOSYSTEM},e=>{a.sentry.captureAxiosError("signupEmailPassword",e)})}async validateCredentials(e,a){if(!e.refreshToken)throw new r.OpenfortError("No refresh token provided",r.OpenfortErrorType.AUTHENTICATION_ERROR);if(a)return this.refreshTokens(e.refreshToken,a);t.debugLog("Validating credentials with token:",e.token);const n=d.parse(e.token);return n?n.isExpired()?(t.debugLog("Token expired, refreshing..."),this.refreshTokens(e.refreshToken)):{player:n.subject,accessToken:e.token,refreshToken:e.refreshToken}:this.refreshTokens(e.refreshToken)}async refreshTokens(e,t){const a={refreshTokenRequest:{refreshToken:e,forceRefresh:t}};return r.withOpenfortError(async()=>{const e=await this.backendApiClients.authenticationApi.refresh(a);return{player:e.data.player.id,accessToken:e.data.token,refreshToken:e.data.refreshToken}},{default:r.OpenfortErrorType.REFRESH_TOKEN_ERROR})}async logout(e,t){const a={logoutRequest:{refreshToken:t}};return r.withOpenfortError(async()=>{await this.backendApiClients.authenticationApi.logout(a,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e}})},{default:r.OpenfortErrorType.LOGOUT_ERROR})}async getUser(e){return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.me({headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}})).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async linkThirdParty(e,t,a,n,i){const o={thirdPartyLinkRequest:{provider:t,token:a,tokenType:n}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.linkThirdParty(o,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider||void 0,"x-token-type":e.thirdPartyTokenType||void 0,"x-game":i||void 0}})).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async linkOAuth(e,t,a,n){const i=a?.skipBrowserRedirect??!1;delete a?.skipBrowserRedirect;const o={oAuthInitRequest:{provider:t,options:a,usePooling:a?.usePooling||!1}},s=await r.withOpenfortError(async()=>this.backendApiClients.authenticationApi.linkOAuth(o,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider||void 0,"x-token-type":e.thirdPartyTokenType||void 0,"x-game":n||void 0}}),{default:r.OpenfortErrorType.AUTHENTICATION_ERROR});return"undefined"==typeof window||i||window.location.assign(s.data.url),{url:s.data.url,key:s.data.key}}async unlinkOAuth(e,t){const a={unlinkOAuthRequest:{provider:e}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.unlinkOAuth(a,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t}})).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async unlinkWallet(e,t){const a={sIWERequest:{address:e}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.unlinkSIWE(a,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t}})).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async linkWallet(e,t,a,n,i){const o={sIWEAuthenticateRequest:{signature:e,message:t,walletClientType:a,connectorType:n}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.linkSIWE(o,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":i}})).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async unlinkEmail(e,t){const a={unlinkEmailRequest:{email:e}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.unlinkEmail(a,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t}})).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async linkEmail(e,t,a,n){const i={loginRequest:{email:e,password:t}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.linkEmail(i,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":a,"x-game":n||void 0}})).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}}exports.AuthManager=u;
1
+ "use strict";var e=require("jose"),t=require("../utils/debug.js"),r=require("../core/errors/openfortError.js"),a=require("../core/errors/sentry.js"),n=require("../storage/istorage.js"),i=require("../types/types.js"),o=require("../utils/crypto.js");async function s(e){const t=(new TextEncoder).encode(e),r=await o.cryptoDigest("SHA-256",t);return new Uint8Array(r)}function p(e){const t=new Uint8Array(e);return crypto.getRandomValues(t),t}class d{decodedPayload;value;constructor(t){this.value=t;try{this.decodedPayload=e.decodeJwt(t)}catch(e){throw new r.OpenfortError("Invalid token format",r.OpenfortErrorType.AUTHENTICATION_ERROR)}}get subject(){return this.decodedPayload.sub}get expiration(){return this.decodedPayload.exp}get issuer(){return this.decodedPayload.iss}isExpired(e=30){return!this.expiration||(t.debugLog("Token expiration:",1e3*(this.expiration-e),"Current time:",Date.now()),Date.now()>=1e3*(this.expiration-e))}static parse(e){try{return new d(e)}catch{return null}}}class c{storage;constructor(e){this.storage=e}async savePKCEData(e){this.storage.save(n.StorageKeys.PKCE_STATE,e.state),this.storage.save(n.StorageKeys.PKCE_VERIFIER,e.verifier)}async getPKCEData(){const e=await this.storage.get(n.StorageKeys.PKCE_STATE),t=await this.storage.get(n.StorageKeys.PKCE_VERIFIER);return e&&t?{state:e,verifier:t}:null}async clearPKCEData(){this.storage.remove(n.StorageKeys.PKCE_STATE),this.storage.remove(n.StorageKeys.PKCE_VERIFIER)}}class u{deviceCredentialsManager;backendApiClientsInstance;publishableKeyInstance;constructor(e){this.deviceCredentialsManager=new c(e)}setBackendApiClients(e,t){this.backendApiClientsInstance=e,this.publishableKeyInstance=t}get backendApiClients(){if(!this.backendApiClientsInstance)throw new r.OpenfortError("Backend API clients not initialized",r.OpenfortErrorType.INTERNAL_ERROR);return this.backendApiClientsInstance}get publishableKey(){if(!this.publishableKeyInstance)throw new r.OpenfortError("Publishable key not initialized",r.OpenfortErrorType.INTERNAL_ERROR);return this.publishableKeyInstance}async initOAuth(e,t,a){const n=t?.usePooling??!1,i=t?.skipBrowserRedirect??!1,{usePooling:o,skipBrowserRedirect:s,...p}=t||{},d={oAuthInitRequest:{provider:e,options:p,usePooling:n}},c=await r.withOpenfortError(async()=>this.backendApiClients.authenticationApi.initOAuth(d,u.getEcosystemGameOptsOrUndefined(a)),{default:r.OpenfortErrorType.AUTHENTICATION_ERROR});return"undefined"==typeof window||i||window.location.assign(c.data.url),{url:c.data.url,key:c.data.key}}async registerGuest(){const e={};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.registerGuest(e)).data,{default:r.OpenfortErrorType.USER_REGISTRATION_ERROR})}async poolOAuth(e){const t={key:e};for(let e=0;e<600;e++)try{const e=await r.withOpenfortError(async()=>this.backendApiClients.authenticationApi.poolOAuth(t),{default:r.OpenfortErrorType.AUTHENTICATION_ERROR});if(200===e.status)return e.data}catch(e){if(e.response&&404===e.response.status){await new Promise(e=>{setTimeout(e,500)});continue}throw e}throw new Error("Failed to pool OAuth, try again later")}async loginWithIdToken(e,t,n){const i={loginWithIdTokenRequest:{provider:e,token:t}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.loginWithIdToken(i,u.getEcosystemGameOptsOrUndefined(n))).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR,401:r.OpenfortErrorType.AUTHENTICATION_ERROR,403:r.OpenfortErrorType.USER_NOT_AUTHORIZED_ON_ECOSYSTEM},e=>{a.sentry.captureAxiosError("loginWithIdToken",e)})}async authenticateThirdParty(e,t,n,i){const o={thirdPartyOAuthRequest:{provider:e,token:t,tokenType:n}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.thirdParty(o,u.getEcosystemGameOptsOrUndefined(i))).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR,401:r.OpenfortErrorType.AUTHENTICATION_ERROR,403:r.OpenfortErrorType.USER_NOT_AUTHORIZED_ON_ECOSYSTEM},e=>{a.sentry.captureAxiosError("authenticateThirdParty",e)})}async initSIWE(e,t){const a={sIWERequest:{address:e}},n=await r.withOpenfortError(async()=>this.backendApiClients.authenticationApi.initSIWE(a,u.getEcosystemGameOptsOrUndefined(t)),{default:r.OpenfortErrorType.AUTHENTICATION_ERROR});return{address:n.data.address,nonce:n.data.nonce,expiresAt:n.data.expiresAt}}async authenticateSIWE(e,t,n,i){const o={sIWEAuthenticateRequest:{signature:e,message:t,walletClientType:n,connectorType:i}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.authenticateSIWE(o)).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR,401:r.OpenfortErrorType.AUTHENTICATION_ERROR,403:r.OpenfortErrorType.USER_NOT_AUTHORIZED_ON_ECOSYSTEM},e=>{a.sentry.captureAxiosError("authenticateSIWE",e)})}static getEcosystemGameOptsOrUndefined(e){if(e)return{headers:{"x-game":e}}}async loginEmailPassword(e,t,n){const i={loginRequest:{email:e,password:t}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.loginEmailPassword(i,u.getEcosystemGameOptsOrUndefined(n))).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR,401:r.OpenfortErrorType.AUTHENTICATION_ERROR,403:r.OpenfortErrorType.USER_NOT_AUTHORIZED_ON_ECOSYSTEM},e=>{a.sentry.captureAxiosError("loginEmailPassword",e)})}async requestResetPassword(t,a){const n=p(32),o=e.base64url.encode(n),d=await s(o),c=e.base64url.encode(d),u=p(32),l=e.base64url.encode(u);await this.deviceCredentialsManager.savePKCEData({state:l,verifier:o});const h={requestResetPasswordRequest:{email:t,redirectUrl:a,challenge:{codeChallenge:c,method:i.CodeChallengeMethodEnum.S256}}};await r.withOpenfortError(async()=>{await this.backendApiClients.authenticationApi.requestResetPassword(h)},{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async resetPassword(e,t,a){return r.withOpenfortError(async()=>{const r=await this.deviceCredentialsManager.getPKCEData();if(!r)throw new Error("No code verifier or state for PKCE");const n={resetPasswordRequest:{email:e,password:t,state:a,challenge:{codeVerifier:r.verifier}}};await this.backendApiClients.authenticationApi.resetPassword(n)},{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async requestEmailVerification(t,a){const n=p(32),o=e.base64url.encode(n),d=await s(o),c=e.base64url.encode(d),u=p(32),l=e.base64url.encode(u);await this.deviceCredentialsManager.savePKCEData({state:l,verifier:o});const h={requestVerifyEmailRequest:{email:t,redirectUrl:a,challenge:{codeChallenge:c,method:i.CodeChallengeMethodEnum.S256}}};await r.withOpenfortError(async()=>{await this.backendApiClients.authenticationApi.requestEmailVerification(h)},{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async verifyEmail(e,t){return r.withOpenfortError(async()=>{const r=await this.deviceCredentialsManager.getPKCEData();if(!r)throw new Error("No code verifier or state for PKCE");const a={verifyEmailRequest:{email:e,token:t,challenge:{codeVerifier:r.verifier}}};await this.backendApiClients.authenticationApi.verifyEmail(a)},{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async signupEmailPassword(e,t,n,i){const o={signupRequest:{email:e,password:t,name:n}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.signupEmailPassword(o,u.getEcosystemGameOptsOrUndefined(i))).data,{default:r.OpenfortErrorType.USER_REGISTRATION_ERROR,401:r.OpenfortErrorType.USER_REGISTRATION_ERROR,403:r.OpenfortErrorType.USER_NOT_AUTHORIZED_ON_ECOSYSTEM},e=>{a.sentry.captureAxiosError("signupEmailPassword",e)})}async validateCredentials(e,a){if(!e.refreshToken)throw new r.OpenfortError("No refresh token provided",r.OpenfortErrorType.AUTHENTICATION_ERROR);if(a)return this.refreshTokens(e.refreshToken,a);t.debugLog("Validating credentials with token:",e.token);const n=d.parse(e.token);return n?n.isExpired()?(t.debugLog("Token expired, refreshing..."),this.refreshTokens(e.refreshToken)):{player:n.subject,accessToken:e.token,refreshToken:e.refreshToken}:this.refreshTokens(e.refreshToken)}async refreshTokens(e,t){const a={refreshTokenRequest:{refreshToken:e,forceRefresh:t}};return r.withOpenfortError(async()=>{const e=await this.backendApiClients.authenticationApi.refresh(a);return{player:e.data.player.id,accessToken:e.data.token,refreshToken:e.data.refreshToken}},{default:r.OpenfortErrorType.REFRESH_TOKEN_ERROR})}async logout(e,t){const a={logoutRequest:{refreshToken:t}};return r.withOpenfortError(async()=>{await this.backendApiClients.authenticationApi.logout(a,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e}})},{default:r.OpenfortErrorType.LOGOUT_ERROR})}async getUser(e){return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.me({headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider,"x-token-type":e.thirdPartyTokenType}})).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async linkThirdParty(e,t,a,n,i){const o={thirdPartyLinkRequest:{provider:t,token:a,tokenType:n}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.linkThirdParty(o,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider||void 0,"x-token-type":e.thirdPartyTokenType||void 0,"x-game":i||void 0}})).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async linkOAuth(e,t,a,n){const i=a?.skipBrowserRedirect??!1;delete a?.skipBrowserRedirect;const o={oAuthInitRequest:{provider:t,options:a,usePooling:a?.usePooling||!1}},s=await r.withOpenfortError(async()=>this.backendApiClients.authenticationApi.linkOAuth(o,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e.token,"x-auth-provider":e.thirdPartyProvider||void 0,"x-token-type":e.thirdPartyTokenType||void 0,"x-game":n||void 0}}),{default:r.OpenfortErrorType.AUTHENTICATION_ERROR});return"undefined"==typeof window||i||window.location.assign(s.data.url),{url:s.data.url,key:s.data.key}}async unlinkOAuth(e,t){const a={unlinkOAuthRequest:{provider:e}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.unlinkOAuth(a,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t}})).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async unlinkWallet(e,t){const a={sIWERequest:{address:e}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.unlinkSIWE(a,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t}})).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async linkWallet(e,t,a,n,i){const o={sIWEAuthenticateRequest:{signature:e,message:t,walletClientType:a,connectorType:n}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.linkSIWE(o,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":i}})).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async unlinkEmail(e,t){const a={unlinkEmailRequest:{email:e}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.unlinkEmail(a,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t}})).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async linkEmail(e,t,a,n){const i={loginRequest:{email:e,password:t}};return r.withOpenfortError(async()=>(await this.backendApiClients.authenticationApi.linkEmail(i,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":a,"x-game":n||void 0}})).data,{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}}exports.AuthManager=u;
@@ -1 +1 @@
1
- "use strict";require("../errors/openfortError.js");var e=require("../../types/types.js"),r=require("../../storage/istorage.js");require("../../wallets/messaging/browserMessenger/backwardCompatibility.js"),require("../../wallets/types.js"),require("../errors/sentry.js"),require("jose"),require("human-id"),require("../../wallets/evm/types.js"),require("../../wallets/evm/JsonRpcError.js"),require("eventemitter3"),require("../../wallets/evm/provider/eip6963.js");class t{constructor(e){this.user=e.user,this.id=e.id,this.chainType=e.chainType,this.address=e.address,this.accountType=e.accountType,this.chainId=e.chainId,this.createdAt=e.createdAt,this.implementationType=e.implementationType,this.factoryAddress=e.factoryAddress,this.recoveryMethod=e.recoveryMethod,this.recoveryMethodDetails=e.recoveryMethodDetails,this.salt=e.salt,this.ownerAddress=e.ownerAddress,this.type=e.type}user;id;chainType;address;accountType;chainId;ownerAddress;factoryAddress;salt;createdAt;implementationType;recoveryMethod;recoveryMethodDetails;type;save(e){e.save(r.StorageKeys.ACCOUNT,JSON.stringify({user:this.user,id:this.id,chainType:this.chainType,address:this.address,accountType:this.accountType,chainId:this.chainId,ownerAddress:this.ownerAddress,createdAt:this.createdAt,implementationType:this.implementationType,factoryAddress:this.factoryAddress,salt:this.salt,recoveryMethod:this.recoveryMethod,recoveryMethodDetails:this.recoveryMethodDetails}))}static parseRecoveryMethod=r=>{switch(r){case"user":case e.RecoveryMethod.PASSWORD:return e.RecoveryMethod.PASSWORD;case"project":case e.RecoveryMethod.AUTOMATIC:return e.RecoveryMethod.AUTOMATIC;case"passkey":case e.RecoveryMethod.PASSKEY:return e.RecoveryMethod.PASSKEY;default:return}};static async fromStorage(e){const s=await e.get(r.StorageKeys.ACCOUNT);if(!s)return null;try{const e=JSON.parse(s);return new t(e)}catch{return null}}}exports.Account=t;
1
+ "use strict";var e=require("../../storage/istorage.js");require("../errors/openfortError.js");var r=require("../../types/types.js");require("human-id"),require("eventemitter3"),require("../../wallets/evm/JsonRpcError.js"),require("../../wallets/evm/types.js"),require("../../wallets/evm/provider/eip6963.js"),require("../errors/sentry.js"),require("../../wallets/messaging/browserMessenger/backwardCompatibility.js"),require("../../wallets/types.js"),require("jose");class t{constructor(e){this.user=e.user,this.id=e.id,this.chainType=e.chainType,this.address=e.address,this.accountType=e.accountType,this.chainId=e.chainId,this.createdAt=e.createdAt,this.implementationType=e.implementationType,this.factoryAddress=e.factoryAddress,this.recoveryMethod=e.recoveryMethod,this.recoveryMethodDetails=e.recoveryMethodDetails,this.salt=e.salt,this.ownerAddress=e.ownerAddress,this.type=e.type}user;id;chainType;address;accountType;chainId;ownerAddress;factoryAddress;salt;createdAt;implementationType;recoveryMethod;recoveryMethodDetails;type;save(r){r.save(e.StorageKeys.ACCOUNT,JSON.stringify({user:this.user,id:this.id,chainType:this.chainType,address:this.address,accountType:this.accountType,chainId:this.chainId,ownerAddress:this.ownerAddress,createdAt:this.createdAt,implementationType:this.implementationType,factoryAddress:this.factoryAddress,salt:this.salt,recoveryMethod:this.recoveryMethod,recoveryMethodDetails:this.recoveryMethodDetails}))}static parseRecoveryMethod=e=>{switch(e){case"user":case r.RecoveryMethod.PASSWORD:return r.RecoveryMethod.PASSWORD;case"project":case r.RecoveryMethod.AUTOMATIC:return r.RecoveryMethod.AUTOMATIC;case"passkey":case r.RecoveryMethod.PASSKEY:return r.RecoveryMethod.PASSKEY;default:return}};static async fromStorage(r){const s=await r.get(e.StorageKeys.ACCOUNT);if(!s)return null;try{const e=JSON.parse(s);return new t(e)}catch{return null}}}exports.Account=t;
@@ -1 +1 @@
1
- "use strict";var R,E=require("axios");exports.OpenfortErrorType=void 0,(R=exports.OpenfortErrorType||(exports.OpenfortErrorType={})).AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",R.INVALID_CONFIGURATION="INVALID_CONFIGURATION",R.NOT_LOGGED_IN_ERROR="NOT_LOGGED_IN_ERROR",R.ALREADY_LOGGED_IN_ERROR="ALREADY_LOGGED_IN_ERROR",R.REFRESH_TOKEN_ERROR="REFRESH_TOKEN_ERROR",R.USER_REGISTRATION_ERROR="USER_REGISTRATION_ERROR",R.LOGOUT_ERROR="LOGOUT_ERROR",R.OPERATION_NOT_SUPPORTED_ERROR="OPERATION_NOT_SUPPORTED_ERROR",R.MISSING_SIGNER_ERROR="MISSING_SIGNER_ERROR",R.USER_NOT_AUTHORIZED_ON_ECOSYSTEM="USER_NOT_AUTHORIZED_ON_ECOSYSTEM",R.INTERNAL_ERROR="INTERNAL_ERROR";class O extends Error{type;data;constructor(R,E,O={}){super(R),this.type=E,this.data=O}}exports.OpenfortError=O,exports.withOpenfortError=async(R,r,e)=>{try{return await R()}catch(R){let _;const t={};let s;E.isAxiosError(R)?(s=R.response?.status,_=R.response?.data&&R.response.data.error&&function(R){return"type"in R&&"message"in R}(R.response.data.error)?R.response.data.error.message:R.message):_=R.message;const o=void 0!==s&&r[s]?r[s]:r.default,N=new O(_,o,t);throw void 0!==s&&r[s]||e?.(R,N),N}};
1
+ "use strict";var R,E=require("axios");exports.OpenfortErrorType=void 0,(R=exports.OpenfortErrorType||(exports.OpenfortErrorType={})).AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",R.INVALID_CONFIGURATION="INVALID_CONFIGURATION",R.NOT_LOGGED_IN_ERROR="NOT_LOGGED_IN_ERROR",R.ALREADY_LOGGED_IN_ERROR="ALREADY_LOGGED_IN_ERROR",R.REFRESH_TOKEN_ERROR="REFRESH_TOKEN_ERROR",R.USER_REGISTRATION_ERROR="USER_REGISTRATION_ERROR",R.LOGOUT_ERROR="LOGOUT_ERROR",R.OPERATION_NOT_SUPPORTED_ERROR="OPERATION_NOT_SUPPORTED_ERROR",R.MISSING_SIGNER_ERROR="MISSING_SIGNER_ERROR",R.USER_NOT_AUTHORIZED_ON_ECOSYSTEM="USER_NOT_AUTHORIZED_ON_ECOSYSTEM",R.INTERNAL_ERROR="INTERNAL_ERROR";class O extends Error{type;data;constructor(R,E,O={}){super(R),this.type=E,this.data=O}}exports.OpenfortError=O,exports.withOpenfortError=async(R,r,e)=>{try{return await R()}catch(R){let _;const t={};let s;E.isAxiosError(R)?(s=R.response?.status,_=R.response?.data?.error&&function(R){return"type"in R&&"message"in R}(R.response.data.error)?R.response.data.error.message:R.message):_=R.message;const N=void 0!==s&&r[s]?r[s]:r.default,o=new O(_,N,t);throw void 0!==s&&r[s]||e?.(R,o),o}};
@@ -1 +1 @@
1
- "use strict";var t=require("axios"),s=require("../../version.js");const e="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class r{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(s){const r=s.getDsn();if(!r)throw new Error("Sentry DSN is not set");if(r.projectId!==e.split("https://")[1].split("/")[1]||r.host!==e.split("@")[1].split("/")[0]||r.publicKey!==e.split("@")[0].split("https://")[1])throw new Error("Sentry DSN is not valid");s.captureAxiosError=(e,r,n,a)=>{r instanceof t.AxiosError?(r.name=e,s.captureException(r,{...n,captureContext:{...n?.captureContext,extra:{errorResponseData:r.response?.data,errorStatus:r.response?.status,errorHeaders:r.response?.headers,errorRequest:r.request},tags:{...this.baseTags,method:e}}})):s.captureException(r,n,a)},this.sentryInstance=s}static get sentry(){return this.proxy}static async init({sentry:t,configuration:r}){if(t)return void(this.sentry=t);const n=await import("@sentry/browser");this.sentry=new n.BrowserClient({dsn:e,integrations:[],stackParser:n.defaultStackParser,transport:n.makeFetchTransport}),this.baseTags={projectId:r?.baseConfiguration.publishableKey,sdk:s.PACKAGE,sdkVersion:s.VERSION},this.processQueuedCalls()}static proxy=new Proxy({},{get:(t,s)=>r.sentryInstance&&"function"==typeof r.sentryInstance[s]?(...t)=>r.sentryInstance[s](...t):(...t)=>{r.queuedCalls.push({fn:s,args:t})}});static processQueuedCalls(){this.sentryInstance&&(this.queuedCalls.forEach(({fn:t,args:s})=>{"function"==typeof this.sentryInstance[t]&&this.sentryInstance[t](...s)}),this.queuedCalls=[])}}const{sentry:n}=r;exports.InternalSentry=r,exports.sentry=n;
1
+ "use strict";var t=require("axios"),e=require("../../version.js");const s="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class r{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(e){const n=e.getDsn();if(!n)throw new Error("Sentry DSN is not set");if(n.projectId!==s.split("https://")[1].split("/")[1]||n.host!==s.split("@")[1].split("/")[0]||n.publicKey!==s.split("@")[0].split("https://")[1])throw new Error("Sentry DSN is not valid");e.captureAxiosError=(s,n,a,o)=>{n instanceof t.AxiosError?(n.name=s,e.captureException(n,{...a,captureContext:{...a?.captureContext,extra:{errorResponseData:n.response?.data,errorStatus:n.response?.status,errorHeaders:n.response?.headers,errorRequest:n.request},tags:{...r.baseTags,method:s}}})):e.captureException(n,a,o)},r.sentryInstance=e}static get sentry(){return r.proxy}static async init({sentry:t,configuration:n}){if(t)return void(r.sentry=t);const a=await import("@sentry/browser");r.sentry=new a.BrowserClient({dsn:s,integrations:[],stackParser:a.defaultStackParser,transport:a.makeFetchTransport}),r.baseTags={projectId:n?.baseConfiguration.publishableKey,sdk:e.PACKAGE,sdkVersion:e.VERSION},r.processQueuedCalls()}static proxy=new Proxy({},{get:(t,e)=>r.sentryInstance&&"function"==typeof r.sentryInstance[e]?(...t)=>r.sentryInstance[e](...t):(...t)=>{r.queuedCalls.push({fn:e,args:t})}});static processQueuedCalls(){r.sentryInstance&&(r.queuedCalls.forEach(({fn:t,args:e})=>{"function"==typeof r.sentryInstance[t]&&r.sentryInstance[t](...e)}),r.queuedCalls=[])}}const{sentry:n}=r;exports.InternalSentry=r,exports.sentry=n;
@@ -1 +1 @@
1
- "use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.js"),t=require("./errors/sentry.js"),i=require("../storage/istorage.js"),n=require("../storage/lazyStorage.js"),r=require("./errors/openfortError.js"),a=require("./config/config.js"),s=require("../auth/authManager.js"),o=require("../api/auth.js"),h=require("./configuration/passkey.js"),l=require("../api/embeddedWallet.js"),c=require("../api/user.js"),u=require("../api/proxy.js"),d=require("./openfortInternal.js"),p=require("../utils/typedEventEmitter.js");class I{storage;iAuthManager=null;openfortInternal;initPromise;asyncInitPromise=null;authInstance;embeddedWalletInstance;userInstance;proxyInstance;configuration;eventEmitter;iPasskeyHandler;get auth(){if(!this.authInstance)throw new r.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.",r.OpenfortErrorType.INVALID_CONFIGURATION);return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new r.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.",r.OpenfortErrorType.INVALID_CONFIGURATION);return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new r.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.",r.OpenfortErrorType.INVALID_CONFIGURATION);return this.userInstance}get proxy(){if(!this.proxyInstance)throw new r.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.",r.OpenfortErrorType.INVALID_CONFIGURATION);return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new s.AuthManager(this.storage),this.openfortInternal=new d.OpenfortInternal(this.storage,this.authManager,this.eventEmitter),this.authInstance=new o.AuthApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter),this.embeddedWalletInstance=new l.EmbeddedWalletApi(this.storage,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),this.eventEmitter,this.passkeyHandler),this.userInstance=new c.UserApi(this.storage,this.authManager,this.validateAndRefreshToken.bind(this)),this.proxyInstance=new u.ProxyApi(this.storage,this.backendApiClients,this.validateAndRefreshToken.bind(this),this.ensureInitialized.bind(this),async()=>{if(!this.embeddedWalletInstance)throw new r.OpenfortError("Embedded wallet not initialized",r.OpenfortErrorType.MISSING_SIGNER_ERROR);const e=this.embeddedWalletInstance;return t=>e.signMessage(t,{hashMessage:!0,arrayifyMessage:!0})})}catch(e){throw new r.OpenfortError("Openfort SDK synchronous initialization failed",r.OpenfortErrorType.INVALID_CONFIGURATION)}}constructor(e){this.configuration=new a.SDKConfiguration(e),this.storage=new n.LazyStorage(this.configuration.storage),this.eventEmitter=new p,this.iPasskeyHandler=new h.PasskeyHandler({rpId:this.configuration.passkeyRpId,rpName:this.configuration.passkeyRpName,extractableKey:!0}),t.InternalSentry.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}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})}get authManager(){if(!this.iAuthManager)throw new r.OpenfortError("AuthManager not initialized",r.OpenfortErrorType.INTERNAL_ERROR);return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(e){try{const t=i.StorageKeys.TEST,n="openfort_storage_test";e.save(t,n);const r=await e.get(t);return e.remove(t),r===n}catch(e){return!1}}async initializeAsync(){try{if(!await I.isStorageAccessible(this.storage))throw new r.OpenfortError("Storage is not accessible",r.OpenfortErrorType.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}catch(e){throw new r.OpenfortError("Openfort SDK async initialization failed",r.OpenfortErrorType.INTERNAL_ERROR)}}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}exports.Openfort=I;
1
+ "use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.js"),t=require("../api/auth.js"),i=require("../api/embeddedWallet.js"),n=require("../api/proxy.js"),r=require("../api/user.js"),a=require("../auth/authManager.js"),s=require("../storage/istorage.js"),o=require("../storage/lazyStorage.js"),h=require("../utils/typedEventEmitter.js"),l=require("./config/config.js"),c=require("./configuration/passkey.js"),u=require("./errors/openfortError.js"),d=require("./errors/sentry.js"),p=require("./openfortInternal.js");class I{storage;iAuthManager=null;openfortInternal;initPromise;asyncInitPromise=null;authInstance;embeddedWalletInstance;userInstance;proxyInstance;configuration;eventEmitter;iPasskeyHandler;get auth(){if(!this.authInstance)throw new u.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing auth.",u.OpenfortErrorType.INVALID_CONFIGURATION);return this.authInstance}get embeddedWallet(){if(!this.embeddedWalletInstance)throw new u.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing embeddedWallet.",u.OpenfortErrorType.INVALID_CONFIGURATION);return this.embeddedWalletInstance}get user(){if(!this.userInstance)throw new u.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing user.",u.OpenfortErrorType.INVALID_CONFIGURATION);return this.userInstance}get proxy(){if(!this.proxyInstance)throw new u.OpenfortError("Openfort SDK not initialized. Please await waitForInitialization() before accessing proxy.",u.OpenfortErrorType.INVALID_CONFIGURATION);return this.proxyInstance}initializeSynchronously(){try{this.iAuthManager=new a.AuthManager(this.storage),this.openfortInternal=new p.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 r.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.OpenfortError("Embedded wallet not initialized",u.OpenfortErrorType.MISSING_SIGNER_ERROR);const e=this.embeddedWalletInstance;return t=>e.signMessage(t,{hashMessage:!0,arrayifyMessage:!0})})}catch(e){throw new u.OpenfortError("Openfort SDK synchronous initialization failed",u.OpenfortErrorType.INVALID_CONFIGURATION)}}constructor(e){this.configuration=new l.SDKConfiguration(e),this.storage=new o.LazyStorage(this.configuration.storage),this.eventEmitter=new h,this.iPasskeyHandler=new c.PasskeyHandler({rpId:this.configuration.passkeyRpId,rpName:this.configuration.passkeyRpName,extractableKey:!0}),d.InternalSentry.init({configuration:this.configuration}),this.initializeSynchronously(),this.initPromise=Promise.resolve()}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})}get authManager(){if(!this.iAuthManager)throw new u.OpenfortError("AuthManager not initialized",u.OpenfortErrorType.INTERNAL_ERROR);return this.iAuthManager}get passkeyHandler(){return this.iPasskeyHandler}static async isStorageAccessible(e){try{const t=s.StorageKeys.TEST,i="openfort_storage_test";e.save(t,i);const n=await e.get(t);return e.remove(t),n===i}catch(e){return!1}}async initializeAsync(){try{if(!await I.isStorageAccessible(this.storage))throw new u.OpenfortError("Storage is not accessible",u.OpenfortErrorType.INVALID_CONFIGURATION);this.authManager.setBackendApiClients(this.backendApiClients,this.configuration.baseConfiguration.publishableKey)}catch(e){throw new u.OpenfortError("Openfort SDK async initialization failed",u.OpenfortErrorType.INTERNAL_ERROR)}}async ensureAsyncInitialized(){this.asyncInitPromise||(this.asyncInitPromise=this.initializeAsync()),await this.asyncInitPromise}async ensureInitialized(){await this.initPromise,await this.ensureAsyncInitialized()}}exports.Openfort=I;
@@ -1 +1 @@
1
- "use strict";var e=require("./errors/openfortError.js"),r=require("../types/types.js");require("../storage/istorage.js"),require("../wallets/messaging/browserMessenger/backwardCompatibility.js");var t=require("../utils/debug.js"),n=require("./configuration/authentication.js");require("../wallets/types.js"),require("./errors/sentry.js");var i=require("./config/config.js");require("jose"),require("human-id"),require("../wallets/evm/types.js"),require("../wallets/evm/JsonRpcError.js"),require("eventemitter3"),require("../wallets/evm/provider/eip6963.js");exports.OpenfortInternal=class{storage;authManager;eventEmitter;constructor(e,r,t){this.storage=e,this.authManager=r,this.eventEmitter=t}async getThirdPartyAuthToken(){const t=i.SDKConfiguration.getInstance();if(!t?.thirdPartyAuth)throw new e.OpenfortError("No third party configuration found",e.OpenfortErrorType.INTERNAL_ERROR);const{getAccessToken:o,provider:a}=t.thirdPartyAuth;if(!o||!a)throw new e.OpenfortError("Third party is not configured. Please configure getAccessToken and thirdPartyAuthProvider in your Openfort instance",e.OpenfortErrorType.INVALID_CONFIGURATION);const s=await o();if(!s)throw new e.OpenfortError("Could not get access token",e.OpenfortErrorType.AUTHENTICATION_ERROR);let u=(await n.Authentication.fromStorage(this.storage))?.player;if(!u){const e=await this.authManager.authenticateThirdParty(a,s,r.TokenType.ID_TOKEN);u=e?.id}return new n.Authentication("third_party",s,u,null,a,r.TokenType.ID_TOKEN).save(this.storage),s}async getAccessToken(){if(i.SDKConfiguration.getInstance()?.thirdPartyAuth)return this.getThirdPartyAuthToken();return(await n.Authentication.fromStorage(this.storage))?.token??null}async validateAndRefreshToken(o){if(i.SDKConfiguration.getInstance()?.thirdPartyAuth)return void await this.getThirdPartyAuthToken();const a=await n.Authentication.fromStorage(this.storage);if(!a)throw new e.OpenfortError("Must be logged in to validate and refresh token",e.OpenfortErrorType.NOT_LOGGED_IN_ERROR);let s;t.debugLog("validating credentials...");try{s=await this.authManager.validateCredentials(a,o)}catch(e){throw n.Authentication.clear(this.storage),this.eventEmitter.emit(r.OpenfortEvents.LOGGED_OUT),e}if(!s.player)throw new e.OpenfortError("No user found in credentials",e.OpenfortErrorType.INTERNAL_ERROR);s.accessToken!==a.token&&(t.debugLog("tokens refreshed"),new n.Authentication("jwt",s.accessToken,s.player,s.refreshToken).save(this.storage))}};
1
+ "use strict";var e=require("./configuration/authentication.js"),r=require("./errors/openfortError.js"),t=require("../types/types.js");require("human-id");var n=require("./config/config.js");require("../storage/istorage.js");var i=require("../utils/debug.js");require("eventemitter3"),require("../wallets/evm/JsonRpcError.js"),require("../wallets/evm/types.js"),require("../wallets/evm/provider/eip6963.js"),require("./errors/sentry.js"),require("../wallets/messaging/browserMessenger/backwardCompatibility.js"),require("../wallets/types.js"),require("jose");exports.OpenfortInternal=class{storage;authManager;eventEmitter;constructor(e,r,t){this.storage=e,this.authManager=r,this.eventEmitter=t}async getThirdPartyAuthToken(){const i=n.SDKConfiguration.getInstance();if(!i?.thirdPartyAuth)throw new r.OpenfortError("No third party configuration found",r.OpenfortErrorType.INTERNAL_ERROR);const{getAccessToken:o,provider:a}=i.thirdPartyAuth;if(!o||!a)throw new r.OpenfortError("Third party is not configured. Please configure getAccessToken and thirdPartyAuthProvider in your Openfort instance",r.OpenfortErrorType.INVALID_CONFIGURATION);const s=await o();if(!s)throw new r.OpenfortError("Could not get access token",r.OpenfortErrorType.AUTHENTICATION_ERROR);let u=(await e.Authentication.fromStorage(this.storage))?.player;if(!u){const e=await this.authManager.authenticateThirdParty(a,s,t.TokenType.ID_TOKEN);u=e?.id}return new e.Authentication("third_party",s,u,null,a,t.TokenType.ID_TOKEN).save(this.storage),s}async getAccessToken(){if(n.SDKConfiguration.getInstance()?.thirdPartyAuth)return this.getThirdPartyAuthToken();return(await e.Authentication.fromStorage(this.storage))?.token??null}async validateAndRefreshToken(o){if(n.SDKConfiguration.getInstance()?.thirdPartyAuth)return void await this.getThirdPartyAuthToken();const a=await e.Authentication.fromStorage(this.storage);if(!a)throw new r.OpenfortError("Must be logged in to validate and refresh token",r.OpenfortErrorType.NOT_LOGGED_IN_ERROR);let s;i.debugLog("validating credentials...");try{s=await this.authManager.validateCredentials(a,o)}catch(r){throw e.Authentication.clear(this.storage),this.eventEmitter.emit(t.OpenfortEvents.LOGGED_OUT),r}if(!s.player)throw new r.OpenfortError("No user found in credentials",r.OpenfortErrorType.INTERNAL_ERROR);s.accessToken!==a.token&&(i.debugLog("tokens refreshed"),new e.Authentication("jwt",s.accessToken,s.player,s.refreshToken).save(this.storage))}};
@@ -1 +1 @@
1
- "use strict";var e=require("./core/errors/openfortError.js"),r=require("./types/types.js"),t=require("./wallets/iframeManager.js"),o=require("./core/config/config.js"),n=require("./core/openfort.js"),i=require("./api/auth.js"),p=require("./api/embeddedWallet.js"),u=require("./api/user.js"),s=require("./core/openfortInternal.js"),d=require("./api/proxy.js");exports.OpenfortError=e.OpenfortError,Object.defineProperty(exports,"OpenfortErrorType",{enumerable:!0,get:function(){return e.OpenfortErrorType}}),Object.defineProperty(exports,"AccountTypeEnum",{enumerable:!0,get:function(){return r.AccountTypeEnum}}),Object.defineProperty(exports,"AuthActionRequiredActions",{enumerable:!0,get:function(){return r.AuthActionRequiredActions}}),Object.defineProperty(exports,"AuthType",{enumerable:!0,get:function(){return r.AuthType}}),Object.defineProperty(exports,"BasicAuthProvider",{enumerable:!0,get:function(){return r.BasicAuthProvider}}),Object.defineProperty(exports,"ChainTypeEnum",{enumerable:!0,get:function(){return r.ChainTypeEnum}}),Object.defineProperty(exports,"EmbeddedState",{enumerable:!0,get:function(){return r.EmbeddedState}}),Object.defineProperty(exports,"OAuthProvider",{enumerable:!0,get:function(){return r.OAuthProvider}}),Object.defineProperty(exports,"RecoveryMethod",{enumerable:!0,get:function(){return r.RecoveryMethod}}),Object.defineProperty(exports,"ThirdPartyOAuthProvider",{enumerable:!0,get:function(){return r.ThirdPartyAuthProvider}}),Object.defineProperty(exports,"TokenType",{enumerable:!0,get:function(){return r.TokenType}}),exports.MissingProjectEntropyError=t.MissingProjectEntropyError,exports.MissingRecoveryPasswordError=t.MissingRecoveryPasswordError,exports.NotConfiguredError=t.NotConfiguredError,exports.OTPRequiredError=t.OTPRequiredError,exports.WrongRecoveryPasswordError=t.WrongRecoveryPasswordError,exports.OpenfortConfiguration=o.OpenfortConfiguration,exports.SDKConfiguration=o.SDKConfiguration,exports.ShieldConfiguration=o.ShieldConfiguration,exports.Openfort=n.Openfort,exports.AuthApi=i.AuthApi,exports.EmbeddedWalletApi=p.EmbeddedWalletApi,exports.UserApi=u.UserApi,exports.OpenfortInternal=s.OpenfortInternal,exports.ProxyApi=d.ProxyApi;
1
+ "use strict";var e=require("./api/auth.js"),r=require("./api/embeddedWallet.js"),t=require("./api/proxy.js"),o=require("./api/user.js"),n=require("./core/openfort.js"),i=require("./core/config/config.js"),p=require("./core/errors/openfortError.js"),u=require("./core/openfortInternal.js"),s=require("./wallets/iframeManager.js"),d=require("./types/types.js");exports.AuthApi=e.AuthApi,exports.EmbeddedWalletApi=r.EmbeddedWalletApi,exports.ProxyApi=t.ProxyApi,exports.UserApi=o.UserApi,exports.Openfort=n.Openfort,exports.OpenfortConfiguration=i.OpenfortConfiguration,exports.SDKConfiguration=i.SDKConfiguration,exports.ShieldConfiguration=i.ShieldConfiguration,exports.OpenfortError=p.OpenfortError,Object.defineProperty(exports,"OpenfortErrorType",{enumerable:!0,get:function(){return p.OpenfortErrorType}}),exports.OpenfortInternal=u.OpenfortInternal,exports.MissingProjectEntropyError=s.MissingProjectEntropyError,exports.MissingRecoveryPasswordError=s.MissingRecoveryPasswordError,exports.NotConfiguredError=s.NotConfiguredError,exports.OTPRequiredError=s.OTPRequiredError,exports.WrongRecoveryPasswordError=s.WrongRecoveryPasswordError,Object.defineProperty(exports,"AccountTypeEnum",{enumerable:!0,get:function(){return d.AccountTypeEnum}}),Object.defineProperty(exports,"AuthActionRequiredActions",{enumerable:!0,get:function(){return d.AuthActionRequiredActions}}),Object.defineProperty(exports,"AuthType",{enumerable:!0,get:function(){return d.AuthType}}),Object.defineProperty(exports,"BasicAuthProvider",{enumerable:!0,get:function(){return d.BasicAuthProvider}}),Object.defineProperty(exports,"ChainTypeEnum",{enumerable:!0,get:function(){return d.ChainTypeEnum}}),Object.defineProperty(exports,"EmbeddedState",{enumerable:!0,get:function(){return d.EmbeddedState}}),Object.defineProperty(exports,"OAuthProvider",{enumerable:!0,get:function(){return d.OAuthProvider}}),Object.defineProperty(exports,"RecoveryMethod",{enumerable:!0,get:function(){return d.RecoveryMethod}}),Object.defineProperty(exports,"ThirdPartyOAuthProvider",{enumerable:!0,get:function(){return d.ThirdPartyAuthProvider}}),Object.defineProperty(exports,"TokenType",{enumerable:!0,get:function(){return d.TokenType}});
@@ -1 +1 @@
1
- "use strict";var e=require("./storage.js"),r=require("../core/errors/openfortError.js");exports.LazyStorage=class{realStorage=null;customStorage;constructor(e){this.customStorage=e}getRealStorage(){if(!this.realStorage)if(this.customStorage)this.realStorage=this.customStorage;else{if("undefined"==typeof window||"undefined"==typeof localStorage)throw new r.OpenfortError("Storage not available. Please provide custom storage or use in browser environment.",r.OpenfortErrorType.INVALID_CONFIGURATION);this.realStorage=new e.StorageImplementation(localStorage)}return this.realStorage}async get(e){return this.getRealStorage().get(e)}save(e,r){this.getRealStorage().save(e,r)}remove(e){this.getRealStorage().remove(e)}flush(){this.getRealStorage().flush()}};
1
+ "use strict";var e=require("../core/errors/openfortError.js"),r=require("./storage.js");exports.LazyStorage=class{realStorage=null;customStorage;constructor(e){this.customStorage=e}getRealStorage(){if(!this.realStorage)if(this.customStorage)this.realStorage=this.customStorage;else{if("undefined"==typeof window||"undefined"==typeof localStorage)throw new e.OpenfortError("Storage not available. Please provide custom storage or use in browser environment.",e.OpenfortErrorType.INVALID_CONFIGURATION);this.realStorage=new r.StorageImplementation(localStorage)}return this.realStorage}async get(e){return this.getRealStorage().get(e)}save(e,r){this.getRealStorage().save(e,r)}remove(e){this.getRealStorage().remove(e)}flush(){this.getRealStorage().flush()}};
@@ -1 +1 @@
1
- "use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="0.10.21";
1
+ "use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="0.10.22";
@@ -1 +1 @@
1
- "use strict";var e=require("../core/configuration/authentication.js"),t=require("../core/errors/openfortError.js"),r=require("../types/types.js"),a=require("../core/configuration/account.js");require("./messaging/browserMessenger/backwardCompatibility.js");var o=require("../storage/istorage.js"),n=require("../core/config/config.js");require("./types.js"),require("../core/errors/sentry.js"),require("jose");var s=require("../core/configuration/passkey.js");require("./evm/types.js"),require("./evm/JsonRpcError.js"),require("eventemitter3"),require("./evm/provider/eip6963.js");exports.EmbeddedSigner=class{iframeManager;storage;backendApiClients;passkeyHandler;eventEmitter;constructor(e,t,r,a,o){this.iframeManager=e,this.storage=t,this.backendApiClients=r,this.passkeyHandler=a,this.eventEmitter=o}async createPasskey(e){const t=await this.passkeyHandler.createPasskey({id:s.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:e});return{id:t.id,key:t.key}}async configure(o){const s=await e.Authentication.fromStorage(this.storage);if(!s)throw new t.OpenfortError("No access token found",t.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const i=n.SDKConfiguration.getInstance();if(!i)throw new t.OpenfortError("Configuration not found",t.OpenfortErrorType.INVALID_CONFIGURATION);const c=await a.Account.fromStorage(this.storage);let d;if(c){const e={account:c.id,...o.entropy&&{entropy:{...o.entropy.recoveryPassword&&{recoveryPassword:o.entropy.recoveryPassword},...o.entropy.encryptionSession&&{encryptionSession:o.entropy.encryptionSession},..."passkey"===c.recoveryMethod&&{passkey:{id:c.recoveryMethodDetails?.passkeyId,env:c.recoveryMethodDetails?.passkeyEnv,key:await o.getPasskeyKeyFn(c.recoveryMethodDetails?.passkeyId)}}}}},t=await this.iframeManager.recover(e);d=t.account}else{const e=await this.backendApiClients.accountsApi.getAccountsV2({user:s.player,accountType:o.accountType,chainType:o.chainType},{headers:{authorization:`Bearer ${i.baseConfiguration.publishableKey}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}});if(0===e.data.data.length){const e=o.entropy?.passkey?await this.createPasskey(s.player):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}}}},r=await this.iframeManager.create(t);d=r.account}else{const t=e.data.data,r=t.find(e=>e.chainId===o.chainId),a=r||t[0],n={account:a.id,...o.entropy&&{entropy:{...o.entropy.recoveryPassword&&{recoveryPassword:o.entropy.recoveryPassword},...o.entropy.encryptionSession&&{encryptionSession:o.entropy.encryptionSession},..."passkey"===a.recoveryMethod&&{passkey:{id:a.recoveryMethodDetails?.passkeyId,env:a.recoveryMethodDetails?.passkeyEnv,key:await o.getPasskeyKeyFn(a.recoveryMethodDetails?.passkeyId)}}}}},s=await this.iframeManager.recover(n);if(d=s.account,!r){const e=await this.iframeManager.switchChain(o.chainId);d=e.account}}}return t.withOpenfortError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:d},{headers:{authorization:`Bearer ${i.baseConfiguration.publishableKey}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}}),t=new a.Account({user:e.data.user,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,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:a.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(r.OpenfortEvents.SWITCH_ACCOUNT,e.data.address),t},{default:t.OpenfortErrorType.AUTHENTICATION_ERROR})}async sign(e,t,r,a){return await this.iframeManager.sign(e,t,r,a)}async export(){return await this.iframeManager.export()}async switchChain({chainId:e}){const t=await this.iframeManager.switchChain(e),r=await a.Account.fromStorage(this.storage);new a.Account({...r,id:t.account,chainId:e}).save(this.storage)}async create(o){const s=await this.iframeManager.create(o),i=await e.Authentication.fromStorage(this.storage);if(!i)throw new t.OpenfortError("No access token found",t.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const c=n.SDKConfiguration.getInstance();if(!c)throw new t.OpenfortError("Configuration not found",t.OpenfortErrorType.INVALID_CONFIGURATION);return t.withOpenfortError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:s.account},{headers:{authorization:`Bearer ${c.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}}),t=new a.Account({user:e.data.user,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,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:a.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(r.OpenfortEvents.SWITCH_ACCOUNT,e.data.address),t},{default:t.OpenfortErrorType.AUTHENTICATION_ERROR})}async recover(o){const s=await this.iframeManager.recover(o),i=await e.Authentication.fromStorage(this.storage);if(!i)throw new t.OpenfortError("No access token found",t.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const c=n.SDKConfiguration.getInstance();if(!c)throw new t.OpenfortError("Configuration not found",t.OpenfortErrorType.INVALID_CONFIGURATION);return t.withOpenfortError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:s.account},{headers:{authorization:`Bearer ${c.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}}),t=new a.Account({user:e.data.user,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,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:a.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(r.OpenfortEvents.SWITCH_ACCOUNT,e.data.address),t},{default:t.OpenfortErrorType.AUTHENTICATION_ERROR})}async setRecoveryMethod({recoveryMethod:e,recoveryPassword:t,encryptionSession:r,passkeyInfo:a}){await this.iframeManager.setRecoveryMethod(e,t,r,a?.passkeyKey,a?.passkeyId)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(o.StorageKeys.ACCOUNT)}};
1
+ "use strict";var e=require("../core/configuration/authentication.js"),t=require("../core/configuration/passkey.js"),r=require("../core/errors/openfortError.js"),a=require("../types/types.js"),o=require("../core/config/config.js"),n=require("../core/configuration/account.js"),s=require("../storage/istorage.js");require("eventemitter3"),require("./evm/JsonRpcError.js"),require("./evm/types.js"),require("./evm/provider/eip6963.js"),require("../core/errors/sentry.js"),require("./messaging/browserMessenger/backwardCompatibility.js"),require("./types.js"),require("jose");exports.EmbeddedSigner=class{iframeManager;storage;backendApiClients;passkeyHandler;eventEmitter;constructor(e,t,r,a,o){this.iframeManager=e,this.storage=t,this.backendApiClients=r,this.passkeyHandler=a,this.eventEmitter=o}async createPasskey(e){const r=await this.passkeyHandler.createPasskey({id:t.PasskeyHandler.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:e});return{id:r.id,key:r.key}}async configure(t){const s=await e.Authentication.fromStorage(this.storage);if(!s)throw new r.OpenfortError("No access token found",r.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const i=o.SDKConfiguration.getInstance();if(!i)throw new r.OpenfortError("Configuration not found",r.OpenfortErrorType.INVALID_CONFIGURATION);const c=await n.Account.fromStorage(this.storage);let d;if(c){const e={account:c.id,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},..."passkey"===c.recoveryMethod&&{passkey:{id:c.recoveryMethodDetails?.passkeyId,env:c.recoveryMethodDetails?.passkeyEnv,key:await t.getPasskeyKeyFn(c.recoveryMethodDetails?.passkeyId)}}}}},r=await this.iframeManager.recover(e);d=r.account}else{const e=await this.backendApiClients.accountsApi.getAccountsV2({user:s.player,accountType:t.accountType,chainType:t.chainType},{headers:{authorization:`Bearer ${i.baseConfiguration.publishableKey}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}});if(0===e.data.data.length){const e=t.entropy?.passkey?await this.createPasskey(s.player):void 0,r={accountType:t.accountType,chainType:t.chainType,chainId:t.chainId,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},...t.entropy.passkey&&{passkey:e}}}},a=await this.iframeManager.create(r);d=a.account}else{const r=e.data.data,a=r.find(e=>e.chainId===t.chainId),o=a||r[0],n={account:o.id,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},..."passkey"===o.recoveryMethod&&{passkey:{id:o.recoveryMethodDetails?.passkeyId,env:o.recoveryMethodDetails?.passkeyEnv,key:await t.getPasskeyKeyFn(o.recoveryMethodDetails?.passkeyId)}}}}},s=await this.iframeManager.recover(n);if(d=s.account,!a){const e=await this.iframeManager.switchChain(t.chainId);d=e.account}}}return r.withOpenfortError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:d},{headers:{authorization:`Bearer ${i.baseConfiguration.publishableKey}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}}),t=new n.Account({user:e.data.user,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,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:n.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(a.OpenfortEvents.SWITCH_ACCOUNT,e.data.address),t},{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async sign(e,t,r,a){return await this.iframeManager.sign(e,t,r,a)}async export(){return await this.iframeManager.export()}async switchChain({chainId:e}){const t=await this.iframeManager.switchChain(e),r=await n.Account.fromStorage(this.storage);new n.Account({...r,id:t.account,chainId:e}).save(this.storage)}async create(t){const s=await this.iframeManager.create(t),i=await e.Authentication.fromStorage(this.storage);if(!i)throw new r.OpenfortError("No access token found",r.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const c=o.SDKConfiguration.getInstance();if(!c)throw new r.OpenfortError("Configuration not found",r.OpenfortErrorType.INVALID_CONFIGURATION);return r.withOpenfortError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:s.account},{headers:{authorization:`Bearer ${c.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}}),t=new n.Account({user:e.data.user,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,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:n.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(a.OpenfortEvents.SWITCH_ACCOUNT,e.data.address),t},{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async recover(t){const s=await this.iframeManager.recover(t),i=await e.Authentication.fromStorage(this.storage);if(!i)throw new r.OpenfortError("No access token found",r.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const c=o.SDKConfiguration.getInstance();if(!c)throw new r.OpenfortError("Configuration not found",r.OpenfortErrorType.INVALID_CONFIGURATION);return r.withOpenfortError(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:s.account},{headers:{authorization:`Bearer ${c.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}}),t=new n.Account({user:e.data.user,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,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:n.Account.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(a.OpenfortEvents.SWITCH_ACCOUNT,e.data.address),t},{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async setRecoveryMethod({recoveryMethod:e,recoveryPassword:t,encryptionSession:r,passkeyInfo:a}){await this.iframeManager.setRecoveryMethod(e,t,r,a?.passkeyKey,a?.passkeyId)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(s.StorageKeys.ACCOUNT)}};
@@ -1 +1 @@
1
- "use strict";var e=require("../../core/configuration/authentication.js"),t=require("./types.js"),r=require("./JsonRpcError.js"),i=require("./signTypedDataV4.js"),s=require("../../types/types.js"),a=require("../../utils/typedEventEmitter.js"),n=require("../../utils/chains/index.js"),o=require("../../core/configuration/account.js"),c=require("./addEthereumChain.js"),h=require("./registerSession.js"),d=require("./revokeSession.js"),u=require("./sendCalls.js"),p=require("./getCallsStatus.js"),l=require("./personalSign.js"),w=require("./estimateGas.js"),g=require("../../utils/crypto.js");exports.EvmProvider=class{#e;#t;#r;#i;updatePolicy(e){this.#t=e}#s;#a;#n=null;#o;isOpenfort=!0;#c;constructor({storage:e,backendApiClients:t,openfortEventEmitter:r,policyId:i,ensureSigner:n,chains:o,validateAndRefreshSession:c}){this.#c=n,this.#e=e,this.#r=o,this.#t=i,this.#s=c,this.#o=t,this.#o=t,this.#a=new a,r.on(s.OpenfortEvents.LOGGED_OUT,this.#h),r.on(s.OpenfortEvents.SWITCH_ACCOUNT,this.#d)}#u=async()=>(this.#i||(this.#i=await this.#c()),this.#i);#h=async()=>{this.#i=void 0,this.#a.emit(t.ProviderEvent.ACCOUNTS_CHANGED,[])};#d=async e=>{this.#a.emit(t.ProviderEvent.ACCOUNTS_CHANGED,[e])};async getRpcProvider(){if(!this.#n){const e=await o.Account.fromStorage(this.#e),t=e?.chainId||8453;await import("@ethersproject/providers").then(e=>{const r=this.#r?this.#r[t]:void 0;this.#n=new e.StaticJsonRpcProvider(r??n.defaultChainRpcs[t])})}if(!this.#n)throw new Error("RPC provider not initialized");return this.#n}async#p(s){switch(s.method){case"eth_accounts":{const e=await o.Account.fromStorage(this.#e);return e?[e.address]:[]}case"eth_requestAccounts":{const e=await o.Account.fromStorage(this.#e);if(e)return this.#a.emit(t.ProviderEvent.ACCOUNTS_CONNECT,{chainId:String(e.chainId)}),[e.address];throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer.")}case"eth_sendTransaction":{const t=await o.Account.fromStorage(this.#e),i=await this.#u(),a=await e.Authentication.fromStorage(this.#e);if(!t||!a)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await u.sendCalls({params:s.params||[],signer:i,account:t,authentication:a,backendClient:this.#o,policyId:this.#t})}case"eth_estimateGas":{const t=await o.Account.fromStorage(this.#e),i=await e.Authentication.fromStorage(this.#e);if(!t||!i)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await w.estimateGas({params:s.params||[],account:t,authentication:i,backendClient:this.#o,policyId:this.#t})}case"eth_signTypedData":case"eth_signTypedData_v4":{const e=await o.Account.fromStorage(this.#e),t=await this.#u();if(!e)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#s();const a=await this.getRpcProvider();return await i.signTypedDataV4({method:s.method,params:s.params||[],signer:t,implementationType:e.implementationType||e.type,rpcProvider:a,account:e})}case"personal_sign":{const e=await o.Account.fromStorage(this.#e);if(!e)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const t=await this.#u();return await this.#s(),await l.personalSign({params:s.params||[],signer:t,account:e})}case"eth_chainId":{const e=await this.getRpcProvider(),{chainId:t}=await e.detectNetwork();return g.numberToHex(t)}case"wallet_switchEthereumChain":{const e=await this.#u();if(!s.params||!Array.isArray(s.params)||0===s.params.length)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#s();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.#n=new e.StaticJsonRpcProvider(r??n.defaultChainRpcs[t])})}catch(e){const t=e;throw new r.JsonRpcError(r.RpcErrorCode.INTERNAL_ERROR,`Failed to switch chain: ${t.message}`)}return null}case"wallet_addEthereumChain":{await this.#u();const e=await this.getRpcProvider();return await c.addEthereumChain({params:s.params||[],rpcProvider:e,storage:this.#e})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const t=await o.Account.fromStorage(this.#e);await this.#u();const i=await e.Authentication.fromStorage(this.#e);if(!t||!i)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await p.getCallStatus({params:s.params||{},authentication:i,backendClient:this.#o,account:t})}case"wallet_sendCalls":{const t=await o.Account.fromStorage(this.#e),i=await this.#u(),a=await e.Authentication.fromStorage(this.#e);if(!t||!a)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await u.sendCalls({params:s.params?s.params[0].calls:[],signer:i,account:t,authentication:a,backendClient:this.#o,policyId:this.#t})}case"wallet_grantPermissions":{const t=await o.Account.fromStorage(this.#e),i=await this.#u(),a=await e.Authentication.fromStorage(this.#e);if(!t||!a)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await h.registerSession({params:s.params||[],signer:i,account:t,authentication:a,backendClient:this.#o,policyId:this.#t})}case"wallet_revokePermissions":{const t=await o.Account.fromStorage(this.#e),i=await this.#u(),a=await e.Authentication.fromStorage(this.#e);if(!t||!a)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await d.revokeSession({params:s.params||[],signer:i,account:t,authentication:a,backendClient:this.#o})}case"wallet_getCapabilities":{const e=await this.getRpcProvider(),{chainId:t}=await e.detectNetwork();return{[g.numberToHex(t)]:{permissions:{supported:!0,signerTypes:["account","key"],keyTypes:["secp256k1"],permissionTypes:["contract-calls"]},paymasterService:{supported:!0},atomicBatch:{supported:!0}}}}case"eth_gasPrice":case"eth_getBalance":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 r.JsonRpcError(r.ProviderErrorCode.UNSUPPORTED_METHOD,`${s.method}: Method not supported`)}}async request(e){try{return this.#p(e)}catch(e){if(e instanceof r.JsonRpcError)throw e;if(e instanceof Error)throw new r.JsonRpcError(r.RpcErrorCode.INTERNAL_ERROR,e.message);throw new r.JsonRpcError(r.RpcErrorCode.INTERNAL_ERROR,"Internal error")}}on(e,t){this.#a.on(e,t)}removeListener(e,t){this.#a.off(e,t)}};
1
+ "use strict";var e=require("../../core/configuration/account.js"),t=require("../../core/configuration/authentication.js"),r=require("../../types/types.js"),i=require("../../utils/chains/index.js"),s=require("../../utils/crypto.js"),a=require("../../utils/typedEventEmitter.js"),n=require("./addEthereumChain.js"),o=require("./estimateGas.js"),c=require("./getCallsStatus.js"),h=require("./JsonRpcError.js"),d=require("./personalSign.js"),u=require("./registerSession.js"),p=require("./revokeSession.js"),l=require("./sendCalls.js"),w=require("./signTypedDataV4.js"),g=require("./types.js");exports.EvmProvider=class{#e;#t;#r;#i;updatePolicy(e){this.#t=e}#s;#a;#n=null;#o;isOpenfort=!0;#c;constructor({storage:e,backendApiClients:t,openfortEventEmitter:i,policyId:s,ensureSigner:n,chains:o,validateAndRefreshSession:c}){this.#c=n,this.#e=e,this.#r=o,this.#t=s,this.#s=c,this.#o=t,this.#o=t,this.#a=new a,i.on(r.OpenfortEvents.LOGGED_OUT,this.#h),i.on(r.OpenfortEvents.SWITCH_ACCOUNT,this.#d)}#u=async()=>(this.#i||(this.#i=await this.#c()),this.#i);#h=async()=>{this.#i=void 0,this.#a.emit(g.ProviderEvent.ACCOUNTS_CHANGED,[])};#d=async e=>{this.#a.emit(g.ProviderEvent.ACCOUNTS_CHANGED,[e])};async getRpcProvider(){if(!this.#n){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.#n=new e.StaticJsonRpcProvider(t??i.defaultChainRpcs[r])})}if(!this.#n)throw new Error("RPC provider not initialized");return this.#n}async#p(r){switch(r.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)return this.#a.emit(g.ProviderEvent.ACCOUNTS_CONNECT,{chainId:String(t.chainId)}),[t.address];throw new h.JsonRpcError(h.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer.")}case"eth_sendTransaction":{const i=await e.Account.fromStorage(this.#e),s=await this.#u(),a=await t.Authentication.fromStorage(this.#e);if(!i||!a)throw new h.JsonRpcError(h.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await l.sendCalls({params:r.params||[],signer:s,account:i,authentication:a,backendClient:this.#o,policyId:this.#t})}case"eth_estimateGas":{const i=await e.Account.fromStorage(this.#e),s=await t.Authentication.fromStorage(this.#e);if(!i||!s)throw new h.JsonRpcError(h.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await o.estimateGas({params:r.params||[],account:i,authentication:s,backendClient:this.#o,policyId:this.#t})}case"eth_signTypedData":case"eth_signTypedData_v4":{const t=await e.Account.fromStorage(this.#e),i=await this.#u();if(!t)throw new h.JsonRpcError(h.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#s();const s=await this.getRpcProvider();return await w.signTypedDataV4({method:r.method,params:r.params||[],signer:i,implementationType:t.implementationType||t.type,rpcProvider:s,account:t})}case"personal_sign":{const t=await e.Account.fromStorage(this.#e);if(!t)throw new h.JsonRpcError(h.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");const i=await this.#u();return await this.#s(),await d.personalSign({params:r.params||[],signer:i,account:t})}case"eth_chainId":{const e=await this.getRpcProvider(),{chainId:t}=await e.detectNetwork();return s.numberToHex(t)}case"wallet_switchEthereumChain":{const e=await this.#u();if(!r.params||!Array.isArray(r.params)||0===r.params.length)throw new h.JsonRpcError(h.RpcErrorCode.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#s();try{const t=parseInt(r.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.#n=new e.StaticJsonRpcProvider(r??i.defaultChainRpcs[t])})}catch(e){const t=e;throw new h.JsonRpcError(h.RpcErrorCode.INTERNAL_ERROR,`Failed to switch chain: ${t.message}`)}return null}case"wallet_addEthereumChain":{await this.#u();const e=await this.getRpcProvider();return await n.addEthereumChain({params:r.params||[],rpcProvider:e,storage:this.#e})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const i=await e.Account.fromStorage(this.#e);await this.#u();const s=await t.Authentication.fromStorage(this.#e);if(!i||!s)throw new h.JsonRpcError(h.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await c.getCallStatus({params:r.params||{},authentication:s,backendClient:this.#o,account:i})}case"wallet_sendCalls":{const i=await e.Account.fromStorage(this.#e),s=await this.#u(),a=await t.Authentication.fromStorage(this.#e);if(!i||!a)throw new h.JsonRpcError(h.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await l.sendCalls({params:r.params?r.params[0].calls:[],signer:s,account:i,authentication:a,backendClient:this.#o,policyId:this.#t})}case"wallet_grantPermissions":{const i=await e.Account.fromStorage(this.#e),s=await this.#u(),a=await t.Authentication.fromStorage(this.#e);if(!i||!a)throw new h.JsonRpcError(h.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await u.registerSession({params:r.params||[],signer:s,account:i,authentication:a,backendClient:this.#o,policyId:this.#t})}case"wallet_revokePermissions":{const i=await e.Account.fromStorage(this.#e),s=await this.#u(),a=await t.Authentication.fromStorage(this.#e);if(!i||!a)throw new h.JsonRpcError(h.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await p.revokeSession({params:r.params||[],signer:s,account:i,authentication:a,backendClient:this.#o})}case"wallet_getCapabilities":{const e=await this.getRpcProvider(),{chainId:t}=await e.detectNetwork();return{[s.numberToHex(t)]:{permissions:{supported:!0,signerTypes:["account","key"],keyTypes:["secp256k1"],permissionTypes:["contract-calls"]},paymasterService:{supported:!0},atomicBatch:{supported:!0}}}}case"eth_gasPrice":case"eth_getBalance":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(r.method,r.params||[]);default:throw new h.JsonRpcError(h.ProviderErrorCode.UNSUPPORTED_METHOD,`${r.method}: Method not supported`)}}async request(e){try{return this.#p(e)}catch(e){if(e instanceof h.JsonRpcError)throw e;if(e instanceof Error)throw new h.JsonRpcError(h.RpcErrorCode.INTERNAL_ERROR,e.message);throw new h.JsonRpcError(h.RpcErrorCode.INTERNAL_ERROR,"Internal error")}}on(e,t){this.#a.on(e,t)}removeListener(e,t){this.#a.off(e,t)}};
@@ -1 +1 @@
1
- "use strict";var t=require("../../core/errors/openfortError.js"),e=require("./JsonRpcError.js");function r(t){return{data:(()=>{if("token-allowance"===t.type)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"token-allowance policy is not supported with this account implementation.");if("gas-limit"===t.type)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"gas-limit policy is not supported with this account implementation.");if("rate-limit"===t.type)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"rate-limit policy is not supported with this account implementation.");return t.data})(),type:t.type.custom}}function i(t){if("native-token-transfer"===t.type)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"native-token-transfer permission is not supported with this account implementation.");if("rate-limit"===t.type)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"rate-limit permission is not supported with this account implementation.");if("gas-limit"===t.type)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"gas-limit permission is not supported with this account implementation.");return{...t,policies:t?.policies?.map(r),required:t.required??!1,type:"string"==typeof t.type?t.type:t.type.custom}}function o(t){return{expiry:t.validUntil?Number(t.validUntil):0,grantedPermissions:t.whitelist?t.whitelist.map(e=>({type:"contract-call",data:{address:e,calls:[]},policies:[{data:{limit:t.limit},type:{custom:"usage-limit"}}]})):[],permissionsContext:t.id}}exports.registerSession=async({params:r,signer:n,account:s,authentication:a,backendClient:p,policyId:c})=>{const l=await(async(r,o,n,s,a)=>{const p=r[0],c=Math.floor((new Date).getTime()/1e3),l=Math.floor(new Date(Date.now()+1e3*p.expiry).getTime()/1e3),d=p.permissions.map(i),u=d.filter(t=>"contract-call"===t.type||"erc20-token-transfer"===t.type||"erc721-token-transfer"===t.type||"erc1155-token-transfer"===t.type).map(t=>t.data.address);let m,y=d.find(t=>"call-limit"===t.type)?.data;if(y=d[0]?.policies?.find(t=>"call-limit"===t.type)?.data?.limit,"signer"in p&&p.signer){if("keys"===p.signer.type)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"Multi-key signers are not supported for session creation");"key"!==p.signer.type&&"account"!==p.signer.type||(m=p.signer.data.id)}else"account"in p&&p.account&&(m=p.account);if(!m)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"Failed to request permissions - missing session address");const R=((t,e,r,i,o,n=!1,s,a,p,c)=>{const l={address:t,chainId:e,validAfter:r,validUntil:i,optimistic:n,whitelist:s,player:a,account:c};return o&&(l.policy=o),p&&(l.limit=p),l})(m,n.chainId,c,l,a,!1,u,s.player,y,n.id);return t.withOpenfortError(async()=>(await o.sessionsApi.createSession({createSessionRequest:R},{headers:{authorization:`Bearer ${o.config.backend.accessToken}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}})).data,{default:t.OpenfortErrorType.AUTHENTICATION_ERROR})})(r,p,s,a,c).catch(t=>{throw new e.JsonRpcError(e.RpcErrorCode.TRANSACTION_REJECTED,t.message)});if(l?.nextAction?.payload?.signableHash){let r;r=[300,531050104,324,50104,2741,11124].includes(s.chainId)?await n.sign(l.nextAction.payload.signableHash,!1,!1):await n.sign(l.nextAction.payload.signableHash);return o(await t.withOpenfortError(async()=>(await p.sessionsApi.signatureSession({id:l.id,signatureRequest:{signature:r}})).data,{default:t.OpenfortErrorType.AUTHENTICATION_ERROR}).catch(t=>{throw new e.JsonRpcError(e.RpcErrorCode.TRANSACTION_REJECTED,t.message)}))}if(!1===l.isActive)throw new e.JsonRpcError(e.RpcErrorCode.TRANSACTION_REJECTED,"Failed to grant permissions");return o(l)};
1
+ "use strict";var t=require("../../core/errors/openfortError.js"),e=require("./JsonRpcError.js");function r(t){return{data:(()=>{if("token-allowance"===t.type)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"token-allowance policy is not supported with this account implementation.");if("gas-limit"===t.type)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"gas-limit policy is not supported with this account implementation.");if("rate-limit"===t.type)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"rate-limit policy is not supported with this account implementation.");return t.data})(),type:t.type.custom}}function i(t){if("native-token-transfer"===t.type)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"native-token-transfer permission is not supported with this account implementation.");if("rate-limit"===t.type)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"rate-limit permission is not supported with this account implementation.");if("gas-limit"===t.type)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"gas-limit permission is not supported with this account implementation.");return{...t,policies:t?.policies?.map(r),required:t.required??!1,type:"string"==typeof t.type?t.type:t.type.custom}}function o(t){return{expiry:t.validUntil?Number(t.validUntil):0,grantedPermissions:t.whitelist?t.whitelist.map(e=>({type:"contract-call",data:{address:e,calls:[]},policies:[{data:{limit:t.limit},type:{custom:"usage-limit"}}]})):[],permissionsContext:t.id}}exports.registerSession=async({params:r,signer:n,account:s,authentication:a,backendClient:p,policyId:c})=>{const l=await(async(r,o,n,s,a)=>{const p=r[0],c=Math.floor(Date.now()/1e3),l=Math.floor(new Date(Date.now()+1e3*p.expiry).getTime()/1e3),d=p.permissions.map(i),u=d.filter(t=>"contract-call"===t.type||"erc20-token-transfer"===t.type||"erc721-token-transfer"===t.type||"erc1155-token-transfer"===t.type).map(t=>t.data.address);let y,m=d.find(t=>"call-limit"===t.type)?.data;if(m=d[0]?.policies?.find(t=>"call-limit"===t.type)?.data?.limit,"signer"in p&&p.signer){if("keys"===p.signer.type)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"Multi-key signers are not supported for session creation");"key"!==p.signer.type&&"account"!==p.signer.type||(y=p.signer.data.id)}else"account"in p&&p.account&&(y=p.account);if(!y)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,"Failed to request permissions - missing session address");const R=((t,e,r,i,o,n=!1,s,a,p,c)=>{const l={address:t,chainId:e,validAfter:r,validUntil:i,optimistic:n,whitelist:s,player:a,account:c};return o&&(l.policy=o),p&&(l.limit=p),l})(y,n.chainId,c,l,a,!1,u,s.player,m,n.id);return t.withOpenfortError(async()=>(await o.sessionsApi.createSession({createSessionRequest:R},{headers:{authorization:`Bearer ${o.config.backend.accessToken}`,"x-player-token":s.token,"x-auth-provider":s.thirdPartyProvider,"x-token-type":s.thirdPartyTokenType}})).data,{default:t.OpenfortErrorType.AUTHENTICATION_ERROR})})(r,p,s,a,c).catch(t=>{throw new e.JsonRpcError(e.RpcErrorCode.TRANSACTION_REJECTED,t.message)});if(l?.nextAction?.payload?.signableHash){let r;r=[300,531050104,324,50104,2741,11124].includes(s.chainId)?await n.sign(l.nextAction.payload.signableHash,!1,!1):await n.sign(l.nextAction.payload.signableHash);return o(await t.withOpenfortError(async()=>(await p.sessionsApi.signatureSession({id:l.id,signatureRequest:{signature:r}})).data,{default:t.OpenfortErrorType.AUTHENTICATION_ERROR}).catch(t=>{throw new e.JsonRpcError(e.RpcErrorCode.TRANSACTION_REJECTED,t.message)}))}if(!1===l.isActive)throw new e.JsonRpcError(e.RpcErrorCode.TRANSACTION_REJECTED,"Failed to grant permissions");return o(l)};
@@ -1 +1 @@
1
- "use strict";var e=require("./walletHelpers.js"),r=require("./JsonRpcError.js");const a=["types","domain","primaryType","message"],t=(e,t)=>{let o;if("string"==typeof e)try{o=JSON.parse(e)}catch(e){throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,`Failed to parse typed data JSON: ${e}`)}else{if("object"!=typeof e)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,`Invalid typed data argument: ${e}`);o=e}if(!(e=>a.every(r=>r in e))(o))throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,`Invalid typed data argument. The following properties are required: \n ${a.join(", ")}`);const n=o.domain?.chainId;if(n&&("string"==typeof n&&(n.startsWith("0x")?o.domain.chainId=parseInt(n,16):o.domain.chainId=parseInt(n,10)),o.domain.chainId!==t))throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,`Invalid chainId, expected ${t}`);return o};exports.signTypedDataV4=async({params:a,method:o,signer:n,implementationType:s,rpcProvider:d,account:i})=>{const p=a[0],c=a[1];if(!p||!c)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,`${o} requires an address and a typed data JSON`);const{chainId:h}=await d.detectNetwork(),I=t(c,h),y={...I.types};delete y.EIP712Domain;const{_TypedDataEncoder:m}=await import("@ethersproject/hash"),A=m.hash(I.domain,y,I.message);return await e.signMessage({hash:A,implementationType:s,chainId:h,signer:n,address:p,ownerAddress:i.ownerAddress,factoryAddress:i.factoryAddress,salt:i.salt})};
1
+ "use strict";var e=require("./JsonRpcError.js"),r=require("./walletHelpers.js");const a=["types","domain","primaryType","message"],t=(r,t)=>{let o;if("string"==typeof r)try{o=JSON.parse(r)}catch(r){throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,`Failed to parse typed data JSON: ${r}`)}else{if("object"!=typeof r)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,`Invalid typed data argument: ${r}`);o=r}if(!(e=>a.every(r=>r in e))(o))throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,`Invalid typed data argument. The following properties are required: \n ${a.join(", ")}`);const n=o.domain?.chainId;if(n&&("string"==typeof n&&(n.startsWith("0x")?o.domain.chainId=parseInt(n,16):o.domain.chainId=parseInt(n,10)),o.domain.chainId!==t))throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,`Invalid chainId, expected ${t}`);return o};exports.signTypedDataV4=async({params:a,method:o,signer:n,implementationType:s,rpcProvider:d,account:i})=>{const p=a[0],c=a[1];if(!p||!c)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,`${o} requires an address and a typed data JSON`);const{chainId:h}=await d.detectNetwork(),I=t(c,h),y={...I.types};delete y.EIP712Domain;const{_TypedDataEncoder:m}=await import("@ethersproject/hash"),A=m.hash(I.domain,y,I.message);return await r.signMessage({hash:A,implementationType:s,chainId:h,signer:n,address:p,ownerAddress:i.ownerAddress,factoryAddress:i.factoryAddress,salt:i.salt})};
@@ -1 +1 @@
1
- "use strict";var e=require("../core/configuration/account.js"),r=require("./messaging/browserMessenger/connect.js");require("./messaging/browserMessenger/backwardCompatibility.js");var i=require("../storage/istorage.js"),t=require("../core/errors/openfortError.js"),o=require("../utils/debug.js"),n=require("../utils/crypto.js"),s=require("../core/configuration/authentication.js"),a=require("./messaging/ReactNativeMessenger.js"),d=require("./types.js"),c=require("../core/errors/sentry.js");class u extends Error{constructor(){super("This embedded signer requires a password to be recovered")}}class h extends Error{constructor(){super("Wrong recovery passkey for this embedded signer")}}class g extends Error{constructor(){super("MissingProjectEntropyError")}}class l extends Error{constructor(){super("Wrong recovery password for this embedded signer")}}class y extends Error{constructor(){super("Not configured")}}class p extends Error{constructor(){super("OTP required")}}exports.IframeManager=class{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;constructor(e,r,i){if(!e)throw new t.OpenfortError("Configuration is required for IframeManager",t.OpenfortErrorType.INVALID_CONFIGURATION);if(!r)throw new t.OpenfortError("Storage is required for IframeManager",t.OpenfortErrorType.INVALID_CONFIGURATION);if(!i)throw new t.OpenfortError("Messenger is required for IframeManager",t.OpenfortErrorType.INVALID_CONFIGURATION);this.sdkConfiguration=e,this.storage=r,this.messenger=i}async initialize(){if(!this.isInitialized)if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.initializationPromise=null,e}}}async doInitialize(){o.debugLog("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:o.debugLog}),this.connection=r({messenger:this.messenger,timeout:1e4,log:o.debugLog});try{this.remote=await this.connection.promise,o.debugLog("IframeManager connection established")}catch(e){const r=e;throw c.sentry.captureException(r),this.destroy(),o.debugLog("Failed to establish connection:",r),new t.OpenfortError(`Failed to establish iFrame connection: ${r.cause||r.message}`,t.OpenfortErrorType.INTERNAL_ERROR,e)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new t.OpenfortError("Failed to establish connection",t.OpenfortErrorType.INTERNAL_ERROR);return this.remote}handleError(e){if(d.isErrorResponse(e)){if(e.error===d.NOT_CONFIGURED_ERROR)throw this.storage.remove(i.StorageKeys.ACCOUNT),new y;if(e.error===d.MISSING_USER_ENTROPY_ERROR)throw this.storage.remove(i.StorageKeys.ACCOUNT),new u;if(e.error===d.MISSING_PROJECT_ENTROPY_ERROR)throw this.storage.remove(i.StorageKeys.ACCOUNT),new g;if(e.error===d.INCORRECT_USER_ENTROPY_ERROR)throw new l;if(e.error===d.MISSING_PASSKEY_ERROR)throw this.storage.remove(i.StorageKeys.ACCOUNT),new u;if(e.error===d.INCORRECT_PASSKEY_ERROR)throw new h;if(e.error===d.OTP_REQUIRED_ERROR)throw new p;throw this.storage.remove(i.StorageKeys.ACCOUNT),new t.OpenfortError(`Unknown error: ${e.error}`,t.OpenfortErrorType.INTERNAL_ERROR)}throw e}async buildRequestConfiguration(){const e=await s.Authentication.fromStorage(this.storage);if(!e)throw new t.OpenfortError("Must be authenticated to create a signer",t.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const r={auth:d.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:r,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??void 0}}async buildIFrameRequestConfiguration(){const e=await s.Authentication.fromStorage(this.storage);if(!e)throw new t.OpenfortError("Must be authenticated to create a signer",t.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const r={auth:d.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.player,recovery:r,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await this.ensureConnection(),i=await this.buildIFrameRequestConfiguration();i.chainId=e.chainId??null,i.password=e?.entropy?.recoveryPassword??null,i.recovery={...i.recovery,encryptionSession:e?.entropy?.encryptionSession},i.passkey=e?.entropy?.passkey??null;const t={uuid:n.randomUUID(),action:d.Event.CREATE,recovery:i.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:i.accessToken,playerID:i.playerID,thirdPartyProvider:i.thirdPartyProvider,thirdPartyTokenType:i.thirdPartyTokenType,encryptionKey:i.password,encryptionSession:i.recovery?.encryptionSession??null,passkey:i.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType},o=await r.create(t);return d.isErrorResponse(o)&&this.handleError(o),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",o.version??"undefined"),o}async recover(r){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await e.Account.fromStorage(this.storage),t=await this.ensureConnection(),o=await this.buildIFrameRequestConfiguration();o.chainId=i?.chainId??null,o.password=r?.entropy?.recoveryPassword??null,o.recovery={...o.recovery,encryptionSession:r?.entropy?.encryptionSession},o.passkey=r?.entropy?.passkey??null;const s={uuid:n.randomUUID(),action:d.Event.RECOVER,recovery:o.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:o.accessToken,playerID:o.playerID,thirdPartyProvider:o.thirdPartyProvider,thirdPartyTokenType:o.thirdPartyTokenType,encryptionKey:o.password,encryptionSession:o.recovery?.encryptionSession??null,passkey:o.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:r.account},a=await t.recover(s);return d.isErrorResponse(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,r,i,t){o.debugLog("[iframe] ensureConnection");const s=await this.ensureConnection(),a=new d.SignRequest(n.randomUUID(),e,await this.buildRequestConfiguration(),r,i,t);o.debugLog("[iframe] done ensureConnection");const c=await s.sign(a);return o.debugLog("[iframe] response",c),d.isErrorResponse(c)&&this.handleError(c),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",c.version??"undefined"),c.signature}async switchChain(e){const r=await this.ensureConnection(),i=new d.SwitchChainRequest(n.randomUUID(),e,await this.buildRequestConfiguration()),t=await r.switchChain(i);return d.isErrorResponse(t)&&this.handleError(t),t}async export(){const e=await this.ensureConnection(),r=new d.ExportPrivateKeyRequest(n.randomUUID(),await this.buildRequestConfiguration()),i=await e.export(r);return d.isErrorResponse(i)&&this.handleError(i),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",i.version??"undefined"),i.key}async setRecoveryMethod(e,r,i,t,o){const s=await this.ensureConnection(),a=new d.SetRecoveryMethodRequest(n.randomUUID(),e,await this.buildRequestConfiguration(),r,i,t,o),c=await s.setRecoveryMethod(a);d.isErrorResponse(c)&&this.handleError(c),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",c.version??"undefined")}async getCurrentDevice(e){const r=await this.ensureConnection(),i=new d.GetCurrentDeviceRequest(n.randomUUID(),e);try{const e=await r.getCurrentDevice(i);return d.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 o.debugLog("IframeManager not loaded, skipping authentication update");const e=await s.Authentication.fromStorage(this.storage);if(!e)return void o.debugLog("No authentication found, skipping update");const r=new d.UpdateAuthenticationRequest(n.randomUUID(),e.token);o.debugLog("Updating authentication in iframe with token");const i=await this.remote.updateAuthentication(r);d.isErrorResponse(i)&&this.handleError(i)}async disconnect(){const e=await this.ensureConnection(),r={uuid:n.randomUUID()};await e.logout(r)}async onMessage(e){o.debugLog("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof a.ReactNativeMessenger?(this.isInitialized||this.connection?o.debugLog(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(o.debugLog("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{o.debugLog("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),o.debugLog("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):o.debugLog("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.messenger.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}},exports.MissingProjectEntropyError=g,exports.MissingRecoveryPasswordError=u,exports.NotConfiguredError=y,exports.OTPRequiredError=p,exports.WrongPasskeyError=h,exports.WrongRecoveryPasswordError=l;
1
+ "use strict";var e=require("../core/configuration/account.js"),r=require("../core/configuration/authentication.js"),i=require("../core/errors/openfortError.js"),t=require("../core/errors/sentry.js"),o=require("../storage/istorage.js"),n=require("../utils/crypto.js"),s=require("../utils/debug.js"),a=require("./messaging/ReactNativeMessenger.js"),d=require("./messaging/browserMessenger/connect.js");require("./messaging/browserMessenger/backwardCompatibility.js");var c=require("./types.js");class u extends Error{constructor(){super("This embedded signer requires a password to be recovered")}}class h extends Error{constructor(){super("Wrong recovery passkey for this embedded signer")}}class g extends Error{constructor(){super("MissingProjectEntropyError")}}class l extends Error{constructor(){super("Wrong recovery password for this embedded signer")}}class y extends Error{constructor(){super("Not configured")}}class p extends Error{constructor(){super("OTP required")}}exports.IframeManager=class{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;constructor(e,r,t){if(!e)throw new i.OpenfortError("Configuration is required for IframeManager",i.OpenfortErrorType.INVALID_CONFIGURATION);if(!r)throw new i.OpenfortError("Storage is required for IframeManager",i.OpenfortErrorType.INVALID_CONFIGURATION);if(!t)throw new i.OpenfortError("Messenger is required for IframeManager",i.OpenfortErrorType.INVALID_CONFIGURATION);this.sdkConfiguration=e,this.storage=r,this.messenger=t}async initialize(){if(!this.isInitialized)if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.initializationPromise=null,e}}}async doInitialize(){s.debugLog("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:s.debugLog}),this.connection=d({messenger:this.messenger,timeout:1e4,log:s.debugLog});try{this.remote=await this.connection.promise,s.debugLog("IframeManager connection established")}catch(e){const r=e;throw t.sentry.captureException(r),this.destroy(),s.debugLog("Failed to establish connection:",r),new i.OpenfortError(`Failed to establish iFrame connection: ${r.cause||r.message}`,i.OpenfortErrorType.INTERNAL_ERROR,e)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new i.OpenfortError("Failed to establish connection",i.OpenfortErrorType.INTERNAL_ERROR);return this.remote}handleError(e){if(c.isErrorResponse(e)){if(e.error===c.NOT_CONFIGURED_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new y;if(e.error===c.MISSING_USER_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new u;if(e.error===c.MISSING_PROJECT_ENTROPY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new g;if(e.error===c.INCORRECT_USER_ENTROPY_ERROR)throw new l;if(e.error===c.MISSING_PASSKEY_ERROR)throw this.storage.remove(o.StorageKeys.ACCOUNT),new u;if(e.error===c.INCORRECT_PASSKEY_ERROR)throw new h;if(e.error===c.OTP_REQUIRED_ERROR)throw new p;throw this.storage.remove(o.StorageKeys.ACCOUNT),new i.OpenfortError(`Unknown error: ${e.error}`,i.OpenfortErrorType.INTERNAL_ERROR)}throw e}async buildRequestConfiguration(){const e=await r.Authentication.fromStorage(this.storage);if(!e)throw new i.OpenfortError("Must be authenticated to create a signer",i.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const t={auth:c.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:t,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??void 0}}async buildIFrameRequestConfiguration(){const e=await r.Authentication.fromStorage(this.storage);if(!e)throw new i.OpenfortError("Must be authenticated to create a signer",i.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const t={auth:c.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.player,recovery:t,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const r=await this.ensureConnection(),i=await this.buildIFrameRequestConfiguration();i.chainId=e.chainId??null,i.password=e?.entropy?.recoveryPassword??null,i.recovery={...i.recovery,encryptionSession:e?.entropy?.encryptionSession},i.passkey=e?.entropy?.passkey??null;const t={uuid:n.randomUUID(),action:c.Event.CREATE,recovery:i.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:i.accessToken,playerID:i.playerID,thirdPartyProvider:i.thirdPartyProvider,thirdPartyTokenType:i.thirdPartyTokenType,encryptionKey:i.password,encryptionSession:i.recovery?.encryptionSession??null,passkey:i.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType},o=await r.create(t);return c.isErrorResponse(o)&&this.handleError(o),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",o.version??"undefined"),o}async recover(r){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await e.Account.fromStorage(this.storage),t=await this.ensureConnection(),o=await this.buildIFrameRequestConfiguration();o.chainId=i?.chainId??null,o.password=r?.entropy?.recoveryPassword??null,o.recovery={...o.recovery,encryptionSession:r?.entropy?.encryptionSession},o.passkey=r?.entropy?.passkey??null;const s={uuid:n.randomUUID(),action:c.Event.RECOVER,recovery:o.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:o.accessToken,playerID:o.playerID,thirdPartyProvider:o.thirdPartyProvider,thirdPartyTokenType:o.thirdPartyTokenType,encryptionKey:o.password,encryptionSession:o.recovery?.encryptionSession??null,passkey:o.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:r.account},a=await t.recover(s);return c.isErrorResponse(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,r,i,t){s.debugLog("[iframe] ensureConnection");const o=await this.ensureConnection(),a=new c.SignRequest(n.randomUUID(),e,await this.buildRequestConfiguration(),r,i,t);s.debugLog("[iframe] done ensureConnection");const d=await o.sign(a);return s.debugLog("[iframe] response",d),c.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined"),d.signature}async switchChain(e){const r=await this.ensureConnection(),i=new c.SwitchChainRequest(n.randomUUID(),e,await this.buildRequestConfiguration()),t=await r.switchChain(i);return c.isErrorResponse(t)&&this.handleError(t),t}async export(){const e=await this.ensureConnection(),r=new c.ExportPrivateKeyRequest(n.randomUUID(),await this.buildRequestConfiguration()),i=await e.export(r);return c.isErrorResponse(i)&&this.handleError(i),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",i.version??"undefined"),i.key}async setRecoveryMethod(e,r,i,t,o){const s=await this.ensureConnection(),a=new c.SetRecoveryMethodRequest(n.randomUUID(),e,await this.buildRequestConfiguration(),r,i,t,o),d=await s.setRecoveryMethod(a);c.isErrorResponse(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined")}async getCurrentDevice(e){const r=await this.ensureConnection(),i=new c.GetCurrentDeviceRequest(n.randomUUID(),e);try{const e=await r.getCurrentDevice(i);return c.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 s.debugLog("IframeManager not loaded, skipping authentication update");const e=await r.Authentication.fromStorage(this.storage);if(!e)return void s.debugLog("No authentication found, skipping update");const i=new c.UpdateAuthenticationRequest(n.randomUUID(),e.token);s.debugLog("Updating authentication in iframe with token");const t=await this.remote.updateAuthentication(i);c.isErrorResponse(t)&&this.handleError(t)}async disconnect(){const e=await this.ensureConnection(),r={uuid:n.randomUUID()};await e.logout(r)}async onMessage(e){s.debugLog("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof a.ReactNativeMessenger?(this.isInitialized||this.connection?s.debugLog(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(s.debugLog("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{s.debugLog("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),s.debugLog("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):s.debugLog("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.messenger.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}},exports.MissingProjectEntropyError=g,exports.MissingRecoveryPasswordError=u,exports.NotConfiguredError=y,exports.OTPRequiredError=p,exports.WrongPasskeyError=h,exports.WrongRecoveryPasswordError=l;
@@ -1 +1 @@
1
- "use strict";const t=Symbol("CallOptions");module.exports=class{transferables;timeout;#t=t;constructor(t){this.transferables=t?.transferables,this.timeout=t?.timeout}};
1
+ "use strict";module.exports=class{transferables;timeout;constructor(t){this.transferables=t?.transferables,this.timeout=t?.timeout}};
@@ -1 +1 @@
1
- "use strict";const s=Symbol("Reply");module.exports=class{value;transferables;#s=s;constructor(s,e){this.value=s,this.transferables=e?.transferables}};
1
+ "use strict";module.exports=class{value;transferables;constructor(s,e){this.value=s,this.transferables=e?.transferables}};
@@ -1 +1 @@
1
- "use strict";var e=require("./namespace.js"),a=require("./guards.js"),r=require("./PenpalBugError.js");const l="deprecated-penpal";var n,t;!function(e){e.Call="call",e.Reply="reply",e.Syn="syn",e.SynAck="synAck",e.Ack="ack"}(n||(n={})),function(e){e.Fulfilled="fulfilled",e.Rejected="rejected"}(t||(t={}));const s=e=>e.split("."),i=e=>e.join("."),p=e=>new r(`Unexpected message to translate: ${JSON.stringify(e)}`);exports.DEPRECATED_PENPAL_PARTICIPANT_ID=l,exports.downgradeMessage=e=>{if(a.isAck1Message(e))return{penpal:n.SynAck,methodNames:e.methodPaths.map(i)};if(a.isCallMessage(e))return{penpal:n.Call,id:e.id,methodName:i(e.methodPath),args:e.args};if(a.isReplyMessage(e))return e.isError?{penpal:n.Reply,id:e.callId,resolution:t.Rejected,...e.isSerializedErrorInstance?{returnValue:e.value,returnValueIsError:!0}:{returnValue:e.value}}:{penpal:n.Reply,id:e.callId,resolution:t.Fulfilled,returnValue:e.value};throw p(e)},exports.isDeprecatedMessage=e=>a.isObject(e)&&"penpal"in e,exports.upgradeMessage=a=>{if(a.penpal===n.Syn)return{namespace:e,channel:void 0,type:"SYN",participantId:l};if(a.penpal===n.SynAck)return{namespace:e,channel:void 0,type:"ACK1",methodPaths:a.methodNames.map(s)};if(a.penpal===n.Ack)return{namespace:e,channel:void 0,type:"ACK2"};if(a.penpal===n.Call)return{namespace:e,channel:void 0,type:"CALL",id:a.id,methodPath:s(a.methodName),args:a.args};if(a.penpal===n.Reply)return a.resolution===t.Fulfilled?{namespace:e,channel:void 0,type:"REPLY",callId:a.id,value:a.returnValue}:{namespace:e,channel:void 0,type:"REPLY",callId:a.id,isError:!0,...a.returnValueIsError?{value:a.returnValue,isSerializedErrorInstance:!0}:{value:a.returnValue}};throw p(a)};
1
+ "use strict";var e=require("./guards.js"),a=require("./namespace.js"),r=require("./PenpalBugError.js");const l="deprecated-penpal";var n,t;!function(e){e.Call="call",e.Reply="reply",e.Syn="syn",e.SynAck="synAck",e.Ack="ack"}(n||(n={})),function(e){e.Fulfilled="fulfilled",e.Rejected="rejected"}(t||(t={}));const s=e=>e.split("."),i=e=>e.join("."),p=e=>new r(`Unexpected message to translate: ${JSON.stringify(e)}`);exports.DEPRECATED_PENPAL_PARTICIPANT_ID=l,exports.downgradeMessage=a=>{if(e.isAck1Message(a))return{penpal:n.SynAck,methodNames:a.methodPaths.map(i)};if(e.isCallMessage(a))return{penpal:n.Call,id:a.id,methodName:i(a.methodPath),args:a.args};if(e.isReplyMessage(a))return a.isError?{penpal:n.Reply,id:a.callId,resolution:t.Rejected,...a.isSerializedErrorInstance?{returnValue:a.value,returnValueIsError:!0}:{returnValue:a.value}}:{penpal:n.Reply,id:a.callId,resolution:t.Fulfilled,returnValue:a.value};throw p(a)},exports.isDeprecatedMessage=a=>e.isObject(a)&&"penpal"in a,exports.upgradeMessage=e=>{if(e.penpal===n.Syn)return{namespace:a,channel:void 0,type:"SYN",participantId:l};if(e.penpal===n.SynAck)return{namespace:a,channel:void 0,type:"ACK1",methodPaths:e.methodNames.map(s)};if(e.penpal===n.Ack)return{namespace:a,channel:void 0,type:"ACK2"};if(e.penpal===n.Call)return{namespace:a,channel:void 0,type:"CALL",id:e.id,methodPath:s(e.methodName),args:e.args};if(e.penpal===n.Reply)return e.resolution===t.Fulfilled?{namespace:a,channel:void 0,type:"REPLY",callId:e.id,value:e.returnValue}:{namespace:a,channel:void 0,type:"REPLY",callId:e.id,isError:!0,...e.returnValueIsError?{value:e.returnValue,isSerializedErrorInstance:!0}:{value:e.returnValue}};throw p(e)};
@@ -1 +1 @@
1
- "use strict";var e=require("./PenpalError.js"),s=require("./shakeHands.js"),n=require("./guards.js"),r=require("./once.js"),t=require("./namespace.js");const o=new WeakSet;module.exports=({messenger:a,methods:i={},timeout:c,channel:d,log:u})=>{if(!a)throw new e("INVALID_ARGUMENT","messenger must be defined");if(o.has(a))throw new e("INVALID_ARGUMENT","A messenger can only be used for a single connection");o.add(a);const g=[a.destroy],h=r(e=>{if(e){const e={namespace:t,channel:d,type:"DESTROY"};try{a.sendMessage(e)}catch(e){}}for(const e of g)e();u?.("Connection destroyed")}),l=e=>n.isMessage(e)&&e.channel===d;return{promise:(async()=>{try{a.initialize({log:u,validateReceivedMessage:l}),a.addMessageHandler(e=>{n.isDestroyMessage(e)&&h(!1)});const{remoteProxy:e,destroy:r}=await s({messenger:a,methods:i,timeout:c,channel:d,log:u});return g.push(r),e}catch(e){throw h(!0),e}})(),destroy:()=>{h(!0)}}};
1
+ "use strict";var e=require("./guards.js"),s=require("./namespace.js"),n=require("./once.js"),r=require("./PenpalError.js"),t=require("./shakeHands.js");const o=new WeakSet;module.exports=({messenger:a,methods:i={},timeout:c,channel:d,log:u})=>{if(!a)throw new r("INVALID_ARGUMENT","messenger must be defined");if(o.has(a))throw new r("INVALID_ARGUMENT","A messenger can only be used for a single connection");o.add(a);const g=[a.destroy],h=n(e=>{if(e){const e={namespace:s,channel:d,type:"DESTROY"};try{a.sendMessage(e)}catch(e){}}for(const e of g)e();u?.("Connection destroyed")}),l=s=>e.isMessage(s)&&s.channel===d;return{promise:(async()=>{try{a.initialize({log:u,validateReceivedMessage:l}),a.addMessageHandler(s=>{e.isDestroyMessage(s)&&h(!1)});const{remoteProxy:s,destroy:n}=await t({messenger:a,methods:i,timeout:c,channel:d,log:u});return g.push(n),s}catch(e){throw h(!0),e}})(),destroy:()=>{h(!0)}}};
@@ -1 +1 @@
1
- "use strict";var e=require("./errorSerialization.js"),r=require("./Reply.js"),a=require("./PenpalError.js"),t=require("./methodSerialization.js"),s=require("./guards.js"),n=require("./namespace.js");const o=(r,a,t)=>({namespace:n,channel:r,type:"REPLY",callId:a,isError:!0,...t instanceof Error?{value:e.serializeError(t),isSerializedErrorInstance:!0}:{value:t}});module.exports=(e,i,l,d)=>{let h=!1;const c=async c=>{if(h)return;if(!s.isCallMessage(c))return;d?.(`Received ${t.formatMethodPath(c.methodPath)}() call`,c);const{methodPath:u,args:m,id:M}=c;let f,g;try{const e=t.getMethodAtMethodPath(u,i);if(!e)throw new a("METHOD_NOT_FOUND",`Method \`${t.formatMethodPath(u)}\` is not found.`);let s=await e(...m);s instanceof r&&(g=s.transferables,s=await s.value),f={namespace:n,channel:l,type:"REPLY",callId:M,value:s}}catch(e){f=o(l,M,e)}if(!h)try{d?.(`Sending ${t.formatMethodPath(u)}() reply`,f),e.sendMessage(f,g)}catch(r){throw"DataCloneError"===r.name&&(f=o(l,M,r),d?.(`Sending ${t.formatMethodPath(u)}() reply`,f),e.sendMessage(f)),r}};return e.addMessageHandler(c),()=>{h=!0,e.removeMessageHandler(c)}};
1
+ "use strict";var e=require("./errorSerialization.js"),r=require("./guards.js"),a=require("./methodSerialization.js"),t=require("./namespace.js"),s=require("./PenpalError.js"),n=require("./Reply.js");const o=(r,a,s)=>({namespace:t,channel:r,type:"REPLY",callId:a,isError:!0,...s instanceof Error?{value:e.serializeError(s),isSerializedErrorInstance:!0}:{value:s}});module.exports=(e,i,l,d)=>{let h=!1;const c=async c=>{if(h)return;if(!r.isCallMessage(c))return;d?.(`Received ${a.formatMethodPath(c.methodPath)}() call`,c);const{methodPath:u,args:m,id:M}=c;let f,g;try{const e=a.getMethodAtMethodPath(u,i);if(!e)throw new s("METHOD_NOT_FOUND",`Method \`${a.formatMethodPath(u)}\` is not found.`);let r=await e(...m);r instanceof n&&(g=r.transferables,r=await r.value),f={namespace:t,channel:l,type:"REPLY",callId:M,value:r}}catch(e){f=o(l,M,e)}if(!h)try{d?.(`Sending ${a.formatMethodPath(u)}() reply`,f),e.sendMessage(f,g)}catch(r){throw"DataCloneError"===r.name&&(f=o(l,M,r),d?.(`Sending ${a.formatMethodPath(u)}() reply`,f),e.sendMessage(f)),r}};return e.addMessageHandler(c),()=>{h=!0,e.removeMessageHandler(c)}};
@@ -1 +1 @@
1
- "use strict";var e=require("../../../utils/crypto.js"),t=require("./errorSerialization.js"),r=require("./methodSerialization.js"),a=require("./CallOptions.js"),o=require("./PenpalError.js"),s=require("./guards.js"),n=require("./namespace.js");const l=new Set(["apply","call","bind"]),i=(e,t,r=[])=>new Proxy(r.length?()=>{}:Object.create(null),{get(a,o){if("then"!==o)return r.length&&l.has(o)?Reflect.get(a,o):i(e,t,[...r,o])},apply:(t,a,o)=>e(r,o)}),d=e=>new o("CONNECTION_DESTROYED",`Method call ${r.formatMethodPath(e)}() failed due to destroyed connection`);module.exports=(l,c,h)=>{let u=!1;const m=new Map,f=e=>{if(!s.isReplyMessage(e))return;const{callId:a,value:o,isError:n,isSerializedErrorInstance:l}=e,i=m.get(a);i&&(m.delete(a),h?.(`Received ${r.formatMethodPath(i.methodPath)}() call`,e),n?i.reject(l?t.deserializeError(o):o):i.resolve(o))};l.addMessageHandler(f);return{remoteProxy:i((t,s)=>{if(u)throw d(t);const i=e.randomUUID(),f=s[s.length-1],g=f instanceof a,{timeout:M,transferables:p}=g?f:{},P=g?s.slice(0,-1):s;return new Promise((e,a)=>{const s=void 0!==M?window.setTimeout(()=>{m.delete(i),a(new o("METHOD_CALL_TIMEOUT",`Method call ${r.formatMethodPath(t)}() timed out after ${M}ms`))},M):void 0;m.set(i,{methodPath:t,resolve:e,reject:a,timeoutId:s});try{const e={namespace:n,channel:c,type:"CALL",id:i,methodPath:t,args:P};h?.(`Sending ${r.formatMethodPath(t)}() call`,e),l.sendMessage(e,p)}catch(e){a(new o("TRANSMISSION_FAILED",e.message))}})},h),destroy:()=>{u=!0,l.removeMessageHandler(f);for(const{methodPath:e,reject:t,timeoutId:r}of m.values())clearTimeout(r),t(d(e));m.clear()}}};
1
+ "use strict";var e=require("../../../utils/crypto.js"),t=require("./CallOptions.js"),r=require("./errorSerialization.js"),a=require("./guards.js"),o=require("./methodSerialization.js"),s=require("./namespace.js"),n=require("./PenpalError.js");const l=new Set(["apply","call","bind"]),i=(e,t,r=[])=>new Proxy(r.length?()=>{}:Object.create(null),{get(a,o){if("then"!==o)return r.length&&l.has(o)?Reflect.get(a,o):i(e,t,[...r,o])},apply:(t,a,o)=>e(r,o)}),d=e=>new n("CONNECTION_DESTROYED",`Method call ${o.formatMethodPath(e)}() failed due to destroyed connection`);module.exports=(l,c,h)=>{let u=!1;const m=new Map,f=e=>{if(!a.isReplyMessage(e))return;const{callId:t,value:s,isError:n,isSerializedErrorInstance:l}=e,i=m.get(t);i&&(m.delete(t),h?.(`Received ${o.formatMethodPath(i.methodPath)}() call`,e),n?i.reject(l?r.deserializeError(s):s):i.resolve(s))};l.addMessageHandler(f);return{remoteProxy:i((r,a)=>{if(u)throw d(r);const i=e.randomUUID(),f=a[a.length-1],g=f instanceof t,{timeout:M,transferables:p}=g?f:{},P=g?a.slice(0,-1):a;return new Promise((e,t)=>{const a=void 0!==M?window.setTimeout(()=>{m.delete(i),t(new n("METHOD_CALL_TIMEOUT",`Method call ${o.formatMethodPath(r)}() timed out after ${M}ms`))},M):void 0;m.set(i,{methodPath:r,resolve:e,reject:t,timeoutId:a});try{const e={namespace:s,channel:c,type:"CALL",id:i,methodPath:r,args:P};h?.(`Sending ${o.formatMethodPath(r)}() call`,e),l.sendMessage(e,p)}catch(e){t(new n("TRANSMISSION_FAILED",e.message))}})},h),destroy:()=>{u=!0,l.removeMessageHandler(f);for(const{methodPath:e,reject:t,timeoutId:r}of m.values())clearTimeout(r),t(d(e));m.clear()}}};
@@ -1 +1 @@
1
- "use strict";var e=require("../backwardCompatibility.js"),s=require("../guards.js"),i=require("../PenpalError.js"),t=require("../PenpalBugError.js");module.exports=class{#e;#s;#i;#t;#r;#o=new Set;#a;#n=!1;constructor({remoteWindow:e,allowedOrigins:s}){if(!e)throw new i("INVALID_ARGUMENT","remoteWindow must be defined");this.#e=e,this.#s=s?.length?s:[window.origin]}initialize=({log:e,validateReceivedMessage:s})=>{this.#i=e,this.#t=s,window.addEventListener("message",this.#g)};sendMessage=(i,r)=>{if(s.isSynMessage(i)){const e=this.#d(i);return void this.#e.postMessage(i,{targetOrigin:e,transfer:r})}if(s.isAck1Message(i)||this.#n){const s=this.#n?e.downgradeMessage(i):i,t=this.#d(i);return void this.#e.postMessage(s,{targetOrigin:t,transfer:r})}if(s.isAck2Message(i)){const{port1:e,port2:s}=new MessageChannel;this.#a=e,e.addEventListener("message",this.#l),e.start();const t=[s,...r||[]],o=this.#d(i);return void this.#e.postMessage(i,{targetOrigin:o,transfer:t})}if(!this.#a)throw new t("Port is undefined");this.#a.postMessage(i,{transfer:r})};addMessageHandler=e=>{this.#o.add(e)};removeMessageHandler=e=>{this.#o.delete(e)};destroy=()=>{window.removeEventListener("message",this.#g),this.#h(),this.#o.clear()};#c=e=>this.#s.some(s=>s instanceof RegExp?s.test(e):s===e||"*"===s);#d=e=>{if(s.isSynMessage(e))return"*";if(!this.#r)throw new t("Concrete remote origin not set");return"null"===this.#r&&this.#s.includes("*")?"*":this.#r};#h=()=>{this.#a?.removeEventListener("message",this.#l),this.#a?.close(),this.#a=void 0};#g=({source:i,origin:r,ports:o,data:a})=>{if(i===this.#e&&(e.isDeprecatedMessage(a)&&(this.#i?.("Please upgrade the child window to the latest version of Penpal."),this.#n=!0,a=e.upgradeMessage(a)),this.#t?.(a)))if(this.#c(r)){if(s.isSynMessage(a)&&(this.#h(),this.#r=r),s.isAck2Message(a)&&!this.#n){if([this.#a]=o,!this.#a)throw new t("No port received on ACK2");this.#a.addEventListener("message",this.#l),this.#a.start()}for(const e of this.#o)e(a)}else this.#i?.(`Received a message from origin \`${r}\` which did not match allowed origins \`[${this.#s.join(", ")}]\``)};#l=({data:e})=>{if(this.#t?.(e))for(const s of this.#o)s(e)}};
1
+ "use strict";var e=require("../backwardCompatibility.js"),s=require("../guards.js"),i=require("../PenpalBugError.js"),t=require("../PenpalError.js");module.exports=class{#e;#s;#i;#t;#r;#o=new Set;#a;#n=!1;constructor({remoteWindow:e,allowedOrigins:s}){if(!e)throw new t("INVALID_ARGUMENT","remoteWindow must be defined");this.#e=e,this.#s=s?.length?s:[window.origin]}initialize=({log:e,validateReceivedMessage:s})=>{this.#i=e,this.#t=s,window.addEventListener("message",this.#g)};sendMessage=(t,r)=>{if(s.isSynMessage(t)){const e=this.#d(t);return void this.#e.postMessage(t,{targetOrigin:e,transfer:r})}if(s.isAck1Message(t)||this.#n){const s=this.#n?e.downgradeMessage(t):t,i=this.#d(t);return void this.#e.postMessage(s,{targetOrigin:i,transfer:r})}if(s.isAck2Message(t)){const{port1:e,port2:s}=new MessageChannel;this.#a=e,e.addEventListener("message",this.#l),e.start();const i=[s,...r||[]],o=this.#d(t);return void this.#e.postMessage(t,{targetOrigin:o,transfer:i})}if(!this.#a)throw new i("Port is undefined");this.#a.postMessage(t,{transfer:r})};addMessageHandler=e=>{this.#o.add(e)};removeMessageHandler=e=>{this.#o.delete(e)};destroy=()=>{window.removeEventListener("message",this.#g),this.#h(),this.#o.clear()};#c=e=>this.#s.some(s=>s instanceof RegExp?s.test(e):s===e||"*"===s);#d=e=>{if(s.isSynMessage(e))return"*";if(!this.#r)throw new i("Concrete remote origin not set");return"null"===this.#r&&this.#s.includes("*")?"*":this.#r};#h=()=>{this.#a?.removeEventListener("message",this.#l),this.#a?.close(),this.#a=void 0};#g=({source:t,origin:r,ports:o,data:a})=>{if(t===this.#e&&(e.isDeprecatedMessage(a)&&(this.#i?.("Please upgrade the child window to the latest version of Penpal."),this.#n=!0,a=e.upgradeMessage(a)),this.#t?.(a)))if(this.#c(r)){if(s.isSynMessage(a)&&(this.#h(),this.#r=r),s.isAck2Message(a)&&!this.#n){if([this.#a]=o,!this.#a)throw new i("No port received on ACK2");this.#a.addEventListener("message",this.#l),this.#a.start()}for(const e of this.#o)e(a)}else this.#i?.(`Received a message from origin \`${r}\` which did not match allowed origins \`[${this.#s.join(", ")}]\``)};#l=({data:e})=>{if(this.#t?.(e))for(const s of this.#o)s(e)}};
@@ -1 +1 @@
1
- "use strict";var e=require("../../../utils/crypto.js"),s=require("./PenpalError.js"),r=require("./connectCallHandler.js"),t=require("./connectRemoteProxy.js"),a=require("./guards.js"),n=require("./getPromiseWithResolvers.js"),o=require("./methodSerialization.js"),i=require("./backwardCompatibility.js"),c=require("./namespace.js");module.exports=({messenger:d,methods:h,timeout:m,channel:u,log:A})=>{const p=e.randomUUID();let I;const l=[];let g=!1;const P=o.extractMethodPathsFromMethods(h),{promise:S,resolve:N,reject:C}=n(),y=void 0!==m?setTimeout(()=>{C(new s("CONNECTION_TIMEOUT",`Connection timed out after ${m}ms`))},m):void 0,E=()=>{for(const e of l)e()},M=()=>{if(g)return;l.push(r(d,h,u,A));const{remoteProxy:e,destroy:s}=t(d,u,A);l.push(s),clearTimeout(y),g=!0,N({remoteProxy:e,destroy:E})},T=()=>{const e={namespace:c,type:"SYN",channel:u,participantId:p};A?.("Sending handshake SYN",e);try{d.sendMessage(e)}catch(e){C(new s("TRANSMISSION_FAILED",e.message))}},R=e=>{a.isSynMessage(e)&&(e=>{if(A?.("Received handshake SYN",e),e.participantId===I&&I!==i.DEPRECATED_PENPAL_PARTICIPANT_ID)return;if(I=e.participantId,T(),!(p>I||I===i.DEPRECATED_PENPAL_PARTICIPANT_ID))return;const r={namespace:c,channel:u,type:"ACK1",methodPaths:P};A?.("Sending handshake ACK1",r);try{d.sendMessage(r)}catch(e){C(new s("TRANSMISSION_FAILED",e.message))}})(e),a.isAck1Message(e)&&(e=>{A?.("Received handshake ACK1",e);const r={namespace:c,channel:u,type:"ACK2"};A?.("Sending handshake ACK2",r);try{d.sendMessage(r)}catch(e){return void C(new s("TRANSMISSION_FAILED",e.message))}M()})(e),a.isAck2Message(e)&&(e=>{A?.("Received handshake ACK2",e),M()})(e)};return d.addMessageHandler(R),l.push(()=>d.removeMessageHandler(R)),T(),S};
1
+ "use strict";var e=require("../../../utils/crypto.js"),s=require("./backwardCompatibility.js"),r=require("./connectCallHandler.js"),t=require("./connectRemoteProxy.js"),a=require("./getPromiseWithResolvers.js"),n=require("./guards.js"),o=require("./methodSerialization.js"),i=require("./namespace.js"),c=require("./PenpalError.js");module.exports=({messenger:d,methods:h,timeout:m,channel:u,log:A})=>{const p=e.randomUUID();let I;const l=[];let g=!1;const P=o.extractMethodPathsFromMethods(h),{promise:S,resolve:N,reject:C}=a(),y=void 0!==m?setTimeout(()=>{C(new c("CONNECTION_TIMEOUT",`Connection timed out after ${m}ms`))},m):void 0,E=()=>{for(const e of l)e()},M=()=>{if(g)return;l.push(r(d,h,u,A));const{remoteProxy:e,destroy:s}=t(d,u,A);l.push(s),clearTimeout(y),g=!0,N({remoteProxy:e,destroy:E})},T=()=>{const e={namespace:i,type:"SYN",channel:u,participantId:p};A?.("Sending handshake SYN",e);try{d.sendMessage(e)}catch(e){C(new c("TRANSMISSION_FAILED",e.message))}},R=e=>{n.isSynMessage(e)&&(e=>{if(A?.("Received handshake SYN",e),e.participantId===I&&I!==s.DEPRECATED_PENPAL_PARTICIPANT_ID)return;if(I=e.participantId,T(),!(p>I||I===s.DEPRECATED_PENPAL_PARTICIPANT_ID))return;const r={namespace:i,channel:u,type:"ACK1",methodPaths:P};A?.("Sending handshake ACK1",r);try{d.sendMessage(r)}catch(e){C(new c("TRANSMISSION_FAILED",e.message))}})(e),n.isAck1Message(e)&&(e=>{A?.("Received handshake ACK1",e);const s={namespace:i,channel:u,type:"ACK2"};A?.("Sending handshake ACK2",s);try{d.sendMessage(s)}catch(e){return void C(new c("TRANSMISSION_FAILED",e.message))}M()})(e),n.isAck2Message(e)&&(e=>{A?.("Received handshake ACK2",e),M()})(e)};return d.addMessageHandler(R),l.push(()=>d.removeMessageHandler(R)),T(),S};