@openkey/sdk 0.7.2 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,20 +1,117 @@
1
- import{generateCodeVerifier as O,generateCodeChallenge as A,generateState as I,buildAuthorizationUrl as M}from"@openkey/core";var S="https://openkey.so",f=400,w=600,T=300*1e3,R=3e3,k="openkey_oauth",P=class{root;shadow;iframe;onClose;onMessage;messageHandler;host;constructor(e){this.host=e.host,this.onClose=e.onClose,this.onMessage=e.onMessage;let t=window.matchMedia("(max-width: 639px)").matches;this.root=document.createElement("div"),this.shadow=this.root.attachShadow({mode:"closed"});let s=document.createElement("style");s.textContent=`
1
+ // src/index.ts
2
+ import {
3
+ generateCodeVerifier,
4
+ generateCodeChallenge,
5
+ generateState,
6
+ buildAuthorizationUrl
7
+ } from "@openkey/core";
8
+ var DEFAULT_HOST = "https://openkey.so";
9
+ var POPUP_WIDTH = 400;
10
+ var POPUP_HEIGHT = 600;
11
+ var DEFAULT_TIMEOUT = 5 * 60 * 1e3;
12
+ var IFRAME_READY_TIMEOUT = 3e3;
13
+ var OAUTH_STORAGE_KEY = "openkey_oauth";
14
+ var IframeModal = class {
15
+ root;
16
+ shadow;
17
+ iframe;
18
+ onClose;
19
+ onMessage;
20
+ messageHandler;
21
+ host;
22
+ constructor(opts) {
23
+ this.host = opts.host;
24
+ this.onClose = opts.onClose;
25
+ this.onMessage = opts.onMessage;
26
+ const isMobile = window.matchMedia("(max-width: 639px)").matches;
27
+ this.root = document.createElement("div");
28
+ this.shadow = this.root.attachShadow({ mode: "closed" });
29
+ const style = document.createElement("style");
30
+ style.textContent = `
2
31
  :host{all:initial}
3
- .ok-backdrop{position:fixed;inset:0;background:rgba(0,0,0,0.4);backdrop-filter:blur(4px);z-index:999999;display:flex;align-items:${t?"flex-end":"center"};justify-content:center;animation:ok-fade-in 150ms ease-out}
4
- .ok-card{position:relative;background:#fafafa;width:${t?"100%":"400px"};border-radius:${t?"16px 16px 0 0":"16px"};box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);overflow:hidden;overflow-y:auto;animation:${t?"ok-slide-up 250ms ease-out":"ok-scale-in 200ms ease-out"};max-height:90vh}
32
+ .ok-backdrop{position:fixed;inset:0;background:rgba(0,0,0,0.4);backdrop-filter:blur(4px);z-index:999999;display:flex;align-items:${isMobile ? "flex-end" : "center"};justify-content:center;animation:ok-fade-in 150ms ease-out}
33
+ .ok-card{position:relative;background:#fafafa;width:${isMobile ? "100%" : "400px"};border-radius:${isMobile ? "16px 16px 0 0" : "16px"};box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);overflow:hidden;overflow-y:auto;animation:${isMobile ? "ok-slide-up 250ms ease-out" : "ok-scale-in 200ms ease-out"};max-height:90vh}
5
34
  .ok-close{position:absolute;top:8px;right:8px;width:24px;height:24px;border:none;background:transparent;color:#6b7280;font-size:18px;cursor:pointer;z-index:1;display:flex;align-items:center;justify-content:center;border-radius:4px}
6
35
  .ok-close:hover{color:#111827}
7
36
  .ok-handle{width:40px;height:4px;background:#d4d4d4;border-radius:2px;margin:8px auto 0}
8
37
  iframe{border:none;width:100%;height:400px;display:block;transition:height 200ms ease}
9
38
  .ok-backdrop.ok-exit{animation:ok-fade-out 150ms ease-in}
10
- .ok-backdrop.ok-exit .ok-card{animation:${t?"ok-slide-down 200ms ease-in":"ok-scale-out 150ms ease-in"}}
39
+ .ok-backdrop.ok-exit .ok-card{animation:${isMobile ? "ok-slide-down 200ms ease-in" : "ok-scale-out 150ms ease-in"}}
11
40
  @keyframes ok-fade-in{from{opacity:0}to{opacity:1}}
12
41
  @keyframes ok-fade-out{from{opacity:1}to{opacity:0}}
13
42
  @keyframes ok-scale-in{from{opacity:0;transform:scale(0.95)}to{opacity:1;transform:scale(1)}}
14
43
  @keyframes ok-scale-out{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(0.95)}}
15
44
  @keyframes ok-slide-up{from{transform:translateY(100%)}to{transform:translateY(0)}}
16
45
  @keyframes ok-slide-down{from{transform:translateY(0)}to{transform:translateY(100%)}}
17
- `;let r=document.createElement("div");r.className="ok-backdrop",r.addEventListener("click",i=>{i.target===r&&this.close()});let o=document.createElement("div");if(o.className="ok-card",t){let i=document.createElement("div");i.className="ok-handle",o.appendChild(i)}let a=document.createElement("button");a.className="ok-close",a.textContent="\xD7",a.addEventListener("click",()=>this.close()),o.appendChild(a),this.iframe=document.createElement("iframe"),this.iframe.src=e.url,this.iframe.setAttribute("allow","publickey-credentials-get *; publickey-credentials-create *"),this.iframe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups"),o.appendChild(this.iframe),r.appendChild(o),this.shadow.appendChild(s),this.shadow.appendChild(r),this.messageHandler=i=>{if(i.origin!==this.host||i.source!==this.iframe.contentWindow)return;let c=i.data;if(c.type==="openkey:resize"){let l=Math.min(c.height,Math.floor(window.innerHeight*.85));this.iframe.style.height=`${l}px`;return}this.onMessage(c)},window.addEventListener("message",this.messageHandler),document.body.appendChild(this.root)}postMessage(e){this.iframe.contentWindow?.postMessage(e,this.host)}destroy(){window.removeEventListener("message",this.messageHandler),this.root.remove()}close(){let e=this.shadow.querySelector(".ok-backdrop");e?(e.classList.add("ok-exit"),setTimeout(()=>{this.destroy(),this.onClose()},200)):(this.destroy(),this.onClose())}},v=class{root;shadow;constructor(e){this.root=document.createElement("div"),this.shadow=this.root.attachShadow({mode:"closed"});let t=document.createElement("style");t.textContent=`
46
+ `;
47
+ const backdrop = document.createElement("div");
48
+ backdrop.className = "ok-backdrop";
49
+ backdrop.addEventListener("click", (e) => {
50
+ if (e.target === backdrop) this.close();
51
+ });
52
+ const card = document.createElement("div");
53
+ card.className = "ok-card";
54
+ if (isMobile) {
55
+ const handle = document.createElement("div");
56
+ handle.className = "ok-handle";
57
+ card.appendChild(handle);
58
+ }
59
+ const closeBtn = document.createElement("button");
60
+ closeBtn.className = "ok-close";
61
+ closeBtn.textContent = "\xD7";
62
+ closeBtn.addEventListener("click", () => this.close());
63
+ card.appendChild(closeBtn);
64
+ this.iframe = document.createElement("iframe");
65
+ this.iframe.src = opts.url;
66
+ this.iframe.setAttribute("allow", "publickey-credentials-get *; publickey-credentials-create *");
67
+ this.iframe.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms allow-popups");
68
+ card.appendChild(this.iframe);
69
+ backdrop.appendChild(card);
70
+ this.shadow.appendChild(style);
71
+ this.shadow.appendChild(backdrop);
72
+ this.messageHandler = (event) => {
73
+ if (event.origin !== this.host) return;
74
+ if (event.source !== this.iframe.contentWindow) return;
75
+ const data = event.data;
76
+ if (data.type === "openkey:resize") {
77
+ const h = Math.min(data.height, Math.floor(window.innerHeight * 0.85));
78
+ this.iframe.style.height = `${h}px`;
79
+ return;
80
+ }
81
+ this.onMessage(data);
82
+ };
83
+ window.addEventListener("message", this.messageHandler);
84
+ document.body.appendChild(this.root);
85
+ }
86
+ postMessage(message) {
87
+ this.iframe.contentWindow?.postMessage(message, this.host);
88
+ }
89
+ destroy() {
90
+ window.removeEventListener("message", this.messageHandler);
91
+ this.root.remove();
92
+ }
93
+ close() {
94
+ const backdrop = this.shadow.querySelector(".ok-backdrop");
95
+ if (backdrop) {
96
+ backdrop.classList.add("ok-exit");
97
+ setTimeout(() => {
98
+ this.destroy();
99
+ this.onClose();
100
+ }, 200);
101
+ } else {
102
+ this.destroy();
103
+ this.onClose();
104
+ }
105
+ }
106
+ };
107
+ var WalletPicker = class {
108
+ root;
109
+ shadow;
110
+ constructor(opts) {
111
+ this.root = document.createElement("div");
112
+ this.shadow = this.root.attachShadow({ mode: "closed" });
113
+ const style = document.createElement("style");
114
+ style.textContent = `
18
115
  :host{all:initial}
19
116
  .wp-backdrop{position:fixed;inset:0;background:rgba(0,0,0,0.4);backdrop-filter:blur(4px);z-index:1000000;display:flex;align-items:center;justify-content:center;animation:wp-fade 150ms ease-out}
20
117
  .wp-card{background:#fff;width:340px;border-radius:16px;box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);padding:20px;animation:wp-scale 200ms ease-out}
@@ -37,5 +134,771 @@ import{generateCodeVerifier as O,generateCodeChallenge as A,generateState as I,b
37
134
  .wp-cancel{color:#9ca3af}
38
135
  .wp-cancel:hover{background:#262626;color:#f3f4f6}
39
136
  }
40
- `;let s=document.createElement("div");s.className="wp-backdrop",s.addEventListener("click",i=>{i.target===s&&(this.destroy(),e.onCancel())});let r=document.createElement("div");r.className="wp-card";let o=document.createElement("h2");if(o.className="wp-title",o.textContent="Select a wallet",r.appendChild(o),e.providers.length===0){let i=document.createElement("div");i.className="wp-empty",i.textContent="No wallets detected",r.appendChild(i)}else{let i=document.createElement("ul");i.className="wp-list";for(let{info:c,provider:l}of e.providers){let p=document.createElement("button");if(p.className="wp-item",c.icon){let n=document.createElement("img");n.className="wp-icon",n.src=c.icon,n.alt=c.name,p.appendChild(n)}let u=document.createElement("span");u.textContent=c.name,p.appendChild(u),p.addEventListener("click",()=>{this.destroy(),e.onSelect(l)}),i.appendChild(p)}r.appendChild(i)}let a=document.createElement("button");a.className="wp-cancel",a.textContent="Cancel",a.addEventListener("click",()=>{this.destroy(),e.onCancel()}),r.appendChild(a),s.appendChild(r),this.shadow.appendChild(t),this.shadow.appendChild(s),document.body.appendChild(this.root)}destroy(){this.root.remove()}};function g(h="Opening in new window\u2026",e="info"){let t=e==="error"?"#dc2626":"#1f2937",s=document.createElement("div"),r=s.attachShadow({mode:"closed"});r.innerHTML=`<style>:host{all:initial}.ok-toast{position:fixed;top:16px;right:16px;z-index:1000000;background:${t};color:#f9fafb;padding:10px 16px;border-radius:8px;font:14px/1.4 system-ui,sans-serif;box-shadow:0 4px 12px rgba(0,0,0,0.15);animation:ok-t-in 200ms ease-out;max-width:360px}@keyframes ok-t-in{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}</style><div class="ok-toast">${h}</div>`,document.body.appendChild(s),setTimeout(()=>s.remove(),4e3)}var b=class extends Error{constructor(e){super(e),this.name="ExternalWalletError"}},E=class{host;oauthHost;appName;mode;config;popup=null;lastAuth=null;discoveredProviders=[];sessionToken=null;constructor(e={}){this.config=e,this.host=e.host||S,this.oauthHost=e.oauthHost||this.deriveOAuthHost(this.host),this.appName=e.appName||window.location.hostname,this.mode=e.mode??"iframe",typeof window<"u"&&(this.discoveredProviders=[],window.addEventListener("eip6963:announceProvider",t=>{this.discoveredProviders.push(t.detail)}),window.dispatchEvent(new Event("eip6963:requestProvider")))}deriveOAuthHost(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?e.replace(/\/$/,""):(t.hostname="api."+t.hostname,t.toString().replace(/\/$/,""))}catch{return"https://api.openkey.so"}}async connect(e){let t=await this.openFlow("connect",{type:"openkey:auth:request",appName:this.appName},e?.mode);return this.lastAuth=t,t}async linkWallet(e){return this.openFlow("link-wallet",{type:"openkey:link-wallet:request"},e?.mode)}async signMessage(e,t){return this.lastAuth?.keyType==="EXTERNAL"?this.signWithExternalWallet(e):this.signWithOpenKey(e,t?.mode)}async signTypedData(e,t){return this.lastAuth?.keyType==="EXTERNAL"?this.signTypedDataWithExternalWallet(e):this.signTypedDataWithOpenKey(e,t?.mode)}async findWalletProvider(e){if(this.config.externalProvider)return this.config.externalProvider;for(let{provider:t}of this.discoveredProviders)try{if((await t.request({method:"eth_accounts"})).some(r=>r.toLowerCase()===e.toLowerCase()))return t}catch{}if(typeof window<"u"&&window.ethereum){let t=window.ethereum;try{if((await t.request({method:"eth_accounts"})).some(r=>r.toLowerCase()===e.toLowerCase()))return t}catch{}}throw new b("External wallet not found. Connect the wallet that owns this key and try again.")}async signWithExternalWallet(e){let t;try{t=await this.findWalletProvider(this.lastAuth.address)}catch(s){throw g(s.message,"error"),s}try{let s=this.toHex(e.message);return{signature:await t.request({method:"personal_sign",params:[s,this.lastAuth.address]}),address:this.lastAuth.address}}catch(s){let r=s?.message?.includes("not been authorized")?"Wallet rejected the request. Approve the connection in your wallet and try again.":s?.message||"Signing failed";throw g(r,"error"),new Error(r)}}async signTypedDataWithExternalWallet(e){let t;try{t=await this.findWalletProvider(this.lastAuth.address)}catch(s){throw g(s.message,"error"),s}try{return{signature:await t.request({method:"eth_signTypedData_v4",params:[this.lastAuth.address,JSON.stringify(e)]}),address:this.lastAuth.address}}catch(s){let r=s?.message?.includes("not been authorized")?"Wallet rejected the request. Approve the connection in your wallet and try again.":s?.message||"Signing failed";throw g(r,"error"),new Error(r)}}signWithOpenKey(e,t){return this.openFlow("sign",{type:"openkey:sign:request",message:e.message,keyId:e.keyId,sessionToken:this.sessionToken||void 0},t)}signTypedDataWithOpenKey(e,t){return this.openFlow("sign-typed-data",{type:"openkey:signTypedData:request",data:e,sessionToken:this.sessionToken||void 0},t)}toHex(e){return"0x"+Array.from(new TextEncoder().encode(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}async isConnected(){try{let e=await fetch(`${this.host}/api/auth/session`,{credentials:"include"});return e.ok?!!(await e.json()).user:!1}catch{return!1}}oauth={connect:async e=>{let t=O(),s=await A(t),r=e.state||I();sessionStorage.setItem(k,JSON.stringify({verifier:t,state:r}));let o=M({host:this.oauthHost,clientId:e.clientId,redirectUri:e.redirectUri,codeChallenge:s,state:r,scopes:["openid"]});return this.openOAuthFlow(o,r,e.redirectUri)},exchangeCode:async(e,t)=>{let s=sessionStorage.getItem(k);if(!s)throw new Error("No PKCE verifier found. Start a new OAuth flow.");let{verifier:r}=JSON.parse(s),o=await fetch(`${this.oauthHost}/api/auth/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,redirect_uri:t.redirectUri,client_id:t.clientId,code_verifier:r})});if(sessionStorage.removeItem(k),!o.ok){let a=await o.json();throw new Error(a.error_description||"Token exchange failed")}return o.json()},verifyState:e=>{let t=sessionStorage.getItem(k);if(!t)return!1;let{state:s}=JSON.parse(t);return s===e},parseCallback:e=>{let t=new URL(e||window.location.href),s=t.searchParams.get("error");if(s)return{error:s,errorDescription:t.searchParams.get("error_description")||void 0};let r=t.searchParams.get("code"),o=t.searchParams.get("state");return!r||!o?{error:"missing_params",errorDescription:"Missing code or state parameter"}:{code:r,state:o}}};openOAuthFlow(e,t,s){return new Promise((r,o)=>{this.mode!=="redirect"?this.openOAuthPopup(e,t,s,r,o):window.location.href=e})}openOAuthPopup(e,t,s,r,o){let a=window.screenX+(window.outerWidth-f)/2,i=window.screenY+(window.outerHeight-w)/2;if(this.popup=window.open(e,"openkey-oauth",`width=${f},height=${w},left=${a},top=${i},popup=true`),!this.popup){g("Popup was blocked. Please allow popups for this site.","error"),o({code:"POPUP_BLOCKED",message:"Popup was blocked. Please allow popups or use redirect mode."});return}let c=new URL(s).origin,l=setInterval(()=>{try{if(this.popup?.closed){clearInterval(l),clearTimeout(p),o({code:"USER_CANCELLED",message:"User closed the popup"});return}let u=this.popup?.location?.href;if(u&&u.startsWith(c)){clearInterval(l),clearTimeout(p);let n=new URL(u),m=n.searchParams.get("code"),d=n.searchParams.get("state"),y=n.searchParams.get("error");if(this.popup?.close(),y){o({code:"UNAUTHORIZED",message:n.searchParams.get("error_description")||y});return}if(d!==t){o({code:"STATE_MISMATCH",message:"State mismatch - possible CSRF attack"});return}m?r({code:m,state:d}):o({code:"UNAUTHORIZED",message:"Authorization failed - no code returned"})}}catch{}},100),p=setTimeout(()=>{clearInterval(l),this.popup?.close(),o({code:"TIMEOUT",message:"OAuth flow timed out"})},T)}resolveMode(e){return e??this.mode}hasDetectedEoa(){return!!(this.discoveredProviders.length>0||typeof window<"u"&&window.ethereum)}async openFlow(e,t,s){let r=this.resolveMode(s),o=encodeURIComponent(window.location.origin),a=e==="connect"&&this.hasDetectedEoa()?"&hasEoa=true":"";if(r==="popup"){let c=`${this.host}/widget/${e}?origin=${o}${a}`;return new Promise((l,p)=>this.openPopup(c,t,l,p))}if(r==="redirect"){let c=`${this.host}/widget/${e}?origin=${o}${a}`;return window.location.href=c,new Promise(()=>{})}let i=`${this.host}/widget/embed/${e}?origin=${o}${a}`;return this.openIframeModal(i,e,t,o)}openIframeModal(e,t,s,r){return new Promise((o,a)=>{let i=!1,c=!1,l=null,p=d=>{c||(c=!0,d())},u=()=>{clearTimeout(n),clearTimeout(m),l?.destroy(),l=null};l=new P({url:e,host:this.host,onClose:()=>{p(()=>{clearTimeout(n),clearTimeout(m),l=null,a({code:"USER_CANCELLED",message:"User cancelled the request"})})},onMessage:d=>{if(d.type==="openkey:ready"){i=!0,l?.postMessage(s);return}if(d.type==="openkey:close"){p(()=>{u(),a({code:"USER_CANCELLED",message:"User cancelled the request"})});return}if(d.type==="openkey:link-wallet:delegate"){this.handleWalletLinkDelegation(l);return}if(d.type==="openkey:auth:use-external-wallet"){u(),this.handleExternalWalletConnect(o,a);return}(d.type==="openkey:auth:response"||d.type==="openkey:sign:response"||d.type==="openkey:signTypedData:response"||d.type==="openkey:link-wallet:response")&&p(()=>{u(),d.success?d.type==="openkey:auth:response"?(d.sessionToken&&(this.sessionToken=d.sessionToken),o({address:d.address,keyId:d.keyId,keyType:d.keyType||"MANAGED"})):d.type==="openkey:link-wallet:response"?o({address:d.address,keyId:d.keyId}):o({signature:d.signature,address:d.address}):a(d.error)})}});let n=setTimeout(()=>{if(i||c)return;u(),console.warn("OpenKey: iframe blocked by CSP, falling back to popup. Add frame-src https://openkey.so to your CSP."),g();let d=`${this.host}/widget/${t}?origin=${r}`;this.openPopup(d,s,y=>p(()=>o(y)),y=>p(()=>a(y)))},R),m=setTimeout(()=>{p(()=>{u(),a({code:"TIMEOUT",message:"Request timed out"})})},T)})}handleWalletLinkDelegation(e){let t=s=>e.postMessage(s);new v({providers:this.discoveredProviders,onCancel:()=>{t({type:"openkey:link-wallet:result",success:!1,error:{code:"USER_CANCELLED",message:"Wallet linking cancelled"}})},onSelect:async s=>{try{let o=(await s.request({method:"eth_requestAccounts"}))[0];if(!o)throw new Error("No account returned");let a=await fetch(`${this.host}/api/keys/link/challenge`,{method:"POST",credentials:"include"});if(!a.ok)throw new Error("Failed to get challenge");let{message:i}=await a.json(),c=this.toHex(i),l=await s.request({method:"personal_sign",params:[c,o]}),p=await fetch(`${this.host}/api/keys/link`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({address:o,signature:l,message:i})});if(!p.ok){let n=await p.json();throw new Error(n.error||"Failed to link wallet")}let{key:u}=await p.json();t({type:"openkey:link-wallet:result",success:!0,address:u.address,keyId:u.id})}catch(r){t({type:"openkey:link-wallet:result",success:!1,error:{code:"UNKNOWN",message:r.message||"Wallet linking failed"}})}}})}handleExternalWalletConnect(e,t){new v({providers:this.discoveredProviders,onCancel:()=>{t({code:"USER_CANCELLED",message:"User cancelled wallet selection"})},onSelect:async s=>{try{let o=(await s.request({method:"eth_requestAccounts"}))[0];if(!o)throw new Error("No account returned");let a={address:o,keyId:`external:${o}`,keyType:"EXTERNAL"};this.lastAuth=a,e(a)}catch(r){t({code:"UNKNOWN",message:r.message||"Failed to connect wallet"})}}})}openPopup(e,t,s,r){let o=window.screenX+(window.outerWidth-f)/2,a=window.screenY+(window.outerHeight-w)/2;if(this.popup=window.open(e,"openkey",`width=${f},height=${w},left=${o},top=${a},popup=true`),!this.popup){g("Popup was blocked. Please allow popups for this site.","error"),r({code:"POPUP_BLOCKED",message:"Popup was blocked. Please allow popups for this site."});return}let i=()=>{window.removeEventListener("message",p),clearInterval(c),clearTimeout(l)},c=setInterval(()=>{this.popup?.closed&&(i(),r({code:"USER_CANCELLED",message:"User closed the popup"}))},500),l=setTimeout(()=>{i(),this.popup?.close(),r({code:"TIMEOUT",message:"Request timed out"})},T),p=u=>{if(u.origin!==this.host||u.source!==this.popup)return;let n=u.data;if(n.type==="openkey:ready"){this.popup?.postMessage(t,this.host);return}if(n.type==="openkey:close"){i(),this.popup?.close(),r({code:"USER_CANCELLED",message:"User cancelled the request"});return}if(n.type==="openkey:auth:use-external-wallet"){i(),this.popup?.close(),this.handleExternalWalletConnect(s,r);return}(n.type==="openkey:auth:response"||n.type==="openkey:sign:response"||n.type==="openkey:signTypedData:response"||n.type==="openkey:link-wallet:response")&&(i(),this.popup?.close(),n.success?n.type==="openkey:auth:response"?(n.sessionToken&&(this.sessionToken=n.sessionToken),s({address:n.address,keyId:n.keyId,keyType:n.keyType||"MANAGED"})):n.type==="openkey:link-wallet:response"?s({address:n.address,keyId:n.keyId}):s({signature:n.signature,address:n.address}):r(n.error))};window.addEventListener("message",p)}disconnect(){this.popup?.close(),this.popup=null}},C=class{openkey;address;keyId;keyType;constructor(e,t){this.openkey=e,this.address=t.address,this.keyId=t.keyId,this.keyType=t.keyType}async request({method:e,params:t}){switch(e){case"eth_accounts":case"eth_requestAccounts":return[this.address];case"eth_chainId":return"0x1";case"personal_sign":{if(this.keyType==="EXTERNAL")try{return await(await this.openkey.findWalletProvider(this.address)).request({method:e,params:t})}catch(o){throw g(o?.message||"External wallet signing failed","error"),o}let s=this.hexToString(t[0]);return(await this.openkey.signMessage({message:s,keyId:this.keyId})).signature}case"eth_signTypedData_v4":{if(this.keyType==="EXTERNAL")try{return await(await this.openkey.findWalletProvider(this.address)).request({method:e,params:t})}catch(o){throw g(o?.message||"External wallet signing failed","error"),o}let s=JSON.parse(t[1]);return(await this.openkey.signTypedData(s)).signature}default:throw new Error(`Unsupported method: ${e}`)}}hexToString(e){let t=new Uint8Array((e.startsWith("0x")?e.slice(2):e).match(/.{1,2}/g).map(s=>parseInt(s,16)));return new TextDecoder().decode(t)}},D=E,x=null;function L(h){return(!x||h)&&(x=new E(h)),x}export{E as OpenKey,C as OpenKeyEIP1193Provider,D as default,L as getOpenKey};
137
+ `;
138
+ const backdrop = document.createElement("div");
139
+ backdrop.className = "wp-backdrop";
140
+ backdrop.addEventListener("click", (e) => {
141
+ if (e.target === backdrop) {
142
+ this.destroy();
143
+ opts.onCancel();
144
+ }
145
+ });
146
+ const card = document.createElement("div");
147
+ card.className = "wp-card";
148
+ const title = document.createElement("h2");
149
+ title.className = "wp-title";
150
+ title.textContent = "Select a wallet";
151
+ card.appendChild(title);
152
+ if (opts.providers.length === 0) {
153
+ const empty = document.createElement("div");
154
+ empty.className = "wp-empty";
155
+ empty.textContent = "No wallets detected";
156
+ card.appendChild(empty);
157
+ } else {
158
+ const list = document.createElement("ul");
159
+ list.className = "wp-list";
160
+ for (const { info, provider } of opts.providers) {
161
+ const item = document.createElement("button");
162
+ item.className = "wp-item";
163
+ if (info.icon) {
164
+ const icon = document.createElement("img");
165
+ icon.className = "wp-icon";
166
+ icon.src = info.icon;
167
+ icon.alt = info.name;
168
+ item.appendChild(icon);
169
+ }
170
+ const name = document.createElement("span");
171
+ name.textContent = info.name;
172
+ item.appendChild(name);
173
+ item.addEventListener("click", () => {
174
+ this.destroy();
175
+ opts.onSelect(provider);
176
+ });
177
+ list.appendChild(item);
178
+ }
179
+ card.appendChild(list);
180
+ }
181
+ const cancel = document.createElement("button");
182
+ cancel.className = "wp-cancel";
183
+ cancel.textContent = "Cancel";
184
+ cancel.addEventListener("click", () => {
185
+ this.destroy();
186
+ opts.onCancel();
187
+ });
188
+ card.appendChild(cancel);
189
+ backdrop.appendChild(card);
190
+ this.shadow.appendChild(style);
191
+ this.shadow.appendChild(backdrop);
192
+ document.body.appendChild(this.root);
193
+ }
194
+ destroy() {
195
+ this.root.remove();
196
+ }
197
+ };
198
+ function showToast(message = "Opening in new window\u2026", variant = "info") {
199
+ const bg = variant === "error" ? "#dc2626" : "#1f2937";
200
+ const root = document.createElement("div");
201
+ const shadow = root.attachShadow({ mode: "closed" });
202
+ shadow.innerHTML = `<style>:host{all:initial}.ok-toast{position:fixed;top:16px;right:16px;z-index:1000000;background:${bg};color:#f9fafb;padding:10px 16px;border-radius:8px;font:14px/1.4 system-ui,sans-serif;box-shadow:0 4px 12px rgba(0,0,0,0.15);animation:ok-t-in 200ms ease-out;max-width:360px}@keyframes ok-t-in{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}</style><div class="ok-toast">${message}</div>`;
203
+ document.body.appendChild(root);
204
+ setTimeout(() => root.remove(), 4e3);
205
+ }
206
+ var ExternalWalletError = class extends Error {
207
+ constructor(message) {
208
+ super(message);
209
+ this.name = "ExternalWalletError";
210
+ }
211
+ };
212
+ var OpenKey = class {
213
+ host;
214
+ oauthHost;
215
+ appName;
216
+ mode;
217
+ config;
218
+ popup = null;
219
+ lastAuth = null;
220
+ discoveredProviders = [];
221
+ sessionToken = null;
222
+ constructor(config = {}) {
223
+ this.config = config;
224
+ this.host = config.host || DEFAULT_HOST;
225
+ this.oauthHost = config.oauthHost || this.deriveOAuthHost(this.host);
226
+ this.appName = config.appName || window.location.hostname;
227
+ this.mode = config.mode ?? "iframe";
228
+ if (typeof window !== "undefined") {
229
+ this.discoveredProviders = [];
230
+ window.addEventListener("eip6963:announceProvider", (event) => {
231
+ this.discoveredProviders.push(event.detail);
232
+ });
233
+ window.dispatchEvent(new Event("eip6963:requestProvider"));
234
+ }
235
+ }
236
+ /**
237
+ * Derive the OAuth API host from the main host by prefixing 'api.'
238
+ * @param host - The main host URL
239
+ * @returns The derived OAuth API host URL
240
+ */
241
+ deriveOAuthHost(host) {
242
+ try {
243
+ const url = new URL(host);
244
+ if (url.hostname === "localhost" || url.hostname === "127.0.0.1") {
245
+ return host.replace(/\/$/, "");
246
+ }
247
+ url.hostname = "api." + url.hostname;
248
+ return url.toString().replace(/\/$/, "");
249
+ } catch {
250
+ return "https://api.openkey.so";
251
+ }
252
+ }
253
+ /**
254
+ * Connect to OpenKey and get user's wallet address
255
+ * Opens auth flow for user to select/create a key
256
+ */
257
+ async connect(opts) {
258
+ const result = await this.openFlow("connect", {
259
+ type: "openkey:auth:request",
260
+ appName: this.appName
261
+ }, opts?.mode);
262
+ this.lastAuth = result;
263
+ return result;
264
+ }
265
+ /**
266
+ * Link an external wallet to the user's OpenKey account
267
+ * Opens link-wallet widget flow
268
+ */
269
+ async linkWallet(opts) {
270
+ return this.openFlow("link-wallet", {
271
+ type: "openkey:link-wallet:request"
272
+ }, opts?.mode);
273
+ }
274
+ /**
275
+ * Sign a message with the user's OpenKey wallet
276
+ * For external keys, routes directly to the user's wallet provider
277
+ */
278
+ async signMessage(request, opts) {
279
+ if (this.lastAuth?.keyType === "EXTERNAL") {
280
+ return this.signWithExternalWallet(request);
281
+ }
282
+ return this.signWithOpenKey(request, opts?.mode);
283
+ }
284
+ /**
285
+ * Sign typed data (EIP-712) with the user's OpenKey wallet
286
+ * For external keys, routes directly to the user's wallet provider
287
+ */
288
+ async signTypedData(request, opts) {
289
+ if (this.lastAuth?.keyType === "EXTERNAL") {
290
+ return this.signTypedDataWithExternalWallet(request);
291
+ }
292
+ return this.signTypedDataWithOpenKey(request, opts?.mode);
293
+ }
294
+ /**
295
+ * Find a wallet provider that controls the given address.
296
+ * Checks: 1) app-provided externalProvider, 2) EIP-6963 discovered wallets, 3) window.ethereum
297
+ */
298
+ async findWalletProvider(targetAddress) {
299
+ if (this.config.externalProvider) {
300
+ return this.config.externalProvider;
301
+ }
302
+ for (const { provider } of this.discoveredProviders) {
303
+ try {
304
+ const accounts = await provider.request({ method: "eth_accounts" });
305
+ if (accounts.some((a) => a.toLowerCase() === targetAddress.toLowerCase())) {
306
+ return provider;
307
+ }
308
+ } catch {
309
+ }
310
+ }
311
+ if (typeof window !== "undefined" && window.ethereum) {
312
+ const provider = window.ethereum;
313
+ try {
314
+ const accounts = await provider.request({ method: "eth_accounts" });
315
+ if (accounts.some((a) => a.toLowerCase() === targetAddress.toLowerCase())) {
316
+ return provider;
317
+ }
318
+ } catch {
319
+ }
320
+ }
321
+ throw new ExternalWalletError("External wallet not found. Connect the wallet that owns this key and try again.");
322
+ }
323
+ async signWithExternalWallet(request) {
324
+ let provider;
325
+ try {
326
+ provider = await this.findWalletProvider(this.lastAuth.address);
327
+ } catch (e) {
328
+ showToast(e.message, "error");
329
+ throw e;
330
+ }
331
+ try {
332
+ const hexMessage = this.toHex(request.message);
333
+ const signature = await provider.request({
334
+ method: "personal_sign",
335
+ params: [hexMessage, this.lastAuth.address]
336
+ });
337
+ return { signature, address: this.lastAuth.address };
338
+ } catch (e) {
339
+ const msg = e?.message?.includes("not been authorized") ? "Wallet rejected the request. Approve the connection in your wallet and try again." : e?.message || "Signing failed";
340
+ showToast(msg, "error");
341
+ throw new Error(msg);
342
+ }
343
+ }
344
+ async signTypedDataWithExternalWallet(request) {
345
+ let provider;
346
+ try {
347
+ provider = await this.findWalletProvider(this.lastAuth.address);
348
+ } catch (e) {
349
+ showToast(e.message, "error");
350
+ throw e;
351
+ }
352
+ try {
353
+ const signature = await provider.request({
354
+ method: "eth_signTypedData_v4",
355
+ params: [this.lastAuth.address, JSON.stringify(request)]
356
+ });
357
+ return { signature, address: this.lastAuth.address };
358
+ } catch (e) {
359
+ const msg = e?.message?.includes("not been authorized") ? "Wallet rejected the request. Approve the connection in your wallet and try again." : e?.message || "Signing failed";
360
+ showToast(msg, "error");
361
+ throw new Error(msg);
362
+ }
363
+ }
364
+ signWithOpenKey(request, mode) {
365
+ return this.openFlow("sign", {
366
+ type: "openkey:sign:request",
367
+ message: request.message,
368
+ keyId: request.keyId,
369
+ sessionToken: this.sessionToken || void 0
370
+ }, mode);
371
+ }
372
+ signTypedDataWithOpenKey(request, mode) {
373
+ return this.openFlow("sign-typed-data", {
374
+ type: "openkey:signTypedData:request",
375
+ data: request,
376
+ sessionToken: this.sessionToken || void 0
377
+ }, mode);
378
+ }
379
+ toHex(str) {
380
+ return "0x" + Array.from(new TextEncoder().encode(str)).map((b) => b.toString(16).padStart(2, "0")).join("");
381
+ }
382
+ /**
383
+ * Check if user is already authenticated
384
+ */
385
+ async isConnected() {
386
+ try {
387
+ const res = await fetch(`${this.host}/api/auth/session`, {
388
+ credentials: "include"
389
+ });
390
+ if (!res.ok) return false;
391
+ const data = await res.json();
392
+ return !!data.user;
393
+ } catch {
394
+ return false;
395
+ }
396
+ }
397
+ // ======= OAuth 2.1 Provider Methods =======
398
+ /**
399
+ * OAuth 2.1 methods for third-party app authentication
400
+ * Use this when your app has registered OAuth client credentials with OpenKey
401
+ */
402
+ oauth = {
403
+ /**
404
+ * Start OAuth authorization flow
405
+ * Opens popup/redirect to OpenKey authorization endpoint
406
+ * @returns Promise that resolves with authorization code after user consent
407
+ */
408
+ connect: async (config) => {
409
+ const verifier = generateCodeVerifier();
410
+ const challenge = await generateCodeChallenge(verifier);
411
+ const state = config.state || generateState();
412
+ sessionStorage.setItem(
413
+ OAUTH_STORAGE_KEY,
414
+ JSON.stringify({ verifier, state })
415
+ );
416
+ const authUrl = buildAuthorizationUrl({
417
+ host: this.oauthHost,
418
+ clientId: config.clientId,
419
+ redirectUri: config.redirectUri,
420
+ codeChallenge: challenge,
421
+ state,
422
+ scopes: ["openid"]
423
+ });
424
+ return this.openOAuthFlow(authUrl, state, config.redirectUri);
425
+ },
426
+ /**
427
+ * Exchange authorization code for tokens
428
+ * Call this after receiving the callback with authorization code
429
+ * @param code - Authorization code from callback URL
430
+ * @param config - Same config used for connect()
431
+ * @returns Promise that resolves with access_token, id_token, etc.
432
+ */
433
+ exchangeCode: async (code, config) => {
434
+ const stored = sessionStorage.getItem(OAUTH_STORAGE_KEY);
435
+ if (!stored) {
436
+ throw new Error("No PKCE verifier found. Start a new OAuth flow.");
437
+ }
438
+ const { verifier } = JSON.parse(stored);
439
+ const response = await fetch(`${this.oauthHost}/api/auth/oauth2/token`, {
440
+ method: "POST",
441
+ headers: {
442
+ "Content-Type": "application/x-www-form-urlencoded"
443
+ },
444
+ body: new URLSearchParams({
445
+ grant_type: "authorization_code",
446
+ code,
447
+ redirect_uri: config.redirectUri,
448
+ client_id: config.clientId,
449
+ code_verifier: verifier
450
+ })
451
+ });
452
+ sessionStorage.removeItem(OAUTH_STORAGE_KEY);
453
+ if (!response.ok) {
454
+ const error = await response.json();
455
+ throw new Error(error.error_description || "Token exchange failed");
456
+ }
457
+ return response.json();
458
+ },
459
+ /**
460
+ * Verify state parameter from callback
461
+ * Call this before exchangeCode to prevent CSRF attacks
462
+ * @param receivedState - State parameter from callback URL
463
+ * @returns true if state matches, false otherwise
464
+ */
465
+ verifyState: (receivedState) => {
466
+ const stored = sessionStorage.getItem(OAUTH_STORAGE_KEY);
467
+ if (!stored) return false;
468
+ const { state } = JSON.parse(stored);
469
+ return state === receivedState;
470
+ },
471
+ /**
472
+ * Parse authorization response from callback URL
473
+ * @param url - Callback URL (defaults to current window.location.href)
474
+ * @returns Parsed code and state, or error
475
+ */
476
+ parseCallback: (url) => {
477
+ const urlObj = new URL(url || window.location.href);
478
+ const error = urlObj.searchParams.get("error");
479
+ if (error) {
480
+ return {
481
+ error,
482
+ errorDescription: urlObj.searchParams.get("error_description") || void 0
483
+ };
484
+ }
485
+ const code = urlObj.searchParams.get("code");
486
+ const state = urlObj.searchParams.get("state");
487
+ if (!code || !state) {
488
+ return { error: "missing_params", errorDescription: "Missing code or state parameter" };
489
+ }
490
+ return { code, state };
491
+ }
492
+ };
493
+ openOAuthFlow(url, state, redirectUri) {
494
+ return new Promise((resolve, reject) => {
495
+ if (this.mode !== "redirect") {
496
+ this.openOAuthPopup(url, state, redirectUri, resolve, reject);
497
+ } else {
498
+ window.location.href = url;
499
+ }
500
+ });
501
+ }
502
+ openOAuthPopup(url, state, redirectUri, resolve, reject) {
503
+ const left = window.screenX + (window.outerWidth - POPUP_WIDTH) / 2;
504
+ const top = window.screenY + (window.outerHeight - POPUP_HEIGHT) / 2;
505
+ this.popup = window.open(
506
+ url,
507
+ "openkey-oauth",
508
+ `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},popup=true`
509
+ );
510
+ if (!this.popup) {
511
+ showToast("Popup was blocked. Please allow popups for this site.", "error");
512
+ reject({
513
+ code: "POPUP_BLOCKED",
514
+ message: "Popup was blocked. Please allow popups or use redirect mode."
515
+ });
516
+ return;
517
+ }
518
+ const redirectHost = new URL(redirectUri).origin;
519
+ const pollInterval = setInterval(() => {
520
+ try {
521
+ if (this.popup?.closed) {
522
+ clearInterval(pollInterval);
523
+ clearTimeout(timeout);
524
+ reject({
525
+ code: "USER_CANCELLED",
526
+ message: "User closed the popup"
527
+ });
528
+ return;
529
+ }
530
+ const popupUrl = this.popup?.location?.href;
531
+ if (popupUrl && popupUrl.startsWith(redirectHost)) {
532
+ clearInterval(pollInterval);
533
+ clearTimeout(timeout);
534
+ const urlObj = new URL(popupUrl);
535
+ const code = urlObj.searchParams.get("code");
536
+ const returnedState = urlObj.searchParams.get("state");
537
+ const error = urlObj.searchParams.get("error");
538
+ this.popup?.close();
539
+ if (error) {
540
+ reject({
541
+ code: "UNAUTHORIZED",
542
+ message: urlObj.searchParams.get("error_description") || error
543
+ });
544
+ return;
545
+ }
546
+ if (returnedState !== state) {
547
+ reject({
548
+ code: "STATE_MISMATCH",
549
+ message: "State mismatch - possible CSRF attack"
550
+ });
551
+ return;
552
+ }
553
+ if (code) {
554
+ resolve({ code, state: returnedState });
555
+ } else {
556
+ reject({
557
+ code: "UNAUTHORIZED",
558
+ message: "Authorization failed - no code returned"
559
+ });
560
+ }
561
+ }
562
+ } catch {
563
+ }
564
+ }, 100);
565
+ const timeout = setTimeout(() => {
566
+ clearInterval(pollInterval);
567
+ this.popup?.close();
568
+ reject({
569
+ code: "TIMEOUT",
570
+ message: "OAuth flow timed out"
571
+ });
572
+ }, DEFAULT_TIMEOUT);
573
+ }
574
+ resolveMode(override) {
575
+ return override ?? this.mode;
576
+ }
577
+ hasDetectedEoa() {
578
+ if (this.discoveredProviders.length > 0) return true;
579
+ if (typeof window !== "undefined" && window.ethereum) return true;
580
+ return false;
581
+ }
582
+ async openFlow(action, message, modeOverride) {
583
+ const mode = this.resolveMode(modeOverride);
584
+ const origin = encodeURIComponent(window.location.origin);
585
+ const eoaFlag = action === "connect" && this.hasDetectedEoa() ? "&hasEoa=true" : "";
586
+ if (mode === "popup") {
587
+ const url2 = `${this.host}/widget/${action}?origin=${origin}${eoaFlag}`;
588
+ return new Promise((resolve, reject) => this.openPopup(url2, message, resolve, reject));
589
+ }
590
+ if (mode === "redirect") {
591
+ const url2 = `${this.host}/widget/${action}?origin=${origin}${eoaFlag}`;
592
+ window.location.href = url2;
593
+ return new Promise(() => {
594
+ });
595
+ }
596
+ const url = `${this.host}/widget/embed/${action}?origin=${origin}${eoaFlag}`;
597
+ return this.openIframeModal(url, action, message, origin);
598
+ }
599
+ openIframeModal(url, action, message, origin) {
600
+ return new Promise((resolve, reject) => {
601
+ let readyReceived = false;
602
+ let settled = false;
603
+ let modal = null;
604
+ const settle = (fn) => {
605
+ if (settled) return;
606
+ settled = true;
607
+ fn();
608
+ };
609
+ const cleanup = () => {
610
+ clearTimeout(readyTimeout);
611
+ clearTimeout(overallTimeout);
612
+ modal?.destroy();
613
+ modal = null;
614
+ };
615
+ modal = new IframeModal({
616
+ url,
617
+ host: this.host,
618
+ onClose: () => {
619
+ settle(() => {
620
+ clearTimeout(readyTimeout);
621
+ clearTimeout(overallTimeout);
622
+ modal = null;
623
+ reject({ code: "USER_CANCELLED", message: "User cancelled the request" });
624
+ });
625
+ },
626
+ onMessage: (data) => {
627
+ if (data.type === "openkey:ready") {
628
+ readyReceived = true;
629
+ modal?.postMessage(message);
630
+ return;
631
+ }
632
+ if (data.type === "openkey:close") {
633
+ settle(() => {
634
+ cleanup();
635
+ reject({ code: "USER_CANCELLED", message: "User cancelled the request" });
636
+ });
637
+ return;
638
+ }
639
+ if (data.type === "openkey:link-wallet:delegate") {
640
+ this.handleWalletLinkDelegation(modal);
641
+ return;
642
+ }
643
+ if (data.type === "openkey:auth:use-external-wallet") {
644
+ cleanup();
645
+ this.handleExternalWalletConnect(resolve, reject);
646
+ return;
647
+ }
648
+ if (data.type === "openkey:auth:response" || data.type === "openkey:sign:response" || data.type === "openkey:signTypedData:response" || data.type === "openkey:link-wallet:response") {
649
+ settle(() => {
650
+ cleanup();
651
+ if (data.success) {
652
+ if (data.type === "openkey:auth:response") {
653
+ if (data.sessionToken) this.sessionToken = data.sessionToken;
654
+ resolve({ address: data.address, keyId: data.keyId, keyType: data.keyType || "MANAGED" });
655
+ } else if (data.type === "openkey:link-wallet:response") {
656
+ resolve({ address: data.address, keyId: data.keyId });
657
+ } else {
658
+ resolve({ signature: data.signature, address: data.address });
659
+ }
660
+ } else {
661
+ reject(data.error);
662
+ }
663
+ });
664
+ }
665
+ }
666
+ });
667
+ const readyTimeout = setTimeout(() => {
668
+ if (readyReceived || settled) return;
669
+ cleanup();
670
+ console.warn("OpenKey: iframe blocked by CSP, falling back to popup. Add frame-src https://openkey.so to your CSP.");
671
+ showToast();
672
+ const popupUrl = `${this.host}/widget/${action}?origin=${origin}`;
673
+ this.openPopup(popupUrl, message, (val) => settle(() => resolve(val)), (err) => settle(() => reject(err)));
674
+ }, IFRAME_READY_TIMEOUT);
675
+ const overallTimeout = setTimeout(() => {
676
+ settle(() => {
677
+ cleanup();
678
+ reject({ code: "TIMEOUT", message: "Request timed out" });
679
+ });
680
+ }, DEFAULT_TIMEOUT);
681
+ });
682
+ }
683
+ handleWalletLinkDelegation(modal) {
684
+ const sendResult = (result) => modal.postMessage(result);
685
+ new WalletPicker({
686
+ providers: this.discoveredProviders,
687
+ onCancel: () => {
688
+ sendResult({ type: "openkey:link-wallet:result", success: false, error: { code: "USER_CANCELLED", message: "Wallet linking cancelled" } });
689
+ },
690
+ onSelect: async (provider) => {
691
+ try {
692
+ const accounts = await provider.request({ method: "eth_requestAccounts" });
693
+ const address = accounts[0];
694
+ if (!address) throw new Error("No account returned");
695
+ const challengeRes = await fetch(`${this.host}/api/keys/link/challenge`, {
696
+ method: "POST",
697
+ credentials: "include"
698
+ });
699
+ if (!challengeRes.ok) throw new Error("Failed to get challenge");
700
+ const { message } = await challengeRes.json();
701
+ const hexMessage = this.toHex(message);
702
+ const signature = await provider.request({
703
+ method: "personal_sign",
704
+ params: [hexMessage, address]
705
+ });
706
+ const linkRes = await fetch(`${this.host}/api/keys/link`, {
707
+ method: "POST",
708
+ headers: { "Content-Type": "application/json" },
709
+ credentials: "include",
710
+ body: JSON.stringify({ address, signature, message })
711
+ });
712
+ if (!linkRes.ok) {
713
+ const err = await linkRes.json();
714
+ throw new Error(err.error || "Failed to link wallet");
715
+ }
716
+ const { key } = await linkRes.json();
717
+ sendResult({ type: "openkey:link-wallet:result", success: true, address: key.address, keyId: key.id });
718
+ } catch (e) {
719
+ sendResult({ type: "openkey:link-wallet:result", success: false, error: { code: "UNKNOWN", message: e.message || "Wallet linking failed" } });
720
+ }
721
+ }
722
+ });
723
+ }
724
+ handleExternalWalletConnect(resolve, reject) {
725
+ new WalletPicker({
726
+ providers: this.discoveredProviders,
727
+ onCancel: () => {
728
+ reject({ code: "USER_CANCELLED", message: "User cancelled wallet selection" });
729
+ },
730
+ onSelect: async (provider) => {
731
+ try {
732
+ const accounts = await provider.request({ method: "eth_requestAccounts" });
733
+ const address = accounts[0];
734
+ if (!address) throw new Error("No account returned");
735
+ const result = { address, keyId: `external:${address}`, keyType: "EXTERNAL" };
736
+ this.lastAuth = result;
737
+ resolve(result);
738
+ } catch (e) {
739
+ reject({ code: "UNKNOWN", message: e.message || "Failed to connect wallet" });
740
+ }
741
+ }
742
+ });
743
+ }
744
+ openPopup(url, message, resolve, reject) {
745
+ const left = window.screenX + (window.outerWidth - POPUP_WIDTH) / 2;
746
+ const top = window.screenY + (window.outerHeight - POPUP_HEIGHT) / 2;
747
+ this.popup = window.open(
748
+ url,
749
+ "openkey",
750
+ `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},popup=true`
751
+ );
752
+ if (!this.popup) {
753
+ showToast("Popup was blocked. Please allow popups for this site.", "error");
754
+ reject({
755
+ code: "POPUP_BLOCKED",
756
+ message: "Popup was blocked. Please allow popups for this site."
757
+ });
758
+ return;
759
+ }
760
+ const cleanup = () => {
761
+ window.removeEventListener("message", handleMessage);
762
+ clearInterval(pollClosed);
763
+ clearTimeout(timeout);
764
+ };
765
+ const pollClosed = setInterval(() => {
766
+ if (this.popup?.closed) {
767
+ cleanup();
768
+ reject({
769
+ code: "USER_CANCELLED",
770
+ message: "User closed the popup"
771
+ });
772
+ }
773
+ }, 500);
774
+ const timeout = setTimeout(() => {
775
+ cleanup();
776
+ this.popup?.close();
777
+ reject({
778
+ code: "TIMEOUT",
779
+ message: "Request timed out"
780
+ });
781
+ }, DEFAULT_TIMEOUT);
782
+ const handleMessage = (event) => {
783
+ if (event.origin !== this.host) return;
784
+ if (event.source !== this.popup) return;
785
+ const data = event.data;
786
+ if (data.type === "openkey:ready") {
787
+ this.popup?.postMessage(message, this.host);
788
+ return;
789
+ }
790
+ if (data.type === "openkey:close") {
791
+ cleanup();
792
+ this.popup?.close();
793
+ reject({
794
+ code: "USER_CANCELLED",
795
+ message: "User cancelled the request"
796
+ });
797
+ return;
798
+ }
799
+ if (data.type === "openkey:auth:use-external-wallet") {
800
+ cleanup();
801
+ this.popup?.close();
802
+ this.handleExternalWalletConnect(resolve, reject);
803
+ return;
804
+ }
805
+ if (data.type === "openkey:auth:response" || data.type === "openkey:sign:response" || data.type === "openkey:signTypedData:response" || data.type === "openkey:link-wallet:response") {
806
+ cleanup();
807
+ this.popup?.close();
808
+ if (data.success) {
809
+ if (data.type === "openkey:auth:response") {
810
+ if (data.sessionToken) this.sessionToken = data.sessionToken;
811
+ resolve({ address: data.address, keyId: data.keyId, keyType: data.keyType || "MANAGED" });
812
+ } else if (data.type === "openkey:link-wallet:response") {
813
+ resolve({ address: data.address, keyId: data.keyId });
814
+ } else {
815
+ resolve({ signature: data.signature, address: data.address });
816
+ }
817
+ } else {
818
+ reject(data.error);
819
+ }
820
+ }
821
+ };
822
+ window.addEventListener("message", handleMessage);
823
+ }
824
+ /**
825
+ * Disconnect and close any open flows
826
+ */
827
+ disconnect() {
828
+ this.popup?.close();
829
+ this.popup = null;
830
+ }
831
+ };
832
+ var OpenKeyProvider = class {
833
+ openkey;
834
+ address;
835
+ keyId;
836
+ keyType;
837
+ constructor(openkey, authResult) {
838
+ this.openkey = openkey;
839
+ this.address = authResult.address;
840
+ this.keyId = authResult.keyId;
841
+ this.keyType = authResult.keyType;
842
+ }
843
+ async request({ method, params }) {
844
+ switch (method) {
845
+ case "eth_accounts":
846
+ case "eth_requestAccounts":
847
+ return [this.address];
848
+ case "eth_chainId":
849
+ return "0x1";
850
+ // mainnet
851
+ case "personal_sign": {
852
+ if (this.keyType === "EXTERNAL") {
853
+ try {
854
+ const provider = await this.openkey.findWalletProvider(this.address);
855
+ return await provider.request({ method, params });
856
+ } catch (e) {
857
+ showToast(e?.message || "External wallet signing failed", "error");
858
+ throw e;
859
+ }
860
+ }
861
+ const message = this.hexToString(params[0]);
862
+ const result = await this.openkey.signMessage({ message, keyId: this.keyId });
863
+ return result.signature;
864
+ }
865
+ case "eth_signTypedData_v4": {
866
+ if (this.keyType === "EXTERNAL") {
867
+ try {
868
+ const provider = await this.openkey.findWalletProvider(this.address);
869
+ return await provider.request({ method, params });
870
+ } catch (e) {
871
+ showToast(e?.message || "External wallet signing failed", "error");
872
+ throw e;
873
+ }
874
+ }
875
+ const data = JSON.parse(params[1]);
876
+ const result = await this.openkey.signTypedData(data);
877
+ return result.signature;
878
+ }
879
+ default:
880
+ throw new Error(`Unsupported method: ${method}`);
881
+ }
882
+ }
883
+ hexToString(hex) {
884
+ const bytes = new Uint8Array(
885
+ (hex.startsWith("0x") ? hex.slice(2) : hex).match(/.{1,2}/g).map((b) => parseInt(b, 16))
886
+ );
887
+ return new TextDecoder().decode(bytes);
888
+ }
889
+ };
890
+ var index_default = OpenKey;
891
+ var defaultInstance = null;
892
+ function getOpenKey(config) {
893
+ if (!defaultInstance || config) {
894
+ defaultInstance = new OpenKey(config);
895
+ }
896
+ return defaultInstance;
897
+ }
898
+ export {
899
+ OpenKey,
900
+ OpenKeyProvider,
901
+ index_default as default,
902
+ getOpenKey
903
+ };
41
904
  //# sourceMappingURL=index.mjs.map