@stacknet/userutils 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import {clsx}from'clsx';import {twMerge}from'tailwind-merge';import {createContext,useState,useCallback,useEffect,useRef,useContext}from'react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';function kt(...e){return twMerge(clsx(e))}function bt(e){return e>=1e12?`${(e/1e12).toFixed(e%1e12===0?0:1)}T`:e>=1e9?`${(e/1e9).toFixed(e%1e9===0?0:1)}B`:e>=1e6?`${(e/1e6).toFixed(e%1e6===0?0:1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:e.toLocaleString()}function wt(e,t){if(!e)return "/";if(e.startsWith("/")&&!e.startsWith("//"))return e;try{let r=new URL(e,t);return r.origin!==t?"/":r.pathname+r.search+r.hash}catch{return "/"}}function xt(e){try{let t=e.split(".");if(t.length!==3)return null;let r=atob(t[1].replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(r)}catch{return null}}function he(){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 W(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 X(){let[e,t]=useState(null),[r,c]=useState(true),m=useCallback(()=>{let o=he();o&&o.expiresAt>Date.now()?t({userId:o.userId,address:o.address,chain:o.chain,expiresAt:o.expiresAt,planId:o.planId,authMethod:o.authMethod}):t(null),c(false);},[]);useEffect(()=>{m();},[m]);let h=useCallback(async(o="")=>{try{let s=await fetch(`${o}/api/auth/session`);if(s.ok){let l=await s.json();if(l.session)return t(l.session),l.session}return t(null),null}catch{return null}},[]),p=!!e&&e.expiresAt>Date.now();return {session:e,loading:r,isAuthenticated:p,refresh:h,readSession:m}}function ye(e="__csrf",t="x-csrf-token"){let[r,c]=useState(null);useEffect(()=>{c(W(e));},[e]);let m=r?{[t]:r}:{};return {token:r,headers:m}}function ke(){let[e,t]=useState({connected:false,address:null,chain:null,provider:null}),[r,c]=useState(null),m=useCallback(async(s="phantom")=>{c(null);try{let l=typeof window<"u"?window:null,g=s==="phantom"?l?.phantom?.solana||l?.solana:l?.solflare;if(!g)return c(`${s} wallet not found`),null;let u=(await g.connect()).publicKey.toString();return t({connected:!0,address:u,chain:"solana",provider:s}),u}catch(l){return c(l.message||"Failed to connect wallet"),null}},[]),h=useCallback(async()=>{c(null);try{let l=(typeof window<"u"?window:null)?.ethereum;if(!l)return c("MetaMask not found"),null;let g=l;l.providers?.length&&(g=l.providers.find(n=>n.isMetaMask)||l);let u=(await g.request({method:"eth_requestAccounts"}))[0];return u?(t({connected:!0,address:u,chain:"ethereum",provider:"metamask"}),u):(c("No account selected"),null)}catch(s){return c(s.message||"Failed to connect wallet"),null}},[]),p=useCallback(async(s,l)=>{c(null);let g=l?.chain||e.chain,i=l?.provider||e.provider,u=l?.address||e.address;try{if(g==="solana"){let n=typeof window<"u"?window:null,y=i==="solflare"?n?.solflare:n?.phantom?.solana||n?.solana;if(!y)throw new Error("Wallet not available");let a=new TextEncoder().encode(s),b=await y.signMessage(a,"utf8"),v=new Uint8Array(b.signature||b),w="";for(let T=0;T<v.byteLength;T++)w+=String.fromCharCode(v[T]);return btoa(w)}if(g==="ethereum"){let y=(typeof window<"u"?window:null)?.ethereum;if(y?.providers?.length&&(y=y.providers.find(b=>b.isMetaMask)||y),!y)throw new Error("MetaMask not available");return await y.request({method:"personal_sign",params:[s,u]})}throw new Error("No wallet connected")}catch(n){return c(n.message||"Signing failed"),null}},[e]),o=useCallback(()=>{t({connected:false,address:null,chain:null,provider:null}),c(null);},[]);return {wallet:e,error:r,connectSolana:m,connectEVM:h,signMessage:p,disconnect:o}}var Mt="https://stacknet.magma-rpc.com/auth/bridge",ae="stacknet-auth-bridge";function we(e){let t=e?.bridgeUrl||Mt,r=e?.disabled||false,c=useRef(null),[m,h]=useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),p=useRef([]),o=useRef(false),s=useCallback(n=>{let y={...n,protocol:ae};o.current&&c.current?.contentWindow?c.current.contentWindow.postMessage(y,new URL(t).origin):p.current.push(y);},[t]);useEffect(()=>{if(r)return;let n=a=>{if(!(!a.data||a.data.protocol!==ae)){try{if(a.origin!==new URL(t).origin)return}catch{return}switch(a.data.type){case "bridge:ready":o.current=true,h(b=>({...b,ready:true}));for(let b of p.current)c.current?.contentWindow?.postMessage(b,a.origin);p.current=[],c.current?.contentWindow?.postMessage({protocol:ae,type:"auth:check"},a.origin),c.current?.contentWindow?.postMessage({protocol:ae,type:"auth:resolve-stack"},a.origin);break;case "auth:status":h(b=>({...b,known:a.data.known,identity:a.data.identity,identityCount:a.data.identityCount||0}));break;case "auth:resolved-stack":h(b=>({...b,resolvedStackId:a.data.stackId||null}));break;}}};window.addEventListener("message",n);let y=document.createElement("iframe");return y.src=t,y.style.display="none",y.setAttribute("aria-hidden","true"),y.setAttribute("tabindex","-1"),y.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(y),c.current=y,()=>{window.removeEventListener("message",n),y.parentNode&&y.parentNode.removeChild(y),c.current=null,o.current=false;}},[t,r]);let l=useCallback(n=>{s({type:"auth:connected",...n});},[s]),g=useCallback(n=>{s({type:"auth:disconnected",...n});},[s]),i=useCallback(()=>{s({type:"auth:clear"}),h({ready:m.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[s,m.ready]),u=useCallback(()=>{s({type:"auth:check"});},[s]);return {...m,reportConnected:l,reportDisconnected:g,clearAll:i,refresh:u}}async function qe(e,t,r,c){let m=e.apiVersion||"v2",h=`${e.baseUrl}/api/${m}${r}`;try{let p=await fetch(h,{method:t,headers:{"Content-Type":"application/json"},body:c?JSON.stringify(c):void 0}),o=await p.json();return p.ok?o.success&&o.data!==void 0?{success:!0,data:o.data}:{success:!0,data:o}:{success:!1,error:o.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(p){return {success:false,error:{code:"NETWORK_ERROR",message:p instanceof Error?p.message:"Network error"}}}}function xe(e){return {getNetworkStatus:()=>qe(e,"GET","/network/status"),getWeb3Challenge:(t,r)=>qe(e,"POST",`/stacks/${e.stackId}/auth/web3/challenge`,{chain:t,address:r})}}function Ce(e={apiBaseUrl:""}){let{wallet:t,connectSolana:r,connectEVM:c,signMessage:m,disconnect:h}=ke(),{session:p,isAuthenticated:o,refresh:s,readSession:l}=X(),{headers:g}=ye(),i=we({disabled:typeof window>"u"}),[u,n]=useState(false),[y,a]=useState(null),[b,v]=useState(false),w=e.apiBaseUrl||"",T=e.stacknetUrl||"https://stacknet.magma-rpc.com",x=e.stackId||i.resolvedStackId||"",S=xe({baseUrl:T,stackId:x}),O=useCallback(async(N,I,E,R)=>{n(true),a(null);try{let L=I;if(!L){let Y=await E();if(!Y)return n(!1),!1;L=Y;}let D=await S.getWeb3Challenge(N,L);if(!D.success||!D.data)return a("Failed to get challenge"),n(!1),!1;let Q=await m(D.data.message,{chain:N,provider:R,address:L});if(!Q)return n(!1),!1;let V={chain:N,message:D.data.message,signature:Q,stackId:x};N==="solana"&&(V.publicKey=L);let Z=await fetch(`${w}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(V)});if(!Z.ok){let Y=await Z.json().catch(()=>({}));return a(Y.error||"Authentication failed"),n(!1),!1}return i.reportConnected({address:L,chain:N,method:R||(N==="solana"?"phantom":"metamask"),stackId:x}),l(),n(!1),!0}catch(L){return a(L.message||"Authentication failed"),n(false),false}},[w,S,m,l,i,x]),_=useCallback(async(N="phantom")=>{let I=await r(N);return I?O("solana",I,()=>r(N),N):false},[r,O]),j=useCallback(async()=>{let N=await c();return N?O("ethereum",N,c,"metamask"):false},[c,O]),k=useCallback(async N=>{n(true),a(null);try{let I=await fetch(`${w}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:N})});if(!I.ok){let E=await I.json().catch(()=>({}));return a(E.error||"Invalid code"),n(!1),!1}return l(),n(!1),!0}catch(I){return a(I.message||"OTP verification failed"),n(false),false}},[w,l]),U=useCallback(async(N,I)=>{n(true),a(null);try{let E=I||`${window.location.origin}/api/auth/oauth/callback`,R=new URLSearchParams({provider:N,redirectUri:E,stackId:x}),L=await fetch(`${w}/api/auth/oauth/start?${R}`);if(!L.ok){let Q=await L.json().catch(()=>({}));return a(Q.error||"Failed to start OAuth flow"),n(!1),!1}let D=await L.json();return D.redirect_url?(typeof sessionStorage<"u"&&(sessionStorage.setItem("oauth_state",D.state||""),sessionStorage.setItem("oauth_provider",N)),window.location.href=D.redirect_url,!0):(a("No redirect URL returned"),n(!1),!1)}catch(E){return a(E.message||"OAuth flow failed"),n(false),false}},[w,x]),M=useCallback(async(N,I,E)=>{n(true),a(null);try{let R=await fetch(`${w}/api/auth/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:N,code:I,state:E,stackId:x})});if(!R.ok){let L=await R.json().catch(()=>({}));return a(L.error||"OAuth authentication failed"),n(!1),!1}return l(),n(!1),!0}catch(R){return a(R.message||"OAuth callback failed"),n(false),false}},[w,x,l]),z=useCallback(async()=>{t.address&&t.chain&&i.reportDisconnected({address:t.address,chain:t.chain,stackId:x});try{await fetch(`${w}/api/auth/logout`,{method:"POST",headers:g});}catch{}h(),l();},[w,g,h,l,t,i,x]);return useEffect(()=>{if(!e.autoConnect||b||o||!i.ready||!i.known||!i.identity)return;v(true);let{chain:N,method:I}=i.identity;N==="solana"&&(I==="phantom"||I==="solflare")?_(I):N==="ethereum"&&j();},[e.autoConnect,b,o,i,_,j]),{session:p,isAuthenticated:o,wallet:t,loading:u,error:y,authenticateSolana:_,authenticateEVM:j,authenticateOTP:k,authenticateOAuth:U,authenticateOAuthCallback:M,logout:z,refresh:()=>s(w),stackId:x,bridge:{ready:i.ready,known:i.known,identity:i.identity,identityCount:i.identityCount,resolvedStackId:i.resolvedStackId}}}function te(e,t="https://stacknet.magma-rpc.com"){let[r,c]=useState(null),[m,h]=useState(false),[p,o]=useState(null),s=useCallback(async g=>{h(true),o(null);try{let i=await fetch(`${t}/api/v2/stacks/${g}`);if(!i.ok)return o("Stack not found"),h(!1),null;let u=await i.json(),n=u.data?.stack||u.stack||u,y={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(a=>({provider:a.provider,clientId:a.clientId,enabled:a.enabled!==!1}))};return c(y),h(!1),y}catch(i){return o(i.message),h(false),null}},[t]);useEffect(()=>{e&&s(e);},[e,s]);let l=r?Tt(r):[];return {config:r,loading:m,error:p,identityProviders:l,fetchConfig:s}}function Tt(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 zt(e=""){let[t,r]=useState([]),[c,m]=useState(true),[h,p]=useState(null),o=useCallback(async()=>{try{let s=await fetch(`${e}/api/billing/plans`);if(s.ok){let l=await s.json();r(l.plans||l||[]);}}catch(s){p(s.message);}finally{m(false);}},[e]);return useEffect(()=>{o();},[o]),{plans:t,loading:c,error:h,refresh:o}}function Dt(e=""){let[t,r]=useState(null),[c,m]=useState(true),[h,p]=useState(null),o=useCallback(async()=>{try{let g=await fetch(`${e}/api/billing/subscription`);if(g.ok){let i=await g.json();r(i.plan?i:null);}}catch(g){p(g.message);}finally{m(false);}},[e]);useEffect(()=>{o();},[o]);let s=useCallback(async g=>{let i=W(),n=await(await fetch(`${e}/api/billing/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",...i?{"x-csrf-token":i}:{}},body:JSON.stringify({planId:g})})).json();return n.url||n.checkoutUrl||null},[e]),l=useCallback(async()=>{let g=W();return (await fetch(`${e}/api/billing/cancel`,{method:"POST",headers:g?{"x-csrf-token":g}:{}})).ok?(await o(),true):false},[e,o]);return {subscription:t,loading:c,error:h,refresh:o,subscribe:s,cancel:l}}function _t(e=""){let[t,r]=useState(null),[c,m]=useState(true),[h,p]=useState(null),o=useCallback(async()=>{try{let s=await fetch(`${e}/api/billing/usage`);if(s.ok){let l=await s.json();r(l);}}catch(s){p(s.message);}finally{m(false);}},[e]);return useEffect(()=>{o();},[o]),{usage:t,loading:c,error:h,refresh:o}}function Wt(e=""){let[t,r]=useState(false),[c,m]=useState(null),h=useCallback(async o=>{r(true),m(null);try{let s=W(),l=await fetch(`${e}/api/billing/prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...s?{"x-csrf-token":s}:{}},body:JSON.stringify({amountCents:o})}),g=await l.json();return l.ok?g.url||null:(m(g.error||"Purchase failed"),null)}catch(s){return m(s.message),null}finally{r(false);}},[e]),p=useCallback(async o=>{r(true),m(null);try{let s=W(),l=await fetch(`${e}/api/billing/verify-prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...s?{"x-csrf-token":s}:{}},body:JSON.stringify({sessionId:o})}),g=await l.json();return l.ok?g:(m(g.error||"Verification failed"),null)}catch(s){return m(s.message),null}finally{r(false);}},[e]);return {purchase:h,verifySession:p,loading:t,error:c}}function Gt(e="",t){let[r,c]=useState([]),[m,h]=useState(true),[p,o]=useState(null),s=t?.limit||50,l=t?.offset||0,g=useCallback(async()=>{try{let i=await fetch(`${e}/api/billing/history?limit=${s}&offset=${l}`);if(i.ok){let u=await i.json();c(u.records||u.history||(Array.isArray(u)?u:[]));}}catch(i){o(i.message);}finally{h(false);}},[e,s,l]);return useEffect(()=>{g();},[g]),{records:r,loading:m,error:p,refresh:g}}function Ht(){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 Te(e,t){let[r,c]=useState(null),[m,h]=useState(true),[p,o]=useState(false),[s,l]=useState(null),g=t?.apiBaseUrl??"",i=t?.scope??"global",u=useCallback(a=>i==="global"?`${g}/api/user/profile/${a}`:`${g}/api/v2/stacks/${i.stackId}/members/${a}/profile`,[g,i]),n=useCallback(async()=>{if(!e){c(null),h(false);return}h(true),l(null);try{let a=await fetch(u(e));if(a.ok){let b=await a.json(),v=b.profile||b.data?.profile||b;c({mid:v.mid||e,username:v.username||"",avatarUrl:v.avatar_url||v.avatarUrl,bio:v.bio,createdAt:v.created_at||v.createdAt,updatedAt:v.updated_at||v.updatedAt});}else if(a.status===404)c({mid:e,username:""});else throw new Error(`${a.status}`)}catch(a){l(a instanceof Error?a.message:"Failed to load profile");}finally{h(false);}},[e,u]);useEffect(()=>{n();},[n]);let y=useCallback(async a=>{if(!e)return false;o(true),l(null);try{let b=Ht(),v=await fetch(u(e),{method:"PUT",headers:{"Content-Type":"application/json",...b?{"x-csrf-token":b}:{}},credentials:"same-origin",body:JSON.stringify({username:a.username,avatar_url:a.avatarUrl,bio:a.bio})});if(!v.ok){let x=await v.json().catch(()=>({}));throw new Error(x.error||x.message||`Update failed: ${v.status}`)}let w=await v.json(),T=w.profile||w.data?.profile||w;return c(x=>({mid:x?.mid||e,username:a.username??x?.username??"",avatarUrl:a.avatarUrl??x?.avatarUrl,bio:a.bio??x?.bio,createdAt:x?.createdAt,updatedAt:T.updated_at||T.updatedAt||Date.now()})),!0}catch(b){return l(b instanceof Error?b.message:"Update failed"),false}finally{o(false);}},[e,u]);return {profile:r,loading:m,saving:p,error:s,updateProfile:y,refresh:n}}var nt="google-identity-services",Qt="https://accounts.google.com/gsi/client";function Vt({stackId:e,stacknetUrl:t="https://stacknet.magma-rpc.com",apiBaseUrl:r="",autoPrompt:c=true,cancelOnTapOutside:m=true,onSuccess:h,onError:p,disabled:o=false}){let{config:s}=te(e,t),{isAuthenticated:l,loading:g,readSession:i}=X(),[u,n]=useState(false),[y,a]=useState(null),[b,v]=useState(false),w=useRef(false),T=useRef(false),S=s?.oauthProviders?.find(k=>k.provider==="google"&&k.enabled&&k.clientId)?.clientId||null;useEffect(()=>{if(o||!S||typeof window>"u")return;if(document.getElementById(nt)){v(true);return}let k=document.createElement("script");k.id=nt,k.src=Qt,k.async=true,k.defer=true,k.onload=()=>v(true),k.onerror=()=>{a("Failed to load Google sign-in"),p?.("Failed to load Google Identity Services script");},document.head.appendChild(k);},[o,S,p]);let O=useCallback(async k=>{n(true),a(null);try{let U=await fetch(`${r}/api/auth/google/one-tap`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({credential:k.credential,stackId:e})});if(!U.ok){let z=(await U.json().catch(()=>({}))).error||"Google sign-in failed";a(z),p?.(z),n(!1);return}i(),n(!1),h?.();}catch(U){let M=U.message||"Google sign-in failed";a(M),p?.(M),n(false);}},[r,e,i,h,p]);useEffect(()=>{if(o){console.debug("[GoogleOneTap] Disabled");return}if(!b){console.debug("[GoogleOneTap] Script not loaded yet, clientId:",S);return}if(!S){console.debug("[GoogleOneTap] No Google clientId from stack config");return}if(g){console.debug("[GoogleOneTap] Session still loading");return}if(l){console.debug("[GoogleOneTap] User already authenticated, skipping");return}if(!window.google?.accounts?.id){console.debug("[GoogleOneTap] GIS library not available on window");return}w.current||(console.debug("[GoogleOneTap] Initializing with clientId:",S),w.current=true,window.google.accounts.id.initialize({client_id:S,callback:O,auto_select:true,cancel_on_tap_outside:m}),c&&!T.current&&(T.current=true,console.debug("[GoogleOneTap] Showing prompt..."),window.google.accounts.id.prompt(k=>{k.isDisplayed?.()&&console.debug("[GoogleOneTap] Prompt displayed"),k.isNotDisplayed?.()&&console.debug("[GoogleOneTap] Not displayed:",k.getNotDisplayedReason?.()),k.isSkippedMoment?.()&&console.debug("[GoogleOneTap] Skipped:",k.getSkippedReason?.()),k.isDismissedMoment?.()&&console.debug("[GoogleOneTap] Dismissed:",k.getDismissedReason?.());})));},[o,b,S,g,l,O,c,m]),useEffect(()=>()=>{window.google?.accounts?.id&&w.current&&window.google.accounts.id.cancel();},[]);let _=useCallback(()=>{!window.google?.accounts?.id||!w.current||window.google.accounts.id.prompt();},[]),j=useCallback((k,U)=>{!k||!window.google?.accounts?.id||!w.current||window.google.accounts.id.renderButton(k,{theme:U?.theme||"filled_black",size:U?.size||"large",text:U?.text||"signin_with",width:U?.width});},[]);return {available:!!S,ready:b&&!!S,loading:u,error:y,prompt:_,renderButton:j,clientId:S}}var ot=createContext(null);function Jt(){let e=useContext(ot);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function Kt({config:e,callbacks:t,children:r}){return jsx(ot.Provider,{value:{config:e,callbacks:t},children:r})}function le({length:e=6,onComplete:t,disabled:r=false,error:c,className:m="",inputClassName:h=""}){let [p,o]=useState(Array(e).fill("")),s=useCallback((i,u)=>{if(u.length>1){let y=u.replace(/\D/g,"").slice(0,e).split(""),a=[...p];y.forEach((v,w)=>{i+w<e&&(a[i+w]=v);}),o(a);let b=Math.min(i+y.length,e-1);document.getElementById(`userutils-otp-${b}`)?.focus(),a.every(v=>v!=="")&&setTimeout(()=>t(a.join("")),100);return}if(!/^\d?$/.test(u))return;let n=[...p];n[i]=u,o(n),u&&i<e-1&&document.getElementById(`userutils-otp-${i+1}`)?.focus(),u&&i===e-1&&n.every(y=>y!=="")&&setTimeout(()=>t(n.join("")),100);},[p,e,t]),l=useCallback((i,u)=>{if(u.key==="Backspace"&&!p[i]&&i>0){document.getElementById(`userutils-otp-${i-1}`)?.focus();let n=[...p];n[i-1]="",o(n);}if(u.key==="Enter"){let n=p.join("");n.length===e&&t(n);}},[p,e,t]);useCallback(()=>{o(Array(e).fill("")),document.getElementById("userutils-otp-0")?.focus();},[e]);return jsxs("div",{className:m,children:[jsx("div",{className:"flex gap-2 justify-center",children:p.map((i,u)=>jsx("input",{id:`userutils-otp-${u}`,type:"text",inputMode:"numeric",maxLength:e,value:i,onChange:n=>s(u,n.target.value),onKeyDown:n=>l(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 ${h}`},u))}),c&&jsx("p",{className:"text-center text-sm text-red-400 mt-2",children:c})]})}le.displayName="OTPInput";var tn="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function ce({className:e}){return jsx("img",{src:tn,alt:"Phantom",className:e})}function de({className:e}){return jsxs("svg",{className:e,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 507.83 470.86",children:[jsx("polygon",{fill:"#e2761b",stroke:"#e2761b",strokeLinecap:"round",strokeLinejoin:"round",points:"482.09 0.5 284.32 147.38 320.9 60.72 482.09 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"25.54 0.5 221.72 148.77 186.93 60.72 25.54 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"410.93 340.97 358.26 421.67 470.96 452.67 503.36 342.76 410.93 340.97"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"4.67 342.76 36.87 452.67 149.57 421.67 96.9 340.97 4.67 342.76"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 111.8 252.13 223.7 257.1 219.73 136.85 143.21 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"364.42 204.62 286.91 135.46 284.32 257.1 396.03 252.13 364.42 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 216.75 388.87 158.71 343.55 149.57 421.67"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 358.26 421.67 348.92 343.55 290.88 388.87"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"358.26 421.67 290.88 388.87 296.25 432.8 295.65 451.28 358.26 421.67"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 212.18 451.28 211.78 432.8 216.75 388.87 149.57 421.67"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"213.17 314.54 157.12 298.04 196.67 279.95 213.17 314.54"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"294.46 314.54 310.96 279.95 350.71 298.04 294.46 314.54"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 159.11 340.97 96.9 342.76 149.57 421.67"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"348.72 340.97 358.26 421.67 410.93 342.76 348.72 340.97"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"396.03 252.13 284.32 257.1 294.66 314.54 311.16 279.95 350.91 298.04 396.03 252.13"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 196.87 279.95 213.17 314.54 223.7 257.1 111.8 252.13 157.12 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"111.8 252.13 158.71 343.55 157.12 298.04 111.8 252.13"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"350.91 298.04 348.92 343.55 396.03 252.13 350.91 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"223.7 257.1 213.17 314.54 226.29 382.31 229.27 293.07 223.7 257.1"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 278.96 292.87 281.34 382.31 294.66 314.54 284.32 257.1"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"294.66 314.54 281.34 382.31 290.88 388.87 348.92 343.55 350.91 298.04 294.66 314.54"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 158.71 343.55 216.75 388.87 226.29 382.31 213.17 314.54 157.12 298.04"}),jsx("polygon",{fill:"#c0ad9e",stroke:"#c0ad9e",strokeLinecap:"round",strokeLinejoin:"round",points:"295.65 451.28 296.25 432.8 291.28 428.42 216.35 428.42 211.78 432.8 212.18 451.28 149.57 421.67 171.43 439.55 215.75 470.36 291.88 470.36 336.4 439.55 358.26 421.67 295.65 451.28"}),jsx("polygon",{fill:"#161616",stroke:"#161616",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 281.34 382.31 226.29 382.31 216.75 388.87 211.78 432.8 216.35 428.42 291.28 428.42 296.25 432.8 290.88 388.87"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"490.44 156.92 507.33 75.83 482.09 0.5 290.88 142.41 364.42 204.62 468.37 235.03 491.43 208.2 481.49 201.05 497.39 186.54 485.07 177 500.97 164.87 490.44 156.92"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"0.5 75.83 17.39 156.92 6.66 164.87 22.56 177 10.44 186.54 26.34 201.05 16.4 208.2 39.26 235.03 143.21 204.62 216.75 142.41 25.54 0.5 0.5 75.83"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"468.37 235.03 364.42 204.62 396.03 252.13 348.92 343.55 410.93 342.76 503.36 342.76 468.37 235.03"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 39.26 235.03 4.67 342.76 96.9 342.76 158.71 343.55 111.8 252.13 143.21 204.62"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 290.88 142.41 321.1 60.72 186.93 60.72 216.75 142.41 223.7 257.1 226.09 293.27 226.29 382.31 281.34 382.31 281.74 293.27 284.32 257.1"})]})}function Ee({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 _e({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 We({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#F1F2F9"}),jsx("path",{d:"M26.1001 16.2273C26.1001 15.5182 26.0365 14.8364 25.9183 14.1818H16.5001V18.05H21.8819C21.6501 19.3 20.9456 20.3591 19.8865 21.0682V23.5773H23.1183C25.0092 21.8364 26.1001 19.2727 26.1001 16.2273Z",fill:"#4285F4"}),jsx("path",{d:"M16.5001 26C19.2001 26 21.4637 25.1046 23.1182 23.5773L19.8864 21.0682C18.991 21.6682 17.8455 22.0227 16.5001 22.0227C13.8955 22.0227 11.691 20.2637 10.9046 17.9H7.56372V20.4909C9.20917 23.7591 12.591 26 16.5001 26Z",fill:"#34A853"}),jsx("path",{d:"M10.9047 17.8999C10.7047 17.2999 10.591 16.659 10.591 15.9999C10.591 15.3408 10.7047 14.6999 10.9047 14.0999V11.509H7.56376C6.86376 12.9025 6.49951 14.4405 6.50012 15.9999C6.50012 17.6136 6.88649 19.1408 7.56376 20.4908L10.9047 17.8999Z",fill:"#FBBC05"}),jsx("path",{d:"M16.5001 9.97726C17.9682 9.97726 19.2864 10.4818 20.3228 11.4727L23.191 8.60454C21.4591 6.99091 19.1955 6 16.5001 6C12.591 6 9.20917 8.2409 7.56372 11.5091L10.9046 14.1C11.691 11.7364 13.8955 9.97726 16.5001 9.97726Z",fill:"#EA4335"})]})}function $e({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#5462EB"}),jsx("path",{d:"M23.5433 8.87438C22.2479 8.26174 20.8587 7.81038 19.4063 7.55187C19.3799 7.54688 19.3534 7.55934 19.3398 7.58428C19.1612 7.91179 18.9633 8.33905 18.8247 8.67487C17.2625 8.43382 15.7084 8.43382 14.1782 8.67487C14.0396 8.33158 13.8345 7.91179 13.6551 7.58428C13.6414 7.56018 13.615 7.54771 13.5886 7.55187C12.1369 7.80955 10.7478 8.26092 9.45159 8.87438C9.44037 8.87937 9.43075 8.88769 9.42437 8.89849C6.78947 12.9558 6.06766 16.9134 6.42176 20.8219C6.42336 20.841 6.43378 20.8593 6.4482 20.871C8.18663 22.1868 9.87059 22.9857 11.5233 23.5152C11.5497 23.5235 11.5778 23.5135 11.5946 23.491C11.9855 22.9408 12.334 22.3606 12.6328 21.7504C12.6505 21.7147 12.6336 21.6723 12.5976 21.6581C12.0448 21.442 11.5185 21.1785 11.0122 20.8793C10.9721 20.8552 10.9689 20.7961 11.0058 20.7679C11.1123 20.6856 11.2189 20.6 11.3206 20.5135C11.339 20.4977 11.3647 20.4944 11.3863 20.5044C14.7125 22.0696 18.3136 22.0696 21.6006 20.5044C21.6222 20.4936 21.6479 20.4969 21.6671 20.5127C21.7688 20.5991 21.8754 20.6856 21.9827 20.7679C22.0196 20.7961 22.0172 20.8552 21.9771 20.8793C21.4708 21.1843 20.9445 21.442 20.3909 21.6573C20.3548 21.6715 20.3388 21.7147 20.3564 21.7504C20.6617 22.3597 21.0101 22.9399 21.3939 23.4902C21.4099 23.5135 21.4387 23.5235 21.4652 23.5152C23.1259 22.9857 24.8099 22.1868 26.5483 20.871C26.5635 20.8593 26.5731 20.8419 26.5747 20.8228C26.9985 16.3041 25.8649 12.3789 23.5697 8.89931C23.5641 8.88769 23.5545 8.87937 23.5433 8.87438Z",fill:"#F7F7F7"})]})}function Fe({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"black"}),jsx("path",{d:"M8.53901 8L14.7164 16.2153L8.5 22.8947H9.89907L15.3415 17.0468L19.7389 22.8947H24.5L17.975 14.2173L23.7612 8H22.3621L17.3499 13.3858L13.3001 8H8.53901ZM10.5964 9.02501H12.7837L22.4422 21.8695H20.255L10.5964 9.02501Z",fill:"#F7F7F7"})]})}function cn({config:e,onSuccess:t,title:r="Log in or Sign up",showWallets:c,showOTP:m,hideHeader:h,onOTPSubmit:p,otpLabel:o="Access Code",oauthInline:s,oauthFirst:l,className:g=""}){let i=Ce(e),{isAuthenticated:u,wallet:n,loading:y,error:a,authenticateSolana:b,authenticateEVM:v,authenticateOTP:w,authenticateOAuth:T,bridge:x,stackId:S}=i,O=!e.stackId&&!S,_=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:j,identityProviders:k,loading:U}=te(S||e.stackId||null,_),[M,z]=useState(O?"stack-select":"select"),[N,I]=useState(null),[E,R]=useState(false),[L,D]=useState("idle"),[Q,V]=useState(""),[Z,Y]=useState([]),[ct,Ge]=useState(e.stackId||null),[re,dt]=useState(false),[ut,ft]=useState(false);useEffect(()=>{if(typeof window>"u")return;let f=()=>{let B=window;dt(!!(B.phantom?.solana?.isPhantom||B.solana?.isPhantom));let K=B.ethereum;ft(!!(K?.isMetaMask||K?.providers?.some(q=>q.isMetaMask)));};f(),window.addEventListener("ethereum#initialized",f);let F=setTimeout(f,500);return ()=>{window.removeEventListener("ethereum#initialized",f),clearTimeout(F);}},[]),useEffect(()=>{M==="stack-select"&&S&&(Ge(S),z("select"));},[M,S]),useEffect(()=>{if(!(!x.ready||!O)&&x.identity){let f=[];x.resolvedStackId&&f.push({stackId:x.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(f.map(async F=>{try{let B=await fetch(`${_}/api/v2/stacks/${F.stackId}`);if(B.ok){let K=await B.json(),q=K.data?.stack||K;F.name=q.displayName||q.name,F.logoUrl=q.logoUrl;}}catch{}return F})).then(Y);}},[x.ready,x.identity,x.resolvedStackId,O,_]),useEffect(()=>{u&&M==="success"&&t?.();},[u,M,t]);let Be=c||(k.length>0?k.filter(f=>f.type==="wallet").map(f=>f.id):["phantom","metamask"]),He=m!==void 0?m:k.length>0?k.some(f=>f.type==="otp"):true,J=k.filter(f=>f.type==="oauth"),ge=new Set(l||[]),Qe=J.filter(f=>ge.has(f.id)),me=s?J.filter(f=>!ge.has(f.id)):J,Ve=async f=>{I(f),z("connecting"),await T(f)||z("error");},pt=async()=>{I("phantom"),z("connecting");let f=await b("phantom");z(f?"success":"error");},gt=async()=>{I("metamask"),z("connecting");let f=await v();z(f?"success":"error");},mt=async f=>{D("verifying"),V(""),await(p||w)(f)?(D("success"),z("success")):(D("error"),V("Invalid or expired code"),setTimeout(()=>D("idle"),2e3));},Ye=()=>{z(O&&!ct?"stack-select":"select"),I(null),R(false),D("idle"),V("");};return jsxs("div",{className:`w-full max-w-md space-y-3 ${g}`,children:[!h&&jsxs("div",{className:"mb-6 text-center",children:[j?.logoUrl&&M!=="stack-select"&&jsx("img",{src:j.logoUrl,alt:j.displayName||"",className:"h-16 w-16 mx-auto mb-4 rounded-xl"}),j?.displayName&&jsx("p",{className:"text-sm text-zinc-400 mb-2",children:j.displayName}),jsx("h1",{className:"font-semibold text-2xl text-white",children:"Log in or Sign up"})]}),M==="stack-select"&&jsxs("div",{className:"space-y-3",children:[jsx("p",{className:"text-center text-sm text-zinc-400 mb-4",children:Z.length>0?"Select a network to continue":"No previous connections found. Enter a Stack ID to continue."}),Z.map(f=>jsxs("button",{onClick:()=>{Ge(f.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:[f.logoUrl?jsx("img",{src:f.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:f.name?.[0]?.toUpperCase()||"S"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-white",children:f.name||f.stackId}),jsx("p",{className:"text-xs text-zinc-500",children:f.domain})]}),jsx("span",{className:"text-xs text-zinc-600",children:"Previously connected"})]},f.stackId)),x.ready&&!x.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."})]}),M==="select"&&U&&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%"}})}),a&&M==="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:a}),jsx("button",{className:"mt-3 w-full text-sm text-zinc-400 hover:text-white",onClick:Ye,children:"Try Again"})]}),M==="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..."})]}),M==="connecting"&&y&&jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 text-center",children:[jsxs("div",{className:"mx-auto mb-3 h-14 w-14 animate-pulse",children:[N==="phantom"&&jsx(ce,{className:"h-14 w-14"}),N==="metamask"&&jsx(de,{className:"h-14 w-14"})]}),jsx("p",{className:"font-medium text-sm text-white",children:n.connected?"Signing message...":"Connecting wallet..."}),jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Please confirm in your wallet"}),jsx("button",{className:"mt-4 text-sm text-zinc-500 hover:text-white",onClick:Ye,children:"Cancel"})]}),M==="select"&&!y&&!U&&jsxs(Fragment,{children:[Qe.map(f=>jsxs("button",{onClick:()=>Ve(f.id),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:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-xl overflow-hidden",children:jsx(it,{provider:f.id})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white capitalize",children:f.name})})]},f.id)),Be.includes("phantom")&&jsxs("button",{onClick:pt,disabled:!re,className:`flex w-full items-center gap-4 rounded-xl border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a] ${re?"cursor-pointer":"cursor-not-allowed opacity-50"}`,children:[jsx(ce,{className:"h-14 w-14 flex-shrink-0 rounded-xl"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-lg text-white",children:"Phantom"}),!re&&jsx("p",{className:"text-xs text-zinc-500",children:"Not installed"})]}),jsxs("div",{className:"flex items-center gap-2",children:[re&&jsx("span",{className:"rounded-full border border-zinc-700 px-3 py-1 text-xs text-zinc-500",children:"Last used"}),jsx(Ee,{className:"h-8 w-8 rounded-xl"})]})]}),Be.includes("metamask")&&ut&&jsxs("button",{onClick:gt,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:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-xl bg-white p-2",children:jsx(de,{className:"h-10 w-10"})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white",children:"MetaMask"})}),jsx(_e,{className:"h-8 w-8 rounded-xl"})]}),He&&!E&&jsxs("button",{onClick:()=>R(true),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:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-xl border border-zinc-700 bg-[#2a2a3e]",children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"28px",viewBox:"0 -960 960 960",width:"28px",fill:"#e3e3e3",children:jsx("path",{d:"M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v480q0 33-23.5 56.5T800-160H160Z"})})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white",children:o})})]}),He&&E&&jsxs("div",{className:"rounded-xl border border-zinc-800 bg-[#25252f] p-6 space-y-4",children:[jsx("p",{className:"text-center text-sm text-zinc-400",children:"Enter your 6-digit access code"}),jsx(le,{onComplete:mt,disabled:L==="verifying",error:Q}),L==="verifying"&&jsx("p",{className:"text-center text-sm text-zinc-400 animate-pulse",children:"Verifying..."}),L==="success"&&jsx("p",{className:"text-center text-sm text-green-400",children:"Verified!"}),j?.webPageUrl&&L==="idle"&&jsx("a",{href:`${j.webPageUrl}/connect/pair`,target:"_blank",rel:"noopener noreferrer",className:"block text-center text-sm text-zinc-500 hover:text-white transition-colors",children:"Get code"})]}),(s?me:J).length>0&&(!s||me.length>0)&&jsxs(Fragment,{children:[!s&&Qe.length===0&&jsxs("div",{className:"flex items-center gap-3 py-1",children:[jsx("div",{className:"flex-1 border-t border-zinc-800"}),jsx("span",{className:"text-xs text-zinc-600",children:"or continue with"}),jsx("div",{className:"flex-1 border-t border-zinc-800"})]}),(s?me:J.filter(f=>!ge.has(f.id))).map(f=>jsxs("button",{onClick:()=>Ve(f.id),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:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center",children:jsx(it,{provider:f.id})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white capitalize",children:f.name})})]},f.id))]})]})]})}function it({provider:e}){switch(e){case "google":return jsx(We,{className:"h-14 w-14 rounded-xl"});case "discord":return jsx($e,{className:"h-14 w-14 rounded-xl"});case "twitter":return jsx(Fe,{className:"h-14 w-14 rounded-xl"});default:return jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-xl border border-zinc-700 bg-[#2a2a3e] text-sm text-zinc-400 font-mono",children:e[0]?.toUpperCase()})}}function fn({mid:e,apiBaseUrl:t="",scope:r,onSave:c,className:m}){let{profile:h,loading:p,saving:o,error:s,updateProfile:l}=Te(e,{apiBaseUrl:t,scope:r}),[g,i]=useState(null),[u,n]=useState(null),[y,a]=useState(null),b=useRef(null),[v,w]=useState(false),T=g??h?.username??"",x=u??h?.bio??"",S=y??h?.avatarUrl,O=useCallback(k=>{let U=k.target.files?.[0];if(!U)return;let M=new FileReader;M.onload=()=>{a(M.result),w(true);},M.readAsDataURL(U);},[]),_=async()=>{await l({username:T||void 0,avatarUrl:y??h?.avatarUrl,bio:x||void 0})&&(w(false),c?.());};if(p)return jsxs("div",{className:m,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 j=r==="global"||!r?"Global profile":`Stack profile (${r.stackId})`;return jsxs("div",{className:m,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:j}),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:()=>b.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:S?jsx("img",{src:S,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:k=>{i(k.target.value),w(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:b,type:"file",accept:"image/*",onChange:O,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:x,onChange:k=>{n(k.target.value),w(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"}})]})]}),s&&jsx("p",{style:{fontSize:13,color:"var(--x-color-red-500, #BF4D43)"},children:s}),v&&jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[jsx("button",{onClick:_,disabled:o,style:{padding:"0.5rem 1.25rem",fontSize:13,fontWeight:700,background:"var(--x-color-blue-600, #165DFC)",color:"#FFF",border:"none",cursor:o?"wait":"pointer",opacity:o?.6:1},children:o?"Saving...":"Save"}),jsx("button",{onClick:()=>{i(null),n(null),a(null),w(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 pn({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{cn as ConnectWidget,$e as DiscordIcon,_e as EthereumIcon,We as GoogleIcon,de as MetaMaskIcon,le as OTPInput,ce as PhantomIcon,fn as ProfileSettings,Ee as SolanaIcon,pn as TelegramIcon,Fe as TwitterIcon,Kt as UserUtilsProvider,kt as cn,xe as createStackNetClient,xt as decodeJwtPayloadClient,bt as formatTokens,W as readCSRFCookie,he as readSessionCookie,we as useAuthBridge,Gt as useBillingHistory,ye as useCSRFToken,Vt as useGoogleOneTap,zt as usePlans,Wt as usePrepaidCheckout,Te as useProfile,X as useSession,Ce as useStackAuth,te as useStackConfig,Dt as useSubscription,_t as useUsage,Jt as useUserUtilsContext,ke as useWeb3Wallet,wt as validateRedirectUrl};
1
+ import {clsx}from'clsx';import {twMerge}from'tailwind-merge';import {createContext,useState,useCallback,useEffect,useRef,useContext}from'react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';function xt(...e){return twMerge(clsx(e))}function vt(e){return e>=1e12?`${(e/1e12).toFixed(e%1e12===0?0:1)}T`:e>=1e9?`${(e/1e9).toFixed(e%1e9===0?0:1)}B`:e>=1e6?`${(e/1e6).toFixed(e%1e6===0?0:1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}K`:e.toLocaleString()}function St(e,t){if(!e)return "/";if(e.startsWith("/")&&!e.startsWith("//"))return e;try{let s=new URL(e,t);return s.origin!==t?"/":s.pathname+s.search+s.hash}catch{return "/"}}function X(e,t="#"){if(!e||typeof e!="string")return t;let s=e.trim();if(s===""||s==="#")return t;if(s.startsWith("/")||s.startsWith("./")||s.startsWith("../"))return s;try{let d=new URL(s);if(d.protocol==="http:"||d.protocol==="https:")return d.toString()}catch{}return t}function Ct(e){try{let t=e.split(".");if(t.length!==3)return null;let s=atob(t[1].replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(s)}catch{return null}}function ee(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(s=>s.trim()).find(s=>s.startsWith("stackauth_session="));if(!e)return null;let t=e.slice(18);return JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function W(e="__csrf"){if(typeof document>"u")return null;let t=document.cookie.split(";").map(s=>s.trim()).find(s=>s.startsWith(`${e}=`));return t?t.slice(e.length+1):null}function te(){let[e,t]=useState(null),[s,d]=useState(true),u=useCallback(()=>{let i=ee();i&&i.expiresAt>Date.now()?t({userId:i.userId,address:i.address,chain:i.chain,expiresAt:i.expiresAt,planId:i.planId,authMethod:i.authMethod}):t(null),d(false);},[]);useEffect(()=>{u();},[u]);let y=useCallback(async(i="")=>{try{let l=await fetch(`${i}/api/auth/session`);if(l.ok){let c=await l.json();if(c.session)return t(c.session),c.session}return t(null),null}catch{return null}},[]),m=!!e&&e.expiresAt>Date.now();return {session:e,loading:s,isAuthenticated:m,refresh:y,readSession:u}}function ke(e="__csrf",t="x-csrf-token"){let[s,d]=useState(null);useEffect(()=>{d(W(e));},[e]);let u=s?{[t]:s}:{};return {token:s,headers:u}}function be(){let[e,t]=useState({connected:false,address:null,chain:null,provider:null}),[s,d]=useState(null),u=useCallback(async(l="phantom")=>{d(null);try{let c=typeof window<"u"?window:null,h=l==="phantom"?c?.phantom?.solana||c?.solana:c?.solflare;if(!h)return d(`${l} wallet not found`),null;let a=(await h.connect()).publicKey.toString();return t({connected:!0,address:a,chain:"solana",provider:l}),a}catch(c){return d(c.message||"Failed to connect wallet"),null}},[]),y=useCallback(async()=>{d(null);try{let c=(typeof window<"u"?window:null)?.ethereum;if(!c)return d("MetaMask not found"),null;let h=c;c.providers?.length&&(h=c.providers.find(n=>n.isMetaMask)||c);let a=(await h.request({method:"eth_requestAccounts"}))[0];return a?(t({connected:!0,address:a,chain:"ethereum",provider:"metamask"}),a):(d("No account selected"),null)}catch(l){return d(l.message||"Failed to connect wallet"),null}},[]),m=useCallback(async(l,c)=>{d(null);let h=c?.chain||e.chain,o=c?.provider||e.provider,a=c?.address||e.address;try{if(h==="solana"){let n=typeof window<"u"?window:null,f=o==="solflare"?n?.solflare:n?.phantom?.solana||n?.solana;if(!f)throw new Error("Wallet not available");let r=new TextEncoder().encode(l),k=await f.signMessage(r,"utf8"),x=new Uint8Array(k.signature||k),w="";for(let L=0;L<x.byteLength;L++)w+=String.fromCharCode(x[L]);return btoa(w)}if(h==="ethereum"){let f=(typeof window<"u"?window:null)?.ethereum;if(f?.providers?.length&&(f=f.providers.find(k=>k.isMetaMask)||f),!f)throw new Error("MetaMask not available");return await f.request({method:"personal_sign",params:[l,a]})}throw new Error("No wallet connected")}catch(n){return d(n.message||"Signing failed"),null}},[e]),i=useCallback(()=>{t({connected:false,address:null,chain:null,provider:null}),d(null);},[]);return {wallet:e,error:s,connectSolana:u,connectEVM:y,signMessage:m,disconnect:i}}var Lt="https://stacknet.magma-rpc.com/auth/bridge",le="stacknet-auth-bridge";function xe(e){let t=e?.bridgeUrl||Lt,s=e?.disabled||false,d=useRef(null),[u,y]=useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),m=useRef([]),i=useRef(false),l=useCallback(n=>{let f={...n,protocol:le};i.current&&d.current?.contentWindow?d.current.contentWindow.postMessage(f,new URL(t).origin):m.current.push(f);},[t]);useEffect(()=>{if(s)return;let n=r=>{if(!(!r.data||r.data.protocol!==le)){try{if(r.origin!==new URL(t).origin)return}catch{return}switch(r.data.type){case "bridge:ready":i.current=true,y(k=>({...k,ready:true}));for(let k of m.current)d.current?.contentWindow?.postMessage(k,r.origin);m.current=[],d.current?.contentWindow?.postMessage({protocol:le,type:"auth:check"},r.origin),d.current?.contentWindow?.postMessage({protocol:le,type:"auth:resolve-stack"},r.origin);break;case "auth:status":y(k=>({...k,known:r.data.known,identity:r.data.identity,identityCount:r.data.identityCount||0}));break;case "auth:resolved-stack":y(k=>({...k,resolvedStackId:r.data.stackId||null}));break;}}};window.addEventListener("message",n);let f=document.createElement("iframe");return f.src=t,f.style.display="none",f.setAttribute("aria-hidden","true"),f.setAttribute("tabindex","-1"),f.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(f),d.current=f,()=>{window.removeEventListener("message",n),f.parentNode&&f.parentNode.removeChild(f),d.current=null,i.current=false;}},[t,s]);let c=useCallback(n=>{l({type:"auth:connected",...n});},[l]),h=useCallback(n=>{l({type:"auth:disconnected",...n});},[l]),o=useCallback(()=>{l({type:"auth:clear"}),y({ready:u.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[l,u.ready]),a=useCallback(()=>{l({type:"auth:check"});},[l]);return {...u,reportConnected:c,reportDisconnected:h,clearAll:o,refresh:a}}async function tt(e,t,s,d){let u=e.apiVersion||"v2",y=`${e.baseUrl}/api/${u}${s}`;try{let m=await fetch(y,{method:t,headers:{"Content-Type":"application/json"},body:d?JSON.stringify(d):void 0}),i=await m.json();return m.ok?i.success&&i.data!==void 0?{success:!0,data:i.data}:{success:!0,data:i}:{success:!1,error:i.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(m){return {success:false,error:{code:"NETWORK_ERROR",message:m instanceof Error?m.message:"Network error"}}}}function ve(e){return {getNetworkStatus:()=>tt(e,"GET","/network/status"),getWeb3Challenge:(t,s)=>tt(e,"POST",`/stacks/${encodeURIComponent(e.stackId)}/auth/web3/challenge`,{chain:t,address:s})}}function Ce(e={apiBaseUrl:""}){let{wallet:t,connectSolana:s,connectEVM:d,signMessage:u,disconnect:y}=be(),{session:m,isAuthenticated:i,refresh:l,readSession:c}=te(),{headers:h}=ke(),o=xe({disabled:typeof window>"u"}),[a,n]=useState(false),[f,r]=useState(null),[k,x]=useState(false),w=e.apiBaseUrl||"",L=e.stacknetUrl||"https://stacknet.magma-rpc.com",S=e.stackId||o.resolvedStackId||"",v=ve({baseUrl:L,stackId:S}),D=useCallback(async(N,I,E,R)=>{n(true),r(null);try{let P=I;if(!P){let J=await E();if(!J)return n(!1),!1;P=J;}let U=await v.getWeb3Challenge(N,P);if(!U.success||!U.data)return r("Failed to get challenge"),n(!1),!1;let _=await u(U.data.message,{chain:N,provider:R,address:P});if(!_)return n(!1),!1;let B={chain:N,message:U.data.message,signature:_,stackId:S};N==="solana"&&(B.publicKey=P);let Q=await fetch(`${w}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(B)});if(!Q.ok){let J=await Q.json().catch(()=>({}));return r(J.error||"Authentication failed"),n(!1),!1}return o.reportConnected({address:P,chain:N,method:R||(N==="solana"?"phantom":"metamask"),stackId:S}),c(),n(!1),!0}catch(P){return r(P.message||"Authentication failed"),n(false),false}},[w,v,u,c,o,S]),$=useCallback(async(N="phantom")=>{let I=await s(N);return I?D("solana",I,()=>s(N),N):false},[s,D]),j=useCallback(async()=>{let N=await d();return N?D("ethereum",N,d,"metamask"):false},[d,D]),b=useCallback(async N=>{n(true),r(null);try{let I=await fetch(`${w}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({code:N})});if(!I.ok){let E=await I.json().catch(()=>({}));return r(E.error||"Invalid code"),n(!1),!1}return c(),n(!1),!0}catch(I){return r(I.message||"OTP verification failed"),n(false),false}},[w,c]),T=useCallback(async(N,I)=>{n(true),r(null);try{let E=I||`${window.location.origin}/api/auth/oauth/callback`,R=new URLSearchParams({provider:N,redirectUri:E,stackId:S}),P=await fetch(`${w}/api/auth/oauth/start?${R}`,{credentials:"include"});if(!P.ok){let _=await P.json().catch(()=>({}));return r(_.error||"Failed to start OAuth flow"),n(!1),!1}let U=await P.json();if(U.redirect_url){let _;try{_=new URL(U.redirect_url);}catch{return r("Invalid OAuth redirect URL"),n(!1),!1}let B=[/(^|\.)accounts\.google\.com$/,/(^|\.)discord\.com$/,/(^|\.)github\.com$/,/(^|\.)x\.com$/,/(^|\.)twitter\.com$/,/(^|\.)apple\.com$/];return _.protocol!=="https:"||!B.some(Q=>Q.test(_.hostname))?(r(`Refusing to redirect to non-OAuth host: ${_.hostname}`),n(!1),!1):(typeof sessionStorage<"u"&&(sessionStorage.setItem("oauth_state",U.state||""),sessionStorage.setItem("oauth_provider",N)),window.location.href=_.toString(),!0)}return r("No redirect URL returned"),n(!1),!1}catch(E){return r(E.message||"OAuth flow failed"),n(false),false}},[w,S]),A=useCallback(async(N,I,E)=>{n(true),r(null);try{if(typeof sessionStorage<"u"){let P=sessionStorage.getItem("oauth_state"),U=sessionStorage.getItem("oauth_provider");if(sessionStorage.removeItem("oauth_state"),sessionStorage.removeItem("oauth_provider"),!P||P!==E)return r("OAuth state mismatch \u2014 refusing to complete login"),n(!1),!1;if(U&&U!==N)return r("OAuth provider mismatch \u2014 refusing to complete login"),n(!1),!1}let R=await fetch(`${w}/api/auth/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({provider:N,code:I,state:E,stackId:S})});if(!R.ok){let P=await R.json().catch(()=>({}));return r(P.error||"OAuth authentication failed"),n(!1),!1}return c(),n(!1),!0}catch(R){return r(R.message||"OAuth callback failed"),n(false),false}},[w,S,c]),z=useCallback(async()=>{t.address&&t.chain&&o.reportDisconnected({address:t.address,chain:t.chain,stackId:S});try{await fetch(`${w}/api/auth/logout`,{method:"POST",headers:h,credentials:"include"});}catch{}y(),c();},[w,h,y,c,t,o,S]);return useEffect(()=>{if(!e.autoConnect||k||i||!o.ready||!o.known||!o.identity)return;x(true);let{chain:N,method:I}=o.identity;N==="solana"&&(I==="phantom"||I==="solflare")?$(I):N==="ethereum"&&j();},[e.autoConnect,k,i,o,$,j]),{session:m,isAuthenticated:i,wallet:t,loading:a,error:f,authenticateSolana:$,authenticateEVM:j,authenticateOTP:b,authenticateOAuth:T,authenticateOAuthCallback:A,logout:z,refresh:()=>l(w),stackId:S,bridge:{ready:o.ready,known:o.known,identity:o.identity,identityCount:o.identityCount,resolvedStackId:o.resolvedStackId}}}function oe(e,t="https://stacknet.magma-rpc.com"){let[s,d]=useState(null),[u,y]=useState(false),[m,i]=useState(null),l=useCallback(async h=>{y(true),i(null);try{let o=await fetch(`${t}/api/v2/stacks/${h}`);if(!o.ok)return i("Stack not found"),y(!1),null;let a=await o.json(),n=a.data?.stack||a.stack||a,f={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(r=>({provider:r.provider,clientId:r.clientId,enabled:r.enabled!==!1}))};return d(f),y(!1),f}catch(o){return i(o.message),y(false),null}},[t]);useEffect(()=>{e&&l(e);},[e,l]);let c=s?jt(s):[];return {config:s,loading:u,error:m,identityProviders:c,fetchConfig:l}}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 s of e.oauthProviders)s.enabled&&t.push({type:"oauth",id:s.provider,name:s.provider});return t}function Et(e=""){let[t,s]=useState([]),[d,u]=useState(true),[y,m]=useState(null),i=useCallback(async()=>{try{let l=await fetch(`${e}/api/billing/plans`);if(l.ok){let c=await l.json();s(c.plans||c||[]);}}catch(l){m(l.message);}finally{u(false);}},[e]);return useEffect(()=>{i();},[i]),{plans:t,loading:d,error:y,refresh:i}}function _t(e=""){let[t,s]=useState(null),[d,u]=useState(true),[y,m]=useState(null),i=useCallback(async()=>{try{let h=await fetch(`${e}/api/billing/subscription`);if(h.ok){let o=await h.json();s(o.plan?o:null);}}catch(h){m(h.message);}finally{u(false);}},[e]);useEffect(()=>{i();},[i]);let l=useCallback(async h=>{let o=W(),n=await(await fetch(`${e}/api/billing/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",...o?{"x-csrf-token":o}:{}},body:JSON.stringify({planId:h})})).json();return n.url||n.checkoutUrl||null},[e]),c=useCallback(async()=>{let h=W();return (await fetch(`${e}/api/billing/cancel`,{method:"POST",headers:h?{"x-csrf-token":h}:{}})).ok?(await i(),true):false},[e,i]);return {subscription:t,loading:d,error:y,refresh:i,subscribe:l,cancel:c}}function Ft(e=""){let[t,s]=useState(null),[d,u]=useState(true),[y,m]=useState(null),i=useCallback(async()=>{try{let l=await fetch(`${e}/api/billing/usage`);if(l.ok){let c=await l.json();s(c);}}catch(l){m(l.message);}finally{u(false);}},[e]);return useEffect(()=>{i();},[i]),{usage:t,loading:d,error:y,refresh:i}}function Bt(e=""){let[t,s]=useState(false),[d,u]=useState(null),y=useCallback(async i=>{s(true),u(null);try{let l=W(),c=await fetch(`${e}/api/billing/prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...l?{"x-csrf-token":l}:{}},body:JSON.stringify({amountCents:i})}),h=await c.json();return c.ok?h.url||null:(u(h.error||"Purchase failed"),null)}catch(l){return u(l.message),null}finally{s(false);}},[e]),m=useCallback(async i=>{s(true),u(null);try{let l=W(),c=await fetch(`${e}/api/billing/verify-prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...l?{"x-csrf-token":l}:{}},body:JSON.stringify({sessionId:i})}),h=await c.json();return c.ok?h:(u(h.error||"Verification failed"),null)}catch(l){return u(l.message),null}finally{s(false);}},[e]);return {purchase:y,verifySession:m,loading:t,error:d}}function Qt(e="",t){let[s,d]=useState([]),[u,y]=useState(true),[m,i]=useState(null),l=t?.limit||50,c=t?.offset||0,h=useCallback(async()=>{try{let o=await fetch(`${e}/api/billing/history?limit=${l}&offset=${c}`);if(o.ok){let a=await o.json();d(a.records||a.history||(Array.isArray(a)?a:[]));}}catch(o){i(o.message);}finally{y(false);}},[e,l,c]);return useEffect(()=>{h();},[h]),{records:s,loading:u,error:m,refresh:h}}function Yt(){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 Ue(e,t){let[s,d]=useState(null),[u,y]=useState(true),[m,i]=useState(false),[l,c]=useState(null),h=t?.apiBaseUrl??"",o=t?.scope??"global",a=useCallback(r=>{let k=encodeURIComponent(r);return o==="global"?`${h}/api/user/profile/${k}`:`${h}/api/v2/stacks/${encodeURIComponent(o.stackId)}/members/${k}/profile`},[h,o]),n=useCallback(async()=>{if(!e){d(null),y(false);return}y(true),c(null);try{let r=await fetch(a(e));if(r.ok){let k=await r.json(),x=k.profile||k.data?.profile||k;d({mid:x.mid||e,username:x.username||"",avatarUrl:x.avatar_url||x.avatarUrl,bio:x.bio,paymentAddress:x.payment_address||x.paymentAddress,createdAt:x.created_at||x.createdAt,updatedAt:x.updated_at||x.updatedAt});}else if(r.status===404)d({mid:e,username:""});else throw new Error(`${r.status}`)}catch(r){c(r instanceof Error?r.message:"Failed to load profile");}finally{y(false);}},[e,a]);useEffect(()=>{n();},[n]);let f=useCallback(async r=>{if(!e)return false;i(true),c(null);try{let k=Yt(),x={};r.username!==void 0&&(x.username=r.username),r.avatarUrl!==void 0&&(x.avatar_url=r.avatarUrl),r.bio!==void 0&&(x.bio=r.bio),r.paymentAddress!==void 0&&(x.payment_address=r.paymentAddress);let w=await fetch(a(e),{method:"PUT",headers:{"Content-Type":"application/json",...k?{"x-csrf-token":k}:{}},credentials:"same-origin",body:JSON.stringify(x)});if(!w.ok){let v=await w.json().catch(()=>({}));throw new Error(v.error||v.message||`Update failed: ${w.status}`)}let L=await w.json(),S=L.profile||L.data?.profile||L;return d(v=>({mid:v?.mid||e,username:r.username??v?.username??"",avatarUrl:r.avatarUrl??v?.avatarUrl,bio:r.bio??v?.bio,paymentAddress:r.paymentAddress??S.payment_address??S.paymentAddress??v?.paymentAddress,createdAt:v?.createdAt,updatedAt:S.updated_at||S.updatedAt||Date.now()})),!0}catch(k){return c(k instanceof Error?k.message:"Update failed"),false}finally{i(false);}},[e,a]);return {profile:s,loading:u,saving:m,error:l,updateProfile:f,refresh:n}}var st="google-identity-services",Jt="https://accounts.google.com/gsi/client";function Zt({stackId:e,stacknetUrl:t="https://stacknet.magma-rpc.com",apiBaseUrl:s="",autoPrompt:d=true,cancelOnTapOutside:u=true,onSuccess:y,onError:m,disabled:i=false}){let{config:l}=oe(e,t),{isAuthenticated:c,loading:h,readSession:o}=te(),[a,n]=useState(false),[f,r]=useState(null),[k,x]=useState(false),w=useRef(false),L=useRef(false),v=l?.oauthProviders?.find(b=>b.provider==="google"&&b.enabled&&b.clientId)?.clientId||null;useEffect(()=>{if(i||!v||typeof window>"u")return;if(document.getElementById(st)){x(true);return}let b=document.createElement("script");b.id=st,b.src=Jt,b.async=true,b.defer=true,b.onload=()=>x(true),b.onerror=()=>{r("Failed to load Google sign-in"),m?.("Failed to load Google Identity Services script");},document.head.appendChild(b);},[i,v,m]);let D=useCallback(async b=>{n(true),r(null);try{let T=await fetch(`${s}/api/auth/google/one-tap`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({credential:b.credential,stackId:e})});if(!T.ok){let z=(await T.json().catch(()=>({}))).error||"Google sign-in failed";r(z),m?.(z),n(!1);return}o(),n(!1),y?.();}catch(T){let A=T.message||"Google sign-in failed";r(A),m?.(A),n(false);}},[s,e,o,y,m]);useEffect(()=>{if(i){console.debug("[GoogleOneTap] Disabled");return}if(!k){console.debug("[GoogleOneTap] Script not loaded yet, clientId:",v);return}if(!v){console.debug("[GoogleOneTap] No Google clientId from stack config");return}if(h){console.debug("[GoogleOneTap] Session still loading");return}if(c){console.debug("[GoogleOneTap] User already authenticated, skipping");return}if(!window.google?.accounts?.id){console.debug("[GoogleOneTap] GIS library not available on window");return}w.current||(console.debug("[GoogleOneTap] Initializing with clientId:",v),w.current=true,window.google.accounts.id.initialize({client_id:v,callback:D,auto_select:true,cancel_on_tap_outside:u}),d&&!L.current&&(L.current=true,console.debug("[GoogleOneTap] Showing prompt..."),window.google.accounts.id.prompt(b=>{b.isDisplayed?.()&&console.debug("[GoogleOneTap] Prompt displayed"),b.isNotDisplayed?.()&&console.debug("[GoogleOneTap] Not displayed:",b.getNotDisplayedReason?.()),b.isSkippedMoment?.()&&console.debug("[GoogleOneTap] Skipped:",b.getSkippedReason?.()),b.isDismissedMoment?.()&&console.debug("[GoogleOneTap] Dismissed:",b.getDismissedReason?.());})));},[i,k,v,h,c,D,d,u]),useEffect(()=>()=>{window.google?.accounts?.id&&w.current&&window.google.accounts.id.cancel();},[]);let $=useCallback(()=>{!window.google?.accounts?.id||!w.current||window.google.accounts.id.prompt();},[]),j=useCallback((b,T)=>{!b||!window.google?.accounts?.id||!w.current||window.google.accounts.id.renderButton(b,{theme:T?.theme||"filled_black",size:T?.size||"large",text:T?.text||"signin_with",width:T?.width});},[]);return {available:!!v,ready:k&&!!v,loading:a,error:f,prompt:$,renderButton:j,clientId:v}}var at=createContext(null);function Xt(){let e=useContext(at);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function en({config:e,callbacks:t,children:s}){return jsx(at.Provider,{value:{config:e,callbacks:t},children:s})}function de({length:e=6,onComplete:t,disabled:s=false,error:d,className:u="",inputClassName:y=""}){let [m,i]=useState(Array(e).fill("")),l=useCallback((o,a)=>{if(a.length>1){let f=a.replace(/\D/g,"").slice(0,e).split(""),r=[...m];f.forEach((x,w)=>{o+w<e&&(r[o+w]=x);}),i(r);let k=Math.min(o+f.length,e-1);document.getElementById(`userutils-otp-${k}`)?.focus(),r.every(x=>x!=="")&&setTimeout(()=>t(r.join("")),100);return}if(!/^\d?$/.test(a))return;let n=[...m];n[o]=a,i(n),a&&o<e-1&&document.getElementById(`userutils-otp-${o+1}`)?.focus(),a&&o===e-1&&n.every(f=>f!=="")&&setTimeout(()=>t(n.join("")),100);},[m,e,t]),c=useCallback((o,a)=>{if(a.key==="Backspace"&&!m[o]&&o>0){document.getElementById(`userutils-otp-${o-1}`)?.focus();let n=[...m];n[o-1]="",i(n);}if(a.key==="Enter"){let n=m.join("");n.length===e&&t(n);}},[m,e,t]);useCallback(()=>{i(Array(e).fill("")),document.getElementById("userutils-otp-0")?.focus();},[e]);return jsxs("div",{className:u,children:[jsx("div",{className:"flex gap-2 justify-center",children:m.map((o,a)=>jsx("input",{id:`userutils-otp-${a}`,type:"text",inputMode:"numeric",maxLength:e,value:o,onChange:n=>l(a,n.target.value),onKeyDown:n=>c(a,n),disabled:s,autoFocus:a===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}`},a))}),d&&jsx("p",{className:"text-center text-sm text-red-400 mt-2",children:d})]})}de.displayName="OTPInput";var rn="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function ue({className:e}){return jsx("img",{src:rn,alt:"Phantom",className:e})}function pe({className:e}){return jsxs("svg",{className:e,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 507.83 470.86",children:[jsx("polygon",{fill:"#e2761b",stroke:"#e2761b",strokeLinecap:"round",strokeLinejoin:"round",points:"482.09 0.5 284.32 147.38 320.9 60.72 482.09 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"25.54 0.5 221.72 148.77 186.93 60.72 25.54 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"410.93 340.97 358.26 421.67 470.96 452.67 503.36 342.76 410.93 340.97"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"4.67 342.76 36.87 452.67 149.57 421.67 96.9 340.97 4.67 342.76"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 111.8 252.13 223.7 257.1 219.73 136.85 143.21 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"364.42 204.62 286.91 135.46 284.32 257.1 396.03 252.13 364.42 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 216.75 388.87 158.71 343.55 149.57 421.67"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 358.26 421.67 348.92 343.55 290.88 388.87"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"358.26 421.67 290.88 388.87 296.25 432.8 295.65 451.28 358.26 421.67"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 212.18 451.28 211.78 432.8 216.75 388.87 149.57 421.67"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"213.17 314.54 157.12 298.04 196.67 279.95 213.17 314.54"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"294.46 314.54 310.96 279.95 350.71 298.04 294.46 314.54"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 159.11 340.97 96.9 342.76 149.57 421.67"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"348.72 340.97 358.26 421.67 410.93 342.76 348.72 340.97"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"396.03 252.13 284.32 257.1 294.66 314.54 311.16 279.95 350.91 298.04 396.03 252.13"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 196.87 279.95 213.17 314.54 223.7 257.1 111.8 252.13 157.12 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"111.8 252.13 158.71 343.55 157.12 298.04 111.8 252.13"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"350.91 298.04 348.92 343.55 396.03 252.13 350.91 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"223.7 257.1 213.17 314.54 226.29 382.31 229.27 293.07 223.7 257.1"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 278.96 292.87 281.34 382.31 294.66 314.54 284.32 257.1"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"294.66 314.54 281.34 382.31 290.88 388.87 348.92 343.55 350.91 298.04 294.66 314.54"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 158.71 343.55 216.75 388.87 226.29 382.31 213.17 314.54 157.12 298.04"}),jsx("polygon",{fill:"#c0ad9e",stroke:"#c0ad9e",strokeLinecap:"round",strokeLinejoin:"round",points:"295.65 451.28 296.25 432.8 291.28 428.42 216.35 428.42 211.78 432.8 212.18 451.28 149.57 421.67 171.43 439.55 215.75 470.36 291.88 470.36 336.4 439.55 358.26 421.67 295.65 451.28"}),jsx("polygon",{fill:"#161616",stroke:"#161616",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 281.34 382.31 226.29 382.31 216.75 388.87 211.78 432.8 216.35 428.42 291.28 428.42 296.25 432.8 290.88 388.87"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"490.44 156.92 507.33 75.83 482.09 0.5 290.88 142.41 364.42 204.62 468.37 235.03 491.43 208.2 481.49 201.05 497.39 186.54 485.07 177 500.97 164.87 490.44 156.92"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"0.5 75.83 17.39 156.92 6.66 164.87 22.56 177 10.44 186.54 26.34 201.05 16.4 208.2 39.26 235.03 143.21 204.62 216.75 142.41 25.54 0.5 0.5 75.83"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"468.37 235.03 364.42 204.62 396.03 252.13 348.92 343.55 410.93 342.76 503.36 342.76 468.37 235.03"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 39.26 235.03 4.67 342.76 96.9 342.76 158.71 343.55 111.8 252.13 143.21 204.62"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 290.88 142.41 321.1 60.72 186.93 60.72 216.75 142.41 223.7 257.1 226.09 293.27 226.29 382.31 281.34 382.31 281.74 293.27 284.32 257.1"})]})}function Re({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 $e({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 We({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#F1F2F9"}),jsx("path",{d:"M26.1001 16.2273C26.1001 15.5182 26.0365 14.8364 25.9183 14.1818H16.5001V18.05H21.8819C21.6501 19.3 20.9456 20.3591 19.8865 21.0682V23.5773H23.1183C25.0092 21.8364 26.1001 19.2727 26.1001 16.2273Z",fill:"#4285F4"}),jsx("path",{d:"M16.5001 26C19.2001 26 21.4637 25.1046 23.1182 23.5773L19.8864 21.0682C18.991 21.6682 17.8455 22.0227 16.5001 22.0227C13.8955 22.0227 11.691 20.2637 10.9046 17.9H7.56372V20.4909C9.20917 23.7591 12.591 26 16.5001 26Z",fill:"#34A853"}),jsx("path",{d:"M10.9047 17.8999C10.7047 17.2999 10.591 16.659 10.591 15.9999C10.591 15.3408 10.7047 14.6999 10.9047 14.0999V11.509H7.56376C6.86376 12.9025 6.49951 14.4405 6.50012 15.9999C6.50012 17.6136 6.88649 19.1408 7.56376 20.4908L10.9047 17.8999Z",fill:"#FBBC05"}),jsx("path",{d:"M16.5001 9.97726C17.9682 9.97726 19.2864 10.4818 20.3228 11.4727L23.191 8.60454C21.4591 6.99091 19.1955 6 16.5001 6C12.591 6 9.20917 8.2409 7.56372 11.5091L10.9046 14.1C11.691 11.7364 13.8955 9.97726 16.5001 9.97726Z",fill:"#EA4335"})]})}function Fe({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#5462EB"}),jsx("path",{d:"M23.5433 8.87438C22.2479 8.26174 20.8587 7.81038 19.4063 7.55187C19.3799 7.54688 19.3534 7.55934 19.3398 7.58428C19.1612 7.91179 18.9633 8.33905 18.8247 8.67487C17.2625 8.43382 15.7084 8.43382 14.1782 8.67487C14.0396 8.33158 13.8345 7.91179 13.6551 7.58428C13.6414 7.56018 13.615 7.54771 13.5886 7.55187C12.1369 7.80955 10.7478 8.26092 9.45159 8.87438C9.44037 8.87937 9.43075 8.88769 9.42437 8.89849C6.78947 12.9558 6.06766 16.9134 6.42176 20.8219C6.42336 20.841 6.43378 20.8593 6.4482 20.871C8.18663 22.1868 9.87059 22.9857 11.5233 23.5152C11.5497 23.5235 11.5778 23.5135 11.5946 23.491C11.9855 22.9408 12.334 22.3606 12.6328 21.7504C12.6505 21.7147 12.6336 21.6723 12.5976 21.6581C12.0448 21.442 11.5185 21.1785 11.0122 20.8793C10.9721 20.8552 10.9689 20.7961 11.0058 20.7679C11.1123 20.6856 11.2189 20.6 11.3206 20.5135C11.339 20.4977 11.3647 20.4944 11.3863 20.5044C14.7125 22.0696 18.3136 22.0696 21.6006 20.5044C21.6222 20.4936 21.6479 20.4969 21.6671 20.5127C21.7688 20.5991 21.8754 20.6856 21.9827 20.7679C22.0196 20.7961 22.0172 20.8552 21.9771 20.8793C21.4708 21.1843 20.9445 21.442 20.3909 21.6573C20.3548 21.6715 20.3388 21.7147 20.3564 21.7504C20.6617 22.3597 21.0101 22.9399 21.3939 23.4902C21.4099 23.5135 21.4387 23.5235 21.4652 23.5152C23.1259 22.9857 24.8099 22.1868 26.5483 20.871C26.5635 20.8593 26.5731 20.8419 26.5747 20.8228C26.9985 16.3041 25.8649 12.3789 23.5697 8.89931C23.5641 8.88769 23.5545 8.87937 23.5433 8.87438Z",fill:"#F7F7F7"})]})}function Be({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"black"}),jsx("path",{d:"M8.53901 8L14.7164 16.2153L8.5 22.8947H9.89907L15.3415 17.0468L19.7389 22.8947H24.5L17.975 14.2173L23.7612 8H22.3621L17.3499 13.3858L13.3001 8H8.53901ZM10.5964 9.02501H12.7837L22.4422 21.8695H20.255L10.5964 9.02501Z",fill:"#F7F7F7"})]})}function pn({config:e,onSuccess:t,title:s="Log in or Sign up",showWallets:d,showOTP:u,hideHeader:y,onOTPSubmit:m,otpLabel:i="Access Code",oauthInline:l,oauthFirst:c,className:h=""}){let o=Ce(e),{isAuthenticated:a,wallet:n,loading:f,error:r,authenticateSolana:k,authenticateEVM:x,authenticateOTP:w,authenticateOAuth:L,bridge:S,stackId:v}=o,D=!e.stackId&&!v,$=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:j,identityProviders:b,loading:T}=oe(v||e.stackId||null,$),[A,z]=useState(D?"stack-select":"select"),[N,I]=useState(null),[E,R]=useState(false),[P,U]=useState("idle"),[_,B]=useState(""),[Q,J]=useState([]),[pt,Qe]=useState(e.stackId||null),[ae,ft]=useState(false),[gt,mt]=useState(false);useEffect(()=>{if(typeof window>"u")return;let g=()=>{let V=window;ft(!!(V.phantom?.solana?.isPhantom||V.solana?.isPhantom));let K=V.ethereum;mt(!!(K?.isMetaMask||K?.providers?.some(q=>q.isMetaMask)));};g(),window.addEventListener("ethereum#initialized",g);let G=setTimeout(g,500);return ()=>{window.removeEventListener("ethereum#initialized",g),clearTimeout(G);}},[]),useEffect(()=>{A==="stack-select"&&v&&(Qe(v),z("select"));},[A,v]),useEffect(()=>{if(!(!S.ready||!D)&&S.identity){let g=[];S.resolvedStackId&&g.push({stackId:S.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(g.map(async G=>{try{let V=await fetch(`${$}/api/v2/stacks/${G.stackId}`);if(V.ok){let K=await V.json(),q=K.data?.stack||K;G.name=q.displayName||q.name,G.logoUrl=q.logoUrl;}}catch{}return G})).then(J);}},[S.ready,S.identity,S.resolvedStackId,D,$]),useEffect(()=>{a&&A==="success"&&t?.();},[a,A,t]);let Ve=d||(b.length>0?b.filter(g=>g.type==="wallet").map(g=>g.id):["phantom","metamask"]),Ye=u!==void 0?u:b.length>0?b.some(g=>g.type==="otp"):true,Z=b.filter(g=>g.type==="oauth"),he=new Set(c||[]),Je=Z.filter(g=>he.has(g.id)),ye=l?Z.filter(g=>!he.has(g.id)):Z,Ze=async g=>{I(g),z("connecting"),await L(g)||z("error");},ht=async()=>{I("phantom"),z("connecting");let g=await k("phantom");z(g?"success":"error");},yt=async()=>{I("metamask"),z("connecting");let g=await x();z(g?"success":"error");},kt=async g=>{U("verifying"),B(""),await(m||w)(g)?(U("success"),z("success")):(U("error"),B("Invalid or expired code"),setTimeout(()=>U("idle"),2e3));},Ke=()=>{z(D&&!pt?"stack-select":"select"),I(null),R(false),U("idle"),B("");};return jsxs("div",{className:`w-full max-w-md space-y-3 ${h}`,children:[!y&&jsxs("div",{className:"mb-6 text-center",children:[j?.logoUrl&&A!=="stack-select"&&jsx("img",{src:X(j.logoUrl),alt:j.displayName||"",className:"h-16 w-16 mx-auto mb-4 rounded-xl"}),j?.displayName&&jsx("p",{className:"text-sm text-zinc-400 mb-2",children:j.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:Q.length>0?"Select a network to continue":"No previous connections found. Enter a Stack ID to continue."}),Q.map(g=>jsxs("button",{onClick:()=>{Qe(g.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:[g.logoUrl?jsx("img",{src:X(g.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:g.name?.[0]?.toUpperCase()||"S"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-white",children:g.name||g.stackId}),jsx("p",{className:"text-xs text-zinc-500",children:g.domain})]}),jsx("span",{className:"text-xs text-zinc-600",children:"Previously connected"})]},g.stackId)),S.ready&&!S.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"&&T&&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%"}})}),r&&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:r}),jsx("button",{className:"mt-3 w-full text-sm text-zinc-400 hover:text-white",onClick:Ke,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"&&f&&jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 text-center",children:[jsxs("div",{className:"mx-auto mb-3 h-14 w-14 animate-pulse",children:[N==="phantom"&&jsx(ue,{className:"h-14 w-14"}),N==="metamask"&&jsx(pe,{className:"h-14 w-14"})]}),jsx("p",{className:"font-medium text-sm text-white",children:n.connected?"Signing message...":"Connecting wallet..."}),jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Please confirm in your wallet"}),jsx("button",{className:"mt-4 text-sm text-zinc-500 hover:text-white",onClick:Ke,children:"Cancel"})]}),A==="select"&&!f&&!T&&jsxs(Fragment,{children:[Je.map(g=>jsxs("button",{onClick:()=>Ze(g.id),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:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-xl overflow-hidden",children:jsx(dt,{provider:g.id})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white capitalize",children:g.name})})]},g.id)),Ve.includes("phantom")&&jsxs("button",{onClick:ht,disabled:!ae,className:`flex w-full items-center gap-4 rounded-xl border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a] ${ae?"cursor-pointer":"cursor-not-allowed opacity-50"}`,children:[jsx(ue,{className:"h-14 w-14 flex-shrink-0 rounded-xl"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-lg text-white",children:"Phantom"}),!ae&&jsx("p",{className:"text-xs text-zinc-500",children:"Not installed"})]}),jsxs("div",{className:"flex items-center gap-2",children:[ae&&jsx("span",{className:"rounded-full border border-zinc-700 px-3 py-1 text-xs text-zinc-500",children:"Last used"}),jsx(Re,{className:"h-8 w-8 rounded-xl"})]})]}),Ve.includes("metamask")&&gt&&jsxs("button",{onClick:yt,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:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-xl bg-white p-2",children:jsx(pe,{className:"h-10 w-10"})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white",children:"MetaMask"})}),jsx($e,{className:"h-8 w-8 rounded-xl"})]}),Ye&&!E&&jsxs("button",{onClick:()=>R(true),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:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-xl border border-zinc-700 bg-[#2a2a3e]",children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"28px",viewBox:"0 -960 960 960",width:"28px",fill:"#e3e3e3",children:jsx("path",{d:"M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v480q0 33-23.5 56.5T800-160H160Z"})})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white",children:i})})]}),Ye&&E&&jsxs("div",{className:"rounded-xl border border-zinc-800 bg-[#25252f] p-6 space-y-4",children:[jsx("p",{className:"text-center text-sm text-zinc-400",children:"Enter your 6-digit access code"}),jsx(de,{onComplete:kt,disabled:P==="verifying",error:_}),P==="verifying"&&jsx("p",{className:"text-center text-sm text-zinc-400 animate-pulse",children:"Verifying..."}),P==="success"&&jsx("p",{className:"text-center text-sm text-green-400",children:"Verified!"}),j?.webPageUrl&&P==="idle"&&(()=>{let g=X(j.webPageUrl);return g==="#"?null:jsx("a",{href:`${g.replace(/\/$/,"")}/connect/pair`,target:"_blank",rel:"noopener noreferrer",className:"block text-center text-sm text-zinc-500 hover:text-white transition-colors",children:"Get code"})})()]}),(l?ye:Z).length>0&&(!l||ye.length>0)&&jsxs(Fragment,{children:[!l&&Je.length===0&&jsxs("div",{className:"flex items-center gap-3 py-1",children:[jsx("div",{className:"flex-1 border-t border-zinc-800"}),jsx("span",{className:"text-xs text-zinc-600",children:"or continue with"}),jsx("div",{className:"flex-1 border-t border-zinc-800"})]}),(l?ye:Z.filter(g=>!he.has(g.id))).map(g=>jsxs("button",{onClick:()=>Ze(g.id),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:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center",children:jsx(dt,{provider:g.id})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white capitalize",children:g.name})})]},g.id))]})]})]})}function dt({provider:e}){switch(e){case "google":return jsx(We,{className:"h-14 w-14 rounded-xl"});case "discord":return jsx(Fe,{className:"h-14 w-14 rounded-xl"});case "twitter":return jsx(Be,{className:"h-14 w-14 rounded-xl"});default:return jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-xl border border-zinc-700 bg-[#2a2a3e] text-sm text-zinc-400 font-mono",children:e[0]?.toUpperCase()})}}function mn({mid:e,apiBaseUrl:t="",scope:s,onSave:d,className:u}){let{profile:y,loading:m,saving:i,error:l,updateProfile:c}=Ue(e,{apiBaseUrl:t,scope:s}),[h,o]=useState(null),[a,n]=useState(null),[f,r]=useState(null),k=useRef(null),[x,w]=useState(false),L=h??y?.username??"",S=a??y?.bio??"",v=f??y?.avatarUrl,D=useCallback(b=>{let T=b.target.files?.[0];if(!T)return;let A=new FileReader;A.onload=()=>{r(A.result),w(true);},A.readAsDataURL(T);},[]),$=async()=>{await c({username:L||void 0,avatarUrl:f??y?.avatarUrl,bio:S||void 0})&&(w(false),d?.());};if(m)return jsxs("div",{className:u,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 j=s==="global"||!s?"Global profile":`Stack profile (${s.stackId})`;return jsxs("div",{className:u,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:j}),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:()=>k.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:v?jsx("img",{src:v,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:L,onChange:b=>{o(b.target.value),w(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:k,type:"file",accept:"image/*",onChange:D,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:S,onChange:b=>{n(b.target.value),w(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"}})]})]}),l&&jsx("p",{style:{fontSize:13,color:"var(--x-color-red-500, #BF4D43)"},children:l}),x&&jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[jsx("button",{onClick:$,disabled:i,style:{padding:"0.5rem 1.25rem",fontSize:13,fontWeight:700,background:"var(--x-color-blue-600, #165DFC)",color:"#FFF",border:"none",cursor:i?"wait":"pointer",opacity:i?.6:1},children:i?"Saving...":"Save"}),jsx("button",{onClick:()=>{o(null),n(null),r(null),w(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 hn({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"})]})}function kn(e){let{apiBaseUrl:t,stacknetUrl:s="https://stacknet.magma-rpc.com",stackId:d="",transport:u,serviceKey:y,onAuthSuccess:m,onAuthError:i,onLogout:l}=e;async function c(o){if(!o.ok){let r=await o.json().catch(()=>({})),k=new Error(r.error||`Authentication failed (${o.status})`);throw i?.(k),k}let a=await o.json(),n=a.token||a.jwt,f=a.session||{userId:a.user?.id||a.userId||a.sub||"",address:a.user?.address||a.address,chain:a.user?.chain||a.chain,expiresAt:a.expiresAt||Date.now()+10080*60*1e3,authMethod:a.authMethod||a.method};return n&&await u.storeCredentials(n,f),m?.(f),f}return {async login(o,a){let n=await fetch(`${t}/api/auth/callback/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:o,password:a})});return c(n)},async loginWeb3({chain:o,address:a,message:n,signature:f}){let r={chain:o,message:n,signature:f,stackId:d};o==="solana"&&(r.publicKey=a);let k=await fetch(`${t}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return c(k)},async loginOTP(o){let a=await fetch(`${t}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:o})});return c(a)},async getSession(){let o=await u.getStoredSession();if(o&&o.expiresAt>Date.now())return o;try{let a=await u.getHeaders(),n=await fetch(`${t}/api/auth/session`,{headers:a});if(n.ok){let f=await n.json();if(f.session)return f.session}}catch{if(o)return o}return null},async checkSession(){let o=await u.getToken();if(!o)return false;try{let a=await fetch(`${t}/api/history?limit=1`,{headers:{Authorization:`Bearer ${o}`}});return a.ok?!0:a.status===401?(await u.clear(),!1):!0}catch{return true}},async getChallenge(o,a){let f=`${s}/api/v2/stacks/${encodeURIComponent(d)}/auth/web3/challenge`,r=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chain:o,address:a})});if(!r.ok)throw new Error("Failed to get challenge");let k=await r.json();return k.data||k},async logout(){try{let o=await u.getHeaders();await fetch(`${t}/api/auth/logout`,{method:"POST",headers:o});}catch{}await u.clear(),l?.();},async getHeaders(){let o=await u.getHeaders();return Object.keys(o).length>0?o:y?{Authorization:`Bearer ${y}`}:{}},async getToken(){return u.getToken()}}}function bn(){return {async storeCredentials(e,t){},async getToken(){return null},async getHeaders(){return {}},async getStoredSession(){let e=ee();return !e||e.expiresAt<=Date.now()?null:{userId:e.userId,address:e.address,chain:e.chain,expiresAt:e.expiresAt,planId:e.planId,authMethod:e.authMethod}},async clear(){}}}var Ge="stackauth_token",He="stackauth_session";function wn(e){return {async storeCredentials(t,s){await e.setItemAsync(Ge,t),await e.setItemAsync(He,JSON.stringify(s));},async getToken(){try{return await e.getItemAsync(Ge)}catch{return null}},async getHeaders(){let t=await this.getToken();return t?{Authorization:`Bearer ${t}`}:{}},async getStoredSession(){try{let t=await e.getItemAsync(He);return t?JSON.parse(t):null}catch{return null}},async clear(){await e.deleteItemAsync(Ge).catch(()=>{}),await e.deleteItemAsync(He).catch(()=>{});}}}
2
+ export{pn as ConnectWidget,Fe as DiscordIcon,$e as EthereumIcon,We as GoogleIcon,pe as MetaMaskIcon,de as OTPInput,ue as PhantomIcon,mn as ProfileSettings,Re as SolanaIcon,hn as TelegramIcon,Be as TwitterIcon,en as UserUtilsProvider,xt as cn,kn as createAuthClient,wn as createNativeTransport,ve as createStackNetClient,bn as createWebTransport,Ct as decodeJwtPayloadClient,vt as formatTokens,W as readCSRFCookie,ee as readSessionCookie,X as safeUrl,xe as useAuthBridge,Qt as useBillingHistory,ke as useCSRFToken,Zt as useGoogleOneTap,Et as usePlans,Bt as usePrepaidCheckout,Ue as useProfile,te as useSession,Ce as useStackAuth,oe as useStackConfig,_t as useSubscription,Ft as useUsage,Xt as useUserUtilsContext,be as useWeb3Wallet,St as validateRedirectUrl};
@@ -1,2 +1,2 @@
1
- 'use strict';var crypto=require('crypto');function G(e){return Buffer.from(e).toString("base64url")}function ee(e){return Buffer.from(e,"base64url").toString()}function v(e){try{let r=e.split(".");return r.length!==3?null:JSON.parse(ee(r[1]))}catch{return null}}function $(e,r){let t=G(JSON.stringify({alg:"HS256",typ:"JWT"})),a=G(JSON.stringify(e)),n=crypto.createHmac("sha256",r).update(`${t}.${a}`).digest("base64url");return `${t}.${a}.${n}`}function K(e,r){try{let t=e.split(".");if(t.length!==3)return !1;let[a,n,o]=t,i=crypto.createHmac("sha256",r).update(`${a}.${n}`).digest("base64url"),y=Buffer.from(o),m=Buffer.from(i);return y.length!==m.length?!1:crypto.timingSafeEqual(y,m)}catch{return false}}function M(e,r){if(!K(e,r))return null;let t=v(e);return !t||t.exp&&t.exp<Math.floor(Date.now()/1e3)?null:t}function D(e,r,t=900,a=300){let n=M(e,r);return !n?.exp||n.exp*1e3-Date.now()>a*1e3?null:$({...n,exp:Math.floor(Date.now()/1e3)+t},r)}function W(e=32){return crypto.randomBytes(e).toString("hex")}function O(e){return e.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||e.headers.get("x-real-ip")||"unknown"}var re="__csrf",se="x-csrf-token";function j(e={}){let r=e.cookieName||re,t=e.headerName||se,a=e.tokenLength||32,n=e.secure!==false;return {generateToken(o){let i=W(a),y=[`${r}=${i}`,"Path=/","SameSite=Lax"];return n&&y.push("Secure"),o.append("Set-Cookie",y.join("; ")),i},validateRequest(o){let i=o.headers.get("cookie");if(!i)return {valid:false,error:"No cookies present"};let y=i.split(";").map(l=>l.trim()).find(l=>l.startsWith(`${r}=`))?.slice(r.length+1);if(!y)return {valid:false,error:"CSRF cookie missing"};let m=o.headers.get(t);if(!m)return {valid:false,error:"CSRF header missing"};try{let l=Buffer.from(y),u=Buffer.from(m);return l.length!==u.length?{valid:!1,error:"CSRF token mismatch"}:crypto.timingSafeEqual(l,u)?{valid:!0}:{valid:!1,error:"CSRF token mismatch"}}catch{return {valid:false,error:"CSRF validation failed"}}},cookieName:r,headerName:t}}function C(e){let r=new Map,t=setInterval(()=>{let a=Date.now();for(let[n,o]of r)a>=o.resetAt&&r.delete(n);},6e4);return typeof t=="object"&&"unref"in t&&t.unref(),{async check(a){let n=Date.now(),o=r.get(a);return (!o||n>=o.resetAt)&&(o={count:0,resetAt:n+e.windowMs},r.set(a,o)),o.count++,o.count>e.maxRequests?{allowed:false,remaining:0,retryAfter:Math.ceil((o.resetAt-n)/1e3)}:{allowed:true,remaining:e.maxRequests-o.count}}}}function oe(){let e=new Map,r=setInterval(()=>{let t=Date.now();for(let[a,n]of e)t>=n&&e.delete(a);},6e4);return typeof r=="object"&&"unref"in r&&r.unref(),{async has(t){let a=e.get(t);return a?Date.now()>=a?(e.delete(t),false):true:false},async set(t,a){e.set(t,Date.now()+a*1e3);}}}function ne(e,r){let t=r?.rateLimiter||C({maxRequests:10,windowMs:6e4}),a=j({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,o=e.sessionMaxAge||604800;e.stacknetJwtSecret||e.authSecret;return async function(m){let l=O(m),u=await t.check(`auth:${l}`);if(!u.allowed)return Response.json({error:"Too many login attempts. Please wait."},{status:429,headers:{"Retry-After":String(u.retryAfter||60)}});let s;try{s=await m.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{chain:c,message:p,signature:d,publicKey:f,otp:h,code:g,redirectUrl:k,stackId:w}=s,x=w||e.stackId,R;if(c&&p&&d){let Y={"Content-Type":"application/json"},_=await fetch(`${e.stacknetUrl}/api/v2/stacks/${x}/auth/web3/verify`,{method:"POST",headers:Y,body:JSON.stringify({chain:c,message:p,signature:d,public_key:f}),signal:AbortSignal.timeout(1e4)});if(!_.ok){let q=await _.json().catch(()=>({})),U=q?.error?.message||q?.message||q?.error||`StackNet returned ${_.status}`;return console.error(`[auth-callback] Verify failed: ${_.status}`,U),Response.json({error:"Wallet verification failed",detail:typeof U=="string"?U:void 0},{status:401})}let N=await _.json();R=N.data?.session||N.session||N.data||N,console.log(`[auth-callback] Verify OK, sessionData keys: ${Object.keys(R||{}).join(", ")}`);}else return h||g?Response.json({error:"Use /api/auth/otp for OTP verification"},{status:400}):Response.json({error:"Provide wallet signature or OTP code"},{status:400});if(!R?.jwt)return Response.json({error:"Authentication failed \u2014 no session returned"},{status:401});let S=JSON.parse(Buffer.from(R.jwt.split(".")[1],"base64url").toString()),b=Math.floor(Date.now()/1e3),T={...S,exp:b+n,iat:b},P=$(T,e.authSecret),J={userId:S.sub||S.user_id||S.session_id||S.global_id||"",address:R.address||S.address,chain:R.chain||c,expiresAt:Date.now()+o*1e3,authMethod:c?`web3:${c}`:"otp"},H=new Headers({"Content-Type":"application/json"}),L=e.secureCookies!==false?"; Secure":"",F=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";H.append("Set-Cookie",`stackauth_jwt=${P}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${L}${F}`);let z=Buffer.from(JSON.stringify(J)).toString("base64url");return H.append("Set-Cookie",`stackauth_session=${z}; Path=/; SameSite=Lax; Max-Age=${o}${L}${F}`),a.generateToken(H),new Response(JSON.stringify({user:J}),{status:200,headers:H})}}function X(e,r){if(!r)return null;try{let t=v(e);if(!t||t.exp&&t.exp<Math.floor(Date.now()/1e3))return null;let a=Buffer.from(JSON.stringify({alg:"HS256",typ:"JWT"})).toString("base64url"),n=Buffer.from(JSON.stringify(t)).toString("base64url"),o=crypto.createHmac("sha256",r).update(`${a}.${n}`).digest("base64url");return `${a}.${n}.${o}`}catch{return null}}function E(e,r){let t=X(e,r);return t?{Cookie:`stackauth_jwt=${t}`}:{Cookie:`stackauth_jwt=${e}`}}function A(e){let r=e.headers.get("cookie");if(r){let a=r.split(";").map(n=>n.trim()).find(n=>n.startsWith("stackauth_jwt="));if(a)return a.slice(14)}let t=e.headers.get("authorization");return t?.startsWith("Bearer ")?t.slice(7):null}function ie(e){return async function(t){let a=A(t);if(a){let y=v(a),m=y?.session_id||y?.sub;if(m)try{await fetch(`${e.stacknetUrl}/api/v2/sessions/${m}`,{method:"DELETE",signal:AbortSignal.timeout(5e3)});}catch{}}let n=e.secureCookies!==false?"; Secure":"",o=e.cookieDomain?`; Domain=${e.cookieDomain}`:"",i=new Headers({"Content-Type":"application/json"});return i.append("Set-Cookie",`stackauth_jwt=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${n}${o}`),i.append("Set-Cookie",`stackauth_session=; Path=/; SameSite=Lax; Max-Age=0${n}${o}`),i.append("Set-Cookie",`__csrf=; Path=/; SameSite=Lax; Max-Age=0${n}${o}`),new Response(JSON.stringify({success:true}),{status:200,headers:i})}}function ce(e){let r=e.jwtExpiry||900,t=e.sessionMaxAge||604800;return async function(n){let o=A(n);if(!o)return Response.json({session:null},{status:200});let i=M(o,e.authSecret);if(!i)return Response.json({session:null},{status:200});let m={userId:i.sub||i.user_id||i.session_id||i.global_id||"",address:i.address,chain:i.chain,expiresAt:i.session_expires_at||(i.exp?i.exp*1e3:Date.now()+t*1e3),planId:i.plan_id,authMethod:i.auth_method},l=new Headers({"Content-Type":"application/json"}),u=D(o,e.authSecret,r,300);if(u){let s=e.secureCookies!==false?"; Secure":"",c=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";l.append("Set-Cookie",`stackauth_jwt=${u}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${t}${s}${c}`);}return new Response(JSON.stringify({session:m}),{status:200,headers:l})}}function pe(e,r){if(e.length!==r.length)return false;try{return crypto.timingSafeEqual(Buffer.from(e),Buffer.from(r))}catch{return false}}function de(e){let r=e.rateLimiter||C({maxRequests:5,windowMs:3e5}),t=j({secure:e.secureCookies!==false}),a=e.jwtExpiry||900,n=e.sessionMaxAge||604800;return async function(i){let y=O(i),m=await r.check(`otp:${y}`);if(!m.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(m.retryAfter||300)}});let l;try{l=await i.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{code:u}=l;if(!u||typeof u!="string"||u.length!==6)return Response.json({error:"Invalid code format"},{status:400});if(!pe(u,e.otpSecret))return Response.json({error:"Invalid code"},{status:401});let s=Math.floor(Date.now()/1e3),p={sub:`otp:${crypto.createHash("sha256").update(`otp:${u}:${Date.now()}`).digest("hex").slice(0,32)}`,auth_method:"otp",iat:s,exp:s+a},d=$(p,e.authSecret),f={userId:p.sub,expiresAt:Date.now()+n*1e3,authMethod:"otp"},h=new Headers({"Content-Type":"application/json"}),g=e.secureCookies!==false?"; Secure":"",k=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";h.append("Set-Cookie",`stackauth_jwt=${d}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${n}${g}${k}`);let w=Buffer.from(JSON.stringify(f)).toString("base64url");return h.append("Set-Cookie",`stackauth_session=${w}; Path=/; SameSite=Lax; Max-Age=${n}${g}${k}`),t.generateToken(h),new Response(JSON.stringify({success:true,data:{user:f}}),{status:200,headers:h})}}function fe(e,r){let t=r?.rateLimiter||C({maxRequests:10,windowMs:6e4}),a=j({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,o=e.sessionMaxAge||604800;async function i(m){let l=new URL(m.url),u=l.searchParams.get("provider"),s=l.searchParams.get("redirectUri")||l.searchParams.get("redirect_uri"),c=l.searchParams.get("stackId")||e.stackId;if(!u)return Response.json({error:"Missing provider parameter"},{status:400});if(!s)return Response.json({error:"Missing redirectUri parameter"},{status:400});try{let p=await fetch(`${e.stacknetUrl}/api/v2/stacks/${c}/auth/oauth/${u}/initiate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirectUrl:s}),signal:AbortSignal.timeout(1e4)});if(!p.ok){let h=await p.json().catch(()=>({}));return Response.json({error:h.error?.message||`Failed to start OAuth flow: ${p.statusText}`},{status:p.status})}let d=await p.json(),f=d.data||d;return Response.json({redirect_url:f.url,state:f.state})}catch(p){return Response.json({error:p.message||"Failed to start OAuth flow"},{status:500})}}async function y(m){let l=O(m),u=await t.check(`oauth:${l}`);if(!u.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(u.retryAfter||60)}});let s;try{s=await m.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{provider:c,code:p,state:d,stackId:f}=s,h=f||e.stackId;if(!c||!p||!d)return Response.json({error:"Missing provider, code, or state"},{status:400});try{let g=await fetch(`${e.stacknetUrl}/api/v2/stacks/${h}/auth/oauth/${c}/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:p,state:d}),signal:AbortSignal.timeout(1e4)});if(!g.ok){let L=await g.json().catch(()=>({}));return Response.json({error:L.error?.message||`OAuth verification failed: ${g.statusText}`},{status:401})}let k=await g.json(),w=k.data?.session||k.session||k.data||k;if(!w?.jwt)return Response.json({error:"OAuth authentication failed \u2014 no session returned"},{status:401});let x=JSON.parse(Buffer.from(w.jwt.split(".")[1],"base64url").toString()),R=Math.floor(Date.now()/1e3),S=$({...x,exp:R+n,iat:R},e.authSecret),T={userId:x.sub||x.user_id||x.session_id||x.global_id||"",address:w.address||x.address,chain:void 0,expiresAt:Date.now()+o*1e3,authMethod:`oauth:${c}`},P=new Headers({"Content-Type":"application/json"}),I=e.secureCookies!==!1?"; Secure":"",J=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";P.append("Set-Cookie",`stackauth_jwt=${S}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${I}${J}`);let H=Buffer.from(JSON.stringify(T)).toString("base64url");return P.append("Set-Cookie",`stackauth_session=${H}; Path=/; SameSite=Lax; Max-Age=${o}${I}${J}`),a.generateToken(P),new Response(JSON.stringify({user:T}),{status:200,headers:P})}catch(g){return Response.json({error:g.message||"OAuth callback failed"},{status:500})}}return {startFlow:i,handleCallback:y}}function me(e,r){let t=r?.rateLimiter||C({maxRequests:10,windowMs:6e4}),a=j({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,o=e.sessionMaxAge||604800;return async function(y){let m=O(y),l=await t.check(`google-onetap:${m}`);if(!l.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(l.retryAfter||60)}});let u;try{u=await y.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{credential:s,stackId:c}=u,p=c||e.stackId;if(!s)return Response.json({error:"Missing credential"},{status:400});let d;try{let f=s.split(".");if(f.length!==3)throw new Error("Invalid JWT");d=JSON.parse(Buffer.from(f[1],"base64url").toString());}catch{return Response.json({error:"Invalid credential format"},{status:400})}try{let f=await fetch(`https://oauth2.googleapis.com/tokeninfo?id_token=${encodeURIComponent(s)}`,{signal:AbortSignal.timeout(1e4)});if(!f.ok)return Response.json({error:"Google credential verification failed"},{status:401});let h=await f.json();if(!h.sub||!h.email)return Response.json({error:"Invalid Google token \u2014 missing user info"},{status:401})}catch{return Response.json({error:"Failed to verify Google credential"},{status:500})}try{let f=await fetch(`${e.stacknetUrl}/api/v2/stacks/${p}/auth/oauth/google/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({credential:s,google_id:d.sub,email:d.email,name:d.name,picture:d.picture,one_tap:!0}),signal:AbortSignal.timeout(1e4)});if(!f.ok){let k=Math.floor(Date.now()/1e3),w=d.sub,x=$({sub:w,global_id:`google:${w}`,stack_id:p,chain:"google",email:d.email,credentials:["oauth:google"],iat:k,exp:k+n,iss:"stackauth.network",signed_by:["local"]},e.authSecret),R={userId:w,address:d.email,chain:void 0,expiresAt:Date.now()+o*1e3,authMethod:"oauth:google"},S=new Headers({"Content-Type":"application/json"}),b=e.secureCookies!==!1?"; Secure":"",T=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";S.append("Set-Cookie",`stackauth_jwt=${x}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${b}${T}`);let P=Buffer.from(JSON.stringify(R)).toString("base64url");return S.append("Set-Cookie",`stackauth_session=${P}; Path=/; SameSite=Lax; Max-Age=${o}${b}${T}`),a.generateToken(S),new Response(JSON.stringify({user:R}),{status:200,headers:S})}let h=await f.json(),g=h.data?.session||h.session||h.data||h;if(g?.jwt){let k=JSON.parse(Buffer.from(g.jwt.split(".")[1],"base64url").toString()),w=Math.floor(Date.now()/1e3),x=$({...k,exp:w+n,iat:w},e.authSecret),S={userId:k.sub||k.user_id||d.sub,address:d.email||g.address,chain:void 0,expiresAt:Date.now()+o*1e3,authMethod:"oauth:google"},b=new Headers({"Content-Type":"application/json"}),T=e.secureCookies!==!1?"; Secure":"",P=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";b.append("Set-Cookie",`stackauth_jwt=${x}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${T}${P}`);let I=Buffer.from(JSON.stringify(S)).toString("base64url");return b.append("Set-Cookie",`stackauth_session=${I}; Path=/; SameSite=Lax; Max-Age=${o}${T}${P}`),a.generateToken(b),new Response(JSON.stringify({user:S}),{status:200,headers:b})}return Response.json({error:"No session returned"},{status:401})}catch(f){return Response.json({error:f.message||"Google One Tap authentication failed"},{status:500})}}}function ye(e){let r=j({secure:e.secureCookies!==false}),t=e.rateLimiter||C({maxRequests:20,windowMs:6e4}),a=e.stacknetJwtSecret||e.authSecret,n=e.jwtExpiry||900,o=e.sessionMaxAge||604800;function i(s){let c=A(s);if(!c)return null;let p=M(c,e.authSecret);return p?{jwt:c,payload:p}:null}function y(s,c){let p=D(s,e.authSecret,n,300);if(p){let d=e.secureCookies!==false?"; Secure":"",f=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";c.append("Set-Cookie",`stackauth_jwt=${p}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${d}${f}`);}}async function m(s,c){let p=i(s);if(!p)return Response.json({error:"Unauthorized"},{status:401});let d=E(p.jwt,a),f=await fetch(`${e.stacknetUrl}${c}`,{headers:d,signal:AbortSignal.timeout(15e3)}),h=await f.json().catch(()=>({})),g=new Headers({"Content-Type":"application/json"});return y(p.jwt,g),new Response(JSON.stringify(h),{status:f.status,headers:g})}async function l(s,c,p){let d=i(s);if(!d)return Response.json({error:"Unauthorized"},{status:401});let f=r.validateRequest(s);if(!f.valid)return Response.json({error:f.error||"CSRF validation failed"},{status:403});let h=d.payload.sub||d.payload.user_id||"unknown";if(!(await t.check(`billing:${h}`)).allowed)return Response.json({error:"Too many requests"},{status:429});let k=await s.json().catch(()=>({})),w=E(d.jwt,a);w["Content-Type"]="application/json";let x=await fetch(`${e.stacknetUrl}${c}`,{method:"POST",headers:w,body:JSON.stringify({...k,...p}),signal:AbortSignal.timeout(15e3)}),R=await x.json().catch(()=>({})),S=new Headers({"Content-Type":"application/json"});return y(d.jwt,S),new Response(JSON.stringify(R),{status:x.status,headers:S})}let u=`/api/v2/stacks/${e.stackId}`;return {plans:{GET:async s=>{let c=await fetch(`${e.stacknetUrl}${u}/plans`,{signal:AbortSignal.timeout(1e4)}),p=await c.json().catch(()=>({}));return Response.json(p,{status:c.status})}},subscription:{GET:(s=>m(s,`${u}/subscription`))},subscribe:{POST:(s=>{let c=new URL(s.url).origin;return l(s,`${u}/subscribe`,{successUrl:`${c}/billing/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${c}/pricing`})})},cancel:{POST:(s=>l(s,`${u}/cancel-subscription`))},usage:{GET:(s=>m(s,"/v1/account/usage"))},history:{GET:(s=>m(s,`${u}/billing`))},prepaid:{POST:(s=>{let c=new URL(s.url).origin;return l(s,`${u}/prepaid`,{successUrl:`${c}/pricing/prepaid/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${c}/pricing/prepaid`})})},verifyPrepaid:{POST:(s=>l(s,`${u}/verify-prepaid`))},verifySession:{POST:(s=>l(s,`${u}/verify-session`))},subscribeSol:{POST:(s=>l(s,`${u}/subscribe-sol`))},prepaidSol:{POST:(s=>{new URL(s.url).origin;return l(s,`${u}/prepaid-sol`)})},topup:{POST:(s=>l(s,"/v1/account/topup"))}}}function he(e){return async function(t){let a=t.headers.get("stripe-signature");if(!a)return Response.json({error:"Missing Stripe signature"},{status:400});try{let n=await t.text(),o=await fetch(`${e.stacknetUrl}/api/v2/stacks/${e.stackId}/webhook/stripe`,{method:"POST",headers:{"Content-Type":"application/json","stripe-signature":a},body:n,signal:AbortSignal.timeout(1e4)}),i=await o.json().catch(()=>({received:!0}));return Response.json(i,{status:o.status})}catch{return Response.json({error:"Webhook processing failed"},{status:502})}}}function B(){return {"Strict-Transport-Security":"max-age=63072000; includeSubDomains; preload","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","X-XSS-Protection":"0","Referrer-Policy":"strict-origin-when-cross-origin","Permissions-Policy":"camera=(), microphone=(), geolocation=()"}}function ge(e){return async r=>{let t=await e(r),a=B(),n=new Headers(t.headers);for(let[o,i]of Object.entries(a))n.set(o,i);return new Response(t.body,{status:t.status,statusText:t.statusText,headers:n})}}function Se(){return Object.entries(B()).map(([e,r])=>({key:e,value:r}))}
2
- exports.buildStackNetHeaders=E;exports.createAuthCallback=ne;exports.createBillingProxy=ye;exports.createCSRFProtection=j;exports.createGoogleOneTapHandler=me;exports.createInMemoryRateLimiter=C;exports.createInMemoryReplayStore=oe;exports.createLogoutHandler=ie;exports.createOAuthHandlers=fe;exports.createOTPHandler=de;exports.createSessionHandler=ce;exports.createWebhookHandler=he;exports.decodeJWTPayload=v;exports.extractIP=O;exports.extractJwt=A;exports.generateToken=W;exports.maybeRefreshJWT=D;exports.nextSecurityHeaders=Se;exports.resignForStackNet=X;exports.securityHeaders=B;exports.signJWT=$;exports.verifyJWT=M;exports.verifyJWTSignature=K;exports.withSecurityHeaders=ge;
1
+ 'use strict';var crypto=require('crypto');function G(e){return Buffer.from(e).toString("base64url")}function te(e){return Buffer.from(e,"base64url").toString()}function E(e){try{let r=e.split(".");return r.length!==3?null:JSON.parse(te(r[1]))}catch{return null}}function P(e,r){let t=G(JSON.stringify({alg:"HS256",typ:"JWT"})),o=G(JSON.stringify(e)),n=crypto.createHmac("sha256",r).update(`${t}.${o}`).digest("base64url");return `${t}.${o}.${n}`}function V(e,r){try{let t=e.split(".");if(t.length!==3)return !1;let[o,n,a]=t,i=crypto.createHmac("sha256",r).update(`${o}.${n}`).digest("base64url"),m=Buffer.from(a),f=Buffer.from(i);return m.length!==f.length?!1:crypto.timingSafeEqual(m,f)}catch{return false}}function _(e,r){if(!V(e,r))return null;let t=E(e);return !t||t.exp&&t.exp<Math.floor(Date.now()/1e3)?null:t}function D(e,r,t=900,o=300){let n=_(e,r);return !n?.exp||n.exp*1e3-Date.now()>o*1e3?null:P({...n,exp:Math.floor(Date.now()/1e3)+t},r)}function B(e=32){return crypto.randomBytes(e).toString("hex")}function I(e){return e.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||e.headers.get("x-real-ip")||"unknown"}var se="__csrf",oe="x-csrf-token",ne=/^[A-Za-z_$][A-Za-z0-9_$-]{0,63}$/,ae=/^[A-Za-z][A-Za-z0-9-]{0,63}$/;function j(e={}){let r=e.cookieName||se,t=e.headerName||oe,o=e.tokenLength||32,n=e.secure!==false;if(!ne.test(r))throw new Error(`createCSRFProtection: invalid cookieName "${r}"`);if(!ae.test(t))throw new Error(`createCSRFProtection: invalid headerName "${t}"`);if(o<16||o>128)throw new Error("createCSRFProtection: tokenLength must be between 16 and 128 bytes");return {generateToken(a){let i=B(o),m=[`${r}=${i}`,"Path=/","SameSite=Lax"];return n&&m.push("Secure"),a.append("Set-Cookie",m.join("; ")),i},validateRequest(a){let i=a.headers.get("cookie");if(!i)return {valid:false,error:"No cookies present"};let m=i.split(";").map(p=>p.trim()).find(p=>p.startsWith(`${r}=`))?.slice(r.length+1);if(!m)return {valid:false,error:"CSRF cookie missing"};let f=a.headers.get(t);if(!f)return {valid:false,error:"CSRF header missing"};try{let p=Buffer.from(m),l=Buffer.from(f);return p.length!==l.length?{valid:!1,error:"CSRF token mismatch"}:crypto.timingSafeEqual(p,l)?{valid:!0}:{valid:!1,error:"CSRF token mismatch"}}catch{return {valid:false,error:"CSRF validation failed"}}},cookieName:r,headerName:t}}function T(e){let r=new Map,t=setInterval(()=>{let o=Date.now();for(let[n,a]of r)o>=a.resetAt&&r.delete(n);},6e4);return typeof t=="object"&&"unref"in t&&t.unref(),{async check(o){let n=Date.now(),a=r.get(o);return (!a||n>=a.resetAt)&&(a={count:0,resetAt:n+e.windowMs},r.set(o,a)),a.count++,a.count>e.maxRequests?{allowed:false,remaining:0,retryAfter:Math.ceil((a.resetAt-n)/1e3)}:{allowed:true,remaining:e.maxRequests-a.count}}}}function ie(){let e=new Map,r=setInterval(()=>{let t=Date.now();for(let[o,n]of e)t>=n&&e.delete(o);},6e4);return typeof r=="object"&&"unref"in r&&r.unref(),{async has(t){let o=e.get(t);return o?Date.now()>=o?(e.delete(t),false):true:false},async set(t,o){e.set(t,Date.now()+o*1e3);}}}function ce(e,r){let t=r?.rateLimiter||T({maxRequests:10,windowMs:6e4}),o=j({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,a=e.sessionMaxAge||604800;e.stacknetJwtSecret||e.authSecret;return async function(f){let p=I(f),l=await t.check(`auth:${p}`);if(!l.allowed)return Response.json({error:"Too many login attempts. Please wait."},{status:429,headers:{"Retry-After":String(l.retryAfter||60)}});let s;try{s=await f.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{chain:c,message:d,signature:u,publicKey:g,otp:y,code:w,redirectUrl:h,stackId:S}=s,R=S||e.stackId,x;if(c&&d&&u){let Y={"Content-Type":"application/json"},J=await fetch(`${e.stacknetUrl}/api/v2/stacks/${encodeURIComponent(R)}/auth/web3/verify`,{method:"POST",headers:Y,body:JSON.stringify({chain:c,message:d,signature:u,public_key:g}),signal:AbortSignal.timeout(1e4)});if(!J.ok){let q=await J.json().catch(()=>({})),W=q?.error?.message||q?.message||q?.error||`StackNet returned ${J.status}`;return console.error(`[auth-callback] Verify failed: ${J.status}`,W),Response.json({error:"Wallet verification failed",detail:typeof W=="string"?W:void 0},{status:401})}let N=await J.json();x=N.data?.session||N.session||N.data||N,console.log(`[auth-callback] Verify OK, sessionData keys: ${Object.keys(x||{}).join(", ")}`);}else return y||w?Response.json({error:"Use /api/auth/otp for OTP verification"},{status:400}):Response.json({error:"Provide wallet signature or OTP code"},{status:400});if(!x?.jwt)return Response.json({error:"Authentication failed \u2014 no session returned"},{status:401});let k=JSON.parse(Buffer.from(x.jwt.split(".")[1],"base64url").toString()),A=Math.floor(Date.now()/1e3),H={...k,exp:A+n,iat:A},v=P(H,e.authSecret),b={userId:k.sub||k.user_id||k.session_id||k.global_id||"",address:x.address||k.address,chain:x.chain||c,expiresAt:Date.now()+a*1e3,authMethod:c?`web3:${c}`:"otp"},$=new Headers({"Content-Type":"application/json"}),O=e.secureCookies!==false?"; Secure":"",L=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";$.append("Set-Cookie",`stackauth_jwt=${v}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${a}${O}${L}`);let X=Buffer.from(JSON.stringify(b)).toString("base64url");return $.append("Set-Cookie",`stackauth_session=${X}; Path=/; SameSite=Lax; Max-Age=${a}${O}${L}`),o.generateToken($),new Response(JSON.stringify({user:b}),{status:200,headers:$})}}function K(e,r){if(!r)return null;try{let t=E(e);if(!t||t.exp&&t.exp<Math.floor(Date.now()/1e3))return null;let o=Buffer.from(JSON.stringify({alg:"HS256",typ:"JWT"})).toString("base64url"),n=Buffer.from(JSON.stringify(t)).toString("base64url"),a=crypto.createHmac("sha256",r).update(`${o}.${n}`).digest("base64url");return `${o}.${n}.${a}`}catch{return null}}var le=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;function Z(e){return typeof e!="string"||e.length===0||e.length>8192?null:le.test(e)?e:null}function U(e,r){let t=K(e,r),o=t&&Z(t);if(o)return {Cookie:`stackauth_jwt=${o}`};let n=Z(e);return n?{Cookie:`stackauth_jwt=${n}`}:{}}function M(e){let r=e.headers.get("cookie");if(r){let o=r.split(";").map(n=>n.trim()).find(n=>n.startsWith("stackauth_jwt="));if(o)return o.slice(14)}let t=e.headers.get("authorization");return t?.startsWith("Bearer ")?t.slice(7):null}function pe(e){return !e.authSecret&&typeof console<"u"&&console.warn("[userutils] createLogoutHandler called without authSecret \u2014 upstream session revocation is disabled. Pass authSecret to enable it safely."),async function(t){let o=M(t);if(o&&e.authSecret){let m=_(o,e.authSecret),f=m?.session_id||m?.sub;if(f&&typeof f=="string")try{await fetch(`${e.stacknetUrl}/api/v2/sessions/${encodeURIComponent(f)}`,{method:"DELETE",signal:AbortSignal.timeout(5e3)});}catch{}}let n=e.secureCookies!==false?"; Secure":"",a=e.cookieDomain?`; Domain=${e.cookieDomain}`:"",i=new Headers({"Content-Type":"application/json"});return i.append("Set-Cookie",`stackauth_jwt=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${n}${a}`),i.append("Set-Cookie",`stackauth_session=; Path=/; SameSite=Lax; Max-Age=0${n}${a}`),i.append("Set-Cookie",`__csrf=; Path=/; SameSite=Lax; Max-Age=0${n}${a}`),new Response(JSON.stringify({success:true}),{status:200,headers:i})}}function de(e){let r=e.jwtExpiry||900,t=e.sessionMaxAge||604800;return async function(n){let a=M(n);if(!a)return Response.json({session:null},{status:200});let i=_(a,e.authSecret);if(!i)return Response.json({session:null},{status:200});let f={userId:i.sub||i.user_id||i.session_id||i.global_id||"",address:i.address,chain:i.chain,expiresAt:i.session_expires_at||(i.exp?i.exp*1e3:Date.now()+t*1e3),planId:i.plan_id,authMethod:i.auth_method},p=new Headers({"Content-Type":"application/json"}),l=D(a,e.authSecret,r,300);if(l){let s=e.secureCookies!==false?"; Secure":"",c=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";p.append("Set-Cookie",`stackauth_jwt=${l}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${t}${s}${c}`);}return new Response(JSON.stringify({session:f}),{status:200,headers:p})}}function ge(e,r){if(e.length!==r.length)return false;try{return crypto.timingSafeEqual(Buffer.from(e),Buffer.from(r))}catch{return false}}function he(e){let r=e.rateLimiter||T({maxRequests:5,windowMs:3e5}),t=j({secure:e.secureCookies!==false}),o=e.jwtExpiry||900,n=e.sessionMaxAge||604800;return async function(i){let m=I(i),f=await r.check(`otp:${m}`);if(!f.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(f.retryAfter||300)}});let p;try{p=await i.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{code:l}=p;if(!l||typeof l!="string"||l.length!==6)return Response.json({error:"Invalid code format"},{status:400});if(!ge(l,e.otpSecret))return Response.json({error:"Invalid code"},{status:401});let s=Math.floor(Date.now()/1e3),d={sub:`otp:${crypto.createHash("sha256").update(`otp:${l}:${Date.now()}`).digest("hex").slice(0,32)}`,auth_method:"otp",iat:s,exp:s+o},u=P(d,e.authSecret),g={userId:d.sub,expiresAt:Date.now()+n*1e3,authMethod:"otp"},y=new Headers({"Content-Type":"application/json"}),w=e.secureCookies!==false?"; Secure":"",h=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";y.append("Set-Cookie",`stackauth_jwt=${u}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${n}${w}${h}`);let S=Buffer.from(JSON.stringify(g)).toString("base64url");return y.append("Set-Cookie",`stackauth_session=${S}; Path=/; SameSite=Lax; Max-Age=${n}${w}${h}`),t.generateToken(y),new Response(JSON.stringify({success:true,data:{user:g}}),{status:200,headers:y})}}function ye(e,r){let t=r?.rateLimiter||T({maxRequests:10,windowMs:6e4}),o=j({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,a=e.sessionMaxAge||604800;async function i(f){let p=new URL(f.url),l=p.searchParams.get("provider"),s=p.searchParams.get("redirectUri")||p.searchParams.get("redirect_uri"),c=p.searchParams.get("stackId")||e.stackId;if(!l)return Response.json({error:"Missing provider parameter"},{status:400});if(!s)return Response.json({error:"Missing redirectUri parameter"},{status:400});if(!/^[a-z][a-z0-9_-]{0,32}$/.test(l))return Response.json({error:"Invalid provider name"},{status:400});if(!c||!/^[a-zA-Z0-9_-]{1,64}$/.test(c))return Response.json({error:"Invalid stackId"},{status:400});try{let d=await fetch(`${e.stacknetUrl}/api/v2/stacks/${encodeURIComponent(c)}/auth/oauth/${encodeURIComponent(l)}/initiate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirectUrl:s}),signal:AbortSignal.timeout(1e4)});if(!d.ok){let y=await d.json().catch(()=>({}));return Response.json({error:y.error?.message||`Failed to start OAuth flow: ${d.statusText}`},{status:d.status})}let u=await d.json(),g=u.data||u;return Response.json({redirect_url:g.url,state:g.state})}catch(d){return Response.json({error:d.message||"Failed to start OAuth flow"},{status:500})}}async function m(f){let p=I(f),l=await t.check(`oauth:${p}`);if(!l.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(l.retryAfter||60)}});let s;try{s=await f.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{provider:c,code:d,state:u,stackId:g}=s,y=g||e.stackId;if(!c||!d||!u)return Response.json({error:"Missing provider, code, or state"},{status:400});if(!/^[a-z][a-z0-9_-]{0,32}$/.test(c))return Response.json({error:"Invalid provider name"},{status:400});if(!y||!/^[a-zA-Z0-9_-]{1,64}$/.test(y))return Response.json({error:"Invalid stackId"},{status:400});try{let w=await fetch(`${e.stacknetUrl}/api/v2/stacks/${encodeURIComponent(y)}/auth/oauth/${encodeURIComponent(c)}/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:d,state:u}),signal:AbortSignal.timeout(1e4)});if(!w.ok){let O=await w.json().catch(()=>({}));return Response.json({error:O.error?.message||`OAuth verification failed: ${w.statusText}`},{status:401})}let h=await w.json(),S=h.data?.session||h.session||h.data||h;if(!S?.jwt)return Response.json({error:"OAuth authentication failed \u2014 no session returned"},{status:401});let R=JSON.parse(Buffer.from(S.jwt.split(".")[1],"base64url").toString()),x=Math.floor(Date.now()/1e3),k=P({...R,exp:x+n,iat:x},e.authSecret),H={userId:R.sub||R.user_id||R.session_id||R.global_id||"",address:S.address||R.address,chain:void 0,expiresAt:Date.now()+a*1e3,authMethod:`oauth:${c}`},v=new Headers({"Content-Type":"application/json"}),C=e.secureCookies!==!1?"; Secure":"",b=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";v.append("Set-Cookie",`stackauth_jwt=${k}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${a}${C}${b}`);let $=Buffer.from(JSON.stringify(H)).toString("base64url");return v.append("Set-Cookie",`stackauth_session=${$}; Path=/; SameSite=Lax; Max-Age=${a}${C}${b}`),o.generateToken(v),new Response(JSON.stringify({user:H}),{status:200,headers:v})}catch(w){return Response.json({error:w.message||"OAuth callback failed"},{status:500})}}return {startFlow:i,handleCallback:m}}function Se(e,r){let t=r?.rateLimiter||T({maxRequests:10,windowMs:6e4}),o=j({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,a=e.sessionMaxAge||604800;return async function(m){let f=I(m),p=await t.check(`google-onetap:${f}`);if(!p.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(p.retryAfter||60)}});let l;try{l=await m.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{credential:s,stackId:c}=l,d=c||e.stackId;if(!s)return Response.json({error:"Missing credential"},{status:400});if(s.split(".").length!==3)return Response.json({error:"Invalid credential format"},{status:400});let u;try{let S=await fetch(`https://oauth2.googleapis.com/tokeninfo?id_token=${encodeURIComponent(s)}`,{signal:AbortSignal.timeout(1e4)});if(!S.ok)return Response.json({error:"Google credential verification failed"},{status:401});u=await S.json();}catch{return Response.json({error:"Failed to verify Google credential"},{status:500})}if(!u.sub||!u.email)return Response.json({error:"Invalid Google token \u2014 missing user info"},{status:401});if(u.iss!=="https://accounts.google.com"&&u.iss!=="accounts.google.com")return Response.json({error:"Invalid Google token issuer"},{status:401});let g=typeof u.exp=="string"?parseInt(u.exp,10):Number(u.exp);if(!Number.isFinite(g)||g<Math.floor(Date.now()/1e3))return Response.json({error:"Google token expired"},{status:401});let y=e.googleClientIds||(e.googleClientId?[e.googleClientId]:[]);if(y.length===0)return Response.json({error:"Google One Tap not configured \u2014 set ServerConfig.googleClientId(s)"},{status:500});if(!u.aud||!y.includes(u.aud))return Response.json({error:"Invalid Google token audience"},{status:401});if(!(u.email_verified===true||u.email_verified==="true"))return Response.json({error:"Google email is not verified"},{status:401});let h={sub:u.sub,email:u.email,name:u.name,picture:u.picture};try{let S=await fetch(`${e.stacknetUrl}/api/v2/stacks/${encodeURIComponent(d)}/auth/oauth/google/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({credential:s,google_id:h.sub,email:h.email,name:h.name,picture:h.picture,one_tap:!0}),signal:AbortSignal.timeout(1e4)});if(!S.ok){let k=Math.floor(Date.now()/1e3),A=h.sub,H=P({sub:A,global_id:`google:${A}`,stack_id:d,chain:"google",email:h.email,credentials:["oauth:google"],iat:k,exp:k+n,iss:"stackauth.network",signed_by:["local"]},e.authSecret),v={userId:A,address:h.email,chain:void 0,expiresAt:Date.now()+a*1e3,authMethod:"oauth:google"},C=new Headers({"Content-Type":"application/json"}),b=e.secureCookies!==!1?"; Secure":"",$=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";C.append("Set-Cookie",`stackauth_jwt=${H}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${a}${b}${$}`);let O=Buffer.from(JSON.stringify(v)).toString("base64url");return C.append("Set-Cookie",`stackauth_session=${O}; Path=/; SameSite=Lax; Max-Age=${a}${b}${$}`),o.generateToken(C),new Response(JSON.stringify({user:v}),{status:200,headers:C})}let R=await S.json(),x=R.data?.session||R.session||R.data||R;if(x?.jwt){let k=JSON.parse(Buffer.from(x.jwt.split(".")[1],"base64url").toString()),A=Math.floor(Date.now()/1e3),H=P({...k,exp:A+n,iat:A},e.authSecret),C={userId:k.sub||k.user_id||h.sub,address:h.email||x.address,chain:void 0,expiresAt:Date.now()+a*1e3,authMethod:"oauth:google"},b=new Headers({"Content-Type":"application/json"}),$=e.secureCookies!==!1?"; Secure":"",O=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";b.append("Set-Cookie",`stackauth_jwt=${H}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${a}${$}${O}`);let L=Buffer.from(JSON.stringify(C)).toString("base64url");return b.append("Set-Cookie",`stackauth_session=${L}; Path=/; SameSite=Lax; Max-Age=${a}${$}${O}`),o.generateToken(b),new Response(JSON.stringify({user:C}),{status:200,headers:b})}return Response.json({error:"No session returned"},{status:401})}catch(S){return Response.json({error:S.message||"Google One Tap authentication failed"},{status:500})}}}function ke(e){let r=j({secure:e.secureCookies!==false}),t=e.rateLimiter||T({maxRequests:20,windowMs:6e4}),o=e.stacknetJwtSecret||e.authSecret,n=e.jwtExpiry||900,a=e.sessionMaxAge||604800;function i(s){let c=M(s);if(!c)return null;let d=_(c,e.authSecret);return d?{jwt:c,payload:d}:null}function m(s,c){let d=D(s,e.authSecret,n,300);if(d){let u=e.secureCookies!==false?"; Secure":"",g=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";c.append("Set-Cookie",`stackauth_jwt=${d}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${a}${u}${g}`);}}async function f(s,c){let d=i(s);if(!d)return Response.json({error:"Unauthorized"},{status:401});let u=U(d.jwt,o),g=await fetch(`${e.stacknetUrl}${c}`,{headers:u,signal:AbortSignal.timeout(15e3)}),y=await g.json().catch(()=>({})),w=new Headers({"Content-Type":"application/json"});return m(d.jwt,w),new Response(JSON.stringify(y),{status:g.status,headers:w})}async function p(s,c,d){let u=i(s);if(!u)return Response.json({error:"Unauthorized"},{status:401});let g=r.validateRequest(s);if(!g.valid)return Response.json({error:g.error||"CSRF validation failed"},{status:403});let y=u.payload.sub||u.payload.user_id||"unknown";if(!(await t.check(`billing:${y}`)).allowed)return Response.json({error:"Too many requests"},{status:429});let h=await s.json().catch(()=>({})),S=U(u.jwt,o);S["Content-Type"]="application/json";let R=await fetch(`${e.stacknetUrl}${c}`,{method:"POST",headers:S,body:JSON.stringify({...h,...d}),signal:AbortSignal.timeout(15e3)}),x=await R.json().catch(()=>({})),k=new Headers({"Content-Type":"application/json"});return m(u.jwt,k),new Response(JSON.stringify(x),{status:R.status,headers:k})}let l=`/api/v2/stacks/${encodeURIComponent(e.stackId)}`;return {plans:{GET:async s=>{let c=await fetch(`${e.stacknetUrl}${l}/plans`,{signal:AbortSignal.timeout(1e4)}),d=await c.json().catch(()=>({}));return Response.json(d,{status:c.status})}},subscription:{GET:(s=>f(s,`${l}/subscription`))},subscribe:{POST:(s=>{let c=new URL(s.url).origin;return p(s,`${l}/subscribe`,{successUrl:`${c}/billing/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${c}/pricing`})})},cancel:{POST:(s=>p(s,`${l}/cancel-subscription`))},usage:{GET:(s=>f(s,"/v1/account/usage"))},history:{GET:(s=>f(s,`${l}/billing`))},prepaid:{POST:(s=>{let c=new URL(s.url).origin;return p(s,`${l}/prepaid`,{successUrl:`${c}/pricing/prepaid/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${c}/pricing/prepaid`})})},verifyPrepaid:{POST:(s=>p(s,`${l}/verify-prepaid`))},verifySession:{POST:(s=>p(s,`${l}/verify-session`))},subscribeSol:{POST:(s=>p(s,`${l}/subscribe-sol`))},prepaidSol:{POST:(s=>{new URL(s.url).origin;return p(s,`${l}/prepaid-sol`)})},topup:{POST:(s=>p(s,"/v1/account/topup"))}}}function we(e){return async function(t){let o=t.headers.get("stripe-signature");if(!o)return Response.json({error:"Missing Stripe signature"},{status:400});try{let n=await t.text(),a=await fetch(`${e.stacknetUrl}/api/v2/stacks/${encodeURIComponent(e.stackId)}/webhook/stripe`,{method:"POST",headers:{"Content-Type":"application/json","stripe-signature":o},body:n,signal:AbortSignal.timeout(1e4)}),i=await a.json().catch(()=>({received:!0}));return Response.json(i,{status:a.status})}catch{return Response.json({error:"Webhook processing failed"},{status:502})}}}function F(){return {"Strict-Transport-Security":"max-age=63072000; includeSubDomains; preload","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","X-XSS-Protection":"0","Referrer-Policy":"strict-origin-when-cross-origin","Permissions-Policy":"camera=(), microphone=(), geolocation=()"}}function Re(e){return async r=>{let t=await e(r),o=F(),n=new Headers(t.headers);for(let[a,i]of Object.entries(o))n.set(a,i);return new Response(t.body,{status:t.status,statusText:t.statusText,headers:n})}}function xe(){return Object.entries(F()).map(([e,r])=>({key:e,value:r}))}
2
+ exports.buildStackNetHeaders=U;exports.createAuthCallback=ce;exports.createBillingProxy=ke;exports.createCSRFProtection=j;exports.createGoogleOneTapHandler=Se;exports.createInMemoryRateLimiter=T;exports.createInMemoryReplayStore=ie;exports.createLogoutHandler=pe;exports.createOAuthHandlers=ye;exports.createOTPHandler=he;exports.createSessionHandler=de;exports.createWebhookHandler=we;exports.decodeJWTPayload=E;exports.extractIP=I;exports.extractJwt=M;exports.generateToken=B;exports.maybeRefreshJWT=D;exports.nextSecurityHeaders=xe;exports.resignForStackNet=K;exports.securityHeaders=F;exports.signJWT=P;exports.verifyJWT=_;exports.verifyJWTSignature=V;exports.withSecurityHeaders=Re;
@@ -1,4 +1,5 @@
1
- import { S as Session, g as ServerConfig } from '../config-BrziGArs.cjs';
1
+ import { S as Session } from '../auth-DR2aYcor.cjs';
2
+ import { e as ServerConfig } from '../config-Bjh8PEhY.cjs';
2
3
 
3
4
  /**
4
5
  * Server-only session type that includes the JWT.
@@ -49,7 +50,18 @@ declare function createAuthCallback(config: ServerConfig, opts?: AuthCallbackOpt
49
50
  * Factory: POST handler for logout.
50
51
  * Revokes session with StackNet and clears all auth cookies.
51
52
  */
52
- declare function createLogoutHandler(config: Pick<ServerConfig, 'stacknetUrl' | 'secureCookies' | 'cookieDomain'>): (request: Request) => Promise<Response>;
53
+ declare function createLogoutHandler(config: Pick<ServerConfig, 'stacknetUrl' | 'secureCookies' | 'cookieDomain'> & {
54
+ /**
55
+ * HMAC secret used to verify the JWT signature before extracting the
56
+ * sessionId for upstream revocation. STRONGLY RECOMMENDED.
57
+ *
58
+ * Without this, the handler skips upstream revocation entirely and only
59
+ * clears cookies — because trusting an unverified JWT for the sessionId
60
+ * would let an attacker plant a forged cookie and trigger DELETE on
61
+ * another user's session.
62
+ */
63
+ authSecret?: string;
64
+ }): (request: Request) => Promise<Response>;
53
65
 
54
66
  /**
55
67
  * Factory: GET handler for session validation.
@@ -238,6 +250,10 @@ declare function resignForStackNet(jwt: string, stacknetJwtSecret: string): stri
238
250
  /**
239
251
  * Build headers for proxying a user-scoped request to StackNet.
240
252
  * Re-signs the JWT so StackNet recognises the user's identity.
253
+ *
254
+ * Refuses to interpolate any value that doesn't match the compact JWT
255
+ * format (header.body.signature, base64url segments only) to prevent
256
+ * header injection.
241
257
  */
242
258
  declare function buildStackNetHeaders(jwt: string, stacknetJwtSecret: string): Record<string, string>;
243
259
  /**
@@ -1,4 +1,5 @@
1
- import { S as Session, g as ServerConfig } from '../config-BrziGArs.js';
1
+ import { S as Session } from '../auth-DR2aYcor.js';
2
+ import { e as ServerConfig } from '../config-_ZjAzNkJ.js';
2
3
 
3
4
  /**
4
5
  * Server-only session type that includes the JWT.
@@ -49,7 +50,18 @@ declare function createAuthCallback(config: ServerConfig, opts?: AuthCallbackOpt
49
50
  * Factory: POST handler for logout.
50
51
  * Revokes session with StackNet and clears all auth cookies.
51
52
  */
52
- declare function createLogoutHandler(config: Pick<ServerConfig, 'stacknetUrl' | 'secureCookies' | 'cookieDomain'>): (request: Request) => Promise<Response>;
53
+ declare function createLogoutHandler(config: Pick<ServerConfig, 'stacknetUrl' | 'secureCookies' | 'cookieDomain'> & {
54
+ /**
55
+ * HMAC secret used to verify the JWT signature before extracting the
56
+ * sessionId for upstream revocation. STRONGLY RECOMMENDED.
57
+ *
58
+ * Without this, the handler skips upstream revocation entirely and only
59
+ * clears cookies — because trusting an unverified JWT for the sessionId
60
+ * would let an attacker plant a forged cookie and trigger DELETE on
61
+ * another user's session.
62
+ */
63
+ authSecret?: string;
64
+ }): (request: Request) => Promise<Response>;
53
65
 
54
66
  /**
55
67
  * Factory: GET handler for session validation.
@@ -238,6 +250,10 @@ declare function resignForStackNet(jwt: string, stacknetJwtSecret: string): stri
238
250
  /**
239
251
  * Build headers for proxying a user-scoped request to StackNet.
240
252
  * Re-signs the JWT so StackNet recognises the user's identity.
253
+ *
254
+ * Refuses to interpolate any value that doesn't match the compact JWT
255
+ * format (header.body.signature, base64url segments only) to prevent
256
+ * header injection.
241
257
  */
242
258
  declare function buildStackNetHeaders(jwt: string, stacknetJwtSecret: string): Record<string, string>;
243
259
  /**
@@ -1,2 +1,2 @@
1
- import {createHmac,timingSafeEqual,randomBytes,createHash}from'crypto';function G(e){return Buffer.from(e).toString("base64url")}function ee(e){return Buffer.from(e,"base64url").toString()}function v(e){try{let r=e.split(".");return r.length!==3?null:JSON.parse(ee(r[1]))}catch{return null}}function $(e,r){let t=G(JSON.stringify({alg:"HS256",typ:"JWT"})),a=G(JSON.stringify(e)),n=createHmac("sha256",r).update(`${t}.${a}`).digest("base64url");return `${t}.${a}.${n}`}function K(e,r){try{let t=e.split(".");if(t.length!==3)return !1;let[a,n,o]=t,i=createHmac("sha256",r).update(`${a}.${n}`).digest("base64url"),y=Buffer.from(o),m=Buffer.from(i);return y.length!==m.length?!1:timingSafeEqual(y,m)}catch{return false}}function M(e,r){if(!K(e,r))return null;let t=v(e);return !t||t.exp&&t.exp<Math.floor(Date.now()/1e3)?null:t}function D(e,r,t=900,a=300){let n=M(e,r);return !n?.exp||n.exp*1e3-Date.now()>a*1e3?null:$({...n,exp:Math.floor(Date.now()/1e3)+t},r)}function W(e=32){return randomBytes(e).toString("hex")}function O(e){return e.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||e.headers.get("x-real-ip")||"unknown"}var re="__csrf",se="x-csrf-token";function j(e={}){let r=e.cookieName||re,t=e.headerName||se,a=e.tokenLength||32,n=e.secure!==false;return {generateToken(o){let i=W(a),y=[`${r}=${i}`,"Path=/","SameSite=Lax"];return n&&y.push("Secure"),o.append("Set-Cookie",y.join("; ")),i},validateRequest(o){let i=o.headers.get("cookie");if(!i)return {valid:false,error:"No cookies present"};let y=i.split(";").map(l=>l.trim()).find(l=>l.startsWith(`${r}=`))?.slice(r.length+1);if(!y)return {valid:false,error:"CSRF cookie missing"};let m=o.headers.get(t);if(!m)return {valid:false,error:"CSRF header missing"};try{let l=Buffer.from(y),u=Buffer.from(m);return l.length!==u.length?{valid:!1,error:"CSRF token mismatch"}:timingSafeEqual(l,u)?{valid:!0}:{valid:!1,error:"CSRF token mismatch"}}catch{return {valid:false,error:"CSRF validation failed"}}},cookieName:r,headerName:t}}function C(e){let r=new Map,t=setInterval(()=>{let a=Date.now();for(let[n,o]of r)a>=o.resetAt&&r.delete(n);},6e4);return typeof t=="object"&&"unref"in t&&t.unref(),{async check(a){let n=Date.now(),o=r.get(a);return (!o||n>=o.resetAt)&&(o={count:0,resetAt:n+e.windowMs},r.set(a,o)),o.count++,o.count>e.maxRequests?{allowed:false,remaining:0,retryAfter:Math.ceil((o.resetAt-n)/1e3)}:{allowed:true,remaining:e.maxRequests-o.count}}}}function oe(){let e=new Map,r=setInterval(()=>{let t=Date.now();for(let[a,n]of e)t>=n&&e.delete(a);},6e4);return typeof r=="object"&&"unref"in r&&r.unref(),{async has(t){let a=e.get(t);return a?Date.now()>=a?(e.delete(t),false):true:false},async set(t,a){e.set(t,Date.now()+a*1e3);}}}function ne(e,r){let t=r?.rateLimiter||C({maxRequests:10,windowMs:6e4}),a=j({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,o=e.sessionMaxAge||604800;e.stacknetJwtSecret||e.authSecret;return async function(m){let l=O(m),u=await t.check(`auth:${l}`);if(!u.allowed)return Response.json({error:"Too many login attempts. Please wait."},{status:429,headers:{"Retry-After":String(u.retryAfter||60)}});let s;try{s=await m.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{chain:c,message:p,signature:d,publicKey:f,otp:h,code:g,redirectUrl:k,stackId:w}=s,x=w||e.stackId,R;if(c&&p&&d){let Y={"Content-Type":"application/json"},_=await fetch(`${e.stacknetUrl}/api/v2/stacks/${x}/auth/web3/verify`,{method:"POST",headers:Y,body:JSON.stringify({chain:c,message:p,signature:d,public_key:f}),signal:AbortSignal.timeout(1e4)});if(!_.ok){let q=await _.json().catch(()=>({})),U=q?.error?.message||q?.message||q?.error||`StackNet returned ${_.status}`;return console.error(`[auth-callback] Verify failed: ${_.status}`,U),Response.json({error:"Wallet verification failed",detail:typeof U=="string"?U:void 0},{status:401})}let N=await _.json();R=N.data?.session||N.session||N.data||N,console.log(`[auth-callback] Verify OK, sessionData keys: ${Object.keys(R||{}).join(", ")}`);}else return h||g?Response.json({error:"Use /api/auth/otp for OTP verification"},{status:400}):Response.json({error:"Provide wallet signature or OTP code"},{status:400});if(!R?.jwt)return Response.json({error:"Authentication failed \u2014 no session returned"},{status:401});let S=JSON.parse(Buffer.from(R.jwt.split(".")[1],"base64url").toString()),b=Math.floor(Date.now()/1e3),T={...S,exp:b+n,iat:b},P=$(T,e.authSecret),J={userId:S.sub||S.user_id||S.session_id||S.global_id||"",address:R.address||S.address,chain:R.chain||c,expiresAt:Date.now()+o*1e3,authMethod:c?`web3:${c}`:"otp"},H=new Headers({"Content-Type":"application/json"}),L=e.secureCookies!==false?"; Secure":"",F=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";H.append("Set-Cookie",`stackauth_jwt=${P}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${L}${F}`);let z=Buffer.from(JSON.stringify(J)).toString("base64url");return H.append("Set-Cookie",`stackauth_session=${z}; Path=/; SameSite=Lax; Max-Age=${o}${L}${F}`),a.generateToken(H),new Response(JSON.stringify({user:J}),{status:200,headers:H})}}function X(e,r){if(!r)return null;try{let t=v(e);if(!t||t.exp&&t.exp<Math.floor(Date.now()/1e3))return null;let a=Buffer.from(JSON.stringify({alg:"HS256",typ:"JWT"})).toString("base64url"),n=Buffer.from(JSON.stringify(t)).toString("base64url"),o=createHmac("sha256",r).update(`${a}.${n}`).digest("base64url");return `${a}.${n}.${o}`}catch{return null}}function E(e,r){let t=X(e,r);return t?{Cookie:`stackauth_jwt=${t}`}:{Cookie:`stackauth_jwt=${e}`}}function A(e){let r=e.headers.get("cookie");if(r){let a=r.split(";").map(n=>n.trim()).find(n=>n.startsWith("stackauth_jwt="));if(a)return a.slice(14)}let t=e.headers.get("authorization");return t?.startsWith("Bearer ")?t.slice(7):null}function ie(e){return async function(t){let a=A(t);if(a){let y=v(a),m=y?.session_id||y?.sub;if(m)try{await fetch(`${e.stacknetUrl}/api/v2/sessions/${m}`,{method:"DELETE",signal:AbortSignal.timeout(5e3)});}catch{}}let n=e.secureCookies!==false?"; Secure":"",o=e.cookieDomain?`; Domain=${e.cookieDomain}`:"",i=new Headers({"Content-Type":"application/json"});return i.append("Set-Cookie",`stackauth_jwt=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${n}${o}`),i.append("Set-Cookie",`stackauth_session=; Path=/; SameSite=Lax; Max-Age=0${n}${o}`),i.append("Set-Cookie",`__csrf=; Path=/; SameSite=Lax; Max-Age=0${n}${o}`),new Response(JSON.stringify({success:true}),{status:200,headers:i})}}function ce(e){let r=e.jwtExpiry||900,t=e.sessionMaxAge||604800;return async function(n){let o=A(n);if(!o)return Response.json({session:null},{status:200});let i=M(o,e.authSecret);if(!i)return Response.json({session:null},{status:200});let m={userId:i.sub||i.user_id||i.session_id||i.global_id||"",address:i.address,chain:i.chain,expiresAt:i.session_expires_at||(i.exp?i.exp*1e3:Date.now()+t*1e3),planId:i.plan_id,authMethod:i.auth_method},l=new Headers({"Content-Type":"application/json"}),u=D(o,e.authSecret,r,300);if(u){let s=e.secureCookies!==false?"; Secure":"",c=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";l.append("Set-Cookie",`stackauth_jwt=${u}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${t}${s}${c}`);}return new Response(JSON.stringify({session:m}),{status:200,headers:l})}}function pe(e,r){if(e.length!==r.length)return false;try{return timingSafeEqual(Buffer.from(e),Buffer.from(r))}catch{return false}}function de(e){let r=e.rateLimiter||C({maxRequests:5,windowMs:3e5}),t=j({secure:e.secureCookies!==false}),a=e.jwtExpiry||900,n=e.sessionMaxAge||604800;return async function(i){let y=O(i),m=await r.check(`otp:${y}`);if(!m.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(m.retryAfter||300)}});let l;try{l=await i.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{code:u}=l;if(!u||typeof u!="string"||u.length!==6)return Response.json({error:"Invalid code format"},{status:400});if(!pe(u,e.otpSecret))return Response.json({error:"Invalid code"},{status:401});let s=Math.floor(Date.now()/1e3),p={sub:`otp:${createHash("sha256").update(`otp:${u}:${Date.now()}`).digest("hex").slice(0,32)}`,auth_method:"otp",iat:s,exp:s+a},d=$(p,e.authSecret),f={userId:p.sub,expiresAt:Date.now()+n*1e3,authMethod:"otp"},h=new Headers({"Content-Type":"application/json"}),g=e.secureCookies!==false?"; Secure":"",k=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";h.append("Set-Cookie",`stackauth_jwt=${d}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${n}${g}${k}`);let w=Buffer.from(JSON.stringify(f)).toString("base64url");return h.append("Set-Cookie",`stackauth_session=${w}; Path=/; SameSite=Lax; Max-Age=${n}${g}${k}`),t.generateToken(h),new Response(JSON.stringify({success:true,data:{user:f}}),{status:200,headers:h})}}function fe(e,r){let t=r?.rateLimiter||C({maxRequests:10,windowMs:6e4}),a=j({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,o=e.sessionMaxAge||604800;async function i(m){let l=new URL(m.url),u=l.searchParams.get("provider"),s=l.searchParams.get("redirectUri")||l.searchParams.get("redirect_uri"),c=l.searchParams.get("stackId")||e.stackId;if(!u)return Response.json({error:"Missing provider parameter"},{status:400});if(!s)return Response.json({error:"Missing redirectUri parameter"},{status:400});try{let p=await fetch(`${e.stacknetUrl}/api/v2/stacks/${c}/auth/oauth/${u}/initiate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirectUrl:s}),signal:AbortSignal.timeout(1e4)});if(!p.ok){let h=await p.json().catch(()=>({}));return Response.json({error:h.error?.message||`Failed to start OAuth flow: ${p.statusText}`},{status:p.status})}let d=await p.json(),f=d.data||d;return Response.json({redirect_url:f.url,state:f.state})}catch(p){return Response.json({error:p.message||"Failed to start OAuth flow"},{status:500})}}async function y(m){let l=O(m),u=await t.check(`oauth:${l}`);if(!u.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(u.retryAfter||60)}});let s;try{s=await m.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{provider:c,code:p,state:d,stackId:f}=s,h=f||e.stackId;if(!c||!p||!d)return Response.json({error:"Missing provider, code, or state"},{status:400});try{let g=await fetch(`${e.stacknetUrl}/api/v2/stacks/${h}/auth/oauth/${c}/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:p,state:d}),signal:AbortSignal.timeout(1e4)});if(!g.ok){let L=await g.json().catch(()=>({}));return Response.json({error:L.error?.message||`OAuth verification failed: ${g.statusText}`},{status:401})}let k=await g.json(),w=k.data?.session||k.session||k.data||k;if(!w?.jwt)return Response.json({error:"OAuth authentication failed \u2014 no session returned"},{status:401});let x=JSON.parse(Buffer.from(w.jwt.split(".")[1],"base64url").toString()),R=Math.floor(Date.now()/1e3),S=$({...x,exp:R+n,iat:R},e.authSecret),T={userId:x.sub||x.user_id||x.session_id||x.global_id||"",address:w.address||x.address,chain:void 0,expiresAt:Date.now()+o*1e3,authMethod:`oauth:${c}`},P=new Headers({"Content-Type":"application/json"}),I=e.secureCookies!==!1?"; Secure":"",J=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";P.append("Set-Cookie",`stackauth_jwt=${S}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${I}${J}`);let H=Buffer.from(JSON.stringify(T)).toString("base64url");return P.append("Set-Cookie",`stackauth_session=${H}; Path=/; SameSite=Lax; Max-Age=${o}${I}${J}`),a.generateToken(P),new Response(JSON.stringify({user:T}),{status:200,headers:P})}catch(g){return Response.json({error:g.message||"OAuth callback failed"},{status:500})}}return {startFlow:i,handleCallback:y}}function me(e,r){let t=r?.rateLimiter||C({maxRequests:10,windowMs:6e4}),a=j({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,o=e.sessionMaxAge||604800;return async function(y){let m=O(y),l=await t.check(`google-onetap:${m}`);if(!l.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(l.retryAfter||60)}});let u;try{u=await y.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{credential:s,stackId:c}=u,p=c||e.stackId;if(!s)return Response.json({error:"Missing credential"},{status:400});let d;try{let f=s.split(".");if(f.length!==3)throw new Error("Invalid JWT");d=JSON.parse(Buffer.from(f[1],"base64url").toString());}catch{return Response.json({error:"Invalid credential format"},{status:400})}try{let f=await fetch(`https://oauth2.googleapis.com/tokeninfo?id_token=${encodeURIComponent(s)}`,{signal:AbortSignal.timeout(1e4)});if(!f.ok)return Response.json({error:"Google credential verification failed"},{status:401});let h=await f.json();if(!h.sub||!h.email)return Response.json({error:"Invalid Google token \u2014 missing user info"},{status:401})}catch{return Response.json({error:"Failed to verify Google credential"},{status:500})}try{let f=await fetch(`${e.stacknetUrl}/api/v2/stacks/${p}/auth/oauth/google/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({credential:s,google_id:d.sub,email:d.email,name:d.name,picture:d.picture,one_tap:!0}),signal:AbortSignal.timeout(1e4)});if(!f.ok){let k=Math.floor(Date.now()/1e3),w=d.sub,x=$({sub:w,global_id:`google:${w}`,stack_id:p,chain:"google",email:d.email,credentials:["oauth:google"],iat:k,exp:k+n,iss:"stackauth.network",signed_by:["local"]},e.authSecret),R={userId:w,address:d.email,chain:void 0,expiresAt:Date.now()+o*1e3,authMethod:"oauth:google"},S=new Headers({"Content-Type":"application/json"}),b=e.secureCookies!==!1?"; Secure":"",T=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";S.append("Set-Cookie",`stackauth_jwt=${x}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${b}${T}`);let P=Buffer.from(JSON.stringify(R)).toString("base64url");return S.append("Set-Cookie",`stackauth_session=${P}; Path=/; SameSite=Lax; Max-Age=${o}${b}${T}`),a.generateToken(S),new Response(JSON.stringify({user:R}),{status:200,headers:S})}let h=await f.json(),g=h.data?.session||h.session||h.data||h;if(g?.jwt){let k=JSON.parse(Buffer.from(g.jwt.split(".")[1],"base64url").toString()),w=Math.floor(Date.now()/1e3),x=$({...k,exp:w+n,iat:w},e.authSecret),S={userId:k.sub||k.user_id||d.sub,address:d.email||g.address,chain:void 0,expiresAt:Date.now()+o*1e3,authMethod:"oauth:google"},b=new Headers({"Content-Type":"application/json"}),T=e.secureCookies!==!1?"; Secure":"",P=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";b.append("Set-Cookie",`stackauth_jwt=${x}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${T}${P}`);let I=Buffer.from(JSON.stringify(S)).toString("base64url");return b.append("Set-Cookie",`stackauth_session=${I}; Path=/; SameSite=Lax; Max-Age=${o}${T}${P}`),a.generateToken(b),new Response(JSON.stringify({user:S}),{status:200,headers:b})}return Response.json({error:"No session returned"},{status:401})}catch(f){return Response.json({error:f.message||"Google One Tap authentication failed"},{status:500})}}}function ye(e){let r=j({secure:e.secureCookies!==false}),t=e.rateLimiter||C({maxRequests:20,windowMs:6e4}),a=e.stacknetJwtSecret||e.authSecret,n=e.jwtExpiry||900,o=e.sessionMaxAge||604800;function i(s){let c=A(s);if(!c)return null;let p=M(c,e.authSecret);return p?{jwt:c,payload:p}:null}function y(s,c){let p=D(s,e.authSecret,n,300);if(p){let d=e.secureCookies!==false?"; Secure":"",f=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";c.append("Set-Cookie",`stackauth_jwt=${p}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${o}${d}${f}`);}}async function m(s,c){let p=i(s);if(!p)return Response.json({error:"Unauthorized"},{status:401});let d=E(p.jwt,a),f=await fetch(`${e.stacknetUrl}${c}`,{headers:d,signal:AbortSignal.timeout(15e3)}),h=await f.json().catch(()=>({})),g=new Headers({"Content-Type":"application/json"});return y(p.jwt,g),new Response(JSON.stringify(h),{status:f.status,headers:g})}async function l(s,c,p){let d=i(s);if(!d)return Response.json({error:"Unauthorized"},{status:401});let f=r.validateRequest(s);if(!f.valid)return Response.json({error:f.error||"CSRF validation failed"},{status:403});let h=d.payload.sub||d.payload.user_id||"unknown";if(!(await t.check(`billing:${h}`)).allowed)return Response.json({error:"Too many requests"},{status:429});let k=await s.json().catch(()=>({})),w=E(d.jwt,a);w["Content-Type"]="application/json";let x=await fetch(`${e.stacknetUrl}${c}`,{method:"POST",headers:w,body:JSON.stringify({...k,...p}),signal:AbortSignal.timeout(15e3)}),R=await x.json().catch(()=>({})),S=new Headers({"Content-Type":"application/json"});return y(d.jwt,S),new Response(JSON.stringify(R),{status:x.status,headers:S})}let u=`/api/v2/stacks/${e.stackId}`;return {plans:{GET:async s=>{let c=await fetch(`${e.stacknetUrl}${u}/plans`,{signal:AbortSignal.timeout(1e4)}),p=await c.json().catch(()=>({}));return Response.json(p,{status:c.status})}},subscription:{GET:(s=>m(s,`${u}/subscription`))},subscribe:{POST:(s=>{let c=new URL(s.url).origin;return l(s,`${u}/subscribe`,{successUrl:`${c}/billing/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${c}/pricing`})})},cancel:{POST:(s=>l(s,`${u}/cancel-subscription`))},usage:{GET:(s=>m(s,"/v1/account/usage"))},history:{GET:(s=>m(s,`${u}/billing`))},prepaid:{POST:(s=>{let c=new URL(s.url).origin;return l(s,`${u}/prepaid`,{successUrl:`${c}/pricing/prepaid/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${c}/pricing/prepaid`})})},verifyPrepaid:{POST:(s=>l(s,`${u}/verify-prepaid`))},verifySession:{POST:(s=>l(s,`${u}/verify-session`))},subscribeSol:{POST:(s=>l(s,`${u}/subscribe-sol`))},prepaidSol:{POST:(s=>{new URL(s.url).origin;return l(s,`${u}/prepaid-sol`)})},topup:{POST:(s=>l(s,"/v1/account/topup"))}}}function he(e){return async function(t){let a=t.headers.get("stripe-signature");if(!a)return Response.json({error:"Missing Stripe signature"},{status:400});try{let n=await t.text(),o=await fetch(`${e.stacknetUrl}/api/v2/stacks/${e.stackId}/webhook/stripe`,{method:"POST",headers:{"Content-Type":"application/json","stripe-signature":a},body:n,signal:AbortSignal.timeout(1e4)}),i=await o.json().catch(()=>({received:!0}));return Response.json(i,{status:o.status})}catch{return Response.json({error:"Webhook processing failed"},{status:502})}}}function B(){return {"Strict-Transport-Security":"max-age=63072000; includeSubDomains; preload","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","X-XSS-Protection":"0","Referrer-Policy":"strict-origin-when-cross-origin","Permissions-Policy":"camera=(), microphone=(), geolocation=()"}}function ge(e){return async r=>{let t=await e(r),a=B(),n=new Headers(t.headers);for(let[o,i]of Object.entries(a))n.set(o,i);return new Response(t.body,{status:t.status,statusText:t.statusText,headers:n})}}function Se(){return Object.entries(B()).map(([e,r])=>({key:e,value:r}))}
2
- export{E as buildStackNetHeaders,ne as createAuthCallback,ye as createBillingProxy,j as createCSRFProtection,me as createGoogleOneTapHandler,C as createInMemoryRateLimiter,oe as createInMemoryReplayStore,ie as createLogoutHandler,fe as createOAuthHandlers,de as createOTPHandler,ce as createSessionHandler,he as createWebhookHandler,v as decodeJWTPayload,O as extractIP,A as extractJwt,W as generateToken,D as maybeRefreshJWT,Se as nextSecurityHeaders,X as resignForStackNet,B as securityHeaders,$ as signJWT,M as verifyJWT,K as verifyJWTSignature,ge as withSecurityHeaders};
1
+ import {createHmac,timingSafeEqual,randomBytes,createHash}from'crypto';function G(e){return Buffer.from(e).toString("base64url")}function te(e){return Buffer.from(e,"base64url").toString()}function E(e){try{let r=e.split(".");return r.length!==3?null:JSON.parse(te(r[1]))}catch{return null}}function P(e,r){let t=G(JSON.stringify({alg:"HS256",typ:"JWT"})),o=G(JSON.stringify(e)),n=createHmac("sha256",r).update(`${t}.${o}`).digest("base64url");return `${t}.${o}.${n}`}function V(e,r){try{let t=e.split(".");if(t.length!==3)return !1;let[o,n,a]=t,i=createHmac("sha256",r).update(`${o}.${n}`).digest("base64url"),m=Buffer.from(a),f=Buffer.from(i);return m.length!==f.length?!1:timingSafeEqual(m,f)}catch{return false}}function _(e,r){if(!V(e,r))return null;let t=E(e);return !t||t.exp&&t.exp<Math.floor(Date.now()/1e3)?null:t}function D(e,r,t=900,o=300){let n=_(e,r);return !n?.exp||n.exp*1e3-Date.now()>o*1e3?null:P({...n,exp:Math.floor(Date.now()/1e3)+t},r)}function B(e=32){return randomBytes(e).toString("hex")}function I(e){return e.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||e.headers.get("x-real-ip")||"unknown"}var se="__csrf",oe="x-csrf-token",ne=/^[A-Za-z_$][A-Za-z0-9_$-]{0,63}$/,ae=/^[A-Za-z][A-Za-z0-9-]{0,63}$/;function j(e={}){let r=e.cookieName||se,t=e.headerName||oe,o=e.tokenLength||32,n=e.secure!==false;if(!ne.test(r))throw new Error(`createCSRFProtection: invalid cookieName "${r}"`);if(!ae.test(t))throw new Error(`createCSRFProtection: invalid headerName "${t}"`);if(o<16||o>128)throw new Error("createCSRFProtection: tokenLength must be between 16 and 128 bytes");return {generateToken(a){let i=B(o),m=[`${r}=${i}`,"Path=/","SameSite=Lax"];return n&&m.push("Secure"),a.append("Set-Cookie",m.join("; ")),i},validateRequest(a){let i=a.headers.get("cookie");if(!i)return {valid:false,error:"No cookies present"};let m=i.split(";").map(p=>p.trim()).find(p=>p.startsWith(`${r}=`))?.slice(r.length+1);if(!m)return {valid:false,error:"CSRF cookie missing"};let f=a.headers.get(t);if(!f)return {valid:false,error:"CSRF header missing"};try{let p=Buffer.from(m),l=Buffer.from(f);return p.length!==l.length?{valid:!1,error:"CSRF token mismatch"}:timingSafeEqual(p,l)?{valid:!0}:{valid:!1,error:"CSRF token mismatch"}}catch{return {valid:false,error:"CSRF validation failed"}}},cookieName:r,headerName:t}}function T(e){let r=new Map,t=setInterval(()=>{let o=Date.now();for(let[n,a]of r)o>=a.resetAt&&r.delete(n);},6e4);return typeof t=="object"&&"unref"in t&&t.unref(),{async check(o){let n=Date.now(),a=r.get(o);return (!a||n>=a.resetAt)&&(a={count:0,resetAt:n+e.windowMs},r.set(o,a)),a.count++,a.count>e.maxRequests?{allowed:false,remaining:0,retryAfter:Math.ceil((a.resetAt-n)/1e3)}:{allowed:true,remaining:e.maxRequests-a.count}}}}function ie(){let e=new Map,r=setInterval(()=>{let t=Date.now();for(let[o,n]of e)t>=n&&e.delete(o);},6e4);return typeof r=="object"&&"unref"in r&&r.unref(),{async has(t){let o=e.get(t);return o?Date.now()>=o?(e.delete(t),false):true:false},async set(t,o){e.set(t,Date.now()+o*1e3);}}}function ce(e,r){let t=r?.rateLimiter||T({maxRequests:10,windowMs:6e4}),o=j({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,a=e.sessionMaxAge||604800;e.stacknetJwtSecret||e.authSecret;return async function(f){let p=I(f),l=await t.check(`auth:${p}`);if(!l.allowed)return Response.json({error:"Too many login attempts. Please wait."},{status:429,headers:{"Retry-After":String(l.retryAfter||60)}});let s;try{s=await f.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{chain:c,message:d,signature:u,publicKey:g,otp:y,code:w,redirectUrl:h,stackId:S}=s,R=S||e.stackId,x;if(c&&d&&u){let Y={"Content-Type":"application/json"},J=await fetch(`${e.stacknetUrl}/api/v2/stacks/${encodeURIComponent(R)}/auth/web3/verify`,{method:"POST",headers:Y,body:JSON.stringify({chain:c,message:d,signature:u,public_key:g}),signal:AbortSignal.timeout(1e4)});if(!J.ok){let q=await J.json().catch(()=>({})),W=q?.error?.message||q?.message||q?.error||`StackNet returned ${J.status}`;return console.error(`[auth-callback] Verify failed: ${J.status}`,W),Response.json({error:"Wallet verification failed",detail:typeof W=="string"?W:void 0},{status:401})}let N=await J.json();x=N.data?.session||N.session||N.data||N,console.log(`[auth-callback] Verify OK, sessionData keys: ${Object.keys(x||{}).join(", ")}`);}else return y||w?Response.json({error:"Use /api/auth/otp for OTP verification"},{status:400}):Response.json({error:"Provide wallet signature or OTP code"},{status:400});if(!x?.jwt)return Response.json({error:"Authentication failed \u2014 no session returned"},{status:401});let k=JSON.parse(Buffer.from(x.jwt.split(".")[1],"base64url").toString()),A=Math.floor(Date.now()/1e3),H={...k,exp:A+n,iat:A},v=P(H,e.authSecret),b={userId:k.sub||k.user_id||k.session_id||k.global_id||"",address:x.address||k.address,chain:x.chain||c,expiresAt:Date.now()+a*1e3,authMethod:c?`web3:${c}`:"otp"},$=new Headers({"Content-Type":"application/json"}),O=e.secureCookies!==false?"; Secure":"",L=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";$.append("Set-Cookie",`stackauth_jwt=${v}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${a}${O}${L}`);let X=Buffer.from(JSON.stringify(b)).toString("base64url");return $.append("Set-Cookie",`stackauth_session=${X}; Path=/; SameSite=Lax; Max-Age=${a}${O}${L}`),o.generateToken($),new Response(JSON.stringify({user:b}),{status:200,headers:$})}}function K(e,r){if(!r)return null;try{let t=E(e);if(!t||t.exp&&t.exp<Math.floor(Date.now()/1e3))return null;let o=Buffer.from(JSON.stringify({alg:"HS256",typ:"JWT"})).toString("base64url"),n=Buffer.from(JSON.stringify(t)).toString("base64url"),a=createHmac("sha256",r).update(`${o}.${n}`).digest("base64url");return `${o}.${n}.${a}`}catch{return null}}var le=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;function Z(e){return typeof e!="string"||e.length===0||e.length>8192?null:le.test(e)?e:null}function U(e,r){let t=K(e,r),o=t&&Z(t);if(o)return {Cookie:`stackauth_jwt=${o}`};let n=Z(e);return n?{Cookie:`stackauth_jwt=${n}`}:{}}function M(e){let r=e.headers.get("cookie");if(r){let o=r.split(";").map(n=>n.trim()).find(n=>n.startsWith("stackauth_jwt="));if(o)return o.slice(14)}let t=e.headers.get("authorization");return t?.startsWith("Bearer ")?t.slice(7):null}function pe(e){return !e.authSecret&&typeof console<"u"&&console.warn("[userutils] createLogoutHandler called without authSecret \u2014 upstream session revocation is disabled. Pass authSecret to enable it safely."),async function(t){let o=M(t);if(o&&e.authSecret){let m=_(o,e.authSecret),f=m?.session_id||m?.sub;if(f&&typeof f=="string")try{await fetch(`${e.stacknetUrl}/api/v2/sessions/${encodeURIComponent(f)}`,{method:"DELETE",signal:AbortSignal.timeout(5e3)});}catch{}}let n=e.secureCookies!==false?"; Secure":"",a=e.cookieDomain?`; Domain=${e.cookieDomain}`:"",i=new Headers({"Content-Type":"application/json"});return i.append("Set-Cookie",`stackauth_jwt=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${n}${a}`),i.append("Set-Cookie",`stackauth_session=; Path=/; SameSite=Lax; Max-Age=0${n}${a}`),i.append("Set-Cookie",`__csrf=; Path=/; SameSite=Lax; Max-Age=0${n}${a}`),new Response(JSON.stringify({success:true}),{status:200,headers:i})}}function de(e){let r=e.jwtExpiry||900,t=e.sessionMaxAge||604800;return async function(n){let a=M(n);if(!a)return Response.json({session:null},{status:200});let i=_(a,e.authSecret);if(!i)return Response.json({session:null},{status:200});let f={userId:i.sub||i.user_id||i.session_id||i.global_id||"",address:i.address,chain:i.chain,expiresAt:i.session_expires_at||(i.exp?i.exp*1e3:Date.now()+t*1e3),planId:i.plan_id,authMethod:i.auth_method},p=new Headers({"Content-Type":"application/json"}),l=D(a,e.authSecret,r,300);if(l){let s=e.secureCookies!==false?"; Secure":"",c=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";p.append("Set-Cookie",`stackauth_jwt=${l}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${t}${s}${c}`);}return new Response(JSON.stringify({session:f}),{status:200,headers:p})}}function ge(e,r){if(e.length!==r.length)return false;try{return timingSafeEqual(Buffer.from(e),Buffer.from(r))}catch{return false}}function he(e){let r=e.rateLimiter||T({maxRequests:5,windowMs:3e5}),t=j({secure:e.secureCookies!==false}),o=e.jwtExpiry||900,n=e.sessionMaxAge||604800;return async function(i){let m=I(i),f=await r.check(`otp:${m}`);if(!f.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(f.retryAfter||300)}});let p;try{p=await i.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{code:l}=p;if(!l||typeof l!="string"||l.length!==6)return Response.json({error:"Invalid code format"},{status:400});if(!ge(l,e.otpSecret))return Response.json({error:"Invalid code"},{status:401});let s=Math.floor(Date.now()/1e3),d={sub:`otp:${createHash("sha256").update(`otp:${l}:${Date.now()}`).digest("hex").slice(0,32)}`,auth_method:"otp",iat:s,exp:s+o},u=P(d,e.authSecret),g={userId:d.sub,expiresAt:Date.now()+n*1e3,authMethod:"otp"},y=new Headers({"Content-Type":"application/json"}),w=e.secureCookies!==false?"; Secure":"",h=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";y.append("Set-Cookie",`stackauth_jwt=${u}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${n}${w}${h}`);let S=Buffer.from(JSON.stringify(g)).toString("base64url");return y.append("Set-Cookie",`stackauth_session=${S}; Path=/; SameSite=Lax; Max-Age=${n}${w}${h}`),t.generateToken(y),new Response(JSON.stringify({success:true,data:{user:g}}),{status:200,headers:y})}}function ye(e,r){let t=r?.rateLimiter||T({maxRequests:10,windowMs:6e4}),o=j({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,a=e.sessionMaxAge||604800;async function i(f){let p=new URL(f.url),l=p.searchParams.get("provider"),s=p.searchParams.get("redirectUri")||p.searchParams.get("redirect_uri"),c=p.searchParams.get("stackId")||e.stackId;if(!l)return Response.json({error:"Missing provider parameter"},{status:400});if(!s)return Response.json({error:"Missing redirectUri parameter"},{status:400});if(!/^[a-z][a-z0-9_-]{0,32}$/.test(l))return Response.json({error:"Invalid provider name"},{status:400});if(!c||!/^[a-zA-Z0-9_-]{1,64}$/.test(c))return Response.json({error:"Invalid stackId"},{status:400});try{let d=await fetch(`${e.stacknetUrl}/api/v2/stacks/${encodeURIComponent(c)}/auth/oauth/${encodeURIComponent(l)}/initiate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirectUrl:s}),signal:AbortSignal.timeout(1e4)});if(!d.ok){let y=await d.json().catch(()=>({}));return Response.json({error:y.error?.message||`Failed to start OAuth flow: ${d.statusText}`},{status:d.status})}let u=await d.json(),g=u.data||u;return Response.json({redirect_url:g.url,state:g.state})}catch(d){return Response.json({error:d.message||"Failed to start OAuth flow"},{status:500})}}async function m(f){let p=I(f),l=await t.check(`oauth:${p}`);if(!l.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(l.retryAfter||60)}});let s;try{s=await f.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{provider:c,code:d,state:u,stackId:g}=s,y=g||e.stackId;if(!c||!d||!u)return Response.json({error:"Missing provider, code, or state"},{status:400});if(!/^[a-z][a-z0-9_-]{0,32}$/.test(c))return Response.json({error:"Invalid provider name"},{status:400});if(!y||!/^[a-zA-Z0-9_-]{1,64}$/.test(y))return Response.json({error:"Invalid stackId"},{status:400});try{let w=await fetch(`${e.stacknetUrl}/api/v2/stacks/${encodeURIComponent(y)}/auth/oauth/${encodeURIComponent(c)}/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:d,state:u}),signal:AbortSignal.timeout(1e4)});if(!w.ok){let O=await w.json().catch(()=>({}));return Response.json({error:O.error?.message||`OAuth verification failed: ${w.statusText}`},{status:401})}let h=await w.json(),S=h.data?.session||h.session||h.data||h;if(!S?.jwt)return Response.json({error:"OAuth authentication failed \u2014 no session returned"},{status:401});let R=JSON.parse(Buffer.from(S.jwt.split(".")[1],"base64url").toString()),x=Math.floor(Date.now()/1e3),k=P({...R,exp:x+n,iat:x},e.authSecret),H={userId:R.sub||R.user_id||R.session_id||R.global_id||"",address:S.address||R.address,chain:void 0,expiresAt:Date.now()+a*1e3,authMethod:`oauth:${c}`},v=new Headers({"Content-Type":"application/json"}),C=e.secureCookies!==!1?"; Secure":"",b=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";v.append("Set-Cookie",`stackauth_jwt=${k}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${a}${C}${b}`);let $=Buffer.from(JSON.stringify(H)).toString("base64url");return v.append("Set-Cookie",`stackauth_session=${$}; Path=/; SameSite=Lax; Max-Age=${a}${C}${b}`),o.generateToken(v),new Response(JSON.stringify({user:H}),{status:200,headers:v})}catch(w){return Response.json({error:w.message||"OAuth callback failed"},{status:500})}}return {startFlow:i,handleCallback:m}}function Se(e,r){let t=r?.rateLimiter||T({maxRequests:10,windowMs:6e4}),o=j({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,a=e.sessionMaxAge||604800;return async function(m){let f=I(m),p=await t.check(`google-onetap:${f}`);if(!p.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(p.retryAfter||60)}});let l;try{l=await m.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{credential:s,stackId:c}=l,d=c||e.stackId;if(!s)return Response.json({error:"Missing credential"},{status:400});if(s.split(".").length!==3)return Response.json({error:"Invalid credential format"},{status:400});let u;try{let S=await fetch(`https://oauth2.googleapis.com/tokeninfo?id_token=${encodeURIComponent(s)}`,{signal:AbortSignal.timeout(1e4)});if(!S.ok)return Response.json({error:"Google credential verification failed"},{status:401});u=await S.json();}catch{return Response.json({error:"Failed to verify Google credential"},{status:500})}if(!u.sub||!u.email)return Response.json({error:"Invalid Google token \u2014 missing user info"},{status:401});if(u.iss!=="https://accounts.google.com"&&u.iss!=="accounts.google.com")return Response.json({error:"Invalid Google token issuer"},{status:401});let g=typeof u.exp=="string"?parseInt(u.exp,10):Number(u.exp);if(!Number.isFinite(g)||g<Math.floor(Date.now()/1e3))return Response.json({error:"Google token expired"},{status:401});let y=e.googleClientIds||(e.googleClientId?[e.googleClientId]:[]);if(y.length===0)return Response.json({error:"Google One Tap not configured \u2014 set ServerConfig.googleClientId(s)"},{status:500});if(!u.aud||!y.includes(u.aud))return Response.json({error:"Invalid Google token audience"},{status:401});if(!(u.email_verified===true||u.email_verified==="true"))return Response.json({error:"Google email is not verified"},{status:401});let h={sub:u.sub,email:u.email,name:u.name,picture:u.picture};try{let S=await fetch(`${e.stacknetUrl}/api/v2/stacks/${encodeURIComponent(d)}/auth/oauth/google/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({credential:s,google_id:h.sub,email:h.email,name:h.name,picture:h.picture,one_tap:!0}),signal:AbortSignal.timeout(1e4)});if(!S.ok){let k=Math.floor(Date.now()/1e3),A=h.sub,H=P({sub:A,global_id:`google:${A}`,stack_id:d,chain:"google",email:h.email,credentials:["oauth:google"],iat:k,exp:k+n,iss:"stackauth.network",signed_by:["local"]},e.authSecret),v={userId:A,address:h.email,chain:void 0,expiresAt:Date.now()+a*1e3,authMethod:"oauth:google"},C=new Headers({"Content-Type":"application/json"}),b=e.secureCookies!==!1?"; Secure":"",$=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";C.append("Set-Cookie",`stackauth_jwt=${H}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${a}${b}${$}`);let O=Buffer.from(JSON.stringify(v)).toString("base64url");return C.append("Set-Cookie",`stackauth_session=${O}; Path=/; SameSite=Lax; Max-Age=${a}${b}${$}`),o.generateToken(C),new Response(JSON.stringify({user:v}),{status:200,headers:C})}let R=await S.json(),x=R.data?.session||R.session||R.data||R;if(x?.jwt){let k=JSON.parse(Buffer.from(x.jwt.split(".")[1],"base64url").toString()),A=Math.floor(Date.now()/1e3),H=P({...k,exp:A+n,iat:A},e.authSecret),C={userId:k.sub||k.user_id||h.sub,address:h.email||x.address,chain:void 0,expiresAt:Date.now()+a*1e3,authMethod:"oauth:google"},b=new Headers({"Content-Type":"application/json"}),$=e.secureCookies!==!1?"; Secure":"",O=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";b.append("Set-Cookie",`stackauth_jwt=${H}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${a}${$}${O}`);let L=Buffer.from(JSON.stringify(C)).toString("base64url");return b.append("Set-Cookie",`stackauth_session=${L}; Path=/; SameSite=Lax; Max-Age=${a}${$}${O}`),o.generateToken(b),new Response(JSON.stringify({user:C}),{status:200,headers:b})}return Response.json({error:"No session returned"},{status:401})}catch(S){return Response.json({error:S.message||"Google One Tap authentication failed"},{status:500})}}}function ke(e){let r=j({secure:e.secureCookies!==false}),t=e.rateLimiter||T({maxRequests:20,windowMs:6e4}),o=e.stacknetJwtSecret||e.authSecret,n=e.jwtExpiry||900,a=e.sessionMaxAge||604800;function i(s){let c=M(s);if(!c)return null;let d=_(c,e.authSecret);return d?{jwt:c,payload:d}:null}function m(s,c){let d=D(s,e.authSecret,n,300);if(d){let u=e.secureCookies!==false?"; Secure":"",g=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";c.append("Set-Cookie",`stackauth_jwt=${d}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${a}${u}${g}`);}}async function f(s,c){let d=i(s);if(!d)return Response.json({error:"Unauthorized"},{status:401});let u=U(d.jwt,o),g=await fetch(`${e.stacknetUrl}${c}`,{headers:u,signal:AbortSignal.timeout(15e3)}),y=await g.json().catch(()=>({})),w=new Headers({"Content-Type":"application/json"});return m(d.jwt,w),new Response(JSON.stringify(y),{status:g.status,headers:w})}async function p(s,c,d){let u=i(s);if(!u)return Response.json({error:"Unauthorized"},{status:401});let g=r.validateRequest(s);if(!g.valid)return Response.json({error:g.error||"CSRF validation failed"},{status:403});let y=u.payload.sub||u.payload.user_id||"unknown";if(!(await t.check(`billing:${y}`)).allowed)return Response.json({error:"Too many requests"},{status:429});let h=await s.json().catch(()=>({})),S=U(u.jwt,o);S["Content-Type"]="application/json";let R=await fetch(`${e.stacknetUrl}${c}`,{method:"POST",headers:S,body:JSON.stringify({...h,...d}),signal:AbortSignal.timeout(15e3)}),x=await R.json().catch(()=>({})),k=new Headers({"Content-Type":"application/json"});return m(u.jwt,k),new Response(JSON.stringify(x),{status:R.status,headers:k})}let l=`/api/v2/stacks/${encodeURIComponent(e.stackId)}`;return {plans:{GET:async s=>{let c=await fetch(`${e.stacknetUrl}${l}/plans`,{signal:AbortSignal.timeout(1e4)}),d=await c.json().catch(()=>({}));return Response.json(d,{status:c.status})}},subscription:{GET:(s=>f(s,`${l}/subscription`))},subscribe:{POST:(s=>{let c=new URL(s.url).origin;return p(s,`${l}/subscribe`,{successUrl:`${c}/billing/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${c}/pricing`})})},cancel:{POST:(s=>p(s,`${l}/cancel-subscription`))},usage:{GET:(s=>f(s,"/v1/account/usage"))},history:{GET:(s=>f(s,`${l}/billing`))},prepaid:{POST:(s=>{let c=new URL(s.url).origin;return p(s,`${l}/prepaid`,{successUrl:`${c}/pricing/prepaid/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${c}/pricing/prepaid`})})},verifyPrepaid:{POST:(s=>p(s,`${l}/verify-prepaid`))},verifySession:{POST:(s=>p(s,`${l}/verify-session`))},subscribeSol:{POST:(s=>p(s,`${l}/subscribe-sol`))},prepaidSol:{POST:(s=>{new URL(s.url).origin;return p(s,`${l}/prepaid-sol`)})},topup:{POST:(s=>p(s,"/v1/account/topup"))}}}function we(e){return async function(t){let o=t.headers.get("stripe-signature");if(!o)return Response.json({error:"Missing Stripe signature"},{status:400});try{let n=await t.text(),a=await fetch(`${e.stacknetUrl}/api/v2/stacks/${encodeURIComponent(e.stackId)}/webhook/stripe`,{method:"POST",headers:{"Content-Type":"application/json","stripe-signature":o},body:n,signal:AbortSignal.timeout(1e4)}),i=await a.json().catch(()=>({received:!0}));return Response.json(i,{status:a.status})}catch{return Response.json({error:"Webhook processing failed"},{status:502})}}}function F(){return {"Strict-Transport-Security":"max-age=63072000; includeSubDomains; preload","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","X-XSS-Protection":"0","Referrer-Policy":"strict-origin-when-cross-origin","Permissions-Policy":"camera=(), microphone=(), geolocation=()"}}function Re(e){return async r=>{let t=await e(r),o=F(),n=new Headers(t.headers);for(let[a,i]of Object.entries(o))n.set(a,i);return new Response(t.body,{status:t.status,statusText:t.statusText,headers:n})}}function xe(){return Object.entries(F()).map(([e,r])=>({key:e,value:r}))}
2
+ export{U as buildStackNetHeaders,ce as createAuthCallback,ke as createBillingProxy,j as createCSRFProtection,Se as createGoogleOneTapHandler,T as createInMemoryRateLimiter,ie as createInMemoryReplayStore,pe as createLogoutHandler,ye as createOAuthHandlers,he as createOTPHandler,de as createSessionHandler,we as createWebhookHandler,E as decodeJWTPayload,I as extractIP,M as extractJwt,B as generateToken,D as maybeRefreshJWT,xe as nextSecurityHeaders,K as resignForStackNet,F as securityHeaders,P as signJWT,_ as verifyJWT,V as verifyJWTSignature,Re as withSecurityHeaders};