@openfort/openfort-js 0.10.35 → 0.10.36-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/packages/internal/openapi-clients/dist/index.js +1 -1
- package/dist/cjs/sdk/src/api/auth.js +1 -1
- package/dist/cjs/sdk/src/api/embeddedWallet.js +1 -1
- package/dist/cjs/sdk/src/api/proxy.js +1 -1
- package/dist/cjs/sdk/src/api/user.js +1 -1
- package/dist/cjs/sdk/src/auth/authManager.js +1 -1
- package/dist/cjs/sdk/src/core/configuration/account.js +1 -1
- package/dist/cjs/sdk/src/core/configuration/authentication.js +1 -1
- package/dist/cjs/sdk/src/core/errors/authErrorCodes.js +1 -0
- package/dist/cjs/sdk/src/core/errors/internal/extractApiError.js +1 -0
- package/dist/cjs/sdk/src/core/errors/internal/extractAuthError.js +1 -0
- package/dist/cjs/sdk/src/core/errors/openfortError.js +1 -1
- package/dist/cjs/sdk/src/core/errors/sentry.js +1 -1
- package/dist/cjs/sdk/src/core/errors/withApiError.js +1 -0
- package/dist/cjs/sdk/src/core/openfort.js +1 -1
- package/dist/cjs/sdk/src/core/openfortInternal.js +1 -1
- package/dist/cjs/sdk/src/index.js +1 -1
- package/dist/cjs/sdk/src/storage/istorage.js +1 -1
- package/dist/cjs/sdk/src/storage/lazyStorage.js +1 -1
- package/dist/cjs/sdk/src/types/types.js +1 -1
- package/dist/cjs/sdk/src/utils/crypto.js +1 -1
- package/dist/cjs/sdk/src/version.js +1 -1
- package/dist/cjs/sdk/src/wallets/embedded.js +1 -1
- package/dist/cjs/sdk/src/wallets/evm/estimateGas.js +1 -1
- package/dist/cjs/sdk/src/wallets/evm/getAssets.js +1 -1
- package/dist/cjs/sdk/src/wallets/evm/getCallsStatus.js +1 -1
- package/dist/cjs/sdk/src/wallets/evm/registerSession.js +1 -1
- package/dist/cjs/sdk/src/wallets/evm/revokeSession.js +1 -1
- package/dist/cjs/sdk/src/wallets/evm/sendCallSync.js +1 -1
- package/dist/cjs/sdk/src/wallets/iframeManager.js +1 -1
- package/dist/index.d.ts +7323 -2893
- package/dist/packages/internal/openapi-clients/dist/index.js +1 -1
- package/dist/sdk/src/api/auth.js +1 -1
- package/dist/sdk/src/api/embeddedWallet.js +1 -1
- package/dist/sdk/src/api/proxy.js +1 -1
- package/dist/sdk/src/api/user.js +1 -1
- package/dist/sdk/src/auth/authManager.js +1 -1
- package/dist/sdk/src/core/configuration/account.js +1 -1
- package/dist/sdk/src/core/configuration/authentication.js +1 -1
- package/dist/sdk/src/core/errors/authErrorCodes.js +1 -0
- package/dist/sdk/src/core/errors/internal/extractApiError.js +1 -0
- package/dist/sdk/src/core/errors/internal/extractAuthError.js +1 -0
- package/dist/sdk/src/core/errors/openfortError.js +1 -1
- package/dist/sdk/src/core/errors/sentry.js +1 -1
- package/dist/sdk/src/core/errors/withApiError.js +1 -0
- package/dist/sdk/src/core/openfort.js +1 -1
- package/dist/sdk/src/core/openfortInternal.js +1 -1
- package/dist/sdk/src/index.js +1 -1
- package/dist/sdk/src/storage/istorage.js +1 -1
- package/dist/sdk/src/storage/lazyStorage.js +1 -1
- package/dist/sdk/src/types/types.js +1 -1
- package/dist/sdk/src/utils/crypto.js +1 -1
- package/dist/sdk/src/version.js +1 -1
- package/dist/sdk/src/wallets/embedded.js +1 -1
- package/dist/sdk/src/wallets/evm/estimateGas.js +1 -1
- package/dist/sdk/src/wallets/evm/getAssets.js +1 -1
- package/dist/sdk/src/wallets/evm/getCallsStatus.js +1 -1
- package/dist/sdk/src/wallets/evm/registerSession.js +1 -1
- package/dist/sdk/src/wallets/evm/revokeSession.js +1 -1
- package/dist/sdk/src/wallets/evm/sendCallSync.js +1 -1
- package/dist/sdk/src/wallets/iframeManager.js +1 -1
- package/package.json +8 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Authentication as t}from"./configuration/authentication.js";import{
|
|
1
|
+
import{Authentication as t}from"./configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as e}from"./errors/authErrorCodes.js";import{RequestError as r,ConfigurationError as o,AuthenticationError as i,SessionError as s}from"./errors/openfortError.js";import{TokenType as a,OpenfortEvents as n}from"../types/types.js";import"human-id";import{SDKConfiguration as h}from"./config/config.js";import"../storage/istorage.js";import"axios";import"./errors/sentry.js";import{debugLog as d}from"../utils/debug.js";import"eventemitter3";import"../wallets/evm/JsonRpcError.js";import"@ethersproject/keccak256";import"../wallets/evm/types.js";import"../wallets/evm/provider/eip6963.js";import"../wallets/messaging/browserMessenger/backwardCompatibility.js";import"../wallets/types.js";import{singlePromise as c}from"../utils/promiseUtils.js";class g{storage;authManager;eventEmitter;constructor(t,e,r){this.storage=t,this.authManager=e,this.eventEmitter=r}async getThirdPartyAuthToken(){const s=h.getInstance();if(!s?.thirdPartyAuth)throw new r("No third party configuration found");const{getAccessToken:n,provider:d}=s.thirdPartyAuth;if(!n||!d)throw new o("Third party is not configured. Please configure getAccessToken and thirdPartyAuthProvider in your Openfort instance");const c=await n();if(!c)throw new i(e.INVALID_TOKEN,"Could not get access token");let g=(await t.fromStorage(this.storage))?.userId;if(!g){g=(await this.authManager.authenticateThirdParty(d,c,a.ID_TOKEN)).userId}return new t("third_party",c,g,d,a.ID_TOKEN).save(this.storage),c}async getAccessToken(){if(h.getInstance()?.thirdPartyAuth)return this.getThirdPartyAuthToken();return(await t.fromStorage(this.storage))?.token??null}async validateAndRefreshToken(o){return c(async()=>{if(h.getInstance()?.thirdPartyAuth)return void await this.getThirdPartyAuthToken();const i=await t.fromStorage(this.storage);if(!i)throw new s(e.NOT_LOGGED_IN,"Must be logged in to validate and refresh token");let a;d("validating credentials...");try{a=await this.authManager.validateCredentials(i,o)}catch(e){throw t.clear(this.storage),this.eventEmitter.emit(n.ON_LOGOUT),e}if(!a.user?.id)throw new r("No user found in credentials");a.token!==i.token&&(d("tokens refreshed"),new t("session",a.token,a.user.id).save(this.storage))},"openfort.validateAndRefreshToken")}}export{g as OpenfortInternal};
|
package/dist/sdk/src/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Openfort as r}from"./core/openfort.js";export{AuthApi}from"./api/auth.js";export{EmbeddedWalletApi}from"./api/embeddedWallet.js";export{ProxyApi}from"./api/proxy.js";export{UserApi}from"./api/user.js";export{
|
|
1
|
+
import{Openfort as r}from"./core/openfort.js";export{AuthApi}from"./api/auth.js";export{EmbeddedWalletApi}from"./api/embeddedWallet.js";export{ProxyApi}from"./api/proxy.js";export{UserApi}from"./api/user.js";export{OPENFORT_AUTH_ERROR_CODES,OPENFORT_ERROR_CODES}from"./core/errors/authErrorCodes.js";export{AuthenticationError,AuthorizationError,ConfigurationError,OAuthError,OTPError,OpenfortError,RecoveryError,RequestError,SessionError,SignerError,UserError}from"./core/errors/openfortError.js";export{OpenfortConfiguration,SDKConfiguration,ShieldConfiguration}from"./core/config/config.js";export{OpenfortInternal}from"./core/openfortInternal.js";export{prepareAndSignAuthorization,serializeSignedAuthorization,signAuthorization}from"./utils/authorization.js";export{MissingProjectEntropyError,MissingRecoveryPasswordError,NotConfiguredError,OTPRequiredError,WrongRecoveryPasswordError}from"./wallets/iframeManager.js";export{AccountTypeEnum,AuthActionRequiredActions,AuthType,BasicAuthProvider,ChainTypeEnum,EmbeddedState,OAuthProvider,OpenfortEvents,RecoveryMethod,ThirdPartyAuthProvider as ThirdPartyOAuthProvider,TokenType}from"./types/types.js";const o=r.getEventEmitter();export{r as Openfort,o as openfortEvents};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var o;!function(o){o.AUTHENTICATION="openfort.authentication",o.CONFIGURATION="openfort.configuration",o.ACCOUNT="openfort.account",o.TEST="openfort.test",o.SESSION="openfort.session"
|
|
1
|
+
var o;!function(o){o.AUTHENTICATION="openfort.authentication",o.CONFIGURATION="openfort.configuration",o.ACCOUNT="openfort.account",o.TEST="openfort.test",o.SESSION="openfort.session"}(o||(o={}));export{o as StorageKeys};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ConfigurationError as e}from"../core/errors/openfortError.js";import{StorageImplementation as t}from"./storage.js";class r{realStorage=null;customStorage;constructor(e){this.customStorage=e}getRealStorage(){if(!this.realStorage)if(this.customStorage)this.realStorage=this.customStorage;else{if("undefined"==typeof window||"undefined"==typeof localStorage)throw new e("Storage not available. Please provide custom storage or use in browser environment.");this.realStorage=new t(localStorage)}return this.realStorage}async get(e){return this.getRealStorage().get(e)}save(e,t){this.getRealStorage().save(e,t)}remove(e){this.getRealStorage().remove(e)}flush(){this.getRealStorage().flush()}}export{r as LazyStorage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var E,A,e,n,
|
|
1
|
+
var E,A,e,n,T,t,o,O,_,C,a,N,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.ON_AUTH_INIT="onAuthInit",E.ON_AUTH_SUCCESS="onAuthSuccess",E.ON_OTP_REQUEST="onOtpRequest",E.ON_OTP_FAILURE="onOtpFailure",E.ON_AUTH_FAILURE="onAuthFailure",E.ON_LOGOUT="onLogout",E.ON_SWITCH_ACCOUNT="onSwitchAccount",E.ON_SIGNED_MESSAGE="onSignedMessage",E.ON_EMBEDDED_WALLET_CREATED="onEmbeddedWalletCreated",E.ON_EMBEDDED_WALLET_RECOVERED="onEmbeddedWalletRecovered"}(A||(A={})),function(E){E.PASSWORD="password",E.AUTOMATIC="automatic",E.PASSKEY="passkey"}(e||(e={})),function(E){E.ERC6551V1="ERC6551V1",E.UPGRADEABLE_V5="UpgradeableV5",E.UPGRADEABLE_V4="UpgradeableV4",E.UPGRADEABLE_V6="UpgradeableV6",E.ZKSYNC_UPGRADEABLE_V1="ZKSyncUpgradeableV1",E.ZKSYNC_UPGRADEABLE_V2="ZKSyncUpgradeableV2",E.SIMPLE="Simple",E.CALIBUR="Calibur"}(n||(n={})),function(E){E.OPENFORT="openfort",E.THIRD_PARTY="thirdParty"}(T||(T={})),function(E){E.ID_TOKEN="idToken",E.CUSTOM_TOKEN="customToken"}(t||(t={})),function(E){E.ACCELBYTE="accelbyte",E.FIREBASE="firebase",E.BETTER_AUTH="better-auth",E.LOOTLOCKER="lootlocker",E.PLAYFAB="playfab",E.SUPABASE="supabase",E.CUSTOM="custom",E.OIDC="oidc"}(o||(o={})),function(E){E.EMAIL="email",E.WALLET="wallet"}(O||(O={})),function(E){E.GOOGLE="google",E.TWITTER="twitter",E.APPLE="apple",E.FACEBOOK="facebook",E.DISCORD="discord",E.EPIC_GAMES="epic_games",E.LINE="line"}(_||(_={})),function(E){E.ACTION_VERIFY_EMAIL="verify_email"}(C||(C={})),function(E){E.EOA="Externally Owned Account",E.SMART_ACCOUNT="Smart Account",E.DELEGATED_ACCOUNT="Delegated Account"}(a||(a={})),function(E){E.EVM="EVM",E.SVM="SVM"}(N||(N={})),function(E){E.ASC="asc",E.DESC="desc"}(c||(c={}));export{n as AccountType,a as AccountTypeEnum,C as AuthActionRequiredActions,T as AuthType,O as BasicAuthProvider,N as ChainTypeEnum,E as EmbeddedState,_ as OAuthProvider,A as OpenfortEvents,e as RecoveryMethod,o as ThirdPartyAuthProvider,t as TokenType};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function t(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(16);return crypto.getRandomValues(t),t[6]=15&t[6]|64,t[8]=63&t[8]|128,[...t].map((t,
|
|
1
|
+
function t(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(16);return crypto.getRandomValues(t),t[6]=15&t[6]|64,t[8]=63&t[8]|128,[...t].map((t,n)=>{const r=t.toString(16).padStart(2,"0");return[4,6,8,10].includes(n)?`-${r}`:r}).join("")}function n(t){return`0x${t.toString(16)}`}function r(t){let n="";const r=t.startsWith("0x")?t.slice(2):t;for(let t=0;t<r.length;t+=2){const o=parseInt(r.substring(t,t+2),16);0!==o&&(n+=String.fromCharCode(o))}return n}function o(t){}export{r as hexToString,n as numberToHex,t as randomUUID,o as setCryptoDigestOverride};
|
package/dist/sdk/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.10.
|
|
1
|
+
const o="0.10.36-beta.1",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Authentication as e}from"../core/configuration/authentication.js";import{PasskeyHandler as t}from"../core/configuration/passkey.js";import{
|
|
1
|
+
import{Authentication as e}from"../core/configuration/authentication.js";import{PasskeyHandler as t}from"../core/configuration/passkey.js";import{OPENFORT_AUTH_ERROR_CODES as a}from"../core/errors/authErrorCodes.js";import{SessionError as r,ConfigurationError as o}from"../core/errors/openfortError.js";import{withApiError as s}from"../core/errors/withApiError.js";import{OpenfortEvents as n,AccountTypeEnum as i}from"../types/types.js";import{SDKConfiguration as c}from"../core/config/config.js";import{Account as d}from"../core/configuration/account.js";import{StorageKeys as y}from"../storage/istorage.js";import"eventemitter3";import"./evm/JsonRpcError.js";import"@ethersproject/keccak256";import"./evm/types.js";import"./evm/provider/eip6963.js";import"../core/errors/sentry.js";import"./messaging/browserMessenger/backwardCompatibility.js";import"./types.js";class p{iframeManager;storage;backendApiClients;passkeyHandler;eventEmitter;constructor(e,t,a,r,o){this.iframeManager=e,this.storage=t,this.backendApiClients=a,this.passkeyHandler=r,this.eventEmitter=o}async createPasskey(e){const a=await this.passkeyHandler.createPasskey({id:t.randomPasskeyName(),displayName:"Openfort - Embedded Wallet",seed:e});return{id:a.id,key:a.key}}async configure(t){const i=await e.fromStorage(this.storage);if(!i)throw new r(a.NOT_LOGGED_IN,"No access token found");const y=c.getInstance();if(!y)throw new o("Configuration not found");const p=await d.fromStorage(this.storage);let h;if(p){const e={account:p.id,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},..."passkey"===p.recoveryMethod&&{passkey:{id:p.recoveryMethodDetails?.passkeyId,env:p.recoveryMethodDetails?.passkeyEnv,key:await t.getPasskeyKeyFn(p.recoveryMethodDetails?.passkeyId)}}}}},a=await this.iframeManager.recover(e);h=a.account}else{const e=await this.backendApiClients.accountsApi.getAccountsV2({user:i.userId,accountType:t.accountType,chainType:t.chainType},{headers:i.thirdPartyProvider?{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":y.baseConfiguration.publishableKey}});if(0===e.data.data.length){const e=t.entropy?.passkey?await this.createPasskey(i.userId):void 0,a={accountType:t.accountType,chainType:t.chainType,chainId:t.chainId,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},...t.entropy.passkey&&{passkey:e}}}},r=await this.iframeManager.create(a);h=r.account}else{const a=e.data.data,r=a.find(e=>e.chainId===t.chainId),o=r||a[0],s={account:o.id,...t.entropy&&{entropy:{...t.entropy.recoveryPassword&&{recoveryPassword:t.entropy.recoveryPassword},...t.entropy.encryptionSession&&{encryptionSession:t.entropy.encryptionSession},..."passkey"===o.recoveryMethod&&{passkey:{id:o.recoveryMethodDetails?.passkeyId,env:o.recoveryMethodDetails?.passkeyEnv,key:await t.getPasskeyKeyFn(o.recoveryMethodDetails?.passkeyId)}}}}},n=await this.iframeManager.recover(s);if(h=n.account,!r){const e=await this.iframeManager.switchChain(t.chainId);h=e.account}}}return s(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:h},{headers:i.thirdPartyProvider?{authorization:`Bearer ${y.baseConfiguration.publishableKey}`,"x-player-token":i.token,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":y.baseConfiguration.publishableKey}}),t=new d({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:d.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(n.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"configure"})}async sign(e,t,a,r){const o=await this.iframeManager.sign(e,t,a,r);return this.eventEmitter.emit(n.ON_SIGNED_MESSAGE,{message:e,signature:o}),o}async export(){return await this.iframeManager.export()}async switchChain({chainId:e}){const t=await d.fromStorage(this.storage);if(t?.accountType===i.EOA)new d({...t,chainId:e}).save(this.storage);else{const a=await this.iframeManager.switchChain(e);new d({...t,id:a.account,chainId:e}).save(this.storage)}}async create(t){const i=await this.iframeManager.create(t),y=await e.fromStorage(this.storage);if(!y)throw new r(a.NOT_LOGGED_IN,"No access token found");const p=c.getInstance();if(!p)throw new o("Configuration not found");return s(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:i.account},{headers:y.thirdPartyProvider?{authorization:`Bearer ${p.baseConfiguration.publishableKey}`,"x-player-token":y.token,"x-auth-provider":y.thirdPartyProvider,"x-token-type":y.thirdPartyTokenType}:{authorization:`Bearer ${y.token}`,"x-project-key":p.baseConfiguration.publishableKey}}),t=new d({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,implementationAddress:e.data.smartAccount?.implementationAddress,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:d.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(n.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"create"})}async recover(t){const i=await this.iframeManager.recover(t),y=await e.fromStorage(this.storage);if(!y)throw new r(a.NOT_LOGGED_IN,"No access token found");const p=c.getInstance();if(!p)throw new o("Configuration not found");return s(async()=>{const e=await this.backendApiClients.accountsApi.getAccountV2({id:i.account},{headers:y.thirdPartyProvider?{authorization:`Bearer ${p.baseConfiguration.publishableKey}`,"x-player-token":y.token,"x-auth-provider":y.thirdPartyProvider,"x-token-type":y.thirdPartyTokenType}:{authorization:`Bearer ${y.token}`,"x-project-key":p.baseConfiguration.publishableKey}}),t=new d({user:e.data.user,chainType:e.data.chainType,id:e.data.id,address:e.data.address,ownerAddress:e.data.ownerAddress,accountType:e.data.accountType,createdAt:e.data.createdAt,implementationAddress:e.data.smartAccount?.implementationAddress,implementationType:e.data.smartAccount?.implementationType,chainId:e.data.chainId,salt:e.data.smartAccount?.salt,factoryAddress:e.data.smartAccount?.factoryAddress,recoveryMethod:d.parseRecoveryMethod(e.data.recoveryMethod),recoveryMethodDetails:e.data.recoveryMethodDetails});return t.save(this.storage),this.eventEmitter.emit(n.ON_SWITCH_ACCOUNT,e.data.address),t},{context:"recover"})}async setRecoveryMethod({recoveryMethod:e,recoveryPassword:t,encryptionSession:a,passkeyInfo:r}){await this.iframeManager.setRecoveryMethod(e,t,a,r?.passkeyKey,r?.passkeyId)}async disconnect(){await this.iframeManager.disconnect(),this.storage.remove(y.ACCOUNT)}}export{p as EmbeddedSigner};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{withApiError as t}from"../../core/errors/withApiError.js";import{JsonRpcError as a,RpcErrorCode as e}from"./JsonRpcError.js";const r=async({params:r,account:n,authentication:o,backendClient:i,policyId:c})=>{const s=await(async(r,n,o,i,c)=>{const s=r.map(t=>{if(!t.to)throw new a(e.INVALID_PARAMS,'eth_estimateGas requires a "to" field');return{to:String(t.to),data:t.data?String(t.data):void 0,value:t.value?String(t.value):void 0}});return t(async()=>(await n.transactionIntentsApi.estimateTransactionIntentCost({createTransactionIntentRequest:{policy:c,chainId:o.chainId,interactions:s}},{headers:i.thirdPartyProvider?{authorization:`Bearer ${n.config.backend.accessToken}`,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":String(n.config.backend.accessToken)}})).data,{context:"operation"})})(r,i,n,o,c).catch(t=>{throw new a(e.TRANSACTION_REJECTED,t.message)});return s.estimatedTXGas};export{r as estimateGas};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{withApiError as e}from"../../core/errors/withApiError.js";import{JsonRpcError as t,RpcErrorCode as r}from"./JsonRpcError.js";const a=async({params:a,account:o,authentication:s,backendClient:n})=>{const i=await(async(t,r,a,o)=>{const s=o?.chainFilter?.map(e=>Number.parseInt(e,16));return e(async()=>(await t.rpcApi.handleRpcRequest({jsonRpcRequest:{method:"wallet_getAssets",params:{account:r.address,chainFilter:s,assetFilter:o?.assetFilter,assetTypeFilter:o?.assetTypeFilter},id:1,jsonrpc:"2.0"}},{headers:a.thirdPartyProvider?{authorization:`Bearer ${t.config.backend.accessToken}`,"x-auth-provider":a.thirdPartyProvider,"x-token-type":a.thirdPartyTokenType}:{authorization:`Bearer ${a.token}`,"x-project-key":String(t.config.backend.accessToken)}})).data,{context:"operation"})})(n,o,s,a).catch(e=>{throw new t(r.INTERNAL_ERROR,e.message)});return i.result};export{a as getAssets};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{withApiError as e}from"../../core/errors/withApiError.js";import{JsonRpcError as s,RpcErrorCode as t}from"./JsonRpcError.js";const r=async({params:r,authentication:a,backendClient:o})=>{const n=await(async(s,t,r)=>e(async()=>(await t.transactionIntentsApi.getTransactionIntent({id:s},{headers:r.thirdPartyProvider?{authorization:`Bearer ${t.config.backend.accessToken}`,"x-auth-provider":r.thirdPartyProvider,"x-token-type":r.thirdPartyTokenType}:{authorization:`Bearer ${r.token}`,"x-project-key":String(t.config.backend.accessToken)}})).data,{context:"operation"}))(r[0],o,a).catch(e=>{throw new s(t.TRANSACTION_REJECTED,e.message)});return{status:n.response?"CONFIRMED":"PENDING",receipts:n.response?[{status:0===n.response.status?"reverted":"success",logs:n.response.logs?.map(e=>({address:e.address,data:e.data,topics:e.topics}))||[],blockHash:n.response.transactionHash||"",blockNumber:BigInt(n.response.blockNumber||0),gasUsed:BigInt(n.response.gasUsed||0),transactionHash:n.response.transactionHash||""}]:void 0}};export{r as getCallStatus};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{withApiError as t}from"../../core/errors/withApiError.js";import{AccountType as e}from"../../types/types.js";import{JsonRpcError as i,RpcErrorCode as n}from"./JsonRpcError.js";function a(t){return{data:(()=>{if("token-allowance"===t.type)throw new i(n.INVALID_PARAMS,"token-allowance policy is not supported with this account implementation.");if("gas-limit"===t.type)throw new i(n.INVALID_PARAMS,"gas-limit policy is not supported with this account implementation.");if("rate-limit"===t.type)throw new i(n.INVALID_PARAMS,"rate-limit policy is not supported with this account implementation.");return t.data})(),type:t.type.custom}}function s(t){if("native-token-transfer"===t.type)throw new i(n.INVALID_PARAMS,"native-token-transfer permission is not supported with this account implementation.");if("rate-limit"===t.type)throw new i(n.INVALID_PARAMS,"rate-limit permission is not supported with this account implementation.");if("gas-limit"===t.type)throw new i(n.INVALID_PARAMS,"gas-limit permission is not supported with this account implementation.");return{...t,policies:t?.policies?.map(a),required:t.required??!1,type:"string"==typeof t.type?t.type:t.type.custom}}function o(t){return{expiry:t.validUntil?Number(t.validUntil):0,grantedPermissions:t.whitelist?t.whitelist.map(e=>({type:"contract-call",data:{address:e,calls:[]},policies:[{data:{limit:t.limit},type:{custom:"usage-limit"}}]})):[],permissionsContext:t.id}}const r=async({params:a,signer:r,account:c,authentication:p,backendClient:l,policyId:d})=>{const m=await(async(e,a,o,r,c)=>{const p=e[0],l=Math.floor(Date.now()/1e3),d=Math.floor(new Date(Date.now()+1e3*p.expiry).getTime()/1e3),m=p.permissions.map(s),y=m.filter(t=>"contract-call"===t.type||"erc20-token-transfer"===t.type||"erc721-token-transfer"===t.type||"erc1155-token-transfer"===t.type).map(t=>t.data.address);let u,h=m.find(t=>"call-limit"===t.type)?.data;if(h=m[0]?.policies?.find(t=>"call-limit"===t.type)?.data?.limit,"signer"in p&&p.signer){if("keys"===p.signer.type)throw new i(n.INVALID_PARAMS,"Multi-key signers are not supported for session creation");"key"!==p.signer.type&&"account"!==p.signer.type||(u=p.signer.data.id)}else"account"in p&&p.account&&(u=p.account);if(!u)throw new i(n.INVALID_PARAMS,"Failed to request permissions - missing session address");const w=((t,e,i,n,a,s=!1,o,r,c,p)=>{const l={address:t,chainId:e,validAfter:i,validUntil:n,optimistic:s,whitelist:o,player:r,account:p};return a&&(l.policy=a),c&&(l.limit=c),l})(u,o.chainId,l,d,c,!1,y,r.userId,h,o.id);return t(async()=>(await a.sessionsApi.createSession({createSessionRequest:w},{headers:r.thirdPartyProvider?{authorization:`Bearer ${a.config.backend.accessToken}`,"x-auth-provider":r.thirdPartyProvider,"x-token-type":r.thirdPartyTokenType}:{authorization:`Bearer ${r.token}`,"x-project-key":String(a.config.backend.accessToken)}})).data,{context:"operation"})})(a,l,c,p,d).catch(t=>{throw new i(n.TRANSACTION_REJECTED,t.message)});if(m?.nextAction?.payload?.signableHash){let a;a=[300,531050104,324,50104,2741,11124].includes(c.chainId)||c.implementationType&&[e.CALIBUR].includes(c.implementationType)?await r.sign(m.nextAction.payload.signableHash,!1,!1):await r.sign(m.nextAction.payload.signableHash);return o(await t(async()=>(await l.sessionsApi.signatureSession({id:m.id,signatureRequest:{signature:a}})).data,{context:"operation"}).catch(t=>{throw new i(n.TRANSACTION_REJECTED,t.message)}))}if(!1===m.isActive)throw new i(n.TRANSACTION_REJECTED,"Failed to grant permissions");return o(m)};export{r as registerSession};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{withApiError as e}from"../../core/errors/withApiError.js";import{AccountType as t}from"../../types/types.js";import{JsonRpcError as n,RpcErrorCode as a}from"./JsonRpcError.js";const i=async({params:i,signer:r,account:s,authentication:o,backendClient:c,policyId:d})=>{const p=i[0];if(!p.permissionContext)return await r.disconnect(),{};const h=await(async(t,n,a,i,r)=>{const s=((e,t,n,a,i)=>{const r={address:e,chainId:t,player:n,account:i};return a&&(r.policy=a),r})(t.permissionContext,a.chainId,i.userId,r,a.id);return e(async()=>(await n.sessionsApi.revokeSession({revokeSessionRequest:s},{headers:i.thirdPartyProvider?{authorization:`Bearer ${n.config.backend.accessToken}`,"x-auth-provider":i.thirdPartyProvider,"x-token-type":i.thirdPartyTokenType}:{authorization:`Bearer ${i.token}`,"x-project-key":String(n.config.backend.accessToken)}})).data,{context:"operation"})})(p,c,s,o,d).catch(e=>{throw new n(a.TRANSACTION_REJECTED,e.message)});if(h?.nextAction?.payload?.signableHash){let e;e=[300,531050104,324,50104,2741,11124].includes(s.chainId)||s.implementationType&&[t.CALIBUR].includes(s.implementationType)?await r.sign(h.nextAction.payload.signableHash,!1,!1):await r.sign(h.nextAction.payload.signableHash);return(await c.sessionsApi.signatureSession({id:h.id,signatureRequest:{signature:e}}).catch(e=>{throw new n(a.TRANSACTION_REJECTED,e.message)})).data}return h};export{i as revokeSession};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{withApiError as t}from"../../core/errors/withApiError.js";import{AccountTypeEnum as e,AccountType as a}from"../../types/types.js";import{prepareAndSignAuthorization as n,serializeSignedAuthorization as o}from"../../utils/authorization.js";import{JsonRpcError as r,RpcErrorCode as s}from"./JsonRpcError.js";const i=t=>{const e=t?.logs?.[0];return{blockHash:e?.blockHash,blockNumber:t?.blockNumber?.toString(),contractAddress:void 0,cumulativeGasUsed:t?.gasUsed,effectiveGasPrice:t?.gasFee,from:void 0,gasUsed:t?.gasUsed,logs:t?.logs||[],logsBloom:void 0,status:1===t?.status?"success":0===t?.status?"reverted":void 0,to:t?.to,transactionHash:t?.transactionHash,transactionIndex:e?.transactionIndex,type:"eip1559",blobGasPrice:void 0,blobGasUsed:void 0,root:void 0}};async function c(t,e){try{const a=await t.getCode(e);return"0x"!==a&&a.length>2}catch{return!1}}const d=async({params:d,signer:p,account:l,authentication:u,backendClient:h,rpcProvider:g,policyId:T})=>{const A=d[0]?.capabilities?.paymasterService?.policy??T;let m;if(l.accountType===e.DELEGATED_ACCOUNT){const[t,e]=await Promise.all([c(g,l.address),g.getTransactionCount(l.address)]);if(!t){const t=await n({signer:p,accountAddress:l.address,contractAddress:l.implementationAddress,chainId:l.chainId,nonce:e});m=o(t)}}const w=await(async(e,a,n,o,i,c)=>{const d=e.map(t=>{if(!t.to)throw new r(s.INVALID_PARAMS,'wallet_sendCalls requires a "to" field');return{to:String(t.to),data:t.data?String(t.data):void 0,value:t.value?String(t.value):void 0}});return t(async()=>(await a.transactionIntentsApi.createTransactionIntent({createTransactionIntentRequest:{account:n.id,policy:i,signedAuthorization:c,chainId:n.chainId,interactions:d}},{headers:o.thirdPartyProvider?{authorization:`Bearer ${a.config.backend.accessToken}`,"x-auth-provider":o.thirdPartyProvider,"x-token-type":o.thirdPartyTokenType}:{authorization:`Bearer ${o.token}`,"x-project-key":String(a.config.backend.accessToken)}})).data,{context:"operation"})})(d,h,l,u,A,m).catch(t=>{throw new r(s.TRANSACTION_REJECTED,t.message)});if(w.response?.error.reason)throw new r(s.TRANSACTION_REJECTED,w.response?.error.reason);if(w?.nextAction?.payload?.signableHash){let e;e=[300,531050104,324,50104,2741,11124].includes(l.chainId)||l.implementationType&&[a.CALIBUR].includes(l.implementationType)?await p.sign(w.nextAction.payload.signableHash,!1,!1):await p.sign(w.nextAction.payload.signableHash);const n=await t(async()=>await h.transactionIntentsApi.signature({id:w.id,signatureRequest:{signature:e}}),{context:"operation"}).catch(t=>{throw new r(s.TRANSACTION_REJECTED,t.message)});if(0===n.data.response?.status)throw new r(s.TRANSACTION_REJECTED,n.data.response?.error.reason);if(!n.data.response)throw new r(s.TRANSACTION_REJECTED,"No transaction response received");return{id:w.id,receipt:i(n.data.response)}}if(!w.response)throw new r(s.TRANSACTION_REJECTED,"No transaction response received");return{id:w.id,receipt:i(w.response)}};export{d as sendCallsSync};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Account as e}from"../core/configuration/account.js";import{Authentication as i}from"../core/configuration/authentication.js";import{OpenfortError as t,OpenfortErrorType as n}from"../core/errors/openfortError.js";import{sentry as r}from"../core/errors/sentry.js";import{StorageKeys as o}from"../storage/istorage.js";import{randomUUID as s}from"../utils/crypto.js";import{debugLog as a}from"../utils/debug.js";import{ReactNativeMessenger as d}from"./messaging/ReactNativeMessenger.js";import c from"./messaging/browserMessenger/connect.js";import"./messaging/browserMessenger/backwardCompatibility.js";import{isErrorResponse as h,NOT_CONFIGURED_ERROR as u,MISSING_USER_ENTROPY_ERROR as l,MISSING_PROJECT_ENTROPY_ERROR as y,INCORRECT_USER_ENTROPY_ERROR as f,MISSING_PASSKEY_ERROR as g,INCORRECT_PASSKEY_ERROR as p,OTP_REQUIRED_ERROR as m,ShieldAuthType as w,Event as C,SignRequest as v,SwitchChainRequest as I,ExportPrivateKeyRequest as k,SetRecoveryMethodRequest as P,GetCurrentDeviceRequest as E,UpdateAuthenticationRequest as R}from"./types.js";class T extends Error{constructor(){super("This embedded signer requires a password to be recovered")}}class b extends Error{constructor(){super("Wrong recovery passkey for this embedded signer")}}class N extends Error{constructor(){super("MissingProjectEntropyError")}}class A extends Error{constructor(){super("Wrong recovery password for this embedded signer")}}class S extends Error{constructor(){super("Not configured")}}class U extends Error{constructor(){super("OTP required")}}class O{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;hasFailed=!1;constructor(e,i,r){if(!e)throw new t("Configuration is required for IframeManager",n.INVALID_CONFIGURATION);if(!i)throw new t("Storage is required for IframeManager",n.INVALID_CONFIGURATION);if(!r)throw new t("Messenger is required for IframeManager",n.INVALID_CONFIGURATION);this.sdkConfiguration=e,this.storage=i,this.messenger=r}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new t("Failed to establish iFrame connection: Previous connection attempt failed",n.INTERNAL_ERROR);if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){a("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:a}),this.connection=c({messenger:this.messenger,timeout:1e4,log:a});try{this.remote=await this.connection.promise,a("IframeManager connection established")}catch(e){const i=e;throw r.captureException(i),this.destroy(),a("Failed to establish connection:",i),new t(`Failed to establish iFrame connection: ${i.cause||i.message}`,n.INTERNAL_ERROR,e)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new t("Failed to establish connection",n.INTERNAL_ERROR);return this.remote}handleError(e){if(h(e)){if(e.error===u)throw this.storage.remove(o.ACCOUNT),new S;if(e.error===l)throw this.storage.remove(o.ACCOUNT),new T;if(e.error===y)throw this.storage.remove(o.ACCOUNT),new N;if(e.error===f)throw new A;if(e.error===g)throw this.storage.remove(o.ACCOUNT),new T;if(e.error===p)throw new b;if(e.error===m)throw new U;throw this.storage.remove(o.ACCOUNT),new t(`Unknown error: ${e.error}`,n.INTERNAL_ERROR)}throw e}async buildRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new t("Must be authenticated to create a signer",n.NOT_LOGGED_IN_ERROR);const r={auth:w.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:r,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new t("Must be authenticated to create a signer",n.NOT_LOGGED_IN_ERROR);const r={auth:w.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.player,recovery:r,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),t=await this.buildIFrameRequestConfiguration();t.chainId=e.chainId??null,t.password=e?.entropy?.recoveryPassword??null,t.recovery={...t.recovery,encryptionSession:e?.entropy?.encryptionSession},t.passkey=e?.entropy?.passkey??null;const n={uuid:s(),action:C.CREATE,recovery:t.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:t.accessToken,playerID:t.playerID,thirdPartyProvider:t.thirdPartyProvider,thirdPartyTokenType:t.thirdPartyTokenType,encryptionKey:t.password,encryptionSession:t.recovery?.encryptionSession??null,passkey:t.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},r=await i.create(n);return h(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const t=await e.fromStorage(this.storage),n=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=t?.chainId??null,r.password=i?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:i?.entropy?.encryptionSession},r.passkey=i?.entropy?.passkey??null;const o={uuid:s(),action:C.RECOVER,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},a=await n.recover(o);return h(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined"),a}async sign(e,i,t,n){a("[iframe] ensureConnection");const r=await this.ensureConnection(),o=new v(s(),e,await this.buildRequestConfiguration(),i,t,n);a("[iframe] done ensureConnection");const d=await r.sign(o);return a("[iframe] response",d),h(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined"),d.signature}async switchChain(e){const i=await this.ensureConnection(),t=new I(s(),e,await this.buildRequestConfiguration()),n=await i.switchChain(t);return h(n)&&this.handleError(n),n}async export(){const e=await this.ensureConnection(),i=new k(s(),await this.buildRequestConfiguration()),t=await e.export(i);return h(t)&&this.handleError(t),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",t.version??"undefined"),t.key}async setRecoveryMethod(e,i,t,n,r){const o=await this.ensureConnection(),a=new P(s(),e,await this.buildRequestConfiguration(),i,t,n,r),d=await o.setRecoveryMethod(a);h(d)&&this.handleError(d),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",d.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),t=new E(s(),e);try{const e=await i.getCurrentDevice(t);return h(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof S)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void a("IframeManager not loaded, skipping authentication update");const e=await i.fromStorage(this.storage);if(!e)return void a("No authentication found, skipping update");const t=new R(s(),e.token);a("Updating authentication in iframe with token");const n=await this.remote.updateAuthentication(t);h(n)&&this.handleError(n)}async disconnect(){const e=await this.ensureConnection(),i={uuid:s()};await e.logout(i)}async onMessage(e){a("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof d?(this.isInitialized||this.connection?a(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(a("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{a("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),a("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):a("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}}export{O as IframeManager,N as MissingProjectEntropyError,T as MissingRecoveryPasswordError,S as NotConfiguredError,U as OTPRequiredError,A as WrongRecoveryPasswordError};
|
|
1
|
+
import{Account as e}from"../core/configuration/account.js";import{Authentication as i}from"../core/configuration/authentication.js";import{OPENFORT_AUTH_ERROR_CODES as t}from"../core/errors/authErrorCodes.js";import{RecoveryError as n,SignerError as r,OpenfortError as o,ConfigurationError as s,SessionError as a}from"../core/errors/openfortError.js";import{sentry as d}from"../core/errors/sentry.js";import{StorageKeys as c}from"../storage/istorage.js";import{randomUUID as h}from"../utils/crypto.js";import{debugLog as u}from"../utils/debug.js";import{ReactNativeMessenger as l}from"./messaging/ReactNativeMessenger.js";import y from"./messaging/browserMessenger/connect.js";import"./messaging/browserMessenger/backwardCompatibility.js";import{isErrorResponse as f,NOT_CONFIGURED_ERROR as g,MISSING_USER_ENTROPY_ERROR as p,MISSING_PROJECT_ENTROPY_ERROR as m,INCORRECT_USER_ENTROPY_ERROR as w,MISSING_PASSKEY_ERROR as C,INCORRECT_PASSKEY_ERROR as v,OTP_REQUIRED_ERROR as k,ShieldAuthType as I,Event as P,SignRequest as R,SwitchChainRequest as E,ExportPrivateKeyRequest as T,SetRecoveryMethodRequest as b,GetCurrentDeviceRequest as S,UpdateAuthenticationRequest as N}from"./types.js";class A extends n{constructor(){super(t.MISSING_RECOVERY_PASSWORD,"This embedded signer requires a password to be recovered","password")}}class O extends n{constructor(){super(t.INCORRECT_PASSKEY,"Wrong recovery passkey for this embedded signer","passkey")}}class U extends n{constructor(){super(t.MISSING_PROJECT_ENTROPY,"Project entropy is missing","entropy")}}class z extends n{constructor(){super(t.WRONG_RECOVERY_PASSWORD,"Wrong recovery password for this embedded signer","password")}}class D extends r{constructor(){super(t.NOT_CONFIGURED,"Signer is not configured")}}class K extends o{constructor(){super(t.OTP_REQUIRED,"OTP verification required")}}class M{messenger;connection;remote;storage;sdkConfiguration;isInitialized=!1;initializationPromise=null;hasFailed=!1;constructor(e,i,t){if(!e)throw new s("Configuration is required for IframeManager");if(!i)throw new s("Storage is required for IframeManager");if(!t)throw new s("Messenger is required for IframeManager");this.sdkConfiguration=e,this.storage=i,this.messenger=t}async initialize(){if(!this.isInitialized){if(this.hasFailed)throw new o(t.INTERNAL_ERROR,"Failed to establish iFrame connection: Previous connection attempt failed");if(this.initializationPromise)await this.initializationPromise;else{this.initializationPromise=this.doInitialize();try{await this.initializationPromise,this.isInitialized=!0}catch(e){throw this.hasFailed=!0,this.initializationPromise=null,e}}}}async doInitialize(){u("Initializing IframeManager connection..."),this.messenger.initialize({validateReceivedMessage:e=>!(!e||"object"!=typeof e),log:u}),this.connection=y({messenger:this.messenger,timeout:1e4,log:u});try{this.remote=await this.connection.promise,u("IframeManager connection established")}catch(e){const i=e;throw d.captureException(i),this.destroy(),u("Failed to establish connection:",i),new o(t.INTERNAL_ERROR,`Failed to establish iFrame connection: ${i.cause||i.message}`)}}async ensureConnection(){if(this.isInitialized&&this.remote||await this.initialize(),!this.remote)throw new o(t.INTERNAL_ERROR,"Failed to establish connection");return this.remote}handleError(e){if(f(e)){if(e.error===g)throw this.storage.remove(c.ACCOUNT),new D;if(e.error===p)throw this.storage.remove(c.ACCOUNT),new A;if(e.error===m)throw this.storage.remove(c.ACCOUNT),new U;if(e.error===w)throw new z;if(e.error===C)throw this.storage.remove(c.ACCOUNT),new A;if(e.error===v)throw new O;if(e.error===k)throw new K;throw this.storage.remove(c.ACCOUNT),new o(t.INTERNAL_ERROR,`Unknown error: ${e.error}`)}throw e}async buildRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(t.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:I.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,token:e.token,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl,shieldAuthentication:n,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",shieldURL:this.sdkConfiguration.shieldUrl,encryptionKey:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??void 0,appNativeIdentifier:this.sdkConfiguration?.nativeAppIdentifier??void 0}}async buildIFrameRequestConfiguration(){const e=await i.fromStorage(this.storage);if(!e)throw new a(t.NOT_LOGGED_IN,"Must be authenticated to create a signer");const n={auth:I.OPENFORT,authProvider:e.thirdPartyProvider,token:e.token,tokenType:e.thirdPartyTokenType};return{thirdPartyTokenType:e.thirdPartyTokenType??null,thirdPartyProvider:e.thirdPartyProvider??null,accessToken:e.token,playerID:e.userId,recovery:n,chainId:null,password:null,passkey:null}}async create(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const i=await this.ensureConnection(),t=await this.buildIFrameRequestConfiguration();t.chainId=e.chainId??null,t.password=e?.entropy?.recoveryPassword??null,t.recovery={...t.recovery,encryptionSession:e?.entropy?.encryptionSession},t.passkey=e?.entropy?.passkey??null;const n={uuid:h(),action:P.CREATE,recovery:t.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:t.accessToken,playerID:t.playerID,thirdPartyProvider:t.thirdPartyProvider,thirdPartyTokenType:t.thirdPartyTokenType,encryptionKey:t.password,encryptionSession:t.recovery?.encryptionSession??null,passkey:t.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,chainId:e.chainId??null,accountType:e.accountType,chainType:e.chainType,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},r=await i.create(n);return f(r)&&this.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r}async recover(i){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const t=await e.fromStorage(this.storage),n=await this.ensureConnection(),r=await this.buildIFrameRequestConfiguration();r.chainId=t?.chainId??null,r.password=i?.entropy?.recoveryPassword??null,r.recovery={...r.recovery,encryptionSession:i?.entropy?.encryptionSession},r.passkey=i?.entropy?.passkey??null;const o={uuid:h(),action:P.RECOVER,recovery:r.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:r.accessToken,playerID:r.playerID,thirdPartyProvider:r.thirdPartyProvider,thirdPartyTokenType:r.thirdPartyTokenType,encryptionKey:r.password,encryptionSession:r.recovery?.encryptionSession??null,passkey:r.passkey??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl,account:i.account,nativeAppIdentifier:this.sdkConfiguration?.nativeAppIdentifier??null},s=await n.recover(o);return f(s)&&this.handleError(s),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",s.version??"undefined"),s}async sign(e,i,t,n){u("[iframe] ensureConnection");const r=await this.ensureConnection(),o=new R(h(),e,await this.buildRequestConfiguration(),i,t,n);u("[iframe] done ensureConnection");const s=await r.sign(o);return u("[iframe] response",s),f(s)&&this.handleError(s),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",s.version??"undefined"),s.signature}async switchChain(e){const i=await this.ensureConnection(),t=new E(h(),e,await this.buildRequestConfiguration()),n=await i.switchChain(t);return f(n)&&this.handleError(n),n}async export(){const e=await this.ensureConnection(),i=new T(h(),await this.buildRequestConfiguration()),t=await e.export(i);return f(t)&&this.handleError(t),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",t.version??"undefined"),t.key}async setRecoveryMethod(e,i,t,n,r){const o=await this.ensureConnection(),s=new b(h(),e,await this.buildRequestConfiguration(),i,t,n,r),a=await o.setRecoveryMethod(s);f(a)&&this.handleError(a),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",a.version??"undefined")}async getCurrentDevice(e){const i=await this.ensureConnection(),t=new S(h(),e);try{const e=await i.getCurrentDevice(t);return f(e)&&this.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof D)return null;throw e}}async updateAuthentication(){if(!this.isLoaded()||!this.remote)return void u("IframeManager not loaded, skipping authentication update");const e=await i.fromStorage(this.storage);if(!e)return void u("No authentication found, skipping update");const t=new N(h(),e.token);u("Updating authentication in iframe with token");const n=await this.remote.updateAuthentication(t);f(n)&&this.handleError(n)}async disconnect(){const e=await this.ensureConnection(),i={uuid:h()};await e.logout(i)}async onMessage(e){u("[HANDSHAKE DEBUG] IframeManager.onMessage called with:",e),this.messenger instanceof l?(this.isInitialized||this.connection?u(`[HANDSHAKE DEBUG] Connection already initialized (isInitialized: ${this.isInitialized}, hasConnection: ${!!this.connection})`):(u("[HANDSHAKE DEBUG] First message received, initializing connection..."),this.initialize().catch(e=>{u("[HANDSHAKE DEBUG] Failed to initialize connection:",e)})),u("[HANDSHAKE DEBUG] Passing message to ReactNativeMessenger"),this.messenger.handleMessage(e)):u("[HANDSHAKE DEBUG] Not a ReactNativeMessenger, ignoring message")}isLoaded(){return this.isInitialized&&void 0!==this.remote}destroy(){this.connection&&this.connection.destroy(),this.remote=void 0,this.isInitialized=!1,this.connection=void 0,this.initializationPromise=null}}export{M as IframeManager,U as MissingProjectEntropyError,A as MissingRecoveryPasswordError,D as NotConfiguredError,K as OTPRequiredError,O as WrongPasskeyError,z as WrongRecoveryPasswordError};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openfort/openfort-js",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.36-beta.1",
|
|
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",
|
|
@@ -48,12 +48,14 @@
|
|
|
48
48
|
"@rollup/plugin-replace": "^5.0.2",
|
|
49
49
|
"@rollup/plugin-terser": "^0.4.3",
|
|
50
50
|
"@rollup/plugin-typescript": "^11.1.0",
|
|
51
|
-
"@types/
|
|
52
|
-
"
|
|
51
|
+
"@types/node": "^20.0.0",
|
|
52
|
+
"@vitest/coverage-v8": "^2.1.8",
|
|
53
|
+
"jsdom": "^25.0.1",
|
|
53
54
|
"rollup": "^4.0.0",
|
|
54
55
|
"rollup-plugin-dts": "^5.3.0",
|
|
55
56
|
"rollup-plugin-visualizer": "^5.14.0",
|
|
56
57
|
"typescript": "^5.8.3",
|
|
58
|
+
"vitest": "^2.1.8",
|
|
57
59
|
"@openfort/openapi-clients": "0.0.0"
|
|
58
60
|
},
|
|
59
61
|
"main": "./dist/cjs/sdk/src/index.js",
|
|
@@ -63,8 +65,9 @@
|
|
|
63
65
|
"sideEffects": false,
|
|
64
66
|
"scripts": {
|
|
65
67
|
"test": "pnpm check && pnpm test:unit",
|
|
66
|
-
"test:unit": "
|
|
67
|
-
"test:watch": "
|
|
68
|
+
"test:unit": "vitest run",
|
|
69
|
+
"test:watch": "vitest",
|
|
70
|
+
"test:coverage": "vitest run --coverage",
|
|
68
71
|
"packageList": "./scripts/generate-package-list.sh",
|
|
69
72
|
"dev": "NODE_ENV=development pnpm rollup --config rollup.config.js --watch",
|
|
70
73
|
"check": "biome check --write src",
|