better-auth 0.4.13 → 0.4.14-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.
@@ -1,4 +1,4 @@
1
- import { A as Adapter } from '../auth-C6fr77co.js';
1
+ import { A as Adapter } from '../auth-BTj2ofMy.js';
2
2
  import 'zod';
3
3
  import 'kysely';
4
4
  import '../schema-Dkt0LqYs.js';
@@ -1,5 +1,5 @@
1
1
  import { Kysely } from 'kysely';
2
- import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-C6fr77co.js';
2
+ import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-BTj2ofMy.js';
3
3
  import 'zod';
4
4
  import '../schema-Dkt0LqYs.js';
5
5
  import 'better-call';
@@ -1,5 +1,5 @@
1
1
  import { Db } from 'mongodb';
2
- import { W as Where } from '../auth-C6fr77co.js';
2
+ import { W as Where } from '../auth-BTj2ofMy.js';
3
3
  import 'zod';
4
4
  import 'kysely';
5
5
  import '../schema-Dkt0LqYs.js';
@@ -1,4 +1,4 @@
1
- import { A as Adapter } from '../auth-C6fr77co.js';
1
+ import { A as Adapter } from '../auth-BTj2ofMy.js';
2
2
  import 'zod';
3
3
  import 'kysely';
4
4
  import '../schema-Dkt0LqYs.js';
