@openfort/openfort-js 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="0.9.0";
1
+ "use strict";exports.PACKAGE="@openfort/openfort-js",exports.VERSION="0.9.1";
@@ -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("../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"))},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 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;
@@ -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
- const o="0.9.0",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
1
+ const o="0.9.1",t="@openfort/openfort-js";export{t as PACKAGE,o as VERSION};
@@ -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{StorageKeys as o}from"../storage/istorage.js";import{randomUUID as r}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,o)=>{const r=setTimeout(()=>{o(new Error("Iframe load timeout"))},1e4);t.onload=()=>{clearTimeout(r),e()},t.onerror=()=>{clearTimeout(r),o(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 o=new URL(this.sdkConfiguration.iframeUrl).origin,r=new e({remoteWindow:this.iframe.contentWindow,allowedOrigins:[o]});this.connection=t({messenger:r,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:r(),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(o.SIGNER),e}}async sign(e,t,o,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(r(),t,o,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(r){if(r instanceof k)return await this.configure(e),this.sign(e,t,o,i);throw r}}async switchChain(e,t){const o=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(r(),t,i);try{const e=await o.switchChain(n);return s(e)&&T.handleError(e),"undefined"!=typeof sessionStorage&&sessionStorage.setItem("iframe-version",e.version??"undefined"),e}catch(o){if(o instanceof k)return await this.configure(e),this.switchChain(e,t);throw o}}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},i=new l(r(),o);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,o,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(r(),t,o,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(r){if(r instanceof k)return await this.configure(e),this.setEmbeddedRecovery(e,t,o,i);throw r}}async getCurrentUser(e){const t=await this.ensureConnection(),o=new w(r(),e);try{const e=await t.getCurrentDevice(o);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:r()};await e.logout(t)}async updateAuthentication(e,t,o){const i={...e};i.accessToken=t,o===p.OPENFORT&&i.recovery&&(i.recovery={...i.recovery,token:t});const n=await this.ensureConnection(),s=new g(r(),t);try{await n.updateAuthentication(s)}catch(e){if(e instanceof k)return await this.configure(i),void await this.updateAuthentication(i,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{T as IframeManager,C as MissingProjectEntropyError,v as MissingRecoveryPasswordError,k as NotConfiguredError,b as UnknownResponseError,I as WrongRecoveryPasswordError};
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.1",
4
4
  "author": "Openfort (https://www.openfort.io)",
5
5
  "bugs": "https://github.com/openfort-xyz/openfort-js/issues",
6
6
  "repository": "openfort-xyz/openfort-js.git",