better-auth 1.0.21 → 1.0.22-beta.2

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.
Files changed (47) hide show
  1. package/dist/adapters/prisma.d.cts +1 -1
  2. package/dist/adapters/prisma.d.ts +1 -1
  3. package/dist/api.cjs +1 -1
  4. package/dist/api.js +1 -1
  5. package/dist/client/plugins.d.cts +1 -1
  6. package/dist/client/plugins.d.ts +1 -1
  7. package/dist/{index-Dt4lZbQi.d.ts → index-Dd3_WG87.d.ts} +105 -103
  8. package/dist/{index-CgaJXZ9u.d.cts → index-Dp04oxSM.d.cts} +105 -103
  9. package/dist/index.cjs +2 -2
  10. package/dist/index.js +2 -2
  11. package/dist/plugin/custom-session.cjs +4 -4
  12. package/dist/plugin/custom-session.js +2 -2
  13. package/dist/plugins/admin.cjs +1 -1
  14. package/dist/plugins/admin.js +1 -1
  15. package/dist/plugins/anonymous.cjs +1 -1
  16. package/dist/plugins/anonymous.js +1 -1
  17. package/dist/plugins/bearer.cjs +1 -1
  18. package/dist/plugins/bearer.js +1 -1
  19. package/dist/plugins/email-otp.cjs +1 -1
  20. package/dist/plugins/email-otp.js +1 -1
  21. package/dist/plugins/generic-oauth.cjs +1 -1
  22. package/dist/plugins/generic-oauth.js +1 -1
  23. package/dist/plugins/jwt.cjs +2 -2
  24. package/dist/plugins/jwt.js +2 -2
  25. package/dist/plugins/multi-session.cjs +1 -1
  26. package/dist/plugins/multi-session.js +1 -1
  27. package/dist/plugins/one-tap.cjs +1 -1
  28. package/dist/plugins/one-tap.js +1 -1
  29. package/dist/plugins/open-api.cjs +1 -1
  30. package/dist/plugins/open-api.js +1 -1
  31. package/dist/plugins/organization.cjs +4 -4
  32. package/dist/plugins/organization.d.cts +1 -1
  33. package/dist/plugins/organization.d.ts +1 -1
  34. package/dist/plugins/organization.js +2 -2
  35. package/dist/plugins/passkey.cjs +1 -1
  36. package/dist/plugins/passkey.js +1 -1
  37. package/dist/plugins/phone-number.cjs +1 -1
  38. package/dist/plugins/phone-number.js +1 -1
  39. package/dist/plugins/two-factor.cjs +1 -1
  40. package/dist/plugins/two-factor.js +1 -1
  41. package/dist/plugins/username.cjs +1 -1
  42. package/dist/plugins/username.js +1 -1
  43. package/dist/plugins.cjs +3 -3
  44. package/dist/plugins.d.cts +1 -1
  45. package/dist/plugins.d.ts +1 -1
  46. package/dist/plugins.js +4 -4
  47. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  import{z as u}from"zod";import{APIError as Ga,createRouter as Wa,getCookie as Za,getSignedCookie as Qa,setCookie as Ka,setSignedCookie as Ja}from"better-call";import{APIError as et}from"better-call";import{createEndpointCreator as Ze,createMiddleware as ue,createMiddlewareCreator as Qe}from"better-call";var le=ue(async()=>({})),$=Qe({use:[le,ue(async()=>({}))]}),p=Ze({use:[le]});function ne(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function Ke(e){let t="";for(let r=0;r<e.length;r++)t+=ne(e[r]);return t}function me(e,t=!0){if(Array.isArray(e))return`(?:${e.map(m=>`^${me(m,t)}$`).join("|")})`;let r="",n="",o=".";t===!0?(r="/",n="[/\\\\]",o="[^/\\\\]"):t&&(r=t,n=Ke(r),n.length>1?(n=`(?:${n})`,o=`((?!${n}).)`):o=`[^${n}]`);let s=t?`${n}+?`:"",i=t?`${n}*?`:"",d=t?e.split(r):[e],a="";for(let c=0;c<d.length;c++){let m=d[c],g=d[c+1],R="";if(!(!m&&c>0)){if(t&&(c===d.length-1?R=i:g!=="**"?R=s:R=""),t&&m==="**"){R&&(a+=c===0?"":R,a+=`(?:${o}*?${R})*?`);continue}for(let w=0;w<m.length;w++){let b=m[w];b==="\\"?w<m.length-1&&(a+=ne(m[w+1]),w++):b==="?"?a+=o:b==="*"?a+=`${o}*?`:a+=ne(b)}a+=R}}return a}function Je(e,t){if(typeof t!="string")throw new TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function se(e,t){if(typeof e!="string"&&!Array.isArray(e))throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if((typeof t=="string"||typeof t=="boolean")&&(t={separator:t}),arguments.length===2&&!(typeof t>"u"||typeof t=="object"&&t!==null&&!Array.isArray(t)))throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if(t=t||{},t.separator==="\\")throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let r=me(e,t.separator),n=new RegExp(`^${r}$`,t.flags),o=Je.bind(null,n);return o.options=t,o.pattern=e,o.regexp=n,o}var Q=Object.create(null),M=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Q:globalThis),fe=new Proxy(Q,{get(e,t){return M()[t]??Q[t]},has(e,t){let r=M();return t in r||t in Q},set(e,t,r){let n=M(!0);return n[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=M(!0);return delete r[t],!0},ownKeys(){let e=M(!0);return Object.keys(e)}});function Ye(e){return e?e!=="false":!1}var ie=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var ae=ie==="dev"||ie==="development",Xe=ie==="test"||Ye(fe.TEST);var q=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function ge(e){try{return new URL(e).origin}catch{return null}}function he(e){return e.includes("://")?new URL(e).host:e}var tt=$(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:n}=e,o=e.headers?.get("origin")||e.headers?.get("referer")||"",s=t?.callbackURL||r?.callbackURL,i=t?.redirectTo,d=r?.currentURL,a=t?.errorCallbackURL,c=t?.newUserCallbackURL,m=n.trustedOrigins,g=e.headers?.has("cookie"),R=(b,_)=>b.startsWith("/")?!1:_.includes("*")?se(_)(he(b)):b.startsWith(_),w=(b,_)=>{if(!b)return;if(!m.some(re=>R(b,re)||b?.startsWith("/")&&_!=="origin"&&!b.includes(":")))throw e.context.logger.error(`Invalid ${_}: ${b}`),e.context.logger.info(`If it's a valid URL, please add ${b} to trustedOrigins in your auth config
2
- `,`Current list of trustedOrigins: ${m}`),new et("FORBIDDEN",{message:`Invalid ${_}`})};g&&!e.context.options.advanced?.disableCSRFCheck&&w(o,"origin"),s&&w(s,"callbackURL"),i&&w(i,"redirectURL"),d&&w(d,"currentURL"),a&&w(a,"errorCallbackURL"),c&&w(i,"newUserCallbackURL")});import{APIError as k}from"better-call";import{z as A}from"zod";import{TimeSpan as $r}from"oslo";import{base64url as st}from"oslo/encoding";import{HMAC as we,sha256 as xr}from"oslo/crypto";async function ot({value:e,secret:t}){return new we("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(n=>Buffer.from(n).toString("base64"))}function nt({value:e,signature:t,secret:r}){return new we("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var K={sign:ot,verify:nt};var T=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function U(e,t,r,n){let o=e.context.authCookies.sessionToken.options,s=r?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...o,maxAge:s,...n}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled){let d=st.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:T(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await K.sign({value:JSON.stringify(t),secret:e.context.secret})})),{includePadding:!1});if(d.length>4093)throw new q("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");e.setCookie(e.context.authCookies.sessionData.name,d,e.context.authCookies.sessionData.options)}e.context.setNewSession(t),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3))}function v(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}import{betterFetch as ut}from"@better-fetch/fetch";import{APIError as lt}from"better-call";import{decodeProtectedHeader as mt,importJWK as ft,jwtVerify as gt}from"jose";import{parseJWT as ht}from"oslo/jwt";import{sha256 as it}from"oslo/crypto";import{base64url as at}from"oslo/encoding";async function ye(e){let t=await it(new TextEncoder().encode(e));return at.encode(new Uint8Array(t),{includePadding:!1})}function J(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?T(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function y({id:e,options:t,authorizationEndpoint:r,state:n,codeVerifier:o,scopes:s,claims:i,redirectURI:d,duration:a}){let c=new URL(r);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",t.clientId),c.searchParams.set("state",n),c.searchParams.set("scope",s.join(" ")),c.searchParams.set("redirect_uri",t.redirectURI||d),o){let m=await ye(o);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",m)}if(i){let m=i.reduce((g,R)=>(g[R]=null,g),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...m}}))}return a&&c.searchParams.set("duration",a),c}import{betterFetch as dt}from"@better-fetch/fetch";async function h({code:e,codeVerifier:t,redirectURI:r,options:n,tokenEndpoint:o,authentication:s}){let i=new URLSearchParams,d={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),s==="basic"){let g=btoa(`${n.clientId}:${n.clientSecret}`);d.authorization=`Basic ${g}`}else i.set("client_id",n.clientId),i.set("client_secret",n.clientSecret);let{data:a,error:c}=await dt(o,{method:"POST",body:i,headers:d});if(c)throw c;return J(a)}import{generateCodeVerifier as ct,generateState as pt}from"oslo/oauth2";import{z as j}from"zod";import{APIError as be}from"better-call";async function Y(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?ge(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new be("BAD_REQUEST",{message:"callbackURL is required"});let n=ct(),o=pt(),s=JSON.stringify({callbackURL:r,codeVerifier:n,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,newUserURL:e.body?.newUserCallbackURL,link:t,expiresAt:Date.now()+10*60*1e3}),i=new Date;i.setMinutes(i.getMinutes()+10);let d=await e.context.internalAdapter.createVerificationValue({value:s,identifier:o,expiresAt:i});if(!d)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new be("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:d.identifier,codeVerifier:n}}async function Ae(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let n=j.object({callbackURL:j.string(),codeVerifier:j.string(),errorURL:j.string().optional(),newUserURL:j.string().optional(),expiresAt:j.number(),link:j.object({email:j.string(),userId:j.string()}).optional()}).parse(JSON.parse(r.value));if(n.errorURL||(n.errorURL=`${e.context.baseURL}/error`),n.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),n}var Re=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:n,redirectURI:o}){let s=n||["email","name"];return e.scope&&s.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${o||e.redirectURI}&scope=${s.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:o})=>h({code:r,codeVerifier:n,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async verifyIdToken(r,n){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,n);let o=mt(r),{kid:s,alg:i}=o;if(!s||!i)return!1;let d=await wt(s),{payload:a}=await gt(r,d,{algorithms:[i],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(c=>{a[c]!==void 0&&(a[c]=!!a[c])}),n&&a.nonce!==n?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let n=ht(r.idToken)?.payload;if(!n)return null;let o=n.user?`${n.user.name.firstName} ${n.user.name.lastName}`:n.email,s=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:o,emailVerified:!1,email:n.email,...s},data:n}}}},wt=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:n}=await ut(`${t}${r}`);if(!n?.keys)throw new lt("BAD_REQUEST",{message:"Keys not found"});let o=n.keys.find(s=>s.kid===e);if(!o)throw new Error(`JWK with kid ${e} not found`);return await ft(o,o.alg)};import{betterFetch as yt}from"@better-fetch/fetch";var Ee=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let o=r||["identify","email"];return e.scope&&o.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${o.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||n)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>h({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await yt("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(n)return null;if(r.avatar===null){let s=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${s}.png`}else{let s=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${s}`}let o=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...o},data:r}}});import{betterFetch as bt}from"@better-fetch/fetch";var Ue=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let o=r||["email","public_profile"];return e.scope&&o.push(...e.scope),await y({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:o,state:t,redirectURI:n})},validateAuthorizationCode:async({code:t,redirectURI:r})=>h({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await bt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(n)return null;let o=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...o},data:r}}});import{betterFetch as ke}from"@better-fetch/fetch";var _e=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:n,codeVerifier:o,redirectURI:s}){let i=n||["user:email"];return e.scope&&i.push(...e.scope),y({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:i,state:r,redirectURI:s})},validateAuthorizationCode:async({code:r,redirectURI:n})=>h({code:r,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:n,error:o}=await ke("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(o)return null;let s=!1;if(!n.email){let{data:d,error:a}=await ke("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(n.email=(d.find(c=>c.primary)??d[0])?.email,s=d.find(c=>c.email===n.email)?.verified??!1)}let i=await e.mapProfileToUser?.(n);return{user:{id:n.id.toString(),name:n.name||n.login,email:n.email,image:n.avatar_url,emailVerified:s,...i},data:n}}}};import{parseJWT as kt}from"oslo/jwt";import{createConsola as At}from"consola";var de=["info","success","warn","error","debug"];function Rt(e,t){return de.indexOf(t)<=de.indexOf(e)}var Et=At({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Ut=e=>{let t=e?.disabled!==!0,r=e?.level??"error",n=(o,s,i=[])=>{if(!(!t||!Rt(r,o))){if(!e||typeof e.log!="function"){Et[o]("",s,...i);return}e.log(o==="success"?"info":o,s,i)}};return Object.fromEntries(de.map(o=>[o,(...[s,...i])=>n(o,s,i)]))},P=Ut();import{betterFetch as _t}from"@better-fetch/fetch";var Te=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:o}){if(!e.clientId||!e.clientSecret)throw P.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new q("CLIENT_ID_AND_SECRET_REQUIRED");if(!n)throw new q("codeVerifier is required for Google");let s=r||["email","profile","openid"];e.scope&&s.push(...e.scope);let i=await y({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:s,state:t,codeVerifier:n,redirectURI:o});return e.accessType&&i.searchParams.set("access_type",e.accessType),e.prompt&&i.searchParams.set("prompt",e.prompt),i},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>h({code:t,codeVerifier:r,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let n=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:o}=await _t(n);return o?o.aud===e.clientId&&o.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=kt(t.idToken)?.payload,n=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...n},data:r}}});import{betterFetch as Tt}from"@better-fetch/fetch";import{parseJWT as St}from"oslo/jwt";var Se=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,n=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(o){let s=o.scopes||["openid","profile","email","User.Read"];return e.scope&&s.push(...e.scope),y({id:"microsoft",options:e,authorizationEndpoint:r,state:o.state,codeVerifier:o.codeVerifier,scopes:s,redirectURI:o.redirectURI})},validateAuthorizationCode({code:o,codeVerifier:s,redirectURI:i}){return h({code:o,codeVerifier:s,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:n})},async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);if(!o.idToken)return null;let s=St(o.idToken)?.payload,i=e.profilePhotoSize||48;await Tt(`https://graph.microsoft.com/v1.0/me/photos/${i}x${i}/$value`,{headers:{Authorization:`Bearer ${o.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let m=await a.response.clone().arrayBuffer(),g=Buffer.from(m).toString("base64");s.picture=`data:image/jpeg;base64, ${g}`}catch(c){P.error(c&&typeof c=="object"&&"name"in c?c.name:"",c)}}});let d=await e.mapProfileToUser?.(s);return{user:{id:s.sub,name:s.name,email:s.email,image:s.picture,emailVerified:!0,...d},data:s}}}};import{betterFetch as Ot}from"@better-fetch/fetch";var Oe=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:o}){let s=r||["user-read-email"];return e.scope&&s.push(...e.scope),y({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:s,state:t,codeVerifier:n,redirectURI:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>h({code:t,codeVerifier:r,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await Ot("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let o=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...o},data:r}}});var F={isAction:!1};import{nanoid as It}from"nanoid";var Ie=e=>It(e);import{parseJWT as vt}from"oslo/jwt";var ve=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let o=r||["user:read:email","openid"];return e.scope&&o.push(...e.scope),y({id:"twitch",redirectURI:n,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>h({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return P.error("No idToken found in token"),null;let n=vt(r)?.payload,o=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.preferred_username,email:n.email,image:n.picture,emailVerified:!1,...o},data:n}}});import{betterFetch as Lt}from"@better-fetch/fetch";var Le=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),y({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>h({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||n,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await Lt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let o=await e.mapProfileToUser?.(r);return{user:{id:r.data.id,name:r.data.name,email:r.data.username||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1,...o},data:r}}});import{betterFetch as Pt}from"@better-fetch/fetch";var Pe=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:n,codeVerifier:o,redirectURI:s})=>{let i=n||["account_info.read"];return e.scope&&i.push(...e.scope),await y({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:i,state:r,redirectURI:s,codeVerifier:o})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:o})=>await h({code:r,codeVerifier:n,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:n,error:o}=await Pt("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(o)return null;let s=await e.mapProfileToUser?.(n);return{user:{id:n.account_id,name:n.name?.display_name,email:n.email,emailVerified:n.email_verified||!1,image:n.profile_photo_url,...s},data:n}}}};import{betterFetch as xt}from"@better-fetch/fetch";var xe=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:n,scopes:o,redirectURI:s})=>{let i=o||["profile","email","openid"];return e.scope&&i.push(...e.scope),await y({id:"linkedin",options:e,authorizationEndpoint:t,scopes:i,state:n,redirectURI:s})},validateAuthorizationCode:async({code:n,redirectURI:o})=>await h({code:n,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:r}),async getUserInfo(n){let{data:o,error:s}=await xt("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${n.accessToken}`}});if(s)return null;let i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified||!1,image:o.picture,...i},data:o}}}};import{betterFetch as Dt}from"@better-fetch/fetch";var ce=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Ct=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ce(`${t}/oauth/authorize`),tokenEndpoint:ce(`${t}/oauth/token`),userinfoEndpoint:ce(`${t}/api/v4/user`)}},De=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:n}=Ct(e.issuer),o="gitlab";return{id:o,name:"Gitlab",createAuthorizationURL:async({state:i,scopes:d,codeVerifier:a,redirectURI:c})=>{let m=d||["read_user"];return e.scope&&m.push(...e.scope),await y({id:o,options:e,authorizationEndpoint:t,scopes:m,state:i,redirectURI:c,codeVerifier:a})},validateAuthorizationCode:async({code:i,redirectURI:d,codeVerifier:a})=>h({code:i,redirectURI:e.redirectURI||d,options:e,codeVerifier:a,tokenEndpoint:r}),async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let{data:d,error:a}=await Dt(n,{headers:{authorization:`Bearer ${i.accessToken}`}});if(a||d.state!=="active"||d.locked)return null;let c=await e.mapProfileToUser?.(d);return{user:{id:d.id.toString(),name:d.name??d.username,email:d.email,image:d.avatar_url,emailVerified:!0,...c},data:d}}}};import{betterFetch as Ce}from"@better-fetch/fetch";var Ne=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let o=r||["identity"];return e.scope&&o.push(...e.scope),y({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:o,state:t,redirectURI:n,duration:e.duration})},validateAuthorizationCode:async({code:t,redirectURI:r})=>{let n=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:e.redirectURI||r}),o={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`},{data:s,error:i}=await Ce("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:o,body:n.toString()});if(i)throw i;return J(s)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await Ce("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(n)return null;let o=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.oauth_client_id,emailVerified:r.has_verified_email,image:r.icon_img?.split("?")[0],...o},data:r}}});var Nt={apple:Re,discord:Ee,facebook:Ue,github:_e,microsoft:Se,google:Te,spotify:Oe,twitch:ve,twitter:Le,dropbox:Pe,linkedin:xe,gitlab:De,reddit:Ne},X=Object.keys(Nt);import{TimeSpan as $t}from"oslo";import{createJWT as qt,validateJWT as zt}from"oslo/jwt";import{z as x}from"zod";import{APIError as H}from"better-call";import{APIError as B}from"better-call";import{z}from"zod";function je(e){try{return JSON.parse(e)}catch{return null}}var l={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found"};var Be=()=>p("/get-session",{method:"GET",query:z.optional(z.object({disableCookieCache:z.boolean({description:"Disable cookie cache and fetch session from database"}).or(z.string().transform(e=>e==="true")).optional(),disableRefresh:z.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),n=r?je(Buffer.from(r,"base64").toString()):null;if(n&&!await K.verify({value:JSON.stringify(n.session),signature:n?.signature,secret:e.context.secret}))return v(e),e.json(null);let o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(n?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let m=n.session;if(n.expiresAt<Date.now()||m.session.expiresAt<new Date){let R=e.context.authCookies.sessionData.name;e.setCookie(R,"",{maxAge:0})}else return e.json(m)}let s=await e.context.internalAdapter.findSession(t);if(e.context.session=s,!s||s.session.expiresAt<new Date)return v(e),s&&await e.context.internalAdapter.deleteSession(s.session.token),e.json(null);if(o||e.query?.disableRefresh)return e.json(s);let i=e.context.sessionConfig.expiresIn,d=e.context.sessionConfig.updateAge;if(s.session.expiresAt.valueOf()-i*1e3+d*1e3<=Date.now()){let m=await e.context.internalAdapter.updateSession(s.session.token,{expiresAt:T(e.context.sessionConfig.expiresIn,"sec")});if(!m)return v(e),e.json(null,{status:401});let g=(m.expiresAt.valueOf()-Date.now())/1e3;return await U(e,{session:m,user:s.user},!1,{maxAge:g}),e.json({session:m,user:s.user})}return e.json(s)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new B("INTERNAL_SERVER_ERROR",{message:l.FAILED_TO_GET_SESSION})}}),C=async(e,t)=>{if(e.context.session)return e.context.session;let r=await Be()({...e,_flag:"json",headers:e.headers,query:t}).catch(n=>null);return e.context.session=r,r},N=$(async e=>{let t=await C(e);if(!t?.session)throw new B("UNAUTHORIZED");return{session:t}}),Ve=$(async e=>{let t=await C(e);if(!t?.session)throw new B("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,n=t.session.createdAt.valueOf(),o=Date.now();if(!(n+r*1e3>o))throw new B("FORBIDDEN",{message:"Session is not fresh"});return{session:t}});var jt=p("/revoke-session",{method:"POST",body:z.object({token:z.string({description:"The token to revoke"})}),use:[N],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let t=e.body.token,r=await e.context.internalAdapter.findSession(t);if(!r)throw new B("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new B("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(n){throw e.context.logger.error(n&&typeof n=="object"&&"name"in n?n.name:"",n),new B("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Bt=p("/revoke-sessions",{method:"POST",use:[N],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new B("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Vt=p("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[N],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw new B("UNAUTHORIZED");let o=(await e.context.internalAdapter.listSessions(t.user.id)).filter(s=>s.expiresAt>new Date).filter(s=>s.token!==e.context.session.session.token);return await Promise.all(o.map(s=>e.context.internalAdapter.deleteSession(s.token))),e.json({status:!0})});async function V(e,t,r){return await qt("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new $t(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Ft(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new H("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await V(e.context.secret,t.email),n=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:n,token:r},e.request)}var Mt=p("/send-verification-email",{method:"POST",query:x.object({currentURL:x.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:x.object({email:x.string({description:"The email to send the verification email to"}).email(),callbackURL:x.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new H("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new H("BAD_REQUEST",{message:l.USER_NOT_FOUND});return await Ft(e,r.user),e.json({status:!0})}),Ht=p("/verify-email",{method:"GET",query:x.object({token:x.string({description:"The token to verify the email"}),callbackURL:x.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(d){throw e.query.callbackURL?e.query.callbackURL.includes("?")?e.redirect(`${e.query.callbackURL}&error=${d}`):e.redirect(`${e.query.callbackURL}?error=${d}`):new H("UNAUTHORIZED",{message:d})}let{token:r}=e.query,n;try{n=await zt("HS256",Buffer.from(e.context.secret),r)}catch(d){return e.context.logger.error("Failed to verify email",d),t("invalid_token")}let s=x.object({email:x.string().email(),updateTo:x.string().optional()}).parse(n.payload),i=await e.context.internalAdapter.findUserByEmail(s.email);if(!i)return t("user_not_found");if(s.updateTo){let d=await C(e);if(!d){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(d.user.email!==s.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(s.email,{email:s.updateTo,emailVerified:!1}),c=await V(e.context.secret,s.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${c}`,token:c},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(s.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await C(e)){let a=await e.context.internalAdapter.createSession(i.user.id,e.request);if(!a)throw new H("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await U(e,{session:a,user:i.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function ee(e,{userInfo:t,account:r,callbackURL:n}){let o=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw P.error(`Better auth was unable to query your database.
2
+ `,`Current list of trustedOrigins: ${m}`),new et("FORBIDDEN",{message:`Invalid ${_}`})};g&&!e.context.options.advanced?.disableCSRFCheck&&w(o,"origin"),s&&w(s,"callbackURL"),i&&w(i,"redirectURL"),d&&w(d,"currentURL"),a&&w(a,"errorCallbackURL"),c&&w(i,"newUserCallbackURL")});import{APIError as k}from"better-call";import{z as A}from"zod";import{TimeSpan as $r}from"oslo";import{base64url as st}from"oslo/encoding";import{HMAC as we,sha256 as xr}from"oslo/crypto";async function ot({value:e,secret:t}){return new we("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(n=>Buffer.from(n).toString("base64"))}function nt({value:e,signature:t,secret:r}){return new we("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var K={sign:ot,verify:nt};var T=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function U(e,t,r,n){let o=e.context.authCookies.sessionToken.options,s=r?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...o,maxAge:s,...n}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled){let d=st.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:T(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await K.sign({value:JSON.stringify(t),secret:e.context.secret})})),{includePadding:!1});if(d.length>4093)throw new q("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");e.setCookie(e.context.authCookies.sessionData.name,d,e.context.authCookies.sessionData.options)}e.context.setNewSession(t),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3))}function v(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}import{betterFetch as ut}from"@better-fetch/fetch";import{APIError as lt}from"better-call";import{decodeProtectedHeader as mt,importJWK as ft,jwtVerify as gt}from"jose";import{parseJWT as ht}from"oslo/jwt";import{sha256 as it}from"oslo/crypto";import{base64url as at}from"oslo/encoding";async function ye(e){let t=await it(new TextEncoder().encode(e));return at.encode(new Uint8Array(t),{includePadding:!1})}function J(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?T(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function y({id:e,options:t,authorizationEndpoint:r,state:n,codeVerifier:o,scopes:s,claims:i,redirectURI:d,duration:a}){let c=new URL(r);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",t.clientId),c.searchParams.set("state",n),c.searchParams.set("scope",s.join(" ")),c.searchParams.set("redirect_uri",t.redirectURI||d),o){let m=await ye(o);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",m)}if(i){let m=i.reduce((g,R)=>(g[R]=null,g),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...m}}))}return a&&c.searchParams.set("duration",a),c}import{betterFetch as dt}from"@better-fetch/fetch";async function h({code:e,codeVerifier:t,redirectURI:r,options:n,tokenEndpoint:o,authentication:s}){let i=new URLSearchParams,d={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),s==="basic"){let g=btoa(`${n.clientId}:${n.clientSecret}`);d.authorization=`Basic ${g}`}else i.set("client_id",n.clientId),i.set("client_secret",n.clientSecret);let{data:a,error:c}=await dt(o,{method:"POST",body:i,headers:d});if(c)throw c;return J(a)}import{generateCodeVerifier as ct,generateState as pt}from"oslo/oauth2";import{z as j}from"zod";import{APIError as be}from"better-call";async function Y(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?ge(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new be("BAD_REQUEST",{message:"callbackURL is required"});let n=ct(),o=pt(),s=JSON.stringify({callbackURL:r,codeVerifier:n,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,newUserURL:e.body?.newUserCallbackURL,link:t,expiresAt:Date.now()+10*60*1e3}),i=new Date;i.setMinutes(i.getMinutes()+10);let d=await e.context.internalAdapter.createVerificationValue({value:s,identifier:o,expiresAt:i});if(!d)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new be("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:d.identifier,codeVerifier:n}}async function Ae(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let n=j.object({callbackURL:j.string(),codeVerifier:j.string(),errorURL:j.string().optional(),newUserURL:j.string().optional(),expiresAt:j.number(),link:j.object({email:j.string(),userId:j.string()}).optional()}).parse(JSON.parse(r.value));if(n.errorURL||(n.errorURL=`${e.context.baseURL}/error`),n.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),n}var Re=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:n,redirectURI:o}){let s=n||["email","name"];return e.scope&&s.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${o||e.redirectURI}&scope=${s.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:o})=>h({code:r,codeVerifier:n,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async verifyIdToken(r,n){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,n);let o=mt(r),{kid:s,alg:i}=o;if(!s||!i)return!1;let d=await wt(s),{payload:a}=await gt(r,d,{algorithms:[i],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(c=>{a[c]!==void 0&&(a[c]=!!a[c])}),n&&a.nonce!==n?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let n=ht(r.idToken)?.payload;if(!n)return null;let o=n.user?`${n.user.name.firstName} ${n.user.name.lastName}`:n.email,s=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:o,emailVerified:!1,email:n.email,...s},data:n}}}},wt=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:n}=await ut(`${t}${r}`);if(!n?.keys)throw new lt("BAD_REQUEST",{message:"Keys not found"});let o=n.keys.find(s=>s.kid===e);if(!o)throw new Error(`JWK with kid ${e} not found`);return await ft(o,o.alg)};import{betterFetch as yt}from"@better-fetch/fetch";var Ee=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let o=r||["identify","email"];return e.scope&&o.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${o.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||n)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>h({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await yt("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(n)return null;if(r.avatar===null){let s=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${s}.png`}else{let s=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${s}`}let o=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...o},data:r}}});import{betterFetch as bt}from"@better-fetch/fetch";var Ue=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let o=r||["email","public_profile"];return e.scope&&o.push(...e.scope),await y({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:o,state:t,redirectURI:n})},validateAuthorizationCode:async({code:t,redirectURI:r})=>h({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await bt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(n)return null;let o=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...o},data:r}}});import{betterFetch as ke}from"@better-fetch/fetch";var _e=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:n,codeVerifier:o,redirectURI:s}){let i=n||["user:email"];return e.scope&&i.push(...e.scope),y({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:i,state:r,redirectURI:s})},validateAuthorizationCode:async({code:r,redirectURI:n})=>h({code:r,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:n,error:o}=await ke("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(o)return null;let s=!1;if(!n.email){let{data:d,error:a}=await ke("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(n.email=(d.find(c=>c.primary)??d[0])?.email,s=d.find(c=>c.email===n.email)?.verified??!1)}let i=await e.mapProfileToUser?.(n);return{user:{id:n.id.toString(),name:n.name||n.login,email:n.email,image:n.avatar_url,emailVerified:s,...i},data:n}}}};import{parseJWT as kt}from"oslo/jwt";import{createConsola as At}from"consola";var de=["info","success","warn","error","debug"];function Rt(e,t){return de.indexOf(t)<=de.indexOf(e)}var Et=At({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Ut=e=>{let t=e?.disabled!==!0,r=e?.level??"error",n=(o,s,i=[])=>{if(!(!t||!Rt(r,o))){if(!e||typeof e.log!="function"){Et[o]("",s,...i);return}e.log(o==="success"?"info":o,s,i)}};return Object.fromEntries(de.map(o=>[o,(...[s,...i])=>n(o,s,i)]))},P=Ut();import{betterFetch as _t}from"@better-fetch/fetch";var Te=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:o}){if(!e.clientId||!e.clientSecret)throw P.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new q("CLIENT_ID_AND_SECRET_REQUIRED");if(!n)throw new q("codeVerifier is required for Google");let s=r||["email","profile","openid"];e.scope&&s.push(...e.scope);let i=await y({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:s,state:t,codeVerifier:n,redirectURI:o});return e.accessType&&i.searchParams.set("access_type",e.accessType),e.prompt&&i.searchParams.set("prompt",e.prompt),i},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>h({code:t,codeVerifier:r,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let n=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:o}=await _t(n);return o?o.aud===e.clientId&&o.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=kt(t.idToken)?.payload,n=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...n},data:r}}});import{betterFetch as Tt}from"@better-fetch/fetch";import{parseJWT as St}from"oslo/jwt";var Se=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,n=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(o){let s=o.scopes||["openid","profile","email","User.Read"];return e.scope&&s.push(...e.scope),y({id:"microsoft",options:e,authorizationEndpoint:r,state:o.state,codeVerifier:o.codeVerifier,scopes:s,redirectURI:o.redirectURI})},validateAuthorizationCode({code:o,codeVerifier:s,redirectURI:i}){return h({code:o,codeVerifier:s,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:n})},async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);if(!o.idToken)return null;let s=St(o.idToken)?.payload,i=e.profilePhotoSize||48;await Tt(`https://graph.microsoft.com/v1.0/me/photos/${i}x${i}/$value`,{headers:{Authorization:`Bearer ${o.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let m=await a.response.clone().arrayBuffer(),g=Buffer.from(m).toString("base64");s.picture=`data:image/jpeg;base64, ${g}`}catch(c){P.error(c&&typeof c=="object"&&"name"in c?c.name:"",c)}}});let d=await e.mapProfileToUser?.(s);return{user:{id:s.sub,name:s.name,email:s.email,image:s.picture,emailVerified:!0,...d},data:s}}}};import{betterFetch as Ot}from"@better-fetch/fetch";var Oe=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:n,redirectURI:o}){let s=r||["user-read-email"];return e.scope&&s.push(...e.scope),y({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:s,state:t,codeVerifier:n,redirectURI:o})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>h({code:t,codeVerifier:r,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await Ot("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let o=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...o},data:r}}});var F={isAction:!1};import{nanoid as It}from"nanoid";var Ie=e=>It(e);import{parseJWT as vt}from"oslo/jwt";var ve=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let o=r||["user:read:email","openid"];return e.scope&&o.push(...e.scope),y({id:"twitch",redirectURI:n,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>h({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return P.error("No idToken found in token"),null;let n=vt(r)?.payload,o=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.preferred_username,email:n.email,image:n.picture,emailVerified:!1,...o},data:n}}});import{betterFetch as Lt}from"@better-fetch/fetch";var Le=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),y({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:n})=>h({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||n,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await Lt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let o=await e.mapProfileToUser?.(r);return{user:{id:r.data.id,name:r.data.name,email:r.data.username||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1,...o},data:r}}});import{betterFetch as Pt}from"@better-fetch/fetch";var Pe=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:n,codeVerifier:o,redirectURI:s})=>{let i=n||["account_info.read"];return e.scope&&i.push(...e.scope),await y({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:i,state:r,redirectURI:s,codeVerifier:o})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:o})=>await h({code:r,codeVerifier:n,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:n,error:o}=await Pt("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(o)return null;let s=await e.mapProfileToUser?.(n);return{user:{id:n.account_id,name:n.name?.display_name,email:n.email,emailVerified:n.email_verified||!1,image:n.profile_photo_url,...s},data:n}}}};import{betterFetch as xt}from"@better-fetch/fetch";var xe=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:n,scopes:o,redirectURI:s})=>{let i=o||["profile","email","openid"];return e.scope&&i.push(...e.scope),await y({id:"linkedin",options:e,authorizationEndpoint:t,scopes:i,state:n,redirectURI:s})},validateAuthorizationCode:async({code:n,redirectURI:o})=>await h({code:n,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:r}),async getUserInfo(n){let{data:o,error:s}=await xt("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${n.accessToken}`}});if(s)return null;let i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified||!1,image:o.picture,...i},data:o}}}};import{betterFetch as Dt}from"@better-fetch/fetch";var ce=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Ct=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ce(`${t}/oauth/authorize`),tokenEndpoint:ce(`${t}/oauth/token`),userinfoEndpoint:ce(`${t}/api/v4/user`)}},De=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:n}=Ct(e.issuer),o="gitlab";return{id:o,name:"Gitlab",createAuthorizationURL:async({state:i,scopes:d,codeVerifier:a,redirectURI:c})=>{let m=d||["read_user"];return e.scope&&m.push(...e.scope),await y({id:o,options:e,authorizationEndpoint:t,scopes:m,state:i,redirectURI:c,codeVerifier:a})},validateAuthorizationCode:async({code:i,redirectURI:d,codeVerifier:a})=>h({code:i,redirectURI:e.redirectURI||d,options:e,codeVerifier:a,tokenEndpoint:r}),async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let{data:d,error:a}=await Dt(n,{headers:{authorization:`Bearer ${i.accessToken}`}});if(a||d.state!=="active"||d.locked)return null;let c=await e.mapProfileToUser?.(d);return{user:{id:d.id.toString(),name:d.name??d.username,email:d.email,image:d.avatar_url,emailVerified:!0,...c},data:d}}}};import{betterFetch as Ce}from"@better-fetch/fetch";var Ne=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:n}){let o=r||["identity"];return e.scope&&o.push(...e.scope),y({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:o,state:t,redirectURI:n,duration:e.duration})},validateAuthorizationCode:async({code:t,redirectURI:r})=>{let n=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:e.redirectURI||r}),o={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`},{data:s,error:i}=await Ce("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:o,body:n.toString()});if(i)throw i;return J(s)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:n}=await Ce("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(n)return null;let o=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.oauth_client_id,emailVerified:r.has_verified_email,image:r.icon_img?.split("?")[0],...o},data:r}}});var Nt={apple:Re,discord:Ee,facebook:Ue,github:_e,microsoft:Se,google:Te,spotify:Oe,twitch:ve,twitter:Le,dropbox:Pe,linkedin:xe,gitlab:De,reddit:Ne},X=Object.keys(Nt);import{TimeSpan as $t}from"oslo";import{createJWT as qt,validateJWT as zt}from"oslo/jwt";import{z as x}from"zod";import{APIError as H}from"better-call";import{APIError as B}from"better-call";import{z}from"zod";function je(e){try{return JSON.parse(e)}catch{return null}}var l={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found"};var Be=()=>p("/get-session",{method:"GET",query:z.optional(z.object({disableCookieCache:z.boolean({description:"Disable cookie cache and fetch session from database"}).or(z.string().transform(e=>e==="true")).optional(),disableRefresh:z.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),n=r?je(Buffer.from(r,"base64").toString()):null;if(n&&!await K.verify({value:JSON.stringify(n.session),signature:n?.signature,secret:e.context.secret}))return v(e),e.json(null);let o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(n?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let m=n.session;if(n.expiresAt<Date.now()||m.session.expiresAt<new Date){let R=e.context.authCookies.sessionData.name;e.setCookie(R,"",{maxAge:0})}else return e.json(m)}let s=await e.context.internalAdapter.findSession(t);if(e.context.session=s,!s||s.session.expiresAt<new Date)return v(e),s&&await e.context.internalAdapter.deleteSession(s.session.token),e.json(null);if(o||e.query?.disableRefresh)return e.json(s);let i=e.context.sessionConfig.expiresIn,d=e.context.sessionConfig.updateAge;if(s.session.expiresAt.valueOf()-i*1e3+d*1e3<=Date.now()){let m=await e.context.internalAdapter.updateSession(s.session.token,{expiresAt:T(e.context.sessionConfig.expiresIn,"sec")});if(!m)return v(e),e.json(null,{status:401});let g=(m.expiresAt.valueOf()-Date.now())/1e3;return await U(e,{session:m,user:s.user},!1,{maxAge:g}),e.json({session:m,user:s.user})}return e.json(s)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new B("INTERNAL_SERVER_ERROR",{message:l.FAILED_TO_GET_SESSION})}}),C=async(e,t)=>{if(e.context.session)return e.context.session;let r=await Be()({...e,_flag:"json",headers:e.headers,query:t}).catch(n=>null);return e.context.session=r,r},N=$(async e=>{let t=await C(e);if(!t?.session)throw new B("UNAUTHORIZED");return{session:t}}),Ve=$(async e=>{let t=await C(e);if(!t?.session)throw new B("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,n=t.session.updatedAt?.valueOf()||t.session.createdAt.valueOf();if(!(Date.now()-n<r*1e3))throw new B("FORBIDDEN",{message:"Session is not fresh"});return{session:t}});var jt=p("/revoke-session",{method:"POST",body:z.object({token:z.string({description:"The token to revoke"})}),use:[N],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let t=e.body.token,r=await e.context.internalAdapter.findSession(t);if(!r)throw new B("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new B("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(n){throw e.context.logger.error(n&&typeof n=="object"&&"name"in n?n.name:"",n),new B("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Bt=p("/revoke-sessions",{method:"POST",use:[N],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new B("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Vt=p("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[N],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw new B("UNAUTHORIZED");let o=(await e.context.internalAdapter.listSessions(t.user.id)).filter(s=>s.expiresAt>new Date).filter(s=>s.token!==e.context.session.session.token);return await Promise.all(o.map(s=>e.context.internalAdapter.deleteSession(s.token))),e.json({status:!0})});async function V(e,t,r){return await qt("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new $t(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Ft(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new H("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await V(e.context.secret,t.email),n=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:n,token:r},e.request)}var Mt=p("/send-verification-email",{method:"POST",query:x.object({currentURL:x.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:x.object({email:x.string({description:"The email to send the verification email to"}).email(),callbackURL:x.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new H("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new H("BAD_REQUEST",{message:l.USER_NOT_FOUND});return await Ft(e,r.user),e.json({status:!0})}),Ht=p("/verify-email",{method:"GET",query:x.object({token:x.string({description:"The token to verify the email"}),callbackURL:x.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(d){throw e.query.callbackURL?e.query.callbackURL.includes("?")?e.redirect(`${e.query.callbackURL}&error=${d}`):e.redirect(`${e.query.callbackURL}?error=${d}`):new H("UNAUTHORIZED",{message:d})}let{token:r}=e.query,n;try{n=await zt("HS256",Buffer.from(e.context.secret),r)}catch(d){return e.context.logger.error("Failed to verify email",d),t("invalid_token")}let s=x.object({email:x.string().email(),updateTo:x.string().optional()}).parse(n.payload),i=await e.context.internalAdapter.findUserByEmail(s.email);if(!i)return t("user_not_found");if(s.updateTo){let d=await C(e);if(!d){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(d.user.email!==s.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(s.email,{email:s.updateTo,emailVerified:!1}),c=await V(e.context.secret,s.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${c}`,token:c},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(s.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await C(e)){let a=await e.context.internalAdapter.createSession(i.user.id,e.request);if(!a)throw new H("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await U(e,{session:a,user:i.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function ee(e,{userInfo:t,account:r,callbackURL:n}){let o=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw P.error(`Better auth was unable to query your database.
3
3
  Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),s=o?.user,i=!s;if(o){let a=o.accounts.find(c=>c.providerId===r.providerId);if(a){let c=Object.fromEntries(Object.entries({accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([m,g])=>g!==void 0));Object.keys(c).length>0&&await e.context.internalAdapter.updateAccount(a.id,c)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return ae&&P.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),userId:o.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope})}catch(g){return P.error("Unable to link account",g),{error:"unable to link account",data:null}}s=await e.context.internalAdapter.updateUser(o.user.id,{...t,updatedAt:new Date})}}else if(s=await e.context.internalAdapter.createOAuthUser({...t,email:t.email.toLowerCase(),id:void 0},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:t.id.toString()}).then(a=>a?.user),!t.emailVerified&&s&&e.context.options.emailVerification?.sendOnSignUp){let a=await V(e.context.secret,s.email),c=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${n}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:s,url:c,token:a},e.request)}if(!s)return{error:"unable to create user",data:null,isRegister:!1};let d=await e.context.internalAdapter.createSession(s.id,e.request);return d?{data:{session:d,user:s},error:null,isRegister:i}:{error:"unable to create session",data:null,isRegister:!1}}var Gt=p("/sign-in/social",{method:"POST",query:A.object({currentURL:A.string().optional()}).optional(),body:A.object({callbackURL:A.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:A.string().optional(),errorCallbackURL:A.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:A.enum(X,{description:"OAuth2 provider to use"}),disableRedirect:A.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:A.optional(A.object({token:A.string({description:"ID token from the provider"}),nonce:A.string({description:"Nonce used to generate the token"}).optional(),accessToken:A.string({description:"Access token from the provider"}).optional(),refreshToken:A.string({description:"Refresh token from the provider"}).optional(),expiresAt:A.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(s=>s.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new k("NOT_FOUND",{message:l.PROVIDER_NOT_FOUND});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new k("NOT_FOUND",{message:l.ID_TOKEN_NOT_SUPPORTED});let{token:s,nonce:i}=e.body.idToken;if(!await t.verifyIdToken(s,i))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new k("UNAUTHORIZED",{message:l.INVALID_TOKEN});let a=await t.getUserInfo({idToken:s,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new k("UNAUTHORIZED",{message:l.FAILED_TO_GET_USER_INFO});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new k("UNAUTHORIZED",{message:l.USER_EMAIL_NOT_FOUND});let c=await ee(e,{userInfo:{email:a.user.email,id:a.user.id,name:a.user.name||"",image:a.user.image,emailVerified:a.user.emailVerified||!1},account:{providerId:t.id,accountId:a.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new k("UNAUTHORIZED",{message:c.error});return await U(e,c.data),e.json({session:c.data.session,user:c.data.user,url:void 0,redirect:!1})}let{codeVerifier:r,state:n}=await Y(e),o=await t.createAuthorizationURL({state:n,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:o.toString(),redirect:!e.body.disableRedirect})}),Wt=p("/sign-in/email",{method:"POST",body:A.object({email:A.string({description:"Email of the user"}),password:A.string({description:"Password of the user"}),callbackURL:A.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:A.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new k("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!A.string().email().safeParse(t).success)throw new k("BAD_REQUEST",{message:l.INVALID_EMAIL});let o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new k("UNAUTHORIZED",{message:l.INVALID_EMAIL_OR_PASSWORD});let s=o.accounts.find(c=>c.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new k("UNAUTHORIZED",{message:l.INVALID_EMAIL_OR_PASSWORD});let i=s?.password;if(!i)throw e.context.logger.error("Password not found",{email:t}),new k("UNAUTHORIZED",{message:l.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:i,password:r}))throw e.context.logger.error("Invalid password"),new k("UNAUTHORIZED",{message:l.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!o.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new k("UNAUTHORIZED",{message:l.EMAIL_NOT_VERIFIED});let c=await V(e.context.secret,o.user.email),m=`${e.context.baseURL}/verify-email?token=${c}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:o.user,url:m,token:c},e.request),e.context.logger.error("Email not verified",{email:t}),new k("FORBIDDEN",{message:l.EMAIL_NOT_VERIFIED})}let a=await e.context.internalAdapter.createSession(o.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new k("UNAUTHORIZED",{message:l.FAILED_TO_CREATE_SESSION});return await U(e,{session:a,user:o.user},e.body.rememberMe===!1),e.json({user:{id:o.user.id,email:o.user.email,name:o.user.name,image:o.user.image,emailVerified:o.user.emailVerified,createdAt:o.user.createdAt,updatedAt:o.user.updatedAt},redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as G}from"zod";var te=G.object({code:G.string().optional(),error:G.string().optional(),error_description:G.string().optional(),state:G.string().optional()}),Zt=p("/callback/:id",{method:["GET","POST"],body:te.optional(),query:te.optional(),metadata:F},async e=>{let t;try{if(e.method==="GET")t=te.parse(e.query);else if(e.method==="POST")t=te.parse(e.body);else throw new Error("Unsupported method")}catch(I){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",I),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:n,state:o,error_description:s}=t;if(!o)throw e.context.logger.error("State not found",n),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${n||"no_code"}&error_description=${s}`);let i=e.context.socialProviders.find(I=>I.id===e.params.id);if(!i)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:d,callbackURL:a,link:c,errorURL:m,newUserURL:g}=await Ae(e),R;try{R=await i.validateAuthorizationCode({code:r,codeVerifier:d,redirectURI:`${e.context.baseURL}/callback/${i.id}`})}catch(I){throw e.context.logger.error("",I),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let w=await i.getUserInfo(R).then(I=>I?.user);function b(I){let D=m||a||`${e.context.baseURL}/error`;throw D.includes("?")?D=`${D}&error=${I}`:D=`${D}?error=${I}`,e.redirect(D)}if(!w)return e.context.logger.error("Unable to get user info"),b("unable_to_get_user_info");if(!w.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),b("email_not_found");if(!a)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(c){if(c.email!==w.email.toLowerCase())return b("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:c.userId,providerId:i.id,accountId:w.id}))return b("unable_to_link_account");let D;try{D=a.toString()}catch{D=a}throw e.redirect(D)}let _=await ee(e,{userInfo:{...w,email:w.email,name:w.name||w.email},account:{providerId:i.id,accountId:w.id,...R,scope:R.scopes?.join(",")},callbackURL:a});if(_.error)return e.context.logger.error(_.error.split(" ").join("_")),b(_.error.split(" ").join("_"));let{session:pe,user:re}=_.data;await U(e,{session:pe,user:re});let oe;try{oe=(_.isRegister&&g||a).toString()}catch{oe=_.isRegister&&g||a}throw e.redirect(oe)});import"zod";import{APIError as Qt}from"better-call";var Kt=p("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw v(e),new Qt("BAD_REQUEST",{message:l.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(t),v(e),e.json({success:!0})});import{z as L}from"zod";import{APIError as W}from"better-call";function $e(e,t,r){let n=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([o,s])=>n.searchParams.set(o,s)),n.href}function Jt(e,t,r){let n=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([o,s])=>n.searchParams.set(o,s)),n.href}var Yt=p("/forget-password",{method:"POST",body:L.object({email:L.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:L.string({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new W("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let o=60*60*1,s=T(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||o,"sec"),i=Ie(24);await e.context.internalAdapter.createVerificationValue({value:n.user.id.toString(),identifier:`reset-password:${i}`,expiresAt:s});let d=`${e.context.baseURL}/reset-password/${i}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:n.user,url:d,token:i},e.request),e.json({status:!0})}),Xt=p("/reset-password/:token",{method:"GET",query:L.object({callbackURL:L.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect($e(e.context,r,{error:"INVALID_TOKEN"}));let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect($e(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Jt(e.context,r,{token:t}))}),er=p("/reset-password",{query:L.optional(L.object({token:L.string().optional(),currentURL:L.string().optional()})),method:"POST",body:L.object({newPassword:L.string({description:"The new password to set"}),token:L.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new W("BAD_REQUEST",{message:l.INVALID_TOKEN});let{newPassword:r}=e.body,n=e.context.password?.config.minPasswordLength,o=e.context.password?.config.maxPasswordLength;if(r.length<n)throw new W("BAD_REQUEST",{message:l.PASSWORD_TOO_SHORT});if(r.length>o)throw new W("BAD_REQUEST",{message:l.PASSWORD_TOO_LONG});let s=`reset-password:${t}`,i=await e.context.internalAdapter.findVerificationValue(s);if(!i||i.expiresAt<new Date)throw new W("BAD_REQUEST",{message:l.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(i.id);let d=i.value,a=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(d)).find(g=>g.providerId==="credential")?(await e.context.internalAdapter.updatePassword(d,a),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:d,providerId:"credential",password:a,accountId:d}),e.json({status:!0}))});import{z as S}from"zod";import{APIError as E}from"better-call";import{z as f}from"zod";import{APIError as ei}from"better-call";var ti=f.object({id:f.string(),providerId:f.string(),accountId:f.string(),userId:f.string(),accessToken:f.string().nullish(),refreshToken:f.string().nullish(),idToken:f.string().nullish(),accessTokenExpiresAt:f.date().nullish(),refreshTokenExpiresAt:f.date().nullish(),scope:f.string().nullish(),password:f.string().nullish(),createdAt:f.date().default(()=>new Date),updatedAt:f.date().default(()=>new Date)}),ri=f.object({id:f.string(),email:f.string().transform(e=>e.toLowerCase()),emailVerified:f.boolean().default(!1),name:f.string(),image:f.string().nullish(),createdAt:f.date().default(()=>new Date),updatedAt:f.date().default(()=>new Date)}),oi=f.object({id:f.string(),userId:f.string(),expiresAt:f.date(),createdAt:f.date().default(()=>new Date),updatedAt:f.date().default(()=>new Date),token:f.string(),ipAddress:f.string().nullish(),userAgent:f.string().nullish()}),ni=f.object({id:f.string(),value:f.string(),createdAt:f.date().default(()=>new Date),updatedAt:f.date().default(()=>new Date),expiresAt:f.date(),identifier:f.string()});function qe(e,t){if(!t)return e;for(let r in t){let n=t[r]?.modelName;n&&(e[r].modelName=n);for(let o in e[r].fields){let s=t[r]?.fields?.[o];s&&(e[r].fields[o].fieldName=s)}}return e}import{xchacha20poly1305 as yi}from"@noble/ciphers/chacha";import{bytesToHex as Ai,hexToBytes as Ri,utf8ToBytes as Ei}from"@noble/ciphers/utils";import{managedNonce as ki}from"@noble/ciphers/webcrypto";import{sha256 as Ti}from"oslo/crypto";import Oi from"uncrypto";import{decodeHex as ai,encodeHex as di}from"oslo/encoding";import{scryptAsync as ui}from"@noble/hashes/scrypt";import{getRandomValues as mi}from"uncrypto";import ze from"uncrypto";function tr(e){return e.toString(2).padStart(8,"0")}function rr(e){return[...e].map(t=>tr(t)).join("")}function Fe(e){return parseInt(rr(e),2)}function or(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,n=new Uint8Array(Math.ceil(t/8));ze.getRandomValues(n),r!==0&&(n[0]&=(1<<r)-1);let o=Fe(n);for(;o>=e;)ze.getRandomValues(n),r!==0&&(n[0]&=(1<<r)-1),o=Fe(n);return o}function Me(e,t){let r="";for(let n=0;n<e;n++)r+=t[or(t.length)];return r}function He(...e){let t=new Set(e),r="";for(let n of t)n==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":n==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":n==="0-9"?r+="0123456789":r+=n;return r}var sr=p("/change-password",{method:"POST",body:S.object({newPassword:S.string({description:"The new password to set"}),currentPassword:S.string({description:"The current password"}),revokeOtherSessions:S.boolean({description:"Revoke all other sessions"}).optional()}),use:[N],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:n}=e.body,o=e.context.session,s=e.context.password.config.minPasswordLength;if(t.length<s)throw e.context.logger.error("Password is too short"),new E("BAD_REQUEST",{message:l.PASSWORD_TOO_SHORT});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new E("BAD_REQUEST",{message:l.PASSWORD_TOO_LONG});let a=(await e.context.internalAdapter.findAccounts(o.user.id)).find(g=>g.providerId==="credential"&&g.password);if(!a||!a.password)throw new E("BAD_REQUEST",{message:l.CREDENTIAL_ACCOUNT_NOT_FOUND});let c=await e.context.password.hash(t);if(!await e.context.password.verify({hash:a.password,password:r}))throw new E("BAD_REQUEST",{message:l.INVALID_PASSWORD});if(await e.context.internalAdapter.updateAccount(a.id,{password:c}),n){await e.context.internalAdapter.deleteSessions(o.user.id);let g=await e.context.internalAdapter.createSession(o.user.id,e.headers);if(!g)throw new E("INTERNAL_SERVER_ERROR",{message:l.FAILED_TO_GET_SESSION});await U(e,{session:g,user:o.user})}return e.json(o.user)}),ir=p("/set-password",{method:"POST",body:S.object({newPassword:S.string()}),metadata:{SERVER_ONLY:!0},use:[N]},async e=>{let{newPassword:t}=e.body,r=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new E("BAD_REQUEST",{message:l.PASSWORD_TOO_SHORT});let o=e.context.password.config.maxPasswordLength;if(t.length>o)throw e.context.logger.error("Password is too long"),new E("BAD_REQUEST",{message:l.PASSWORD_TOO_LONG});let i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password),d=await e.context.password.hash(t);if(!i)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:d}),e.json(r.user);throw new E("BAD_REQUEST",{message:"user already has a password"})}),ar=p("/delete-user",{method:"POST",use:[Ve],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options",{session:e.context.session}),new E("NOT_FOUND");let t=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let o=Me(32,He("a-z","A-Z","0-9"));await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${o}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let s=`${e.context.baseURL}/delete-user/callback?token=${o}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:s,token:o},e.request),e.json({success:!0,message:"Verification email sent"})}let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),v(e);let n=e.context.options.user.deleteUser?.afterDelete;return n&&await n(t.user,e.request),e.json({success:!0,message:"User deleted"})}),dr=p("/delete-user/callback",{method:"GET",query:S.object({token:S.string()})},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new E("NOT_FOUND");let t=await C(e);if(!t)throw new E("NOT_FOUND",{message:l.FAILED_TO_GET_USER_INFO});let r=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!r||r.expiresAt<new Date)throw r&&await e.context.internalAdapter.deleteVerificationValue(r.id),new E("NOT_FOUND",{message:l.INVALID_TOKEN});if(r.value!==t.user.id)throw new E("NOT_FOUND",{message:l.INVALID_TOKEN});let n=e.context.options.user.deleteUser?.beforeDelete;n&&await n(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),await e.context.internalAdapter.deleteVerificationValue(r.id),v(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})}),cr=p("/change-email",{method:"POST",query:S.object({currentURL:S.string().optional()}).optional(),body:S.object({newEmail:S.string({description:"The new email to set"}).email(),callbackURL:S.string({description:"The URL to redirect to after email verification"}).optional()}),use:[N],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new E("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new E("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new E("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let o=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:o,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await V(e.context.secret,e.context.session.user.email,e.body.newEmail),n=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:n,token:r},e.request),e.json({user:null,status:!0})});var pr=(e="Unknown")=>`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
@@ -1,5 +1,5 @@
1
1
  "use strict";var Tt=Object.create;var K=Object.defineProperty;var St=Object.getOwnPropertyDescriptor;var Ot=Object.getOwnPropertyNames;var vt=Object.getPrototypeOf,It=Object.prototype.hasOwnProperty;var xt=(e,t)=>{for(var r in t)K(e,r,{get:t[r],enumerable:!0})},_e=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ot(t))!It.call(e,n)&&n!==r&&K(e,n,{get:()=>t[n],enumerable:!(o=St(t,n))||o.enumerable});return e};var le=(e,t,r)=>(r=e!=null?Tt(vt(e)):{},_e(t||!e||!e.__esModule?K(r,"default",{value:e,enumerable:!0}):r,e)),Lt=e=>_e(K({},"__esModule",{value:!0}),e);var Cr={};xt(Cr,{anonymous:()=>Pr});module.exports=Lt(Cr);var Z=require("better-call");var Ie=require("better-call");var $=require("better-call"),Te=(0,$.createMiddleware)(async()=>({})),z=(0,$.createMiddlewareCreator)({use:[Te,(0,$.createMiddleware)(async()=>({}))]}),m=(0,$.createEndpointCreator)({use:[Te]});function ue(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function Pt(e){let t="";for(let r=0;r<e.length;r++)t+=ue(e[r]);return t}function Se(e,t=!0){if(Array.isArray(e))return`(?:${e.map(l=>`^${Se(l,t)}$`).join("|")})`;let r="",o="",n=".";t===!0?(r="/",o="[/\\\\]",n="[^/\\\\]"):t&&(r=t,o=Pt(r),o.length>1?(o=`(?:${o})`,n=`((?!${o}).)`):n=`[^${o}]`);let i=t?`${o}+?`:"",s=t?`${o}*?`:"",c=t?e.split(r):[e],a="";for(let d=0;d<c.length;d++){let l=c[d],g=c[d+1],A="";if(!(!l&&d>0)){if(t&&(d===c.length-1?A=s:g!=="**"?A=i:A=""),t&&l==="**"){A&&(a+=d===0?"":A,a+=`(?:${n}*?${A})*?`);continue}for(let h=0;h<l.length;h++){let f=l[h];f==="\\"?h<l.length-1&&(a+=ue(l[h+1]),h++):f==="?"?a+=n:f==="*"?a+=`${n}*?`:a+=ue(f)}a+=A}}return a}function Ct(e,t){if(typeof t!="string")throw new TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function pe(e,t){if(typeof e!="string"&&!Array.isArray(e))throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if((typeof t=="string"||typeof t=="boolean")&&(t={separator:t}),arguments.length===2&&!(typeof t>"u"||typeof t=="object"&&t!==null&&!Array.isArray(t)))throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if(t=t||{},t.separator==="\\")throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let r=Se(e,t.separator),o=new RegExp(`^${r}$`,t.flags),n=Ct.bind(null,o);return n.options=t,n.pattern=e,n.regexp=o,n}var J=Object.create(null),Q=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?J:globalThis),Oe=new Proxy(J,{get(e,t){return Q()[t]??J[t]},has(e,t){let r=Q();return t in r||t in J},set(e,t,r){let o=Q(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=Q(!0);return delete r[t],!0},ownKeys(){let e=Q(!0);return Object.keys(e)}});function Dt(e){return e?e!=="false":!1}var me=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var fe=me==="dev"||me==="development",Nt=me==="test"||Dt(Oe.TEST);var j=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function Y(e){try{return new URL(e).origin}catch{return null}}function ve(e){return e.includes("://")?new URL(e).host:e}var jt=z(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=t?.callbackURL||r?.callbackURL,s=t?.redirectTo,c=r?.currentURL,a=t?.errorCallbackURL,d=t?.newUserCallbackURL,l=o.trustedOrigins,g=e.headers?.has("cookie"),A=(f,k)=>f.startsWith("/")?!1:k.includes("*")?pe(k)(ve(f)):f.startsWith(k),h=(f,k)=>{if(!f)return;if(!l.some(ce=>A(f,ce)||f?.startsWith("/")&&k!=="origin"&&!f.includes(":")))throw e.context.logger.error(`Invalid ${k}: ${f}`),e.context.logger.info(`If it's a valid URL, please add ${f} to trustedOrigins in your auth config
2
- `,`Current list of trustedOrigins: ${l}`),new Ie.APIError("FORBIDDEN",{message:`Invalid ${k}`})};g&&!e.context.options.advanced?.disableCSRFCheck&&h(n,"origin"),i&&h(i,"callbackURL"),s&&h(s,"redirectURL"),c&&h(c,"currentURL"),a&&h(a,"errorCallbackURL"),d&&h(s,"newUserCallbackURL")});var E=require("better-call"),b=require("zod");var zt=require("oslo"),Le=require("oslo/encoding");var X=require("oslo/crypto");async function Bt({value:e,secret:t}){return new X.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function $t({value:e,signature:t,secret:r}){return new X.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var ee={sign:Bt,verify:$t};var V=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));function xe(e){let t=new Map;return e.split(", ").forEach(o=>{let n=o.split(";").map(g=>g.trim()),[i,...s]=n,[c,...a]=i.split("="),d=a.join("=");if(!c||d===void 0)return;let l={value:d};s.forEach(g=>{let[A,...h]=g.split("="),f=h.join("="),k=A.trim().toLowerCase();switch(k){case"max-age":l["max-age"]=f?parseInt(f.trim(),10):void 0;break;case"expires":l.expires=f?new Date(f.trim()):void 0;break;case"domain":l.domain=f?f.trim():void 0;break;case"path":l.path=f?f.trim():void 0;break;case"secure":l.secure=!0;break;case"httponly":l.httponly=!0;break;case"samesite":l.samesite=f?f.trim().toLowerCase():void 0;break;default:l[k]=f?f.trim():!0;break}}),t.set(c,l)}),t}async function U(e,t,r,o){let n=e.context.authCookies.sessionToken.options,i=r?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...n,maxAge:i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled){let c=Le.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:V(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await ee.sign({value:JSON.stringify(t),secret:e.context.secret})})),{includePadding:!1});if(c.length>4093)throw new j("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");e.setCookie(e.context.authCookies.sessionData.name,c,e.context.authCookies.sessionData.options)}e.context.setNewSession(t),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3))}function x(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}var Ve=require("@better-fetch/fetch"),Be=require("better-call"),q=require("jose"),$e=require("oslo/jwt");var Pe=require("oslo/crypto"),Ce=require("oslo/encoding");async function De(e){let t=await(0,Pe.sha256)(new TextEncoder().encode(e));return Ce.base64url.encode(new Uint8Array(t),{includePadding:!1})}function te(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?V(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function y({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,redirectURI:c,duration:a}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",i.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),n){let l=await De(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((g,A)=>(g[A]=null,g),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return a&&d.searchParams.set("duration",a),d}var Ne=require("@better-fetch/fetch");async function w({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n,authentication:i}){let s=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),i==="basic"){let g=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${g}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await(0,Ne.betterFetch)(n,{method:"POST",body:s,headers:c});if(d)throw d;return te(a)}var re=require("oslo/oauth2"),L=require("zod"),ge=require("better-call");async function oe(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Y(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ge.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,re.generateCodeVerifier)(),n=(0,re.generateState)(),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,newUserURL:e.body?.newUserCallbackURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:s});if(!c)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ge.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function je(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=L.z.object({callbackURL:L.z.string(),codeVerifier:L.z.string(),errorURL:L.z.string().optional(),newUserURL:L.z.string().optional(),expiresAt:L.z.number(),link:L.z.object({email:L.z.string(),userId:L.z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var ze=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let n=(0,q.decodeProtectedHeader)(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let c=await qt(i),{payload:a}=await(0,q.jwtVerify)(r,c,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=(0,$e.parseJWT)(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email,...i},data:o}}}},qt=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,Ve.betterFetch)(`${t}${r}`);if(!o?.keys)throw new Be.APIError("BAD_REQUEST",{message:"Keys not found"});let n=o.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await(0,q.importJWK)(n,n.alg)};var qe=require("@better-fetch/fetch");var Fe=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,qe.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...n},data:r}}});var Me=require("@better-fetch/fetch");var He=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await y({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,Me.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...n},data:r}}});var he=require("@better-fetch/fetch");var Ge=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),y({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>w({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await(0,he.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:c,error:a}=await(0,he.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(c.find(d=>d.primary)??c[0])?.email,i=c.find(d=>d.email===o.email)?.verified??!1)}let s=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i,...s},data:o}}}};var Ze=require("oslo/jwt");var We=require("consola"),we=["info","success","warn","error","debug"];function Ft(e,t){return we.indexOf(t)<=we.indexOf(e)}var Mt=(0,We.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Ht=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,s=[])=>{if(!(!t||!Ft(r,n))){if(!e||typeof e.log!="function"){Mt[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(we.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},v=Ht();var Qe=require("@better-fetch/fetch"),Ke=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw v.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new j("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new j("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await y({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:n}=await(0,Qe.betterFetch)(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,Ze.parseJWT)(t.idToken)?.payload,o=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...o},data:r}}});var Je=require("@better-fetch/fetch"),Ye=require("oslo/jwt");var Xe=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),y({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return w({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=(0,Ye.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;await(0,Je.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let l=await a.response.clone().arrayBuffer(),g=Buffer.from(l).toString("base64");i.picture=`data:image/jpeg;base64, ${g}`}catch(d){v.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0,...c},data:i}}}};var et=require("@better-fetch/fetch");var tt=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),y({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,et.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...n},data:r}}});var F={isAction:!1};var rt=require("nanoid"),ot=e=>(0,rt.nanoid)(e);var nt=require("oslo/jwt");var it=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),y({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return v.error("No idToken found in token"),null;let o=(0,nt.parseJWT)(r)?.payload,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...n},data:o}}});var st=require("@better-fetch/fetch");var at=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),y({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,st.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.data.id,name:r.data.name,email:r.data.username||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1,...n},data:r}}});var ct=require("@better-fetch/fetch");var dt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await y({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await(0,ct.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...i},data:o}}}};var lt=require("@better-fetch/fetch");var ut=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await y({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await w({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await(0,lt.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(i)return null;let s=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture,...s},data:n}}}};var pt=require("@better-fetch/fetch");var ye=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Gt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ye(`${t}/oauth/authorize`),tokenEndpoint:ye(`${t}/oauth/token`),userinfoEndpoint:ye(`${t}/api/v4/user`)}},mt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Gt(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let l=c||["read_user"];return e.scope&&l.push(...e.scope),await y({id:n,options:e,authorizationEndpoint:t,scopes:l,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>w({code:s,redirectURI:e.redirectURI||c,options:e,codeVerifier:a,tokenEndpoint:r}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:c,error:a}=await(0,pt.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(a||c.state!=="active"||c.locked)return null;let d=await e.mapProfileToUser?.(c);return{user:{id:c.id.toString(),name:c.name??c.username,email:c.email,image:c.avatar_url,emailVerified:!0,...d},data:c}}}};var be=require("@better-fetch/fetch");var ft=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identity"];return e.scope&&n.push(...e.scope),y({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:n,state:t,redirectURI:o,duration:e.duration})},validateAuthorizationCode:async({code:t,redirectURI:r})=>{let o=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:e.redirectURI||r}),n={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`},{data:i,error:s}=await(0,be.betterFetch)("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:n,body:o.toString()});if(s)throw s;return te(i)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,be.betterFetch)("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.oauth_client_id,emailVerified:r.has_verified_email,image:r.icon_img?.split("?")[0],...n},data:r}}});var Wt={apple:ze,discord:Fe,facebook:He,github:Ge,microsoft:Xe,google:Ke,spotify:tt,twitch:it,twitter:at,dropbox:dt,linkedin:ut,gitlab:mt,reddit:ft},ne=Object.keys(Wt);var yt=require("oslo"),ie=require("oslo/jwt"),O=require("zod");var M=require("better-call");var P=require("better-call");var B=require("zod");function gt(e){try{return JSON.parse(e)}catch{return null}}var u={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found"};var ht=()=>m("/get-session",{method:"GET",query:B.z.optional(B.z.object({disableCookieCache:B.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(B.z.string().transform(e=>e==="true")).optional(),disableRefresh:B.z.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?gt(Buffer.from(r,"base64").toString()):null;if(o&&!await ee.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return x(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let l=o.session;if(o.expiresAt<Date.now()||l.session.expiresAt<new Date){let A=e.context.authCookies.sessionData.name;e.setCookie(A,"",{maxAge:0})}else return e.json(l)}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return x(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n||e.query?.disableRefresh)return e.json(i);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let l=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:V(e.context.sessionConfig.expiresIn,"sec")});if(!l)return x(e),e.json(null,{status:401});let g=(l.expiresAt.valueOf()-Date.now())/1e3;return await U(e,{session:l,user:i.user},!1,{maxAge:g}),e.json({session:l,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new P.APIError("INTERNAL_SERVER_ERROR",{message:u.FAILED_TO_GET_SESSION})}}),D=async(e,t)=>{if(e.context.session)return e.context.session;let r=await ht()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},C=z(async e=>{let t=await D(e);if(!t?.session)throw new P.APIError("UNAUTHORIZED");return{session:t}}),wt=z(async e=>{let t=await D(e);if(!t?.session)throw new P.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),n=Date.now();if(!(o+r*1e3>n))throw new P.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}});var Zt=m("/revoke-session",{method:"POST",body:B.z.object({token:B.z.string({description:"The token to revoke"})}),use:[C],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let t=e.body.token,r=await e.context.internalAdapter.findSession(t);if(!r)throw new P.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new P.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new P.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Qt=m("/revoke-sessions",{method:"POST",use:[C],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new P.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Kt=m("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[C],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw new P.APIError("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});async function N(e,t,r){return await(0,ie.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new yt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Jt(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new M.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await N(e.context.secret,t.email),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:r},e.request)}var Yt=m("/send-verification-email",{method:"POST",query:O.z.object({currentURL:O.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:O.z.object({email:O.z.string({description:"The email to send the verification email to"}).email(),callbackURL:O.z.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new M.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new M.APIError("BAD_REQUEST",{message:u.USER_NOT_FOUND});return await Jt(e,r.user),e.json({status:!0})}),Xt=m("/verify-email",{method:"GET",query:O.z.object({token:O.z.string({description:"The token to verify the email"}),callbackURL:O.z.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(c){throw e.query.callbackURL?e.query.callbackURL.includes("?")?e.redirect(`${e.query.callbackURL}&error=${c}`):e.redirect(`${e.query.callbackURL}?error=${c}`):new M.APIError("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await(0,ie.validateJWT)("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let i=O.z.object({email:O.z.string().email(),updateTo:O.z.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(i.email);if(!s)return t("user_not_found");if(i.updateTo){let c=await D(e);if(!c){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(c.user.email!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),d=await N(e.context.secret,i.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${d}`,token:d},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await D(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new M.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await U(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function se(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw v.error(`Better auth was unable to query your database.
2
+ `,`Current list of trustedOrigins: ${l}`),new Ie.APIError("FORBIDDEN",{message:`Invalid ${k}`})};g&&!e.context.options.advanced?.disableCSRFCheck&&h(n,"origin"),i&&h(i,"callbackURL"),s&&h(s,"redirectURL"),c&&h(c,"currentURL"),a&&h(a,"errorCallbackURL"),d&&h(s,"newUserCallbackURL")});var E=require("better-call"),b=require("zod");var zt=require("oslo"),Le=require("oslo/encoding");var X=require("oslo/crypto");async function Bt({value:e,secret:t}){return new X.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function $t({value:e,signature:t,secret:r}){return new X.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var ee={sign:Bt,verify:$t};var V=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));function xe(e){let t=new Map;return e.split(", ").forEach(o=>{let n=o.split(";").map(g=>g.trim()),[i,...s]=n,[c,...a]=i.split("="),d=a.join("=");if(!c||d===void 0)return;let l={value:d};s.forEach(g=>{let[A,...h]=g.split("="),f=h.join("="),k=A.trim().toLowerCase();switch(k){case"max-age":l["max-age"]=f?parseInt(f.trim(),10):void 0;break;case"expires":l.expires=f?new Date(f.trim()):void 0;break;case"domain":l.domain=f?f.trim():void 0;break;case"path":l.path=f?f.trim():void 0;break;case"secure":l.secure=!0;break;case"httponly":l.httponly=!0;break;case"samesite":l.samesite=f?f.trim().toLowerCase():void 0;break;default:l[k]=f?f.trim():!0;break}}),t.set(c,l)}),t}async function U(e,t,r,o){let n=e.context.authCookies.sessionToken.options,i=r?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...n,maxAge:i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled){let c=Le.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:V(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await ee.sign({value:JSON.stringify(t),secret:e.context.secret})})),{includePadding:!1});if(c.length>4093)throw new j("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");e.setCookie(e.context.authCookies.sessionData.name,c,e.context.authCookies.sessionData.options)}e.context.setNewSession(t),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3))}function x(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}var Ve=require("@better-fetch/fetch"),Be=require("better-call"),q=require("jose"),$e=require("oslo/jwt");var Pe=require("oslo/crypto"),Ce=require("oslo/encoding");async function De(e){let t=await(0,Pe.sha256)(new TextEncoder().encode(e));return Ce.base64url.encode(new Uint8Array(t),{includePadding:!1})}function te(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?V(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function y({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,redirectURI:c,duration:a}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",i.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),n){let l=await De(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((g,A)=>(g[A]=null,g),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return a&&d.searchParams.set("duration",a),d}var Ne=require("@better-fetch/fetch");async function w({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n,authentication:i}){let s=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),i==="basic"){let g=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${g}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await(0,Ne.betterFetch)(n,{method:"POST",body:s,headers:c});if(d)throw d;return te(a)}var re=require("oslo/oauth2"),L=require("zod"),ge=require("better-call");async function oe(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Y(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ge.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,re.generateCodeVerifier)(),n=(0,re.generateState)(),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,newUserURL:e.body?.newUserCallbackURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:s});if(!c)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ge.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function je(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=L.z.object({callbackURL:L.z.string(),codeVerifier:L.z.string(),errorURL:L.z.string().optional(),newUserURL:L.z.string().optional(),expiresAt:L.z.number(),link:L.z.object({email:L.z.string(),userId:L.z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var ze=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let n=(0,q.decodeProtectedHeader)(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let c=await qt(i),{payload:a}=await(0,q.jwtVerify)(r,c,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=(0,$e.parseJWT)(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email,...i},data:o}}}},qt=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,Ve.betterFetch)(`${t}${r}`);if(!o?.keys)throw new Be.APIError("BAD_REQUEST",{message:"Keys not found"});let n=o.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await(0,q.importJWK)(n,n.alg)};var qe=require("@better-fetch/fetch");var Fe=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,qe.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...n},data:r}}});var Me=require("@better-fetch/fetch");var He=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await y({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,Me.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...n},data:r}}});var he=require("@better-fetch/fetch");var Ge=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),y({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>w({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await(0,he.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:c,error:a}=await(0,he.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(c.find(d=>d.primary)??c[0])?.email,i=c.find(d=>d.email===o.email)?.verified??!1)}let s=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i,...s},data:o}}}};var Ze=require("oslo/jwt");var We=require("consola"),we=["info","success","warn","error","debug"];function Ft(e,t){return we.indexOf(t)<=we.indexOf(e)}var Mt=(0,We.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Ht=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,s=[])=>{if(!(!t||!Ft(r,n))){if(!e||typeof e.log!="function"){Mt[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(we.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},v=Ht();var Qe=require("@better-fetch/fetch"),Ke=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw v.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new j("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new j("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await y({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:n}=await(0,Qe.betterFetch)(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,Ze.parseJWT)(t.idToken)?.payload,o=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...o},data:r}}});var Je=require("@better-fetch/fetch"),Ye=require("oslo/jwt");var Xe=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),y({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return w({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=(0,Ye.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;await(0,Je.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let l=await a.response.clone().arrayBuffer(),g=Buffer.from(l).toString("base64");i.picture=`data:image/jpeg;base64, ${g}`}catch(d){v.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0,...c},data:i}}}};var et=require("@better-fetch/fetch");var tt=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),y({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,et.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...n},data:r}}});var F={isAction:!1};var rt=require("nanoid"),ot=e=>(0,rt.nanoid)(e);var nt=require("oslo/jwt");var it=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),y({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return v.error("No idToken found in token"),null;let o=(0,nt.parseJWT)(r)?.payload,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...n},data:o}}});var st=require("@better-fetch/fetch");var at=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),y({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,st.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.data.id,name:r.data.name,email:r.data.username||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1,...n},data:r}}});var ct=require("@better-fetch/fetch");var dt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await y({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await(0,ct.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...i},data:o}}}};var lt=require("@better-fetch/fetch");var ut=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await y({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await w({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await(0,lt.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(i)return null;let s=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture,...s},data:n}}}};var pt=require("@better-fetch/fetch");var ye=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Gt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ye(`${t}/oauth/authorize`),tokenEndpoint:ye(`${t}/oauth/token`),userinfoEndpoint:ye(`${t}/api/v4/user`)}},mt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Gt(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let l=c||["read_user"];return e.scope&&l.push(...e.scope),await y({id:n,options:e,authorizationEndpoint:t,scopes:l,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>w({code:s,redirectURI:e.redirectURI||c,options:e,codeVerifier:a,tokenEndpoint:r}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:c,error:a}=await(0,pt.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(a||c.state!=="active"||c.locked)return null;let d=await e.mapProfileToUser?.(c);return{user:{id:c.id.toString(),name:c.name??c.username,email:c.email,image:c.avatar_url,emailVerified:!0,...d},data:c}}}};var be=require("@better-fetch/fetch");var ft=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identity"];return e.scope&&n.push(...e.scope),y({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:n,state:t,redirectURI:o,duration:e.duration})},validateAuthorizationCode:async({code:t,redirectURI:r})=>{let o=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:e.redirectURI||r}),n={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`},{data:i,error:s}=await(0,be.betterFetch)("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:n,body:o.toString()});if(s)throw s;return te(i)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,be.betterFetch)("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.oauth_client_id,emailVerified:r.has_verified_email,image:r.icon_img?.split("?")[0],...n},data:r}}});var Wt={apple:ze,discord:Fe,facebook:He,github:Ge,microsoft:Xe,google:Ke,spotify:tt,twitch:it,twitter:at,dropbox:dt,linkedin:ut,gitlab:mt,reddit:ft},ne=Object.keys(Wt);var yt=require("oslo"),ie=require("oslo/jwt"),O=require("zod");var M=require("better-call");var P=require("better-call");var B=require("zod");function gt(e){try{return JSON.parse(e)}catch{return null}}var u={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found"};var ht=()=>m("/get-session",{method:"GET",query:B.z.optional(B.z.object({disableCookieCache:B.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(B.z.string().transform(e=>e==="true")).optional(),disableRefresh:B.z.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?gt(Buffer.from(r,"base64").toString()):null;if(o&&!await ee.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return x(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let l=o.session;if(o.expiresAt<Date.now()||l.session.expiresAt<new Date){let A=e.context.authCookies.sessionData.name;e.setCookie(A,"",{maxAge:0})}else return e.json(l)}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return x(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n||e.query?.disableRefresh)return e.json(i);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let l=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:V(e.context.sessionConfig.expiresIn,"sec")});if(!l)return x(e),e.json(null,{status:401});let g=(l.expiresAt.valueOf()-Date.now())/1e3;return await U(e,{session:l,user:i.user},!1,{maxAge:g}),e.json({session:l,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new P.APIError("INTERNAL_SERVER_ERROR",{message:u.FAILED_TO_GET_SESSION})}}),D=async(e,t)=>{if(e.context.session)return e.context.session;let r=await ht()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},C=z(async e=>{let t=await D(e);if(!t?.session)throw new P.APIError("UNAUTHORIZED");return{session:t}}),wt=z(async e=>{let t=await D(e);if(!t?.session)throw new P.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.updatedAt?.valueOf()||t.session.createdAt.valueOf();if(!(Date.now()-o<r*1e3))throw new P.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}});var Zt=m("/revoke-session",{method:"POST",body:B.z.object({token:B.z.string({description:"The token to revoke"})}),use:[C],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let t=e.body.token,r=await e.context.internalAdapter.findSession(t);if(!r)throw new P.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new P.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new P.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Qt=m("/revoke-sessions",{method:"POST",use:[C],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new P.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Kt=m("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[C],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw new P.APIError("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});async function N(e,t,r){return await(0,ie.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new yt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Jt(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new M.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await N(e.context.secret,t.email),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:r},e.request)}var Yt=m("/send-verification-email",{method:"POST",query:O.z.object({currentURL:O.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:O.z.object({email:O.z.string({description:"The email to send the verification email to"}).email(),callbackURL:O.z.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new M.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new M.APIError("BAD_REQUEST",{message:u.USER_NOT_FOUND});return await Jt(e,r.user),e.json({status:!0})}),Xt=m("/verify-email",{method:"GET",query:O.z.object({token:O.z.string({description:"The token to verify the email"}),callbackURL:O.z.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(c){throw e.query.callbackURL?e.query.callbackURL.includes("?")?e.redirect(`${e.query.callbackURL}&error=${c}`):e.redirect(`${e.query.callbackURL}?error=${c}`):new M.APIError("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await(0,ie.validateJWT)("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let i=O.z.object({email:O.z.string().email(),updateTo:O.z.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(i.email);if(!s)return t("user_not_found");if(i.updateTo){let c=await D(e);if(!c){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(c.user.email!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),d=await N(e.context.secret,i.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${d}`,token:d},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await D(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new M.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await U(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function se(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw v.error(`Better auth was unable to query your database.
3
3
  Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user,s=!i;if(n){let a=n.accounts.find(d=>d.providerId===r.providerId);if(a){let d=Object.fromEntries(Object.entries({accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([l,g])=>g!==void 0));Object.keys(d).length>0&&await e.context.internalAdapter.updateAccount(a.id,d)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return fe&&v.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),userId:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope})}catch(g){return v.error("Unable to link account",g),{error:"unable to link account",data:null}}i=await e.context.internalAdapter.updateUser(n.user.id,{...t,updatedAt:new Date})}}else if(i=await e.context.internalAdapter.createOAuthUser({...t,email:t.email.toLowerCase(),id:void 0},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:t.id.toString()}).then(a=>a?.user),!t.emailVerified&&i&&e.context.options.emailVerification?.sendOnSignUp){let a=await N(e.context.secret,i.email),d=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:d,token:a},e.request)}if(!i)return{error:"unable to create user",data:null,isRegister:!1};let c=await e.context.internalAdapter.createSession(i.id,e.request);return c?{data:{session:c,user:i},error:null,isRegister:s}:{error:"unable to create session",data:null,isRegister:!1}}var er=m("/sign-in/social",{method:"POST",query:b.z.object({currentURL:b.z.string().optional()}).optional(),body:b.z.object({callbackURL:b.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:b.z.string().optional(),errorCallbackURL:b.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:b.z.enum(ne,{description:"OAuth2 provider to use"}),disableRedirect:b.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:b.z.optional(b.z.object({token:b.z.string({description:"ID token from the provider"}),nonce:b.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:b.z.string({description:"Access token from the provider"}).optional(),refreshToken:b.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:b.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new E.APIError("NOT_FOUND",{message:u.PROVIDER_NOT_FOUND});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new E.APIError("NOT_FOUND",{message:u.ID_TOKEN_NOT_SUPPORTED});let{token:i,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new E.APIError("UNAUTHORIZED",{message:u.INVALID_TOKEN});let a=await t.getUserInfo({idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new E.APIError("UNAUTHORIZED",{message:u.FAILED_TO_GET_USER_INFO});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new E.APIError("UNAUTHORIZED",{message:u.USER_EMAIL_NOT_FOUND});let d=await se(e,{userInfo:{email:a.user.email,id:a.user.id,name:a.user.name||"",image:a.user.image,emailVerified:a.user.emailVerified||!1},account:{providerId:t.id,accountId:a.user.id,accessToken:e.body.idToken.accessToken}});if(d.error)throw new E.APIError("UNAUTHORIZED",{message:d.error});return await U(e,d.data),e.json({session:d.data.session,user:d.data.user,url:void 0,redirect:!1})}let{codeVerifier:r,state:o}=await oe(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),tr=m("/sign-in/email",{method:"POST",body:b.z.object({email:b.z.string({description:"Email of the user"}),password:b.z.string({description:"Password of the user"}),callbackURL:b.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:b.z.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new E.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!b.z.string().email().safeParse(t).success)throw new E.APIError("BAD_REQUEST",{message:u.INVALID_EMAIL});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new E.APIError("UNAUTHORIZED",{message:u.INVALID_EMAIL_OR_PASSWORD});let i=n.accounts.find(d=>d.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new E.APIError("UNAUTHORIZED",{message:u.INVALID_EMAIL_OR_PASSWORD});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new E.APIError("UNAUTHORIZED",{message:u.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new E.APIError("UNAUTHORIZED",{message:u.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new E.APIError("UNAUTHORIZED",{message:u.EMAIL_NOT_VERIFIED});let d=await N(e.context.secret,n.user.email),l=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:l,token:d},e.request),e.context.logger.error("Email not verified",{email:t}),new E.APIError("FORBIDDEN",{message:u.EMAIL_NOT_VERIFIED})}let a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new E.APIError("UNAUTHORIZED",{message:u.FAILED_TO_CREATE_SESSION});return await U(e,{session:a,user:n.user},e.body.rememberMe===!1),e.json({user:{id:n.user.id,email:n.user.email,name:n.user.name,image:n.user.image,emailVerified:n.user.emailVerified,createdAt:n.user.createdAt,updatedAt:n.user.updatedAt},redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var H=require("zod");var ae=H.z.object({code:H.z.string().optional(),error:H.z.string().optional(),error_description:H.z.string().optional(),state:H.z.string().optional()}),rr=m("/callback/:id",{method:["GET","POST"],body:ae.optional(),query:ae.optional(),metadata:F},async e=>{let t;try{if(e.method==="GET")t=ae.parse(e.query);else if(e.method==="POST")t=ae.parse(e.body);else throw new Error("Unsupported method")}catch(S){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",S),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n,error_description:i}=t;if(!n)throw e.context.logger.error("State not found",o),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}&error_description=${i}`);let s=e.context.socialProviders.find(S=>S.id===e.params.id);if(!s)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:c,callbackURL:a,link:d,errorURL:l,newUserURL:g}=await je(e),A;try{A=await s.validateAuthorizationCode({code:r,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${s.id}`})}catch(S){throw e.context.logger.error("",S),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let h=await s.getUserInfo(A).then(S=>S?.user);function f(S){let I=l||a||`${e.context.baseURL}/error`;throw I.includes("?")?I=`${I}&error=${S}`:I=`${I}?error=${S}`,e.redirect(I)}if(!h)return e.context.logger.error("Unable to get user info"),f("unable_to_get_user_info");if(!h.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),f("email_not_found");if(!a)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(d){if(d.email!==h.email.toLowerCase())return f("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:s.id,accountId:h.id}))return f("unable_to_link_account");let I;try{I=a.toString()}catch{I=a}throw e.redirect(I)}let k=await se(e,{userInfo:{...h,email:h.email,name:h.name||h.email},account:{providerId:s.id,accountId:h.id,...A,scope:A.scopes?.join(",")},callbackURL:a});if(k.error)return e.context.logger.error(k.error.split(" ").join("_")),f(k.error.split(" ").join("_"));let{session:Ue,user:ce}=k.data;await U(e,{session:Ue,user:ce});let de;try{de=(k.isRegister&&g||a).toString()}catch{de=k.isRegister&&g||a}throw e.redirect(de)});var gi=require("zod");var bt=require("better-call");var or=m("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw x(e),new bt.APIError("BAD_REQUEST",{message:u.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(t),x(e),e.json({success:!0})});var T=require("zod");var G=require("better-call");function At(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function nr(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var ir=m("/forget-password",{method:"POST",body:T.z.object({email:T.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:T.z.string({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new G.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=V(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=ot(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:i});let c=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:c,token:s},e.request),e.json({status:!0})}),sr=m("/reset-password/:token",{method:"GET",query:T.z.object({callbackURL:T.z.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(At(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(At(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(nr(e.context,r,{token:t}))}),ar=m("/reset-password",{query:T.z.optional(T.z.object({token:T.z.string().optional(),currentURL:T.z.string().optional()})),method:"POST",body:T.z.object({newPassword:T.z.string({description:"The new password to set"}),token:T.z.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new G.APIError("BAD_REQUEST",{message:u.INVALID_TOKEN});let{newPassword:r}=e.body,o=e.context.password?.config.minPasswordLength,n=e.context.password?.config.maxPasswordLength;if(r.length<o)throw new G.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_SHORT});if(r.length>n)throw new G.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_LONG});let i=`reset-password:${t}`,s=await e.context.internalAdapter.findVerificationValue(i);if(!s||s.expiresAt<new Date)throw new G.APIError("BAD_REQUEST",{message:u.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(s.id);let c=s.value,a=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(c)).find(g=>g.providerId==="credential")?(await e.context.internalAdapter.updatePassword(c,a),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:c,providerId:"credential",password:a,accountId:c}),e.json({status:!0}))});var _=require("zod");var R=require("better-call");var p=require("zod"),cr=require("better-call"),Ti=p.z.object({id:p.z.string(),providerId:p.z.string(),accountId:p.z.string(),userId:p.z.string(),accessToken:p.z.string().nullish(),refreshToken:p.z.string().nullish(),idToken:p.z.string().nullish(),accessTokenExpiresAt:p.z.date().nullish(),refreshTokenExpiresAt:p.z.date().nullish(),scope:p.z.string().nullish(),password:p.z.string().nullish(),createdAt:p.z.date().default(()=>new Date),updatedAt:p.z.date().default(()=>new Date)}),Si=p.z.object({id:p.z.string(),email:p.z.string().transform(e=>e.toLowerCase()),emailVerified:p.z.boolean().default(!1),name:p.z.string(),image:p.z.string().nullish(),createdAt:p.z.date().default(()=>new Date),updatedAt:p.z.date().default(()=>new Date)}),Oi=p.z.object({id:p.z.string(),userId:p.z.string(),expiresAt:p.z.date(),createdAt:p.z.date().default(()=>new Date),updatedAt:p.z.date().default(()=>new Date),token:p.z.string(),ipAddress:p.z.string().nullish(),userAgent:p.z.string().nullish()}),vi=p.z.object({id:p.z.string(),value:p.z.string(),createdAt:p.z.date().default(()=>new Date),updatedAt:p.z.date().default(()=>new Date),expiresAt:p.z.date(),identifier:p.z.string()});function Rt(e,t){if(!t)return e;for(let r in t){let o=t[r]?.modelName;o&&(e[r].modelName=o);for(let n in e[r].fields){let i=t[r]?.fields?.[n];i&&(e[r].fields[n].fieldName=i)}}return e}var fr=require("@noble/ciphers/chacha"),Re=require("@noble/ciphers/utils"),gr=require("@noble/ciphers/webcrypto"),hr=require("oslo/crypto"),wr=le(require("uncrypto"),1);var kt=require("oslo/encoding");var dr=require("@noble/hashes/scrypt"),lr=require("uncrypto");var Ae=le(require("uncrypto"),1);function ur(e){return e.toString(2).padStart(8,"0")}function pr(e){return[...e].map(t=>ur(t)).join("")}function Et(e){return parseInt(pr(e),2)}function mr(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,o=new Uint8Array(Math.ceil(t/8));Ae.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=Et(o);for(;n>=e;)Ae.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=Et(o);return n}function Ut(e,t){let r="";for(let o=0;o<e;o++)r+=t[mr(t.length)];return r}function _t(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}var br=m("/change-password",{method:"POST",body:_.z.object({newPassword:_.z.string({description:"The new password to set"}),currentPassword:_.z.string({description:"The current password"}),revokeOtherSessions:_.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[C],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new R.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_SHORT});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new R.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_LONG});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(g=>g.providerId==="credential"&&g.password);if(!a||!a.password)throw new R.APIError("BAD_REQUEST",{message:u.CREDENTIAL_ACCOUNT_NOT_FOUND});let d=await e.context.password.hash(t);if(!await e.context.password.verify({hash:a.password,password:r}))throw new R.APIError("BAD_REQUEST",{message:u.INVALID_PASSWORD});if(await e.context.internalAdapter.updateAccount(a.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let g=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!g)throw new R.APIError("INTERNAL_SERVER_ERROR",{message:u.FAILED_TO_GET_SESSION});await U(e,{session:g,user:n.user})}return e.json(n.user)}),Ar=m("/set-password",{method:"POST",body:_.z.object({newPassword:_.z.string()}),metadata:{SERVER_ONLY:!0},use:[C]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new R.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_SHORT});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new R.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_LONG});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password),c=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:c}),e.json(r.user);throw new R.APIError("BAD_REQUEST",{message:"user already has a password"})}),Rr=m("/delete-user",{method:"POST",use:[wt],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options",{session:e.context.session}),new R.APIError("NOT_FOUND");let t=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=Ut(32,_t("a-z","A-Z","0-9"));await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${n}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let i=`${e.context.baseURL}/delete-user/callback?token=${n}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:i,token:n},e.request),e.json({success:!0,message:"Verification email sent"})}let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),x(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})}),kr=m("/delete-user/callback",{method:"GET",query:_.z.object({token:_.z.string()})},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new R.APIError("NOT_FOUND");let t=await D(e);if(!t)throw new R.APIError("NOT_FOUND",{message:u.FAILED_TO_GET_USER_INFO});let r=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!r||r.expiresAt<new Date)throw r&&await e.context.internalAdapter.deleteVerificationValue(r.id),new R.APIError("NOT_FOUND",{message:u.INVALID_TOKEN});if(r.value!==t.user.id)throw new R.APIError("NOT_FOUND",{message:u.INVALID_TOKEN});let o=e.context.options.user.deleteUser?.beforeDelete;o&&await o(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),await e.context.internalAdapter.deleteVerificationValue(r.id),x(e);let n=e.context.options.user.deleteUser?.afterDelete;return n&&await n(t.user,e.request),e.json({success:!0,message:"User deleted"})}),Er=m("/change-email",{method:"POST",query:_.z.object({currentURL:_.z.string().optional()}).optional(),body:_.z.object({newEmail:_.z.string({description:"The new email to set"}).email(),callbackURL:_.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[C],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new R.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new R.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new R.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new R.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await N(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),e.json({user:null,status:!0})});var Ur=(e="Unknown")=>`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>