package/dist/api.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { e as AuthEndpoint, f as AuthMiddleware, a0 as callbackOAuth, af as changePassword, d as createAuthEndpoint, c as createAuthMiddleware, ab as createEmailVerificationToken, am as csrfMiddleware, ah as deleteUser, aj as error, a8 as forgetPassword, a9 as forgetPasswordCallback, ai as getCSRFToken, Y as getEndpoints, a1 as getSession, a2 as getSessionFromCtx, a4 as listSessions, ak as ok, o as optionsMiddleware, aa as resetPassword, a5 as revokeSession, a6 as revokeSessions, Z as router, ac as sendVerificationEmail, a3 as sessionMiddleware, ag as setPassword, $ as signInEmail, _ as signInOAuth, a7 as signOut, al as signUpEmail, ae as updateUser, ad as verifyEmail } from './auth-C6fr77co.js';
1
+ export { e as AuthEndpoint, f as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, d as createAuthEndpoint, c as createAuthMiddleware, ac as createEmailVerificationToken, ao as csrfMiddleware, ai as deleteUser, al as error, a9 as forgetPassword, aa as forgetPasswordCallback, ak as getCSRFToken, Z as getEndpoints, a2 as getSession, a3 as getSessionFromCtx, a5 as listSessions, am as ok, o as optionsMiddleware, ab as resetPassword, a6 as revokeSession, a7 as revokeSessions, _ as router, ad as sendVerificationEmail, a4 as sessionMiddleware, ah as setPassword, a0 as signInEmail, $ as signInOAuth, a8 as signOut, an as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-BTj2ofMy.js';
2
2
  import './helper-DPDj8Nix.js';
3
3
  export { APIError } from 'better-call';
4
4
  import 'zod';
package/dist/api.js CHANGED
@@ -1,6 +1,6 @@
1
- import{APIError as It,createRouter as Ct}from"better-call";import{APIError as Z}from"better-call";import{z as oe}from"zod";import{xchacha20poly1305 as Qt}from"@noble/ciphers/chacha";import{bytesToHex as Wt,hexToBytes as Jt,utf8ToBytes as Kt}from"@noble/ciphers/utils";import{managedNonce as Yt}from"@noble/ciphers/webcrypto";import{sha256 as tr}from"oslo/crypto";function Q(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let n=0;for(let i=0;i<r.length;i++)n|=r[i]^o[i];return n===0}import{decodeHex as zt,encodeHex as jt}from"oslo/encoding";import{scryptAsync as Mt}from"@noble/hashes/scrypt";function Je(e){return e.toString(2).padStart(8,"0")}function Ke(e){return[...e].map(t=>Je(t)).join("")}function X(e){return parseInt(Ke(e),2)}function Xe(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));crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=X(o);for(;n>=e;)crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=X(o);return n}function Y(e,t){let r="";for(let o=0;o<e;o++)r+=t[Xe(t.length)];return r}function ee(...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}async function q(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),i=await crypto.subtle.sign(o.name,n,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(i)))}import{createEndpointCreator as Ye,createMiddleware as te,createMiddlewareCreator as et}from"better-call";var re=te(async()=>({})),$=et({use:[re,te(async()=>({}))]}),p=Ye({use:[re]});var ne=$({body:oe.object({csrfToken:oe.string().optional()}).optional()},async e=>{if(e.request?.method!=="POST"||e.context.options.advanced?.disableCSRFCheck)return;let t=new URL(e.request.url);if(e.context.trustedOrigins.includes(t.origin))return;let r=e.body?.csrfToken;if(!r)throw new Z("UNAUTHORIZED",{message:"CSRF Token is required"});let o=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[n,i]=o?.split("!")||[null,null];if(!r||!o||!n||!i||n!==r)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new Z("UNAUTHORIZED",{message:"Invalid CSRF Token"});let s=await q(e.context.secret,n);if(i!==s)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new Z("UNAUTHORIZED",{message:"Invalid CSRF Token"})});import{APIError as P}from"better-call";import{generateCodeVerifier as Rt}from"oslo/oauth2";import{z as E}from"zod";import{generateState as tt}from"oslo/oauth2";import{z as N}from"zod";import{sha256 as ie}from"oslo/crypto";async function se(e){let t=await ie(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function ae(e,t){let r=await ie(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return Q(r,o)}import"better-call";async function ce(e){let t=tt(),r=JSON.stringify({code:t,callbackURL:e}),o=await se(r);return{raw:r,hash:o}}function W(e){return N.object({code:N.string(),callbackURL:N.string().optional(),currentURL:N.string().optional()}).safeParse(JSON.parse(e))}import{TimeSpan as vr}from"oslo";var I=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};async function v(e,t,r,o){let n=e.context.authCookies.sessionToken.options;n.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options)}function z(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}import{APIError as de}from"better-call";import{createConsola as rt}from"consola";var C=rt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),ot=e=>({log:(...t)=>{!e?.disabled&&C.log("",...t)},error:(...t)=>{!e?.disabled&&C.error("",...t)},warn:(...t)=>{!e?.disabled&&C.warn("",...t)},info:(...t)=>{!e?.disabled&&C.info("",...t)},debug:(...t)=>{!e?.disabled&&C.debug("",...t)},box:(...t)=>{!e?.disabled&&C.box("",...t)},success:(...t)=>{!e?.disabled&&C.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
2
- `)}}),w=ot();var U=$(async e=>{let t=e.body?.callbackURL||e.query?.callbackURL||e.query?.redirectTo||e.body?.redirectTo,r=e.headers?.get("referer"),o=e.query?.currentURL||r||e.context.baseURL,n=e.context.trustedOrigins;if(t?.includes("http")){let i=new URL(t).origin;if(!n.includes(i))throw w.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new de("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let i=new URL(o).origin;if(!n.includes(i))throw w.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new de("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as at}from"oslo/jwt";import{sha256 as nt}from"oslo/crypto";import{base64url as it}from"oslo/encoding";async function ue(e){let t=await nt(new TextEncoder().encode(e));return it.encode(new Uint8Array(t),{includePadding:!1})}function pe(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_at?new Date((Date.now()+e.expires_in)*1e3):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function k({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,disablePkce:d,redirectURI:a}){let c=new URL(r);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",t.clientId),c.searchParams.set("state",o),c.searchParams.set("scope",i.join(" ")),c.searchParams.set("redirect_uri",t.redirectURI||a),!d&&n){let u=await ue(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",u)}if(s){let u=s.reduce((y,g)=>(y[g]=null,y),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return c}import{betterFetch as st}from"@better-fetch/fetch";async function b({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:s,error:d}=await st(n,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(d)throw d;return pe(s)}function J(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var le=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=e.scope||o||["email","name","openid"];return 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}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=at(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};import{betterFetch as ct}from"@better-fetch/fetch";var me=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["identify","email"];return 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}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await ct("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}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});import{betterFetch as dt}from"@better-fetch/fetch";var fe=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["email","public_profile"];return await k({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})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await dt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,emailVerified:r.email_verified},data:r}}});import{betterFetch as ge}from"@better-fetch/fetch";var he=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=e.scope||o||["user:email"];return k({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>b({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await ge("https://api.github.com/user",{auth:{type:"Bearer",token:r.accessToken}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:d}=await ge("https://api.github.com/user/emails",{auth:{type:"Bearer",token:r.accessToken}});d||(o.email=(s.find(a=>a.primary)??s[0])?.email,i=s.find(a=>a.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};import{parseJWT as ut}from"oslo/jwt";var we=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw w.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new I("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new I("codeVerifier is required for Google");let i=e.scope||r||["email","profile"];return k({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=ut(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});import{betterFetch as pt}from"@better-fetch/fetch";import{parseJWT as lt}from"oslo/jwt";var ye=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=e.scope||n.scopes||["openid","profile","email","User.Read"];return k({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 b({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=lt(n.idToken)?.payload,s=e.profilePhotoSize||48;return await pt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(d){if(!(e.disableProfilePhoto||!d.response.ok))try{let c=await d.response.clone().arrayBuffer(),u=Buffer.from(c).toString("base64");i.picture=`data:image/jpeg;base64, ${u}`}catch(a){w.error(a)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as mt}from"@better-fetch/fetch";var be=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=e.scope||r||["user-read-email"];return k({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})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await mt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";var L={isAction:!1};import{nanoid as ft}from"nanoid";var Ae=e=>ft(e);import{parseJWT as gt}from"oslo/jwt";var Re=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return k({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})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return w.error("No idToken found in token"),null;let o=gt(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as ht}from"@better-fetch/fetch";var ke=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return k({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await ht("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var wt={apple:le,discord:me,facebook:fe,github:he,microsoft:ye,google:we,spotify:be,twitch:Re,twitter:ke},Ue=Object.keys(wt);import{TimeSpan as yt}from"oslo";import{createJWT as bt,validateJWT as At}from"oslo/jwt";import{z as T}from"zod";import{APIError as M}from"better-call";async function B(e,t){return await bt("HS256",Buffer.from(e),{email:t.toLowerCase()},{expiresIn:new yt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Ee=p("/send-verification-email",{method:"POST",query:T.object({currentURL:T.string().optional()}).optional(),body:T.object({email:T.string().email(),callbackURL:T.string().optional()}),use:[U]},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled. Pass `sendVerificationEmail` in `emailAndPassword` options to enable it."),new M("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new M("BAD_REQUEST",{message:"User not found"});let o=await B(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,n,o),e.json({status:!0})}),xe=p("/verify-email",{method:"GET",query:T.object({token:T.string(),callbackURL:T.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await At("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new M("BAD_REQUEST",{message:"Invalid token"})}let n=T.object({email:T.string().email()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new M("BAD_REQUEST",{message:"User not found"});if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})});var ve=p("/sign-in/social",{method:"POST",requireHeaders:!0,query:E.object({currentURL:E.string().optional()}).optional(),body:E.object({callbackURL:E.string().optional(),provider:E.enum(Ue)}),use:[U]},async e=>{let t=e.context.socialProviders.find(a=>a.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 P("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,n=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,i=await ce(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,i.hash,e.context.secret,r.state.options);let s=Rt();await e.setSignedCookie(r.pkCodeVerifier.name,s,e.context.secret,r.pkCodeVerifier.options);let d=await t.createAuthorizationURL({state:i.raw,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:d.toString(),state:i,codeVerifier:s,redirect:!0})}),Te=p("/sign-in/email",{method:"POST",body:E.object({email:E.string().email(),password:E.string(),callbackURL:E.string().optional(),dontRememberMe:E.boolean().default(!1).optional()}),use:[U]},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 P("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!E.string().email().safeParse(t).success)throw new P("BAD_REQUEST",{message:"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 P("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw w.error("Email verification is required but no email verification handler is provided"),new P("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await B(e.context.secret,n.user.email),u=`${e.context.options.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,u,c),e.context.logger.error("Email not verified",{email:t}),new P("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let i=n.accounts.find(c=>c.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new P("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new P("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new P("UNAUTHORIZED",{message:"Invalid email or password"});let a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!a)throw e.context.logger.error("Failed to create session"),new P("UNAUTHORIZED",{message:"Failed to create session"});return await v(e,a.id,e.body.dontRememberMe),e.json({user:n.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{APIError as Ut}from"better-call";import{z as F}from"zod";import{z as m}from"zod";var Bn=m.object({id:m.string(),providerId:m.string(),accountId:m.string(),userId:m.string(),accessToken:m.string().nullable().optional(),refreshToken:m.string().nullable().optional(),idToken:m.string().nullable().optional(),expiresAt:m.date().nullable().optional(),password:m.string().optional().nullable()}),Pe=m.object({id:m.string(),email:m.string().transform(e=>e.toLowerCase()),emailVerified:m.boolean().default(!1),name:m.string(),image:m.string().optional(),createdAt:m.date().default(new Date),updatedAt:m.date().default(new Date)}),Dn=m.object({id:m.string(),userId:m.string(),expiresAt:m.date(),ipAddress:m.string().optional(),userAgent:m.string().optional()}),$n=m.object({id:m.string(),value:m.string(),expiresAt:m.date(),identifier:m.string()});function kt(e,t){let r=t.fields,o={};for(let n in r){if(n in e){if(r[n].input===!1){if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}continue}o[n]=e[n];continue}if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}}return o}function _e(e,t){let r={...e.user?.additionalFields};return kt(t||{},{fields:r})}var Se=p("/callback/:id",{method:"GET",query:F.object({state:F.string(),code:F.string().optional(),error:F.string().optional()}),metadata:L},async e=>{if(e.query.error||!e.query.code){let h=W(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${h}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(l=>l.id===e.params.id);if(!t)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 r=W(e.query.state);if(!r.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:n}}=r,i=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!i)throw w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await ae(e.query.state,i))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let d=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),a;try{a=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:d,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(l){throw e.context.logger.error(l),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let c=await t.getUserInfo(a).then(l=>l?.user),u=Ae(),y=Pe.safeParse({...c,id:u});if(!c||y.success===!1)throw w.error("Unable to get user info",y.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let g=await e.context.internalAdapter.findUserByEmail(c.email,{includeAccounts:!0}).catch(l=>{throw w.error(`Better auth was unable to query your database.
3
- Error: `,l),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),f=g?.user.id;if(g){let l=g.accounts.find(R=>R.providerId===t.id),h=e.context.options.account?.accountLinking?.trustedProviders,A=h?h.includes(t.id):!0;if(!l&&(!c.emailVerified||!A)){let R;try{R=new URL(n||o),R.searchParams.set("error","account_not_linked")}catch{throw e.redirect(`${e.context.baseURL}/error?error=account_not_linked`)}throw e.redirect(R.toString())}if(!l)try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:c.id.toString(),id:`${t.id}:${c.id}`,userId:g.user.id,...J(a)})}catch(R){throw console.log(R),e.redirect(`${e.context.baseURL}/error?error=failed_linking_account`)}}else try{let l=c.emailVerified,h=await e.context.internalAdapter.createOAuthUser({...y.data,emailVerified:l},{...J(a),id:`${t.id}:${c.id}`,providerId:t.id,accountId:c.id.toString()});if(!l&&h&&e.context.options.emailVerification?.sendOnSignUp){let A=await B(e.context.secret,c.email),R=`${e.context.baseURL}/verify-email?token=${A}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(h.user,R,A)}}catch{let h=new URL(n||o);throw h.searchParams.set("error","unable_to_create_user"),e.redirect(h.toString())}if(!f&&!u)throw new Ut("INTERNAL_SERVER_ERROR",{message:"Unable to create user"});try{let l=await e.context.internalAdapter.createSession(f||u,e.request);if(!l){let h=new URL(n||o);throw h.searchParams.set("error","unable_to_create_session"),e.redirect(h.toString())}try{await v(e,l.id)}catch(h){e.context.logger.error("Unable to set session cookie",h);let A=new URL(n||o);throw A.searchParams.set("error","unable_to_create_session"),e.redirect(A.toString())}}catch{let l=new URL(n||o||"");throw l.searchParams.set("error","unable_to_create_session"),e.redirect(l.toString())}throw e.redirect(o)});import{APIError as j}from"better-call";var H=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as Le}from"zod";var K=()=>p("/session",{method:"GET",requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return z(e),r&&await e.context.internalAdapter.deleteSession(r.session.id),e.json(null,{status:401});if(await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(r);let n=e.context.sessionConfig.expiresIn,i=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+i*1e3<=Date.now()){let a=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:H(e.context.sessionConfig.expiresIn,"sec")});if(!a)return z(e),e.json(null,{status:401});let c=(a.expiresAt.valueOf()-Date.now())/1e3;return await v(e,a.id,!1,{maxAge:c}),e.json({session:a,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),Et=async e=>await K()({...e,_flag:"json",headers:e.headers}),O=$(async e=>{let t=await Et(e);if(!t?.session)throw new j("UNAUTHORIZED");return{session:t}}),Oe=()=>p("/user/list-sessions",{method:"GET",use:[O],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Ie=p("/user/revoke-session",{method:"POST",body:Le.object({id:Le.string()}),use:[O],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new j("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new j("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new j("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Ce=p("/user/revoke-sessions",{method:"POST",use:[O],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new j("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});import"zod";import{APIError as xt}from"better-call";var Be=p("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new xt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),z(e),e.json({success:!0})});import{z as S}from"zod";import{APIError as G}from"better-call";var De=p("/forget-password",{method:"POST",body:S.object({email:S.string().email(),redirectTo:S.string()}),use:[U]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new G("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=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n)),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let d=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,d),e.json({status:!0})}),$e=p("/reset-password/:token",{method:"GET",query:S.object({callbackURL:S.string()}),use:[U]},async e=>{let{token:t}=e.params,r=e.query.callbackURL,o=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}?token=${t}`)}),Ve=p("/reset-password",{query:S.object({token:S.string()}).optional(),method:"POST",body:S.object({newPassword:S.string()})},async e=>{let t=e.query?.token;if(!t)throw new G("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new G("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(i)).find(u=>u.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(i,s))throw new G("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as x}from"zod";import{APIError as _}from"better-call";var ze=p("/user/update",{method:"POST",body:x.object({name:x.string().optional(),image:x.string().optional()}),use:[O,U]},async e=>{let{name:t,image:r}=e.body,o=e.context.session;if(!r&&!t)return e.json({user:o.user});let n=await e.context.internalAdapter.updateUserByEmail(o.user.email,{name:t,image:r});return e.json({user:n})}),je=p("/user/change-password",{method:"POST",body:x.object({newPassword:x.string(),currentPassword:x.string(),revokeOtherSessions:x.boolean().optional()}),use:[O]},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 _("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new _("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(y=>y.providerId==="credential"&&y.password);if(!a||!a.password)throw new _("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(a.password,r))throw new _("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(a.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let y=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!y)throw new _("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await v(e,y.id)}return e.json(n.user)}),qe=p("/user/set-password",{method:"POST",body:x.object({newPassword:x.string()}),use:[O]},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 _("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new _("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password),d=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:d}),e.json(r.user);throw new _("BAD_REQUEST",{message:"user already has a password"})}),Ne=p("/user/delete",{method:"POST",body:x.object({password:x.string()}),use:[O]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password);if(!n||!n.password)throw new _("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new _("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),e.json(null)});var Me=p("/csrf",{method:"GET",metadata:L},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t){let[i,s]=t.split("!")||[null,null];return e.json({csrfToken:i})}let r=Y(32,ee("a-z","0-9","A-Z")),o=await q(e.context.secret,r),n=`${r}!${o}`;return await e.setSignedCookie(e.context.authCookies.csrfToken.name,n,e.context.secret,e.context.authCookies.csrfToken.options),e.json({csrfToken:r})});var vt=(e="Unknown")=>`<!DOCTYPE html>
1
+ import{APIError as et,createRouter as $t,statusCode as Vt}from"better-call";import{APIError as W}from"better-call";import{z as se}from"zod";import{xchacha20poly1305 as Jt}from"@noble/ciphers/chacha";import{bytesToHex as Xt,hexToBytes as Yt,utf8ToBytes as er}from"@noble/ciphers/utils";import{managedNonce as rr}from"@noble/ciphers/webcrypto";import{sha256 as nr}from"oslo/crypto";function Z(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let n=0;for(let i=0;i<r.length;i++)n|=r[i]^o[i];return n===0}import{decodeHex as Nt,encodeHex as Mt}from"oslo/encoding";import{scryptAsync as Qt}from"@noble/hashes/scrypt";function tt(e){return e.toString(2).padStart(8,"0")}function rt(e){return[...e].map(t=>tt(t)).join("")}function te(e){return parseInt(rt(e),2)}function ot(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));crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=te(o);for(;n>=e;)crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=te(o);return n}function re(e,t){let r="";for(let o=0;o<e;o++)r+=t[ot(t.length)];return r}function oe(...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}async function N(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),i=await crypto.subtle.sign(o.name,n,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(i)))}import{createEndpointCreator as nt,createMiddleware as ne,createMiddlewareCreator as it}from"better-call";var ie=ne(async()=>({})),$=it({use:[ie,ne(async()=>({}))]}),p=nt({use:[ie]});var ae=$({body:se.object({csrfToken:se.string().optional()}).optional()},async e=>{if(e.request?.method!=="POST"||e.context.options.advanced?.disableCSRFCheck)return;let t=new URL(e.request.url);if(e.context.trustedOrigins.includes(t.origin))return;let r=e.body?.csrfToken;if(!r)throw new W("UNAUTHORIZED",{message:"CSRF Token is required"});let o=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[n,i]=o?.split("!")||[null,null];if(!r||!o||!n||!i||n!==r)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new W("UNAUTHORIZED",{message:"Invalid CSRF Token"});let s=await N(e.context.secret,n);if(i!==s)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new W("UNAUTHORIZED",{message:"Invalid CSRF Token"})});import{APIError as _}from"better-call";import{generateCodeVerifier as vt}from"oslo/oauth2";import{z as x}from"zod";import{generateState as st}from"oslo/oauth2";import{z as M}from"zod";import{sha256 as ce}from"oslo/crypto";async function de(e){let t=await ce(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function le(e,t){let r=await ce(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return Z(r,o)}import"better-call";async function ue(e){let t=st(),r=JSON.stringify({code:t,callbackURL:e}),o=await de(r);return{raw:r,hash:o}}function J(e){return M.object({code:M.string(),callbackURL:M.string().optional(),currentURL:M.string().optional()}).safeParse(JSON.parse(e))}import{TimeSpan as _r}from"oslo";var C=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};async function P(e,t,r,o){let n=e.context.authCookies.sessionToken.options;n.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options)}function j(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}import{APIError as pe}from"better-call";import{createConsola as at}from"consola";var B=at({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),ct=e=>({log:(...t)=>{!e?.disabled&&B.log("",...t)},error:(...t)=>{!e?.disabled&&B.error("",...t)},warn:(...t)=>{!e?.disabled&&B.warn("",...t)},info:(...t)=>{!e?.disabled&&B.info("",...t)},debug:(...t)=>{!e?.disabled&&B.debug("",...t)},box:(...t)=>{!e?.disabled&&B.box("",...t)},success:(...t)=>{!e?.disabled&&B.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
2
+ `)}}),y=ct();var U=$(async e=>{let t=e.body?.callbackURL||e.query?.callbackURL||e.query?.redirectTo||e.body?.redirectTo,r=e.headers?.get("referer"),o=e.query?.currentURL||r||e.context.baseURL,n=e.context.trustedOrigins;if(t?.includes("http")){let i=new URL(t).origin;if(!n.includes(i))throw y.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new pe("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let i=new URL(o).origin;if(!n.includes(i))throw y.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new pe("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as pt}from"oslo/jwt";import{sha256 as dt}from"oslo/crypto";import{base64url as lt}from"oslo/encoding";async function me(e){let t=await dt(new TextEncoder().encode(e));return lt.encode(new Uint8Array(t),{includePadding:!1})}function fe(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_at?new Date((Date.now()+e.expires_in)*1e3):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,disablePkce:d,redirectURI:a}){let c=new URL(r);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",t.clientId),c.searchParams.set("state",o),c.searchParams.set("scope",i.join(" ")),c.searchParams.set("redirect_uri",t.redirectURI||a),!d&&n){let u=await me(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",u)}if(s){let u=s.reduce((b,w)=>(b[w]=null,b),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return c}import{betterFetch as ut}from"@better-fetch/fetch";async function A({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:s,error:d}=await ut(n,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(d)throw d;return fe(s)}function K(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var ge=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=e.scope||o||["email","name","openid"];return 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}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>A({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=pt(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};import{betterFetch as mt}from"@better-fetch/fetch";var he=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["identify","email"];return 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}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await mt("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}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});import{betterFetch as ft}from"@better-fetch/fetch";var we=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["email","public_profile"];return 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})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await ft("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,emailVerified:r.email_verified},data:r}}});import{betterFetch as ye}from"@better-fetch/fetch";var be=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=e.scope||o||["user:email"];return E({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>A({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await ye("https://api.github.com/user",{auth:{type:"Bearer",token:r.accessToken}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:d}=await ye("https://api.github.com/user/emails",{auth:{type:"Bearer",token:r.accessToken}});d||(o.email=(s.find(a=>a.primary)??s[0])?.email,i=s.find(a=>a.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};import{parseJWT as gt}from"oslo/jwt";var Ae=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw y.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new C("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new C("codeVerifier is required for Google");let i=e.scope||r||["email","profile"];return E({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>A({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=gt(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});import{betterFetch as ht}from"@better-fetch/fetch";import{parseJWT as wt}from"oslo/jwt";var Re=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=e.scope||n.scopes||["openid","profile","email","User.Read"];return 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 A({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=wt(n.idToken)?.payload,s=e.profilePhotoSize||48;return await ht(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(d){if(!(e.disableProfilePhoto||!d.response.ok))try{let c=await d.response.clone().arrayBuffer(),u=Buffer.from(c).toString("base64");i.picture=`data:image/jpeg;base64, ${u}`}catch(a){y.error(a)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as yt}from"@better-fetch/fetch";var ke=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=e.scope||r||["user-read-email"];return 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})=>A({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await yt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";var I={isAction:!1};import{nanoid as bt}from"nanoid";var Ue=e=>bt(e);import{parseJWT as At}from"oslo/jwt";var Ee=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return 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})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return y.error("No idToken found in token"),null;let o=At(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as Rt}from"@better-fetch/fetch";var Te=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return E({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>A({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await Rt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var kt={apple:ge,discord:he,facebook:we,github:be,microsoft:Re,google:Ae,spotify:ke,twitch:Ee,twitter:Te},ve=Object.keys(kt);import{TimeSpan as Ut}from"oslo";import{createJWT as Et,validateJWT as Tt}from"oslo/jwt";import{z as v}from"zod";import{APIError as V}from"better-call";import{APIError as q}from"better-call";var F=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as xe}from"zod";var X=()=>p("/session",{method:"GET",requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return j(e),r&&await e.context.internalAdapter.deleteSession(r.session.id),e.json(null,{status:401});if(await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(r);let n=e.context.sessionConfig.expiresIn,i=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+i*1e3<=Date.now()){let a=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:F(e.context.sessionConfig.expiresIn,"sec")});if(!a)return j(e),e.json(null,{status:401});let c=(a.expiresAt.valueOf()-Date.now())/1e3;return await P(e,a.id,!1,{maxAge:c}),e.json({session:a,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),Y=async e=>await X()({...e,_flag:"json",headers:e.headers}),L=$(async e=>{let t=await Y(e);if(!t?.session)throw new q("UNAUTHORIZED");return{session:t}}),Pe=()=>p("/user/list-sessions",{method:"GET",use:[L],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),_e=p("/user/revoke-session",{method:"POST",body:xe.object({id:xe.string()}),use:[L],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new q("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new q("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new q("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Se=p("/user/revoke-sessions",{method:"POST",use:[L],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new q("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});import{z as k}from"zod";import{APIError as T}from"better-call";var Le=p("/user/update",{method:"POST",body:k.object({name:k.string().optional(),image:k.string().optional()}),use:[L,U]},async e=>{let{name:t,image:r}=e.body,o=e.context.session;if(!r&&!t)return e.json({user:o.user});let n=await e.context.internalAdapter.updateUserByEmail(o.user.email,{name:t,image:r});return e.json({user:n})}),Oe=p("/user/change-password",{method:"POST",body:k.object({newPassword:k.string(),currentPassword:k.string(),revokeOtherSessions:k.boolean().optional()}),use:[L]},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:"Password is 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:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(b=>b.providerId==="credential"&&b.password);if(!a||!a.password)throw new T("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(a.password,r))throw new T("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(a.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let b=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!b)throw new T("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await P(e,b.id)}return e.json(n.user)}),Ie=p("/user/set-password",{method:"POST",body:k.object({newPassword:k.string()}),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("BAD_REQUEST",{message:"Password is 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:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password),d=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:d}),e.json(r.user);throw new T("BAD_REQUEST",{message:"user already has a password"})}),Ce=p("/user/delete",{method:"POST",body:k.object({password:k.string()}),use:[L]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password);if(!n||!n.password)throw new T("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new T("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),e.json(null)}),Be=p("/user/change-email",{method:"POST",query:k.object({currentURL:k.string().optional()}).optional(),body:k.object({newEmail:k.string(),callbackURL:k.string().optional()}),use:[L,U]},async e=>{if(e.context.options.user?.changeEmail?.disable===!0)throw e.context.logger.error("Change email is disabled."),new T("BAD_REQUEST",{message:"Change email is disabled"});if(e.context.options.user?.changeEmail?.sendVerificationEmail===!1){let o=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:o,status:!0})}if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new T("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await O(e.context.secret,e.context.session.user.email,e.body.newEmail),r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(e.context.session.user,r,t),e.json({user:null,status:!0})});async function O(e,t,r){return await Et("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Ut(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var De=p("/send-verification-email",{method:"POST",query:v.object({currentURL:v.string().optional()}).optional(),body:v.object({email:v.string().email(),callbackURL:v.string().optional()}),use:[U]},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new V("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new V("BAD_REQUEST",{message:"User not found"});let o=await O(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,n,o),e.json({status:!0})}),$e=p("/verify-email",{method:"GET",query:v.object({token:v.string(),callbackURL:v.string().optional()}),use:[U]},async e=>{let{token:t}=e.query,r;try{r=await Tt("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new V("BAD_REQUEST",{message:"Invalid token"})}let n=v.object({email:v.string().email(),updateTo:v.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new V("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await Y(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new V("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new V("UNAUTHORIZED",{message:"Invalid session"});let d=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo,emailVerified:!0});if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:d,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var Ve=p("/sign-in/social",{method:"POST",requireHeaders:!0,query:x.object({currentURL:x.string().optional()}).optional(),body:x.object({callbackURL:x.string().optional(),provider:x.enum(ve)}),use:[U]},async e=>{let t=e.context.socialProviders.find(a=>a.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 _("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,n=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,i=await ue(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,i.hash,e.context.secret,r.state.options);let s=vt();await e.setSignedCookie(r.pkCodeVerifier.name,s,e.context.secret,r.pkCodeVerifier.options);let d=await t.createAuthorizationURL({state:i.raw,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:d.toString(),state:i,codeVerifier:s,redirect:!0})}),ze=p("/sign-in/email",{method:"POST",body:x.object({email:x.string().email(),password:x.string(),callbackURL:x.string().optional(),dontRememberMe:x.boolean().default(!1).optional()}),use:[U]},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 _("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!x.string().email().safeParse(t).success)throw new _("BAD_REQUEST",{message:"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 _("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw y.error("Email verification is required but no email verification handler is provided"),new _("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await O(e.context.secret,n.user.email),u=`${e.context.options.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,u,c),e.context.logger.error("Email not verified",{email:t}),new _("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let i=n.accounts.find(c=>c.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new _("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new _("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new _("UNAUTHORIZED",{message:"Invalid email or password"});let a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!a)throw e.context.logger.error("Failed to create session"),new _("UNAUTHORIZED",{message:"Failed to create session"});return await P(e,a.id,e.body.dontRememberMe),e.json({user:n.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{APIError as Pt}from"better-call";import{z as H}from"zod";import{z as f}from"zod";var si=f.object({id:f.string(),providerId:f.string(),accountId:f.string(),userId:f.string(),accessToken:f.string().nullable().optional(),refreshToken:f.string().nullable().optional(),idToken:f.string().nullable().optional(),expiresAt:f.date().nullable().optional(),password:f.string().optional().nullable()}),je=f.object({id:f.string(),email:f.string().transform(e=>e.toLowerCase()),emailVerified:f.boolean().default(!1),name:f.string(),image:f.string().optional(),createdAt:f.date().default(new Date),updatedAt:f.date().default(new Date)}),ai=f.object({id:f.string(),userId:f.string(),expiresAt:f.date(),ipAddress:f.string().optional(),userAgent:f.string().optional()}),ci=f.object({id:f.string(),value:f.string(),expiresAt:f.date(),identifier:f.string()});function xt(e,t){let r=t.fields,o={};for(let n in r){if(n in e){if(r[n].input===!1){if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}continue}o[n]=e[n];continue}if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}}return o}function qe(e,t){let r={...e.user?.additionalFields};return xt(t||{},{fields:r})}var Ne=p("/callback/:id",{method:"GET",query:H.object({state:H.string(),code:H.string().optional(),error:H.string().optional()}),metadata:I},async e=>{if(e.query.error||!e.query.code){let g=J(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${g}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(l=>l.id===e.params.id);if(!t)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 r=J(e.query.state);if(!r.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:n}}=r,i=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!i)throw y.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await le(e.query.state,i))throw y.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let d=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),a;try{a=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:d,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(l){throw e.context.logger.error(l),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let c=await t.getUserInfo(a).then(l=>l?.user),u=Ue(),b=je.safeParse({...c,id:u});if(!c||b.success===!1)throw y.error("Unable to get user info",b.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let w=await e.context.internalAdapter.findUserByEmail(c.email,{includeAccounts:!0}).catch(l=>{throw y.error(`Better auth was unable to query your database.
3
+ Error: `,l),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),m=w?.user.id;if(w){let l=w.accounts.find(R=>R.providerId===t.id),g=e.context.options.account?.accountLinking?.trustedProviders,h=g?g.includes(t.id):!0;if(!l&&(!c.emailVerified||!h)){let R;try{R=new URL(n||o),R.searchParams.set("error","account_not_linked")}catch{throw e.redirect(`${e.context.baseURL}/error?error=account_not_linked`)}throw e.redirect(R.toString())}if(!l)try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:c.id.toString(),id:`${t.id}:${c.id}`,userId:w.user.id,...K(a)})}catch(R){throw console.log(R),e.redirect(`${e.context.baseURL}/error?error=failed_linking_account`)}}else try{let l=c.emailVerified,g=await e.context.internalAdapter.createOAuthUser({...b.data,emailVerified:l},{...K(a),id:`${t.id}:${c.id}`,providerId:t.id,accountId:c.id.toString()});if(!l&&g&&e.context.options.emailVerification?.sendOnSignUp){let h=await O(e.context.secret,c.email),R=`${e.context.baseURL}/verify-email?token=${h}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(g.user,R,h)}}catch{let g=new URL(n||o);throw g.searchParams.set("error","unable_to_create_user"),e.redirect(g.toString())}if(!m&&!u)throw new Pt("INTERNAL_SERVER_ERROR",{message:"Unable to create user"});try{let l=await e.context.internalAdapter.createSession(m||u,e.request);if(!l){let g=new URL(n||o);throw g.searchParams.set("error","unable_to_create_session"),e.redirect(g.toString())}try{await P(e,l.id)}catch(g){e.context.logger.error("Unable to set session cookie",g);let h=new URL(n||o);throw h.searchParams.set("error","unable_to_create_session"),e.redirect(h.toString())}}catch{let l=new URL(n||o||"");throw l.searchParams.set("error","unable_to_create_session"),e.redirect(l.toString())}throw e.redirect(o)});import"zod";import{APIError as _t}from"better-call";var Me=p("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new _t("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),j(e),e.json({success:!0})});import{z as S}from"zod";import{APIError as Q}from"better-call";var Fe=p("/forget-password",{method:"POST",body:S.object({email:S.string().email(),redirectTo:S.string()}),use:[U]},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 Q("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=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n)),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let d=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,d),e.json({status:!0})}),He=p("/reset-password/:token",{method:"GET",query:S.object({callbackURL:S.string()}),use:[U]},async e=>{let{token:t}=e.params,r=e.query.callbackURL,o=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}?token=${t}`)}),Qe=p("/reset-password",{query:S.optional(S.object({token:S.string()})),method:"POST",body:S.object({newPassword:S.string()})},async e=>{let t=e.query?.token;if(!t)throw new Q("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new Q("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(i)).find(u=>u.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(i,s))throw new Q("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});var Ge=p("/csrf",{method:"GET",metadata:I},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t){let[i,s]=t.split("!")||[null,null];return e.json({csrfToken:i})}let r=re(32,oe("a-z","0-9","A-Z")),o=await N(e.context.secret,r),n=`${r}!${o}`;return await e.setSignedCookie(e.context.authCookies.csrfToken.name,n,e.context.secret,e.context.authCookies.csrfToken.options),e.json({csrfToken:r})});var St=(e="Unknown")=>`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">
@@ -80,4 +80,4 @@ Error: `,l),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
80
80
  <div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
