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
@@ -59,4 +59,4 @@ declare const prismaAdapter: (prisma: PrismaClient, config: PrismaConfig) => (op
59
59
  options: PrismaConfig;
60
60
  };
61
61
 
62
- export { prismaAdapter };
62
+ export { type PrismaConfig, prismaAdapter };
@@ -59,4 +59,4 @@ declare const prismaAdapter: (prisma: PrismaClient, config: PrismaConfig) => (op
59
59
  options: PrismaConfig;
60
60
  };
61
61
 
62
- export { prismaAdapter };
62
+ export { type PrismaConfig, prismaAdapter };
package/dist/api.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";var ar=Object.create;var re=Object.defineProperty;var cr=Object.getOwnPropertyDescriptor;var dr=Object.getOwnPropertyNames;var lr=Object.getPrototypeOf,ur=Object.prototype.hasOwnProperty;var pr=(e,t)=>{for(var r in t)re(e,r,{get:t[r],enumerable:!0})},tt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of dr(t))!ur.call(e,i)&&i!==r&&re(e,i,{get:()=>t[i],enumerable:!(o=cr(t,i))||o.enumerable});return e};var we=(e,t,r)=>(r=e!=null?ar(lr(e)):{},tt(t||!e||!e.__esModule?re(r,"default",{value:e,enumerable:!0}):r,e)),mr=e=>tt(re({},"__esModule",{value:!0}),e);var Wr={};pr(Wr,{APIError:()=>sr.APIError,callbackOAuth:()=>Ne,changeEmail:()=>Ze,changePassword:()=>Me,createAuthEndpoint:()=>f,createAuthMiddleware:()=>Z,createEmailVerificationToken:()=>j,deleteUser:()=>Ge,deleteUserCallback:()=>We,error:()=>Qe,forgetPassword:()=>Ve,forgetPasswordCallback:()=>Be,freshSessionMiddleware:()=>Oe,getEndpoints:()=>nr,getSession:()=>pe,getSessionFromCtx:()=>H,linkSocialAccount:()=>et,listSessions:()=>Se,listUserAccounts:()=>Xe,ok:()=>Ke,optionsMiddleware:()=>ye,originCheckMiddleware:()=>Re,resetPassword:()=>$e,revokeOtherSessions:()=>Ie,revokeSession:()=>ve,revokeSessions:()=>xe,router:()=>Gr,sendVerificationEmail:()=>Le,sendVerificationEmailFn:()=>Wt,sessionMiddleware:()=>L,setPassword:()=>He,signInEmail:()=>Ce,signInSocial:()=>De,signOut:()=>je,signUpEmail:()=>Je,updateUser:()=>Fe,verifyEmail:()=>Pe});module.exports=mr(Wr);var O=require("better-call");var at=require("better-call");var G=require("better-call"),ye=(0,G.createMiddleware)(async()=>({})),Z=(0,G.createMiddlewareCreator)({use:[ye,(0,G.createMiddleware)(async()=>({}))]}),f=(0,G.createEndpointCreator)({use:[ye]});function be(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function fr(e){let t="";for(let r=0;r<e.length;r++)t+=be(e[r]);return t}function rt(e,t=!0){if(Array.isArray(e))return`(?:${e.map(u=>`^${rt(u,t)}$`).join("|")})`;let r="",o="",i=".";t===!0?(r="/",o="[/\\\\]",i="[^/\\\\]"):t&&(r=t,o=fr(r),o.length>1?(o=`(?:${o})`,i=`((?!${o}).)`):i=`[^${o}]`);let n=t?`${o}+?`:"",s=t?`${o}*?`:"",c=t?e.split(r):[e],a="";for(let d=0;d<c.length;d++){let u=c[d],g=c[d+1],h="";if(!(!u&&d>0)){if(t&&(d===c.length-1?h=s:g!=="**"?h=n:h=""),t&&u==="**"){h&&(a+=d===0?"":h,a+=`(?:${i}*?${h})*?`);continue}for(let l=0;l<u.length;l++){let b=u[l];b==="\\"?l<u.length-1&&(a+=be(u[l+1]),l++):b==="?"?a+=i:b==="*"?a+=`${i}*?`:a+=be(b)}a+=h}}return a}function gr(e,t){if(typeof t!="string")throw new TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function oe(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=rt(e,t.separator),o=new RegExp(`^${r}$`,t.flags),i=gr.bind(null,o);return i.options=t,i.pattern=e,i.regexp=o,i}var ie=Object.create(null),te=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?ie:globalThis),ot=new Proxy(ie,{get(e,t){return te()[t]??ie[t]},has(e,t){let r=te();return t in r||t in ie},set(e,t,r){let o=te(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=te(!0);return delete r[t],!0},ownKeys(){let e=te(!0);return Object.keys(e)}});function hr(e){return e?e!=="false":!1}var Ae=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var ne=Ae==="dev"||Ae==="development",it=Ae==="test"||hr(ot.TEST);var q=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function nt(e){try{return new URL(e).origin}catch{return null}}function st(e){return e.includes("://")?new URL(e).host:e}var Re=Z(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,i=e.headers?.get("origin")||e.headers?.get("referer")||"",n=t?.callbackURL||r?.callbackURL,s=t?.redirectTo,c=r?.currentURL,a=t?.errorCallbackURL,d=t?.newUserCallbackURL,u=o.trustedOrigins,g=e.headers?.has("cookie"),h=(b,_)=>b.startsWith("/")?!1:_.includes("*")?oe(_)(st(b)):b.startsWith(_),l=(b,_)=>{if(!b)return;if(!u.some(w=>h(b,w)||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: ${u}`),new at.APIError("FORBIDDEN",{message:`Invalid ${_}`})};g&&!e.context.options.advanced?.disableCSRFCheck&&l(i,"origin"),n&&l(n,"callbackURL"),s&&l(s,"redirectURL"),c&&l(c,"currentURL"),a&&l(a,"errorCallbackURL"),d&&l(s,"newUserCallbackURL")});var v=require("better-call"),U=require("zod");var Ar=require("oslo"),ct=require("oslo/encoding");var se=require("oslo/crypto");async function yr({value:e,secret:t}){return new se.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function br({value:e,signature:t,secret:r}){return new se.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var ae={sign:yr,verify:br};var F=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function x(e,t,r,o){let i=e.context.authCookies.sessionToken.options,n=r?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:n,...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=ct.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:F(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await ae.sign({value:JSON.stringify(t),secret:e.context.secret})})),{includePadding:!1});if(c.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,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 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})}var ft=require("@better-fetch/fetch"),gt=require("better-call"),Q=require("jose"),ht=require("oslo/jwt");var dt=require("oslo/crypto"),lt=require("oslo/encoding");async function ut(e){let t=await(0,dt.sha256)(new TextEncoder().encode(e));return lt.base64url.encode(new Uint8Array(t),{includePadding:!1})}function ce(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?F(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function E({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,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",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),i){let u=await ut(i);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",u)}if(s){let u=s.reduce((g,h)=>(g[h]=null,g),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return a&&d.searchParams.set("duration",a),d}var pt=require("@better-fetch/fetch");async function k({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i,authentication:n}){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),n==="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,pt.betterFetch)(i,{method:"POST",body:s,headers:c});if(d)throw d;return ce(a)}var de=require("oslo/oauth2"),B=require("zod"),ke=require("better-call");async function le(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?nt(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ke.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,de.generateCodeVerifier)(),i=(0,de.generateState)(),n=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:n,identifier:i,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 ke.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function mt(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=B.z.object({callbackURL:B.z.string(),codeVerifier:B.z.string(),errorURL:B.z.string().optional(),newUserURL:B.z.string().optional(),expiresAt:B.z.number(),link:B.z.object({email:B.z.string(),userId:B.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 wt=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=o||["email","name"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>k({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let i=(0,Q.decodeProtectedHeader)(r),{kid:n,alg:s}=i;if(!n||!s)return!1;let c=await Rr(n),{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,ht.parseJWT)(r.idToken)?.payload;if(!o)return null;let i=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:i,emailVerified:!1,email:o.email,...n},data:o}}}},Rr=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,ft.betterFetch)(`${t}${r}`);if(!o?.keys)throw new gt.APIError("BAD_REQUEST",{message:"Keys not found"});let i=o.keys.find(n=>n.kid===e);if(!i)throw new Error(`JWK with kid ${e} not found`);return await(0,Q.importJWK)(i,i.alg)};var yt=require("@better-fetch/fetch");var bt=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.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})=>k({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,yt.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}let i=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,...i},data:r}}});var At=require("@better-fetch/fetch");var Rt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await E({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>k({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,At.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...i},data:r}}});var Ee=require("@better-fetch/fetch");var kt=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),E({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>k({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await(0,Ee.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:c,error:a}=await(0,Ee.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,n=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:n,...s},data:o}}}};var Ut=require("oslo/jwt");var Et=require("consola"),Ue=["info","success","warn","error","debug"];function kr(e,t){return Ue.indexOf(t)<=Ue.indexOf(e)}var Er=(0,Et.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Ur=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(i,n,s=[])=>{if(!(!t||!kr(r,i))){if(!e||typeof e.log!="function"){Er[i]("",n,...s);return}e.log(i==="success"?"info":i,n,s)}};return Object.fromEntries(Ue.map(i=>[i,(...[n,...s])=>o(i,n,s)]))},C=Ur();var _t=require("@better-fetch/fetch"),Tt=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw C.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(!o)throw new q("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await E({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});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})=>k({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:i}=await(0,_t.betterFetch)(o);return i?i.aud===e.clientId&&i.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,Ut.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 Ot=require("@better-fetch/fetch"),St=require("oslo/jwt");var vt=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(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),E({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return k({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);if(!i.idToken)return null;let n=(0,St.parseJWT)(i.idToken)?.payload,s=e.profilePhotoSize||48;await(0,Ot.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let u=await a.response.clone().arrayBuffer(),g=Buffer.from(u).toString("base64");n.picture=`data:image/jpeg;base64, ${g}`}catch(d){C.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0,...c},data:n}}}};var xt=require("@better-fetch/fetch");var It=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),E({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>k({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,xt.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...i},data:r}}});var K={isAction:!1};var Lt=require("nanoid"),Pt=e=>(0,Lt.nanoid)(e);var Dt=require("oslo/jwt");var Ct=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),E({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>k({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 C.error("No idToken found in token"),null;let o=(0,Dt.parseJWT)(r)?.payload,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...i},data:o}}});var Nt=require("@better-fetch/fetch");var jt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),E({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})=>k({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,Nt.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 i=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,...i},data:r}}});var Vt=require("@better-fetch/fetch");var Bt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await E({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await k({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await(0,Vt.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=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,...n},data:o}}}};var $t=require("@better-fetch/fetch");var zt=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:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await E({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await k({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await(0,$t.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(n)return null;let s=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture,...s},data:i}}}};var qt=require("@better-fetch/fetch");var _e=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),_r=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:_e(`${t}/oauth/authorize`),tokenEndpoint:_e(`${t}/oauth/token`),userinfoEndpoint:_e(`${t}/api/v4/user`)}},Ft=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=_r(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let u=c||["read_user"];return e.scope&&u.push(...e.scope),await E({id:i,options:e,authorizationEndpoint:t,scopes:u,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>k({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,qt.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 Te=require("@better-fetch/fetch");var Mt=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identity"];return e.scope&&i.push(...e.scope),E({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:i,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}),i={"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:n,error:s}=await(0,Te.betterFetch)("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:i,body:o.toString()});if(s)throw s;return ce(n)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,Te.betterFetch)("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let i=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],...i},data:r}}});var Tr={apple:wt,discord:bt,facebook:Rt,github:kt,microsoft:vt,google:Tt,spotify:It,twitch:Ct,twitter:jt,dropbox:Bt,linkedin:zt,gitlab:Ft,reddit:Mt},ue=Object.keys(Tr);var Gt=require("oslo"),me=require("oslo/jwt"),N=require("zod");var J=require("better-call");var $=require("better-call");var M=require("zod");function Ht(e){try{return JSON.parse(e)}catch{return null}}var p={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 pe=()=>f("/get-session",{method:"GET",query:M.z.optional(M.z.object({disableCookieCache:M.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(M.z.string().transform(e=>e==="true")).optional(),disableRefresh:M.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?Ht(Buffer.from(r,"base64").toString()):null;if(o&&!await ae.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return V(e),e.json(null);let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let u=o.session;if(o.expiresAt<Date.now()||u.session.expiresAt<new Date){let h=e.context.authCookies.sessionData.name;e.setCookie(h,"",{maxAge:0})}else return e.json(u)}let n=await e.context.internalAdapter.findSession(t);if(e.context.session=n,!n||n.session.expiresAt<new Date)return V(e),n&&await e.context.internalAdapter.deleteSession(n.session.token),e.json(null);if(i||e.query?.disableRefresh)return e.json(n);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let u=await e.context.internalAdapter.updateSession(n.session.token,{expiresAt:F(e.context.sessionConfig.expiresIn,"sec")});if(!u)return V(e),e.json(null,{status:401});let g=(u.expiresAt.valueOf()-Date.now())/1e3;return await x(e,{session:u,user:n.user},!1,{maxAge:g}),e.json({session:u,user:n.user})}return e.json(n)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new $.APIError("INTERNAL_SERVER_ERROR",{message:p.FAILED_TO_GET_SESSION})}}),H=async(e,t)=>{if(e.context.session)return e.context.session;let r=await pe()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},L=Z(async e=>{let t=await H(e);if(!t?.session)throw new $.APIError("UNAUTHORIZED");return{session:t}}),Oe=Z(async e=>{let t=await H(e);if(!t?.session)throw new $.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),i=Date.now();if(!(o+r*1e3>i))throw new $.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),Se=()=>f("/list-sessions",{method:"GET",use:[L],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),ve=f("/revoke-session",{method:"POST",body:M.z.object({token:M.z.string({description:"The token to revoke"})}),use:[L],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 $.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new $.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 $.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),xe=f("/revoke-sessions",{method:"POST",use:[L],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 $.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Ie=f("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[L],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 $.APIError("UNAUTHORIZED");let i=(await e.context.internalAdapter.listSessions(t.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.token!==e.context.session.session.token);return await Promise.all(i.map(n=>e.context.internalAdapter.deleteSession(n.token))),e.json({status:!0})});async function j(e,t,r){return await(0,me.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Gt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Wt(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(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 Le=f("/send-verification-email",{method:"POST",query:N.z.object({currentURL:N.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:N.z.object({email:N.z.string({description:"The email to send the verification email to"}).email(),callbackURL:N.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 J.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 J.APIError("BAD_REQUEST",{message:p.USER_NOT_FOUND});return await Wt(e,r.user),e.json({status:!0})}),Pe=f("/verify-email",{method:"GET",query:N.z.object({token:N.z.string({description:"The token to verify the email"}),callbackURL:N.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 J.APIError("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await(0,me.validateJWT)("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let n=N.z.object({email:N.z.string().email(),updateTo:N.z.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(n.email);if(!s)return t("user_not_found");if(n.updateTo){let c=await H(e);if(!c){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(c.user.email!==n.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo,emailVerified:!1}),d=await j(e.context.secret,n.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(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await H(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new J.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await x(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 fe(e,{userInfo:t,account:r,callbackURL:o}){let i=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw C.error(`Better auth was unable to query your database.
2
+ `,`Current list of trustedOrigins: ${u}`),new at.APIError("FORBIDDEN",{message:`Invalid ${_}`})};g&&!e.context.options.advanced?.disableCSRFCheck&&l(i,"origin"),n&&l(n,"callbackURL"),s&&l(s,"redirectURL"),c&&l(c,"currentURL"),a&&l(a,"errorCallbackURL"),d&&l(s,"newUserCallbackURL")});var v=require("better-call"),U=require("zod");var Ar=require("oslo"),ct=require("oslo/encoding");var se=require("oslo/crypto");async function yr({value:e,secret:t}){return new se.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function br({value:e,signature:t,secret:r}){return new se.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var ae={sign:yr,verify:br};var F=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function x(e,t,r,o){let i=e.context.authCookies.sessionToken.options,n=r?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:n,...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=ct.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:F(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await ae.sign({value:JSON.stringify(t),secret:e.context.secret})})),{includePadding:!1});if(c.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,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 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})}var ft=require("@better-fetch/fetch"),gt=require("better-call"),Q=require("jose"),ht=require("oslo/jwt");var dt=require("oslo/crypto"),lt=require("oslo/encoding");async function ut(e){let t=await(0,dt.sha256)(new TextEncoder().encode(e));return lt.base64url.encode(new Uint8Array(t),{includePadding:!1})}function ce(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?F(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function E({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,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",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),i){let u=await ut(i);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",u)}if(s){let u=s.reduce((g,h)=>(g[h]=null,g),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return a&&d.searchParams.set("duration",a),d}var pt=require("@better-fetch/fetch");async function k({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i,authentication:n}){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),n==="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,pt.betterFetch)(i,{method:"POST",body:s,headers:c});if(d)throw d;return ce(a)}var de=require("oslo/oauth2"),B=require("zod"),ke=require("better-call");async function le(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?nt(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ke.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,de.generateCodeVerifier)(),i=(0,de.generateState)(),n=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:n,identifier:i,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 ke.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function mt(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=B.z.object({callbackURL:B.z.string(),codeVerifier:B.z.string(),errorURL:B.z.string().optional(),newUserURL:B.z.string().optional(),expiresAt:B.z.number(),link:B.z.object({email:B.z.string(),userId:B.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 wt=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=o||["email","name"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>k({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let i=(0,Q.decodeProtectedHeader)(r),{kid:n,alg:s}=i;if(!n||!s)return!1;let c=await Rr(n),{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,ht.parseJWT)(r.idToken)?.payload;if(!o)return null;let i=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:i,emailVerified:!1,email:o.email,...n},data:o}}}},Rr=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,ft.betterFetch)(`${t}${r}`);if(!o?.keys)throw new gt.APIError("BAD_REQUEST",{message:"Keys not found"});let i=o.keys.find(n=>n.kid===e);if(!i)throw new Error(`JWK with kid ${e} not found`);return await(0,Q.importJWK)(i,i.alg)};var yt=require("@better-fetch/fetch");var bt=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.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})=>k({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,yt.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}let i=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,...i},data:r}}});var At=require("@better-fetch/fetch");var Rt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await E({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>k({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,At.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...i},data:r}}});var Ee=require("@better-fetch/fetch");var kt=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),E({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>k({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await(0,Ee.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:c,error:a}=await(0,Ee.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,n=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:n,...s},data:o}}}};var Ut=require("oslo/jwt");var Et=require("consola"),Ue=["info","success","warn","error","debug"];function kr(e,t){return Ue.indexOf(t)<=Ue.indexOf(e)}var Er=(0,Et.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Ur=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(i,n,s=[])=>{if(!(!t||!kr(r,i))){if(!e||typeof e.log!="function"){Er[i]("",n,...s);return}e.log(i==="success"?"info":i,n,s)}};return Object.fromEntries(Ue.map(i=>[i,(...[n,...s])=>o(i,n,s)]))},C=Ur();var _t=require("@better-fetch/fetch"),Tt=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw C.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(!o)throw new q("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await E({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});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})=>k({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:i}=await(0,_t.betterFetch)(o);return i?i.aud===e.clientId&&i.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,Ut.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 Ot=require("@better-fetch/fetch"),St=require("oslo/jwt");var vt=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(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),E({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return k({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);if(!i.idToken)return null;let n=(0,St.parseJWT)(i.idToken)?.payload,s=e.profilePhotoSize||48;await(0,Ot.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let u=await a.response.clone().arrayBuffer(),g=Buffer.from(u).toString("base64");n.picture=`data:image/jpeg;base64, ${g}`}catch(d){C.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0,...c},data:n}}}};var xt=require("@better-fetch/fetch");var It=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),E({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>k({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,xt.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...i},data:r}}});var K={isAction:!1};var Lt=require("nanoid"),Pt=e=>(0,Lt.nanoid)(e);var Dt=require("oslo/jwt");var Ct=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),E({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>k({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 C.error("No idToken found in token"),null;let o=(0,Dt.parseJWT)(r)?.payload,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...i},data:o}}});var Nt=require("@better-fetch/fetch");var jt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),E({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})=>k({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,Nt.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 i=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,...i},data:r}}});var Vt=require("@better-fetch/fetch");var Bt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await E({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await k({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await(0,Vt.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=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,...n},data:o}}}};var $t=require("@better-fetch/fetch");var zt=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:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await E({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await k({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await(0,$t.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(n)return null;let s=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture,...s},data:i}}}};var qt=require("@better-fetch/fetch");var _e=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),_r=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:_e(`${t}/oauth/authorize`),tokenEndpoint:_e(`${t}/oauth/token`),userinfoEndpoint:_e(`${t}/api/v4/user`)}},Ft=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=_r(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let u=c||["read_user"];return e.scope&&u.push(...e.scope),await E({id:i,options:e,authorizationEndpoint:t,scopes:u,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>k({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,qt.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 Te=require("@better-fetch/fetch");var Mt=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identity"];return e.scope&&i.push(...e.scope),E({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:i,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}),i={"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:n,error:s}=await(0,Te.betterFetch)("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:i,body:o.toString()});if(s)throw s;return ce(n)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,Te.betterFetch)("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let i=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],...i},data:r}}});var Tr={apple:wt,discord:bt,facebook:Rt,github:kt,microsoft:vt,google:Tt,spotify:It,twitch:Ct,twitter:jt,dropbox:Bt,linkedin:zt,gitlab:Ft,reddit:Mt},ue=Object.keys(Tr);var Gt=require("oslo"),me=require("oslo/jwt"),N=require("zod");var J=require("better-call");var $=require("better-call");var M=require("zod");function Ht(e){try{return JSON.parse(e)}catch{return null}}var p={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 pe=()=>f("/get-session",{method:"GET",query:M.z.optional(M.z.object({disableCookieCache:M.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(M.z.string().transform(e=>e==="true")).optional(),disableRefresh:M.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?Ht(Buffer.from(r,"base64").toString()):null;if(o&&!await ae.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return V(e),e.json(null);let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let u=o.session;if(o.expiresAt<Date.now()||u.session.expiresAt<new Date){let h=e.context.authCookies.sessionData.name;e.setCookie(h,"",{maxAge:0})}else return e.json(u)}let n=await e.context.internalAdapter.findSession(t);if(e.context.session=n,!n||n.session.expiresAt<new Date)return V(e),n&&await e.context.internalAdapter.deleteSession(n.session.token),e.json(null);if(i||e.query?.disableRefresh)return e.json(n);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let u=await e.context.internalAdapter.updateSession(n.session.token,{expiresAt:F(e.context.sessionConfig.expiresIn,"sec")});if(!u)return V(e),e.json(null,{status:401});let g=(u.expiresAt.valueOf()-Date.now())/1e3;return await x(e,{session:u,user:n.user},!1,{maxAge:g}),e.json({session:u,user:n.user})}return e.json(n)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new $.APIError("INTERNAL_SERVER_ERROR",{message:p.FAILED_TO_GET_SESSION})}}),H=async(e,t)=>{if(e.context.session)return e.context.session;let r=await pe()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},L=Z(async e=>{let t=await H(e);if(!t?.session)throw new $.APIError("UNAUTHORIZED");return{session:t}}),Oe=Z(async e=>{let t=await H(e);if(!t?.session)throw new $.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 $.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),Se=()=>f("/list-sessions",{method:"GET",use:[L],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),ve=f("/revoke-session",{method:"POST",body:M.z.object({token:M.z.string({description:"The token to revoke"})}),use:[L],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 $.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new $.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 $.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),xe=f("/revoke-sessions",{method:"POST",use:[L],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 $.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Ie=f("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[L],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 $.APIError("UNAUTHORIZED");let i=(await e.context.internalAdapter.listSessions(t.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.token!==e.context.session.session.token);return await Promise.all(i.map(n=>e.context.internalAdapter.deleteSession(n.token))),e.json({status:!0})});async function j(e,t,r){return await(0,me.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Gt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Wt(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(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 Le=f("/send-verification-email",{method:"POST",query:N.z.object({currentURL:N.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:N.z.object({email:N.z.string({description:"The email to send the verification email to"}).email(),callbackURL:N.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 J.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 J.APIError("BAD_REQUEST",{message:p.USER_NOT_FOUND});return await Wt(e,r.user),e.json({status:!0})}),Pe=f("/verify-email",{method:"GET",query:N.z.object({token:N.z.string({description:"The token to verify the email"}),callbackURL:N.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 J.APIError("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await(0,me.validateJWT)("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let n=N.z.object({email:N.z.string().email(),updateTo:N.z.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(n.email);if(!s)return t("user_not_found");if(n.updateTo){let c=await H(e);if(!c){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(c.user.email!==n.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo,emailVerified:!1}),d=await j(e.context.secret,n.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(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await H(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new J.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await x(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 fe(e,{userInfo:t,account:r,callbackURL:o}){let i=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw C.error(`Better auth was unable to query your database.
3
3
  Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=i?.user,s=!n;if(i){let a=i.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(([u,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 ne&&C.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:i.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope})}catch(g){return C.error("Unable to link account",g),{error:"unable to link account",data:null}}n=await e.context.internalAdapter.updateUser(i.user.id,{...t,updatedAt:new Date})}}else if(n=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&&n&&e.context.options.emailVerification?.sendOnSignUp){let a=await j(e.context.secret,n.email),d=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:n,url:d,token:a},e.request)}if(!n)return{error:"unable to create user",data:null,isRegister:!1};let c=await e.context.internalAdapter.createSession(n.id,e.request);return c?{data:{session:c,user:n},error:null,isRegister:s}:{error:"unable to create session",data:null,isRegister:!1}}var De=f("/sign-in/social",{method:"POST",query:U.z.object({currentURL:U.z.string().optional()}).optional(),body:U.z.object({callbackURL:U.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:U.z.string().optional(),errorCallbackURL:U.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:U.z.enum(ue,{description:"OAuth2 provider to use"}),disableRedirect:U.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:U.z.optional(U.z.object({token:U.z.string({description:"ID token from the provider"}),nonce:U.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:U.z.string({description:"Access token from the provider"}).optional(),refreshToken:U.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:U.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(n=>n.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 v.APIError("NOT_FOUND",{message:p.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 v.APIError("NOT_FOUND",{message:p.ID_TOKEN_NOT_SUPPORTED});let{token:n,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(n,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:p.INVALID_TOKEN});let a=await t.getUserInfo({idToken:n,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 v.APIError("UNAUTHORIZED",{message:p.FAILED_TO_GET_USER_INFO});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:p.USER_EMAIL_NOT_FOUND});let d=await fe(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 v.APIError("UNAUTHORIZED",{message:d.error});return await x(e,d.data),e.json({session:d.data.session,user:d.data.user,url:void 0,redirect:!1})}let{codeVerifier:r,state:o}=await le(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!e.body.disableRedirect})}),Ce=f("/sign-in/email",{method:"POST",body:U.z.object({email:U.z.string({description:"Email of the user"}),password:U.z.string({description:"Password of the user"}),callbackURL:U.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:U.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 v.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!U.z.string().email().safeParse(t).success)throw new v.APIError("BAD_REQUEST",{message:p.INVALID_EMAIL});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:p.INVALID_EMAIL_OR_PASSWORD});let n=i.accounts.find(d=>d.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:p.INVALID_EMAIL_OR_PASSWORD});let s=n?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:p.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new v.APIError("UNAUTHORIZED",{message:p.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new v.APIError("UNAUTHORIZED",{message:p.EMAIL_NOT_VERIFIED});let d=await j(e.context.secret,i.user.email),u=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:i.user,url:u,token:d},e.request),e.context.logger.error("Email not verified",{email:t}),new v.APIError("FORBIDDEN",{message:p.EMAIL_NOT_VERIFIED})}let a=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new v.APIError("UNAUTHORIZED",{message:p.FAILED_TO_CREATE_SESSION});return await x(e,{session:a,user:i.user},e.body.rememberMe===!1),e.json({user:{id:i.user.id,email:i.user.email,name:i.user.name,image:i.user.image,emailVerified:i.user.emailVerified,createdAt:i.user.createdAt,updatedAt:i.user.updatedAt},redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Y=require("zod");var ge=Y.z.object({code:Y.z.string().optional(),error:Y.z.string().optional(),error_description:Y.z.string().optional(),state:Y.z.string().optional()}),Ne=f("/callback/:id",{method:["GET","POST"],body:ge.optional(),query:ge.optional(),metadata:K},async e=>{let t;try{if(e.method==="GET")t=ge.parse(e.query);else if(e.method==="POST")t=ge.parse(e.body);else throw new Error("Unsupported method")}catch(A){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",A),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:i,error_description:n}=t;if(!i)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=${n}`);let s=e.context.socialProviders.find(A=>A.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:u,newUserURL:g}=await mt(e),h;try{h=await s.validateAuthorizationCode({code:r,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${s.id}`})}catch(A){throw e.context.logger.error("",A),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let l=await s.getUserInfo(h).then(A=>A?.user);function b(A){let y=u||a||`${e.context.baseURL}/error`;throw y.includes("?")?y=`${y}&error=${A}`:y=`${y}?error=${A}`,e.redirect(y)}if(!l)return e.context.logger.error("Unable to get user info"),b("unable_to_get_user_info");if(!l.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(d){if(d.email!==l.email.toLowerCase())return b("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:s.id,accountId:l.id}))return b("unable_to_link_account");let y;try{y=a.toString()}catch{y=a}throw e.redirect(y)}let _=await fe(e,{userInfo:{...l,email:l.email,name:l.name||l.email},account:{providerId:s.id,accountId:l.id,...h,scope:h.scopes?.join(",")},callbackURL:a});if(_.error)return e.context.logger.error(_.error.split(" ").join("_")),b(_.error.split(" ").join("_"));let{session:I,user:w}=_.data;await x(e,{session:I,user:w});let R;try{R=(_.isRegister&&g||a).toString()}catch{R=_.isRegister&&g||a}throw e.redirect(R)});var On=require("zod");var Zt=require("better-call");var je=f("/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 Zt.APIError("BAD_REQUEST",{message:p.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(t),V(e),e.json({success:!0})});var P=require("zod");var X=require("better-call");function Qt(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}function Or(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}var Ve=f("/forget-password",{method:"POST",body:P.z.object({email:P.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:P.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 X.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 i=60*60*1,n=F(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||i,"sec"),s=Pt(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:n});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})}),Be=f("/reset-password/:token",{method:"GET",query:P.z.object({callbackURL:P.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(Qt(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Qt(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Or(e.context,r,{token:t}))}),$e=f("/reset-password",{query:P.z.optional(P.z.object({token:P.z.string().optional(),currentURL:P.z.string().optional()})),method:"POST",body:P.z.object({newPassword:P.z.string({description:"The new password to set"}),token:P.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 X.APIError("BAD_REQUEST",{message:p.INVALID_TOKEN});let{newPassword:r}=e.body,o=e.context.password?.config.minPasswordLength,i=e.context.password?.config.maxPasswordLength;if(r.length<o)throw new X.APIError("BAD_REQUEST",{message:p.PASSWORD_TOO_SHORT});if(r.length>i)throw new X.APIError("BAD_REQUEST",{message:p.PASSWORD_TOO_LONG});let n=`reset-password:${t}`,s=await e.context.internalAdapter.findVerificationValue(n);if(!s||s.expiresAt<new Date)throw new X.APIError("BAD_REQUEST",{message:p.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 S=require("zod");var T=require("better-call");var m=require("zod"),Kt=require("better-call"),Vn=m.z.object({id:m.z.string(),providerId:m.z.string(),accountId:m.z.string(),userId:m.z.string(),accessToken:m.z.string().nullish(),refreshToken:m.z.string().nullish(),idToken:m.z.string().nullish(),accessTokenExpiresAt:m.z.date().nullish(),refreshTokenExpiresAt:m.z.date().nullish(),scope:m.z.string().nullish(),password:m.z.string().nullish(),createdAt:m.z.date().default(()=>new Date),updatedAt:m.z.date().default(()=>new Date)}),Bn=m.z.object({id:m.z.string(),email:m.z.string().transform(e=>e.toLowerCase()),emailVerified:m.z.boolean().default(!1),name:m.z.string(),image:m.z.string().nullish(),createdAt:m.z.date().default(()=>new Date),updatedAt:m.z.date().default(()=>new Date)}),$n=m.z.object({id:m.z.string(),userId:m.z.string(),expiresAt:m.z.date(),createdAt:m.z.date().default(()=>new Date),updatedAt:m.z.date().default(()=>new Date),token:m.z.string(),ipAddress:m.z.string().nullish(),userAgent:m.z.string().nullish()}),zn=m.z.object({id:m.z.string(),value:m.z.string(),createdAt:m.z.date().default(()=>new Date),updatedAt:m.z.date().default(()=>new Date),expiresAt:m.z.date(),identifier:m.z.string()});function Sr(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function vr(e,t){let r=t.action||"create",o=t.fields,i={};for(let n in o){if(n in e){if(o[n].input===!1){if(o[n].defaultValue){i[n]=o[n].defaultValue;continue}continue}if(o[n].validator?.input&&e[n]!==void 0){i[n]=o[n].validator.input.parse(e[n]);continue}if(o[n].transform?.input&&e[n]!==void 0){i[n]=o[n].transform?.input(e[n]);continue}i[n]=e[n];continue}if(o[n].defaultValue&&r==="create"){i[n]=o[n].defaultValue;continue}if(o[n].required&&r==="create")throw new Kt.APIError("BAD_REQUEST",{message:`${n} is required`})}return i}function he(e,t,r){let o=Sr(e,"user");return vr(t||{},{fields:o,action:r})}var Cr=require("@noble/ciphers/chacha"),qe=require("@noble/ciphers/utils"),Nr=require("@noble/ciphers/webcrypto"),jr=require("oslo/crypto"),Vr=we(require("uncrypto"),1);var Jt=require("oslo/encoding");var xr=require("@noble/hashes/scrypt"),Ir=require("uncrypto");var ze=we(require("uncrypto"),1);function Lr(e){return e.toString(2).padStart(8,"0")}function Pr(e){return[...e].map(t=>Lr(t)).join("")}function Yt(e){return parseInt(Pr(e),2)}function Dr(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));ze.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let i=Yt(o);for(;i>=e;)ze.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),i=Yt(o);return i}function Xt(e,t){let r="";for(let o=0;o<e;o++)r+=t[Dr(t.length)];return r}function er(...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 Fe=()=>f("/update-user",{method:"POST",body:S.z.record(S.z.string(),S.z.any()),use:[L],metadata:{openapi:{description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"}}}}}}}}}},async e=>{let t=e.body;if(t.email)throw new T.APIError("BAD_REQUEST",{message:p.EMAIL_CAN_NOT_BE_UPDATED});let{name:r,image:o,...i}=t,n=e.context.session;if(o===void 0&&r===void 0&&Object.keys(i).length===0)return e.json({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});let s=he(e.context.options,i,"update"),c=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:r,image:o,...s});return await x(e,{session:n.session,user:c}),e.json({id:c.id,email:c.email,name:c.name,image:c.image,emailVerified:c.emailVerified,createdAt:c.createdAt,updatedAt:c.updatedAt})}),Me=f("/change-password",{method:"POST",body:S.z.object({newPassword:S.z.string({description:"The new password to set"}),currentPassword:S.z.string({description:"The current password"}),revokeOtherSessions:S.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[L],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,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new T.APIError("BAD_REQUEST",{message:p.PASSWORD_TOO_SHORT});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new T.APIError("BAD_REQUEST",{message:p.PASSWORD_TOO_LONG});let a=(await e.context.internalAdapter.findAccounts(i.user.id)).find(g=>g.providerId==="credential"&&g.password);if(!a||!a.password)throw new T.APIError("BAD_REQUEST",{message:p.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 T.APIError("BAD_REQUEST",{message:p.INVALID_PASSWORD});if(await e.context.internalAdapter.updateAccount(a.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(i.user.id);let g=await e.context.internalAdapter.createSession(i.user.id,e.headers);if(!g)throw new T.APIError("INTERNAL_SERVER_ERROR",{message:p.FAILED_TO_GET_SESSION});await x(e,{session:g,user:i.user})}return e.json(i.user)}),He=f("/set-password",{method:"POST",body:S.z.object({newPassword:S.z.string()}),metadata:{SERVER_ONLY:!0},use:[L]},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 T.APIError("BAD_REQUEST",{message:p.PASSWORD_TOO_SHORT});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new T.APIError("BAD_REQUEST",{message:p.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 T.APIError("BAD_REQUEST",{message:"user already has a password"})}),Ge=f("/delete-user",{method:"POST",use:[Oe],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 T.APIError("NOT_FOUND");let t=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let i=Xt(32,er("a-z","A-Z","0-9"));await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${i}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let n=`${e.context.baseURL}/delete-user/callback?token=${i}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:n,token:i},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 o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})}),We=f("/delete-user/callback",{method:"GET",query:S.z.object({token:S.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 T.APIError("NOT_FOUND");let t=await H(e);if(!t)throw new T.APIError("NOT_FOUND",{message:p.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 T.APIError("NOT_FOUND",{message:p.INVALID_TOKEN});if(r.value!==t.user.id)throw new T.APIError("NOT_FOUND",{message:p.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),V(e);let i=e.context.options.user.deleteUser?.afterDelete;return i&&await i(t.user,e.request),e.json({success:!0,message:"User deleted"})}),Ze=f("/change-email",{method:"POST",query:S.z.object({currentURL:S.z.string().optional()}).optional(),body:S.z.object({newEmail:S.z.string({description:"The new email to set"}).email(),callbackURL:S.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[L],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 T.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 T.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 T.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let i=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:i,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new T.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(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 Br=(e="Unknown")=>`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
package/dist/api.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import{APIError as H,createRouter as xr,getCookie as Ir,getSignedCookie as Lr,setCookie as Pr,setSignedCookie as Dr}from"better-call";import{APIError as vt}from"better-call";import{createEndpointCreator as Ut,createMiddleware as ge,createMiddlewareCreator as _t}from"better-call";var he=ge(async()=>({})),Z=_t({use:[he,ge(async()=>({}))]}),h=Ut({use:[he]});function le(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function Tt(e){let t="";for(let r=0;r<e.length;r++)t+=le(e[r]);return t}function we(e,t=!0){if(Array.isArray(e))return`(?:${e.map(u=>`^${we(u,t)}$`).join("|")})`;let r="",o="",n=".";t===!0?(r="/",o="[/\\\\]",n="[^/\\\\]"):t&&(r=t,o=Tt(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 u=c[d],f=c[d+1],g="";if(!(!u&&d>0)){if(t&&(d===c.length-1?g=s:f!=="**"?g=i:g=""),t&&u==="**"){g&&(a+=d===0?"":g,a+=`(?:${n}*?${g})*?`);continue}for(let l=0;l<u.length;l++){let b=u[l];b==="\\"?l<u.length-1&&(a+=le(u[l+1]),l++):b==="?"?a+=n:b==="*"?a+=`${n}*?`:a+=le(b)}a+=g}}return a}function Ot(e,t){if(typeof t!="string")throw new TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function ee(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=we(e,t.separator),o=new RegExp(`^${r}$`,t.flags),n=Ot.bind(null,o);return n.options=t,n.pattern=e,n.regexp=o,n}var te=Object.create(null),Q=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?te:globalThis),ye=new Proxy(te,{get(e,t){return Q()[t]??te[t]},has(e,t){let r=Q();return t in r||t in te},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 St(e){return e?e!=="false":!1}var ue=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var re=ue==="dev"||ue==="development",be=ue==="test"||St(ye.TEST);var z=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function Ae(e){try{return new URL(e).origin}catch{return null}}function Re(e){return e.includes("://")?new URL(e).host:e}var ke=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,u=o.trustedOrigins,f=e.headers?.has("cookie"),g=(b,_)=>b.startsWith("/")?!1:_.includes("*")?ee(_)(Re(b)):b.startsWith(_),l=(b,_)=>{if(!b)return;if(!u.some(w=>g(b,w)||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: ${u}`),new vt("FORBIDDEN",{message:`Invalid ${_}`})};f&&!e.context.options.advanced?.disableCSRFCheck&&l(n,"origin"),i&&l(i,"callbackURL"),s&&l(s,"redirectURL"),c&&l(c,"currentURL"),a&&l(a,"errorCallbackURL"),d&&l(s,"newUserCallbackURL")});import{APIError as S}from"better-call";import{z as U}from"zod";import{TimeSpan as no}from"oslo";import{base64url as Pt}from"oslo/encoding";import{HMAC as Ee,sha256 as Yr}from"oslo/crypto";async function It({value:e,secret:t}){return new Ee("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function Lt({value:e,signature:t,secret:r}){return new Ee("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var oe={sign:It,verify:Lt};var q=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function v(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=Pt.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:q(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await oe.sign({value:JSON.stringify(t),secret:e.context.secret})})),{includePadding:!1});if(c.length>4093)throw new z("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 N(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 Bt}from"@better-fetch/fetch";import{APIError as $t}from"better-call";import{decodeProtectedHeader as zt,importJWK as qt,jwtVerify as Ft}from"jose";import{parseJWT as Mt}from"oslo/jwt";import{sha256 as Dt}from"oslo/crypto";import{base64url as Ct}from"oslo/encoding";async function Ue(e){let t=await Dt(new TextEncoder().encode(e));return Ct.encode(new Uint8Array(t),{includePadding:!1})}function ie(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?q(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function E({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 u=await Ue(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",u)}if(s){let u=s.reduce((f,g)=>(f[g]=null,f),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return a&&d.searchParams.set("duration",a),d}import{betterFetch as Nt}from"@better-fetch/fetch";async function k({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 f=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${f}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await Nt(n,{method:"POST",body:s,headers:c});if(d)throw d;return ie(a)}import{generateCodeVerifier as jt,generateState as Vt}from"oslo/oauth2";import{z as V}from"zod";import{APIError as _e}from"better-call";async function ne(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Ae(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new _e("BAD_REQUEST",{message:"callbackURL is required"});let o=jt(),n=Vt(),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 _e("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function Te(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=V.object({callbackURL:V.string(),codeVerifier:V.string(),errorURL:V.string().optional(),newUserURL:V.string().optional(),expiresAt:V.number(),link:V.object({email:V.string(),userId:V.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 Oe=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})=>k({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=zt(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let c=await Ht(i),{payload:a}=await Ft(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=Mt(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}}}},Ht=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await Bt(`${t}${r}`);if(!o?.keys)throw new $t("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 qt(n,n.alg)};import{betterFetch as Gt}from"@better-fetch/fetch";var Se=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})=>k({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 Gt("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}}});import{betterFetch as Wt}from"@better-fetch/fetch";var ve=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 E({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})=>k({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 Wt("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}}});import{betterFetch as xe}from"@better-fetch/fetch";var Ie=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),E({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>k({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 xe("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 xe("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}}}};import{parseJWT as Yt}from"oslo/jwt";import{createConsola as Zt}from"consola";var pe=["info","success","warn","error","debug"];function Qt(e,t){return pe.indexOf(t)<=pe.indexOf(e)}var Kt=Zt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Jt=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,s=[])=>{if(!(!t||!Qt(r,n))){if(!e||typeof e.log!="function"){Kt[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(pe.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},L=Jt();import{betterFetch as Xt}from"@better-fetch/fetch";var Le=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw L.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new z("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new z("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await E({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})=>k({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 Xt(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=Yt(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}}});import{betterFetch as er}from"@better-fetch/fetch";import{parseJWT as tr}from"oslo/jwt";var Pe=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),E({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 k({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=tr(n.idToken)?.payload,s=e.profilePhotoSize||48;await er(`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 u=await a.response.clone().arrayBuffer(),f=Buffer.from(u).toString("base64");i.picture=`data:image/jpeg;base64, ${f}`}catch(d){L.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}}}};import{betterFetch as rr}from"@better-fetch/fetch";var De=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),E({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})=>k({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 rr("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 G={isAction:!1};import{nanoid as or}from"nanoid";var Ce=e=>or(e);import{parseJWT as ir}from"oslo/jwt";var Ne=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),E({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})=>k({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 L.error("No idToken found in token"),null;let o=ir(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}}});import{betterFetch as nr}from"@better-fetch/fetch";var je=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),E({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})=>k({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 nr("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}}});import{betterFetch as sr}from"@better-fetch/fetch";var Ve=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 E({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 k({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 sr("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}}}};import{betterFetch as ar}from"@better-fetch/fetch";var Be=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 E({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await k({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await ar("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}}}};import{betterFetch as cr}from"@better-fetch/fetch";var me=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),dr=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:me(`${t}/oauth/authorize`),tokenEndpoint:me(`${t}/oauth/token`),userinfoEndpoint:me(`${t}/api/v4/user`)}},$e=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=dr(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let u=c||["read_user"];return e.scope&&u.push(...e.scope),await E({id:n,options:e,authorizationEndpoint:t,scopes:u,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>k({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 cr(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}}}};import{betterFetch as ze}from"@better-fetch/fetch";var qe=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identity"];return e.scope&&n.push(...e.scope),E({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 ze("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:n,body:o.toString()});if(s)throw s;return ie(i)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await ze("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 lr={apple:Oe,discord:Se,facebook:ve,github:Ie,microsoft:Pe,google:Le,spotify:De,twitch:Ne,twitter:je,dropbox:Ve,linkedin:Be,gitlab:$e,reddit:qe},se=Object.keys(lr);import{TimeSpan as ur}from"oslo";import{createJWT as pr,validateJWT as mr}from"oslo/jwt";import{z as C}from"zod";import{APIError as K}from"better-call";import{APIError as B}from"better-call";import{z as F}from"zod";function Fe(e){try{return JSON.parse(e)}catch{return null}}var p={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 fe=()=>h("/get-session",{method:"GET",query:F.optional(F.object({disableCookieCache:F.boolean({description:"Disable cookie cache and fetch session from database"}).or(F.string().transform(e=>e==="true")).optional(),disableRefresh:F.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?Fe(Buffer.from(r,"base64").toString()):null;if(o&&!await oe.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return N(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 u=o.session;if(o.expiresAt<Date.now()||u.session.expiresAt<new Date){let g=e.context.authCookies.sessionData.name;e.setCookie(g,"",{maxAge:0})}else return e.json(u)}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return N(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 u=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:q(e.context.sessionConfig.expiresIn,"sec")});if(!u)return N(e),e.json(null,{status:401});let f=(u.expiresAt.valueOf()-Date.now())/1e3;return await v(e,{session:u,user:i.user},!1,{maxAge:f}),e.json({session:u,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new B("INTERNAL_SERVER_ERROR",{message:p.FAILED_TO_GET_SESSION})}}),M=async(e,t)=>{if(e.context.session)return e.context.session;let r=await fe()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},P=Z(async e=>{let t=await M(e);if(!t?.session)throw new B("UNAUTHORIZED");return{session:t}}),Me=Z(async e=>{let t=await M(e);if(!t?.session)throw new B("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 B("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),He=()=>h("/list-sessions",{method:"GET",use:[P],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Ge=h("/revoke-session",{method:"POST",body:F.object({token:F.string({description:"The token to revoke"})}),use:[P],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(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new B("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),We=h("/revoke-sessions",{method:"POST",use:[P],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})}),Ze=h("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[P],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 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 j(e,t,r){return await pr("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new ur(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function fr(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new K("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(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 Qe=h("/send-verification-email",{method:"POST",query:C.object({currentURL:C.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:C.object({email:C.string({description:"The email to send the verification email to"}).email(),callbackURL:C.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 K("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new K("BAD_REQUEST",{message:p.USER_NOT_FOUND});return await fr(e,r.user),e.json({status:!0})}),Ke=h("/verify-email",{method:"GET",query:C.object({token:C.string({description:"The token to verify the email"}),callbackURL:C.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 K("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await mr("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let i=C.object({email:C.string().email(),updateTo:C.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 M(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 j(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 M(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new K("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await v(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 ae(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw L.error(`Better auth was unable to query your database.
2
+ `,`Current list of trustedOrigins: ${u}`),new vt("FORBIDDEN",{message:`Invalid ${_}`})};f&&!e.context.options.advanced?.disableCSRFCheck&&l(n,"origin"),i&&l(i,"callbackURL"),s&&l(s,"redirectURL"),c&&l(c,"currentURL"),a&&l(a,"errorCallbackURL"),d&&l(s,"newUserCallbackURL")});import{APIError as S}from"better-call";import{z as U}from"zod";import{TimeSpan as no}from"oslo";import{base64url as Pt}from"oslo/encoding";import{HMAC as Ee,sha256 as Yr}from"oslo/crypto";async function It({value:e,secret:t}){return new Ee("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function Lt({value:e,signature:t,secret:r}){return new Ee("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var oe={sign:It,verify:Lt};var q=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function v(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=Pt.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:q(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await oe.sign({value:JSON.stringify(t),secret:e.context.secret})})),{includePadding:!1});if(c.length>4093)throw new z("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 N(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 Bt}from"@better-fetch/fetch";import{APIError as $t}from"better-call";import{decodeProtectedHeader as zt,importJWK as qt,jwtVerify as Ft}from"jose";import{parseJWT as Mt}from"oslo/jwt";import{sha256 as Dt}from"oslo/crypto";import{base64url as Ct}from"oslo/encoding";async function Ue(e){let t=await Dt(new TextEncoder().encode(e));return Ct.encode(new Uint8Array(t),{includePadding:!1})}function ie(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?q(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function E({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 u=await Ue(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",u)}if(s){let u=s.reduce((f,g)=>(f[g]=null,f),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return a&&d.searchParams.set("duration",a),d}import{betterFetch as Nt}from"@better-fetch/fetch";async function k({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 f=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${f}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await Nt(n,{method:"POST",body:s,headers:c});if(d)throw d;return ie(a)}import{generateCodeVerifier as jt,generateState as Vt}from"oslo/oauth2";import{z as V}from"zod";import{APIError as _e}from"better-call";async function ne(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Ae(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new _e("BAD_REQUEST",{message:"callbackURL is required"});let o=jt(),n=Vt(),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 _e("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function Te(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=V.object({callbackURL:V.string(),codeVerifier:V.string(),errorURL:V.string().optional(),newUserURL:V.string().optional(),expiresAt:V.number(),link:V.object({email:V.string(),userId:V.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 Oe=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})=>k({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=zt(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let c=await Ht(i),{payload:a}=await Ft(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=Mt(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}}}},Ht=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await Bt(`${t}${r}`);if(!o?.keys)throw new $t("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 qt(n,n.alg)};import{betterFetch as Gt}from"@better-fetch/fetch";var Se=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})=>k({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 Gt("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}}});import{betterFetch as Wt}from"@better-fetch/fetch";var ve=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 E({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})=>k({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 Wt("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}}});import{betterFetch as xe}from"@better-fetch/fetch";var Ie=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),E({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>k({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 xe("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 xe("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}}}};import{parseJWT as Yt}from"oslo/jwt";import{createConsola as Zt}from"consola";var pe=["info","success","warn","error","debug"];function Qt(e,t){return pe.indexOf(t)<=pe.indexOf(e)}var Kt=Zt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Jt=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,s=[])=>{if(!(!t||!Qt(r,n))){if(!e||typeof e.log!="function"){Kt[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(pe.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},L=Jt();import{betterFetch as Xt}from"@better-fetch/fetch";var Le=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw L.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new z("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new z("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await E({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})=>k({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 Xt(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=Yt(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}}});import{betterFetch as er}from"@better-fetch/fetch";import{parseJWT as tr}from"oslo/jwt";var Pe=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),E({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 k({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=tr(n.idToken)?.payload,s=e.profilePhotoSize||48;await er(`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 u=await a.response.clone().arrayBuffer(),f=Buffer.from(u).toString("base64");i.picture=`data:image/jpeg;base64, ${f}`}catch(d){L.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}}}};import{betterFetch as rr}from"@better-fetch/fetch";var De=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),E({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})=>k({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 rr("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 G={isAction:!1};import{nanoid as or}from"nanoid";var Ce=e=>or(e);import{parseJWT as ir}from"oslo/jwt";var Ne=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),E({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})=>k({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 L.error("No idToken found in token"),null;let o=ir(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}}});import{betterFetch as nr}from"@better-fetch/fetch";var je=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),E({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})=>k({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 nr("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}}});import{betterFetch as sr}from"@better-fetch/fetch";var Ve=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 E({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 k({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 sr("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}}}};import{betterFetch as ar}from"@better-fetch/fetch";var Be=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 E({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await k({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await ar("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}}}};import{betterFetch as cr}from"@better-fetch/fetch";var me=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),dr=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:me(`${t}/oauth/authorize`),tokenEndpoint:me(`${t}/oauth/token`),userinfoEndpoint:me(`${t}/api/v4/user`)}},$e=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=dr(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let u=c||["read_user"];return e.scope&&u.push(...e.scope),await E({id:n,options:e,authorizationEndpoint:t,scopes:u,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>k({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 cr(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}}}};import{betterFetch as ze}from"@better-fetch/fetch";var qe=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identity"];return e.scope&&n.push(...e.scope),E({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 ze("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:n,body:o.toString()});if(s)throw s;return ie(i)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await ze("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 lr={apple:Oe,discord:Se,facebook:ve,github:Ie,microsoft:Pe,google:Le,spotify:De,twitch:Ne,twitter:je,dropbox:Ve,linkedin:Be,gitlab:$e,reddit:qe},se=Object.keys(lr);import{TimeSpan as ur}from"oslo";import{createJWT as pr,validateJWT as mr}from"oslo/jwt";import{z as C}from"zod";import{APIError as K}from"better-call";import{APIError as B}from"better-call";import{z as F}from"zod";function Fe(e){try{return JSON.parse(e)}catch{return null}}var p={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 fe=()=>h("/get-session",{method:"GET",query:F.optional(F.object({disableCookieCache:F.boolean({description:"Disable cookie cache and fetch session from database"}).or(F.string().transform(e=>e==="true")).optional(),disableRefresh:F.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?Fe(Buffer.from(r,"base64").toString()):null;if(o&&!await oe.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return N(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 u=o.session;if(o.expiresAt<Date.now()||u.session.expiresAt<new Date){let g=e.context.authCookies.sessionData.name;e.setCookie(g,"",{maxAge:0})}else return e.json(u)}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return N(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 u=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:q(e.context.sessionConfig.expiresIn,"sec")});if(!u)return N(e),e.json(null,{status:401});let f=(u.expiresAt.valueOf()-Date.now())/1e3;return await v(e,{session:u,user:i.user},!1,{maxAge:f}),e.json({session:u,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new B("INTERNAL_SERVER_ERROR",{message:p.FAILED_TO_GET_SESSION})}}),M=async(e,t)=>{if(e.context.session)return e.context.session;let r=await fe()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},P=Z(async e=>{let t=await M(e);if(!t?.session)throw new B("UNAUTHORIZED");return{session:t}}),Me=Z(async e=>{let t=await M(e);if(!t?.session)throw new B("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 B("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),He=()=>h("/list-sessions",{method:"GET",use:[P],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Ge=h("/revoke-session",{method:"POST",body:F.object({token:F.string({description:"The token to revoke"})}),use:[P],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(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new B("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),We=h("/revoke-sessions",{method:"POST",use:[P],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})}),Ze=h("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[P],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 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 j(e,t,r){return await pr("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new ur(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function fr(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new K("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(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 Qe=h("/send-verification-email",{method:"POST",query:C.object({currentURL:C.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:C.object({email:C.string({description:"The email to send the verification email to"}).email(),callbackURL:C.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 K("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new K("BAD_REQUEST",{message:p.USER_NOT_FOUND});return await fr(e,r.user),e.json({status:!0})}),Ke=h("/verify-email",{method:"GET",query:C.object({token:C.string({description:"The token to verify the email"}),callbackURL:C.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 K("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await mr("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let i=C.object({email:C.string().email(),updateTo:C.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 M(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 j(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 M(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new K("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await v(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 ae(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw L.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(([u,f])=>f!==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 re&&L.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(f){return L.error("Unable to link account",f),{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 j(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 Je=h("/sign-in/social",{method:"POST",query:U.object({currentURL:U.string().optional()}).optional(),body:U.object({callbackURL:U.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:U.string().optional(),errorCallbackURL:U.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:U.enum(se,{description:"OAuth2 provider to use"}),disableRedirect:U.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:U.optional(U.object({token:U.string({description:"ID token from the provider"}),nonce:U.string({description:"Nonce used to generate the token"}).optional(),accessToken:U.string({description:"Access token from the provider"}).optional(),refreshToken:U.string({description:"Refresh token from the provider"}).optional(),expiresAt:U.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 S("NOT_FOUND",{message:p.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 S("NOT_FOUND",{message:p.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 S("UNAUTHORIZED",{message:p.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 S("UNAUTHORIZED",{message:p.FAILED_TO_GET_USER_INFO});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new S("UNAUTHORIZED",{message:p.USER_EMAIL_NOT_FOUND});let d=await ae(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 S("UNAUTHORIZED",{message:d.error});return await v(e,d.data),e.json({session:d.data.session,user:d.data.user,url:void 0,redirect:!1})}let{codeVerifier:r,state:o}=await ne(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})}),Ye=h("/sign-in/email",{method:"POST",body:U.object({email:U.string({description:"Email of the user"}),password:U.string({description:"Password of the user"}),callbackURL:U.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:U.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 S("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!U.string().email().safeParse(t).success)throw new S("BAD_REQUEST",{message:p.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 S("UNAUTHORIZED",{message:p.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 S("UNAUTHORIZED",{message:p.INVALID_EMAIL_OR_PASSWORD});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new S("UNAUTHORIZED",{message:p.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new S("UNAUTHORIZED",{message:p.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new S("UNAUTHORIZED",{message:p.EMAIL_NOT_VERIFIED});let d=await j(e.context.secret,n.user.email),u=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:u,token:d},e.request),e.context.logger.error("Email not verified",{email:t}),new S("FORBIDDEN",{message:p.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 S("UNAUTHORIZED",{message:p.FAILED_TO_CREATE_SESSION});return await v(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})});import{z as J}from"zod";var ce=J.object({code:J.string().optional(),error:J.string().optional(),error_description:J.string().optional(),state:J.string().optional()}),Xe=h("/callback/:id",{method:["GET","POST"],body:ce.optional(),query:ce.optional(),metadata:G},async e=>{let t;try{if(e.method==="GET")t=ce.parse(e.query);else if(e.method==="POST")t=ce.parse(e.body);else throw new Error("Unsupported method")}catch(A){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",A),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(A=>A.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:u,newUserURL:f}=await Te(e),g;try{g=await s.validateAuthorizationCode({code:r,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${s.id}`})}catch(A){throw e.context.logger.error("",A),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let l=await s.getUserInfo(g).then(A=>A?.user);function b(A){let y=u||a||`${e.context.baseURL}/error`;throw y.includes("?")?y=`${y}&error=${A}`:y=`${y}?error=${A}`,e.redirect(y)}if(!l)return e.context.logger.error("Unable to get user info"),b("unable_to_get_user_info");if(!l.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(d){if(d.email!==l.email.toLowerCase())return b("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:s.id,accountId:l.id}))return b("unable_to_link_account");let y;try{y=a.toString()}catch{y=a}throw e.redirect(y)}let _=await ae(e,{userInfo:{...l,email:l.email,name:l.name||l.email},account:{providerId:s.id,accountId:l.id,...g,scope:g.scopes?.join(",")},callbackURL:a});if(_.error)return e.context.logger.error(_.error.split(" ").join("_")),b(_.error.split(" ").join("_"));let{session:x,user:w}=_.data;await v(e,{session:x,user:w});let R;try{R=(_.isRegister&&f||a).toString()}catch{R=_.isRegister&&f||a}throw e.redirect(R)});import"zod";import{APIError as gr}from"better-call";var et=h("/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 N(e),new gr("BAD_REQUEST",{message:p.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(t),N(e),e.json({success:!0})});import{z as D}from"zod";import{APIError as Y}from"better-call";function tt(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 hr(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 rt=h("/forget-password",{method:"POST",body:D.object({email:D.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:D.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 Y("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=q(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=Ce(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})}),ot=h("/reset-password/:token",{method:"GET",query:D.object({callbackURL:D.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(tt(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(tt(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(hr(e.context,r,{token:t}))}),it=h("/reset-password",{query:D.optional(D.object({token:D.string().optional(),currentURL:D.string().optional()})),method:"POST",body:D.object({newPassword:D.string({description:"The new password to set"}),token:D.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 Y("BAD_REQUEST",{message:p.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 Y("BAD_REQUEST",{message:p.PASSWORD_TOO_SHORT});if(r.length>n)throw new Y("BAD_REQUEST",{message:p.PASSWORD_TOO_LONG});let i=`reset-password:${t}`,s=await e.context.internalAdapter.findVerificationValue(i);if(!s||s.expiresAt<new Date)throw new Y("BAD_REQUEST",{message:p.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(f=>f.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}))});import{z as O}from"zod";import{APIError as T}from"better-call";import{z as m}from"zod";import{APIError as wr}from"better-call";var bs=m.object({id:m.string(),providerId:m.string(),accountId:m.string(),userId:m.string(),accessToken:m.string().nullish(),refreshToken:m.string().nullish(),idToken:m.string().nullish(),accessTokenExpiresAt:m.date().nullish(),refreshTokenExpiresAt:m.date().nullish(),scope:m.string().nullish(),password:m.string().nullish(),createdAt:m.date().default(()=>new Date),updatedAt:m.date().default(()=>new Date)}),As=m.object({id:m.string(),email:m.string().transform(e=>e.toLowerCase()),emailVerified:m.boolean().default(!1),name:m.string(),image:m.string().nullish(),createdAt:m.date().default(()=>new Date),updatedAt:m.date().default(()=>new Date)}),Rs=m.object({id:m.string(),userId:m.string(),expiresAt:m.date(),createdAt:m.date().default(()=>new Date),updatedAt:m.date().default(()=>new Date),token:m.string(),ipAddress:m.string().nullish(),userAgent:m.string().nullish()}),ks=m.object({id:m.string(),value:m.string(),createdAt:m.date().default(()=>new Date),updatedAt:m.date().default(()=>new Date),expiresAt:m.date(),identifier:m.string()});function yr(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function br(e,t){let r=t.action||"create",o=t.fields,n={};for(let i in o){if(i in e){if(o[i].input===!1){if(o[i].defaultValue){n[i]=o[i].defaultValue;continue}continue}if(o[i].validator?.input&&e[i]!==void 0){n[i]=o[i].validator.input.parse(e[i]);continue}if(o[i].transform?.input&&e[i]!==void 0){n[i]=o[i].transform?.input(e[i]);continue}n[i]=e[i];continue}if(o[i].defaultValue&&r==="create"){n[i]=o[i].defaultValue;continue}if(o[i].required&&r==="create")throw new wr("BAD_REQUEST",{message:`${i} is required`})}return n}function de(e,t,r){let o=yr(e,"user");return br(t||{},{fields:o,action:r})}import{xchacha20poly1305 as Ns}from"@noble/ciphers/chacha";import{bytesToHex as Vs,hexToBytes as Bs,utf8ToBytes as $s}from"@noble/ciphers/utils";import{managedNonce as qs}from"@noble/ciphers/webcrypto";import{sha256 as Ms}from"oslo/crypto";import Gs from"uncrypto";import{decodeHex as _s,encodeHex as Ts}from"oslo/encoding";import{scryptAsync as vs}from"@noble/hashes/scrypt";import{getRandomValues as Is}from"uncrypto";import nt from"uncrypto";function Ar(e){return e.toString(2).padStart(8,"0")}function Rr(e){return[...e].map(t=>Ar(t)).join("")}function st(e){return parseInt(Rr(e),2)}function kr(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));nt.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=st(o);for(;n>=e;)nt.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=st(o);return n}function at(e,t){let r="";for(let o=0;o<e;o++)r+=t[kr(t.length)];return r}function ct(...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 dt=()=>h("/update-user",{method:"POST",body:O.record(O.string(),O.any()),use:[P],metadata:{openapi:{description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"}}}}}}}}}},async e=>{let t=e.body;if(t.email)throw new T("BAD_REQUEST",{message:p.EMAIL_CAN_NOT_BE_UPDATED});let{name:r,image:o,...n}=t,i=e.context.session;if(o===void 0&&r===void 0&&Object.keys(n).length===0)return e.json({id:i.user.id,email:i.user.email,name:i.user.name,image:i.user.image,emailVerified:i.user.emailVerified,createdAt:i.user.createdAt,updatedAt:i.user.updatedAt});let s=de(e.context.options,n,"update"),c=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await v(e,{session:i.session,user:c}),e.json({id:c.id,email:c.email,name:c.name,image:c.image,emailVerified:c.emailVerified,createdAt:c.createdAt,updatedAt:c.updatedAt})}),lt=h("/change-password",{method:"POST",body:O.object({newPassword:O.string({description:"The new password to set"}),currentPassword:O.string({description:"The current password"}),revokeOtherSessions:O.boolean({description:"Revoke all other sessions"}).optional()}),use:[P],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 T("BAD_REQUEST",{message:p.PASSWORD_TOO_SHORT});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new T("BAD_REQUEST",{message:p.PASSWORD_TOO_LONG});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(f=>f.providerId==="credential"&&f.password);if(!a||!a.password)throw new T("BAD_REQUEST",{message:p.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 T("BAD_REQUEST",{message:p.INVALID_PASSWORD});if(await e.context.internalAdapter.updateAccount(a.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let f=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!f)throw new T("INTERNAL_SERVER_ERROR",{message:p.FAILED_TO_GET_SESSION});await v(e,{session:f,user:n.user})}return e.json(n.user)}),ut=h("/set-password",{method:"POST",body:O.object({newPassword:O.string()}),metadata:{SERVER_ONLY:!0},use:[P]},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 T("BAD_REQUEST",{message:p.PASSWORD_TOO_SHORT});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new T("BAD_REQUEST",{message:p.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 T("BAD_REQUEST",{message:"user already has a password"})}),pt=h("/delete-user",{method:"POST",use:[Me],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 T("NOT_FOUND");let t=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=at(32,ct("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),N(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})}),mt=h("/delete-user/callback",{method:"GET",query:O.object({token:O.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 T("NOT_FOUND");let t=await M(e);if(!t)throw new T("NOT_FOUND",{message:p.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 T("NOT_FOUND",{message:p.INVALID_TOKEN});if(r.value!==t.user.id)throw new T("NOT_FOUND",{message:p.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),N(e);let n=e.context.options.user.deleteUser?.afterDelete;return n&&await n(t.user,e.request),e.json({success:!0,message:"User deleted"})}),ft=h("/change-email",{method:"POST",query:O.object({currentURL:O.string().optional()}).optional(),body:O.object({newEmail:O.string({description:"The new email to set"}).email(),callbackURL:O.string({description:"The URL to redirect to after email verification"}).optional()}),use:[P],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 T("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 T("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 T("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 T("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(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 Er=(e="Unknown")=>`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
@@ -2,7 +2,7 @@ import * as nanostores from 'nanostores';
2
2
  import { AccessControl, StatementsPrimitive, Role } from '../plugins/access.cjs';
3
3
  import * as _better_fetch_fetch from '@better-fetch/fetch';
4
4
  import { BetterFetchOption } from '@better-fetch/fetch';
5
- import { o as organization, a as Organization, M as Member, I as Invitation } from '../index-CgaJXZ9u.cjs';
5
+ import { o as organization, a as Organization, M as Member, I as Invitation } from '../index-Dp04oxSM.cjs';
6
6
  import { b as Prettify } from '../helper-Bi8FQwDD.cjs';
7
7
  import { username } from '../plugins/username.cjs';
8
8
  export { getPasskeyActions, passkeyClient } from '../plugins/passkey.cjs';
@@ -2,7 +2,7 @@ import * as nanostores from 'nanostores';
2
2
  import { AccessControl, StatementsPrimitive, Role } from '../plugins/access.js';
3
3
  import * as _better_fetch_fetch from '@better-fetch/fetch';
4
4
  import { BetterFetchOption } from '@better-fetch/fetch';
5
- import { o as organization, a as Organization, M as Member, I as Invitation } from '../index-Dt4lZbQi.js';
5
+ import { o as organization, a as Organization, M as Member, I as Invitation } from '../index-Dd3_WG87.js';
6
6
  import { b as Prettify } from '../helper-Bi8FQwDD.js';
7
7
  import { username } from '../plugins/username.js';
8
8
  export { getPasskeyActions, passkeyClient } from '../plugins/passkey.js';