@stacknet/userutils 0.2.4 → 0.2.41

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.
@@ -1,2 +1,2 @@
1
- 'use strict';var react=require('react'),jsxRuntime=require('react/jsx-runtime');var ge=react.createContext(null);function We(){let e=react.useContext(ge);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function Re({config:e,callbacks:n,children:r}){return jsxRuntime.jsx(ge.Provider,{value:{config:e,callbacks:n},children:r})}function he(){let[e,n]=react.useState({connected:false,address:null,chain:null,provider:null}),[r,l]=react.useState(null),h=react.useCallback(async(p="phantom")=>{l(null);try{let d=typeof window<"u"?window:null,b=p==="phantom"?d?.phantom?.solana||d?.solana:d?.solflare;if(!b)return l(`${p} wallet not found`),null;let u=(await b.connect()).publicKey.toString();return n({connected:!0,address:u,chain:"solana",provider:p}),u}catch(d){return l(d.message||"Failed to connect wallet"),null}},[]),y=react.useCallback(async()=>{l(null);try{let d=(typeof window<"u"?window:null)?.ethereum;if(!d)return l("MetaMask not found"),null;let b=d;d.providers?.length&&(b=d.providers.find(t=>t.isMetaMask)||d);let u=(await b.request({method:"eth_requestAccounts"}))[0];return u?(n({connected:!0,address:u,chain:"ethereum",provider:"metamask"}),u):(l("No account selected"),null)}catch(p){return l(p.message||"Failed to connect wallet"),null}},[]),g=react.useCallback(async(p,d)=>{l(null);let b=d?.chain||e.chain,s=d?.provider||e.provider,u=d?.address||e.address;try{if(b==="solana"){let t=typeof window<"u"?window:null,o=s==="solflare"?t?.solflare:t?.phantom?.solana||t?.solana;if(!o)throw new Error("Wallet not available");let c=new TextEncoder().encode(p),w=await o.signMessage(c,"utf8"),S=w.signature||w,N="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",I=BigInt(0);for(let x of S)I=I*256n+BigInt(x);let M="";for(;I>0n;)M=N[Number(I%58n)]+M,I=I/58n;for(let x of S)if(x===0)M="1"+M;else break;return M}if(b==="ethereum"){let o=(typeof window<"u"?window:null)?.ethereum;if(o?.providers?.length&&(o=o.providers.find(w=>w.isMetaMask)||o),!o)throw new Error("MetaMask not available");return await o.request({method:"personal_sign",params:[p,u]})}throw new Error("No wallet connected")}catch(t){return l(t.message||"Signing failed"),null}},[e]),i=react.useCallback(()=>{n({connected:false,address:null,chain:null,provider:null}),l(null);},[]);return {wallet:e,error:r,connectSolana:h,connectEVM:y,signMessage:g,disconnect:i}}function ke(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith("stackauth_session="));if(!e)return null;let n=e.slice(18);return JSON.parse(atob(n.replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function ye(e="__csrf"){if(typeof document>"u")return null;let n=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith(`${e}=`));return n?n.slice(e.length+1):null}function Ne(){let[e,n]=react.useState(null),[r,l]=react.useState(true),h=react.useCallback(()=>{let i=ke();i&&i.expiresAt>Date.now()?n({userId:i.userId,address:i.address,chain:i.chain,expiresAt:i.expiresAt,planId:i.planId,authMethod:i.authMethod}):n(null),l(false);},[]);react.useEffect(()=>{h();},[h]);let y=react.useCallback(async(i="")=>{try{let p=await fetch(`${i}/api/auth/session`);if(p.ok){let d=await p.json();if(d.session)return n(d.session),d.session}return n(null),null}catch{return null}},[]),g=!!e&&e.expiresAt>Date.now();return {session:e,loading:r,isAuthenticated:g,refresh:y,readSession:h}}function xe(e="__csrf",n="x-csrf-token"){let[r,l]=react.useState(null);react.useEffect(()=>{l(ye(e));},[e]);let h=r?{[n]:r}:{};return {token:r,headers:h}}var Ge="https://stacknet.magma-rpc.com/auth/bridge",J="stacknet-auth-bridge";function Ce(e){let n=e?.bridgeUrl||Ge,r=e?.disabled||false,l=react.useRef(null),[h,y]=react.useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),g=react.useRef([]),i=react.useRef(false),p=react.useCallback(t=>{let o={...t,protocol:J};i.current&&l.current?.contentWindow?l.current.contentWindow.postMessage(o,new URL(n).origin):g.current.push(o);},[n]);react.useEffect(()=>{if(r)return;let t=c=>{if(!(!c.data||c.data.protocol!==J)){try{if(c.origin!==new URL(n).origin)return}catch{return}switch(c.data.type){case "bridge:ready":i.current=true,y(w=>({...w,ready:true}));for(let w of g.current)l.current?.contentWindow?.postMessage(w,c.origin);g.current=[],l.current?.contentWindow?.postMessage({protocol:J,type:"auth:check"},c.origin),l.current?.contentWindow?.postMessage({protocol:J,type:"auth:resolve-stack"},c.origin);break;case "auth:status":y(w=>({...w,known:c.data.known,identity:c.data.identity,identityCount:c.data.identityCount||0}));break;case "auth:resolved-stack":y(w=>({...w,resolvedStackId:c.data.stackId||null}));break;}}};window.addEventListener("message",t);let o=document.createElement("iframe");return o.src=n,o.style.display="none",o.setAttribute("aria-hidden","true"),o.setAttribute("tabindex","-1"),o.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(o),l.current=o,()=>{window.removeEventListener("message",t),o.parentNode&&o.parentNode.removeChild(o),l.current=null,i.current=false;}},[n,r]);let d=react.useCallback(t=>{p({type:"auth:connected",...t});},[p]),b=react.useCallback(t=>{p({type:"auth:disconnected",...t});},[p]),s=react.useCallback(()=>{p({type:"auth:clear"}),y({ready:h.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[p,h.ready]),u=react.useCallback(()=>{p({type:"auth:check"});},[p]);return {...h,reportConnected:d,reportDisconnected:b,clearAll:s,refresh:u}}async function Me(e,n,r,l){let h=e.apiVersion||"v2",y=`${e.baseUrl}/api/${h}${r}`;try{let g=await fetch(y,{method:n,headers:{"Content-Type":"application/json"},body:l?JSON.stringify(l):void 0}),i=await g.json();return g.ok?i.success&&i.data!==void 0?{success:!0,data:i.data}:{success:!0,data:i}:{success:!1,error:i.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(g){return {success:false,error:{code:"NETWORK_ERROR",message:g instanceof Error?g.message:"Network error"}}}}function ve(e){return {getNetworkStatus:()=>Me(e,"GET","/network/status"),getWeb3Challenge:(n,r)=>Me(e,"POST",`/stacks/${e.stackId}/auth/web3/challenge`,{chain:n,address:r})}}function Ie(e={apiBaseUrl:""}){let{wallet:n,connectSolana:r,connectEVM:l,signMessage:h,disconnect:y}=he(),{session:g,isAuthenticated:i,refresh:p,readSession:d}=Ne(),{headers:b}=xe(),s=Ce({disabled:typeof window>"u"}),[u,t]=react.useState(false),[o,c]=react.useState(null),[w,S]=react.useState(false),N=e.apiBaseUrl||"",I=e.stacknetUrl||"https://stacknet.magma-rpc.com",M=e.stackId||s.resolvedStackId||"",x=ve({baseUrl:I,stackId:M}),L=react.useCallback(async(k,C,R,D)=>{t(true),c(null);try{let U=C;if(!U){let E=await R();if(!E)return t(!1),!1;U=E;}let T=await x.getWeb3Challenge(k,U);if(!T.success||!T.data)return c("Failed to get challenge"),t(!1),!1;let _=await h(T.data.message,{chain:k,provider:D,address:U});if(!_)return t(!1),!1;let B={chain:k,message:T.data.message,signature:_};k==="solana"&&(B.publicKey=U);let O=await fetch(`${N}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!O.ok){let E=await O.json().catch(()=>({}));return c(E.error||"Authentication failed"),t(!1),!1}return s.reportConnected({address:U,chain:k,method:D||(k==="solana"?"phantom":"metamask"),stackId:M}),d(),t(!1),!0}catch(U){return c(U.message||"Authentication failed"),t(false),false}},[N,x,h,d,s,M]),P=react.useCallback(async(k="phantom")=>{let C=await r(k);return C?L("solana",C,()=>r(k),k):false},[r,L]),z=react.useCallback(async()=>{let k=await l();return k?L("ethereum",k,l,"metamask"):false},[l,L]),Z=react.useCallback(async k=>{t(true),c(null);try{let C=await fetch(`${N}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:k})});if(!C.ok){let R=await C.json().catch(()=>({}));return c(R.error||"Invalid code"),t(!1),!1}return d(),t(!1),!0}catch(C){return c(C.message||"OTP verification failed"),t(false),false}},[N,d]),V=react.useCallback(async()=>{n.address&&n.chain&&s.reportDisconnected({address:n.address,chain:n.chain,stackId:M});try{await fetch(`${N}/api/auth/logout`,{method:"POST",headers:b});}catch{}y(),d();},[N,b,y,d,n,s,M]);return react.useEffect(()=>{if(!e.autoConnect||w||i||!s.ready||!s.known||!s.identity)return;S(true);let{chain:k,method:C}=s.identity;k==="solana"&&(C==="phantom"||C==="solflare")?P(C):k==="ethereum"&&z();},[e.autoConnect,w,i,s,P,z]),{session:g,isAuthenticated:i,wallet:n,loading:u,error:o,authenticateSolana:P,authenticateEVM:z,authenticateOTP:Z,logout:V,refresh:()=>p(N),stackId:M,bridge:{ready:s.ready,known:s.known,identity:s.identity,identityCount:s.identityCount,resolvedStackId:s.resolvedStackId}}}function Le(e,n="https://stacknet.magma-rpc.com"){let[r,l]=react.useState(null),[h,y]=react.useState(false),[g,i]=react.useState(null),p=react.useCallback(async b=>{y(true),i(null);try{let s=await fetch(`${n}/api/v2/stacks/${b}`);if(!s.ok)return i("Stack not found"),y(!1),null;let u=await s.json(),t=u.data?.stack||u.stack||u,o={id:t.id,name:t.name,displayName:t.displayName||t.name,description:t.description,logoUrl:t.logoUrl,webPageUrl:t.webPageUrl,allowedChains:t.allowedChains||[],features:t.features,stripeProvider:t.stripeProvider,oauthProviders:t.oauthProviders?.map(c=>({provider:c.provider,enabled:c.enabled!==!1}))};return l(o),y(!1),o}catch(s){return i(s.message),y(false),null}},[n]);react.useEffect(()=>{e&&p(e);},[e,p]);let d=r?Ke(r):[];return {config:r,loading:h,error:g,identityProviders:d,fetchConfig:p}}function Ke(e){let n=[];if(e.features?.web3Auth!==false&&(e.allowedChains.includes("solana")&&(n.push({type:"wallet",id:"phantom",name:"Phantom",chain:"solana"}),n.push({type:"wallet",id:"solflare",name:"Solflare",chain:"solana"})),(e.allowedChains.includes("ethereum")||e.allowedChains.includes("polygon")||e.allowedChains.includes("base"))&&n.push({type:"wallet",id:"metamask",name:"MetaMask",chain:"ethereum"})),e.features?.apiKeyAuth!==false&&n.push({type:"otp",id:"otp",name:"Access Code"}),e.features?.oauthAuth&&e.oauthProviders)for(let r of e.oauthProviders)r.enabled&&n.push({type:"oauth",id:r.provider,name:r.provider});return n}function q({length:e=6,onComplete:n,disabled:r=false,error:l,className:h="",inputClassName:y=""}){let [g,i]=react.useState(Array(e).fill("")),p=react.useCallback((s,u)=>{if(u.length>1){let o=u.replace(/\D/g,"").slice(0,e).split(""),c=[...g];o.forEach((S,N)=>{s+N<e&&(c[s+N]=S);}),i(c);let w=Math.min(s+o.length,e-1);document.getElementById(`userutils-otp-${w}`)?.focus(),c.every(S=>S!=="")&&setTimeout(()=>n(c.join("")),100);return}if(!/^\d?$/.test(u))return;let t=[...g];t[s]=u,i(t),u&&s<e-1&&document.getElementById(`userutils-otp-${s+1}`)?.focus(),u&&s===e-1&&t.every(o=>o!=="")&&setTimeout(()=>n(t.join("")),100);},[g,e,n]),d=react.useCallback((s,u)=>{if(u.key==="Backspace"&&!g[s]&&s>0){document.getElementById(`userutils-otp-${s-1}`)?.focus();let t=[...g];t[s-1]="",i(t);}if(u.key==="Enter"){let t=g.join("");t.length===e&&n(t);}},[g,e,n]);react.useCallback(()=>{i(Array(e).fill("")),document.getElementById("userutils-otp-0")?.focus();},[e]);return jsxRuntime.jsxs("div",{className:h,children:[jsxRuntime.jsx("div",{className:"flex gap-2 justify-center",children:g.map((s,u)=>jsxRuntime.jsx("input",{id:`userutils-otp-${u}`,type:"text",inputMode:"numeric",maxLength:e,value:s,onChange:t=>p(u,t.target.value),onKeyDown:t=>d(u,t),disabled:r,autoFocus:u===0,className:`w-12 h-14 text-center text-xl font-mono bg-secondary border border-primary/10 text-foreground focus:outline-none focus:border-primary/30 disabled:opacity-50 ${y}`},u))}),l&&jsxRuntime.jsx("p",{className:"text-center text-sm text-red-400 mt-2",children:l})]})}q.displayName="OTPInput";var Xe="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function X({className:e}){return jsxRuntime.jsx("img",{src:Xe,alt:"Phantom",className:e})}function ee({className:e}){return jsxRuntime.jsxs("svg",{className:e,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 507.83 470.86",children:[jsxRuntime.jsx("polygon",{fill:"#e2761b",stroke:"#e2761b",strokeLinecap:"round",strokeLinejoin:"round",points:"482.09 0.5 284.32 147.38 320.9 60.72 482.09 0.5"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"25.54 0.5 221.72 148.77 186.93 60.72 25.54 0.5"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"410.93 340.97 358.26 421.67 470.96 452.67 503.36 342.76 410.93 340.97"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"4.67 342.76 36.87 452.67 149.57 421.67 96.9 340.97 4.67 342.76"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 111.8 252.13 223.7 257.1 219.73 136.85 143.21 204.62"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"364.42 204.62 286.91 135.46 284.32 257.1 396.03 252.13 364.42 204.62"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 216.75 388.87 158.71 343.55 149.57 421.67"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 358.26 421.67 348.92 343.55 290.88 388.87"}),jsxRuntime.jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"358.26 421.67 290.88 388.87 296.25 432.8 295.65 451.28 358.26 421.67"}),jsxRuntime.jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 212.18 451.28 211.78 432.8 216.75 388.87 149.57 421.67"}),jsxRuntime.jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"213.17 314.54 157.12 298.04 196.67 279.95 213.17 314.54"}),jsxRuntime.jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"294.46 314.54 310.96 279.95 350.71 298.04 294.46 314.54"}),jsxRuntime.jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 159.11 340.97 96.9 342.76 149.57 421.67"}),jsxRuntime.jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"348.72 340.97 358.26 421.67 410.93 342.76 348.72 340.97"}),jsxRuntime.jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"396.03 252.13 284.32 257.1 294.66 314.54 311.16 279.95 350.91 298.04 396.03 252.13"}),jsxRuntime.jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 196.87 279.95 213.17 314.54 223.7 257.1 111.8 252.13 157.12 298.04"}),jsxRuntime.jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"111.8 252.13 158.71 343.55 157.12 298.04 111.8 252.13"}),jsxRuntime.jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"350.91 298.04 348.92 343.55 396.03 252.13 350.91 298.04"}),jsxRuntime.jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"223.7 257.1 213.17 314.54 226.29 382.31 229.27 293.07 223.7 257.1"}),jsxRuntime.jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 278.96 292.87 281.34 382.31 294.66 314.54 284.32 257.1"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"294.66 314.54 281.34 382.31 290.88 388.87 348.92 343.55 350.91 298.04 294.66 314.54"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 158.71 343.55 216.75 388.87 226.29 382.31 213.17 314.54 157.12 298.04"}),jsxRuntime.jsx("polygon",{fill:"#c0ad9e",stroke:"#c0ad9e",strokeLinecap:"round",strokeLinejoin:"round",points:"295.65 451.28 296.25 432.8 291.28 428.42 216.35 428.42 211.78 432.8 212.18 451.28 149.57 421.67 171.43 439.55 215.75 470.36 291.88 470.36 336.4 439.55 358.26 421.67 295.65 451.28"}),jsxRuntime.jsx("polygon",{fill:"#161616",stroke:"#161616",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 281.34 382.31 226.29 382.31 216.75 388.87 211.78 432.8 216.35 428.42 291.28 428.42 296.25 432.8 290.88 388.87"}),jsxRuntime.jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"490.44 156.92 507.33 75.83 482.09 0.5 290.88 142.41 364.42 204.62 468.37 235.03 491.43 208.2 481.49 201.05 497.39 186.54 485.07 177 500.97 164.87 490.44 156.92"}),jsxRuntime.jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"0.5 75.83 17.39 156.92 6.66 164.87 22.56 177 10.44 186.54 26.34 201.05 16.4 208.2 39.26 235.03 143.21 204.62 216.75 142.41 25.54 0.5 0.5 75.83"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"468.37 235.03 364.42 204.62 396.03 252.13 348.92 343.55 410.93 342.76 503.36 342.76 468.37 235.03"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 39.26 235.03 4.67 342.76 96.9 342.76 158.71 343.55 111.8 252.13 143.21 204.62"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 290.88 142.41 321.1 60.72 186.93 60.72 216.75 142.41 223.7 257.1 226.09 293.27 226.29 382.31 281.34 382.31 281.74 293.27 284.32 257.1"})]})}function le({className:e}){return jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",className:e||"h-5 w-5",children:[jsxRuntime.jsxs("linearGradient",{id:"sol-g",x1:"7.233",x2:"24.766",y1:"24.766",y2:"7.234",gradientUnits:"userSpaceOnUse",children:[jsxRuntime.jsx("stop",{offset:"0",stopColor:"#9945ff"}),jsxRuntime.jsx("stop",{offset:"0.2",stopColor:"#7962e7"}),jsxRuntime.jsx("stop",{offset:"1",stopColor:"#00d18c"})]}),jsxRuntime.jsx("path",{fill:"#10111a",d:"M0 0h32v32H0z"}),jsxRuntime.jsx("path",{fill:"url(#sol-g)",fillRule:"evenodd",d:"M9.873 20.41a.65.65 0 0 1 .476-.21l14.662.012a.323.323 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54zm15.376-2.862a.322.322 0 0 1-.238.54l-14.662.012a.64.64 0 0 1-.476-.21l-3.122-3.44a.323.323 0 0 1 .238-.54l14.662-.012a.64.64 0 0 1 .475.21zM9.873 7.81a.64.64 0 0 1 .476-.21l14.662.012a.322.322 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54z",clipRule:"evenodd"})]})}function de({className:e}){return jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",className:e||"h-5 w-5",children:[jsxRuntime.jsx("rect",{width:"20",height:"20",rx:"4",fill:"#627EEA",fillOpacity:"0.2"}),jsxRuntime.jsx("path",{fill:"#627EEA",d:"M10 3l-4 6.5 4 2.5 4-2.5L10 3z"}),jsxRuntime.jsx("path",{fill:"#627EEA",fillOpacity:"0.6",d:"M6 9.5L10 12l4-2.5L10 17 6 9.5z"})]})}function st({config:e,onSuccess:n,title:r="Log in or Sign up",showWallets:l,showOTP:h,className:y=""}){let g=Ie(e),{isAuthenticated:i,wallet:p,loading:d,error:b,authenticateSolana:s,authenticateEVM:u,authenticateOTP:t,bridge:o,stackId:c}=g,w=!e.stackId&&!c,S=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:N,identityProviders:I,loading:M}=Le(c||e.stackId||null,S),[x,L]=react.useState(w?"stack-select":"select"),[P,z]=react.useState(null),[Z,V]=react.useState(false),[k,C]=react.useState("idle"),[R,D]=react.useState(""),[U,T]=react.useState([]),[_,B]=react.useState(e.stackId||null),[O,E]=react.useState(false),[ze,Ae]=react.useState(false);react.useEffect(()=>{if(typeof window>"u")return;let m=()=>{let W=window;E(!!(W.phantom?.solana?.isPhantom||W.solana?.isPhantom));let H=W.ethereum;Ae(!!(H?.isMetaMask||H?.providers?.some(Q=>Q.isMetaMask)));};m(),window.addEventListener("ethereum#initialized",m);let A=setTimeout(m,500);return ()=>{window.removeEventListener("ethereum#initialized",m),clearTimeout(A);}},[]),react.useEffect(()=>{x==="stack-select"&&c&&(B(c),L("select"));},[x,c]),react.useEffect(()=>{if(!(!o.ready||!w)&&o.identity){let m=[];o.resolvedStackId&&m.push({stackId:o.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(m.map(async A=>{try{let W=await fetch(`${S}/api/v2/stacks/${A.stackId}`);if(W.ok){let H=await W.json(),Q=H.data?.stack||H;A.name=Q.displayName||Q.name,A.logoUrl=Q.logoUrl;}}catch{}return A})).then(T);}},[o.ready,o.identity,o.resolvedStackId,w,S]),react.useEffect(()=>{i&&x==="success"&&n?.();},[i,x,n]);let ue=l||(I.length>0?I.filter(m=>m.type==="wallet").map(m=>m.id):["phantom","metamask"]),pe=h!==void 0?h:I.length>0?I.some(m=>m.type==="otp"):true,Pe=async()=>{z("phantom"),L("connecting");let m=await s("phantom");L(m?"success":"error");},De=async()=>{z("metamask"),L("connecting");let m=await u();L(m?"success":"error");},Te=async m=>{C("verifying"),D(""),await t(m)?(C("success"),L("success")):(C("error"),D("Invalid or expired code"),setTimeout(()=>C("idle"),2e3));},fe=()=>{L(w&&!_?"stack-select":"select"),z(null),V(false),C("idle"),D("");};return jsxRuntime.jsxs("div",{className:`w-full max-w-md space-y-3 ${y}`,children:[jsxRuntime.jsxs("div",{className:"mb-6 text-center",children:[N?.logoUrl&&x!=="stack-select"&&jsxRuntime.jsx("img",{src:N.logoUrl,alt:"",className:"h-10 w-10 mx-auto mb-3"}),jsxRuntime.jsx("h1",{className:"font-semibold text-2xl text-white",children:r}),N?.displayName&&x!=="stack-select"&&jsxRuntime.jsx("p",{className:"text-sm text-zinc-400 mt-1",children:N.displayName})]}),x==="stack-select"&&jsxRuntime.jsxs("div",{className:"space-y-3",children:[jsxRuntime.jsx("p",{className:"text-center text-sm text-zinc-400 mb-4",children:U.length>0?"Select a network to continue":"No previous connections found. Enter a Stack ID to continue."}),U.map(m=>jsxRuntime.jsxs("button",{onClick:()=>{B(m.stackId),L("select");},className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[m.logoUrl?jsxRuntime.jsx("img",{src:m.logoUrl,alt:"",className:"h-10 w-10 flex-shrink-0"}):jsxRuntime.jsx("div",{className:"h-10 w-10 flex-shrink-0 bg-zinc-700 flex items-center justify-center text-zinc-400 text-sm font-mono",children:m.name?.[0]?.toUpperCase()||"S"}),jsxRuntime.jsxs("div",{className:"flex-1 text-left",children:[jsxRuntime.jsx("span",{className:"font-medium text-white",children:m.name||m.stackId}),jsxRuntime.jsx("p",{className:"text-xs text-zinc-500",children:m.domain})]}),jsxRuntime.jsx("span",{className:"text-xs text-zinc-600",children:"Previously connected"})]},m.stackId)),o.ready&&!o.known&&jsxRuntime.jsx("p",{className:"text-center text-xs text-zinc-600 mt-4",children:"Connect to a stack for the first time to get started."})]}),x==="select"&&M&&jsxRuntime.jsx("div",{className:"flex items-center justify-center py-8",children:jsxRuntime.jsx("div",{className:"h-6 w-6 border-2 border-zinc-600 border-t-white animate-spin",style:{borderRadius:"50%"}})}),b&&x==="error"&&jsxRuntime.jsxs("div",{className:"mb-4 border border-red-500/30 bg-red-500/10 p-4",children:[jsxRuntime.jsx("p",{className:"text-center text-red-400 text-sm",children:b}),jsxRuntime.jsx("button",{className:"mt-3 w-full text-sm text-zinc-400 hover:text-white",onClick:fe,children:"Try Again"})]}),x==="success"&&jsxRuntime.jsxs("div",{className:"border border-green-500/30 bg-green-500/10 p-6 text-center",children:[jsxRuntime.jsx("p",{className:"font-medium text-green-400 text-sm",children:"Connected!"}),jsxRuntime.jsx("p",{className:"mt-1 text-xs text-zinc-400",children:"Redirecting..."})]}),x==="connecting"&&d&&jsxRuntime.jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 text-center",children:[jsxRuntime.jsxs("div",{className:"mx-auto mb-3 h-14 w-14 animate-pulse",children:[P==="phantom"&&jsxRuntime.jsx(X,{className:"h-14 w-14"}),P==="metamask"&&jsxRuntime.jsx(ee,{className:"h-14 w-14"})]}),jsxRuntime.jsx("p",{className:"font-medium text-sm text-white",children:p.connected?"Signing message...":"Connecting wallet..."}),jsxRuntime.jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Please confirm in your wallet"}),jsxRuntime.jsx("button",{className:"mt-4 text-sm text-zinc-500 hover:text-white",onClick:fe,children:"Cancel"})]}),x==="select"&&!d&&!M&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[ue.includes("phantom")&&jsxRuntime.jsxs("button",{onClick:Pe,disabled:!O,className:`flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a] ${O?"":"cursor-not-allowed opacity-50"}`,children:[jsxRuntime.jsx(X,{className:"h-14 w-14 flex-shrink-0"}),jsxRuntime.jsxs("div",{className:"flex-1 text-left",children:[jsxRuntime.jsx("span",{className:"font-medium text-lg text-white",children:"Phantom"}),!O&&jsxRuntime.jsx("p",{className:"text-xs text-zinc-500",children:"Not installed"})]}),jsxRuntime.jsx(le,{className:"h-8 w-8"})]}),ue.includes("metamask")&&ze&&jsxRuntime.jsxs("button",{onClick:De,className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsxRuntime.jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center bg-white p-2",children:jsxRuntime.jsx(ee,{className:"h-10 w-10"})}),jsxRuntime.jsx("div",{className:"flex-1 text-left",children:jsxRuntime.jsx("span",{className:"font-medium text-lg text-white",children:"MetaMask"})}),jsxRuntime.jsx(de,{className:"h-8 w-8"})]}),pe&&!Z&&jsxRuntime.jsxs("button",{onClick:()=>V(true),className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsxRuntime.jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center border border-zinc-700 bg-[#2a2a3e]",children:jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"28px",viewBox:"0 -960 960 960",width:"28px",fill:"#e3e3e3",children:jsxRuntime.jsx("path",{d:"M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v480q0 33-23.5 56.5T800-160H160Z"})})}),jsxRuntime.jsx("div",{className:"flex-1 text-left",children:jsxRuntime.jsx("span",{className:"font-medium text-lg text-white",children:"Access Code"})})]}),pe&&Z&&jsxRuntime.jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 space-y-4",children:[jsxRuntime.jsx("p",{className:"text-center text-sm text-zinc-400",children:"Enter your 6-digit access code"}),jsxRuntime.jsx(q,{onComplete:Te,disabled:k==="verifying",error:R}),k==="verifying"&&jsxRuntime.jsx("p",{className:"text-center text-sm text-zinc-400 animate-pulse",children:"Verifying..."}),k==="success"&&jsxRuntime.jsx("p",{className:"text-center text-sm text-green-400",children:"Verified!"}),N?.webPageUrl&&k==="idle"&&jsxRuntime.jsx("a",{href:`${N.webPageUrl}/connect/pair`,target:"_blank",rel:"noopener noreferrer",className:"block text-center text-sm text-zinc-500 hover:text-white transition-colors",children:"Get code"})]})]})]})}function rt({className:e}){return jsxRuntime.jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"black"}),jsxRuntime.jsx("path",{d:"M8.53901 8L14.7164 16.2153L8.5 22.8947H9.89907L15.3415 17.0468L19.7389 22.8947H24.5L17.975 14.2173L23.7612 8H22.3621L17.3499 13.3858L13.3001 8H8.53901ZM10.5964 9.02501H12.7837L22.4422 21.8695H20.255L10.5964 9.02501Z",fill:"#F7F7F7"})]})}function it({className:e}){return jsxRuntime.jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#F1F2F9"}),jsxRuntime.jsx("path",{d:"M26.1001 16.2273C26.1001 15.5182 26.0365 14.8364 25.9183 14.1818H16.5001V18.05H21.8819C21.6501 19.3 20.9456 20.3591 19.8865 21.0682V23.5773H23.1183C25.0092 21.8364 26.1001 19.2727 26.1001 16.2273Z",fill:"#4285F4"}),jsxRuntime.jsx("path",{d:"M16.5001 26C19.2001 26 21.4637 25.1046 23.1182 23.5773L19.8864 21.0682C18.991 21.6682 17.8455 22.0227 16.5001 22.0227C13.8955 22.0227 11.691 20.2637 10.9046 17.9H7.56372V20.4909C9.20917 23.7591 12.591 26 16.5001 26Z",fill:"#34A853"}),jsxRuntime.jsx("path",{d:"M10.9047 17.8999C10.7047 17.2999 10.591 16.659 10.591 15.9999C10.591 15.3408 10.7047 14.6999 10.9047 14.0999V11.509H7.56376C6.86376 12.9025 6.49951 14.4405 6.50012 15.9999C6.50012 17.6136 6.88649 19.1408 7.56376 20.4908L10.9047 17.8999Z",fill:"#FBBC05"}),jsxRuntime.jsx("path",{d:"M16.5001 9.97726C17.9682 9.97726 19.2864 10.4818 20.3228 11.4727L23.191 8.60454C21.4591 6.99091 19.1955 6 16.5001 6C12.591 6 9.20917 8.2409 7.56372 11.5091L10.9046 14.1C11.691 11.7364 13.8955 9.97726 16.5001 9.97726Z",fill:"#EA4335"})]})}function ct({className:e}){return jsxRuntime.jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#5462EB"}),jsxRuntime.jsx("path",{d:"M23.5433 8.87438C22.2479 8.26174 20.8587 7.81038 19.4063 7.55187C19.3799 7.54688 19.3534 7.55934 19.3398 7.58428C19.1612 7.91179 18.9633 8.33905 18.8247 8.67487C17.2625 8.43382 15.7084 8.43382 14.1782 8.67487C14.0396 8.33158 13.8345 7.91179 13.6551 7.58428C13.6414 7.56018 13.615 7.54771 13.5886 7.55187C12.1369 7.80955 10.7478 8.26092 9.45159 8.87438C9.44037 8.87937 9.43075 8.88769 9.42437 8.89849C6.78947 12.9558 6.06766 16.9134 6.42176 20.8219C6.42336 20.841 6.43378 20.8593 6.4482 20.871C8.18663 22.1868 9.87059 22.9857 11.5233 23.5152C11.5497 23.5235 11.5778 23.5135 11.5946 23.491C11.9855 22.9408 12.334 22.3606 12.6328 21.7504C12.6505 21.7147 12.6336 21.6723 12.5976 21.6581C12.0448 21.442 11.5185 21.1785 11.0122 20.8793C10.9721 20.8552 10.9689 20.7961 11.0058 20.7679C11.1123 20.6856 11.2189 20.6 11.3206 20.5135C11.339 20.4977 11.3647 20.4944 11.3863 20.5044C14.7125 22.0696 18.3136 22.0696 21.6006 20.5044C21.6222 20.4936 21.6479 20.4969 21.6671 20.5127C21.7688 20.5991 21.8754 20.6856 21.9827 20.7679C22.0196 20.7961 22.0172 20.8552 21.9771 20.8793C21.4708 21.1843 20.9445 21.442 20.3909 21.6573C20.3548 21.6715 20.3388 21.7147 20.3564 21.7504C20.6617 22.3597 21.0101 22.9399 21.3939 23.4902C21.4099 23.5135 21.4387 23.5235 21.4652 23.5152C23.1259 22.9857 24.8099 22.1868 26.5483 20.871C26.5635 20.8593 26.5731 20.8419 26.5747 20.8228C26.9985 16.3041 25.8649 12.3789 23.5697 8.89931C23.5641 8.88769 23.5545 8.87937 23.5433 8.87438Z",fill:"#F7F7F7"})]})}function ut({className:e}){return jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",className:e||"h-8 w-8",children:[jsxRuntime.jsx("rect",{width:"512",height:"512",rx:"15%",fill:"#37aee2"}),jsxRuntime.jsx("path",{fill:"#c8daea",d:"M199 404c-11 0-10-4-13-14l-32-105 245-144"}),jsxRuntime.jsx("path",{fill:"#a9c9dd",d:"M199 404c7 0 11-4 16-8l45-43-56-34"}),jsxRuntime.jsx("path",{fill:"#f6fbfe",d:"M204 319l135 99c14 9 26 4 30-14l55-258c5-22-9-32-24-25L79 245c-21 8-21 21-4 26l83 26 190-121c9-5 17-3 11 4"})]})}
1
+ 'use strict';var react=require('react'),jsxRuntime=require('react/jsx-runtime');var ge=react.createContext(null);function We(){let e=react.useContext(ge);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function Re({config:e,callbacks:n,children:r}){return jsxRuntime.jsx(ge.Provider,{value:{config:e,callbacks:n},children:r})}function he(){let[e,n]=react.useState({connected:false,address:null,chain:null,provider:null}),[r,l]=react.useState(null),h=react.useCallback(async(p="phantom")=>{l(null);try{let d=typeof window<"u"?window:null,b=p==="phantom"?d?.phantom?.solana||d?.solana:d?.solflare;if(!b)return l(`${p} wallet not found`),null;let u=(await b.connect()).publicKey.toString();return n({connected:!0,address:u,chain:"solana",provider:p}),u}catch(d){return l(d.message||"Failed to connect wallet"),null}},[]),y=react.useCallback(async()=>{l(null);try{let d=(typeof window<"u"?window:null)?.ethereum;if(!d)return l("MetaMask not found"),null;let b=d;d.providers?.length&&(b=d.providers.find(t=>t.isMetaMask)||d);let u=(await b.request({method:"eth_requestAccounts"}))[0];return u?(n({connected:!0,address:u,chain:"ethereum",provider:"metamask"}),u):(l("No account selected"),null)}catch(p){return l(p.message||"Failed to connect wallet"),null}},[]),g=react.useCallback(async(p,d)=>{l(null);let b=d?.chain||e.chain,s=d?.provider||e.provider,u=d?.address||e.address;try{if(b==="solana"){let t=typeof window<"u"?window:null,o=s==="solflare"?t?.solflare:t?.phantom?.solana||t?.solana;if(!o)throw new Error("Wallet not available");let c=new TextEncoder().encode(p),w=await o.signMessage(c,"utf8"),S=w.signature||w,N="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",I=BigInt(0);for(let x of S)I=I*256n+BigInt(x);let M="";for(;I>0n;)M=N[Number(I%58n)]+M,I=I/58n;for(let x of S)if(x===0)M="1"+M;else break;return M}if(b==="ethereum"){let o=(typeof window<"u"?window:null)?.ethereum;if(o?.providers?.length&&(o=o.providers.find(w=>w.isMetaMask)||o),!o)throw new Error("MetaMask not available");return await o.request({method:"personal_sign",params:[p,u]})}throw new Error("No wallet connected")}catch(t){return l(t.message||"Signing failed"),null}},[e]),i=react.useCallback(()=>{n({connected:false,address:null,chain:null,provider:null}),l(null);},[]);return {wallet:e,error:r,connectSolana:h,connectEVM:y,signMessage:g,disconnect:i}}function ke(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith("stackauth_session="));if(!e)return null;let n=e.slice(18);return JSON.parse(atob(n.replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function ye(e="__csrf"){if(typeof document>"u")return null;let n=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith(`${e}=`));return n?n.slice(e.length+1):null}function Ne(){let[e,n]=react.useState(null),[r,l]=react.useState(true),h=react.useCallback(()=>{let i=ke();i&&i.expiresAt>Date.now()?n({userId:i.userId,address:i.address,chain:i.chain,expiresAt:i.expiresAt,planId:i.planId,authMethod:i.authMethod}):n(null),l(false);},[]);react.useEffect(()=>{h();},[h]);let y=react.useCallback(async(i="")=>{try{let p=await fetch(`${i}/api/auth/session`);if(p.ok){let d=await p.json();if(d.session)return n(d.session),d.session}return n(null),null}catch{return null}},[]),g=!!e&&e.expiresAt>Date.now();return {session:e,loading:r,isAuthenticated:g,refresh:y,readSession:h}}function xe(e="__csrf",n="x-csrf-token"){let[r,l]=react.useState(null);react.useEffect(()=>{l(ye(e));},[e]);let h=r?{[n]:r}:{};return {token:r,headers:h}}var Ge="https://stacknet.magma-rpc.com/auth/bridge",J="stacknet-auth-bridge";function Ce(e){let n=e?.bridgeUrl||Ge,r=e?.disabled||false,l=react.useRef(null),[h,y]=react.useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),g=react.useRef([]),i=react.useRef(false),p=react.useCallback(t=>{let o={...t,protocol:J};i.current&&l.current?.contentWindow?l.current.contentWindow.postMessage(o,new URL(n).origin):g.current.push(o);},[n]);react.useEffect(()=>{if(r)return;let t=c=>{if(!(!c.data||c.data.protocol!==J)){try{if(c.origin!==new URL(n).origin)return}catch{return}switch(c.data.type){case "bridge:ready":i.current=true,y(w=>({...w,ready:true}));for(let w of g.current)l.current?.contentWindow?.postMessage(w,c.origin);g.current=[],l.current?.contentWindow?.postMessage({protocol:J,type:"auth:check"},c.origin),l.current?.contentWindow?.postMessage({protocol:J,type:"auth:resolve-stack"},c.origin);break;case "auth:status":y(w=>({...w,known:c.data.known,identity:c.data.identity,identityCount:c.data.identityCount||0}));break;case "auth:resolved-stack":y(w=>({...w,resolvedStackId:c.data.stackId||null}));break;}}};window.addEventListener("message",t);let o=document.createElement("iframe");return o.src=n,o.style.display="none",o.setAttribute("aria-hidden","true"),o.setAttribute("tabindex","-1"),o.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(o),l.current=o,()=>{window.removeEventListener("message",t),o.parentNode&&o.parentNode.removeChild(o),l.current=null,i.current=false;}},[n,r]);let d=react.useCallback(t=>{p({type:"auth:connected",...t});},[p]),b=react.useCallback(t=>{p({type:"auth:disconnected",...t});},[p]),s=react.useCallback(()=>{p({type:"auth:clear"}),y({ready:h.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[p,h.ready]),u=react.useCallback(()=>{p({type:"auth:check"});},[p]);return {...h,reportConnected:d,reportDisconnected:b,clearAll:s,refresh:u}}async function Me(e,n,r,l){let h=e.apiVersion||"v2",y=`${e.baseUrl}/api/${h}${r}`;try{let g=await fetch(y,{method:n,headers:{"Content-Type":"application/json"},body:l?JSON.stringify(l):void 0}),i=await g.json();return g.ok?i.success&&i.data!==void 0?{success:!0,data:i.data}:{success:!0,data:i}:{success:!1,error:i.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(g){return {success:false,error:{code:"NETWORK_ERROR",message:g instanceof Error?g.message:"Network error"}}}}function ve(e){return {getNetworkStatus:()=>Me(e,"GET","/network/status"),getWeb3Challenge:(n,r)=>Me(e,"POST",`/stacks/${e.stackId}/auth/web3/challenge`,{chain:n,address:r})}}function Ie(e={apiBaseUrl:""}){let{wallet:n,connectSolana:r,connectEVM:l,signMessage:h,disconnect:y}=he(),{session:g,isAuthenticated:i,refresh:p,readSession:d}=Ne(),{headers:b}=xe(),s=Ce({disabled:typeof window>"u"}),[u,t]=react.useState(false),[o,c]=react.useState(null),[w,S]=react.useState(false),N=e.apiBaseUrl||"",I=e.stacknetUrl||"https://stacknet.magma-rpc.com",M=e.stackId||s.resolvedStackId||"",x=ve({baseUrl:I,stackId:M}),L=react.useCallback(async(k,C,R,D)=>{t(true),c(null);try{let U=C;if(!U){let E=await R();if(!E)return t(!1),!1;U=E;}let T=await x.getWeb3Challenge(k,U);if(!T.success||!T.data)return c("Failed to get challenge"),t(!1),!1;let _=await h(T.data.message,{chain:k,provider:D,address:U});if(!_)return t(!1),!1;let B={chain:k,message:T.data.message,signature:_,stackId:M};k==="solana"&&(B.publicKey=U);let O=await fetch(`${N}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!O.ok){let E=await O.json().catch(()=>({}));return c(E.error||"Authentication failed"),t(!1),!1}return s.reportConnected({address:U,chain:k,method:D||(k==="solana"?"phantom":"metamask"),stackId:M}),d(),t(!1),!0}catch(U){return c(U.message||"Authentication failed"),t(false),false}},[N,x,h,d,s,M]),P=react.useCallback(async(k="phantom")=>{let C=await r(k);return C?L("solana",C,()=>r(k),k):false},[r,L]),z=react.useCallback(async()=>{let k=await l();return k?L("ethereum",k,l,"metamask"):false},[l,L]),Z=react.useCallback(async k=>{t(true),c(null);try{let C=await fetch(`${N}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:k})});if(!C.ok){let R=await C.json().catch(()=>({}));return c(R.error||"Invalid code"),t(!1),!1}return d(),t(!1),!0}catch(C){return c(C.message||"OTP verification failed"),t(false),false}},[N,d]),V=react.useCallback(async()=>{n.address&&n.chain&&s.reportDisconnected({address:n.address,chain:n.chain,stackId:M});try{await fetch(`${N}/api/auth/logout`,{method:"POST",headers:b});}catch{}y(),d();},[N,b,y,d,n,s,M]);return react.useEffect(()=>{if(!e.autoConnect||w||i||!s.ready||!s.known||!s.identity)return;S(true);let{chain:k,method:C}=s.identity;k==="solana"&&(C==="phantom"||C==="solflare")?P(C):k==="ethereum"&&z();},[e.autoConnect,w,i,s,P,z]),{session:g,isAuthenticated:i,wallet:n,loading:u,error:o,authenticateSolana:P,authenticateEVM:z,authenticateOTP:Z,logout:V,refresh:()=>p(N),stackId:M,bridge:{ready:s.ready,known:s.known,identity:s.identity,identityCount:s.identityCount,resolvedStackId:s.resolvedStackId}}}function Le(e,n="https://stacknet.magma-rpc.com"){let[r,l]=react.useState(null),[h,y]=react.useState(false),[g,i]=react.useState(null),p=react.useCallback(async b=>{y(true),i(null);try{let s=await fetch(`${n}/api/v2/stacks/${b}`);if(!s.ok)return i("Stack not found"),y(!1),null;let u=await s.json(),t=u.data?.stack||u.stack||u,o={id:t.id,name:t.name,displayName:t.displayName||t.name,description:t.description,logoUrl:t.logoUrl,webPageUrl:t.webPageUrl,allowedChains:t.allowedChains||[],features:t.features,stripeProvider:t.stripeProvider,oauthProviders:t.oauthProviders?.map(c=>({provider:c.provider,enabled:c.enabled!==!1}))};return l(o),y(!1),o}catch(s){return i(s.message),y(false),null}},[n]);react.useEffect(()=>{e&&p(e);},[e,p]);let d=r?Ke(r):[];return {config:r,loading:h,error:g,identityProviders:d,fetchConfig:p}}function Ke(e){let n=[];if(e.features?.web3Auth!==false&&(e.allowedChains.includes("solana")&&(n.push({type:"wallet",id:"phantom",name:"Phantom",chain:"solana"}),n.push({type:"wallet",id:"solflare",name:"Solflare",chain:"solana"})),(e.allowedChains.includes("ethereum")||e.allowedChains.includes("polygon")||e.allowedChains.includes("base"))&&n.push({type:"wallet",id:"metamask",name:"MetaMask",chain:"ethereum"})),e.features?.apiKeyAuth!==false&&n.push({type:"otp",id:"otp",name:"Access Code"}),e.features?.oauthAuth&&e.oauthProviders)for(let r of e.oauthProviders)r.enabled&&n.push({type:"oauth",id:r.provider,name:r.provider});return n}function q({length:e=6,onComplete:n,disabled:r=false,error:l,className:h="",inputClassName:y=""}){let [g,i]=react.useState(Array(e).fill("")),p=react.useCallback((s,u)=>{if(u.length>1){let o=u.replace(/\D/g,"").slice(0,e).split(""),c=[...g];o.forEach((S,N)=>{s+N<e&&(c[s+N]=S);}),i(c);let w=Math.min(s+o.length,e-1);document.getElementById(`userutils-otp-${w}`)?.focus(),c.every(S=>S!=="")&&setTimeout(()=>n(c.join("")),100);return}if(!/^\d?$/.test(u))return;let t=[...g];t[s]=u,i(t),u&&s<e-1&&document.getElementById(`userutils-otp-${s+1}`)?.focus(),u&&s===e-1&&t.every(o=>o!=="")&&setTimeout(()=>n(t.join("")),100);},[g,e,n]),d=react.useCallback((s,u)=>{if(u.key==="Backspace"&&!g[s]&&s>0){document.getElementById(`userutils-otp-${s-1}`)?.focus();let t=[...g];t[s-1]="",i(t);}if(u.key==="Enter"){let t=g.join("");t.length===e&&n(t);}},[g,e,n]);react.useCallback(()=>{i(Array(e).fill("")),document.getElementById("userutils-otp-0")?.focus();},[e]);return jsxRuntime.jsxs("div",{className:h,children:[jsxRuntime.jsx("div",{className:"flex gap-2 justify-center",children:g.map((s,u)=>jsxRuntime.jsx("input",{id:`userutils-otp-${u}`,type:"text",inputMode:"numeric",maxLength:e,value:s,onChange:t=>p(u,t.target.value),onKeyDown:t=>d(u,t),disabled:r,autoFocus:u===0,className:`w-12 h-14 text-center text-xl font-mono bg-secondary border border-primary/10 text-foreground focus:outline-none focus:border-primary/30 disabled:opacity-50 ${y}`},u))}),l&&jsxRuntime.jsx("p",{className:"text-center text-sm text-red-400 mt-2",children:l})]})}q.displayName="OTPInput";var Xe="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function X({className:e}){return jsxRuntime.jsx("img",{src:Xe,alt:"Phantom",className:e})}function ee({className:e}){return jsxRuntime.jsxs("svg",{className:e,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 507.83 470.86",children:[jsxRuntime.jsx("polygon",{fill:"#e2761b",stroke:"#e2761b",strokeLinecap:"round",strokeLinejoin:"round",points:"482.09 0.5 284.32 147.38 320.9 60.72 482.09 0.5"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"25.54 0.5 221.72 148.77 186.93 60.72 25.54 0.5"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"410.93 340.97 358.26 421.67 470.96 452.67 503.36 342.76 410.93 340.97"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"4.67 342.76 36.87 452.67 149.57 421.67 96.9 340.97 4.67 342.76"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 111.8 252.13 223.7 257.1 219.73 136.85 143.21 204.62"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"364.42 204.62 286.91 135.46 284.32 257.1 396.03 252.13 364.42 204.62"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 216.75 388.87 158.71 343.55 149.57 421.67"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 358.26 421.67 348.92 343.55 290.88 388.87"}),jsxRuntime.jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"358.26 421.67 290.88 388.87 296.25 432.8 295.65 451.28 358.26 421.67"}),jsxRuntime.jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 212.18 451.28 211.78 432.8 216.75 388.87 149.57 421.67"}),jsxRuntime.jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"213.17 314.54 157.12 298.04 196.67 279.95 213.17 314.54"}),jsxRuntime.jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"294.46 314.54 310.96 279.95 350.71 298.04 294.46 314.54"}),jsxRuntime.jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 159.11 340.97 96.9 342.76 149.57 421.67"}),jsxRuntime.jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"348.72 340.97 358.26 421.67 410.93 342.76 348.72 340.97"}),jsxRuntime.jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"396.03 252.13 284.32 257.1 294.66 314.54 311.16 279.95 350.91 298.04 396.03 252.13"}),jsxRuntime.jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 196.87 279.95 213.17 314.54 223.7 257.1 111.8 252.13 157.12 298.04"}),jsxRuntime.jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"111.8 252.13 158.71 343.55 157.12 298.04 111.8 252.13"}),jsxRuntime.jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"350.91 298.04 348.92 343.55 396.03 252.13 350.91 298.04"}),jsxRuntime.jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"223.7 257.1 213.17 314.54 226.29 382.31 229.27 293.07 223.7 257.1"}),jsxRuntime.jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 278.96 292.87 281.34 382.31 294.66 314.54 284.32 257.1"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"294.66 314.54 281.34 382.31 290.88 388.87 348.92 343.55 350.91 298.04 294.66 314.54"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 158.71 343.55 216.75 388.87 226.29 382.31 213.17 314.54 157.12 298.04"}),jsxRuntime.jsx("polygon",{fill:"#c0ad9e",stroke:"#c0ad9e",strokeLinecap:"round",strokeLinejoin:"round",points:"295.65 451.28 296.25 432.8 291.28 428.42 216.35 428.42 211.78 432.8 212.18 451.28 149.57 421.67 171.43 439.55 215.75 470.36 291.88 470.36 336.4 439.55 358.26 421.67 295.65 451.28"}),jsxRuntime.jsx("polygon",{fill:"#161616",stroke:"#161616",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 281.34 382.31 226.29 382.31 216.75 388.87 211.78 432.8 216.35 428.42 291.28 428.42 296.25 432.8 290.88 388.87"}),jsxRuntime.jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"490.44 156.92 507.33 75.83 482.09 0.5 290.88 142.41 364.42 204.62 468.37 235.03 491.43 208.2 481.49 201.05 497.39 186.54 485.07 177 500.97 164.87 490.44 156.92"}),jsxRuntime.jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"0.5 75.83 17.39 156.92 6.66 164.87 22.56 177 10.44 186.54 26.34 201.05 16.4 208.2 39.26 235.03 143.21 204.62 216.75 142.41 25.54 0.5 0.5 75.83"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"468.37 235.03 364.42 204.62 396.03 252.13 348.92 343.55 410.93 342.76 503.36 342.76 468.37 235.03"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 39.26 235.03 4.67 342.76 96.9 342.76 158.71 343.55 111.8 252.13 143.21 204.62"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 290.88 142.41 321.1 60.72 186.93 60.72 216.75 142.41 223.7 257.1 226.09 293.27 226.29 382.31 281.34 382.31 281.74 293.27 284.32 257.1"})]})}function le({className:e}){return jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",className:e||"h-5 w-5",children:[jsxRuntime.jsxs("linearGradient",{id:"sol-g",x1:"7.233",x2:"24.766",y1:"24.766",y2:"7.234",gradientUnits:"userSpaceOnUse",children:[jsxRuntime.jsx("stop",{offset:"0",stopColor:"#9945ff"}),jsxRuntime.jsx("stop",{offset:"0.2",stopColor:"#7962e7"}),jsxRuntime.jsx("stop",{offset:"1",stopColor:"#00d18c"})]}),jsxRuntime.jsx("path",{fill:"#10111a",d:"M0 0h32v32H0z"}),jsxRuntime.jsx("path",{fill:"url(#sol-g)",fillRule:"evenodd",d:"M9.873 20.41a.65.65 0 0 1 .476-.21l14.662.012a.323.323 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54zm15.376-2.862a.322.322 0 0 1-.238.54l-14.662.012a.64.64 0 0 1-.476-.21l-3.122-3.44a.323.323 0 0 1 .238-.54l14.662-.012a.64.64 0 0 1 .475.21zM9.873 7.81a.64.64 0 0 1 .476-.21l14.662.012a.322.322 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54z",clipRule:"evenodd"})]})}function de({className:e}){return jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",className:e||"h-5 w-5",children:[jsxRuntime.jsx("rect",{width:"20",height:"20",rx:"4",fill:"#627EEA",fillOpacity:"0.2"}),jsxRuntime.jsx("path",{fill:"#627EEA",d:"M10 3l-4 6.5 4 2.5 4-2.5L10 3z"}),jsxRuntime.jsx("path",{fill:"#627EEA",fillOpacity:"0.6",d:"M6 9.5L10 12l4-2.5L10 17 6 9.5z"})]})}function st({config:e,onSuccess:n,title:r="Log in or Sign up",showWallets:l,showOTP:h,className:y=""}){let g=Ie(e),{isAuthenticated:i,wallet:p,loading:d,error:b,authenticateSolana:s,authenticateEVM:u,authenticateOTP:t,bridge:o,stackId:c}=g,w=!e.stackId&&!c,S=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:N,identityProviders:I,loading:M}=Le(c||e.stackId||null,S),[x,L]=react.useState(w?"stack-select":"select"),[P,z]=react.useState(null),[Z,V]=react.useState(false),[k,C]=react.useState("idle"),[R,D]=react.useState(""),[U,T]=react.useState([]),[_,B]=react.useState(e.stackId||null),[O,E]=react.useState(false),[ze,Ae]=react.useState(false);react.useEffect(()=>{if(typeof window>"u")return;let m=()=>{let W=window;E(!!(W.phantom?.solana?.isPhantom||W.solana?.isPhantom));let H=W.ethereum;Ae(!!(H?.isMetaMask||H?.providers?.some(Q=>Q.isMetaMask)));};m(),window.addEventListener("ethereum#initialized",m);let A=setTimeout(m,500);return ()=>{window.removeEventListener("ethereum#initialized",m),clearTimeout(A);}},[]),react.useEffect(()=>{x==="stack-select"&&c&&(B(c),L("select"));},[x,c]),react.useEffect(()=>{if(!(!o.ready||!w)&&o.identity){let m=[];o.resolvedStackId&&m.push({stackId:o.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(m.map(async A=>{try{let W=await fetch(`${S}/api/v2/stacks/${A.stackId}`);if(W.ok){let H=await W.json(),Q=H.data?.stack||H;A.name=Q.displayName||Q.name,A.logoUrl=Q.logoUrl;}}catch{}return A})).then(T);}},[o.ready,o.identity,o.resolvedStackId,w,S]),react.useEffect(()=>{i&&x==="success"&&n?.();},[i,x,n]);let ue=l||(I.length>0?I.filter(m=>m.type==="wallet").map(m=>m.id):["phantom","metamask"]),pe=h!==void 0?h:I.length>0?I.some(m=>m.type==="otp"):true,Pe=async()=>{z("phantom"),L("connecting");let m=await s("phantom");L(m?"success":"error");},De=async()=>{z("metamask"),L("connecting");let m=await u();L(m?"success":"error");},Te=async m=>{C("verifying"),D(""),await t(m)?(C("success"),L("success")):(C("error"),D("Invalid or expired code"),setTimeout(()=>C("idle"),2e3));},fe=()=>{L(w&&!_?"stack-select":"select"),z(null),V(false),C("idle"),D("");};return jsxRuntime.jsxs("div",{className:`w-full max-w-md space-y-3 ${y}`,children:[jsxRuntime.jsxs("div",{className:"mb-6 text-center",children:[N?.logoUrl&&x!=="stack-select"&&jsxRuntime.jsx("img",{src:N.logoUrl,alt:"",className:"h-10 w-10 mx-auto mb-3"}),jsxRuntime.jsx("h1",{className:"font-semibold text-2xl text-white",children:r}),N?.displayName&&x!=="stack-select"&&jsxRuntime.jsx("p",{className:"text-sm text-zinc-400 mt-1",children:N.displayName})]}),x==="stack-select"&&jsxRuntime.jsxs("div",{className:"space-y-3",children:[jsxRuntime.jsx("p",{className:"text-center text-sm text-zinc-400 mb-4",children:U.length>0?"Select a network to continue":"No previous connections found. Enter a Stack ID to continue."}),U.map(m=>jsxRuntime.jsxs("button",{onClick:()=>{B(m.stackId),L("select");},className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[m.logoUrl?jsxRuntime.jsx("img",{src:m.logoUrl,alt:"",className:"h-10 w-10 flex-shrink-0"}):jsxRuntime.jsx("div",{className:"h-10 w-10 flex-shrink-0 bg-zinc-700 flex items-center justify-center text-zinc-400 text-sm font-mono",children:m.name?.[0]?.toUpperCase()||"S"}),jsxRuntime.jsxs("div",{className:"flex-1 text-left",children:[jsxRuntime.jsx("span",{className:"font-medium text-white",children:m.name||m.stackId}),jsxRuntime.jsx("p",{className:"text-xs text-zinc-500",children:m.domain})]}),jsxRuntime.jsx("span",{className:"text-xs text-zinc-600",children:"Previously connected"})]},m.stackId)),o.ready&&!o.known&&jsxRuntime.jsx("p",{className:"text-center text-xs text-zinc-600 mt-4",children:"Connect to a stack for the first time to get started."})]}),x==="select"&&M&&jsxRuntime.jsx("div",{className:"flex items-center justify-center py-8",children:jsxRuntime.jsx("div",{className:"h-6 w-6 border-2 border-zinc-600 border-t-white animate-spin",style:{borderRadius:"50%"}})}),b&&x==="error"&&jsxRuntime.jsxs("div",{className:"mb-4 border border-red-500/30 bg-red-500/10 p-4",children:[jsxRuntime.jsx("p",{className:"text-center text-red-400 text-sm",children:b}),jsxRuntime.jsx("button",{className:"mt-3 w-full text-sm text-zinc-400 hover:text-white",onClick:fe,children:"Try Again"})]}),x==="success"&&jsxRuntime.jsxs("div",{className:"border border-green-500/30 bg-green-500/10 p-6 text-center",children:[jsxRuntime.jsx("p",{className:"font-medium text-green-400 text-sm",children:"Connected!"}),jsxRuntime.jsx("p",{className:"mt-1 text-xs text-zinc-400",children:"Redirecting..."})]}),x==="connecting"&&d&&jsxRuntime.jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 text-center",children:[jsxRuntime.jsxs("div",{className:"mx-auto mb-3 h-14 w-14 animate-pulse",children:[P==="phantom"&&jsxRuntime.jsx(X,{className:"h-14 w-14"}),P==="metamask"&&jsxRuntime.jsx(ee,{className:"h-14 w-14"})]}),jsxRuntime.jsx("p",{className:"font-medium text-sm text-white",children:p.connected?"Signing message...":"Connecting wallet..."}),jsxRuntime.jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Please confirm in your wallet"}),jsxRuntime.jsx("button",{className:"mt-4 text-sm text-zinc-500 hover:text-white",onClick:fe,children:"Cancel"})]}),x==="select"&&!d&&!M&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[ue.includes("phantom")&&jsxRuntime.jsxs("button",{onClick:Pe,disabled:!O,className:`flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a] ${O?"":"cursor-not-allowed opacity-50"}`,children:[jsxRuntime.jsx(X,{className:"h-14 w-14 flex-shrink-0"}),jsxRuntime.jsxs("div",{className:"flex-1 text-left",children:[jsxRuntime.jsx("span",{className:"font-medium text-lg text-white",children:"Phantom"}),!O&&jsxRuntime.jsx("p",{className:"text-xs text-zinc-500",children:"Not installed"})]}),jsxRuntime.jsx(le,{className:"h-8 w-8"})]}),ue.includes("metamask")&&ze&&jsxRuntime.jsxs("button",{onClick:De,className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsxRuntime.jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center bg-white p-2",children:jsxRuntime.jsx(ee,{className:"h-10 w-10"})}),jsxRuntime.jsx("div",{className:"flex-1 text-left",children:jsxRuntime.jsx("span",{className:"font-medium text-lg text-white",children:"MetaMask"})}),jsxRuntime.jsx(de,{className:"h-8 w-8"})]}),pe&&!Z&&jsxRuntime.jsxs("button",{onClick:()=>V(true),className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsxRuntime.jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center border border-zinc-700 bg-[#2a2a3e]",children:jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"28px",viewBox:"0 -960 960 960",width:"28px",fill:"#e3e3e3",children:jsxRuntime.jsx("path",{d:"M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v480q0 33-23.5 56.5T800-160H160Z"})})}),jsxRuntime.jsx("div",{className:"flex-1 text-left",children:jsxRuntime.jsx("span",{className:"font-medium text-lg text-white",children:"Access Code"})})]}),pe&&Z&&jsxRuntime.jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 space-y-4",children:[jsxRuntime.jsx("p",{className:"text-center text-sm text-zinc-400",children:"Enter your 6-digit access code"}),jsxRuntime.jsx(q,{onComplete:Te,disabled:k==="verifying",error:R}),k==="verifying"&&jsxRuntime.jsx("p",{className:"text-center text-sm text-zinc-400 animate-pulse",children:"Verifying..."}),k==="success"&&jsxRuntime.jsx("p",{className:"text-center text-sm text-green-400",children:"Verified!"}),N?.webPageUrl&&k==="idle"&&jsxRuntime.jsx("a",{href:`${N.webPageUrl}/connect/pair`,target:"_blank",rel:"noopener noreferrer",className:"block text-center text-sm text-zinc-500 hover:text-white transition-colors",children:"Get code"})]})]})]})}function rt({className:e}){return jsxRuntime.jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"black"}),jsxRuntime.jsx("path",{d:"M8.53901 8L14.7164 16.2153L8.5 22.8947H9.89907L15.3415 17.0468L19.7389 22.8947H24.5L17.975 14.2173L23.7612 8H22.3621L17.3499 13.3858L13.3001 8H8.53901ZM10.5964 9.02501H12.7837L22.4422 21.8695H20.255L10.5964 9.02501Z",fill:"#F7F7F7"})]})}function it({className:e}){return jsxRuntime.jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#F1F2F9"}),jsxRuntime.jsx("path",{d:"M26.1001 16.2273C26.1001 15.5182 26.0365 14.8364 25.9183 14.1818H16.5001V18.05H21.8819C21.6501 19.3 20.9456 20.3591 19.8865 21.0682V23.5773H23.1183C25.0092 21.8364 26.1001 19.2727 26.1001 16.2273Z",fill:"#4285F4"}),jsxRuntime.jsx("path",{d:"M16.5001 26C19.2001 26 21.4637 25.1046 23.1182 23.5773L19.8864 21.0682C18.991 21.6682 17.8455 22.0227 16.5001 22.0227C13.8955 22.0227 11.691 20.2637 10.9046 17.9H7.56372V20.4909C9.20917 23.7591 12.591 26 16.5001 26Z",fill:"#34A853"}),jsxRuntime.jsx("path",{d:"M10.9047 17.8999C10.7047 17.2999 10.591 16.659 10.591 15.9999C10.591 15.3408 10.7047 14.6999 10.9047 14.0999V11.509H7.56376C6.86376 12.9025 6.49951 14.4405 6.50012 15.9999C6.50012 17.6136 6.88649 19.1408 7.56376 20.4908L10.9047 17.8999Z",fill:"#FBBC05"}),jsxRuntime.jsx("path",{d:"M16.5001 9.97726C17.9682 9.97726 19.2864 10.4818 20.3228 11.4727L23.191 8.60454C21.4591 6.99091 19.1955 6 16.5001 6C12.591 6 9.20917 8.2409 7.56372 11.5091L10.9046 14.1C11.691 11.7364 13.8955 9.97726 16.5001 9.97726Z",fill:"#EA4335"})]})}function ct({className:e}){return jsxRuntime.jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#5462EB"}),jsxRuntime.jsx("path",{d:"M23.5433 8.87438C22.2479 8.26174 20.8587 7.81038 19.4063 7.55187C19.3799 7.54688 19.3534 7.55934 19.3398 7.58428C19.1612 7.91179 18.9633 8.33905 18.8247 8.67487C17.2625 8.43382 15.7084 8.43382 14.1782 8.67487C14.0396 8.33158 13.8345 7.91179 13.6551 7.58428C13.6414 7.56018 13.615 7.54771 13.5886 7.55187C12.1369 7.80955 10.7478 8.26092 9.45159 8.87438C9.44037 8.87937 9.43075 8.88769 9.42437 8.89849C6.78947 12.9558 6.06766 16.9134 6.42176 20.8219C6.42336 20.841 6.43378 20.8593 6.4482 20.871C8.18663 22.1868 9.87059 22.9857 11.5233 23.5152C11.5497 23.5235 11.5778 23.5135 11.5946 23.491C11.9855 22.9408 12.334 22.3606 12.6328 21.7504C12.6505 21.7147 12.6336 21.6723 12.5976 21.6581C12.0448 21.442 11.5185 21.1785 11.0122 20.8793C10.9721 20.8552 10.9689 20.7961 11.0058 20.7679C11.1123 20.6856 11.2189 20.6 11.3206 20.5135C11.339 20.4977 11.3647 20.4944 11.3863 20.5044C14.7125 22.0696 18.3136 22.0696 21.6006 20.5044C21.6222 20.4936 21.6479 20.4969 21.6671 20.5127C21.7688 20.5991 21.8754 20.6856 21.9827 20.7679C22.0196 20.7961 22.0172 20.8552 21.9771 20.8793C21.4708 21.1843 20.9445 21.442 20.3909 21.6573C20.3548 21.6715 20.3388 21.7147 20.3564 21.7504C20.6617 22.3597 21.0101 22.9399 21.3939 23.4902C21.4099 23.5135 21.4387 23.5235 21.4652 23.5152C23.1259 22.9857 24.8099 22.1868 26.5483 20.871C26.5635 20.8593 26.5731 20.8419 26.5747 20.8228C26.9985 16.3041 25.8649 12.3789 23.5697 8.89931C23.5641 8.88769 23.5545 8.87937 23.5433 8.87438Z",fill:"#F7F7F7"})]})}function ut({className:e}){return jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",className:e||"h-8 w-8",children:[jsxRuntime.jsx("rect",{width:"512",height:"512",rx:"15%",fill:"#37aee2"}),jsxRuntime.jsx("path",{fill:"#c8daea",d:"M199 404c-11 0-10-4-13-14l-32-105 245-144"}),jsxRuntime.jsx("path",{fill:"#a9c9dd",d:"M199 404c7 0 11-4 16-8l45-43-56-34"}),jsxRuntime.jsx("path",{fill:"#f6fbfe",d:"M204 319l135 99c14 9 26 4 30-14l55-258c5-22-9-32-24-25L79 245c-21 8-21 21-4 26l83 26 190-121c9-5 17-3 11 4"})]})}
2
2
  exports.ConnectWidget=st;exports.DiscordIcon=ct;exports.EthereumIcon=de;exports.GoogleIcon=it;exports.MetaMaskIcon=ee;exports.OTPInput=q;exports.PhantomIcon=X;exports.SolanaIcon=le;exports.TelegramIcon=ut;exports.TwitterIcon=rt;exports.UserUtilsProvider=Re;exports.useUserUtilsContext=We;
@@ -1,2 +1,2 @@
1
- import {createContext,useContext,useState,useCallback,useEffect,useRef}from'react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var ge=createContext(null);function We(){let e=useContext(ge);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function Re({config:e,callbacks:n,children:r}){return jsx(ge.Provider,{value:{config:e,callbacks:n},children:r})}function he(){let[e,n]=useState({connected:false,address:null,chain:null,provider:null}),[r,l]=useState(null),h=useCallback(async(p="phantom")=>{l(null);try{let d=typeof window<"u"?window:null,b=p==="phantom"?d?.phantom?.solana||d?.solana:d?.solflare;if(!b)return l(`${p} wallet not found`),null;let u=(await b.connect()).publicKey.toString();return n({connected:!0,address:u,chain:"solana",provider:p}),u}catch(d){return l(d.message||"Failed to connect wallet"),null}},[]),y=useCallback(async()=>{l(null);try{let d=(typeof window<"u"?window:null)?.ethereum;if(!d)return l("MetaMask not found"),null;let b=d;d.providers?.length&&(b=d.providers.find(t=>t.isMetaMask)||d);let u=(await b.request({method:"eth_requestAccounts"}))[0];return u?(n({connected:!0,address:u,chain:"ethereum",provider:"metamask"}),u):(l("No account selected"),null)}catch(p){return l(p.message||"Failed to connect wallet"),null}},[]),g=useCallback(async(p,d)=>{l(null);let b=d?.chain||e.chain,s=d?.provider||e.provider,u=d?.address||e.address;try{if(b==="solana"){let t=typeof window<"u"?window:null,o=s==="solflare"?t?.solflare:t?.phantom?.solana||t?.solana;if(!o)throw new Error("Wallet not available");let c=new TextEncoder().encode(p),w=await o.signMessage(c,"utf8"),S=w.signature||w,N="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",I=BigInt(0);for(let x of S)I=I*256n+BigInt(x);let M="";for(;I>0n;)M=N[Number(I%58n)]+M,I=I/58n;for(let x of S)if(x===0)M="1"+M;else break;return M}if(b==="ethereum"){let o=(typeof window<"u"?window:null)?.ethereum;if(o?.providers?.length&&(o=o.providers.find(w=>w.isMetaMask)||o),!o)throw new Error("MetaMask not available");return await o.request({method:"personal_sign",params:[p,u]})}throw new Error("No wallet connected")}catch(t){return l(t.message||"Signing failed"),null}},[e]),i=useCallback(()=>{n({connected:false,address:null,chain:null,provider:null}),l(null);},[]);return {wallet:e,error:r,connectSolana:h,connectEVM:y,signMessage:g,disconnect:i}}function ke(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith("stackauth_session="));if(!e)return null;let n=e.slice(18);return JSON.parse(atob(n.replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function ye(e="__csrf"){if(typeof document>"u")return null;let n=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith(`${e}=`));return n?n.slice(e.length+1):null}function Ne(){let[e,n]=useState(null),[r,l]=useState(true),h=useCallback(()=>{let i=ke();i&&i.expiresAt>Date.now()?n({userId:i.userId,address:i.address,chain:i.chain,expiresAt:i.expiresAt,planId:i.planId,authMethod:i.authMethod}):n(null),l(false);},[]);useEffect(()=>{h();},[h]);let y=useCallback(async(i="")=>{try{let p=await fetch(`${i}/api/auth/session`);if(p.ok){let d=await p.json();if(d.session)return n(d.session),d.session}return n(null),null}catch{return null}},[]),g=!!e&&e.expiresAt>Date.now();return {session:e,loading:r,isAuthenticated:g,refresh:y,readSession:h}}function xe(e="__csrf",n="x-csrf-token"){let[r,l]=useState(null);useEffect(()=>{l(ye(e));},[e]);let h=r?{[n]:r}:{};return {token:r,headers:h}}var Ge="https://stacknet.magma-rpc.com/auth/bridge",J="stacknet-auth-bridge";function Ce(e){let n=e?.bridgeUrl||Ge,r=e?.disabled||false,l=useRef(null),[h,y]=useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),g=useRef([]),i=useRef(false),p=useCallback(t=>{let o={...t,protocol:J};i.current&&l.current?.contentWindow?l.current.contentWindow.postMessage(o,new URL(n).origin):g.current.push(o);},[n]);useEffect(()=>{if(r)return;let t=c=>{if(!(!c.data||c.data.protocol!==J)){try{if(c.origin!==new URL(n).origin)return}catch{return}switch(c.data.type){case "bridge:ready":i.current=true,y(w=>({...w,ready:true}));for(let w of g.current)l.current?.contentWindow?.postMessage(w,c.origin);g.current=[],l.current?.contentWindow?.postMessage({protocol:J,type:"auth:check"},c.origin),l.current?.contentWindow?.postMessage({protocol:J,type:"auth:resolve-stack"},c.origin);break;case "auth:status":y(w=>({...w,known:c.data.known,identity:c.data.identity,identityCount:c.data.identityCount||0}));break;case "auth:resolved-stack":y(w=>({...w,resolvedStackId:c.data.stackId||null}));break;}}};window.addEventListener("message",t);let o=document.createElement("iframe");return o.src=n,o.style.display="none",o.setAttribute("aria-hidden","true"),o.setAttribute("tabindex","-1"),o.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(o),l.current=o,()=>{window.removeEventListener("message",t),o.parentNode&&o.parentNode.removeChild(o),l.current=null,i.current=false;}},[n,r]);let d=useCallback(t=>{p({type:"auth:connected",...t});},[p]),b=useCallback(t=>{p({type:"auth:disconnected",...t});},[p]),s=useCallback(()=>{p({type:"auth:clear"}),y({ready:h.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[p,h.ready]),u=useCallback(()=>{p({type:"auth:check"});},[p]);return {...h,reportConnected:d,reportDisconnected:b,clearAll:s,refresh:u}}async function Me(e,n,r,l){let h=e.apiVersion||"v2",y=`${e.baseUrl}/api/${h}${r}`;try{let g=await fetch(y,{method:n,headers:{"Content-Type":"application/json"},body:l?JSON.stringify(l):void 0}),i=await g.json();return g.ok?i.success&&i.data!==void 0?{success:!0,data:i.data}:{success:!0,data:i}:{success:!1,error:i.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(g){return {success:false,error:{code:"NETWORK_ERROR",message:g instanceof Error?g.message:"Network error"}}}}function ve(e){return {getNetworkStatus:()=>Me(e,"GET","/network/status"),getWeb3Challenge:(n,r)=>Me(e,"POST",`/stacks/${e.stackId}/auth/web3/challenge`,{chain:n,address:r})}}function Ie(e={apiBaseUrl:""}){let{wallet:n,connectSolana:r,connectEVM:l,signMessage:h,disconnect:y}=he(),{session:g,isAuthenticated:i,refresh:p,readSession:d}=Ne(),{headers:b}=xe(),s=Ce({disabled:typeof window>"u"}),[u,t]=useState(false),[o,c]=useState(null),[w,S]=useState(false),N=e.apiBaseUrl||"",I=e.stacknetUrl||"https://stacknet.magma-rpc.com",M=e.stackId||s.resolvedStackId||"",x=ve({baseUrl:I,stackId:M}),L=useCallback(async(k,C,R,D)=>{t(true),c(null);try{let U=C;if(!U){let E=await R();if(!E)return t(!1),!1;U=E;}let T=await x.getWeb3Challenge(k,U);if(!T.success||!T.data)return c("Failed to get challenge"),t(!1),!1;let _=await h(T.data.message,{chain:k,provider:D,address:U});if(!_)return t(!1),!1;let B={chain:k,message:T.data.message,signature:_};k==="solana"&&(B.publicKey=U);let O=await fetch(`${N}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!O.ok){let E=await O.json().catch(()=>({}));return c(E.error||"Authentication failed"),t(!1),!1}return s.reportConnected({address:U,chain:k,method:D||(k==="solana"?"phantom":"metamask"),stackId:M}),d(),t(!1),!0}catch(U){return c(U.message||"Authentication failed"),t(false),false}},[N,x,h,d,s,M]),P=useCallback(async(k="phantom")=>{let C=await r(k);return C?L("solana",C,()=>r(k),k):false},[r,L]),z=useCallback(async()=>{let k=await l();return k?L("ethereum",k,l,"metamask"):false},[l,L]),Z=useCallback(async k=>{t(true),c(null);try{let C=await fetch(`${N}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:k})});if(!C.ok){let R=await C.json().catch(()=>({}));return c(R.error||"Invalid code"),t(!1),!1}return d(),t(!1),!0}catch(C){return c(C.message||"OTP verification failed"),t(false),false}},[N,d]),V=useCallback(async()=>{n.address&&n.chain&&s.reportDisconnected({address:n.address,chain:n.chain,stackId:M});try{await fetch(`${N}/api/auth/logout`,{method:"POST",headers:b});}catch{}y(),d();},[N,b,y,d,n,s,M]);return useEffect(()=>{if(!e.autoConnect||w||i||!s.ready||!s.known||!s.identity)return;S(true);let{chain:k,method:C}=s.identity;k==="solana"&&(C==="phantom"||C==="solflare")?P(C):k==="ethereum"&&z();},[e.autoConnect,w,i,s,P,z]),{session:g,isAuthenticated:i,wallet:n,loading:u,error:o,authenticateSolana:P,authenticateEVM:z,authenticateOTP:Z,logout:V,refresh:()=>p(N),stackId:M,bridge:{ready:s.ready,known:s.known,identity:s.identity,identityCount:s.identityCount,resolvedStackId:s.resolvedStackId}}}function Le(e,n="https://stacknet.magma-rpc.com"){let[r,l]=useState(null),[h,y]=useState(false),[g,i]=useState(null),p=useCallback(async b=>{y(true),i(null);try{let s=await fetch(`${n}/api/v2/stacks/${b}`);if(!s.ok)return i("Stack not found"),y(!1),null;let u=await s.json(),t=u.data?.stack||u.stack||u,o={id:t.id,name:t.name,displayName:t.displayName||t.name,description:t.description,logoUrl:t.logoUrl,webPageUrl:t.webPageUrl,allowedChains:t.allowedChains||[],features:t.features,stripeProvider:t.stripeProvider,oauthProviders:t.oauthProviders?.map(c=>({provider:c.provider,enabled:c.enabled!==!1}))};return l(o),y(!1),o}catch(s){return i(s.message),y(false),null}},[n]);useEffect(()=>{e&&p(e);},[e,p]);let d=r?Ke(r):[];return {config:r,loading:h,error:g,identityProviders:d,fetchConfig:p}}function Ke(e){let n=[];if(e.features?.web3Auth!==false&&(e.allowedChains.includes("solana")&&(n.push({type:"wallet",id:"phantom",name:"Phantom",chain:"solana"}),n.push({type:"wallet",id:"solflare",name:"Solflare",chain:"solana"})),(e.allowedChains.includes("ethereum")||e.allowedChains.includes("polygon")||e.allowedChains.includes("base"))&&n.push({type:"wallet",id:"metamask",name:"MetaMask",chain:"ethereum"})),e.features?.apiKeyAuth!==false&&n.push({type:"otp",id:"otp",name:"Access Code"}),e.features?.oauthAuth&&e.oauthProviders)for(let r of e.oauthProviders)r.enabled&&n.push({type:"oauth",id:r.provider,name:r.provider});return n}function q({length:e=6,onComplete:n,disabled:r=false,error:l,className:h="",inputClassName:y=""}){let [g,i]=useState(Array(e).fill("")),p=useCallback((s,u)=>{if(u.length>1){let o=u.replace(/\D/g,"").slice(0,e).split(""),c=[...g];o.forEach((S,N)=>{s+N<e&&(c[s+N]=S);}),i(c);let w=Math.min(s+o.length,e-1);document.getElementById(`userutils-otp-${w}`)?.focus(),c.every(S=>S!=="")&&setTimeout(()=>n(c.join("")),100);return}if(!/^\d?$/.test(u))return;let t=[...g];t[s]=u,i(t),u&&s<e-1&&document.getElementById(`userutils-otp-${s+1}`)?.focus(),u&&s===e-1&&t.every(o=>o!=="")&&setTimeout(()=>n(t.join("")),100);},[g,e,n]),d=useCallback((s,u)=>{if(u.key==="Backspace"&&!g[s]&&s>0){document.getElementById(`userutils-otp-${s-1}`)?.focus();let t=[...g];t[s-1]="",i(t);}if(u.key==="Enter"){let t=g.join("");t.length===e&&n(t);}},[g,e,n]);useCallback(()=>{i(Array(e).fill("")),document.getElementById("userutils-otp-0")?.focus();},[e]);return jsxs("div",{className:h,children:[jsx("div",{className:"flex gap-2 justify-center",children:g.map((s,u)=>jsx("input",{id:`userutils-otp-${u}`,type:"text",inputMode:"numeric",maxLength:e,value:s,onChange:t=>p(u,t.target.value),onKeyDown:t=>d(u,t),disabled:r,autoFocus:u===0,className:`w-12 h-14 text-center text-xl font-mono bg-secondary border border-primary/10 text-foreground focus:outline-none focus:border-primary/30 disabled:opacity-50 ${y}`},u))}),l&&jsx("p",{className:"text-center text-sm text-red-400 mt-2",children:l})]})}q.displayName="OTPInput";var Xe="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function X({className:e}){return jsx("img",{src:Xe,alt:"Phantom",className:e})}function ee({className:e}){return jsxs("svg",{className:e,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 507.83 470.86",children:[jsx("polygon",{fill:"#e2761b",stroke:"#e2761b",strokeLinecap:"round",strokeLinejoin:"round",points:"482.09 0.5 284.32 147.38 320.9 60.72 482.09 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"25.54 0.5 221.72 148.77 186.93 60.72 25.54 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"410.93 340.97 358.26 421.67 470.96 452.67 503.36 342.76 410.93 340.97"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"4.67 342.76 36.87 452.67 149.57 421.67 96.9 340.97 4.67 342.76"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 111.8 252.13 223.7 257.1 219.73 136.85 143.21 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"364.42 204.62 286.91 135.46 284.32 257.1 396.03 252.13 364.42 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 216.75 388.87 158.71 343.55 149.57 421.67"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 358.26 421.67 348.92 343.55 290.88 388.87"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"358.26 421.67 290.88 388.87 296.25 432.8 295.65 451.28 358.26 421.67"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 212.18 451.28 211.78 432.8 216.75 388.87 149.57 421.67"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"213.17 314.54 157.12 298.04 196.67 279.95 213.17 314.54"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"294.46 314.54 310.96 279.95 350.71 298.04 294.46 314.54"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 159.11 340.97 96.9 342.76 149.57 421.67"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"348.72 340.97 358.26 421.67 410.93 342.76 348.72 340.97"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"396.03 252.13 284.32 257.1 294.66 314.54 311.16 279.95 350.91 298.04 396.03 252.13"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 196.87 279.95 213.17 314.54 223.7 257.1 111.8 252.13 157.12 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"111.8 252.13 158.71 343.55 157.12 298.04 111.8 252.13"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"350.91 298.04 348.92 343.55 396.03 252.13 350.91 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"223.7 257.1 213.17 314.54 226.29 382.31 229.27 293.07 223.7 257.1"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 278.96 292.87 281.34 382.31 294.66 314.54 284.32 257.1"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"294.66 314.54 281.34 382.31 290.88 388.87 348.92 343.55 350.91 298.04 294.66 314.54"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 158.71 343.55 216.75 388.87 226.29 382.31 213.17 314.54 157.12 298.04"}),jsx("polygon",{fill:"#c0ad9e",stroke:"#c0ad9e",strokeLinecap:"round",strokeLinejoin:"round",points:"295.65 451.28 296.25 432.8 291.28 428.42 216.35 428.42 211.78 432.8 212.18 451.28 149.57 421.67 171.43 439.55 215.75 470.36 291.88 470.36 336.4 439.55 358.26 421.67 295.65 451.28"}),jsx("polygon",{fill:"#161616",stroke:"#161616",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 281.34 382.31 226.29 382.31 216.75 388.87 211.78 432.8 216.35 428.42 291.28 428.42 296.25 432.8 290.88 388.87"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"490.44 156.92 507.33 75.83 482.09 0.5 290.88 142.41 364.42 204.62 468.37 235.03 491.43 208.2 481.49 201.05 497.39 186.54 485.07 177 500.97 164.87 490.44 156.92"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"0.5 75.83 17.39 156.92 6.66 164.87 22.56 177 10.44 186.54 26.34 201.05 16.4 208.2 39.26 235.03 143.21 204.62 216.75 142.41 25.54 0.5 0.5 75.83"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"468.37 235.03 364.42 204.62 396.03 252.13 348.92 343.55 410.93 342.76 503.36 342.76 468.37 235.03"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 39.26 235.03 4.67 342.76 96.9 342.76 158.71 343.55 111.8 252.13 143.21 204.62"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 290.88 142.41 321.1 60.72 186.93 60.72 216.75 142.41 223.7 257.1 226.09 293.27 226.29 382.31 281.34 382.31 281.74 293.27 284.32 257.1"})]})}function le({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",className:e||"h-5 w-5",children:[jsxs("linearGradient",{id:"sol-g",x1:"7.233",x2:"24.766",y1:"24.766",y2:"7.234",gradientUnits:"userSpaceOnUse",children:[jsx("stop",{offset:"0",stopColor:"#9945ff"}),jsx("stop",{offset:"0.2",stopColor:"#7962e7"}),jsx("stop",{offset:"1",stopColor:"#00d18c"})]}),jsx("path",{fill:"#10111a",d:"M0 0h32v32H0z"}),jsx("path",{fill:"url(#sol-g)",fillRule:"evenodd",d:"M9.873 20.41a.65.65 0 0 1 .476-.21l14.662.012a.323.323 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54zm15.376-2.862a.322.322 0 0 1-.238.54l-14.662.012a.64.64 0 0 1-.476-.21l-3.122-3.44a.323.323 0 0 1 .238-.54l14.662-.012a.64.64 0 0 1 .475.21zM9.873 7.81a.64.64 0 0 1 .476-.21l14.662.012a.322.322 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54z",clipRule:"evenodd"})]})}function de({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",className:e||"h-5 w-5",children:[jsx("rect",{width:"20",height:"20",rx:"4",fill:"#627EEA",fillOpacity:"0.2"}),jsx("path",{fill:"#627EEA",d:"M10 3l-4 6.5 4 2.5 4-2.5L10 3z"}),jsx("path",{fill:"#627EEA",fillOpacity:"0.6",d:"M6 9.5L10 12l4-2.5L10 17 6 9.5z"})]})}function st({config:e,onSuccess:n,title:r="Log in or Sign up",showWallets:l,showOTP:h,className:y=""}){let g=Ie(e),{isAuthenticated:i,wallet:p,loading:d,error:b,authenticateSolana:s,authenticateEVM:u,authenticateOTP:t,bridge:o,stackId:c}=g,w=!e.stackId&&!c,S=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:N,identityProviders:I,loading:M}=Le(c||e.stackId||null,S),[x,L]=useState(w?"stack-select":"select"),[P,z]=useState(null),[Z,V]=useState(false),[k,C]=useState("idle"),[R,D]=useState(""),[U,T]=useState([]),[_,B]=useState(e.stackId||null),[O,E]=useState(false),[ze,Ae]=useState(false);useEffect(()=>{if(typeof window>"u")return;let m=()=>{let W=window;E(!!(W.phantom?.solana?.isPhantom||W.solana?.isPhantom));let H=W.ethereum;Ae(!!(H?.isMetaMask||H?.providers?.some(Q=>Q.isMetaMask)));};m(),window.addEventListener("ethereum#initialized",m);let A=setTimeout(m,500);return ()=>{window.removeEventListener("ethereum#initialized",m),clearTimeout(A);}},[]),useEffect(()=>{x==="stack-select"&&c&&(B(c),L("select"));},[x,c]),useEffect(()=>{if(!(!o.ready||!w)&&o.identity){let m=[];o.resolvedStackId&&m.push({stackId:o.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(m.map(async A=>{try{let W=await fetch(`${S}/api/v2/stacks/${A.stackId}`);if(W.ok){let H=await W.json(),Q=H.data?.stack||H;A.name=Q.displayName||Q.name,A.logoUrl=Q.logoUrl;}}catch{}return A})).then(T);}},[o.ready,o.identity,o.resolvedStackId,w,S]),useEffect(()=>{i&&x==="success"&&n?.();},[i,x,n]);let ue=l||(I.length>0?I.filter(m=>m.type==="wallet").map(m=>m.id):["phantom","metamask"]),pe=h!==void 0?h:I.length>0?I.some(m=>m.type==="otp"):true,Pe=async()=>{z("phantom"),L("connecting");let m=await s("phantom");L(m?"success":"error");},De=async()=>{z("metamask"),L("connecting");let m=await u();L(m?"success":"error");},Te=async m=>{C("verifying"),D(""),await t(m)?(C("success"),L("success")):(C("error"),D("Invalid or expired code"),setTimeout(()=>C("idle"),2e3));},fe=()=>{L(w&&!_?"stack-select":"select"),z(null),V(false),C("idle"),D("");};return jsxs("div",{className:`w-full max-w-md space-y-3 ${y}`,children:[jsxs("div",{className:"mb-6 text-center",children:[N?.logoUrl&&x!=="stack-select"&&jsx("img",{src:N.logoUrl,alt:"",className:"h-10 w-10 mx-auto mb-3"}),jsx("h1",{className:"font-semibold text-2xl text-white",children:r}),N?.displayName&&x!=="stack-select"&&jsx("p",{className:"text-sm text-zinc-400 mt-1",children:N.displayName})]}),x==="stack-select"&&jsxs("div",{className:"space-y-3",children:[jsx("p",{className:"text-center text-sm text-zinc-400 mb-4",children:U.length>0?"Select a network to continue":"No previous connections found. Enter a Stack ID to continue."}),U.map(m=>jsxs("button",{onClick:()=>{B(m.stackId),L("select");},className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[m.logoUrl?jsx("img",{src:m.logoUrl,alt:"",className:"h-10 w-10 flex-shrink-0"}):jsx("div",{className:"h-10 w-10 flex-shrink-0 bg-zinc-700 flex items-center justify-center text-zinc-400 text-sm font-mono",children:m.name?.[0]?.toUpperCase()||"S"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-white",children:m.name||m.stackId}),jsx("p",{className:"text-xs text-zinc-500",children:m.domain})]}),jsx("span",{className:"text-xs text-zinc-600",children:"Previously connected"})]},m.stackId)),o.ready&&!o.known&&jsx("p",{className:"text-center text-xs text-zinc-600 mt-4",children:"Connect to a stack for the first time to get started."})]}),x==="select"&&M&&jsx("div",{className:"flex items-center justify-center py-8",children:jsx("div",{className:"h-6 w-6 border-2 border-zinc-600 border-t-white animate-spin",style:{borderRadius:"50%"}})}),b&&x==="error"&&jsxs("div",{className:"mb-4 border border-red-500/30 bg-red-500/10 p-4",children:[jsx("p",{className:"text-center text-red-400 text-sm",children:b}),jsx("button",{className:"mt-3 w-full text-sm text-zinc-400 hover:text-white",onClick:fe,children:"Try Again"})]}),x==="success"&&jsxs("div",{className:"border border-green-500/30 bg-green-500/10 p-6 text-center",children:[jsx("p",{className:"font-medium text-green-400 text-sm",children:"Connected!"}),jsx("p",{className:"mt-1 text-xs text-zinc-400",children:"Redirecting..."})]}),x==="connecting"&&d&&jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 text-center",children:[jsxs("div",{className:"mx-auto mb-3 h-14 w-14 animate-pulse",children:[P==="phantom"&&jsx(X,{className:"h-14 w-14"}),P==="metamask"&&jsx(ee,{className:"h-14 w-14"})]}),jsx("p",{className:"font-medium text-sm text-white",children:p.connected?"Signing message...":"Connecting wallet..."}),jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Please confirm in your wallet"}),jsx("button",{className:"mt-4 text-sm text-zinc-500 hover:text-white",onClick:fe,children:"Cancel"})]}),x==="select"&&!d&&!M&&jsxs(Fragment,{children:[ue.includes("phantom")&&jsxs("button",{onClick:Pe,disabled:!O,className:`flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a] ${O?"":"cursor-not-allowed opacity-50"}`,children:[jsx(X,{className:"h-14 w-14 flex-shrink-0"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-lg text-white",children:"Phantom"}),!O&&jsx("p",{className:"text-xs text-zinc-500",children:"Not installed"})]}),jsx(le,{className:"h-8 w-8"})]}),ue.includes("metamask")&&ze&&jsxs("button",{onClick:De,className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center bg-white p-2",children:jsx(ee,{className:"h-10 w-10"})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white",children:"MetaMask"})}),jsx(de,{className:"h-8 w-8"})]}),pe&&!Z&&jsxs("button",{onClick:()=>V(true),className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center border border-zinc-700 bg-[#2a2a3e]",children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"28px",viewBox:"0 -960 960 960",width:"28px",fill:"#e3e3e3",children:jsx("path",{d:"M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v480q0 33-23.5 56.5T800-160H160Z"})})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white",children:"Access Code"})})]}),pe&&Z&&jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 space-y-4",children:[jsx("p",{className:"text-center text-sm text-zinc-400",children:"Enter your 6-digit access code"}),jsx(q,{onComplete:Te,disabled:k==="verifying",error:R}),k==="verifying"&&jsx("p",{className:"text-center text-sm text-zinc-400 animate-pulse",children:"Verifying..."}),k==="success"&&jsx("p",{className:"text-center text-sm text-green-400",children:"Verified!"}),N?.webPageUrl&&k==="idle"&&jsx("a",{href:`${N.webPageUrl}/connect/pair`,target:"_blank",rel:"noopener noreferrer",className:"block text-center text-sm text-zinc-500 hover:text-white transition-colors",children:"Get code"})]})]})]})}function rt({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"black"}),jsx("path",{d:"M8.53901 8L14.7164 16.2153L8.5 22.8947H9.89907L15.3415 17.0468L19.7389 22.8947H24.5L17.975 14.2173L23.7612 8H22.3621L17.3499 13.3858L13.3001 8H8.53901ZM10.5964 9.02501H12.7837L22.4422 21.8695H20.255L10.5964 9.02501Z",fill:"#F7F7F7"})]})}function it({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#F1F2F9"}),jsx("path",{d:"M26.1001 16.2273C26.1001 15.5182 26.0365 14.8364 25.9183 14.1818H16.5001V18.05H21.8819C21.6501 19.3 20.9456 20.3591 19.8865 21.0682V23.5773H23.1183C25.0092 21.8364 26.1001 19.2727 26.1001 16.2273Z",fill:"#4285F4"}),jsx("path",{d:"M16.5001 26C19.2001 26 21.4637 25.1046 23.1182 23.5773L19.8864 21.0682C18.991 21.6682 17.8455 22.0227 16.5001 22.0227C13.8955 22.0227 11.691 20.2637 10.9046 17.9H7.56372V20.4909C9.20917 23.7591 12.591 26 16.5001 26Z",fill:"#34A853"}),jsx("path",{d:"M10.9047 17.8999C10.7047 17.2999 10.591 16.659 10.591 15.9999C10.591 15.3408 10.7047 14.6999 10.9047 14.0999V11.509H7.56376C6.86376 12.9025 6.49951 14.4405 6.50012 15.9999C6.50012 17.6136 6.88649 19.1408 7.56376 20.4908L10.9047 17.8999Z",fill:"#FBBC05"}),jsx("path",{d:"M16.5001 9.97726C17.9682 9.97726 19.2864 10.4818 20.3228 11.4727L23.191 8.60454C21.4591 6.99091 19.1955 6 16.5001 6C12.591 6 9.20917 8.2409 7.56372 11.5091L10.9046 14.1C11.691 11.7364 13.8955 9.97726 16.5001 9.97726Z",fill:"#EA4335"})]})}function ct({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#5462EB"}),jsx("path",{d:"M23.5433 8.87438C22.2479 8.26174 20.8587 7.81038 19.4063 7.55187C19.3799 7.54688 19.3534 7.55934 19.3398 7.58428C19.1612 7.91179 18.9633 8.33905 18.8247 8.67487C17.2625 8.43382 15.7084 8.43382 14.1782 8.67487C14.0396 8.33158 13.8345 7.91179 13.6551 7.58428C13.6414 7.56018 13.615 7.54771 13.5886 7.55187C12.1369 7.80955 10.7478 8.26092 9.45159 8.87438C9.44037 8.87937 9.43075 8.88769 9.42437 8.89849C6.78947 12.9558 6.06766 16.9134 6.42176 20.8219C6.42336 20.841 6.43378 20.8593 6.4482 20.871C8.18663 22.1868 9.87059 22.9857 11.5233 23.5152C11.5497 23.5235 11.5778 23.5135 11.5946 23.491C11.9855 22.9408 12.334 22.3606 12.6328 21.7504C12.6505 21.7147 12.6336 21.6723 12.5976 21.6581C12.0448 21.442 11.5185 21.1785 11.0122 20.8793C10.9721 20.8552 10.9689 20.7961 11.0058 20.7679C11.1123 20.6856 11.2189 20.6 11.3206 20.5135C11.339 20.4977 11.3647 20.4944 11.3863 20.5044C14.7125 22.0696 18.3136 22.0696 21.6006 20.5044C21.6222 20.4936 21.6479 20.4969 21.6671 20.5127C21.7688 20.5991 21.8754 20.6856 21.9827 20.7679C22.0196 20.7961 22.0172 20.8552 21.9771 20.8793C21.4708 21.1843 20.9445 21.442 20.3909 21.6573C20.3548 21.6715 20.3388 21.7147 20.3564 21.7504C20.6617 22.3597 21.0101 22.9399 21.3939 23.4902C21.4099 23.5135 21.4387 23.5235 21.4652 23.5152C23.1259 22.9857 24.8099 22.1868 26.5483 20.871C26.5635 20.8593 26.5731 20.8419 26.5747 20.8228C26.9985 16.3041 25.8649 12.3789 23.5697 8.89931C23.5641 8.88769 23.5545 8.87937 23.5433 8.87438Z",fill:"#F7F7F7"})]})}function ut({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",className:e||"h-8 w-8",children:[jsx("rect",{width:"512",height:"512",rx:"15%",fill:"#37aee2"}),jsx("path",{fill:"#c8daea",d:"M199 404c-11 0-10-4-13-14l-32-105 245-144"}),jsx("path",{fill:"#a9c9dd",d:"M199 404c7 0 11-4 16-8l45-43-56-34"}),jsx("path",{fill:"#f6fbfe",d:"M204 319l135 99c14 9 26 4 30-14l55-258c5-22-9-32-24-25L79 245c-21 8-21 21-4 26l83 26 190-121c9-5 17-3 11 4"})]})}
1
+ import {createContext,useContext,useState,useCallback,useEffect,useRef}from'react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var ge=createContext(null);function We(){let e=useContext(ge);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function Re({config:e,callbacks:n,children:r}){return jsx(ge.Provider,{value:{config:e,callbacks:n},children:r})}function he(){let[e,n]=useState({connected:false,address:null,chain:null,provider:null}),[r,l]=useState(null),h=useCallback(async(p="phantom")=>{l(null);try{let d=typeof window<"u"?window:null,b=p==="phantom"?d?.phantom?.solana||d?.solana:d?.solflare;if(!b)return l(`${p} wallet not found`),null;let u=(await b.connect()).publicKey.toString();return n({connected:!0,address:u,chain:"solana",provider:p}),u}catch(d){return l(d.message||"Failed to connect wallet"),null}},[]),y=useCallback(async()=>{l(null);try{let d=(typeof window<"u"?window:null)?.ethereum;if(!d)return l("MetaMask not found"),null;let b=d;d.providers?.length&&(b=d.providers.find(t=>t.isMetaMask)||d);let u=(await b.request({method:"eth_requestAccounts"}))[0];return u?(n({connected:!0,address:u,chain:"ethereum",provider:"metamask"}),u):(l("No account selected"),null)}catch(p){return l(p.message||"Failed to connect wallet"),null}},[]),g=useCallback(async(p,d)=>{l(null);let b=d?.chain||e.chain,s=d?.provider||e.provider,u=d?.address||e.address;try{if(b==="solana"){let t=typeof window<"u"?window:null,o=s==="solflare"?t?.solflare:t?.phantom?.solana||t?.solana;if(!o)throw new Error("Wallet not available");let c=new TextEncoder().encode(p),w=await o.signMessage(c,"utf8"),S=w.signature||w,N="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",I=BigInt(0);for(let x of S)I=I*256n+BigInt(x);let M="";for(;I>0n;)M=N[Number(I%58n)]+M,I=I/58n;for(let x of S)if(x===0)M="1"+M;else break;return M}if(b==="ethereum"){let o=(typeof window<"u"?window:null)?.ethereum;if(o?.providers?.length&&(o=o.providers.find(w=>w.isMetaMask)||o),!o)throw new Error("MetaMask not available");return await o.request({method:"personal_sign",params:[p,u]})}throw new Error("No wallet connected")}catch(t){return l(t.message||"Signing failed"),null}},[e]),i=useCallback(()=>{n({connected:false,address:null,chain:null,provider:null}),l(null);},[]);return {wallet:e,error:r,connectSolana:h,connectEVM:y,signMessage:g,disconnect:i}}function ke(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith("stackauth_session="));if(!e)return null;let n=e.slice(18);return JSON.parse(atob(n.replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function ye(e="__csrf"){if(typeof document>"u")return null;let n=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith(`${e}=`));return n?n.slice(e.length+1):null}function Ne(){let[e,n]=useState(null),[r,l]=useState(true),h=useCallback(()=>{let i=ke();i&&i.expiresAt>Date.now()?n({userId:i.userId,address:i.address,chain:i.chain,expiresAt:i.expiresAt,planId:i.planId,authMethod:i.authMethod}):n(null),l(false);},[]);useEffect(()=>{h();},[h]);let y=useCallback(async(i="")=>{try{let p=await fetch(`${i}/api/auth/session`);if(p.ok){let d=await p.json();if(d.session)return n(d.session),d.session}return n(null),null}catch{return null}},[]),g=!!e&&e.expiresAt>Date.now();return {session:e,loading:r,isAuthenticated:g,refresh:y,readSession:h}}function xe(e="__csrf",n="x-csrf-token"){let[r,l]=useState(null);useEffect(()=>{l(ye(e));},[e]);let h=r?{[n]:r}:{};return {token:r,headers:h}}var Ge="https://stacknet.magma-rpc.com/auth/bridge",J="stacknet-auth-bridge";function Ce(e){let n=e?.bridgeUrl||Ge,r=e?.disabled||false,l=useRef(null),[h,y]=useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),g=useRef([]),i=useRef(false),p=useCallback(t=>{let o={...t,protocol:J};i.current&&l.current?.contentWindow?l.current.contentWindow.postMessage(o,new URL(n).origin):g.current.push(o);},[n]);useEffect(()=>{if(r)return;let t=c=>{if(!(!c.data||c.data.protocol!==J)){try{if(c.origin!==new URL(n).origin)return}catch{return}switch(c.data.type){case "bridge:ready":i.current=true,y(w=>({...w,ready:true}));for(let w of g.current)l.current?.contentWindow?.postMessage(w,c.origin);g.current=[],l.current?.contentWindow?.postMessage({protocol:J,type:"auth:check"},c.origin),l.current?.contentWindow?.postMessage({protocol:J,type:"auth:resolve-stack"},c.origin);break;case "auth:status":y(w=>({...w,known:c.data.known,identity:c.data.identity,identityCount:c.data.identityCount||0}));break;case "auth:resolved-stack":y(w=>({...w,resolvedStackId:c.data.stackId||null}));break;}}};window.addEventListener("message",t);let o=document.createElement("iframe");return o.src=n,o.style.display="none",o.setAttribute("aria-hidden","true"),o.setAttribute("tabindex","-1"),o.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(o),l.current=o,()=>{window.removeEventListener("message",t),o.parentNode&&o.parentNode.removeChild(o),l.current=null,i.current=false;}},[n,r]);let d=useCallback(t=>{p({type:"auth:connected",...t});},[p]),b=useCallback(t=>{p({type:"auth:disconnected",...t});},[p]),s=useCallback(()=>{p({type:"auth:clear"}),y({ready:h.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[p,h.ready]),u=useCallback(()=>{p({type:"auth:check"});},[p]);return {...h,reportConnected:d,reportDisconnected:b,clearAll:s,refresh:u}}async function Me(e,n,r,l){let h=e.apiVersion||"v2",y=`${e.baseUrl}/api/${h}${r}`;try{let g=await fetch(y,{method:n,headers:{"Content-Type":"application/json"},body:l?JSON.stringify(l):void 0}),i=await g.json();return g.ok?i.success&&i.data!==void 0?{success:!0,data:i.data}:{success:!0,data:i}:{success:!1,error:i.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(g){return {success:false,error:{code:"NETWORK_ERROR",message:g instanceof Error?g.message:"Network error"}}}}function ve(e){return {getNetworkStatus:()=>Me(e,"GET","/network/status"),getWeb3Challenge:(n,r)=>Me(e,"POST",`/stacks/${e.stackId}/auth/web3/challenge`,{chain:n,address:r})}}function Ie(e={apiBaseUrl:""}){let{wallet:n,connectSolana:r,connectEVM:l,signMessage:h,disconnect:y}=he(),{session:g,isAuthenticated:i,refresh:p,readSession:d}=Ne(),{headers:b}=xe(),s=Ce({disabled:typeof window>"u"}),[u,t]=useState(false),[o,c]=useState(null),[w,S]=useState(false),N=e.apiBaseUrl||"",I=e.stacknetUrl||"https://stacknet.magma-rpc.com",M=e.stackId||s.resolvedStackId||"",x=ve({baseUrl:I,stackId:M}),L=useCallback(async(k,C,R,D)=>{t(true),c(null);try{let U=C;if(!U){let E=await R();if(!E)return t(!1),!1;U=E;}let T=await x.getWeb3Challenge(k,U);if(!T.success||!T.data)return c("Failed to get challenge"),t(!1),!1;let _=await h(T.data.message,{chain:k,provider:D,address:U});if(!_)return t(!1),!1;let B={chain:k,message:T.data.message,signature:_,stackId:M};k==="solana"&&(B.publicKey=U);let O=await fetch(`${N}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!O.ok){let E=await O.json().catch(()=>({}));return c(E.error||"Authentication failed"),t(!1),!1}return s.reportConnected({address:U,chain:k,method:D||(k==="solana"?"phantom":"metamask"),stackId:M}),d(),t(!1),!0}catch(U){return c(U.message||"Authentication failed"),t(false),false}},[N,x,h,d,s,M]),P=useCallback(async(k="phantom")=>{let C=await r(k);return C?L("solana",C,()=>r(k),k):false},[r,L]),z=useCallback(async()=>{let k=await l();return k?L("ethereum",k,l,"metamask"):false},[l,L]),Z=useCallback(async k=>{t(true),c(null);try{let C=await fetch(`${N}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:k})});if(!C.ok){let R=await C.json().catch(()=>({}));return c(R.error||"Invalid code"),t(!1),!1}return d(),t(!1),!0}catch(C){return c(C.message||"OTP verification failed"),t(false),false}},[N,d]),V=useCallback(async()=>{n.address&&n.chain&&s.reportDisconnected({address:n.address,chain:n.chain,stackId:M});try{await fetch(`${N}/api/auth/logout`,{method:"POST",headers:b});}catch{}y(),d();},[N,b,y,d,n,s,M]);return useEffect(()=>{if(!e.autoConnect||w||i||!s.ready||!s.known||!s.identity)return;S(true);let{chain:k,method:C}=s.identity;k==="solana"&&(C==="phantom"||C==="solflare")?P(C):k==="ethereum"&&z();},[e.autoConnect,w,i,s,P,z]),{session:g,isAuthenticated:i,wallet:n,loading:u,error:o,authenticateSolana:P,authenticateEVM:z,authenticateOTP:Z,logout:V,refresh:()=>p(N),stackId:M,bridge:{ready:s.ready,known:s.known,identity:s.identity,identityCount:s.identityCount,resolvedStackId:s.resolvedStackId}}}function Le(e,n="https://stacknet.magma-rpc.com"){let[r,l]=useState(null),[h,y]=useState(false),[g,i]=useState(null),p=useCallback(async b=>{y(true),i(null);try{let s=await fetch(`${n}/api/v2/stacks/${b}`);if(!s.ok)return i("Stack not found"),y(!1),null;let u=await s.json(),t=u.data?.stack||u.stack||u,o={id:t.id,name:t.name,displayName:t.displayName||t.name,description:t.description,logoUrl:t.logoUrl,webPageUrl:t.webPageUrl,allowedChains:t.allowedChains||[],features:t.features,stripeProvider:t.stripeProvider,oauthProviders:t.oauthProviders?.map(c=>({provider:c.provider,enabled:c.enabled!==!1}))};return l(o),y(!1),o}catch(s){return i(s.message),y(false),null}},[n]);useEffect(()=>{e&&p(e);},[e,p]);let d=r?Ke(r):[];return {config:r,loading:h,error:g,identityProviders:d,fetchConfig:p}}function Ke(e){let n=[];if(e.features?.web3Auth!==false&&(e.allowedChains.includes("solana")&&(n.push({type:"wallet",id:"phantom",name:"Phantom",chain:"solana"}),n.push({type:"wallet",id:"solflare",name:"Solflare",chain:"solana"})),(e.allowedChains.includes("ethereum")||e.allowedChains.includes("polygon")||e.allowedChains.includes("base"))&&n.push({type:"wallet",id:"metamask",name:"MetaMask",chain:"ethereum"})),e.features?.apiKeyAuth!==false&&n.push({type:"otp",id:"otp",name:"Access Code"}),e.features?.oauthAuth&&e.oauthProviders)for(let r of e.oauthProviders)r.enabled&&n.push({type:"oauth",id:r.provider,name:r.provider});return n}function q({length:e=6,onComplete:n,disabled:r=false,error:l,className:h="",inputClassName:y=""}){let [g,i]=useState(Array(e).fill("")),p=useCallback((s,u)=>{if(u.length>1){let o=u.replace(/\D/g,"").slice(0,e).split(""),c=[...g];o.forEach((S,N)=>{s+N<e&&(c[s+N]=S);}),i(c);let w=Math.min(s+o.length,e-1);document.getElementById(`userutils-otp-${w}`)?.focus(),c.every(S=>S!=="")&&setTimeout(()=>n(c.join("")),100);return}if(!/^\d?$/.test(u))return;let t=[...g];t[s]=u,i(t),u&&s<e-1&&document.getElementById(`userutils-otp-${s+1}`)?.focus(),u&&s===e-1&&t.every(o=>o!=="")&&setTimeout(()=>n(t.join("")),100);},[g,e,n]),d=useCallback((s,u)=>{if(u.key==="Backspace"&&!g[s]&&s>0){document.getElementById(`userutils-otp-${s-1}`)?.focus();let t=[...g];t[s-1]="",i(t);}if(u.key==="Enter"){let t=g.join("");t.length===e&&n(t);}},[g,e,n]);useCallback(()=>{i(Array(e).fill("")),document.getElementById("userutils-otp-0")?.focus();},[e]);return jsxs("div",{className:h,children:[jsx("div",{className:"flex gap-2 justify-center",children:g.map((s,u)=>jsx("input",{id:`userutils-otp-${u}`,type:"text",inputMode:"numeric",maxLength:e,value:s,onChange:t=>p(u,t.target.value),onKeyDown:t=>d(u,t),disabled:r,autoFocus:u===0,className:`w-12 h-14 text-center text-xl font-mono bg-secondary border border-primary/10 text-foreground focus:outline-none focus:border-primary/30 disabled:opacity-50 ${y}`},u))}),l&&jsx("p",{className:"text-center text-sm text-red-400 mt-2",children:l})]})}q.displayName="OTPInput";var Xe="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function X({className:e}){return jsx("img",{src:Xe,alt:"Phantom",className:e})}function ee({className:e}){return jsxs("svg",{className:e,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 507.83 470.86",children:[jsx("polygon",{fill:"#e2761b",stroke:"#e2761b",strokeLinecap:"round",strokeLinejoin:"round",points:"482.09 0.5 284.32 147.38 320.9 60.72 482.09 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"25.54 0.5 221.72 148.77 186.93 60.72 25.54 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"410.93 340.97 358.26 421.67 470.96 452.67 503.36 342.76 410.93 340.97"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"4.67 342.76 36.87 452.67 149.57 421.67 96.9 340.97 4.67 342.76"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 111.8 252.13 223.7 257.1 219.73 136.85 143.21 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"364.42 204.62 286.91 135.46 284.32 257.1 396.03 252.13 364.42 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 216.75 388.87 158.71 343.55 149.57 421.67"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 358.26 421.67 348.92 343.55 290.88 388.87"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"358.26 421.67 290.88 388.87 296.25 432.8 295.65 451.28 358.26 421.67"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 212.18 451.28 211.78 432.8 216.75 388.87 149.57 421.67"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"213.17 314.54 157.12 298.04 196.67 279.95 213.17 314.54"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"294.46 314.54 310.96 279.95 350.71 298.04 294.46 314.54"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 159.11 340.97 96.9 342.76 149.57 421.67"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"348.72 340.97 358.26 421.67 410.93 342.76 348.72 340.97"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"396.03 252.13 284.32 257.1 294.66 314.54 311.16 279.95 350.91 298.04 396.03 252.13"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 196.87 279.95 213.17 314.54 223.7 257.1 111.8 252.13 157.12 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"111.8 252.13 158.71 343.55 157.12 298.04 111.8 252.13"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"350.91 298.04 348.92 343.55 396.03 252.13 350.91 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"223.7 257.1 213.17 314.54 226.29 382.31 229.27 293.07 223.7 257.1"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 278.96 292.87 281.34 382.31 294.66 314.54 284.32 257.1"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"294.66 314.54 281.34 382.31 290.88 388.87 348.92 343.55 350.91 298.04 294.66 314.54"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 158.71 343.55 216.75 388.87 226.29 382.31 213.17 314.54 157.12 298.04"}),jsx("polygon",{fill:"#c0ad9e",stroke:"#c0ad9e",strokeLinecap:"round",strokeLinejoin:"round",points:"295.65 451.28 296.25 432.8 291.28 428.42 216.35 428.42 211.78 432.8 212.18 451.28 149.57 421.67 171.43 439.55 215.75 470.36 291.88 470.36 336.4 439.55 358.26 421.67 295.65 451.28"}),jsx("polygon",{fill:"#161616",stroke:"#161616",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 281.34 382.31 226.29 382.31 216.75 388.87 211.78 432.8 216.35 428.42 291.28 428.42 296.25 432.8 290.88 388.87"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"490.44 156.92 507.33 75.83 482.09 0.5 290.88 142.41 364.42 204.62 468.37 235.03 491.43 208.2 481.49 201.05 497.39 186.54 485.07 177 500.97 164.87 490.44 156.92"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"0.5 75.83 17.39 156.92 6.66 164.87 22.56 177 10.44 186.54 26.34 201.05 16.4 208.2 39.26 235.03 143.21 204.62 216.75 142.41 25.54 0.5 0.5 75.83"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"468.37 235.03 364.42 204.62 396.03 252.13 348.92 343.55 410.93 342.76 503.36 342.76 468.37 235.03"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 39.26 235.03 4.67 342.76 96.9 342.76 158.71 343.55 111.8 252.13 143.21 204.62"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 290.88 142.41 321.1 60.72 186.93 60.72 216.75 142.41 223.7 257.1 226.09 293.27 226.29 382.31 281.34 382.31 281.74 293.27 284.32 257.1"})]})}function le({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",className:e||"h-5 w-5",children:[jsxs("linearGradient",{id:"sol-g",x1:"7.233",x2:"24.766",y1:"24.766",y2:"7.234",gradientUnits:"userSpaceOnUse",children:[jsx("stop",{offset:"0",stopColor:"#9945ff"}),jsx("stop",{offset:"0.2",stopColor:"#7962e7"}),jsx("stop",{offset:"1",stopColor:"#00d18c"})]}),jsx("path",{fill:"#10111a",d:"M0 0h32v32H0z"}),jsx("path",{fill:"url(#sol-g)",fillRule:"evenodd",d:"M9.873 20.41a.65.65 0 0 1 .476-.21l14.662.012a.323.323 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54zm15.376-2.862a.322.322 0 0 1-.238.54l-14.662.012a.64.64 0 0 1-.476-.21l-3.122-3.44a.323.323 0 0 1 .238-.54l14.662-.012a.64.64 0 0 1 .475.21zM9.873 7.81a.64.64 0 0 1 .476-.21l14.662.012a.322.322 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54z",clipRule:"evenodd"})]})}function de({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",className:e||"h-5 w-5",children:[jsx("rect",{width:"20",height:"20",rx:"4",fill:"#627EEA",fillOpacity:"0.2"}),jsx("path",{fill:"#627EEA",d:"M10 3l-4 6.5 4 2.5 4-2.5L10 3z"}),jsx("path",{fill:"#627EEA",fillOpacity:"0.6",d:"M6 9.5L10 12l4-2.5L10 17 6 9.5z"})]})}function st({config:e,onSuccess:n,title:r="Log in or Sign up",showWallets:l,showOTP:h,className:y=""}){let g=Ie(e),{isAuthenticated:i,wallet:p,loading:d,error:b,authenticateSolana:s,authenticateEVM:u,authenticateOTP:t,bridge:o,stackId:c}=g,w=!e.stackId&&!c,S=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:N,identityProviders:I,loading:M}=Le(c||e.stackId||null,S),[x,L]=useState(w?"stack-select":"select"),[P,z]=useState(null),[Z,V]=useState(false),[k,C]=useState("idle"),[R,D]=useState(""),[U,T]=useState([]),[_,B]=useState(e.stackId||null),[O,E]=useState(false),[ze,Ae]=useState(false);useEffect(()=>{if(typeof window>"u")return;let m=()=>{let W=window;E(!!(W.phantom?.solana?.isPhantom||W.solana?.isPhantom));let H=W.ethereum;Ae(!!(H?.isMetaMask||H?.providers?.some(Q=>Q.isMetaMask)));};m(),window.addEventListener("ethereum#initialized",m);let A=setTimeout(m,500);return ()=>{window.removeEventListener("ethereum#initialized",m),clearTimeout(A);}},[]),useEffect(()=>{x==="stack-select"&&c&&(B(c),L("select"));},[x,c]),useEffect(()=>{if(!(!o.ready||!w)&&o.identity){let m=[];o.resolvedStackId&&m.push({stackId:o.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(m.map(async A=>{try{let W=await fetch(`${S}/api/v2/stacks/${A.stackId}`);if(W.ok){let H=await W.json(),Q=H.data?.stack||H;A.name=Q.displayName||Q.name,A.logoUrl=Q.logoUrl;}}catch{}return A})).then(T);}},[o.ready,o.identity,o.resolvedStackId,w,S]),useEffect(()=>{i&&x==="success"&&n?.();},[i,x,n]);let ue=l||(I.length>0?I.filter(m=>m.type==="wallet").map(m=>m.id):["phantom","metamask"]),pe=h!==void 0?h:I.length>0?I.some(m=>m.type==="otp"):true,Pe=async()=>{z("phantom"),L("connecting");let m=await s("phantom");L(m?"success":"error");},De=async()=>{z("metamask"),L("connecting");let m=await u();L(m?"success":"error");},Te=async m=>{C("verifying"),D(""),await t(m)?(C("success"),L("success")):(C("error"),D("Invalid or expired code"),setTimeout(()=>C("idle"),2e3));},fe=()=>{L(w&&!_?"stack-select":"select"),z(null),V(false),C("idle"),D("");};return jsxs("div",{className:`w-full max-w-md space-y-3 ${y}`,children:[jsxs("div",{className:"mb-6 text-center",children:[N?.logoUrl&&x!=="stack-select"&&jsx("img",{src:N.logoUrl,alt:"",className:"h-10 w-10 mx-auto mb-3"}),jsx("h1",{className:"font-semibold text-2xl text-white",children:r}),N?.displayName&&x!=="stack-select"&&jsx("p",{className:"text-sm text-zinc-400 mt-1",children:N.displayName})]}),x==="stack-select"&&jsxs("div",{className:"space-y-3",children:[jsx("p",{className:"text-center text-sm text-zinc-400 mb-4",children:U.length>0?"Select a network to continue":"No previous connections found. Enter a Stack ID to continue."}),U.map(m=>jsxs("button",{onClick:()=>{B(m.stackId),L("select");},className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[m.logoUrl?jsx("img",{src:m.logoUrl,alt:"",className:"h-10 w-10 flex-shrink-0"}):jsx("div",{className:"h-10 w-10 flex-shrink-0 bg-zinc-700 flex items-center justify-center text-zinc-400 text-sm font-mono",children:m.name?.[0]?.toUpperCase()||"S"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-white",children:m.name||m.stackId}),jsx("p",{className:"text-xs text-zinc-500",children:m.domain})]}),jsx("span",{className:"text-xs text-zinc-600",children:"Previously connected"})]},m.stackId)),o.ready&&!o.known&&jsx("p",{className:"text-center text-xs text-zinc-600 mt-4",children:"Connect to a stack for the first time to get started."})]}),x==="select"&&M&&jsx("div",{className:"flex items-center justify-center py-8",children:jsx("div",{className:"h-6 w-6 border-2 border-zinc-600 border-t-white animate-spin",style:{borderRadius:"50%"}})}),b&&x==="error"&&jsxs("div",{className:"mb-4 border border-red-500/30 bg-red-500/10 p-4",children:[jsx("p",{className:"text-center text-red-400 text-sm",children:b}),jsx("button",{className:"mt-3 w-full text-sm text-zinc-400 hover:text-white",onClick:fe,children:"Try Again"})]}),x==="success"&&jsxs("div",{className:"border border-green-500/30 bg-green-500/10 p-6 text-center",children:[jsx("p",{className:"font-medium text-green-400 text-sm",children:"Connected!"}),jsx("p",{className:"mt-1 text-xs text-zinc-400",children:"Redirecting..."})]}),x==="connecting"&&d&&jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 text-center",children:[jsxs("div",{className:"mx-auto mb-3 h-14 w-14 animate-pulse",children:[P==="phantom"&&jsx(X,{className:"h-14 w-14"}),P==="metamask"&&jsx(ee,{className:"h-14 w-14"})]}),jsx("p",{className:"font-medium text-sm text-white",children:p.connected?"Signing message...":"Connecting wallet..."}),jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Please confirm in your wallet"}),jsx("button",{className:"mt-4 text-sm text-zinc-500 hover:text-white",onClick:fe,children:"Cancel"})]}),x==="select"&&!d&&!M&&jsxs(Fragment,{children:[ue.includes("phantom")&&jsxs("button",{onClick:Pe,disabled:!O,className:`flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a] ${O?"":"cursor-not-allowed opacity-50"}`,children:[jsx(X,{className:"h-14 w-14 flex-shrink-0"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-lg text-white",children:"Phantom"}),!O&&jsx("p",{className:"text-xs text-zinc-500",children:"Not installed"})]}),jsx(le,{className:"h-8 w-8"})]}),ue.includes("metamask")&&ze&&jsxs("button",{onClick:De,className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center bg-white p-2",children:jsx(ee,{className:"h-10 w-10"})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white",children:"MetaMask"})}),jsx(de,{className:"h-8 w-8"})]}),pe&&!Z&&jsxs("button",{onClick:()=>V(true),className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center border border-zinc-700 bg-[#2a2a3e]",children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"28px",viewBox:"0 -960 960 960",width:"28px",fill:"#e3e3e3",children:jsx("path",{d:"M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v480q0 33-23.5 56.5T800-160H160Z"})})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white",children:"Access Code"})})]}),pe&&Z&&jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 space-y-4",children:[jsx("p",{className:"text-center text-sm text-zinc-400",children:"Enter your 6-digit access code"}),jsx(q,{onComplete:Te,disabled:k==="verifying",error:R}),k==="verifying"&&jsx("p",{className:"text-center text-sm text-zinc-400 animate-pulse",children:"Verifying..."}),k==="success"&&jsx("p",{className:"text-center text-sm text-green-400",children:"Verified!"}),N?.webPageUrl&&k==="idle"&&jsx("a",{href:`${N.webPageUrl}/connect/pair`,target:"_blank",rel:"noopener noreferrer",className:"block text-center text-sm text-zinc-500 hover:text-white transition-colors",children:"Get code"})]})]})]})}function rt({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"black"}),jsx("path",{d:"M8.53901 8L14.7164 16.2153L8.5 22.8947H9.89907L15.3415 17.0468L19.7389 22.8947H24.5L17.975 14.2173L23.7612 8H22.3621L17.3499 13.3858L13.3001 8H8.53901ZM10.5964 9.02501H12.7837L22.4422 21.8695H20.255L10.5964 9.02501Z",fill:"#F7F7F7"})]})}function it({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#F1F2F9"}),jsx("path",{d:"M26.1001 16.2273C26.1001 15.5182 26.0365 14.8364 25.9183 14.1818H16.5001V18.05H21.8819C21.6501 19.3 20.9456 20.3591 19.8865 21.0682V23.5773H23.1183C25.0092 21.8364 26.1001 19.2727 26.1001 16.2273Z",fill:"#4285F4"}),jsx("path",{d:"M16.5001 26C19.2001 26 21.4637 25.1046 23.1182 23.5773L19.8864 21.0682C18.991 21.6682 17.8455 22.0227 16.5001 22.0227C13.8955 22.0227 11.691 20.2637 10.9046 17.9H7.56372V20.4909C9.20917 23.7591 12.591 26 16.5001 26Z",fill:"#34A853"}),jsx("path",{d:"M10.9047 17.8999C10.7047 17.2999 10.591 16.659 10.591 15.9999C10.591 15.3408 10.7047 14.6999 10.9047 14.0999V11.509H7.56376C6.86376 12.9025 6.49951 14.4405 6.50012 15.9999C6.50012 17.6136 6.88649 19.1408 7.56376 20.4908L10.9047 17.8999Z",fill:"#FBBC05"}),jsx("path",{d:"M16.5001 9.97726C17.9682 9.97726 19.2864 10.4818 20.3228 11.4727L23.191 8.60454C21.4591 6.99091 19.1955 6 16.5001 6C12.591 6 9.20917 8.2409 7.56372 11.5091L10.9046 14.1C11.691 11.7364 13.8955 9.97726 16.5001 9.97726Z",fill:"#EA4335"})]})}function ct({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#5462EB"}),jsx("path",{d:"M23.5433 8.87438C22.2479 8.26174 20.8587 7.81038 19.4063 7.55187C19.3799 7.54688 19.3534 7.55934 19.3398 7.58428C19.1612 7.91179 18.9633 8.33905 18.8247 8.67487C17.2625 8.43382 15.7084 8.43382 14.1782 8.67487C14.0396 8.33158 13.8345 7.91179 13.6551 7.58428C13.6414 7.56018 13.615 7.54771 13.5886 7.55187C12.1369 7.80955 10.7478 8.26092 9.45159 8.87438C9.44037 8.87937 9.43075 8.88769 9.42437 8.89849C6.78947 12.9558 6.06766 16.9134 6.42176 20.8219C6.42336 20.841 6.43378 20.8593 6.4482 20.871C8.18663 22.1868 9.87059 22.9857 11.5233 23.5152C11.5497 23.5235 11.5778 23.5135 11.5946 23.491C11.9855 22.9408 12.334 22.3606 12.6328 21.7504C12.6505 21.7147 12.6336 21.6723 12.5976 21.6581C12.0448 21.442 11.5185 21.1785 11.0122 20.8793C10.9721 20.8552 10.9689 20.7961 11.0058 20.7679C11.1123 20.6856 11.2189 20.6 11.3206 20.5135C11.339 20.4977 11.3647 20.4944 11.3863 20.5044C14.7125 22.0696 18.3136 22.0696 21.6006 20.5044C21.6222 20.4936 21.6479 20.4969 21.6671 20.5127C21.7688 20.5991 21.8754 20.6856 21.9827 20.7679C22.0196 20.7961 22.0172 20.8552 21.9771 20.8793C21.4708 21.1843 20.9445 21.442 20.3909 21.6573C20.3548 21.6715 20.3388 21.7147 20.3564 21.7504C20.6617 22.3597 21.0101 22.9399 21.3939 23.4902C21.4099 23.5135 21.4387 23.5235 21.4652 23.5152C23.1259 22.9857 24.8099 22.1868 26.5483 20.871C26.5635 20.8593 26.5731 20.8419 26.5747 20.8228C26.9985 16.3041 25.8649 12.3789 23.5697 8.89931C23.5641 8.88769 23.5545 8.87937 23.5433 8.87438Z",fill:"#F7F7F7"})]})}function ut({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",className:e||"h-8 w-8",children:[jsx("rect",{width:"512",height:"512",rx:"15%",fill:"#37aee2"}),jsx("path",{fill:"#c8daea",d:"M199 404c-11 0-10-4-13-14l-32-105 245-144"}),jsx("path",{fill:"#a9c9dd",d:"M199 404c7 0 11-4 16-8l45-43-56-34"}),jsx("path",{fill:"#f6fbfe",d:"M204 319l135 99c14 9 26 4 30-14l55-258c5-22-9-32-24-25L79 245c-21 8-21 21-4 26l83 26 190-121c9-5 17-3 11 4"})]})}
2
2
  export{st as ConnectWidget,ct as DiscordIcon,de as EthereumIcon,it as GoogleIcon,ee as MetaMaskIcon,q as OTPInput,X as PhantomIcon,le as SolanaIcon,ut as TelegramIcon,rt as TwitterIcon,Re as UserUtilsProvider,We as useUserUtilsContext};
@@ -1,2 +1,2 @@
1
- 'use strict';var react=require('react');function Y(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith("stackauth_session="));if(!e)return null;let t=e.slice(18);return JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function P(e="__csrf"){if(typeof document>"u")return null;let t=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith(`${e}=`));return t?t.slice(e.length+1):null}function U(){let[e,t]=react.useState(null),[r,i]=react.useState(true),u=react.useCallback(()=>{let s=Y();s&&s.expiresAt>Date.now()?t({userId:s.userId,address:s.address,chain:s.chain,expiresAt:s.expiresAt,planId:s.planId,authMethod:s.authMethod}):t(null),i(false);},[]);react.useEffect(()=>{u();},[u]);let d=react.useCallback(async(s="")=>{try{let n=await fetch(`${s}/api/auth/session`);if(n.ok){let a=await n.json();if(a.session)return t(a.session),a.session}return t(null),null}catch{return null}},[]),p=!!e&&e.expiresAt>Date.now();return {session:e,loading:r,isAuthenticated:p,refresh:d,readSession:u}}function j(e="__csrf",t="x-csrf-token"){let[r,i]=react.useState(null);react.useEffect(()=>{i(P(e));},[e]);let u=r?{[t]:r}:{};return {token:r,headers:u}}function L(){let[e,t]=react.useState({connected:false,address:null,chain:null,provider:null}),[r,i]=react.useState(null),u=react.useCallback(async(n="phantom")=>{i(null);try{let a=typeof window<"u"?window:null,c=n==="phantom"?a?.phantom?.solana||a?.solana:a?.solflare;if(!c)return i(`${n} wallet not found`),null;let g=(await c.connect()).publicKey.toString();return t({connected:!0,address:g,chain:"solana",provider:n}),g}catch(a){return i(a.message||"Failed to connect wallet"),null}},[]),d=react.useCallback(async()=>{i(null);try{let a=(typeof window<"u"?window:null)?.ethereum;if(!a)return i("MetaMask not found"),null;let c=a;a.providers?.length&&(c=a.providers.find(o=>o.isMetaMask)||a);let g=(await c.request({method:"eth_requestAccounts"}))[0];return g?(t({connected:!0,address:g,chain:"ethereum",provider:"metamask"}),g):(i("No account selected"),null)}catch(n){return i(n.message||"Failed to connect wallet"),null}},[]),p=react.useCallback(async(n,a)=>{i(null);let c=a?.chain||e.chain,l=a?.provider||e.provider,g=a?.address||e.address;try{if(c==="solana"){let o=typeof window<"u"?window:null,f=l==="solflare"?o?.solflare:o?.phantom?.solana||o?.solana;if(!f)throw new Error("Wallet not available");let h=new TextEncoder().encode(n),y=await f.signMessage(h,"utf8"),R=y.signature||y,w="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",C=BigInt(0);for(let x of R)C=C*256n+BigInt(x);let k="";for(;C>0n;)k=w[Number(C%58n)]+k,C=C/58n;for(let x of R)if(x===0)k="1"+k;else break;return k}if(c==="ethereum"){let f=(typeof window<"u"?window:null)?.ethereum;if(f?.providers?.length&&(f=f.providers.find(y=>y.isMetaMask)||f),!f)throw new Error("MetaMask not available");return await f.request({method:"personal_sign",params:[n,g]})}throw new Error("No wallet connected")}catch(o){return i(o.message||"Signing failed"),null}},[e]),s=react.useCallback(()=>{t({connected:false,address:null,chain:null,provider:null}),i(null);},[]);return {wallet:e,error:r,connectSolana:u,connectEVM:d,signMessage:p,disconnect:s}}var pe="https://stacknet.magma-rpc.com/auth/bridge",N="stacknet-auth-bridge";function F(e){let t=e?.bridgeUrl||pe,r=e?.disabled||false,i=react.useRef(null),[u,d]=react.useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),p=react.useRef([]),s=react.useRef(false),n=react.useCallback(o=>{let f={...o,protocol:N};s.current&&i.current?.contentWindow?i.current.contentWindow.postMessage(f,new URL(t).origin):p.current.push(f);},[t]);react.useEffect(()=>{if(r)return;let o=h=>{if(!(!h.data||h.data.protocol!==N)){try{if(h.origin!==new URL(t).origin)return}catch{return}switch(h.data.type){case "bridge:ready":s.current=true,d(y=>({...y,ready:true}));for(let y of p.current)i.current?.contentWindow?.postMessage(y,h.origin);p.current=[],i.current?.contentWindow?.postMessage({protocol:N,type:"auth:check"},h.origin),i.current?.contentWindow?.postMessage({protocol:N,type:"auth:resolve-stack"},h.origin);break;case "auth:status":d(y=>({...y,known:h.data.known,identity:h.data.identity,identityCount:h.data.identityCount||0}));break;case "auth:resolved-stack":d(y=>({...y,resolvedStackId:h.data.stackId||null}));break;}}};window.addEventListener("message",o);let f=document.createElement("iframe");return f.src=t,f.style.display="none",f.setAttribute("aria-hidden","true"),f.setAttribute("tabindex","-1"),f.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(f),i.current=f,()=>{window.removeEventListener("message",o),f.parentNode&&f.parentNode.removeChild(f),i.current=null,s.current=false;}},[t,r]);let a=react.useCallback(o=>{n({type:"auth:connected",...o});},[n]),c=react.useCallback(o=>{n({type:"auth:disconnected",...o});},[n]),l=react.useCallback(()=>{n({type:"auth:clear"}),d({ready:u.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[n,u.ready]),g=react.useCallback(()=>{n({type:"auth:check"});},[n]);return {...u,reportConnected:a,reportDisconnected:c,clearAll:l,refresh:g}}async function ne(e,t,r,i){let u=e.apiVersion||"v2",d=`${e.baseUrl}/api/${u}${r}`;try{let p=await fetch(d,{method:t,headers:{"Content-Type":"application/json"},body:i?JSON.stringify(i):void 0}),s=await p.json();return p.ok?s.success&&s.data!==void 0?{success:!0,data:s.data}:{success:!0,data:s}:{success:!1,error:s.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(p){return {success:false,error:{code:"NETWORK_ERROR",message:p instanceof Error?p.message:"Network error"}}}}function se(e){return {getNetworkStatus:()=>ne(e,"GET","/network/status"),getWeb3Challenge:(t,r)=>ne(e,"POST",`/stacks/${e.stackId}/auth/web3/challenge`,{chain:t,address:r})}}function ge(e={apiBaseUrl:""}){let{wallet:t,connectSolana:r,connectEVM:i,signMessage:u,disconnect:d}=L(),{session:p,isAuthenticated:s,refresh:n,readSession:a}=U(),{headers:c}=j(),l=F({disabled:typeof window>"u"}),[g,o]=react.useState(false),[f,h]=react.useState(null),[y,R]=react.useState(false),w=e.apiBaseUrl||"",C=e.stacknetUrl||"https://stacknet.magma-rpc.com",k=e.stackId||l.resolvedStackId||"",x=se({baseUrl:C,stackId:k}),E=react.useCallback(async(m,b,$,G)=>{o(true),h(null);try{let S=b;if(!S){let I=await $();if(!I)return o(!1),!1;S=I;}let W=await x.getWeb3Challenge(m,S);if(!W.success||!W.data)return h("Failed to get challenge"),o(!1),!1;let z=await u(W.data.message,{chain:m,provider:G,address:S});if(!z)return o(!1),!1;let Q={chain:m,message:W.data.message,signature:z};m==="solana"&&(Q.publicKey=S);let X=await fetch(`${w}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)});if(!X.ok){let I=await X.json().catch(()=>({}));return h(I.error||"Authentication failed"),o(!1),!1}return l.reportConnected({address:S,chain:m,method:G||(m==="solana"?"phantom":"metamask"),stackId:k}),a(),o(!1),!0}catch(S){return h(S.message||"Authentication failed"),o(false),false}},[w,x,u,a,l,k]),M=react.useCallback(async(m="phantom")=>{let b=await r(m);return b?E("solana",b,()=>r(m),m):false},[r,E]),O=react.useCallback(async()=>{let m=await i();return m?E("ethereum",m,i,"metamask"):false},[i,E]),oe=react.useCallback(async m=>{o(true),h(null);try{let b=await fetch(`${w}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:m})});if(!b.ok){let $=await b.json().catch(()=>({}));return h($.error||"Invalid code"),o(!1),!1}return a(),o(!1),!0}catch(b){return h(b.message||"OTP verification failed"),o(false),false}},[w,a]),ie=react.useCallback(async()=>{t.address&&t.chain&&l.reportDisconnected({address:t.address,chain:t.chain,stackId:k});try{await fetch(`${w}/api/auth/logout`,{method:"POST",headers:c});}catch{}d(),a();},[w,c,d,a,t,l,k]);return react.useEffect(()=>{if(!e.autoConnect||y||s||!l.ready||!l.known||!l.identity)return;R(true);let{chain:m,method:b}=l.identity;m==="solana"&&(b==="phantom"||b==="solflare")?M(b):m==="ethereum"&&O();},[e.autoConnect,y,s,l,M,O]),{session:p,isAuthenticated:s,wallet:t,loading:g,error:f,authenticateSolana:M,authenticateEVM:O,authenticateOTP:oe,logout:ie,refresh:()=>n(w),stackId:k,bridge:{ready:l.ready,known:l.known,identity:l.identity,identityCount:l.identityCount,resolvedStackId:l.resolvedStackId}}}function be(e,t="https://stacknet.magma-rpc.com"){let[r,i]=react.useState(null),[u,d]=react.useState(false),[p,s]=react.useState(null),n=react.useCallback(async c=>{d(true),s(null);try{let l=await fetch(`${t}/api/v2/stacks/${c}`);if(!l.ok)return s("Stack not found"),d(!1),null;let g=await l.json(),o=g.data?.stack||g.stack||g,f={id:o.id,name:o.name,displayName:o.displayName||o.name,description:o.description,logoUrl:o.logoUrl,webPageUrl:o.webPageUrl,allowedChains:o.allowedChains||[],features:o.features,stripeProvider:o.stripeProvider,oauthProviders:o.oauthProviders?.map(h=>({provider:h.provider,enabled:h.enabled!==!1}))};return i(f),d(!1),f}catch(l){return s(l.message),d(false),null}},[t]);react.useEffect(()=>{e&&n(e);},[e,n]);let a=r?ke(r):[];return {config:r,loading:u,error:p,identityProviders:a,fetchConfig:n}}function ke(e){let t=[];if(e.features?.web3Auth!==false&&(e.allowedChains.includes("solana")&&(t.push({type:"wallet",id:"phantom",name:"Phantom",chain:"solana"}),t.push({type:"wallet",id:"solflare",name:"Solflare",chain:"solana"})),(e.allowedChains.includes("ethereum")||e.allowedChains.includes("polygon")||e.allowedChains.includes("base"))&&t.push({type:"wallet",id:"metamask",name:"MetaMask",chain:"ethereum"})),e.features?.apiKeyAuth!==false&&t.push({type:"otp",id:"otp",name:"Access Code"}),e.features?.oauthAuth&&e.oauthProviders)for(let r of e.oauthProviders)r.enabled&&t.push({type:"oauth",id:r.provider,name:r.provider});return t}function Se(e=""){let[t,r]=react.useState([]),[i,u]=react.useState(true),[d,p]=react.useState(null),s=react.useCallback(async()=>{try{let n=await fetch(`${e}/api/billing/plans`);if(n.ok){let a=await n.json();r(a.plans||a||[]);}}catch(n){p(n.message);}finally{u(false);}},[e]);return react.useEffect(()=>{s();},[s]),{plans:t,loading:i,error:d,refresh:s}}function xe(e=""){let[t,r]=react.useState(null),[i,u]=react.useState(true),[d,p]=react.useState(null),s=react.useCallback(async()=>{try{let c=await fetch(`${e}/api/billing/subscription`);if(c.ok){let l=await c.json();r(l.plan?l:null);}}catch(c){p(c.message);}finally{u(false);}},[e]);react.useEffect(()=>{s();},[s]);let n=react.useCallback(async c=>{let l=P(),o=await(await fetch(`${e}/api/billing/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",...l?{"x-csrf-token":l}:{}},body:JSON.stringify({planId:c})})).json();return o.url||o.checkoutUrl||null},[e]),a=react.useCallback(async()=>{let c=P();return (await fetch(`${e}/api/billing/cancel`,{method:"POST",headers:c?{"x-csrf-token":c}:{}})).ok?(await s(),true):false},[e,s]);return {subscription:t,loading:i,error:d,refresh:s,subscribe:n,cancel:a}}function Re(e=""){let[t,r]=react.useState(null),[i,u]=react.useState(true),[d,p]=react.useState(null),s=react.useCallback(async()=>{try{let n=await fetch(`${e}/api/billing/usage`);if(n.ok){let a=await n.json();r(a);}}catch(n){p(n.message);}finally{u(false);}},[e]);return react.useEffect(()=>{s();},[s]),{usage:t,loading:i,error:d,refresh:s}}function Ee(e=""){let[t,r]=react.useState(false),[i,u]=react.useState(null),d=react.useCallback(async s=>{r(true),u(null);try{let n=P(),a=await fetch(`${e}/api/billing/prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...n?{"x-csrf-token":n}:{}},body:JSON.stringify({amountCents:s})}),c=await a.json();return a.ok?c.url||null:(u(c.error||"Purchase failed"),null)}catch(n){return u(n.message),null}finally{r(false);}},[e]),p=react.useCallback(async s=>{r(true),u(null);try{let n=P(),a=await fetch(`${e}/api/billing/verify-prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...n?{"x-csrf-token":n}:{}},body:JSON.stringify({sessionId:s})}),c=await a.json();return a.ok?c:(u(c.error||"Verification failed"),null)}catch(n){return u(n.message),null}finally{r(false);}},[e]);return {purchase:d,verifySession:p,loading:t,error:i}}function Te(e="",t){let[r,i]=react.useState([]),[u,d]=react.useState(true),[p,s]=react.useState(null),n=t?.limit||50,a=t?.offset||0,c=react.useCallback(async()=>{try{let l=await fetch(`${e}/api/billing/history?limit=${n}&offset=${a}`);if(l.ok){let g=await l.json();i(g.records||g.history||(Array.isArray(g)?g:[]));}}catch(l){s(l.message);}finally{d(false);}},[e,n,a]);return react.useEffect(()=>{c();},[c]),{records:r,loading:u,error:p,refresh:c}}
1
+ 'use strict';var react=require('react');function Y(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith("stackauth_session="));if(!e)return null;let t=e.slice(18);return JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function P(e="__csrf"){if(typeof document>"u")return null;let t=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith(`${e}=`));return t?t.slice(e.length+1):null}function U(){let[e,t]=react.useState(null),[r,i]=react.useState(true),u=react.useCallback(()=>{let s=Y();s&&s.expiresAt>Date.now()?t({userId:s.userId,address:s.address,chain:s.chain,expiresAt:s.expiresAt,planId:s.planId,authMethod:s.authMethod}):t(null),i(false);},[]);react.useEffect(()=>{u();},[u]);let d=react.useCallback(async(s="")=>{try{let n=await fetch(`${s}/api/auth/session`);if(n.ok){let a=await n.json();if(a.session)return t(a.session),a.session}return t(null),null}catch{return null}},[]),p=!!e&&e.expiresAt>Date.now();return {session:e,loading:r,isAuthenticated:p,refresh:d,readSession:u}}function j(e="__csrf",t="x-csrf-token"){let[r,i]=react.useState(null);react.useEffect(()=>{i(P(e));},[e]);let u=r?{[t]:r}:{};return {token:r,headers:u}}function L(){let[e,t]=react.useState({connected:false,address:null,chain:null,provider:null}),[r,i]=react.useState(null),u=react.useCallback(async(n="phantom")=>{i(null);try{let a=typeof window<"u"?window:null,c=n==="phantom"?a?.phantom?.solana||a?.solana:a?.solflare;if(!c)return i(`${n} wallet not found`),null;let g=(await c.connect()).publicKey.toString();return t({connected:!0,address:g,chain:"solana",provider:n}),g}catch(a){return i(a.message||"Failed to connect wallet"),null}},[]),d=react.useCallback(async()=>{i(null);try{let a=(typeof window<"u"?window:null)?.ethereum;if(!a)return i("MetaMask not found"),null;let c=a;a.providers?.length&&(c=a.providers.find(o=>o.isMetaMask)||a);let g=(await c.request({method:"eth_requestAccounts"}))[0];return g?(t({connected:!0,address:g,chain:"ethereum",provider:"metamask"}),g):(i("No account selected"),null)}catch(n){return i(n.message||"Failed to connect wallet"),null}},[]),p=react.useCallback(async(n,a)=>{i(null);let c=a?.chain||e.chain,l=a?.provider||e.provider,g=a?.address||e.address;try{if(c==="solana"){let o=typeof window<"u"?window:null,f=l==="solflare"?o?.solflare:o?.phantom?.solana||o?.solana;if(!f)throw new Error("Wallet not available");let h=new TextEncoder().encode(n),y=await f.signMessage(h,"utf8"),R=y.signature||y,w="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",C=BigInt(0);for(let x of R)C=C*256n+BigInt(x);let b="";for(;C>0n;)b=w[Number(C%58n)]+b,C=C/58n;for(let x of R)if(x===0)b="1"+b;else break;return b}if(c==="ethereum"){let f=(typeof window<"u"?window:null)?.ethereum;if(f?.providers?.length&&(f=f.providers.find(y=>y.isMetaMask)||f),!f)throw new Error("MetaMask not available");return await f.request({method:"personal_sign",params:[n,g]})}throw new Error("No wallet connected")}catch(o){return i(o.message||"Signing failed"),null}},[e]),s=react.useCallback(()=>{t({connected:false,address:null,chain:null,provider:null}),i(null);},[]);return {wallet:e,error:r,connectSolana:u,connectEVM:d,signMessage:p,disconnect:s}}var pe="https://stacknet.magma-rpc.com/auth/bridge",N="stacknet-auth-bridge";function F(e){let t=e?.bridgeUrl||pe,r=e?.disabled||false,i=react.useRef(null),[u,d]=react.useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),p=react.useRef([]),s=react.useRef(false),n=react.useCallback(o=>{let f={...o,protocol:N};s.current&&i.current?.contentWindow?i.current.contentWindow.postMessage(f,new URL(t).origin):p.current.push(f);},[t]);react.useEffect(()=>{if(r)return;let o=h=>{if(!(!h.data||h.data.protocol!==N)){try{if(h.origin!==new URL(t).origin)return}catch{return}switch(h.data.type){case "bridge:ready":s.current=true,d(y=>({...y,ready:true}));for(let y of p.current)i.current?.contentWindow?.postMessage(y,h.origin);p.current=[],i.current?.contentWindow?.postMessage({protocol:N,type:"auth:check"},h.origin),i.current?.contentWindow?.postMessage({protocol:N,type:"auth:resolve-stack"},h.origin);break;case "auth:status":d(y=>({...y,known:h.data.known,identity:h.data.identity,identityCount:h.data.identityCount||0}));break;case "auth:resolved-stack":d(y=>({...y,resolvedStackId:h.data.stackId||null}));break;}}};window.addEventListener("message",o);let f=document.createElement("iframe");return f.src=t,f.style.display="none",f.setAttribute("aria-hidden","true"),f.setAttribute("tabindex","-1"),f.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(f),i.current=f,()=>{window.removeEventListener("message",o),f.parentNode&&f.parentNode.removeChild(f),i.current=null,s.current=false;}},[t,r]);let a=react.useCallback(o=>{n({type:"auth:connected",...o});},[n]),c=react.useCallback(o=>{n({type:"auth:disconnected",...o});},[n]),l=react.useCallback(()=>{n({type:"auth:clear"}),d({ready:u.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[n,u.ready]),g=react.useCallback(()=>{n({type:"auth:check"});},[n]);return {...u,reportConnected:a,reportDisconnected:c,clearAll:l,refresh:g}}async function ne(e,t,r,i){let u=e.apiVersion||"v2",d=`${e.baseUrl}/api/${u}${r}`;try{let p=await fetch(d,{method:t,headers:{"Content-Type":"application/json"},body:i?JSON.stringify(i):void 0}),s=await p.json();return p.ok?s.success&&s.data!==void 0?{success:!0,data:s.data}:{success:!0,data:s}:{success:!1,error:s.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(p){return {success:false,error:{code:"NETWORK_ERROR",message:p instanceof Error?p.message:"Network error"}}}}function se(e){return {getNetworkStatus:()=>ne(e,"GET","/network/status"),getWeb3Challenge:(t,r)=>ne(e,"POST",`/stacks/${e.stackId}/auth/web3/challenge`,{chain:t,address:r})}}function ge(e={apiBaseUrl:""}){let{wallet:t,connectSolana:r,connectEVM:i,signMessage:u,disconnect:d}=L(),{session:p,isAuthenticated:s,refresh:n,readSession:a}=U(),{headers:c}=j(),l=F({disabled:typeof window>"u"}),[g,o]=react.useState(false),[f,h]=react.useState(null),[y,R]=react.useState(false),w=e.apiBaseUrl||"",C=e.stacknetUrl||"https://stacknet.magma-rpc.com",b=e.stackId||l.resolvedStackId||"",x=se({baseUrl:C,stackId:b}),E=react.useCallback(async(m,k,$,G)=>{o(true),h(null);try{let S=k;if(!S){let W=await $();if(!W)return o(!1),!1;S=W;}let I=await x.getWeb3Challenge(m,S);if(!I.success||!I.data)return h("Failed to get challenge"),o(!1),!1;let z=await u(I.data.message,{chain:m,provider:G,address:S});if(!z)return o(!1),!1;let Q={chain:m,message:I.data.message,signature:z,stackId:b};m==="solana"&&(Q.publicKey=S);let X=await fetch(`${w}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)});if(!X.ok){let W=await X.json().catch(()=>({}));return h(W.error||"Authentication failed"),o(!1),!1}return l.reportConnected({address:S,chain:m,method:G||(m==="solana"?"phantom":"metamask"),stackId:b}),a(),o(!1),!0}catch(S){return h(S.message||"Authentication failed"),o(false),false}},[w,x,u,a,l,b]),M=react.useCallback(async(m="phantom")=>{let k=await r(m);return k?E("solana",k,()=>r(m),m):false},[r,E]),O=react.useCallback(async()=>{let m=await i();return m?E("ethereum",m,i,"metamask"):false},[i,E]),oe=react.useCallback(async m=>{o(true),h(null);try{let k=await fetch(`${w}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:m})});if(!k.ok){let $=await k.json().catch(()=>({}));return h($.error||"Invalid code"),o(!1),!1}return a(),o(!1),!0}catch(k){return h(k.message||"OTP verification failed"),o(false),false}},[w,a]),ie=react.useCallback(async()=>{t.address&&t.chain&&l.reportDisconnected({address:t.address,chain:t.chain,stackId:b});try{await fetch(`${w}/api/auth/logout`,{method:"POST",headers:c});}catch{}d(),a();},[w,c,d,a,t,l,b]);return react.useEffect(()=>{if(!e.autoConnect||y||s||!l.ready||!l.known||!l.identity)return;R(true);let{chain:m,method:k}=l.identity;m==="solana"&&(k==="phantom"||k==="solflare")?M(k):m==="ethereum"&&O();},[e.autoConnect,y,s,l,M,O]),{session:p,isAuthenticated:s,wallet:t,loading:g,error:f,authenticateSolana:M,authenticateEVM:O,authenticateOTP:oe,logout:ie,refresh:()=>n(w),stackId:b,bridge:{ready:l.ready,known:l.known,identity:l.identity,identityCount:l.identityCount,resolvedStackId:l.resolvedStackId}}}function be(e,t="https://stacknet.magma-rpc.com"){let[r,i]=react.useState(null),[u,d]=react.useState(false),[p,s]=react.useState(null),n=react.useCallback(async c=>{d(true),s(null);try{let l=await fetch(`${t}/api/v2/stacks/${c}`);if(!l.ok)return s("Stack not found"),d(!1),null;let g=await l.json(),o=g.data?.stack||g.stack||g,f={id:o.id,name:o.name,displayName:o.displayName||o.name,description:o.description,logoUrl:o.logoUrl,webPageUrl:o.webPageUrl,allowedChains:o.allowedChains||[],features:o.features,stripeProvider:o.stripeProvider,oauthProviders:o.oauthProviders?.map(h=>({provider:h.provider,enabled:h.enabled!==!1}))};return i(f),d(!1),f}catch(l){return s(l.message),d(false),null}},[t]);react.useEffect(()=>{e&&n(e);},[e,n]);let a=r?ke(r):[];return {config:r,loading:u,error:p,identityProviders:a,fetchConfig:n}}function ke(e){let t=[];if(e.features?.web3Auth!==false&&(e.allowedChains.includes("solana")&&(t.push({type:"wallet",id:"phantom",name:"Phantom",chain:"solana"}),t.push({type:"wallet",id:"solflare",name:"Solflare",chain:"solana"})),(e.allowedChains.includes("ethereum")||e.allowedChains.includes("polygon")||e.allowedChains.includes("base"))&&t.push({type:"wallet",id:"metamask",name:"MetaMask",chain:"ethereum"})),e.features?.apiKeyAuth!==false&&t.push({type:"otp",id:"otp",name:"Access Code"}),e.features?.oauthAuth&&e.oauthProviders)for(let r of e.oauthProviders)r.enabled&&t.push({type:"oauth",id:r.provider,name:r.provider});return t}function Se(e=""){let[t,r]=react.useState([]),[i,u]=react.useState(true),[d,p]=react.useState(null),s=react.useCallback(async()=>{try{let n=await fetch(`${e}/api/billing/plans`);if(n.ok){let a=await n.json();r(a.plans||a||[]);}}catch(n){p(n.message);}finally{u(false);}},[e]);return react.useEffect(()=>{s();},[s]),{plans:t,loading:i,error:d,refresh:s}}function xe(e=""){let[t,r]=react.useState(null),[i,u]=react.useState(true),[d,p]=react.useState(null),s=react.useCallback(async()=>{try{let c=await fetch(`${e}/api/billing/subscription`);if(c.ok){let l=await c.json();r(l.plan?l:null);}}catch(c){p(c.message);}finally{u(false);}},[e]);react.useEffect(()=>{s();},[s]);let n=react.useCallback(async c=>{let l=P(),o=await(await fetch(`${e}/api/billing/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",...l?{"x-csrf-token":l}:{}},body:JSON.stringify({planId:c})})).json();return o.url||o.checkoutUrl||null},[e]),a=react.useCallback(async()=>{let c=P();return (await fetch(`${e}/api/billing/cancel`,{method:"POST",headers:c?{"x-csrf-token":c}:{}})).ok?(await s(),true):false},[e,s]);return {subscription:t,loading:i,error:d,refresh:s,subscribe:n,cancel:a}}function Re(e=""){let[t,r]=react.useState(null),[i,u]=react.useState(true),[d,p]=react.useState(null),s=react.useCallback(async()=>{try{let n=await fetch(`${e}/api/billing/usage`);if(n.ok){let a=await n.json();r(a);}}catch(n){p(n.message);}finally{u(false);}},[e]);return react.useEffect(()=>{s();},[s]),{usage:t,loading:i,error:d,refresh:s}}function Ee(e=""){let[t,r]=react.useState(false),[i,u]=react.useState(null),d=react.useCallback(async s=>{r(true),u(null);try{let n=P(),a=await fetch(`${e}/api/billing/prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...n?{"x-csrf-token":n}:{}},body:JSON.stringify({amountCents:s})}),c=await a.json();return a.ok?c.url||null:(u(c.error||"Purchase failed"),null)}catch(n){return u(n.message),null}finally{r(false);}},[e]),p=react.useCallback(async s=>{r(true),u(null);try{let n=P(),a=await fetch(`${e}/api/billing/verify-prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...n?{"x-csrf-token":n}:{}},body:JSON.stringify({sessionId:s})}),c=await a.json();return a.ok?c:(u(c.error||"Verification failed"),null)}catch(n){return u(n.message),null}finally{r(false);}},[e]);return {purchase:d,verifySession:p,loading:t,error:i}}function Te(e="",t){let[r,i]=react.useState([]),[u,d]=react.useState(true),[p,s]=react.useState(null),n=t?.limit||50,a=t?.offset||0,c=react.useCallback(async()=>{try{let l=await fetch(`${e}/api/billing/history?limit=${n}&offset=${a}`);if(l.ok){let g=await l.json();i(g.records||g.history||(Array.isArray(g)?g:[]));}}catch(l){s(l.message);}finally{d(false);}},[e,n,a]);return react.useEffect(()=>{c();},[c]),{records:r,loading:u,error:p,refresh:c}}
2
2
  exports.useAuthBridge=F;exports.useBillingHistory=Te;exports.useCSRFToken=j;exports.usePlans=Se;exports.usePrepaidCheckout=Ee;exports.useSession=U;exports.useStackAuth=ge;exports.useStackConfig=be;exports.useSubscription=xe;exports.useUsage=Re;exports.useWeb3Wallet=L;
@@ -1,2 +1,2 @@
1
- import {useState,useCallback,useEffect,useRef}from'react';function Y(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith("stackauth_session="));if(!e)return null;let t=e.slice(18);return JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function P(e="__csrf"){if(typeof document>"u")return null;let t=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith(`${e}=`));return t?t.slice(e.length+1):null}function U(){let[e,t]=useState(null),[r,i]=useState(true),u=useCallback(()=>{let s=Y();s&&s.expiresAt>Date.now()?t({userId:s.userId,address:s.address,chain:s.chain,expiresAt:s.expiresAt,planId:s.planId,authMethod:s.authMethod}):t(null),i(false);},[]);useEffect(()=>{u();},[u]);let d=useCallback(async(s="")=>{try{let n=await fetch(`${s}/api/auth/session`);if(n.ok){let a=await n.json();if(a.session)return t(a.session),a.session}return t(null),null}catch{return null}},[]),p=!!e&&e.expiresAt>Date.now();return {session:e,loading:r,isAuthenticated:p,refresh:d,readSession:u}}function j(e="__csrf",t="x-csrf-token"){let[r,i]=useState(null);useEffect(()=>{i(P(e));},[e]);let u=r?{[t]:r}:{};return {token:r,headers:u}}function L(){let[e,t]=useState({connected:false,address:null,chain:null,provider:null}),[r,i]=useState(null),u=useCallback(async(n="phantom")=>{i(null);try{let a=typeof window<"u"?window:null,c=n==="phantom"?a?.phantom?.solana||a?.solana:a?.solflare;if(!c)return i(`${n} wallet not found`),null;let g=(await c.connect()).publicKey.toString();return t({connected:!0,address:g,chain:"solana",provider:n}),g}catch(a){return i(a.message||"Failed to connect wallet"),null}},[]),d=useCallback(async()=>{i(null);try{let a=(typeof window<"u"?window:null)?.ethereum;if(!a)return i("MetaMask not found"),null;let c=a;a.providers?.length&&(c=a.providers.find(o=>o.isMetaMask)||a);let g=(await c.request({method:"eth_requestAccounts"}))[0];return g?(t({connected:!0,address:g,chain:"ethereum",provider:"metamask"}),g):(i("No account selected"),null)}catch(n){return i(n.message||"Failed to connect wallet"),null}},[]),p=useCallback(async(n,a)=>{i(null);let c=a?.chain||e.chain,l=a?.provider||e.provider,g=a?.address||e.address;try{if(c==="solana"){let o=typeof window<"u"?window:null,f=l==="solflare"?o?.solflare:o?.phantom?.solana||o?.solana;if(!f)throw new Error("Wallet not available");let h=new TextEncoder().encode(n),y=await f.signMessage(h,"utf8"),R=y.signature||y,w="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",C=BigInt(0);for(let x of R)C=C*256n+BigInt(x);let k="";for(;C>0n;)k=w[Number(C%58n)]+k,C=C/58n;for(let x of R)if(x===0)k="1"+k;else break;return k}if(c==="ethereum"){let f=(typeof window<"u"?window:null)?.ethereum;if(f?.providers?.length&&(f=f.providers.find(y=>y.isMetaMask)||f),!f)throw new Error("MetaMask not available");return await f.request({method:"personal_sign",params:[n,g]})}throw new Error("No wallet connected")}catch(o){return i(o.message||"Signing failed"),null}},[e]),s=useCallback(()=>{t({connected:false,address:null,chain:null,provider:null}),i(null);},[]);return {wallet:e,error:r,connectSolana:u,connectEVM:d,signMessage:p,disconnect:s}}var pe="https://stacknet.magma-rpc.com/auth/bridge",N="stacknet-auth-bridge";function F(e){let t=e?.bridgeUrl||pe,r=e?.disabled||false,i=useRef(null),[u,d]=useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),p=useRef([]),s=useRef(false),n=useCallback(o=>{let f={...o,protocol:N};s.current&&i.current?.contentWindow?i.current.contentWindow.postMessage(f,new URL(t).origin):p.current.push(f);},[t]);useEffect(()=>{if(r)return;let o=h=>{if(!(!h.data||h.data.protocol!==N)){try{if(h.origin!==new URL(t).origin)return}catch{return}switch(h.data.type){case "bridge:ready":s.current=true,d(y=>({...y,ready:true}));for(let y of p.current)i.current?.contentWindow?.postMessage(y,h.origin);p.current=[],i.current?.contentWindow?.postMessage({protocol:N,type:"auth:check"},h.origin),i.current?.contentWindow?.postMessage({protocol:N,type:"auth:resolve-stack"},h.origin);break;case "auth:status":d(y=>({...y,known:h.data.known,identity:h.data.identity,identityCount:h.data.identityCount||0}));break;case "auth:resolved-stack":d(y=>({...y,resolvedStackId:h.data.stackId||null}));break;}}};window.addEventListener("message",o);let f=document.createElement("iframe");return f.src=t,f.style.display="none",f.setAttribute("aria-hidden","true"),f.setAttribute("tabindex","-1"),f.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(f),i.current=f,()=>{window.removeEventListener("message",o),f.parentNode&&f.parentNode.removeChild(f),i.current=null,s.current=false;}},[t,r]);let a=useCallback(o=>{n({type:"auth:connected",...o});},[n]),c=useCallback(o=>{n({type:"auth:disconnected",...o});},[n]),l=useCallback(()=>{n({type:"auth:clear"}),d({ready:u.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[n,u.ready]),g=useCallback(()=>{n({type:"auth:check"});},[n]);return {...u,reportConnected:a,reportDisconnected:c,clearAll:l,refresh:g}}async function ne(e,t,r,i){let u=e.apiVersion||"v2",d=`${e.baseUrl}/api/${u}${r}`;try{let p=await fetch(d,{method:t,headers:{"Content-Type":"application/json"},body:i?JSON.stringify(i):void 0}),s=await p.json();return p.ok?s.success&&s.data!==void 0?{success:!0,data:s.data}:{success:!0,data:s}:{success:!1,error:s.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(p){return {success:false,error:{code:"NETWORK_ERROR",message:p instanceof Error?p.message:"Network error"}}}}function se(e){return {getNetworkStatus:()=>ne(e,"GET","/network/status"),getWeb3Challenge:(t,r)=>ne(e,"POST",`/stacks/${e.stackId}/auth/web3/challenge`,{chain:t,address:r})}}function ge(e={apiBaseUrl:""}){let{wallet:t,connectSolana:r,connectEVM:i,signMessage:u,disconnect:d}=L(),{session:p,isAuthenticated:s,refresh:n,readSession:a}=U(),{headers:c}=j(),l=F({disabled:typeof window>"u"}),[g,o]=useState(false),[f,h]=useState(null),[y,R]=useState(false),w=e.apiBaseUrl||"",C=e.stacknetUrl||"https://stacknet.magma-rpc.com",k=e.stackId||l.resolvedStackId||"",x=se({baseUrl:C,stackId:k}),E=useCallback(async(m,b,$,G)=>{o(true),h(null);try{let S=b;if(!S){let I=await $();if(!I)return o(!1),!1;S=I;}let W=await x.getWeb3Challenge(m,S);if(!W.success||!W.data)return h("Failed to get challenge"),o(!1),!1;let z=await u(W.data.message,{chain:m,provider:G,address:S});if(!z)return o(!1),!1;let Q={chain:m,message:W.data.message,signature:z};m==="solana"&&(Q.publicKey=S);let X=await fetch(`${w}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)});if(!X.ok){let I=await X.json().catch(()=>({}));return h(I.error||"Authentication failed"),o(!1),!1}return l.reportConnected({address:S,chain:m,method:G||(m==="solana"?"phantom":"metamask"),stackId:k}),a(),o(!1),!0}catch(S){return h(S.message||"Authentication failed"),o(false),false}},[w,x,u,a,l,k]),M=useCallback(async(m="phantom")=>{let b=await r(m);return b?E("solana",b,()=>r(m),m):false},[r,E]),O=useCallback(async()=>{let m=await i();return m?E("ethereum",m,i,"metamask"):false},[i,E]),oe=useCallback(async m=>{o(true),h(null);try{let b=await fetch(`${w}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:m})});if(!b.ok){let $=await b.json().catch(()=>({}));return h($.error||"Invalid code"),o(!1),!1}return a(),o(!1),!0}catch(b){return h(b.message||"OTP verification failed"),o(false),false}},[w,a]),ie=useCallback(async()=>{t.address&&t.chain&&l.reportDisconnected({address:t.address,chain:t.chain,stackId:k});try{await fetch(`${w}/api/auth/logout`,{method:"POST",headers:c});}catch{}d(),a();},[w,c,d,a,t,l,k]);return useEffect(()=>{if(!e.autoConnect||y||s||!l.ready||!l.known||!l.identity)return;R(true);let{chain:m,method:b}=l.identity;m==="solana"&&(b==="phantom"||b==="solflare")?M(b):m==="ethereum"&&O();},[e.autoConnect,y,s,l,M,O]),{session:p,isAuthenticated:s,wallet:t,loading:g,error:f,authenticateSolana:M,authenticateEVM:O,authenticateOTP:oe,logout:ie,refresh:()=>n(w),stackId:k,bridge:{ready:l.ready,known:l.known,identity:l.identity,identityCount:l.identityCount,resolvedStackId:l.resolvedStackId}}}function be(e,t="https://stacknet.magma-rpc.com"){let[r,i]=useState(null),[u,d]=useState(false),[p,s]=useState(null),n=useCallback(async c=>{d(true),s(null);try{let l=await fetch(`${t}/api/v2/stacks/${c}`);if(!l.ok)return s("Stack not found"),d(!1),null;let g=await l.json(),o=g.data?.stack||g.stack||g,f={id:o.id,name:o.name,displayName:o.displayName||o.name,description:o.description,logoUrl:o.logoUrl,webPageUrl:o.webPageUrl,allowedChains:o.allowedChains||[],features:o.features,stripeProvider:o.stripeProvider,oauthProviders:o.oauthProviders?.map(h=>({provider:h.provider,enabled:h.enabled!==!1}))};return i(f),d(!1),f}catch(l){return s(l.message),d(false),null}},[t]);useEffect(()=>{e&&n(e);},[e,n]);let a=r?ke(r):[];return {config:r,loading:u,error:p,identityProviders:a,fetchConfig:n}}function ke(e){let t=[];if(e.features?.web3Auth!==false&&(e.allowedChains.includes("solana")&&(t.push({type:"wallet",id:"phantom",name:"Phantom",chain:"solana"}),t.push({type:"wallet",id:"solflare",name:"Solflare",chain:"solana"})),(e.allowedChains.includes("ethereum")||e.allowedChains.includes("polygon")||e.allowedChains.includes("base"))&&t.push({type:"wallet",id:"metamask",name:"MetaMask",chain:"ethereum"})),e.features?.apiKeyAuth!==false&&t.push({type:"otp",id:"otp",name:"Access Code"}),e.features?.oauthAuth&&e.oauthProviders)for(let r of e.oauthProviders)r.enabled&&t.push({type:"oauth",id:r.provider,name:r.provider});return t}function Se(e=""){let[t,r]=useState([]),[i,u]=useState(true),[d,p]=useState(null),s=useCallback(async()=>{try{let n=await fetch(`${e}/api/billing/plans`);if(n.ok){let a=await n.json();r(a.plans||a||[]);}}catch(n){p(n.message);}finally{u(false);}},[e]);return useEffect(()=>{s();},[s]),{plans:t,loading:i,error:d,refresh:s}}function xe(e=""){let[t,r]=useState(null),[i,u]=useState(true),[d,p]=useState(null),s=useCallback(async()=>{try{let c=await fetch(`${e}/api/billing/subscription`);if(c.ok){let l=await c.json();r(l.plan?l:null);}}catch(c){p(c.message);}finally{u(false);}},[e]);useEffect(()=>{s();},[s]);let n=useCallback(async c=>{let l=P(),o=await(await fetch(`${e}/api/billing/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",...l?{"x-csrf-token":l}:{}},body:JSON.stringify({planId:c})})).json();return o.url||o.checkoutUrl||null},[e]),a=useCallback(async()=>{let c=P();return (await fetch(`${e}/api/billing/cancel`,{method:"POST",headers:c?{"x-csrf-token":c}:{}})).ok?(await s(),true):false},[e,s]);return {subscription:t,loading:i,error:d,refresh:s,subscribe:n,cancel:a}}function Re(e=""){let[t,r]=useState(null),[i,u]=useState(true),[d,p]=useState(null),s=useCallback(async()=>{try{let n=await fetch(`${e}/api/billing/usage`);if(n.ok){let a=await n.json();r(a);}}catch(n){p(n.message);}finally{u(false);}},[e]);return useEffect(()=>{s();},[s]),{usage:t,loading:i,error:d,refresh:s}}function Ee(e=""){let[t,r]=useState(false),[i,u]=useState(null),d=useCallback(async s=>{r(true),u(null);try{let n=P(),a=await fetch(`${e}/api/billing/prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...n?{"x-csrf-token":n}:{}},body:JSON.stringify({amountCents:s})}),c=await a.json();return a.ok?c.url||null:(u(c.error||"Purchase failed"),null)}catch(n){return u(n.message),null}finally{r(false);}},[e]),p=useCallback(async s=>{r(true),u(null);try{let n=P(),a=await fetch(`${e}/api/billing/verify-prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...n?{"x-csrf-token":n}:{}},body:JSON.stringify({sessionId:s})}),c=await a.json();return a.ok?c:(u(c.error||"Verification failed"),null)}catch(n){return u(n.message),null}finally{r(false);}},[e]);return {purchase:d,verifySession:p,loading:t,error:i}}function Te(e="",t){let[r,i]=useState([]),[u,d]=useState(true),[p,s]=useState(null),n=t?.limit||50,a=t?.offset||0,c=useCallback(async()=>{try{let l=await fetch(`${e}/api/billing/history?limit=${n}&offset=${a}`);if(l.ok){let g=await l.json();i(g.records||g.history||(Array.isArray(g)?g:[]));}}catch(l){s(l.message);}finally{d(false);}},[e,n,a]);return useEffect(()=>{c();},[c]),{records:r,loading:u,error:p,refresh:c}}
1
+ import {useState,useCallback,useEffect,useRef}from'react';function Y(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith("stackauth_session="));if(!e)return null;let t=e.slice(18);return JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function P(e="__csrf"){if(typeof document>"u")return null;let t=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith(`${e}=`));return t?t.slice(e.length+1):null}function U(){let[e,t]=useState(null),[r,i]=useState(true),u=useCallback(()=>{let s=Y();s&&s.expiresAt>Date.now()?t({userId:s.userId,address:s.address,chain:s.chain,expiresAt:s.expiresAt,planId:s.planId,authMethod:s.authMethod}):t(null),i(false);},[]);useEffect(()=>{u();},[u]);let d=useCallback(async(s="")=>{try{let n=await fetch(`${s}/api/auth/session`);if(n.ok){let a=await n.json();if(a.session)return t(a.session),a.session}return t(null),null}catch{return null}},[]),p=!!e&&e.expiresAt>Date.now();return {session:e,loading:r,isAuthenticated:p,refresh:d,readSession:u}}function j(e="__csrf",t="x-csrf-token"){let[r,i]=useState(null);useEffect(()=>{i(P(e));},[e]);let u=r?{[t]:r}:{};return {token:r,headers:u}}function L(){let[e,t]=useState({connected:false,address:null,chain:null,provider:null}),[r,i]=useState(null),u=useCallback(async(n="phantom")=>{i(null);try{let a=typeof window<"u"?window:null,c=n==="phantom"?a?.phantom?.solana||a?.solana:a?.solflare;if(!c)return i(`${n} wallet not found`),null;let g=(await c.connect()).publicKey.toString();return t({connected:!0,address:g,chain:"solana",provider:n}),g}catch(a){return i(a.message||"Failed to connect wallet"),null}},[]),d=useCallback(async()=>{i(null);try{let a=(typeof window<"u"?window:null)?.ethereum;if(!a)return i("MetaMask not found"),null;let c=a;a.providers?.length&&(c=a.providers.find(o=>o.isMetaMask)||a);let g=(await c.request({method:"eth_requestAccounts"}))[0];return g?(t({connected:!0,address:g,chain:"ethereum",provider:"metamask"}),g):(i("No account selected"),null)}catch(n){return i(n.message||"Failed to connect wallet"),null}},[]),p=useCallback(async(n,a)=>{i(null);let c=a?.chain||e.chain,l=a?.provider||e.provider,g=a?.address||e.address;try{if(c==="solana"){let o=typeof window<"u"?window:null,f=l==="solflare"?o?.solflare:o?.phantom?.solana||o?.solana;if(!f)throw new Error("Wallet not available");let h=new TextEncoder().encode(n),y=await f.signMessage(h,"utf8"),R=y.signature||y,w="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",C=BigInt(0);for(let x of R)C=C*256n+BigInt(x);let b="";for(;C>0n;)b=w[Number(C%58n)]+b,C=C/58n;for(let x of R)if(x===0)b="1"+b;else break;return b}if(c==="ethereum"){let f=(typeof window<"u"?window:null)?.ethereum;if(f?.providers?.length&&(f=f.providers.find(y=>y.isMetaMask)||f),!f)throw new Error("MetaMask not available");return await f.request({method:"personal_sign",params:[n,g]})}throw new Error("No wallet connected")}catch(o){return i(o.message||"Signing failed"),null}},[e]),s=useCallback(()=>{t({connected:false,address:null,chain:null,provider:null}),i(null);},[]);return {wallet:e,error:r,connectSolana:u,connectEVM:d,signMessage:p,disconnect:s}}var pe="https://stacknet.magma-rpc.com/auth/bridge",N="stacknet-auth-bridge";function F(e){let t=e?.bridgeUrl||pe,r=e?.disabled||false,i=useRef(null),[u,d]=useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),p=useRef([]),s=useRef(false),n=useCallback(o=>{let f={...o,protocol:N};s.current&&i.current?.contentWindow?i.current.contentWindow.postMessage(f,new URL(t).origin):p.current.push(f);},[t]);useEffect(()=>{if(r)return;let o=h=>{if(!(!h.data||h.data.protocol!==N)){try{if(h.origin!==new URL(t).origin)return}catch{return}switch(h.data.type){case "bridge:ready":s.current=true,d(y=>({...y,ready:true}));for(let y of p.current)i.current?.contentWindow?.postMessage(y,h.origin);p.current=[],i.current?.contentWindow?.postMessage({protocol:N,type:"auth:check"},h.origin),i.current?.contentWindow?.postMessage({protocol:N,type:"auth:resolve-stack"},h.origin);break;case "auth:status":d(y=>({...y,known:h.data.known,identity:h.data.identity,identityCount:h.data.identityCount||0}));break;case "auth:resolved-stack":d(y=>({...y,resolvedStackId:h.data.stackId||null}));break;}}};window.addEventListener("message",o);let f=document.createElement("iframe");return f.src=t,f.style.display="none",f.setAttribute("aria-hidden","true"),f.setAttribute("tabindex","-1"),f.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(f),i.current=f,()=>{window.removeEventListener("message",o),f.parentNode&&f.parentNode.removeChild(f),i.current=null,s.current=false;}},[t,r]);let a=useCallback(o=>{n({type:"auth:connected",...o});},[n]),c=useCallback(o=>{n({type:"auth:disconnected",...o});},[n]),l=useCallback(()=>{n({type:"auth:clear"}),d({ready:u.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[n,u.ready]),g=useCallback(()=>{n({type:"auth:check"});},[n]);return {...u,reportConnected:a,reportDisconnected:c,clearAll:l,refresh:g}}async function ne(e,t,r,i){let u=e.apiVersion||"v2",d=`${e.baseUrl}/api/${u}${r}`;try{let p=await fetch(d,{method:t,headers:{"Content-Type":"application/json"},body:i?JSON.stringify(i):void 0}),s=await p.json();return p.ok?s.success&&s.data!==void 0?{success:!0,data:s.data}:{success:!0,data:s}:{success:!1,error:s.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(p){return {success:false,error:{code:"NETWORK_ERROR",message:p instanceof Error?p.message:"Network error"}}}}function se(e){return {getNetworkStatus:()=>ne(e,"GET","/network/status"),getWeb3Challenge:(t,r)=>ne(e,"POST",`/stacks/${e.stackId}/auth/web3/challenge`,{chain:t,address:r})}}function ge(e={apiBaseUrl:""}){let{wallet:t,connectSolana:r,connectEVM:i,signMessage:u,disconnect:d}=L(),{session:p,isAuthenticated:s,refresh:n,readSession:a}=U(),{headers:c}=j(),l=F({disabled:typeof window>"u"}),[g,o]=useState(false),[f,h]=useState(null),[y,R]=useState(false),w=e.apiBaseUrl||"",C=e.stacknetUrl||"https://stacknet.magma-rpc.com",b=e.stackId||l.resolvedStackId||"",x=se({baseUrl:C,stackId:b}),E=useCallback(async(m,k,$,G)=>{o(true),h(null);try{let S=k;if(!S){let W=await $();if(!W)return o(!1),!1;S=W;}let I=await x.getWeb3Challenge(m,S);if(!I.success||!I.data)return h("Failed to get challenge"),o(!1),!1;let z=await u(I.data.message,{chain:m,provider:G,address:S});if(!z)return o(!1),!1;let Q={chain:m,message:I.data.message,signature:z,stackId:b};m==="solana"&&(Q.publicKey=S);let X=await fetch(`${w}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)});if(!X.ok){let W=await X.json().catch(()=>({}));return h(W.error||"Authentication failed"),o(!1),!1}return l.reportConnected({address:S,chain:m,method:G||(m==="solana"?"phantom":"metamask"),stackId:b}),a(),o(!1),!0}catch(S){return h(S.message||"Authentication failed"),o(false),false}},[w,x,u,a,l,b]),M=useCallback(async(m="phantom")=>{let k=await r(m);return k?E("solana",k,()=>r(m),m):false},[r,E]),O=useCallback(async()=>{let m=await i();return m?E("ethereum",m,i,"metamask"):false},[i,E]),oe=useCallback(async m=>{o(true),h(null);try{let k=await fetch(`${w}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:m})});if(!k.ok){let $=await k.json().catch(()=>({}));return h($.error||"Invalid code"),o(!1),!1}return a(),o(!1),!0}catch(k){return h(k.message||"OTP verification failed"),o(false),false}},[w,a]),ie=useCallback(async()=>{t.address&&t.chain&&l.reportDisconnected({address:t.address,chain:t.chain,stackId:b});try{await fetch(`${w}/api/auth/logout`,{method:"POST",headers:c});}catch{}d(),a();},[w,c,d,a,t,l,b]);return useEffect(()=>{if(!e.autoConnect||y||s||!l.ready||!l.known||!l.identity)return;R(true);let{chain:m,method:k}=l.identity;m==="solana"&&(k==="phantom"||k==="solflare")?M(k):m==="ethereum"&&O();},[e.autoConnect,y,s,l,M,O]),{session:p,isAuthenticated:s,wallet:t,loading:g,error:f,authenticateSolana:M,authenticateEVM:O,authenticateOTP:oe,logout:ie,refresh:()=>n(w),stackId:b,bridge:{ready:l.ready,known:l.known,identity:l.identity,identityCount:l.identityCount,resolvedStackId:l.resolvedStackId}}}function be(e,t="https://stacknet.magma-rpc.com"){let[r,i]=useState(null),[u,d]=useState(false),[p,s]=useState(null),n=useCallback(async c=>{d(true),s(null);try{let l=await fetch(`${t}/api/v2/stacks/${c}`);if(!l.ok)return s("Stack not found"),d(!1),null;let g=await l.json(),o=g.data?.stack||g.stack||g,f={id:o.id,name:o.name,displayName:o.displayName||o.name,description:o.description,logoUrl:o.logoUrl,webPageUrl:o.webPageUrl,allowedChains:o.allowedChains||[],features:o.features,stripeProvider:o.stripeProvider,oauthProviders:o.oauthProviders?.map(h=>({provider:h.provider,enabled:h.enabled!==!1}))};return i(f),d(!1),f}catch(l){return s(l.message),d(false),null}},[t]);useEffect(()=>{e&&n(e);},[e,n]);let a=r?ke(r):[];return {config:r,loading:u,error:p,identityProviders:a,fetchConfig:n}}function ke(e){let t=[];if(e.features?.web3Auth!==false&&(e.allowedChains.includes("solana")&&(t.push({type:"wallet",id:"phantom",name:"Phantom",chain:"solana"}),t.push({type:"wallet",id:"solflare",name:"Solflare",chain:"solana"})),(e.allowedChains.includes("ethereum")||e.allowedChains.includes("polygon")||e.allowedChains.includes("base"))&&t.push({type:"wallet",id:"metamask",name:"MetaMask",chain:"ethereum"})),e.features?.apiKeyAuth!==false&&t.push({type:"otp",id:"otp",name:"Access Code"}),e.features?.oauthAuth&&e.oauthProviders)for(let r of e.oauthProviders)r.enabled&&t.push({type:"oauth",id:r.provider,name:r.provider});return t}function Se(e=""){let[t,r]=useState([]),[i,u]=useState(true),[d,p]=useState(null),s=useCallback(async()=>{try{let n=await fetch(`${e}/api/billing/plans`);if(n.ok){let a=await n.json();r(a.plans||a||[]);}}catch(n){p(n.message);}finally{u(false);}},[e]);return useEffect(()=>{s();},[s]),{plans:t,loading:i,error:d,refresh:s}}function xe(e=""){let[t,r]=useState(null),[i,u]=useState(true),[d,p]=useState(null),s=useCallback(async()=>{try{let c=await fetch(`${e}/api/billing/subscription`);if(c.ok){let l=await c.json();r(l.plan?l:null);}}catch(c){p(c.message);}finally{u(false);}},[e]);useEffect(()=>{s();},[s]);let n=useCallback(async c=>{let l=P(),o=await(await fetch(`${e}/api/billing/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",...l?{"x-csrf-token":l}:{}},body:JSON.stringify({planId:c})})).json();return o.url||o.checkoutUrl||null},[e]),a=useCallback(async()=>{let c=P();return (await fetch(`${e}/api/billing/cancel`,{method:"POST",headers:c?{"x-csrf-token":c}:{}})).ok?(await s(),true):false},[e,s]);return {subscription:t,loading:i,error:d,refresh:s,subscribe:n,cancel:a}}function Re(e=""){let[t,r]=useState(null),[i,u]=useState(true),[d,p]=useState(null),s=useCallback(async()=>{try{let n=await fetch(`${e}/api/billing/usage`);if(n.ok){let a=await n.json();r(a);}}catch(n){p(n.message);}finally{u(false);}},[e]);return useEffect(()=>{s();},[s]),{usage:t,loading:i,error:d,refresh:s}}function Ee(e=""){let[t,r]=useState(false),[i,u]=useState(null),d=useCallback(async s=>{r(true),u(null);try{let n=P(),a=await fetch(`${e}/api/billing/prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...n?{"x-csrf-token":n}:{}},body:JSON.stringify({amountCents:s})}),c=await a.json();return a.ok?c.url||null:(u(c.error||"Purchase failed"),null)}catch(n){return u(n.message),null}finally{r(false);}},[e]),p=useCallback(async s=>{r(true),u(null);try{let n=P(),a=await fetch(`${e}/api/billing/verify-prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...n?{"x-csrf-token":n}:{}},body:JSON.stringify({sessionId:s})}),c=await a.json();return a.ok?c:(u(c.error||"Verification failed"),null)}catch(n){return u(n.message),null}finally{r(false);}},[e]);return {purchase:d,verifySession:p,loading:t,error:i}}function Te(e="",t){let[r,i]=useState([]),[u,d]=useState(true),[p,s]=useState(null),n=t?.limit||50,a=t?.offset||0,c=useCallback(async()=>{try{let l=await fetch(`${e}/api/billing/history?limit=${n}&offset=${a}`);if(l.ok){let g=await l.json();i(g.records||g.history||(Array.isArray(g)?g:[]));}}catch(l){s(l.message);}finally{d(false);}},[e,n,a]);return useEffect(()=>{c();},[c]),{records:r,loading:u,error:p,refresh:c}}
2
2
  export{F as useAuthBridge,Te as useBillingHistory,j as useCSRFToken,Se as usePlans,Ee as usePrepaidCheckout,U as useSession,ge as useStackAuth,be as useStackConfig,xe as useSubscription,Re as useUsage,L as useWeb3Wallet};
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var clsx=require('clsx'),tailwindMerge=require('tailwind-merge'),react=require('react'),jsxRuntime=require('react/jsx-runtime');function Qe(...e){return tailwindMerge.twMerge(clsx.clsx(e))}function Ve(e){return e>=1e12?`${(e/1e12).toFixed(e%1e12===0?0:1)}T`:e>=1e9?`${(e/1e9).toFixed(e%1e9===0?0:1)}B`:e>=1e6?`${(e/1e6).toFixed(e%1e6===0?0:1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:e.toLocaleString()}function Ye(e,t){if(!e)return "/";if(e.startsWith("/")&&!e.startsWith("//"))return e;try{let s=new URL(e,t);return s.origin!==t?"/":s.pathname+s.search+s.hash}catch{return "/"}}function Ge(e){try{let t=e.split(".");if(t.length!==3)return null;let s=atob(t[1].replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(s)}catch{return null}}function oe(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(s=>s.trim()).find(s=>s.startsWith("stackauth_session="));if(!e)return null;let t=e.slice(18);return JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function j(e="__csrf"){if(typeof document>"u")return null;let t=document.cookie.split(";").map(s=>s.trim()).find(s=>s.startsWith(`${e}=`));return t?t.slice(e.length+1):null}function re(){let[e,t]=react.useState(null),[s,l]=react.useState(true),f=react.useCallback(()=>{let o=oe();o&&o.expiresAt>Date.now()?t({userId:o.userId,address:o.address,chain:o.chain,expiresAt:o.expiresAt,planId:o.planId,authMethod:o.authMethod}):t(null),l(false);},[]);react.useEffect(()=>{f();},[f]);let h=react.useCallback(async(o="")=>{try{let r=await fetch(`${o}/api/auth/session`);if(r.ok){let i=await r.json();if(i.session)return t(i.session),i.session}return t(null),null}catch{return null}},[]),m=!!e&&e.expiresAt>Date.now();return {session:e,loading:s,isAuthenticated:m,refresh:h,readSession:f}}function ae(e="__csrf",t="x-csrf-token"){let[s,l]=react.useState(null);react.useEffect(()=>{l(j(e));},[e]);let f=s?{[t]:s}:{};return {token:s,headers:f}}function ie(){let[e,t]=react.useState({connected:false,address:null,chain:null,provider:null}),[s,l]=react.useState(null),f=react.useCallback(async(r="phantom")=>{l(null);try{let i=typeof window<"u"?window:null,p=r==="phantom"?i?.phantom?.solana||i?.solana:i?.solflare;if(!p)return l(`${r} wallet not found`),null;let d=(await p.connect()).publicKey.toString();return t({connected:!0,address:d,chain:"solana",provider:r}),d}catch(i){return l(i.message||"Failed to connect wallet"),null}},[]),h=react.useCallback(async()=>{l(null);try{let i=(typeof window<"u"?window:null)?.ethereum;if(!i)return l("MetaMask not found"),null;let p=i;i.providers?.length&&(p=i.providers.find(n=>n.isMetaMask)||i);let d=(await p.request({method:"eth_requestAccounts"}))[0];return d?(t({connected:!0,address:d,chain:"ethereum",provider:"metamask"}),d):(l("No account selected"),null)}catch(r){return l(r.message||"Failed to connect wallet"),null}},[]),m=react.useCallback(async(r,i)=>{l(null);let p=i?.chain||e.chain,a=i?.provider||e.provider,d=i?.address||e.address;try{if(p==="solana"){let n=typeof window<"u"?window:null,c=a==="solflare"?n?.solflare:n?.phantom?.solana||n?.solana;if(!c)throw new Error("Wallet not available");let g=new TextEncoder().encode(r),b=await c.signMessage(g,"utf8"),L=b.signature||b,x="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",v=BigInt(0);for(let N of L)v=v*256n+BigInt(N);let M="";for(;v>0n;)M=x[Number(v%58n)]+M,v=v/58n;for(let N of L)if(N===0)M="1"+M;else break;return M}if(p==="ethereum"){let c=(typeof window<"u"?window:null)?.ethereum;if(c?.providers?.length&&(c=c.providers.find(b=>b.isMetaMask)||c),!c)throw new Error("MetaMask not available");return await c.request({method:"personal_sign",params:[r,d]})}throw new Error("No wallet connected")}catch(n){return l(n.message||"Signing failed"),null}},[e]),o=react.useCallback(()=>{t({connected:false,address:null,chain:null,provider:null}),l(null);},[]);return {wallet:e,error:s,connectSolana:f,connectEVM:h,signMessage:m,disconnect:o}}var et="https://stacknet.magma-rpc.com/auth/bridge",q="stacknet-auth-bridge";function ce(e){let t=e?.bridgeUrl||et,s=e?.disabled||false,l=react.useRef(null),[f,h]=react.useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),m=react.useRef([]),o=react.useRef(false),r=react.useCallback(n=>{let c={...n,protocol:q};o.current&&l.current?.contentWindow?l.current.contentWindow.postMessage(c,new URL(t).origin):m.current.push(c);},[t]);react.useEffect(()=>{if(s)return;let n=g=>{if(!(!g.data||g.data.protocol!==q)){try{if(g.origin!==new URL(t).origin)return}catch{return}switch(g.data.type){case "bridge:ready":o.current=true,h(b=>({...b,ready:true}));for(let b of m.current)l.current?.contentWindow?.postMessage(b,g.origin);m.current=[],l.current?.contentWindow?.postMessage({protocol:q,type:"auth:check"},g.origin),l.current?.contentWindow?.postMessage({protocol:q,type:"auth:resolve-stack"},g.origin);break;case "auth:status":h(b=>({...b,known:g.data.known,identity:g.data.identity,identityCount:g.data.identityCount||0}));break;case "auth:resolved-stack":h(b=>({...b,resolvedStackId:g.data.stackId||null}));break;}}};window.addEventListener("message",n);let c=document.createElement("iframe");return c.src=t,c.style.display="none",c.setAttribute("aria-hidden","true"),c.setAttribute("tabindex","-1"),c.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(c),l.current=c,()=>{window.removeEventListener("message",n),c.parentNode&&c.parentNode.removeChild(c),l.current=null,o.current=false;}},[t,s]);let i=react.useCallback(n=>{r({type:"auth:connected",...n});},[r]),p=react.useCallback(n=>{r({type:"auth:disconnected",...n});},[r]),a=react.useCallback(()=>{r({type:"auth:clear"}),h({ready:f.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[r,f.ready]),d=react.useCallback(()=>{r({type:"auth:check"});},[r]);return {...f,reportConnected:i,reportDisconnected:p,clearAll:a,refresh:d}}async function Ue(e,t,s,l){let f=e.apiVersion||"v2",h=`${e.baseUrl}/api/${f}${s}`;try{let m=await fetch(h,{method:t,headers:{"Content-Type":"application/json"},body:l?JSON.stringify(l):void 0}),o=await m.json();return m.ok?o.success&&o.data!==void 0?{success:!0,data:o.data}:{success:!0,data:o}:{success:!1,error:o.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(m){return {success:false,error:{code:"NETWORK_ERROR",message:m instanceof Error?m.message:"Network error"}}}}function de(e){return {getNetworkStatus:()=>Ue(e,"GET","/network/status"),getWeb3Challenge:(t,s)=>Ue(e,"POST",`/stacks/${e.stackId}/auth/web3/challenge`,{chain:t,address:s})}}function pe(e={apiBaseUrl:""}){let{wallet:t,connectSolana:s,connectEVM:l,signMessage:f,disconnect:h}=ie(),{session:m,isAuthenticated:o,refresh:r,readSession:i}=re(),{headers:p}=ae(),a=ce({disabled:typeof window>"u"}),[d,n]=react.useState(false),[c,g]=react.useState(null),[b,L]=react.useState(false),x=e.apiBaseUrl||"",v=e.stacknetUrl||"https://stacknet.magma-rpc.com",M=e.stackId||a.resolvedStackId||"",N=de({baseUrl:v,stackId:M}),I=react.useCallback(async(w,C,_,D)=>{n(true),g(null);try{let P=C;if(!P){let R=await _();if(!R)return n(!1),!1;P=R;}let O=await N.getWeb3Challenge(w,P);if(!O.success||!O.data)return g("Failed to get challenge"),n(!1),!1;let J=await f(O.data.message,{chain:w,provider:D,address:P});if(!J)return n(!1),!1;let $={chain:w,message:O.data.message,signature:J};w==="solana"&&($.publicKey=P);let E=await fetch(`${x}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)});if(!E.ok){let R=await E.json().catch(()=>({}));return g(R.error||"Authentication failed"),n(!1),!1}return a.reportConnected({address:P,chain:w,method:D||(w==="solana"?"phantom":"metamask"),stackId:M}),i(),n(!1),!0}catch(P){return g(P.message||"Authentication failed"),n(false),false}},[x,N,f,i,a,M]),T=react.useCallback(async(w="phantom")=>{let C=await s(w);return C?I("solana",C,()=>s(w),w):false},[s,I]),A=react.useCallback(async()=>{let w=await l();return w?I("ethereum",w,l,"metamask"):false},[l,I]),G=react.useCallback(async w=>{n(true),g(null);try{let C=await fetch(`${x}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:w})});if(!C.ok){let _=await C.json().catch(()=>({}));return g(_.error||"Invalid code"),n(!1),!1}return i(),n(!1),!0}catch(C){return g(C.message||"OTP verification failed"),n(false),false}},[x,i]),Z=react.useCallback(async()=>{t.address&&t.chain&&a.reportDisconnected({address:t.address,chain:t.chain,stackId:M});try{await fetch(`${x}/api/auth/logout`,{method:"POST",headers:p});}catch{}h(),i();},[x,p,h,i,t,a,M]);return react.useEffect(()=>{if(!e.autoConnect||b||o||!a.ready||!a.known||!a.identity)return;L(true);let{chain:w,method:C}=a.identity;w==="solana"&&(C==="phantom"||C==="solflare")?T(C):w==="ethereum"&&A();},[e.autoConnect,b,o,a,T,A]),{session:m,isAuthenticated:o,wallet:t,loading:d,error:c,authenticateSolana:T,authenticateEVM:A,authenticateOTP:G,logout:Z,refresh:()=>r(x),stackId:M,bridge:{ready:a.ready,known:a.known,identity:a.identity,identityCount:a.identityCount,resolvedStackId:a.resolvedStackId}}}function me(e,t="https://stacknet.magma-rpc.com"){let[s,l]=react.useState(null),[f,h]=react.useState(false),[m,o]=react.useState(null),r=react.useCallback(async p=>{h(true),o(null);try{let a=await fetch(`${t}/api/v2/stacks/${p}`);if(!a.ok)return o("Stack not found"),h(!1),null;let d=await a.json(),n=d.data?.stack||d.stack||d,c={id:n.id,name:n.name,displayName:n.displayName||n.name,description:n.description,logoUrl:n.logoUrl,webPageUrl:n.webPageUrl,allowedChains:n.allowedChains||[],features:n.features,stripeProvider:n.stripeProvider,oauthProviders:n.oauthProviders?.map(g=>({provider:g.provider,enabled:g.enabled!==!1}))};return l(c),h(!1),c}catch(a){return o(a.message),h(false),null}},[t]);react.useEffect(()=>{e&&r(e);},[e,r]);let i=s?ot(s):[];return {config:s,loading:f,error:m,identityProviders:i,fetchConfig:r}}function ot(e){let t=[];if(e.features?.web3Auth!==false&&(e.allowedChains.includes("solana")&&(t.push({type:"wallet",id:"phantom",name:"Phantom",chain:"solana"}),t.push({type:"wallet",id:"solflare",name:"Solflare",chain:"solana"})),(e.allowedChains.includes("ethereum")||e.allowedChains.includes("polygon")||e.allowedChains.includes("base"))&&t.push({type:"wallet",id:"metamask",name:"MetaMask",chain:"ethereum"})),e.features?.apiKeyAuth!==false&&t.push({type:"otp",id:"otp",name:"Access Code"}),e.features?.oauthAuth&&e.oauthProviders)for(let s of e.oauthProviders)s.enabled&&t.push({type:"oauth",id:s.provider,name:s.provider});return t}function it(e=""){let[t,s]=react.useState([]),[l,f]=react.useState(true),[h,m]=react.useState(null),o=react.useCallback(async()=>{try{let r=await fetch(`${e}/api/billing/plans`);if(r.ok){let i=await r.json();s(i.plans||i||[]);}}catch(r){m(r.message);}finally{f(false);}},[e]);return react.useEffect(()=>{o();},[o]),{plans:t,loading:l,error:h,refresh:o}}function ct(e=""){let[t,s]=react.useState(null),[l,f]=react.useState(true),[h,m]=react.useState(null),o=react.useCallback(async()=>{try{let p=await fetch(`${e}/api/billing/subscription`);if(p.ok){let a=await p.json();s(a.plan?a:null);}}catch(p){m(p.message);}finally{f(false);}},[e]);react.useEffect(()=>{o();},[o]);let r=react.useCallback(async p=>{let a=j(),n=await(await fetch(`${e}/api/billing/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-csrf-token":a}:{}},body:JSON.stringify({planId:p})})).json();return n.url||n.checkoutUrl||null},[e]),i=react.useCallback(async()=>{let p=j();return (await fetch(`${e}/api/billing/cancel`,{method:"POST",headers:p?{"x-csrf-token":p}:{}})).ok?(await o(),true):false},[e,o]);return {subscription:t,loading:l,error:h,refresh:o,subscribe:r,cancel:i}}function pt(e=""){let[t,s]=react.useState(null),[l,f]=react.useState(true),[h,m]=react.useState(null),o=react.useCallback(async()=>{try{let r=await fetch(`${e}/api/billing/usage`);if(r.ok){let i=await r.json();s(i);}}catch(r){m(r.message);}finally{f(false);}},[e]);return react.useEffect(()=>{o();},[o]),{usage:t,loading:l,error:h,refresh:o}}function ft(e=""){let[t,s]=react.useState(false),[l,f]=react.useState(null),h=react.useCallback(async o=>{s(true),f(null);try{let r=j(),i=await fetch(`${e}/api/billing/prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...r?{"x-csrf-token":r}:{}},body:JSON.stringify({amountCents:o})}),p=await i.json();return i.ok?p.url||null:(f(p.error||"Purchase failed"),null)}catch(r){return f(r.message),null}finally{s(false);}},[e]),m=react.useCallback(async o=>{s(true),f(null);try{let r=j(),i=await fetch(`${e}/api/billing/verify-prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...r?{"x-csrf-token":r}:{}},body:JSON.stringify({sessionId:o})}),p=await i.json();return i.ok?p:(f(p.error||"Verification failed"),null)}catch(r){return f(r.message),null}finally{s(false);}},[e]);return {purchase:h,verifySession:m,loading:t,error:l}}function ht(e="",t){let[s,l]=react.useState([]),[f,h]=react.useState(true),[m,o]=react.useState(null),r=t?.limit||50,i=t?.offset||0,p=react.useCallback(async()=>{try{let a=await fetch(`${e}/api/billing/history?limit=${r}&offset=${i}`);if(a.ok){let d=await a.json();l(d.records||d.history||(Array.isArray(d)?d:[]));}}catch(a){o(a.message);}finally{h(false);}},[e,r,i]);return react.useEffect(()=>{p();},[p]),{records:s,loading:f,error:m,refresh:p}}var Te=react.createContext(null);function wt(){let e=react.useContext(Te);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function bt({config:e,callbacks:t,children:s}){return jsxRuntime.jsx(Te.Provider,{value:{config:e,callbacks:t},children:s})}function X({length:e=6,onComplete:t,disabled:s=false,error:l,className:f="",inputClassName:h=""}){let [m,o]=react.useState(Array(e).fill("")),r=react.useCallback((a,d)=>{if(d.length>1){let c=d.replace(/\D/g,"").slice(0,e).split(""),g=[...m];c.forEach((L,x)=>{a+x<e&&(g[a+x]=L);}),o(g);let b=Math.min(a+c.length,e-1);document.getElementById(`userutils-otp-${b}`)?.focus(),g.every(L=>L!=="")&&setTimeout(()=>t(g.join("")),100);return}if(!/^\d?$/.test(d))return;let n=[...m];n[a]=d,o(n),d&&a<e-1&&document.getElementById(`userutils-otp-${a+1}`)?.focus(),d&&a===e-1&&n.every(c=>c!=="")&&setTimeout(()=>t(n.join("")),100);},[m,e,t]),i=react.useCallback((a,d)=>{if(d.key==="Backspace"&&!m[a]&&a>0){document.getElementById(`userutils-otp-${a-1}`)?.focus();let n=[...m];n[a-1]="",o(n);}if(d.key==="Enter"){let n=m.join("");n.length===e&&t(n);}},[m,e,t]);react.useCallback(()=>{o(Array(e).fill("")),document.getElementById("userutils-otp-0")?.focus();},[e]);return jsxRuntime.jsxs("div",{className:f,children:[jsxRuntime.jsx("div",{className:"flex gap-2 justify-center",children:m.map((a,d)=>jsxRuntime.jsx("input",{id:`userutils-otp-${d}`,type:"text",inputMode:"numeric",maxLength:e,value:a,onChange:n=>r(d,n.target.value),onKeyDown:n=>i(d,n),disabled:s,autoFocus:d===0,className:`w-12 h-14 text-center text-xl font-mono bg-secondary border border-primary/10 text-foreground focus:outline-none focus:border-primary/30 disabled:opacity-50 ${h}`},d))}),l&&jsxRuntime.jsx("p",{className:"text-center text-sm text-red-400 mt-2",children:l})]})}X.displayName="OTPInput";var Mt="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function ee({className:e}){return jsxRuntime.jsx("img",{src:Mt,alt:"Phantom",className:e})}function te({className:e}){return jsxRuntime.jsxs("svg",{className:e,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 507.83 470.86",children:[jsxRuntime.jsx("polygon",{fill:"#e2761b",stroke:"#e2761b",strokeLinecap:"round",strokeLinejoin:"round",points:"482.09 0.5 284.32 147.38 320.9 60.72 482.09 0.5"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"25.54 0.5 221.72 148.77 186.93 60.72 25.54 0.5"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"410.93 340.97 358.26 421.67 470.96 452.67 503.36 342.76 410.93 340.97"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"4.67 342.76 36.87 452.67 149.57 421.67 96.9 340.97 4.67 342.76"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 111.8 252.13 223.7 257.1 219.73 136.85 143.21 204.62"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"364.42 204.62 286.91 135.46 284.32 257.1 396.03 252.13 364.42 204.62"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 216.75 388.87 158.71 343.55 149.57 421.67"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 358.26 421.67 348.92 343.55 290.88 388.87"}),jsxRuntime.jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"358.26 421.67 290.88 388.87 296.25 432.8 295.65 451.28 358.26 421.67"}),jsxRuntime.jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 212.18 451.28 211.78 432.8 216.75 388.87 149.57 421.67"}),jsxRuntime.jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"213.17 314.54 157.12 298.04 196.67 279.95 213.17 314.54"}),jsxRuntime.jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"294.46 314.54 310.96 279.95 350.71 298.04 294.46 314.54"}),jsxRuntime.jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 159.11 340.97 96.9 342.76 149.57 421.67"}),jsxRuntime.jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"348.72 340.97 358.26 421.67 410.93 342.76 348.72 340.97"}),jsxRuntime.jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"396.03 252.13 284.32 257.1 294.66 314.54 311.16 279.95 350.91 298.04 396.03 252.13"}),jsxRuntime.jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 196.87 279.95 213.17 314.54 223.7 257.1 111.8 252.13 157.12 298.04"}),jsxRuntime.jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"111.8 252.13 158.71 343.55 157.12 298.04 111.8 252.13"}),jsxRuntime.jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"350.91 298.04 348.92 343.55 396.03 252.13 350.91 298.04"}),jsxRuntime.jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"223.7 257.1 213.17 314.54 226.29 382.31 229.27 293.07 223.7 257.1"}),jsxRuntime.jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 278.96 292.87 281.34 382.31 294.66 314.54 284.32 257.1"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"294.66 314.54 281.34 382.31 290.88 388.87 348.92 343.55 350.91 298.04 294.66 314.54"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 158.71 343.55 216.75 388.87 226.29 382.31 213.17 314.54 157.12 298.04"}),jsxRuntime.jsx("polygon",{fill:"#c0ad9e",stroke:"#c0ad9e",strokeLinecap:"round",strokeLinejoin:"round",points:"295.65 451.28 296.25 432.8 291.28 428.42 216.35 428.42 211.78 432.8 212.18 451.28 149.57 421.67 171.43 439.55 215.75 470.36 291.88 470.36 336.4 439.55 358.26 421.67 295.65 451.28"}),jsxRuntime.jsx("polygon",{fill:"#161616",stroke:"#161616",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 281.34 382.31 226.29 382.31 216.75 388.87 211.78 432.8 216.35 428.42 291.28 428.42 296.25 432.8 290.88 388.87"}),jsxRuntime.jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"490.44 156.92 507.33 75.83 482.09 0.5 290.88 142.41 364.42 204.62 468.37 235.03 491.43 208.2 481.49 201.05 497.39 186.54 485.07 177 500.97 164.87 490.44 156.92"}),jsxRuntime.jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"0.5 75.83 17.39 156.92 6.66 164.87 22.56 177 10.44 186.54 26.34 201.05 16.4 208.2 39.26 235.03 143.21 204.62 216.75 142.41 25.54 0.5 0.5 75.83"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"468.37 235.03 364.42 204.62 396.03 252.13 348.92 343.55 410.93 342.76 503.36 342.76 468.37 235.03"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 39.26 235.03 4.67 342.76 96.9 342.76 158.71 343.55 111.8 252.13 143.21 204.62"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 290.88 142.41 321.1 60.72 186.93 60.72 216.75 142.41 223.7 257.1 226.09 293.27 226.29 382.31 281.34 382.31 281.74 293.27 284.32 257.1"})]})}function Ne({className:e}){return jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",className:e||"h-5 w-5",children:[jsxRuntime.jsxs("linearGradient",{id:"sol-g",x1:"7.233",x2:"24.766",y1:"24.766",y2:"7.234",gradientUnits:"userSpaceOnUse",children:[jsxRuntime.jsx("stop",{offset:"0",stopColor:"#9945ff"}),jsxRuntime.jsx("stop",{offset:"0.2",stopColor:"#7962e7"}),jsxRuntime.jsx("stop",{offset:"1",stopColor:"#00d18c"})]}),jsxRuntime.jsx("path",{fill:"#10111a",d:"M0 0h32v32H0z"}),jsxRuntime.jsx("path",{fill:"url(#sol-g)",fillRule:"evenodd",d:"M9.873 20.41a.65.65 0 0 1 .476-.21l14.662.012a.323.323 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54zm15.376-2.862a.322.322 0 0 1-.238.54l-14.662.012a.64.64 0 0 1-.476-.21l-3.122-3.44a.323.323 0 0 1 .238-.54l14.662-.012a.64.64 0 0 1 .475.21zM9.873 7.81a.64.64 0 0 1 .476-.21l14.662.012a.322.322 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54z",clipRule:"evenodd"})]})}function Me({className:e}){return jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",className:e||"h-5 w-5",children:[jsxRuntime.jsx("rect",{width:"20",height:"20",rx:"4",fill:"#627EEA",fillOpacity:"0.2"}),jsxRuntime.jsx("path",{fill:"#627EEA",d:"M10 3l-4 6.5 4 2.5 4-2.5L10 3z"}),jsxRuntime.jsx("path",{fill:"#627EEA",fillOpacity:"0.6",d:"M6 9.5L10 12l4-2.5L10 17 6 9.5z"})]})}function Lt({config:e,onSuccess:t,title:s="Log in or Sign up",showWallets:l,showOTP:f,className:h=""}){let m=pe(e),{isAuthenticated:o,wallet:r,loading:i,error:p,authenticateSolana:a,authenticateEVM:d,authenticateOTP:n,bridge:c,stackId:g}=m,b=!e.stackId&&!g,L=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:x,identityProviders:v,loading:M}=me(g||e.stackId||null,L),[N,I]=react.useState(b?"stack-select":"select"),[T,A]=react.useState(null),[G,Z]=react.useState(false),[w,C]=react.useState("idle"),[_,D]=react.useState(""),[P,O]=react.useState([]),[J,$]=react.useState(e.stackId||null),[E,R]=react.useState(false),[Re,We]=react.useState(false);react.useEffect(()=>{if(typeof window>"u")return;let k=()=>{let W=window;R(!!(W.phantom?.solana?.isPhantom||W.solana?.isPhantom));let B=W.ethereum;We(!!(B?.isMetaMask||B?.providers?.some(H=>H.isMetaMask)));};k(),window.addEventListener("ethereum#initialized",k);let z=setTimeout(k,500);return ()=>{window.removeEventListener("ethereum#initialized",k),clearTimeout(z);}},[]),react.useEffect(()=>{N==="stack-select"&&g&&($(g),I("select"));},[N,g]),react.useEffect(()=>{if(!(!c.ready||!b)&&c.identity){let k=[];c.resolvedStackId&&k.push({stackId:c.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(k.map(async z=>{try{let W=await fetch(`${L}/api/v2/stacks/${z.stackId}`);if(W.ok){let B=await W.json(),H=B.data?.stack||B;z.name=H.displayName||H.name,z.logoUrl=H.logoUrl;}}catch{}return z})).then(O);}},[c.ready,c.identity,c.resolvedStackId,b,L]),react.useEffect(()=>{o&&N==="success"&&t?.();},[o,N,t]);let Se=l||(v.length>0?v.filter(k=>k.type==="wallet").map(k=>k.id):["phantom","metamask"]),ve=f!==void 0?f:v.length>0?v.some(k=>k.type==="otp"):true,_e=async()=>{A("phantom"),I("connecting");let k=await a("phantom");I(k?"success":"error");},$e=async()=>{A("metamask"),I("connecting");let k=await d();I(k?"success":"error");},Be=async k=>{C("verifying"),D(""),await n(k)?(C("success"),I("success")):(C("error"),D("Invalid or expired code"),setTimeout(()=>C("idle"),2e3));},Ie=()=>{I(b&&!J?"stack-select":"select"),A(null),Z(false),C("idle"),D("");};return jsxRuntime.jsxs("div",{className:`w-full max-w-md space-y-3 ${h}`,children:[jsxRuntime.jsxs("div",{className:"mb-6 text-center",children:[x?.logoUrl&&N!=="stack-select"&&jsxRuntime.jsx("img",{src:x.logoUrl,alt:"",className:"h-10 w-10 mx-auto mb-3"}),jsxRuntime.jsx("h1",{className:"font-semibold text-2xl text-white",children:s}),x?.displayName&&N!=="stack-select"&&jsxRuntime.jsx("p",{className:"text-sm text-zinc-400 mt-1",children:x.displayName})]}),N==="stack-select"&&jsxRuntime.jsxs("div",{className:"space-y-3",children:[jsxRuntime.jsx("p",{className:"text-center text-sm text-zinc-400 mb-4",children:P.length>0?"Select a network to continue":"No previous connections found. Enter a Stack ID to continue."}),P.map(k=>jsxRuntime.jsxs("button",{onClick:()=>{$(k.stackId),I("select");},className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[k.logoUrl?jsxRuntime.jsx("img",{src:k.logoUrl,alt:"",className:"h-10 w-10 flex-shrink-0"}):jsxRuntime.jsx("div",{className:"h-10 w-10 flex-shrink-0 bg-zinc-700 flex items-center justify-center text-zinc-400 text-sm font-mono",children:k.name?.[0]?.toUpperCase()||"S"}),jsxRuntime.jsxs("div",{className:"flex-1 text-left",children:[jsxRuntime.jsx("span",{className:"font-medium text-white",children:k.name||k.stackId}),jsxRuntime.jsx("p",{className:"text-xs text-zinc-500",children:k.domain})]}),jsxRuntime.jsx("span",{className:"text-xs text-zinc-600",children:"Previously connected"})]},k.stackId)),c.ready&&!c.known&&jsxRuntime.jsx("p",{className:"text-center text-xs text-zinc-600 mt-4",children:"Connect to a stack for the first time to get started."})]}),N==="select"&&M&&jsxRuntime.jsx("div",{className:"flex items-center justify-center py-8",children:jsxRuntime.jsx("div",{className:"h-6 w-6 border-2 border-zinc-600 border-t-white animate-spin",style:{borderRadius:"50%"}})}),p&&N==="error"&&jsxRuntime.jsxs("div",{className:"mb-4 border border-red-500/30 bg-red-500/10 p-4",children:[jsxRuntime.jsx("p",{className:"text-center text-red-400 text-sm",children:p}),jsxRuntime.jsx("button",{className:"mt-3 w-full text-sm text-zinc-400 hover:text-white",onClick:Ie,children:"Try Again"})]}),N==="success"&&jsxRuntime.jsxs("div",{className:"border border-green-500/30 bg-green-500/10 p-6 text-center",children:[jsxRuntime.jsx("p",{className:"font-medium text-green-400 text-sm",children:"Connected!"}),jsxRuntime.jsx("p",{className:"mt-1 text-xs text-zinc-400",children:"Redirecting..."})]}),N==="connecting"&&i&&jsxRuntime.jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 text-center",children:[jsxRuntime.jsxs("div",{className:"mx-auto mb-3 h-14 w-14 animate-pulse",children:[T==="phantom"&&jsxRuntime.jsx(ee,{className:"h-14 w-14"}),T==="metamask"&&jsxRuntime.jsx(te,{className:"h-14 w-14"})]}),jsxRuntime.jsx("p",{className:"font-medium text-sm text-white",children:r.connected?"Signing message...":"Connecting wallet..."}),jsxRuntime.jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Please confirm in your wallet"}),jsxRuntime.jsx("button",{className:"mt-4 text-sm text-zinc-500 hover:text-white",onClick:Ie,children:"Cancel"})]}),N==="select"&&!i&&!M&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[Se.includes("phantom")&&jsxRuntime.jsxs("button",{onClick:_e,disabled:!E,className:`flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a] ${E?"":"cursor-not-allowed opacity-50"}`,children:[jsxRuntime.jsx(ee,{className:"h-14 w-14 flex-shrink-0"}),jsxRuntime.jsxs("div",{className:"flex-1 text-left",children:[jsxRuntime.jsx("span",{className:"font-medium text-lg text-white",children:"Phantom"}),!E&&jsxRuntime.jsx("p",{className:"text-xs text-zinc-500",children:"Not installed"})]}),jsxRuntime.jsx(Ne,{className:"h-8 w-8"})]}),Se.includes("metamask")&&Re&&jsxRuntime.jsxs("button",{onClick:$e,className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsxRuntime.jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center bg-white p-2",children:jsxRuntime.jsx(te,{className:"h-10 w-10"})}),jsxRuntime.jsx("div",{className:"flex-1 text-left",children:jsxRuntime.jsx("span",{className:"font-medium text-lg text-white",children:"MetaMask"})}),jsxRuntime.jsx(Me,{className:"h-8 w-8"})]}),ve&&!G&&jsxRuntime.jsxs("button",{onClick:()=>Z(true),className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsxRuntime.jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center border border-zinc-700 bg-[#2a2a3e]",children:jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"28px",viewBox:"0 -960 960 960",width:"28px",fill:"#e3e3e3",children:jsxRuntime.jsx("path",{d:"M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v480q0 33-23.5 56.5T800-160H160Z"})})}),jsxRuntime.jsx("div",{className:"flex-1 text-left",children:jsxRuntime.jsx("span",{className:"font-medium text-lg text-white",children:"Access Code"})})]}),ve&&G&&jsxRuntime.jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 space-y-4",children:[jsxRuntime.jsx("p",{className:"text-center text-sm text-zinc-400",children:"Enter your 6-digit access code"}),jsxRuntime.jsx(X,{onComplete:Be,disabled:w==="verifying",error:_}),w==="verifying"&&jsxRuntime.jsx("p",{className:"text-center text-sm text-zinc-400 animate-pulse",children:"Verifying..."}),w==="success"&&jsxRuntime.jsx("p",{className:"text-center text-sm text-green-400",children:"Verified!"}),x?.webPageUrl&&w==="idle"&&jsxRuntime.jsx("a",{href:`${x.webPageUrl}/connect/pair`,target:"_blank",rel:"noopener noreferrer",className:"block text-center text-sm text-zinc-500 hover:text-white transition-colors",children:"Get code"})]})]})]})}function jt({className:e}){return jsxRuntime.jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"black"}),jsxRuntime.jsx("path",{d:"M8.53901 8L14.7164 16.2153L8.5 22.8947H9.89907L15.3415 17.0468L19.7389 22.8947H24.5L17.975 14.2173L23.7612 8H22.3621L17.3499 13.3858L13.3001 8H8.53901ZM10.5964 9.02501H12.7837L22.4422 21.8695H20.255L10.5964 9.02501Z",fill:"#F7F7F7"})]})}function At({className:e}){return jsxRuntime.jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#F1F2F9"}),jsxRuntime.jsx("path",{d:"M26.1001 16.2273C26.1001 15.5182 26.0365 14.8364 25.9183 14.1818H16.5001V18.05H21.8819C21.6501 19.3 20.9456 20.3591 19.8865 21.0682V23.5773H23.1183C25.0092 21.8364 26.1001 19.2727 26.1001 16.2273Z",fill:"#4285F4"}),jsxRuntime.jsx("path",{d:"M16.5001 26C19.2001 26 21.4637 25.1046 23.1182 23.5773L19.8864 21.0682C18.991 21.6682 17.8455 22.0227 16.5001 22.0227C13.8955 22.0227 11.691 20.2637 10.9046 17.9H7.56372V20.4909C9.20917 23.7591 12.591 26 16.5001 26Z",fill:"#34A853"}),jsxRuntime.jsx("path",{d:"M10.9047 17.8999C10.7047 17.2999 10.591 16.659 10.591 15.9999C10.591 15.3408 10.7047 14.6999 10.9047 14.0999V11.509H7.56376C6.86376 12.9025 6.49951 14.4405 6.50012 15.9999C6.50012 17.6136 6.88649 19.1408 7.56376 20.4908L10.9047 17.8999Z",fill:"#FBBC05"}),jsxRuntime.jsx("path",{d:"M16.5001 9.97726C17.9682 9.97726 19.2864 10.4818 20.3228 11.4727L23.191 8.60454C21.4591 6.99091 19.1955 6 16.5001 6C12.591 6 9.20917 8.2409 7.56372 11.5091L10.9046 14.1C11.691 11.7364 13.8955 9.97726 16.5001 9.97726Z",fill:"#EA4335"})]})}function Tt({className:e}){return jsxRuntime.jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#5462EB"}),jsxRuntime.jsx("path",{d:"M23.5433 8.87438C22.2479 8.26174 20.8587 7.81038 19.4063 7.55187C19.3799 7.54688 19.3534 7.55934 19.3398 7.58428C19.1612 7.91179 18.9633 8.33905 18.8247 8.67487C17.2625 8.43382 15.7084 8.43382 14.1782 8.67487C14.0396 8.33158 13.8345 7.91179 13.6551 7.58428C13.6414 7.56018 13.615 7.54771 13.5886 7.55187C12.1369 7.80955 10.7478 8.26092 9.45159 8.87438C9.44037 8.87937 9.43075 8.88769 9.42437 8.89849C6.78947 12.9558 6.06766 16.9134 6.42176 20.8219C6.42336 20.841 6.43378 20.8593 6.4482 20.871C8.18663 22.1868 9.87059 22.9857 11.5233 23.5152C11.5497 23.5235 11.5778 23.5135 11.5946 23.491C11.9855 22.9408 12.334 22.3606 12.6328 21.7504C12.6505 21.7147 12.6336 21.6723 12.5976 21.6581C12.0448 21.442 11.5185 21.1785 11.0122 20.8793C10.9721 20.8552 10.9689 20.7961 11.0058 20.7679C11.1123 20.6856 11.2189 20.6 11.3206 20.5135C11.339 20.4977 11.3647 20.4944 11.3863 20.5044C14.7125 22.0696 18.3136 22.0696 21.6006 20.5044C21.6222 20.4936 21.6479 20.4969 21.6671 20.5127C21.7688 20.5991 21.8754 20.6856 21.9827 20.7679C22.0196 20.7961 22.0172 20.8552 21.9771 20.8793C21.4708 21.1843 20.9445 21.442 20.3909 21.6573C20.3548 21.6715 20.3388 21.7147 20.3564 21.7504C20.6617 22.3597 21.0101 22.9399 21.3939 23.4902C21.4099 23.5135 21.4387 23.5235 21.4652 23.5152C23.1259 22.9857 24.8099 22.1868 26.5483 20.871C26.5635 20.8593 26.5731 20.8419 26.5747 20.8228C26.9985 16.3041 25.8649 12.3789 23.5697 8.89931C23.5641 8.88769 23.5545 8.87937 23.5433 8.87438Z",fill:"#F7F7F7"})]})}function Ot({className:e}){return jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",className:e||"h-8 w-8",children:[jsxRuntime.jsx("rect",{width:"512",height:"512",rx:"15%",fill:"#37aee2"}),jsxRuntime.jsx("path",{fill:"#c8daea",d:"M199 404c-11 0-10-4-13-14l-32-105 245-144"}),jsxRuntime.jsx("path",{fill:"#a9c9dd",d:"M199 404c7 0 11-4 16-8l45-43-56-34"}),jsxRuntime.jsx("path",{fill:"#f6fbfe",d:"M204 319l135 99c14 9 26 4 30-14l55-258c5-22-9-32-24-25L79 245c-21 8-21 21-4 26l83 26 190-121c9-5 17-3 11 4"})]})}
1
+ 'use strict';var clsx=require('clsx'),tailwindMerge=require('tailwind-merge'),react=require('react'),jsxRuntime=require('react/jsx-runtime');function Qe(...e){return tailwindMerge.twMerge(clsx.clsx(e))}function Ve(e){return e>=1e12?`${(e/1e12).toFixed(e%1e12===0?0:1)}T`:e>=1e9?`${(e/1e9).toFixed(e%1e9===0?0:1)}B`:e>=1e6?`${(e/1e6).toFixed(e%1e6===0?0:1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:e.toLocaleString()}function Ye(e,t){if(!e)return "/";if(e.startsWith("/")&&!e.startsWith("//"))return e;try{let s=new URL(e,t);return s.origin!==t?"/":s.pathname+s.search+s.hash}catch{return "/"}}function Ge(e){try{let t=e.split(".");if(t.length!==3)return null;let s=atob(t[1].replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(s)}catch{return null}}function oe(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(s=>s.trim()).find(s=>s.startsWith("stackauth_session="));if(!e)return null;let t=e.slice(18);return JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function j(e="__csrf"){if(typeof document>"u")return null;let t=document.cookie.split(";").map(s=>s.trim()).find(s=>s.startsWith(`${e}=`));return t?t.slice(e.length+1):null}function re(){let[e,t]=react.useState(null),[s,l]=react.useState(true),f=react.useCallback(()=>{let o=oe();o&&o.expiresAt>Date.now()?t({userId:o.userId,address:o.address,chain:o.chain,expiresAt:o.expiresAt,planId:o.planId,authMethod:o.authMethod}):t(null),l(false);},[]);react.useEffect(()=>{f();},[f]);let h=react.useCallback(async(o="")=>{try{let r=await fetch(`${o}/api/auth/session`);if(r.ok){let i=await r.json();if(i.session)return t(i.session),i.session}return t(null),null}catch{return null}},[]),m=!!e&&e.expiresAt>Date.now();return {session:e,loading:s,isAuthenticated:m,refresh:h,readSession:f}}function ae(e="__csrf",t="x-csrf-token"){let[s,l]=react.useState(null);react.useEffect(()=>{l(j(e));},[e]);let f=s?{[t]:s}:{};return {token:s,headers:f}}function ie(){let[e,t]=react.useState({connected:false,address:null,chain:null,provider:null}),[s,l]=react.useState(null),f=react.useCallback(async(r="phantom")=>{l(null);try{let i=typeof window<"u"?window:null,p=r==="phantom"?i?.phantom?.solana||i?.solana:i?.solflare;if(!p)return l(`${r} wallet not found`),null;let d=(await p.connect()).publicKey.toString();return t({connected:!0,address:d,chain:"solana",provider:r}),d}catch(i){return l(i.message||"Failed to connect wallet"),null}},[]),h=react.useCallback(async()=>{l(null);try{let i=(typeof window<"u"?window:null)?.ethereum;if(!i)return l("MetaMask not found"),null;let p=i;i.providers?.length&&(p=i.providers.find(n=>n.isMetaMask)||i);let d=(await p.request({method:"eth_requestAccounts"}))[0];return d?(t({connected:!0,address:d,chain:"ethereum",provider:"metamask"}),d):(l("No account selected"),null)}catch(r){return l(r.message||"Failed to connect wallet"),null}},[]),m=react.useCallback(async(r,i)=>{l(null);let p=i?.chain||e.chain,a=i?.provider||e.provider,d=i?.address||e.address;try{if(p==="solana"){let n=typeof window<"u"?window:null,c=a==="solflare"?n?.solflare:n?.phantom?.solana||n?.solana;if(!c)throw new Error("Wallet not available");let g=new TextEncoder().encode(r),b=await c.signMessage(g,"utf8"),L=b.signature||b,x="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",v=BigInt(0);for(let N of L)v=v*256n+BigInt(N);let M="";for(;v>0n;)M=x[Number(v%58n)]+M,v=v/58n;for(let N of L)if(N===0)M="1"+M;else break;return M}if(p==="ethereum"){let c=(typeof window<"u"?window:null)?.ethereum;if(c?.providers?.length&&(c=c.providers.find(b=>b.isMetaMask)||c),!c)throw new Error("MetaMask not available");return await c.request({method:"personal_sign",params:[r,d]})}throw new Error("No wallet connected")}catch(n){return l(n.message||"Signing failed"),null}},[e]),o=react.useCallback(()=>{t({connected:false,address:null,chain:null,provider:null}),l(null);},[]);return {wallet:e,error:s,connectSolana:f,connectEVM:h,signMessage:m,disconnect:o}}var et="https://stacknet.magma-rpc.com/auth/bridge",q="stacknet-auth-bridge";function ce(e){let t=e?.bridgeUrl||et,s=e?.disabled||false,l=react.useRef(null),[f,h]=react.useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),m=react.useRef([]),o=react.useRef(false),r=react.useCallback(n=>{let c={...n,protocol:q};o.current&&l.current?.contentWindow?l.current.contentWindow.postMessage(c,new URL(t).origin):m.current.push(c);},[t]);react.useEffect(()=>{if(s)return;let n=g=>{if(!(!g.data||g.data.protocol!==q)){try{if(g.origin!==new URL(t).origin)return}catch{return}switch(g.data.type){case "bridge:ready":o.current=true,h(b=>({...b,ready:true}));for(let b of m.current)l.current?.contentWindow?.postMessage(b,g.origin);m.current=[],l.current?.contentWindow?.postMessage({protocol:q,type:"auth:check"},g.origin),l.current?.contentWindow?.postMessage({protocol:q,type:"auth:resolve-stack"},g.origin);break;case "auth:status":h(b=>({...b,known:g.data.known,identity:g.data.identity,identityCount:g.data.identityCount||0}));break;case "auth:resolved-stack":h(b=>({...b,resolvedStackId:g.data.stackId||null}));break;}}};window.addEventListener("message",n);let c=document.createElement("iframe");return c.src=t,c.style.display="none",c.setAttribute("aria-hidden","true"),c.setAttribute("tabindex","-1"),c.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(c),l.current=c,()=>{window.removeEventListener("message",n),c.parentNode&&c.parentNode.removeChild(c),l.current=null,o.current=false;}},[t,s]);let i=react.useCallback(n=>{r({type:"auth:connected",...n});},[r]),p=react.useCallback(n=>{r({type:"auth:disconnected",...n});},[r]),a=react.useCallback(()=>{r({type:"auth:clear"}),h({ready:f.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[r,f.ready]),d=react.useCallback(()=>{r({type:"auth:check"});},[r]);return {...f,reportConnected:i,reportDisconnected:p,clearAll:a,refresh:d}}async function Ue(e,t,s,l){let f=e.apiVersion||"v2",h=`${e.baseUrl}/api/${f}${s}`;try{let m=await fetch(h,{method:t,headers:{"Content-Type":"application/json"},body:l?JSON.stringify(l):void 0}),o=await m.json();return m.ok?o.success&&o.data!==void 0?{success:!0,data:o.data}:{success:!0,data:o}:{success:!1,error:o.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(m){return {success:false,error:{code:"NETWORK_ERROR",message:m instanceof Error?m.message:"Network error"}}}}function de(e){return {getNetworkStatus:()=>Ue(e,"GET","/network/status"),getWeb3Challenge:(t,s)=>Ue(e,"POST",`/stacks/${e.stackId}/auth/web3/challenge`,{chain:t,address:s})}}function pe(e={apiBaseUrl:""}){let{wallet:t,connectSolana:s,connectEVM:l,signMessage:f,disconnect:h}=ie(),{session:m,isAuthenticated:o,refresh:r,readSession:i}=re(),{headers:p}=ae(),a=ce({disabled:typeof window>"u"}),[d,n]=react.useState(false),[c,g]=react.useState(null),[b,L]=react.useState(false),x=e.apiBaseUrl||"",v=e.stacknetUrl||"https://stacknet.magma-rpc.com",M=e.stackId||a.resolvedStackId||"",N=de({baseUrl:v,stackId:M}),I=react.useCallback(async(w,C,_,D)=>{n(true),g(null);try{let P=C;if(!P){let R=await _();if(!R)return n(!1),!1;P=R;}let O=await N.getWeb3Challenge(w,P);if(!O.success||!O.data)return g("Failed to get challenge"),n(!1),!1;let J=await f(O.data.message,{chain:w,provider:D,address:P});if(!J)return n(!1),!1;let $={chain:w,message:O.data.message,signature:J,stackId:M};w==="solana"&&($.publicKey=P);let E=await fetch(`${x}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)});if(!E.ok){let R=await E.json().catch(()=>({}));return g(R.error||"Authentication failed"),n(!1),!1}return a.reportConnected({address:P,chain:w,method:D||(w==="solana"?"phantom":"metamask"),stackId:M}),i(),n(!1),!0}catch(P){return g(P.message||"Authentication failed"),n(false),false}},[x,N,f,i,a,M]),T=react.useCallback(async(w="phantom")=>{let C=await s(w);return C?I("solana",C,()=>s(w),w):false},[s,I]),A=react.useCallback(async()=>{let w=await l();return w?I("ethereum",w,l,"metamask"):false},[l,I]),G=react.useCallback(async w=>{n(true),g(null);try{let C=await fetch(`${x}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:w})});if(!C.ok){let _=await C.json().catch(()=>({}));return g(_.error||"Invalid code"),n(!1),!1}return i(),n(!1),!0}catch(C){return g(C.message||"OTP verification failed"),n(false),false}},[x,i]),Z=react.useCallback(async()=>{t.address&&t.chain&&a.reportDisconnected({address:t.address,chain:t.chain,stackId:M});try{await fetch(`${x}/api/auth/logout`,{method:"POST",headers:p});}catch{}h(),i();},[x,p,h,i,t,a,M]);return react.useEffect(()=>{if(!e.autoConnect||b||o||!a.ready||!a.known||!a.identity)return;L(true);let{chain:w,method:C}=a.identity;w==="solana"&&(C==="phantom"||C==="solflare")?T(C):w==="ethereum"&&A();},[e.autoConnect,b,o,a,T,A]),{session:m,isAuthenticated:o,wallet:t,loading:d,error:c,authenticateSolana:T,authenticateEVM:A,authenticateOTP:G,logout:Z,refresh:()=>r(x),stackId:M,bridge:{ready:a.ready,known:a.known,identity:a.identity,identityCount:a.identityCount,resolvedStackId:a.resolvedStackId}}}function me(e,t="https://stacknet.magma-rpc.com"){let[s,l]=react.useState(null),[f,h]=react.useState(false),[m,o]=react.useState(null),r=react.useCallback(async p=>{h(true),o(null);try{let a=await fetch(`${t}/api/v2/stacks/${p}`);if(!a.ok)return o("Stack not found"),h(!1),null;let d=await a.json(),n=d.data?.stack||d.stack||d,c={id:n.id,name:n.name,displayName:n.displayName||n.name,description:n.description,logoUrl:n.logoUrl,webPageUrl:n.webPageUrl,allowedChains:n.allowedChains||[],features:n.features,stripeProvider:n.stripeProvider,oauthProviders:n.oauthProviders?.map(g=>({provider:g.provider,enabled:g.enabled!==!1}))};return l(c),h(!1),c}catch(a){return o(a.message),h(false),null}},[t]);react.useEffect(()=>{e&&r(e);},[e,r]);let i=s?ot(s):[];return {config:s,loading:f,error:m,identityProviders:i,fetchConfig:r}}function ot(e){let t=[];if(e.features?.web3Auth!==false&&(e.allowedChains.includes("solana")&&(t.push({type:"wallet",id:"phantom",name:"Phantom",chain:"solana"}),t.push({type:"wallet",id:"solflare",name:"Solflare",chain:"solana"})),(e.allowedChains.includes("ethereum")||e.allowedChains.includes("polygon")||e.allowedChains.includes("base"))&&t.push({type:"wallet",id:"metamask",name:"MetaMask",chain:"ethereum"})),e.features?.apiKeyAuth!==false&&t.push({type:"otp",id:"otp",name:"Access Code"}),e.features?.oauthAuth&&e.oauthProviders)for(let s of e.oauthProviders)s.enabled&&t.push({type:"oauth",id:s.provider,name:s.provider});return t}function it(e=""){let[t,s]=react.useState([]),[l,f]=react.useState(true),[h,m]=react.useState(null),o=react.useCallback(async()=>{try{let r=await fetch(`${e}/api/billing/plans`);if(r.ok){let i=await r.json();s(i.plans||i||[]);}}catch(r){m(r.message);}finally{f(false);}},[e]);return react.useEffect(()=>{o();},[o]),{plans:t,loading:l,error:h,refresh:o}}function ct(e=""){let[t,s]=react.useState(null),[l,f]=react.useState(true),[h,m]=react.useState(null),o=react.useCallback(async()=>{try{let p=await fetch(`${e}/api/billing/subscription`);if(p.ok){let a=await p.json();s(a.plan?a:null);}}catch(p){m(p.message);}finally{f(false);}},[e]);react.useEffect(()=>{o();},[o]);let r=react.useCallback(async p=>{let a=j(),n=await(await fetch(`${e}/api/billing/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-csrf-token":a}:{}},body:JSON.stringify({planId:p})})).json();return n.url||n.checkoutUrl||null},[e]),i=react.useCallback(async()=>{let p=j();return (await fetch(`${e}/api/billing/cancel`,{method:"POST",headers:p?{"x-csrf-token":p}:{}})).ok?(await o(),true):false},[e,o]);return {subscription:t,loading:l,error:h,refresh:o,subscribe:r,cancel:i}}function pt(e=""){let[t,s]=react.useState(null),[l,f]=react.useState(true),[h,m]=react.useState(null),o=react.useCallback(async()=>{try{let r=await fetch(`${e}/api/billing/usage`);if(r.ok){let i=await r.json();s(i);}}catch(r){m(r.message);}finally{f(false);}},[e]);return react.useEffect(()=>{o();},[o]),{usage:t,loading:l,error:h,refresh:o}}function ft(e=""){let[t,s]=react.useState(false),[l,f]=react.useState(null),h=react.useCallback(async o=>{s(true),f(null);try{let r=j(),i=await fetch(`${e}/api/billing/prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...r?{"x-csrf-token":r}:{}},body:JSON.stringify({amountCents:o})}),p=await i.json();return i.ok?p.url||null:(f(p.error||"Purchase failed"),null)}catch(r){return f(r.message),null}finally{s(false);}},[e]),m=react.useCallback(async o=>{s(true),f(null);try{let r=j(),i=await fetch(`${e}/api/billing/verify-prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...r?{"x-csrf-token":r}:{}},body:JSON.stringify({sessionId:o})}),p=await i.json();return i.ok?p:(f(p.error||"Verification failed"),null)}catch(r){return f(r.message),null}finally{s(false);}},[e]);return {purchase:h,verifySession:m,loading:t,error:l}}function ht(e="",t){let[s,l]=react.useState([]),[f,h]=react.useState(true),[m,o]=react.useState(null),r=t?.limit||50,i=t?.offset||0,p=react.useCallback(async()=>{try{let a=await fetch(`${e}/api/billing/history?limit=${r}&offset=${i}`);if(a.ok){let d=await a.json();l(d.records||d.history||(Array.isArray(d)?d:[]));}}catch(a){o(a.message);}finally{h(false);}},[e,r,i]);return react.useEffect(()=>{p();},[p]),{records:s,loading:f,error:m,refresh:p}}var Te=react.createContext(null);function wt(){let e=react.useContext(Te);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function bt({config:e,callbacks:t,children:s}){return jsxRuntime.jsx(Te.Provider,{value:{config:e,callbacks:t},children:s})}function X({length:e=6,onComplete:t,disabled:s=false,error:l,className:f="",inputClassName:h=""}){let [m,o]=react.useState(Array(e).fill("")),r=react.useCallback((a,d)=>{if(d.length>1){let c=d.replace(/\D/g,"").slice(0,e).split(""),g=[...m];c.forEach((L,x)=>{a+x<e&&(g[a+x]=L);}),o(g);let b=Math.min(a+c.length,e-1);document.getElementById(`userutils-otp-${b}`)?.focus(),g.every(L=>L!=="")&&setTimeout(()=>t(g.join("")),100);return}if(!/^\d?$/.test(d))return;let n=[...m];n[a]=d,o(n),d&&a<e-1&&document.getElementById(`userutils-otp-${a+1}`)?.focus(),d&&a===e-1&&n.every(c=>c!=="")&&setTimeout(()=>t(n.join("")),100);},[m,e,t]),i=react.useCallback((a,d)=>{if(d.key==="Backspace"&&!m[a]&&a>0){document.getElementById(`userutils-otp-${a-1}`)?.focus();let n=[...m];n[a-1]="",o(n);}if(d.key==="Enter"){let n=m.join("");n.length===e&&t(n);}},[m,e,t]);react.useCallback(()=>{o(Array(e).fill("")),document.getElementById("userutils-otp-0")?.focus();},[e]);return jsxRuntime.jsxs("div",{className:f,children:[jsxRuntime.jsx("div",{className:"flex gap-2 justify-center",children:m.map((a,d)=>jsxRuntime.jsx("input",{id:`userutils-otp-${d}`,type:"text",inputMode:"numeric",maxLength:e,value:a,onChange:n=>r(d,n.target.value),onKeyDown:n=>i(d,n),disabled:s,autoFocus:d===0,className:`w-12 h-14 text-center text-xl font-mono bg-secondary border border-primary/10 text-foreground focus:outline-none focus:border-primary/30 disabled:opacity-50 ${h}`},d))}),l&&jsxRuntime.jsx("p",{className:"text-center text-sm text-red-400 mt-2",children:l})]})}X.displayName="OTPInput";var Mt="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function ee({className:e}){return jsxRuntime.jsx("img",{src:Mt,alt:"Phantom",className:e})}function te({className:e}){return jsxRuntime.jsxs("svg",{className:e,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 507.83 470.86",children:[jsxRuntime.jsx("polygon",{fill:"#e2761b",stroke:"#e2761b",strokeLinecap:"round",strokeLinejoin:"round",points:"482.09 0.5 284.32 147.38 320.9 60.72 482.09 0.5"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"25.54 0.5 221.72 148.77 186.93 60.72 25.54 0.5"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"410.93 340.97 358.26 421.67 470.96 452.67 503.36 342.76 410.93 340.97"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"4.67 342.76 36.87 452.67 149.57 421.67 96.9 340.97 4.67 342.76"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 111.8 252.13 223.7 257.1 219.73 136.85 143.21 204.62"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"364.42 204.62 286.91 135.46 284.32 257.1 396.03 252.13 364.42 204.62"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 216.75 388.87 158.71 343.55 149.57 421.67"}),jsxRuntime.jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 358.26 421.67 348.92 343.55 290.88 388.87"}),jsxRuntime.jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"358.26 421.67 290.88 388.87 296.25 432.8 295.65 451.28 358.26 421.67"}),jsxRuntime.jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 212.18 451.28 211.78 432.8 216.75 388.87 149.57 421.67"}),jsxRuntime.jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"213.17 314.54 157.12 298.04 196.67 279.95 213.17 314.54"}),jsxRuntime.jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"294.46 314.54 310.96 279.95 350.71 298.04 294.46 314.54"}),jsxRuntime.jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 159.11 340.97 96.9 342.76 149.57 421.67"}),jsxRuntime.jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"348.72 340.97 358.26 421.67 410.93 342.76 348.72 340.97"}),jsxRuntime.jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"396.03 252.13 284.32 257.1 294.66 314.54 311.16 279.95 350.91 298.04 396.03 252.13"}),jsxRuntime.jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 196.87 279.95 213.17 314.54 223.7 257.1 111.8 252.13 157.12 298.04"}),jsxRuntime.jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"111.8 252.13 158.71 343.55 157.12 298.04 111.8 252.13"}),jsxRuntime.jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"350.91 298.04 348.92 343.55 396.03 252.13 350.91 298.04"}),jsxRuntime.jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"223.7 257.1 213.17 314.54 226.29 382.31 229.27 293.07 223.7 257.1"}),jsxRuntime.jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 278.96 292.87 281.34 382.31 294.66 314.54 284.32 257.1"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"294.66 314.54 281.34 382.31 290.88 388.87 348.92 343.55 350.91 298.04 294.66 314.54"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 158.71 343.55 216.75 388.87 226.29 382.31 213.17 314.54 157.12 298.04"}),jsxRuntime.jsx("polygon",{fill:"#c0ad9e",stroke:"#c0ad9e",strokeLinecap:"round",strokeLinejoin:"round",points:"295.65 451.28 296.25 432.8 291.28 428.42 216.35 428.42 211.78 432.8 212.18 451.28 149.57 421.67 171.43 439.55 215.75 470.36 291.88 470.36 336.4 439.55 358.26 421.67 295.65 451.28"}),jsxRuntime.jsx("polygon",{fill:"#161616",stroke:"#161616",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 281.34 382.31 226.29 382.31 216.75 388.87 211.78 432.8 216.35 428.42 291.28 428.42 296.25 432.8 290.88 388.87"}),jsxRuntime.jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"490.44 156.92 507.33 75.83 482.09 0.5 290.88 142.41 364.42 204.62 468.37 235.03 491.43 208.2 481.49 201.05 497.39 186.54 485.07 177 500.97 164.87 490.44 156.92"}),jsxRuntime.jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"0.5 75.83 17.39 156.92 6.66 164.87 22.56 177 10.44 186.54 26.34 201.05 16.4 208.2 39.26 235.03 143.21 204.62 216.75 142.41 25.54 0.5 0.5 75.83"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"468.37 235.03 364.42 204.62 396.03 252.13 348.92 343.55 410.93 342.76 503.36 342.76 468.37 235.03"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 39.26 235.03 4.67 342.76 96.9 342.76 158.71 343.55 111.8 252.13 143.21 204.62"}),jsxRuntime.jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 290.88 142.41 321.1 60.72 186.93 60.72 216.75 142.41 223.7 257.1 226.09 293.27 226.29 382.31 281.34 382.31 281.74 293.27 284.32 257.1"})]})}function Ne({className:e}){return jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",className:e||"h-5 w-5",children:[jsxRuntime.jsxs("linearGradient",{id:"sol-g",x1:"7.233",x2:"24.766",y1:"24.766",y2:"7.234",gradientUnits:"userSpaceOnUse",children:[jsxRuntime.jsx("stop",{offset:"0",stopColor:"#9945ff"}),jsxRuntime.jsx("stop",{offset:"0.2",stopColor:"#7962e7"}),jsxRuntime.jsx("stop",{offset:"1",stopColor:"#00d18c"})]}),jsxRuntime.jsx("path",{fill:"#10111a",d:"M0 0h32v32H0z"}),jsxRuntime.jsx("path",{fill:"url(#sol-g)",fillRule:"evenodd",d:"M9.873 20.41a.65.65 0 0 1 .476-.21l14.662.012a.323.323 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54zm15.376-2.862a.322.322 0 0 1-.238.54l-14.662.012a.64.64 0 0 1-.476-.21l-3.122-3.44a.323.323 0 0 1 .238-.54l14.662-.012a.64.64 0 0 1 .475.21zM9.873 7.81a.64.64 0 0 1 .476-.21l14.662.012a.322.322 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54z",clipRule:"evenodd"})]})}function Me({className:e}){return jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",className:e||"h-5 w-5",children:[jsxRuntime.jsx("rect",{width:"20",height:"20",rx:"4",fill:"#627EEA",fillOpacity:"0.2"}),jsxRuntime.jsx("path",{fill:"#627EEA",d:"M10 3l-4 6.5 4 2.5 4-2.5L10 3z"}),jsxRuntime.jsx("path",{fill:"#627EEA",fillOpacity:"0.6",d:"M6 9.5L10 12l4-2.5L10 17 6 9.5z"})]})}function Lt({config:e,onSuccess:t,title:s="Log in or Sign up",showWallets:l,showOTP:f,className:h=""}){let m=pe(e),{isAuthenticated:o,wallet:r,loading:i,error:p,authenticateSolana:a,authenticateEVM:d,authenticateOTP:n,bridge:c,stackId:g}=m,b=!e.stackId&&!g,L=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:x,identityProviders:v,loading:M}=me(g||e.stackId||null,L),[N,I]=react.useState(b?"stack-select":"select"),[T,A]=react.useState(null),[G,Z]=react.useState(false),[w,C]=react.useState("idle"),[_,D]=react.useState(""),[P,O]=react.useState([]),[J,$]=react.useState(e.stackId||null),[E,R]=react.useState(false),[Re,We]=react.useState(false);react.useEffect(()=>{if(typeof window>"u")return;let k=()=>{let W=window;R(!!(W.phantom?.solana?.isPhantom||W.solana?.isPhantom));let B=W.ethereum;We(!!(B?.isMetaMask||B?.providers?.some(H=>H.isMetaMask)));};k(),window.addEventListener("ethereum#initialized",k);let z=setTimeout(k,500);return ()=>{window.removeEventListener("ethereum#initialized",k),clearTimeout(z);}},[]),react.useEffect(()=>{N==="stack-select"&&g&&($(g),I("select"));},[N,g]),react.useEffect(()=>{if(!(!c.ready||!b)&&c.identity){let k=[];c.resolvedStackId&&k.push({stackId:c.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(k.map(async z=>{try{let W=await fetch(`${L}/api/v2/stacks/${z.stackId}`);if(W.ok){let B=await W.json(),H=B.data?.stack||B;z.name=H.displayName||H.name,z.logoUrl=H.logoUrl;}}catch{}return z})).then(O);}},[c.ready,c.identity,c.resolvedStackId,b,L]),react.useEffect(()=>{o&&N==="success"&&t?.();},[o,N,t]);let Se=l||(v.length>0?v.filter(k=>k.type==="wallet").map(k=>k.id):["phantom","metamask"]),ve=f!==void 0?f:v.length>0?v.some(k=>k.type==="otp"):true,_e=async()=>{A("phantom"),I("connecting");let k=await a("phantom");I(k?"success":"error");},$e=async()=>{A("metamask"),I("connecting");let k=await d();I(k?"success":"error");},Be=async k=>{C("verifying"),D(""),await n(k)?(C("success"),I("success")):(C("error"),D("Invalid or expired code"),setTimeout(()=>C("idle"),2e3));},Ie=()=>{I(b&&!J?"stack-select":"select"),A(null),Z(false),C("idle"),D("");};return jsxRuntime.jsxs("div",{className:`w-full max-w-md space-y-3 ${h}`,children:[jsxRuntime.jsxs("div",{className:"mb-6 text-center",children:[x?.logoUrl&&N!=="stack-select"&&jsxRuntime.jsx("img",{src:x.logoUrl,alt:"",className:"h-10 w-10 mx-auto mb-3"}),jsxRuntime.jsx("h1",{className:"font-semibold text-2xl text-white",children:s}),x?.displayName&&N!=="stack-select"&&jsxRuntime.jsx("p",{className:"text-sm text-zinc-400 mt-1",children:x.displayName})]}),N==="stack-select"&&jsxRuntime.jsxs("div",{className:"space-y-3",children:[jsxRuntime.jsx("p",{className:"text-center text-sm text-zinc-400 mb-4",children:P.length>0?"Select a network to continue":"No previous connections found. Enter a Stack ID to continue."}),P.map(k=>jsxRuntime.jsxs("button",{onClick:()=>{$(k.stackId),I("select");},className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[k.logoUrl?jsxRuntime.jsx("img",{src:k.logoUrl,alt:"",className:"h-10 w-10 flex-shrink-0"}):jsxRuntime.jsx("div",{className:"h-10 w-10 flex-shrink-0 bg-zinc-700 flex items-center justify-center text-zinc-400 text-sm font-mono",children:k.name?.[0]?.toUpperCase()||"S"}),jsxRuntime.jsxs("div",{className:"flex-1 text-left",children:[jsxRuntime.jsx("span",{className:"font-medium text-white",children:k.name||k.stackId}),jsxRuntime.jsx("p",{className:"text-xs text-zinc-500",children:k.domain})]}),jsxRuntime.jsx("span",{className:"text-xs text-zinc-600",children:"Previously connected"})]},k.stackId)),c.ready&&!c.known&&jsxRuntime.jsx("p",{className:"text-center text-xs text-zinc-600 mt-4",children:"Connect to a stack for the first time to get started."})]}),N==="select"&&M&&jsxRuntime.jsx("div",{className:"flex items-center justify-center py-8",children:jsxRuntime.jsx("div",{className:"h-6 w-6 border-2 border-zinc-600 border-t-white animate-spin",style:{borderRadius:"50%"}})}),p&&N==="error"&&jsxRuntime.jsxs("div",{className:"mb-4 border border-red-500/30 bg-red-500/10 p-4",children:[jsxRuntime.jsx("p",{className:"text-center text-red-400 text-sm",children:p}),jsxRuntime.jsx("button",{className:"mt-3 w-full text-sm text-zinc-400 hover:text-white",onClick:Ie,children:"Try Again"})]}),N==="success"&&jsxRuntime.jsxs("div",{className:"border border-green-500/30 bg-green-500/10 p-6 text-center",children:[jsxRuntime.jsx("p",{className:"font-medium text-green-400 text-sm",children:"Connected!"}),jsxRuntime.jsx("p",{className:"mt-1 text-xs text-zinc-400",children:"Redirecting..."})]}),N==="connecting"&&i&&jsxRuntime.jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 text-center",children:[jsxRuntime.jsxs("div",{className:"mx-auto mb-3 h-14 w-14 animate-pulse",children:[T==="phantom"&&jsxRuntime.jsx(ee,{className:"h-14 w-14"}),T==="metamask"&&jsxRuntime.jsx(te,{className:"h-14 w-14"})]}),jsxRuntime.jsx("p",{className:"font-medium text-sm text-white",children:r.connected?"Signing message...":"Connecting wallet..."}),jsxRuntime.jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Please confirm in your wallet"}),jsxRuntime.jsx("button",{className:"mt-4 text-sm text-zinc-500 hover:text-white",onClick:Ie,children:"Cancel"})]}),N==="select"&&!i&&!M&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[Se.includes("phantom")&&jsxRuntime.jsxs("button",{onClick:_e,disabled:!E,className:`flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a] ${E?"":"cursor-not-allowed opacity-50"}`,children:[jsxRuntime.jsx(ee,{className:"h-14 w-14 flex-shrink-0"}),jsxRuntime.jsxs("div",{className:"flex-1 text-left",children:[jsxRuntime.jsx("span",{className:"font-medium text-lg text-white",children:"Phantom"}),!E&&jsxRuntime.jsx("p",{className:"text-xs text-zinc-500",children:"Not installed"})]}),jsxRuntime.jsx(Ne,{className:"h-8 w-8"})]}),Se.includes("metamask")&&Re&&jsxRuntime.jsxs("button",{onClick:$e,className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsxRuntime.jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center bg-white p-2",children:jsxRuntime.jsx(te,{className:"h-10 w-10"})}),jsxRuntime.jsx("div",{className:"flex-1 text-left",children:jsxRuntime.jsx("span",{className:"font-medium text-lg text-white",children:"MetaMask"})}),jsxRuntime.jsx(Me,{className:"h-8 w-8"})]}),ve&&!G&&jsxRuntime.jsxs("button",{onClick:()=>Z(true),className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsxRuntime.jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center border border-zinc-700 bg-[#2a2a3e]",children:jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"28px",viewBox:"0 -960 960 960",width:"28px",fill:"#e3e3e3",children:jsxRuntime.jsx("path",{d:"M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v480q0 33-23.5 56.5T800-160H160Z"})})}),jsxRuntime.jsx("div",{className:"flex-1 text-left",children:jsxRuntime.jsx("span",{className:"font-medium text-lg text-white",children:"Access Code"})})]}),ve&&G&&jsxRuntime.jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 space-y-4",children:[jsxRuntime.jsx("p",{className:"text-center text-sm text-zinc-400",children:"Enter your 6-digit access code"}),jsxRuntime.jsx(X,{onComplete:Be,disabled:w==="verifying",error:_}),w==="verifying"&&jsxRuntime.jsx("p",{className:"text-center text-sm text-zinc-400 animate-pulse",children:"Verifying..."}),w==="success"&&jsxRuntime.jsx("p",{className:"text-center text-sm text-green-400",children:"Verified!"}),x?.webPageUrl&&w==="idle"&&jsxRuntime.jsx("a",{href:`${x.webPageUrl}/connect/pair`,target:"_blank",rel:"noopener noreferrer",className:"block text-center text-sm text-zinc-500 hover:text-white transition-colors",children:"Get code"})]})]})]})}function jt({className:e}){return jsxRuntime.jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"black"}),jsxRuntime.jsx("path",{d:"M8.53901 8L14.7164 16.2153L8.5 22.8947H9.89907L15.3415 17.0468L19.7389 22.8947H24.5L17.975 14.2173L23.7612 8H22.3621L17.3499 13.3858L13.3001 8H8.53901ZM10.5964 9.02501H12.7837L22.4422 21.8695H20.255L10.5964 9.02501Z",fill:"#F7F7F7"})]})}function At({className:e}){return jsxRuntime.jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#F1F2F9"}),jsxRuntime.jsx("path",{d:"M26.1001 16.2273C26.1001 15.5182 26.0365 14.8364 25.9183 14.1818H16.5001V18.05H21.8819C21.6501 19.3 20.9456 20.3591 19.8865 21.0682V23.5773H23.1183C25.0092 21.8364 26.1001 19.2727 26.1001 16.2273Z",fill:"#4285F4"}),jsxRuntime.jsx("path",{d:"M16.5001 26C19.2001 26 21.4637 25.1046 23.1182 23.5773L19.8864 21.0682C18.991 21.6682 17.8455 22.0227 16.5001 22.0227C13.8955 22.0227 11.691 20.2637 10.9046 17.9H7.56372V20.4909C9.20917 23.7591 12.591 26 16.5001 26Z",fill:"#34A853"}),jsxRuntime.jsx("path",{d:"M10.9047 17.8999C10.7047 17.2999 10.591 16.659 10.591 15.9999C10.591 15.3408 10.7047 14.6999 10.9047 14.0999V11.509H7.56376C6.86376 12.9025 6.49951 14.4405 6.50012 15.9999C6.50012 17.6136 6.88649 19.1408 7.56376 20.4908L10.9047 17.8999Z",fill:"#FBBC05"}),jsxRuntime.jsx("path",{d:"M16.5001 9.97726C17.9682 9.97726 19.2864 10.4818 20.3228 11.4727L23.191 8.60454C21.4591 6.99091 19.1955 6 16.5001 6C12.591 6 9.20917 8.2409 7.56372 11.5091L10.9046 14.1C11.691 11.7364 13.8955 9.97726 16.5001 9.97726Z",fill:"#EA4335"})]})}function Tt({className:e}){return jsxRuntime.jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#5462EB"}),jsxRuntime.jsx("path",{d:"M23.5433 8.87438C22.2479 8.26174 20.8587 7.81038 19.4063 7.55187C19.3799 7.54688 19.3534 7.55934 19.3398 7.58428C19.1612 7.91179 18.9633 8.33905 18.8247 8.67487C17.2625 8.43382 15.7084 8.43382 14.1782 8.67487C14.0396 8.33158 13.8345 7.91179 13.6551 7.58428C13.6414 7.56018 13.615 7.54771 13.5886 7.55187C12.1369 7.80955 10.7478 8.26092 9.45159 8.87438C9.44037 8.87937 9.43075 8.88769 9.42437 8.89849C6.78947 12.9558 6.06766 16.9134 6.42176 20.8219C6.42336 20.841 6.43378 20.8593 6.4482 20.871C8.18663 22.1868 9.87059 22.9857 11.5233 23.5152C11.5497 23.5235 11.5778 23.5135 11.5946 23.491C11.9855 22.9408 12.334 22.3606 12.6328 21.7504C12.6505 21.7147 12.6336 21.6723 12.5976 21.6581C12.0448 21.442 11.5185 21.1785 11.0122 20.8793C10.9721 20.8552 10.9689 20.7961 11.0058 20.7679C11.1123 20.6856 11.2189 20.6 11.3206 20.5135C11.339 20.4977 11.3647 20.4944 11.3863 20.5044C14.7125 22.0696 18.3136 22.0696 21.6006 20.5044C21.6222 20.4936 21.6479 20.4969 21.6671 20.5127C21.7688 20.5991 21.8754 20.6856 21.9827 20.7679C22.0196 20.7961 22.0172 20.8552 21.9771 20.8793C21.4708 21.1843 20.9445 21.442 20.3909 21.6573C20.3548 21.6715 20.3388 21.7147 20.3564 21.7504C20.6617 22.3597 21.0101 22.9399 21.3939 23.4902C21.4099 23.5135 21.4387 23.5235 21.4652 23.5152C23.1259 22.9857 24.8099 22.1868 26.5483 20.871C26.5635 20.8593 26.5731 20.8419 26.5747 20.8228C26.9985 16.3041 25.8649 12.3789 23.5697 8.89931C23.5641 8.88769 23.5545 8.87937 23.5433 8.87438Z",fill:"#F7F7F7"})]})}function Ot({className:e}){return jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",className:e||"h-8 w-8",children:[jsxRuntime.jsx("rect",{width:"512",height:"512",rx:"15%",fill:"#37aee2"}),jsxRuntime.jsx("path",{fill:"#c8daea",d:"M199 404c-11 0-10-4-13-14l-32-105 245-144"}),jsxRuntime.jsx("path",{fill:"#a9c9dd",d:"M199 404c7 0 11-4 16-8l45-43-56-34"}),jsxRuntime.jsx("path",{fill:"#f6fbfe",d:"M204 319l135 99c14 9 26 4 30-14l55-258c5-22-9-32-24-25L79 245c-21 8-21 21-4 26l83 26 190-121c9-5 17-3 11 4"})]})}
2
2
  exports.ConnectWidget=Lt;exports.DiscordIcon=Tt;exports.EthereumIcon=Me;exports.GoogleIcon=At;exports.MetaMaskIcon=te;exports.OTPInput=X;exports.PhantomIcon=ee;exports.SolanaIcon=Ne;exports.TelegramIcon=Ot;exports.TwitterIcon=jt;exports.UserUtilsProvider=bt;exports.cn=Qe;exports.createStackNetClient=de;exports.decodeJwtPayloadClient=Ge;exports.formatTokens=Ve;exports.readCSRFCookie=j;exports.readSessionCookie=oe;exports.useAuthBridge=ce;exports.useBillingHistory=ht;exports.useCSRFToken=ae;exports.usePlans=it;exports.usePrepaidCheckout=ft;exports.useSession=re;exports.useStackAuth=pe;exports.useStackConfig=me;exports.useSubscription=ct;exports.useUsage=pt;exports.useUserUtilsContext=wt;exports.useWeb3Wallet=ie;exports.validateRedirectUrl=Ye;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import {clsx}from'clsx';import {twMerge}from'tailwind-merge';import {createContext,useState,useCallback,useEffect,useRef,useContext}from'react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';function Qe(...e){return twMerge(clsx(e))}function Ve(e){return e>=1e12?`${(e/1e12).toFixed(e%1e12===0?0:1)}T`:e>=1e9?`${(e/1e9).toFixed(e%1e9===0?0:1)}B`:e>=1e6?`${(e/1e6).toFixed(e%1e6===0?0:1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:e.toLocaleString()}function Ye(e,t){if(!e)return "/";if(e.startsWith("/")&&!e.startsWith("//"))return e;try{let s=new URL(e,t);return s.origin!==t?"/":s.pathname+s.search+s.hash}catch{return "/"}}function Ge(e){try{let t=e.split(".");if(t.length!==3)return null;let s=atob(t[1].replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(s)}catch{return null}}function oe(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(s=>s.trim()).find(s=>s.startsWith("stackauth_session="));if(!e)return null;let t=e.slice(18);return JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function j(e="__csrf"){if(typeof document>"u")return null;let t=document.cookie.split(";").map(s=>s.trim()).find(s=>s.startsWith(`${e}=`));return t?t.slice(e.length+1):null}function re(){let[e,t]=useState(null),[s,l]=useState(true),f=useCallback(()=>{let o=oe();o&&o.expiresAt>Date.now()?t({userId:o.userId,address:o.address,chain:o.chain,expiresAt:o.expiresAt,planId:o.planId,authMethod:o.authMethod}):t(null),l(false);},[]);useEffect(()=>{f();},[f]);let h=useCallback(async(o="")=>{try{let r=await fetch(`${o}/api/auth/session`);if(r.ok){let i=await r.json();if(i.session)return t(i.session),i.session}return t(null),null}catch{return null}},[]),m=!!e&&e.expiresAt>Date.now();return {session:e,loading:s,isAuthenticated:m,refresh:h,readSession:f}}function ae(e="__csrf",t="x-csrf-token"){let[s,l]=useState(null);useEffect(()=>{l(j(e));},[e]);let f=s?{[t]:s}:{};return {token:s,headers:f}}function ie(){let[e,t]=useState({connected:false,address:null,chain:null,provider:null}),[s,l]=useState(null),f=useCallback(async(r="phantom")=>{l(null);try{let i=typeof window<"u"?window:null,p=r==="phantom"?i?.phantom?.solana||i?.solana:i?.solflare;if(!p)return l(`${r} wallet not found`),null;let d=(await p.connect()).publicKey.toString();return t({connected:!0,address:d,chain:"solana",provider:r}),d}catch(i){return l(i.message||"Failed to connect wallet"),null}},[]),h=useCallback(async()=>{l(null);try{let i=(typeof window<"u"?window:null)?.ethereum;if(!i)return l("MetaMask not found"),null;let p=i;i.providers?.length&&(p=i.providers.find(n=>n.isMetaMask)||i);let d=(await p.request({method:"eth_requestAccounts"}))[0];return d?(t({connected:!0,address:d,chain:"ethereum",provider:"metamask"}),d):(l("No account selected"),null)}catch(r){return l(r.message||"Failed to connect wallet"),null}},[]),m=useCallback(async(r,i)=>{l(null);let p=i?.chain||e.chain,a=i?.provider||e.provider,d=i?.address||e.address;try{if(p==="solana"){let n=typeof window<"u"?window:null,c=a==="solflare"?n?.solflare:n?.phantom?.solana||n?.solana;if(!c)throw new Error("Wallet not available");let g=new TextEncoder().encode(r),b=await c.signMessage(g,"utf8"),L=b.signature||b,x="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",v=BigInt(0);for(let N of L)v=v*256n+BigInt(N);let M="";for(;v>0n;)M=x[Number(v%58n)]+M,v=v/58n;for(let N of L)if(N===0)M="1"+M;else break;return M}if(p==="ethereum"){let c=(typeof window<"u"?window:null)?.ethereum;if(c?.providers?.length&&(c=c.providers.find(b=>b.isMetaMask)||c),!c)throw new Error("MetaMask not available");return await c.request({method:"personal_sign",params:[r,d]})}throw new Error("No wallet connected")}catch(n){return l(n.message||"Signing failed"),null}},[e]),o=useCallback(()=>{t({connected:false,address:null,chain:null,provider:null}),l(null);},[]);return {wallet:e,error:s,connectSolana:f,connectEVM:h,signMessage:m,disconnect:o}}var et="https://stacknet.magma-rpc.com/auth/bridge",q="stacknet-auth-bridge";function ce(e){let t=e?.bridgeUrl||et,s=e?.disabled||false,l=useRef(null),[f,h]=useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),m=useRef([]),o=useRef(false),r=useCallback(n=>{let c={...n,protocol:q};o.current&&l.current?.contentWindow?l.current.contentWindow.postMessage(c,new URL(t).origin):m.current.push(c);},[t]);useEffect(()=>{if(s)return;let n=g=>{if(!(!g.data||g.data.protocol!==q)){try{if(g.origin!==new URL(t).origin)return}catch{return}switch(g.data.type){case "bridge:ready":o.current=true,h(b=>({...b,ready:true}));for(let b of m.current)l.current?.contentWindow?.postMessage(b,g.origin);m.current=[],l.current?.contentWindow?.postMessage({protocol:q,type:"auth:check"},g.origin),l.current?.contentWindow?.postMessage({protocol:q,type:"auth:resolve-stack"},g.origin);break;case "auth:status":h(b=>({...b,known:g.data.known,identity:g.data.identity,identityCount:g.data.identityCount||0}));break;case "auth:resolved-stack":h(b=>({...b,resolvedStackId:g.data.stackId||null}));break;}}};window.addEventListener("message",n);let c=document.createElement("iframe");return c.src=t,c.style.display="none",c.setAttribute("aria-hidden","true"),c.setAttribute("tabindex","-1"),c.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(c),l.current=c,()=>{window.removeEventListener("message",n),c.parentNode&&c.parentNode.removeChild(c),l.current=null,o.current=false;}},[t,s]);let i=useCallback(n=>{r({type:"auth:connected",...n});},[r]),p=useCallback(n=>{r({type:"auth:disconnected",...n});},[r]),a=useCallback(()=>{r({type:"auth:clear"}),h({ready:f.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[r,f.ready]),d=useCallback(()=>{r({type:"auth:check"});},[r]);return {...f,reportConnected:i,reportDisconnected:p,clearAll:a,refresh:d}}async function Ue(e,t,s,l){let f=e.apiVersion||"v2",h=`${e.baseUrl}/api/${f}${s}`;try{let m=await fetch(h,{method:t,headers:{"Content-Type":"application/json"},body:l?JSON.stringify(l):void 0}),o=await m.json();return m.ok?o.success&&o.data!==void 0?{success:!0,data:o.data}:{success:!0,data:o}:{success:!1,error:o.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(m){return {success:false,error:{code:"NETWORK_ERROR",message:m instanceof Error?m.message:"Network error"}}}}function de(e){return {getNetworkStatus:()=>Ue(e,"GET","/network/status"),getWeb3Challenge:(t,s)=>Ue(e,"POST",`/stacks/${e.stackId}/auth/web3/challenge`,{chain:t,address:s})}}function pe(e={apiBaseUrl:""}){let{wallet:t,connectSolana:s,connectEVM:l,signMessage:f,disconnect:h}=ie(),{session:m,isAuthenticated:o,refresh:r,readSession:i}=re(),{headers:p}=ae(),a=ce({disabled:typeof window>"u"}),[d,n]=useState(false),[c,g]=useState(null),[b,L]=useState(false),x=e.apiBaseUrl||"",v=e.stacknetUrl||"https://stacknet.magma-rpc.com",M=e.stackId||a.resolvedStackId||"",N=de({baseUrl:v,stackId:M}),I=useCallback(async(w,C,_,D)=>{n(true),g(null);try{let P=C;if(!P){let R=await _();if(!R)return n(!1),!1;P=R;}let O=await N.getWeb3Challenge(w,P);if(!O.success||!O.data)return g("Failed to get challenge"),n(!1),!1;let J=await f(O.data.message,{chain:w,provider:D,address:P});if(!J)return n(!1),!1;let $={chain:w,message:O.data.message,signature:J};w==="solana"&&($.publicKey=P);let E=await fetch(`${x}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)});if(!E.ok){let R=await E.json().catch(()=>({}));return g(R.error||"Authentication failed"),n(!1),!1}return a.reportConnected({address:P,chain:w,method:D||(w==="solana"?"phantom":"metamask"),stackId:M}),i(),n(!1),!0}catch(P){return g(P.message||"Authentication failed"),n(false),false}},[x,N,f,i,a,M]),T=useCallback(async(w="phantom")=>{let C=await s(w);return C?I("solana",C,()=>s(w),w):false},[s,I]),A=useCallback(async()=>{let w=await l();return w?I("ethereum",w,l,"metamask"):false},[l,I]),G=useCallback(async w=>{n(true),g(null);try{let C=await fetch(`${x}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:w})});if(!C.ok){let _=await C.json().catch(()=>({}));return g(_.error||"Invalid code"),n(!1),!1}return i(),n(!1),!0}catch(C){return g(C.message||"OTP verification failed"),n(false),false}},[x,i]),Z=useCallback(async()=>{t.address&&t.chain&&a.reportDisconnected({address:t.address,chain:t.chain,stackId:M});try{await fetch(`${x}/api/auth/logout`,{method:"POST",headers:p});}catch{}h(),i();},[x,p,h,i,t,a,M]);return useEffect(()=>{if(!e.autoConnect||b||o||!a.ready||!a.known||!a.identity)return;L(true);let{chain:w,method:C}=a.identity;w==="solana"&&(C==="phantom"||C==="solflare")?T(C):w==="ethereum"&&A();},[e.autoConnect,b,o,a,T,A]),{session:m,isAuthenticated:o,wallet:t,loading:d,error:c,authenticateSolana:T,authenticateEVM:A,authenticateOTP:G,logout:Z,refresh:()=>r(x),stackId:M,bridge:{ready:a.ready,known:a.known,identity:a.identity,identityCount:a.identityCount,resolvedStackId:a.resolvedStackId}}}function me(e,t="https://stacknet.magma-rpc.com"){let[s,l]=useState(null),[f,h]=useState(false),[m,o]=useState(null),r=useCallback(async p=>{h(true),o(null);try{let a=await fetch(`${t}/api/v2/stacks/${p}`);if(!a.ok)return o("Stack not found"),h(!1),null;let d=await a.json(),n=d.data?.stack||d.stack||d,c={id:n.id,name:n.name,displayName:n.displayName||n.name,description:n.description,logoUrl:n.logoUrl,webPageUrl:n.webPageUrl,allowedChains:n.allowedChains||[],features:n.features,stripeProvider:n.stripeProvider,oauthProviders:n.oauthProviders?.map(g=>({provider:g.provider,enabled:g.enabled!==!1}))};return l(c),h(!1),c}catch(a){return o(a.message),h(false),null}},[t]);useEffect(()=>{e&&r(e);},[e,r]);let i=s?ot(s):[];return {config:s,loading:f,error:m,identityProviders:i,fetchConfig:r}}function ot(e){let t=[];if(e.features?.web3Auth!==false&&(e.allowedChains.includes("solana")&&(t.push({type:"wallet",id:"phantom",name:"Phantom",chain:"solana"}),t.push({type:"wallet",id:"solflare",name:"Solflare",chain:"solana"})),(e.allowedChains.includes("ethereum")||e.allowedChains.includes("polygon")||e.allowedChains.includes("base"))&&t.push({type:"wallet",id:"metamask",name:"MetaMask",chain:"ethereum"})),e.features?.apiKeyAuth!==false&&t.push({type:"otp",id:"otp",name:"Access Code"}),e.features?.oauthAuth&&e.oauthProviders)for(let s of e.oauthProviders)s.enabled&&t.push({type:"oauth",id:s.provider,name:s.provider});return t}function it(e=""){let[t,s]=useState([]),[l,f]=useState(true),[h,m]=useState(null),o=useCallback(async()=>{try{let r=await fetch(`${e}/api/billing/plans`);if(r.ok){let i=await r.json();s(i.plans||i||[]);}}catch(r){m(r.message);}finally{f(false);}},[e]);return useEffect(()=>{o();},[o]),{plans:t,loading:l,error:h,refresh:o}}function ct(e=""){let[t,s]=useState(null),[l,f]=useState(true),[h,m]=useState(null),o=useCallback(async()=>{try{let p=await fetch(`${e}/api/billing/subscription`);if(p.ok){let a=await p.json();s(a.plan?a:null);}}catch(p){m(p.message);}finally{f(false);}},[e]);useEffect(()=>{o();},[o]);let r=useCallback(async p=>{let a=j(),n=await(await fetch(`${e}/api/billing/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-csrf-token":a}:{}},body:JSON.stringify({planId:p})})).json();return n.url||n.checkoutUrl||null},[e]),i=useCallback(async()=>{let p=j();return (await fetch(`${e}/api/billing/cancel`,{method:"POST",headers:p?{"x-csrf-token":p}:{}})).ok?(await o(),true):false},[e,o]);return {subscription:t,loading:l,error:h,refresh:o,subscribe:r,cancel:i}}function pt(e=""){let[t,s]=useState(null),[l,f]=useState(true),[h,m]=useState(null),o=useCallback(async()=>{try{let r=await fetch(`${e}/api/billing/usage`);if(r.ok){let i=await r.json();s(i);}}catch(r){m(r.message);}finally{f(false);}},[e]);return useEffect(()=>{o();},[o]),{usage:t,loading:l,error:h,refresh:o}}function ft(e=""){let[t,s]=useState(false),[l,f]=useState(null),h=useCallback(async o=>{s(true),f(null);try{let r=j(),i=await fetch(`${e}/api/billing/prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...r?{"x-csrf-token":r}:{}},body:JSON.stringify({amountCents:o})}),p=await i.json();return i.ok?p.url||null:(f(p.error||"Purchase failed"),null)}catch(r){return f(r.message),null}finally{s(false);}},[e]),m=useCallback(async o=>{s(true),f(null);try{let r=j(),i=await fetch(`${e}/api/billing/verify-prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...r?{"x-csrf-token":r}:{}},body:JSON.stringify({sessionId:o})}),p=await i.json();return i.ok?p:(f(p.error||"Verification failed"),null)}catch(r){return f(r.message),null}finally{s(false);}},[e]);return {purchase:h,verifySession:m,loading:t,error:l}}function ht(e="",t){let[s,l]=useState([]),[f,h]=useState(true),[m,o]=useState(null),r=t?.limit||50,i=t?.offset||0,p=useCallback(async()=>{try{let a=await fetch(`${e}/api/billing/history?limit=${r}&offset=${i}`);if(a.ok){let d=await a.json();l(d.records||d.history||(Array.isArray(d)?d:[]));}}catch(a){o(a.message);}finally{h(false);}},[e,r,i]);return useEffect(()=>{p();},[p]),{records:s,loading:f,error:m,refresh:p}}var Te=createContext(null);function wt(){let e=useContext(Te);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function bt({config:e,callbacks:t,children:s}){return jsx(Te.Provider,{value:{config:e,callbacks:t},children:s})}function X({length:e=6,onComplete:t,disabled:s=false,error:l,className:f="",inputClassName:h=""}){let [m,o]=useState(Array(e).fill("")),r=useCallback((a,d)=>{if(d.length>1){let c=d.replace(/\D/g,"").slice(0,e).split(""),g=[...m];c.forEach((L,x)=>{a+x<e&&(g[a+x]=L);}),o(g);let b=Math.min(a+c.length,e-1);document.getElementById(`userutils-otp-${b}`)?.focus(),g.every(L=>L!=="")&&setTimeout(()=>t(g.join("")),100);return}if(!/^\d?$/.test(d))return;let n=[...m];n[a]=d,o(n),d&&a<e-1&&document.getElementById(`userutils-otp-${a+1}`)?.focus(),d&&a===e-1&&n.every(c=>c!=="")&&setTimeout(()=>t(n.join("")),100);},[m,e,t]),i=useCallback((a,d)=>{if(d.key==="Backspace"&&!m[a]&&a>0){document.getElementById(`userutils-otp-${a-1}`)?.focus();let n=[...m];n[a-1]="",o(n);}if(d.key==="Enter"){let n=m.join("");n.length===e&&t(n);}},[m,e,t]);useCallback(()=>{o(Array(e).fill("")),document.getElementById("userutils-otp-0")?.focus();},[e]);return jsxs("div",{className:f,children:[jsx("div",{className:"flex gap-2 justify-center",children:m.map((a,d)=>jsx("input",{id:`userutils-otp-${d}`,type:"text",inputMode:"numeric",maxLength:e,value:a,onChange:n=>r(d,n.target.value),onKeyDown:n=>i(d,n),disabled:s,autoFocus:d===0,className:`w-12 h-14 text-center text-xl font-mono bg-secondary border border-primary/10 text-foreground focus:outline-none focus:border-primary/30 disabled:opacity-50 ${h}`},d))}),l&&jsx("p",{className:"text-center text-sm text-red-400 mt-2",children:l})]})}X.displayName="OTPInput";var Mt="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function ee({className:e}){return jsx("img",{src:Mt,alt:"Phantom",className:e})}function te({className:e}){return jsxs("svg",{className:e,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 507.83 470.86",children:[jsx("polygon",{fill:"#e2761b",stroke:"#e2761b",strokeLinecap:"round",strokeLinejoin:"round",points:"482.09 0.5 284.32 147.38 320.9 60.72 482.09 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"25.54 0.5 221.72 148.77 186.93 60.72 25.54 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"410.93 340.97 358.26 421.67 470.96 452.67 503.36 342.76 410.93 340.97"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"4.67 342.76 36.87 452.67 149.57 421.67 96.9 340.97 4.67 342.76"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 111.8 252.13 223.7 257.1 219.73 136.85 143.21 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"364.42 204.62 286.91 135.46 284.32 257.1 396.03 252.13 364.42 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 216.75 388.87 158.71 343.55 149.57 421.67"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 358.26 421.67 348.92 343.55 290.88 388.87"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"358.26 421.67 290.88 388.87 296.25 432.8 295.65 451.28 358.26 421.67"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 212.18 451.28 211.78 432.8 216.75 388.87 149.57 421.67"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"213.17 314.54 157.12 298.04 196.67 279.95 213.17 314.54"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"294.46 314.54 310.96 279.95 350.71 298.04 294.46 314.54"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 159.11 340.97 96.9 342.76 149.57 421.67"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"348.72 340.97 358.26 421.67 410.93 342.76 348.72 340.97"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"396.03 252.13 284.32 257.1 294.66 314.54 311.16 279.95 350.91 298.04 396.03 252.13"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 196.87 279.95 213.17 314.54 223.7 257.1 111.8 252.13 157.12 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"111.8 252.13 158.71 343.55 157.12 298.04 111.8 252.13"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"350.91 298.04 348.92 343.55 396.03 252.13 350.91 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"223.7 257.1 213.17 314.54 226.29 382.31 229.27 293.07 223.7 257.1"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 278.96 292.87 281.34 382.31 294.66 314.54 284.32 257.1"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"294.66 314.54 281.34 382.31 290.88 388.87 348.92 343.55 350.91 298.04 294.66 314.54"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 158.71 343.55 216.75 388.87 226.29 382.31 213.17 314.54 157.12 298.04"}),jsx("polygon",{fill:"#c0ad9e",stroke:"#c0ad9e",strokeLinecap:"round",strokeLinejoin:"round",points:"295.65 451.28 296.25 432.8 291.28 428.42 216.35 428.42 211.78 432.8 212.18 451.28 149.57 421.67 171.43 439.55 215.75 470.36 291.88 470.36 336.4 439.55 358.26 421.67 295.65 451.28"}),jsx("polygon",{fill:"#161616",stroke:"#161616",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 281.34 382.31 226.29 382.31 216.75 388.87 211.78 432.8 216.35 428.42 291.28 428.42 296.25 432.8 290.88 388.87"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"490.44 156.92 507.33 75.83 482.09 0.5 290.88 142.41 364.42 204.62 468.37 235.03 491.43 208.2 481.49 201.05 497.39 186.54 485.07 177 500.97 164.87 490.44 156.92"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"0.5 75.83 17.39 156.92 6.66 164.87 22.56 177 10.44 186.54 26.34 201.05 16.4 208.2 39.26 235.03 143.21 204.62 216.75 142.41 25.54 0.5 0.5 75.83"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"468.37 235.03 364.42 204.62 396.03 252.13 348.92 343.55 410.93 342.76 503.36 342.76 468.37 235.03"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 39.26 235.03 4.67 342.76 96.9 342.76 158.71 343.55 111.8 252.13 143.21 204.62"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 290.88 142.41 321.1 60.72 186.93 60.72 216.75 142.41 223.7 257.1 226.09 293.27 226.29 382.31 281.34 382.31 281.74 293.27 284.32 257.1"})]})}function Ne({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",className:e||"h-5 w-5",children:[jsxs("linearGradient",{id:"sol-g",x1:"7.233",x2:"24.766",y1:"24.766",y2:"7.234",gradientUnits:"userSpaceOnUse",children:[jsx("stop",{offset:"0",stopColor:"#9945ff"}),jsx("stop",{offset:"0.2",stopColor:"#7962e7"}),jsx("stop",{offset:"1",stopColor:"#00d18c"})]}),jsx("path",{fill:"#10111a",d:"M0 0h32v32H0z"}),jsx("path",{fill:"url(#sol-g)",fillRule:"evenodd",d:"M9.873 20.41a.65.65 0 0 1 .476-.21l14.662.012a.323.323 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54zm15.376-2.862a.322.322 0 0 1-.238.54l-14.662.012a.64.64 0 0 1-.476-.21l-3.122-3.44a.323.323 0 0 1 .238-.54l14.662-.012a.64.64 0 0 1 .475.21zM9.873 7.81a.64.64 0 0 1 .476-.21l14.662.012a.322.322 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54z",clipRule:"evenodd"})]})}function Me({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",className:e||"h-5 w-5",children:[jsx("rect",{width:"20",height:"20",rx:"4",fill:"#627EEA",fillOpacity:"0.2"}),jsx("path",{fill:"#627EEA",d:"M10 3l-4 6.5 4 2.5 4-2.5L10 3z"}),jsx("path",{fill:"#627EEA",fillOpacity:"0.6",d:"M6 9.5L10 12l4-2.5L10 17 6 9.5z"})]})}function Lt({config:e,onSuccess:t,title:s="Log in or Sign up",showWallets:l,showOTP:f,className:h=""}){let m=pe(e),{isAuthenticated:o,wallet:r,loading:i,error:p,authenticateSolana:a,authenticateEVM:d,authenticateOTP:n,bridge:c,stackId:g}=m,b=!e.stackId&&!g,L=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:x,identityProviders:v,loading:M}=me(g||e.stackId||null,L),[N,I]=useState(b?"stack-select":"select"),[T,A]=useState(null),[G,Z]=useState(false),[w,C]=useState("idle"),[_,D]=useState(""),[P,O]=useState([]),[J,$]=useState(e.stackId||null),[E,R]=useState(false),[Re,We]=useState(false);useEffect(()=>{if(typeof window>"u")return;let k=()=>{let W=window;R(!!(W.phantom?.solana?.isPhantom||W.solana?.isPhantom));let B=W.ethereum;We(!!(B?.isMetaMask||B?.providers?.some(H=>H.isMetaMask)));};k(),window.addEventListener("ethereum#initialized",k);let z=setTimeout(k,500);return ()=>{window.removeEventListener("ethereum#initialized",k),clearTimeout(z);}},[]),useEffect(()=>{N==="stack-select"&&g&&($(g),I("select"));},[N,g]),useEffect(()=>{if(!(!c.ready||!b)&&c.identity){let k=[];c.resolvedStackId&&k.push({stackId:c.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(k.map(async z=>{try{let W=await fetch(`${L}/api/v2/stacks/${z.stackId}`);if(W.ok){let B=await W.json(),H=B.data?.stack||B;z.name=H.displayName||H.name,z.logoUrl=H.logoUrl;}}catch{}return z})).then(O);}},[c.ready,c.identity,c.resolvedStackId,b,L]),useEffect(()=>{o&&N==="success"&&t?.();},[o,N,t]);let Se=l||(v.length>0?v.filter(k=>k.type==="wallet").map(k=>k.id):["phantom","metamask"]),ve=f!==void 0?f:v.length>0?v.some(k=>k.type==="otp"):true,_e=async()=>{A("phantom"),I("connecting");let k=await a("phantom");I(k?"success":"error");},$e=async()=>{A("metamask"),I("connecting");let k=await d();I(k?"success":"error");},Be=async k=>{C("verifying"),D(""),await n(k)?(C("success"),I("success")):(C("error"),D("Invalid or expired code"),setTimeout(()=>C("idle"),2e3));},Ie=()=>{I(b&&!J?"stack-select":"select"),A(null),Z(false),C("idle"),D("");};return jsxs("div",{className:`w-full max-w-md space-y-3 ${h}`,children:[jsxs("div",{className:"mb-6 text-center",children:[x?.logoUrl&&N!=="stack-select"&&jsx("img",{src:x.logoUrl,alt:"",className:"h-10 w-10 mx-auto mb-3"}),jsx("h1",{className:"font-semibold text-2xl text-white",children:s}),x?.displayName&&N!=="stack-select"&&jsx("p",{className:"text-sm text-zinc-400 mt-1",children:x.displayName})]}),N==="stack-select"&&jsxs("div",{className:"space-y-3",children:[jsx("p",{className:"text-center text-sm text-zinc-400 mb-4",children:P.length>0?"Select a network to continue":"No previous connections found. Enter a Stack ID to continue."}),P.map(k=>jsxs("button",{onClick:()=>{$(k.stackId),I("select");},className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[k.logoUrl?jsx("img",{src:k.logoUrl,alt:"",className:"h-10 w-10 flex-shrink-0"}):jsx("div",{className:"h-10 w-10 flex-shrink-0 bg-zinc-700 flex items-center justify-center text-zinc-400 text-sm font-mono",children:k.name?.[0]?.toUpperCase()||"S"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-white",children:k.name||k.stackId}),jsx("p",{className:"text-xs text-zinc-500",children:k.domain})]}),jsx("span",{className:"text-xs text-zinc-600",children:"Previously connected"})]},k.stackId)),c.ready&&!c.known&&jsx("p",{className:"text-center text-xs text-zinc-600 mt-4",children:"Connect to a stack for the first time to get started."})]}),N==="select"&&M&&jsx("div",{className:"flex items-center justify-center py-8",children:jsx("div",{className:"h-6 w-6 border-2 border-zinc-600 border-t-white animate-spin",style:{borderRadius:"50%"}})}),p&&N==="error"&&jsxs("div",{className:"mb-4 border border-red-500/30 bg-red-500/10 p-4",children:[jsx("p",{className:"text-center text-red-400 text-sm",children:p}),jsx("button",{className:"mt-3 w-full text-sm text-zinc-400 hover:text-white",onClick:Ie,children:"Try Again"})]}),N==="success"&&jsxs("div",{className:"border border-green-500/30 bg-green-500/10 p-6 text-center",children:[jsx("p",{className:"font-medium text-green-400 text-sm",children:"Connected!"}),jsx("p",{className:"mt-1 text-xs text-zinc-400",children:"Redirecting..."})]}),N==="connecting"&&i&&jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 text-center",children:[jsxs("div",{className:"mx-auto mb-3 h-14 w-14 animate-pulse",children:[T==="phantom"&&jsx(ee,{className:"h-14 w-14"}),T==="metamask"&&jsx(te,{className:"h-14 w-14"})]}),jsx("p",{className:"font-medium text-sm text-white",children:r.connected?"Signing message...":"Connecting wallet..."}),jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Please confirm in your wallet"}),jsx("button",{className:"mt-4 text-sm text-zinc-500 hover:text-white",onClick:Ie,children:"Cancel"})]}),N==="select"&&!i&&!M&&jsxs(Fragment,{children:[Se.includes("phantom")&&jsxs("button",{onClick:_e,disabled:!E,className:`flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a] ${E?"":"cursor-not-allowed opacity-50"}`,children:[jsx(ee,{className:"h-14 w-14 flex-shrink-0"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-lg text-white",children:"Phantom"}),!E&&jsx("p",{className:"text-xs text-zinc-500",children:"Not installed"})]}),jsx(Ne,{className:"h-8 w-8"})]}),Se.includes("metamask")&&Re&&jsxs("button",{onClick:$e,className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center bg-white p-2",children:jsx(te,{className:"h-10 w-10"})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white",children:"MetaMask"})}),jsx(Me,{className:"h-8 w-8"})]}),ve&&!G&&jsxs("button",{onClick:()=>Z(true),className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center border border-zinc-700 bg-[#2a2a3e]",children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"28px",viewBox:"0 -960 960 960",width:"28px",fill:"#e3e3e3",children:jsx("path",{d:"M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v480q0 33-23.5 56.5T800-160H160Z"})})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white",children:"Access Code"})})]}),ve&&G&&jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 space-y-4",children:[jsx("p",{className:"text-center text-sm text-zinc-400",children:"Enter your 6-digit access code"}),jsx(X,{onComplete:Be,disabled:w==="verifying",error:_}),w==="verifying"&&jsx("p",{className:"text-center text-sm text-zinc-400 animate-pulse",children:"Verifying..."}),w==="success"&&jsx("p",{className:"text-center text-sm text-green-400",children:"Verified!"}),x?.webPageUrl&&w==="idle"&&jsx("a",{href:`${x.webPageUrl}/connect/pair`,target:"_blank",rel:"noopener noreferrer",className:"block text-center text-sm text-zinc-500 hover:text-white transition-colors",children:"Get code"})]})]})]})}function jt({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"black"}),jsx("path",{d:"M8.53901 8L14.7164 16.2153L8.5 22.8947H9.89907L15.3415 17.0468L19.7389 22.8947H24.5L17.975 14.2173L23.7612 8H22.3621L17.3499 13.3858L13.3001 8H8.53901ZM10.5964 9.02501H12.7837L22.4422 21.8695H20.255L10.5964 9.02501Z",fill:"#F7F7F7"})]})}function At({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#F1F2F9"}),jsx("path",{d:"M26.1001 16.2273C26.1001 15.5182 26.0365 14.8364 25.9183 14.1818H16.5001V18.05H21.8819C21.6501 19.3 20.9456 20.3591 19.8865 21.0682V23.5773H23.1183C25.0092 21.8364 26.1001 19.2727 26.1001 16.2273Z",fill:"#4285F4"}),jsx("path",{d:"M16.5001 26C19.2001 26 21.4637 25.1046 23.1182 23.5773L19.8864 21.0682C18.991 21.6682 17.8455 22.0227 16.5001 22.0227C13.8955 22.0227 11.691 20.2637 10.9046 17.9H7.56372V20.4909C9.20917 23.7591 12.591 26 16.5001 26Z",fill:"#34A853"}),jsx("path",{d:"M10.9047 17.8999C10.7047 17.2999 10.591 16.659 10.591 15.9999C10.591 15.3408 10.7047 14.6999 10.9047 14.0999V11.509H7.56376C6.86376 12.9025 6.49951 14.4405 6.50012 15.9999C6.50012 17.6136 6.88649 19.1408 7.56376 20.4908L10.9047 17.8999Z",fill:"#FBBC05"}),jsx("path",{d:"M16.5001 9.97726C17.9682 9.97726 19.2864 10.4818 20.3228 11.4727L23.191 8.60454C21.4591 6.99091 19.1955 6 16.5001 6C12.591 6 9.20917 8.2409 7.56372 11.5091L10.9046 14.1C11.691 11.7364 13.8955 9.97726 16.5001 9.97726Z",fill:"#EA4335"})]})}function Tt({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#5462EB"}),jsx("path",{d:"M23.5433 8.87438C22.2479 8.26174 20.8587 7.81038 19.4063 7.55187C19.3799 7.54688 19.3534 7.55934 19.3398 7.58428C19.1612 7.91179 18.9633 8.33905 18.8247 8.67487C17.2625 8.43382 15.7084 8.43382 14.1782 8.67487C14.0396 8.33158 13.8345 7.91179 13.6551 7.58428C13.6414 7.56018 13.615 7.54771 13.5886 7.55187C12.1369 7.80955 10.7478 8.26092 9.45159 8.87438C9.44037 8.87937 9.43075 8.88769 9.42437 8.89849C6.78947 12.9558 6.06766 16.9134 6.42176 20.8219C6.42336 20.841 6.43378 20.8593 6.4482 20.871C8.18663 22.1868 9.87059 22.9857 11.5233 23.5152C11.5497 23.5235 11.5778 23.5135 11.5946 23.491C11.9855 22.9408 12.334 22.3606 12.6328 21.7504C12.6505 21.7147 12.6336 21.6723 12.5976 21.6581C12.0448 21.442 11.5185 21.1785 11.0122 20.8793C10.9721 20.8552 10.9689 20.7961 11.0058 20.7679C11.1123 20.6856 11.2189 20.6 11.3206 20.5135C11.339 20.4977 11.3647 20.4944 11.3863 20.5044C14.7125 22.0696 18.3136 22.0696 21.6006 20.5044C21.6222 20.4936 21.6479 20.4969 21.6671 20.5127C21.7688 20.5991 21.8754 20.6856 21.9827 20.7679C22.0196 20.7961 22.0172 20.8552 21.9771 20.8793C21.4708 21.1843 20.9445 21.442 20.3909 21.6573C20.3548 21.6715 20.3388 21.7147 20.3564 21.7504C20.6617 22.3597 21.0101 22.9399 21.3939 23.4902C21.4099 23.5135 21.4387 23.5235 21.4652 23.5152C23.1259 22.9857 24.8099 22.1868 26.5483 20.871C26.5635 20.8593 26.5731 20.8419 26.5747 20.8228C26.9985 16.3041 25.8649 12.3789 23.5697 8.89931C23.5641 8.88769 23.5545 8.87937 23.5433 8.87438Z",fill:"#F7F7F7"})]})}function Ot({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",className:e||"h-8 w-8",children:[jsx("rect",{width:"512",height:"512",rx:"15%",fill:"#37aee2"}),jsx("path",{fill:"#c8daea",d:"M199 404c-11 0-10-4-13-14l-32-105 245-144"}),jsx("path",{fill:"#a9c9dd",d:"M199 404c7 0 11-4 16-8l45-43-56-34"}),jsx("path",{fill:"#f6fbfe",d:"M204 319l135 99c14 9 26 4 30-14l55-258c5-22-9-32-24-25L79 245c-21 8-21 21-4 26l83 26 190-121c9-5 17-3 11 4"})]})}
1
+ import {clsx}from'clsx';import {twMerge}from'tailwind-merge';import {createContext,useState,useCallback,useEffect,useRef,useContext}from'react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';function Qe(...e){return twMerge(clsx(e))}function Ve(e){return e>=1e12?`${(e/1e12).toFixed(e%1e12===0?0:1)}T`:e>=1e9?`${(e/1e9).toFixed(e%1e9===0?0:1)}B`:e>=1e6?`${(e/1e6).toFixed(e%1e6===0?0:1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:e.toLocaleString()}function Ye(e,t){if(!e)return "/";if(e.startsWith("/")&&!e.startsWith("//"))return e;try{let s=new URL(e,t);return s.origin!==t?"/":s.pathname+s.search+s.hash}catch{return "/"}}function Ge(e){try{let t=e.split(".");if(t.length!==3)return null;let s=atob(t[1].replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(s)}catch{return null}}function oe(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(s=>s.trim()).find(s=>s.startsWith("stackauth_session="));if(!e)return null;let t=e.slice(18);return JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function j(e="__csrf"){if(typeof document>"u")return null;let t=document.cookie.split(";").map(s=>s.trim()).find(s=>s.startsWith(`${e}=`));return t?t.slice(e.length+1):null}function re(){let[e,t]=useState(null),[s,l]=useState(true),f=useCallback(()=>{let o=oe();o&&o.expiresAt>Date.now()?t({userId:o.userId,address:o.address,chain:o.chain,expiresAt:o.expiresAt,planId:o.planId,authMethod:o.authMethod}):t(null),l(false);},[]);useEffect(()=>{f();},[f]);let h=useCallback(async(o="")=>{try{let r=await fetch(`${o}/api/auth/session`);if(r.ok){let i=await r.json();if(i.session)return t(i.session),i.session}return t(null),null}catch{return null}},[]),m=!!e&&e.expiresAt>Date.now();return {session:e,loading:s,isAuthenticated:m,refresh:h,readSession:f}}function ae(e="__csrf",t="x-csrf-token"){let[s,l]=useState(null);useEffect(()=>{l(j(e));},[e]);let f=s?{[t]:s}:{};return {token:s,headers:f}}function ie(){let[e,t]=useState({connected:false,address:null,chain:null,provider:null}),[s,l]=useState(null),f=useCallback(async(r="phantom")=>{l(null);try{let i=typeof window<"u"?window:null,p=r==="phantom"?i?.phantom?.solana||i?.solana:i?.solflare;if(!p)return l(`${r} wallet not found`),null;let d=(await p.connect()).publicKey.toString();return t({connected:!0,address:d,chain:"solana",provider:r}),d}catch(i){return l(i.message||"Failed to connect wallet"),null}},[]),h=useCallback(async()=>{l(null);try{let i=(typeof window<"u"?window:null)?.ethereum;if(!i)return l("MetaMask not found"),null;let p=i;i.providers?.length&&(p=i.providers.find(n=>n.isMetaMask)||i);let d=(await p.request({method:"eth_requestAccounts"}))[0];return d?(t({connected:!0,address:d,chain:"ethereum",provider:"metamask"}),d):(l("No account selected"),null)}catch(r){return l(r.message||"Failed to connect wallet"),null}},[]),m=useCallback(async(r,i)=>{l(null);let p=i?.chain||e.chain,a=i?.provider||e.provider,d=i?.address||e.address;try{if(p==="solana"){let n=typeof window<"u"?window:null,c=a==="solflare"?n?.solflare:n?.phantom?.solana||n?.solana;if(!c)throw new Error("Wallet not available");let g=new TextEncoder().encode(r),b=await c.signMessage(g,"utf8"),L=b.signature||b,x="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",v=BigInt(0);for(let N of L)v=v*256n+BigInt(N);let M="";for(;v>0n;)M=x[Number(v%58n)]+M,v=v/58n;for(let N of L)if(N===0)M="1"+M;else break;return M}if(p==="ethereum"){let c=(typeof window<"u"?window:null)?.ethereum;if(c?.providers?.length&&(c=c.providers.find(b=>b.isMetaMask)||c),!c)throw new Error("MetaMask not available");return await c.request({method:"personal_sign",params:[r,d]})}throw new Error("No wallet connected")}catch(n){return l(n.message||"Signing failed"),null}},[e]),o=useCallback(()=>{t({connected:false,address:null,chain:null,provider:null}),l(null);},[]);return {wallet:e,error:s,connectSolana:f,connectEVM:h,signMessage:m,disconnect:o}}var et="https://stacknet.magma-rpc.com/auth/bridge",q="stacknet-auth-bridge";function ce(e){let t=e?.bridgeUrl||et,s=e?.disabled||false,l=useRef(null),[f,h]=useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),m=useRef([]),o=useRef(false),r=useCallback(n=>{let c={...n,protocol:q};o.current&&l.current?.contentWindow?l.current.contentWindow.postMessage(c,new URL(t).origin):m.current.push(c);},[t]);useEffect(()=>{if(s)return;let n=g=>{if(!(!g.data||g.data.protocol!==q)){try{if(g.origin!==new URL(t).origin)return}catch{return}switch(g.data.type){case "bridge:ready":o.current=true,h(b=>({...b,ready:true}));for(let b of m.current)l.current?.contentWindow?.postMessage(b,g.origin);m.current=[],l.current?.contentWindow?.postMessage({protocol:q,type:"auth:check"},g.origin),l.current?.contentWindow?.postMessage({protocol:q,type:"auth:resolve-stack"},g.origin);break;case "auth:status":h(b=>({...b,known:g.data.known,identity:g.data.identity,identityCount:g.data.identityCount||0}));break;case "auth:resolved-stack":h(b=>({...b,resolvedStackId:g.data.stackId||null}));break;}}};window.addEventListener("message",n);let c=document.createElement("iframe");return c.src=t,c.style.display="none",c.setAttribute("aria-hidden","true"),c.setAttribute("tabindex","-1"),c.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(c),l.current=c,()=>{window.removeEventListener("message",n),c.parentNode&&c.parentNode.removeChild(c),l.current=null,o.current=false;}},[t,s]);let i=useCallback(n=>{r({type:"auth:connected",...n});},[r]),p=useCallback(n=>{r({type:"auth:disconnected",...n});},[r]),a=useCallback(()=>{r({type:"auth:clear"}),h({ready:f.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[r,f.ready]),d=useCallback(()=>{r({type:"auth:check"});},[r]);return {...f,reportConnected:i,reportDisconnected:p,clearAll:a,refresh:d}}async function Ue(e,t,s,l){let f=e.apiVersion||"v2",h=`${e.baseUrl}/api/${f}${s}`;try{let m=await fetch(h,{method:t,headers:{"Content-Type":"application/json"},body:l?JSON.stringify(l):void 0}),o=await m.json();return m.ok?o.success&&o.data!==void 0?{success:!0,data:o.data}:{success:!0,data:o}:{success:!1,error:o.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(m){return {success:false,error:{code:"NETWORK_ERROR",message:m instanceof Error?m.message:"Network error"}}}}function de(e){return {getNetworkStatus:()=>Ue(e,"GET","/network/status"),getWeb3Challenge:(t,s)=>Ue(e,"POST",`/stacks/${e.stackId}/auth/web3/challenge`,{chain:t,address:s})}}function pe(e={apiBaseUrl:""}){let{wallet:t,connectSolana:s,connectEVM:l,signMessage:f,disconnect:h}=ie(),{session:m,isAuthenticated:o,refresh:r,readSession:i}=re(),{headers:p}=ae(),a=ce({disabled:typeof window>"u"}),[d,n]=useState(false),[c,g]=useState(null),[b,L]=useState(false),x=e.apiBaseUrl||"",v=e.stacknetUrl||"https://stacknet.magma-rpc.com",M=e.stackId||a.resolvedStackId||"",N=de({baseUrl:v,stackId:M}),I=useCallback(async(w,C,_,D)=>{n(true),g(null);try{let P=C;if(!P){let R=await _();if(!R)return n(!1),!1;P=R;}let O=await N.getWeb3Challenge(w,P);if(!O.success||!O.data)return g("Failed to get challenge"),n(!1),!1;let J=await f(O.data.message,{chain:w,provider:D,address:P});if(!J)return n(!1),!1;let $={chain:w,message:O.data.message,signature:J,stackId:M};w==="solana"&&($.publicKey=P);let E=await fetch(`${x}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)});if(!E.ok){let R=await E.json().catch(()=>({}));return g(R.error||"Authentication failed"),n(!1),!1}return a.reportConnected({address:P,chain:w,method:D||(w==="solana"?"phantom":"metamask"),stackId:M}),i(),n(!1),!0}catch(P){return g(P.message||"Authentication failed"),n(false),false}},[x,N,f,i,a,M]),T=useCallback(async(w="phantom")=>{let C=await s(w);return C?I("solana",C,()=>s(w),w):false},[s,I]),A=useCallback(async()=>{let w=await l();return w?I("ethereum",w,l,"metamask"):false},[l,I]),G=useCallback(async w=>{n(true),g(null);try{let C=await fetch(`${x}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:w})});if(!C.ok){let _=await C.json().catch(()=>({}));return g(_.error||"Invalid code"),n(!1),!1}return i(),n(!1),!0}catch(C){return g(C.message||"OTP verification failed"),n(false),false}},[x,i]),Z=useCallback(async()=>{t.address&&t.chain&&a.reportDisconnected({address:t.address,chain:t.chain,stackId:M});try{await fetch(`${x}/api/auth/logout`,{method:"POST",headers:p});}catch{}h(),i();},[x,p,h,i,t,a,M]);return useEffect(()=>{if(!e.autoConnect||b||o||!a.ready||!a.known||!a.identity)return;L(true);let{chain:w,method:C}=a.identity;w==="solana"&&(C==="phantom"||C==="solflare")?T(C):w==="ethereum"&&A();},[e.autoConnect,b,o,a,T,A]),{session:m,isAuthenticated:o,wallet:t,loading:d,error:c,authenticateSolana:T,authenticateEVM:A,authenticateOTP:G,logout:Z,refresh:()=>r(x),stackId:M,bridge:{ready:a.ready,known:a.known,identity:a.identity,identityCount:a.identityCount,resolvedStackId:a.resolvedStackId}}}function me(e,t="https://stacknet.magma-rpc.com"){let[s,l]=useState(null),[f,h]=useState(false),[m,o]=useState(null),r=useCallback(async p=>{h(true),o(null);try{let a=await fetch(`${t}/api/v2/stacks/${p}`);if(!a.ok)return o("Stack not found"),h(!1),null;let d=await a.json(),n=d.data?.stack||d.stack||d,c={id:n.id,name:n.name,displayName:n.displayName||n.name,description:n.description,logoUrl:n.logoUrl,webPageUrl:n.webPageUrl,allowedChains:n.allowedChains||[],features:n.features,stripeProvider:n.stripeProvider,oauthProviders:n.oauthProviders?.map(g=>({provider:g.provider,enabled:g.enabled!==!1}))};return l(c),h(!1),c}catch(a){return o(a.message),h(false),null}},[t]);useEffect(()=>{e&&r(e);},[e,r]);let i=s?ot(s):[];return {config:s,loading:f,error:m,identityProviders:i,fetchConfig:r}}function ot(e){let t=[];if(e.features?.web3Auth!==false&&(e.allowedChains.includes("solana")&&(t.push({type:"wallet",id:"phantom",name:"Phantom",chain:"solana"}),t.push({type:"wallet",id:"solflare",name:"Solflare",chain:"solana"})),(e.allowedChains.includes("ethereum")||e.allowedChains.includes("polygon")||e.allowedChains.includes("base"))&&t.push({type:"wallet",id:"metamask",name:"MetaMask",chain:"ethereum"})),e.features?.apiKeyAuth!==false&&t.push({type:"otp",id:"otp",name:"Access Code"}),e.features?.oauthAuth&&e.oauthProviders)for(let s of e.oauthProviders)s.enabled&&t.push({type:"oauth",id:s.provider,name:s.provider});return t}function it(e=""){let[t,s]=useState([]),[l,f]=useState(true),[h,m]=useState(null),o=useCallback(async()=>{try{let r=await fetch(`${e}/api/billing/plans`);if(r.ok){let i=await r.json();s(i.plans||i||[]);}}catch(r){m(r.message);}finally{f(false);}},[e]);return useEffect(()=>{o();},[o]),{plans:t,loading:l,error:h,refresh:o}}function ct(e=""){let[t,s]=useState(null),[l,f]=useState(true),[h,m]=useState(null),o=useCallback(async()=>{try{let p=await fetch(`${e}/api/billing/subscription`);if(p.ok){let a=await p.json();s(a.plan?a:null);}}catch(p){m(p.message);}finally{f(false);}},[e]);useEffect(()=>{o();},[o]);let r=useCallback(async p=>{let a=j(),n=await(await fetch(`${e}/api/billing/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-csrf-token":a}:{}},body:JSON.stringify({planId:p})})).json();return n.url||n.checkoutUrl||null},[e]),i=useCallback(async()=>{let p=j();return (await fetch(`${e}/api/billing/cancel`,{method:"POST",headers:p?{"x-csrf-token":p}:{}})).ok?(await o(),true):false},[e,o]);return {subscription:t,loading:l,error:h,refresh:o,subscribe:r,cancel:i}}function pt(e=""){let[t,s]=useState(null),[l,f]=useState(true),[h,m]=useState(null),o=useCallback(async()=>{try{let r=await fetch(`${e}/api/billing/usage`);if(r.ok){let i=await r.json();s(i);}}catch(r){m(r.message);}finally{f(false);}},[e]);return useEffect(()=>{o();},[o]),{usage:t,loading:l,error:h,refresh:o}}function ft(e=""){let[t,s]=useState(false),[l,f]=useState(null),h=useCallback(async o=>{s(true),f(null);try{let r=j(),i=await fetch(`${e}/api/billing/prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...r?{"x-csrf-token":r}:{}},body:JSON.stringify({amountCents:o})}),p=await i.json();return i.ok?p.url||null:(f(p.error||"Purchase failed"),null)}catch(r){return f(r.message),null}finally{s(false);}},[e]),m=useCallback(async o=>{s(true),f(null);try{let r=j(),i=await fetch(`${e}/api/billing/verify-prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...r?{"x-csrf-token":r}:{}},body:JSON.stringify({sessionId:o})}),p=await i.json();return i.ok?p:(f(p.error||"Verification failed"),null)}catch(r){return f(r.message),null}finally{s(false);}},[e]);return {purchase:h,verifySession:m,loading:t,error:l}}function ht(e="",t){let[s,l]=useState([]),[f,h]=useState(true),[m,o]=useState(null),r=t?.limit||50,i=t?.offset||0,p=useCallback(async()=>{try{let a=await fetch(`${e}/api/billing/history?limit=${r}&offset=${i}`);if(a.ok){let d=await a.json();l(d.records||d.history||(Array.isArray(d)?d:[]));}}catch(a){o(a.message);}finally{h(false);}},[e,r,i]);return useEffect(()=>{p();},[p]),{records:s,loading:f,error:m,refresh:p}}var Te=createContext(null);function wt(){let e=useContext(Te);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function bt({config:e,callbacks:t,children:s}){return jsx(Te.Provider,{value:{config:e,callbacks:t},children:s})}function X({length:e=6,onComplete:t,disabled:s=false,error:l,className:f="",inputClassName:h=""}){let [m,o]=useState(Array(e).fill("")),r=useCallback((a,d)=>{if(d.length>1){let c=d.replace(/\D/g,"").slice(0,e).split(""),g=[...m];c.forEach((L,x)=>{a+x<e&&(g[a+x]=L);}),o(g);let b=Math.min(a+c.length,e-1);document.getElementById(`userutils-otp-${b}`)?.focus(),g.every(L=>L!=="")&&setTimeout(()=>t(g.join("")),100);return}if(!/^\d?$/.test(d))return;let n=[...m];n[a]=d,o(n),d&&a<e-1&&document.getElementById(`userutils-otp-${a+1}`)?.focus(),d&&a===e-1&&n.every(c=>c!=="")&&setTimeout(()=>t(n.join("")),100);},[m,e,t]),i=useCallback((a,d)=>{if(d.key==="Backspace"&&!m[a]&&a>0){document.getElementById(`userutils-otp-${a-1}`)?.focus();let n=[...m];n[a-1]="",o(n);}if(d.key==="Enter"){let n=m.join("");n.length===e&&t(n);}},[m,e,t]);useCallback(()=>{o(Array(e).fill("")),document.getElementById("userutils-otp-0")?.focus();},[e]);return jsxs("div",{className:f,children:[jsx("div",{className:"flex gap-2 justify-center",children:m.map((a,d)=>jsx("input",{id:`userutils-otp-${d}`,type:"text",inputMode:"numeric",maxLength:e,value:a,onChange:n=>r(d,n.target.value),onKeyDown:n=>i(d,n),disabled:s,autoFocus:d===0,className:`w-12 h-14 text-center text-xl font-mono bg-secondary border border-primary/10 text-foreground focus:outline-none focus:border-primary/30 disabled:opacity-50 ${h}`},d))}),l&&jsx("p",{className:"text-center text-sm text-red-400 mt-2",children:l})]})}X.displayName="OTPInput";var Mt="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function ee({className:e}){return jsx("img",{src:Mt,alt:"Phantom",className:e})}function te({className:e}){return jsxs("svg",{className:e,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 507.83 470.86",children:[jsx("polygon",{fill:"#e2761b",stroke:"#e2761b",strokeLinecap:"round",strokeLinejoin:"round",points:"482.09 0.5 284.32 147.38 320.9 60.72 482.09 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"25.54 0.5 221.72 148.77 186.93 60.72 25.54 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"410.93 340.97 358.26 421.67 470.96 452.67 503.36 342.76 410.93 340.97"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"4.67 342.76 36.87 452.67 149.57 421.67 96.9 340.97 4.67 342.76"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 111.8 252.13 223.7 257.1 219.73 136.85 143.21 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"364.42 204.62 286.91 135.46 284.32 257.1 396.03 252.13 364.42 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 216.75 388.87 158.71 343.55 149.57 421.67"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 358.26 421.67 348.92 343.55 290.88 388.87"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"358.26 421.67 290.88 388.87 296.25 432.8 295.65 451.28 358.26 421.67"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 212.18 451.28 211.78 432.8 216.75 388.87 149.57 421.67"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"213.17 314.54 157.12 298.04 196.67 279.95 213.17 314.54"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"294.46 314.54 310.96 279.95 350.71 298.04 294.46 314.54"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 159.11 340.97 96.9 342.76 149.57 421.67"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"348.72 340.97 358.26 421.67 410.93 342.76 348.72 340.97"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"396.03 252.13 284.32 257.1 294.66 314.54 311.16 279.95 350.91 298.04 396.03 252.13"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 196.87 279.95 213.17 314.54 223.7 257.1 111.8 252.13 157.12 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"111.8 252.13 158.71 343.55 157.12 298.04 111.8 252.13"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"350.91 298.04 348.92 343.55 396.03 252.13 350.91 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"223.7 257.1 213.17 314.54 226.29 382.31 229.27 293.07 223.7 257.1"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 278.96 292.87 281.34 382.31 294.66 314.54 284.32 257.1"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"294.66 314.54 281.34 382.31 290.88 388.87 348.92 343.55 350.91 298.04 294.66 314.54"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 158.71 343.55 216.75 388.87 226.29 382.31 213.17 314.54 157.12 298.04"}),jsx("polygon",{fill:"#c0ad9e",stroke:"#c0ad9e",strokeLinecap:"round",strokeLinejoin:"round",points:"295.65 451.28 296.25 432.8 291.28 428.42 216.35 428.42 211.78 432.8 212.18 451.28 149.57 421.67 171.43 439.55 215.75 470.36 291.88 470.36 336.4 439.55 358.26 421.67 295.65 451.28"}),jsx("polygon",{fill:"#161616",stroke:"#161616",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 281.34 382.31 226.29 382.31 216.75 388.87 211.78 432.8 216.35 428.42 291.28 428.42 296.25 432.8 290.88 388.87"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"490.44 156.92 507.33 75.83 482.09 0.5 290.88 142.41 364.42 204.62 468.37 235.03 491.43 208.2 481.49 201.05 497.39 186.54 485.07 177 500.97 164.87 490.44 156.92"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"0.5 75.83 17.39 156.92 6.66 164.87 22.56 177 10.44 186.54 26.34 201.05 16.4 208.2 39.26 235.03 143.21 204.62 216.75 142.41 25.54 0.5 0.5 75.83"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"468.37 235.03 364.42 204.62 396.03 252.13 348.92 343.55 410.93 342.76 503.36 342.76 468.37 235.03"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 39.26 235.03 4.67 342.76 96.9 342.76 158.71 343.55 111.8 252.13 143.21 204.62"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 290.88 142.41 321.1 60.72 186.93 60.72 216.75 142.41 223.7 257.1 226.09 293.27 226.29 382.31 281.34 382.31 281.74 293.27 284.32 257.1"})]})}function Ne({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",className:e||"h-5 w-5",children:[jsxs("linearGradient",{id:"sol-g",x1:"7.233",x2:"24.766",y1:"24.766",y2:"7.234",gradientUnits:"userSpaceOnUse",children:[jsx("stop",{offset:"0",stopColor:"#9945ff"}),jsx("stop",{offset:"0.2",stopColor:"#7962e7"}),jsx("stop",{offset:"1",stopColor:"#00d18c"})]}),jsx("path",{fill:"#10111a",d:"M0 0h32v32H0z"}),jsx("path",{fill:"url(#sol-g)",fillRule:"evenodd",d:"M9.873 20.41a.65.65 0 0 1 .476-.21l14.662.012a.323.323 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54zm15.376-2.862a.322.322 0 0 1-.238.54l-14.662.012a.64.64 0 0 1-.476-.21l-3.122-3.44a.323.323 0 0 1 .238-.54l14.662-.012a.64.64 0 0 1 .475.21zM9.873 7.81a.64.64 0 0 1 .476-.21l14.662.012a.322.322 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54z",clipRule:"evenodd"})]})}function Me({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",className:e||"h-5 w-5",children:[jsx("rect",{width:"20",height:"20",rx:"4",fill:"#627EEA",fillOpacity:"0.2"}),jsx("path",{fill:"#627EEA",d:"M10 3l-4 6.5 4 2.5 4-2.5L10 3z"}),jsx("path",{fill:"#627EEA",fillOpacity:"0.6",d:"M6 9.5L10 12l4-2.5L10 17 6 9.5z"})]})}function Lt({config:e,onSuccess:t,title:s="Log in or Sign up",showWallets:l,showOTP:f,className:h=""}){let m=pe(e),{isAuthenticated:o,wallet:r,loading:i,error:p,authenticateSolana:a,authenticateEVM:d,authenticateOTP:n,bridge:c,stackId:g}=m,b=!e.stackId&&!g,L=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:x,identityProviders:v,loading:M}=me(g||e.stackId||null,L),[N,I]=useState(b?"stack-select":"select"),[T,A]=useState(null),[G,Z]=useState(false),[w,C]=useState("idle"),[_,D]=useState(""),[P,O]=useState([]),[J,$]=useState(e.stackId||null),[E,R]=useState(false),[Re,We]=useState(false);useEffect(()=>{if(typeof window>"u")return;let k=()=>{let W=window;R(!!(W.phantom?.solana?.isPhantom||W.solana?.isPhantom));let B=W.ethereum;We(!!(B?.isMetaMask||B?.providers?.some(H=>H.isMetaMask)));};k(),window.addEventListener("ethereum#initialized",k);let z=setTimeout(k,500);return ()=>{window.removeEventListener("ethereum#initialized",k),clearTimeout(z);}},[]),useEffect(()=>{N==="stack-select"&&g&&($(g),I("select"));},[N,g]),useEffect(()=>{if(!(!c.ready||!b)&&c.identity){let k=[];c.resolvedStackId&&k.push({stackId:c.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(k.map(async z=>{try{let W=await fetch(`${L}/api/v2/stacks/${z.stackId}`);if(W.ok){let B=await W.json(),H=B.data?.stack||B;z.name=H.displayName||H.name,z.logoUrl=H.logoUrl;}}catch{}return z})).then(O);}},[c.ready,c.identity,c.resolvedStackId,b,L]),useEffect(()=>{o&&N==="success"&&t?.();},[o,N,t]);let Se=l||(v.length>0?v.filter(k=>k.type==="wallet").map(k=>k.id):["phantom","metamask"]),ve=f!==void 0?f:v.length>0?v.some(k=>k.type==="otp"):true,_e=async()=>{A("phantom"),I("connecting");let k=await a("phantom");I(k?"success":"error");},$e=async()=>{A("metamask"),I("connecting");let k=await d();I(k?"success":"error");},Be=async k=>{C("verifying"),D(""),await n(k)?(C("success"),I("success")):(C("error"),D("Invalid or expired code"),setTimeout(()=>C("idle"),2e3));},Ie=()=>{I(b&&!J?"stack-select":"select"),A(null),Z(false),C("idle"),D("");};return jsxs("div",{className:`w-full max-w-md space-y-3 ${h}`,children:[jsxs("div",{className:"mb-6 text-center",children:[x?.logoUrl&&N!=="stack-select"&&jsx("img",{src:x.logoUrl,alt:"",className:"h-10 w-10 mx-auto mb-3"}),jsx("h1",{className:"font-semibold text-2xl text-white",children:s}),x?.displayName&&N!=="stack-select"&&jsx("p",{className:"text-sm text-zinc-400 mt-1",children:x.displayName})]}),N==="stack-select"&&jsxs("div",{className:"space-y-3",children:[jsx("p",{className:"text-center text-sm text-zinc-400 mb-4",children:P.length>0?"Select a network to continue":"No previous connections found. Enter a Stack ID to continue."}),P.map(k=>jsxs("button",{onClick:()=>{$(k.stackId),I("select");},className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[k.logoUrl?jsx("img",{src:k.logoUrl,alt:"",className:"h-10 w-10 flex-shrink-0"}):jsx("div",{className:"h-10 w-10 flex-shrink-0 bg-zinc-700 flex items-center justify-center text-zinc-400 text-sm font-mono",children:k.name?.[0]?.toUpperCase()||"S"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-white",children:k.name||k.stackId}),jsx("p",{className:"text-xs text-zinc-500",children:k.domain})]}),jsx("span",{className:"text-xs text-zinc-600",children:"Previously connected"})]},k.stackId)),c.ready&&!c.known&&jsx("p",{className:"text-center text-xs text-zinc-600 mt-4",children:"Connect to a stack for the first time to get started."})]}),N==="select"&&M&&jsx("div",{className:"flex items-center justify-center py-8",children:jsx("div",{className:"h-6 w-6 border-2 border-zinc-600 border-t-white animate-spin",style:{borderRadius:"50%"}})}),p&&N==="error"&&jsxs("div",{className:"mb-4 border border-red-500/30 bg-red-500/10 p-4",children:[jsx("p",{className:"text-center text-red-400 text-sm",children:p}),jsx("button",{className:"mt-3 w-full text-sm text-zinc-400 hover:text-white",onClick:Ie,children:"Try Again"})]}),N==="success"&&jsxs("div",{className:"border border-green-500/30 bg-green-500/10 p-6 text-center",children:[jsx("p",{className:"font-medium text-green-400 text-sm",children:"Connected!"}),jsx("p",{className:"mt-1 text-xs text-zinc-400",children:"Redirecting..."})]}),N==="connecting"&&i&&jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 text-center",children:[jsxs("div",{className:"mx-auto mb-3 h-14 w-14 animate-pulse",children:[T==="phantom"&&jsx(ee,{className:"h-14 w-14"}),T==="metamask"&&jsx(te,{className:"h-14 w-14"})]}),jsx("p",{className:"font-medium text-sm text-white",children:r.connected?"Signing message...":"Connecting wallet..."}),jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Please confirm in your wallet"}),jsx("button",{className:"mt-4 text-sm text-zinc-500 hover:text-white",onClick:Ie,children:"Cancel"})]}),N==="select"&&!i&&!M&&jsxs(Fragment,{children:[Se.includes("phantom")&&jsxs("button",{onClick:_e,disabled:!E,className:`flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a] ${E?"":"cursor-not-allowed opacity-50"}`,children:[jsx(ee,{className:"h-14 w-14 flex-shrink-0"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-lg text-white",children:"Phantom"}),!E&&jsx("p",{className:"text-xs text-zinc-500",children:"Not installed"})]}),jsx(Ne,{className:"h-8 w-8"})]}),Se.includes("metamask")&&Re&&jsxs("button",{onClick:$e,className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center bg-white p-2",children:jsx(te,{className:"h-10 w-10"})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white",children:"MetaMask"})}),jsx(Me,{className:"h-8 w-8"})]}),ve&&!G&&jsxs("button",{onClick:()=>Z(true),className:"flex w-full items-center gap-4 border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center border border-zinc-700 bg-[#2a2a3e]",children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"28px",viewBox:"0 -960 960 960",width:"28px",fill:"#e3e3e3",children:jsx("path",{d:"M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v480q0 33-23.5 56.5T800-160H160Z"})})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white",children:"Access Code"})})]}),ve&&G&&jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 space-y-4",children:[jsx("p",{className:"text-center text-sm text-zinc-400",children:"Enter your 6-digit access code"}),jsx(X,{onComplete:Be,disabled:w==="verifying",error:_}),w==="verifying"&&jsx("p",{className:"text-center text-sm text-zinc-400 animate-pulse",children:"Verifying..."}),w==="success"&&jsx("p",{className:"text-center text-sm text-green-400",children:"Verified!"}),x?.webPageUrl&&w==="idle"&&jsx("a",{href:`${x.webPageUrl}/connect/pair`,target:"_blank",rel:"noopener noreferrer",className:"block text-center text-sm text-zinc-500 hover:text-white transition-colors",children:"Get code"})]})]})]})}function jt({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"black"}),jsx("path",{d:"M8.53901 8L14.7164 16.2153L8.5 22.8947H9.89907L15.3415 17.0468L19.7389 22.8947H24.5L17.975 14.2173L23.7612 8H22.3621L17.3499 13.3858L13.3001 8H8.53901ZM10.5964 9.02501H12.7837L22.4422 21.8695H20.255L10.5964 9.02501Z",fill:"#F7F7F7"})]})}function At({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#F1F2F9"}),jsx("path",{d:"M26.1001 16.2273C26.1001 15.5182 26.0365 14.8364 25.9183 14.1818H16.5001V18.05H21.8819C21.6501 19.3 20.9456 20.3591 19.8865 21.0682V23.5773H23.1183C25.0092 21.8364 26.1001 19.2727 26.1001 16.2273Z",fill:"#4285F4"}),jsx("path",{d:"M16.5001 26C19.2001 26 21.4637 25.1046 23.1182 23.5773L19.8864 21.0682C18.991 21.6682 17.8455 22.0227 16.5001 22.0227C13.8955 22.0227 11.691 20.2637 10.9046 17.9H7.56372V20.4909C9.20917 23.7591 12.591 26 16.5001 26Z",fill:"#34A853"}),jsx("path",{d:"M10.9047 17.8999C10.7047 17.2999 10.591 16.659 10.591 15.9999C10.591 15.3408 10.7047 14.6999 10.9047 14.0999V11.509H7.56376C6.86376 12.9025 6.49951 14.4405 6.50012 15.9999C6.50012 17.6136 6.88649 19.1408 7.56376 20.4908L10.9047 17.8999Z",fill:"#FBBC05"}),jsx("path",{d:"M16.5001 9.97726C17.9682 9.97726 19.2864 10.4818 20.3228 11.4727L23.191 8.60454C21.4591 6.99091 19.1955 6 16.5001 6C12.591 6 9.20917 8.2409 7.56372 11.5091L10.9046 14.1C11.691 11.7364 13.8955 9.97726 16.5001 9.97726Z",fill:"#EA4335"})]})}function Tt({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#5462EB"}),jsx("path",{d:"M23.5433 8.87438C22.2479 8.26174 20.8587 7.81038 19.4063 7.55187C19.3799 7.54688 19.3534 7.55934 19.3398 7.58428C19.1612 7.91179 18.9633 8.33905 18.8247 8.67487C17.2625 8.43382 15.7084 8.43382 14.1782 8.67487C14.0396 8.33158 13.8345 7.91179 13.6551 7.58428C13.6414 7.56018 13.615 7.54771 13.5886 7.55187C12.1369 7.80955 10.7478 8.26092 9.45159 8.87438C9.44037 8.87937 9.43075 8.88769 9.42437 8.89849C6.78947 12.9558 6.06766 16.9134 6.42176 20.8219C6.42336 20.841 6.43378 20.8593 6.4482 20.871C8.18663 22.1868 9.87059 22.9857 11.5233 23.5152C11.5497 23.5235 11.5778 23.5135 11.5946 23.491C11.9855 22.9408 12.334 22.3606 12.6328 21.7504C12.6505 21.7147 12.6336 21.6723 12.5976 21.6581C12.0448 21.442 11.5185 21.1785 11.0122 20.8793C10.9721 20.8552 10.9689 20.7961 11.0058 20.7679C11.1123 20.6856 11.2189 20.6 11.3206 20.5135C11.339 20.4977 11.3647 20.4944 11.3863 20.5044C14.7125 22.0696 18.3136 22.0696 21.6006 20.5044C21.6222 20.4936 21.6479 20.4969 21.6671 20.5127C21.7688 20.5991 21.8754 20.6856 21.9827 20.7679C22.0196 20.7961 22.0172 20.8552 21.9771 20.8793C21.4708 21.1843 20.9445 21.442 20.3909 21.6573C20.3548 21.6715 20.3388 21.7147 20.3564 21.7504C20.6617 22.3597 21.0101 22.9399 21.3939 23.4902C21.4099 23.5135 21.4387 23.5235 21.4652 23.5152C23.1259 22.9857 24.8099 22.1868 26.5483 20.871C26.5635 20.8593 26.5731 20.8419 26.5747 20.8228C26.9985 16.3041 25.8649 12.3789 23.5697 8.89931C23.5641 8.88769 23.5545 8.87937 23.5433 8.87438Z",fill:"#F7F7F7"})]})}function Ot({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",className:e||"h-8 w-8",children:[jsx("rect",{width:"512",height:"512",rx:"15%",fill:"#37aee2"}),jsx("path",{fill:"#c8daea",d:"M199 404c-11 0-10-4-13-14l-32-105 245-144"}),jsx("path",{fill:"#a9c9dd",d:"M199 404c7 0 11-4 16-8l45-43-56-34"}),jsx("path",{fill:"#f6fbfe",d:"M204 319l135 99c14 9 26 4 30-14l55-258c5-22-9-32-24-25L79 245c-21 8-21 21-4 26l83 26 190-121c9-5 17-3 11 4"})]})}
2
2
  export{Lt as ConnectWidget,Tt as DiscordIcon,Me as EthereumIcon,At as GoogleIcon,te as MetaMaskIcon,X as OTPInput,ee as PhantomIcon,Ne as SolanaIcon,Ot as TelegramIcon,jt as TwitterIcon,bt as UserUtilsProvider,Qe as cn,de as createStackNetClient,Ge as decodeJwtPayloadClient,Ve as formatTokens,j as readCSRFCookie,oe as readSessionCookie,ce as useAuthBridge,ht as useBillingHistory,ae as useCSRFToken,it as usePlans,ft as usePrepaidCheckout,re as useSession,pe as useStackAuth,me as useStackConfig,ct as useSubscription,pt as useUsage,wt as useUserUtilsContext,ie as useWeb3Wallet,Ye as validateRedirectUrl};
@@ -1 +1 @@
1
- 'use strict';var crypto=require('crypto');function N(e){return Buffer.from(e).toString("base64url")}function z(e){return Buffer.from(e,"base64url").toString()}function b(e){try{let r=e.split(".");return r.length!==3?null:JSON.parse(z(r[1]))}catch{return null}}function P(e,r){let t=N(JSON.stringify({alg:"HS256",typ:"JWT"})),n=N(JSON.stringify(e)),s=crypto.createHmac("sha256",r).update(`${t}.${n}`).digest("base64url");return `${t}.${n}.${s}`}function W(e,r){try{let t=e.split(".");if(t.length!==3)return !1;let[n,s,o]=t,a=crypto.createHmac("sha256",r).update(`${n}.${s}`).digest("base64url"),f=Buffer.from(o),p=Buffer.from(a);return f.length!==p.length?!1:crypto.timingSafeEqual(f,p)}catch{return false}}function C(e,r){if(!W(e,r))return null;let t=b(e);return !t||t.exp&&t.exp<Math.floor(Date.now()/1e3)?null:t}function $(e,r,t=900,n=300){let s=C(e,r);return !s?.exp||s.exp*1e3-Date.now()>n*1e3?null:P({...s,exp:Math.floor(Date.now()/1e3)+t},r)}function D(e=32){return crypto.randomBytes(e).toString("hex")}function j(e){return e.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||e.headers.get("x-real-ip")||"unknown"}var Y="__csrf",Q="x-csrf-token";function x(e={}){let r=e.cookieName||Y,t=e.headerName||Q,n=e.tokenLength||32,s=e.secure!==false;return {generateToken(o){let a=D(n),f=[`${r}=${a}`,"Path=/","SameSite=Lax"];return s&&f.push("Secure"),o.append("Set-Cookie",f.join("; ")),a},validateRequest(o){let a=o.headers.get("cookie");if(!a)return {valid:false,error:"No cookies present"};let f=a.split(";").map(l=>l.trim()).find(l=>l.startsWith(`${r}=`))?.slice(r.length+1);if(!f)return {valid:false,error:"CSRF cookie missing"};let p=o.headers.get(t);if(!p)return {valid:false,error:"CSRF header missing"};try{let l=Buffer.from(f),u=Buffer.from(p);return l.length!==u.length?{valid:!1,error:"CSRF token mismatch"}:crypto.timingSafeEqual(l,u)?{valid:!0}:{valid:!1,error:"CSRF token mismatch"}}catch{return {valid:false,error:"CSRF validation failed"}}},cookieName:r,headerName:t}}function w(e){let r=new Map,t=setInterval(()=>{let n=Date.now();for(let[s,o]of r)n>=o.resetAt&&r.delete(s);},6e4);return typeof t=="object"&&"unref"in t&&t.unref(),{async check(n){let s=Date.now(),o=r.get(n);return (!o||s>=o.resetAt)&&(o={count:0,resetAt:s+e.windowMs},r.set(n,o)),o.count++,o.count>e.maxRequests?{allowed:false,remaining:0,retryAfter:Math.ceil((o.resetAt-s)/1e3)}:{allowed:true,remaining:e.maxRequests-o.count}}}}function Z(){let e=new Map,r=setInterval(()=>{let t=Date.now();for(let[n,s]of e)t>=s&&e.delete(n);},6e4);return typeof r=="object"&&"unref"in r&&r.unref(),{async has(t){let n=e.get(t);return n?Date.now()>=n?(e.delete(t),false):true:false},async set(t,n){e.set(t,Date.now()+n*1e3);}}}function ee(e,r){let t=r?.rateLimiter||w({maxRequests:10,windowMs:6e4}),n=x({secure:e.secureCookies!==false}),s=e.jwtExpiry||900,o=e.sessionMaxAge||604800;e.stacknetJwtSecret||e.authSecret;return async function(p){let l=j(p),u=await t.check(`auth:${l}`);if(!u.allowed)return Response.json({error:"Too many login attempts. Please wait."},{status:429,headers:{"Retry-After":String(u.retryAfter||60)}});let i;try{i=await p.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{chain:c,message:d,signature:m,publicKey:y,otp:g,code:k,redirectUrl:T}=i,h;if(c&&d&&m){let G={"Content-Type":"application/json"},M=await fetch(`${e.stacknetUrl}/api/v2/stacks/${e.stackId}/auth/web3/verify`,{method:"POST",headers:G,body:JSON.stringify({chain:c,message:d,signature:m,public_key:y}),signal:AbortSignal.timeout(1e4)});if(!M.ok){await M.json().catch(()=>({}));return Response.json({error:"Wallet verification failed"},{status:401})}let O=await M.json();h=O.data?.session||O.session||O.data||O;}else return g||k?Response.json({error:"Use /api/auth/otp for OTP verification"},{status:400}):Response.json({error:"Provide wallet signature or OTP code"},{status:400});if(!h?.jwt)return Response.json({error:"Authentication failed \u2014 no session returned"},{status:401});let S=JSON.parse(Buffer.from(h.jwt.split(".")[1],"base64url").toString()),H=Math.floor(Date.now()/1e3),v={...S,exp:H+s,iat:H},U=P(v,e.authSecret),L={userId:S.sub||S.user_id||S.session_id||S.global_id||"",address:h.address||S.address,chain:h.chain||c,expiresAt:Date.now()+o*1e3,authMethod:c?`web3:${c}`:"otp"},A=new Headers({"Content-Type":"application/json"}),I=e.secureCookies!==false?"; Secure":"",E=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";A.append("Set-Cookie",`stackauth_jwt=${U}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${I}${E}`);let F=Buffer.from(JSON.stringify(L)).toString("base64url");return A.append("Set-Cookie",`stackauth_session=${F}; Path=/; SameSite=Lax; Max-Age=${o}${I}${E}`),n.generateToken(A),new Response(JSON.stringify({user:L}),{status:200,headers:A})}}function B(e,r){if(!r)return null;try{let t=b(e);if(!t||t.exp&&t.exp<Math.floor(Date.now()/1e3))return null;let n=Buffer.from(JSON.stringify({alg:"HS256",typ:"JWT"})).toString("base64url"),s=Buffer.from(JSON.stringify(t)).toString("base64url"),o=crypto.createHmac("sha256",r).update(`${n}.${s}`).digest("base64url");return `${n}.${s}.${o}`}catch{return null}}function J(e,r){let t=B(e,r);return t?{Cookie:`stackauth_jwt=${t}`}:{Cookie:`stackauth_jwt=${e}`}}function R(e){let r=e.headers.get("cookie");if(r){let n=r.split(";").map(s=>s.trim()).find(s=>s.startsWith("stackauth_jwt="));if(n)return n.slice(14)}let t=e.headers.get("authorization");return t?.startsWith("Bearer ")?t.slice(7):null}function re(e){return async function(t){let n=R(t);if(n){let f=b(n),p=f?.session_id||f?.sub;if(p)try{await fetch(`${e.stacknetUrl}/api/v2/sessions/${p}`,{method:"DELETE",signal:AbortSignal.timeout(5e3)});}catch{}}let s=e.secureCookies!==false?"; Secure":"",o=e.cookieDomain?`; Domain=${e.cookieDomain}`:"",a=new Headers({"Content-Type":"application/json"});return a.append("Set-Cookie",`stackauth_jwt=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${s}${o}`),a.append("Set-Cookie",`stackauth_session=; Path=/; SameSite=Lax; Max-Age=0${s}${o}`),a.append("Set-Cookie",`__csrf=; Path=/; SameSite=Lax; Max-Age=0${s}${o}`),new Response(JSON.stringify({success:true}),{status:200,headers:a})}}function se(e){let r=e.jwtExpiry||900,t=e.sessionMaxAge||604800;return async function(s){let o=R(s);if(!o)return Response.json({session:null},{status:200});let a=C(o,e.authSecret);if(!a)return Response.json({session:null},{status:200});let p={userId:a.sub||a.user_id||a.session_id||a.global_id||"",address:a.address,chain:a.chain,expiresAt:a.session_expires_at||(a.exp?a.exp*1e3:Date.now()+t*1e3),planId:a.plan_id,authMethod:a.auth_method},l=new Headers({"Content-Type":"application/json"}),u=$(o,e.authSecret,r,300);if(u){let i=e.secureCookies!==false?"; Secure":"",c=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";l.append("Set-Cookie",`stackauth_jwt=${u}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${t}${i}${c}`);}return new Response(JSON.stringify({session:p}),{status:200,headers:l})}}function ae(e,r){if(e.length!==r.length)return false;try{return crypto.timingSafeEqual(Buffer.from(e),Buffer.from(r))}catch{return false}}function ie(e){let r=e.rateLimiter||w({maxRequests:5,windowMs:3e5}),t=x({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,s=e.sessionMaxAge||604800;return async function(a){let f=j(a),p=await r.check(`otp:${f}`);if(!p.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(p.retryAfter||300)}});let l;try{l=await a.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{code:u}=l;if(!u||typeof u!="string"||u.length!==6)return Response.json({error:"Invalid code format"},{status:400});if(!ae(u,e.otpSecret))return Response.json({error:"Invalid code"},{status:401});let i=Math.floor(Date.now()/1e3),d={sub:`otp:${crypto.createHash("sha256").update(`otp:${u}:${Date.now()}`).digest("hex").slice(0,32)}`,auth_method:"otp",iat:i,exp:i+n},m=P(d,e.authSecret),y={userId:d.sub,expiresAt:Date.now()+s*1e3,authMethod:"otp"},g=new Headers({"Content-Type":"application/json"}),k=e.secureCookies!==false?"; Secure":"",T=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";g.append("Set-Cookie",`stackauth_jwt=${m}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${s}${k}${T}`);let h=Buffer.from(JSON.stringify(y)).toString("base64url");return g.append("Set-Cookie",`stackauth_session=${h}; Path=/; SameSite=Lax; Max-Age=${s}${k}${T}`),t.generateToken(g),new Response(JSON.stringify({success:true,data:{user:y}}),{status:200,headers:g})}}function ce(e){let r=x({secure:e.secureCookies!==false}),t=e.rateLimiter||w({maxRequests:20,windowMs:6e4}),n=e.stacknetJwtSecret||e.authSecret,s=e.jwtExpiry||900,o=e.sessionMaxAge||604800;function a(i){let c=R(i);if(!c)return null;let d=C(c,e.authSecret);return d?{jwt:c,payload:d}:null}function f(i,c){let d=$(i,e.authSecret,s,300);if(d){let m=e.secureCookies!==false?"; Secure":"",y=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";c.append("Set-Cookie",`stackauth_jwt=${d}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${m}${y}`);}}async function p(i,c){let d=a(i);if(!d)return Response.json({error:"Unauthorized"},{status:401});let m=J(d.jwt,n),y=await fetch(`${e.stacknetUrl}${c}`,{headers:m,signal:AbortSignal.timeout(15e3)}),g=await y.json().catch(()=>({})),k=new Headers({"Content-Type":"application/json"});return f(d.jwt,k),new Response(JSON.stringify(g),{status:y.status,headers:k})}async function l(i,c,d){let m=a(i);if(!m)return Response.json({error:"Unauthorized"},{status:401});let y=r.validateRequest(i);if(!y.valid)return Response.json({error:y.error||"CSRF validation failed"},{status:403});let g=m.payload.sub||m.payload.user_id||"unknown";if(!(await t.check(`billing:${g}`)).allowed)return Response.json({error:"Too many requests"},{status:429});let T=await i.json().catch(()=>({})),h=J(m.jwt,n);h["Content-Type"]="application/json";let S=await fetch(`${e.stacknetUrl}${c}`,{method:"POST",headers:h,body:JSON.stringify({...T,...d}),signal:AbortSignal.timeout(15e3)}),H=await S.json().catch(()=>({})),v=new Headers({"Content-Type":"application/json"});return f(m.jwt,v),new Response(JSON.stringify(H),{status:S.status,headers:v})}let u=`/api/v2/stacks/${e.stackId}`;return {plans:{GET:async i=>{let c=await fetch(`${e.stacknetUrl}${u}/plans`,{signal:AbortSignal.timeout(1e4)}),d=await c.json().catch(()=>({}));return Response.json(d,{status:c.status})}},subscription:{GET:(i=>p(i,`${u}/subscription`))},subscribe:{POST:(i=>{let c=new URL(i.url).origin;return l(i,`${u}/subscribe`,{successUrl:`${c}/billing/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${c}/pricing`})})},cancel:{POST:(i=>l(i,`${u}/cancel-subscription`))},usage:{GET:(i=>p(i,"/v1/account/usage"))},history:{GET:(i=>p(i,`${u}/billing`))},prepaid:{POST:(i=>{let c=new URL(i.url).origin;return l(i,`${u}/prepaid`,{successUrl:`${c}/pricing/prepaid/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${c}/pricing/prepaid`})})},verifyPrepaid:{POST:(i=>l(i,`${u}/verify-prepaid`))},verifySession:{POST:(i=>l(i,`${u}/verify-session`))}}}function ue(e){return async function(t){let n=t.headers.get("stripe-signature");if(!n)return Response.json({error:"Missing Stripe signature"},{status:400});try{let s=await t.text(),o=await fetch(`${e.stacknetUrl}/api/v2/stacks/${e.stackId}/webhook/stripe`,{method:"POST",headers:{"Content-Type":"application/json","stripe-signature":n},body:s,signal:AbortSignal.timeout(1e4)}),a=await o.json().catch(()=>({received:!0}));return Response.json(a,{status:o.status})}catch{return Response.json({error:"Webhook processing failed"},{status:502})}}}function _(){return {"Strict-Transport-Security":"max-age=63072000; includeSubDomains; preload","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","X-XSS-Protection":"0","Referrer-Policy":"strict-origin-when-cross-origin","Permissions-Policy":"camera=(), microphone=(), geolocation=()"}}function pe(e){return async r=>{let t=await e(r),n=_(),s=new Headers(t.headers);for(let[o,a]of Object.entries(n))s.set(o,a);return new Response(t.body,{status:t.status,statusText:t.statusText,headers:s})}}function le(){return Object.entries(_()).map(([e,r])=>({key:e,value:r}))}exports.buildStackNetHeaders=J;exports.createAuthCallback=ee;exports.createBillingProxy=ce;exports.createCSRFProtection=x;exports.createInMemoryRateLimiter=w;exports.createInMemoryReplayStore=Z;exports.createLogoutHandler=re;exports.createOTPHandler=ie;exports.createSessionHandler=se;exports.createWebhookHandler=ue;exports.decodeJWTPayload=b;exports.extractIP=j;exports.extractJwt=R;exports.generateToken=D;exports.maybeRefreshJWT=$;exports.nextSecurityHeaders=le;exports.resignForStackNet=B;exports.securityHeaders=_;exports.signJWT=P;exports.verifyJWT=C;exports.verifyJWTSignature=W;exports.withSecurityHeaders=pe;
1
+ 'use strict';var crypto=require('crypto');function B(e){return Buffer.from(e).toString("base64url")}function Z(e){return Buffer.from(e,"base64url").toString()}function P(e){try{let r=e.split(".");return r.length!==3?null:JSON.parse(Z(r[1]))}catch{return null}}function $(e,r){let t=B(JSON.stringify({alg:"HS256",typ:"JWT"})),n=B(JSON.stringify(e)),s=crypto.createHmac("sha256",r).update(`${t}.${n}`).digest("base64url");return `${t}.${n}.${s}`}function F(e,r){try{let t=e.split(".");if(t.length!==3)return !1;let[n,s,o]=t,a=crypto.createHmac("sha256",r).update(`${n}.${s}`).digest("base64url"),f=Buffer.from(o),p=Buffer.from(a);return f.length!==p.length?!1:crypto.timingSafeEqual(f,p)}catch{return false}}function C(e,r){if(!F(e,r))return null;let t=P(e);return !t||t.exp&&t.exp<Math.floor(Date.now()/1e3)?null:t}function H(e,r,t=900,n=300){let s=C(e,r);return !s?.exp||s.exp*1e3-Date.now()>n*1e3?null:$({...s,exp:Math.floor(Date.now()/1e3)+t},r)}function I(e=32){return crypto.randomBytes(e).toString("hex")}function v(e){return e.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||e.headers.get("x-real-ip")||"unknown"}var te="__csrf",re="x-csrf-token";function x(e={}){let r=e.cookieName||te,t=e.headerName||re,n=e.tokenLength||32,s=e.secure!==false;return {generateToken(o){let a=I(n),f=[`${r}=${a}`,"Path=/","SameSite=Lax"];return s&&f.push("Secure"),o.append("Set-Cookie",f.join("; ")),a},validateRequest(o){let a=o.headers.get("cookie");if(!a)return {valid:false,error:"No cookies present"};let f=a.split(";").map(l=>l.trim()).find(l=>l.startsWith(`${r}=`))?.slice(r.length+1);if(!f)return {valid:false,error:"CSRF cookie missing"};let p=o.headers.get(t);if(!p)return {valid:false,error:"CSRF header missing"};try{let l=Buffer.from(f),u=Buffer.from(p);return l.length!==u.length?{valid:!1,error:"CSRF token mismatch"}:crypto.timingSafeEqual(l,u)?{valid:!0}:{valid:!1,error:"CSRF token mismatch"}}catch{return {valid:false,error:"CSRF validation failed"}}},cookieName:r,headerName:t}}function w(e){let r=new Map,t=setInterval(()=>{let n=Date.now();for(let[s,o]of r)n>=o.resetAt&&r.delete(s);},6e4);return typeof t=="object"&&"unref"in t&&t.unref(),{async check(n){let s=Date.now(),o=r.get(n);return (!o||s>=o.resetAt)&&(o={count:0,resetAt:s+e.windowMs},r.set(n,o)),o.count++,o.count>e.maxRequests?{allowed:false,remaining:0,retryAfter:Math.ceil((o.resetAt-s)/1e3)}:{allowed:true,remaining:e.maxRequests-o.count}}}}function se(){let e=new Map,r=setInterval(()=>{let t=Date.now();for(let[n,s]of e)t>=s&&e.delete(n);},6e4);return typeof r=="object"&&"unref"in r&&r.unref(),{async has(t){let n=e.get(t);return n?Date.now()>=n?(e.delete(t),false):true:false},async set(t,n){e.set(t,Date.now()+n*1e3);}}}function ne(e,r){let t=r?.rateLimiter||w({maxRequests:10,windowMs:6e4}),n=x({secure:e.secureCookies!==false}),s=e.jwtExpiry||900,o=e.sessionMaxAge||604800;e.stacknetJwtSecret||e.authSecret;return async function(p){let l=v(p),u=await t.check(`auth:${l}`);if(!u.allowed)return Response.json({error:"Too many login attempts. Please wait."},{status:429,headers:{"Retry-After":String(u.retryAfter||60)}});let i;try{i=await p.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{chain:c,message:d,signature:m,publicKey:y,otp:g,code:S,redirectUrl:T,stackId:b}=i,O=b||e.stackId,k;if(c&&d&&m){let z={"Content-Type":"application/json"},j=await fetch(`${e.stacknetUrl}/api/v2/stacks/${O}/auth/web3/verify`,{method:"POST",headers:z,body:JSON.stringify({chain:c,message:d,signature:m,public_key:y}),signal:AbortSignal.timeout(1e4)});if(!j.ok){let D=await j.json().catch(()=>({})),_=D?.error?.message||D?.message||D?.error||`StackNet returned ${j.status}`;return console.error(`[auth-callback] Verify failed: ${j.status}`,_),Response.json({error:"Wallet verification failed",detail:typeof _=="string"?_:void 0},{status:401})}let J=await j.json();k=J.data?.session||J.session||J.data||J,console.log(`[auth-callback] Verify OK, sessionData keys: ${Object.keys(k||{}).join(", ")}`);}else return g||S?Response.json({error:"Use /api/auth/otp for OTP verification"},{status:400}):Response.json({error:"Provide wallet signature or OTP code"},{status:400});if(!k?.jwt)return Response.json({error:"Authentication failed \u2014 no session returned"},{status:401});let h=JSON.parse(Buffer.from(k.jwt.split(".")[1],"base64url").toString()),N=Math.floor(Date.now()/1e3),K={...h,exp:N+s,iat:N},V=$(K,e.authSecret),E={userId:h.sub||h.user_id||h.session_id||h.global_id||"",address:k.address||h.address,chain:k.chain||c,expiresAt:Date.now()+o*1e3,authMethod:c?`web3:${c}`:"otp"},A=new Headers({"Content-Type":"application/json"}),q=e.secureCookies!==false?"; Secure":"",W=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";A.append("Set-Cookie",`stackauth_jwt=${V}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${q}${W}`);let X=Buffer.from(JSON.stringify(E)).toString("base64url");return A.append("Set-Cookie",`stackauth_session=${X}; Path=/; SameSite=Lax; Max-Age=${o}${q}${W}`),n.generateToken(A),new Response(JSON.stringify({user:E}),{status:200,headers:A})}}function G(e,r){if(!r)return null;try{let t=P(e);if(!t||t.exp&&t.exp<Math.floor(Date.now()/1e3))return null;let n=Buffer.from(JSON.stringify({alg:"HS256",typ:"JWT"})).toString("base64url"),s=Buffer.from(JSON.stringify(t)).toString("base64url"),o=crypto.createHmac("sha256",r).update(`${n}.${s}`).digest("base64url");return `${n}.${s}.${o}`}catch{return null}}function M(e,r){let t=G(e,r);return t?{Cookie:`stackauth_jwt=${t}`}:{Cookie:`stackauth_jwt=${e}`}}function R(e){let r=e.headers.get("cookie");if(r){let n=r.split(";").map(s=>s.trim()).find(s=>s.startsWith("stackauth_jwt="));if(n)return n.slice(14)}let t=e.headers.get("authorization");return t?.startsWith("Bearer ")?t.slice(7):null}function ae(e){return async function(t){let n=R(t);if(n){let f=P(n),p=f?.session_id||f?.sub;if(p)try{await fetch(`${e.stacknetUrl}/api/v2/sessions/${p}`,{method:"DELETE",signal:AbortSignal.timeout(5e3)});}catch{}}let s=e.secureCookies!==false?"; Secure":"",o=e.cookieDomain?`; Domain=${e.cookieDomain}`:"",a=new Headers({"Content-Type":"application/json"});return a.append("Set-Cookie",`stackauth_jwt=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${s}${o}`),a.append("Set-Cookie",`stackauth_session=; Path=/; SameSite=Lax; Max-Age=0${s}${o}`),a.append("Set-Cookie",`__csrf=; Path=/; SameSite=Lax; Max-Age=0${s}${o}`),new Response(JSON.stringify({success:true}),{status:200,headers:a})}}function ie(e){let r=e.jwtExpiry||900,t=e.sessionMaxAge||604800;return async function(s){let o=R(s);if(!o)return Response.json({session:null},{status:200});let a=C(o,e.authSecret);if(!a)return Response.json({session:null},{status:200});let p={userId:a.sub||a.user_id||a.session_id||a.global_id||"",address:a.address,chain:a.chain,expiresAt:a.session_expires_at||(a.exp?a.exp*1e3:Date.now()+t*1e3),planId:a.plan_id,authMethod:a.auth_method},l=new Headers({"Content-Type":"application/json"}),u=H(o,e.authSecret,r,300);if(u){let i=e.secureCookies!==false?"; Secure":"",c=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";l.append("Set-Cookie",`stackauth_jwt=${u}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${t}${i}${c}`);}return new Response(JSON.stringify({session:p}),{status:200,headers:l})}}function pe(e,r){if(e.length!==r.length)return false;try{return crypto.timingSafeEqual(Buffer.from(e),Buffer.from(r))}catch{return false}}function le(e){let r=e.rateLimiter||w({maxRequests:5,windowMs:3e5}),t=x({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,s=e.sessionMaxAge||604800;return async function(a){let f=v(a),p=await r.check(`otp:${f}`);if(!p.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(p.retryAfter||300)}});let l;try{l=await a.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{code:u}=l;if(!u||typeof u!="string"||u.length!==6)return Response.json({error:"Invalid code format"},{status:400});if(!pe(u,e.otpSecret))return Response.json({error:"Invalid code"},{status:401});let i=Math.floor(Date.now()/1e3),d={sub:`otp:${crypto.createHash("sha256").update(`otp:${u}:${Date.now()}`).digest("hex").slice(0,32)}`,auth_method:"otp",iat:i,exp:i+n},m=$(d,e.authSecret),y={userId:d.sub,expiresAt:Date.now()+s*1e3,authMethod:"otp"},g=new Headers({"Content-Type":"application/json"}),S=e.secureCookies!==false?"; Secure":"",T=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";g.append("Set-Cookie",`stackauth_jwt=${m}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${s}${S}${T}`);let b=Buffer.from(JSON.stringify(y)).toString("base64url");return g.append("Set-Cookie",`stackauth_session=${b}; Path=/; SameSite=Lax; Max-Age=${s}${S}${T}`),t.generateToken(g),new Response(JSON.stringify({success:true,data:{user:y}}),{status:200,headers:g})}}function de(e){let r=x({secure:e.secureCookies!==false}),t=e.rateLimiter||w({maxRequests:20,windowMs:6e4}),n=e.stacknetJwtSecret||e.authSecret,s=e.jwtExpiry||900,o=e.sessionMaxAge||604800;function a(i){let c=R(i);if(!c)return null;let d=C(c,e.authSecret);return d?{jwt:c,payload:d}:null}function f(i,c){let d=H(i,e.authSecret,s,300);if(d){let m=e.secureCookies!==false?"; Secure":"",y=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";c.append("Set-Cookie",`stackauth_jwt=${d}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${m}${y}`);}}async function p(i,c){let d=a(i);if(!d)return Response.json({error:"Unauthorized"},{status:401});let m=M(d.jwt,n),y=await fetch(`${e.stacknetUrl}${c}`,{headers:m,signal:AbortSignal.timeout(15e3)}),g=await y.json().catch(()=>({})),S=new Headers({"Content-Type":"application/json"});return f(d.jwt,S),new Response(JSON.stringify(g),{status:y.status,headers:S})}async function l(i,c,d){let m=a(i);if(!m)return Response.json({error:"Unauthorized"},{status:401});let y=r.validateRequest(i);if(!y.valid)return Response.json({error:y.error||"CSRF validation failed"},{status:403});let g=m.payload.sub||m.payload.user_id||"unknown";if(!(await t.check(`billing:${g}`)).allowed)return Response.json({error:"Too many requests"},{status:429});let T=await i.json().catch(()=>({})),b=M(m.jwt,n);b["Content-Type"]="application/json";let O=await fetch(`${e.stacknetUrl}${c}`,{method:"POST",headers:b,body:JSON.stringify({...T,...d}),signal:AbortSignal.timeout(15e3)}),k=await O.json().catch(()=>({})),h=new Headers({"Content-Type":"application/json"});return f(m.jwt,h),new Response(JSON.stringify(k),{status:O.status,headers:h})}let u=`/api/v2/stacks/${e.stackId}`;return {plans:{GET:async i=>{let c=await fetch(`${e.stacknetUrl}${u}/plans`,{signal:AbortSignal.timeout(1e4)}),d=await c.json().catch(()=>({}));return Response.json(d,{status:c.status})}},subscription:{GET:(i=>p(i,`${u}/subscription`))},subscribe:{POST:(i=>{let c=new URL(i.url).origin;return l(i,`${u}/subscribe`,{successUrl:`${c}/billing/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${c}/pricing`})})},cancel:{POST:(i=>l(i,`${u}/cancel-subscription`))},usage:{GET:(i=>p(i,"/v1/account/usage"))},history:{GET:(i=>p(i,`${u}/billing`))},prepaid:{POST:(i=>{let c=new URL(i.url).origin;return l(i,`${u}/prepaid`,{successUrl:`${c}/pricing/prepaid/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${c}/pricing/prepaid`})})},verifyPrepaid:{POST:(i=>l(i,`${u}/verify-prepaid`))},verifySession:{POST:(i=>l(i,`${u}/verify-session`))}}}function fe(e){return async function(t){let n=t.headers.get("stripe-signature");if(!n)return Response.json({error:"Missing Stripe signature"},{status:400});try{let s=await t.text(),o=await fetch(`${e.stacknetUrl}/api/v2/stacks/${e.stackId}/webhook/stripe`,{method:"POST",headers:{"Content-Type":"application/json","stripe-signature":n},body:s,signal:AbortSignal.timeout(1e4)}),a=await o.json().catch(()=>({received:!0}));return Response.json(a,{status:o.status})}catch{return Response.json({error:"Webhook processing failed"},{status:502})}}}function L(){return {"Strict-Transport-Security":"max-age=63072000; includeSubDomains; preload","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","X-XSS-Protection":"0","Referrer-Policy":"strict-origin-when-cross-origin","Permissions-Policy":"camera=(), microphone=(), geolocation=()"}}function me(e){return async r=>{let t=await e(r),n=L(),s=new Headers(t.headers);for(let[o,a]of Object.entries(n))s.set(o,a);return new Response(t.body,{status:t.status,statusText:t.statusText,headers:s})}}function ye(){return Object.entries(L()).map(([e,r])=>({key:e,value:r}))}exports.buildStackNetHeaders=M;exports.createAuthCallback=ne;exports.createBillingProxy=de;exports.createCSRFProtection=x;exports.createInMemoryRateLimiter=w;exports.createInMemoryReplayStore=se;exports.createLogoutHandler=ae;exports.createOTPHandler=le;exports.createSessionHandler=ie;exports.createWebhookHandler=fe;exports.decodeJWTPayload=P;exports.extractIP=v;exports.extractJwt=R;exports.generateToken=I;exports.maybeRefreshJWT=H;exports.nextSecurityHeaders=ye;exports.resignForStackNet=G;exports.securityHeaders=L;exports.signJWT=$;exports.verifyJWT=C;exports.verifyJWTSignature=F;exports.withSecurityHeaders=me;
@@ -1 +1 @@
1
- import {createHmac,timingSafeEqual,randomBytes,createHash}from'crypto';function N(e){return Buffer.from(e).toString("base64url")}function z(e){return Buffer.from(e,"base64url").toString()}function b(e){try{let r=e.split(".");return r.length!==3?null:JSON.parse(z(r[1]))}catch{return null}}function P(e,r){let t=N(JSON.stringify({alg:"HS256",typ:"JWT"})),n=N(JSON.stringify(e)),s=createHmac("sha256",r).update(`${t}.${n}`).digest("base64url");return `${t}.${n}.${s}`}function W(e,r){try{let t=e.split(".");if(t.length!==3)return !1;let[n,s,o]=t,a=createHmac("sha256",r).update(`${n}.${s}`).digest("base64url"),f=Buffer.from(o),p=Buffer.from(a);return f.length!==p.length?!1:timingSafeEqual(f,p)}catch{return false}}function C(e,r){if(!W(e,r))return null;let t=b(e);return !t||t.exp&&t.exp<Math.floor(Date.now()/1e3)?null:t}function $(e,r,t=900,n=300){let s=C(e,r);return !s?.exp||s.exp*1e3-Date.now()>n*1e3?null:P({...s,exp:Math.floor(Date.now()/1e3)+t},r)}function D(e=32){return randomBytes(e).toString("hex")}function j(e){return e.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||e.headers.get("x-real-ip")||"unknown"}var Y="__csrf",Q="x-csrf-token";function x(e={}){let r=e.cookieName||Y,t=e.headerName||Q,n=e.tokenLength||32,s=e.secure!==false;return {generateToken(o){let a=D(n),f=[`${r}=${a}`,"Path=/","SameSite=Lax"];return s&&f.push("Secure"),o.append("Set-Cookie",f.join("; ")),a},validateRequest(o){let a=o.headers.get("cookie");if(!a)return {valid:false,error:"No cookies present"};let f=a.split(";").map(l=>l.trim()).find(l=>l.startsWith(`${r}=`))?.slice(r.length+1);if(!f)return {valid:false,error:"CSRF cookie missing"};let p=o.headers.get(t);if(!p)return {valid:false,error:"CSRF header missing"};try{let l=Buffer.from(f),u=Buffer.from(p);return l.length!==u.length?{valid:!1,error:"CSRF token mismatch"}:timingSafeEqual(l,u)?{valid:!0}:{valid:!1,error:"CSRF token mismatch"}}catch{return {valid:false,error:"CSRF validation failed"}}},cookieName:r,headerName:t}}function w(e){let r=new Map,t=setInterval(()=>{let n=Date.now();for(let[s,o]of r)n>=o.resetAt&&r.delete(s);},6e4);return typeof t=="object"&&"unref"in t&&t.unref(),{async check(n){let s=Date.now(),o=r.get(n);return (!o||s>=o.resetAt)&&(o={count:0,resetAt:s+e.windowMs},r.set(n,o)),o.count++,o.count>e.maxRequests?{allowed:false,remaining:0,retryAfter:Math.ceil((o.resetAt-s)/1e3)}:{allowed:true,remaining:e.maxRequests-o.count}}}}function Z(){let e=new Map,r=setInterval(()=>{let t=Date.now();for(let[n,s]of e)t>=s&&e.delete(n);},6e4);return typeof r=="object"&&"unref"in r&&r.unref(),{async has(t){let n=e.get(t);return n?Date.now()>=n?(e.delete(t),false):true:false},async set(t,n){e.set(t,Date.now()+n*1e3);}}}function ee(e,r){let t=r?.rateLimiter||w({maxRequests:10,windowMs:6e4}),n=x({secure:e.secureCookies!==false}),s=e.jwtExpiry||900,o=e.sessionMaxAge||604800;e.stacknetJwtSecret||e.authSecret;return async function(p){let l=j(p),u=await t.check(`auth:${l}`);if(!u.allowed)return Response.json({error:"Too many login attempts. Please wait."},{status:429,headers:{"Retry-After":String(u.retryAfter||60)}});let i;try{i=await p.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{chain:c,message:d,signature:m,publicKey:y,otp:g,code:k,redirectUrl:T}=i,h;if(c&&d&&m){let G={"Content-Type":"application/json"},M=await fetch(`${e.stacknetUrl}/api/v2/stacks/${e.stackId}/auth/web3/verify`,{method:"POST",headers:G,body:JSON.stringify({chain:c,message:d,signature:m,public_key:y}),signal:AbortSignal.timeout(1e4)});if(!M.ok){await M.json().catch(()=>({}));return Response.json({error:"Wallet verification failed"},{status:401})}let O=await M.json();h=O.data?.session||O.session||O.data||O;}else return g||k?Response.json({error:"Use /api/auth/otp for OTP verification"},{status:400}):Response.json({error:"Provide wallet signature or OTP code"},{status:400});if(!h?.jwt)return Response.json({error:"Authentication failed \u2014 no session returned"},{status:401});let S=JSON.parse(Buffer.from(h.jwt.split(".")[1],"base64url").toString()),H=Math.floor(Date.now()/1e3),v={...S,exp:H+s,iat:H},U=P(v,e.authSecret),L={userId:S.sub||S.user_id||S.session_id||S.global_id||"",address:h.address||S.address,chain:h.chain||c,expiresAt:Date.now()+o*1e3,authMethod:c?`web3:${c}`:"otp"},A=new Headers({"Content-Type":"application/json"}),I=e.secureCookies!==false?"; Secure":"",E=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";A.append("Set-Cookie",`stackauth_jwt=${U}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${I}${E}`);let F=Buffer.from(JSON.stringify(L)).toString("base64url");return A.append("Set-Cookie",`stackauth_session=${F}; Path=/; SameSite=Lax; Max-Age=${o}${I}${E}`),n.generateToken(A),new Response(JSON.stringify({user:L}),{status:200,headers:A})}}function B(e,r){if(!r)return null;try{let t=b(e);if(!t||t.exp&&t.exp<Math.floor(Date.now()/1e3))return null;let n=Buffer.from(JSON.stringify({alg:"HS256",typ:"JWT"})).toString("base64url"),s=Buffer.from(JSON.stringify(t)).toString("base64url"),o=createHmac("sha256",r).update(`${n}.${s}`).digest("base64url");return `${n}.${s}.${o}`}catch{return null}}function J(e,r){let t=B(e,r);return t?{Cookie:`stackauth_jwt=${t}`}:{Cookie:`stackauth_jwt=${e}`}}function R(e){let r=e.headers.get("cookie");if(r){let n=r.split(";").map(s=>s.trim()).find(s=>s.startsWith("stackauth_jwt="));if(n)return n.slice(14)}let t=e.headers.get("authorization");return t?.startsWith("Bearer ")?t.slice(7):null}function re(e){return async function(t){let n=R(t);if(n){let f=b(n),p=f?.session_id||f?.sub;if(p)try{await fetch(`${e.stacknetUrl}/api/v2/sessions/${p}`,{method:"DELETE",signal:AbortSignal.timeout(5e3)});}catch{}}let s=e.secureCookies!==false?"; Secure":"",o=e.cookieDomain?`; Domain=${e.cookieDomain}`:"",a=new Headers({"Content-Type":"application/json"});return a.append("Set-Cookie",`stackauth_jwt=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${s}${o}`),a.append("Set-Cookie",`stackauth_session=; Path=/; SameSite=Lax; Max-Age=0${s}${o}`),a.append("Set-Cookie",`__csrf=; Path=/; SameSite=Lax; Max-Age=0${s}${o}`),new Response(JSON.stringify({success:true}),{status:200,headers:a})}}function se(e){let r=e.jwtExpiry||900,t=e.sessionMaxAge||604800;return async function(s){let o=R(s);if(!o)return Response.json({session:null},{status:200});let a=C(o,e.authSecret);if(!a)return Response.json({session:null},{status:200});let p={userId:a.sub||a.user_id||a.session_id||a.global_id||"",address:a.address,chain:a.chain,expiresAt:a.session_expires_at||(a.exp?a.exp*1e3:Date.now()+t*1e3),planId:a.plan_id,authMethod:a.auth_method},l=new Headers({"Content-Type":"application/json"}),u=$(o,e.authSecret,r,300);if(u){let i=e.secureCookies!==false?"; Secure":"",c=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";l.append("Set-Cookie",`stackauth_jwt=${u}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${t}${i}${c}`);}return new Response(JSON.stringify({session:p}),{status:200,headers:l})}}function ae(e,r){if(e.length!==r.length)return false;try{return timingSafeEqual(Buffer.from(e),Buffer.from(r))}catch{return false}}function ie(e){let r=e.rateLimiter||w({maxRequests:5,windowMs:3e5}),t=x({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,s=e.sessionMaxAge||604800;return async function(a){let f=j(a),p=await r.check(`otp:${f}`);if(!p.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(p.retryAfter||300)}});let l;try{l=await a.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{code:u}=l;if(!u||typeof u!="string"||u.length!==6)return Response.json({error:"Invalid code format"},{status:400});if(!ae(u,e.otpSecret))return Response.json({error:"Invalid code"},{status:401});let i=Math.floor(Date.now()/1e3),d={sub:`otp:${createHash("sha256").update(`otp:${u}:${Date.now()}`).digest("hex").slice(0,32)}`,auth_method:"otp",iat:i,exp:i+n},m=P(d,e.authSecret),y={userId:d.sub,expiresAt:Date.now()+s*1e3,authMethod:"otp"},g=new Headers({"Content-Type":"application/json"}),k=e.secureCookies!==false?"; Secure":"",T=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";g.append("Set-Cookie",`stackauth_jwt=${m}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${s}${k}${T}`);let h=Buffer.from(JSON.stringify(y)).toString("base64url");return g.append("Set-Cookie",`stackauth_session=${h}; Path=/; SameSite=Lax; Max-Age=${s}${k}${T}`),t.generateToken(g),new Response(JSON.stringify({success:true,data:{user:y}}),{status:200,headers:g})}}function ce(e){let r=x({secure:e.secureCookies!==false}),t=e.rateLimiter||w({maxRequests:20,windowMs:6e4}),n=e.stacknetJwtSecret||e.authSecret,s=e.jwtExpiry||900,o=e.sessionMaxAge||604800;function a(i){let c=R(i);if(!c)return null;let d=C(c,e.authSecret);return d?{jwt:c,payload:d}:null}function f(i,c){let d=$(i,e.authSecret,s,300);if(d){let m=e.secureCookies!==false?"; Secure":"",y=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";c.append("Set-Cookie",`stackauth_jwt=${d}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${m}${y}`);}}async function p(i,c){let d=a(i);if(!d)return Response.json({error:"Unauthorized"},{status:401});let m=J(d.jwt,n),y=await fetch(`${e.stacknetUrl}${c}`,{headers:m,signal:AbortSignal.timeout(15e3)}),g=await y.json().catch(()=>({})),k=new Headers({"Content-Type":"application/json"});return f(d.jwt,k),new Response(JSON.stringify(g),{status:y.status,headers:k})}async function l(i,c,d){let m=a(i);if(!m)return Response.json({error:"Unauthorized"},{status:401});let y=r.validateRequest(i);if(!y.valid)return Response.json({error:y.error||"CSRF validation failed"},{status:403});let g=m.payload.sub||m.payload.user_id||"unknown";if(!(await t.check(`billing:${g}`)).allowed)return Response.json({error:"Too many requests"},{status:429});let T=await i.json().catch(()=>({})),h=J(m.jwt,n);h["Content-Type"]="application/json";let S=await fetch(`${e.stacknetUrl}${c}`,{method:"POST",headers:h,body:JSON.stringify({...T,...d}),signal:AbortSignal.timeout(15e3)}),H=await S.json().catch(()=>({})),v=new Headers({"Content-Type":"application/json"});return f(m.jwt,v),new Response(JSON.stringify(H),{status:S.status,headers:v})}let u=`/api/v2/stacks/${e.stackId}`;return {plans:{GET:async i=>{let c=await fetch(`${e.stacknetUrl}${u}/plans`,{signal:AbortSignal.timeout(1e4)}),d=await c.json().catch(()=>({}));return Response.json(d,{status:c.status})}},subscription:{GET:(i=>p(i,`${u}/subscription`))},subscribe:{POST:(i=>{let c=new URL(i.url).origin;return l(i,`${u}/subscribe`,{successUrl:`${c}/billing/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${c}/pricing`})})},cancel:{POST:(i=>l(i,`${u}/cancel-subscription`))},usage:{GET:(i=>p(i,"/v1/account/usage"))},history:{GET:(i=>p(i,`${u}/billing`))},prepaid:{POST:(i=>{let c=new URL(i.url).origin;return l(i,`${u}/prepaid`,{successUrl:`${c}/pricing/prepaid/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${c}/pricing/prepaid`})})},verifyPrepaid:{POST:(i=>l(i,`${u}/verify-prepaid`))},verifySession:{POST:(i=>l(i,`${u}/verify-session`))}}}function ue(e){return async function(t){let n=t.headers.get("stripe-signature");if(!n)return Response.json({error:"Missing Stripe signature"},{status:400});try{let s=await t.text(),o=await fetch(`${e.stacknetUrl}/api/v2/stacks/${e.stackId}/webhook/stripe`,{method:"POST",headers:{"Content-Type":"application/json","stripe-signature":n},body:s,signal:AbortSignal.timeout(1e4)}),a=await o.json().catch(()=>({received:!0}));return Response.json(a,{status:o.status})}catch{return Response.json({error:"Webhook processing failed"},{status:502})}}}function _(){return {"Strict-Transport-Security":"max-age=63072000; includeSubDomains; preload","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","X-XSS-Protection":"0","Referrer-Policy":"strict-origin-when-cross-origin","Permissions-Policy":"camera=(), microphone=(), geolocation=()"}}function pe(e){return async r=>{let t=await e(r),n=_(),s=new Headers(t.headers);for(let[o,a]of Object.entries(n))s.set(o,a);return new Response(t.body,{status:t.status,statusText:t.statusText,headers:s})}}function le(){return Object.entries(_()).map(([e,r])=>({key:e,value:r}))}export{J as buildStackNetHeaders,ee as createAuthCallback,ce as createBillingProxy,x as createCSRFProtection,w as createInMemoryRateLimiter,Z as createInMemoryReplayStore,re as createLogoutHandler,ie as createOTPHandler,se as createSessionHandler,ue as createWebhookHandler,b as decodeJWTPayload,j as extractIP,R as extractJwt,D as generateToken,$ as maybeRefreshJWT,le as nextSecurityHeaders,B as resignForStackNet,_ as securityHeaders,P as signJWT,C as verifyJWT,W as verifyJWTSignature,pe as withSecurityHeaders};
1
+ import {createHmac,timingSafeEqual,randomBytes,createHash}from'crypto';function B(e){return Buffer.from(e).toString("base64url")}function Z(e){return Buffer.from(e,"base64url").toString()}function P(e){try{let r=e.split(".");return r.length!==3?null:JSON.parse(Z(r[1]))}catch{return null}}function $(e,r){let t=B(JSON.stringify({alg:"HS256",typ:"JWT"})),n=B(JSON.stringify(e)),s=createHmac("sha256",r).update(`${t}.${n}`).digest("base64url");return `${t}.${n}.${s}`}function F(e,r){try{let t=e.split(".");if(t.length!==3)return !1;let[n,s,o]=t,a=createHmac("sha256",r).update(`${n}.${s}`).digest("base64url"),f=Buffer.from(o),p=Buffer.from(a);return f.length!==p.length?!1:timingSafeEqual(f,p)}catch{return false}}function C(e,r){if(!F(e,r))return null;let t=P(e);return !t||t.exp&&t.exp<Math.floor(Date.now()/1e3)?null:t}function H(e,r,t=900,n=300){let s=C(e,r);return !s?.exp||s.exp*1e3-Date.now()>n*1e3?null:$({...s,exp:Math.floor(Date.now()/1e3)+t},r)}function I(e=32){return randomBytes(e).toString("hex")}function v(e){return e.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||e.headers.get("x-real-ip")||"unknown"}var te="__csrf",re="x-csrf-token";function x(e={}){let r=e.cookieName||te,t=e.headerName||re,n=e.tokenLength||32,s=e.secure!==false;return {generateToken(o){let a=I(n),f=[`${r}=${a}`,"Path=/","SameSite=Lax"];return s&&f.push("Secure"),o.append("Set-Cookie",f.join("; ")),a},validateRequest(o){let a=o.headers.get("cookie");if(!a)return {valid:false,error:"No cookies present"};let f=a.split(";").map(l=>l.trim()).find(l=>l.startsWith(`${r}=`))?.slice(r.length+1);if(!f)return {valid:false,error:"CSRF cookie missing"};let p=o.headers.get(t);if(!p)return {valid:false,error:"CSRF header missing"};try{let l=Buffer.from(f),u=Buffer.from(p);return l.length!==u.length?{valid:!1,error:"CSRF token mismatch"}:timingSafeEqual(l,u)?{valid:!0}:{valid:!1,error:"CSRF token mismatch"}}catch{return {valid:false,error:"CSRF validation failed"}}},cookieName:r,headerName:t}}function w(e){let r=new Map,t=setInterval(()=>{let n=Date.now();for(let[s,o]of r)n>=o.resetAt&&r.delete(s);},6e4);return typeof t=="object"&&"unref"in t&&t.unref(),{async check(n){let s=Date.now(),o=r.get(n);return (!o||s>=o.resetAt)&&(o={count:0,resetAt:s+e.windowMs},r.set(n,o)),o.count++,o.count>e.maxRequests?{allowed:false,remaining:0,retryAfter:Math.ceil((o.resetAt-s)/1e3)}:{allowed:true,remaining:e.maxRequests-o.count}}}}function se(){let e=new Map,r=setInterval(()=>{let t=Date.now();for(let[n,s]of e)t>=s&&e.delete(n);},6e4);return typeof r=="object"&&"unref"in r&&r.unref(),{async has(t){let n=e.get(t);return n?Date.now()>=n?(e.delete(t),false):true:false},async set(t,n){e.set(t,Date.now()+n*1e3);}}}function ne(e,r){let t=r?.rateLimiter||w({maxRequests:10,windowMs:6e4}),n=x({secure:e.secureCookies!==false}),s=e.jwtExpiry||900,o=e.sessionMaxAge||604800;e.stacknetJwtSecret||e.authSecret;return async function(p){let l=v(p),u=await t.check(`auth:${l}`);if(!u.allowed)return Response.json({error:"Too many login attempts. Please wait."},{status:429,headers:{"Retry-After":String(u.retryAfter||60)}});let i;try{i=await p.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{chain:c,message:d,signature:m,publicKey:y,otp:g,code:S,redirectUrl:T,stackId:b}=i,O=b||e.stackId,k;if(c&&d&&m){let z={"Content-Type":"application/json"},j=await fetch(`${e.stacknetUrl}/api/v2/stacks/${O}/auth/web3/verify`,{method:"POST",headers:z,body:JSON.stringify({chain:c,message:d,signature:m,public_key:y}),signal:AbortSignal.timeout(1e4)});if(!j.ok){let D=await j.json().catch(()=>({})),_=D?.error?.message||D?.message||D?.error||`StackNet returned ${j.status}`;return console.error(`[auth-callback] Verify failed: ${j.status}`,_),Response.json({error:"Wallet verification failed",detail:typeof _=="string"?_:void 0},{status:401})}let J=await j.json();k=J.data?.session||J.session||J.data||J,console.log(`[auth-callback] Verify OK, sessionData keys: ${Object.keys(k||{}).join(", ")}`);}else return g||S?Response.json({error:"Use /api/auth/otp for OTP verification"},{status:400}):Response.json({error:"Provide wallet signature or OTP code"},{status:400});if(!k?.jwt)return Response.json({error:"Authentication failed \u2014 no session returned"},{status:401});let h=JSON.parse(Buffer.from(k.jwt.split(".")[1],"base64url").toString()),N=Math.floor(Date.now()/1e3),K={...h,exp:N+s,iat:N},V=$(K,e.authSecret),E={userId:h.sub||h.user_id||h.session_id||h.global_id||"",address:k.address||h.address,chain:k.chain||c,expiresAt:Date.now()+o*1e3,authMethod:c?`web3:${c}`:"otp"},A=new Headers({"Content-Type":"application/json"}),q=e.secureCookies!==false?"; Secure":"",W=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";A.append("Set-Cookie",`stackauth_jwt=${V}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${q}${W}`);let X=Buffer.from(JSON.stringify(E)).toString("base64url");return A.append("Set-Cookie",`stackauth_session=${X}; Path=/; SameSite=Lax; Max-Age=${o}${q}${W}`),n.generateToken(A),new Response(JSON.stringify({user:E}),{status:200,headers:A})}}function G(e,r){if(!r)return null;try{let t=P(e);if(!t||t.exp&&t.exp<Math.floor(Date.now()/1e3))return null;let n=Buffer.from(JSON.stringify({alg:"HS256",typ:"JWT"})).toString("base64url"),s=Buffer.from(JSON.stringify(t)).toString("base64url"),o=createHmac("sha256",r).update(`${n}.${s}`).digest("base64url");return `${n}.${s}.${o}`}catch{return null}}function M(e,r){let t=G(e,r);return t?{Cookie:`stackauth_jwt=${t}`}:{Cookie:`stackauth_jwt=${e}`}}function R(e){let r=e.headers.get("cookie");if(r){let n=r.split(";").map(s=>s.trim()).find(s=>s.startsWith("stackauth_jwt="));if(n)return n.slice(14)}let t=e.headers.get("authorization");return t?.startsWith("Bearer ")?t.slice(7):null}function ae(e){return async function(t){let n=R(t);if(n){let f=P(n),p=f?.session_id||f?.sub;if(p)try{await fetch(`${e.stacknetUrl}/api/v2/sessions/${p}`,{method:"DELETE",signal:AbortSignal.timeout(5e3)});}catch{}}let s=e.secureCookies!==false?"; Secure":"",o=e.cookieDomain?`; Domain=${e.cookieDomain}`:"",a=new Headers({"Content-Type":"application/json"});return a.append("Set-Cookie",`stackauth_jwt=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${s}${o}`),a.append("Set-Cookie",`stackauth_session=; Path=/; SameSite=Lax; Max-Age=0${s}${o}`),a.append("Set-Cookie",`__csrf=; Path=/; SameSite=Lax; Max-Age=0${s}${o}`),new Response(JSON.stringify({success:true}),{status:200,headers:a})}}function ie(e){let r=e.jwtExpiry||900,t=e.sessionMaxAge||604800;return async function(s){let o=R(s);if(!o)return Response.json({session:null},{status:200});let a=C(o,e.authSecret);if(!a)return Response.json({session:null},{status:200});let p={userId:a.sub||a.user_id||a.session_id||a.global_id||"",address:a.address,chain:a.chain,expiresAt:a.session_expires_at||(a.exp?a.exp*1e3:Date.now()+t*1e3),planId:a.plan_id,authMethod:a.auth_method},l=new Headers({"Content-Type":"application/json"}),u=H(o,e.authSecret,r,300);if(u){let i=e.secureCookies!==false?"; Secure":"",c=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";l.append("Set-Cookie",`stackauth_jwt=${u}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${t}${i}${c}`);}return new Response(JSON.stringify({session:p}),{status:200,headers:l})}}function pe(e,r){if(e.length!==r.length)return false;try{return timingSafeEqual(Buffer.from(e),Buffer.from(r))}catch{return false}}function le(e){let r=e.rateLimiter||w({maxRequests:5,windowMs:3e5}),t=x({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,s=e.sessionMaxAge||604800;return async function(a){let f=v(a),p=await r.check(`otp:${f}`);if(!p.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(p.retryAfter||300)}});let l;try{l=await a.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{code:u}=l;if(!u||typeof u!="string"||u.length!==6)return Response.json({error:"Invalid code format"},{status:400});if(!pe(u,e.otpSecret))return Response.json({error:"Invalid code"},{status:401});let i=Math.floor(Date.now()/1e3),d={sub:`otp:${createHash("sha256").update(`otp:${u}:${Date.now()}`).digest("hex").slice(0,32)}`,auth_method:"otp",iat:i,exp:i+n},m=$(d,e.authSecret),y={userId:d.sub,expiresAt:Date.now()+s*1e3,authMethod:"otp"},g=new Headers({"Content-Type":"application/json"}),S=e.secureCookies!==false?"; Secure":"",T=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";g.append("Set-Cookie",`stackauth_jwt=${m}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${s}${S}${T}`);let b=Buffer.from(JSON.stringify(y)).toString("base64url");return g.append("Set-Cookie",`stackauth_session=${b}; Path=/; SameSite=Lax; Max-Age=${s}${S}${T}`),t.generateToken(g),new Response(JSON.stringify({success:true,data:{user:y}}),{status:200,headers:g})}}function de(e){let r=x({secure:e.secureCookies!==false}),t=e.rateLimiter||w({maxRequests:20,windowMs:6e4}),n=e.stacknetJwtSecret||e.authSecret,s=e.jwtExpiry||900,o=e.sessionMaxAge||604800;function a(i){let c=R(i);if(!c)return null;let d=C(c,e.authSecret);return d?{jwt:c,payload:d}:null}function f(i,c){let d=H(i,e.authSecret,s,300);if(d){let m=e.secureCookies!==false?"; Secure":"",y=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";c.append("Set-Cookie",`stackauth_jwt=${d}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${m}${y}`);}}async function p(i,c){let d=a(i);if(!d)return Response.json({error:"Unauthorized"},{status:401});let m=M(d.jwt,n),y=await fetch(`${e.stacknetUrl}${c}`,{headers:m,signal:AbortSignal.timeout(15e3)}),g=await y.json().catch(()=>({})),S=new Headers({"Content-Type":"application/json"});return f(d.jwt,S),new Response(JSON.stringify(g),{status:y.status,headers:S})}async function l(i,c,d){let m=a(i);if(!m)return Response.json({error:"Unauthorized"},{status:401});let y=r.validateRequest(i);if(!y.valid)return Response.json({error:y.error||"CSRF validation failed"},{status:403});let g=m.payload.sub||m.payload.user_id||"unknown";if(!(await t.check(`billing:${g}`)).allowed)return Response.json({error:"Too many requests"},{status:429});let T=await i.json().catch(()=>({})),b=M(m.jwt,n);b["Content-Type"]="application/json";let O=await fetch(`${e.stacknetUrl}${c}`,{method:"POST",headers:b,body:JSON.stringify({...T,...d}),signal:AbortSignal.timeout(15e3)}),k=await O.json().catch(()=>({})),h=new Headers({"Content-Type":"application/json"});return f(m.jwt,h),new Response(JSON.stringify(k),{status:O.status,headers:h})}let u=`/api/v2/stacks/${e.stackId}`;return {plans:{GET:async i=>{let c=await fetch(`${e.stacknetUrl}${u}/plans`,{signal:AbortSignal.timeout(1e4)}),d=await c.json().catch(()=>({}));return Response.json(d,{status:c.status})}},subscription:{GET:(i=>p(i,`${u}/subscription`))},subscribe:{POST:(i=>{let c=new URL(i.url).origin;return l(i,`${u}/subscribe`,{successUrl:`${c}/billing/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${c}/pricing`})})},cancel:{POST:(i=>l(i,`${u}/cancel-subscription`))},usage:{GET:(i=>p(i,"/v1/account/usage"))},history:{GET:(i=>p(i,`${u}/billing`))},prepaid:{POST:(i=>{let c=new URL(i.url).origin;return l(i,`${u}/prepaid`,{successUrl:`${c}/pricing/prepaid/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${c}/pricing/prepaid`})})},verifyPrepaid:{POST:(i=>l(i,`${u}/verify-prepaid`))},verifySession:{POST:(i=>l(i,`${u}/verify-session`))}}}function fe(e){return async function(t){let n=t.headers.get("stripe-signature");if(!n)return Response.json({error:"Missing Stripe signature"},{status:400});try{let s=await t.text(),o=await fetch(`${e.stacknetUrl}/api/v2/stacks/${e.stackId}/webhook/stripe`,{method:"POST",headers:{"Content-Type":"application/json","stripe-signature":n},body:s,signal:AbortSignal.timeout(1e4)}),a=await o.json().catch(()=>({received:!0}));return Response.json(a,{status:o.status})}catch{return Response.json({error:"Webhook processing failed"},{status:502})}}}function L(){return {"Strict-Transport-Security":"max-age=63072000; includeSubDomains; preload","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","X-XSS-Protection":"0","Referrer-Policy":"strict-origin-when-cross-origin","Permissions-Policy":"camera=(), microphone=(), geolocation=()"}}function me(e){return async r=>{let t=await e(r),n=L(),s=new Headers(t.headers);for(let[o,a]of Object.entries(n))s.set(o,a);return new Response(t.body,{status:t.status,statusText:t.statusText,headers:s})}}function ye(){return Object.entries(L()).map(([e,r])=>({key:e,value:r}))}export{M as buildStackNetHeaders,ne as createAuthCallback,de as createBillingProxy,x as createCSRFProtection,w as createInMemoryRateLimiter,se as createInMemoryReplayStore,ae as createLogoutHandler,le as createOTPHandler,ie as createSessionHandler,fe as createWebhookHandler,P as decodeJWTPayload,v as extractIP,R as extractJwt,I as generateToken,H as maybeRefreshJWT,ye as nextSecurityHeaders,G as resignForStackNet,L as securityHeaders,$ as signJWT,C as verifyJWT,F as verifyJWTSignature,me as withSecurityHeaders};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stacknet/userutils",
3
- "version": "0.2.4",
3
+ "version": "0.2.41",
4
4
  "description": "Reusable auth, billing, and security utilities for StackNet stacks and applications",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",