@stacknet/userutils 0.5.6 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/index.d.cts +2 -2
- package/dist/adapters/index.d.ts +2 -2
- package/dist/{auth-DR2aYcor.d.cts → auth-c1d7Eji2.d.cts} +6 -0
- package/dist/{auth-DR2aYcor.d.ts → auth-c1d7Eji2.d.ts} +6 -0
- package/dist/components/index.cjs +2 -2
- package/dist/components/index.d.cts +25 -3
- package/dist/components/index.d.ts +25 -3
- package/dist/components/index.js +2 -2
- package/dist/config-CLzVWDrU.d.cts +177 -0
- package/dist/config-xNca5ufB.d.ts +177 -0
- package/dist/core/index.d.cts +3 -3
- package/dist/core/index.d.ts +3 -3
- package/dist/hooks/index.cjs +2 -2
- package/dist/hooks/index.d.cts +52 -3
- package/dist/hooks/index.d.ts +52 -3
- package/dist/hooks/index.js +2 -2
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2 -2
- package/dist/server/index.cjs +2 -2
- package/dist/server/index.d.cts +116 -21
- package/dist/server/index.d.ts +116 -21
- package/dist/server/index.js +2 -2
- package/dist/types/index.d.cts +2 -2
- package/dist/types/index.d.ts +2 -2
- package/dist/{types-CAoB_5kk.d.cts → types-B_Vj6cr4.d.cts} +1 -1
- package/dist/{types-Dghy_8Wh.d.ts → types-Cu0do-w-.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/config-Bjh8PEhY.d.cts +0 -123
- package/dist/config-_ZjAzNkJ.d.ts +0 -123
package/dist/components/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {createContext,useContext,useState,useCallback,useEffect,useRef}from'react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var De=createContext(null);function dt(){let e=useContext(De);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function ut({config:e,callbacks:t,children:r}){return jsx(De.Provider,{value:{config:e,callbacks:t},children:r})}function ze(){let[e,t]=useState({connected:false,address:null,chain:null,provider:null}),[r,i]=useState(null),C=useCallback(async(f="phantom")=>{i(null);try{let d=typeof window<"u"?window:null,x=f==="phantom"?d?.phantom?.solana||d?.solana:d?.solflare;if(!x)return i(`${f} wallet not found`),null;let u=(await x.connect()).publicKey.toString();return t({connected:!0,address:u,chain:"solana",provider:f}),u}catch(d){return i(d.message||"Failed to connect wallet"),null}},[]),y=useCallback(async()=>{i(null);try{let d=(typeof window<"u"?window:null)?.ethereum;if(!d)return i("MetaMask not found"),null;let x=d;d.providers?.length&&(x=d.providers.find(n=>n.isMetaMask)||d);let u=(await x.request({method:"eth_requestAccounts"}))[0];return u?(t({connected:!0,address:u,chain:"ethereum",provider:"metamask"}),u):(i("No account selected"),null)}catch(f){return i(f.message||"Failed to connect wallet"),null}},[]),m=useCallback(async(f,d)=>{i(null);let x=d?.chain||e.chain,a=d?.provider||e.provider,u=d?.address||e.address;try{if(x==="solana"){let n=typeof window<"u"?window:null,p=a==="solflare"?n?.solflare:n?.phantom?.solana||n?.solana;if(!p)throw new Error("Wallet not available");let o=new TextEncoder().encode(f),g=await p.signMessage(o,"utf8"),h=new Uint8Array(g.signature||g),k="";for(let P=0;P<h.byteLength;P++)k+=String.fromCharCode(h[P]);return btoa(k)}if(x==="ethereum"){let p=(typeof window<"u"?window:null)?.ethereum;if(p?.providers?.length&&(p=p.providers.find(g=>g.isMetaMask)||p),!p)throw new Error("MetaMask not available");return await p.request({method:"personal_sign",params:[f,u]})}throw new Error("No wallet connected")}catch(n){return i(n.message||"Signing failed"),null}},[e]),c=useCallback(()=>{t({connected:false,address:null,chain:null,provider:null}),i(null);},[]);return {wallet:e,error:r,connectSolana:C,connectEVM:y,signMessage:m,disconnect:c}}function Oe(){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 Ee(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 Fe(){let[e,t]=useState(null),[r,i]=useState(true),C=useCallback(()=>{let c=Oe();c&&c.expiresAt>Date.now()?t({userId:c.userId,address:c.address,chain:c.chain,expiresAt:c.expiresAt,planId:c.planId,authMethod:c.authMethod}):t(null),i(false);},[]);useEffect(()=>{C();},[C]);let y=useCallback(async(c="")=>{try{let f=await fetch(`${c}/api/auth/session`);if(f.ok){let d=await f.json();if(d.session)return t(d.session),d.session}return t(null),null}catch{return null}},[]),m=!!e&&e.expiresAt>Date.now();return {session:e,loading:r,isAuthenticated:m,refresh:y,readSession:C}}function Be(e="__csrf",t="x-csrf-token"){let[r,i]=useState(null);useEffect(()=>{i(Ee(e));},[e]);let C=r?{[t]:r}:{};return {token:r,headers:C}}var kt="https://stacknet.magma-rpc.com/auth/bridge",se="stacknet-auth-bridge";function $e(e){let t=e?.bridgeUrl||kt,r=e?.disabled||false,i=useRef(null),[C,y]=useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),m=useRef([]),c=useRef(false),f=useCallback(n=>{let p={...n,protocol:se};c.current&&i.current?.contentWindow?i.current.contentWindow.postMessage(p,new URL(t).origin):m.current.push(p);},[t]);useEffect(()=>{if(r)return;let n=o=>{if(!(!o.data||o.data.protocol!==se)){try{if(o.origin!==new URL(t).origin)return}catch{return}switch(o.data.type){case "bridge:ready":c.current=true,y(g=>({...g,ready:true}));for(let g of m.current)i.current?.contentWindow?.postMessage(g,o.origin);m.current=[],i.current?.contentWindow?.postMessage({protocol:se,type:"auth:check"},o.origin),i.current?.contentWindow?.postMessage({protocol:se,type:"auth:resolve-stack"},o.origin);break;case "auth:status":y(g=>({...g,known:o.data.known,identity:o.data.identity,identityCount:o.data.identityCount||0}));break;case "auth:resolved-stack":y(g=>({...g,resolvedStackId:o.data.stackId||null}));break;}}};window.addEventListener("message",n);let p=document.createElement("iframe");return p.src=t,p.style.display="none",p.setAttribute("aria-hidden","true"),p.setAttribute("tabindex","-1"),p.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(p),i.current=p,()=>{window.removeEventListener("message",n),p.parentNode&&p.parentNode.removeChild(p),i.current=null,c.current=false;}},[t,r]);let d=useCallback(n=>{f({type:"auth:connected",...n});},[f]),x=useCallback(n=>{f({type:"auth:disconnected",...n});},[f]),a=useCallback(()=>{f({type:"auth:clear"}),y({ready:C.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[f,C.ready]),u=useCallback(()=>{f({type:"auth:check"});},[f]);return {...C,reportConnected:d,reportDisconnected:x,clearAll:a,refresh:u}}async function He(e,t,r,i){let C=e.apiVersion||"v2",y=`${e.baseUrl}/api/${C}${r}`;try{let m=await fetch(y,{method:t,headers:{"Content-Type":"application/json"},body:i?JSON.stringify(i):void 0}),c=await m.json();return m.ok?c.success&&c.data!==void 0?{success:!0,data:c.data}:{success:!0,data:c}:{success:!1,error:c.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 _e(e){return {getNetworkStatus:()=>He(e,"GET","/network/status"),getWeb3Challenge:(t,r)=>He(e,"POST",`/stacks/${encodeURIComponent(e.stackId)}/auth/web3/challenge`,{chain:t,address:r})}}function Qe(e={apiBaseUrl:""}){let{wallet:t,connectSolana:r,connectEVM:i,signMessage:C,disconnect:y}=ze(),{session:m,isAuthenticated:c,refresh:f,readSession:d}=Fe(),{headers:x}=Be(),a=$e({disabled:typeof window>"u"}),[u,n]=useState(false),[p,o]=useState(null),[g,h]=useState(false),k=e.apiBaseUrl||"",P=e.stacknetUrl||"https://stacknet.magma-rpc.com",b=e.stackId||a.resolvedStackId||"",I=_e({baseUrl:P,stackId:b}),R=useCallback(async(v,S,T,O)=>{n(true),o(null);try{let N=S;if(!N){let V=await T();if(!V)return n(!1),!1;N=V;}let L=await I.getWeb3Challenge(v,N);if(!L.success||!L.data)return o("Failed to get challenge"),n(!1),!1;let E=await C(L.data.message,{chain:v,provider:O,address:N});if(!E)return n(!1),!1;let $={chain:v,message:L.data.message,signature:E,stackId:b};v==="solana"&&($.publicKey=N);let G=await fetch(`${k}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify($)});if(!G.ok){let V=await G.json().catch(()=>({}));return o(V.error||"Authentication failed"),n(!1),!1}return a.reportConnected({address:N,chain:v,method:O||(v==="solana"?"phantom":"metamask"),stackId:b}),d(),n(!1),!0}catch(N){return o(N.message||"Authentication failed"),n(false),false}},[k,I,C,d,a,b]),F=useCallback(async(v="phantom")=>{let S=await r(v);return S?R("solana",S,()=>r(v),v):false},[r,R]),D=useCallback(async()=>{let v=await i();return v?R("ethereum",v,i,"metamask"):false},[i,R]),j=useCallback(async v=>{n(true),o(null);try{let S=await fetch(`${k}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({code:v})});if(!S.ok){let T=await S.json().catch(()=>({}));return o(T.error||"Invalid code"),n(!1),!1}return d(),n(!1),!0}catch(S){return o(S.message||"OTP verification failed"),n(false),false}},[k,d]),Q=useCallback(async(v,S)=>{n(true),o(null);try{let T=S||`${window.location.origin}/api/auth/oauth/callback`,O=new URLSearchParams({provider:v,redirectUri:T,stackId:b}),N=await fetch(`${k}/api/auth/oauth/start?${O}`,{credentials:"include"});if(!N.ok){let E=await N.json().catch(()=>({}));return o(E.error||"Failed to start OAuth flow"),n(!1),!1}let L=await N.json();if(L.redirect_url){let E;try{E=new URL(L.redirect_url);}catch{return o("Invalid OAuth redirect URL"),n(!1),!1}let $=[/(^|\.)accounts\.google\.com$/,/(^|\.)discord\.com$/,/(^|\.)github\.com$/,/(^|\.)x\.com$/,/(^|\.)twitter\.com$/,/(^|\.)apple\.com$/];return E.protocol!=="https:"||!$.some(G=>G.test(E.hostname))?(o(`Refusing to redirect to non-OAuth host: ${E.hostname}`),n(!1),!1):(typeof sessionStorage<"u"&&(sessionStorage.setItem("oauth_state",L.state||""),sessionStorage.setItem("oauth_provider",v)),window.location.href=E.toString(),!0)}return o("No redirect URL returned"),n(!1),!1}catch(T){return o(T.message||"OAuth flow failed"),n(false),false}},[k,b]),A=useCallback(async(v,S,T)=>{n(true),o(null);try{if(typeof sessionStorage<"u"){let N=sessionStorage.getItem("oauth_state"),L=sessionStorage.getItem("oauth_provider");if(sessionStorage.removeItem("oauth_state"),sessionStorage.removeItem("oauth_provider"),!N||N!==T)return o("OAuth state mismatch \u2014 refusing to complete login"),n(!1),!1;if(L&&L!==v)return o("OAuth provider mismatch \u2014 refusing to complete login"),n(!1),!1}let O=await fetch(`${k}/api/auth/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({provider:v,code:S,state:T,stackId:b})});if(!O.ok){let N=await O.json().catch(()=>({}));return o(N.error||"OAuth authentication failed"),n(!1),!1}return d(),n(!1),!0}catch(O){return o(O.message||"OAuth callback failed"),n(false),false}},[k,b,d]),z=useCallback(async()=>{t.address&&t.chain&&a.reportDisconnected({address:t.address,chain:t.chain,stackId:b});try{await fetch(`${k}/api/auth/logout`,{method:"POST",headers:x,credentials:"include"});}catch{}y(),d();},[k,x,y,d,t,a,b]);return useEffect(()=>{if(!e.autoConnect||g||c||!a.ready||!a.known||!a.identity)return;h(true);let{chain:v,method:S}=a.identity;v==="solana"&&(S==="phantom"||S==="solflare")?F(S):v==="ethereum"&&D();},[e.autoConnect,g,c,a,F,D]),{session:m,isAuthenticated:c,wallet:t,loading:u,error:p,authenticateSolana:F,authenticateEVM:D,authenticateOTP:j,authenticateOAuth:Q,authenticateOAuthCallback:A,logout:z,refresh:()=>f(k),stackId:b,bridge:{ready:a.ready,known:a.known,identity:a.identity,identityCount:a.identityCount,resolvedStackId:a.resolvedStackId}}}function Ge(e,t="https://stacknet.magma-rpc.com"){let[r,i]=useState(null),[C,y]=useState(false),[m,c]=useState(null),f=useCallback(async x=>{y(true),c(null);try{let a=await fetch(`${t}/api/v2/stacks/${x}`);if(!a.ok)return c("Stack not found"),y(!1),null;let u=await a.json(),n=u.data?.stack||u.stack||u,p={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(o=>({provider:o.provider,clientId:o.clientId,enabled:o.enabled!==!1}))};return i(p),y(!1),p}catch(a){return c(a.message),y(false),null}},[t]);useEffect(()=>{e&&f(e);},[e,f]);let d=r?vt(r):[];return {config:r,loading:C,error:m,identityProviders:d,fetchConfig:f}}function vt(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 ae(e,t="#"){if(!e||typeof e!="string")return t;let r=e.trim();if(r===""||r==="#")return t;if(r.startsWith("/")||r.startsWith("./")||r.startsWith("../"))return r;try{let i=new URL(r);if(i.protocol==="http:"||i.protocol==="https:")return i.toString()}catch{}return t}function ie({length:e=6,onComplete:t,disabled:r=false,error:i,className:C="",inputClassName:y=""}){let [m,c]=useState(Array(e).fill("")),f=useCallback((a,u)=>{if(u.length>1){let p=u.replace(/\D/g,"").slice(0,e).split(""),o=[...m];p.forEach((h,k)=>{a+k<e&&(o[a+k]=h);}),c(o);let g=Math.min(a+p.length,e-1);document.getElementById(`userutils-otp-${g}`)?.focus(),o.every(h=>h!=="")&&setTimeout(()=>t(o.join("")),100);return}if(!/^\d?$/.test(u))return;let n=[...m];n[a]=u,c(n),u&&a<e-1&&document.getElementById(`userutils-otp-${a+1}`)?.focus(),u&&a===e-1&&n.every(p=>p!=="")&&setTimeout(()=>t(n.join("")),100);},[m,e,t]),d=useCallback((a,u)=>{if(u.key==="Backspace"&&!m[a]&&a>0){document.getElementById(`userutils-otp-${a-1}`)?.focus();let n=[...m];n[a-1]="",c(n);}if(u.key==="Enter"){let n=m.join("");n.length===e&&t(n);}},[m,e,t]);useCallback(()=>{c(Array(e).fill("")),document.getElementById("userutils-otp-0")?.focus();},[e]);return jsxs("div",{className:C,children:[jsx("div",{className:"flex gap-2 justify-center",children:m.map((a,u)=>jsx("input",{id:`userutils-otp-${u}`,type:"text",inputMode:"numeric",maxLength:e,value:a,onChange:n=>f(u,n.target.value),onKeyDown:n=>d(u,n),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))}),i&&jsx("p",{className:"text-center text-sm text-red-400 mt-2",children:i})]})}ie.displayName="OTPInput";var Nt="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function le({className:e,style:t}){return jsx("img",{src:Nt,alt:"Phantom",className:e,style:t})}function ce({className:e,style:t}){return jsxs("svg",{className:e,style:t,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 Ce({className:e,style:t}){return jsxs("svg",{className:e,style:t,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 ve({className:e,style:t}){return jsxs("svg",{className:e,style:t,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 xe({className:e,style:t}){return jsxs("svg",{className:e,style:t,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 Se({className:e,style:t}){return jsxs("svg",{className:e,style:t,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:"#000000"}),jsx("path",{d:"M21.3611 16.7384C21.3807 18.9244 23.2792 19.6519 23.3001 19.661C23.2841 19.7124 22.9971 20.6962 22.3005 21.7115C21.6987 22.5892 21.0742 23.4636 20.0904 23.4816C19.1237 23.4994 18.8127 22.9098 17.7076 22.9098C16.6029 22.9098 16.2574 23.4636 15.3423 23.4994C14.3928 23.5352 13.6694 22.5504 13.0626 21.676C11.8226 19.8879 10.8747 16.6229 12.1471 14.4182C12.7791 13.3234 13.9087 12.6304 15.1346 12.6126C16.0668 12.5948 16.9468 13.2378 17.5167 13.2378C18.0865 13.2378 19.1555 12.4647 20.2795 12.579C20.7501 12.5986 22.0715 12.7692 22.9207 14.0122C22.852 14.0549 21.3453 14.9328 21.3611 16.7384ZM19.5432 11.392C20.0472 10.7809 20.3862 9.93 20.2939 9.08325C19.5709 9.11221 18.6961 9.56574 18.1749 10.1763C17.708 10.717 17.2995 11.582 17.4096 12.4111C18.2158 12.4736 19.0391 12.003 19.5432 11.392Z",fill:"#FFFFFF"})]})}function jt({config:e,onSuccess:t,title:r="Log in or Sign up",showWallets:i,showOTP:C,hideHeader:y,onOTPSubmit:m,otpLabel:c="Access Code",oauthInline:f,oauthFirst:d,className:x=""}){let a=Qe(e),{isAuthenticated:u,wallet:n,loading:p,error:o,authenticateSolana:g,authenticateEVM:h,authenticateOTP:k,authenticateOAuth:P,bridge:b,stackId:I}=a,R=!e.stackId&&!I,F=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:D,identityProviders:j,loading:Q}=Ge(I||e.stackId||null,F),[A,z]=useState(R?"stack-select":"select"),[v,S]=useState(null),[T,O]=useState(false),[N,L]=useState("idle"),[E,$]=useState(""),[G,V]=useState([]),[tt,Me]=useState(e.stackId||null),[oe,nt]=useState(false),[ot,rt]=useState(false);useEffect(()=>{if(typeof window>"u")return;let s=()=>{let Y=window;nt(!!(Y.phantom?.solana?.isPhantom||Y.solana?.isPhantom));let K=Y.ethereum;rt(!!(K?.isMetaMask||K?.providers?.some(q=>q.isMetaMask)));};s(),window.addEventListener("ethereum#initialized",s);let H=setTimeout(s,500);return ()=>{window.removeEventListener("ethereum#initialized",s),clearTimeout(H);}},[]),useEffect(()=>{A==="stack-select"&&I&&(Me(I),z("select"));},[A,I]),useEffect(()=>{if(!(!b.ready||!R)&&b.identity){let s=[];b.resolvedStackId&&s.push({stackId:b.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(s.map(async H=>{try{let Y=await fetch(`${F}/api/v2/stacks/${H.stackId}`);if(Y.ok){let K=await Y.json(),q=K.data?.stack||K;H.name=q.displayName||q.name,H.logoUrl=q.logoUrl;}}catch{}return H})).then(V);}},[b.ready,b.identity,b.resolvedStackId,R,F]),useEffect(()=>{u&&A==="success"&&t?.();},[u,A,t]);let Ae=i||(j.length>0?j.filter(s=>s.type==="wallet").map(s=>s.id):["phantom","metamask"]),Le=C!==void 0?C:j.length>0?j.some(s=>s.type==="otp"):true,J=j.filter(s=>s.type==="oauth"),ge=new Set(d||[]),Ue=J.filter(s=>ge.has(s.id)),me=f?J.filter(s=>!ge.has(s.id)):J,Pe=async s=>{S(s),z("connecting"),await P(s)||z("error");},st=async()=>{S("phantom"),z("connecting");let s=await g("phantom");z(s?"success":"error");},at=async()=>{S("metamask"),z("connecting");let s=await h();z(s?"success":"error");},it=async s=>{L("verifying"),$(""),await(m||k)(s)?(L("success"),z("success")):(L("error"),$("Invalid or expired code"),setTimeout(()=>L("idle"),2e3));},je=()=>{z(R&&!tt?"stack-select":"select"),S(null),O(false),L("idle"),$("");};return jsxs("div",{className:`w-full max-w-md space-y-3 ${x}`,children:[!y&&jsxs("div",{className:"mb-6 text-center",children:[D?.logoUrl&&A!=="stack-select"&&jsx("img",{src:ae(D.logoUrl),alt:D.displayName||"",className:"h-16 w-16 mx-auto mb-4 rounded-xl"}),D?.displayName&&jsx("p",{className:"text-sm text-zinc-400 mb-2",children:D.displayName}),jsx("h1",{className:"font-semibold text-2xl text-white",children:"Log in or Sign up"})]}),A==="stack-select"&&jsxs("div",{className:"space-y-3",children:[jsx("p",{className:"text-center text-sm text-zinc-400 mb-4",children:G.length>0?"Select a network to continue":"No previous connections found. Enter a Stack ID to continue."}),G.map(s=>jsxs("button",{onClick:()=>{Me(s.stackId),z("select");},className:"flex w-full cursor-pointer items-center gap-4 rounded-xl border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[s.logoUrl?jsx("img",{src:ae(s.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:s.name?.[0]?.toUpperCase()||"S"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-white",children:s.name||s.stackId}),jsx("p",{className:"text-xs text-zinc-500",children:s.domain})]}),jsx("span",{className:"text-xs text-zinc-600",children:"Previously connected"})]},s.stackId)),b.ready&&!b.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."})]}),A==="select"&&Q&&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%"}})}),o&&A==="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:o}),jsx("button",{className:"mt-3 w-full text-sm text-zinc-400 hover:text-white",onClick:je,children:"Try Again"})]}),A==="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..."})]}),A==="connecting"&&p&&jsxs("div",{style:{border:"1px solid #27272a",background:"#25252f",padding:24,textAlign:"center"},children:[jsxs("div",{style:{width:40,height:40,margin:"0 auto 12px"},children:[v==="phantom"&&jsx(le,{style:W}),v==="metamask"&&jsx(ce,{style:W})]}),jsx("p",{style:{fontWeight:500,fontSize:14,color:"#fff"},children:n.connected?"Signing message...":"Connecting wallet..."}),jsx("p",{style:{marginTop:4,fontSize:12,color:"#71717a"},children:"Please confirm in your wallet"}),jsx("button",{style:{marginTop:16,fontSize:14,color:"#71717a",background:"none",border:"none",cursor:"pointer"},onClick:je,children:"Cancel"})]}),A==="select"&&!p&&!Q&&jsxs(Fragment,{children:[Ue.map(s=>jsxs("button",{onClick:()=>Pe(s.id),style:te,children:[jsx(Je,{provider:s.id}),jsx("span",{style:{fontWeight:500,color:"#fff"},children:Ke(s.id,s.name)})]},s.id)),Ae.includes("phantom")&&jsxs("button",{onClick:st,disabled:!oe,style:{...te,opacity:oe?1:.5,cursor:oe?"pointer":"not-allowed"},children:[jsx(le,{style:{...W,borderRadius:8}}),jsx("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:"Phantom"}),!oe&&jsx("span",{style:{fontSize:12,color:"#71717a"},children:"Not installed"})]}),Ae.includes("metamask")&&ot&&jsxs("button",{onClick:at,style:te,children:[jsx(ce,{style:W}),jsx("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:"MetaMask"})]}),Le&&!T&&jsxs("button",{onClick:()=>O(true),style:te,children:[jsx("div",{style:{...W,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8,border:"1px solid #3f3f46",background:"#2a2a3e"},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"20px",viewBox:"0 -960 960 960",width:"20px",fill:"#a1a1aa",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("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:c})]}),Le&&T&&jsxs("div",{style:{borderRadius:12,border:"1px solid #27272a",background:"#25252f",padding:24},children:[jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginBottom:16},children:"Enter your 6-digit access code"}),jsx(ie,{onComplete:it,disabled:N==="verifying",error:E}),N==="verifying"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginTop:16},children:"Verifying..."}),N==="success"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#4ade80",marginTop:16},children:"Verified!"}),D?.webPageUrl&&N==="idle"&&(()=>{let s=ae(D.webPageUrl);return s==="#"?null:jsx("a",{href:`${s.replace(/\/$/,"")}/connect/pair`,target:"_blank",rel:"noopener noreferrer",style:{display:"block",textAlign:"center",fontSize:14,color:"#71717a",marginTop:16},children:"Get code"})})()]}),(f?me:J).length>0&&(!f||me.length>0)&&jsxs(Fragment,{children:[!f&&Ue.length===0&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 0"},children:[jsx("div",{style:{flex:1,borderTop:"1px solid #27272a"}}),jsx("span",{style:{fontSize:12,color:"#52525b"},children:"or continue with"}),jsx("div",{style:{flex:1,borderTop:"1px solid #27272a"}})]}),(f?me:J.filter(s=>!ge.has(s.id))).map(s=>jsxs("button",{onClick:()=>Pe(s.id),style:te,children:[jsx(Je,{provider:s.id}),jsx("span",{style:{fontWeight:500,color:"#fff"},children:Ke(s.id,s.name)})]},s.id))]})]})]})}var W={width:40,height:40,flexShrink:0},te={display:"flex",width:"100%",alignItems:"center",gap:12,borderRadius:12,border:"1px solid #27272a",background:"#25252f",padding:16,cursor:"pointer",transition:"background 0.15s"};function Je({provider:e}){switch(e){case "google":return jsx(Ce,{style:{...W,borderRadius:8}});case "discord":return jsx(ve,{style:{...W,borderRadius:8}});case "twitter":return jsx(xe,{style:{...W,borderRadius:8}});case "apple":return jsx(Se,{style:{...W,borderRadius:8}});default:return jsx("div",{style:{...W,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8,border:"1px solid #3f3f46",background:"#2a2a3e",fontSize:14,color:"#a1a1aa",fontFamily:"monospace"},children:e[0]?.toUpperCase()})}}function Ke(e,t){return {google:"Google",discord:"Discord",twitter:"Twitter",apple:"Apple"}[e]||t||e}function Tt(){if(typeof document>"u")return null;let e=document.cookie.split(";").map(t=>t.trim()).find(t=>t.startsWith("__csrf="));return e?e.slice(7):null}function Xe(e,t){let[r,i]=useState(null),[C,y]=useState(true),[m,c]=useState(false),[f,d]=useState(null),x=t?.apiBaseUrl??"",a=t?.scope===void 0||t?.scope==="global"?"global":`stack:${t.scope.stackId}`,u=useCallback(o=>{let g=encodeURIComponent(o);if(a==="global")return `${x}/api/user/profile/${g}`;let h=a.slice(6);return `${x}/api/v2/stacks/${encodeURIComponent(h)}/members/${g}/profile`},[x,a]),n=useCallback(async()=>{if(!e){i(null),y(false);return}y(true),d(null);try{let o=await fetch(u(e));if(o.ok){let g=await o.json(),h=g.profile||g.data?.profile||g;i({mid:h.mid||e,username:h.username||"",avatarUrl:h.avatar_url||h.avatarUrl,bio:h.bio,paymentAddress:h.payment_address||h.paymentAddress,createdAt:h.created_at||h.createdAt,updatedAt:h.updated_at||h.updatedAt});}else if(o.status===404)i({mid:e,username:""});else throw new Error(`${o.status}`)}catch(o){d(o instanceof Error?o.message:"Failed to load profile");}finally{y(false);}},[e,u]);useEffect(()=>{n();},[n]);let p=useCallback(async o=>{if(!e)return false;c(true),d(null);try{let g=Tt(),h={};o.username!==void 0&&(h.username=o.username),o.avatarUrl!==void 0&&(h.avatar_url=o.avatarUrl),o.bio!==void 0&&(h.bio=o.bio),o.paymentAddress!==void 0&&(h.payment_address=o.paymentAddress);let k=await fetch(u(e),{method:"PUT",headers:{"Content-Type":"application/json",...g?{"x-csrf-token":g}:{}},credentials:"same-origin",body:JSON.stringify(h)});if(!k.ok){let I=await k.json().catch(()=>({}));throw new Error(I.error||I.message||`Update failed: ${k.status}`)}let P=await k.json(),b=P.profile||P.data?.profile||P;return i(I=>({mid:I?.mid||e,username:o.username??I?.username??"",avatarUrl:o.avatarUrl??I?.avatarUrl,bio:o.bio??I?.bio,paymentAddress:o.paymentAddress??b.payment_address??b.paymentAddress??I?.paymentAddress,createdAt:I?.createdAt,updatedAt:b.updated_at||b.updatedAt||Date.now()})),!0}catch(g){return d(g instanceof Error?g.message:"Update failed"),false}finally{c(false);}},[e,u]);return {profile:r,loading:C,saving:m,error:f,updateProfile:p,refresh:n}}function Et({mid:e,apiBaseUrl:t="",scope:r,onSave:i,className:C}){let{profile:y,loading:m,saving:c,error:f,updateProfile:d}=Xe(e,{apiBaseUrl:t,scope:r}),[x,a]=useState(null),[u,n]=useState(null),[p,o]=useState(null),g=useRef(null),[h,k]=useState(false),P=x??y?.username??"",b=u??y?.bio??"",I=p??y?.avatarUrl,R=useCallback(j=>{let Q=j.target.files?.[0];if(!Q)return;let A=new FileReader;A.onload=()=>{o(A.result),k(true);},A.readAsDataURL(Q);},[]),F=async()=>{await d({username:P||void 0,avatarUrl:p??y?.avatarUrl,bio:b||void 0})&&(k(false),i?.());};if(m)return jsxs("div",{className:C,style:{display:"grid",gap:"1.5rem"},children:[jsx("div",{style:{height:40,background:"var(--x-color-neutral-800, #333)",animation:"pulse 2s infinite"}}),jsx("div",{style:{height:40,background:"var(--x-color-neutral-800, #333)",animation:"pulse 2s infinite"}})]});let D=r==="global"||!r?"Global profile":`Stack profile (${r.stackId})`;return jsxs("div",{className:C,style:{display:"grid",gap:"1.5rem"},children:[jsx("p",{style:{fontSize:11,color:"var(--x-color-neutral-500, #91918D)",textTransform:"uppercase",letterSpacing:"0.05em"},children:D}),jsxs("div",{style:{display:"grid",gap:"1.5rem",gridTemplateColumns:"1fr 1fr"},children:[jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[jsx("label",{style:{fontSize:14,color:"var(--x-color-neutral-400, #91918D)"},children:"Username"}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[jsx("button",{type:"button",onClick:()=>g.current?.click(),style:{width:40,height:40,flexShrink:0,cursor:"pointer",overflow:"hidden",background:"var(--x-color-neutral-800, #262625)",border:"none",position:"relative",display:"flex",alignItems:"center",justifyContent:"center"},children:I?jsx("img",{src:I,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--x-color-neutral-500, #91918D)"},children:[jsx("path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}),jsx("circle",{cx:"12",cy:"7",r:"4"})]})}),jsx("input",{type:"text",value:P,onChange:j=>{a(j.target.value),k(true);},placeholder:"Enter username",maxLength:30,style:{flex:1,padding:"0.75rem 1rem",fontSize:14,background:"var(--x-color-neutral-800, #262625)",color:"var(--x-color-neutral-100, #FAFAF7)",border:"none",outline:"none"}})]}),jsx("input",{ref:g,type:"file",accept:"image/*",onChange:R,style:{display:"none"}})]}),jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[jsx("label",{style:{fontSize:14,color:"var(--x-color-neutral-400, #91918D)"},children:"Bio"}),jsx("input",{type:"text",value:b,onChange:j=>{n(j.target.value),k(true);},placeholder:"Tell us about yourself",maxLength:200,style:{width:"100%",padding:"0.75rem 1rem",fontSize:14,background:"var(--x-color-neutral-800, #262625)",color:"var(--x-color-neutral-100, #FAFAF7)",border:"none",outline:"none"}})]})]}),f&&jsx("p",{style:{fontSize:13,color:"var(--x-color-red-500, #BF4D43)"},children:f}),h&&jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[jsx("button",{onClick:F,disabled:c,style:{padding:"0.5rem 1.25rem",fontSize:13,fontWeight:700,background:"var(--x-color-blue-600, #165DFC)",color:"#FFF",border:"none",cursor:c?"wait":"pointer",opacity:c?.6:1},children:c?"Saving...":"Save"}),jsx("button",{onClick:()=>{a(null),n(null),o(null),k(false);},style:{padding:"0.5rem 1.25rem",fontSize:13,background:"var(--x-color-neutral-800, #262625)",color:"var(--x-color-neutral-400, #91918D)",border:"none",cursor:"pointer"},children:"Cancel"}),jsx("p",{style:{fontSize:11,color:"var(--x-color-neutral-500, #666663)",alignSelf:"center",marginLeft:"0.5rem"},children:"Profile updates cost 10M tokens"})]})]})}function Rt({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 Wt({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 Bt({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
|
-
export{
|
|
1
|
+
import {createContext,useContext,useState,useCallback,useEffect,useRef}from'react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var $e=createContext(null);function vt(){let e=useContext($e);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function Ct({config:e,callbacks:t,children:a}){return jsx($e.Provider,{value:{config:e,callbacks:t},children:a})}function Fe(){let[e,t]=useState({connected:false,address:null,chain:null,provider:null}),[a,l]=useState(null),v=useCallback(async(f="phantom")=>{l(null);try{let d=typeof window<"u"?window:null,x=f==="phantom"?d?.phantom?.solana||d?.solana:d?.solflare;if(!x)return l(`${f} wallet not found`),null;let u=(await x.connect()).publicKey.toString();return t({connected:!0,address:u,chain:"solana",provider:f}),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 x=d;d.providers?.length&&(x=d.providers.find(n=>n.isMetaMask)||d);let u=(await x.request({method:"eth_requestAccounts"}))[0];return u?(t({connected:!0,address:u,chain:"ethereum",provider:"metamask"}),u):(l("No account selected"),null)}catch(f){return l(f.message||"Failed to connect wallet"),null}},[]),h=useCallback(async(f,d)=>{l(null);let x=d?.chain||e.chain,i=d?.provider||e.provider,u=d?.address||e.address;try{if(x==="solana"){let n=typeof window<"u"?window:null,p=i==="solflare"?n?.solflare:n?.phantom?.solana||n?.solana;if(!p)throw new Error("Wallet not available");let o=new TextEncoder().encode(f),g=await p.signMessage(o,"utf8"),m=new Uint8Array(g.signature||g),k="";for(let T=0;T<m.byteLength;T++)k+=String.fromCharCode(m[T]);return btoa(k)}if(x==="ethereum"){let p=(typeof window<"u"?window:null)?.ethereum;if(p?.providers?.length&&(p=p.providers.find(g=>g.isMetaMask)||p),!p)throw new Error("MetaMask not available");return await p.request({method:"personal_sign",params:[f,u]})}throw new Error("No wallet connected")}catch(n){return l(n.message||"Signing failed"),null}},[e]),c=useCallback(()=>{t({connected:false,address:null,chain:null,provider:null}),l(null);},[]);return {wallet:e,error:a,connectSolana:v,connectEVM:y,signMessage:h,disconnect:c}}function He(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(a=>a.trim()).find(a=>a.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 _e(e="__csrf"){if(typeof document>"u")return null;let t=document.cookie.split(";").map(a=>a.trim()).find(a=>a.startsWith(`${e}=`));return t?t.slice(e.length+1):null}function Ge(){let[e,t]=useState(null),[a,l]=useState(true),v=useCallback(()=>{let c=He();c&&c.expiresAt>Date.now()?t({userId:c.userId,address:c.address,chain:c.chain,expiresAt:c.expiresAt,planId:c.planId,authMethod:c.authMethod}):t(null),l(false);},[]);useEffect(()=>{v();},[v]);let y=useCallback(async(c="")=>{try{let f=await fetch(`${c}/api/auth/session`);if(f.ok){let d=await f.json();if(d.session)return t(d.session),d.session}return t(null),null}catch{return null}},[]),h=!!e&&e.expiresAt>Date.now();return {session:e,loading:a,isAuthenticated:h,refresh:y,readSession:v}}function Ye(e="__csrf",t="x-csrf-token"){let[a,l]=useState(null);useEffect(()=>{l(_e(e));},[e]);let v=a?{[t]:a}:{};return {token:a,headers:v}}var Lt="https://stacknet.magma-rpc.com/auth/bridge",le="stacknet-auth-bridge";function Ve(e){let t=e?.bridgeUrl||Lt,a=e?.disabled||false,l=useRef(null),[v,y]=useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),h=useRef([]),c=useRef(false),f=useCallback(n=>{let p={...n,protocol:le};c.current&&l.current?.contentWindow?l.current.contentWindow.postMessage(p,new URL(t).origin):h.current.push(p);},[t]);useEffect(()=>{if(a)return;let n=o=>{if(!(!o.data||o.data.protocol!==le)){try{if(o.origin!==new URL(t).origin)return}catch{return}switch(o.data.type){case "bridge:ready":c.current=true,y(g=>({...g,ready:true}));for(let g of h.current)l.current?.contentWindow?.postMessage(g,o.origin);h.current=[],l.current?.contentWindow?.postMessage({protocol:le,type:"auth:check"},o.origin),l.current?.contentWindow?.postMessage({protocol:le,type:"auth:resolve-stack"},o.origin);break;case "auth:status":y(g=>({...g,known:o.data.known,identity:o.data.identity,identityCount:o.data.identityCount||0}));break;case "auth:resolved-stack":y(g=>({...g,resolvedStackId:o.data.stackId||null}));break;}}};window.addEventListener("message",n);let p=document.createElement("iframe");return p.src=t,p.style.display="none",p.setAttribute("aria-hidden","true"),p.setAttribute("tabindex","-1"),p.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(p),l.current=p,()=>{window.removeEventListener("message",n),p.parentNode&&p.parentNode.removeChild(p),l.current=null,c.current=false;}},[t,a]);let d=useCallback(n=>{f({type:"auth:connected",...n});},[f]),x=useCallback(n=>{f({type:"auth:disconnected",...n});},[f]),i=useCallback(()=>{f({type:"auth:clear"}),y({ready:v.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[f,v.ready]),u=useCallback(()=>{f({type:"auth:check"});},[f]);return {...v,reportConnected:d,reportDisconnected:x,clearAll:i,refresh:u}}async function qe(e,t,a,l){let v=e.apiVersion||"v2",y=`${e.baseUrl}/api/${v}${a}`;try{let h=await fetch(y,{method:t,headers:{"Content-Type":"application/json"},body:l?JSON.stringify(l):void 0}),c=await h.json();return h.ok?c.success&&c.data!==void 0?{success:!0,data:c.data}:{success:!0,data:c}:{success:!1,error:c.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(h){return {success:false,error:{code:"NETWORK_ERROR",message:h instanceof Error?h.message:"Network error"}}}}function Je(e){return {getNetworkStatus:()=>qe(e,"GET","/network/status"),getWeb3Challenge:(t,a)=>qe(e,"POST",`/stacks/${encodeURIComponent(e.stackId)}/auth/web3/challenge`,{chain:t,address:a})}}function Ke(e={apiBaseUrl:""}){let{wallet:t,connectSolana:a,connectEVM:l,signMessage:v,disconnect:y}=Fe(),{session:h,isAuthenticated:c,refresh:f,readSession:d}=Ge(),{headers:x}=Ye(),i=Ve({disabled:typeof window>"u"}),[u,n]=useState(false),[p,o]=useState(null),[g,m]=useState(false),k=e.apiBaseUrl||"",T=e.stacknetUrl||"https://stacknet.magma-rpc.com",I=e.stackId||i.resolvedStackId||"",A=Je({baseUrl:T,stackId:I}),Q=useCallback(async(C,b,S,E)=>{n(true),o(null);try{let N=b;if(!N){let V=await S();if(!V)return n(!1),!1;N=V;}let j=await A.getWeb3Challenge(C,N);if(!j.success||!j.data)return o("Failed to get challenge"),n(!1),!1;let O=await v(j.data.message,{chain:C,provider:E,address:N});if(!O)return n(!1),!1;let _={chain:C,message:j.data.message,signature:O,stackId:I};C==="solana"&&(_.publicKey=N);let F=await fetch(`${k}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(_)});if(!F.ok){let V=await F.json().catch(()=>({}));return o(V.error||"Authentication failed"),n(!1),!1}return i.reportConnected({address:N,chain:C,method:E||(C==="solana"?"phantom":"metamask"),stackId:I}),d(),n(!1),!0}catch(N){return o(N.message||"Authentication failed"),n(false),false}},[k,A,v,d,i,I]),U=useCallback(async(C="phantom")=>{let b=await a(C);return b?Q("solana",b,()=>a(C),C):false},[a,Q]),$=useCallback(async()=>{let C=await l();return C?Q("ethereum",C,l,"metamask"):false},[l,Q]),z=useCallback(async C=>{n(true),o(null);try{let b=await fetch(`${k}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({code:C})});if(!b.ok){let S=await b.json().catch(()=>({}));return o(S.error||"Invalid code"),n(!1),!1}return d(),n(!1),!0}catch(b){return o(b.message||"OTP verification failed"),n(false),false}},[k,d]),H=useCallback(async(C,b)=>{n(true),o(null);try{let S=b||`${window.location.origin}/api/auth/oauth/callback`,E=new URLSearchParams({provider:C,redirectUri:S,stackId:I}),N=await fetch(`${k}/api/auth/oauth/start?${E}`,{credentials:"include"});if(!N.ok){let O=await N.json().catch(()=>({}));return o(O.error||"Failed to start OAuth flow"),n(!1),!1}let j=await N.json();if(j.redirect_url){let O;try{O=new URL(j.redirect_url);}catch{return o("Invalid OAuth redirect URL"),n(!1),!1}let _=[/(^|\.)accounts\.google\.com$/,/(^|\.)discord\.com$/,/(^|\.)github\.com$/,/(^|\.)x\.com$/,/(^|\.)twitter\.com$/,/(^|\.)apple\.com$/];return O.protocol!=="https:"||!_.some(F=>F.test(O.hostname))?(o(`Refusing to redirect to non-OAuth host: ${O.hostname}`),n(!1),!1):(typeof sessionStorage<"u"&&(sessionStorage.setItem("oauth_state",j.state||""),sessionStorage.setItem("oauth_provider",C)),window.location.href=O.toString(),!0)}return o("No redirect URL returned"),n(!1),!1}catch(S){return o(S.message||"OAuth flow failed"),n(false),false}},[k,I]),D=useCallback(async(C,b,S)=>{n(true),o(null);try{if(typeof sessionStorage<"u"){let N=sessionStorage.getItem("oauth_state"),j=sessionStorage.getItem("oauth_provider");if(sessionStorage.removeItem("oauth_state"),sessionStorage.removeItem("oauth_provider"),!N||N!==S)return o("OAuth state mismatch \u2014 refusing to complete login"),n(!1),!1;if(j&&j!==C)return o("OAuth provider mismatch \u2014 refusing to complete login"),n(!1),!1}let E=await fetch(`${k}/api/auth/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({provider:C,code:b,state:S,stackId:I})});if(!E.ok){let N=await E.json().catch(()=>({}));return o(N.error||"OAuth authentication failed"),n(!1),!1}return d(),n(!1),!0}catch(E){return o(E.message||"OAuth callback failed"),n(false),false}},[k,I,d]),G=useCallback(async()=>{t.address&&t.chain&&i.reportDisconnected({address:t.address,chain:t.chain,stackId:I});try{await fetch(`${k}/api/auth/logout`,{method:"POST",headers:x,credentials:"include"});}catch{}y(),d();},[k,x,y,d,t,i,I]);return useEffect(()=>{if(!e.autoConnect||g||c||!i.ready||!i.known||!i.identity)return;m(true);let{chain:C,method:b}=i.identity;C==="solana"&&(b==="phantom"||b==="solflare")?U(b):C==="ethereum"&&$();},[e.autoConnect,g,c,i,U,$]),{session:h,isAuthenticated:c,wallet:t,loading:u,error:p,authenticateSolana:U,authenticateEVM:$,authenticateOTP:z,authenticateOAuth:H,authenticateOAuthCallback:D,logout:G,refresh:()=>f(k),stackId:I,bridge:{ready:i.ready,known:i.known,identity:i.identity,identityCount:i.identityCount,resolvedStackId:i.resolvedStackId}}}function Xe(e,t="https://stacknet.magma-rpc.com"){let[a,l]=useState(null),[v,y]=useState(false),[h,c]=useState(null),f=useCallback(async x=>{y(true),c(null);try{let i=await fetch(`${t}/api/v2/stacks/${x}`);if(!i.ok)return c("Stack not found"),y(!1),null;let u=await i.json(),n=u.data?.stack||u.stack||u,p={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(o=>({provider:o.provider,clientId:o.clientId,enabled:o.enabled!==!1}))};return l(p),y(!1),p}catch(i){return c(i.message),y(false),null}},[t]);useEffect(()=>{e&&f(e);},[e,f]);let d=a?jt(a):[];return {config:a,loading:v,error:h,identityProviders:d,fetchConfig:f}}function jt(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 a of e.oauthProviders)a.enabled&&t.push({type:"oauth",id:a.provider,name:a.provider});return t}function ce(e,t="#"){if(!e||typeof e!="string")return t;let a=e.trim();if(a===""||a==="#")return t;if(a.startsWith("/")||a.startsWith("./")||a.startsWith("../"))return a;try{let l=new URL(a);if(l.protocol==="http:"||l.protocol==="https:")return l.toString()}catch{}return t}function ne({length:e=6,onComplete:t,disabled:a=false,error:l,className:v="",inputClassName:y=""}){let [h,c]=useState(Array(e).fill("")),f=useCallback((i,u)=>{if(u.length>1){let p=u.replace(/\D/g,"").slice(0,e).split(""),o=[...h];p.forEach((m,k)=>{i+k<e&&(o[i+k]=m);}),c(o);let g=Math.min(i+p.length,e-1);document.getElementById(`userutils-otp-${g}`)?.focus(),o.every(m=>m!=="")&&setTimeout(()=>t(o.join("")),100);return}if(!/^\d?$/.test(u))return;let n=[...h];n[i]=u,c(n),u&&i<e-1&&document.getElementById(`userutils-otp-${i+1}`)?.focus(),u&&i===e-1&&n.every(p=>p!=="")&&setTimeout(()=>t(n.join("")),100);},[h,e,t]),d=useCallback((i,u)=>{if(u.key==="Backspace"&&!h[i]&&i>0){document.getElementById(`userutils-otp-${i-1}`)?.focus();let n=[...h];n[i-1]="",c(n);}if(u.key==="Enter"){let n=h.join("");n.length===e&&t(n);}},[h,e,t]);useCallback(()=>{c(Array(e).fill("")),document.getElementById("userutils-otp-0")?.focus();},[e]);return jsxs("div",{className:v,children:[jsx("div",{className:"flex gap-2 justify-center",children:h.map((i,u)=>jsx("input",{id:`userutils-otp-${u}`,type:"text",inputMode:"numeric",maxLength:e,value:i,onChange:n=>f(u,n.target.value),onKeyDown:n=>d(u,n),disabled:a,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})]})}ne.displayName="OTPInput";var Ot="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function de({className:e,style:t}){return jsx("img",{src:Ot,alt:"Phantom",className:e,style:t})}function ue({className:e,style:t}){return jsxs("svg",{className:e,style:t,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 Ie({className:e,style:t}){return jsxs("svg",{className:e,style:t,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 Me({className:e,style:t}){return jsxs("svg",{className:e,style:t,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 Ae({className:e,style:t}){return jsxs("svg",{className:e,style:t,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 Le({className:e,style:t}){return jsxs("svg",{className:e,style:t,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:"#000000"}),jsx("path",{d:"M21.3611 16.7384C21.3807 18.9244 23.2792 19.6519 23.3001 19.661C23.2841 19.7124 22.9971 20.6962 22.3005 21.7115C21.6987 22.5892 21.0742 23.4636 20.0904 23.4816C19.1237 23.4994 18.8127 22.9098 17.7076 22.9098C16.6029 22.9098 16.2574 23.4636 15.3423 23.4994C14.3928 23.5352 13.6694 22.5504 13.0626 21.676C11.8226 19.8879 10.8747 16.6229 12.1471 14.4182C12.7791 13.3234 13.9087 12.6304 15.1346 12.6126C16.0668 12.5948 16.9468 13.2378 17.5167 13.2378C18.0865 13.2378 19.1555 12.4647 20.2795 12.579C20.7501 12.5986 22.0715 12.7692 22.9207 14.0122C22.852 14.0549 21.3453 14.9328 21.3611 16.7384ZM19.5432 11.392C20.0472 10.7809 20.3862 9.93 20.2939 9.08325C19.5709 9.11221 18.6961 9.56574 18.1749 10.1763C17.708 10.717 17.2995 11.582 17.4096 12.4111C18.2158 12.4736 19.0391 12.003 19.5432 11.392Z",fill:"#FFFFFF"})]})}function Ht({config:e,onSuccess:t,title:a="Log in or Sign up",showWallets:l,showOTP:v,hideHeader:y,onOTPSubmit:h,otpLabel:c="Access Code",showPreviewCode:f=false,onPreviewCodeSubmit:d,previewCodeLabel:x="Preview Code",oauthInline:i,oauthFirst:u,className:n=""}){let p=Ke(e),{isAuthenticated:o,wallet:g,loading:m,error:k,authenticateSolana:T,authenticateEVM:I,authenticateOTP:A,authenticateOAuth:Q,bridge:U,stackId:$}=p,z=!e.stackId&&!$,H=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:D,identityProviders:G,loading:C}=Xe($||e.stackId||null,H),[b,S]=useState(z?"stack-select":"select"),[E,N]=useState(null),[j,O]=useState(false),[_,F]=useState("idle"),[V,he]=useState(""),[Te,ye]=useState(false),[ke,q]=useState("idle"),[lt,se]=useState(""),[je,ct]=useState([]),[dt,ze]=useState(e.stackId||null),[ae,ut]=useState(false),[pt,ft]=useState(false);useEffect(()=>{if(typeof window>"u")return;let r=()=>{let L=window;ut(!!(L.phantom?.solana?.isPhantom||L.solana?.isPhantom));let X=L.ethereum;ft(!!(X?.isMetaMask||X?.providers?.some(ee=>ee.isMetaMask)));};r(),window.addEventListener("ethereum#initialized",r);let R=setTimeout(r,500);return ()=>{window.removeEventListener("ethereum#initialized",r),clearTimeout(R);}},[]),useEffect(()=>{b==="stack-select"&&$&&(ze($),S("select"));},[b,$]),useEffect(()=>{if(!(!U.ready||!z)&&U.identity){let r=[];U.resolvedStackId&&r.push({stackId:U.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(r.map(async R=>{try{let L=await fetch(`${H}/api/v2/stacks/${R.stackId}`);if(L.ok){let X=await L.json(),ee=X.data?.stack||X;R.name=ee.displayName||ee.name,R.logoUrl=ee.logoUrl;}}catch{}return R})).then(ct);}},[U.ready,U.identity,U.resolvedStackId,z,H]),useEffect(()=>{o&&b==="success"&&t?.();},[o,b,t]);let De=l||(G.length>0?G.filter(r=>r.type==="wallet").map(r=>r.id):["phantom","metamask"]),Oe=v!==void 0?v:G.length>0?G.some(r=>r.type==="otp"):true,K=G.filter(r=>r.type==="oauth"),be=new Set(u||[]),Ee=K.filter(r=>be.has(r.id)),we=i?K.filter(r=>!be.has(r.id)):K,Re=async r=>{N(r),S("connecting"),await Q(r)||S("error");},gt=async()=>{N("phantom"),S("connecting");let r=await T("phantom");S(r?"success":"error");},mt=async()=>{N("metamask"),S("connecting");let r=await I();S(r?"success":"error");},ht=async r=>{F("verifying"),he(""),await(h||A)(r)?(F("success"),S("success")):(F("error"),he("Invalid or expired code"),setTimeout(()=>F("idle"),2e3));},yt=async r=>{if(!/^\d{6}$/.test(r))return false;try{let R=await fetch(`${H.replace(/\/$/,"")}/v1/preview-codes/${encodeURIComponent(r)}`,{method:"GET",headers:{Accept:"application/json"}});if(!R.ok)return !1;let L=await R.json();return !L||L.code!==r||L.revoked===!0||typeof L.expiresAt=="number"&&L.expiresAt<=Date.now()||typeof L.tokensRemaining=="number"&&L.tokensRemaining<=0?!1:(typeof window<"u"&&window.localStorage&&window.localStorage.setItem("stacknet-api-key",`pc_${r}`),!0)}catch{return false}},kt=async r=>{q("verifying"),se(""),await(d||yt)(r)?(q("success"),S("success")):(q("error"),se("Invalid or expired preview code"),setTimeout(()=>q("idle"),2e3));},We=()=>{S(z&&!dt?"stack-select":"select"),N(null),O(false),F("idle"),he(""),ye(false),q("idle"),se("");};return jsxs("div",{className:`w-full max-w-md space-y-3 ${n}`,children:[!y&&jsxs("div",{className:"mb-6 text-center",children:[D?.logoUrl&&b!=="stack-select"&&jsx("img",{src:ce(D.logoUrl),alt:D.displayName||"",className:"h-16 w-16 mx-auto mb-4 rounded-xl"}),D?.displayName&&jsx("p",{className:"text-sm text-zinc-400 mb-2",children:D.displayName}),jsx("h1",{className:"font-semibold text-2xl text-white",children:"Log in or Sign up"})]}),b==="stack-select"&&jsxs("div",{className:"space-y-3",children:[jsx("p",{className:"text-center text-sm text-zinc-400 mb-4",children:je.length>0?"Select a network to continue":"No previous connections found. Enter a Stack ID to continue."}),je.map(r=>jsxs("button",{onClick:()=>{ze(r.stackId),S("select");},className:"flex w-full cursor-pointer items-center gap-4 rounded-xl border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[r.logoUrl?jsx("img",{src:ce(r.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:r.name?.[0]?.toUpperCase()||"S"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-white",children:r.name||r.stackId}),jsx("p",{className:"text-xs text-zinc-500",children:r.domain})]}),jsx("span",{className:"text-xs text-zinc-600",children:"Previously connected"})]},r.stackId)),U.ready&&!U.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."})]}),b==="select"&&C&&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%"}})}),k&&b==="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:k}),jsx("button",{className:"mt-3 w-full text-sm text-zinc-400 hover:text-white",onClick:We,children:"Try Again"})]}),b==="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..."})]}),b==="connecting"&&m&&jsxs("div",{style:{border:"1px solid #27272a",background:"#25252f",padding:24,textAlign:"center"},children:[jsxs("div",{style:{width:40,height:40,margin:"0 auto 12px"},children:[E==="phantom"&&jsx(de,{style:B}),E==="metamask"&&jsx(ue,{style:B})]}),jsx("p",{style:{fontWeight:500,fontSize:14,color:"#fff"},children:g.connected?"Signing message...":"Connecting wallet..."}),jsx("p",{style:{marginTop:4,fontSize:12,color:"#71717a"},children:"Please confirm in your wallet"}),jsx("button",{style:{marginTop:16,fontSize:14,color:"#71717a",background:"none",border:"none",cursor:"pointer"},onClick:We,children:"Cancel"})]}),b==="select"&&!m&&!C&&jsxs(Fragment,{children:[Ee.map(r=>jsxs("button",{onClick:()=>Re(r.id),style:J,children:[jsx(ot,{provider:r.id}),jsx("span",{style:{fontWeight:500,color:"#fff"},children:rt(r.id,r.name)})]},r.id)),De.includes("phantom")&&jsxs("button",{onClick:gt,disabled:!ae,style:{...J,opacity:ae?1:.5,cursor:ae?"pointer":"not-allowed"},children:[jsx(de,{style:{...B,borderRadius:8}}),jsx("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:"Phantom"}),!ae&&jsx("span",{style:{fontSize:12,color:"#71717a"},children:"Not installed"})]}),De.includes("metamask")&&pt&&jsxs("button",{onClick:mt,style:J,children:[jsx(ue,{style:B}),jsx("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:"MetaMask"})]}),Oe&&!j&&jsxs("button",{onClick:()=>O(true),style:J,children:[jsx("div",{style:{...B,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8,border:"1px solid #3f3f46",background:"#2a2a3e"},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"20px",viewBox:"0 -960 960 960",width:"20px",fill:"#a1a1aa",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("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:c})]}),f&&!Te&&jsxs("button",{onClick:()=>ye(true),style:J,children:[jsx("div",{style:{...B,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8,border:"1px solid #3f3f46",background:"#2a2a3e"},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"20px",viewBox:"0 -960 960 960",width:"20px",fill:"#a1a1aa",children:jsx("path",{d:"M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm0-80h560v-560H200v560Zm80-80h400v-40H280v40Zm0-120h400v-240H280v240Z"})})}),jsx("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:x})]}),f&&Te&&jsxs("div",{style:{borderRadius:12,border:"1px solid #27272a",background:"#25252f",padding:24},children:[jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginBottom:16},children:"Enter your 6-digit preview code"}),jsx(ne,{onComplete:kt,disabled:ke==="verifying",error:lt}),ke==="verifying"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginTop:16},children:"Verifying..."}),ke==="success"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#4ade80",marginTop:16},children:"Verified!"}),jsx("button",{onClick:()=>{ye(false),q("idle"),se("");},style:{display:"block",marginTop:16,marginLeft:"auto",marginRight:"auto",fontSize:13,color:"#71717a",background:"none",border:"none",cursor:"pointer"},children:"Cancel"})]}),Oe&&j&&jsxs("div",{style:{borderRadius:12,border:"1px solid #27272a",background:"#25252f",padding:24},children:[jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginBottom:16},children:"Enter your 6-digit access code"}),jsx(ne,{onComplete:ht,disabled:_==="verifying",error:V}),_==="verifying"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginTop:16},children:"Verifying..."}),_==="success"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#4ade80",marginTop:16},children:"Verified!"}),D?.webPageUrl&&_==="idle"&&(()=>{let r=ce(D.webPageUrl);return r==="#"?null:jsx("a",{href:`${r.replace(/\/$/,"")}/connect/pair`,target:"_blank",rel:"noopener noreferrer",style:{display:"block",textAlign:"center",fontSize:14,color:"#71717a",marginTop:16},children:"Get code"})})()]}),(i?we:K).length>0&&(!i||we.length>0)&&jsxs(Fragment,{children:[!i&&Ee.length===0&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 0"},children:[jsx("div",{style:{flex:1,borderTop:"1px solid #27272a"}}),jsx("span",{style:{fontSize:12,color:"#52525b"},children:"or continue with"}),jsx("div",{style:{flex:1,borderTop:"1px solid #27272a"}})]}),(i?we:K.filter(r=>!be.has(r.id))).map(r=>jsxs("button",{onClick:()=>Re(r.id),style:J,children:[jsx(ot,{provider:r.id}),jsx("span",{style:{fontWeight:500,color:"#fff"},children:rt(r.id,r.name)})]},r.id))]})]})]})}var B={width:40,height:40,flexShrink:0},J={display:"flex",width:"100%",alignItems:"center",gap:12,borderRadius:12,border:"1px solid #27272a",background:"#25252f",padding:16,cursor:"pointer",transition:"background 0.15s"};function ot({provider:e}){switch(e){case "google":return jsx(Ie,{style:{...B,borderRadius:8}});case "discord":return jsx(Me,{style:{...B,borderRadius:8}});case "twitter":return jsx(Ae,{style:{...B,borderRadius:8}});case "apple":return jsx(Le,{style:{...B,borderRadius:8}});default:return jsx("div",{style:{...B,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8,border:"1px solid #3f3f46",background:"#2a2a3e",fontSize:14,color:"#a1a1aa",fontFamily:"monospace"},children:e[0]?.toUpperCase()})}}function rt(e,t){return {google:"Google",discord:"Discord",twitter:"Twitter",apple:"Apple"}[e]||t||e}function Qt(){if(typeof document>"u")return null;let e=document.cookie.split(";").map(t=>t.trim()).find(t=>t.startsWith("__csrf="));return e?e.slice(7):null}function at(e,t){let[a,l]=useState(null),[v,y]=useState(true),[h,c]=useState(false),[f,d]=useState(null),x=t?.apiBaseUrl??"",i=t?.scope===void 0||t?.scope==="global"?"global":`stack:${t.scope.stackId}`,u=useCallback(o=>{let g=encodeURIComponent(o);if(i==="global")return `${x}/api/user/profile/${g}`;let m=i.slice(6);return `${x}/api/v2/stacks/${encodeURIComponent(m)}/members/${g}/profile`},[x,i]),n=useCallback(async()=>{if(!e){l(null),y(false);return}y(true),d(null);try{let o=await fetch(u(e));if(o.ok){let g=await o.json(),m=g.profile||g.data?.profile||g;l({mid:m.mid||e,username:m.username||"",avatarUrl:m.avatar_url||m.avatarUrl,bio:m.bio,paymentAddress:m.payment_address||m.paymentAddress,createdAt:m.created_at||m.createdAt,updatedAt:m.updated_at||m.updatedAt});}else if(o.status===404)l({mid:e,username:""});else throw new Error(`${o.status}`)}catch(o){d(o instanceof Error?o.message:"Failed to load profile");}finally{y(false);}},[e,u]);useEffect(()=>{n();},[n]);let p=useCallback(async o=>{if(!e)return false;c(true),d(null);try{let g=Qt(),m={};o.username!==void 0&&(m.username=o.username),o.avatarUrl!==void 0&&(m.avatar_url=o.avatarUrl),o.bio!==void 0&&(m.bio=o.bio),o.paymentAddress!==void 0&&(m.payment_address=o.paymentAddress);let k=await fetch(u(e),{method:"PUT",headers:{"Content-Type":"application/json",...g?{"x-csrf-token":g}:{}},credentials:"same-origin",body:JSON.stringify(m)});if(!k.ok){let A=await k.json().catch(()=>({}));throw new Error(A.error||A.message||`Update failed: ${k.status}`)}let T=await k.json(),I=T.profile||T.data?.profile||T;return l(A=>({mid:A?.mid||e,username:o.username??A?.username??"",avatarUrl:o.avatarUrl??A?.avatarUrl,bio:o.bio??A?.bio,paymentAddress:o.paymentAddress??I.payment_address??I.paymentAddress??A?.paymentAddress,createdAt:A?.createdAt,updatedAt:I.updated_at||I.updatedAt||Date.now()})),!0}catch(g){return d(g instanceof Error?g.message:"Update failed"),false}finally{c(false);}},[e,u]);return {profile:a,loading:v,saving:h,error:f,updateProfile:p,refresh:n}}function Yt({mid:e,apiBaseUrl:t="",scope:a,onSave:l,className:v}){let{profile:y,loading:h,saving:c,error:f,updateProfile:d}=at(e,{apiBaseUrl:t,scope:a}),[x,i]=useState(null),[u,n]=useState(null),[p,o]=useState(null),g=useRef(null),[m,k]=useState(false),T=x??y?.username??"",I=u??y?.bio??"",A=p??y?.avatarUrl,Q=useCallback(z=>{let H=z.target.files?.[0];if(!H)return;let D=new FileReader;D.onload=()=>{o(D.result),k(true);},D.readAsDataURL(H);},[]),U=async()=>{await d({username:T||void 0,avatarUrl:p??y?.avatarUrl,bio:I||void 0})&&(k(false),l?.());};if(h)return jsxs("div",{className:v,style:{display:"grid",gap:"1.5rem"},children:[jsx("div",{style:{height:40,background:"var(--x-color-neutral-800, #333)",animation:"pulse 2s infinite"}}),jsx("div",{style:{height:40,background:"var(--x-color-neutral-800, #333)",animation:"pulse 2s infinite"}})]});let $=a==="global"||!a?"Global profile":`Stack profile (${a.stackId})`;return jsxs("div",{className:v,style:{display:"grid",gap:"1.5rem"},children:[jsx("p",{style:{fontSize:11,color:"var(--x-color-neutral-500, #91918D)",textTransform:"uppercase",letterSpacing:"0.05em"},children:$}),jsxs("div",{style:{display:"grid",gap:"1.5rem",gridTemplateColumns:"1fr 1fr"},children:[jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[jsx("label",{style:{fontSize:14,color:"var(--x-color-neutral-400, #91918D)"},children:"Username"}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[jsx("button",{type:"button",onClick:()=>g.current?.click(),style:{width:40,height:40,flexShrink:0,cursor:"pointer",overflow:"hidden",background:"var(--x-color-neutral-800, #262625)",border:"none",position:"relative",display:"flex",alignItems:"center",justifyContent:"center"},children:A?jsx("img",{src:A,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--x-color-neutral-500, #91918D)"},children:[jsx("path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}),jsx("circle",{cx:"12",cy:"7",r:"4"})]})}),jsx("input",{type:"text",value:T,onChange:z=>{i(z.target.value),k(true);},placeholder:"Enter username",maxLength:30,style:{flex:1,padding:"0.75rem 1rem",fontSize:14,background:"var(--x-color-neutral-800, #262625)",color:"var(--x-color-neutral-100, #FAFAF7)",border:"none",outline:"none"}})]}),jsx("input",{ref:g,type:"file",accept:"image/*",onChange:Q,style:{display:"none"}})]}),jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[jsx("label",{style:{fontSize:14,color:"var(--x-color-neutral-400, #91918D)"},children:"Bio"}),jsx("input",{type:"text",value:I,onChange:z=>{n(z.target.value),k(true);},placeholder:"Tell us about yourself",maxLength:200,style:{width:"100%",padding:"0.75rem 1rem",fontSize:14,background:"var(--x-color-neutral-800, #262625)",color:"var(--x-color-neutral-100, #FAFAF7)",border:"none",outline:"none"}})]})]}),f&&jsx("p",{style:{fontSize:13,color:"var(--x-color-red-500, #BF4D43)"},children:f}),m&&jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[jsx("button",{onClick:U,disabled:c,style:{padding:"0.5rem 1.25rem",fontSize:13,fontWeight:700,background:"var(--x-color-blue-600, #165DFC)",color:"#FFF",border:"none",cursor:c?"wait":"pointer",opacity:c?.6:1},children:c?"Saving...":"Save"}),jsx("button",{onClick:()=>{i(null),n(null),o(null),k(false);},style:{padding:"0.5rem 1.25rem",fontSize:13,background:"var(--x-color-neutral-800, #262625)",color:"var(--x-color-neutral-400, #91918D)",border:"none",cursor:"pointer"},children:"Cancel"}),jsx("p",{style:{fontSize:11,color:"var(--x-color-neutral-500, #666663)",alignSelf:"center",marginLeft:"0.5rem"},children:"Profile updates cost 10M tokens"})]})]})}function Vt({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 qt({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 Kt({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
|
+
export{Le as AppleIcon,Ht as ConnectWidget,Me as DiscordIcon,qt as EthereumIcon,Ie as GoogleIcon,ue as MetaMaskIcon,ne as OTPInput,de as PhantomIcon,Yt as ProfileSettings,Vt as SolanaIcon,Kt as TelegramIcon,Ae as TwitterIcon,Ct as UserUtilsProvider,vt as useUserUtilsContext};
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { P as PublicSession } from './auth-c1d7Eji2.cjs';
|
|
2
|
+
|
|
3
|
+
interface BillingPlan {
|
|
4
|
+
id: string;
|
|
5
|
+
name: string;
|
|
6
|
+
price_cents: number;
|
|
7
|
+
token_allocation: number;
|
|
8
|
+
features: string;
|
|
9
|
+
sort_order?: number;
|
|
10
|
+
is_active?: boolean;
|
|
11
|
+
}
|
|
12
|
+
interface Subscription {
|
|
13
|
+
plan?: {
|
|
14
|
+
id: string;
|
|
15
|
+
name: string;
|
|
16
|
+
priceCents: number;
|
|
17
|
+
tokenAllocation: number;
|
|
18
|
+
};
|
|
19
|
+
planId?: string;
|
|
20
|
+
planName?: string;
|
|
21
|
+
status: string;
|
|
22
|
+
tokensUsed?: number;
|
|
23
|
+
tokensRemaining?: number;
|
|
24
|
+
usagePercent?: number;
|
|
25
|
+
periodStart?: number;
|
|
26
|
+
periodEnd?: number;
|
|
27
|
+
cancelAtPeriodEnd?: boolean;
|
|
28
|
+
stripeCustomerId?: string;
|
|
29
|
+
}
|
|
30
|
+
interface UsageSummary {
|
|
31
|
+
ownerId: string;
|
|
32
|
+
planAllocation: number;
|
|
33
|
+
planId: string | null;
|
|
34
|
+
planName: string;
|
|
35
|
+
inferenceUsed: number;
|
|
36
|
+
ledgerSpent: number;
|
|
37
|
+
totalUsed: number;
|
|
38
|
+
remaining: number;
|
|
39
|
+
percent: number;
|
|
40
|
+
exceeded: boolean;
|
|
41
|
+
breakdown: {
|
|
42
|
+
subscription: number;
|
|
43
|
+
prepaidCredit: number;
|
|
44
|
+
tokenGrants: number;
|
|
45
|
+
inference: number;
|
|
46
|
+
skillRegistrations: number;
|
|
47
|
+
skillRegistrationCount: number;
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
interface PrepaidCheckoutResult {
|
|
51
|
+
url: string;
|
|
52
|
+
sessionId?: string;
|
|
53
|
+
}
|
|
54
|
+
interface PrepaidVerifyResult {
|
|
55
|
+
alreadyCredited: boolean;
|
|
56
|
+
tokensCredited?: number;
|
|
57
|
+
amountCents?: number;
|
|
58
|
+
paymentRef?: string;
|
|
59
|
+
}
|
|
60
|
+
interface BillingRecord {
|
|
61
|
+
id: string;
|
|
62
|
+
recorded_at?: number;
|
|
63
|
+
date?: string;
|
|
64
|
+
reason?: string;
|
|
65
|
+
description?: string;
|
|
66
|
+
amount: number;
|
|
67
|
+
direction?: string;
|
|
68
|
+
source?: string;
|
|
69
|
+
status?: string;
|
|
70
|
+
payment_ref?: string;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Decode JWT payload without verification (server-side helper) */
|
|
74
|
+
declare function decodeJWTPayload(jwt: string): Record<string, any> | null;
|
|
75
|
+
/** Sign a JWT with HMAC-SHA256 */
|
|
76
|
+
declare function signJWT(payload: Record<string, any>, secret: string): string;
|
|
77
|
+
/** Verify a JWT signature with HMAC-SHA256 (constant-time comparison) */
|
|
78
|
+
declare function verifyJWTSignature(jwt: string, secret: string): boolean;
|
|
79
|
+
/** Verify JWT and return payload if valid (checks signature + expiry) */
|
|
80
|
+
declare function verifyJWT(jwt: string, secret: string): Record<string, any> | null;
|
|
81
|
+
/**
|
|
82
|
+
* Check if JWT needs refresh and return a new one if so.
|
|
83
|
+
* Returns null if no refresh needed or JWT is invalid.
|
|
84
|
+
*/
|
|
85
|
+
declare function maybeRefreshJWT(jwt: string, secret: string, expirySeconds?: number, refreshWindowSeconds?: number): string | null;
|
|
86
|
+
/** Generate a cryptographically secure random token */
|
|
87
|
+
declare function generateToken(bytes?: number): string;
|
|
88
|
+
/** Options controlling how the real client IP is extracted from a Request.
|
|
89
|
+
*
|
|
90
|
+
* The previous implementation trusted `X-Forwarded-For[0]` unconditionally,
|
|
91
|
+
* which lets any direct caller pin arbitrary values and bypass per-IP rate
|
|
92
|
+
* limits. The correct read depends on how many reverse proxies sit between
|
|
93
|
+
* the app and the real client: with N trusted hops, the real client IP is
|
|
94
|
+
* at position `(length - N)` in the XFF list, because each trusted hop
|
|
95
|
+
* appends its peer IP and the attacker-controlled prefix is pushed left. */
|
|
96
|
+
interface IPExtractorConfig {
|
|
97
|
+
/** Number of trusted reverse-proxy hops between this app and the real client.
|
|
98
|
+
* - `0`: do NOT trust X-Forwarded-For (app is directly internet-exposed).
|
|
99
|
+
* - `1` (default): one trusted proxy (e.g. single LB, Vercel edge, Nginx).
|
|
100
|
+
* - `N`: N trusted hops; the real client IP is `XFF[length - N]`.
|
|
101
|
+
* If XFF has fewer entries than expected, the chain is misconfigured or
|
|
102
|
+
* spoofed and the extractor falls through to the next source. */
|
|
103
|
+
trustedProxyCount?: number;
|
|
104
|
+
/** Trust the `X-Real-IP` header. Only enable if your proxy sets it AND
|
|
105
|
+
* strips any inbound `X-Real-IP` from clients. Default: `false`. */
|
|
106
|
+
trustRealIpHeader?: boolean;
|
|
107
|
+
/** Override entirely — return the real client IP from a request however
|
|
108
|
+
* you know best (e.g. a platform-specific header like `cf-connecting-ip`
|
|
109
|
+
* or `x-vercel-forwarded-for`). If this returns a non-empty string it
|
|
110
|
+
* wins; if it returns null/empty the other strategies run. */
|
|
111
|
+
customExtractor?: (request: Request) => string | null | undefined;
|
|
112
|
+
}
|
|
113
|
+
/** Extract the real client IP address from a request.
|
|
114
|
+
*
|
|
115
|
+
* Default behavior (`trustedProxyCount: 1`) is safe for the common case of
|
|
116
|
+
* one trusted reverse proxy. Consumers with no proxy must pass `0`, and
|
|
117
|
+
* consumers behind multiple proxies must pass the exact hop count. */
|
|
118
|
+
declare function extractIP(request: Request, config?: IPExtractorConfig): string;
|
|
119
|
+
|
|
120
|
+
/** Client-side configuration for UserUtilsProvider */
|
|
121
|
+
interface UserUtilsConfig {
|
|
122
|
+
/** Base URL for API calls (empty string = same origin) */
|
|
123
|
+
apiBaseUrl: string;
|
|
124
|
+
/** StackNet stack identifier */
|
|
125
|
+
stackId?: string;
|
|
126
|
+
/** Direct StackNet URL for client-side API calls (e.g. challenges) */
|
|
127
|
+
stacknetUrl?: string;
|
|
128
|
+
/** Theme preference */
|
|
129
|
+
theme?: 'light' | 'dark' | 'system';
|
|
130
|
+
}
|
|
131
|
+
/** Callbacks for auth and billing events */
|
|
132
|
+
interface UserUtilsCallbacks {
|
|
133
|
+
onAuthSuccess?: (session: PublicSession) => void;
|
|
134
|
+
onAuthError?: (error: Error) => void;
|
|
135
|
+
onLogout?: () => void;
|
|
136
|
+
onSubscriptionChange?: (subscription: Subscription) => void;
|
|
137
|
+
}
|
|
138
|
+
/** Server-side configuration for handler factories */
|
|
139
|
+
interface ServerConfig {
|
|
140
|
+
/** HMAC-SHA256 secret for signing JWTs */
|
|
141
|
+
authSecret: string;
|
|
142
|
+
/** StackNet backend URL (always https://stacknet.magma-rpc.com) */
|
|
143
|
+
stacknetUrl: string;
|
|
144
|
+
/** StackNet stack identifier */
|
|
145
|
+
stackId: string;
|
|
146
|
+
/** JWT secret for re-signing to StackNet (defaults to authSecret) */
|
|
147
|
+
stacknetJwtSecret?: string;
|
|
148
|
+
/** Cookie domain for subdomain sharing (e.g. '.geoff.ai') */
|
|
149
|
+
cookieDomain?: string;
|
|
150
|
+
/** Use Secure flag on cookies (default: true) */
|
|
151
|
+
secureCookies?: boolean;
|
|
152
|
+
/** Session max age in seconds (default: 604800 = 7 days) */
|
|
153
|
+
sessionMaxAge?: number;
|
|
154
|
+
/** JWT expiry in seconds (default: 900 = 15 minutes) */
|
|
155
|
+
jwtExpiry?: number;
|
|
156
|
+
/**
|
|
157
|
+
* Google OAuth client ID (single). Used by createGoogleOneTapHandler to
|
|
158
|
+
* validate the `aud` claim on incoming Google ID tokens. Required for
|
|
159
|
+
* Google One Tap — without it, an ID token issued to any other Google
|
|
160
|
+
* application could be replayed against this endpoint.
|
|
161
|
+
*/
|
|
162
|
+
googleClientId?: string;
|
|
163
|
+
/**
|
|
164
|
+
* Google OAuth client IDs (multiple). Use when the stack accepts tokens
|
|
165
|
+
* from more than one Google client (e.g. web + native).
|
|
166
|
+
*/
|
|
167
|
+
googleClientIds?: string[];
|
|
168
|
+
/**
|
|
169
|
+
* How the handlers should derive the real client IP for rate-limit keys.
|
|
170
|
+
* Defaults to `{ trustedProxyCount: 1 }`. Set `trustedProxyCount: 0` if
|
|
171
|
+
* the app is exposed directly (no proxy) — otherwise any caller can pin
|
|
172
|
+
* their X-Forwarded-For and bypass rate limiting.
|
|
173
|
+
*/
|
|
174
|
+
ipConfig?: IPExtractorConfig;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export { type BillingPlan as B, type IPExtractorConfig as I, type PrepaidCheckoutResult as P, type Subscription as S, type UsageSummary as U, type BillingRecord as a, type PrepaidVerifyResult as b, type UserUtilsCallbacks as c, type UserUtilsConfig as d, type ServerConfig as e, decodeJWTPayload as f, extractIP as g, generateToken as h, verifyJWTSignature as i, maybeRefreshJWT as m, signJWT as s, verifyJWT as v };
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { P as PublicSession } from './auth-c1d7Eji2.js';
|
|
2
|
+
|
|
3
|
+
interface BillingPlan {
|
|
4
|
+
id: string;
|
|
5
|
+
name: string;
|
|
6
|
+
price_cents: number;
|
|
7
|
+
token_allocation: number;
|
|
8
|
+
features: string;
|
|
9
|
+
sort_order?: number;
|
|
10
|
+
is_active?: boolean;
|
|
11
|
+
}
|
|
12
|
+
interface Subscription {
|
|
13
|
+
plan?: {
|
|
14
|
+
id: string;
|
|
15
|
+
name: string;
|
|
16
|
+
priceCents: number;
|
|
17
|
+
tokenAllocation: number;
|
|
18
|
+
};
|
|
19
|
+
planId?: string;
|
|
20
|
+
planName?: string;
|
|
21
|
+
status: string;
|
|
22
|
+
tokensUsed?: number;
|
|
23
|
+
tokensRemaining?: number;
|
|
24
|
+
usagePercent?: number;
|
|
25
|
+
periodStart?: number;
|
|
26
|
+
periodEnd?: number;
|
|
27
|
+
cancelAtPeriodEnd?: boolean;
|
|
28
|
+
stripeCustomerId?: string;
|
|
29
|
+
}
|
|
30
|
+
interface UsageSummary {
|
|
31
|
+
ownerId: string;
|
|
32
|
+
planAllocation: number;
|
|
33
|
+
planId: string | null;
|
|
34
|
+
planName: string;
|
|
35
|
+
inferenceUsed: number;
|
|
36
|
+
ledgerSpent: number;
|
|
37
|
+
totalUsed: number;
|
|
38
|
+
remaining: number;
|
|
39
|
+
percent: number;
|
|
40
|
+
exceeded: boolean;
|
|
41
|
+
breakdown: {
|
|
42
|
+
subscription: number;
|
|
43
|
+
prepaidCredit: number;
|
|
44
|
+
tokenGrants: number;
|
|
45
|
+
inference: number;
|
|
46
|
+
skillRegistrations: number;
|
|
47
|
+
skillRegistrationCount: number;
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
interface PrepaidCheckoutResult {
|
|
51
|
+
url: string;
|
|
52
|
+
sessionId?: string;
|
|
53
|
+
}
|
|
54
|
+
interface PrepaidVerifyResult {
|
|
55
|
+
alreadyCredited: boolean;
|
|
56
|
+
tokensCredited?: number;
|
|
57
|
+
amountCents?: number;
|
|
58
|
+
paymentRef?: string;
|
|
59
|
+
}
|
|
60
|
+
interface BillingRecord {
|
|
61
|
+
id: string;
|
|
62
|
+
recorded_at?: number;
|
|
63
|
+
date?: string;
|
|
64
|
+
reason?: string;
|
|
65
|
+
description?: string;
|
|
66
|
+
amount: number;
|
|
67
|
+
direction?: string;
|
|
68
|
+
source?: string;
|
|
69
|
+
status?: string;
|
|
70
|
+
payment_ref?: string;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Decode JWT payload without verification (server-side helper) */
|
|
74
|
+
declare function decodeJWTPayload(jwt: string): Record<string, any> | null;
|
|
75
|
+
/** Sign a JWT with HMAC-SHA256 */
|
|
76
|
+
declare function signJWT(payload: Record<string, any>, secret: string): string;
|
|
77
|
+
/** Verify a JWT signature with HMAC-SHA256 (constant-time comparison) */
|
|
78
|
+
declare function verifyJWTSignature(jwt: string, secret: string): boolean;
|
|
79
|
+
/** Verify JWT and return payload if valid (checks signature + expiry) */
|
|
80
|
+
declare function verifyJWT(jwt: string, secret: string): Record<string, any> | null;
|
|
81
|
+
/**
|
|
82
|
+
* Check if JWT needs refresh and return a new one if so.
|
|
83
|
+
* Returns null if no refresh needed or JWT is invalid.
|
|
84
|
+
*/
|
|
85
|
+
declare function maybeRefreshJWT(jwt: string, secret: string, expirySeconds?: number, refreshWindowSeconds?: number): string | null;
|
|
86
|
+
/** Generate a cryptographically secure random token */
|
|
87
|
+
declare function generateToken(bytes?: number): string;
|
|
88
|
+
/** Options controlling how the real client IP is extracted from a Request.
|
|
89
|
+
*
|
|
90
|
+
* The previous implementation trusted `X-Forwarded-For[0]` unconditionally,
|
|
91
|
+
* which lets any direct caller pin arbitrary values and bypass per-IP rate
|
|
92
|
+
* limits. The correct read depends on how many reverse proxies sit between
|
|
93
|
+
* the app and the real client: with N trusted hops, the real client IP is
|
|
94
|
+
* at position `(length - N)` in the XFF list, because each trusted hop
|
|
95
|
+
* appends its peer IP and the attacker-controlled prefix is pushed left. */
|
|
96
|
+
interface IPExtractorConfig {
|
|
97
|
+
/** Number of trusted reverse-proxy hops between this app and the real client.
|
|
98
|
+
* - `0`: do NOT trust X-Forwarded-For (app is directly internet-exposed).
|
|
99
|
+
* - `1` (default): one trusted proxy (e.g. single LB, Vercel edge, Nginx).
|
|
100
|
+
* - `N`: N trusted hops; the real client IP is `XFF[length - N]`.
|
|
101
|
+
* If XFF has fewer entries than expected, the chain is misconfigured or
|
|
102
|
+
* spoofed and the extractor falls through to the next source. */
|
|
103
|
+
trustedProxyCount?: number;
|
|
104
|
+
/** Trust the `X-Real-IP` header. Only enable if your proxy sets it AND
|
|
105
|
+
* strips any inbound `X-Real-IP` from clients. Default: `false`. */
|
|
106
|
+
trustRealIpHeader?: boolean;
|
|
107
|
+
/** Override entirely — return the real client IP from a request however
|
|
108
|
+
* you know best (e.g. a platform-specific header like `cf-connecting-ip`
|
|
109
|
+
* or `x-vercel-forwarded-for`). If this returns a non-empty string it
|
|
110
|
+
* wins; if it returns null/empty the other strategies run. */
|
|
111
|
+
customExtractor?: (request: Request) => string | null | undefined;
|
|
112
|
+
}
|
|
113
|
+
/** Extract the real client IP address from a request.
|
|
114
|
+
*
|
|
115
|
+
* Default behavior (`trustedProxyCount: 1`) is safe for the common case of
|
|
116
|
+
* one trusted reverse proxy. Consumers with no proxy must pass `0`, and
|
|
117
|
+
* consumers behind multiple proxies must pass the exact hop count. */
|
|
118
|
+
declare function extractIP(request: Request, config?: IPExtractorConfig): string;
|
|
119
|
+
|
|
120
|
+
/** Client-side configuration for UserUtilsProvider */
|
|
121
|
+
interface UserUtilsConfig {
|
|
122
|
+
/** Base URL for API calls (empty string = same origin) */
|
|
123
|
+
apiBaseUrl: string;
|
|
124
|
+
/** StackNet stack identifier */
|
|
125
|
+
stackId?: string;
|
|
126
|
+
/** Direct StackNet URL for client-side API calls (e.g. challenges) */
|
|
127
|
+
stacknetUrl?: string;
|
|
128
|
+
/** Theme preference */
|
|
129
|
+
theme?: 'light' | 'dark' | 'system';
|
|
130
|
+
}
|
|
131
|
+
/** Callbacks for auth and billing events */
|
|
132
|
+
interface UserUtilsCallbacks {
|
|
133
|
+
onAuthSuccess?: (session: PublicSession) => void;
|
|
134
|
+
onAuthError?: (error: Error) => void;
|
|
135
|
+
onLogout?: () => void;
|
|
136
|
+
onSubscriptionChange?: (subscription: Subscription) => void;
|
|
137
|
+
}
|
|
138
|
+
/** Server-side configuration for handler factories */
|
|
139
|
+
interface ServerConfig {
|
|
140
|
+
/** HMAC-SHA256 secret for signing JWTs */
|
|
141
|
+
authSecret: string;
|
|
142
|
+
/** StackNet backend URL (always https://stacknet.magma-rpc.com) */
|
|
143
|
+
stacknetUrl: string;
|
|
144
|
+
/** StackNet stack identifier */
|
|
145
|
+
stackId: string;
|
|
146
|
+
/** JWT secret for re-signing to StackNet (defaults to authSecret) */
|
|
147
|
+
stacknetJwtSecret?: string;
|
|
148
|
+
/** Cookie domain for subdomain sharing (e.g. '.geoff.ai') */
|
|
149
|
+
cookieDomain?: string;
|
|
150
|
+
/** Use Secure flag on cookies (default: true) */
|
|
151
|
+
secureCookies?: boolean;
|
|
152
|
+
/** Session max age in seconds (default: 604800 = 7 days) */
|
|
153
|
+
sessionMaxAge?: number;
|
|
154
|
+
/** JWT expiry in seconds (default: 900 = 15 minutes) */
|
|
155
|
+
jwtExpiry?: number;
|
|
156
|
+
/**
|
|
157
|
+
* Google OAuth client ID (single). Used by createGoogleOneTapHandler to
|
|
158
|
+
* validate the `aud` claim on incoming Google ID tokens. Required for
|
|
159
|
+
* Google One Tap — without it, an ID token issued to any other Google
|
|
160
|
+
* application could be replayed against this endpoint.
|
|
161
|
+
*/
|
|
162
|
+
googleClientId?: string;
|
|
163
|
+
/**
|
|
164
|
+
* Google OAuth client IDs (multiple). Use when the stack accepts tokens
|
|
165
|
+
* from more than one Google client (e.g. web + native).
|
|
166
|
+
*/
|
|
167
|
+
googleClientIds?: string[];
|
|
168
|
+
/**
|
|
169
|
+
* How the handlers should derive the real client IP for rate-limit keys.
|
|
170
|
+
* Defaults to `{ trustedProxyCount: 1 }`. Set `trustedProxyCount: 0` if
|
|
171
|
+
* the app is exposed directly (no proxy) — otherwise any caller can pin
|
|
172
|
+
* their X-Forwarded-For and bypass rate limiting.
|
|
173
|
+
*/
|
|
174
|
+
ipConfig?: IPExtractorConfig;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export { type BillingPlan as B, type IPExtractorConfig as I, type PrepaidCheckoutResult as P, type Subscription as S, type UsageSummary as U, type BillingRecord as a, type PrepaidVerifyResult as b, type UserUtilsCallbacks as c, type UserUtilsConfig as d, type ServerConfig as e, decodeJWTPayload as f, extractIP as g, generateToken as h, verifyJWTSignature as i, maybeRefreshJWT as m, signJWT as s, verifyJWT as v };
|
package/dist/core/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { a as AuthClientConfig, A as AuthClient } from '../types-
|
|
2
|
-
export { b as AuthTransport } from '../types-
|
|
3
|
-
import '../auth-
|
|
1
|
+
import { a as AuthClientConfig, A as AuthClient } from '../types-B_Vj6cr4.cjs';
|
|
2
|
+
export { b as AuthTransport } from '../types-B_Vj6cr4.cjs';
|
|
3
|
+
import '../auth-c1d7Eji2.cjs';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Platform-agnostic auth client factory.
|
package/dist/core/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { a as AuthClientConfig, A as AuthClient } from '../types-
|
|
2
|
-
export { b as AuthTransport } from '../types-
|
|
3
|
-
import '../auth-
|
|
1
|
+
import { a as AuthClientConfig, A as AuthClient } from '../types-Cu0do-w-.js';
|
|
2
|
+
export { b as AuthTransport } from '../types-Cu0do-w-.js';
|
|
3
|
+
import '../auth-c1d7Eji2.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Platform-agnostic auth client factory.
|