@openfort/openfort-js 0.8.30 → 0.8.32
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/evm/evmProvider.js +1 -1
- package/dist/cjs/sdk/src/evm/provider/eip6963.js +1 -1
- package/dist/cjs/sdk/src/evm/sendCalls.js +1 -1
- package/dist/cjs/sdk/src/evm/walletHelpers.js +1 -1
- package/dist/cjs/sdk/src/manager/signer.js +1 -1
- package/dist/cjs/sdk/src/openfort.js +1 -1
- package/dist/cjs/sdk/src/utils/crypto.js +1 -0
- package/dist/cjs/sdk/src/version.js +1 -1
- package/dist/index.d.ts +0 -51
- package/dist/sdk/src/authManager.js +1 -1
- package/dist/sdk/src/evm/evmProvider.js +1 -1
- package/dist/sdk/src/evm/provider/eip6963.js +1 -1
- package/dist/sdk/src/evm/sendCalls.js +1 -1
- package/dist/sdk/src/evm/walletHelpers.js +1 -1
- package/dist/sdk/src/manager/signer.js +1 -1
- package/dist/sdk/src/openfort.js +1 -1
- package/dist/sdk/src/utils/crypto.js +1 -0
- package/dist/sdk/src/version.js +1 -1
- package/package.json +5 -14
- package/dist/cjs/sdk/src/configuration/session.js +0 -1
- package/dist/cjs/sdk/src/crypto/key-pair.js +0 -1
- package/dist/cjs/sdk/src/signer/session.js +0 -1
- package/dist/sdk/src/configuration/session.js +0 -1
- package/dist/sdk/src/crypto/key-pair.js +0 -1
- package/dist/sdk/src/signer/session.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../packages/internal/openapi-clients/dist/index.js"),t=require("crypto"),r=require("
|
|
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 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);p.getWebCrypto();return this.validateCredentialsWithCrypto(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 +1 @@
|
|
|
1
|
-
"use strict";var e=require("
|
|
1
|
+
"use strict";var e=require("../configuration/authentication.js"),r=require("./types.js"),t=require("./JsonRpcError.js"),a=require("./signTypedDataV4.js"),s=require("../types.js"),o=require("../utils/typedEventEmitter.js"),i=require("../chains/index.js"),n=require("../configuration/account.js"),c=require("../manager/signer.js"),h=require("../storage/istorage.js"),d=require("./addEthereumChain.js"),u=require("./registerSession.js"),g=require("./revokeSession.js"),p=require("./sendCalls.js"),l=require("./getCallsStatus.js"),m=require("./personalSign.js"),E=require("./estimateGas.js"),f=require("../utils/crypto.js");exports.EvmProvider=class{#e;#r;updatePolicy(e){this.#r=e}#t;#a;#s=null;#o;isOpenfort=!0;constructor({storage:e,backendApiClients:r,openfortEventEmitter:t,policyId:a,validateAndRefreshSession:i}){this.#e=e,this.#r=a,this.#t=i,this.#o=r,this.#o=r,this.#a=new o,t.on(s.OpenfortEvents.LOGGED_OUT,this.#i)}#i=()=>{const e=!!n.Account.fromStorage(this.#e),t=c.SignerManager.fromStorage();t?.logout(),this.#e.remove(h.StorageKeys.ACCOUNT),this.#e.remove(h.StorageKeys.AUTHENTICATION),this.#e.remove(h.StorageKeys.SIGNER),e&&this.#a.emit(r.ProviderEvent.ACCOUNTS_CHANGED,[])};async getRpcProvider(){if(!this.#s){const e=n.Account.fromStorage(this.#e),r=e?.chainId||8453;await import("@ethersproject/providers").then((e=>{this.#s=new e.StaticJsonRpcProvider(i.chainRpcs[r])}))}if(!this.#s)throw new Error("RPC provider not initialized");return this.#s}async#n(s){switch(s.method){case"eth_accounts":{const e=n.Account.fromStorage(this.#e);return e?[e.address]:[]}case"eth_requestAccounts":{let e=n.Account.fromStorage(this.#e);if(e)return this.#a.emit(r.ProviderEvent.ACCOUNTS_CONNECT,{chainId:f.numberToHex(e.chainId)}),[e.address];if(!c.SignerManager.fromStorage())throw new t.JsonRpcError(t.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");if(await c.SignerManager.embedded(),e=n.Account.fromStorage(this.#e),!e)throw new t.JsonRpcError(t.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - no account available");return this.#a.emit(r.ProviderEvent.ACCOUNTS_CHANGED,[e.address]),[e.address]}case"eth_sendTransaction":{const r=n.Account.fromStorage(this.#e),a=c.SignerManager.fromStorage(),o=e.Authentication.fromStorage(this.#e);if(!r||!a||!o)throw new t.JsonRpcError(t.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return this.#t(),await p.sendCalls({params:s.params||[],signer:a,account:r,authentication:o,backendClient:this.#o,policyId:this.#r})}case"eth_estimateGas":{const r=n.Account.fromStorage(this.#e),a=e.Authentication.fromStorage(this.#e);if(!r||!a)throw new t.JsonRpcError(t.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return this.#t(),await E.estimateGas({params:s.params||[],account:r,authentication:a,backendClient:this.#o,policyId:this.#r})}case"eth_signTypedData":case"eth_signTypedData_v4":{const e=n.Account.fromStorage(this.#e),r=c.SignerManager.fromStorage();if(!e||!r)throw new t.JsonRpcError(t.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");this.#t();const o=await this.getRpcProvider();return await a.signTypedDataV4({method:s.method,params:s.params||[],signer:r,accountType:e.type,rpcProvider:o})}case"personal_sign":{const e=n.Account.fromStorage(this.#e),r=c.SignerManager.fromStorage();if(!e||!r)throw new t.JsonRpcError(t.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return this.#t(),await m.personalSign({params:s.params||[],signer:r,account:e})}case"eth_chainId":{const e=await this.getRpcProvider(),{chainId:r}=await e.detectNetwork();return f.numberToHex(r)}case"wallet_switchEthereumChain":{const e=c.SignerManager.fromStorage();if(!e)throw new t.JsonRpcError(t.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");if(!s.params||!Array.isArray(s.params)||0===s.params.length)throw new t.JsonRpcError(t.RpcErrorCode.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");this.#t();try{const r=parseInt(s.params[0].chainId,16);await e.switchChain({chainId:r}),await import("@ethersproject/providers").then((e=>{this.#s=new e.StaticJsonRpcProvider(i.chainRpcs[r])}))}catch(e){throw new t.JsonRpcError(t.RpcErrorCode.INTERNAL_ERROR,"Failed to switch chain")}return null}case"wallet_addEthereumChain":{if(!c.SignerManager.fromStorage())throw new t.JsonRpcError(t.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");const e=await this.getRpcProvider();return await d.addEthereumChain({params:s.params||[],rpcProvider:e})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const r=n.Account.fromStorage(this.#e),a=c.SignerManager.fromStorage(),o=e.Authentication.fromStorage(this.#e);if(!r||!a||!o)throw new t.JsonRpcError(t.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return this.#t(),await l.getCallStatus({params:s.params||{},authentication:o,backendClient:this.#o,account:r})}case"wallet_sendCalls":{const r=n.Account.fromStorage(this.#e),a=c.SignerManager.fromStorage(),o=e.Authentication.fromStorage(this.#e);if(!r||!a||!o)throw new t.JsonRpcError(t.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return this.#t(),await p.sendCalls({params:s.params?s.params[0].calls:[],signer:a,account:r,authentication:o,backendClient:this.#o,policyId:this.#r})}case"wallet_grantPermissions":{const r=n.Account.fromStorage(this.#e),a=c.SignerManager.fromStorage(),o=e.Authentication.fromStorage(this.#e);if(!r||!a||!o)throw new t.JsonRpcError(t.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return this.#t(),await u.registerSession({params:s.params||[],signer:a,account:r,authentication:o,backendClient:this.#o,policyId:this.#r})}case"wallet_revokePermissions":{const r=n.Account.fromStorage(this.#e),a=c.SignerManager.fromStorage(),o=e.Authentication.fromStorage(this.#e);if(!r||!a||!o)throw new t.JsonRpcError(t.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return this.#t(),await g.revokeSession({params:s.params||[],signer:a,account:r,authentication:o,backendClient:this.#o})}case"wallet_getCapabilities":{const e=await this.getRpcProvider(),{chainId:r}=await e.detectNetwork();return{[f.numberToHex(r)]:{permissions:{supported:!0,signerTypes:["account","key"],keyTypes:["secp256k1"],permissionTypes:["contract-calls"]},paymasterService:{supported:!0},atomicBatch:{supported:!0}}}}case"eth_gasPrice":case"eth_getBalance":case"eth_getCode":case"eth_getStorageAt":case"eth_call":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":case"eth_getTransactionCount":return(await this.getRpcProvider()).send(s.method,s.params||[]);default:throw new t.JsonRpcError(t.ProviderErrorCode.UNSUPPORTED_METHOD,`${s.method}: Method not supported`)}}async request(e){try{return this.#n(e)}catch(e){if(e instanceof t.JsonRpcError)throw e;if(e instanceof Error)throw new t.JsonRpcError(t.RpcErrorCode.INTERNAL_ERROR,e.message);throw new t.JsonRpcError(t.RpcErrorCode.INTERNAL_ERROR,"Internal error")}}on(e,r){this.#a.on(e,r)}removeListener(e,r){this.#a.removeListener(e,r)}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const e={icon:'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="597.32 331.34 171.36 105.32" ><g><rect x="673.9" y="404.26" width="18.2" height="32.4" /><polygon points="768.68,331.36 768.68,331.36 768.68,331.34 610.78,331.34 610.78,331.36 597.32,331.36 597.32,436.64 615.52,436.64 615.52,349.54 750.48,349.54 750.48,436.64 768.68,436.64 " /><polygon points="732.16,367.79 633.83,367.79 633.83,370.19 633.79,370.19 633.79,436.64 651.99,436.64 651.99,385.99 713.9,385.99 713.9,436.64 732.09,436.64 732.09,385.99 732.16,385.99 " /></g></svg>',name:"Openfort",rdns:"xyz.openfort",uuid:
|
|
1
|
+
"use strict";const e={icon:'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="597.32 331.34 171.36 105.32" ><g><rect x="673.9" y="404.26" width="18.2" height="32.4" /><polygon points="768.68,331.36 768.68,331.36 768.68,331.34 610.78,331.34 610.78,331.36 597.32,331.36 597.32,436.64 615.52,436.64 615.52,349.54 750.48,349.54 750.48,436.64 768.68,436.64 " /><polygon points="732.16,367.79 633.83,367.79 633.83,370.19 633.79,370.19 633.79,436.64 651.99,436.64 651.99,385.99 713.9,385.99 713.9,436.64 732.09,436.64 732.09,385.99 732.16,385.99 " /></g></svg>',name:"Openfort",rdns:"xyz.openfort",uuid:crypto.randomUUID()};exports.announceProvider=function(e){if("undefined"==typeof window)return;const n=new CustomEvent("eip6963:announceProvider",{detail:Object.freeze(e)});window.dispatchEvent(n),window.addEventListener("eip6963:requestProvider",(()=>window.dispatchEvent(n)))},exports.openfortProviderInfo=e;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var r=require("../errors/openfortError.js"),
|
|
1
|
+
"use strict";var r=require("../errors/openfortError.js"),e=require("./JsonRpcError.js");exports.sendCalls=async({params:a,signer:t,account:n,authentication:o,backendClient:s,policyId:i})=>{const c=a[0]?.capabilities?.paymasterService?.policy??i,p=await(async(a,t,n,o,s)=>{const i=a.map((r=>{if(!r.to)throw new e.JsonRpcError(e.RpcErrorCode.INVALID_PARAMS,'wallet_sendCalls requires a "to" field');return{to:String(r.to),data:r.data?String(r.data):void 0,value:r.value?String(r.value):void 0}}));return r.withOpenfortError((async()=>(await t.transactionIntentsApi.createTransactionIntent({createTransactionIntentRequest:{policy:s,chainId:n.chainId,interactions:i}},{headers:{authorization:`Bearer ${t.config.backend.accessToken}`,"x-player-token":o.token,"x-auth-provider":o.thirdPartyProvider,"x-token-type":o.thirdPartyTokenType}})).data),{default:r.OpenfortErrorType.AUTHENTICATION_ERROR})})(a,s,n,o,c).catch((r=>{throw new e.JsonRpcError(e.RpcErrorCode.TRANSACTION_REJECTED,r.message)}));if(p.response?.error.reason)throw new e.JsonRpcError(e.RpcErrorCode.TRANSACTION_REJECTED,p.response?.error.reason);if(p?.nextAction?.payload?.signableHash){let a;a=[300,531050104,324,50104,2741,11124].includes(n.chainId)?await t.sign(p.nextAction.payload.signableHash,!1,!1):await t.sign(p.nextAction.payload.signableHash);const o=await r.withOpenfortError((async()=>await s.transactionIntentsApi.signature({id:p.id,signatureRequest:{signature:a}})),{default:r.OpenfortErrorType.AUTHENTICATION_ERROR}).catch((r=>{throw new e.JsonRpcError(e.RpcErrorCode.TRANSACTION_REJECTED,r.message)}));if(0===o.data.response?.status)throw new e.JsonRpcError(e.RpcErrorCode.TRANSACTION_REJECTED,o.data.response?.error.reason);return o.data.response?.transactionHash}return p.response?.transactionHash};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("
|
|
1
|
+
"use strict";var e=require("../types.js");exports.getSignedTypedData=async(t,s,a,n,c)=>{const o={...t.types};delete o.EIP712Domain;const{_TypedDataEncoder:r}=await import("@ethersproject/hash");let i=r.hash(t.domain,o,t.message);if([e.AccountType.UPGRADEABLE_V5,e.AccountType.UPGRADEABLE_V6,e.AccountType.ZKSYNC_UPGRADEABLE_V1,e.AccountType.ZKSYNC_UPGRADEABLE_V2].includes(s)){const e={name:"Openfort",version:"0.5",chainId:Number(a),verifyingContract:c},t={OpenfortMessage:[{name:"hashedMessage",type:"bytes32"}]},s={hashedMessage:i};i=r.hash(e,t,s)}return await n.sign(i,!1,!1)};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("
|
|
1
|
+
"use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.js"),r=require("../storage/istorage.js"),t=require("../iframe/iframeManager.js"),o=require("../storage/localStorage.js"),n=require("../configuration/authentication.js"),i=require("../errors/openfortError.js"),a=require("../iframe/types.js"),s=require("../configuration/configuration.js"),c=require("../configuration/recovery.js"),d=require("../signer/embedded.js"),u=require("../configuration/account.js");let h=null;class l{static storage=new o.LocalStorage;static fromStorage(){const e=this.storage.get(r.StorageKeys.SIGNER);if(!e)return null;const t=JSON.parse(e);return"embedded"===t.type?this.embeddedFromStorage(t.chainId):null}static embeddedFromStorage(e){const{iframeManager:r}=this,t=n.Authentication.fromStorage(this.storage);if(!t)throw new i.OpenfortError("Must be authenticated to create a signer",i.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const o=c.Recovery.fromStorage(this.storage);if(!o)throw new i.OpenfortError("Must have recovery to create a signer",i.OpenfortErrorType.INVALID_CONFIGURATION);const a={thirdPartyTokenType:t.thirdPartyTokenType,thirdPartyProvider:t.thirdPartyProvider,accessToken:t.token,playerID:t.player,recovery:this.shieldAuthentication(o,t,null),chainId:e,password:null};return new d.EmbeddedSigner(r,a,this.storage)}static get iframeManager(){if(h)return h;const r=s.Configuration.fromStorage();if(!r)throw new i.OpenfortError("Must be configured to create a signer",i.OpenfortErrorType.INVALID_CONFIGURATION);const o=new t.IframeManager({backendUrl:r.openfortURL,baseConfiguration:{publishableKey:r.publishableKey},iframeUrl:r.iframeURL,openfortAPIConfig:{backend:e.createConfig({basePath:r.openfortURL,accessToken:r.publishableKey})},shieldConfiguration:{shieldPublishableKey:r.shieldPublishableKey,shieldEncryptionKey:r.shieldEncryptionKey,debug:r.debug},shieldUrl:r.shieldURL});return h=o,o}static async embedded(e=null,t=null,o=null,a=null){const{iframeManager:s}=this,h=n.Authentication.fromStorage(this.storage);if(!h)throw new i.OpenfortError("Must be authenticated to create a signer",i.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const y=c.Recovery.fromStorage(this.storage),g=o||y?.type||"openfort",p=a||y?.customToken,f=new c.Recovery(g,p),T=this.shieldAuthentication(f,h,t),m={thirdPartyTokenType:h.thirdPartyTokenType,thirdPartyProvider:h.thirdPartyProvider,accessToken:h.token,playerID:h.player,recovery:T,chainId:e,password:t?.recoveryPassword||null},b={type:"embedded",chainId:e},O=await s.configure(m);return l.storage.save(r.StorageKeys.SIGNER,JSON.stringify(b)),new u.Account(O.accountType,O.address,O.chainId,O.ownerAddress).save(this.storage),new d.EmbeddedSigner(s,m,this.storage)}static shieldAuthentication(e,r,t){let o=null;if("openfort"===e.type)o={auth:a.ShieldAuthType.OPENFORT,authProvider:r.thirdPartyProvider||void 0,token:r.token,tokenType:r.thirdPartyTokenType||void 0,encryptionSession:t?.encryptionSession||void 0},new c.Recovery("openfort").save(this.storage);else if("custom"===e.type){if(!e.customToken)throw new i.OpenfortError("Custom recovery requires a token",i.OpenfortErrorType.INVALID_CONFIGURATION);o={auth:a.ShieldAuthType.CUSTOM,token:e.customToken},new c.Recovery("custom",e.customToken).save(this.storage)}return o}}exports.SignerManager=l;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../../packages/internal/openapi-clients/dist/index.js"),r=require("./evm/walletHelpers.js"),t=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/session.js"),g=require("./crypto/key-pair.js"),d=require("./configuration/authentication.js"),c=require("./iframe/iframeManager.js"),l=require("./authManager.js"),p=require("./evm/evmProvider.js");require("./evm/types.js");var f=require("./utils/typedEventEmitter.js"),y=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(t.StorageKeys.AUTHENTICATION),this.storage.remove(t.StorageKeys.SIGNER),this.storage.remove(t.StorageKeys.ACCOUNT),e&&await e.logout()}getEthereumProvider(e){const r={announceProvider:!0,...e},t=d.Authentication.fromStorage(this.storage),a=n.SignerManager.fromStorage(),o=u.Account.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new p.EvmProvider({storage:this.storage,openfortEventEmitter:new f,signer:a||void 0,account:o||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this)}),r.announceProvider&&y.announceProvider({info:{...y.openfortProviderInfo,...r.providerInfo},provider:this.provider})),this.provider}configureSessionKey(){const e=h.Session.fromStorage(this.storage);if(e)return{address:e.key.getPublicKey(),isRegistered:!0};const r=new g.KeyPair;return new h.Session(r).save(this.storage),{address:r.getPublicKey(),isRegistered:!1}}async configureEmbeddedSigner(e=null,r=null,t=null){await this.validateAndRefreshToken();const a=s.Configuration.fromStorage();let o=null;(t||r?.encryptionSession)&&(o={encryptionSession:r?.encryptionSession||null,recoveryPassword:t||null,encryptionPart:a?.shieldEncryptionKey||null});let i=null,u=null;r&&(i="openfort"===r.auth?"openfort":"custom",u=r.token),await n.SignerManager.embedded(e,o,i,u)}async signMessage(e,r){await this.validateAndRefreshToken();const t=n.SignerManager.fromStorage();if(!t)throw new o.OpenfortError("No signer configured",o.OpenfortErrorType.MISSING_SIGNER_ERROR);const{hashMessage:a=!0,arrayifyMessage:i=!1}=r||{};return await t.sign(e,i,a)}async signTypedData(e,t,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 r.getSignedTypedData({domain:e,types:t,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:r,encryptionSession:t}){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&&!r)throw new o.OpenfortError("Recovery password is required",o.OpenfortErrorType.INVALID_CONFIGURATION);await a.setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:r,encryptionSession:t})}async logInWithEmailPassword({email:e,password:r,ecosystemGame:t}){const a=d.Authentication.fromStorage(this.storage),n=await this.authManager.loginEmailPassword(e,r,t);return a&&a.player!==n.player.id&&this.logout(),new d.Authentication("jwt",n.token,n.player.id,n.refreshToken).save(this.storage),n}async signUpGuest(){const e=d.Authentication.fromStorage(this.storage),r=await this.authManager.registerGuest();return e&&e.player!==r.player.id&&this.logout(),new d.Authentication("jwt",r.token,r.player.id,r.refreshToken).save(this.storage),r}async signUpWithEmailPassword({email:e,password:r,options:t,ecosystemGame:a}){const n=d.Authentication.fromStorage(this.storage),o=await this.authManager.signupEmailPassword(e,r,t?.data.name,a);return n&&n.player!==o.player.id&&this.logout(),new d.Authentication("jwt",o.token,o.player.id,o.refreshToken).save(this.storage),o}async linkEmailPassword({email:e,password:r,authToken:t,ecosystemGame:a}){return await this.authManager.linkEmail(e,r,t,a)}async unlinkEmailPassword({email:e,authToken:r}){return await this.authManager.unlinkEmail(e,r)}async requestEmailVerification({email:e,redirectUrl:r}){await this.authManager.requestEmailVerification(e,r)}async resetPassword({email:e,password:r,state:t}){await this.authManager.resetPassword(e,r,t)}async requestResetPassword({email:e,redirectUrl:r}){await this.authManager.requestResetPassword(e,r)}async verifyEmail({email:e,state:r}){await this.authManager.verifyEmail(e,r)}async initOAuth({provider:e,options:r,ecosystemGame:a}){return this.storage.remove(t.StorageKeys.AUTHENTICATION),await this.authManager.initOAuth(e,r,a)}async initLinkOAuth({provider:e,options:r,ecosystemGame:t}){const a=d.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,r,t)}async linkThirdPartyProvider({provider:e,token:r,tokenType:t}){const a=d.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,r,t)}async unlinkOAuth({provider:e,authToken:r}){return await this.authManager.unlinkOAuth(e,r)}async poolOAuth(e){const r=d.Authentication.fromStorage(this.storage),t=await this.authManager.poolOAuth(e);return r&&r.player!==t.player.id&&this.logout(),new d.Authentication("jwt",t.token,t.player.id,t.refreshToken).save(this.storage),t}async authenticateWithThirdPartyProvider({provider:e,token:r,tokenType:t,ecosystemGame:a}){const o=d.Authentication.fromStorage(this.storage),i=await this.authManager.authenticateThirdParty(e,r,t,a);let s=!1;if(o&&o.player!==i.id&&(this.logout(),s=!0),new d.Authentication("third_party",r,i.id,null,e,t).save(this.storage),s)return i;const u=n.SignerManager.fromStorage();try{await(u?.updateAuthentication())}catch(e){throw(e instanceof c.MissingRecoveryPasswordError||e instanceof c.MissingProjectEntropyError)&&await(u?.logout()),e}return i}async initSIWE({address:e,ecosystemGame:r}){return await this.authManager.initSIWE(e,r)}async authenticateWithSIWE({signature:e,message:r,walletClientType:t,connectorType:a}){const n=d.Authentication.fromStorage(this.storage),o=await this.authManager.authenticateSIWE(e,r,t,a);return n&&n.player!==o.player.id&&this.logout(),new d.Authentication("jwt",o.token,o.player.id,o.refreshToken).save(this.storage),o}async linkWallet({signature:e,message:r,walletClientType:t,connectorType:a,authToken:n}){return await this.authManager.linkWallet(e,r,t,a,n)}async unlinkWallet({address:e,authToken:r}){return await this.authManager.unlinkWallet(e,r)}storeCredentials(e){if(this.storage.remove(t.StorageKeys.AUTHENTICATION),!e.player)throw new o.OpenfortError("Player ID is required to store credentials",o.OpenfortErrorType.INVALID_CONFIGURATION);new d.Authentication("jwt",e.accessToken,e.player,e.refreshToken).save(this.storage)}async sendSignatureTransactionIntentRequest(e,r=null,t=null,a=!1){if(!s.Configuration.fromStorage())throw new o.OpenfortError("Configuration not found",o.OpenfortErrorType.INVALID_CONFIGURATION);await this.validateAndRefreshToken();let i=t;if(!i){if(!r)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(r)}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 r=s.Configuration.fromStorage();if(!r)throw new o.OpenfortError("Configuration not found",o.OpenfortErrorType.INVALID_CONFIGURATION);return new e.BackendApiClients({backend:e.createConfig({basePath:r.openfortURL,accessToken:r.publishableKey})})}async sendSignatureSessionRequest(e,r,t){const a={id:e,signatureRequest:{signature:r,optimistic:t}};return(await this.backendApiClients.sessionsApi.signatureSession(a)).data}getEmbeddedState(){if(!d.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 d.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 l.AuthManager(e.publishableKey,e.openfortURL)}return this.iAuthManager}async getUser(){await this.validateAndRefreshToken();const e=d.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 r=d.Authentication.fromStorage(this.storage);if(!r)throw new o.OpenfortError("Must be logged in to validate and refresh token",o.OpenfortErrorType.NOT_LOGGED_IN_ERROR);if("jwt"!==r.type)return;const t=await this.authManager.validateCredentials(r,e);if(!t.player)throw new o.OpenfortError("No player found in credentials",o.OpenfortErrorType.INTERNAL_ERROR);if(t.accessToken===r.token)return;new d.Authentication("jwt",t.accessToken,t.player,t.refreshToken).save(this.storage);const a=n.SignerManager.fromStorage();try{await(a?.updateAuthentication())}catch(e){throw(e instanceof c.MissingRecoveryPasswordError||e instanceof c.MissingProjectEntropyError)&&await(a?.logout()),e}}};
|
|
1
|
+
"use strict";var e=require("../../packages/internal/openapi-clients/dist/index.js"),r=require("./evm/walletHelpers.js"),t=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(t.StorageKeys.AUTHENTICATION),this.storage.remove(t.StorageKeys.SIGNER),this.storage.remove(t.StorageKeys.ACCOUNT),e&&await e.logout()}getEthereumProvider(e){const r={announceProvider:!0,...e},t=h.Authentication.fromStorage(this.storage),a=n.SignerManager.fromStorage(),o=u.Account.fromStorage(this.storage);return this.provider?this.provider&&r.policy&&this.provider.updatePolicy(r.policy):(this.provider=new c.EvmProvider({storage:this.storage,openfortEventEmitter:new l,signer:a||void 0,account:o||void 0,authentication:t||void 0,backendApiClients:this.backendApiClients,policyId:r.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this)}),r.announceProvider&&p.announceProvider({info:{...p.openfortProviderInfo,...r.providerInfo},provider:this.provider})),this.provider}async configureEmbeddedSigner(e=null,r=null,t=null){await this.validateAndRefreshToken();const a=s.Configuration.fromStorage();let o=null;(t||r?.encryptionSession)&&(o={encryptionSession:r?.encryptionSession||null,recoveryPassword:t||null,encryptionPart:a?.shieldEncryptionKey||null});let i=null,u=null;r&&(i="openfort"===r.auth?"openfort":"custom",u=r.token),await n.SignerManager.embedded(e,o,i,u)}async signMessage(e,r){await this.validateAndRefreshToken();const t=n.SignerManager.fromStorage();if(!t)throw new o.OpenfortError("No signer configured",o.OpenfortErrorType.MISSING_SIGNER_ERROR);const{hashMessage:a=!0,arrayifyMessage:i=!1}=r||{};return await t.sign(e,i,a)}async signTypedData(e,t,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 r.getSignedTypedData({domain:e,types:t,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:r,encryptionSession:t}){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&&!r)throw new o.OpenfortError("Recovery password is required",o.OpenfortErrorType.INVALID_CONFIGURATION);await a.setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:r,encryptionSession:t})}async logInWithEmailPassword({email:e,password:r,ecosystemGame:t}){const a=h.Authentication.fromStorage(this.storage),n=await this.authManager.loginEmailPassword(e,r,t);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),r=await this.authManager.registerGuest();return e&&e.player!==r.player.id&&this.logout(),new h.Authentication("jwt",r.token,r.player.id,r.refreshToken).save(this.storage),r}async signUpWithEmailPassword({email:e,password:r,options:t,ecosystemGame:a}){const n=h.Authentication.fromStorage(this.storage),o=await this.authManager.signupEmailPassword(e,r,t?.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:r,authToken:t,ecosystemGame:a}){return await this.authManager.linkEmail(e,r,t,a)}async unlinkEmailPassword({email:e,authToken:r}){return await this.authManager.unlinkEmail(e,r)}async requestEmailVerification({email:e,redirectUrl:r}){await this.authManager.requestEmailVerification(e,r)}async resetPassword({email:e,password:r,state:t}){await this.authManager.resetPassword(e,r,t)}async requestResetPassword({email:e,redirectUrl:r}){await this.authManager.requestResetPassword(e,r)}async verifyEmail({email:e,state:r}){await this.authManager.verifyEmail(e,r)}async initOAuth({provider:e,options:r,ecosystemGame:a}){return this.storage.remove(t.StorageKeys.AUTHENTICATION),await this.authManager.initOAuth(e,r,a)}async initLinkOAuth({provider:e,options:r,ecosystemGame:t}){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,r,t)}async linkThirdPartyProvider({provider:e,token:r,tokenType:t}){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,r,t)}async unlinkOAuth({provider:e,authToken:r}){return await this.authManager.unlinkOAuth(e,r)}async poolOAuth(e){const r=h.Authentication.fromStorage(this.storage),t=await this.authManager.poolOAuth(e);return r&&r.player!==t.player.id&&this.logout(),new h.Authentication("jwt",t.token,t.player.id,t.refreshToken).save(this.storage),t}async authenticateWithThirdPartyProvider({provider:e,token:r,tokenType:t,ecosystemGame:a}){const o=h.Authentication.fromStorage(this.storage),i=await this.authManager.authenticateThirdParty(e,r,t,a);let s=!1;if(o&&o.player!==i.id&&(this.logout(),s=!0),new h.Authentication("third_party",r,i.id,null,e,t).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 initSIWE({address:e,ecosystemGame:r}){return await this.authManager.initSIWE(e,r)}async authenticateWithSIWE({signature:e,message:r,walletClientType:t,connectorType:a}){const n=h.Authentication.fromStorage(this.storage),o=await this.authManager.authenticateSIWE(e,r,t,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:r,walletClientType:t,connectorType:a,authToken:n}){return await this.authManager.linkWallet(e,r,t,a,n)}async unlinkWallet({address:e,authToken:r}){return await this.authManager.unlinkWallet(e,r)}storeCredentials(e){if(this.storage.remove(t.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,r=null,t=null,a=!1){if(!s.Configuration.fromStorage())throw new o.OpenfortError("Configuration not found",o.OpenfortErrorType.INVALID_CONFIGURATION);await this.validateAndRefreshToken();let i=t;if(!i){if(!r)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(r)}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 r=s.Configuration.fromStorage();if(!r)throw new o.OpenfortError("Configuration not found",o.OpenfortErrorType.INVALID_CONFIGURATION);return new e.BackendApiClients({backend:e.createConfig({basePath:r.openfortURL,accessToken:r.publishableKey})})}async sendSignatureSessionRequest(e,r,t){const a={id:e,signatureRequest:{signature:r,optimistic:t}};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 r=h.Authentication.fromStorage(this.storage);if(!r)throw new o.OpenfortError("Must be logged in to validate and refresh token",o.OpenfortErrorType.NOT_LOGGED_IN_ERROR);if("jwt"!==r.type)return;const t=await this.authManager.validateCredentials(r,e);if(!t.player)throw new o.OpenfortError("No player found in credentials",o.OpenfortErrorType.INTERNAL_ERROR);if(t.accessToken===r.token)return;new h.Authentication("jwt",t.accessToken,t.player,t.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}}};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";function t(t,{dir:e,size:n=32}={}){if(null===n)return t;const r=t.replace("0x","");if(r.length>2*n)throw new Error("Hex string is too long");return`0x${r["right"===e?"padEnd":"padStart"](2*n,"0")}`}require("@noble/curves/secp256k1"),require("@noble/hashes/utils"),exports.numberToHex=function(e,n={}){const{size:r}=n,i=BigInt(e);let o;if(r?o=BigInt(2)**(BigInt(r)*BigInt(8))-BigInt(1):"number"==typeof e&&(o=BigInt(Number.MAX_SAFE_INTEGER)),o&&i>o||i<0){throw new Error(`Value out of bounds: ${i}${"bigint"==typeof e?"n":""}`)}const s=`0x${i.toString(16)}`;return r?t(s,{size:r}):s},exports.padHex=t;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.VERSION="0.8.
|
|
1
|
+
"use strict";exports.VERSION="0.8.32";
|
package/dist/index.d.ts
CHANGED
|
@@ -17,10 +17,6 @@ declare enum EmbeddedState {
|
|
|
17
17
|
CREATING_ACCOUNT = 3,
|
|
18
18
|
READY = 4
|
|
19
19
|
}
|
|
20
|
-
type SessionKey = {
|
|
21
|
-
address: string;
|
|
22
|
-
isRegistered: boolean;
|
|
23
|
-
};
|
|
24
20
|
type CurrentAccount = {
|
|
25
21
|
address: string;
|
|
26
22
|
ownerAddress: string;
|
|
@@ -472,32 +468,6 @@ declare class SDKConfiguration {
|
|
|
472
468
|
constructor({ baseConfiguration, shieldConfiguration, overrides, }: OpenfortSDKConfiguration);
|
|
473
469
|
}
|
|
474
470
|
|
|
475
|
-
/**
|
|
476
|
-
* ProviderErrors should take priority over RpcErrorCodes
|
|
477
|
-
* https://eips.ethereum.org/EIPS/eip-1193#provider-errors
|
|
478
|
-
* https://eips.ethereum.org/EIPS/eip-1474#error-codes
|
|
479
|
-
*/
|
|
480
|
-
declare enum ProviderErrorCode {
|
|
481
|
-
USER_REJECTED_REQUEST = 4001,
|
|
482
|
-
UNAUTHORIZED = 4100,
|
|
483
|
-
UNSUPPORTED_METHOD = 4200,
|
|
484
|
-
DISCONNECTED = 4900
|
|
485
|
-
}
|
|
486
|
-
declare enum RpcErrorCode {
|
|
487
|
-
RPC_SERVER_ERROR = -32000,
|
|
488
|
-
INVALID_REQUEST = -32600,
|
|
489
|
-
METHOD_NOT_FOUND = -32601,
|
|
490
|
-
INVALID_PARAMS = -32602,
|
|
491
|
-
INTERNAL_ERROR = -32603,
|
|
492
|
-
PARSE_ERROR = -32700,
|
|
493
|
-
TRANSACTION_REJECTED = -32003
|
|
494
|
-
}
|
|
495
|
-
declare class JsonRpcError extends Error {
|
|
496
|
-
readonly message: string;
|
|
497
|
-
readonly code: ProviderErrorCode | RpcErrorCode;
|
|
498
|
-
constructor(code: ProviderErrorCode | RpcErrorCode, message: string);
|
|
499
|
-
}
|
|
500
|
-
|
|
501
471
|
interface TypedDataPayload {
|
|
502
472
|
types: {
|
|
503
473
|
[K in string]: Array<{
|
|
@@ -524,23 +494,8 @@ interface RequestArguments {
|
|
|
524
494
|
method: string;
|
|
525
495
|
params?: Array<any>;
|
|
526
496
|
}
|
|
527
|
-
type JsonRpcRequestPayload = RequestArguments & {
|
|
528
|
-
jsonrpc?: string;
|
|
529
|
-
id?: string | number;
|
|
530
|
-
};
|
|
531
|
-
interface JsonRpcRequestCallback {
|
|
532
|
-
(err: JsonRpcError | null, result?: JsonRpcResponsePayload | (JsonRpcResponsePayload | null)[] | null): void;
|
|
533
|
-
}
|
|
534
|
-
interface JsonRpcResponsePayload {
|
|
535
|
-
result?: Array<any> | null;
|
|
536
|
-
error?: JsonRpcError | null;
|
|
537
|
-
jsonrpc?: string;
|
|
538
|
-
id?: string | number;
|
|
539
|
-
}
|
|
540
497
|
type Provider = {
|
|
541
498
|
request: (request: RequestArguments) => Promise<any>;
|
|
542
|
-
sendAsync: (request: JsonRpcRequestPayload | JsonRpcRequestPayload[], callback: JsonRpcRequestCallback) => void;
|
|
543
|
-
send: (request: string | JsonRpcRequestPayload | JsonRpcRequestPayload[], callbackOrParams?: JsonRpcRequestCallback | Array<any>, callback?: JsonRpcRequestCallback) => void;
|
|
544
499
|
on: (event: string, listener: (...args: any[]) => void) => void;
|
|
545
500
|
removeListener: (event: string, listener: (...args: any[]) => void) => void;
|
|
546
501
|
isOpenfort: boolean;
|
|
@@ -571,12 +526,6 @@ declare class Openfort {
|
|
|
571
526
|
};
|
|
572
527
|
announceProvider?: boolean;
|
|
573
528
|
}): Provider;
|
|
574
|
-
/**
|
|
575
|
-
* Configures a session key and returns the session key details.
|
|
576
|
-
*
|
|
577
|
-
* @returns A SessionKey object containing the address and registration status.
|
|
578
|
-
*/
|
|
579
|
-
configureSessionKey(): SessionKey;
|
|
580
529
|
/**
|
|
581
530
|
* Configures an embedded signer.
|
|
582
531
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BackendApiClients as e,createConfig as t}from"../../packages/internal/openapi-clients/dist/index.js";import*as a from"crypto";import{
|
|
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 n,OpenfortError as r}from"./errors/openfortError.js";import{CodeChallengeMethodEnum as s}from"./types.js";import o from"./utils/deviceCredentialsManager.js";import{isBrowser as l}from"./utils/helpers.js";function c(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function d(e){return a.createHash("sha256").update(e).digest()}class h{publishableKey;deviceCredentialsManager;backendApiClients;constructor(a,i){this.publishableKey=a,this.deviceCredentialsManager=new o,this.backendApiClients=new e({backend:t({basePath:i,accessToken:a})})}async initOAuth(e,t,a){const i=t?.usePooling??!1;delete t?.usePooling;const n={oAuthInitRequest:{provider:e,options:t,usePooling:i}},r=await this.backendApiClients.authenticationApi.initOAuth(n,h.getEcosystemGameOptsOrUndefined(a));return l()&&t?.skipBrowserRedirect&&window.location.assign(r.data.url),{url:r.data.url,key:r.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 authenticateThirdParty(e,t,a,r){const s={thirdPartyOAuthRequest:{provider:e,token:t,tokenType:a}};return i((async()=>(await this.backendApiClients.authenticationApi.thirdParty(s,h.getEcosystemGameOptsOrUndefined(r))).data),{default:n.AUTHENTICATION_ERROR,403:n.USER_NOT_AUTHORIZED_ON_ECOSYSTEM})}async initSIWE(e,t){const a={sIWERequest:{address:e}},i=await this.backendApiClients.authenticationApi.initSIWE(a,h.getEcosystemGameOptsOrUndefined(t));return{address:i.data.address,nonce:i.data.nonce,expiresAt:i.data.expiresAt}}async authenticateSIWE(e,t,a,r){const s={sIWEAuthenticateRequest:{signature:e,message:t,walletClientType:a,connectorType:r}};return i((async()=>(await this.backendApiClients.authenticationApi.authenticateSIWE(s)).data),{default:n.AUTHENTICATION_ERROR,403:n.USER_NOT_AUTHORIZED_ON_ECOSYSTEM})}static getEcosystemGameOptsOrUndefined(e){if(e)return{headers:{"x-game":e}}}async loginEmailPassword(e,t,a){const r={loginRequest:{email:e,password:t}};return i((async()=>(await this.backendApiClients.authenticationApi.loginEmailPassword(r,h.getEcosystemGameOptsOrUndefined(a))).data),{default:n.AUTHENTICATION_ERROR,403:n.USER_NOT_AUTHORIZED_ON_ECOSYSTEM})}async requestResetPassword(e,t){const i=c(a.randomBytes(32)),n=c(d(i)),r=c(a.randomBytes(32));this.deviceCredentialsManager.savePKCEData({state:r,verifier:i});const o={requestResetPasswordRequest:{email:e,redirectUrl:t,challenge:{codeChallenge:n,method:s.S256}}};await this.backendApiClients.authenticationApi.requestResetPassword(o)}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 n={resetPasswordRequest:{email:e,password:t,state:a,challenge:{codeVerifier:i.verifier}}};await this.backendApiClients.authenticationApi.resetPassword(n)}),{default:n.AUTHENTICATION_ERROR})}async requestEmailVerification(e,t){const i=c(a.randomBytes(32)),n=c(d(i)),r=c(a.randomBytes(32));this.deviceCredentialsManager.savePKCEData({state:r,verifier:i});const o={requestVerifyEmailRequest:{email:e,redirectUrl:t,challenge:{codeChallenge:n,method:s.S256}}};await this.backendApiClients.authenticationApi.requestEmailVerification(o)}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:n.AUTHENTICATION_ERROR})}async signupEmailPassword(e,t,a,r){const s={signupRequest:{email:e,password:t,name:a}};return i((async()=>(await this.backendApiClients.authenticationApi.signupEmailPassword(s,h.getEcosystemGameOptsOrUndefined(r))).data),{default:n.USER_REGISTRATION_ERROR,403:n.USER_NOT_AUTHORIZED_ON_ECOSYSTEM})}async validateCredentialsWithoutCrypto(e,t){if(!t.refreshToken)throw new r("No refresh token provided",n.AUTHENTICATION_ERROR);if(!JWK_UTILS)throw new r("JWK_UTILS not available",n.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("Invalid token signature",n.AUTHENTICATION_ERROR);const s=JSON.parse(i.payloadPP);if(!s.exp)return this.refreshTokens(t.refreshToken);const o=JWK_UTILS.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 r("No refresh token provided",n.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 r("No refresh token provided",n.AUTHENTICATION_ERROR);if(t)return this.refreshTokens(e.refreshToken,t);h.getWebCrypto();return this.validateCredentialsWithCrypto(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("No JWKS keys found",n.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:n.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:n.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,n){const r={thirdPartyLinkRequest:{provider:t,token:a,tokenType:i}};return(await this.backendApiClients.authenticationApi.linkThirdParty(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":n||void 0}})).data}async linkOAuth(e,t,a,i){const n={oAuthInitRequest:{provider:t,options:a,usePooling:a?.usePooling||!1}},r=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":i||void 0}});return l()&&!a?.skipBrowserRedirect&&window.location.assign(r.data.url),{url:r.data.url,key:r.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,n){const r={sIWEAuthenticateRequest:{signature:e,message:t,walletClientType:a,connectorType:i}};return(await this.backendApiClients.authenticationApi.linkSIWE(r,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":n}})).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 l()?window.crypto:"undefined"!=typeof global&&global.crypto?global.crypto:null}async linkEmail(e,t,a,i){const n={loginRequest:{email:e,password:t}};return(await this.backendApiClients.authenticationApi.linkEmail(n,{headers:{authorization:`Bearer ${this.publishableKey}`,"x-player-token":a,"x-game":i||void 0}})).data}}export{h as AuthManager};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Authentication as t}from"../configuration/authentication.js";import{ProviderEvent as e}from"./types.js";import{JsonRpcError as r,ProviderErrorCode as a,RpcErrorCode as s}from"./JsonRpcError.js";import{signTypedDataV4 as i}from"./signTypedDataV4.js";import{OpenfortEvents as o}from"../types.js";import n from"../utils/typedEventEmitter.js";import{chainRpcs as c}from"../chains/index.js";import{Account as h}from"../configuration/account.js";import{SignerManager as d}from"../manager/signer.js";import{StorageKeys as m}from"../storage/istorage.js";import{addEthereumChain as p}from"./addEthereumChain.js";import{registerSession as l}from"./registerSession.js";import{revokeSession as u}from"./revokeSession.js";import{sendCalls as g}from"./sendCalls.js";import{getCallStatus as f}from"./getCallsStatus.js";import{personalSign as w}from"./personalSign.js";import{estimateGas as A}from"./estimateGas.js";import{numberToHex as S}from"../utils/crypto.js";class R{#t;#e;updatePolicy(t){this.#e=t}#r;#a;#s=null;#i;isOpenfort=!0;constructor({storage:t,backendApiClients:e,openfortEventEmitter:r,policyId:a,validateAndRefreshSession:s}){this.#t=t,this.#e=a,this.#r=s,this.#i=e,this.#i=e,this.#a=new n,r.on(o.LOGGED_OUT,this.#o)}#o=()=>{const t=!!h.fromStorage(this.#t),r=d.fromStorage();r?.logout(),this.#t.remove(m.ACCOUNT),this.#t.remove(m.AUTHENTICATION),this.#t.remove(m.SIGNER),t&&this.#a.emit(e.ACCOUNTS_CHANGED,[])};async getRpcProvider(){if(!this.#s){const t=h.fromStorage(this.#t),e=t?.chainId||8453;await import("@ethersproject/providers").then((t=>{this.#s=new t.StaticJsonRpcProvider(c[e])}))}if(!this.#s)throw new Error("RPC provider not initialized");return this.#s}async#n(o){switch(o.method){case"eth_accounts":{const t=h.fromStorage(this.#t);return t?[t.address]:[]}case"eth_requestAccounts":{let t=h.fromStorage(this.#t);if(t)return this.#a.emit(e.ACCOUNTS_CONNECT,{chainId:S(t.chainId)}),[t.address];if(!d.fromStorage())throw new r(a.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");if(await d.embedded(),t=h.fromStorage(this.#t),!t)throw new r(a.UNAUTHORIZED,"Unauthorized - no account available");return this.#a.emit(e.ACCOUNTS_CHANGED,[t.address]),[t.address]}case"eth_sendTransaction":{const e=h.fromStorage(this.#t),s=d.fromStorage(),i=t.fromStorage(this.#t);if(!e||!s||!i)throw new r(a.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return this.#r(),await g({params:o.params||[],signer:s,account:e,authentication:i,backendClient:this.#i,policyId:this.#e})}case"eth_estimateGas":{const e=h.fromStorage(this.#t),s=t.fromStorage(this.#t);if(!e||!s)throw new r(a.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return this.#r(),await A({params:o.params||[],account:e,authentication:s,backendClient:this.#i,policyId:this.#e})}case"eth_signTypedData":case"eth_signTypedData_v4":{const t=h.fromStorage(this.#t),e=d.fromStorage();if(!t||!e)throw new r(a.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");this.#r();const s=await this.getRpcProvider();return await i({method:o.method,params:o.params||[],signer:e,accountType:t.type,rpcProvider:s})}case"personal_sign":{const t=h.fromStorage(this.#t),e=d.fromStorage();if(!t||!e)throw new r(a.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return this.#r(),await w({params:o.params||[],signer:e,account:t})}case"eth_chainId":{const t=await this.getRpcProvider(),{chainId:e}=await t.detectNetwork();return S(e)}case"wallet_switchEthereumChain":{const t=d.fromStorage();if(!t)throw new r(a.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");if(!o.params||!Array.isArray(o.params)||0===o.params.length)throw new r(s.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");this.#r();try{const e=parseInt(o.params[0].chainId,16);await t.switchChain({chainId:e}),await import("@ethersproject/providers").then((t=>{this.#s=new t.StaticJsonRpcProvider(c[e])}))}catch(t){throw new r(s.INTERNAL_ERROR,"Failed to switch chain")}return null}case"wallet_addEthereumChain":{if(!d.fromStorage())throw new r(a.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");const t=await this.getRpcProvider();return await p({params:o.params||[],rpcProvider:t})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const e=h.fromStorage(this.#t),s=d.fromStorage(),i=t.fromStorage(this.#t);if(!e||!s||!i)throw new r(a.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return this.#r(),await f({params:o.params||{},authentication:i,backendClient:this.#i,account:e})}case"wallet_sendCalls":{const e=h.fromStorage(this.#t),s=d.fromStorage(),i=t.fromStorage(this.#t);if(!e||!s||!i)throw new r(a.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return this.#r(),await g({params:o.params?o.params[0].calls:[],signer:s,account:e,authentication:i,backendClient:this.#i,policyId:this.#e})}case"wallet_grantPermissions":{const e=h.fromStorage(this.#t),s=d.fromStorage(),i=t.fromStorage(this.#t);if(!e||!s||!i)throw new r(a.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return this.#r(),await l({params:o.params||[],signer:s,account:e,authentication:i,backendClient:this.#i,policyId:this.#e})}case"wallet_revokePermissions":{const e=h.fromStorage(this.#t),s=d.fromStorage(),i=t.fromStorage(this.#t);if(!e||!s||!i)throw new r(a.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return this.#r(),await u({params:o.params||[],signer:s,account:e,authentication:i,backendClient:this.#i})}case"wallet_getCapabilities":{const t=await this.getRpcProvider(),{chainId:e}=await t.detectNetwork();return{[S(e)]:{permissions:{supported:!0,signerTypes:["account","key"],keyTypes:["secp256k1"],permissionTypes:["contract-calls"]},paymasterService:{supported:!0},atomicBatch:{supported:!0}}}}case"eth_gasPrice":case"eth_getBalance":case"eth_getCode":case"eth_getStorageAt":case"eth_call":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":case"eth_getTransactionCount":return(await this.getRpcProvider()).send(o.method,o.params||[]);default:throw new r(a.UNSUPPORTED_METHOD,`${o.method}: Method not supported`)}}async request(t){try{return this.#n(t)}catch(t){if(t instanceof r)throw t;if(t instanceof Error)throw new r(s.INTERNAL_ERROR,t.message);throw new r(s.INTERNAL_ERROR,"Internal error")}}on(t,e){this.#a.on(t,e)}removeListener(t,e){this.#a.removeListener(t,e)}}export{R as EvmProvider};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
const e={icon:'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="597.32 331.34 171.36 105.32" ><g><rect x="673.9" y="404.26" width="18.2" height="32.4" /><polygon points="768.68,331.36 768.68,331.36 768.68,331.34 610.78,331.34 610.78,331.36 597.32,331.36 597.32,436.64 615.52,436.64 615.52,349.54 750.48,349.54 750.48,436.64 768.68,436.64 " /><polygon points="732.16,367.79 633.83,367.79 633.83,370.19 633.79,370.19 633.79,436.64 651.99,436.64 651.99,385.99 713.9,385.99 713.9,436.64 732.09,436.64 732.09,385.99 732.16,385.99 " /></g></svg>',name:"Openfort",rdns:"xyz.openfort",uuid:crypto.randomUUID()};function n(e){if("undefined"==typeof window)return;const n=new CustomEvent("eip6963:announceProvider",{detail:Object.freeze(e)});window.dispatchEvent(n);window.addEventListener("eip6963:requestProvider",(()=>window.dispatchEvent(n)))}export{n as announceProvider,e as openfortProviderInfo};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{withOpenfortError as a,OpenfortErrorType as t}from"../errors/openfortError.js";import{JsonRpcError as e,RpcErrorCode as n}from"./JsonRpcError.js";const r=async({params:r,signer:
|
|
1
|
+
import{withOpenfortError as a,OpenfortErrorType as t}from"../errors/openfortError.js";import{JsonRpcError as e,RpcErrorCode as n}from"./JsonRpcError.js";const r=async({params:r,signer:s,account:o,authentication:i,backendClient:c,policyId:d})=>{const p=r[0]?.capabilities?.paymasterService?.policy??d,l=await(async(r,s,o,i,c)=>{const d=r.map((a=>{if(!a.to)throw new e(n.INVALID_PARAMS,'wallet_sendCalls requires a "to" field');return{to:String(a.to),data:a.data?String(a.data):void 0,value:a.value?String(a.value):void 0}}));return a((async()=>(await s.transactionIntentsApi.createTransactionIntent({createTransactionIntentRequest:{policy:c,chainId:o.chainId,interactions:d}},{headers:{authorization:`Bearer ${s.config.backend.accessToken}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}})).data),{default:t.AUTHENTICATION_ERROR})})(r,c,o,i,p).catch((a=>{throw new e(n.TRANSACTION_REJECTED,a.message)}));if(l.response?.error.reason)throw new e(n.TRANSACTION_REJECTED,l.response?.error.reason);if(l?.nextAction?.payload?.signableHash){let r;r=[300,531050104,324,50104,2741,11124].includes(o.chainId)?await s.sign(l.nextAction.payload.signableHash,!1,!1):await s.sign(l.nextAction.payload.signableHash);const i=await a((async()=>await c.transactionIntentsApi.signature({id:l.id,signatureRequest:{signature:r}})),{default:t.AUTHENTICATION_ERROR}).catch((a=>{throw new e(n.TRANSACTION_REJECTED,a.message)}));if(0===i.data.response?.status)throw new e(n.TRANSACTION_REJECTED,i.data.response?.error.reason);return i.data.response?.transactionHash}return l.response?.transactionHash};export{r as sendCalls};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{AccountType as e}from"../types.js";const s=async(s,t,a,n,o)=>{const r={...s.types};delete r.EIP712Domain;const{_TypedDataEncoder:i}=await import("@ethersproject/hash");let h=i.hash(s.domain,r,s.message);if([e.UPGRADEABLE_V5,e.UPGRADEABLE_V6,e.ZKSYNC_UPGRADEABLE_V1,e.ZKSYNC_UPGRADEABLE_V2].includes(t)){const e={name:"Openfort",version:"0.5",chainId:Number(a),verifyingContract:o},s={OpenfortMessage:[{name:"hashedMessage",type:"bytes32"}]},t={hashedMessage:h};h=i.hash(e,s,t)}return await n.sign(h,!1,!1)};export{s as getSignedTypedData};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{createConfig as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{StorageKeys as t}from"../storage/istorage.js";import{IframeManager as r}from"../iframe/iframeManager.js";import{LocalStorage as o}from"../storage/localStorage.js";import{Authentication as i}from"../configuration/authentication.js";import{OpenfortError as n,OpenfortErrorType as a}from"../errors/openfortError.js";import{ShieldAuthType as s}from"../iframe/types.js";import{Configuration as c}from"../configuration/configuration.js";import{Recovery as d}from"../configuration/recovery.js";import{EmbeddedSigner as h}from"../signer/embedded.js";import{Account as l}from"../configuration/account.js";let u=null;class f{static storage=new o;static fromStorage(){const e=this.storage.get(t.SIGNER);if(!e)return null;const r=JSON.parse(e);return"embedded"===r.type?this.embeddedFromStorage(r.chainId):null}static embeddedFromStorage(e){const{iframeManager:t}=this,r=i.fromStorage(this.storage);if(!r)throw new n("Must be authenticated to create a signer",a.NOT_LOGGED_IN_ERROR);const o=d.fromStorage(this.storage);if(!o)throw new n("Must have recovery to create a signer",a.INVALID_CONFIGURATION);const s={thirdPartyTokenType:r.thirdPartyTokenType,thirdPartyProvider:r.thirdPartyProvider,accessToken:r.token,playerID:r.player,recovery:this.shieldAuthentication(o,r,null),chainId:e,password:null};return new h(t,s,this.storage)}static get iframeManager(){if(u)return u;const t=c.fromStorage();if(!t)throw new n("Must be configured to create a signer",a.INVALID_CONFIGURATION);const o=new r({backendUrl:t.openfortURL,baseConfiguration:{publishableKey:t.publishableKey},iframeUrl:t.iframeURL,openfortAPIConfig:{backend:e({basePath:t.openfortURL,accessToken:t.publishableKey})},shieldConfiguration:{shieldPublishableKey:t.shieldPublishableKey,shieldEncryptionKey:t.shieldEncryptionKey,debug:t.debug},shieldUrl:t.shieldURL});return u=o,o}static async embedded(e=null,r=null,o=null,s=null){const{iframeManager:c}=this,u=i.fromStorage(this.storage);if(!u)throw new n("Must be authenticated to create a signer",a.NOT_LOGGED_IN_ERROR);const m=d.fromStorage(this.storage),g=new d(o||m?.type||"openfort",s||m?.customToken),p=this.shieldAuthentication(g,u,r),y={thirdPartyTokenType:u.thirdPartyTokenType,thirdPartyProvider:u.thirdPartyProvider,accessToken:u.token,playerID:u.player,recovery:p,chainId:e,password:r?.recoveryPassword||null},T={type:"embedded",chainId:e},b=await c.configure(y);return f.storage.save(t.SIGNER,JSON.stringify(T)),new l(b.accountType,b.address,b.chainId,b.ownerAddress).save(this.storage),new h(c,y,this.storage)}static shieldAuthentication(e,t,r){let o=null;if("openfort"===e.type)o={auth:s.OPENFORT,authProvider:t.thirdPartyProvider||void 0,token:t.token,tokenType:t.thirdPartyTokenType||void 0,encryptionSession:r?.encryptionSession||void 0},new d("openfort").save(this.storage);else if("custom"===e.type){if(!e.customToken)throw new n("Custom recovery requires a token",a.INVALID_CONFIGURATION);o={auth:s.CUSTOM,token:e.customToken},new d("custom",e.customToken).save(this.storage)}return o}}export{f as SignerManager};
|
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
|
|
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 m}from"./evm/evmProvider.js";import"./evm/types.js";import p 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 m({storage:this.storage,openfortEventEmitter:new p,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 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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"@noble/curves/secp256k1";import"@noble/hashes/utils";function t(t,{dir:n,size:r=32}={}){if(null===r)return t;const e=t.replace("0x","");if(e.length>2*r)throw new Error("Hex string is too long");return`0x${e["right"===n?"padEnd":"padStart"](2*r,"0")}`}function n(n,r={}){const{size:e}=r,i=BigInt(n);let o;if(e?o=BigInt(2)**(BigInt(e)*BigInt(8))-BigInt(1):"number"==typeof n&&(o=BigInt(Number.MAX_SAFE_INTEGER)),o&&i>o||i<0){throw new Error(`Value out of bounds: ${i}${"bigint"==typeof n?"n":""}`)}const s=`0x${i.toString(16)}`;return e?t(s,{size:e}):s}export{n as numberToHex,t as padHex};
|
package/dist/sdk/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.8.
|
|
1
|
+
const o="0.8.32";export{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.32",
|
|
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",
|
|
@@ -33,23 +33,16 @@
|
|
|
33
33
|
"registry": "https://registry.npmjs.org/"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@ethersproject/bytes": "^5.8.0",
|
|
37
36
|
"@ethersproject/hash": "^5.8.0",
|
|
38
37
|
"@ethersproject/providers": "^5.8.0",
|
|
39
|
-
"@ethersproject/signing-key": "^5.8.0",
|
|
40
|
-
"@ethersproject/transactions": "^5.8.0",
|
|
41
38
|
"@noble/curves": "^1.1.0",
|
|
42
|
-
"@openfort/shield-js": "^0.1.
|
|
43
|
-
"axios": "1.
|
|
39
|
+
"@openfort/shield-js": "^0.1.14",
|
|
40
|
+
"axios": "1.8.2",
|
|
44
41
|
"buffer": "^6.0.3",
|
|
45
|
-
"crypto-browserify": "^3.12.0",
|
|
46
42
|
"crypto-js": "^4.2.0",
|
|
47
43
|
"es6-promise": "^4.2.8",
|
|
48
44
|
"jose": "^5.2.2",
|
|
49
|
-
"
|
|
50
|
-
"path": "^0.12.7",
|
|
51
|
-
"stream-browserify": "^3.0.0",
|
|
52
|
-
"uuid": "^8.3.2"
|
|
45
|
+
"path": "^0.12.7"
|
|
53
46
|
},
|
|
54
47
|
"exports": {
|
|
55
48
|
"./package.json": "./package.json",
|
|
@@ -60,7 +53,7 @@
|
|
|
60
53
|
}
|
|
61
54
|
},
|
|
62
55
|
"devDependencies": {
|
|
63
|
-
"@babel/core": "^7.
|
|
56
|
+
"@babel/core": "^7.26.10",
|
|
64
57
|
"@openfort/openapi-clients": "0.0.0",
|
|
65
58
|
"@parcel/packager-ts": "2.12.0",
|
|
66
59
|
"@parcel/transformer-typescript-types": "2.12.0",
|
|
@@ -74,8 +67,6 @@
|
|
|
74
67
|
"@swc/jest": "^0.2.24",
|
|
75
68
|
"@types/crypto-js": "^4.2.2",
|
|
76
69
|
"@types/jest": "^29.4.3",
|
|
77
|
-
"@types/jsrsasign": "^10.5.15",
|
|
78
|
-
"@types/uuid": "^8.3.4",
|
|
79
70
|
"@typescript-eslint/eslint-plugin": "^5.57.1",
|
|
80
71
|
"@typescript-eslint/parser": "^5.57.1",
|
|
81
72
|
"buffer": "^5.5.0||^6.0.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";var e=require("../storage/istorage.js"),r=require("../crypto/key-pair.js");class t{key;constructor(e){this.key=e}static fromStorage(s){const a=s.get(e.StorageKeys.RECOVERY);if(!a)return null;const o=r.KeyPair.load(a);return o?new t(o):null}save(r){r.save(e.StorageKeys.RECOVERY,this.key?.getPrivateKey()??"")}}exports.Session=t;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";var e=require("@noble/curves/secp256k1"),r=require("@ethersproject/signing-key"),t=require("@ethersproject/bytes"),s=require("@ethersproject/transactions"),i=require("@ethersproject/hash");class a extends r.SigningKey{constructor(r=e.secp256k1.utils.randomPrivateKey()){super(r)}sign(e){return t.joinSignature(this.signDigest(i.hashMessage(t.arrayify(e))))}static load(e){return e?new a(t.arrayify(e)):null}getPublicKey(){return s.computeAddress(this.privateKey)}getPrivateKey(){return this.privateKey}}exports.KeyPair=a;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";var e=require("../storage/istorage.js");exports.SessionSigner=class{sessionKey;storage;constructor(e,s){this.sessionKey=e,this.storage=s}setEmbeddedRecovery(){return Promise.resolve()}async sign(e){return this.sessionKey.sign(e)}async logout(){this.storage.remove(e.StorageKeys.SESSION),this.storage.remove(e.StorageKeys.SIGNER)}updateAuthentication(){return Promise.resolve()}switchChain(){return Promise.resolve()}async export(){return this.sessionKey.getPrivateKey()}type(){return"session"}};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{StorageKeys as t}from"../storage/istorage.js";import{KeyPair as r}from"../crypto/key-pair.js";class e{key;constructor(t){this.key=t}static fromStorage(o){const s=o.get(t.RECOVERY);if(!s)return null;const a=r.load(s);return a?new e(a):null}save(r){r.save(t.RECOVERY,this.key?.getPrivateKey()??"")}}export{e as Session};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{secp256k1 as e}from"@noble/curves/secp256k1";import{SigningKey as r}from"@ethersproject/signing-key";import{joinSignature as t,arrayify as s}from"@ethersproject/bytes";import{computeAddress as i}from"@ethersproject/transactions";import{hashMessage as o}from"@ethersproject/hash";class n extends r{constructor(r=e.utils.randomPrivateKey()){super(r)}sign(e){return t(this.signDigest(o(s(e))))}static load(e){return e?new n(s(e)):null}getPublicKey(){return i(this.privateKey)}getPrivateKey(){return this.privateKey}}export{n as KeyPair};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{StorageKeys as e}from"../storage/istorage.js";class s{sessionKey;storage;constructor(e,s){this.sessionKey=e,this.storage=s}setEmbeddedRecovery(){return Promise.resolve()}async sign(e){return this.sessionKey.sign(e)}async logout(){this.storage.remove(e.SESSION),this.storage.remove(e.SIGNER)}updateAuthentication(){return Promise.resolve()}switchChain(){return Promise.resolve()}async export(){return this.sessionKey.getPrivateKey()}type(){return"session"}}export{s as SessionSigner};
|