@stacknet/userutils 0.5.4 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/index.d.cts +2 -2
- package/dist/adapters/index.d.ts +2 -2
- package/dist/{auth-DR2aYcor.d.cts → auth-c1d7Eji2.d.cts} +6 -0
- package/dist/{auth-DR2aYcor.d.ts → auth-c1d7Eji2.d.ts} +6 -0
- package/dist/components/index.cjs +2 -2
- package/dist/components/index.d.cts +8 -3
- package/dist/components/index.d.ts +8 -3
- package/dist/components/index.js +2 -2
- package/dist/config-CLzVWDrU.d.cts +177 -0
- package/dist/config-xNca5ufB.d.ts +177 -0
- package/dist/core/index.d.cts +3 -3
- package/dist/core/index.d.ts +3 -3
- package/dist/hooks/index.cjs +2 -2
- package/dist/hooks/index.d.cts +52 -3
- package/dist/hooks/index.d.ts +52 -3
- package/dist/hooks/index.js +2 -2
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +2 -2
- package/dist/server/index.cjs +2 -2
- package/dist/server/index.d.cts +116 -21
- package/dist/server/index.d.ts +116 -21
- package/dist/server/index.js +2 -2
- package/dist/types/index.d.cts +2 -2
- package/dist/types/index.d.ts +2 -2
- package/dist/{types-CAoB_5kk.d.cts → types-B_Vj6cr4.d.cts} +1 -1
- package/dist/{types-Dghy_8Wh.d.ts → types-Cu0do-w-.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/config-Bjh8PEhY.d.cts +0 -123
- package/dist/config-_ZjAzNkJ.d.ts +0 -123
package/dist/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 xt(...e){return twMerge(clsx(e))}function Ct(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 vt(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 ee(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 Nt(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 te(){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 $(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 ne(){let[e,t]=useState(null),[s,d]=useState(true),u=useCallback(()=>{let i=te();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 h=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}},[]),g=!!e&&e.expiresAt>Date.now();return {session:e,loading:s,isAuthenticated:g,refresh:h,readSession:u}}function we(e="__csrf",t="x-csrf-token"){let[s,d]=useState(null);useEffect(()=>{d($(e));},[e]);let u=s?{[t]:s}:{};return {token:s,headers:u}}function Se(){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,m=l==="phantom"?c?.phantom?.solana||c?.solana:c?.solflare;if(!m)return d(`${l} wallet not found`),null;let a=(await m.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}},[]),h=useCallback(async()=>{d(null);try{let c=(typeof window<"u"?window:null)?.ethereum;if(!c)return d("MetaMask not found"),null;let m=c;c.providers?.length&&(m=c.providers.find(n=>n.isMetaMask)||c);let a=(await m.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}},[]),g=useCallback(async(l,c)=>{d(null);let m=c?.chain||e.chain,o=c?.provider||e.provider,a=c?.address||e.address;try{if(m==="solana"){let n=typeof window<"u"?window:null,p=o==="solflare"?n?.solflare:n?.phantom?.solana||n?.solana;if(!p)throw new Error("Wallet not available");let r=new TextEncoder().encode(l),y=await p.signMessage(r,"utf8"),S=new Uint8Array(y.signature||y),w="";for(let T=0;T<S.byteLength;T++)w+=String.fromCharCode(S[T]);return btoa(w)}if(m==="ethereum"){let p=(typeof window<"u"?window:null)?.ethereum;if(p?.providers?.length&&(p=p.providers.find(y=>y.isMetaMask)||p),!p)throw new Error("MetaMask not available");return await p.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:h,signMessage:g,disconnect:i}}var Lt="https://stacknet.magma-rpc.com/auth/bridge",de="stacknet-auth-bridge";function Ce(e){let t=e?.bridgeUrl||Lt,s=e?.disabled||false,d=useRef(null),[u,h]=useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),g=useRef([]),i=useRef(false),l=useCallback(n=>{let p={...n,protocol:de};i.current&&d.current?.contentWindow?d.current.contentWindow.postMessage(p,new URL(t).origin):g.current.push(p);},[t]);useEffect(()=>{if(s)return;let n=r=>{if(!(!r.data||r.data.protocol!==de)){try{if(r.origin!==new URL(t).origin)return}catch{return}switch(r.data.type){case "bridge:ready":i.current=true,h(y=>({...y,ready:true}));for(let y of g.current)d.current?.contentWindow?.postMessage(y,r.origin);g.current=[],d.current?.contentWindow?.postMessage({protocol:de,type:"auth:check"},r.origin),d.current?.contentWindow?.postMessage({protocol:de,type:"auth:resolve-stack"},r.origin);break;case "auth:status":h(y=>({...y,known:r.data.known,identity:r.data.identity,identityCount:r.data.identityCount||0}));break;case "auth:resolved-stack":h(y=>({...y,resolvedStackId:r.data.stackId||null}));break;}}};window.addEventListener("message",n);let p=document.createElement("iframe");return p.src=t,p.style.display="none",p.setAttribute("aria-hidden","true"),p.setAttribute("tabindex","-1"),p.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(p),d.current=p,()=>{window.removeEventListener("message",n),p.parentNode&&p.parentNode.removeChild(p),d.current=null,i.current=false;}},[t,s]);let c=useCallback(n=>{l({type:"auth:connected",...n});},[l]),m=useCallback(n=>{l({type:"auth:disconnected",...n});},[l]),o=useCallback(()=>{l({type:"auth:clear"}),h({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:m,clearAll:o,refresh:a}}async function tt(e,t,s,d){let u=e.apiVersion||"v2",h=`${e.baseUrl}/api/${u}${s}`;try{let g=await fetch(h,{method:t,headers:{"Content-Type":"application/json"},body:d?JSON.stringify(d):void 0}),i=await g.json();return g.ok?i.success&&i.data!==void 0?{success:!0,data:i.data}:{success:!0,data:i}:{success:!1,error:i.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(g){return {success:false,error:{code:"NETWORK_ERROR",message:g instanceof Error?g.message:"Network error"}}}}function ve(e){return {getNetworkStatus:()=>tt(e,"GET","/network/status"),getWeb3Challenge:(t,s)=>tt(e,"POST",`/stacks/${encodeURIComponent(e.stackId)}/auth/web3/challenge`,{chain:t,address:s})}}function Pe(e={apiBaseUrl:""}){let{wallet:t,connectSolana:s,connectEVM:d,signMessage:u,disconnect:h}=Se(),{session:g,isAuthenticated:i,refresh:l,readSession:c}=ne(),{headers:m}=we(),o=Ce({disabled:typeof window>"u"}),[a,n]=useState(false),[p,r]=useState(null),[y,S]=useState(false),w=e.apiBaseUrl||"",T=e.stacknetUrl||"https://stacknet.magma-rpc.com",C=e.stackId||o.resolvedStackId||"",x=ve({baseUrl:T,stackId:C}),z=useCallback(async(N,P,E,R)=>{n(true),r(null);try{let I=P;if(!I){let Z=await E();if(!Z)return n(!1),!1;I=Z;}let U=await x.getWeb3Challenge(N,I);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:I});if(!_)return n(!1),!1;let G={chain:N,message:U.data.message,signature:_,stackId:C};N==="solana"&&(G.publicKey=I);let V=await fetch(`${w}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(G)});if(!V.ok){let Z=await V.json().catch(()=>({}));return r(Z.error||"Authentication failed"),n(!1),!1}return o.reportConnected({address:I,chain:N,method:R||(N==="solana"?"phantom":"metamask"),stackId:C}),c(),n(!1),!0}catch(I){return r(I.message||"Authentication failed"),n(false),false}},[w,x,u,c,o,C]),W=useCallback(async(N="phantom")=>{let P=await s(N);return P?z("solana",P,()=>s(N),N):false},[s,z]),j=useCallback(async()=>{let N=await d();return N?z("ethereum",N,d,"metamask"):false},[d,z]),b=useCallback(async N=>{n(true),r(null);try{let P=await fetch(`${w}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({code:N})});if(!P.ok){let E=await P.json().catch(()=>({}));return r(E.error||"Invalid code"),n(!1),!1}return c(),n(!1),!0}catch(P){return r(P.message||"OTP verification failed"),n(false),false}},[w,c]),L=useCallback(async(N,P)=>{n(true),r(null);try{let E=P||`${window.location.origin}/api/auth/oauth/callback`,R=new URLSearchParams({provider:N,redirectUri:E,stackId:C}),I=await fetch(`${w}/api/auth/oauth/start?${R}`,{credentials:"include"});if(!I.ok){let _=await I.json().catch(()=>({}));return r(_.error||"Failed to start OAuth flow"),n(!1),!1}let U=await I.json();if(U.redirect_url){let _;try{_=new URL(U.redirect_url);}catch{return r("Invalid OAuth redirect URL"),n(!1),!1}let G=[/(^|\.)accounts\.google\.com$/,/(^|\.)discord\.com$/,/(^|\.)github\.com$/,/(^|\.)x\.com$/,/(^|\.)twitter\.com$/,/(^|\.)apple\.com$/];return _.protocol!=="https:"||!G.some(V=>V.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,C]),A=useCallback(async(N,P,E)=>{n(true),r(null);try{if(typeof sessionStorage<"u"){let I=sessionStorage.getItem("oauth_state"),U=sessionStorage.getItem("oauth_provider");if(sessionStorage.removeItem("oauth_state"),sessionStorage.removeItem("oauth_provider"),!I||I!==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:P,state:E,stackId:C})});if(!R.ok){let I=await R.json().catch(()=>({}));return r(I.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,C,c]),D=useCallback(async()=>{t.address&&t.chain&&o.reportDisconnected({address:t.address,chain:t.chain,stackId:C});try{await fetch(`${w}/api/auth/logout`,{method:"POST",headers:m,credentials:"include"});}catch{}h(),c();},[w,m,h,c,t,o,C]);return useEffect(()=>{if(!e.autoConnect||y||i||!o.ready||!o.known||!o.identity)return;S(true);let{chain:N,method:P}=o.identity;N==="solana"&&(P==="phantom"||P==="solflare")?W(P):N==="ethereum"&&j();},[e.autoConnect,y,i,o,W,j]),{session:g,isAuthenticated:i,wallet:t,loading:a,error:p,authenticateSolana:W,authenticateEVM:j,authenticateOTP:b,authenticateOAuth:L,authenticateOAuthCallback:A,logout:D,refresh:()=>l(w),stackId:C,bridge:{ready:o.ready,known:o.known,identity:o.identity,identityCount:o.identityCount,resolvedStackId:o.resolvedStackId}}}function re(e,t="https://stacknet.magma-rpc.com"){let[s,d]=useState(null),[u,h]=useState(false),[g,i]=useState(null),l=useCallback(async m=>{h(true),i(null);try{let o=await fetch(`${t}/api/v2/stacks/${m}`);if(!o.ok)return i("Stack not found"),h(!1),null;let a=await o.json(),n=a.data?.stack||a.stack||a,p={id:n.id,name:n.name,displayName:n.displayName||n.name,description:n.description,logoUrl:n.logoUrl,webPageUrl:n.webPageUrl,allowedChains:n.allowedChains||[],features:n.features,stripeProvider:n.stripeProvider,oauthProviders:n.oauthProviders?.map(r=>({provider:r.provider,clientId:r.clientId,enabled:r.enabled!==!1}))};return d(p),h(!1),p}catch(o){return i(o.message),h(false),null}},[t]);useEffect(()=>{e&&l(e);},[e,l]);let c=s?Dt(s):[];return {config:s,loading:u,error:g,identityProviders:c,fetchConfig:l}}function Dt(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 Rt(e=""){let[t,s]=useState([]),[d,u]=useState(true),[h,g]=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){g(l.message);}finally{u(false);}},[e]);return useEffect(()=>{i();},[i]),{plans:t,loading:d,error:h,refresh:i}}function Wt(e=""){let[t,s]=useState(null),[d,u]=useState(true),[h,g]=useState(null),i=useCallback(async()=>{try{let m=await fetch(`${e}/api/billing/subscription`);if(m.ok){let o=await m.json();s(o.plan?o:null);}}catch(m){g(m.message);}finally{u(false);}},[e]);useEffect(()=>{i();},[i]);let l=useCallback(async m=>{let o=$(),n=await(await fetch(`${e}/api/billing/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",...o?{"x-csrf-token":o}:{}},body:JSON.stringify({planId:m})})).json();return n.url||n.checkoutUrl||null},[e]),c=useCallback(async()=>{let m=$();return (await fetch(`${e}/api/billing/cancel`,{method:"POST",headers:m?{"x-csrf-token":m}:{}})).ok?(await i(),true):false},[e,i]);return {subscription:t,loading:d,error:h,refresh:i,subscribe:l,cancel:c}}function Bt(e=""){let[t,s]=useState(null),[d,u]=useState(true),[h,g]=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){g(l.message);}finally{u(false);}},[e]);return useEffect(()=>{i();},[i]),{usage:t,loading:d,error:h,refresh:i}}function Gt(e=""){let[t,s]=useState(false),[d,u]=useState(null),h=useCallback(async i=>{s(true),u(null);try{let l=$(),c=await fetch(`${e}/api/billing/prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...l?{"x-csrf-token":l}:{}},body:JSON.stringify({amountCents:i})}),m=await c.json();return c.ok?m.url||null:(u(m.error||"Purchase failed"),null)}catch(l){return u(l.message),null}finally{s(false);}},[e]),g=useCallback(async i=>{s(true),u(null);try{let l=$(),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})}),m=await c.json();return c.ok?m:(u(m.error||"Verification failed"),null)}catch(l){return u(l.message),null}finally{s(false);}},[e]);return {purchase:h,verifySession:g,loading:t,error:d}}function Vt(e="",t){let[s,d]=useState([]),[u,h]=useState(true),[g,i]=useState(null),l=t?.limit||50,c=t?.offset||0,m=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{h(false);}},[e,l,c]);return useEffect(()=>{m();},[m]),{records:s,loading:u,error:g,refresh:m}}function Jt(){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 je(e,t){let[s,d]=useState(null),[u,h]=useState(true),[g,i]=useState(false),[l,c]=useState(null),m=t?.apiBaseUrl??"",o=t?.scope===void 0||t?.scope==="global"?"global":`stack:${t.scope.stackId}`,a=useCallback(r=>{let y=encodeURIComponent(r);if(o==="global")return `${m}/api/user/profile/${y}`;let S=o.slice(6);return `${m}/api/v2/stacks/${encodeURIComponent(S)}/members/${y}/profile`},[m,o]),n=useCallback(async()=>{if(!e){d(null),h(false);return}h(true),c(null);try{let r=await fetch(a(e));if(r.ok){let y=await r.json(),S=y.profile||y.data?.profile||y;d({mid:S.mid||e,username:S.username||"",avatarUrl:S.avatar_url||S.avatarUrl,bio:S.bio,paymentAddress:S.payment_address||S.paymentAddress,createdAt:S.created_at||S.createdAt,updatedAt:S.updated_at||S.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{h(false);}},[e,a]);useEffect(()=>{n();},[n]);let p=useCallback(async r=>{if(!e)return false;i(true),c(null);try{let y=Jt(),S={};r.username!==void 0&&(S.username=r.username),r.avatarUrl!==void 0&&(S.avatar_url=r.avatarUrl),r.bio!==void 0&&(S.bio=r.bio),r.paymentAddress!==void 0&&(S.payment_address=r.paymentAddress);let w=await fetch(a(e),{method:"PUT",headers:{"Content-Type":"application/json",...y?{"x-csrf-token":y}:{}},credentials:"same-origin",body:JSON.stringify(S)});if(!w.ok){let x=await w.json().catch(()=>({}));throw new Error(x.error||x.message||`Update failed: ${w.status}`)}let T=await w.json(),C=T.profile||T.data?.profile||T;return d(x=>({mid:x?.mid||e,username:r.username??x?.username??"",avatarUrl:r.avatarUrl??x?.avatarUrl,bio:r.bio??x?.bio,paymentAddress:r.paymentAddress??C.payment_address??C.paymentAddress??x?.paymentAddress,createdAt:x?.createdAt,updatedAt:C.updated_at||C.updatedAt||Date.now()})),!0}catch(y){return c(y instanceof Error?y.message:"Update failed"),false}finally{i(false);}},[e,a]);return {profile:s,loading:u,saving:g,error:l,updateProfile:p,refresh:n}}var st="google-identity-services",Zt="https://accounts.google.com/gsi/client";function Kt({stackId:e,stacknetUrl:t="https://stacknet.magma-rpc.com",apiBaseUrl:s="",autoPrompt:d=true,cancelOnTapOutside:u=true,onSuccess:h,onError:g,disabled:i=false}){let{config:l}=re(e,t),{isAuthenticated:c,loading:m,readSession:o}=ne(),[a,n]=useState(false),[p,r]=useState(null),[y,S]=useState(false),w=useRef(false),T=useRef(false),x=l?.oauthProviders?.find(b=>b.provider==="google"&&b.enabled&&b.clientId)?.clientId||null;useEffect(()=>{if(i||!x||typeof window>"u")return;if(document.getElementById(st)){S(true);return}let b=document.createElement("script");b.id=st,b.src=Zt,b.async=true,b.defer=true,b.onload=()=>S(true),b.onerror=()=>{r("Failed to load Google sign-in"),g?.("Failed to load Google Identity Services script");},document.head.appendChild(b);},[i,x,g]);let z=useCallback(async b=>{n(true),r(null);try{let L=await fetch(`${s}/api/auth/google/one-tap`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({credential:b.credential,stackId:e})});if(!L.ok){let D=(await L.json().catch(()=>({}))).error||"Google sign-in failed";r(D),g?.(D),n(!1);return}o(),n(!1),h?.();}catch(L){let A=L.message||"Google sign-in failed";r(A),g?.(A),n(false);}},[s,e,o,h,g]);useEffect(()=>{if(i){console.debug("[GoogleOneTap] Disabled");return}if(!y){console.debug("[GoogleOneTap] Script not loaded yet, clientId:",x);return}if(!x){console.debug("[GoogleOneTap] No Google clientId from stack config");return}if(m){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:",x),w.current=true,window.google.accounts.id.initialize({client_id:x,callback:z,auto_select:true,cancel_on_tap_outside:u}),d&&!T.current&&(T.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,y,x,m,c,z,d,u]),useEffect(()=>()=>{window.google?.accounts?.id&&w.current&&window.google.accounts.id.cancel();},[]);let W=useCallback(()=>{!window.google?.accounts?.id||!w.current||window.google.accounts.id.prompt();},[]),j=useCallback((b,L)=>{!b||!window.google?.accounts?.id||!w.current||window.google.accounts.id.renderButton(b,{theme:L?.theme||"filled_black",size:L?.size||"large",text:L?.text||"signin_with",width:L?.width});},[]);return {available:!!x,ready:y&&!!x,loading:a,error:p,prompt:W,renderButton:j,clientId:x}}var at=createContext(null);function en(){let e=useContext(at);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function tn({config:e,callbacks:t,children:s}){return jsx(at.Provider,{value:{config:e,callbacks:t},children:s})}function pe({length:e=6,onComplete:t,disabled:s=false,error:d,className:u="",inputClassName:h=""}){let [g,i]=useState(Array(e).fill("")),l=useCallback((o,a)=>{if(a.length>1){let p=a.replace(/\D/g,"").slice(0,e).split(""),r=[...g];p.forEach((S,w)=>{o+w<e&&(r[o+w]=S);}),i(r);let y=Math.min(o+p.length,e-1);document.getElementById(`userutils-otp-${y}`)?.focus(),r.every(S=>S!=="")&&setTimeout(()=>t(r.join("")),100);return}if(!/^\d?$/.test(a))return;let n=[...g];n[o]=a,i(n),a&&o<e-1&&document.getElementById(`userutils-otp-${o+1}`)?.focus(),a&&o===e-1&&n.every(p=>p!=="")&&setTimeout(()=>t(n.join("")),100);},[g,e,t]),c=useCallback((o,a)=>{if(a.key==="Backspace"&&!g[o]&&o>0){document.getElementById(`userutils-otp-${o-1}`)?.focus();let n=[...g];n[o-1]="",i(n);}if(a.key==="Enter"){let n=g.join("");n.length===e&&t(n);}},[g,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:g.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 ${h}`},a))}),d&&jsx("p",{className:"text-center text-sm text-red-400 mt-2",children:d})]})}pe.displayName="OTPInput";var sn="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function fe({className:e,style:t}){return jsx("img",{src:sn,alt:"Phantom",className:e,style:t})}function ge({className:e,style:t}){return jsxs("svg",{className:e,style:t,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 507.83 470.86",children:[jsx("polygon",{fill:"#e2761b",stroke:"#e2761b",strokeLinecap:"round",strokeLinejoin:"round",points:"482.09 0.5 284.32 147.38 320.9 60.72 482.09 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"25.54 0.5 221.72 148.77 186.93 60.72 25.54 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"410.93 340.97 358.26 421.67 470.96 452.67 503.36 342.76 410.93 340.97"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"4.67 342.76 36.87 452.67 149.57 421.67 96.9 340.97 4.67 342.76"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 111.8 252.13 223.7 257.1 219.73 136.85 143.21 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"364.42 204.62 286.91 135.46 284.32 257.1 396.03 252.13 364.42 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 216.75 388.87 158.71 343.55 149.57 421.67"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 358.26 421.67 348.92 343.55 290.88 388.87"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"358.26 421.67 290.88 388.87 296.25 432.8 295.65 451.28 358.26 421.67"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 212.18 451.28 211.78 432.8 216.75 388.87 149.57 421.67"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"213.17 314.54 157.12 298.04 196.67 279.95 213.17 314.54"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"294.46 314.54 310.96 279.95 350.71 298.04 294.46 314.54"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 159.11 340.97 96.9 342.76 149.57 421.67"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"348.72 340.97 358.26 421.67 410.93 342.76 348.72 340.97"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"396.03 252.13 284.32 257.1 294.66 314.54 311.16 279.95 350.91 298.04 396.03 252.13"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 196.87 279.95 213.17 314.54 223.7 257.1 111.8 252.13 157.12 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"111.8 252.13 158.71 343.55 157.12 298.04 111.8 252.13"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"350.91 298.04 348.92 343.55 396.03 252.13 350.91 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"223.7 257.1 213.17 314.54 226.29 382.31 229.27 293.07 223.7 257.1"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 278.96 292.87 281.34 382.31 294.66 314.54 284.32 257.1"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"294.66 314.54 281.34 382.31 290.88 388.87 348.92 343.55 350.91 298.04 294.66 314.54"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 158.71 343.55 216.75 388.87 226.29 382.31 213.17 314.54 157.12 298.04"}),jsx("polygon",{fill:"#c0ad9e",stroke:"#c0ad9e",strokeLinecap:"round",strokeLinejoin:"round",points:"295.65 451.28 296.25 432.8 291.28 428.42 216.35 428.42 211.78 432.8 212.18 451.28 149.57 421.67 171.43 439.55 215.75 470.36 291.88 470.36 336.4 439.55 358.26 421.67 295.65 451.28"}),jsx("polygon",{fill:"#161616",stroke:"#161616",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 281.34 382.31 226.29 382.31 216.75 388.87 211.78 432.8 216.35 428.42 291.28 428.42 296.25 432.8 290.88 388.87"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"490.44 156.92 507.33 75.83 482.09 0.5 290.88 142.41 364.42 204.62 468.37 235.03 491.43 208.2 481.49 201.05 497.39 186.54 485.07 177 500.97 164.87 490.44 156.92"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"0.5 75.83 17.39 156.92 6.66 164.87 22.56 177 10.44 186.54 26.34 201.05 16.4 208.2 39.26 235.03 143.21 204.62 216.75 142.41 25.54 0.5 0.5 75.83"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"468.37 235.03 364.42 204.62 396.03 252.13 348.92 343.55 410.93 342.76 503.36 342.76 468.37 235.03"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 39.26 235.03 4.67 342.76 96.9 342.76 158.71 343.55 111.8 252.13 143.21 204.62"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 290.88 142.41 321.1 60.72 186.93 60.72 216.75 142.41 223.7 257.1 226.09 293.27 226.29 382.31 281.34 382.31 281.74 293.27 284.32 257.1"})]})}function We({className:e,style:t}){return jsxs("svg",{className:e,style:t,viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#F1F2F9"}),jsx("path",{d:"M26.1001 16.2273C26.1001 15.5182 26.0365 14.8364 25.9183 14.1818H16.5001V18.05H21.8819C21.6501 19.3 20.9456 20.3591 19.8865 21.0682V23.5773H23.1183C25.0092 21.8364 26.1001 19.2727 26.1001 16.2273Z",fill:"#4285F4"}),jsx("path",{d:"M16.5001 26C19.2001 26 21.4637 25.1046 23.1182 23.5773L19.8864 21.0682C18.991 21.6682 17.8455 22.0227 16.5001 22.0227C13.8955 22.0227 11.691 20.2637 10.9046 17.9H7.56372V20.4909C9.20917 23.7591 12.591 26 16.5001 26Z",fill:"#34A853"}),jsx("path",{d:"M10.9047 17.8999C10.7047 17.2999 10.591 16.659 10.591 15.9999C10.591 15.3408 10.7047 14.6999 10.9047 14.0999V11.509H7.56376C6.86376 12.9025 6.49951 14.4405 6.50012 15.9999C6.50012 17.6136 6.88649 19.1408 7.56376 20.4908L10.9047 17.8999Z",fill:"#FBBC05"}),jsx("path",{d:"M16.5001 9.97726C17.9682 9.97726 19.2864 10.4818 20.3228 11.4727L23.191 8.60454C21.4591 6.99091 19.1955 6 16.5001 6C12.591 6 9.20917 8.2409 7.56372 11.5091L10.9046 14.1C11.691 11.7364 13.8955 9.97726 16.5001 9.97726Z",fill:"#EA4335"})]})}function $e({className:e,style:t}){return jsxs("svg",{className:e,style:t,viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#5462EB"}),jsx("path",{d:"M23.5433 8.87438C22.2479 8.26174 20.8587 7.81038 19.4063 7.55187C19.3799 7.54688 19.3534 7.55934 19.3398 7.58428C19.1612 7.91179 18.9633 8.33905 18.8247 8.67487C17.2625 8.43382 15.7084 8.43382 14.1782 8.67487C14.0396 8.33158 13.8345 7.91179 13.6551 7.58428C13.6414 7.56018 13.615 7.54771 13.5886 7.55187C12.1369 7.80955 10.7478 8.26092 9.45159 8.87438C9.44037 8.87937 9.43075 8.88769 9.42437 8.89849C6.78947 12.9558 6.06766 16.9134 6.42176 20.8219C6.42336 20.841 6.43378 20.8593 6.4482 20.871C8.18663 22.1868 9.87059 22.9857 11.5233 23.5152C11.5497 23.5235 11.5778 23.5135 11.5946 23.491C11.9855 22.9408 12.334 22.3606 12.6328 21.7504C12.6505 21.7147 12.6336 21.6723 12.5976 21.6581C12.0448 21.442 11.5185 21.1785 11.0122 20.8793C10.9721 20.8552 10.9689 20.7961 11.0058 20.7679C11.1123 20.6856 11.2189 20.6 11.3206 20.5135C11.339 20.4977 11.3647 20.4944 11.3863 20.5044C14.7125 22.0696 18.3136 22.0696 21.6006 20.5044C21.6222 20.4936 21.6479 20.4969 21.6671 20.5127C21.7688 20.5991 21.8754 20.6856 21.9827 20.7679C22.0196 20.7961 22.0172 20.8552 21.9771 20.8793C21.4708 21.1843 20.9445 21.442 20.3909 21.6573C20.3548 21.6715 20.3388 21.7147 20.3564 21.7504C20.6617 22.3597 21.0101 22.9399 21.3939 23.4902C21.4099 23.5135 21.4387 23.5235 21.4652 23.5152C23.1259 22.9857 24.8099 22.1868 26.5483 20.871C26.5635 20.8593 26.5731 20.8419 26.5747 20.8228C26.9985 16.3041 25.8649 12.3789 23.5697 8.89931C23.5641 8.88769 23.5545 8.87937 23.5433 8.87438Z",fill:"#F7F7F7"})]})}function Fe({className:e,style:t}){return jsxs("svg",{className:e,style:t,viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"black"}),jsx("path",{d:"M8.53901 8L14.7164 16.2153L8.5 22.8947H9.89907L15.3415 17.0468L19.7389 22.8947H24.5L17.975 14.2173L23.7612 8H22.3621L17.3499 13.3858L13.3001 8H8.53901ZM10.5964 9.02501H12.7837L22.4422 21.8695H20.255L10.5964 9.02501Z",fill:"#F7F7F7"})]})}function pn({config:e,onSuccess:t,title:s="Log in or Sign up",showWallets:d,showOTP:u,hideHeader:h,onOTPSubmit:g,otpLabel:i="Access Code",oauthInline:l,oauthFirst:c,className:m=""}){let o=Pe(e),{isAuthenticated:a,wallet:n,loading:p,error:r,authenticateSolana:y,authenticateEVM:S,authenticateOTP:w,authenticateOAuth:T,bridge:C,stackId:x}=o,z=!e.stackId&&!x,W=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:j,identityProviders:b,loading:L}=re(x||e.stackId||null,W),[A,D]=useState(z?"stack-select":"select"),[N,P]=useState(null),[E,R]=useState(false),[I,U]=useState("idle"),[_,G]=useState(""),[V,Z]=useState([]),[ft,Qe]=useState(e.stackId||null),[le,gt]=useState(false),[mt,ht]=useState(false);useEffect(()=>{if(typeof window>"u")return;let f=()=>{let Y=window;gt(!!(Y.phantom?.solana?.isPhantom||Y.solana?.isPhantom));let q=Y.ethereum;ht(!!(q?.isMetaMask||q?.providers?.some(X=>X.isMetaMask)));};f(),window.addEventListener("ethereum#initialized",f);let H=setTimeout(f,500);return ()=>{window.removeEventListener("ethereum#initialized",f),clearTimeout(H);}},[]),useEffect(()=>{A==="stack-select"&&x&&(Qe(x),D("select"));},[A,x]),useEffect(()=>{if(!(!C.ready||!z)&&C.identity){let f=[];C.resolvedStackId&&f.push({stackId:C.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(f.map(async H=>{try{let Y=await fetch(`${W}/api/v2/stacks/${H.stackId}`);if(Y.ok){let q=await Y.json(),X=q.data?.stack||q;H.name=X.displayName||X.name,H.logoUrl=X.logoUrl;}}catch{}return H})).then(Z);}},[C.ready,C.identity,C.resolvedStackId,z,W]),useEffect(()=>{a&&A==="success"&&t?.();},[a,A,t]);let Ve=d||(b.length>0?b.filter(f=>f.type==="wallet").map(f=>f.id):["phantom","metamask"]),Ye=u!==void 0?u:b.length>0?b.some(f=>f.type==="otp"):true,K=b.filter(f=>f.type==="oauth"),ke=new Set(c||[]),Je=K.filter(f=>ke.has(f.id)),be=l?K.filter(f=>!ke.has(f.id)):K,Ze=async f=>{P(f),D("connecting"),await T(f)||D("error");},yt=async()=>{P("phantom"),D("connecting");let f=await y("phantom");D(f?"success":"error");},kt=async()=>{P("metamask"),D("connecting");let f=await S();D(f?"success":"error");},bt=async f=>{U("verifying"),G(""),await(g||w)(f)?(U("success"),D("success")):(U("error"),G("Invalid or expired code"),setTimeout(()=>U("idle"),2e3));},Ke=()=>{D(z&&!ft?"stack-select":"select"),P(null),R(false),U("idle"),G("");};return jsxs("div",{className:`w-full max-w-md space-y-3 ${m}`,children:[!h&&jsxs("div",{className:"mb-6 text-center",children:[j?.logoUrl&&A!=="stack-select"&&jsx("img",{src:ee(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:V.length>0?"Select a network to continue":"No previous connections found. Enter a Stack ID to continue."}),V.map(f=>jsxs("button",{onClick:()=>{Qe(f.stackId),D("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:ee(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)),C.ready&&!C.known&&jsx("p",{className:"text-center text-xs text-zinc-600 mt-4",children:"Connect to a stack for the first time to get started."})]}),A==="select"&&L&&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"&&p&&jsxs("div",{style:{border:"1px solid #27272a",background:"#25252f",padding:24,textAlign:"center"},children:[jsxs("div",{style:{width:40,height:40,margin:"0 auto 12px"},children:[N==="phantom"&&jsx(fe,{style:B}),N==="metamask"&&jsx(ge,{style:B})]}),jsx("p",{style:{fontWeight:500,fontSize:14,color:"#fff"},children:n.connected?"Signing message...":"Connecting wallet..."}),jsx("p",{style:{marginTop:4,fontSize:12,color:"#71717a"},children:"Please confirm in your wallet"}),jsx("button",{style:{marginTop:16,fontSize:14,color:"#71717a",background:"none",border:"none",cursor:"pointer"},onClick:Ke,children:"Cancel"})]}),A==="select"&&!p&&!L&&jsxs(Fragment,{children:[Je.map(f=>jsxs("button",{onClick:()=>Ze(f.id),style:ae,children:[jsx(ct,{provider:f.id}),jsx("span",{style:{fontWeight:500,color:"#fff"},children:dt(f.id,f.name)})]},f.id)),Ve.includes("phantom")&&jsxs("button",{onClick:yt,disabled:!le,style:{...ae,opacity:le?1:.5,cursor:le?"pointer":"not-allowed"},children:[jsx(fe,{style:{...B,borderRadius:8}}),jsx("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:"Phantom"}),!le&&jsx("span",{style:{fontSize:12,color:"#71717a"},children:"Not installed"})]}),Ve.includes("metamask")&&mt&&jsxs("button",{onClick:kt,style:ae,children:[jsx(ge,{style:B}),jsx("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:"MetaMask"})]}),Ye&&!E&&jsxs("button",{onClick:()=>R(true),style:ae,children:[jsx("div",{style:{...B,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8,border:"1px solid #3f3f46",background:"#2a2a3e"},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"20px",viewBox:"0 -960 960 960",width:"20px",fill:"#a1a1aa",children:jsx("path",{d:"M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v480q0 33-23.5 56.5T800-160H160Z"})})}),jsx("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:i})]}),Ye&&E&&jsxs("div",{style:{borderRadius:12,border:"1px solid #27272a",background:"#25252f",padding:24},children:[jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginBottom:16},children:"Enter your 6-digit access code"}),jsx(pe,{onComplete:bt,disabled:I==="verifying",error:_}),I==="verifying"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginTop:16},children:"Verifying..."}),I==="success"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#4ade80",marginTop:16},children:"Verified!"}),j?.webPageUrl&&I==="idle"&&(()=>{let f=ee(j.webPageUrl);return f==="#"?null:jsx("a",{href:`${f.replace(/\/$/,"")}/connect/pair`,target:"_blank",rel:"noopener noreferrer",style:{display:"block",textAlign:"center",fontSize:14,color:"#71717a",marginTop:16},children:"Get code"})})()]}),(l?be:K).length>0&&(!l||be.length>0)&&jsxs(Fragment,{children:[!l&&Je.length===0&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 0"},children:[jsx("div",{style:{flex:1,borderTop:"1px solid #27272a"}}),jsx("span",{style:{fontSize:12,color:"#52525b"},children:"or continue with"}),jsx("div",{style:{flex:1,borderTop:"1px solid #27272a"}})]}),(l?be:K.filter(f=>!ke.has(f.id))).map(f=>jsxs("button",{onClick:()=>Ze(f.id),style:ae,children:[jsx(ct,{provider:f.id}),jsx("span",{style:{fontWeight:500,color:"#fff"},children:dt(f.id,f.name)})]},f.id))]})]})]})}var B={width:40,height:40,flexShrink:0},ae={display:"flex",width:"100%",alignItems:"center",gap:12,borderRadius:12,border:"1px solid #27272a",background:"#25252f",padding:16,cursor:"pointer",transition:"background 0.15s"};function ct({provider:e}){switch(e){case "google":return jsx(We,{style:{...B,borderRadius:8}});case "discord":return jsx($e,{style:{...B,borderRadius:8}});case "twitter":return jsx(Fe,{style:{...B,borderRadius:8}});default:return jsx("div",{style:{...B,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8,border:"1px solid #3f3f46",background:"#2a2a3e",fontSize:14,color:"#a1a1aa",fontFamily:"monospace"},children:e[0]?.toUpperCase()})}}function dt(e,t){return {google:"Google",discord:"Discord",twitter:"Twitter"}[e]||t||e}function mn({mid:e,apiBaseUrl:t="",scope:s,onSave:d,className:u}){let{profile:h,loading:g,saving:i,error:l,updateProfile:c}=je(e,{apiBaseUrl:t,scope:s}),[m,o]=useState(null),[a,n]=useState(null),[p,r]=useState(null),y=useRef(null),[S,w]=useState(false),T=m??h?.username??"",C=a??h?.bio??"",x=p??h?.avatarUrl,z=useCallback(b=>{let L=b.target.files?.[0];if(!L)return;let A=new FileReader;A.onload=()=>{r(A.result),w(true);},A.readAsDataURL(L);},[]),W=async()=>{await c({username:T||void 0,avatarUrl:p??h?.avatarUrl,bio:C||void 0})&&(w(false),d?.());};if(g)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:()=>y.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:x?jsx("img",{src:x,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: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:y,type:"file",accept:"image/*",onChange:z,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:C,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}),S&&jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[jsx("button",{onClick:W,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 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 yn({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 bn({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 Sn(e){let{apiBaseUrl:t,stacknetUrl:s="https://stacknet.magma-rpc.com",stackId:d="",transport:u,serviceKey:h,onAuthSuccess:g,onAuthError:i,onLogout:l}=e;async function c(o){if(!o.ok){let r=await o.json().catch(()=>({})),y=new Error(r.error||`Authentication failed (${o.status})`);throw i?.(y),y}let a=await o.json(),n=a.token||a.jwt,p=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,p),g?.(p),p}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:p}){let r={chain:o,message:n,signature:p,stackId:d};o==="solana"&&(r.publicKey=a);let y=await fetch(`${t}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return c(y)},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 p=await n.json();if(p.session)return p.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 p=`${s}/api/v2/stacks/${encodeURIComponent(d)}/auth/web3/challenge`,r=await fetch(p,{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 y=await r.json();return y.data||y},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:h?{Authorization:`Bearer ${h}`}:{}},async getToken(){return u.getToken()}}}function xn(){return {async storeCredentials(e,t){},async getToken(){return null},async getHeaders(){return {}},async getStoredSession(){let e=te();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 Cn(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{
|
|
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 It(...e){return twMerge(clsx(e))}function Nt(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 At(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 ee(e,t="#"){if(!e||typeof e!="string")return t;let r=e.trim();if(r===""||r==="#")return t;if(r.startsWith("/")||r.startsWith("./")||r.startsWith("../"))return r;try{let d=new URL(r);if(d.protocol==="http:"||d.protocol==="https:")return d.toString()}catch{}return t}function Mt(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 te(){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 F(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 ne(){let[e,t]=useState(null),[r,d]=useState(true),u=useCallback(()=>{let i=te();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 h=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}},[]),g=!!e&&e.expiresAt>Date.now();return {session:e,loading:r,isAuthenticated:g,refresh:h,readSession:u}}function we(e="__csrf",t="x-csrf-token"){let[r,d]=useState(null);useEffect(()=>{d(F(e));},[e]);let u=r?{[t]:r}:{};return {token:r,headers:u}}function Ce(){let[e,t]=useState({connected:false,address:null,chain:null,provider:null}),[r,d]=useState(null),u=useCallback(async(l="phantom")=>{d(null);try{let c=typeof window<"u"?window:null,m=l==="phantom"?c?.phantom?.solana||c?.solana:c?.solflare;if(!m)return d(`${l} wallet not found`),null;let a=(await m.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}},[]),h=useCallback(async()=>{d(null);try{let c=(typeof window<"u"?window:null)?.ethereum;if(!c)return d("MetaMask not found"),null;let m=c;c.providers?.length&&(m=c.providers.find(n=>n.isMetaMask)||c);let a=(await m.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}},[]),g=useCallback(async(l,c)=>{d(null);let m=c?.chain||e.chain,o=c?.provider||e.provider,a=c?.address||e.address;try{if(m==="solana"){let n=typeof window<"u"?window:null,p=o==="solflare"?n?.solflare:n?.phantom?.solana||n?.solana;if(!p)throw new Error("Wallet not available");let s=new TextEncoder().encode(l),y=await p.signMessage(s,"utf8"),C=new Uint8Array(y.signature||y),w="";for(let T=0;T<C.byteLength;T++)w+=String.fromCharCode(C[T]);return btoa(w)}if(m==="ethereum"){let p=(typeof window<"u"?window:null)?.ethereum;if(p?.providers?.length&&(p=p.providers.find(y=>y.isMetaMask)||p),!p)throw new Error("MetaMask not available");return await p.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:r,connectSolana:u,connectEVM:h,signMessage:g,disconnect:i}}var Dt="https://stacknet.magma-rpc.com/auth/bridge",de="stacknet-auth-bridge";function xe(e){let t=e?.bridgeUrl||Dt,r=e?.disabled||false,d=useRef(null),[u,h]=useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),g=useRef([]),i=useRef(false),l=useCallback(n=>{let p={...n,protocol:de};i.current&&d.current?.contentWindow?d.current.contentWindow.postMessage(p,new URL(t).origin):g.current.push(p);},[t]);useEffect(()=>{if(r)return;let n=s=>{if(!(!s.data||s.data.protocol!==de)){try{if(s.origin!==new URL(t).origin)return}catch{return}switch(s.data.type){case "bridge:ready":i.current=true,h(y=>({...y,ready:true}));for(let y of g.current)d.current?.contentWindow?.postMessage(y,s.origin);g.current=[],d.current?.contentWindow?.postMessage({protocol:de,type:"auth:check"},s.origin),d.current?.contentWindow?.postMessage({protocol:de,type:"auth:resolve-stack"},s.origin);break;case "auth:status":h(y=>({...y,known:s.data.known,identity:s.data.identity,identityCount:s.data.identityCount||0}));break;case "auth:resolved-stack":h(y=>({...y,resolvedStackId:s.data.stackId||null}));break;}}};window.addEventListener("message",n);let p=document.createElement("iframe");return p.src=t,p.style.display="none",p.setAttribute("aria-hidden","true"),p.setAttribute("tabindex","-1"),p.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(p),d.current=p,()=>{window.removeEventListener("message",n),p.parentNode&&p.parentNode.removeChild(p),d.current=null,i.current=false;}},[t,r]);let c=useCallback(n=>{l({type:"auth:connected",...n});},[l]),m=useCallback(n=>{l({type:"auth:disconnected",...n});},[l]),o=useCallback(()=>{l({type:"auth:clear"}),h({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:m,clearAll:o,refresh:a}}async function ot(e,t,r,d){let u=e.apiVersion||"v2",h=`${e.baseUrl}/api/${u}${r}`;try{let g=await fetch(h,{method:t,headers:{"Content-Type":"application/json"},body:d?JSON.stringify(d):void 0}),i=await g.json();return g.ok?i.success&&i.data!==void 0?{success:!0,data:i.data}:{success:!0,data:i}:{success:!1,error:i.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(g){return {success:false,error:{code:"NETWORK_ERROR",message:g instanceof Error?g.message:"Network error"}}}}function ve(e){return {getNetworkStatus:()=>ot(e,"GET","/network/status"),getWeb3Challenge:(t,r)=>ot(e,"POST",`/stacks/${encodeURIComponent(e.stackId)}/auth/web3/challenge`,{chain:t,address:r})}}function Ie(e={apiBaseUrl:""}){let{wallet:t,connectSolana:r,connectEVM:d,signMessage:u,disconnect:h}=Ce(),{session:g,isAuthenticated:i,refresh:l,readSession:c}=ne(),{headers:m}=we(),o=xe({disabled:typeof window>"u"}),[a,n]=useState(false),[p,s]=useState(null),[y,C]=useState(false),w=e.apiBaseUrl||"",T=e.stacknetUrl||"https://stacknet.magma-rpc.com",x=e.stackId||o.resolvedStackId||"",S=ve({baseUrl:T,stackId:x}),z=useCallback(async(P,I,E,R)=>{n(true),s(null);try{let N=I;if(!N){let Z=await E();if(!Z)return n(!1),!1;N=Z;}let L=await S.getWeb3Challenge(P,N);if(!L.success||!L.data)return s("Failed to get challenge"),n(!1),!1;let _=await u(L.data.message,{chain:P,provider:R,address:N});if(!_)return n(!1),!1;let G={chain:P,message:L.data.message,signature:_,stackId:x};P==="solana"&&(G.publicKey=N);let Q=await fetch(`${w}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(G)});if(!Q.ok){let Z=await Q.json().catch(()=>({}));return s(Z.error||"Authentication failed"),n(!1),!1}return o.reportConnected({address:N,chain:P,method:R||(P==="solana"?"phantom":"metamask"),stackId:x}),c(),n(!1),!0}catch(N){return s(N.message||"Authentication failed"),n(false),false}},[w,S,u,c,o,x]),$=useCallback(async(P="phantom")=>{let I=await r(P);return I?z("solana",I,()=>r(P),P):false},[r,z]),j=useCallback(async()=>{let P=await d();return P?z("ethereum",P,d,"metamask"):false},[d,z]),b=useCallback(async P=>{n(true),s(null);try{let I=await fetch(`${w}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({code:P})});if(!I.ok){let E=await I.json().catch(()=>({}));return s(E.error||"Invalid code"),n(!1),!1}return c(),n(!1),!0}catch(I){return s(I.message||"OTP verification failed"),n(false),false}},[w,c]),U=useCallback(async(P,I)=>{n(true),s(null);try{let E=I||`${window.location.origin}/api/auth/oauth/callback`,R=new URLSearchParams({provider:P,redirectUri:E,stackId:x}),N=await fetch(`${w}/api/auth/oauth/start?${R}`,{credentials:"include"});if(!N.ok){let _=await N.json().catch(()=>({}));return s(_.error||"Failed to start OAuth flow"),n(!1),!1}let L=await N.json();if(L.redirect_url){let _;try{_=new URL(L.redirect_url);}catch{return s("Invalid OAuth redirect URL"),n(!1),!1}let G=[/(^|\.)accounts\.google\.com$/,/(^|\.)discord\.com$/,/(^|\.)github\.com$/,/(^|\.)x\.com$/,/(^|\.)twitter\.com$/,/(^|\.)apple\.com$/];return _.protocol!=="https:"||!G.some(Q=>Q.test(_.hostname))?(s(`Refusing to redirect to non-OAuth host: ${_.hostname}`),n(!1),!1):(typeof sessionStorage<"u"&&(sessionStorage.setItem("oauth_state",L.state||""),sessionStorage.setItem("oauth_provider",P)),window.location.href=_.toString(),!0)}return s("No redirect URL returned"),n(!1),!1}catch(E){return s(E.message||"OAuth flow failed"),n(false),false}},[w,x]),A=useCallback(async(P,I,E)=>{n(true),s(null);try{if(typeof sessionStorage<"u"){let N=sessionStorage.getItem("oauth_state"),L=sessionStorage.getItem("oauth_provider");if(sessionStorage.removeItem("oauth_state"),sessionStorage.removeItem("oauth_provider"),!N||N!==E)return s("OAuth state mismatch \u2014 refusing to complete login"),n(!1),!1;if(L&&L!==P)return s("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:P,code:I,state:E,stackId:x})});if(!R.ok){let N=await R.json().catch(()=>({}));return s(N.error||"OAuth authentication failed"),n(!1),!1}return c(),n(!1),!0}catch(R){return s(R.message||"OAuth callback failed"),n(false),false}},[w,x,c]),D=useCallback(async()=>{t.address&&t.chain&&o.reportDisconnected({address:t.address,chain:t.chain,stackId:x});try{await fetch(`${w}/api/auth/logout`,{method:"POST",headers:m,credentials:"include"});}catch{}h(),c();},[w,m,h,c,t,o,x]);return useEffect(()=>{if(!e.autoConnect||y||i||!o.ready||!o.known||!o.identity)return;C(true);let{chain:P,method:I}=o.identity;P==="solana"&&(I==="phantom"||I==="solflare")?$(I):P==="ethereum"&&j();},[e.autoConnect,y,i,o,$,j]),{session:g,isAuthenticated:i,wallet:t,loading:a,error:p,authenticateSolana:$,authenticateEVM:j,authenticateOTP:b,authenticateOAuth:U,authenticateOAuthCallback:A,logout:D,refresh:()=>l(w),stackId:x,bridge:{ready:o.ready,known:o.known,identity:o.identity,identityCount:o.identityCount,resolvedStackId:o.resolvedStackId}}}function re(e,t="https://stacknet.magma-rpc.com"){let[r,d]=useState(null),[u,h]=useState(false),[g,i]=useState(null),l=useCallback(async m=>{h(true),i(null);try{let o=await fetch(`${t}/api/v2/stacks/${m}`);if(!o.ok)return i("Stack not found"),h(!1),null;let a=await o.json(),n=a.data?.stack||a.stack||a,p={id:n.id,name:n.name,displayName:n.displayName||n.name,description:n.description,logoUrl:n.logoUrl,webPageUrl:n.webPageUrl,allowedChains:n.allowedChains||[],features:n.features,stripeProvider:n.stripeProvider,oauthProviders:n.oauthProviders?.map(s=>({provider:s.provider,clientId:s.clientId,enabled:s.enabled!==!1}))};return d(p),h(!1),p}catch(o){return i(o.message),h(false),null}},[t]);useEffect(()=>{e&&l(e);},[e,l]);let c=r?_t(r):[];return {config:r,loading:u,error:g,identityProviders:c,fetchConfig:l}}function _t(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 Ft(e=""){let[t,r]=useState([]),[d,u]=useState(true),[h,g]=useState(null),i=useCallback(async()=>{try{let l=await fetch(`${e}/api/billing/plans`);if(l.ok){let c=await l.json();r(c.plans||c||[]);}}catch(l){g(l.message);}finally{u(false);}},[e]);return useEffect(()=>{i();},[i]),{plans:t,loading:d,error:h,refresh:i}}function Gt(e=""){let[t,r]=useState(null),[d,u]=useState(true),[h,g]=useState(null),i=useCallback(async()=>{try{let m=await fetch(`${e}/api/billing/subscription`);if(m.ok){let o=await m.json();r(o.plan?o:null);}}catch(m){g(m.message);}finally{u(false);}},[e]);useEffect(()=>{i();},[i]);let l=useCallback(async m=>{let o=F(),n=await(await fetch(`${e}/api/billing/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",...o?{"x-csrf-token":o}:{}},body:JSON.stringify({planId:m})})).json();return n.url||n.checkoutUrl||null},[e]),c=useCallback(async()=>{let m=F();return (await fetch(`${e}/api/billing/cancel`,{method:"POST",headers:m?{"x-csrf-token":m}:{}})).ok?(await i(),true):false},[e,i]);return {subscription:t,loading:d,error:h,refresh:i,subscribe:l,cancel:c}}function Qt(e=""){let[t,r]=useState(null),[d,u]=useState(true),[h,g]=useState(null),i=useCallback(async()=>{try{let l=await fetch(`${e}/api/billing/usage`);if(l.ok){let c=await l.json();r(c);}}catch(l){g(l.message);}finally{u(false);}},[e]);return useEffect(()=>{i();},[i]),{usage:t,loading:d,error:h,refresh:i}}function Vt(e=""){let[t,r]=useState(false),[d,u]=useState(null),h=useCallback(async i=>{r(true),u(null);try{let l=F(),c=await fetch(`${e}/api/billing/prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...l?{"x-csrf-token":l}:{}},body:JSON.stringify({amountCents:i})}),m=await c.json();return c.ok?m.url||null:(u(m.error||"Purchase failed"),null)}catch(l){return u(l.message),null}finally{r(false);}},[e]),g=useCallback(async i=>{r(true),u(null);try{let l=F(),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})}),m=await c.json();return c.ok?m:(u(m.error||"Verification failed"),null)}catch(l){return u(l.message),null}finally{r(false);}},[e]);return {purchase:h,verifySession:g,loading:t,error:d}}function Kt(e="",t){let[r,d]=useState([]),[u,h]=useState(true),[g,i]=useState(null),l=t?.limit||50,c=t?.offset||0,m=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{h(false);}},[e,l,c]);return useEffect(()=>{m();},[m]),{records:r,loading:u,error:g,refresh:m}}function Xt(){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 je(e,t){let[r,d]=useState(null),[u,h]=useState(true),[g,i]=useState(false),[l,c]=useState(null),m=t?.apiBaseUrl??"",o=t?.scope===void 0||t?.scope==="global"?"global":`stack:${t.scope.stackId}`,a=useCallback(s=>{let y=encodeURIComponent(s);if(o==="global")return `${m}/api/user/profile/${y}`;let C=o.slice(6);return `${m}/api/v2/stacks/${encodeURIComponent(C)}/members/${y}/profile`},[m,o]),n=useCallback(async()=>{if(!e){d(null),h(false);return}h(true),c(null);try{let s=await fetch(a(e));if(s.ok){let y=await s.json(),C=y.profile||y.data?.profile||y;d({mid:C.mid||e,username:C.username||"",avatarUrl:C.avatar_url||C.avatarUrl,bio:C.bio,paymentAddress:C.payment_address||C.paymentAddress,createdAt:C.created_at||C.createdAt,updatedAt:C.updated_at||C.updatedAt});}else if(s.status===404)d({mid:e,username:""});else throw new Error(`${s.status}`)}catch(s){c(s instanceof Error?s.message:"Failed to load profile");}finally{h(false);}},[e,a]);useEffect(()=>{n();},[n]);let p=useCallback(async s=>{if(!e)return false;i(true),c(null);try{let y=Xt(),C={};s.username!==void 0&&(C.username=s.username),s.avatarUrl!==void 0&&(C.avatar_url=s.avatarUrl),s.bio!==void 0&&(C.bio=s.bio),s.paymentAddress!==void 0&&(C.payment_address=s.paymentAddress);let w=await fetch(a(e),{method:"PUT",headers:{"Content-Type":"application/json",...y?{"x-csrf-token":y}:{}},credentials:"same-origin",body:JSON.stringify(C)});if(!w.ok){let S=await w.json().catch(()=>({}));throw new Error(S.error||S.message||`Update failed: ${w.status}`)}let T=await w.json(),x=T.profile||T.data?.profile||T;return d(S=>({mid:S?.mid||e,username:s.username??S?.username??"",avatarUrl:s.avatarUrl??S?.avatarUrl,bio:s.bio??S?.bio,paymentAddress:s.paymentAddress??x.payment_address??x.paymentAddress??S?.paymentAddress,createdAt:S?.createdAt,updatedAt:x.updated_at||x.updatedAt||Date.now()})),!0}catch(y){return c(y instanceof Error?y.message:"Update failed"),false}finally{i(false);}},[e,a]);return {profile:r,loading:u,saving:g,error:l,updateProfile:p,refresh:n}}var it="google-identity-services",en="https://accounts.google.com/gsi/client";function tn({stackId:e,stacknetUrl:t="https://stacknet.magma-rpc.com",apiBaseUrl:r="",autoPrompt:d=true,cancelOnTapOutside:u=true,onSuccess:h,onError:g,disabled:i=false}){let{config:l}=re(e,t),{isAuthenticated:c,loading:m,readSession:o}=ne(),[a,n]=useState(false),[p,s]=useState(null),[y,C]=useState(false),w=useRef(false),T=useRef(false),S=l?.oauthProviders?.find(b=>b.provider==="google"&&b.enabled&&b.clientId)?.clientId||null;useEffect(()=>{if(i||!S||typeof window>"u")return;if(document.getElementById(it)){C(true);return}let b=document.createElement("script");b.id=it,b.src=en,b.async=true,b.defer=true,b.onload=()=>C(true),b.onerror=()=>{s("Failed to load Google sign-in"),g?.("Failed to load Google Identity Services script");},document.head.appendChild(b);},[i,S,g]);let z=useCallback(async b=>{n(true),s(null);try{let U=await fetch(`${r}/api/auth/google/one-tap`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({credential:b.credential,stackId:e})});if(!U.ok){let D=(await U.json().catch(()=>({}))).error||"Google sign-in failed";s(D),g?.(D),n(!1);return}o(),n(!1),h?.();}catch(U){let A=U.message||"Google sign-in failed";s(A),g?.(A),n(false);}},[r,e,o,h,g]);useEffect(()=>{if(i){console.debug("[GoogleOneTap] Disabled");return}if(!y){console.debug("[GoogleOneTap] Script not loaded yet, clientId:",S);return}if(!S){console.debug("[GoogleOneTap] No Google clientId from stack config");return}if(m){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:",S),w.current=true,window.google.accounts.id.initialize({client_id:S,callback:z,auto_select:true,cancel_on_tap_outside:u}),d&&!T.current&&(T.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,y,S,m,c,z,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,U)=>{!b||!window.google?.accounts?.id||!w.current||window.google.accounts.id.renderButton(b,{theme:U?.theme||"filled_black",size:U?.size||"large",text:U?.text||"signin_with",width:U?.width});},[]);return {available:!!S,ready:y&&!!S,loading:a,error:p,prompt:$,renderButton:j,clientId:S}}var on="/api";function rn(e,t){return `${(t||(typeof window<"u"?window.location.origin:"")).replace(/\/$/,"")}/?ref=${encodeURIComponent(e)}`}function sn(e={}){let{shareBaseUrl:t,autoMint:r=true}=e,[d,u]=useState(null),[h,g]=useState(true),[i,l]=useState(null),c=useCallback(async()=>{g(true),l(null);try{let a=r?"POST":"GET",n=await fetch(`${on}/social/join-code`,{method:a,credentials:"include"});if(!n.ok){u(null),n.status===401?l("not_authenticated"):l(`HTTP ${n.status}`);return}let p=await n.json();u(p?.code??null);}catch(a){l(a?.message||"network_error"),u(null);}finally{g(false);}},[r]);useEffect(()=>{c();},[c]);let m=d?rn(d,t):null,o=useCallback(async()=>{if(!m)return false;try{if(typeof navigator<"u"&&navigator.clipboard?.writeText)return await navigator.clipboard.writeText(m),!0}catch{}return false},[m]);return {code:d,shareUrl:m,loading:h,error:i,refresh:c,copyShareLink:o}}var ct=createContext(null);function cn(){let e=useContext(ct);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function dn({config:e,callbacks:t,children:r}){return jsx(ct.Provider,{value:{config:e,callbacks:t},children:r})}function pe({length:e=6,onComplete:t,disabled:r=false,error:d,className:u="",inputClassName:h=""}){let [g,i]=useState(Array(e).fill("")),l=useCallback((o,a)=>{if(a.length>1){let p=a.replace(/\D/g,"").slice(0,e).split(""),s=[...g];p.forEach((C,w)=>{o+w<e&&(s[o+w]=C);}),i(s);let y=Math.min(o+p.length,e-1);document.getElementById(`userutils-otp-${y}`)?.focus(),s.every(C=>C!=="")&&setTimeout(()=>t(s.join("")),100);return}if(!/^\d?$/.test(a))return;let n=[...g];n[o]=a,i(n),a&&o<e-1&&document.getElementById(`userutils-otp-${o+1}`)?.focus(),a&&o===e-1&&n.every(p=>p!=="")&&setTimeout(()=>t(n.join("")),100);},[g,e,t]),c=useCallback((o,a)=>{if(a.key==="Backspace"&&!g[o]&&o>0){document.getElementById(`userutils-otp-${o-1}`)?.focus();let n=[...g];n[o-1]="",i(n);}if(a.key==="Enter"){let n=g.join("");n.length===e&&t(n);}},[g,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:g.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:r,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 ${h}`},a))}),d&&jsx("p",{className:"text-center text-sm text-red-400 mt-2",children:d})]})}pe.displayName="OTPInput";var gn="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function fe({className:e,style:t}){return jsx("img",{src:gn,alt:"Phantom",className:e,style:t})}function ge({className:e,style:t}){return jsxs("svg",{className:e,style:t,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 507.83 470.86",children:[jsx("polygon",{fill:"#e2761b",stroke:"#e2761b",strokeLinecap:"round",strokeLinejoin:"round",points:"482.09 0.5 284.32 147.38 320.9 60.72 482.09 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"25.54 0.5 221.72 148.77 186.93 60.72 25.54 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"410.93 340.97 358.26 421.67 470.96 452.67 503.36 342.76 410.93 340.97"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"4.67 342.76 36.87 452.67 149.57 421.67 96.9 340.97 4.67 342.76"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 111.8 252.13 223.7 257.1 219.73 136.85 143.21 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"364.42 204.62 286.91 135.46 284.32 257.1 396.03 252.13 364.42 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 216.75 388.87 158.71 343.55 149.57 421.67"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 358.26 421.67 348.92 343.55 290.88 388.87"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"358.26 421.67 290.88 388.87 296.25 432.8 295.65 451.28 358.26 421.67"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 212.18 451.28 211.78 432.8 216.75 388.87 149.57 421.67"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"213.17 314.54 157.12 298.04 196.67 279.95 213.17 314.54"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"294.46 314.54 310.96 279.95 350.71 298.04 294.46 314.54"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 159.11 340.97 96.9 342.76 149.57 421.67"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"348.72 340.97 358.26 421.67 410.93 342.76 348.72 340.97"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"396.03 252.13 284.32 257.1 294.66 314.54 311.16 279.95 350.91 298.04 396.03 252.13"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 196.87 279.95 213.17 314.54 223.7 257.1 111.8 252.13 157.12 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"111.8 252.13 158.71 343.55 157.12 298.04 111.8 252.13"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"350.91 298.04 348.92 343.55 396.03 252.13 350.91 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"223.7 257.1 213.17 314.54 226.29 382.31 229.27 293.07 223.7 257.1"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 278.96 292.87 281.34 382.31 294.66 314.54 284.32 257.1"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"294.66 314.54 281.34 382.31 290.88 388.87 348.92 343.55 350.91 298.04 294.66 314.54"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 158.71 343.55 216.75 388.87 226.29 382.31 213.17 314.54 157.12 298.04"}),jsx("polygon",{fill:"#c0ad9e",stroke:"#c0ad9e",strokeLinecap:"round",strokeLinejoin:"round",points:"295.65 451.28 296.25 432.8 291.28 428.42 216.35 428.42 211.78 432.8 212.18 451.28 149.57 421.67 171.43 439.55 215.75 470.36 291.88 470.36 336.4 439.55 358.26 421.67 295.65 451.28"}),jsx("polygon",{fill:"#161616",stroke:"#161616",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 281.34 382.31 226.29 382.31 216.75 388.87 211.78 432.8 216.35 428.42 291.28 428.42 296.25 432.8 290.88 388.87"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"490.44 156.92 507.33 75.83 482.09 0.5 290.88 142.41 364.42 204.62 468.37 235.03 491.43 208.2 481.49 201.05 497.39 186.54 485.07 177 500.97 164.87 490.44 156.92"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"0.5 75.83 17.39 156.92 6.66 164.87 22.56 177 10.44 186.54 26.34 201.05 16.4 208.2 39.26 235.03 143.21 204.62 216.75 142.41 25.54 0.5 0.5 75.83"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"468.37 235.03 364.42 204.62 396.03 252.13 348.92 343.55 410.93 342.76 503.36 342.76 468.37 235.03"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 39.26 235.03 4.67 342.76 96.9 342.76 158.71 343.55 111.8 252.13 143.21 204.62"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 290.88 142.41 321.1 60.72 186.93 60.72 216.75 142.41 223.7 257.1 226.09 293.27 226.29 382.31 281.34 382.31 281.74 293.27 284.32 257.1"})]})}function We({className:e,style:t}){return jsxs("svg",{className:e,style:t,viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#F1F2F9"}),jsx("path",{d:"M26.1001 16.2273C26.1001 15.5182 26.0365 14.8364 25.9183 14.1818H16.5001V18.05H21.8819C21.6501 19.3 20.9456 20.3591 19.8865 21.0682V23.5773H23.1183C25.0092 21.8364 26.1001 19.2727 26.1001 16.2273Z",fill:"#4285F4"}),jsx("path",{d:"M16.5001 26C19.2001 26 21.4637 25.1046 23.1182 23.5773L19.8864 21.0682C18.991 21.6682 17.8455 22.0227 16.5001 22.0227C13.8955 22.0227 11.691 20.2637 10.9046 17.9H7.56372V20.4909C9.20917 23.7591 12.591 26 16.5001 26Z",fill:"#34A853"}),jsx("path",{d:"M10.9047 17.8999C10.7047 17.2999 10.591 16.659 10.591 15.9999C10.591 15.3408 10.7047 14.6999 10.9047 14.0999V11.509H7.56376C6.86376 12.9025 6.49951 14.4405 6.50012 15.9999C6.50012 17.6136 6.88649 19.1408 7.56376 20.4908L10.9047 17.8999Z",fill:"#FBBC05"}),jsx("path",{d:"M16.5001 9.97726C17.9682 9.97726 19.2864 10.4818 20.3228 11.4727L23.191 8.60454C21.4591 6.99091 19.1955 6 16.5001 6C12.591 6 9.20917 8.2409 7.56372 11.5091L10.9046 14.1C11.691 11.7364 13.8955 9.97726 16.5001 9.97726Z",fill:"#EA4335"})]})}function Fe({className:e,style:t}){return jsxs("svg",{className:e,style:t,viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#5462EB"}),jsx("path",{d:"M23.5433 8.87438C22.2479 8.26174 20.8587 7.81038 19.4063 7.55187C19.3799 7.54688 19.3534 7.55934 19.3398 7.58428C19.1612 7.91179 18.9633 8.33905 18.8247 8.67487C17.2625 8.43382 15.7084 8.43382 14.1782 8.67487C14.0396 8.33158 13.8345 7.91179 13.6551 7.58428C13.6414 7.56018 13.615 7.54771 13.5886 7.55187C12.1369 7.80955 10.7478 8.26092 9.45159 8.87438C9.44037 8.87937 9.43075 8.88769 9.42437 8.89849C6.78947 12.9558 6.06766 16.9134 6.42176 20.8219C6.42336 20.841 6.43378 20.8593 6.4482 20.871C8.18663 22.1868 9.87059 22.9857 11.5233 23.5152C11.5497 23.5235 11.5778 23.5135 11.5946 23.491C11.9855 22.9408 12.334 22.3606 12.6328 21.7504C12.6505 21.7147 12.6336 21.6723 12.5976 21.6581C12.0448 21.442 11.5185 21.1785 11.0122 20.8793C10.9721 20.8552 10.9689 20.7961 11.0058 20.7679C11.1123 20.6856 11.2189 20.6 11.3206 20.5135C11.339 20.4977 11.3647 20.4944 11.3863 20.5044C14.7125 22.0696 18.3136 22.0696 21.6006 20.5044C21.6222 20.4936 21.6479 20.4969 21.6671 20.5127C21.7688 20.5991 21.8754 20.6856 21.9827 20.7679C22.0196 20.7961 22.0172 20.8552 21.9771 20.8793C21.4708 21.1843 20.9445 21.442 20.3909 21.6573C20.3548 21.6715 20.3388 21.7147 20.3564 21.7504C20.6617 22.3597 21.0101 22.9399 21.3939 23.4902C21.4099 23.5135 21.4387 23.5235 21.4652 23.5152C23.1259 22.9857 24.8099 22.1868 26.5483 20.871C26.5635 20.8593 26.5731 20.8419 26.5747 20.8228C26.9985 16.3041 25.8649 12.3789 23.5697 8.89931C23.5641 8.88769 23.5545 8.87937 23.5433 8.87438Z",fill:"#F7F7F7"})]})}function Be({className:e,style:t}){return jsxs("svg",{className:e,style:t,viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"black"}),jsx("path",{d:"M8.53901 8L14.7164 16.2153L8.5 22.8947H9.89907L15.3415 17.0468L19.7389 22.8947H24.5L17.975 14.2173L23.7612 8H22.3621L17.3499 13.3858L13.3001 8H8.53901ZM10.5964 9.02501H12.7837L22.4422 21.8695H20.255L10.5964 9.02501Z",fill:"#F7F7F7"})]})}function Ge({className:e,style:t}){return jsxs("svg",{className:e,style:t,viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#000000"}),jsx("path",{d:"M21.3611 16.7384C21.3807 18.9244 23.2792 19.6519 23.3001 19.661C23.2841 19.7124 22.9971 20.6962 22.3005 21.7115C21.6987 22.5892 21.0742 23.4636 20.0904 23.4816C19.1237 23.4994 18.8127 22.9098 17.7076 22.9098C16.6029 22.9098 16.2574 23.4636 15.3423 23.4994C14.3928 23.5352 13.6694 22.5504 13.0626 21.676C11.8226 19.8879 10.8747 16.6229 12.1471 14.4182C12.7791 13.3234 13.9087 12.6304 15.1346 12.6126C16.0668 12.5948 16.9468 13.2378 17.5167 13.2378C18.0865 13.2378 19.1555 12.4647 20.2795 12.579C20.7501 12.5986 22.0715 12.7692 22.9207 14.0122C22.852 14.0549 21.3453 14.9328 21.3611 16.7384ZM19.5432 11.392C20.0472 10.7809 20.3862 9.93 20.2939 9.08325C19.5709 9.11221 18.6961 9.56574 18.1749 10.1763C17.708 10.717 17.2995 11.582 17.4096 12.4111C18.2158 12.4736 19.0391 12.003 19.5432 11.392Z",fill:"#FFFFFF"})]})}function Cn({config:e,onSuccess:t,title:r="Log in or Sign up",showWallets:d,showOTP:u,hideHeader:h,onOTPSubmit:g,otpLabel:i="Access Code",oauthInline:l,oauthFirst:c,className:m=""}){let o=Ie(e),{isAuthenticated:a,wallet:n,loading:p,error:s,authenticateSolana:y,authenticateEVM:C,authenticateOTP:w,authenticateOAuth:T,bridge:x,stackId:S}=o,z=!e.stackId&&!S,$=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:j,identityProviders:b,loading:U}=re(S||e.stackId||null,$),[A,D]=useState(z?"stack-select":"select"),[P,I]=useState(null),[E,R]=useState(false),[N,L]=useState("idle"),[_,G]=useState(""),[Q,Z]=useState([]),[yt,Ve]=useState(e.stackId||null),[le,kt]=useState(false),[bt,wt]=useState(false);useEffect(()=>{if(typeof window>"u")return;let f=()=>{let V=window;kt(!!(V.phantom?.solana?.isPhantom||V.solana?.isPhantom));let q=V.ethereum;wt(!!(q?.isMetaMask||q?.providers?.some(X=>X.isMetaMask)));};f(),window.addEventListener("ethereum#initialized",f);let H=setTimeout(f,500);return ()=>{window.removeEventListener("ethereum#initialized",f),clearTimeout(H);}},[]),useEffect(()=>{A==="stack-select"&&S&&(Ve(S),D("select"));},[A,S]),useEffect(()=>{if(!(!x.ready||!z)&&x.identity){let f=[];x.resolvedStackId&&f.push({stackId:x.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(f.map(async H=>{try{let V=await fetch(`${$}/api/v2/stacks/${H.stackId}`);if(V.ok){let q=await V.json(),X=q.data?.stack||q;H.name=X.displayName||X.name,H.logoUrl=X.logoUrl;}}catch{}return H})).then(Z);}},[x.ready,x.identity,x.resolvedStackId,z,$]),useEffect(()=>{a&&A==="success"&&t?.();},[a,A,t]);let Ye=d||(b.length>0?b.filter(f=>f.type==="wallet").map(f=>f.id):["phantom","metamask"]),Ze=u!==void 0?u:b.length>0?b.some(f=>f.type==="otp"):true,K=b.filter(f=>f.type==="oauth"),ke=new Set(c||[]),Ke=K.filter(f=>ke.has(f.id)),be=l?K.filter(f=>!ke.has(f.id)):K,qe=async f=>{I(f),D("connecting"),await T(f)||D("error");},Ct=async()=>{I("phantom"),D("connecting");let f=await y("phantom");D(f?"success":"error");},St=async()=>{I("metamask"),D("connecting");let f=await C();D(f?"success":"error");},xt=async f=>{L("verifying"),G(""),await(g||w)(f)?(L("success"),D("success")):(L("error"),G("Invalid or expired code"),setTimeout(()=>L("idle"),2e3));},Xe=()=>{D(z&&!yt?"stack-select":"select"),I(null),R(false),L("idle"),G("");};return jsxs("div",{className:`w-full max-w-md space-y-3 ${m}`,children:[!h&&jsxs("div",{className:"mb-6 text-center",children:[j?.logoUrl&&A!=="stack-select"&&jsx("img",{src:ee(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(f=>jsxs("button",{onClick:()=>{Ve(f.stackId),D("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:ee(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."})]}),A==="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%"}})}),s&&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:s}),jsx("button",{className:"mt-3 w-full text-sm text-zinc-400 hover:text-white",onClick:Xe,children:"Try Again"})]}),A==="success"&&jsxs("div",{className:"border border-green-500/30 bg-green-500/10 p-6 text-center",children:[jsx("p",{className:"font-medium text-green-400 text-sm",children:"Connected!"}),jsx("p",{className:"mt-1 text-xs text-zinc-400",children:"Redirecting..."})]}),A==="connecting"&&p&&jsxs("div",{style:{border:"1px solid #27272a",background:"#25252f",padding:24,textAlign:"center"},children:[jsxs("div",{style:{width:40,height:40,margin:"0 auto 12px"},children:[P==="phantom"&&jsx(fe,{style:W}),P==="metamask"&&jsx(ge,{style:W})]}),jsx("p",{style:{fontWeight:500,fontSize:14,color:"#fff"},children:n.connected?"Signing message...":"Connecting wallet..."}),jsx("p",{style:{marginTop:4,fontSize:12,color:"#71717a"},children:"Please confirm in your wallet"}),jsx("button",{style:{marginTop:16,fontSize:14,color:"#71717a",background:"none",border:"none",cursor:"pointer"},onClick:Xe,children:"Cancel"})]}),A==="select"&&!p&&!U&&jsxs(Fragment,{children:[Ke.map(f=>jsxs("button",{onClick:()=>qe(f.id),style:ae,children:[jsx(ft,{provider:f.id}),jsx("span",{style:{fontWeight:500,color:"#fff"},children:gt(f.id,f.name)})]},f.id)),Ye.includes("phantom")&&jsxs("button",{onClick:Ct,disabled:!le,style:{...ae,opacity:le?1:.5,cursor:le?"pointer":"not-allowed"},children:[jsx(fe,{style:{...W,borderRadius:8}}),jsx("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:"Phantom"}),!le&&jsx("span",{style:{fontSize:12,color:"#71717a"},children:"Not installed"})]}),Ye.includes("metamask")&&bt&&jsxs("button",{onClick:St,style:ae,children:[jsx(ge,{style:W}),jsx("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:"MetaMask"})]}),Ze&&!E&&jsxs("button",{onClick:()=>R(true),style:ae,children:[jsx("div",{style:{...W,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8,border:"1px solid #3f3f46",background:"#2a2a3e"},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"20px",viewBox:"0 -960 960 960",width:"20px",fill:"#a1a1aa",children:jsx("path",{d:"M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v480q0 33-23.5 56.5T800-160H160Z"})})}),jsx("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:i})]}),Ze&&E&&jsxs("div",{style:{borderRadius:12,border:"1px solid #27272a",background:"#25252f",padding:24},children:[jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginBottom:16},children:"Enter your 6-digit access code"}),jsx(pe,{onComplete:xt,disabled:N==="verifying",error:_}),N==="verifying"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginTop:16},children:"Verifying..."}),N==="success"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#4ade80",marginTop:16},children:"Verified!"}),j?.webPageUrl&&N==="idle"&&(()=>{let f=ee(j.webPageUrl);return f==="#"?null:jsx("a",{href:`${f.replace(/\/$/,"")}/connect/pair`,target:"_blank",rel:"noopener noreferrer",style:{display:"block",textAlign:"center",fontSize:14,color:"#71717a",marginTop:16},children:"Get code"})})()]}),(l?be:K).length>0&&(!l||be.length>0)&&jsxs(Fragment,{children:[!l&&Ke.length===0&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 0"},children:[jsx("div",{style:{flex:1,borderTop:"1px solid #27272a"}}),jsx("span",{style:{fontSize:12,color:"#52525b"},children:"or continue with"}),jsx("div",{style:{flex:1,borderTop:"1px solid #27272a"}})]}),(l?be:K.filter(f=>!ke.has(f.id))).map(f=>jsxs("button",{onClick:()=>qe(f.id),style:ae,children:[jsx(ft,{provider:f.id}),jsx("span",{style:{fontWeight:500,color:"#fff"},children:gt(f.id,f.name)})]},f.id))]})]})]})}var W={width:40,height:40,flexShrink:0},ae={display:"flex",width:"100%",alignItems:"center",gap:12,borderRadius:12,border:"1px solid #27272a",background:"#25252f",padding:16,cursor:"pointer",transition:"background 0.15s"};function ft({provider:e}){switch(e){case "google":return jsx(We,{style:{...W,borderRadius:8}});case "discord":return jsx(Fe,{style:{...W,borderRadius:8}});case "twitter":return jsx(Be,{style:{...W,borderRadius:8}});case "apple":return jsx(Ge,{style:{...W,borderRadius:8}});default:return jsx("div",{style:{...W,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8,border:"1px solid #3f3f46",background:"#2a2a3e",fontSize:14,color:"#a1a1aa",fontFamily:"monospace"},children:e[0]?.toUpperCase()})}}function gt(e,t){return {google:"Google",discord:"Discord",twitter:"Twitter",apple:"Apple"}[e]||t||e}function vn({mid:e,apiBaseUrl:t="",scope:r,onSave:d,className:u}){let{profile:h,loading:g,saving:i,error:l,updateProfile:c}=je(e,{apiBaseUrl:t,scope:r}),[m,o]=useState(null),[a,n]=useState(null),[p,s]=useState(null),y=useRef(null),[C,w]=useState(false),T=m??h?.username??"",x=a??h?.bio??"",S=p??h?.avatarUrl,z=useCallback(b=>{let U=b.target.files?.[0];if(!U)return;let A=new FileReader;A.onload=()=>{s(A.result),w(true);},A.readAsDataURL(U);},[]),$=async()=>{await c({username:T||void 0,avatarUrl:p??h?.avatarUrl,bio:x||void 0})&&(w(false),d?.());};if(g)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=r==="global"||!r?"Global profile":`Stack profile (${r.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:()=>y.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: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:y,type:"file",accept:"image/*",onChange:z,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: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}),C&&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),s(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 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 In({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 An({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 Tn(e){let{apiBaseUrl:t,stacknetUrl:r="https://stacknet.magma-rpc.com",stackId:d="",transport:u,serviceKey:h,onAuthSuccess:g,onAuthError:i,onLogout:l}=e;async function c(o){if(!o.ok){let s=await o.json().catch(()=>({})),y=new Error(s.error||`Authentication failed (${o.status})`);throw i?.(y),y}let a=await o.json(),n=a.token||a.jwt,p=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,p),g?.(p),p}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:p}){let s={chain:o,message:n,signature:p,stackId:d};o==="solana"&&(s.publicKey=a);let y=await fetch(`${t}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return c(y)},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 p=await n.json();if(p.session)return p.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 p=`${r}/api/v2/stacks/${encodeURIComponent(d)}/auth/web3/challenge`,s=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chain:o,address:a})});if(!s.ok)throw new Error("Failed to get challenge");let y=await s.json();return y.data||y},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:h?{Authorization:`Bearer ${h}`}:{}},async getToken(){return u.getToken()}}}function Un(){return {async storeCredentials(e,t){},async getToken(){return null},async getHeaders(){return {}},async getStoredSession(){let e=te();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 Je="stackauth_token",Qe="stackauth_session";function Ln(e){return {async storeCredentials(t,r){await e.setItemAsync(Je,t),await e.setItemAsync(Qe,JSON.stringify(r));},async getToken(){try{return await e.getItemAsync(Je)}catch{return null}},async getHeaders(){let t=await this.getToken();return t?{Authorization:`Bearer ${t}`}:{}},async getStoredSession(){try{let t=await e.getItemAsync(Qe);return t?JSON.parse(t):null}catch{return null}},async clear(){await e.deleteItemAsync(Je).catch(()=>{}),await e.deleteItemAsync(Qe).catch(()=>{});}}}
|
|
2
|
+
export{Ge as AppleIcon,Cn as ConnectWidget,Fe as DiscordIcon,In as EthereumIcon,We as GoogleIcon,ge as MetaMaskIcon,pe as OTPInput,fe as PhantomIcon,vn as ProfileSettings,Pn as SolanaIcon,An as TelegramIcon,Be as TwitterIcon,dn as UserUtilsProvider,It as cn,Tn as createAuthClient,Ln as createNativeTransport,ve as createStackNetClient,Un as createWebTransport,Mt as decodeJwtPayloadClient,Nt as formatTokens,F as readCSRFCookie,te as readSessionCookie,ee as safeUrl,xe as useAuthBridge,Kt as useBillingHistory,we as useCSRFToken,tn as useGoogleOneTap,sn as useJoinCode,Ft as usePlans,Vt as usePrepaidCheckout,je as useProfile,ne as useSession,Ie as useStackAuth,re as useStackConfig,Gt as useSubscription,Qt as useUsage,cn as useUserUtilsContext,Ce as useWeb3Wallet,At as validateRedirectUrl};
|
package/dist/server/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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=
|
|
1
|
+
'use strict';var crypto=require('crypto');function Z(e){return Buffer.from(e).toString("base64url")}function se(e){return Buffer.from(e,"base64url").toString()}function N(e){try{let r=e.split(".");return r.length!==3?null:JSON.parse(se(r[1]))}catch{return null}}function j(e,r){let t=Z(JSON.stringify({alg:"HS256",typ:"JWT"})),o=Z(JSON.stringify(e)),n=crypto.createHmac("sha256",r).update(`${t}.${o}`).digest("base64url");return `${t}.${o}.${n}`}function X(e,r){try{let t=e.split(".");if(t.length!==3)return !1;let[o,n,a]=t,c=crypto.createHmac("sha256",r).update(`${o}.${n}`).digest("base64url"),g=Buffer.from(a),f=Buffer.from(c);return g.length!==f.length?!1:crypto.timingSafeEqual(g,f)}catch{return false}}function C(e,r){if(!X(e,r))return null;let t=N(e);return !t||t.exp&&t.exp<Math.floor(Date.now()/1e3)?null:t}function D(e,r,t=900,o=300){let n=C(e,r);return !n?.exp||n.exp*1e3-Date.now()>o*1e3?null:j({...n,exp:Math.floor(Date.now()/1e3)+t},r)}function F(e=32){return crypto.randomBytes(e).toString("hex")}function O(e,r={}){let t=r.trustedProxyCount??1,o=r.trustRealIpHeader===true;if(r.customExtractor){let n=r.customExtractor(e);if(n)return n}if(t>0){let n=e.headers.get("x-forwarded-for");if(n){let a=n.split(",").map(g=>g.trim()).filter(Boolean),c=a.length-t;if(c>=0&&c<a.length)return a[c]}}if(o){let n=e.headers.get("x-real-ip");if(n)return n.trim()}return "unknown"}var ne="__csrf",ae="x-csrf-token",ie=/^[A-Za-z_$][A-Za-z0-9_$-]{0,63}$/,ce=/^[A-Za-z][A-Za-z0-9-]{0,63}$/;function v(e={}){let r=e.cookieName||ne,t=e.headerName||ae,o=e.tokenLength||32,n=e.secure!==false;if(!ie.test(r))throw new Error(`createCSRFProtection: invalid cookieName "${r}"`);if(!ce.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 c=F(o),g=[`${r}=${c}`,"Path=/","SameSite=Lax"];return n&&g.push("Secure"),a.append("Set-Cookie",g.join("; ")),c},validateRequest(a){let c=a.headers.get("cookie");if(!c)return {valid:false,error:"No cookies present"};let g=c.split(";").map(m=>m.trim()).find(m=>m.startsWith(`${r}=`))?.slice(r.length+1);if(!g)return {valid:false,error:"CSRF cookie missing"};let f=a.headers.get(t);if(!f)return {valid:false,error:"CSRF header missing"};try{let m=Buffer.from(g),p=Buffer.from(f);return m.length!==p.length?{valid:!1,error:"CSRF token mismatch"}:crypto.timingSafeEqual(m,p)?{valid:!0}:{valid:!1,error:"CSRF token mismatch"}}catch{return {valid:false,error:"CSRF validation failed"}}},cookieName:r,headerName:t}}function $(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 ue(){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 le(e,r){let t=r?.rateLimiter||$({maxRequests:10,windowMs:6e4}),o=v({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,a=e.sessionMaxAge||604800,c=e.stacknetJwtSecret||e.authSecret;return async function(f){let m=O(f,e.ipConfig),p=await t.check(`auth:${m}`);if(!p.allowed)return Response.json({error:"Too many login attempts. Please wait."},{status:429,headers:{"Retry-After":String(p.retryAfter||60)}});let y;try{y=await f.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{chain:u,message:d,signature:s,publicKey:i,otp:l,code:h,redirectUrl:k,stackId:x}=y,S=x||e.stackId,w;if(u&&d&&s){let ee={"Content-Type":"application/json"},L=await fetch(`${e.stacknetUrl}/api/v2/stacks/${encodeURIComponent(S)}/auth/web3/verify`,{method:"POST",headers:ee,body:JSON.stringify({chain:u,message:d,signature:s,public_key:i}),signal:AbortSignal.timeout(1e4)});if(!L.ok){let q=await L.json().catch(()=>({})),W=q?.error?.message||q?.message||q?.error||`StackNet returned ${L.status}`;return console.error(`[auth-callback] Verify failed: ${L.status}`,W),Response.json({error:"Wallet verification failed",detail:typeof W=="string"?W:void 0},{status:401})}let U=await L.json();w=U.data?.session||U.session||U.data||U,console.log(`[auth-callback] Verify OK, sessionData keys: ${Object.keys(w||{}).join(", ")}`);}else return l||h?Response.json({error:"Use /api/auth/otp for OTP verification"},{status:400}):Response.json({error:"Provide wallet signature or OTP code"},{status:400});if(!w?.jwt)return Response.json({error:"Authentication failed \u2014 no session returned"},{status:401});let R=C(w.jwt,c);if(!R)return Response.json({error:"Upstream session JWT failed verification"},{status:502});let P=Math.floor(Date.now()/1e3),A={...R,exp:P+n,iat:P},T=j(A,e.authSecret),I={userId:R.sub||R.user_id||R.session_id||R.global_id||"",address:w.address||R.address,chain:w.chain||u,expiresAt:Date.now()+a*1e3,authMethod:u?`web3:${u}`:"otp"},b=new Headers({"Content-Type":"application/json"}),H=e.secureCookies!==false?"; Secure":"",_=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";b.append("Set-Cookie",`stackauth_jwt=${T}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${a}${H}${_}`);let B=Buffer.from(JSON.stringify(I)).toString("base64url");return b.append("Set-Cookie",`stackauth_session=${B}; Path=/; SameSite=Lax; Max-Age=${a}${H}${_}`),o.generateToken(b),new Response(JSON.stringify({user:I}),{status:200,headers:b})}}function Q(e,r){if(!r)return null;try{let t=N(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 de=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;function Y(e){return typeof e!="string"||e.length===0||e.length>8192?null:de.test(e)?e:null}function J(e,r){let t=Q(e,r),o=t&&Y(t);if(o)return {Cookie:`stackauth_jwt=${o}`};let n=Y(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 fe(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 g=C(o,e.authSecret),f=g?.session_id||g?.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}`:"",c=new Headers({"Content-Type":"application/json"});return c.append("Set-Cookie",`stackauth_jwt=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${n}${a}`),c.append("Set-Cookie",`stackauth_session=; Path=/; SameSite=Lax; Max-Age=0${n}${a}`),c.append("Set-Cookie",`__csrf=; Path=/; SameSite=Lax; Max-Age=0${n}${a}`),new Response(JSON.stringify({success:true}),{status:200,headers:c})}}function me(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 c=C(a,e.authSecret);if(!c)return Response.json({session:null},{status:200});let f={userId:c.sub||c.user_id||c.session_id||c.global_id||"",address:c.address,chain:c.chain,expiresAt:c.session_expires_at||(c.exp?c.exp*1e3:Date.now()+t*1e3),planId:c.plan_id,authMethod:c.auth_method},m=new Headers({"Content-Type":"application/json"}),p=D(a,e.authSecret,r,300);if(p){let y=e.secureCookies!==false?"; Secure":"",u=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";m.append("Set-Cookie",`stackauth_jwt=${p}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${t}${y}${u}`);}return new Response(JSON.stringify({session:f}),{status:200,headers:m})}}function ye(e,r){if(e.length!==r.length)return false;try{return crypto.timingSafeEqual(Buffer.from(e),Buffer.from(r))}catch{return false}}function we(e){let r=e.rateLimiter||$({maxRequests:5,windowMs:3e5}),t=v({secure:e.secureCookies!==false}),o=e.jwtExpiry||900,n=e.sessionMaxAge||604800;return async function(c){let g=O(c,e.ipConfig),f=await r.check(`otp:${g}`);if(!f.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(f.retryAfter||300)}});let m;try{m=await c.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{code:p}=m;if(!p||typeof p!="string"||p.length!==6)return Response.json({error:"Invalid code format"},{status:400});if(!ye(p,e.otpSecret))return Response.json({error:"Invalid code"},{status:401});let y=Math.floor(Date.now()/1e3),d={sub:`preview:otp:${crypto.createHash("sha256").update(`otp:${p}:${Date.now()}`).digest("hex").slice(0,32)}`,scope:"preview",auth_method:"otp",credentials:["otp"],iat:y,exp:y+o},s=j(d,e.authSecret),i={userId:d.sub,expiresAt:Date.now()+n*1e3,authMethod:"otp",scope:"preview"},l=new Headers({"Content-Type":"application/json"}),h=e.secureCookies!==false?"; Secure":"",k=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";l.append("Set-Cookie",`stackauth_jwt=${s}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${n}${h}${k}`);let x=Buffer.from(JSON.stringify(i)).toString("base64url");return l.append("Set-Cookie",`stackauth_session=${x}; Path=/; SameSite=Lax; Max-Age=${n}${h}${k}`),t.generateToken(l),new Response(JSON.stringify({success:true,data:{user:i}}),{status:200,headers:l})}}function Se(e,r){let t=r?.rateLimiter||$({maxRequests:10,windowMs:6e4}),o=v({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,a=e.sessionMaxAge||604800,c=e.stacknetJwtSecret||e.authSecret;async function g(m){let p=new URL(m.url),y=p.searchParams.get("provider"),u=p.searchParams.get("redirectUri")||p.searchParams.get("redirect_uri"),d=p.searchParams.get("stackId")||e.stackId;if(!y)return Response.json({error:"Missing provider parameter"},{status:400});if(!u)return Response.json({error:"Missing redirectUri parameter"},{status:400});if(!/^[a-z][a-z0-9_-]{0,32}$/.test(y))return Response.json({error:"Invalid provider name"},{status:400});if(!d||!/^[a-zA-Z0-9_-]{1,64}$/.test(d))return Response.json({error:"Invalid stackId"},{status:400});try{let s=await fetch(`${e.stacknetUrl}/api/v2/stacks/${encodeURIComponent(d)}/auth/oauth/${encodeURIComponent(y)}/initiate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({redirectUrl:u}),signal:AbortSignal.timeout(1e4)});if(!s.ok){let h=await s.json().catch(()=>({}));return Response.json({error:h.error?.message||`Failed to start OAuth flow: ${s.statusText}`},{status:s.status})}let i=await s.json(),l=i.data||i;return Response.json({redirect_url:l.url,state:l.state})}catch(s){return Response.json({error:s.message||"Failed to start OAuth flow"},{status:500})}}async function f(m){let p=O(m,e.ipConfig),y=await t.check(`oauth:${p}`);if(!y.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(y.retryAfter||60)}});let u;try{u=await m.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{provider:d,code:s,state:i,stackId:l}=u,h=l||e.stackId;if(!d||!s||!i)return Response.json({error:"Missing provider, code, or state"},{status:400});if(!/^[a-z][a-z0-9_-]{0,32}$/.test(d))return Response.json({error:"Invalid provider name"},{status:400});if(!h||!/^[a-zA-Z0-9_-]{1,64}$/.test(h))return Response.json({error:"Invalid stackId"},{status:400});try{let k=await fetch(`${e.stacknetUrl}/api/v2/stacks/${encodeURIComponent(h)}/auth/oauth/${encodeURIComponent(d)}/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:s,state:i}),signal:AbortSignal.timeout(1e4)});if(!k.ok){let _=await k.json().catch(()=>({}));return Response.json({error:_.error?.message||`OAuth verification failed: ${k.statusText}`},{status:401})}let x=await k.json(),S=x.data?.session||x.session||x.data||x;if(!S?.jwt)return Response.json({error:"OAuth authentication failed \u2014 no session returned"},{status:401});let w=C(S.jwt,c);if(!w)return Response.json({error:"Upstream session JWT failed verification"},{status:502});let R=Math.floor(Date.now()/1e3),P=j({...w,exp:R+n,iat:R},e.authSecret),T={userId:w.sub||w.user_id||w.session_id||w.global_id||"",address:S.address||w.address,chain:void 0,expiresAt:Date.now()+a*1e3,authMethod:`oauth:${d}`},E=new Headers({"Content-Type":"application/json"}),I=e.secureCookies!==!1?"; Secure":"",b=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";E.append("Set-Cookie",`stackauth_jwt=${P}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${a}${I}${b}`);let H=Buffer.from(JSON.stringify(T)).toString("base64url");return E.append("Set-Cookie",`stackauth_session=${H}; Path=/; SameSite=Lax; Max-Age=${a}${I}${b}`),o.generateToken(E),new Response(JSON.stringify({user:T}),{status:200,headers:E})}catch(k){return Response.json({error:k.message||"OAuth callback failed"},{status:500})}}return {startFlow:g,handleCallback:f}}function ke(e,r){let t=r?.rateLimiter||$({maxRequests:10,windowMs:6e4}),o=v({secure:e.secureCookies!==false}),n=e.jwtExpiry||900,a=e.sessionMaxAge||604800,c=e.stacknetJwtSecret||e.authSecret;return async function(f){let m=O(f,e.ipConfig),p=await t.check(`google-onetap:${m}`);if(!p.allowed)return Response.json({error:"Too many attempts. Please wait."},{status:429,headers:{"Retry-After":String(p.retryAfter||60)}});let y;try{y=await f.json();}catch{return Response.json({error:"Invalid request body"},{status:400})}let{credential:u,stackId:d}=y,s=d||e.stackId;if(!u)return Response.json({error:"Missing credential"},{status:400});if(u.split(".").length!==3)return Response.json({error:"Invalid credential format"},{status:400});let i;try{let S=await fetch(`https://oauth2.googleapis.com/tokeninfo?id_token=${encodeURIComponent(u)}`,{signal:AbortSignal.timeout(1e4)});if(!S.ok)return Response.json({error:"Google credential verification failed"},{status:401});i=await S.json();}catch{return Response.json({error:"Failed to verify Google credential"},{status:500})}if(!i.sub||!i.email)return Response.json({error:"Invalid Google token \u2014 missing user info"},{status:401});if(i.iss!=="https://accounts.google.com"&&i.iss!=="accounts.google.com")return Response.json({error:"Invalid Google token issuer"},{status:401});let l=typeof i.exp=="string"?parseInt(i.exp,10):Number(i.exp);if(!Number.isFinite(l)||l<Math.floor(Date.now()/1e3))return Response.json({error:"Google token expired"},{status:401});let h=e.googleClientIds||(e.googleClientId?[e.googleClientId]:[]);if(h.length===0)return Response.json({error:"Google One Tap not configured \u2014 set ServerConfig.googleClientId(s)"},{status:500});if(!i.aud||!h.includes(i.aud))return Response.json({error:"Invalid Google token audience"},{status:401});if(!(i.email_verified===true||i.email_verified==="true"))return Response.json({error:"Google email is not verified"},{status:401});let x={sub:i.sub,email:i.email,name:i.name,picture:i.picture};try{let S=await fetch(`${e.stacknetUrl}/api/v2/stacks/${encodeURIComponent(s)}/auth/oauth/google/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({credential:u,google_id:x.sub,email:x.email,name:x.name,picture:x.picture,one_tap:!0}),signal:AbortSignal.timeout(1e4)});if(!S.ok){let P=await S.json().catch(()=>({}));return Response.json({error:P?.error?.message||"Google sign-in failed"},{status:S.status})}let w=await S.json(),R=w.data?.session||w.session||w.data||w;if(R?.jwt){let P=C(R.jwt,c);if(!P)return Response.json({error:"Upstream session JWT failed verification"},{status:502});let A=Math.floor(Date.now()/1e3),T=j({...P,exp:A+n,iat:A},e.authSecret),I={userId:P.sub||P.user_id||x.sub,address:x.email||R.address,chain:void 0,expiresAt:Date.now()+a*1e3,authMethod:"oauth:google"},b=new Headers({"Content-Type":"application/json"}),H=e.secureCookies!==!1?"; Secure":"",_=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";b.append("Set-Cookie",`stackauth_jwt=${T}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${a}${H}${_}`);let B=Buffer.from(JSON.stringify(I)).toString("base64url");return b.append("Set-Cookie",`stackauth_session=${B}; Path=/; SameSite=Lax; Max-Age=${a}${H}${_}`),o.generateToken(b),new Response(JSON.stringify({user:I}),{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 xe(e){let r=v({secure:e.secureCookies!==false}),t=e.rateLimiter||$({maxRequests:20,windowMs:6e4}),o=e.stacknetJwtSecret||e.authSecret,n=e.jwtExpiry||900,a=e.sessionMaxAge||604800,c=null;if(e.canonicalOrigin){let s;try{s=new URL(e.canonicalOrigin);}catch{throw new Error(`createBillingProxy: canonicalOrigin "${e.canonicalOrigin}" is not a valid URL`)}if(s.protocol!=="http:"&&s.protocol!=="https:")throw new Error(`createBillingProxy: canonicalOrigin must be http or https (got "${s.protocol}")`);if(s.pathname!=="/"&&s.pathname!=="")throw new Error(`createBillingProxy: canonicalOrigin must have no path (got "${s.pathname}")`);c=s.origin;}let g=false;function f(s){if(c)return c;g||(g=true,console.warn("[userutils] createBillingProxy: canonicalOrigin not set \u2014 falling back to request origin. Set canonicalOrigin to the public URL of this app to prevent Host-header spoofing of Stripe success URLs."));try{let i=new URL(s.url);return i.protocol!=="http:"&&i.protocol!=="https:"?null:i.origin}catch{return null}}function m(s){let i=M(s);if(!i)return null;let l=C(i,e.authSecret);return l?{jwt:i,payload:l}:null}function p(s,i){let l=D(s,e.authSecret,n,300);if(l){let h=e.secureCookies!==false?"; Secure":"",k=e.cookieDomain?`; Domain=${e.cookieDomain}`:"";i.append("Set-Cookie",`stackauth_jwt=${l}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${a}${h}${k}`);}}async function y(s,i){let l=m(s);if(!l)return Response.json({error:"Unauthorized"},{status:401});let h=J(l.jwt,o),k=await fetch(`${e.stacknetUrl}${i}`,{headers:h,signal:AbortSignal.timeout(15e3)}),x=await k.json().catch(()=>({})),S=new Headers({"Content-Type":"application/json"});return p(l.jwt,S),new Response(JSON.stringify(x),{status:k.status,headers:S})}async function u(s,i,l){let h=m(s);if(!h)return Response.json({error:"Unauthorized"},{status:401});let k=r.validateRequest(s);if(!k.valid)return Response.json({error:k.error||"CSRF validation failed"},{status:403});let x=h.payload.sub||h.payload.user_id||"unknown";if(!(await t.check(`billing:${x}`)).allowed)return Response.json({error:"Too many requests"},{status:429});let w=await s.json().catch(()=>({})),R=J(h.jwt,o);R["Content-Type"]="application/json";let P=await fetch(`${e.stacknetUrl}${i}`,{method:"POST",headers:R,body:JSON.stringify({...w,...l}),signal:AbortSignal.timeout(15e3)}),A=await P.json().catch(()=>({})),T=new Headers({"Content-Type":"application/json"});return p(h.jwt,T),new Response(JSON.stringify(A),{status:P.status,headers:T})}let d=`/api/v2/stacks/${encodeURIComponent(e.stackId)}`;return {plans:{GET:async s=>{let i=await fetch(`${e.stacknetUrl}${d}/plans`,{signal:AbortSignal.timeout(1e4)}),l=await i.json().catch(()=>({}));return Response.json(l,{status:i.status})}},subscription:{GET:(s=>y(s,`${d}/subscription`))},subscribe:{POST:(s=>{let i=f(s);return i?u(s,`${d}/subscribe`,{successUrl:`${i}/billing/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${i}/pricing`}):Promise.resolve(Response.json({error:"Invalid request origin for checkout"},{status:400}))})},cancel:{POST:(s=>u(s,`${d}/cancel-subscription`))},usage:{GET:(s=>y(s,"/v1/account/usage"))},history:{GET:(s=>y(s,`${d}/billing`))},prepaid:{POST:(s=>{let i=f(s);return i?u(s,`${d}/prepaid`,{successUrl:`${i}/pricing/prepaid/success?session_id={CHECKOUT_SESSION_ID}`,cancelUrl:`${i}/pricing/prepaid`}):Promise.resolve(Response.json({error:"Invalid request origin for checkout"},{status:400}))})},verifyPrepaid:{POST:(s=>u(s,`${d}/verify-prepaid`))},verifySession:{POST:(s=>u(s,`${d}/verify-session`))},subscribeSol:{POST:(s=>u(s,`${d}/subscribe-sol`))},prepaidSol:{POST:(s=>u(s,`${d}/prepaid-sol`))},topup:{POST:(s=>u(s,"/v1/account/topup"))}}}function Re(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)}),c=await a.json().catch(()=>({received:!0}));return Response.json(c,{status:a.status})}catch{return Response.json({error:"Webhook processing failed"},{status:502})}}}function G(){return {"Strict-Transport-Security":"max-age=63072000; includeSubDomains; preload","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","X-XSS-Protection":"0","Referrer-Policy":"strict-origin-when-cross-origin","Permissions-Policy":"camera=(), microphone=(), geolocation=()"}}function Pe(e){return async r=>{let t=await e(r),o=G(),n=new Headers(t.headers);for(let[a,c]of Object.entries(o))n.set(a,c);return new Response(t.body,{status:t.status,statusText:t.statusText,headers:n})}}function Ce(){return Object.entries(G()).map(([e,r])=>({key:e,value:r}))}function z(e){return {"Content-Type":"application/json",...J(e.jwt,e.stacknetJwtSecret)}}async function be(e,r){let t=await fetch(`${e.stacknetBaseUrl}/v1/preview-codes`,{method:"POST",headers:z(e),body:JSON.stringify({token_budget:r.tokenBudget,code:r.code,expires_at:r.expiresAt,name:r.name})});return t.ok?await t.json():{error:await t.text().catch(()=>"")||`HTTP ${t.status}`,status:t.status}}async function ve(e){let r=await fetch(`${e.stacknetBaseUrl}/v1/preview-codes`,{method:"GET",headers:z(e)});return r.ok?(await r.json()).codes:{error:await r.text().catch(()=>"")||`HTTP ${r.status}`,status:r.status}}async function $e(e,r){let t=await fetch(`${e}/v1/preview-codes/${encodeURIComponent(r)}`,{method:"GET"});return t.status===404||!t.ok?null:await t.json()}async function je(e,r){let t=await fetch(`${e.stacknetBaseUrl}/v1/preview-codes/${encodeURIComponent(r)}`,{method:"DELETE",headers:z(e)});return t.ok?await t.json():{error:await t.text().catch(()=>"")||`HTTP ${t.status}`,status:t.status}}async function Te(e,r,t){let o=await fetch(`${e}/v1/preview-codes/${encodeURIComponent(r)}/redeem`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tokens:t})});return o.ok?await o.json():{error:await o.text().catch(()=>"")||`HTTP ${o.status}`,status:o.status}}var V=["127924fc17182f69cb463d9977348c482d2e784dfdd16f9e6eecc4db07fb04c3","HxLBLBjKbSrJSFCE7LGs9FxMA6M5bztmpNoLuB43HTFs"];function Oe(e){return e?V.includes(e):false}var Ie=V[0];
|
|
2
|
+
exports.PREVIEW_CODE_ADMIN_GLOBAL_ID=Ie;exports.PREVIEW_CODE_ADMIN_GLOBAL_IDS=V;exports.buildStackNetHeaders=J;exports.createAuthCallback=le;exports.createBillingProxy=xe;exports.createCSRFProtection=v;exports.createGoogleOneTapHandler=ke;exports.createInMemoryRateLimiter=$;exports.createInMemoryReplayStore=ue;exports.createLogoutHandler=fe;exports.createOAuthHandlers=Se;exports.createOTPHandler=we;exports.createSessionHandler=me;exports.createWebhookHandler=Re;exports.decodeJWTPayload=N;exports.extractIP=O;exports.extractJwt=M;exports.generateToken=F;exports.getPreviewCode=$e;exports.isPreviewCodeAdmin=Oe;exports.listPreviewCodes=ve;exports.maybeRefreshJWT=D;exports.mintPreviewCode=be;exports.nextSecurityHeaders=Ce;exports.redeemPreviewCode=Te;exports.resignForStackNet=Q;exports.revokePreviewCode=je;exports.securityHeaders=G;exports.signJWT=j;exports.verifyJWT=C;exports.verifyJWTSignature=X;exports.withSecurityHeaders=Pe;
|
package/dist/server/index.d.cts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { S as Session } from '../auth-
|
|
2
|
-
import { e as ServerConfig } from '../config-
|
|
1
|
+
import { S as Session } from '../auth-c1d7Eji2.cjs';
|
|
2
|
+
import { e as ServerConfig, I as IPExtractorConfig } from '../config-CLzVWDrU.cjs';
|
|
3
|
+
export { f as decodeJWTPayload, g as extractIP, h as generateToken, m as maybeRefreshJWT, s as signJWT, v as verifyJWT, i as verifyJWTSignature } from '../config-CLzVWDrU.cjs';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Server-only session type that includes the JWT.
|
|
@@ -75,6 +76,10 @@ interface OTPHandlerConfig extends Pick<ServerConfig, 'authSecret' | 'secureCook
|
|
|
75
76
|
otpSecret: string;
|
|
76
77
|
/** Rate limiter (default: 5 attempts per 5 min per IP) */
|
|
77
78
|
rateLimiter?: RateLimiter;
|
|
79
|
+
/** How to extract the real client IP for rate-limit keys. Defaults to
|
|
80
|
+
* `{ trustedProxyCount: 1 }`. Set `trustedProxyCount: 0` if the handler
|
|
81
|
+
* is exposed directly (no proxy in front). */
|
|
82
|
+
ipConfig?: IPExtractorConfig;
|
|
78
83
|
}
|
|
79
84
|
/**
|
|
80
85
|
* Factory: POST handler for OTP verification.
|
|
@@ -111,6 +116,21 @@ declare function createGoogleOneTapHandler(config: ServerConfig, opts?: GoogleOn
|
|
|
111
116
|
interface BillingProxyConfig extends Pick<ServerConfig, 'authSecret' | 'stacknetUrl' | 'stackId' | 'stacknetJwtSecret' | 'secureCookies' | 'cookieDomain' | 'sessionMaxAge' | 'jwtExpiry'> {
|
|
112
117
|
/** Rate limiter for mutations (default: 20/min per user) */
|
|
113
118
|
rateLimiter?: RateLimiter;
|
|
119
|
+
/**
|
|
120
|
+
* Canonical absolute origin (e.g. "https://app.example.com") used when
|
|
121
|
+
* constructing Stripe success/cancel URLs. STRONGLY RECOMMENDED.
|
|
122
|
+
*
|
|
123
|
+
* Without this, the origin is derived from the request URL — which is
|
|
124
|
+
* populated from the `Host` header. If the app is deployed behind a
|
|
125
|
+
* proxy that does not validate / rewrite `Host`, an attacker can send
|
|
126
|
+
* `Host: evil.example` and the post-checkout redirect will point there.
|
|
127
|
+
* Stripe's dashboard allowlist catches most cases, but we should not
|
|
128
|
+
* depend on that alone.
|
|
129
|
+
*
|
|
130
|
+
* Must be a full http(s) origin with no path. Factory throws on
|
|
131
|
+
* malformed input so misconfigurations surface at boot, not at runtime.
|
|
132
|
+
*/
|
|
133
|
+
canonicalOrigin?: string;
|
|
114
134
|
}
|
|
115
135
|
type Handler = (request: Request) => Promise<Response>;
|
|
116
136
|
/**
|
|
@@ -221,24 +241,6 @@ declare function nextSecurityHeaders(): Array<{
|
|
|
221
241
|
value: string;
|
|
222
242
|
}>;
|
|
223
243
|
|
|
224
|
-
/** Decode JWT payload without verification (server-side helper) */
|
|
225
|
-
declare function decodeJWTPayload(jwt: string): Record<string, any> | null;
|
|
226
|
-
/** Sign a JWT with HMAC-SHA256 */
|
|
227
|
-
declare function signJWT(payload: Record<string, any>, secret: string): string;
|
|
228
|
-
/** Verify a JWT signature with HMAC-SHA256 (constant-time comparison) */
|
|
229
|
-
declare function verifyJWTSignature(jwt: string, secret: string): boolean;
|
|
230
|
-
/** Verify JWT and return payload if valid (checks signature + expiry) */
|
|
231
|
-
declare function verifyJWT(jwt: string, secret: string): Record<string, any> | null;
|
|
232
|
-
/**
|
|
233
|
-
* Check if JWT needs refresh and return a new one if so.
|
|
234
|
-
* Returns null if no refresh needed or JWT is invalid.
|
|
235
|
-
*/
|
|
236
|
-
declare function maybeRefreshJWT(jwt: string, secret: string, expirySeconds?: number, refreshWindowSeconds?: number): string | null;
|
|
237
|
-
/** Generate a cryptographically secure random token */
|
|
238
|
-
declare function generateToken(bytes?: number): string;
|
|
239
|
-
/** Extract IP address from request headers */
|
|
240
|
-
declare function extractIP(request: Request): string;
|
|
241
|
-
|
|
242
244
|
/**
|
|
243
245
|
* Re-sign a JWT using StackNet's HMAC-SHA256 scheme.
|
|
244
246
|
*
|
|
@@ -261,4 +263,97 @@ declare function buildStackNetHeaders(jwt: string, stacknetJwtSecret: string): R
|
|
|
261
263
|
*/
|
|
262
264
|
declare function extractJwt(request: Request): string | null;
|
|
263
265
|
|
|
264
|
-
|
|
266
|
+
/**
|
|
267
|
+
* Server-side proxy helpers for StackNet preview codes.
|
|
268
|
+
*
|
|
269
|
+
* Preview codes are admin-minted 6-digit access credentials with a
|
|
270
|
+
* per-code token budget. Only the pinned admin global id (enforced
|
|
271
|
+
* by StackNet's state machine) can mint / list / revoke codes.
|
|
272
|
+
*
|
|
273
|
+
* These helpers wrap `fetch` against the StackNet HTTP layer with
|
|
274
|
+
* re-signed JWT cookies (same pattern as `buildStackNetHeaders`).
|
|
275
|
+
* Admin-console API routes are expected to call them; the raw
|
|
276
|
+
* endpoints are NOT exposed in the client bundle.
|
|
277
|
+
*/
|
|
278
|
+
interface PreviewCode {
|
|
279
|
+
code: string;
|
|
280
|
+
createdBy: string;
|
|
281
|
+
tokenBudget: number;
|
|
282
|
+
tokensUsed: number;
|
|
283
|
+
tokensRemaining: number;
|
|
284
|
+
createdAt: number;
|
|
285
|
+
expiresAt: number | null;
|
|
286
|
+
revoked: boolean;
|
|
287
|
+
/** Optional human-readable label (e.g. "Tester: Alice"). Absent on
|
|
288
|
+
* codes minted before the name field shipped. */
|
|
289
|
+
name?: string | null;
|
|
290
|
+
}
|
|
291
|
+
interface MintPreviewCodeOptions {
|
|
292
|
+
/** Token budget for the new code. Must be > 0. */
|
|
293
|
+
tokenBudget: number;
|
|
294
|
+
/** Optional explicit 6-digit code string. Server generates one
|
|
295
|
+
* if omitted. */
|
|
296
|
+
code?: string;
|
|
297
|
+
/** Optional Unix-ms expiry. */
|
|
298
|
+
expiresAt?: number;
|
|
299
|
+
/** Optional human-readable label for the code. Shown in the admin
|
|
300
|
+
* list so the operator can tell codes apart. */
|
|
301
|
+
name?: string;
|
|
302
|
+
}
|
|
303
|
+
interface PreviewCodesProxyConfig {
|
|
304
|
+
/** StackNet base URL (no trailing slash). */
|
|
305
|
+
stacknetBaseUrl: string;
|
|
306
|
+
/** Shared HMAC secret for re-signing the caller's JWT. */
|
|
307
|
+
stacknetJwtSecret: string;
|
|
308
|
+
/** Caller's StackAuth JWT (user identity). */
|
|
309
|
+
jwt: string;
|
|
310
|
+
}
|
|
311
|
+
/** Admin-only: mint a new preview code. Returns the new code row. */
|
|
312
|
+
declare function mintPreviewCode(cfg: PreviewCodesProxyConfig, options: MintPreviewCodeOptions): Promise<{
|
|
313
|
+
minted: boolean;
|
|
314
|
+
code: PreviewCode;
|
|
315
|
+
} | {
|
|
316
|
+
error: string;
|
|
317
|
+
status: number;
|
|
318
|
+
}>;
|
|
319
|
+
/** Admin-only: list every preview code in the system. */
|
|
320
|
+
declare function listPreviewCodes(cfg: PreviewCodesProxyConfig): Promise<PreviewCode[] | {
|
|
321
|
+
error: string;
|
|
322
|
+
status: number;
|
|
323
|
+
}>;
|
|
324
|
+
/** Public: read a code's balance + status. Used by auth middleware. */
|
|
325
|
+
declare function getPreviewCode(stacknetBaseUrl: string, code: string): Promise<PreviewCode | null>;
|
|
326
|
+
/** Admin-only: revoke a preview code. */
|
|
327
|
+
declare function revokePreviewCode(cfg: PreviewCodesProxyConfig, code: string): Promise<{
|
|
328
|
+
revoked: boolean;
|
|
329
|
+
code: PreviewCode;
|
|
330
|
+
} | {
|
|
331
|
+
error: string;
|
|
332
|
+
status: number;
|
|
333
|
+
}>;
|
|
334
|
+
/** Internal: debit tokens from a preview code. Called by the metering
|
|
335
|
+
* layer after inference completes. */
|
|
336
|
+
declare function redeemPreviewCode(stacknetBaseUrl: string, code: string, tokens: number): Promise<{
|
|
337
|
+
redeemed: boolean;
|
|
338
|
+
code: string;
|
|
339
|
+
tokensUsed: number;
|
|
340
|
+
tokensRemaining: number;
|
|
341
|
+
} | {
|
|
342
|
+
error: string;
|
|
343
|
+
status: number;
|
|
344
|
+
}>;
|
|
345
|
+
/** Allowlist of admin global ids that can mint / revoke preview
|
|
346
|
+
* codes. Mirrors PREVIEW_CODE_ADMIN_GLOBAL_IDS in the Rust state
|
|
347
|
+
* machine — must stay in sync. Admin-console UI and API route guards
|
|
348
|
+
* should call `isPreviewCodeAdmin(currentUser.userId)` instead of
|
|
349
|
+
* comparing against a single constant so every entry is accepted. */
|
|
350
|
+
declare const PREVIEW_CODE_ADMIN_GLOBAL_IDS: readonly string[];
|
|
351
|
+
/** Returns true if the given global id is in the preview-code admin
|
|
352
|
+
* allowlist. */
|
|
353
|
+
declare function isPreviewCodeAdmin(globalId: string | null | undefined): boolean;
|
|
354
|
+
/** Back-compat alias for callers that only need a single canonical
|
|
355
|
+
* admin id for display/logging. Don't use for gating — use
|
|
356
|
+
* `isPreviewCodeAdmin()` to accept every entry in the allowlist. */
|
|
357
|
+
declare const PREVIEW_CODE_ADMIN_GLOBAL_ID: string;
|
|
358
|
+
|
|
359
|
+
export { type AuthCallbackOptions, type BillingProxyConfig, type CSRFConfig, type GoogleOneTapHandlerConfig, IPExtractorConfig, type MintPreviewCodeOptions, type OAuthHandlerConfig, type OTPHandlerConfig, PREVIEW_CODE_ADMIN_GLOBAL_ID, PREVIEW_CODE_ADMIN_GLOBAL_IDS, type PreviewCode, type PreviewCodesProxyConfig, type RateLimiter, type ReplayStore, ServerConfig, type ServerSession, buildStackNetHeaders, createAuthCallback, createBillingProxy, createCSRFProtection, createGoogleOneTapHandler, createInMemoryRateLimiter, createInMemoryReplayStore, createLogoutHandler, createOAuthHandlers, createOTPHandler, createSessionHandler, createWebhookHandler, extractJwt, getPreviewCode, isPreviewCodeAdmin, listPreviewCodes, mintPreviewCode, nextSecurityHeaders, redeemPreviewCode, resignForStackNet, revokePreviewCode, securityHeaders, withSecurityHeaders };
|