@openfort/openfort-js 0.9.0 → 0.9.2

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/README.md CHANGED
@@ -8,10 +8,6 @@
8
8
  Documentation
9
9
  </a>
10
10
  <span> | </span>
11
- <a href="https://www.openfort.io/docs/reference/api/authentication">
12
- API Docs
13
- </a>
14
- <span> | </span>
15
11
  <a href="https://x.com/openfort_hq">
16
12
  X
17
13
  </a>
@@ -34,59 +30,9 @@ npm install @openfort/openfort-js
34
30
  yarn add @openfort/openfort-js
35
31
  ```
36
32
 
37
- ## Usage
38
-
39
- With the Openfort Unity SDK, you can sign transaction intents using one of four methods or signers:
40
- ```typescript
41
- const sdk = new Openfort({ baseConfiguration: { publishableKey: "pk_test_XXXXXXX"} });
42
- ```
43
-
44
- ### 1. Session Signer
45
- The Session Signer allows you to use external signing keys, without needing to provide it every time. Here's how to use it:
46
-
47
- - **Configure the Session Key**: Call `configureSessionKey()`. This method returns an Ethereum address and a boolean indicating whether you need to register the key from the backend.
48
- ```typescript
49
- const sessionKey = sdk.configureSessionKey();
50
- ```
51
- - **Register Key and Send Signature Session Request**: If `sessionKey.isRegistered` boolean is false, register the key from the backend. Refer to the documentation for [session keys](https://www.openfort.io/docs/guides/javascript/smart-wallet/advanced/session-keys).
52
- - **Send Signature Transaction Intent Request**: When calling sendSignatureTransactionIntentRequest, pass the transaction intent ID and the user operation hash. The session signer will handle the signing.
53
-
54
- ### 2. External Sign
55
-
56
- This method allows you to externally sign transaction intents without logging in or additional configurations:
57
-
58
- - **Call SendSignatureTransactionIntentRequest**: Simply pass the transaction intent ID and the signature.
59
- ```typescript
60
- const response = await sdk.sendSignatureTransactionIntentRequest("tin_xxxx", '0xUserOperationHash');
61
- ```
62
-
63
- ### 3. Embedded Signer
64
-
65
- The Embedded Signer uses SSS to manage the private key on the client side. To learn more, visit our [security documentation](https://www.openfort.io/docs/security).
66
- - **Login and Configure the Embedded Signer**: First, ensure the user is logged in, using `LoginWithEmailPassword`, `AuthenticateWithOAuth` or if not registred `SignUpWithEmailPassword`. Then call `ConfigureEmbeddedSigner`.
67
- ```typescript
68
- const shieldAuth: ShieldAuthentication = {
69
- auth: ShieldAuthType.OPENFORT,
70
- token: identityToken,
71
- authProvider: "firebase",
72
- tokenType: "idToken",
73
- };
74
- await sdk.loginWithEmailPassword("email", "password");
75
- // using automatic recovery
76
- await sdk.configureEmbeddedSigner(chainId, shieldAuth);
77
- ```
78
- For now the only two recovery method available are the `PasswordRecovery` and `AutomaticRecovery`. Learn more about the [recovery methods](https://www.openfort.io/docs/guides/javascript/embedded-signer/recovery).
79
- - **Send Signature Transaction Intent Request**: Similar to the session signer, pass the transaction intent ID and the user operation hash. The embedded signer reconstructs the key and signs the transaction.
80
- ```typescript
81
- const response = await sdk.sendSignatureTransactionIntentRequest("transactionIntentId", "userOp");
82
- ```
83
-
84
-
85
33
  ## Usage examples
86
- - [Next.js application with non-custodial signer](https://github.com/openfort-xyz/samples/tree/main/rainbow-ssv-nextjs)
87
- - [Next.js application with custodial signer and social login](https://github.com/openfort-xyz/samples/tree/main/ssv-social-nextjs)
88
-
89
- [next-action]: https://www.openfort.io/docs/api/transaction_intents#the-transaction-intent-object
34
+ - [Next.js app Embedded Wallet](https://github.com/openfort-xyz/openfort-js/tree/main/examples/apps/auth-sample)
35
+ - [Next.js app - Wagmi - Embedded Wallet](https://github.com/openfort-xyz/openfort-js/tree/main/examples/apps/wallet-libraries/next-wagmi)
90
36
 
91
37
  <!--
92
38
  # vim: set tw=79:
@@ -0,0 +1 @@
1
+ "use strict";var e=class extends Error{code;constructor(e,t){super(t),this.name="PenpalError",this.code=e}},t=t=>({name:t.name,message:t.message,stack:t.stack,penpalCode:t instanceof e?t.code:void 0}),s=Symbol("Reply"),r=class{value;transferables;#e=s;constructor(e,t){this.value=e,this.transferables=t?.transferables}},n="penpal",a=e=>"object"==typeof e&&null!==e,o=e=>"function"==typeof e,i=e=>"SYN"===e.type,l=e=>"ACK1"===e.type,d=e=>"ACK2"===e.type,c=e=>"CALL"===e.type,h=e=>"REPLY"===e.type,g=(e,t=[])=>{const s=[];for(const r of Object.keys(e)){const n=e[r];o(n)?s.push([...t,r]):a(n)&&s.push(...g(n,[...t,r]))}return s},p=e=>e.join("."),m=(e,s,r)=>({namespace:n,channel:e,type:"REPLY",callId:s,isError:!0,...r instanceof Error?{value:t(r),isSerializedErrorInstance:!0}:{value:r}}),u=(t,s,i,l)=>{let d=!1;const h=async h=>{if(d)return;if(!c(h))return;l?.(`Received ${p(h.methodPath)}() call`,h);const{methodPath:g,args:u,id:f}=h;let w,v;try{const t=((e,t)=>{const s=e.reduce((e,t)=>a(e)?e[t]:void 0,t);return o(s)?s:void 0})(g,s);if(!t)throw new e("METHOD_NOT_FOUND",`Method \`${p(g)}\` is not found.`);let l=await t(...u);l instanceof r&&(v=l.transferables,l=await l.value),w={namespace:n,channel:i,type:"REPLY",callId:f,value:l}}catch(e){w=m(i,f,e)}if(!d)try{l?.(`Sending ${p(g)}() reply`,w),t.sendMessage(w,v)}catch(e){throw"DataCloneError"===e.name&&(w=m(i,f,e),l?.(`Sending ${p(g)}() reply`,w),t.sendMessage(w)),e}};return t.addMessageHandler(h),()=>{d=!0,t.removeMessageHandler(h)}},f=crypto.randomUUID?.bind(crypto)??(()=>new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")),w=Symbol("CallOptions"),v=class{transferables;timeout;#e=w;constructor(e){this.transferables=e?.transferables,this.timeout=e?.timeout}},y=new Set(["apply","call","bind"]),M=(e,t,s=[])=>new Proxy(s.length?()=>{}:Object.create(null),{get(r,n){if("then"!==n)return s.length&&y.has(n)?Reflect.get(r,n):M(e,t,[...s,n])},apply:(t,r,n)=>e(s,n)}),E=t=>new e("CONNECTION_DESTROYED",`Method call ${p(t)}() failed due to destroyed connection`),I=(t,s,r)=>{let a=!1;const o=new Map,i=t=>{if(!h(t))return;const{callId:s,value:n,isError:a,isSerializedErrorInstance:i}=t,l=o.get(s);l&&(o.delete(s),r?.(`Received ${p(l.methodPath)}() call`,t),a?l.reject(i?(({name:t,message:s,stack:r,penpalCode:n})=>{const a=n?new e(n,s):new Error(s);return a.name=t,a.stack=r,a})(n):n):l.resolve(n))};t.addMessageHandler(i);return{remoteProxy:M((i,l)=>{if(a)throw E(i);const d=f(),c=l[l.length-1],h=c instanceof v,{timeout:g,transferables:m}=h?c:{},u=h?l.slice(0,-1):l;return new Promise((a,l)=>{const c=void 0!==g?window.setTimeout(()=>{o.delete(d),l(new e("METHOD_CALL_TIMEOUT",`Method call ${p(i)}() timed out after ${g}ms`))},g):void 0;o.set(d,{methodPath:i,resolve:a,reject:l,timeoutId:c});try{const e={namespace:n,channel:s,type:"CALL",id:d,methodPath:i,args:u};r?.(`Sending ${p(i)}() call`,e),t.sendMessage(e,m)}catch(t){l(new e("TRANSMISSION_FAILED",t.message))}})},r),destroy:()=>{a=!0,t.removeMessageHandler(i);for(const{methodPath:e,reject:t,timeoutId:s}of o.values())clearTimeout(s),t(E(e));o.clear()}}},O=()=>{let e,t;return{promise:new Promise((s,r)=>{e=s,t=r}),resolve:e,reject:t}},S=class extends Error{constructor(e){super(`You've hit a bug in Penpal. Please file an issue with the following information: ${e}`)}},P="deprecated-penpal",R=e=>e.join("."),C=e=>new S(`Unexpected message to translate: ${JSON.stringify(e)}`),A=({messenger:t,methods:s,timeout:r,channel:a,log:o})=>{const c=f();let h;const p=[];let m=!1;const w=g(s),{promise:v,resolve:y,reject:M}=O(),E=void 0!==r?setTimeout(()=>{M(new e("CONNECTION_TIMEOUT",`Connection timed out after ${r}ms`))},r):void 0,S=()=>{for(const e of p)e()},R=()=>{if(m)return;p.push(u(t,s,a,o));const{remoteProxy:e,destroy:r}=I(t,a,o);p.push(r),clearTimeout(E),m=!0,y({remoteProxy:e,destroy:S})},C=()=>{const s={namespace:n,type:"SYN",channel:a,participantId:c};o?.("Sending handshake SYN",s);try{t.sendMessage(s)}catch(t){M(new e("TRANSMISSION_FAILED",t.message))}},A=s=>{i(s)&&(s=>{if(o?.("Received handshake SYN",s),s.participantId===h&&h!==P)return;if(h=s.participantId,C(),!(c>h||h===P))return;const r={namespace:n,channel:a,type:"ACK1",methodPaths:w};o?.("Sending handshake ACK1",r);try{t.sendMessage(r)}catch(t){return void M(new e("TRANSMISSION_FAILED",t.message))}})(s),l(s)&&(s=>{o?.("Received handshake ACK1",s);const r={namespace:n,channel:a,type:"ACK2"};o?.("Sending handshake ACK2",r);try{t.sendMessage(r)}catch(t){return void M(new e("TRANSMISSION_FAILED",t.message))}R()})(s),d(s)&&(e=>{o?.("Received handshake ACK2",e),R()})(s)};return t.addMessageHandler(A),p.push(()=>t.removeMessageHandler(A)),C(),v},N=e=>{let t,s=!1;return(...r)=>(s||(s=!0,t=e(...r)),t)},b=new WeakSet,L=({messenger:t,methods:s={},timeout:r,channel:o,log:i})=>{if(!t)throw new e("INVALID_ARGUMENT","messenger must be defined");if(b.has(t))throw new e("INVALID_ARGUMENT","A messenger can only be used for a single connection");b.add(t);const l=[t.destroy],d=N(e=>{if(e){const e={namespace:n,channel:o,type:"DESTROY"};try{t.sendMessage(e)}catch(e){}}for(const e of l)e();i?.("Connection destroyed")}),c=e=>(e=>a(e)&&e.namespace===n)(e)&&e.channel===o;return{promise:(async()=>{try{t.initialize({log:i,validateReceivedMessage:c}),t.addMessageHandler(e=>{(e=>"DESTROY"===e.type)(e)&&d(!1)});const{remoteProxy:e,destroy:n}=await A({messenger:t,methods:s,timeout:r,channel:o,log:i});return l.push(n),e}catch(e){throw d(!0),e}})(),destroy:()=>{d(!0)}}},T=class{#t;#s;#r;#n;#a;#o=new Set;#i;#l=!1;constructor({remoteWindow:t,allowedOrigins:s}){if(!t)throw new e("INVALID_ARGUMENT","remoteWindow must be defined");this.#t=t,this.#s=s?.length?s:[window.origin]}initialize=({log:e,validateReceivedMessage:t})=>{this.#r=e,this.#n=t,window.addEventListener("message",this.#d)};sendMessage=(e,t)=>{if(i(e)){const s=this.#c(e);return void this.#t.postMessage(e,{targetOrigin:s,transfer:t})}if(l(e)||this.#l){const s=this.#l?(e=>{if(l(e))return{penpal:"synAck",methodNames:e.methodPaths.map(R)};if(c(e))return{penpal:"call",id:e.id,methodName:R(e.methodPath),args:e.args};if(h(e))return e.isError?{penpal:"reply",id:e.callId,resolution:"rejected",...e.isSerializedErrorInstance?{returnValue:e.value,returnValueIsError:!0}:{returnValue:e.value}}:{penpal:"reply",id:e.callId,resolution:"fulfilled",returnValue:e.value};throw C(e)})(e):e,r=this.#c(e);return void this.#t.postMessage(s,{targetOrigin:r,transfer:t})}if(d(e)){const{port1:s,port2:r}=new MessageChannel;this.#i=s,s.addEventListener("message",this.#h),s.start();const n=[r,...t||[]],a=this.#c(e);return void this.#t.postMessage(e,{targetOrigin:a,transfer:n})}if(!this.#i)throw new S("Port is undefined");this.#i.postMessage(e,{transfer:t})};addMessageHandler=e=>{this.#o.add(e)};removeMessageHandler=e=>{this.#o.delete(e)};destroy=()=>{window.removeEventListener("message",this.#d),this.#g(),this.#o.clear()};#p=e=>this.#s.some(t=>t instanceof RegExp?t.test(e):t===e||"*"===t);#c=e=>{if(i(e))return"*";if(!this.#a)throw new S("Concrete remote origin not set");return"null"===this.#a&&this.#s.includes("*")?"*":this.#a};#g=()=>{this.#i?.removeEventListener("message",this.#h),this.#i?.close(),this.#i=void 0};#d=({source:e,origin:t,ports:s,data:r})=>{if(e===this.#t&&((e=>a(e)&&"penpal"in e)(r)&&(this.#r?.("Please upgrade the child window to the latest version of Penpal."),this.#l=!0,r=(e=>{if("syn"===e.penpal)return{namespace:n,channel:void 0,type:"SYN",participantId:P};if("ack"===e.penpal)return{namespace:n,channel:void 0,type:"ACK2"};if("call"===e.penpal)return{namespace:n,channel:void 0,type:"CALL",id:e.id,methodPath:(t=e.methodName,t.split(".")),args:e.args};var t;if("reply"===e.penpal)return"fulfilled"===e.resolution?{namespace:n,channel:void 0,type:"REPLY",callId:e.id,value:e.returnValue}:{namespace:n,channel:void 0,type:"REPLY",callId:e.id,isError:!0,...e.returnValueIsError?{value:e.returnValue,isSerializedErrorInstance:!0}:{value:e.returnValue}};throw C(e)})(r)),this.#n?.(r)))if(this.#p(t)){if(i(r)&&(this.#g(),this.#a=t),d(r)&&!this.#l){if(this.#i=s[0],!this.#i)throw new S("No port received on ACK2");this.#i.addEventListener("message",this.#h),this.#i.start()}for(const e of this.#o)e(r)}else this.#r?.(`Received a message from origin \`${t}\` which did not match allowed origins \`[${this.#s.join(", ")}]\``)};#h=({data:e})=>{if(this.#n?.(e))for(const t of this.#o)t(e)}};exports.CallOptions=v,exports.PenpalError=e,exports.Reply=r,exports.WindowMessenger=T,exports.connect=L;
@@ -1 +1 @@
1
- "use strict";var t=require("../storage/istorage.js"),a=require("../core/configuration/authentication.js"),e=require("../wallets/signer.js"),i=require("../core/errors/openfortError.js");exports.AuthApi=class{storage;authManager;validateAndRefreshToken;ensureInitialized;constructor(t,a,e,i){this.storage=t,this.authManager=a,this.validateAndRefreshToken=e,this.ensureInitialized=i}async logInWithEmailPassword({email:t,password:e,ecosystemGame:i}){await this.ensureInitialized();const r=await a.Authentication.fromStorage(this.storage),n=await this.authManager.loginEmailPassword(t,e,i);return"action"in n||(r&&r.player!==n.player.id&&await this.logout(),new a.Authentication("jwt",n.token,n.player.id,n.refreshToken).save(this.storage)),n}async signUpGuest(){await this.ensureInitialized();const t=await a.Authentication.fromStorage(this.storage),e=await this.authManager.registerGuest();return t&&t.player!==e.player.id&&await this.logout(),new a.Authentication("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),e}async signUpWithEmailPassword({email:t,password:e,options:i,ecosystemGame:r}){await this.ensureInitialized();const n=await a.Authentication.fromStorage(this.storage),s=await this.authManager.signupEmailPassword(t,e,i?.data.name,r);return"action"in s||(n&&n.player!==s.player.id&&await this.logout(),new a.Authentication("jwt",s.token,s.player.id,s.refreshToken).save(this.storage)),s}async linkEmailPassword({email:t,password:a,authToken:e,ecosystemGame:i}){return await this.authManager.linkEmail(t,a,e,i)}async unlinkEmailPassword({email:t,authToken:a}){return await this.authManager.unlinkEmail(t,a)}async requestEmailVerification({email:t,redirectUrl:a}){await this.authManager.requestEmailVerification(t,a)}async resetPassword({email:t,password:a,state:e}){await this.authManager.resetPassword(t,a,e)}async requestResetPassword({email:t,redirectUrl:a}){await this.ensureInitialized(),await this.authManager.requestResetPassword(t,a)}async verifyEmail({email:t,state:a}){await this.authManager.verifyEmail(t,a)}async initOAuth({provider:t,options:a,ecosystemGame:e}){return await this.ensureInitialized(),await this.authManager.initOAuth(t,a,e)}async initLinkOAuth({provider:t,options:e,ecosystemGame:r}){const n=await a.Authentication.fromStorage(this.storage);if(!n)throw new i.OpenfortError("No authentication found",i.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return await this.authManager.linkOAuth(n,t,e,r)}async linkThirdPartyProvider({provider:t,token:e,tokenType:r}){const n=await a.Authentication.fromStorage(this.storage);if(!n)throw new i.OpenfortError("No authentication found",i.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return await this.authManager.linkThirdParty(n,t,e,r)}async unlinkOAuth({provider:t,authToken:a}){return await this.authManager.unlinkOAuth(t,a)}async poolOAuth(t){await this.ensureInitialized();const e=await a.Authentication.fromStorage(this.storage),i=await this.authManager.poolOAuth(t);return e&&e.player!==i.player.id&&await this.logout(),new a.Authentication("jwt",i.token,i.player.id,i.refreshToken).save(this.storage),i}async authenticateWithThirdPartyProvider({provider:t,token:e,tokenType:i,ecosystemGame:r}){await this.ensureInitialized();const n=await a.Authentication.fromStorage(this.storage),s=await this.authManager.authenticateThirdParty(t,e,i,r);return n&&n.player!==s.id&&await this.logout(),new a.Authentication("third_party",e,s.id,null,t,i).save(this.storage),s}async loginWithIdToken({provider:t,token:e,ecosystemGame:i}){await this.ensureInitialized();const r=await a.Authentication.fromStorage(this.storage),n=await this.authManager.loginWithIdToken(t,e,i);return r&&r.player!==n.player.id&&await this.logout(),new a.Authentication("jwt",n.token,n.player.id,n.refreshToken).save(this.storage),n}async initSIWE({address:t,ecosystemGame:a}){return await this.ensureInitialized(),await this.authManager.initSIWE(t,a)}async authenticateWithSIWE({signature:t,message:e,walletClientType:i,connectorType:r}){await this.ensureInitialized();const n=await a.Authentication.fromStorage(this.storage),s=await this.authManager.authenticateSIWE(t,e,i,r);return n&&n.player!==s.player.id&&await this.logout(),new a.Authentication("jwt",s.token,s.player.id,s.refreshToken).save(this.storage),s}async linkWallet({signature:t,message:a,walletClientType:e,connectorType:i,authToken:r}){return await this.authManager.linkWallet(t,a,e,i,r)}async unlinkWallet({address:t,authToken:a}){return await this.authManager.unlinkWallet(t,a)}async storeCredentials(t){if(await this.ensureInitialized(),!t.player)throw new i.OpenfortError("Player ID is required to store credentials",i.OpenfortErrorType.INVALID_CONFIGURATION);new a.Authentication("jwt",t.accessToken,t.player,t.refreshToken).save(this.storage)}async logout(){await this.ensureInitialized();const a=await e.SignerManager.fromStorage(this.storage);this.storage.remove(t.StorageKeys.AUTHENTICATION),this.storage.remove(t.StorageKeys.SIGNER),this.storage.remove(t.StorageKeys.ACCOUNT),a&&await a.logout()}};
1
+ "use strict";var t=require("../storage/istorage.js"),a=require("../core/configuration/authentication.js"),e=require("../wallets/signer.js"),i=require("../core/errors/openfortError.js");exports.AuthApi=class{storage;authManager;validateAndRefreshToken;ensureInitialized;constructor(t,a,e,i){this.storage=t,this.authManager=a,this.validateAndRefreshToken=e,this.ensureInitialized=i}async logInWithEmailPassword({email:t,password:e,ecosystemGame:i}){await this.ensureInitialized();const r=await a.Authentication.fromStorage(this.storage),n=await this.authManager.loginEmailPassword(t,e,i);return"action"in n||(r&&r.player!==n.player.id&&await this.logout(),new a.Authentication("jwt",n.token,n.player.id,n.refreshToken).save(this.storage)),n}async signUpGuest(){await this.ensureInitialized();const t=await a.Authentication.fromStorage(this.storage),e=await this.authManager.registerGuest();return t&&t.player!==e.player.id&&await this.logout(),new a.Authentication("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),e}async signUpWithEmailPassword({email:t,password:e,options:i,ecosystemGame:r}){await this.ensureInitialized();const n=await a.Authentication.fromStorage(this.storage),s=await this.authManager.signupEmailPassword(t,e,i?.data.name,r);return"action"in s||(n&&n.player!==s.player.id&&await this.logout(),new a.Authentication("jwt",s.token,s.player.id,s.refreshToken).save(this.storage)),s}async linkEmailPassword({email:t,password:a,authToken:e,ecosystemGame:i}){return await this.authManager.linkEmail(t,a,e,i)}async unlinkEmailPassword({email:t,authToken:a}){return await this.authManager.unlinkEmail(t,a)}async requestEmailVerification({email:t,redirectUrl:a}){await this.authManager.requestEmailVerification(t,a)}async resetPassword({email:t,password:a,state:e}){await this.authManager.resetPassword(t,a,e)}async requestResetPassword({email:t,redirectUrl:a}){await this.ensureInitialized(),await this.authManager.requestResetPassword(t,a)}async verifyEmail({email:t,state:a}){await this.authManager.verifyEmail(t,a)}async initOAuth({provider:t,options:a,ecosystemGame:e}){return await this.ensureInitialized(),await this.authManager.initOAuth(t,a,e)}async initLinkOAuth({provider:t,options:e,ecosystemGame:r}){const n=await a.Authentication.fromStorage(this.storage);if(!n)throw new i.OpenfortError("No authentication found",i.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return await this.authManager.linkOAuth(n,t,e,r)}async linkThirdPartyProvider({provider:t,token:e,tokenType:r}){const n=await a.Authentication.fromStorage(this.storage);if(!n)throw new i.OpenfortError("No authentication found",i.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return await this.authManager.linkThirdParty(n,t,e,r)}async unlinkOAuth({provider:t,authToken:a}){return await this.authManager.unlinkOAuth(t,a)}async poolOAuth(t){await this.ensureInitialized();const e=await a.Authentication.fromStorage(this.storage),i=await this.authManager.poolOAuth(t);return e&&e.player!==i.player.id&&await this.logout(),new a.Authentication("jwt",i.token,i.player.id,i.refreshToken).save(this.storage),i}async authenticateWithThirdPartyProvider({provider:t,token:e,tokenType:i,ecosystemGame:r}){await this.ensureInitialized();const n=await a.Authentication.fromStorage(this.storage),s=await this.authManager.authenticateThirdParty(t,e,i,r);return n&&n.player!==s.id&&await this.logout(),new a.Authentication("third_party",e,s.id,null,t,i).save(this.storage),s}async loginWithIdToken({provider:t,token:e,ecosystemGame:i}){await this.ensureInitialized();const r=await a.Authentication.fromStorage(this.storage),n=await this.authManager.loginWithIdToken(t,e,i);return r&&r.player!==n.player.id&&await this.logout(),new a.Authentication("jwt",n.token,n.player.id,n.refreshToken).save(this.storage),n}async initSIWE({address:t,ecosystemGame:a}){return await this.ensureInitialized(),await this.authManager.initSIWE(t,a)}async authenticateWithSIWE({signature:t,message:e,walletClientType:i,connectorType:r}){await this.ensureInitialized();const n=await a.Authentication.fromStorage(this.storage),s=await this.authManager.authenticateSIWE(t,e,i,r);return n&&n.player!==s.player.id&&await this.logout(),new a.Authentication("jwt",s.token,s.player.id,s.refreshToken).save(this.storage),s}async linkWallet({signature:t,message:a,walletClientType:e,connectorType:i,authToken:r}){return await this.authManager.linkWallet(t,a,e,i,r)}async unlinkWallet({address:t,authToken:a}){return await this.authManager.unlinkWallet(t,a)}async storeCredentials(t){if(await this.ensureInitialized(),!t.player)throw new i.OpenfortError("Player ID is required to store credentials",i.OpenfortErrorType.INVALID_CONFIGURATION);new a.Authentication("jwt",t.accessToken,t.player,t.refreshToken).save(this.storage)}async logout(){await this.ensureInitialized();const a=await e.SignerManager.fromStorage(this.storage);this.storage.remove(t.StorageKeys.AUTHENTICATION),this.storage.remove(t.StorageKeys.ACCOUNT),a&&await a.logout()}};
@@ -1 +1 @@
1
- "use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.js"),r=require("../wallets/signer.js"),t=require("../core/configuration/account.js"),o=require("../core/configuration/authentication.js"),i=require("../core/config/config.js"),n=require("../core/errors/openfortError.js"),a=require("../wallets/evm/walletHelpers.js"),s=require("../wallets/evm/evmProvider.js");require("../wallets/evm/types.js");var d=require("../wallets/evm/provider/eip6963.js"),c=require("../utils/typedEventEmitter.js"),h=require("../types/types.js"),f=require("../wallets/iframeManager.js");exports.EmbeddedWalletApi=class{storage;validateAndRefreshToken;ensureInitialized;provider=null;iframeManager=null;constructor(e,r,t){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t}get backendApiClients(){const r=i.SDKConfiguration.fromStorage();if(!r)throw new n.OpenfortError("Configuration not found",n.OpenfortErrorType.INVALID_CONFIGURATION);return new e.BackendApiClients({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey})}getIframeManager(){if(!this.iframeManager){const e=i.SDKConfiguration.fromStorage();if(!e)throw new n.OpenfortError("Configuration not found",n.OpenfortErrorType.INVALID_CONFIGURATION);this.iframeManager=new f.IframeManager(e,this.storage)}return this.iframeManager}async configure(e={}){const t=e.recoveryParams??{recoveryMethod:h.RecoveryMethod.AUTOMATIC};await this.ensureInitialized(),await this.validateAndRefreshToken();const o=i.SDKConfiguration.fromStorage();let a=null;(t.recoveryMethod===h.RecoveryMethod.PASSWORD||e.shieldAuthentication?.encryptionSession)&&(a={encryptionSession:e.shieldAuthentication?.encryptionSession||null,recoveryPassword:t.recoveryMethod===h.RecoveryMethod.PASSWORD?t.password:null,encryptionPart:o?.shieldConfiguration?.shieldEncryptionKey||null});let s=null,d=null;if(e.shieldAuthentication&&(s="openfort"===e.shieldAuthentication.auth?"openfort":"custom",d=e.shieldAuthentication.token),!this.storage)throw new n.OpenfortError("Storage not available in EmbeddedWalletApi",n.OpenfortErrorType.INVALID_CONFIGURATION);return await r.SignerManager.embedded(this.storage,e.chainId,a,s,d),this.get()}async signMessage(e,t){await this.ensureInitialized(),await this.validateAndRefreshToken();const o=await r.SignerManager.fromStorage(this.storage);if(!o)throw new n.OpenfortError("No signer configured",n.OpenfortErrorType.MISSING_SIGNER_ERROR);const{hashMessage:i=!0,arrayifyMessage:a=!1}=t||{};return await o.sign(e,a,i)}async signTypedData(e,o,i){await this.ensureInitialized(),await this.validateAndRefreshToken();const s=await r.SignerManager.fromStorage(this.storage),d=await t.Account.fromStorage(this.storage);if(!s||!d)throw new n.OpenfortError("No signer configured",n.OpenfortErrorType.MISSING_SIGNER_ERROR);return await a.getSignedTypedData({domain:e,types:o,message:i},d.type,Number(d.chainId),s,d.address)}async exportPrivateKey(){await this.ensureInitialized(),await this.validateAndRefreshToken();const e=await r.SignerManager.fromStorage(this.storage);if(!e)throw new n.OpenfortError("No signer configured",n.OpenfortErrorType.MISSING_SIGNER_ERROR);return await e.export()}async setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:t,encryptionSession:o}){await this.ensureInitialized(),await this.validateAndRefreshToken();const i=await r.SignerManager.fromStorage(this.storage);if(!i)throw new n.OpenfortError("No signer configured",n.OpenfortErrorType.MISSING_SIGNER_ERROR);if("password"===e&&!t)throw new n.OpenfortError("Recovery password is required",n.OpenfortErrorType.INVALID_CONFIGURATION);await i.setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:t,encryptionSession:o})}async get(){const e=await t.Account.fromStorage(this.storage);if(!e)throw new n.OpenfortError("No signer configured",n.OpenfortErrorType.MISSING_SIGNER_ERROR);const r=await o.Authentication.fromStorage(this.storage);if(!r)throw new n.OpenfortError("No access token found",n.OpenfortErrorType.INTERNAL_ERROR);return{chainId:e.chainId.toString(),owner:{id:r.player},address:e.address,ownerAddress:e.ownerAddress,chainType:"ethereum",implementationType:e.type}}async list(){const e=i.SDKConfiguration.fromStorage();if(!e)throw new n.OpenfortError("Configuration not found",n.OpenfortErrorType.INVALID_CONFIGURATION);await this.ensureInitialized(),await this.validateAndRefreshToken();const r=await o.Authentication.fromStorage(this.storage);if(!r)throw new n.OpenfortError("No access token found",n.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return n.withOpenfortError(async()=>(await this.backendApiClients.accountsApi.getAccounts(void 0,{headers:{authorization:`Bearer ${e.baseConfiguration.publishableKey}`,"x-player-token":r.token,"x-auth-provider":r.thirdPartyProvider,"x-token-type":r.thirdPartyTokenType}})).data.data.map(e=>({owner:{id:e.player.id},chainType:"ethereum",address:e.address,ownerAddress:e.ownerAddress,createdAt:e.createdAt,implementationType:e.accountType,chainId:e.chainId.toString()})),{default:n.OpenfortErrorType.AUTHENTICATION_ERROR})}async getEmbeddedState(){try{if(!await o.Authentication.fromStorage(this.storage))return h.EmbeddedState.UNAUTHENTICATED;if(!await r.SignerManager.fromStorage(this.storage))return h.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED;return await t.Account.fromStorage(this.storage)?h.EmbeddedState.READY:h.EmbeddedState.CREATING_ACCOUNT}catch(e){return console.error("Failed to get embedded state:",e),h.EmbeddedState.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const i={announceProvider:!0,...e},n=await o.Authentication.fromStorage(this.storage),a=await r.SignerManager.fromStorage(this.storage),h=await t.Account.fromStorage(this.storage);return this.provider?this.provider&&i.policy&&this.provider.updatePolicy(i.policy):(this.provider=new s.EvmProvider({storage:this.storage,openfortEventEmitter:new c,signer:a||void 0,account:h||void 0,authentication:n||void 0,backendApiClients:this.backendApiClients,policyId:i.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:i.chains}),i.announceProvider&&d.announceProvider({info:{...d.openfortProviderInfo,...i.providerInfo},provider:this.provider})),this.provider}async ping(e){try{const r=this.getIframeManager();if(!r.isLoaded())return!1;e>0&&await new Promise(r=>{setTimeout(r,e)});const t=await o.Authentication.fromStorage(this.storage);if(t)try{return await r.getCurrentUser(t.player),!0}catch(e){return!1}return r.isLoaded()}catch(e){return!1}}getURL(){if(!i.SDKConfiguration.fromStorage())throw new n.OpenfortError("Configuration not found",n.OpenfortErrorType.INVALID_CONFIGURATION);return"http://localhost:5173"}};
1
+ "use strict";var e=require("../../../packages/internal/openapi-clients/dist/index.js"),r=require("../wallets/signer.js"),t=require("../core/configuration/account.js"),o=require("../core/configuration/authentication.js"),i=require("../core/config/config.js"),n=require("../core/errors/openfortError.js"),a=require("../wallets/evm/walletHelpers.js"),s=require("../wallets/evm/evmProvider.js");require("../wallets/evm/types.js");var d=require("../wallets/evm/provider/eip6963.js"),c=require("../utils/typedEventEmitter.js"),h=require("../types/types.js"),f=require("../wallets/iframeManager.js");exports.EmbeddedWalletApi=class{storage;validateAndRefreshToken;ensureInitialized;provider=null;iframeManager=null;constructor(e,r,t){this.storage=e,this.validateAndRefreshToken=r,this.ensureInitialized=t}get backendApiClients(){const r=i.SDKConfiguration.fromStorage();if(!r)throw new n.OpenfortError("Configuration not found",n.OpenfortErrorType.INVALID_CONFIGURATION);return new e.BackendApiClients({basePath:r.backendUrl,accessToken:r.baseConfiguration.publishableKey})}getIframeManager(){if(!this.iframeManager){const e=i.SDKConfiguration.fromStorage();if(!e)throw new n.OpenfortError("Configuration not found",n.OpenfortErrorType.INVALID_CONFIGURATION);this.iframeManager=new f.IframeManager(e,this.storage)}return this.iframeManager}async configure(e={}){const t=e.recoveryParams??{recoveryMethod:h.RecoveryMethod.AUTOMATIC};await this.ensureInitialized(),await this.validateAndRefreshToken();const o=i.SDKConfiguration.fromStorage();let a=null;(t.recoveryMethod===h.RecoveryMethod.PASSWORD||e.shieldAuthentication?.encryptionSession)&&(a={encryptionSession:e.shieldAuthentication?.encryptionSession||null,recoveryPassword:t.recoveryMethod===h.RecoveryMethod.PASSWORD?t.password:null,encryptionPart:o?.shieldConfiguration?.shieldEncryptionKey||null});let s=null,d=null;if(e.shieldAuthentication&&(s="openfort"===e.shieldAuthentication.auth?"openfort":"custom",d=e.shieldAuthentication.token),!this.storage)throw new n.OpenfortError("Storage not available in EmbeddedWalletApi",n.OpenfortErrorType.INVALID_CONFIGURATION);return await r.SignerManager.embedded(this.storage,e.chainId,a,s,d),this.get()}async signMessage(e,t){await this.ensureInitialized(),await this.validateAndRefreshToken();const o=await r.SignerManager.fromStorage(this.storage);if(!o)throw new n.OpenfortError("No signer configured",n.OpenfortErrorType.MISSING_SIGNER_ERROR);const{hashMessage:i=!0,arrayifyMessage:a=!1}=t||{};return await o.sign(e,a,i)}async signTypedData(e,o,i){await this.ensureInitialized(),await this.validateAndRefreshToken();const s=await r.SignerManager.fromStorage(this.storage),d=await t.Account.fromStorage(this.storage);if(!s||!d)throw new n.OpenfortError("No signer configured",n.OpenfortErrorType.MISSING_SIGNER_ERROR);return await a.getSignedTypedData({domain:e,types:o,message:i},d.type,Number(d.chainId),s,d.address)}async exportPrivateKey(){await this.ensureInitialized(),await this.validateAndRefreshToken();const e=await r.SignerManager.fromStorage(this.storage);if(!e)throw new n.OpenfortError("No signer configured",n.OpenfortErrorType.MISSING_SIGNER_ERROR);return await e.export()}async setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:t,encryptionSession:o}){await this.ensureInitialized(),await this.validateAndRefreshToken();const i=await r.SignerManager.fromStorage(this.storage);if(!i)throw new n.OpenfortError("No signer configured",n.OpenfortErrorType.MISSING_SIGNER_ERROR);if("password"===e&&!t)throw new n.OpenfortError("Recovery password is required",n.OpenfortErrorType.INVALID_CONFIGURATION);await i.setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:t,encryptionSession:o})}async get(){const e=await t.Account.fromStorage(this.storage);if(!e)throw new n.OpenfortError("No signer configured",n.OpenfortErrorType.MISSING_SIGNER_ERROR);const r=await o.Authentication.fromStorage(this.storage);if(!r)throw new n.OpenfortError("No access token found",n.OpenfortErrorType.INTERNAL_ERROR);return{chainId:e.chainId.toString(),owner:{id:r.player},address:e.address,ownerAddress:e.ownerAddress,chainType:"ethereum",implementationType:e.type}}async list(){const e=i.SDKConfiguration.fromStorage();if(!e)throw new n.OpenfortError("Configuration not found",n.OpenfortErrorType.INVALID_CONFIGURATION);await this.ensureInitialized(),await this.validateAndRefreshToken();const r=await o.Authentication.fromStorage(this.storage);if(!r)throw new n.OpenfortError("No access token found",n.OpenfortErrorType.NOT_LOGGED_IN_ERROR);return n.withOpenfortError(async()=>(await this.backendApiClients.accountsApi.getAccounts(void 0,{headers:{authorization:`Bearer ${e.baseConfiguration.publishableKey}`,"x-player-token":r.token,"x-auth-provider":r.thirdPartyProvider,"x-token-type":r.thirdPartyTokenType}})).data.data.map(e=>({owner:{id:e.player.id},chainType:"ethereum",address:e.address,ownerAddress:e.ownerAddress,createdAt:e.createdAt,implementationType:e.accountType,chainId:e.chainId.toString()})),{default:n.OpenfortErrorType.AUTHENTICATION_ERROR})}async getEmbeddedState(){try{if(!await o.Authentication.fromStorage(this.storage))return h.EmbeddedState.UNAUTHENTICATED;if(!await r.SignerManager.fromStorage(this.storage))return h.EmbeddedState.EMBEDDED_SIGNER_NOT_CONFIGURED;return await t.Account.fromStorage(this.storage)?h.EmbeddedState.READY:h.EmbeddedState.CREATING_ACCOUNT}catch(e){return console.error("Failed to get embedded state:",e),h.EmbeddedState.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const i={announceProvider:!0,...e},n=await o.Authentication.fromStorage(this.storage),a=await r.SignerManager.fromStorage(this.storage),h=await t.Account.fromStorage(this.storage);return this.provider?this.provider&&i.policy&&this.provider.updatePolicy(i.policy):(this.provider=new s.EvmProvider({storage:this.storage,openfortEventEmitter:new c,signer:a||void 0,account:h||void 0,authentication:n||void 0,backendApiClients:this.backendApiClients,policyId:i.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:i.chains}),i.announceProvider&&d.announceProvider({info:{...d.openfortProviderInfo,...i.providerInfo},provider:this.provider})),this.provider}async ping(e){try{const r=this.getIframeManager();if(!r.isLoaded())return!1;e>0&&await new Promise(r=>{setTimeout(r,e)});const t=await o.Authentication.fromStorage(this.storage);if(t)try{return await r.getCurrentUser(t.player),!0}catch(e){return!1}return r.isLoaded()}catch(e){return!1}}getURL(){const e=i.SDKConfiguration.fromStorage();if(!e)throw new n.OpenfortError("Configuration not found",n.OpenfortErrorType.INVALID_CONFIGURATION);return e.iframeUrl}};
@@ -1 +1 @@
1
- "use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="0.9.0";
1
+ "use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="0.9.2";
@@ -1 +1 @@
1
- "use strict";var e=require("../core/configuration/account.js"),r=require("../core/configuration/authentication.js"),t=require("../core/errors/openfortError.js"),a=require("../core/configuration/recovery.js"),i=require("./types.js"),o=require("../storage/istorage.js");exports.EmbeddedSigner=class{iframeManager;iframeConfiguration;storage;constructor(e,r,t){this.iframeManager=e,this.iframeConfiguration=r,this.storage=t}async sign(e,r,t){return await this.iframeManager.sign(this.iframeConfiguration,e,r,t)}async export(){return await this.iframeManager.export(this.iframeConfiguration)}async switchChain({chainId:r}){const t=await this.iframeManager.switchChain(this.iframeConfiguration,r);new e.Account(t.address,t.chainId,t.ownerAddress,t.accountType).save(this.storage)}async setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:r,encryptionSession:t}){await this.iframeManager.setEmbeddedRecovery(this.iframeConfiguration,e,r,t)}async logout(){await this.iframeManager.logout(),this.storage.remove(o.StorageKeys.RECOVERY),this.storage.remove(o.StorageKeys.SIGNER)}async updateAuthentication(){const e=await r.Authentication.fromStorage(this.storage);if(!e)throw new t.OpenfortError("Must provide authentication to update authentication",t.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const o=await a.Recovery.fromStorage(this.storage);if(!o)throw new t.OpenfortError("Must have recovery to update authentication",t.OpenfortErrorType.INVALID_CONFIGURATION);await this.iframeManager.updateAuthentication(this.iframeConfiguration,e.token,"openfort"===o.type?i.ShieldAuthType.OPENFORT:i.ShieldAuthType.CUSTOM)}};
1
+ "use strict";var e=require("../core/configuration/account.js"),r=require("../core/configuration/authentication.js"),t=require("../core/errors/openfortError.js"),a=require("../core/configuration/recovery.js"),i=require("./types.js"),o=require("../storage/istorage.js");exports.EmbeddedSigner=class{iframeManager;iframeConfiguration;storage;constructor(e,r,t){this.iframeManager=e,this.iframeConfiguration=r,this.storage=t}async sign(e,r,t){return await this.iframeManager.sign(this.iframeConfiguration,e,r,t)}async export(){return await this.iframeManager.export(this.iframeConfiguration)}async switchChain({chainId:r}){const t=await this.iframeManager.switchChain(this.iframeConfiguration,r);new e.Account(t.address,t.chainId,t.ownerAddress,t.accountType).save(this.storage)}async setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:r,encryptionSession:t}){await this.iframeManager.setEmbeddedRecovery(this.iframeConfiguration,e,r,t)}async logout(){await this.iframeManager.logout(),this.storage.remove(o.StorageKeys.RECOVERY)}async updateAuthentication(){const e=await r.Authentication.fromStorage(this.storage);if(!e)throw new t.OpenfortError("Must provide authentication to update authentication",t.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const o=await a.Recovery.fromStorage(this.storage);if(!o)throw new t.OpenfortError("Must have recovery to update authentication",t.OpenfortErrorType.INVALID_CONFIGURATION);await this.iframeManager.updateAuthentication(this.iframeConfiguration,e.token,"openfort"===o.type?i.ShieldAuthType.OPENFORT:i.ShieldAuthType.CUSTOM)}};
@@ -1 +1 @@
1
- "use strict";var e=require("../../core/configuration/authentication.js"),t=require("./types.js"),r=require("./JsonRpcError.js"),a=require("./signTypedDataV4.js"),i=require("../../types/types.js"),s=require("../../utils/typedEventEmitter.js"),o=require("../../utils/chains/index.js"),n=require("../../core/configuration/account.js"),c=require("../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"),w=require("./personalSign.js"),m=require("./estimateGas.js"),f=require("../../utils/crypto.js");exports.EvmProvider=class{#e;#t;#r;updatePolicy(e){this.#t=e}#a;#i;#s=null;#o;isOpenfort=!0;constructor({storage:e,backendApiClients:t,openfortEventEmitter:r,policyId:a,chains:o,validateAndRefreshSession:n}){this.#e=e,this.#r=o,this.#t=a,this.#a=n,this.#o=t,this.#o=t,this.#i=new s,r.on(i.OpenfortEvents.LOGGED_OUT,this.#n)}#n=async()=>{const e=!!await n.Account.fromStorage(this.#e),r=await c.SignerManager.fromStorage(this.#e);r?.logout(),this.#e.remove(h.StorageKeys.ACCOUNT),this.#e.remove(h.StorageKeys.AUTHENTICATION),this.#e.remove(h.StorageKeys.SIGNER),e&&this.#i.emit(t.ProviderEvent.ACCOUNTS_CHANGED,[])};async getRpcProvider(){if(!this.#s){const e=await n.Account.fromStorage(this.#e),t=e?.chainId||8453;await import("@ethersproject/providers").then(e=>{const r=this.#r?this.#r[t]:void 0;this.#s=new e.StaticJsonRpcProvider(r??o.defaultChainRpcs[t])})}if(!this.#s)throw new Error("RPC provider not initialized");return this.#s}async#c(i){switch(i.method){case"eth_accounts":{const e=await n.Account.fromStorage(this.#e);return e?[e.address]:[]}case"eth_requestAccounts":{let e=await n.Account.fromStorage(this.#e);if(e)return this.#i.emit(t.ProviderEvent.ACCOUNTS_CONNECT,{chainId:f.numberToHex(e.chainId)}),[e.address];if(!await c.SignerManager.fromStorage(this.#e))throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");if(await c.SignerManager.embedded(this.#e),e=await n.Account.fromStorage(this.#e),!e)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - no account available");return this.#i.emit(t.ProviderEvent.ACCOUNTS_CHANGED,[e.address]),[e.address]}case"eth_sendTransaction":{const t=await n.Account.fromStorage(this.#e),a=await c.SignerManager.fromStorage(this.#e),s=await e.Authentication.fromStorage(this.#e);if(!t||!a||!s)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await p.sendCalls({params:i.params||[],signer:a,account:t,authentication:s,backendClient:this.#o,policyId:this.#t})}case"eth_estimateGas":{const t=await n.Account.fromStorage(this.#e),a=await e.Authentication.fromStorage(this.#e);if(!t||!a)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await m.estimateGas({params:i.params||[],account:t,authentication:a,backendClient:this.#o,policyId:this.#t})}case"eth_signTypedData":case"eth_signTypedData_v4":{const e=await n.Account.fromStorage(this.#e),t=await c.SignerManager.fromStorage(this.#e);if(!e||!t)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#a();const s=await this.getRpcProvider();return await a.signTypedDataV4({method:i.method,params:i.params||[],signer:t,accountType:e.type,rpcProvider:s})}case"personal_sign":{const e=await n.Account.fromStorage(this.#e),t=await c.SignerManager.fromStorage(this.#e);if(!e||!t)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await w.personalSign({params:i.params||[],signer:t,account:e})}case"eth_chainId":{const e=await this.getRpcProvider(),{chainId:t}=await e.detectNetwork();return f.numberToHex(t)}case"wallet_switchEthereumChain":{const e=await c.SignerManager.fromStorage(this.#e);if(!e)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");if(!i.params||!Array.isArray(i.params)||0===i.params.length)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#a();try{const t=parseInt(i.params[0].chainId,16);await e.switchChain({chainId:t}),await import("@ethersproject/providers").then(e=>{const r=this.#r?this.#r[t]:void 0;this.#s=new e.StaticJsonRpcProvider(r??o.defaultChainRpcs[t])})}catch(e){throw new r.JsonRpcError(r.RpcErrorCode.INTERNAL_ERROR,"Failed to switch chain")}return null}case"wallet_addEthereumChain":{if(!await c.SignerManager.fromStorage(this.#e))throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");const e=await this.getRpcProvider();return await d.addEthereumChain({params:i.params||[],rpcProvider:e,storage:this.#e})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const t=await n.Account.fromStorage(this.#e),a=await c.SignerManager.fromStorage(this.#e),s=await e.Authentication.fromStorage(this.#e);if(!t||!a||!s)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await l.getCallStatus({params:i.params||{},authentication:s,backendClient:this.#o,account:t})}case"wallet_sendCalls":{const t=await n.Account.fromStorage(this.#e),a=await c.SignerManager.fromStorage(this.#e),s=await e.Authentication.fromStorage(this.#e);if(!t||!a||!s)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await p.sendCalls({params:i.params?i.params[0].calls:[],signer:a,account:t,authentication:s,backendClient:this.#o,policyId:this.#t})}case"wallet_grantPermissions":{const t=await n.Account.fromStorage(this.#e),a=await c.SignerManager.fromStorage(this.#e),s=await e.Authentication.fromStorage(this.#e);if(!t||!a||!s)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await u.registerSession({params:i.params||[],signer:a,account:t,authentication:s,backendClient:this.#o,policyId:this.#t})}case"wallet_revokePermissions":{const t=await n.Account.fromStorage(this.#e),a=await c.SignerManager.fromStorage(this.#e),s=await e.Authentication.fromStorage(this.#e);if(!t||!a||!s)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await g.revokeSession({params:i.params||[],signer:a,account:t,authentication:s,backendClient:this.#o})}case"wallet_getCapabilities":{const e=await this.getRpcProvider(),{chainId:t}=await e.detectNetwork();return{[f.numberToHex(t)]:{permissions:{supported:!0,signerTypes:["account","key"],keyTypes:["secp256k1"],permissionTypes:["contract-calls"]},paymasterService:{supported:!0},atomicBatch:{supported:!0}}}}case"eth_gasPrice":case"eth_getBalance":case"eth_getCode":case"eth_getStorageAt":case"eth_call":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":case"eth_getTransactionCount":return(await this.getRpcProvider()).send(i.method,i.params||[]);default:throw new r.JsonRpcError(r.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`)}}async request(e){try{return this.#c(e)}catch(e){if(e instanceof r.JsonRpcError)throw e;if(e instanceof Error)throw new r.JsonRpcError(r.RpcErrorCode.INTERNAL_ERROR,e.message);throw new r.JsonRpcError(r.RpcErrorCode.INTERNAL_ERROR,"Internal error")}}on(e,t){this.#i.on(e,t)}removeListener(e,t){this.#i.off(e,t)}};
1
+ "use strict";var e=require("../../core/configuration/authentication.js"),t=require("./types.js"),r=require("./JsonRpcError.js"),a=require("./signTypedDataV4.js"),i=require("../../types/types.js"),s=require("../../utils/typedEventEmitter.js"),o=require("../../utils/chains/index.js"),n=require("../../core/configuration/account.js"),c=require("../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"),w=require("./personalSign.js"),m=require("./estimateGas.js"),f=require("../../utils/crypto.js");exports.EvmProvider=class{#e;#t;#r;updatePolicy(e){this.#t=e}#a;#i;#s=null;#o;isOpenfort=!0;constructor({storage:e,backendApiClients:t,openfortEventEmitter:r,policyId:a,chains:o,validateAndRefreshSession:n}){this.#e=e,this.#r=o,this.#t=a,this.#a=n,this.#o=t,this.#o=t,this.#i=new s,r.on(i.OpenfortEvents.LOGGED_OUT,this.#n)}#n=async()=>{const e=!!await n.Account.fromStorage(this.#e),r=await c.SignerManager.fromStorage(this.#e);r?.logout(),this.#e.remove(h.StorageKeys.ACCOUNT),this.#e.remove(h.StorageKeys.AUTHENTICATION),e&&this.#i.emit(t.ProviderEvent.ACCOUNTS_CHANGED,[])};async getRpcProvider(){if(!this.#s){const e=await n.Account.fromStorage(this.#e),t=e?.chainId||8453;await import("@ethersproject/providers").then(e=>{const r=this.#r?this.#r[t]:void 0;this.#s=new e.StaticJsonRpcProvider(r??o.defaultChainRpcs[t])})}if(!this.#s)throw new Error("RPC provider not initialized");return this.#s}async#c(i){switch(i.method){case"eth_accounts":{const e=await n.Account.fromStorage(this.#e);return e?[e.address]:[]}case"eth_requestAccounts":{let e=await n.Account.fromStorage(this.#e);if(e)return this.#i.emit(t.ProviderEvent.ACCOUNTS_CONNECT,{chainId:f.numberToHex(e.chainId)}),[e.address];if(!await c.SignerManager.fromStorage(this.#e))throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");if(await c.SignerManager.embedded(this.#e),e=await n.Account.fromStorage(this.#e),!e)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - no account available");return this.#i.emit(t.ProviderEvent.ACCOUNTS_CHANGED,[e.address]),[e.address]}case"eth_sendTransaction":{const t=await n.Account.fromStorage(this.#e),a=await c.SignerManager.fromStorage(this.#e),s=await e.Authentication.fromStorage(this.#e);if(!t||!a||!s)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await p.sendCalls({params:i.params||[],signer:a,account:t,authentication:s,backendClient:this.#o,policyId:this.#t})}case"eth_estimateGas":{const t=await n.Account.fromStorage(this.#e),a=await e.Authentication.fromStorage(this.#e);if(!t||!a)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await m.estimateGas({params:i.params||[],account:t,authentication:a,backendClient:this.#o,policyId:this.#t})}case"eth_signTypedData":case"eth_signTypedData_v4":{const e=await n.Account.fromStorage(this.#e),t=await c.SignerManager.fromStorage(this.#e);if(!e||!t)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#a();const s=await this.getRpcProvider();return await a.signTypedDataV4({method:i.method,params:i.params||[],signer:t,accountType:e.type,rpcProvider:s})}case"personal_sign":{const e=await n.Account.fromStorage(this.#e),t=await c.SignerManager.fromStorage(this.#e);if(!e||!t)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await w.personalSign({params:i.params||[],signer:t,account:e})}case"eth_chainId":{const e=await this.getRpcProvider(),{chainId:t}=await e.detectNetwork();return f.numberToHex(t)}case"wallet_switchEthereumChain":{const e=await c.SignerManager.fromStorage(this.#e);if(!e)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");if(!i.params||!Array.isArray(i.params)||0===i.params.length)throw new r.JsonRpcError(r.RpcErrorCode.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#a();try{const t=parseInt(i.params[0].chainId,16);await e.switchChain({chainId:t}),await import("@ethersproject/providers").then(e=>{const r=this.#r?this.#r[t]:void 0;this.#s=new e.StaticJsonRpcProvider(r??o.defaultChainRpcs[t])})}catch(e){throw new r.JsonRpcError(r.RpcErrorCode.INTERNAL_ERROR,"Failed to switch chain")}return null}case"wallet_addEthereumChain":{if(!await c.SignerManager.fromStorage(this.#e))throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");const e=await this.getRpcProvider();return await d.addEthereumChain({params:i.params||[],rpcProvider:e,storage:this.#e})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const t=await n.Account.fromStorage(this.#e),a=await c.SignerManager.fromStorage(this.#e),s=await e.Authentication.fromStorage(this.#e);if(!t||!a||!s)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await l.getCallStatus({params:i.params||{},authentication:s,backendClient:this.#o,account:t})}case"wallet_sendCalls":{const t=await n.Account.fromStorage(this.#e),a=await c.SignerManager.fromStorage(this.#e),s=await e.Authentication.fromStorage(this.#e);if(!t||!a||!s)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await p.sendCalls({params:i.params?i.params[0].calls:[],signer:a,account:t,authentication:s,backendClient:this.#o,policyId:this.#t})}case"wallet_grantPermissions":{const t=await n.Account.fromStorage(this.#e),a=await c.SignerManager.fromStorage(this.#e),s=await e.Authentication.fromStorage(this.#e);if(!t||!a||!s)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await u.registerSession({params:i.params||[],signer:a,account:t,authentication:s,backendClient:this.#o,policyId:this.#t})}case"wallet_revokePermissions":{const t=await n.Account.fromStorage(this.#e),a=await c.SignerManager.fromStorage(this.#e),s=await e.Authentication.fromStorage(this.#e);if(!t||!a||!s)throw new r.JsonRpcError(r.ProviderErrorCode.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#a(),await g.revokeSession({params:i.params||[],signer:a,account:t,authentication:s,backendClient:this.#o})}case"wallet_getCapabilities":{const e=await this.getRpcProvider(),{chainId:t}=await e.detectNetwork();return{[f.numberToHex(t)]:{permissions:{supported:!0,signerTypes:["account","key"],keyTypes:["secp256k1"],permissionTypes:["contract-calls"]},paymasterService:{supported:!0},atomicBatch:{supported:!0}}}}case"eth_gasPrice":case"eth_getBalance":case"eth_getCode":case"eth_getStorageAt":case"eth_call":case"eth_blockNumber":case"eth_getBlockByHash":case"eth_getBlockByNumber":case"eth_getTransactionByHash":case"eth_getTransactionReceipt":case"eth_getTransactionCount":return(await this.getRpcProvider()).send(i.method,i.params||[]);default:throw new r.JsonRpcError(r.ProviderErrorCode.UNSUPPORTED_METHOD,`${i.method}: Method not supported`)}}async request(e){try{return this.#c(e)}catch(e){if(e instanceof r.JsonRpcError)throw e;if(e instanceof Error)throw new r.JsonRpcError(r.RpcErrorCode.INTERNAL_ERROR,e.message);throw new r.JsonRpcError(r.RpcErrorCode.INTERNAL_ERROR,"Internal error")}}on(e,t){this.#i.on(e,t)}removeListener(e,t){this.#i.off(e,t)}};
@@ -1 +1 @@
1
- "use strict";var e=require("penpal"),r=require("../storage/istorage.js"),o=require("../utils/crypto.js"),t=require("../core/errors/openfortError.js"),n=require("./types.js");class i extends Error{constructor(){super("This embedded signer requires a password to be recovered")}}class s extends Error{constructor(){super("MissingProjectEntropyError")}}class a extends Error{constructor(){super("Wrong recovery password for this embedded signer")}}class d extends Error{message;constructor(e){super(`Unknown response from iframe: ${e}`),this.message=e||""}}class c extends Error{constructor(){super("Not configured")}}class h{iframe;connection;remote;storage;sdkConfiguration;isInitialized=!1;constructor(e,r){if(!e)throw new t.OpenfortError("Configuration is required for IframeManager",t.OpenfortErrorType.INVALID_CONFIGURATION);if(!r)throw new t.OpenfortError("Storage is required for IframeManager",t.OpenfortErrorType.INVALID_CONFIGURATION);this.sdkConfiguration=e,this.storage=r}async iframeSetup(){if("undefined"==typeof document)throw new t.OpenfortError("Document is not available. Please provide a message poster for non-browser environments.",t.OpenfortErrorType.INVALID_CONFIGURATION);const e=document.getElementById("openfort-iframe");e&&document.body.removeChild(e);const r=document.createElement("iframe");r.style.display="none",r.id="openfort-iframe",document.body.appendChild(r),r.src=this.sdkConfiguration.iframeUrl,this.iframe=r,await new Promise((e,o)=>{const t=setTimeout(()=>{o(new Error("Iframe load timeout"))},2e3);r.onload=()=>{clearTimeout(t),e()},r.onerror=()=>{clearTimeout(t),o(new Error("Failed to load iframe"))}})}async establishIframeConnection(){if("undefined"==typeof document)throw new t.OpenfortError("Document is not available.",t.OpenfortErrorType.INVALID_CONFIGURATION);if(!this.iframe?.contentWindow)throw new t.OpenfortError("Iframe does not have content window",t.OpenfortErrorType.INVALID_CONFIGURATION);const r=new URL(this.sdkConfiguration.iframeUrl).origin,o=new e.WindowMessenger({remoteWindow:this.iframe.contentWindow,allowedOrigins:[r]});this.connection=e.connect({messenger:o,timeout:5e3});try{this.remote=await this.connection.promise,this.isInitialized=!0}catch(e){const r=e;throw new Error(`v3 Failed to establish Iframe connection: ${r.cause||r.message}`,r)}}isLoaded(){return this.isInitialized&&void 0!==this.remote}async ensureConnection(){if(!this.isLoaded()){if("undefined"==typeof document)throw new t.OpenfortError("Document is not available.",t.OpenfortErrorType.INVALID_CONFIGURATION);await this.iframeSetup(),await this.establishIframeConnection()}if(!this.remote)throw new Error("Failed to establish connection with iframe");return this.remote}static handleError(e){if(n.isErrorResponse(e)){if(e.error===n.NOT_CONFIGURED_ERROR)throw new c;if(e.error===n.MISSING_USER_ENTROPY_ERROR)throw new i;if(e.error===n.MISSING_PROJECT_ENTROPY_ERROR)throw new s;if(e.error===n.INCORRECT_USER_ENTROPY_ERROR)throw new a;throw new d(e.error)}throw e}async configure(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const t=await this.ensureConnection(),s={uuid:o.randomUUID(),action:n.Event.CONFIGURE,chainId:e.chainId,recovery:e.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:e.accessToken,playerID:e.playerID,thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,encryptionKey:e.password,encryptionPart:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??null,encryptionSession:e.recovery?.encryptionSession??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl};try{const e=await t.configure(s);return n.isErrorResponse(e)&&h.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){throw(e instanceof a||e instanceof i)&&this.storage.remove(r.StorageKeys.SIGNER),e}}async sign(e,r,t,i){const s=await this.ensureConnection(),a={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},d=new n.SignRequest(o.randomUUID(),r,t,i,a);try{const e=await s.sign(d);return n.isErrorResponse(e)&&h.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e.signature}catch(o){if(o instanceof c)return await this.configure(e),this.sign(e,r,t,i);throw o}}async switchChain(e,r){const t=await this.ensureConnection(),i={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},s=new n.SwitchChainRequest(o.randomUUID(),r,i);try{const e=await t.switchChain(s);return n.isErrorResponse(e)&&h.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(o){if(o instanceof c)return await this.configure(e),this.switchChain(e,r);throw o}}async export(e){const r=await this.ensureConnection(),t={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},i=new n.ExportPrivateKeyRequest(o.randomUUID(),t);try{const e=await r.export(i);return n.isErrorResponse(e)&&h.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e.key}catch(r){if(r instanceof c)return await this.configure(e),this.export(e);throw r}}async setEmbeddedRecovery(e,r,t,i){const s=await this.ensureConnection(),a={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},d=new n.SetRecoveryMethodRequest(o.randomUUID(),r,t,i,a);try{const e=await s.setRecoveryMethod(d);n.isErrorResponse(e)&&h.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined")}catch(o){if(o instanceof c)return await this.configure(e),this.setEmbeddedRecovery(e,r,t,i);throw o}}async getCurrentUser(e){const r=await this.ensureConnection(),t=new n.GetCurrentDeviceRequest(o.randomUUID(),e);try{const e=await r.getCurrentDevice(t);return n.isErrorResponse(e)&&h.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof c)return null;throw e}}async logout(){const e=await this.ensureConnection(),r={uuid:o.randomUUID()};await e.logout(r)}async updateAuthentication(e,r,t){const i={...e};i.accessToken=r,t===n.ShieldAuthType.OPENFORT&&i.recovery&&(i.recovery={...i.recovery,token:r});const s=await this.ensureConnection(),a=new n.UpdateAuthenticationRequest(o.randomUUID(),r);try{await s.updateAuthentication(a)}catch(e){if(e instanceof c)return await this.configure(i),void await this.updateAuthentication(i,r,t);throw e}}destroy(){if(this.connection&&(this.connection.destroy(),this.connection=void 0),this.remote=void 0,this.isInitialized=!1,this.iframe&&"undefined"!=typeof document){const e=document.getElementById("openfort-iframe");e&&e.parentNode&&e.parentNode.removeChild(e),this.iframe=void 0}}}exports.IframeManager=h,exports.MissingProjectEntropyError=s,exports.MissingRecoveryPasswordError=i,exports.NotConfiguredError=c,exports.UnknownResponseError=d,exports.WrongRecoveryPasswordError=a;
1
+ "use strict";var e=require("../../../node_modules/penpal/dist/penpal.js"),r=require("../utils/crypto.js"),o=require("../core/errors/openfortError.js"),t=require("./types.js");class n extends Error{constructor(){super("This embedded signer requires a password to be recovered")}}class i extends Error{constructor(){super("MissingProjectEntropyError")}}class s extends Error{constructor(){super("Wrong recovery password for this embedded signer")}}class a extends Error{message;constructor(e){super(`Unknown response from iframe: ${e}`),this.message=e||""}}class d extends Error{constructor(){super("Not configured")}}class c{iframe;connection;remote;storage;sdkConfiguration;isInitialized=!1;constructor(e,r){if(!e)throw new o.OpenfortError("Configuration is required for IframeManager",o.OpenfortErrorType.INVALID_CONFIGURATION);if(!r)throw new o.OpenfortError("Storage is required for IframeManager",o.OpenfortErrorType.INVALID_CONFIGURATION);this.sdkConfiguration=e,this.storage=r}async iframeSetup(){if("undefined"==typeof document)throw new o.OpenfortError("Document is not available. Please provide a message poster for non-browser environments.",o.OpenfortErrorType.INVALID_CONFIGURATION);const e=document.getElementById("openfort-iframe");e&&document.body.removeChild(e);const r=document.createElement("iframe");r.style.display="none",r.id="openfort-iframe",document.body.appendChild(r),r.src=this.sdkConfiguration.iframeUrl,this.iframe=r,await new Promise((e,o)=>{const t=setTimeout(()=>{o(new Error("Iframe load timeout"))},1e4);r.onload=()=>{clearTimeout(t),e()},r.onerror=()=>{clearTimeout(t),o(new Error("Failed to load iframe"))}})}async establishIframeConnection(){if("undefined"==typeof document)throw new o.OpenfortError("Document is not available.",o.OpenfortErrorType.INVALID_CONFIGURATION);if(!this.iframe?.contentWindow)throw new o.OpenfortError("Iframe does not have content window",o.OpenfortErrorType.INVALID_CONFIGURATION);const r=new URL(this.sdkConfiguration.iframeUrl).origin,t=new e.WindowMessenger({remoteWindow:this.iframe.contentWindow,allowedOrigins:[r]});this.connection=e.connect({messenger:t,timeout:5e3});try{this.remote=await this.connection.promise,this.isInitialized=!0}catch(e){const r=e;throw new Error(`v3 Failed to establish Iframe connection: ${r.cause||r.message}`,r)}}isLoaded(){return this.isInitialized&&void 0!==this.remote}async ensureConnection(){if(!this.isLoaded()){if("undefined"==typeof document)throw new o.OpenfortError("Document is not available.",o.OpenfortErrorType.INVALID_CONFIGURATION);await this.iframeSetup(),await this.establishIframeConnection()}if(!this.remote)throw new Error("Failed to establish connection with iframe");return this.remote}static handleError(e){if(t.isErrorResponse(e)){if(e.error===t.NOT_CONFIGURED_ERROR)throw new d;if(e.error===t.MISSING_USER_ENTROPY_ERROR)throw new n;if(e.error===t.MISSING_PROJECT_ENTROPY_ERROR)throw new i;if(e.error===t.INCORRECT_USER_ENTROPY_ERROR)throw new s;throw new a(e.error)}throw e}async configure(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const o=await this.ensureConnection(),n={uuid:r.randomUUID(),action:t.Event.CONFIGURE,chainId:e.chainId,recovery:e.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:e.accessToken,playerID:e.playerID,thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,encryptionKey:e.password,encryptionPart:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??null,encryptionSession:e.recovery?.encryptionSession??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl},i=await o.configure(n);return t.isErrorResponse(i)&&c.handleError(i),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",i.version??"undefined"),i}async sign(e,o,n,i){const s=await this.ensureConnection(),a={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},h=new t.SignRequest(r.randomUUID(),o,n,i,a);try{const e=await s.sign(h);return t.isErrorResponse(e)&&c.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e.signature}catch(r){if(r instanceof d)return await this.configure(e),this.sign(e,o,n,i);throw r}}async switchChain(e,o){const n=await this.ensureConnection(),i={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},s=new t.SwitchChainRequest(r.randomUUID(),o,i);try{const e=await n.switchChain(s);return t.isErrorResponse(e)&&c.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(r){if(r instanceof d)return await this.configure(e),this.switchChain(e,o);throw r}}async export(e){const o=await this.ensureConnection(),n={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},i=new t.ExportPrivateKeyRequest(r.randomUUID(),n);try{const e=await o.export(i);return t.isErrorResponse(e)&&c.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e.key}catch(r){if(r instanceof d)return await this.configure(e),this.export(e);throw r}}async setEmbeddedRecovery(e,o,n,i){const s=await this.ensureConnection(),a={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},h=new t.SetRecoveryMethodRequest(r.randomUUID(),o,n,i,a);try{const e=await s.setRecoveryMethod(h);t.isErrorResponse(e)&&c.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined")}catch(r){if(r instanceof d)return await this.configure(e),this.setEmbeddedRecovery(e,o,n,i);throw r}}async getCurrentUser(e){const o=await this.ensureConnection(),n=new t.GetCurrentDeviceRequest(r.randomUUID(),e);try{const e=await o.getCurrentDevice(n);return t.isErrorResponse(e)&&c.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof d)return null;throw e}}async logout(){const e=await this.ensureConnection(),o={uuid:r.randomUUID()};await e.logout(o)}async updateAuthentication(e,o,n){const i={...e};i.accessToken=o,n===t.ShieldAuthType.OPENFORT&&i.recovery&&(i.recovery={...i.recovery,token:o});const s=await this.ensureConnection(),a=new t.UpdateAuthenticationRequest(r.randomUUID(),o);try{await s.updateAuthentication(a)}catch(e){if(e instanceof d)return await this.configure(i),void await this.updateAuthentication(i,o,n);throw e}}destroy(){if(this.connection&&(this.connection.destroy(),this.connection=void 0),this.remote=void 0,this.isInitialized=!1,this.iframe&&"undefined"!=typeof document){const e=document.getElementById("openfort-iframe");e&&e.parentNode&&e.parentNode.removeChild(e),this.iframe=void 0}}}exports.IframeManager=c,exports.MissingProjectEntropyError=i,exports.MissingRecoveryPasswordError=n,exports.NotConfiguredError=d,exports.UnknownResponseError=a,exports.WrongRecoveryPasswordError=s;
@@ -1 +1 @@
1
- "use strict";var e=require("../core/config/config.js"),r=require("../storage/istorage.js"),t=require("./iframeManager.js"),o=require("../core/configuration/authentication.js"),n=require("../core/errors/openfortError.js"),a=require("./types.js"),i=require("../core/configuration/recovery.js"),s=require("./embedded.js"),c=require("../core/configuration/account.js");const u=new WeakMap;exports.SignerManager=class{static async fromStorage(e){if(!e)throw new n.OpenfortError("Storage is required",n.OpenfortErrorType.INVALID_CONFIGURATION);const t=await e.get(r.StorageKeys.SIGNER);if(!t)return null;const o=JSON.parse(t);return"embedded"===o.type?this.embeddedFromStorage(e,o.chainId):null}static async embeddedFromStorage(e,r){const t=this.getIframeManager(e),a=await o.Authentication.fromStorage(e);if(!a)throw new n.OpenfortError("Must be authenticated to create a signer",n.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const c=await i.Recovery.fromStorage(e);if(!c)throw new n.OpenfortError("Must have recovery to create a signer",n.OpenfortErrorType.INVALID_CONFIGURATION);const u={thirdPartyTokenType:a.thirdPartyTokenType??null,thirdPartyProvider:a.thirdPartyProvider??null,accessToken:a.token,playerID:a.player,recovery:this.shieldAuthentication(e,c,a,null),chainId:r,password:null};return new s.EmbeddedSigner(t,u,e)}static getIframeManager(r){const o=u.get(r);if(o)return o;const a=e.SDKConfiguration.fromStorage();if(!a)throw new n.OpenfortError("Must be configured to create a signer",n.OpenfortErrorType.INVALID_CONFIGURATION);const i=new t.IframeManager(a,r);return u.set(r,i),i}static async embedded(e,t=null,a=null,u=null,d=null){if(!e)throw new n.OpenfortError("Storage is required",n.OpenfortErrorType.INVALID_CONFIGURATION);const y=this.getIframeManager(e);let p;try{p=await o.Authentication.fromStorage(e)}catch(e){throw new n.OpenfortError("Failed to access authentication storage",n.OpenfortErrorType.INVALID_CONFIGURATION)}if(!p)throw new n.OpenfortError("Must be authenticated to create a signer",n.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const f=await i.Recovery.fromStorage(e),h=u||f?.type||"openfort",g=d||f?.customToken,l=new i.Recovery(h,g),I=this.shieldAuthentication(e,l,p,a),O={thirdPartyTokenType:p.thirdPartyTokenType??null,thirdPartyProvider:p.thirdPartyProvider??null,accessToken:p.token,playerID:p.player,recovery:I,chainId:t,password:a?.recoveryPassword||null},T={type:"embedded",chainId:t},w=await y.configure(O);return e.save(r.StorageKeys.SIGNER,JSON.stringify(T)),new c.Account(w.address,w.chainId,w.ownerAddress,w.accountType).save(e),new s.EmbeddedSigner(y,O,e)}static shieldAuthentication(e,r,t,o){let s=null;if("openfort"===r.type)s={auth:a.ShieldAuthType.OPENFORT,authProvider:t.thirdPartyProvider||void 0,token:t.token,tokenType:t.thirdPartyTokenType||void 0,encryptionSession:o?.encryptionSession||void 0},new i.Recovery("openfort").save(e);else if("custom"===r.type){if(!r.customToken)throw new n.OpenfortError("Custom recovery requires a token",n.OpenfortErrorType.INVALID_CONFIGURATION);s={auth:a.ShieldAuthType.CUSTOM,token:r.customToken},new i.Recovery("custom",r.customToken).save(e)}return s}};
1
+ "use strict";var e=require("../core/config/config.js"),r=require("../storage/istorage.js"),t=require("./iframeManager.js"),o=require("../core/configuration/authentication.js"),n=require("../core/errors/openfortError.js"),a=require("./types.js"),i=require("../core/configuration/recovery.js"),s=require("./embedded.js"),c=require("../core/configuration/account.js");const u=new WeakMap;exports.SignerManager=class{static async fromStorage(e){if(!e)throw new n.OpenfortError("Storage is required",n.OpenfortErrorType.INVALID_CONFIGURATION);const t=await e.get(r.StorageKeys.ACCOUNT);if(!t)return null;const o=JSON.parse(t);return this.embeddedFromStorage(e,o.chainId)}static async embeddedFromStorage(e,r){const t=this.getIframeManager(e),a=await o.Authentication.fromStorage(e);if(!a)throw new n.OpenfortError("Must be authenticated to create a signer",n.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const c=await i.Recovery.fromStorage(e);if(!c)throw new n.OpenfortError("Must have recovery to create a signer",n.OpenfortErrorType.INVALID_CONFIGURATION);const u={thirdPartyTokenType:a.thirdPartyTokenType??null,thirdPartyProvider:a.thirdPartyProvider??null,accessToken:a.token,playerID:a.player,recovery:this.shieldAuthentication(e,c,a,null),chainId:r,password:null};return new s.EmbeddedSigner(t,u,e)}static getIframeManager(r){const o=u.get(r);if(o)return o;const a=e.SDKConfiguration.fromStorage();if(!a)throw new n.OpenfortError("Must be configured to create a signer",n.OpenfortErrorType.INVALID_CONFIGURATION);const i=new t.IframeManager(a,r);return u.set(r,i),i}static async embedded(e,r=null,t=null,a=null,u=null){if(!e)throw new n.OpenfortError("Storage is required",n.OpenfortErrorType.INVALID_CONFIGURATION);const d=this.getIframeManager(e);let y;try{y=await o.Authentication.fromStorage(e)}catch(e){throw new n.OpenfortError("Failed to access authentication storage",n.OpenfortErrorType.INVALID_CONFIGURATION)}if(!y)throw new n.OpenfortError("Must be authenticated to create a signer",n.OpenfortErrorType.NOT_LOGGED_IN_ERROR);const p=await i.Recovery.fromStorage(e),f=a||p?.type||"openfort",h=u||p?.customToken,g=new i.Recovery(f,h),l=this.shieldAuthentication(e,g,y,t),O={thirdPartyTokenType:y.thirdPartyTokenType??null,thirdPartyProvider:y.thirdPartyProvider??null,accessToken:y.token,playerID:y.player,recovery:l,chainId:r,password:t?.recoveryPassword||null},T=await d.configure(O);return new c.Account(T.address,T.chainId,T.ownerAddress,T.accountType).save(e),new s.EmbeddedSigner(d,O,e)}static shieldAuthentication(e,r,t,o){let s=null;if("openfort"===r.type)s={auth:a.ShieldAuthType.OPENFORT,authProvider:t.thirdPartyProvider||void 0,token:t.token,tokenType:t.thirdPartyTokenType||void 0,encryptionSession:o?.encryptionSession||void 0},new i.Recovery("openfort").save(e);else if("custom"===r.type){if(!r.customToken)throw new n.OpenfortError("Custom recovery requires a token",n.OpenfortErrorType.INVALID_CONFIGURATION);s={auth:a.ShieldAuthType.CUSTOM,token:r.customToken},new i.Recovery("custom",r.customToken).save(e)}return s}};
@@ -0,0 +1 @@
1
+ var e=class extends Error{code;constructor(e,t){super(t),this.name="PenpalError",this.code=e}},t=t=>({name:t.name,message:t.message,stack:t.stack,penpalCode:t instanceof e?t.code:void 0}),s=Symbol("Reply"),n=class{value;transferables;#e=s;constructor(e,t){this.value=e,this.transferables=t?.transferables}},r="penpal",a=e=>"object"==typeof e&&null!==e,o=e=>"function"==typeof e,i=e=>"SYN"===e.type,l=e=>"ACK1"===e.type,d=e=>"ACK2"===e.type,c=e=>"CALL"===e.type,h=e=>"REPLY"===e.type,g=(e,t=[])=>{const s=[];for(const n of Object.keys(e)){const r=e[n];o(r)?s.push([...t,n]):a(r)&&s.push(...g(r,[...t,n]))}return s},m=e=>e.join("."),p=(e,s,n)=>({namespace:r,channel:e,type:"REPLY",callId:s,isError:!0,...n instanceof Error?{value:t(n),isSerializedErrorInstance:!0}:{value:n}}),u=(t,s,i,l)=>{let d=!1;const h=async h=>{if(d)return;if(!c(h))return;l?.(`Received ${m(h.methodPath)}() call`,h);const{methodPath:g,args:u,id:f}=h;let w,v;try{const t=((e,t)=>{const s=e.reduce((e,t)=>a(e)?e[t]:void 0,t);return o(s)?s:void 0})(g,s);if(!t)throw new e("METHOD_NOT_FOUND",`Method \`${m(g)}\` is not found.`);let l=await t(...u);l instanceof n&&(v=l.transferables,l=await l.value),w={namespace:r,channel:i,type:"REPLY",callId:f,value:l}}catch(e){w=p(i,f,e)}if(!d)try{l?.(`Sending ${m(g)}() reply`,w),t.sendMessage(w,v)}catch(e){throw"DataCloneError"===e.name&&(w=p(i,f,e),l?.(`Sending ${m(g)}() reply`,w),t.sendMessage(w)),e}};return t.addMessageHandler(h),()=>{d=!0,t.removeMessageHandler(h)}},f=crypto.randomUUID?.bind(crypto)??(()=>new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")),w=Symbol("CallOptions"),v=class{transferables;timeout;#e=w;constructor(e){this.transferables=e?.transferables,this.timeout=e?.timeout}},y=new Set(["apply","call","bind"]),M=(e,t,s=[])=>new Proxy(s.length?()=>{}:Object.create(null),{get(n,r){if("then"!==r)return s.length&&y.has(r)?Reflect.get(n,r):M(e,t,[...s,r])},apply:(t,n,r)=>e(s,r)}),E=t=>new e("CONNECTION_DESTROYED",`Method call ${m(t)}() failed due to destroyed connection`),I=(t,s,n)=>{let a=!1;const o=new Map,i=t=>{if(!h(t))return;const{callId:s,value:r,isError:a,isSerializedErrorInstance:i}=t,l=o.get(s);l&&(o.delete(s),n?.(`Received ${m(l.methodPath)}() call`,t),a?l.reject(i?(({name:t,message:s,stack:n,penpalCode:r})=>{const a=r?new e(r,s):new Error(s);return a.name=t,a.stack=n,a})(r):r):l.resolve(r))};t.addMessageHandler(i);return{remoteProxy:M((i,l)=>{if(a)throw E(i);const d=f(),c=l[l.length-1],h=c instanceof v,{timeout:g,transferables:p}=h?c:{},u=h?l.slice(0,-1):l;return new Promise((a,l)=>{const c=void 0!==g?window.setTimeout(()=>{o.delete(d),l(new e("METHOD_CALL_TIMEOUT",`Method call ${m(i)}() timed out after ${g}ms`))},g):void 0;o.set(d,{methodPath:i,resolve:a,reject:l,timeoutId:c});try{const e={namespace:r,channel:s,type:"CALL",id:d,methodPath:i,args:u};n?.(`Sending ${m(i)}() call`,e),t.sendMessage(e,p)}catch(t){l(new e("TRANSMISSION_FAILED",t.message))}})},n),destroy:()=>{a=!0,t.removeMessageHandler(i);for(const{methodPath:e,reject:t,timeoutId:s}of o.values())clearTimeout(s),t(E(e));o.clear()}}},O=()=>{let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}},S=class extends Error{constructor(e){super(`You've hit a bug in Penpal. Please file an issue with the following information: ${e}`)}},P="deprecated-penpal",R=e=>e.join("."),C=e=>new S(`Unexpected message to translate: ${JSON.stringify(e)}`),A=({messenger:t,methods:s,timeout:n,channel:a,log:o})=>{const c=f();let h;const m=[];let p=!1;const w=g(s),{promise:v,resolve:y,reject:M}=O(),E=void 0!==n?setTimeout(()=>{M(new e("CONNECTION_TIMEOUT",`Connection timed out after ${n}ms`))},n):void 0,S=()=>{for(const e of m)e()},R=()=>{if(p)return;m.push(u(t,s,a,o));const{remoteProxy:e,destroy:n}=I(t,a,o);m.push(n),clearTimeout(E),p=!0,y({remoteProxy:e,destroy:S})},C=()=>{const s={namespace:r,type:"SYN",channel:a,participantId:c};o?.("Sending handshake SYN",s);try{t.sendMessage(s)}catch(t){M(new e("TRANSMISSION_FAILED",t.message))}},A=s=>{i(s)&&(s=>{if(o?.("Received handshake SYN",s),s.participantId===h&&h!==P)return;if(h=s.participantId,C(),!(c>h||h===P))return;const n={namespace:r,channel:a,type:"ACK1",methodPaths:w};o?.("Sending handshake ACK1",n);try{t.sendMessage(n)}catch(t){return void M(new e("TRANSMISSION_FAILED",t.message))}})(s),l(s)&&(s=>{o?.("Received handshake ACK1",s);const n={namespace:r,channel:a,type:"ACK2"};o?.("Sending handshake ACK2",n);try{t.sendMessage(n)}catch(t){return void M(new e("TRANSMISSION_FAILED",t.message))}R()})(s),d(s)&&(e=>{o?.("Received handshake ACK2",e),R()})(s)};return t.addMessageHandler(A),m.push(()=>t.removeMessageHandler(A)),C(),v},N=e=>{let t,s=!1;return(...n)=>(s||(s=!0,t=e(...n)),t)},b=new WeakSet,L=({messenger:t,methods:s={},timeout:n,channel:o,log:i})=>{if(!t)throw new e("INVALID_ARGUMENT","messenger must be defined");if(b.has(t))throw new e("INVALID_ARGUMENT","A messenger can only be used for a single connection");b.add(t);const l=[t.destroy],d=N(e=>{if(e){const e={namespace:r,channel:o,type:"DESTROY"};try{t.sendMessage(e)}catch(e){}}for(const e of l)e();i?.("Connection destroyed")}),c=e=>(e=>a(e)&&e.namespace===r)(e)&&e.channel===o;return{promise:(async()=>{try{t.initialize({log:i,validateReceivedMessage:c}),t.addMessageHandler(e=>{(e=>"DESTROY"===e.type)(e)&&d(!1)});const{remoteProxy:e,destroy:r}=await A({messenger:t,methods:s,timeout:n,channel:o,log:i});return l.push(r),e}catch(e){throw d(!0),e}})(),destroy:()=>{d(!0)}}},T=class{#t;#s;#n;#r;#a;#o=new Set;#i;#l=!1;constructor({remoteWindow:t,allowedOrigins:s}){if(!t)throw new e("INVALID_ARGUMENT","remoteWindow must be defined");this.#t=t,this.#s=s?.length?s:[window.origin]}initialize=({log:e,validateReceivedMessage:t})=>{this.#n=e,this.#r=t,window.addEventListener("message",this.#d)};sendMessage=(e,t)=>{if(i(e)){const s=this.#c(e);return void this.#t.postMessage(e,{targetOrigin:s,transfer:t})}if(l(e)||this.#l){const s=this.#l?(e=>{if(l(e))return{penpal:"synAck",methodNames:e.methodPaths.map(R)};if(c(e))return{penpal:"call",id:e.id,methodName:R(e.methodPath),args:e.args};if(h(e))return e.isError?{penpal:"reply",id:e.callId,resolution:"rejected",...e.isSerializedErrorInstance?{returnValue:e.value,returnValueIsError:!0}:{returnValue:e.value}}:{penpal:"reply",id:e.callId,resolution:"fulfilled",returnValue:e.value};throw C(e)})(e):e,n=this.#c(e);return void this.#t.postMessage(s,{targetOrigin:n,transfer:t})}if(d(e)){const{port1:s,port2:n}=new MessageChannel;this.#i=s,s.addEventListener("message",this.#h),s.start();const r=[n,...t||[]],a=this.#c(e);return void this.#t.postMessage(e,{targetOrigin:a,transfer:r})}if(!this.#i)throw new S("Port is undefined");this.#i.postMessage(e,{transfer:t})};addMessageHandler=e=>{this.#o.add(e)};removeMessageHandler=e=>{this.#o.delete(e)};destroy=()=>{window.removeEventListener("message",this.#d),this.#g(),this.#o.clear()};#m=e=>this.#s.some(t=>t instanceof RegExp?t.test(e):t===e||"*"===t);#c=e=>{if(i(e))return"*";if(!this.#a)throw new S("Concrete remote origin not set");return"null"===this.#a&&this.#s.includes("*")?"*":this.#a};#g=()=>{this.#i?.removeEventListener("message",this.#h),this.#i?.close(),this.#i=void 0};#d=({source:e,origin:t,ports:s,data:n})=>{if(e===this.#t&&((e=>a(e)&&"penpal"in e)(n)&&(this.#n?.("Please upgrade the child window to the latest version of Penpal."),this.#l=!0,n=(e=>{if("syn"===e.penpal)return{namespace:r,channel:void 0,type:"SYN",participantId:P};if("ack"===e.penpal)return{namespace:r,channel:void 0,type:"ACK2"};if("call"===e.penpal)return{namespace:r,channel:void 0,type:"CALL",id:e.id,methodPath:(t=e.methodName,t.split(".")),args:e.args};var t;if("reply"===e.penpal)return"fulfilled"===e.resolution?{namespace:r,channel:void 0,type:"REPLY",callId:e.id,value:e.returnValue}:{namespace:r,channel:void 0,type:"REPLY",callId:e.id,isError:!0,...e.returnValueIsError?{value:e.returnValue,isSerializedErrorInstance:!0}:{value:e.returnValue}};throw C(e)})(n)),this.#r?.(n)))if(this.#m(t)){if(i(n)&&(this.#g(),this.#a=t),d(n)&&!this.#l){if(this.#i=s[0],!this.#i)throw new S("No port received on ACK2");this.#i.addEventListener("message",this.#h),this.#i.start()}for(const e of this.#o)e(n)}else this.#n?.(`Received a message from origin \`${t}\` which did not match allowed origins \`[${this.#s.join(", ")}]\``)};#h=({data:e})=>{if(this.#r?.(e))for(const t of this.#o)t(e)}};export{v as CallOptions,e as PenpalError,n as Reply,T as WindowMessenger,L as connect};
@@ -1 +1 @@
1
- import{StorageKeys as a}from"../storage/istorage.js";import{Authentication as t}from"../core/configuration/authentication.js";import{SignerManager as e}from"../wallets/signer.js";import{OpenfortError as i,OpenfortErrorType as r}from"../core/errors/openfortError.js";class s{storage;authManager;validateAndRefreshToken;ensureInitialized;constructor(a,t,e,i){this.storage=a,this.authManager=t,this.validateAndRefreshToken=e,this.ensureInitialized=i}async logInWithEmailPassword({email:a,password:e,ecosystemGame:i}){await this.ensureInitialized();const r=await t.fromStorage(this.storage),s=await this.authManager.loginEmailPassword(a,e,i);return"action"in s||(r&&r.player!==s.player.id&&await this.logout(),new t("jwt",s.token,s.player.id,s.refreshToken).save(this.storage)),s}async signUpGuest(){await this.ensureInitialized();const a=await t.fromStorage(this.storage),e=await this.authManager.registerGuest();return a&&a.player!==e.player.id&&await this.logout(),new t("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),e}async signUpWithEmailPassword({email:a,password:e,options:i,ecosystemGame:r}){await this.ensureInitialized();const s=await t.fromStorage(this.storage),n=await this.authManager.signupEmailPassword(a,e,i?.data.name,r);return"action"in n||(s&&s.player!==n.player.id&&await this.logout(),new t("jwt",n.token,n.player.id,n.refreshToken).save(this.storage)),n}async linkEmailPassword({email:a,password:t,authToken:e,ecosystemGame:i}){return await this.authManager.linkEmail(a,t,e,i)}async unlinkEmailPassword({email:a,authToken:t}){return await this.authManager.unlinkEmail(a,t)}async requestEmailVerification({email:a,redirectUrl:t}){await this.authManager.requestEmailVerification(a,t)}async resetPassword({email:a,password:t,state:e}){await this.authManager.resetPassword(a,t,e)}async requestResetPassword({email:a,redirectUrl:t}){await this.ensureInitialized(),await this.authManager.requestResetPassword(a,t)}async verifyEmail({email:a,state:t}){await this.authManager.verifyEmail(a,t)}async initOAuth({provider:a,options:t,ecosystemGame:e}){return await this.ensureInitialized(),await this.authManager.initOAuth(a,t,e)}async initLinkOAuth({provider:a,options:e,ecosystemGame:s}){const n=await t.fromStorage(this.storage);if(!n)throw new i("No authentication found",r.NOT_LOGGED_IN_ERROR);return await this.authManager.linkOAuth(n,a,e,s)}async linkThirdPartyProvider({provider:a,token:e,tokenType:s}){const n=await t.fromStorage(this.storage);if(!n)throw new i("No authentication found",r.NOT_LOGGED_IN_ERROR);return await this.authManager.linkThirdParty(n,a,e,s)}async unlinkOAuth({provider:a,authToken:t}){return await this.authManager.unlinkOAuth(a,t)}async poolOAuth(a){await this.ensureInitialized();const e=await t.fromStorage(this.storage),i=await this.authManager.poolOAuth(a);return e&&e.player!==i.player.id&&await this.logout(),new t("jwt",i.token,i.player.id,i.refreshToken).save(this.storage),i}async authenticateWithThirdPartyProvider({provider:a,token:e,tokenType:i,ecosystemGame:r}){await this.ensureInitialized();const s=await t.fromStorage(this.storage),n=await this.authManager.authenticateThirdParty(a,e,i,r);return s&&s.player!==n.id&&await this.logout(),new t("third_party",e,n.id,null,a,i).save(this.storage),n}async loginWithIdToken({provider:a,token:e,ecosystemGame:i}){await this.ensureInitialized();const r=await t.fromStorage(this.storage),s=await this.authManager.loginWithIdToken(a,e,i);return r&&r.player!==s.player.id&&await this.logout(),new t("jwt",s.token,s.player.id,s.refreshToken).save(this.storage),s}async initSIWE({address:a,ecosystemGame:t}){return await this.ensureInitialized(),await this.authManager.initSIWE(a,t)}async authenticateWithSIWE({signature:a,message:e,walletClientType:i,connectorType:r}){await this.ensureInitialized();const s=await t.fromStorage(this.storage),n=await this.authManager.authenticateSIWE(a,e,i,r);return s&&s.player!==n.player.id&&await this.logout(),new t("jwt",n.token,n.player.id,n.refreshToken).save(this.storage),n}async linkWallet({signature:a,message:t,walletClientType:e,connectorType:i,authToken:r}){return await this.authManager.linkWallet(a,t,e,i,r)}async unlinkWallet({address:a,authToken:t}){return await this.authManager.unlinkWallet(a,t)}async storeCredentials(a){if(await this.ensureInitialized(),!a.player)throw new i("Player ID is required to store credentials",r.INVALID_CONFIGURATION);new t("jwt",a.accessToken,a.player,a.refreshToken).save(this.storage)}async logout(){await this.ensureInitialized();const t=await e.fromStorage(this.storage);this.storage.remove(a.AUTHENTICATION),this.storage.remove(a.SIGNER),this.storage.remove(a.ACCOUNT),t&&await t.logout()}}export{s as AuthApi};
1
+ import{StorageKeys as a}from"../storage/istorage.js";import{Authentication as t}from"../core/configuration/authentication.js";import{SignerManager as e}from"../wallets/signer.js";import{OpenfortError as i,OpenfortErrorType as r}from"../core/errors/openfortError.js";class s{storage;authManager;validateAndRefreshToken;ensureInitialized;constructor(a,t,e,i){this.storage=a,this.authManager=t,this.validateAndRefreshToken=e,this.ensureInitialized=i}async logInWithEmailPassword({email:a,password:e,ecosystemGame:i}){await this.ensureInitialized();const r=await t.fromStorage(this.storage),s=await this.authManager.loginEmailPassword(a,e,i);return"action"in s||(r&&r.player!==s.player.id&&await this.logout(),new t("jwt",s.token,s.player.id,s.refreshToken).save(this.storage)),s}async signUpGuest(){await this.ensureInitialized();const a=await t.fromStorage(this.storage),e=await this.authManager.registerGuest();return a&&a.player!==e.player.id&&await this.logout(),new t("jwt",e.token,e.player.id,e.refreshToken).save(this.storage),e}async signUpWithEmailPassword({email:a,password:e,options:i,ecosystemGame:r}){await this.ensureInitialized();const s=await t.fromStorage(this.storage),n=await this.authManager.signupEmailPassword(a,e,i?.data.name,r);return"action"in n||(s&&s.player!==n.player.id&&await this.logout(),new t("jwt",n.token,n.player.id,n.refreshToken).save(this.storage)),n}async linkEmailPassword({email:a,password:t,authToken:e,ecosystemGame:i}){return await this.authManager.linkEmail(a,t,e,i)}async unlinkEmailPassword({email:a,authToken:t}){return await this.authManager.unlinkEmail(a,t)}async requestEmailVerification({email:a,redirectUrl:t}){await this.authManager.requestEmailVerification(a,t)}async resetPassword({email:a,password:t,state:e}){await this.authManager.resetPassword(a,t,e)}async requestResetPassword({email:a,redirectUrl:t}){await this.ensureInitialized(),await this.authManager.requestResetPassword(a,t)}async verifyEmail({email:a,state:t}){await this.authManager.verifyEmail(a,t)}async initOAuth({provider:a,options:t,ecosystemGame:e}){return await this.ensureInitialized(),await this.authManager.initOAuth(a,t,e)}async initLinkOAuth({provider:a,options:e,ecosystemGame:s}){const n=await t.fromStorage(this.storage);if(!n)throw new i("No authentication found",r.NOT_LOGGED_IN_ERROR);return await this.authManager.linkOAuth(n,a,e,s)}async linkThirdPartyProvider({provider:a,token:e,tokenType:s}){const n=await t.fromStorage(this.storage);if(!n)throw new i("No authentication found",r.NOT_LOGGED_IN_ERROR);return await this.authManager.linkThirdParty(n,a,e,s)}async unlinkOAuth({provider:a,authToken:t}){return await this.authManager.unlinkOAuth(a,t)}async poolOAuth(a){await this.ensureInitialized();const e=await t.fromStorage(this.storage),i=await this.authManager.poolOAuth(a);return e&&e.player!==i.player.id&&await this.logout(),new t("jwt",i.token,i.player.id,i.refreshToken).save(this.storage),i}async authenticateWithThirdPartyProvider({provider:a,token:e,tokenType:i,ecosystemGame:r}){await this.ensureInitialized();const s=await t.fromStorage(this.storage),n=await this.authManager.authenticateThirdParty(a,e,i,r);return s&&s.player!==n.id&&await this.logout(),new t("third_party",e,n.id,null,a,i).save(this.storage),n}async loginWithIdToken({provider:a,token:e,ecosystemGame:i}){await this.ensureInitialized();const r=await t.fromStorage(this.storage),s=await this.authManager.loginWithIdToken(a,e,i);return r&&r.player!==s.player.id&&await this.logout(),new t("jwt",s.token,s.player.id,s.refreshToken).save(this.storage),s}async initSIWE({address:a,ecosystemGame:t}){return await this.ensureInitialized(),await this.authManager.initSIWE(a,t)}async authenticateWithSIWE({signature:a,message:e,walletClientType:i,connectorType:r}){await this.ensureInitialized();const s=await t.fromStorage(this.storage),n=await this.authManager.authenticateSIWE(a,e,i,r);return s&&s.player!==n.player.id&&await this.logout(),new t("jwt",n.token,n.player.id,n.refreshToken).save(this.storage),n}async linkWallet({signature:a,message:t,walletClientType:e,connectorType:i,authToken:r}){return await this.authManager.linkWallet(a,t,e,i,r)}async unlinkWallet({address:a,authToken:t}){return await this.authManager.unlinkWallet(a,t)}async storeCredentials(a){if(await this.ensureInitialized(),!a.player)throw new i("Player ID is required to store credentials",r.INVALID_CONFIGURATION);new t("jwt",a.accessToken,a.player,a.refreshToken).save(this.storage)}async logout(){await this.ensureInitialized();const t=await e.fromStorage(this.storage);this.storage.remove(a.AUTHENTICATION),this.storage.remove(a.ACCOUNT),t&&await t.logout()}}export{s as AuthApi};
@@ -1 +1 @@
1
- import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{SignerManager as t}from"../wallets/signer.js";import{Account as r}from"../core/configuration/account.js";import{Authentication as i}from"../core/configuration/authentication.js";import{SDKConfiguration as o}from"../core/config/config.js";import{OpenfortError as a,OpenfortErrorType as n,withOpenfortError as s}from"../core/errors/openfortError.js";import{getSignedTypedData as d}from"../wallets/evm/walletHelpers.js";import{EvmProvider as c}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as h,openfortProviderInfo as f}from"../wallets/evm/provider/eip6963.js";import g from"../utils/typedEventEmitter.js";import{RecoveryMethod as l,EmbeddedState as u}from"../types/types.js";import{IframeManager as w}from"../wallets/iframeManager.js";class p{storage;validateAndRefreshToken;ensureInitialized;provider=null;iframeManager=null;constructor(e,t,r){this.storage=e,this.validateAndRefreshToken=t,this.ensureInitialized=r}get backendApiClients(){const t=o.fromStorage();if(!t)throw new a("Configuration not found",n.INVALID_CONFIGURATION);return new e({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey})}getIframeManager(){if(!this.iframeManager){const e=o.fromStorage();if(!e)throw new a("Configuration not found",n.INVALID_CONFIGURATION);this.iframeManager=new w(e,this.storage)}return this.iframeManager}async configure(e={}){const r=e.recoveryParams??{recoveryMethod:l.AUTOMATIC};await this.ensureInitialized(),await this.validateAndRefreshToken();const i=o.fromStorage();let s=null;(r.recoveryMethod===l.PASSWORD||e.shieldAuthentication?.encryptionSession)&&(s={encryptionSession:e.shieldAuthentication?.encryptionSession||null,recoveryPassword:r.recoveryMethod===l.PASSWORD?r.password:null,encryptionPart:i?.shieldConfiguration?.shieldEncryptionKey||null});let d=null,c=null;if(e.shieldAuthentication&&(d="openfort"===e.shieldAuthentication.auth?"openfort":"custom",c=e.shieldAuthentication.token),!this.storage)throw new a("Storage not available in EmbeddedWalletApi",n.INVALID_CONFIGURATION);return await t.embedded(this.storage,e.chainId,s,d,c),this.get()}async signMessage(e,r){await this.ensureInitialized(),await this.validateAndRefreshToken();const i=await t.fromStorage(this.storage);if(!i)throw new a("No signer configured",n.MISSING_SIGNER_ERROR);const{hashMessage:o=!0,arrayifyMessage:s=!1}=r||{};return await i.sign(e,s,o)}async signTypedData(e,i,o){await this.ensureInitialized(),await this.validateAndRefreshToken();const s=await t.fromStorage(this.storage),c=await r.fromStorage(this.storage);if(!s||!c)throw new a("No signer configured",n.MISSING_SIGNER_ERROR);return await d({domain:e,types:i,message:o},c.type,Number(c.chainId),s,c.address)}async exportPrivateKey(){await this.ensureInitialized(),await this.validateAndRefreshToken();const e=await t.fromStorage(this.storage);if(!e)throw new a("No signer configured",n.MISSING_SIGNER_ERROR);return await e.export()}async setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:r,encryptionSession:i}){await this.ensureInitialized(),await this.validateAndRefreshToken();const o=await t.fromStorage(this.storage);if(!o)throw new a("No signer configured",n.MISSING_SIGNER_ERROR);if("password"===e&&!r)throw new a("Recovery password is required",n.INVALID_CONFIGURATION);await o.setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:r,encryptionSession:i})}async get(){const e=await r.fromStorage(this.storage);if(!e)throw new a("No signer configured",n.MISSING_SIGNER_ERROR);const t=await i.fromStorage(this.storage);if(!t)throw new a("No access token found",n.INTERNAL_ERROR);return{chainId:e.chainId.toString(),owner:{id:t.player},address:e.address,ownerAddress:e.ownerAddress,chainType:"ethereum",implementationType:e.type}}async list(){const e=o.fromStorage();if(!e)throw new a("Configuration not found",n.INVALID_CONFIGURATION);await this.ensureInitialized(),await this.validateAndRefreshToken();const t=await i.fromStorage(this.storage);if(!t)throw new a("No access token found",n.NOT_LOGGED_IN_ERROR);return s(async()=>(await this.backendApiClients.accountsApi.getAccounts(void 0,{headers:{authorization:`Bearer ${e.baseConfiguration.publishableKey}`,"x-player-token":t.token,"x-auth-provider":t.thirdPartyProvider,"x-token-type":t.thirdPartyTokenType}})).data.data.map(e=>({owner:{id:e.player.id},chainType:"ethereum",address:e.address,ownerAddress:e.ownerAddress,createdAt:e.createdAt,implementationType:e.accountType,chainId:e.chainId.toString()})),{default:n.AUTHENTICATION_ERROR})}async getEmbeddedState(){try{if(!await i.fromStorage(this.storage))return u.UNAUTHENTICATED;if(!await t.fromStorage(this.storage))return u.EMBEDDED_SIGNER_NOT_CONFIGURED;return await r.fromStorage(this.storage)?u.READY:u.CREATING_ACCOUNT}catch(e){return console.error("Failed to get embedded state:",e),u.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const o={announceProvider:!0,...e},a=await i.fromStorage(this.storage),n=await t.fromStorage(this.storage),s=await r.fromStorage(this.storage);return this.provider?this.provider&&o.policy&&this.provider.updatePolicy(o.policy):(this.provider=new c({storage:this.storage,openfortEventEmitter:new g,signer:n||void 0,account:s||void 0,authentication:a||void 0,backendApiClients:this.backendApiClients,policyId:o.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:o.chains}),o.announceProvider&&h({info:{...f,...o.providerInfo},provider:this.provider})),this.provider}async ping(e){try{const t=this.getIframeManager();if(!t.isLoaded())return!1;e>0&&await new Promise(t=>{setTimeout(t,e)});const r=await i.fromStorage(this.storage);if(r)try{return await t.getCurrentUser(r.player),!0}catch(e){return!1}return t.isLoaded()}catch(e){return!1}}getURL(){if(!o.fromStorage())throw new a("Configuration not found",n.INVALID_CONFIGURATION);return"http://localhost:5173"}}export{p as EmbeddedWalletApi};
1
+ import{BackendApiClients as e}from"../../../packages/internal/openapi-clients/dist/index.js";import{SignerManager as t}from"../wallets/signer.js";import{Account as r}from"../core/configuration/account.js";import{Authentication as i}from"../core/configuration/authentication.js";import{SDKConfiguration as o}from"../core/config/config.js";import{OpenfortError as a,OpenfortErrorType as n,withOpenfortError as s}from"../core/errors/openfortError.js";import{getSignedTypedData as d}from"../wallets/evm/walletHelpers.js";import{EvmProvider as c}from"../wallets/evm/evmProvider.js";import"../wallets/evm/types.js";import{announceProvider as h,openfortProviderInfo as f}from"../wallets/evm/provider/eip6963.js";import g from"../utils/typedEventEmitter.js";import{RecoveryMethod as l,EmbeddedState as u}from"../types/types.js";import{IframeManager as w}from"../wallets/iframeManager.js";class p{storage;validateAndRefreshToken;ensureInitialized;provider=null;iframeManager=null;constructor(e,t,r){this.storage=e,this.validateAndRefreshToken=t,this.ensureInitialized=r}get backendApiClients(){const t=o.fromStorage();if(!t)throw new a("Configuration not found",n.INVALID_CONFIGURATION);return new e({basePath:t.backendUrl,accessToken:t.baseConfiguration.publishableKey})}getIframeManager(){if(!this.iframeManager){const e=o.fromStorage();if(!e)throw new a("Configuration not found",n.INVALID_CONFIGURATION);this.iframeManager=new w(e,this.storage)}return this.iframeManager}async configure(e={}){const r=e.recoveryParams??{recoveryMethod:l.AUTOMATIC};await this.ensureInitialized(),await this.validateAndRefreshToken();const i=o.fromStorage();let s=null;(r.recoveryMethod===l.PASSWORD||e.shieldAuthentication?.encryptionSession)&&(s={encryptionSession:e.shieldAuthentication?.encryptionSession||null,recoveryPassword:r.recoveryMethod===l.PASSWORD?r.password:null,encryptionPart:i?.shieldConfiguration?.shieldEncryptionKey||null});let d=null,c=null;if(e.shieldAuthentication&&(d="openfort"===e.shieldAuthentication.auth?"openfort":"custom",c=e.shieldAuthentication.token),!this.storage)throw new a("Storage not available in EmbeddedWalletApi",n.INVALID_CONFIGURATION);return await t.embedded(this.storage,e.chainId,s,d,c),this.get()}async signMessage(e,r){await this.ensureInitialized(),await this.validateAndRefreshToken();const i=await t.fromStorage(this.storage);if(!i)throw new a("No signer configured",n.MISSING_SIGNER_ERROR);const{hashMessage:o=!0,arrayifyMessage:s=!1}=r||{};return await i.sign(e,s,o)}async signTypedData(e,i,o){await this.ensureInitialized(),await this.validateAndRefreshToken();const s=await t.fromStorage(this.storage),c=await r.fromStorage(this.storage);if(!s||!c)throw new a("No signer configured",n.MISSING_SIGNER_ERROR);return await d({domain:e,types:i,message:o},c.type,Number(c.chainId),s,c.address)}async exportPrivateKey(){await this.ensureInitialized(),await this.validateAndRefreshToken();const e=await t.fromStorage(this.storage);if(!e)throw new a("No signer configured",n.MISSING_SIGNER_ERROR);return await e.export()}async setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:r,encryptionSession:i}){await this.ensureInitialized(),await this.validateAndRefreshToken();const o=await t.fromStorage(this.storage);if(!o)throw new a("No signer configured",n.MISSING_SIGNER_ERROR);if("password"===e&&!r)throw new a("Recovery password is required",n.INVALID_CONFIGURATION);await o.setEmbeddedRecovery({recoveryMethod:e,recoveryPassword:r,encryptionSession:i})}async get(){const e=await r.fromStorage(this.storage);if(!e)throw new a("No signer configured",n.MISSING_SIGNER_ERROR);const t=await i.fromStorage(this.storage);if(!t)throw new a("No access token found",n.INTERNAL_ERROR);return{chainId:e.chainId.toString(),owner:{id:t.player},address:e.address,ownerAddress:e.ownerAddress,chainType:"ethereum",implementationType:e.type}}async list(){const e=o.fromStorage();if(!e)throw new a("Configuration not found",n.INVALID_CONFIGURATION);await this.ensureInitialized(),await this.validateAndRefreshToken();const t=await i.fromStorage(this.storage);if(!t)throw new a("No access token found",n.NOT_LOGGED_IN_ERROR);return s(async()=>(await this.backendApiClients.accountsApi.getAccounts(void 0,{headers:{authorization:`Bearer ${e.baseConfiguration.publishableKey}`,"x-player-token":t.token,"x-auth-provider":t.thirdPartyProvider,"x-token-type":t.thirdPartyTokenType}})).data.data.map(e=>({owner:{id:e.player.id},chainType:"ethereum",address:e.address,ownerAddress:e.ownerAddress,createdAt:e.createdAt,implementationType:e.accountType,chainId:e.chainId.toString()})),{default:n.AUTHENTICATION_ERROR})}async getEmbeddedState(){try{if(!await i.fromStorage(this.storage))return u.UNAUTHENTICATED;if(!await t.fromStorage(this.storage))return u.EMBEDDED_SIGNER_NOT_CONFIGURED;return await r.fromStorage(this.storage)?u.READY:u.CREATING_ACCOUNT}catch(e){return console.error("Failed to get embedded state:",e),u.UNAUTHENTICATED}}async getEthereumProvider(e){await this.ensureInitialized();const o={announceProvider:!0,...e},a=await i.fromStorage(this.storage),n=await t.fromStorage(this.storage),s=await r.fromStorage(this.storage);return this.provider?this.provider&&o.policy&&this.provider.updatePolicy(o.policy):(this.provider=new c({storage:this.storage,openfortEventEmitter:new g,signer:n||void 0,account:s||void 0,authentication:a||void 0,backendApiClients:this.backendApiClients,policyId:o.policy,validateAndRefreshSession:this.validateAndRefreshToken.bind(this),chains:o.chains}),o.announceProvider&&h({info:{...f,...o.providerInfo},provider:this.provider})),this.provider}async ping(e){try{const t=this.getIframeManager();if(!t.isLoaded())return!1;e>0&&await new Promise(t=>{setTimeout(t,e)});const r=await i.fromStorage(this.storage);if(r)try{return await t.getCurrentUser(r.player),!0}catch(e){return!1}return t.isLoaded()}catch(e){return!1}}getURL(){const e=o.fromStorage();if(!e)throw new a("Configuration not found",n.INVALID_CONFIGURATION);return e.iframeUrl}}export{p as EmbeddedWalletApi};
@@ -1 +1 @@
1
- const o="0.9.0",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
1
+ const o="0.9.2",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
@@ -1 +1 @@
1
- import{Account as t}from"../core/configuration/account.js";import{Authentication as a}from"../core/configuration/authentication.js";import{OpenfortError as r,OpenfortErrorType as e}from"../core/errors/openfortError.js";import{Recovery as i}from"../core/configuration/recovery.js";import{ShieldAuthType as o}from"./types.js";import{StorageKeys as n}from"../storage/istorage.js";class s{iframeManager;iframeConfiguration;storage;constructor(t,a,r){this.iframeManager=t,this.iframeConfiguration=a,this.storage=r}async sign(t,a,r){return await this.iframeManager.sign(this.iframeConfiguration,t,a,r)}async export(){return await this.iframeManager.export(this.iframeConfiguration)}async switchChain({chainId:a}){const r=await this.iframeManager.switchChain(this.iframeConfiguration,a);new t(r.address,r.chainId,r.ownerAddress,r.accountType).save(this.storage)}async setEmbeddedRecovery({recoveryMethod:t,recoveryPassword:a,encryptionSession:r}){await this.iframeManager.setEmbeddedRecovery(this.iframeConfiguration,t,a,r)}async logout(){await this.iframeManager.logout(),this.storage.remove(n.RECOVERY),this.storage.remove(n.SIGNER)}async updateAuthentication(){const t=await a.fromStorage(this.storage);if(!t)throw new r("Must provide authentication to update authentication",e.NOT_LOGGED_IN_ERROR);const n=await i.fromStorage(this.storage);if(!n)throw new r("Must have recovery to update authentication",e.INVALID_CONFIGURATION);await this.iframeManager.updateAuthentication(this.iframeConfiguration,t.token,"openfort"===n.type?o.OPENFORT:o.CUSTOM)}}export{s as EmbeddedSigner};
1
+ import{Account as t}from"../core/configuration/account.js";import{Authentication as a}from"../core/configuration/authentication.js";import{OpenfortError as r,OpenfortErrorType as i}from"../core/errors/openfortError.js";import{Recovery as o}from"../core/configuration/recovery.js";import{ShieldAuthType as e}from"./types.js";import{StorageKeys as n}from"../storage/istorage.js";class s{iframeManager;iframeConfiguration;storage;constructor(t,a,r){this.iframeManager=t,this.iframeConfiguration=a,this.storage=r}async sign(t,a,r){return await this.iframeManager.sign(this.iframeConfiguration,t,a,r)}async export(){return await this.iframeManager.export(this.iframeConfiguration)}async switchChain({chainId:a}){const r=await this.iframeManager.switchChain(this.iframeConfiguration,a);new t(r.address,r.chainId,r.ownerAddress,r.accountType).save(this.storage)}async setEmbeddedRecovery({recoveryMethod:t,recoveryPassword:a,encryptionSession:r}){await this.iframeManager.setEmbeddedRecovery(this.iframeConfiguration,t,a,r)}async logout(){await this.iframeManager.logout(),this.storage.remove(n.RECOVERY)}async updateAuthentication(){const t=await a.fromStorage(this.storage);if(!t)throw new r("Must provide authentication to update authentication",i.NOT_LOGGED_IN_ERROR);const n=await o.fromStorage(this.storage);if(!n)throw new r("Must have recovery to update authentication",i.INVALID_CONFIGURATION);await this.iframeManager.updateAuthentication(this.iframeConfiguration,t.token,"openfort"===n.type?e.OPENFORT:e.CUSTOM)}}export{s as EmbeddedSigner};
@@ -1 +1 @@
1
- import{Authentication as t}from"../../core/configuration/authentication.js";import{ProviderEvent as e}from"./types.js";import{JsonRpcError as a,ProviderErrorCode as s,RpcErrorCode as r}from"./JsonRpcError.js";import{signTypedDataV4 as i}from"./signTypedDataV4.js";import{OpenfortEvents as o}from"../../types/types.js";import n from"../../utils/typedEventEmitter.js";import{defaultChainRpcs as c}from"../../utils/chains/index.js";import{Account as h}from"../../core/configuration/account.js";import{SignerManager as d}from"../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 w}from"./revokeSession.js";import{sendCalls as g}from"./sendCalls.js";import{getCallStatus as u}from"./getCallsStatus.js";import{personalSign as f}from"./personalSign.js";import{estimateGas as A}from"./estimateGas.js";import{numberToHex as S}from"../../utils/crypto.js";class v{#t;#e;#a;updatePolicy(t){this.#e=t}#s;#r;#i=null;#o;isOpenfort=!0;constructor({storage:t,backendApiClients:e,openfortEventEmitter:a,policyId:s,chains:r,validateAndRefreshSession:i}){this.#t=t,this.#a=r,this.#e=s,this.#s=i,this.#o=e,this.#o=e,this.#r=new n,a.on(o.LOGGED_OUT,this.#n)}#n=async()=>{const t=!!await h.fromStorage(this.#t),a=await d.fromStorage(this.#t);a?.logout(),this.#t.remove(m.ACCOUNT),this.#t.remove(m.AUTHENTICATION),this.#t.remove(m.SIGNER),t&&this.#r.emit(e.ACCOUNTS_CHANGED,[])};async getRpcProvider(){if(!this.#i){const t=await h.fromStorage(this.#t),e=t?.chainId||8453;await import("@ethersproject/providers").then(t=>{const a=this.#a?this.#a[e]:void 0;this.#i=new t.StaticJsonRpcProvider(a??c[e])})}if(!this.#i)throw new Error("RPC provider not initialized");return this.#i}async#c(o){switch(o.method){case"eth_accounts":{const t=await h.fromStorage(this.#t);return t?[t.address]:[]}case"eth_requestAccounts":{let t=await h.fromStorage(this.#t);if(t)return this.#r.emit(e.ACCOUNTS_CONNECT,{chainId:S(t.chainId)}),[t.address];if(!await d.fromStorage(this.#t))throw new a(s.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");if(await d.embedded(this.#t),t=await h.fromStorage(this.#t),!t)throw new a(s.UNAUTHORIZED,"Unauthorized - no account available");return this.#r.emit(e.ACCOUNTS_CHANGED,[t.address]),[t.address]}case"eth_sendTransaction":{const e=await h.fromStorage(this.#t),r=await d.fromStorage(this.#t),i=await t.fromStorage(this.#t);if(!e||!r||!i)throw new a(s.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await g({params:o.params||[],signer:r,account:e,authentication:i,backendClient:this.#o,policyId:this.#e})}case"eth_estimateGas":{const e=await h.fromStorage(this.#t),r=await t.fromStorage(this.#t);if(!e||!r)throw new a(s.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await A({params:o.params||[],account:e,authentication:r,backendClient:this.#o,policyId:this.#e})}case"eth_signTypedData":case"eth_signTypedData_v4":{const t=await h.fromStorage(this.#t),e=await d.fromStorage(this.#t);if(!t||!e)throw new a(s.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#s();const r=await this.getRpcProvider();return await i({method:o.method,params:o.params||[],signer:e,accountType:t.type,rpcProvider:r})}case"personal_sign":{const t=await h.fromStorage(this.#t),e=await d.fromStorage(this.#t);if(!t||!e)throw new a(s.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await f({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=await d.fromStorage(this.#t);if(!t)throw new a(s.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");if(!o.params||!Array.isArray(o.params)||0===o.params.length)throw new a(r.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#s();try{const e=parseInt(o.params[0].chainId,16);await t.switchChain({chainId:e}),await import("@ethersproject/providers").then(t=>{const a=this.#a?this.#a[e]:void 0;this.#i=new t.StaticJsonRpcProvider(a??c[e])})}catch(t){throw new a(r.INTERNAL_ERROR,"Failed to switch chain")}return null}case"wallet_addEthereumChain":{if(!await d.fromStorage(this.#t))throw new a(s.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");const t=await this.getRpcProvider();return await p({params:o.params||[],rpcProvider:t,storage:this.#t})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const e=await h.fromStorage(this.#t),r=await d.fromStorage(this.#t),i=await t.fromStorage(this.#t);if(!e||!r||!i)throw new a(s.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await u({params:o.params||{},authentication:i,backendClient:this.#o,account:e})}case"wallet_sendCalls":{const e=await h.fromStorage(this.#t),r=await d.fromStorage(this.#t),i=await t.fromStorage(this.#t);if(!e||!r||!i)throw new a(s.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await g({params:o.params?o.params[0].calls:[],signer:r,account:e,authentication:i,backendClient:this.#o,policyId:this.#e})}case"wallet_grantPermissions":{const e=await h.fromStorage(this.#t),r=await d.fromStorage(this.#t),i=await t.fromStorage(this.#t);if(!e||!r||!i)throw new a(s.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await l({params:o.params||[],signer:r,account:e,authentication:i,backendClient:this.#o,policyId:this.#e})}case"wallet_revokePermissions":{const e=await h.fromStorage(this.#t),r=await d.fromStorage(this.#t),i=await t.fromStorage(this.#t);if(!e||!r||!i)throw new a(s.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await w({params:o.params||[],signer:r,account:e,authentication:i,backendClient:this.#o})}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 a(s.UNSUPPORTED_METHOD,`${o.method}: Method not supported`)}}async request(t){try{return this.#c(t)}catch(t){if(t instanceof a)throw t;if(t instanceof Error)throw new a(r.INTERNAL_ERROR,t.message);throw new a(r.INTERNAL_ERROR,"Internal error")}}on(t,e){this.#r.on(t,e)}removeListener(t,e){this.#r.off(t,e)}}export{v as EvmProvider};
1
+ import{Authentication as t}from"../../core/configuration/authentication.js";import{ProviderEvent as e}from"./types.js";import{JsonRpcError as a,ProviderErrorCode as s,RpcErrorCode as r}from"./JsonRpcError.js";import{signTypedDataV4 as i}from"./signTypedDataV4.js";import{OpenfortEvents as o}from"../../types/types.js";import n from"../../utils/typedEventEmitter.js";import{defaultChainRpcs as c}from"../../utils/chains/index.js";import{Account as h}from"../../core/configuration/account.js";import{SignerManager as d}from"../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 w}from"./revokeSession.js";import{sendCalls as g}from"./sendCalls.js";import{getCallStatus as u}from"./getCallsStatus.js";import{personalSign as f}from"./personalSign.js";import{estimateGas as A}from"./estimateGas.js";import{numberToHex as S}from"../../utils/crypto.js";class v{#t;#e;#a;updatePolicy(t){this.#e=t}#s;#r;#i=null;#o;isOpenfort=!0;constructor({storage:t,backendApiClients:e,openfortEventEmitter:a,policyId:s,chains:r,validateAndRefreshSession:i}){this.#t=t,this.#a=r,this.#e=s,this.#s=i,this.#o=e,this.#o=e,this.#r=new n,a.on(o.LOGGED_OUT,this.#n)}#n=async()=>{const t=!!await h.fromStorage(this.#t),a=await d.fromStorage(this.#t);a?.logout(),this.#t.remove(m.ACCOUNT),this.#t.remove(m.AUTHENTICATION),t&&this.#r.emit(e.ACCOUNTS_CHANGED,[])};async getRpcProvider(){if(!this.#i){const t=await h.fromStorage(this.#t),e=t?.chainId||8453;await import("@ethersproject/providers").then(t=>{const a=this.#a?this.#a[e]:void 0;this.#i=new t.StaticJsonRpcProvider(a??c[e])})}if(!this.#i)throw new Error("RPC provider not initialized");return this.#i}async#c(o){switch(o.method){case"eth_accounts":{const t=await h.fromStorage(this.#t);return t?[t.address]:[]}case"eth_requestAccounts":{let t=await h.fromStorage(this.#t);if(t)return this.#r.emit(e.ACCOUNTS_CONNECT,{chainId:S(t.chainId)}),[t.address];if(!await d.fromStorage(this.#t))throw new a(s.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");if(await d.embedded(this.#t),t=await h.fromStorage(this.#t),!t)throw new a(s.UNAUTHORIZED,"Unauthorized - no account available");return this.#r.emit(e.ACCOUNTS_CHANGED,[t.address]),[t.address]}case"eth_sendTransaction":{const e=await h.fromStorage(this.#t),r=await d.fromStorage(this.#t),i=await t.fromStorage(this.#t);if(!e||!r||!i)throw new a(s.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await g({params:o.params||[],signer:r,account:e,authentication:i,backendClient:this.#o,policyId:this.#e})}case"eth_estimateGas":{const e=await h.fromStorage(this.#t),r=await t.fromStorage(this.#t);if(!e||!r)throw new a(s.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await A({params:o.params||[],account:e,authentication:r,backendClient:this.#o,policyId:this.#e})}case"eth_signTypedData":case"eth_signTypedData_v4":{const t=await h.fromStorage(this.#t),e=await d.fromStorage(this.#t);if(!t||!e)throw new a(s.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");await this.#s();const r=await this.getRpcProvider();return await i({method:o.method,params:o.params||[],signer:e,accountType:t.type,rpcProvider:r})}case"personal_sign":{const t=await h.fromStorage(this.#t),e=await d.fromStorage(this.#t);if(!t||!e)throw new a(s.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await f({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=await d.fromStorage(this.#t);if(!t)throw new a(s.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");if(!o.params||!Array.isArray(o.params)||0===o.params.length)throw new a(r.INVALID_PARAMS,"Invalid parameters for wallet_switchEthereumChain");await this.#s();try{const e=parseInt(o.params[0].chainId,16);await t.switchChain({chainId:e}),await import("@ethersproject/providers").then(t=>{const a=this.#a?this.#a[e]:void 0;this.#i=new t.StaticJsonRpcProvider(a??c[e])})}catch(t){throw new a(r.INTERNAL_ERROR,"Failed to switch chain")}return null}case"wallet_addEthereumChain":{if(!await d.fromStorage(this.#t))throw new a(s.UNAUTHORIZED,"Unauthorized - must be authenticated and configured with a signer");const t=await this.getRpcProvider();return await p({params:o.params||[],rpcProvider:t,storage:this.#t})}case"wallet_showCallsStatus":return null;case"wallet_getCallsStatus":{const e=await h.fromStorage(this.#t),r=await d.fromStorage(this.#t),i=await t.fromStorage(this.#t);if(!e||!r||!i)throw new a(s.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await u({params:o.params||{},authentication:i,backendClient:this.#o,account:e})}case"wallet_sendCalls":{const e=await h.fromStorage(this.#t),r=await d.fromStorage(this.#t),i=await t.fromStorage(this.#t);if(!e||!r||!i)throw new a(s.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await g({params:o.params?o.params[0].calls:[],signer:r,account:e,authentication:i,backendClient:this.#o,policyId:this.#e})}case"wallet_grantPermissions":{const e=await h.fromStorage(this.#t),r=await d.fromStorage(this.#t),i=await t.fromStorage(this.#t);if(!e||!r||!i)throw new a(s.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await l({params:o.params||[],signer:r,account:e,authentication:i,backendClient:this.#o,policyId:this.#e})}case"wallet_revokePermissions":{const e=await h.fromStorage(this.#t),r=await d.fromStorage(this.#t),i=await t.fromStorage(this.#t);if(!e||!r||!i)throw new a(s.UNAUTHORIZED,"Unauthorized - call eth_requestAccounts first");return await this.#s(),await w({params:o.params||[],signer:r,account:e,authentication:i,backendClient:this.#o})}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 a(s.UNSUPPORTED_METHOD,`${o.method}: Method not supported`)}}async request(t){try{return this.#c(t)}catch(t){if(t instanceof a)throw t;if(t instanceof Error)throw new a(r.INTERNAL_ERROR,t.message);throw new a(r.INTERNAL_ERROR,"Internal error")}}on(t,e){this.#r.on(t,e)}removeListener(t,e){this.#r.off(t,e)}}export{v as EvmProvider};
@@ -1 +1 @@
1
- import{WindowMessenger as e,connect as t}from"penpal";import{StorageKeys as r}from"../storage/istorage.js";import{randomUUID as o}from"../utils/crypto.js";import{OpenfortError as i,OpenfortErrorType as n}from"../core/errors/openfortError.js";import{isErrorResponse as s,NOT_CONFIGURED_ERROR as a,MISSING_USER_ENTROPY_ERROR as d,MISSING_PROJECT_ENTROPY_ERROR as c,INCORRECT_USER_ENTROPY_ERROR as h,Event as f,SignRequest as u,SwitchChainRequest as y,ExportPrivateKeyRequest as l,SetRecoveryMethodRequest as m,GetCurrentDeviceRequest as w,ShieldAuthType as p,UpdateAuthenticationRequest as g}from"./types.js";class v extends Error{constructor(){super("This embedded signer requires a password to be recovered")}}class C extends Error{constructor(){super("MissingProjectEntropyError")}}class I extends Error{constructor(){super("Wrong recovery password for this embedded signer")}}class b extends Error{message;constructor(e){super(`Unknown response from iframe: ${e}`),this.message=e||""}}class k extends Error{constructor(){super("Not configured")}}class T{iframe;connection;remote;storage;sdkConfiguration;isInitialized=!1;constructor(e,t){if(!e)throw new i("Configuration is required for IframeManager",n.INVALID_CONFIGURATION);if(!t)throw new i("Storage is required for IframeManager",n.INVALID_CONFIGURATION);this.sdkConfiguration=e,this.storage=t}async iframeSetup(){if("undefined"==typeof document)throw new i("Document is not available. Please provide a message poster for non-browser environments.",n.INVALID_CONFIGURATION);const e=document.getElementById("openfort-iframe");e&&document.body.removeChild(e);const t=document.createElement("iframe");t.style.display="none",t.id="openfort-iframe",document.body.appendChild(t),t.src=this.sdkConfiguration.iframeUrl,this.iframe=t,await new Promise((e,r)=>{const o=setTimeout(()=>{r(new Error("Iframe load timeout"))},2e3);t.onload=()=>{clearTimeout(o),e()},t.onerror=()=>{clearTimeout(o),r(new Error("Failed to load iframe"))}})}async establishIframeConnection(){if("undefined"==typeof document)throw new i("Document is not available.",n.INVALID_CONFIGURATION);if(!this.iframe?.contentWindow)throw new i("Iframe does not have content window",n.INVALID_CONFIGURATION);const r=new URL(this.sdkConfiguration.iframeUrl).origin,o=new e({remoteWindow:this.iframe.contentWindow,allowedOrigins:[r]});this.connection=t({messenger:o,timeout:5e3});try{this.remote=await this.connection.promise,this.isInitialized=!0}catch(e){const t=e;throw new Error(`v3 Failed to establish Iframe connection: ${t.cause||t.message}`,t)}}isLoaded(){return this.isInitialized&&void 0!==this.remote}async ensureConnection(){if(!this.isLoaded()){if("undefined"==typeof document)throw new i("Document is not available.",n.INVALID_CONFIGURATION);await this.iframeSetup(),await this.establishIframeConnection()}if(!this.remote)throw new Error("Failed to establish connection with iframe");return this.remote}static handleError(e){if(s(e)){if(e.error===a)throw new k;if(e.error===d)throw new v;if(e.error===c)throw new C;if(e.error===h)throw new I;throw new b(e.error)}throw e}async configure(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const t=await this.ensureConnection(),i={uuid:o(),action:f.CONFIGURE,chainId:e.chainId,recovery:e.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:e.accessToken,playerID:e.playerID,thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,encryptionKey:e.password,encryptionPart:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??null,encryptionSession:e.recovery?.encryptionSession??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl};try{const e=await t.configure(i);return s(e)&&T.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){throw(e instanceof I||e instanceof v)&&this.storage.remove(r.SIGNER),e}}async sign(e,t,r,i){const n=await this.ensureConnection(),a={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},d=new u(o(),t,r,i,a);try{const e=await n.sign(d);return s(e)&&T.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e.signature}catch(o){if(o instanceof k)return await this.configure(e),this.sign(e,t,r,i);throw o}}async switchChain(e,t){const r=await this.ensureConnection(),i={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},n=new y(o(),t,i);try{const e=await r.switchChain(n);return s(e)&&T.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(r){if(r instanceof k)return await this.configure(e),this.switchChain(e,t);throw r}}async export(e){const t=await this.ensureConnection(),r={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},i=new l(o(),r);try{const e=await t.export(i);return s(e)&&T.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e.key}catch(t){if(t instanceof k)return await this.configure(e),this.export(e);throw t}}async setEmbeddedRecovery(e,t,r,i){const n=await this.ensureConnection(),a={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},d=new m(o(),t,r,i,a);try{const e=await n.setRecoveryMethod(d);s(e)&&T.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined")}catch(o){if(o instanceof k)return await this.configure(e),this.setEmbeddedRecovery(e,t,r,i);throw o}}async getCurrentUser(e){const t=await this.ensureConnection(),r=new w(o(),e);try{const e=await t.getCurrentDevice(r);return s(e)&&T.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof k)return null;throw e}}async logout(){const e=await this.ensureConnection(),t={uuid:o()};await e.logout(t)}async updateAuthentication(e,t,r){const i={...e};i.accessToken=t,r===p.OPENFORT&&i.recovery&&(i.recovery={...i.recovery,token:t});const n=await this.ensureConnection(),s=new g(o(),t);try{await n.updateAuthentication(s)}catch(e){if(e instanceof k)return await this.configure(i),void await this.updateAuthentication(i,t,r);throw e}}destroy(){if(this.connection&&(this.connection.destroy(),this.connection=void 0),this.remote=void 0,this.isInitialized=!1,this.iframe&&"undefined"!=typeof document){const e=document.getElementById("openfort-iframe");e&&e.parentNode&&e.parentNode.removeChild(e),this.iframe=void 0}}}export{T as IframeManager,C as MissingProjectEntropyError,v as MissingRecoveryPasswordError,k as NotConfiguredError,b as UnknownResponseError,I as WrongRecoveryPasswordError};
1
+ import{WindowMessenger as e,connect as t}from"../../../node_modules/penpal/dist/penpal.js";import{randomUUID as i}from"../utils/crypto.js";import{OpenfortError as o,OpenfortErrorType as r}from"../core/errors/openfortError.js";import{isErrorResponse as n,NOT_CONFIGURED_ERROR as s,MISSING_USER_ENTROPY_ERROR as a,MISSING_PROJECT_ENTROPY_ERROR as d,INCORRECT_USER_ENTROPY_ERROR as c,Event as h,SignRequest as u,SwitchChainRequest as f,ExportPrivateKeyRequest as y,SetRecoveryMethodRequest as l,GetCurrentDeviceRequest as w,ShieldAuthType as m,UpdateAuthenticationRequest as p}from"./types.js";class g extends Error{constructor(){super("This embedded signer requires a password to be recovered")}}class v extends Error{constructor(){super("MissingProjectEntropyError")}}class C extends Error{constructor(){super("Wrong recovery password for this embedded signer")}}class I extends Error{message;constructor(e){super(`Unknown response from iframe: ${e}`),this.message=e||""}}class b extends Error{constructor(){super("Not configured")}}class k{iframe;connection;remote;storage;sdkConfiguration;isInitialized=!1;constructor(e,t){if(!e)throw new o("Configuration is required for IframeManager",r.INVALID_CONFIGURATION);if(!t)throw new o("Storage is required for IframeManager",r.INVALID_CONFIGURATION);this.sdkConfiguration=e,this.storage=t}async iframeSetup(){if("undefined"==typeof document)throw new o("Document is not available. Please provide a message poster for non-browser environments.",r.INVALID_CONFIGURATION);const e=document.getElementById("openfort-iframe");e&&document.body.removeChild(e);const t=document.createElement("iframe");t.style.display="none",t.id="openfort-iframe",document.body.appendChild(t),t.src=this.sdkConfiguration.iframeUrl,this.iframe=t,await new Promise((e,i)=>{const o=setTimeout(()=>{i(new Error("Iframe load timeout"))},1e4);t.onload=()=>{clearTimeout(o),e()},t.onerror=()=>{clearTimeout(o),i(new Error("Failed to load iframe"))}})}async establishIframeConnection(){if("undefined"==typeof document)throw new o("Document is not available.",r.INVALID_CONFIGURATION);if(!this.iframe?.contentWindow)throw new o("Iframe does not have content window",r.INVALID_CONFIGURATION);const i=new URL(this.sdkConfiguration.iframeUrl).origin,n=new e({remoteWindow:this.iframe.contentWindow,allowedOrigins:[i]});this.connection=t({messenger:n,timeout:5e3});try{this.remote=await this.connection.promise,this.isInitialized=!0}catch(e){const t=e;throw new Error(`v3 Failed to establish Iframe connection: ${t.cause||t.message}`,t)}}isLoaded(){return this.isInitialized&&void 0!==this.remote}async ensureConnection(){if(!this.isLoaded()){if("undefined"==typeof document)throw new o("Document is not available.",r.INVALID_CONFIGURATION);await this.iframeSetup(),await this.establishIframeConnection()}if(!this.remote)throw new Error("Failed to establish connection with iframe");return this.remote}static handleError(e){if(n(e)){if(e.error===s)throw new b;if(e.error===a)throw new g;if(e.error===d)throw new v;if(e.error===c)throw new C;throw new I(e.error)}throw e}async configure(e){if(!this.sdkConfiguration.shieldConfiguration)throw new Error("shieldConfiguration is required");const t=await this.ensureConnection(),o={uuid:i(),action:h.CONFIGURE,chainId:e.chainId,recovery:e.recovery,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,shieldAPIKey:this.sdkConfiguration.shieldConfiguration?.shieldPublishableKey||"",accessToken:e.accessToken,playerID:e.playerID,thirdPartyProvider:e.thirdPartyProvider,thirdPartyTokenType:e.thirdPartyTokenType,encryptionKey:e.password,encryptionPart:this.sdkConfiguration?.shieldConfiguration?.shieldEncryptionKey??null,encryptionSession:e.recovery?.encryptionSession??null,openfortURL:this.sdkConfiguration.backendUrl,shieldURL:this.sdkConfiguration.shieldUrl},r=await t.configure(o);return n(r)&&k.handleError(r),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",r.version??"undefined"),r}async sign(e,t,o,r){const s=await this.ensureConnection(),a={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},d=new u(i(),t,o,r,a);try{const e=await s.sign(d);return n(e)&&k.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e.signature}catch(i){if(i instanceof b)return await this.configure(e),this.sign(e,t,o,r);throw i}}async switchChain(e,t){const o=await this.ensureConnection(),r={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},s=new f(i(),t,r);try{const e=await o.switchChain(s);return n(e)&&k.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(i){if(i instanceof b)return await this.configure(e),this.switchChain(e,t);throw i}}async export(e){const t=await this.ensureConnection(),o={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},r=new y(i(),o);try{const e=await t.export(r);return n(e)&&k.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e.key}catch(t){if(t instanceof b)return await this.configure(e),this.export(e);throw t}}async setEmbeddedRecovery(e,t,o,r){const s=await this.ensureConnection(),a={thirdPartyProvider:e.thirdPartyProvider??void 0,thirdPartyTokenType:e.thirdPartyTokenType??void 0,token:e.accessToken??void 0,publishableKey:this.sdkConfiguration.baseConfiguration.publishableKey,openfortURL:this.sdkConfiguration.backendUrl},d=new l(i(),t,o,r,a);try{const e=await s.setRecoveryMethod(d);n(e)&&k.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined")}catch(i){if(i instanceof b)return await this.configure(e),this.setEmbeddedRecovery(e,t,o,r);throw i}}async getCurrentUser(e){const t=await this.ensureConnection(),o=new w(i(),e);try{const e=await t.getCurrentDevice(o);return n(e)&&k.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(e){if(e instanceof b)return null;throw e}}async logout(){const e=await this.ensureConnection(),t={uuid:i()};await e.logout(t)}async updateAuthentication(e,t,o){const r={...e};r.accessToken=t,o===m.OPENFORT&&r.recovery&&(r.recovery={...r.recovery,token:t});const n=await this.ensureConnection(),s=new p(i(),t);try{await n.updateAuthentication(s)}catch(e){if(e instanceof b)return await this.configure(r),void await this.updateAuthentication(r,t,o);throw e}}destroy(){if(this.connection&&(this.connection.destroy(),this.connection=void 0),this.remote=void 0,this.isInitialized=!1,this.iframe&&"undefined"!=typeof document){const e=document.getElementById("openfort-iframe");e&&e.parentNode&&e.parentNode.removeChild(e),this.iframe=void 0}}}export{k as IframeManager,v as MissingProjectEntropyError,g as MissingRecoveryPasswordError,b as NotConfiguredError,I as UnknownResponseError,C as WrongRecoveryPasswordError};
@@ -1 +1 @@
1
- import{SDKConfiguration as e}from"../core/config/config.js";import{StorageKeys as t}from"../storage/istorage.js";import{IframeManager as r}from"./iframeManager.js";import{Authentication as o}from"../core/configuration/authentication.js";import{OpenfortError as n,OpenfortErrorType as a}from"../core/errors/openfortError.js";import{ShieldAuthType as i}from"./types.js";import{Recovery as s}from"../core/configuration/recovery.js";import{EmbeddedSigner as c}from"./embedded.js";import{Account as d}from"../core/configuration/account.js";const u=new WeakMap;class h{static async fromStorage(e){if(!e)throw new n("Storage is required",a.INVALID_CONFIGURATION);const r=await e.get(t.SIGNER);if(!r)return null;const o=JSON.parse(r);return"embedded"===o.type?this.embeddedFromStorage(e,o.chainId):null}static async embeddedFromStorage(e,t){const r=this.getIframeManager(e),i=await o.fromStorage(e);if(!i)throw new n("Must be authenticated to create a signer",a.NOT_LOGGED_IN_ERROR);const d=await s.fromStorage(e);if(!d)throw new n("Must have recovery to create a signer",a.INVALID_CONFIGURATION);const u={thirdPartyTokenType:i.thirdPartyTokenType??null,thirdPartyProvider:i.thirdPartyProvider??null,accessToken:i.token,playerID:i.player,recovery:this.shieldAuthentication(e,d,i,null),chainId:t,password:null};return new c(r,u,e)}static getIframeManager(t){const o=u.get(t);if(o)return o;const i=e.fromStorage();if(!i)throw new n("Must be configured to create a signer",a.INVALID_CONFIGURATION);const s=new r(i,t);return u.set(t,s),s}static async embedded(e,r=null,i=null,u=null,h=null){if(!e)throw new n("Storage is required",a.INVALID_CONFIGURATION);const m=this.getIframeManager(e);let f;try{f=await o.fromStorage(e)}catch(e){throw new n("Failed to access authentication storage",a.INVALID_CONFIGURATION)}if(!f)throw new n("Must be authenticated to create a signer",a.NOT_LOGGED_IN_ERROR);const l=await s.fromStorage(e),y=new s(u||l?.type||"openfort",h||l?.customToken),I=this.shieldAuthentication(e,y,f,i),p={thirdPartyTokenType:f.thirdPartyTokenType??null,thirdPartyProvider:f.thirdPartyProvider??null,accessToken:f.token,playerID:f.player,recovery:I,chainId:r,password:i?.recoveryPassword||null},g={type:"embedded",chainId:r},w=await m.configure(p);return e.save(t.SIGNER,JSON.stringify(g)),new d(w.address,w.chainId,w.ownerAddress,w.accountType).save(e),new c(m,p,e)}static shieldAuthentication(e,t,r,o){let c=null;if("openfort"===t.type)c={auth:i.OPENFORT,authProvider:r.thirdPartyProvider||void 0,token:r.token,tokenType:r.thirdPartyTokenType||void 0,encryptionSession:o?.encryptionSession||void 0},new s("openfort").save(e);else if("custom"===t.type){if(!t.customToken)throw new n("Custom recovery requires a token",a.INVALID_CONFIGURATION);c={auth:i.CUSTOM,token:t.customToken},new s("custom",t.customToken).save(e)}return c}}export{h as SignerManager};
1
+ import{SDKConfiguration as e}from"../core/config/config.js";import{StorageKeys as t}from"../storage/istorage.js";import{IframeManager as r}from"./iframeManager.js";import{Authentication as o}from"../core/configuration/authentication.js";import{OpenfortError as n,OpenfortErrorType as a}from"../core/errors/openfortError.js";import{ShieldAuthType as i}from"./types.js";import{Recovery as s}from"../core/configuration/recovery.js";import{EmbeddedSigner as c}from"./embedded.js";import{Account as d}from"../core/configuration/account.js";const u=new WeakMap;class h{static async fromStorage(e){if(!e)throw new n("Storage is required",a.INVALID_CONFIGURATION);const r=await e.get(t.ACCOUNT);if(!r)return null;const o=JSON.parse(r);return this.embeddedFromStorage(e,o.chainId)}static async embeddedFromStorage(e,t){const r=this.getIframeManager(e),i=await o.fromStorage(e);if(!i)throw new n("Must be authenticated to create a signer",a.NOT_LOGGED_IN_ERROR);const d=await s.fromStorage(e);if(!d)throw new n("Must have recovery to create a signer",a.INVALID_CONFIGURATION);const u={thirdPartyTokenType:i.thirdPartyTokenType??null,thirdPartyProvider:i.thirdPartyProvider??null,accessToken:i.token,playerID:i.player,recovery:this.shieldAuthentication(e,d,i,null),chainId:t,password:null};return new c(r,u,e)}static getIframeManager(t){const o=u.get(t);if(o)return o;const i=e.fromStorage();if(!i)throw new n("Must be configured to create a signer",a.INVALID_CONFIGURATION);const s=new r(i,t);return u.set(t,s),s}static async embedded(e,t=null,r=null,i=null,u=null){if(!e)throw new n("Storage is required",a.INVALID_CONFIGURATION);const h=this.getIframeManager(e);let f;try{f=await o.fromStorage(e)}catch(e){throw new n("Failed to access authentication storage",a.INVALID_CONFIGURATION)}if(!f)throw new n("Must be authenticated to create a signer",a.NOT_LOGGED_IN_ERROR);const m=await s.fromStorage(e),l=new s(i||m?.type||"openfort",u||m?.customToken),y=this.shieldAuthentication(e,l,f,r),p={thirdPartyTokenType:f.thirdPartyTokenType??null,thirdPartyProvider:f.thirdPartyProvider??null,accessToken:f.token,playerID:f.player,recovery:y,chainId:t,password:r?.recoveryPassword||null},I=await h.configure(p);return new d(I.address,I.chainId,I.ownerAddress,I.accountType).save(e),new c(h,p,e)}static shieldAuthentication(e,t,r,o){let c=null;if("openfort"===t.type)c={auth:i.OPENFORT,authProvider:r.thirdPartyProvider||void 0,token:r.token,tokenType:r.thirdPartyTokenType||void 0,encryptionSession:o?.encryptionSession||void 0},new s("openfort").save(e);else if("custom"===t.type){if(!t.customToken)throw new n("Custom recovery requires a token",a.INVALID_CONFIGURATION);c={auth:i.CUSTOM,token:t.customToken},new s("custom",t.customToken).save(e)}return c}}export{h as SignerManager};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfort/openfort-js",
3
- "version": "0.9.0",
3
+ "version": "0.9.2",
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",