@openfort/openfort-js 0.8.39 → 0.8.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/sdk/src/authManager.js +1 -1
- package/dist/cjs/sdk/src/errors/openfortError.js +1 -1
- package/dist/cjs/sdk/src/errors/sentry.js +1 -0
- package/dist/cjs/sdk/src/iframe/iframeManager.js +1 -1
- package/dist/cjs/sdk/src/openfort.js +1 -1
- package/dist/cjs/sdk/src/types.js +1 -1
- package/dist/cjs/sdk/src/version.js +1 -1
- package/dist/index.d.ts +9 -3
- package/dist/sdk/src/authManager.js +1 -1
- package/dist/sdk/src/errors/openfortError.js +1 -1
- package/dist/sdk/src/errors/sentry.js +1 -0
- package/dist/sdk/src/iframe/iframeManager.js +1 -1
- package/dist/sdk/src/openfort.js +1 -1
- package/dist/sdk/src/types.js +1 -1
- package/dist/sdk/src/version.js +1 -1
- package/package.json +6 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../packages/internal/openapi-clients/dist/index.js"),t=require("crypto"),r=require("./errors/openfortError.js"),a=require("./types.js"),i=require("./utils/deviceCredentialsManager.js"),n=require("./utils/helpers.js");function s(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var o=s(t);function l(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function c(e){return o.createHash("sha256").update(e).digest()}class p{publishableKey;deviceCredentialsManager;backendApiClients;constructor(t,r){this.publishableKey=t,this.deviceCredentialsManager=new i,this.backendApiClients=new e.BackendApiClients({backend:e.createConfig({basePath:r,accessToken:t})})}async initOAuth(e,t,r){const a=t?.usePooling??!1;delete t?.usePooling;const i={oAuthInitRequest:{provider:e,options:t,usePooling:a}},s=await this.backendApiClients.authenticationApi.initOAuth(i,p.getEcosystemGameOptsOrUndefined(r));return n.isBrowser()&&t?.skipBrowserRedirect&&window.location.assign(s.data.url),{url:s.data.url,key:s.data.key}}async registerGuest(){return(await this.backendApiClients.authenticationApi.registerGuest({})).data}async poolOAuth(e){const t={key:e};for(let e=0;e<600;e++)try{const e=await this.backendApiClients.authenticationApi.poolOAuth(t);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,a){const i={loginWithIdTokenRequest:{provider:e,token:t}};return r.withOpenfortError((async()=>(await this.backendApiClients.authenticationApi.loginWithIdToken(i,p.getEcosystemGameOptsOrUndefined(a))).data),{default:r.OpenfortErrorType.AUTHENTICATION_ERROR,403:r.OpenfortErrorType.USER_NOT_AUTHORIZED_ON_ECOSYSTEM})}async authenticateThirdParty(e,t,a,i){const n={thirdPartyOAuthRequest:{provider:e,token:t,tokenType:a}};return r.withOpenfortError((async()=>(await this.backendApiClients.authenticationApi.thirdParty(n,p.getEcosystemGameOptsOrUndefined(i))).data),{default:r.OpenfortErrorType.AUTHENTICATION_ERROR,403:r.OpenfortErrorType.USER_NOT_AUTHORIZED_ON_ECOSYSTEM})}async initSIWE(e,t){const r={sIWERequest:{address:e}},a=await this.backendApiClients.authenticationApi.initSIWE(r,p.getEcosystemGameOptsOrUndefined(t));return{address:a.data.address,nonce:a.data.nonce,expiresAt:a.data.expiresAt}}async authenticateSIWE(e,t,a,i){const n={sIWEAuthenticateRequest:{signature:e,message:t,walletClientType:a,connectorType:i}};return r.withOpenfortError((async()=>(await this.backendApiClients.authenticationApi.authenticateSIWE(n)).data),{default:r.OpenfortErrorType.AUTHENTICATION_ERROR,403:r.OpenfortErrorType.USER_NOT_AUTHORIZED_ON_ECOSYSTEM})}static getEcosystemGameOptsOrUndefined(e){if(e)return{headers:{"x-game":e}}}async loginEmailPassword(e,t,a){const i={loginRequest:{email:e,password:t}};return r.withOpenfortError((async()=>(await this.backendApiClients.authenticationApi.loginEmailPassword(i,p.getEcosystemGameOptsOrUndefined(a))).data),{default:r.OpenfortErrorType.AUTHENTICATION_ERROR,403:r.OpenfortErrorType.USER_NOT_AUTHORIZED_ON_ECOSYSTEM})}async requestResetPassword(e,t){const r=l(o.randomBytes(32)),i=l(c(r)),n=l(o.randomBytes(32));this.deviceCredentialsManager.savePKCEData({state:n,verifier:r});const s={requestResetPasswordRequest:{email:e,redirectUrl:t,challenge:{codeChallenge:i,method:a.CodeChallengeMethodEnum.S256}}};await this.backendApiClients.authenticationApi.requestResetPassword(s)}async resetPassword(e,t,a){return r.withOpenfortError((async()=>{const r=this.deviceCredentialsManager.getPKCEData();if(!r)throw new Error("No code verifier or state for PKCE");const i={resetPasswordRequest:{email:e,password:t,state:a,challenge:{codeVerifier:r.verifier}}};await this.backendApiClients.authenticationApi.resetPassword(i)}),{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})}async requestEmailVerification(e,t){const r=l(o.randomBytes(32)),i=l(c(r)),n=l(o.randomBytes(32));this.deviceCredentialsManager.savePKCEData({state:n,verifier:r});const s={requestVerifyEmailRequest:{email:e,redirectUrl:t,challenge:{codeChallenge:i,method:a.CodeChallengeMethodEnum.S256}}};await this.backendApiClients.authenticationApi.requestEmailVerification(s)}async verifyEmail(e,t){return r.withOpenfortError((async()=>{const r=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,a,i){const n={signupRequest:{email:e,password:t,name:a}};return r.withOpenfortError((async()=>(await this.backendApiClients.authenticationApi.signupEmailPassword(n,p.getEcosystemGameOptsOrUndefined(i))).data),{default:r.OpenfortErrorType.USER_REGISTRATION_ERROR,403:r.OpenfortErrorType.USER_NOT_AUTHORIZED_ON_ECOSYSTEM})}async validateCredentialsWithoutCrypto(e,t){if(!t.refreshToken)throw new r.OpenfortError("No refresh token provided",r.OpenfortErrorType.AUTHENTICATION_ERROR);if(!JWK_UTILS)throw new r.OpenfortError("JWK_UTILS not available",r.OpenfortErrorType.INTERNAL_ERROR);const a=JWK_UTILS.getKey({kty:e.kty,crv:e.crv,x:e.x,y:e.y}),i=JWK_UTILS.parse(t.token);if(!JWK_UTILS.verifyJWT(t.token,a,{alg:[e.alg]}))throw new r.OpenfortError("Invalid token signature",r.OpenfortErrorType.AUTHENTICATION_ERROR);const n=JSON.parse(i.payloadPP);if(!n.exp)return this.refreshTokens(t.refreshToken);const s=JWK_UTILS.getNow();return n.exp<s?this.refreshTokens(t.refreshToken):{player:n.sub,accessToken:t.token,refreshToken:t.refreshToken}}async validateCredentialsWithCrypto(e,t){if(!t.refreshToken)throw new r.OpenfortError("No refresh token provided",r.OpenfortErrorType.AUTHENTICATION_ERROR);const{errors:a,importJWK:i,jwtVerify:n}=await import("jose");try{const r=await i({kty:e.kty,crv:e.crv,x:e.x,y:e.y},e.alg);return{player:(await n(t.token,r)).payload.sub,accessToken:t.token,refreshToken:t.refreshToken}}catch(e){if(e instanceof a.JWTExpired)return this.refreshTokens(t.refreshToken);throw e}}async validateCredentials(e,t){const a=await this.getJWK();if(!e.refreshToken)throw new r.OpenfortError("No refresh token provided",r.OpenfortErrorType.AUTHENTICATION_ERROR);if(t)return this.refreshTokens(e.refreshToken,t);const i=p.getWebCrypto();return i?.subtle?this.validateCredentialsWithCrypto(a,e):this.validateCredentialsWithoutCrypto(a,e)}jwksStorageKey="openfort.jwk";stringToJWK(e){const t=JSON.parse(e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y,alg:t.alg}}async getJWK(){const e=sessionStorage.getItem(this.jwksStorageKey);if(e)return this.stringToJWK(e);const t={publishableKey:this.publishableKey},a=await this.backendApiClients.authenticationApi.getJwks(t);if(0===a.data.keys.length)throw new r.OpenfortError("No JWKS keys found",r.OpenfortErrorType.INTERNAL_ERROR);const i=a.data.keys[0];return sessionStorage.setItem(this.jwksStorageKey,JSON.stringify(i)),{kty:i.kty,crv:i.crv,x:i.x,y:i.y,alg:i.alg}}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}};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(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}async linkThirdParty(e,t,r,a,i){const n={thirdPartyLinkRequest:{provider:t,token:r,tokenType:a}};return(await this.backendApiClients.authenticationApi.linkThirdParty(n,{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}async linkOAuth(e,t,r,a){const i={oAuthInitRequest:{provider:t,options:r,usePooling:r?.usePooling||!1}},s=await this.backendApiClients.authenticationApi.linkOAuth(i,{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":a||void 0}});return n.isBrowser()&&!r?.skipBrowserRedirect&&window.location.assign(s.data.url),{url:s.data.url,key:s.data.key}}async unlinkOAuth(e,t){const r={unlinkOAuthRequest:{provider:e}};return(await this.backendApiClients.authenticationApi.unlinkOAuth(r,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t}})).data}async unlinkWallet(e,t){const r={sIWERequest:{address:e}};return(await this.backendApiClients.authenticationApi.unlinkSIWE(r,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t}})).data}async linkWallet(e,t,r,a,i){const n={sIWEAuthenticateRequest:{signature:e,message:t,walletClientType:r,connectorType:a}};return(await this.backendApiClients.authenticationApi.linkSIWE(n,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":i}})).data}async unlinkEmail(e,t){const r={unlinkEmailRequest:{email:e}};return(await this.backendApiClients.authenticationApi.unlinkEmail(r,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t}})).data}static getWebCrypto(){return n.isBrowser()?window.crypto:"undefined"!=typeof global&&global.crypto?global.crypto:null}async linkEmail(e,t,r,a){const i={loginRequest:{email:e,password:t}};return(await this.backendApiClients.authenticationApi.linkEmail(i,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":r,"x-game":a||void 0}})).data}}exports.AuthManager=p;
|
|
1
|
+
"use strict";var e=require("../../packages/internal/openapi-clients/dist/index.js"),t=require("crypto"),r=require("./errors/openfortError.js"),a=require("./errors/sentry.js"),n=require("./types.js"),i=require("./utils/deviceCredentialsManager.js"),o=require("./utils/helpers.js");function s(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var p=s(t);function c(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function l(e){return p.createHash("sha256").update(e).digest()}class d{publishableKey;deviceCredentialsManager;backendApiClients;constructor(t,r){this.publishableKey=t,this.deviceCredentialsManager=new i,this.backendApiClients=new e.BackendApiClients({backend:e.createConfig({basePath:r,accessToken:t})})}async initOAuth(e,t,r){const a=t?.usePooling??!1;delete t?.usePooling;const n={oAuthInitRequest:{provider:e,options:t,usePooling:a}},i=await this.backendApiClients.authenticationApi.initOAuth(n,d.getEcosystemGameOptsOrUndefined(r));return o.isBrowser()&&t?.skipBrowserRedirect&&window.location.assign(i.data.url),{url:i.data.url,key:i.data.key}}async registerGuest(){return(await this.backendApiClients.authenticationApi.registerGuest({})).data}async poolOAuth(e){const t={key:e};for(let e=0;e<600;e++)try{const e=await this.backendApiClients.authenticationApi.poolOAuth(t);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,d.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,d.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 r={sIWERequest:{address:e}},a=await this.backendApiClients.authenticationApi.initSIWE(r,d.getEcosystemGameOptsOrUndefined(t));return{address:a.data.address,nonce:a.data.nonce,expiresAt:a.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,d.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(e,t){const r=c(p.randomBytes(32)),a=c(l(r)),i=c(p.randomBytes(32));this.deviceCredentialsManager.savePKCEData({state:i,verifier:r});const o={requestResetPasswordRequest:{email:e,redirectUrl:t,challenge:{codeChallenge:a,method:n.CodeChallengeMethodEnum.S256}}};await this.backendApiClients.authenticationApi.requestResetPassword(o)}async resetPassword(e,t,a){return r.withOpenfortError((async()=>{const r=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(e,t){const r=c(p.randomBytes(32)),a=c(l(r)),i=c(p.randomBytes(32));this.deviceCredentialsManager.savePKCEData({state:i,verifier:r});const o={requestVerifyEmailRequest:{email:e,redirectUrl:t,challenge:{codeChallenge:a,method:n.CodeChallengeMethodEnum.S256}}};await this.backendApiClients.authenticationApi.requestEmailVerification(o)}async verifyEmail(e,t){return r.withOpenfortError((async()=>{const r=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,d.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 validateCredentialsWithoutCrypto(e,t){if(!t.refreshToken)throw new r.OpenfortError("No refresh token provided",r.OpenfortErrorType.AUTHENTICATION_ERROR);if(!openfort?.jwk)throw new r.OpenfortError("openfort not available",r.OpenfortErrorType.INTERNAL_ERROR);const a=openfort.jwk.getKey({kty:e.kty,crv:e.crv,x:e.x,y:e.y}),n=openfort.jwk.parse(t.token);if(!openfort.jwk.verifyJWT(t.token,a,{alg:[e.alg]}))throw new r.OpenfortError("Invalid token signature",r.OpenfortErrorType.AUTHENTICATION_ERROR);const i=JSON.parse(n.payloadPP);if(!i.exp)return this.refreshTokens(t.refreshToken);const o=openfort.jwk.getNow();return i.exp<o?this.refreshTokens(t.refreshToken):{player:i.sub,accessToken:t.token,refreshToken:t.refreshToken}}async validateCredentialsWithCrypto(e,t){if(!t.refreshToken)throw new r.OpenfortError("No refresh token provided",r.OpenfortErrorType.AUTHENTICATION_ERROR);const{errors:a,importJWK:n,jwtVerify:i}=await import("jose");try{const r=await n({kty:e.kty,crv:e.crv,x:e.x,y:e.y},e.alg);return{player:(await i(t.token,r)).payload.sub,accessToken:t.token,refreshToken:t.refreshToken}}catch(e){if(e instanceof a.JWTExpired)return this.refreshTokens(t.refreshToken);throw e}}async validateCredentials(e,t){const a=await this.getJWK();if(!e.refreshToken)throw new r.OpenfortError("No refresh token provided",r.OpenfortErrorType.AUTHENTICATION_ERROR);if(t)return this.refreshTokens(e.refreshToken,t);const n=d.getWebCrypto();return n?.subtle?this.validateCredentialsWithCrypto(a,e):this.validateCredentialsWithoutCrypto(a,e)}jwksStorageKey="openfort.jwk";stringToJWK(e){const t=JSON.parse(e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y,alg:t.alg}}async getJWK(){const e=sessionStorage.getItem(this.jwksStorageKey);if(e)return this.stringToJWK(e);const t={publishableKey:this.publishableKey},a=await this.backendApiClients.authenticationApi.getJwks(t);if(0===a.data.keys.length)throw new r.OpenfortError("No JWKS keys found",r.OpenfortErrorType.INTERNAL_ERROR);const n=a.data.keys[0];return sessionStorage.setItem(this.jwksStorageKey,JSON.stringify(n)),{kty:n.kty,crv:n.crv,x:n.x,y:n.y,alg:n.alg}}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}};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(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}async linkThirdParty(e,t,r,a,n){const i={thirdPartyLinkRequest:{provider:t,token:r,tokenType:a}};return(await this.backendApiClients.authenticationApi.linkThirdParty(i,{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}})).data}async linkOAuth(e,t,r,a){const n={oAuthInitRequest:{provider:t,options:r,usePooling:r?.usePooling||!1}},i=await this.backendApiClients.authenticationApi.linkOAuth(n,{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":a||void 0}});return o.isBrowser()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.url),{url:i.data.url,key:i.data.key}}async unlinkOAuth(e,t){const r={unlinkOAuthRequest:{provider:e}};return(await this.backendApiClients.authenticationApi.unlinkOAuth(r,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t}})).data}async unlinkWallet(e,t){const r={sIWERequest:{address:e}};return(await this.backendApiClients.authenticationApi.unlinkSIWE(r,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t}})).data}async linkWallet(e,t,r,a,n){const i={sIWEAuthenticateRequest:{signature:e,message:t,walletClientType:r,connectorType:a}};return(await this.backendApiClients.authenticationApi.linkSIWE(i,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":n}})).data}async unlinkEmail(e,t){const r={unlinkEmailRequest:{email:e}};return(await this.backendApiClients.authenticationApi.unlinkEmail(r,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t}})).data}static getWebCrypto(){return o.isBrowser()?window.crypto:"undefined"!=typeof global&&global.crypto?global.crypto:null}async linkEmail(e,t,r,a){const n={loginRequest:{email:e,password:t}};return(await this.backendApiClients.authenticationApi.linkEmail(n,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":r,"x-game":a||void 0}})).data}}exports.AuthManager=d;
|
|
@@ -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.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_SESSION_SIGNER_ERROR="MISSING_SESSION_SIGNER_ERROR",R.MISSING_EMBEDDED_SIGNER_ERROR="MISSING_EMBEDDED_SIGNER_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)=>{try{return await R()}catch(R){let e;const
|
|
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.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_SESSION_SIGNER_ERROR="MISSING_SESSION_SIGNER_ERROR",R.MISSING_EMBEDDED_SIGNER_ERROR="MISSING_EMBEDDED_SIGNER_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,_)=>{try{return await R()}catch(R){let e;const I={};let N;E.isAxiosError(R)?(N=R.response?.status,e=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):e=R.message;const t=void 0!==N&&r[N]?r[N]:r.default,s=new O(e,t,I);throw void 0!==N&&r[N]||_?.(R,s),s}};
|
|
@@ -0,0 +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,openfortConfiguration: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?.publishableKey||"unknown",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 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../storage/istorage.js"),t=require("../storage/localStorage.js"),r=require("./types.js");class
|
|
1
|
+
"use strict";var e=require("../storage/istorage.js"),t=require("../storage/localStorage.js"),r=require("./types.js");class o extends Error{constructor(){super("This embedded signer requires a password to be recovered")}}class s extends Error{constructor(){super("MissingProjectEntropyError")}}class i extends Error{constructor(){super("Wrong recovery password for this embedded signer")}}class n extends Error{constructor(){super("No response from iframe")}}class a extends Error{message;constructor(e){super(`Unknown response from iframe: ${e}`),this.message=e||""}}class d extends Error{constructor(){super("Invalid response from iframe")}}class h extends Error{constructor(){super("Not configured")}}exports.IframeManager=class{iframe;responses=new Map;storage;sdkConfiguration;constructor(e){this.sdkConfiguration=e,this.storage=new t.LocalStorage}async iframeSetup(){if(window.addEventListener){window.addEventListener("message",(e=>{const t=new URL(this.sdkConfiguration.iframeUrl).origin;if(new URL(e.origin).origin===t){const{data:t}=e;t.action&&(t.action===r.Event.PONG&&this.responses.set("FIRST",t),this.responses.set(t.uuid,t))}}));const e=document.getElementById("openfort-iframe");e&&document.body.removeChild(e);const t=document.createElement("iframe");t.style.display="none",t.id="openfort-iframe",document.body.appendChild(t),this.sdkConfiguration.shieldConfiguration?.debug?t.src=`${this.sdkConfiguration.iframeUrl}?debug=true`:t.src=this.sdkConfiguration.iframeUrl,this.iframe=t}else{if(!global.openfort)return;global.openfort.iframeListener((e=>{const t=new URL(this.sdkConfiguration.iframeUrl).origin;if(new URL(e.origin).origin===t){let{data:t}=e;"string"==typeof t&&(t=JSON.parse(t)),t.action&&this.responses.set(t.uuid,t)}})),this.iframe={contentWindow:{postMessage:e=>{global.openfort&&global.openfort.iframePostMessage(e)}}}}}isLoaded(){return void 0!==this.responses.get("FIRST")}async waitForIframeLoad(){this.iframe||await this.iframeSetup();const e=async()=>{this.isLoaded()||(this.iframe?.contentWindow?.postMessage(new r.PingRequest(this.generateShortUUID()),"*"),await new Promise((e=>{setTimeout(e,100)})),await e())};await e()}responseConstructors={[r.Event.CONFIGURED]:r.ConfigureResponse,[r.Event.AUTHENTICATION_UPDATED]:r.UpdateAuthenticationResponse,[r.Event.CURRENT_DEVICE]:r.GetCurrentDeviceResponse,[r.Event.SIGNED]:r.SignResponse,[r.Event.CHAIN_SWITCHED]:r.SwitchChainResponse,[r.Event.LOGGED_OUT]:r.LogoutResponse,[r.Event.SET_RECOVERY_METHOD]:r.SetRecoveryMethodResponse,[r.Event.EXPORT]:r.ExportPrivateKeyResponse};waitForResponse(e){return new Promise(((t,c)=>{let u=0;const f=setInterval((()=>{u>100&&(clearInterval(f),c(new n)),u++;const p=this.responses.get(e);if(p){clearInterval(f),this.responses.delete(e);const n=this.responseConstructors[p.action];r.isErrorResponse(p)?(p.error===r.NOT_CONFIGURED_ERROR?c(new h):p.error===r.MISSING_USER_ENTROPY_ERROR?c(new o):p.error===r.MISSING_PROJECT_ENTROPY_ERROR?c(new s):p.error===r.INCORRECT_USER_ENTROPY_ERROR&&c(new i),c(new a(p.error))):n?t(p):c(new d)}}),100)}))}async configure(t){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");await this.waitForIframeLoad();const s={uuid:this.generateShortUUID(),action:r.Event.CONFIGURE,chainId:t.chainId,recovery:t.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration.shieldPublishableKey,accessToken:t.accessToken,playerID:t.playerID,thirdPartyProvider:t.thirdPartyProvider,thirdPartyTokenType:t.thirdPartyTokenType,encryptionKey:t.password,encryptionPart:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??null,encryptionSession:t.recovery?.encryptionSession??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl};let n;this.iframe?.contentWindow?.postMessage(s,"*");try{n=await this.waitForResponse(s.uuid)}catch(t){throw(t instanceof i||t instanceof o)&&this.storage.remove(e.StorageKeys.SIGNER),t}return sessionStorage.setItem("iframe-version",n.version??"undefined"),n}async sign(e,t,o,s){await this.waitForIframeLoad();const i=this.generateShortUUID(),n={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},a=new r.SignRequest(i,t,o,s,n);let d;this.iframe?.contentWindow?.postMessage(a,"*");try{d=await this.waitForResponse(i)}catch(r){if(r instanceof h)return await this.configure(e),this.sign(e,t,o,s);throw r}return sessionStorage.setItem("iframe-version",d.version??"undefined"),d.signature}async switchChain(e,t){await this.waitForIframeLoad();const o=this.generateShortUUID(),s={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},i=new r.SwitchChainRequest(o,t,s);let n;this.iframe?.contentWindow?.postMessage(i,"*");try{n=await this.waitForResponse(o)}catch(r){if(r instanceof h)return await this.configure(e),this.switchChain(e,t);throw r}return sessionStorage.setItem("iframe-version",n.version??"undefined"),n}async export(e){await this.waitForIframeLoad();const t=this.generateShortUUID(),o={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},s=new r.ExportPrivateKeyRequest(t,o);let i;this.iframe?.contentWindow?.postMessage(s,"*");try{i=await this.waitForResponse(t)}catch(t){if(t instanceof h)return await this.configure(e),this.export(e);throw t}return sessionStorage.setItem("iframe-version",i.version??"undefined"),i.key}async setEmbeddedRecovery(e,t,o,s){await this.waitForIframeLoad();const i=this.generateShortUUID(),n={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},a=new r.SetRecoveryMethodRequest(i,t,o,s,n);let d;this.iframe?.contentWindow?.postMessage(a,"*");try{d=await this.waitForResponse(i)}catch(r){if(r instanceof h)return await this.configure(e),this.setEmbeddedRecovery(e,t,o,s);throw r}return sessionStorage.setItem("iframe-version",d.version??"undefined"),Promise.resolve()}async getCurrentUser(e){await this.waitForIframeLoad();const t=this.generateShortUUID(),o=new r.GetCurrentDeviceRequest(t,e);this.iframe?.contentWindow?.postMessage(o,"*");try{const e=await this.waitForResponse(t);return sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof h)return null;throw e}}async logout(){await this.waitForIframeLoad();const e=this.generateShortUUID(),t=new r.LogoutRequest(e);this.iframe?.contentWindow?.postMessage(t,"*"),await this.waitForResponse(e)}async updateAuthentication(e,t,o){e.accessToken=t,o===r.ShieldAuthType.OPENFORT&&e.recovery&&(e.recovery.token=t),await this.waitForIframeLoad();const s=this.generateShortUUID(),i=new r.UpdateAuthenticationRequest(s,t);this.iframe?.contentWindow?.postMessage(i,"*");try{await this.waitForResponse(s)}catch(r){if(r instanceof h)return await this.configure(e),void await this.updateAuthentication(e,t,o);throw r}}generateShortUUID(e=8){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let r="";for(let o=0;o<e;o++)r+=t.charAt(Math.floor(62*Math.random()));return r}},exports.InvalidResponseError=d,exports.MissingProjectEntropyError=s,exports.MissingRecoveryPasswordError=o,exports.NoResponseError=n,exports.NotConfiguredError=h,exports.UnknownResponseError=a,exports.WrongRecoveryPasswordError=i;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../packages/internal/openapi-clients/dist/index.js"),t=require("./evm/walletHelpers.js"),r=require("./storage/istorage.js"),a=require("./storage/localStorage.js"),n=require("./manager/signer.js"),o=require("./errors/openfortError.js"),i=require("./types.js"),s=require("./configuration/configuration.js"),u=require("./configuration/account.js"),h=require("./configuration/authentication.js"),g=require("./iframe/iframeManager.js"),d=require("./authManager.js"),c=require("./evm/evmProvider.js");require("./evm/types.js");var l=require("./utils/typedEventEmitter.js"),p=require("./evm/provider/eip6963.js");exports.Openfort=class{storage;provider=null;iAuthManager=null;constructor(e){this.storage=new a.LocalStorage;new s.Configuration(e.baseConfiguration.publishableKey,e.overrides?.backendUrl||"https://api.openfort.xyz",e.shieldConfiguration?.shieldPublishableKey||"",e.shieldConfiguration?.shieldEncryptionKey||"",e.overrides?.shieldUrl||"https://shield.openfort.xyz",e.overrides?.iframeUrl||"https://embedded.openfort.xyz",e.shieldConfiguration?.debug||!1).save()}async logout(){const e=n.SignerManager.fromStorage();this.storage.remove(r.StorageKeys.AUTHENTICATION),this.storage.remove(r.StorageKeys.SIGNER),this.storage.remove(r.StorageKeys.ACCOUNT),e&&await e.logout()}getEthereumProvider(e){const t={announceProvider:!0,...e},r=h.Authentication.fromStorage(this.storage),a=n.SignerManager.fromStorage(),o=u.Account.fromStorage(this.storage);return this.provider?this.provider&&t.policy&&this.provider.updatePolicy(t.policy):(this.provider=new c.EvmProvider({storage:this.storage,openfortEventEmitter:new l,signer:a||void 0,account:o||void 0,authentication:r||void 0,backendApiClients:this.backendApiClients,policyId:t.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this)}),t.announceProvider&&p.announceProvider({info:{...p.openfortProviderInfo,...t.providerInfo},provider:this.provider})),this.provider}async configureEmbeddedSigner(e=null,t=null,r=null){await this.validateAndRefreshToken();const a=s.Configuration.fromStorage();let o=null;(r||t?.encryptionSession)&&(o={encryptionSession:t?.encryptionSession||null,recoveryPassword:r||null,encryptionPart:a?.shieldEncryptionKey||null});let i=null,u=null;t&&(i="openfort"===t.auth?"openfort":"custom",u=t.token),await n.SignerManager.embedded(e,o,i,u)}async signMessage(e,t){await this.validateAndRefreshToken();const r=n.SignerManager.fromStorage();if(!r)throw new o.OpenfortError("No signer configured",o.OpenfortErrorType.MISSING_SIGNER_ERROR);const{hashMessage:a=!0,arrayifyMessage:i=!1}=t||{};return await r.sign(e,i,a)}async signTypedData(e,r,a){await this.validateAndRefreshToken();const i=n.SignerManager.fromStorage(),s=u.Account.fromStorage(this.storage);if(!i||!s)throw new o.OpenfortError("No signer configured",o.OpenfortErrorType.MISSING_SIGNER_ERROR);return await t.getSignedTypedData({domain:e,types:r,message:a},s.type,Number(s.chainId),i,s.address)}async exportPrivateKey(){await this.validateAndRefreshToken();const e=n.SignerManager.fromStorage();if(!e)throw new o.OpenfortError("No signer configured",o.OpenfortErrorType.MISSING_SIGNER_ERROR);return await e.export()}async setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:t,encryptionSession:r}){await this.validateAndRefreshToken();const a=n.SignerManager.fromStorage();if(!a)throw new o.OpenfortError("No signer configured",o.OpenfortErrorType.MISSING_SIGNER_ERROR);if("embedded"!==a.type())throw new o.OpenfortError("Signer must be embedded",o.OpenfortErrorType.INVALID_CONFIGURATION);if("password"===e&&!t)throw new o.OpenfortError("Recovery password is required",o.OpenfortErrorType.INVALID_CONFIGURATION);await a.setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:t,encryptionSession:r})}async logInWithEmailPassword({email:e,password:t,ecosystemGame:r}){const a=h.Authentication.fromStorage(this.storage),n=await this.authManager.loginEmailPassword(e,t,r);return a&&a.player!==n.player.id&&this.logout(),new h.Authentication("jwt",n.token,n.player.id,n.refreshToken).save(this.storage),n}async signUpGuest(){const e=h.Authentication.fromStorage(this.storage),t=await this.authManager.registerGuest();return e&&e.player!==t.player.id&&this.logout(),new h.Authentication("jwt",t.token,t.player.id,t.refreshToken).save(this.storage),t}async signUpWithEmailPassword({email:e,password:t,options:r,ecosystemGame:a}){const n=h.Authentication.fromStorage(this.storage),o=await this.authManager.signupEmailPassword(e,t,r?.data.name,a);return n&&n.player!==o.player.id&&this.logout(),new h.Authentication("jwt",o.token,o.player.id,o.refreshToken).save(this.storage),o}async linkEmailPassword({email:e,password:t,authToken:r,ecosystemGame:a}){return await this.authManager.linkEmail(e,t,r,a)}async unlinkEmailPassword({email:e,authToken:t}){return await this.authManager.unlinkEmail(e,t)}async requestEmailVerification({email:e,redirectUrl:t}){await this.authManager.requestEmailVerification(e,t)}async resetPassword({email:e,password:t,state:r}){await this.authManager.resetPassword(e,t,r)}async requestResetPassword({email:e,redirectUrl:t}){await this.authManager.requestResetPassword(e,t)}async verifyEmail({email:e,state:t}){await this.authManager.verifyEmail(e,t)}async initOAuth({provider:e,options:t,ecosystemGame:a}){return this.storage.remove(r.StorageKeys.AUTHENTICATION),await this.authManager.initOAuth(e,t,a)}async initLinkOAuth({provider:e,options:t,ecosystemGame:r}){const a=h.Authentication.fromStorage(this.storage);if(!a)throw new o.OpenfortError("No authentication found",o.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return await this.authManager.linkOAuth(a,e,t,r)}async linkThirdPartyProvider({provider:e,token:t,tokenType:r}){const a=h.Authentication.fromStorage(this.storage);if(!a)throw new o.OpenfortError("No authentication found",o.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return await this.authManager.linkThirdParty(a,e,t,r)}async unlinkOAuth({provider:e,authToken:t}){return await this.authManager.unlinkOAuth(e,t)}async poolOAuth(e){const t=h.Authentication.fromStorage(this.storage),r=await this.authManager.poolOAuth(e);return t&&t.player!==r.player.id&&this.logout(),new h.Authentication("jwt",r.token,r.player.id,r.refreshToken).save(this.storage),r}async authenticateWithThirdPartyProvider({provider:e,token:t,tokenType:r,ecosystemGame:a}){const o=h.Authentication.fromStorage(this.storage),i=await this.authManager.authenticateThirdParty(e,t,r,a);let s=!1;if(o&&o.player!==i.id&&(this.logout(),s=!0),new h.Authentication("third_party",t,i.id,null,e,r).save(this.storage),s)return i;const u=n.SignerManager.fromStorage();try{await(u?.updateAuthentication())}catch(e){throw(e instanceof g.MissingRecoveryPasswordError||e instanceof g.MissingProjectEntropyError)&&await(u?.logout()),e}return i}async loginWithIdToken({provider:e,token:t,ecosystemGame:r}){const a=h.Authentication.fromStorage(this.storage),n=await this.authManager.loginWithIdToken(e,t,r);return a&&a.player!==n.player.id&&this.logout(),new h.Authentication("jwt",n.token,n.player.id,n.refreshToken).save(this.storage),n}async initSIWE({address:e,ecosystemGame:t}){return await this.authManager.initSIWE(e,t)}async authenticateWithSIWE({signature:e,message:t,walletClientType:r,connectorType:a}){const n=h.Authentication.fromStorage(this.storage),o=await this.authManager.authenticateSIWE(e,t,r,a);return n&&n.player!==o.player.id&&this.logout(),new h.Authentication("jwt",o.token,o.player.id,o.refreshToken).save(this.storage),o}async linkWallet({signature:e,message:t,walletClientType:r,connectorType:a,authToken:n}){return await this.authManager.linkWallet(e,t,r,a,n)}async unlinkWallet({address:e,authToken:t}){return await this.authManager.unlinkWallet(e,t)}storeCredentials(e){if(this.storage.remove(r.StorageKeys.AUTHENTICATION),!e.player)throw new o.OpenfortError("Player ID is required to store credentials",o.OpenfortErrorType.INVALID_CONFIGURATION);new h.Authentication("jwt",e.accessToken,e.player,e.refreshToken).save(this.storage)}async sendSignatureTransactionIntentRequest(e,t=null,r=null,a=!1){if(!s.Configuration.fromStorage())throw new o.OpenfortError("Configuration not found",o.OpenfortErrorType.INVALID_CONFIGURATION);await this.validateAndRefreshToken();let i=r;if(!i){if(!t)throw new o.OpenfortError("No signableHash or signature provided",o.OpenfortErrorType.OPERATION_NOT_SUPPORTED_ERROR);const e=n.SignerManager.fromStorage();if(!e)throw new o.OpenfortError("In order to sign a transaction intent, a signer must be configured",o.OpenfortErrorType.MISSING_SIGNER_ERROR);i=await e.sign(t)}const u={id:e,signatureRequest:{signature:i,optimistic:a}};return(await this.backendApiClients.transactionIntentsApi.signature(u)).data}async getAccount(){const e=u.Account.fromStorage(this.storage);if(!e)throw new o.OpenfortError("No signer configured",o.OpenfortErrorType.MISSING_SIGNER_ERROR);return{chainId:e.chainId,address:e.address,ownerAddress:e.ownerAddress,accountType:e.type}}get backendApiClients(){const t=s.Configuration.fromStorage();if(!t)throw new o.OpenfortError("Configuration not found",o.OpenfortErrorType.INVALID_CONFIGURATION);return new e.BackendApiClients({backend:e.createConfig({basePath:t.openfortURL,accessToken:t.publishableKey})})}async sendSignatureSessionRequest(e,t,r){const a={id:e,signatureRequest:{signature:t,optimistic:r}};return(await this.backendApiClients.sessionsApi.signatureSession(a)).data}getEmbeddedState(){if(!h.Authentication.fromStorage(this.storage))return i.EmbeddedState.UNAUTHENTICATED;const e=n.SignerManager.fromStorage();if(!e||"embedded"!==e.type())return i.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED;return u.Account.fromStorage(this.storage)?i.EmbeddedState.READY:i.EmbeddedState.CREATING_ACCOUNT}getAccessToken(){return h.Authentication.fromStorage(this.storage)?.token??null}get authManager(){if(!this.iAuthManager){const e=s.Configuration.fromStorage();if(!e)throw new o.OpenfortError("Configuration not found",o.OpenfortErrorType.INVALID_CONFIGURATION);this.iAuthManager=new d.AuthManager(e.publishableKey,e.openfortURL)}return this.iAuthManager}async getUser(){await this.validateAndRefreshToken();const e=h.Authentication.fromStorage(this.storage);if(!e)throw new o.OpenfortError("No access token found",o.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return await this.authManager.getUser(e)}async validateAndRefreshToken(e){const t=h.Authentication.fromStorage(this.storage);if(!t)throw new o.OpenfortError("Must be logged in to validate and refresh token",o.OpenfortErrorType.NOT_LOGGED_IN_ERROR);if("jwt"!==t.type)return;const r=await this.authManager.validateCredentials(t,e);if(!r.player)throw new o.OpenfortError("No player found in credentials",o.OpenfortErrorType.INTERNAL_ERROR);if(r.accessToken===t.token)return;new h.Authentication("jwt",r.accessToken,r.player,r.refreshToken).save(this.storage);const a=n.SignerManager.fromStorage();try{await(a?.updateAuthentication())}catch(e){throw(e instanceof g.MissingRecoveryPasswordError||e instanceof g.MissingProjectEntropyError)&&await(a?.logout()),e}}};
|
|
1
|
+
"use strict";var e=require("../../packages/internal/openapi-clients/dist/index.js"),t=require("./evm/walletHelpers.js"),r=require("./errors/sentry.js"),a=require("./storage/istorage.js"),n=require("./storage/localStorage.js"),o=require("./manager/signer.js"),i=require("./errors/openfortError.js"),s=require("./types.js"),u=require("./configuration/configuration.js"),h=require("./configuration/account.js"),g=require("./configuration/authentication.js"),c=require("./iframe/iframeManager.js"),d=require("./authManager.js"),l=require("./evm/evmProvider.js");require("./evm/types.js");var p=require("./utils/typedEventEmitter.js"),f=require("./evm/provider/eip6963.js");exports.Openfort=class{storage;provider=null;iAuthManager=null;constructor(e){this.storage=new n.LocalStorage;const t=new u.Configuration(e.baseConfiguration.publishableKey,e.overrides?.backendUrl||"https://api.openfort.xyz",e.shieldConfiguration?.shieldPublishableKey||"",e.shieldConfiguration?.shieldEncryptionKey||"",e.overrides?.shieldUrl||"https://shield.openfort.xyz",e.overrides?.iframeUrl||"https://embedded.openfort.xyz",e.shieldConfiguration?.debug||!1);r.InternalSentry.init({openfortConfiguration:t}),t.save()}async logout(){const e=o.SignerManager.fromStorage();this.storage.remove(a.StorageKeys.AUTHENTICATION),this.storage.remove(a.StorageKeys.SIGNER),this.storage.remove(a.StorageKeys.ACCOUNT),e&&await e.logout()}getEthereumProvider(e){const t={announceProvider:!0,...e},r=g.Authentication.fromStorage(this.storage),a=o.SignerManager.fromStorage(),n=h.Account.fromStorage(this.storage);return this.provider?this.provider&&t.policy&&this.provider.updatePolicy(t.policy):(this.provider=new l.EvmProvider({storage:this.storage,openfortEventEmitter:new p,signer:a||void 0,account:n||void 0,authentication:r||void 0,backendApiClients:this.backendApiClients,policyId:t.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this)}),t.announceProvider&&f.announceProvider({info:{...f.openfortProviderInfo,...t.providerInfo},provider:this.provider})),this.provider}async configureEmbeddedSigner(e=null,t=null,r=null){await this.validateAndRefreshToken();const a=u.Configuration.fromStorage();let n=null;(r||t?.encryptionSession)&&(n={encryptionSession:t?.encryptionSession||null,recoveryPassword:r||null,encryptionPart:a?.shieldEncryptionKey||null});let i=null,s=null;t&&(i="openfort"===t.auth?"openfort":"custom",s=t.token),await o.SignerManager.embedded(e,n,i,s)}async signMessage(e,t){await this.validateAndRefreshToken();const r=o.SignerManager.fromStorage();if(!r)throw new i.OpenfortError("No signer configured",i.OpenfortErrorType.MISSING_SIGNER_ERROR);const{hashMessage:a=!0,arrayifyMessage:n=!1}=t||{};return await r.sign(e,n,a)}async signTypedData(e,r,a){await this.validateAndRefreshToken();const n=o.SignerManager.fromStorage(),s=h.Account.fromStorage(this.storage);if(!n||!s)throw new i.OpenfortError("No signer configured",i.OpenfortErrorType.MISSING_SIGNER_ERROR);return await t.getSignedTypedData({domain:e,types:r,message:a},s.type,Number(s.chainId),n,s.address)}async exportPrivateKey(){await this.validateAndRefreshToken();const e=o.SignerManager.fromStorage();if(!e)throw new i.OpenfortError("No signer configured",i.OpenfortErrorType.MISSING_SIGNER_ERROR);return await e.export()}async setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:t,encryptionSession:r}){await this.validateAndRefreshToken();const a=o.SignerManager.fromStorage();if(!a)throw new i.OpenfortError("No signer configured",i.OpenfortErrorType.MISSING_SIGNER_ERROR);if("embedded"!==a.type())throw new i.OpenfortError("Signer must be embedded",i.OpenfortErrorType.INVALID_CONFIGURATION);if("password"===e&&!t)throw new i.OpenfortError("Recovery password is required",i.OpenfortErrorType.INVALID_CONFIGURATION);await a.setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:t,encryptionSession:r})}async logInWithEmailPassword({email:e,password:t,ecosystemGame:r}){const a=g.Authentication.fromStorage(this.storage),n=await this.authManager.loginEmailPassword(e,t,r);return"action"in n||(a&&a.player!==n.player.id&&this.logout(),new g.Authentication("jwt",n.token,n.player.id,n.refreshToken).save(this.storage)),n}async signUpGuest(){const e=g.Authentication.fromStorage(this.storage),t=await this.authManager.registerGuest();return e&&e.player!==t.player.id&&this.logout(),new g.Authentication("jwt",t.token,t.player.id,t.refreshToken).save(this.storage),t}async signUpWithEmailPassword({email:e,password:t,options:r,ecosystemGame:a}){const n=g.Authentication.fromStorage(this.storage),o=await this.authManager.signupEmailPassword(e,t,r?.data.name,a);return"action"in o||(n&&n.player!==o.player.id&&this.logout(),new g.Authentication("jwt",o.token,o.player.id,o.refreshToken).save(this.storage)),o}async linkEmailPassword({email:e,password:t,authToken:r,ecosystemGame:a}){return await this.authManager.linkEmail(e,t,r,a)}async unlinkEmailPassword({email:e,authToken:t}){return await this.authManager.unlinkEmail(e,t)}async requestEmailVerification({email:e,redirectUrl:t}){await this.authManager.requestEmailVerification(e,t)}async resetPassword({email:e,password:t,state:r}){await this.authManager.resetPassword(e,t,r)}async requestResetPassword({email:e,redirectUrl:t}){await this.authManager.requestResetPassword(e,t)}async verifyEmail({email:e,state:t}){await this.authManager.verifyEmail(e,t)}async initOAuth({provider:e,options:t,ecosystemGame:r}){return this.storage.remove(a.StorageKeys.AUTHENTICATION),await this.authManager.initOAuth(e,t,r)}async initLinkOAuth({provider:e,options:t,ecosystemGame:r}){const a=g.Authentication.fromStorage(this.storage);if(!a)throw new i.OpenfortError("No authentication found",i.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return await this.authManager.linkOAuth(a,e,t,r)}async linkThirdPartyProvider({provider:e,token:t,tokenType:r}){const a=g.Authentication.fromStorage(this.storage);if(!a)throw new i.OpenfortError("No authentication found",i.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return await this.authManager.linkThirdParty(a,e,t,r)}async unlinkOAuth({provider:e,authToken:t}){return await this.authManager.unlinkOAuth(e,t)}async poolOAuth(e){const t=g.Authentication.fromStorage(this.storage),r=await this.authManager.poolOAuth(e);return t&&t.player!==r.player.id&&this.logout(),new g.Authentication("jwt",r.token,r.player.id,r.refreshToken).save(this.storage),r}async authenticateWithThirdPartyProvider({provider:e,token:t,tokenType:r,ecosystemGame:a}){const n=g.Authentication.fromStorage(this.storage),i=await this.authManager.authenticateThirdParty(e,t,r,a);let s=!1;if(n&&n.player!==i.id&&(this.logout(),s=!0),new g.Authentication("third_party",t,i.id,null,e,r).save(this.storage),s)return i;const u=o.SignerManager.fromStorage();try{await(u?.updateAuthentication())}catch(e){throw(e instanceof c.MissingRecoveryPasswordError||e instanceof c.MissingProjectEntropyError)&&await(u?.logout()),e}return i}async loginWithIdToken({provider:e,token:t,ecosystemGame:r}){const a=g.Authentication.fromStorage(this.storage),n=await this.authManager.loginWithIdToken(e,t,r);return a&&a.player!==n.player.id&&this.logout(),new g.Authentication("jwt",n.token,n.player.id,n.refreshToken).save(this.storage),n}async initSIWE({address:e,ecosystemGame:t}){return await this.authManager.initSIWE(e,t)}async authenticateWithSIWE({signature:e,message:t,walletClientType:r,connectorType:a}){const n=g.Authentication.fromStorage(this.storage),o=await this.authManager.authenticateSIWE(e,t,r,a);return n&&n.player!==o.player.id&&this.logout(),new g.Authentication("jwt",o.token,o.player.id,o.refreshToken).save(this.storage),o}async linkWallet({signature:e,message:t,walletClientType:r,connectorType:a,authToken:n}){return await this.authManager.linkWallet(e,t,r,a,n)}async unlinkWallet({address:e,authToken:t}){return await this.authManager.unlinkWallet(e,t)}storeCredentials(e){if(this.storage.remove(a.StorageKeys.AUTHENTICATION),!e.player)throw new i.OpenfortError("Player ID is required to store credentials",i.OpenfortErrorType.INVALID_CONFIGURATION);new g.Authentication("jwt",e.accessToken,e.player,e.refreshToken).save(this.storage)}async sendSignatureTransactionIntentRequest(e,t=null,r=null,a=!1){if(!u.Configuration.fromStorage())throw new i.OpenfortError("Configuration not found",i.OpenfortErrorType.INVALID_CONFIGURATION);await this.validateAndRefreshToken();let n=r;if(!n){if(!t)throw new i.OpenfortError("No signableHash or signature provided",i.OpenfortErrorType.OPERATION_NOT_SUPPORTED_ERROR);const e=o.SignerManager.fromStorage();if(!e)throw new i.OpenfortError("In order to sign a transaction intent, a signer must be configured",i.OpenfortErrorType.MISSING_SIGNER_ERROR);n=await e.sign(t)}const s={id:e,signatureRequest:{signature:n,optimistic:a}};return(await this.backendApiClients.transactionIntentsApi.signature(s)).data}async getAccount(){const e=h.Account.fromStorage(this.storage);if(!e)throw new i.OpenfortError("No signer configured",i.OpenfortErrorType.MISSING_SIGNER_ERROR);return{chainId:e.chainId,address:e.address,ownerAddress:e.ownerAddress,accountType:e.type}}get backendApiClients(){const t=u.Configuration.fromStorage();if(!t)throw new i.OpenfortError("Configuration not found",i.OpenfortErrorType.INVALID_CONFIGURATION);return new e.BackendApiClients({backend:e.createConfig({basePath:t.openfortURL,accessToken:t.publishableKey})})}async sendSignatureSessionRequest(e,t,r){const a={id:e,signatureRequest:{signature:t,optimistic:r}};return(await this.backendApiClients.sessionsApi.signatureSession(a)).data}getEmbeddedState(){if(!g.Authentication.fromStorage(this.storage))return s.EmbeddedState.UNAUTHENTICATED;const e=o.SignerManager.fromStorage();if(!e||"embedded"!==e.type())return s.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED;return h.Account.fromStorage(this.storage)?s.EmbeddedState.READY:s.EmbeddedState.CREATING_ACCOUNT}getAccessToken(){return g.Authentication.fromStorage(this.storage)?.token??null}get authManager(){if(!this.iAuthManager){const e=u.Configuration.fromStorage();if(!e)throw new i.OpenfortError("Configuration not found",i.OpenfortErrorType.INVALID_CONFIGURATION);this.iAuthManager=new d.AuthManager(e.publishableKey,e.openfortURL)}return this.iAuthManager}async getUser(){await this.validateAndRefreshToken();const e=g.Authentication.fromStorage(this.storage);if(!e)throw new i.OpenfortError("No access token found",i.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return await this.authManager.getUser(e)}async validateAndRefreshToken(e){const t=g.Authentication.fromStorage(this.storage);if(!t)throw new i.OpenfortError("Must be logged in to validate and refresh token",i.OpenfortErrorType.NOT_LOGGED_IN_ERROR);if("jwt"!==t.type)return;const r=await this.authManager.validateCredentials(t,e);if(!r.player)throw new i.OpenfortError("No player found in credentials",i.OpenfortErrorType.INTERNAL_ERROR);if(r.accessToken===t.token)return;new g.Authentication("jwt",r.accessToken,r.player,r.refreshToken).save(this.storage);const a=o.SignerManager.fromStorage();try{await(a?.updateAuthentication())}catch(e){throw(e instanceof c.MissingRecoveryPasswordError||e instanceof c.MissingProjectEntropyError)&&await(a?.logout()),e}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e,o,t,r,E,A,p,d,s;exports.EmbeddedState=void 0,(e=exports.EmbeddedState||(exports.EmbeddedState={}))[e.NONE=0]="NONE",e[e.UNAUTHENTICATED=1]="UNAUTHENTICATED",e[e.EMBEDDED_SIGNER_NOT_CONFIGURED=2]="EMBEDDED_SIGNER_NOT_CONFIGURED",e[e.CREATING_ACCOUNT=3]="CREATING_ACCOUNT",e[e.READY=4]="READY",exports.OpenfortEvents=void 0,(exports.OpenfortEvents||(exports.OpenfortEvents={})).LOGGED_OUT="loggedOut",exports.RecoveryMethod=void 0,(o=exports.RecoveryMethod||(exports.RecoveryMethod={})).PASSWORD="password",o.AUTOMATIC="automatic",exports.AccountType=void 0,(t=exports.AccountType||(exports.AccountType={})).UPGRADEABLE_V4="Upgradeable_v04",t.MANAGED_V4="Managed_v04",t.ERC6551_V4="ERC6551_v04",t.ERC6551_V5="ERC6551_v05",t.RECOVERABLE_V4="Recoverable_v04",t.MANAGED_V5="Managed_v05",t.UPGRADEABLE_V5="Upgradeable_v05",t.UPGRADEABLE_V6="Upgradeable_v06",t.ZKSYNC_UPGRADEABLE_V1="zksync_upgradeable_v1",t.ZKSYNC_UPGRADEABLE_V2="zksync_upgradeable_v2",exports.AuthType=void 0,(r=exports.AuthType||(exports.AuthType={})).OPENFORT="openfort",r.THIRD_PARTY="thirdParty",exports.TokenType=void 0,(E=exports.TokenType||(exports.TokenType={})).ID_TOKEN="idToken",E.CUSTOM_TOKEN="customToken",exports.ThirdPartyOAuthProvider=void 0,(A=exports.ThirdPartyOAuthProvider||(exports.ThirdPartyOAuthProvider={})).ACCELBYTE="accelbyte",A.FIREBASE="firebase",A.LOOTLOCKER="lootlocker",A.PLAYFAB="playfab",A.SUPABASE="supabase",A.CUSTOM="custom",A.OIDC="oidc",exports.BasicAuthProvider=void 0,(p=exports.BasicAuthProvider||(exports.BasicAuthProvider={})).EMAIL="email",p.WALLET="wallet",exports.OAuthProvider=void 0,(d=exports.OAuthProvider||(exports.OAuthProvider={})).GOOGLE="google",d.TWITTER="twitter",d.APPLE="apple",d.FACEBOOK="facebook",d.DISCORD="discord",d.EPIC_GAMES="epic_games",d.LINE="line",exports.CodeChallengeMethodEnum=void 0,(s=exports.CodeChallengeMethodEnum||(exports.CodeChallengeMethodEnum={})).PLAIN="plain",s.S256="S256";
|
|
1
|
+
"use strict";var e,o,t,r,E,A,p,d,s;exports.EmbeddedState=void 0,(e=exports.EmbeddedState||(exports.EmbeddedState={}))[e.NONE=0]="NONE",e[e.UNAUTHENTICATED=1]="UNAUTHENTICATED",e[e.EMBEDDED_SIGNER_NOT_CONFIGURED=2]="EMBEDDED_SIGNER_NOT_CONFIGURED",e[e.CREATING_ACCOUNT=3]="CREATING_ACCOUNT",e[e.READY=4]="READY",exports.OpenfortEvents=void 0,(exports.OpenfortEvents||(exports.OpenfortEvents={})).LOGGED_OUT="loggedOut",exports.RecoveryMethod=void 0,(o=exports.RecoveryMethod||(exports.RecoveryMethod={})).PASSWORD="password",o.AUTOMATIC="automatic",exports.AccountType=void 0,(t=exports.AccountType||(exports.AccountType={})).UPGRADEABLE_V4="Upgradeable_v04",t.MANAGED_V4="Managed_v04",t.ERC6551_V4="ERC6551_v04",t.ERC6551_V5="ERC6551_v05",t.RECOVERABLE_V4="Recoverable_v04",t.MANAGED_V5="Managed_v05",t.UPGRADEABLE_V5="Upgradeable_v05",t.UPGRADEABLE_V6="Upgradeable_v06",t.ZKSYNC_UPGRADEABLE_V1="zksync_upgradeable_v1",t.ZKSYNC_UPGRADEABLE_V2="zksync_upgradeable_v2",exports.AuthType=void 0,(r=exports.AuthType||(exports.AuthType={})).OPENFORT="openfort",r.THIRD_PARTY="thirdParty",exports.TokenType=void 0,(E=exports.TokenType||(exports.TokenType={})).ID_TOKEN="idToken",E.CUSTOM_TOKEN="customToken",exports.ThirdPartyOAuthProvider=void 0,(A=exports.ThirdPartyOAuthProvider||(exports.ThirdPartyOAuthProvider={})).ACCELBYTE="accelbyte",A.FIREBASE="firebase",A.LOOTLOCKER="lootlocker",A.PLAYFAB="playfab",A.SUPABASE="supabase",A.CUSTOM="custom",A.OIDC="oidc",exports.BasicAuthProvider=void 0,(p=exports.BasicAuthProvider||(exports.BasicAuthProvider={})).EMAIL="email",p.WALLET="wallet",exports.OAuthProvider=void 0,(d=exports.OAuthProvider||(exports.OAuthProvider={})).GOOGLE="google",d.TWITTER="twitter",d.APPLE="apple",d.FACEBOOK="facebook",d.DISCORD="discord",d.EPIC_GAMES="epic_games",d.LINE="line",exports.Actions=void 0,(exports.Actions||(exports.Actions={})).ACTION_VERIFY_EMAIL="verify_email",exports.CodeChallengeMethodEnum=void 0,(s=exports.CodeChallengeMethodEnum||(exports.CodeChallengeMethodEnum={})).PLAIN="plain",s.S256="S256";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.VERSION="0.8.
|
|
1
|
+
"use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="0.8.41";
|
package/dist/index.d.ts
CHANGED
|
@@ -302,6 +302,12 @@ interface AuthResponse {
|
|
|
302
302
|
'token': string;
|
|
303
303
|
'refreshToken': string;
|
|
304
304
|
}
|
|
305
|
+
declare enum Actions {
|
|
306
|
+
ACTION_VERIFY_EMAIL = "verify_email"
|
|
307
|
+
}
|
|
308
|
+
interface ActionRequiredResponse {
|
|
309
|
+
action: Actions;
|
|
310
|
+
}
|
|
305
311
|
interface AccountAbstractionV6Details {
|
|
306
312
|
'userOperation': UserOperationV6;
|
|
307
313
|
'userOperationHash': string;
|
|
@@ -578,7 +584,7 @@ declare class Openfort {
|
|
|
578
584
|
email: string;
|
|
579
585
|
password: string;
|
|
580
586
|
ecosystemGame?: string;
|
|
581
|
-
}): Promise<AuthResponse>;
|
|
587
|
+
}): Promise<AuthResponse | ActionRequiredResponse>;
|
|
582
588
|
/**
|
|
583
589
|
* Registers a new guest user.
|
|
584
590
|
*
|
|
@@ -603,7 +609,7 @@ declare class Openfort {
|
|
|
603
609
|
};
|
|
604
610
|
};
|
|
605
611
|
ecosystemGame?: string;
|
|
606
|
-
}): Promise<AuthResponse>;
|
|
612
|
+
}): Promise<AuthResponse | ActionRequiredResponse>;
|
|
607
613
|
/**
|
|
608
614
|
* Links an email and password to an existing account using an authentication token.
|
|
609
615
|
*
|
|
@@ -618,7 +624,7 @@ declare class Openfort {
|
|
|
618
624
|
password: string;
|
|
619
625
|
authToken: string;
|
|
620
626
|
ecosystemGame?: string;
|
|
621
|
-
}): Promise<AuthPlayerResponse>;
|
|
627
|
+
}): Promise<AuthPlayerResponse | ActionRequiredResponse>;
|
|
622
628
|
/**
|
|
623
629
|
* Unlinks an email and password from an existing account using an authentication token.
|
|
624
630
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BackendApiClients as e,createConfig as t}from"../../packages/internal/openapi-clients/dist/index.js";import*as a from"crypto";import{withOpenfortError as i,OpenfortErrorType as
|
|
1
|
+
import{BackendApiClients as e,createConfig as t}from"../../packages/internal/openapi-clients/dist/index.js";import*as a from"crypto";import{withOpenfortError as i,OpenfortErrorType as r,OpenfortError as n}from"./errors/openfortError.js";import{sentry as s}from"./errors/sentry.js";import{CodeChallengeMethodEnum as o}from"./types.js";import l from"./utils/deviceCredentialsManager.js";import{isBrowser as c}from"./utils/helpers.js";function d(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function h(e){return a.createHash("sha256").update(e).digest()}class u{publishableKey;deviceCredentialsManager;backendApiClients;constructor(a,i){this.publishableKey=a,this.deviceCredentialsManager=new l,this.backendApiClients=new e({backend:t({basePath:i,accessToken:a})})}async initOAuth(e,t,a){const i=t?.usePooling??!1;delete t?.usePooling;const r={oAuthInitRequest:{provider:e,options:t,usePooling:i}},n=await this.backendApiClients.authenticationApi.initOAuth(r,u.getEcosystemGameOptsOrUndefined(a));return c()&&t?.skipBrowserRedirect&&window.location.assign(n.data.url),{url:n.data.url,key:n.data.key}}async registerGuest(){return(await this.backendApiClients.authenticationApi.registerGuest({})).data}async poolOAuth(e){const t={key:e};for(let e=0;e<600;e++)try{const e=await this.backendApiClients.authenticationApi.poolOAuth(t);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,a){const n={loginWithIdTokenRequest:{provider:e,token:t}};return i((async()=>(await this.backendApiClients.authenticationApi.loginWithIdToken(n,u.getEcosystemGameOptsOrUndefined(a))).data),{default:r.AUTHENTICATION_ERROR,401:r.AUTHENTICATION_ERROR,403:r.USER_NOT_AUTHORIZED_ON_ECOSYSTEM},(e=>{s.captureAxiosError("loginWithIdToken",e)}))}async authenticateThirdParty(e,t,a,n){const o={thirdPartyOAuthRequest:{provider:e,token:t,tokenType:a}};return i((async()=>(await this.backendApiClients.authenticationApi.thirdParty(o,u.getEcosystemGameOptsOrUndefined(n))).data),{default:r.AUTHENTICATION_ERROR,401:r.AUTHENTICATION_ERROR,403:r.USER_NOT_AUTHORIZED_ON_ECOSYSTEM},(e=>{s.captureAxiosError("authenticateThirdParty",e)}))}async initSIWE(e,t){const a={sIWERequest:{address:e}},i=await this.backendApiClients.authenticationApi.initSIWE(a,u.getEcosystemGameOptsOrUndefined(t));return{address:i.data.address,nonce:i.data.nonce,expiresAt:i.data.expiresAt}}async authenticateSIWE(e,t,a,n){const o={sIWEAuthenticateRequest:{signature:e,message:t,walletClientType:a,connectorType:n}};return i((async()=>(await this.backendApiClients.authenticationApi.authenticateSIWE(o)).data),{default:r.AUTHENTICATION_ERROR,401:r.AUTHENTICATION_ERROR,403:r.USER_NOT_AUTHORIZED_ON_ECOSYSTEM},(e=>{s.captureAxiosError("authenticateSIWE",e)}))}static getEcosystemGameOptsOrUndefined(e){if(e)return{headers:{"x-game":e}}}async loginEmailPassword(e,t,a){const n={loginRequest:{email:e,password:t}};return i((async()=>(await this.backendApiClients.authenticationApi.loginEmailPassword(n,u.getEcosystemGameOptsOrUndefined(a))).data),{default:r.AUTHENTICATION_ERROR,401:r.AUTHENTICATION_ERROR,403:r.USER_NOT_AUTHORIZED_ON_ECOSYSTEM},(e=>{s.captureAxiosError("loginEmailPassword",e)}))}async requestResetPassword(e,t){const i=d(a.randomBytes(32)),r=d(h(i)),n=d(a.randomBytes(32));this.deviceCredentialsManager.savePKCEData({state:n,verifier:i});const s={requestResetPasswordRequest:{email:e,redirectUrl:t,challenge:{codeChallenge:r,method:o.S256}}};await this.backendApiClients.authenticationApi.requestResetPassword(s)}async resetPassword(e,t,a){return i((async()=>{const i=this.deviceCredentialsManager.getPKCEData();if(!i)throw new Error("No code verifier or state for PKCE");const r={resetPasswordRequest:{email:e,password:t,state:a,challenge:{codeVerifier:i.verifier}}};await this.backendApiClients.authenticationApi.resetPassword(r)}),{default:r.AUTHENTICATION_ERROR})}async requestEmailVerification(e,t){const i=d(a.randomBytes(32)),r=d(h(i)),n=d(a.randomBytes(32));this.deviceCredentialsManager.savePKCEData({state:n,verifier:i});const s={requestVerifyEmailRequest:{email:e,redirectUrl:t,challenge:{codeChallenge:r,method:o.S256}}};await this.backendApiClients.authenticationApi.requestEmailVerification(s)}async verifyEmail(e,t){return i((async()=>{const a=this.deviceCredentialsManager.getPKCEData();if(!a)throw new Error("No code verifier or state for PKCE");const i={verifyEmailRequest:{email:e,token:t,challenge:{codeVerifier:a.verifier}}};await this.backendApiClients.authenticationApi.verifyEmail(i)}),{default:r.AUTHENTICATION_ERROR})}async signupEmailPassword(e,t,a,n){const o={signupRequest:{email:e,password:t,name:a}};return i((async()=>(await this.backendApiClients.authenticationApi.signupEmailPassword(o,u.getEcosystemGameOptsOrUndefined(n))).data),{default:r.USER_REGISTRATION_ERROR,401:r.USER_REGISTRATION_ERROR,403:r.USER_NOT_AUTHORIZED_ON_ECOSYSTEM},(e=>{s.captureAxiosError("signupEmailPassword",e)}))}async validateCredentialsWithoutCrypto(e,t){if(!t.refreshToken)throw new n("No refresh token provided",r.AUTHENTICATION_ERROR);if(!openfort?.jwk)throw new n("openfort not available",r.INTERNAL_ERROR);const a=openfort.jwk.getKey({kty:e.kty,crv:e.crv,x:e.x,y:e.y}),i=openfort.jwk.parse(t.token);if(!openfort.jwk.verifyJWT(t.token,a,{alg:[e.alg]}))throw new n("Invalid token signature",r.AUTHENTICATION_ERROR);const s=JSON.parse(i.payloadPP);if(!s.exp)return this.refreshTokens(t.refreshToken);const o=openfort.jwk.getNow();return s.exp<o?this.refreshTokens(t.refreshToken):{player:s.sub,accessToken:t.token,refreshToken:t.refreshToken}}async validateCredentialsWithCrypto(e,t){if(!t.refreshToken)throw new n("No refresh token provided",r.AUTHENTICATION_ERROR);const{errors:a,importJWK:i,jwtVerify:s}=await import("jose");try{const a=await i({kty:e.kty,crv:e.crv,x:e.x,y:e.y},e.alg);return{player:(await s(t.token,a)).payload.sub,accessToken:t.token,refreshToken:t.refreshToken}}catch(e){if(e instanceof a.JWTExpired)return this.refreshTokens(t.refreshToken);throw e}}async validateCredentials(e,t){const a=await this.getJWK();if(!e.refreshToken)throw new n("No refresh token provided",r.AUTHENTICATION_ERROR);if(t)return this.refreshTokens(e.refreshToken,t);const i=u.getWebCrypto();return i?.subtle?this.validateCredentialsWithCrypto(a,e):this.validateCredentialsWithoutCrypto(a,e)}jwksStorageKey="openfort.jwk";stringToJWK(e){const t=JSON.parse(e);return{kty:t.kty,crv:t.crv,x:t.x,y:t.y,alg:t.alg}}async getJWK(){const e=sessionStorage.getItem(this.jwksStorageKey);if(e)return this.stringToJWK(e);const t={publishableKey:this.publishableKey},a=await this.backendApiClients.authenticationApi.getJwks(t);if(0===a.data.keys.length)throw new n("No JWKS keys found",r.INTERNAL_ERROR);const i=a.data.keys[0];return sessionStorage.setItem(this.jwksStorageKey,JSON.stringify(i)),{kty:i.kty,crv:i.crv,x:i.x,y:i.y,alg:i.alg}}async refreshTokens(e,t){const a={refreshTokenRequest:{refreshToken:e,forceRefresh:t}};return i((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.REFRESH_TOKEN_ERROR})}async logout(e,t){const a={logoutRequest:{refreshToken:t}};i((async()=>{await this.backendApiClients.authenticationApi.logout(a,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":e}})}),{default:r.LOGOUT_ERROR})}async getUser(e){return(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}async linkThirdParty(e,t,a,i,r){const n={thirdPartyLinkRequest:{provider:t,token:a,tokenType:i}};return(await this.backendApiClients.authenticationApi.linkThirdParty(n,{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":r||void 0}})).data}async linkOAuth(e,t,a,i){const r={oAuthInitRequest:{provider:t,options:a,usePooling:a?.usePooling||!1}},n=await this.backendApiClients.authenticationApi.linkOAuth(r,{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}});return c()&&!a?.skipBrowserRedirect&&window.location.assign(n.data.url),{url:n.data.url,key:n.data.key}}async unlinkOAuth(e,t){const a={unlinkOAuthRequest:{provider:e}};return(await this.backendApiClients.authenticationApi.unlinkOAuth(a,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t}})).data}async unlinkWallet(e,t){const a={sIWERequest:{address:e}};return(await this.backendApiClients.authenticationApi.unlinkSIWE(a,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t}})).data}async linkWallet(e,t,a,i,r){const n={sIWEAuthenticateRequest:{signature:e,message:t,walletClientType:a,connectorType:i}};return(await this.backendApiClients.authenticationApi.linkSIWE(n,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":r}})).data}async unlinkEmail(e,t){const a={unlinkEmailRequest:{email:e}};return(await this.backendApiClients.authenticationApi.unlinkEmail(a,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":t}})).data}static getWebCrypto(){return c()?window.crypto:"undefined"!=typeof global&&global.crypto?global.crypto:null}async linkEmail(e,t,a,i){const r={loginRequest:{email:e,password:t}};return(await this.backendApiClients.authenticationApi.linkEmail(r,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":a,"x-game":i||void 0}})).data}}export{u as AuthManager};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isAxiosError as R}from"axios";var E;!function(R){R.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",R.INVALID_CONFIGURATION="INVALID_CONFIGURATION",R.NOT_LOGGED_IN_ERROR="NOT_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_SESSION_SIGNER_ERROR="MISSING_SESSION_SIGNER_ERROR",R.MISSING_EMBEDDED_SIGNER_ERROR="MISSING_EMBEDDED_SIGNER_ERROR",R.MISSING_SIGNER_ERROR="MISSING_SIGNER_ERROR",R.USER_NOT_AUTHORIZED_ON_ECOSYSTEM="USER_NOT_AUTHORIZED_ON_ECOSYSTEM",R.INTERNAL_ERROR="INTERNAL_ERROR"}(E||(E={}));class O extends Error{type;data;constructor(R,E,O={}){super(R),this.type=E,this.data=O}}const _=async(E,_)=>{try{return await E()}catch(E){let
|
|
1
|
+
import{isAxiosError as R}from"axios";var E;!function(R){R.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",R.INVALID_CONFIGURATION="INVALID_CONFIGURATION",R.NOT_LOGGED_IN_ERROR="NOT_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_SESSION_SIGNER_ERROR="MISSING_SESSION_SIGNER_ERROR",R.MISSING_EMBEDDED_SIGNER_ERROR="MISSING_EMBEDDED_SIGNER_ERROR",R.MISSING_SIGNER_ERROR="MISSING_SIGNER_ERROR",R.USER_NOT_AUTHORIZED_ON_ECOSYSTEM="USER_NOT_AUTHORIZED_ON_ECOSYSTEM",R.INTERNAL_ERROR="INTERNAL_ERROR"}(E||(E={}));class O extends Error{type;data;constructor(R,E,O={}){super(R),this.type=E,this.data=O}}const _=async(E,_,I)=>{try{return await E()}catch(E){let N;const S={};let e;R(E)?(e=E.response?.status,N=E.response?.data&&E.response.data.error&&function(R){return"type"in R&&"message"in R}(E.response.data.error)?E.response.data.error.message:E.message):N=E.message;const s=void 0!==e&&_[e]?_[e]:_.default,t=new O(N,s,S);throw void 0!==e&&_[e]||I?.(E,t),t}};export{O as OpenfortError,E as OpenfortErrorType,_ as withOpenfortError};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AxiosError as t}from"axios";import{PACKAGE as s,VERSION as e}from"../version.js";const r="https://64a03e4967fb4dad3ecb914918c777b6@o4504593015242752.ingest.us.sentry.io/4509292415287296";class n{static sentryInstance;static queuedCalls=[];static baseTags;static set sentry(s){const e=s.getDsn();if(!e)throw new Error("Sentry DSN is not set");if(e.projectId!==r.split("https://")[1].split("/")[1]||e.host!==r.split("@")[1].split("/")[0]||e.publicKey!==r.split("@")[0].split("https://")[1])throw new Error("Sentry DSN is not valid");s.captureAxiosError=(e,r,n,a)=>{r instanceof t?(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,openfortConfiguration:n}){if(t)return void(this.sentry=t);const a=await import("@sentry/browser");this.sentry=new a.BrowserClient({dsn:r,integrations:[],stackParser:a.defaultStackParser,transport:a.makeFetchTransport}),this.baseTags={projectId:n?.publishableKey||"unknown",sdk:s,sdkVersion:e},this.processQueuedCalls()}static proxy=new Proxy({},{get:(t,s)=>n.sentryInstance&&"function"==typeof n.sentryInstance[s]?(...t)=>n.sentryInstance[s](...t):(...t)=>{n.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:a}=n;export{n as InternalSentry,a as sentry};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{StorageKeys as e}from"../storage/istorage.js";import{LocalStorage as t}from"../storage/localStorage.js";import{Event as r,ConfigureResponse as i,UpdateAuthenticationResponse as o,GetCurrentDeviceResponse as s,SignResponse as n,SwitchChainResponse as a,LogoutResponse as d,SetRecoveryMethodResponse as h,ExportPrivateKeyResponse as c,isErrorResponse as f,NOT_CONFIGURED_ERROR as u,MISSING_USER_ENTROPY_ERROR as g,MISSING_PROJECT_ENTROPY_ERROR as p,INCORRECT_USER_ENTROPY_ERROR as
|
|
1
|
+
import{StorageKeys as e}from"../storage/istorage.js";import{LocalStorage as t}from"../storage/localStorage.js";import{Event as r,ConfigureResponse as i,UpdateAuthenticationResponse as o,GetCurrentDeviceResponse as s,SignResponse as n,SwitchChainResponse as a,LogoutResponse as d,SetRecoveryMethodResponse as h,ExportPrivateKeyResponse as c,isErrorResponse as f,NOT_CONFIGURED_ERROR as u,MISSING_USER_ENTROPY_ERROR as g,MISSING_PROJECT_ENTROPY_ERROR as p,INCORRECT_USER_ENTROPY_ERROR as w,ShieldAuthType as l,PingRequest as y,SignRequest as m,SwitchChainRequest as v,ExportPrivateKeyRequest as k,SetRecoveryMethodRequest as U,GetCurrentDeviceRequest as C,LogoutRequest as I,UpdateAuthenticationRequest as b}from"./types.js";class P extends Error{constructor(){super("This embedded signer requires a password to be recovered")}}class T extends Error{constructor(){super("MissingProjectEntropyError")}}class E extends Error{constructor(){super("Wrong recovery password for this embedded signer")}}class R extends Error{constructor(){super("No response from iframe")}}class S extends Error{message;constructor(e){super(`Unknown response from iframe: ${e}`),this.message=e||""}}class L extends Error{constructor(){super("Invalid response from iframe")}}class F extends Error{constructor(){super("Not configured")}}class D{iframe;responses=new Map;storage;sdkConfiguration;constructor(e){this.sdkConfiguration=e,this.storage=new t}async iframeSetup(){if(window.addEventListener){window.addEventListener("message",(e=>{const t=new URL(this.sdkConfiguration.iframeUrl).origin;if(new URL(e.origin).origin===t){const{data:t}=e;t.action&&(t.action===r.PONG&&this.responses.set("FIRST",t),this.responses.set(t.uuid,t))}}));const e=document.getElementById("openfort-iframe");e&&document.body.removeChild(e);const t=document.createElement("iframe");t.style.display="none",t.id="openfort-iframe",document.body.appendChild(t),this.sdkConfiguration.shieldConfiguration?.debug?t.src=`${this.sdkConfiguration.iframeUrl}?debug=true`:t.src=this.sdkConfiguration.iframeUrl,this.iframe=t}else{if(!global.openfort)return;global.openfort.iframeListener((e=>{const t=new URL(this.sdkConfiguration.iframeUrl).origin;if(new URL(e.origin).origin===t){let{data:t}=e;"string"==typeof t&&(t=JSON.parse(t)),t.action&&this.responses.set(t.uuid,t)}})),this.iframe={contentWindow:{postMessage:e=>{global.openfort&&global.openfort.iframePostMessage(e)}}}}}isLoaded(){return void 0!==this.responses.get("FIRST")}async waitForIframeLoad(){this.iframe||await this.iframeSetup();const e=async()=>{this.isLoaded()||(this.iframe?.contentWindow?.postMessage(new y(this.generateShortUUID()),"*"),await new Promise((e=>{setTimeout(e,100)})),await e())};await e()}responseConstructors={[r.CONFIGURED]:i,[r.AUTHENTICATION_UPDATED]:o,[r.CURRENT_DEVICE]:s,[r.SIGNED]:n,[r.CHAIN_SWITCHED]:a,[r.LOGGED_OUT]:d,[r.SET_RECOVERY_METHOD]:h,[r.EXPORT]:c};waitForResponse(e){return new Promise(((t,r)=>{let i=0;const o=setInterval((()=>{i>100&&(clearInterval(o),r(new R)),i++;const s=this.responses.get(e);if(s){clearInterval(o),this.responses.delete(e);const i=this.responseConstructors[s.action];f(s)?(s.error===u?r(new F):s.error===g?r(new P):s.error===p?r(new T):s.error===w&&r(new E),r(new S(s.error))):i?t(s):r(new L)}}),100)}))}async configure(t){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");await this.waitForIframeLoad();const i={uuid:this.generateShortUUID(),action:r.CONFIGURE,chainId:t.chainId,recovery:t.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration.shieldPublishableKey,accessToken:t.accessToken,playerID:t.playerID,thirdPartyProvider:t.thirdPartyProvider,thirdPartyTokenType:t.thirdPartyTokenType,encryptionKey:t.password,encryptionPart:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??null,encryptionSession:t.recovery?.encryptionSession??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl};let o;this.iframe?.contentWindow?.postMessage(i,"*");try{o=await this.waitForResponse(i.uuid)}catch(t){throw(t instanceof E||t instanceof P)&&this.storage.remove(e.SIGNER),t}return sessionStorage.setItem("iframe-version",o.version??"undefined"),o}async sign(e,t,r,i){await this.waitForIframeLoad();const o=this.generateShortUUID(),s={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},n=new m(o,t,r,i,s);let a;this.iframe?.contentWindow?.postMessage(n,"*");try{a=await this.waitForResponse(o)}catch(o){if(o instanceof F)return await this.configure(e),this.sign(e,t,r,i);throw o}return sessionStorage.setItem("iframe-version",a.version??"undefined"),a.signature}async switchChain(e,t){await this.waitForIframeLoad();const r=this.generateShortUUID(),i={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},o=new v(r,t,i);let s;this.iframe?.contentWindow?.postMessage(o,"*");try{s=await this.waitForResponse(r)}catch(r){if(r instanceof F)return await this.configure(e),this.switchChain(e,t);throw r}return sessionStorage.setItem("iframe-version",s.version??"undefined"),s}async export(e){await this.waitForIframeLoad();const t=this.generateShortUUID(),r={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},i=new k(t,r);let o;this.iframe?.contentWindow?.postMessage(i,"*");try{o=await this.waitForResponse(t)}catch(t){if(t instanceof F)return await this.configure(e),this.export(e);throw t}return sessionStorage.setItem("iframe-version",o.version??"undefined"),o.key}async setEmbeddedRecovery(e,t,r,i){await this.waitForIframeLoad();const o=this.generateShortUUID(),s={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},n=new U(o,t,r,i,s);let a;this.iframe?.contentWindow?.postMessage(n,"*");try{a=await this.waitForResponse(o)}catch(o){if(o instanceof F)return await this.configure(e),this.setEmbeddedRecovery(e,t,r,i);throw o}return sessionStorage.setItem("iframe-version",a.version??"undefined"),Promise.resolve()}async getCurrentUser(e){await this.waitForIframeLoad();const t=this.generateShortUUID(),r=new C(t,e);this.iframe?.contentWindow?.postMessage(r,"*");try{const e=await this.waitForResponse(t);return sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof F)return null;throw e}}async logout(){await this.waitForIframeLoad();const e=this.generateShortUUID(),t=new I(e);this.iframe?.contentWindow?.postMessage(t,"*"),await this.waitForResponse(e)}async updateAuthentication(e,t,r){e.accessToken=t,r===l.OPENFORT&&e.recovery&&(e.recovery.token=t),await this.waitForIframeLoad();const i=this.generateShortUUID(),o=new b(i,t);this.iframe?.contentWindow?.postMessage(o,"*");try{await this.waitForResponse(i)}catch(i){if(i instanceof F)return await this.configure(e),void await this.updateAuthentication(e,t,r);throw i}}generateShortUUID(e=8){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let r="";for(let i=0;i<e;i++)r+=t.charAt(Math.floor(62*Math.random()));return r}}export{D as IframeManager,L as InvalidResponseError,T as MissingProjectEntropyError,P as MissingRecoveryPasswordError,R as NoResponseError,F as NotConfiguredError,S as UnknownResponseError,E as WrongRecoveryPasswordError};
|
package/dist/sdk/src/openfort.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BackendApiClients as e,createConfig as t}from"../../packages/internal/openapi-clients/dist/index.js";import{getSignedTypedData as r}from"./evm/walletHelpers.js";import{StorageKeys as a}from"./storage/istorage.js";import{LocalStorage as o}from"./storage/localStorage.js";import{SignerManager as i}from"./manager/signer.js";import{OpenfortError as n,OpenfortErrorType as s}from"./errors/openfortError.js";import{EmbeddedState as h}from"./types.js";import{Configuration as d}from"./configuration/configuration.js";import{Account as u}from"./configuration/account.js";import{Authentication as g}from"./configuration/authentication.js";import{MissingRecoveryPasswordError as l,MissingProjectEntropyError as c}from"./iframe/iframeManager.js";import{AuthManager as f}from"./authManager.js";import{EvmProvider as p}from"./evm/evmProvider.js";import"./evm/types.js";import m from"./utils/typedEventEmitter.js";import{announceProvider as w,openfortProviderInfo as y}from"./evm/provider/eip6963.js";class R{storage;provider=null;iAuthManager=null;constructor(e){this.storage=new o;new d(e.baseConfiguration.publishableKey,e.overrides?.backendUrl||"https://api.openfort.xyz",e.shieldConfiguration?.shieldPublishableKey||"",e.shieldConfiguration?.shieldEncryptionKey||"",e.overrides?.shieldUrl||"https://shield.openfort.xyz",e.overrides?.iframeUrl||"https://embedded.openfort.xyz",e.shieldConfiguration?.debug||!1).save()}async logout(){const e=i.fromStorage();this.storage.remove(a.AUTHENTICATION),this.storage.remove(a.SIGNER),this.storage.remove(a.ACCOUNT),e&&await e.logout()}getEthereumProvider(e){const t={announceProvider:!0,...e},r=g.fromStorage(this.storage),a=i.fromStorage(),o=u.fromStorage(this.storage);return this.provider?this.provider&&t.policy&&this.provider.updatePolicy(t.policy):(this.provider=new p({storage:this.storage,openfortEventEmitter:new m,signer:a||void 0,account:o||void 0,authentication:r||void 0,backendApiClients:this.backendApiClients,policyId:t.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this)}),t.announceProvider&&w({info:{...y,...t.providerInfo},provider:this.provider})),this.provider}async configureEmbeddedSigner(e=null,t=null,r=null){await this.validateAndRefreshToken();const a=d.fromStorage();let o=null;(r||t?.encryptionSession)&&(o={encryptionSession:t?.encryptionSession||null,recoveryPassword:r||null,encryptionPart:a?.shieldEncryptionKey||null});let n=null,s=null;t&&(n="openfort"===t.auth?"openfort":"custom",s=t.token),await i.embedded(e,o,n,s)}async signMessage(e,t){await this.validateAndRefreshToken();const r=i.fromStorage();if(!r)throw new n("No signer configured",s.MISSING_SIGNER_ERROR);const{hashMessage:a=!0,arrayifyMessage:o=!1}=t||{};return await r.sign(e,o,a)}async signTypedData(e,t,a){await this.validateAndRefreshToken();const o=i.fromStorage(),h=u.fromStorage(this.storage);if(!o||!h)throw new n("No signer configured",s.MISSING_SIGNER_ERROR);return await r({domain:e,types:t,message:a},h.type,Number(h.chainId),o,h.address)}async exportPrivateKey(){await this.validateAndRefreshToken();const e=i.fromStorage();if(!e)throw new n("No signer configured",s.MISSING_SIGNER_ERROR);return await e.export()}async setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:t,encryptionSession:r}){await this.validateAndRefreshToken();const a=i.fromStorage();if(!a)throw new n("No signer configured",s.MISSING_SIGNER_ERROR);if("embedded"!==a.type())throw new n("Signer must be embedded",s.INVALID_CONFIGURATION);if("password"===e&&!t)throw new n("Recovery password is required",s.INVALID_CONFIGURATION);await a.setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:t,encryptionSession:r})}async logInWithEmailPassword({email:e,password:t,ecosystemGame:r}){const a=g.fromStorage(this.storage),o=await this.authManager.loginEmailPassword(e,t,r);return a&&a.player!==o.player.id&&this.logout(),new g("jwt",o.token,o.player.id,o.refreshToken).save(this.storage),o}async signUpGuest(){const e=g.fromStorage(this.storage),t=await this.authManager.registerGuest();return e&&e.player!==t.player.id&&this.logout(),new g("jwt",t.token,t.player.id,t.refreshToken).save(this.storage),t}async signUpWithEmailPassword({email:e,password:t,options:r,ecosystemGame:a}){const o=g.fromStorage(this.storage),i=await this.authManager.signupEmailPassword(e,t,r?.data.name,a);return o&&o.player!==i.player.id&&this.logout(),new g("jwt",i.token,i.player.id,i.refreshToken).save(this.storage),i}async linkEmailPassword({email:e,password:t,authToken:r,ecosystemGame:a}){return await this.authManager.linkEmail(e,t,r,a)}async unlinkEmailPassword({email:e,authToken:t}){return await this.authManager.unlinkEmail(e,t)}async requestEmailVerification({email:e,redirectUrl:t}){await this.authManager.requestEmailVerification(e,t)}async resetPassword({email:e,password:t,state:r}){await this.authManager.resetPassword(e,t,r)}async requestResetPassword({email:e,redirectUrl:t}){await this.authManager.requestResetPassword(e,t)}async verifyEmail({email:e,state:t}){await this.authManager.verifyEmail(e,t)}async initOAuth({provider:e,options:t,ecosystemGame:r}){return this.storage.remove(a.AUTHENTICATION),await this.authManager.initOAuth(e,t,r)}async initLinkOAuth({provider:e,options:t,ecosystemGame:r}){const a=g.fromStorage(this.storage);if(!a)throw new n("No authentication found",s.NOT_LOGGED_IN_ERROR);return await this.authManager.linkOAuth(a,e,t,r)}async linkThirdPartyProvider({provider:e,token:t,tokenType:r}){const a=g.fromStorage(this.storage);if(!a)throw new n("No authentication found",s.NOT_LOGGED_IN_ERROR);return await this.authManager.linkThirdParty(a,e,t,r)}async unlinkOAuth({provider:e,authToken:t}){return await this.authManager.unlinkOAuth(e,t)}async poolOAuth(e){const t=g.fromStorage(this.storage),r=await this.authManager.poolOAuth(e);return t&&t.player!==r.player.id&&this.logout(),new g("jwt",r.token,r.player.id,r.refreshToken).save(this.storage),r}async authenticateWithThirdPartyProvider({provider:e,token:t,tokenType:r,ecosystemGame:a}){const o=g.fromStorage(this.storage),n=await this.authManager.authenticateThirdParty(e,t,r,a);let s=!1;if(o&&o.player!==n.id&&(this.logout(),s=!0),new g("third_party",t,n.id,null,e,r).save(this.storage),s)return n;const h=i.fromStorage();try{await(h?.updateAuthentication())}catch(e){throw(e instanceof l||e instanceof c)&&await(h?.logout()),e}return n}async loginWithIdToken({provider:e,token:t,ecosystemGame:r}){const a=g.fromStorage(this.storage),o=await this.authManager.loginWithIdToken(e,t,r);return a&&a.player!==o.player.id&&this.logout(),new g("jwt",o.token,o.player.id,o.refreshToken).save(this.storage),o}async initSIWE({address:e,ecosystemGame:t}){return await this.authManager.initSIWE(e,t)}async authenticateWithSIWE({signature:e,message:t,walletClientType:r,connectorType:a}){const o=g.fromStorage(this.storage),i=await this.authManager.authenticateSIWE(e,t,r,a);return o&&o.player!==i.player.id&&this.logout(),new g("jwt",i.token,i.player.id,i.refreshToken).save(this.storage),i}async linkWallet({signature:e,message:t,walletClientType:r,connectorType:a,authToken:o}){return await this.authManager.linkWallet(e,t,r,a,o)}async unlinkWallet({address:e,authToken:t}){return await this.authManager.unlinkWallet(e,t)}storeCredentials(e){if(this.storage.remove(a.AUTHENTICATION),!e.player)throw new n("Player ID is required to store credentials",s.INVALID_CONFIGURATION);new g("jwt",e.accessToken,e.player,e.refreshToken).save(this.storage)}async sendSignatureTransactionIntentRequest(e,t=null,r=null,a=!1){if(!d.fromStorage())throw new n("Configuration not found",s.INVALID_CONFIGURATION);await this.validateAndRefreshToken();let o=r;if(!o){if(!t)throw new n("No signableHash or signature provided",s.OPERATION_NOT_SUPPORTED_ERROR);const e=i.fromStorage();if(!e)throw new n("In order to sign a transaction intent, a signer must be configured",s.MISSING_SIGNER_ERROR);o=await e.sign(t)}const h={id:e,signatureRequest:{signature:o,optimistic:a}};return(await this.backendApiClients.transactionIntentsApi.signature(h)).data}async getAccount(){const e=u.fromStorage(this.storage);if(!e)throw new n("No signer configured",s.MISSING_SIGNER_ERROR);return{chainId:e.chainId,address:e.address,ownerAddress:e.ownerAddress,accountType:e.type}}get backendApiClients(){const r=d.fromStorage();if(!r)throw new n("Configuration not found",s.INVALID_CONFIGURATION);return new e({backend:t({basePath:r.openfortURL,accessToken:r.publishableKey})})}async sendSignatureSessionRequest(e,t,r){const a={id:e,signatureRequest:{signature:t,optimistic:r}};return(await this.backendApiClients.sessionsApi.signatureSession(a)).data}getEmbeddedState(){if(!g.fromStorage(this.storage))return h.UNAUTHENTICATED;const e=i.fromStorage();if(!e||"embedded"!==e.type())return h.EMBEDDED_SIGNER_NOT_CONFIGURED;return u.fromStorage(this.storage)?h.READY:h.CREATING_ACCOUNT}getAccessToken(){return g.fromStorage(this.storage)?.token??null}get authManager(){if(!this.iAuthManager){const e=d.fromStorage();if(!e)throw new n("Configuration not found",s.INVALID_CONFIGURATION);this.iAuthManager=new f(e.publishableKey,e.openfortURL)}return this.iAuthManager}async getUser(){await this.validateAndRefreshToken();const e=g.fromStorage(this.storage);if(!e)throw new n("No access token found",s.NOT_LOGGED_IN_ERROR);return await this.authManager.getUser(e)}async validateAndRefreshToken(e){const t=g.fromStorage(this.storage);if(!t)throw new n("Must be logged in to validate and refresh token",s.NOT_LOGGED_IN_ERROR);if("jwt"!==t.type)return;const r=await this.authManager.validateCredentials(t,e);if(!r.player)throw new n("No player found in credentials",s.INTERNAL_ERROR);if(r.accessToken===t.token)return;new g("jwt",r.accessToken,r.player,r.refreshToken).save(this.storage);const a=i.fromStorage();try{await(a?.updateAuthentication())}catch(e){throw(e instanceof l||e instanceof c)&&await(a?.logout()),e}}}export{R as Openfort};
|
|
1
|
+
import{BackendApiClients as e,createConfig as t}from"../../packages/internal/openapi-clients/dist/index.js";import{getSignedTypedData as r}from"./evm/walletHelpers.js";import{InternalSentry as a}from"./errors/sentry.js";import{StorageKeys as o}from"./storage/istorage.js";import{LocalStorage as i}from"./storage/localStorage.js";import{SignerManager as n}from"./manager/signer.js";import{OpenfortError as s,OpenfortErrorType as h}from"./errors/openfortError.js";import{EmbeddedState as d}from"./types.js";import{Configuration as u}from"./configuration/configuration.js";import{Account as g}from"./configuration/account.js";import{Authentication as l}from"./configuration/authentication.js";import{MissingRecoveryPasswordError as c,MissingProjectEntropyError as f}from"./iframe/iframeManager.js";import{AuthManager as p}from"./authManager.js";import{EvmProvider as m}from"./evm/evmProvider.js";import"./evm/types.js";import w from"./utils/typedEventEmitter.js";import{announceProvider as y,openfortProviderInfo as R}from"./evm/provider/eip6963.js";class I{storage;provider=null;iAuthManager=null;constructor(e){this.storage=new i;const t=new u(e.baseConfiguration.publishableKey,e.overrides?.backendUrl||"https://api.openfort.xyz",e.shieldConfiguration?.shieldPublishableKey||"",e.shieldConfiguration?.shieldEncryptionKey||"",e.overrides?.shieldUrl||"https://shield.openfort.xyz",e.overrides?.iframeUrl||"https://embedded.openfort.xyz",e.shieldConfiguration?.debug||!1);a.init({openfortConfiguration:t}),t.save()}async logout(){const e=n.fromStorage();this.storage.remove(o.AUTHENTICATION),this.storage.remove(o.SIGNER),this.storage.remove(o.ACCOUNT),e&&await e.logout()}getEthereumProvider(e){const t={announceProvider:!0,...e},r=l.fromStorage(this.storage),a=n.fromStorage(),o=g.fromStorage(this.storage);return this.provider?this.provider&&t.policy&&this.provider.updatePolicy(t.policy):(this.provider=new m({storage:this.storage,openfortEventEmitter:new w,signer:a||void 0,account:o||void 0,authentication:r||void 0,backendApiClients:this.backendApiClients,policyId:t.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this)}),t.announceProvider&&y({info:{...R,...t.providerInfo},provider:this.provider})),this.provider}async configureEmbeddedSigner(e=null,t=null,r=null){await this.validateAndRefreshToken();const a=u.fromStorage();let o=null;(r||t?.encryptionSession)&&(o={encryptionSession:t?.encryptionSession||null,recoveryPassword:r||null,encryptionPart:a?.shieldEncryptionKey||null});let i=null,s=null;t&&(i="openfort"===t.auth?"openfort":"custom",s=t.token),await n.embedded(e,o,i,s)}async signMessage(e,t){await this.validateAndRefreshToken();const r=n.fromStorage();if(!r)throw new s("No signer configured",h.MISSING_SIGNER_ERROR);const{hashMessage:a=!0,arrayifyMessage:o=!1}=t||{};return await r.sign(e,o,a)}async signTypedData(e,t,a){await this.validateAndRefreshToken();const o=n.fromStorage(),i=g.fromStorage(this.storage);if(!o||!i)throw new s("No signer configured",h.MISSING_SIGNER_ERROR);return await r({domain:e,types:t,message:a},i.type,Number(i.chainId),o,i.address)}async exportPrivateKey(){await this.validateAndRefreshToken();const e=n.fromStorage();if(!e)throw new s("No signer configured",h.MISSING_SIGNER_ERROR);return await e.export()}async setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:t,encryptionSession:r}){await this.validateAndRefreshToken();const a=n.fromStorage();if(!a)throw new s("No signer configured",h.MISSING_SIGNER_ERROR);if("embedded"!==a.type())throw new s("Signer must be embedded",h.INVALID_CONFIGURATION);if("password"===e&&!t)throw new s("Recovery password is required",h.INVALID_CONFIGURATION);await a.setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:t,encryptionSession:r})}async logInWithEmailPassword({email:e,password:t,ecosystemGame:r}){const a=l.fromStorage(this.storage),o=await this.authManager.loginEmailPassword(e,t,r);return"action"in o||(a&&a.player!==o.player.id&&this.logout(),new l("jwt",o.token,o.player.id,o.refreshToken).save(this.storage)),o}async signUpGuest(){const e=l.fromStorage(this.storage),t=await this.authManager.registerGuest();return e&&e.player!==t.player.id&&this.logout(),new l("jwt",t.token,t.player.id,t.refreshToken).save(this.storage),t}async signUpWithEmailPassword({email:e,password:t,options:r,ecosystemGame:a}){const o=l.fromStorage(this.storage),i=await this.authManager.signupEmailPassword(e,t,r?.data.name,a);return"action"in i||(o&&o.player!==i.player.id&&this.logout(),new l("jwt",i.token,i.player.id,i.refreshToken).save(this.storage)),i}async linkEmailPassword({email:e,password:t,authToken:r,ecosystemGame:a}){return await this.authManager.linkEmail(e,t,r,a)}async unlinkEmailPassword({email:e,authToken:t}){return await this.authManager.unlinkEmail(e,t)}async requestEmailVerification({email:e,redirectUrl:t}){await this.authManager.requestEmailVerification(e,t)}async resetPassword({email:e,password:t,state:r}){await this.authManager.resetPassword(e,t,r)}async requestResetPassword({email:e,redirectUrl:t}){await this.authManager.requestResetPassword(e,t)}async verifyEmail({email:e,state:t}){await this.authManager.verifyEmail(e,t)}async initOAuth({provider:e,options:t,ecosystemGame:r}){return this.storage.remove(o.AUTHENTICATION),await this.authManager.initOAuth(e,t,r)}async initLinkOAuth({provider:e,options:t,ecosystemGame:r}){const a=l.fromStorage(this.storage);if(!a)throw new s("No authentication found",h.NOT_LOGGED_IN_ERROR);return await this.authManager.linkOAuth(a,e,t,r)}async linkThirdPartyProvider({provider:e,token:t,tokenType:r}){const a=l.fromStorage(this.storage);if(!a)throw new s("No authentication found",h.NOT_LOGGED_IN_ERROR);return await this.authManager.linkThirdParty(a,e,t,r)}async unlinkOAuth({provider:e,authToken:t}){return await this.authManager.unlinkOAuth(e,t)}async poolOAuth(e){const t=l.fromStorage(this.storage),r=await this.authManager.poolOAuth(e);return t&&t.player!==r.player.id&&this.logout(),new l("jwt",r.token,r.player.id,r.refreshToken).save(this.storage),r}async authenticateWithThirdPartyProvider({provider:e,token:t,tokenType:r,ecosystemGame:a}){const o=l.fromStorage(this.storage),i=await this.authManager.authenticateThirdParty(e,t,r,a);let s=!1;if(o&&o.player!==i.id&&(this.logout(),s=!0),new l("third_party",t,i.id,null,e,r).save(this.storage),s)return i;const h=n.fromStorage();try{await(h?.updateAuthentication())}catch(e){throw(e instanceof c||e instanceof f)&&await(h?.logout()),e}return i}async loginWithIdToken({provider:e,token:t,ecosystemGame:r}){const a=l.fromStorage(this.storage),o=await this.authManager.loginWithIdToken(e,t,r);return a&&a.player!==o.player.id&&this.logout(),new l("jwt",o.token,o.player.id,o.refreshToken).save(this.storage),o}async initSIWE({address:e,ecosystemGame:t}){return await this.authManager.initSIWE(e,t)}async authenticateWithSIWE({signature:e,message:t,walletClientType:r,connectorType:a}){const o=l.fromStorage(this.storage),i=await this.authManager.authenticateSIWE(e,t,r,a);return o&&o.player!==i.player.id&&this.logout(),new l("jwt",i.token,i.player.id,i.refreshToken).save(this.storage),i}async linkWallet({signature:e,message:t,walletClientType:r,connectorType:a,authToken:o}){return await this.authManager.linkWallet(e,t,r,a,o)}async unlinkWallet({address:e,authToken:t}){return await this.authManager.unlinkWallet(e,t)}storeCredentials(e){if(this.storage.remove(o.AUTHENTICATION),!e.player)throw new s("Player ID is required to store credentials",h.INVALID_CONFIGURATION);new l("jwt",e.accessToken,e.player,e.refreshToken).save(this.storage)}async sendSignatureTransactionIntentRequest(e,t=null,r=null,a=!1){if(!u.fromStorage())throw new s("Configuration not found",h.INVALID_CONFIGURATION);await this.validateAndRefreshToken();let o=r;if(!o){if(!t)throw new s("No signableHash or signature provided",h.OPERATION_NOT_SUPPORTED_ERROR);const e=n.fromStorage();if(!e)throw new s("In order to sign a transaction intent, a signer must be configured",h.MISSING_SIGNER_ERROR);o=await e.sign(t)}const i={id:e,signatureRequest:{signature:o,optimistic:a}};return(await this.backendApiClients.transactionIntentsApi.signature(i)).data}async getAccount(){const e=g.fromStorage(this.storage);if(!e)throw new s("No signer configured",h.MISSING_SIGNER_ERROR);return{chainId:e.chainId,address:e.address,ownerAddress:e.ownerAddress,accountType:e.type}}get backendApiClients(){const r=u.fromStorage();if(!r)throw new s("Configuration not found",h.INVALID_CONFIGURATION);return new e({backend:t({basePath:r.openfortURL,accessToken:r.publishableKey})})}async sendSignatureSessionRequest(e,t,r){const a={id:e,signatureRequest:{signature:t,optimistic:r}};return(await this.backendApiClients.sessionsApi.signatureSession(a)).data}getEmbeddedState(){if(!l.fromStorage(this.storage))return d.UNAUTHENTICATED;const e=n.fromStorage();if(!e||"embedded"!==e.type())return d.EMBEDDED_SIGNER_NOT_CONFIGURED;return g.fromStorage(this.storage)?d.READY:d.CREATING_ACCOUNT}getAccessToken(){return l.fromStorage(this.storage)?.token??null}get authManager(){if(!this.iAuthManager){const e=u.fromStorage();if(!e)throw new s("Configuration not found",h.INVALID_CONFIGURATION);this.iAuthManager=new p(e.publishableKey,e.openfortURL)}return this.iAuthManager}async getUser(){await this.validateAndRefreshToken();const e=l.fromStorage(this.storage);if(!e)throw new s("No access token found",h.NOT_LOGGED_IN_ERROR);return await this.authManager.getUser(e)}async validateAndRefreshToken(e){const t=l.fromStorage(this.storage);if(!t)throw new s("Must be logged in to validate and refresh token",h.NOT_LOGGED_IN_ERROR);if("jwt"!==t.type)return;const r=await this.authManager.validateCredentials(t,e);if(!r.player)throw new s("No player found in credentials",h.INTERNAL_ERROR);if(r.accessToken===t.token)return;new l("jwt",r.accessToken,r.player,r.refreshToken).save(this.storage);const a=n.fromStorage();try{await(a?.updateAuthentication())}catch(e){throw(e instanceof c||e instanceof f)&&await(a?.logout()),e}}}export{I as Openfort};
|
package/dist/sdk/src/types.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var E,A,_,e,a,o,T,
|
|
1
|
+
var E,A,_,e,a,n,o,T,O,R,C;!function(E){E[E.NONE=0]="NONE",E[E.UNAUTHENTICATED=1]="UNAUTHENTICATED",E[E.EMBEDDED_SIGNER_NOT_CONFIGURED=2]="EMBEDDED_SIGNER_NOT_CONFIGURED",E[E.CREATING_ACCOUNT=3]="CREATING_ACCOUNT",E[E.READY=4]="READY"}(E||(E={})),function(E){E.LOGGED_OUT="loggedOut"}(A||(A={})),function(E){E.PASSWORD="password",E.AUTOMATIC="automatic"}(_||(_={})),function(E){E.UPGRADEABLE_V4="Upgradeable_v04",E.MANAGED_V4="Managed_v04",E.ERC6551_V4="ERC6551_v04",E.ERC6551_V5="ERC6551_v05",E.RECOVERABLE_V4="Recoverable_v04",E.MANAGED_V5="Managed_v05",E.UPGRADEABLE_V5="Upgradeable_v05",E.UPGRADEABLE_V6="Upgradeable_v06",E.ZKSYNC_UPGRADEABLE_V1="zksync_upgradeable_v1",E.ZKSYNC_UPGRADEABLE_V2="zksync_upgradeable_v2"}(e||(e={})),function(E){E.OPENFORT="openfort",E.THIRD_PARTY="thirdParty"}(a||(a={})),function(E){E.ID_TOKEN="idToken",E.CUSTOM_TOKEN="customToken"}(n||(n={})),function(E){E.ACCELBYTE="accelbyte",E.FIREBASE="firebase",E.LOOTLOCKER="lootlocker",E.PLAYFAB="playfab",E.SUPABASE="supabase",E.CUSTOM="custom",E.OIDC="oidc"}(o||(o={})),function(E){E.EMAIL="email",E.WALLET="wallet"}(T||(T={})),function(E){E.GOOGLE="google",E.TWITTER="twitter",E.APPLE="apple",E.FACEBOOK="facebook",E.DISCORD="discord",E.EPIC_GAMES="epic_games",E.LINE="line"}(O||(O={})),function(E){E.ACTION_VERIFY_EMAIL="verify_email"}(R||(R={})),function(E){E.PLAIN="plain",E.S256="S256"}(C||(C={}));export{e as AccountType,R as Actions,a as AuthType,T as BasicAuthProvider,C as CodeChallengeMethodEnum,E as EmbeddedState,O as OAuthProvider,A as OpenfortEvents,_ as RecoveryMethod,o as ThirdPartyOAuthProvider,n as TokenType};
|
package/dist/sdk/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.8.
|
|
1
|
+
const o="0.8.41",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openfort/openfort-js",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.41",
|
|
4
4
|
"author": "Openfort (https://www.openfort.io)",
|
|
5
5
|
"bugs": "https://github.com/openfort-xyz/openfort-js/issues",
|
|
6
6
|
"repository": "openfort-xyz/openfort-js.git",
|
|
@@ -38,6 +38,8 @@
|
|
|
38
38
|
"@ethersproject/providers": "^5.8.0",
|
|
39
39
|
"@noble/curves": "^1.1.0",
|
|
40
40
|
"@openfort/shield-js": "^0.1.14",
|
|
41
|
+
"@sentry/browser": "^9.15.0",
|
|
42
|
+
"@sentry/core": "^9.15.0",
|
|
41
43
|
"axios": "^1.8.2",
|
|
42
44
|
"buffer": "^6.0.3",
|
|
43
45
|
"crypto-js": "^4.2.0",
|
|
@@ -56,6 +58,7 @@
|
|
|
56
58
|
"devDependencies": {
|
|
57
59
|
"@babel/core": "^7.26.10",
|
|
58
60
|
"@openfort/openapi-clients": "0.0.0",
|
|
61
|
+
"@parcel/core": "^2.15.0",
|
|
59
62
|
"@parcel/packager-ts": "2.12.0",
|
|
60
63
|
"@parcel/transformer-typescript-types": "2.12.0",
|
|
61
64
|
"@rollup/plugin-babel": "^6.0.4",
|
|
@@ -65,6 +68,7 @@
|
|
|
65
68
|
"@rollup/plugin-replace": "^5.0.2",
|
|
66
69
|
"@rollup/plugin-terser": "^0.4.3",
|
|
67
70
|
"@rollup/plugin-typescript": "^11.0.0",
|
|
71
|
+
"@swc/core": "^1.11.24",
|
|
68
72
|
"@swc/jest": "^0.2.24",
|
|
69
73
|
"@types/crypto-js": "^4.2.2",
|
|
70
74
|
"@types/jest": "^29.4.3",
|
|
@@ -74,7 +78,7 @@
|
|
|
74
78
|
"eslint": "^8.40.0",
|
|
75
79
|
"jest": "^29.4.3",
|
|
76
80
|
"jest-environment-jsdom": "^29.4.3",
|
|
77
|
-
"parcel": "^2.
|
|
81
|
+
"parcel": "^2.15.0",
|
|
78
82
|
"prettier": "^2.8.8",
|
|
79
83
|
"rimraf": "^2.6.2",
|
|
80
84
|
"rollup": "^3.17.2",
|