81
81
  </div>
82
82
  </body>
83
- </html>`,Fe=p("/error",{method:"GET",metadata:L},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(vt(t),{headers:{"Content-Type":"text/html"}})});var He=p("/ok",{method:"GET",metadata:L},async e=>e.json({ok:!0}));import{z as V}from"zod";import{APIError as D}from"better-call";var Ge=()=>p("/sign-up/email",{method:"POST",query:V.object({currentURL:V.string().optional()}).optional(),body:V.record(V.string(),V.any()),use:[U]},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new D("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:n,image:i,callbackURL:s,...d}=t;if(!V.string().email().safeParse(o).success)throw new D("BAD_REQUEST",{message:"Invalid email"});let c=e.context.password.config.minPasswordLength;if(n.length<c)throw e.context.logger.error("Password is too short"),new D("BAD_REQUEST",{message:"Password is too short"});let u=e.context.password.config.maxPasswordLength;if(n.length>u)throw e.context.logger.error("Password is too long"),new D("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new D("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let g=_e(e.context.options,d),f=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...g,emailVerified:!1});if(!f)throw new D("BAD_REQUEST",{message:"Failed to create user"});let l=await e.context.password.hash(n);if(await e.context.internalAdapter.linkAccount({userId:f.id,providerId:"credential",accountId:f.id,password:l,expiresAt:H(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let A=await B(e.context.secret,f.email),R=`${e.context.baseURL}/verify-email?token=${A}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(f,R,A)}if(!e.context.options.emailAndPassword.autoSignIn)return e.json({user:f,session:null},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:f,session:null}});let h=await e.context.internalAdapter.createSession(f.id,e.request);if(!h)throw new D("BAD_REQUEST",{message:"Failed to create session"});return await v(e,h.id),e.json({user:f,session:h},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:f,session:h}})});function Qe(e){let t="127.0.0.1";if(process.env.NODE_ENV==="test")return t;let r=["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"];for(let o of r){let n=e.headers.get(o);if(typeof n=="string"){let i=n.split(",")[0].trim();if(i)return i}}return null}function Tt(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function Pt(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":e.toString()}})}function _t(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function St(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async n=>await o.findOne({model:r,where:[{field:"key",value:n}]}),set:async(n,i,s)=>{try{s?await o.update({model:t??"rateLimit",where:[{field:"key",value:n}],update:{count:i.count,lastRequest:i.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:n,count:i.count,lastRequest:i.lastRequest}})}catch(d){w.error("Error setting rate limit",d)}}}}var Ze=new Map;function Lt(e){return e.rateLimit.storage==="secondary-storage"?{get:async r=>{let o=await e.options.secondaryStorage?.get(r);return o?JSON.parse(o):void 0},set:async(r,o)=>{await e.options.secondaryStorage?.set?.(r,JSON.stringify(o))}}:e.rateLimit.storage==="memory"?{async get(r){return Ze.get(r)},async set(r,o,n){Ze.set(r,o)}}:St(e,e.rateLimit.tableName)}async function We(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),n=t.rateLimit.window,i=t.rateLimit.max,s=Qe(e)+o,a=Ot().find(g=>g.pathMatcher(o));a&&(n=a.window,i=a.max);for(let g of t.options.plugins||[])if(g.rateLimit){let f=g.rateLimit.find(l=>l.pathMatcher(o));if(f){n=f.window,i=f.max;break}}if(t.rateLimit.customRules){let g=t.rateLimit.customRules[o];g&&(n=g.window,i=g.max)}let c=Lt(t),u=await c.get(s),y=Date.now();if(!u)await c.set(s,{key:s,count:1,lastRequest:y});else{let g=y-u.lastRequest;if(Tt(i,n,u)){let f=_t(u.lastRequest,n);return Pt(f)}else g>n*1e3?await c.set(s,{...u,count:1,lastRequest:y}):await c.set(s,{...u,count:u.count+1,lastRequest:y})}}function Ot(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:7}]}import{APIError as Ls}from"better-call";function Bt(e,t){let r=t.plugins?.reduce((d,a)=>({...d,...a.endpoints}),{}),o=t.plugins?.map(d=>d.middlewares?.map(a=>{let c=async u=>a.middleware({...u,context:{...e,...u.context}});return c.path=a.path,c.options=a.middleware.options,c.headers=a.middleware.headers,{path:a.path,middleware:c}})).filter(d=>d!==void 0).flat()||[],i={...{signInOAuth:ve,callbackOAuth:Se,getCSRFToken:Me,getSession:K(),signOut:Be,signUpEmail:Ge(),signInEmail:Te,forgetPassword:De,resetPassword:Ve,verifyEmail:xe,sendVerificationEmail:Ee,changePassword:je,setPassword:qe,updateUser:ze,deleteUser:Ne,forgetPasswordCallback:$e,listSessions:Oe(),revokeSession:Ie,revokeSessions:Ce},...r,ok:He,error:Fe},s={};for(let[d,a]of Object.entries(i))s[d]=async(c={})=>{let u=await e;for(let f of t.plugins||[])if(f.hooks?.before){for(let l of f.hooks.before)if(l.matcher({...a,...c,context:u})){let A=await l.handler({...c,context:{...u,...c?.context}});A&&"context"in A&&(u={...u,...A.context})}}let g=await a({...c,context:{...u,...c.context}});for(let f of t.plugins||[])if(f.hooks?.after){for(let l of f.hooks.after)if(l.matcher(c)){let A=Object.assign(c,{context:{...e,returned:g}}),R=await l.handler(A);R&&"response"in R&&(g=R.response)}}return g},s[d].path=a.path,s[d].method=a.method,s[d].options=a.options,s[d].headers=a.headers;return{api:s,middlewares:o}}var xs=(e,t)=>{let{api:r,middlewares:o}=Bt(e,t),n=new URL(e.baseURL).pathname;return Ct(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:ne},...o],async onRequest(i){for(let s of e.options.plugins||[])if(s.onRequest){let d=await s.onRequest(i,e);if(d)return d}return We(i,e)},async onResponse(i){for(let s of e.options.plugins||[])if(s.onResponse){let d=await s.onResponse(i,e);if(d)return d.response}return i},onError(i){if(t.onAPIError?.throw)throw i;if(t.onAPIError?.onError){t.onAPIError.onError(i,e);return}let s=t.logger?.verboseLogging?w:void 0;t.logger?.disabled!==!0&&(i instanceof It?(i.status==="INTERNAL_SERVER_ERROR"&&w.error(i),s?.error(i.message)):w?.error(i))}})};export{Ls as APIError,Se as callbackOAuth,je as changePassword,p as createAuthEndpoint,$ as createAuthMiddleware,B as createEmailVerificationToken,ne as csrfMiddleware,Ne as deleteUser,Fe as error,De as forgetPassword,$e as forgetPasswordCallback,Me as getCSRFToken,Bt as getEndpoints,K as getSession,Et as getSessionFromCtx,Oe as listSessions,He as ok,re as optionsMiddleware,Ve as resetPassword,Ie as revokeSession,Ce as revokeSessions,xs as router,Ee as sendVerificationEmail,O as sessionMiddleware,qe as setPassword,Te as signInEmail,ve as signInOAuth,Be as signOut,Ge as signUpEmail,ze as updateUser,xe as verifyEmail};
83
+ </html>`,Ze=p("/error",{method:"GET",metadata:I},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(St(t),{headers:{"Content-Type":"text/html"}})});var We=p("/ok",{method:"GET",metadata:I},async e=>e.json({ok:!0}));import{z}from"zod";import{APIError as D}from"better-call";var Je=()=>p("/sign-up/email",{method:"POST",query:z.object({currentURL:z.string().optional()}).optional(),body:z.record(z.string(),z.any()),use:[U]},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new D("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:n,image:i,callbackURL:s,...d}=t;if(!z.string().email().safeParse(o).success)throw new D("BAD_REQUEST",{message:"Invalid email"});let c=e.context.password.config.minPasswordLength;if(n.length<c)throw e.context.logger.error("Password is too short"),new D("BAD_REQUEST",{message:"Password is too short"});let u=e.context.password.config.maxPasswordLength;if(n.length>u)throw e.context.logger.error("Password is too long"),new D("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new D("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let w=qe(e.context.options,d),m=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...w,emailVerified:!1});if(!m)throw new D("BAD_REQUEST",{message:"Failed to create user"});let l=await e.context.password.hash(n);if(await e.context.internalAdapter.linkAccount({userId:m.id,providerId:"credential",accountId:m.id,password:l,expiresAt:F(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let h=await O(e.context.secret,m.email),R=`${e.context.baseURL}/verify-email?token=${h}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(m,R,h)}if(!e.context.options.emailAndPassword.autoSignIn)return e.json({user:m,session:null},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:m,session:null}});let g=await e.context.internalAdapter.createSession(m.id,e.request);if(!g)throw new D("BAD_REQUEST",{message:"Failed to create session"});return await P(e,g.id),e.json({user:m,session:g},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:m,session:g}})});function Ke(e){let t="127.0.0.1";if(process.env.NODE_ENV==="test")return t;let r=["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"];for(let o of r){let n=e.headers.get(o);if(typeof n=="string"){let i=n.split(",")[0].trim();if(i)return i}}return null}function Lt(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function Ot(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":e.toString()}})}function It(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function Ct(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async n=>await o.findOne({model:r,where:[{field:"key",value:n}]}),set:async(n,i,s)=>{try{s?await o.update({model:t??"rateLimit",where:[{field:"key",value:n}],update:{count:i.count,lastRequest:i.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:n,count:i.count,lastRequest:i.lastRequest}})}catch(d){y.error("Error setting rate limit",d)}}}}var Xe=new Map;function Bt(e){return e.rateLimit.storage==="secondary-storage"?{get:async r=>{let o=await e.options.secondaryStorage?.get(r);return o?JSON.parse(o):void 0},set:async(r,o)=>{await e.options.secondaryStorage?.set?.(r,JSON.stringify(o))}}:e.rateLimit.storage==="memory"?{async get(r){return Xe.get(r)},async set(r,o,n){Xe.set(r,o)}}:Ct(e,e.rateLimit.tableName)}async function Ye(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),n=t.rateLimit.window,i=t.rateLimit.max,s=Ke(e)+o,a=Dt().find(w=>w.pathMatcher(o));a&&(n=a.window,i=a.max);for(let w of t.options.plugins||[])if(w.rateLimit){let m=w.rateLimit.find(l=>l.pathMatcher(o));if(m){n=m.window,i=m.max;break}}if(t.rateLimit.customRules){let w=t.rateLimit.customRules[o];w&&(n=w.window,i=w.max)}let c=Bt(t),u=await c.get(s),b=Date.now();if(!u)await c.set(s,{key:s,count:1,lastRequest:b});else{let w=b-u.lastRequest;if(Lt(i,n,u)){let m=It(u.lastRequest,n);return Ot(m)}else w>n*1e3?await c.set(s,{...u,count:1,lastRequest:b}):await c.set(s,{...u,count:u.count+1,lastRequest:b})}}function Dt(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:7}]}import{APIError as zs}from"better-call";function zt(e,t){let r=t.plugins?.reduce((d,a)=>({...d,...a.endpoints}),{}),o=t.plugins?.map(d=>d.middlewares?.map(a=>{let c=async u=>a.middleware({...u,context:{...e,...u.context}});return c.path=a.path,c.options=a.middleware.options,c.headers=a.middleware.headers,{path:a.path,middleware:c}})).filter(d=>d!==void 0).flat()||[],i={...{signInOAuth:Ve,callbackOAuth:Ne,getCSRFToken:Ge,getSession:X(),signOut:Me,signUpEmail:Je(),signInEmail:ze,forgetPassword:Fe,resetPassword:Qe,verifyEmail:$e,sendVerificationEmail:De,changeEmail:Be,changePassword:Oe,setPassword:Ie,updateUser:Le,deleteUser:Ce,forgetPasswordCallback:He,listSessions:Pe(),revokeSession:_e,revokeSessions:Se},...r,ok:We,error:Ze},s={};for(let[d,a]of Object.entries(i))s[d]=async(c={})=>{let u=await e;for(let m of t.plugins||[])if(m.hooks?.before){for(let l of m.hooks.before)if(l.matcher({...a,...c,context:u})){let h=await l.handler({...c,context:{...u,...c?.context}});h&&"context"in h&&(u={...u,...h.context})}}let b;try{b=await a({...c,context:{...u,...c.context}})}catch(m){if(m instanceof et){let l=t.plugins?.map(h=>{if(h.hooks?.after)return h.hooks.after}).filter(h=>h!==void 0).flat();if(!l?.length)throw m;let g=new Response(JSON.stringify(m.body),{status:Vt[m.status],headers:m.headers});for(let h of l||[])if(h.matcher(c)){let ee=Object.assign(c,{context:{...e,returned:g}}),G=await h.handler(ee);G&&"response"in G&&(g=G.response)}return g}throw m}let w=b;for(let m of t.plugins||[])if(m.hooks?.after){for(let l of m.hooks.after)if(l.matcher(c)){let h=Object.assign(c,{context:{...e,returned:w}}),R=await l.handler(h);R&&"response"in R&&(w=R.response)}}return w},s[d].path=a.path,s[d].method=a.method,s[d].options=a.options,s[d].headers=a.headers;return{api:s,middlewares:o}}var Is=(e,t)=>{let{api:r,middlewares:o}=zt(e,t),n=new URL(e.baseURL).pathname;return $t(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:ae},...o],async onRequest(i){for(let s of e.options.plugins||[])if(s.onRequest){let d=await s.onRequest(i,e);if(d)return d}return Ye(i,e)},async onResponse(i){for(let s of e.options.plugins||[])if(s.onResponse){let d=await s.onResponse(i,e);if(d)return d.response}return i},onError(i){if(t.onAPIError?.throw)throw i;if(t.onAPIError?.onError){t.onAPIError.onError(i,e);return}let s=t.logger?.verboseLogging?y:void 0;t.logger?.disabled!==!0&&(i instanceof et?(i.status==="INTERNAL_SERVER_ERROR"&&y.error(i),s?.error(i.message)):y?.error(i))}})};export{zs as APIError,Ne as callbackOAuth,Be as changeEmail,Oe as changePassword,p as createAuthEndpoint,$ as createAuthMiddleware,O as createEmailVerificationToken,ae as csrfMiddleware,Ce as deleteUser,Ze as error,Fe as forgetPassword,He as forgetPasswordCallback,Ge as getCSRFToken,zt as getEndpoints,X as getSession,Y as getSessionFromCtx,Pe as listSessions,We as ok,ie as optionsMiddleware,Qe as resetPassword,_e as revokeSession,Se as revokeSessions,Is as router,De as sendVerificationEmail,L as sessionMiddleware,Ie as setPassword,ze as signInEmail,Ve as signInOAuth,Me as signOut,Je as signUpEmail,Le as updateUser,$e as verifyEmail};