better-auth 0.4.10-beta.1 → 0.4.10-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-2pRFLprr.js';
1
+ import { A as Adapter } from '../auth-Nmre53Xe.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 { f as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-2pRFLprr.js';
2
+ import { f as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-Nmre53Xe.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-2pRFLprr.js';
2
+ import { W as Where } from '../auth-Nmre53Xe.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-2pRFLprr.js';
1
+ import { A as Adapter } from '../auth-Nmre53Xe.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 { b as AuthEndpoint, d as AuthMiddleware, a0 as callbackOAuth, af as changePassword, a 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-2pRFLprr.js';
1
+ export { b as AuthEndpoint, d as AuthMiddleware, a0 as callbackOAuth, af as changePassword, a 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-Nmre53Xe.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
1
  import{APIError as qt,createRouter as Vt}from"better-call";import{APIError as J}from"better-call";import{z as se}from"zod";import{xchacha20poly1305 as er}from"@noble/ciphers/chacha";import{bytesToHex as rr,hexToBytes as or,utf8ToBytes as nr}from"@noble/ciphers/utils";import{managedNonce as ir}from"@noble/ciphers/webcrypto";import{sha256 as dr}from"oslo/crypto";function W(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let n=0;for(let s=0;s<r.length;s++)n|=r[s]^o[s];return n===0}import{decodeHex as Qt,encodeHex as Gt}from"oslo/encoding";import{scryptAsync as Jt}from"@noble/hashes/scrypt";function et(e){return e.toString(2).padStart(8,"0")}function tt(e){return[...e].map(t=>et(t)).join("")}function re(e){return parseInt(tt(e),2)}function rt(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=re(o);for(;n>=e;)crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=re(o);return n}function N(e,t){let r="";for(let o=0;o<e;o++)r+=t[rt(t.length)];return r}function F(...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 H(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"]),s=await crypto.subtle.sign(o.name,n,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(s)))}import{createEndpointCreator as ot,createMiddleware as oe,createMiddlewareCreator as nt}from"better-call";var ne=oe(async()=>({})),z=nt({use:[ne,oe(async()=>({}))]}),u=ot({use:[ne]});var ie=z({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 J("UNAUTHORIZED",{message:"CSRF Token is required"});let o=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[n,s]=o?.split("!")||[null,null];if(!r||!o||!n||!s||o!==r)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new J("UNAUTHORIZED",{message:"Invalid CSRF Token"});let i=await H(e.context.secret,n);if(s!==i)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new J("UNAUTHORIZED",{message:"Invalid CSRF Token"})});import{APIError as O}from"better-call";import{generateCodeVerifier as kt}from"oslo/oauth2";import{z as T}from"zod";import{generateState as st}from"oslo/oauth2";import{z as Q}from"zod";import{sha256 as ae}from"oslo/crypto";async function de(e){let t=await ae(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function ce(e,t){let r=await ae(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return W(r,o)}async function ue(e){let t=st(),r=JSON.stringify({code:t,callbackURL:e}),o=await de(r);return{raw:r,hash:o}}function K(e){return Q.object({code:Q.string(),callbackURL:Q.string().optional(),currentURL:Q.string().optional()}).safeParse(JSON.parse(e))}import{TimeSpan as Lr}from"oslo";var L=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 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 it}from"consola";var B=it({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),at=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=at();var x=z(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 s=new URL(t).origin;if(!n.includes(s))throw y.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new pe("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let s=new URL(o).origin;if(!n.includes(s))throw y.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new pe("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as lt}from"oslo/jwt";import{sha256 as ct}from"oslo/crypto";function dt(e){try{return new URL(e).pathname!=="/"}catch{throw new L(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function X(e,t="/api/auth"){return dt(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function le(e,t){if(e)return X(e,t);let r=typeof process<"u"?process.env:{},o=r.BETTER_AUTH_URL||r.NEXT_PUBLIC_BETTER_AUTH_URL||r.PUBLIC_BETTER_AUTH_URL||r.NUXT_PUBLIC_BETTER_AUTH_URL||r.NUXT_PUBLIC_AUTH_URL||(r.BASE_URL!=="/"?r.BASE_URL:void 0);if(o)return X(o,t);if(typeof window<"u")return X(window.location.origin,t)}import{base64url as ut}from"oslo/encoding";function h(e,t){return t||`${le()}/callback/${e}`}async function me(e){let t=await ct(new TextEncoder().encode(e));return ut.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?.split(" ")||[],idToken:e.id_token}}async function R({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:s,disablePkce:i}){let a=new URL(r);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",t.clientId),a.searchParams.set("state",o),a.searchParams.set("scope",s.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||h(e)),!i&&n){let d=await me(n);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",d)}return a}import{betterFetch as pt}from"@better-fetch/fetch";async function b({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let s=new URLSearchParams;s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:i,error:a}=await pt(n,{method:"POST",body:s,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(a)throw a;return fe(i)}function Y(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 s=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=${s.join(" ")}&state=${r}`)},validateAuthorizationCode:async(r,o,n)=>b({code:r,codeVerifier:o,redirectURI:n||h("apple",e.redirectURI),options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=lt(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}){let o=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${o.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(h("discord",e.redirectURI))}&state=${t}`)},validateAuthorizationCode:async(t,r,o)=>b({code:t,redirectURI:o||h("discord",e.redirectURI),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,codeVerifier:o}){let n=e.scope||r||["email","public_profile"];return await R({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v16.0/dialog/oauth",scopes:n,state:t,codeVerifier:o})},validateAuthorizationCode:async(t,r,o)=>b({code:t,codeVerifier:r,redirectURI:o||h("facebook",e.redirectURI),options:e,tokenEndpoint:"https://graph.facebook.com/v16.0/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await ft("https://graph.facebook.com/me",{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}){let s=e.scope||o||["user:email"];return R({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,codeVerifier:n})},validateAuthorizationCode:async(r,o,n)=>b({code:r,redirectURI:e.redirectURI||h("google",n),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 s=!1;if(!o.email){let{data:i,error:a}=await ye("https://api.github.com/user/emails",{auth:{type:"Bearer",token:r.accessToken}});a||(o.email=(i.find(d=>d.primary)??i[0])?.email,s=i.find(d=>d.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:s},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 L("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new L("codeVerifier is required for Google");let s=e.scope||r||["email","profile"];return R({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:s,state:t,codeVerifier:o})},validateAuthorizationCode:async(t,r,o)=>b({code:t,codeVerifier:r,redirectURI:o||h("google",e.redirectURI),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 s=e.scope||n.scopes||["openid","profile","email","User.Read"];return R({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:s})},validateAuthorizationCode(n,s,i){return b({code:n,codeVerifier:s,redirectURI:i||h("microsoft",e.redirectURI),options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let s=wt(n.idToken)?.payload,i=e.profilePhotoSize||48;return await ht(`https://graph.microsoft.com/v1.0/me/photos/${i}x${i}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let c=await a.response.clone().arrayBuffer(),m=Buffer.from(c).toString("base64");s.picture=`data:image/jpeg;base64, ${m}`}catch(d){y.error(d)}}}),{user:{id:s.sub,name:s.name,email:s.email,image:s.picture,emailVerified:!0},data:s}}}};import{betterFetch as yt}from"@better-fetch/fetch";var ke=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o}){let n=e.scope||r||["user-read-email"];return R({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o})},validateAuthorizationCode:async(t,r,o)=>b({code:t,codeVerifier:r,redirectURI:o||h("spotify",e.redirectURI),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{betterFetch as bt}from"@better-fetch/fetch";var Ue=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r}){let o=e.scope||r||["activity:write","read"];return R({id:"twitch",options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:t})},validateAuthorizationCode:async(t,r,o)=>b({code:t,redirectURI:o||h("twitch",e.redirectURI),options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await bt("https://api.twitch.tv/helix/users",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.sub,name:r.preferred_username,email:r.email,image:r.picture,emailVerified:!1},data:r}}});import{betterFetch as At}from"@better-fetch/fetch";var Ee=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return R({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier})},validateAuthorizationCode:async(t,r,o)=>b({code:t,codeVerifier:r,redirectURI:o||h("twitch",e.redirectURI),options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await At("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 Rt={apple:ge,discord:he,facebook:we,github:be,microsoft:Re,google:Ae,spotify:ke,twitch:Ue,twitter:Ee},xe=Object.keys(Rt);var Te=u("/sign-in/social",{method:"POST",requireHeaders:!0,query:T.object({currentURL:T.string().optional()}).optional(),body:T.object({callbackURL:T.string().optional(),provider:T.enum(xe)}),use:[x]},async e=>{let t=e.context.socialProviders.find(d=>d.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider to your auth config",{provider:e.body.provider}),new O("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||""}`,s=await ue(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,s.hash,e.context.secret,r.state.options);let i=kt();await e.setSignedCookie(r.pkCodeVerifier.name,i,e.context.secret,r.pkCodeVerifier.options);let a=await t.createAuthorizationURL({state:s.raw,codeVerifier:i});return a.searchParams.set("redirect_uri",`${e.context.baseURL}/callback/${e.body.provider}`),e.json({url:a.toString(),state:s,codeVerifier:i,redirect:!0})}),Pe=u("/sign-in/email",{method:"POST",body:T.object({email:T.string().email(),password:T.string(),callbackURL:T.string().optional(),dontRememberMe:T.boolean().default(!1).optional()}),use:[x]},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 O("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!T.string().email().safeParse(t).success)throw new O("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 O("UNAUTHORIZED",{message:"Invalid email or password"});let s=n.accounts.find(c=>c.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new O("UNAUTHORIZED",{message:"Invalid email or password"});let i=s?.password;if(!i)throw e.context.logger.error("Password not found",{email:t}),new O("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(i,r))throw e.context.logger.error("Invalid password"),new O("UNAUTHORIZED",{message:"Invalid email or password"});let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new O("UNAUTHORIZED",{message:"Failed to create session"});return await v(e,d.id,e.body.dontRememberMe),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{APIError as Et}from"better-call";import{z as G}from"zod";import{z as l}from"zod";var mn=l.object({id:l.string(),providerId:l.string(),accountId:l.string(),userId:l.string(),accessToken:l.string().nullable().optional(),refreshToken:l.string().nullable().optional(),idToken:l.string().nullable().optional(),expiresAt:l.date().nullable().optional(),password:l.string().optional().nullable()}),ve=l.object({id:l.string(),email:l.string().transform(e=>e.toLowerCase()),emailVerified:l.boolean().default(!1),name:l.string(),image:l.string().optional(),createdAt:l.date().default(new Date),updatedAt:l.date().default(new Date)}),fn=l.object({id:l.string(),userId:l.string(),expiresAt:l.date(),ipAddress:l.string().optional(),userAgent:l.string().optional()}),gn=l.object({id:l.string(),value:l.string(),expiresAt:l.date(),identifier:l.string()});function Ut(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 Ut(t||{},{fields:r})}var Se=e=>N(e||21,F("a-z","0-9","A-Z"));var I={isAction:!1};var Le=u("/callback/:id",{method:"GET",query:G.object({state:G.string(),code:G.string().optional(),error:G.string().optional()}),metadata:I},async e=>{if(e.query.error||!e.query.code){let w=K(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${w}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(p=>p.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=K(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,s=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!s)throw y.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await ce(e.query.state,s))throw y.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let a=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),d;try{d=await t.validateAuthorizationCode(e.query.code,a,`${e.context.baseURL}/callback/${t.id}`)}catch(p){throw console.log(p),e.context.logger.error(p),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let c=await t.getUserInfo(d).then(p=>p?.user),m=Se(),A=ve.safeParse({...c,id:m});if(!c||A.success===!1)throw y.error("Unable to get user info",A.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(p=>{throw y.error(`Better auth was unable to query your database.
3
- Error: `,p),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),f=g?.user.id;if(g){let p=g.accounts.find(U=>U.providerId===t.id),w=e.context.options.account?.accountLinking?.trustedProviders,k=w?w.includes(t.id):!0;if(!p&&(!c.emailVerified||!k)){let U;try{U=new URL(n||o),U.searchParams.set("error","account_not_linked")}catch{throw e.redirect(`${e.context.baseURL}/error?error=account_not_linked`)}throw e.redirect(U.toString())}if(!p)try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:c.id.toString(),id:`${t.id}:${c.id}`,userId:g.user.id,...Y(d)})}catch(U){throw console.log(U),e.redirect(`${e.context.baseURL}/error?error=failed_linking_account`)}}else try{await e.context.internalAdapter.createOAuthUser(A.data,{...Y(d),id:`${t.id}:${c.id}`,providerId:t.id,accountId:c.id.toString(),userId:m})}catch{let w=new URL(n||o);throw w.searchParams.set("error","unable_to_create_user"),e.setHeader("Location",w.toString()),e.redirect(w.toString())}if(!f&&!m)throw new Et("INTERNAL_SERVER_ERROR",{message:"Unable to create user"});try{let p=await e.context.internalAdapter.createSession(f||m,e.request);if(!p){let w=new URL(n||o);throw w.searchParams.set("error","unable_to_create_session"),e.redirect(w.toString())}try{await v(e,p.id)}catch(w){e.context.logger.error("Unable to set session cookie",w);let k=new URL(n||o);throw k.searchParams.set("error","unable_to_create_session"),e.redirect(k.toString())}}catch{let p=new URL(n||o||"");throw p.searchParams.set("error","unable_to_create_session"),e.redirect(p.toString())}throw e.redirect(o)});import{APIError as q}from"better-call";var Z=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as Oe}from"zod";var ee=()=>u("/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,s=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+s*1e3<=Date.now()){let d=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:Z(e.context.sessionConfig.expiresIn,"sec")});if(!d)return j(e),e.json(null,{status:401});let c=(d.expiresAt.valueOf()-Date.now())/1e3;return await v(e,d.id,!1,{maxAge:c}),e.json({session:d,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),xt=async e=>await ee()({...e,_flag:"json",headers:e.headers}),C=z(async e=>{let t=await xt(e);if(!t?.session)throw new q("UNAUTHORIZED");return{session:t}}),Ie=()=>u("/user/list-sessions",{method:"GET",use:[C],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)}),Ce=u("/user/revoke-session",{method:"POST",body:Oe.object({id:Oe.string()}),use:[C],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})}),Be=u("/user/revoke-sessions",{method:"POST",use:[C],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"zod";import{APIError as Tt}from"better-call";var De=u("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Tt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),j(e),e.json({success:!0})});import{TimeSpan as Pt}from"oslo";import{createJWT as vt,parseJWT as _t}from"oslo/jwt";import{validateJWT as ze}from"oslo/jwt";import{z as E}from"zod";import{APIError as V}from"better-call";var $e=u("/forget-password",{method:"POST",body:E.object({email:E.string().email(),redirectTo:E.string()}),use:[x]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function to your auth config!"),new V("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=await vt("HS256",Buffer.from(e.context.secret),{email:o.user.email,redirectTo:r},{expiresIn:new Pt(1,"h"),issuer:"better-auth",subject:"forget-password",audiences:[o.user.email],includeIssuedTimestamp:!0}),s=`${e.context.baseURL}/reset-password/${n}`;return await e.context.options.emailAndPassword.sendResetPassword(s,o.user),e.json({status:!0})}),je=u("/reset-password/:token",{method:"GET"},async e=>{let{token:t}=e.params,r,o=E.object({email:E.string(),redirectTo:E.string()});try{if(r=await ze("HS256",Buffer.from(e.context.secret),t),!r.expiresAt||r.expiresAt<new Date)throw Error("Token expired")}catch{let i=_t(t),a=o.safeParse(i?.payload);throw a.success?e.redirect(`${a.data?.redirectTo}?error=invalid_token`):e.redirect(`${e.context.baseURL}/error?error=invalid_token`)}let{redirectTo:n}=o.parse(r.payload);throw e.redirect(`${n}?token=${t}`)}),qe=u("/reset-password",{method:"POST",query:E.object({currentURL:E.string()}).optional(),body:E.object({newPassword:E.string(),callbackURL:E.string().optional()})},async e=>{let t=e.query?.currentURL.split("?token=")[1];if(!t)throw new V("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body;try{let o=await ze("HS256",Buffer.from(e.context.secret),t),n=E.string().email().parse(o.payload.email),s=await e.context.internalAdapter.findUserByEmail(n);if(!s)return e.json({error:"User not found",data:null},{status:400,body:{message:"failed to reset password"}});if(r.length<(e.context.options.emailAndPassword?.minPasswordLength||8)||r.length>(e.context.options.emailAndPassword?.maxPasswordLength||32))throw new V("BAD_REQUEST",{message:"Password is too short or too long"});let i=await e.context.password.hash(r);if(!await e.context.internalAdapter.updatePassword(s.user.id,i))throw new V("BAD_REQUEST",{message:"Failed to update password"});return e.json({error:null,data:{status:!0,url:e.body.callbackURL,redirect:!!e.body.callbackURL}},{body:{status:!0,url:e.body.callbackURL,redirect:!!e.body.callbackURL}})}catch(o){throw e.context.logger.error("Failed to reset password",o),new V("BAD_REQUEST",{message:"Failed to reset password"})}});import{TimeSpan as St}from"oslo";import{createJWT as Lt,validateJWT as Ot}from"oslo/jwt";import{z as _}from"zod";import{APIError as M}from"better-call";async function te(e,t){return await Lt("HS256",Buffer.from(e),{email:t.toLowerCase()},{expiresIn:new St(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Ve=u("/send-verification-email",{method:"POST",query:_.object({currentURL:_.string().optional()}).optional(),body:_.object({email:_.string().email(),callbackURL:_.string().optional()}),use:[x]},async e=>{if(!e.context.options.emailAndPassword?.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 te(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailAndPassword.sendVerificationEmail(n,r.user,o),e.json({status:!0})}),Me=u("/verify-email",{method:"GET",query:_.object({token:_.string(),callbackURL:_.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await Ot("HS256",Buffer.from(e.context.secret),t)}catch(a){throw e.context.logger.error("Failed to verify email",a),new M("BAD_REQUEST",{message:"Invalid token"})}let n=_.object({email:_.string().email()}).parse(r.payload),s=await e.context.internalAdapter.findUserByEmail(n.email,{includeAccounts:!0});if(!s)throw new M("BAD_REQUEST",{message:"User not found"});if(!s.accounts.find(a=>a.providerId==="credential"))throw new M("BAD_REQUEST",{message:"Account 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})});import{z as P}from"zod";import{APIError as S}from"better-call";var Ne=u("/user/update",{method:"POST",body:P.object({name:P.string().optional(),image:P.string().optional()}),use:[C,x]},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})}),Fe=u("/user/change-password",{method:"POST",body:P.object({newPassword:P.string(),currentPassword:P.string(),revokeOtherSessions:P.boolean().optional()}),use:[C]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,s=e.context.password.config.minPasswordLength;if(t.length<s)throw e.context.logger.error("Password is too short"),new S("BAD_REQUEST",{message:"Password is too short"});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new S("BAD_REQUEST",{message:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(n.user.id)).find(A=>A.providerId==="credential"&&A.password);if(!d||!d.password)throw new S("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(d.password,r))throw new S("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let A=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!A)throw new S("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await v(e,A.id)}return e.json(n.user)}),He=u("/user/set-password",{method:"POST",body:P.object({newPassword:P.string()}),use:[C]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new S("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 S("BAD_REQUEST",{message:"Password too long"});let i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(d=>d.providerId==="credential"&&d.password),a=await e.context.password.hash(t);if(!i)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:a}),e.json(r.user);throw new S("BAD_REQUEST",{message:"user already has a password"})}),Qe=u("/user/delete",{method:"POST",body:P.object({password:P.string()}),use:[C]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(i=>i.providerId==="credential"&&i.password);if(!n||!n.password)throw new S("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new S("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 Ge=u("/csrf",{method:"GET",metadata:I},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t)return{csrfToken:t};let r=N(32,F("a-z","0-9","A-Z")),o=await H(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),{csrfToken:r}});var It=(e="Unknown")=>`<!DOCTYPE html>
2
+ `)}}),y=at();var x=z(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 s=new URL(t).origin;if(!n.includes(s))throw y.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new pe("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let s=new URL(o).origin;if(!n.includes(s))throw y.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new pe("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as lt}from"oslo/jwt";import{sha256 as ct}from"oslo/crypto";function dt(e){try{return new URL(e).pathname!=="/"}catch{throw new L(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function X(e,t="/api/auth"){return dt(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function le(e,t){if(e)return X(e,t);let r=typeof process<"u"?process.env:{},o=r.BETTER_AUTH_URL||r.NEXT_PUBLIC_BETTER_AUTH_URL||r.PUBLIC_BETTER_AUTH_URL||r.NUXT_PUBLIC_BETTER_AUTH_URL||r.NUXT_PUBLIC_AUTH_URL||(r.BASE_URL!=="/"?r.BASE_URL:void 0);if(o)return X(o,t);if(typeof window<"u")return X(window.location.origin,t)}import{base64url as ut}from"oslo/encoding";function h(e,t){return t||`${le()}/callback/${e}`}async function me(e){let t=await ct(new TextEncoder().encode(e));return ut.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?.split(" ")||[],idToken:e.id_token}}async function R({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:s,disablePkce:i}){let a=new URL(r);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",t.clientId),a.searchParams.set("state",o),a.searchParams.set("scope",s.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||h(e)),!i&&n){let d=await me(n);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",d)}return a}import{betterFetch as pt}from"@better-fetch/fetch";async function b({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let s=new URLSearchParams;s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:i,error:a}=await pt(n,{method:"POST",body:s,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(a)throw a;return fe(i)}function Y(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 s=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=${s.join(" ")}&state=${r}`)},validateAuthorizationCode:async(r,o,n)=>b({code:r,codeVerifier:o,redirectURI:n||h("apple",e.redirectURI),options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=lt(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}){let o=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${o.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(h("discord",e.redirectURI))}&state=${t}`)},validateAuthorizationCode:async(t,r,o)=>b({code:t,redirectURI:o||h("discord",e.redirectURI),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,codeVerifier:o}){let n=e.scope||r||["email","public_profile"];return await R({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v16.0/dialog/oauth",scopes:n,state:t,codeVerifier:o})},validateAuthorizationCode:async(t,r,o)=>b({code:t,codeVerifier:r,redirectURI:o||h("facebook",e.redirectURI),options:e,tokenEndpoint:"https://graph.facebook.com/v16.0/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await ft("https://graph.facebook.com/me",{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}){let s=e.scope||o||["user:email"];return R({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,codeVerifier:n})},validateAuthorizationCode:async(r,o,n)=>b({code:r,redirectURI:e.redirectURI||h("google",n),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 s=!1;if(!o.email){let{data:i,error:a}=await ye("https://api.github.com/user/emails",{auth:{type:"Bearer",token:r.accessToken}});a||(o.email=(i.find(d=>d.primary)??i[0])?.email,s=i.find(d=>d.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:s},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 L("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new L("codeVerifier is required for Google");let s=e.scope||r||["email","profile"];return R({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:s,state:t,codeVerifier:o})},validateAuthorizationCode:async(t,r,o)=>b({code:t,codeVerifier:r,redirectURI:o||h("google",e.redirectURI),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 s=e.scope||n.scopes||["openid","profile","email","User.Read"];return R({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:s})},validateAuthorizationCode(n,s,i){return b({code:n,codeVerifier:s,redirectURI:i||h("microsoft",e.redirectURI),options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let s=wt(n.idToken)?.payload,i=e.profilePhotoSize||48;return await ht(`https://graph.microsoft.com/v1.0/me/photos/${i}x${i}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let c=await a.response.clone().arrayBuffer(),m=Buffer.from(c).toString("base64");s.picture=`data:image/jpeg;base64, ${m}`}catch(d){y.error(d)}}}),{user:{id:s.sub,name:s.name,email:s.email,image:s.picture,emailVerified:!0},data:s}}}};import{betterFetch as yt}from"@better-fetch/fetch";var ke=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o}){let n=e.scope||r||["user-read-email"];return R({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o})},validateAuthorizationCode:async(t,r,o)=>b({code:t,codeVerifier:r,redirectURI:o||h("spotify",e.redirectURI),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{betterFetch as bt}from"@better-fetch/fetch";var Ue=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r}){let o=e.scope||r||["activity:write","read"];return R({id:"twitch",options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:t})},validateAuthorizationCode:async(t,r,o)=>b({code:t,redirectURI:o||h("twitch",e.redirectURI),options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await bt("https://api.twitch.tv/helix/users",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.sub,name:r.preferred_username,email:r.email,image:r.picture,emailVerified:!1},data:r}}});import{betterFetch as At}from"@better-fetch/fetch";var Ee=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return R({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier})},validateAuthorizationCode:async(t,r,o)=>b({code:t,codeVerifier:r,redirectURI:o||h("twitch",e.redirectURI),options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await At("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 Rt={apple:ge,discord:he,facebook:we,github:be,microsoft:Re,google:Ae,spotify:ke,twitch:Ue,twitter:Ee},xe=Object.keys(Rt);var Te=u("/sign-in/social",{method:"POST",requireHeaders:!0,query:T.object({currentURL:T.string().optional()}).optional(),body:T.object({callbackURL:T.string().optional(),provider:T.enum(xe)}),use:[x]},async e=>{let t=e.context.socialProviders.find(d=>d.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider to your auth config",{provider:e.body.provider}),new O("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||""}`,s=await ue(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,s.hash,e.context.secret,r.state.options);let i=kt();await e.setSignedCookie(r.pkCodeVerifier.name,i,e.context.secret,r.pkCodeVerifier.options);let a=await t.createAuthorizationURL({state:s.raw,codeVerifier:i});return a.searchParams.set("redirect_uri",`${e.context.baseURL}/callback/${e.body.provider}`),e.json({url:a.toString(),state:s,codeVerifier:i,redirect:!0})}),Pe=u("/sign-in/email",{method:"POST",body:T.object({email:T.string().email(),password:T.string(),callbackURL:T.string().optional(),dontRememberMe:T.boolean().default(!1).optional()}),use:[x]},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 O("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!T.string().email().safeParse(t).success)throw new O("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 O("UNAUTHORIZED",{message:"Invalid email or password"});let s=n.accounts.find(c=>c.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new O("UNAUTHORIZED",{message:"Invalid email or password"});let i=s?.password;if(!i)throw e.context.logger.error("Password not found",{email:t}),new O("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(i,r))throw e.context.logger.error("Invalid password"),new O("UNAUTHORIZED",{message:"Invalid email or password"});let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new O("UNAUTHORIZED",{message:"Failed to create session"});return await v(e,d.id,e.body.dontRememberMe),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{APIError as Et}from"better-call";import{z as G}from"zod";import{z as p}from"zod";var mn=p.object({id:p.string(),providerId:p.string(),accountId:p.string(),userId:p.string(),accessToken:p.string().nullable().optional(),refreshToken:p.string().nullable().optional(),idToken:p.string().nullable().optional(),expiresAt:p.date().nullable().optional(),password:p.string().optional().nullable()}),ve=p.object({id:p.string(),email:p.string().transform(e=>e.toLowerCase()),emailVerified:p.boolean().default(!1),name:p.string(),image:p.string().optional(),createdAt:p.date().default(new Date),updatedAt:p.date().default(new Date)}),fn=p.object({id:p.string(),userId:p.string(),expiresAt:p.date(),ipAddress:p.string().optional(),userAgent:p.string().optional()}),gn=p.object({id:p.string(),value:p.string(),expiresAt:p.date(),identifier:p.string()});function Ut(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 Ut(t||{},{fields:r})}var Se=e=>N(e||21,F("a-z","0-9","A-Z"));var I={isAction:!1};var Le=u("/callback/:id",{method:"GET",query:G.object({state:G.string(),code:G.string().optional(),error:G.string().optional()}),metadata:I},async e=>{if(e.query.error||!e.query.code){let w=K(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${w}?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=K(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,s=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!s)throw y.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await ce(e.query.state,s))throw y.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let a=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),d;try{d=await t.validateAuthorizationCode(e.query.code,a,`${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(d).then(l=>l?.user),m=Se(),A=ve.safeParse({...c,id:m});if(!c||A.success===!1)throw y.error("Unable to get user info",A.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 y.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(U=>U.providerId===t.id),w=e.context.options.account?.accountLinking?.trustedProviders,k=w?w.includes(t.id):!0;if(!l&&(!c.emailVerified||!k)){let U;try{U=new URL(n||o),U.searchParams.set("error","account_not_linked")}catch{throw e.redirect(`${e.context.baseURL}/error?error=account_not_linked`)}throw e.redirect(U.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,...Y(d)})}catch(U){throw console.log(U),e.redirect(`${e.context.baseURL}/error?error=failed_linking_account`)}}else try{await e.context.internalAdapter.createOAuthUser(A.data,{...Y(d),id:`${t.id}:${c.id}`,providerId:t.id,accountId:c.id.toString(),userId:m})}catch{let w=new URL(n||o);throw w.searchParams.set("error","unable_to_create_user"),e.setHeader("Location",w.toString()),e.redirect(w.toString())}if(!f&&!m)throw new Et("INTERNAL_SERVER_ERROR",{message:"Unable to create user"});try{let l=await e.context.internalAdapter.createSession(f||m,e.request);if(!l){let w=new URL(n||o);throw w.searchParams.set("error","unable_to_create_session"),e.redirect(w.toString())}try{await v(e,l.id)}catch(w){e.context.logger.error("Unable to set session cookie",w);let k=new URL(n||o);throw k.searchParams.set("error","unable_to_create_session"),e.redirect(k.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 q}from"better-call";var Z=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as Oe}from"zod";var ee=()=>u("/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,s=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+s*1e3<=Date.now()){let d=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:Z(e.context.sessionConfig.expiresIn,"sec")});if(!d)return j(e),e.json(null,{status:401});let c=(d.expiresAt.valueOf()-Date.now())/1e3;return await v(e,d.id,!1,{maxAge:c}),e.json({session:d,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),xt=async e=>await ee()({...e,_flag:"json",headers:e.headers}),C=z(async e=>{let t=await xt(e);if(!t?.session)throw new q("UNAUTHORIZED");return{session:t}}),Ie=()=>u("/user/list-sessions",{method:"GET",use:[C],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)}),Ce=u("/user/revoke-session",{method:"POST",body:Oe.object({id:Oe.string()}),use:[C],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})}),Be=u("/user/revoke-sessions",{method:"POST",use:[C],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"zod";import{APIError as Tt}from"better-call";var De=u("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Tt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),j(e),e.json({success:!0})});import{TimeSpan as Pt}from"oslo";import{createJWT as vt,parseJWT as _t}from"oslo/jwt";import{validateJWT as ze}from"oslo/jwt";import{z as E}from"zod";import{APIError as V}from"better-call";var $e=u("/forget-password",{method:"POST",body:E.object({email:E.string().email(),redirectTo:E.string()}),use:[x]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function to your auth config!"),new V("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=await vt("HS256",Buffer.from(e.context.secret),{email:o.user.email,redirectTo:r},{expiresIn:new Pt(1,"h"),issuer:"better-auth",subject:"forget-password",audiences:[o.user.email],includeIssuedTimestamp:!0}),s=`${e.context.baseURL}/reset-password/${n}`;return await e.context.options.emailAndPassword.sendResetPassword(s,o.user),e.json({status:!0})}),je=u("/reset-password/:token",{method:"GET"},async e=>{let{token:t}=e.params,r,o=E.object({email:E.string(),redirectTo:E.string()});try{if(r=await ze("HS256",Buffer.from(e.context.secret),t),!r.expiresAt||r.expiresAt<new Date)throw Error("Token expired")}catch{let i=_t(t),a=o.safeParse(i?.payload);throw a.success?e.redirect(`${a.data?.redirectTo}?error=invalid_token`):e.redirect(`${e.context.baseURL}/error?error=invalid_token`)}let{redirectTo:n}=o.parse(r.payload);throw e.redirect(`${n}?token=${t}`)}),qe=u("/reset-password",{method:"POST",query:E.object({currentURL:E.string()}).optional(),body:E.object({newPassword:E.string(),callbackURL:E.string().optional()})},async e=>{let t=e.query?.currentURL.split("?token=")[1];if(!t)throw new V("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body;try{let o=await ze("HS256",Buffer.from(e.context.secret),t),n=E.string().email().parse(o.payload.email),s=await e.context.internalAdapter.findUserByEmail(n);if(!s)return e.json({error:"User not found",data:null},{status:400,body:{message:"failed to reset password"}});if(r.length<(e.context.options.emailAndPassword?.minPasswordLength||8)||r.length>(e.context.options.emailAndPassword?.maxPasswordLength||32))throw new V("BAD_REQUEST",{message:"Password is too short or too long"});let i=await e.context.password.hash(r);if(!await e.context.internalAdapter.updatePassword(s.user.id,i))throw new V("BAD_REQUEST",{message:"Failed to update password"});return e.json({error:null,data:{status:!0,url:e.body.callbackURL,redirect:!!e.body.callbackURL}},{body:{status:!0,url:e.body.callbackURL,redirect:!!e.body.callbackURL}})}catch(o){throw e.context.logger.error("Failed to reset password",o),new V("BAD_REQUEST",{message:"Failed to reset password"})}});import{TimeSpan as St}from"oslo";import{createJWT as Lt,validateJWT as Ot}from"oslo/jwt";import{z as _}from"zod";import{APIError as M}from"better-call";async function te(e,t){return await Lt("HS256",Buffer.from(e),{email:t.toLowerCase()},{expiresIn:new St(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Ve=u("/send-verification-email",{method:"POST",query:_.object({currentURL:_.string().optional()}).optional(),body:_.object({email:_.string().email(),callbackURL:_.string().optional()}),use:[x]},async e=>{if(!e.context.options.emailAndPassword?.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 te(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailAndPassword.sendVerificationEmail(n,r.user,o),e.json({status:!0})}),Me=u("/verify-email",{method:"GET",query:_.object({token:_.string(),callbackURL:_.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await Ot("HS256",Buffer.from(e.context.secret),t)}catch(a){throw e.context.logger.error("Failed to verify email",a),new M("BAD_REQUEST",{message:"Invalid token"})}let n=_.object({email:_.string().email()}).parse(r.payload),s=await e.context.internalAdapter.findUserByEmail(n.email,{includeAccounts:!0});if(!s)throw new M("BAD_REQUEST",{message:"User not found"});if(!s.accounts.find(a=>a.providerId==="credential"))throw new M("BAD_REQUEST",{message:"Account 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})});import{z as P}from"zod";import{APIError as S}from"better-call";var Ne=u("/user/update",{method:"POST",body:P.object({name:P.string().optional(),image:P.string().optional()}),use:[C,x]},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})}),Fe=u("/user/change-password",{method:"POST",body:P.object({newPassword:P.string(),currentPassword:P.string(),revokeOtherSessions:P.boolean().optional()}),use:[C]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,s=e.context.password.config.minPasswordLength;if(t.length<s)throw e.context.logger.error("Password is too short"),new S("BAD_REQUEST",{message:"Password is too short"});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new S("BAD_REQUEST",{message:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(n.user.id)).find(A=>A.providerId==="credential"&&A.password);if(!d||!d.password)throw new S("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(d.password,r))throw new S("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let A=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!A)throw new S("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await v(e,A.id)}return e.json(n.user)}),He=u("/user/set-password",{method:"POST",body:P.object({newPassword:P.string()}),use:[C]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new S("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 S("BAD_REQUEST",{message:"Password too long"});let i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(d=>d.providerId==="credential"&&d.password),a=await e.context.password.hash(t);if(!i)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:a}),e.json(r.user);throw new S("BAD_REQUEST",{message:"user already has a password"})}),Qe=u("/user/delete",{method:"POST",body:P.object({password:P.string()}),use:[C]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(i=>i.providerId==="credential"&&i.password);if(!n||!n.password)throw new S("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new S("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 Ge=u("/csrf",{method:"GET",metadata:I},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t)return{csrfToken:t};let r=N(32,F("a-z","0-9","A-Z")),o=await H(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),{csrfToken:r}});var It=(e="Unknown")=>`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">
@@ -80,4 +80,4 @@ Error: `,p),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>`,Ze=u("/error",{method:"GET",metadata:I},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(It(t),{headers:{"Content-Type":"text/html"}})});var We=u("/ok",{method:"GET",metadata:I},async e=>e.json({ok:!0}));import{z as $}from"zod";import{APIError as D}from"better-call";var Je=()=>u("/sign-up/email",{method:"POST",query:$.object({currentURL:$.string().optional()}).optional(),body:$.record($.string(),$.any()),use:[x]},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:s,callbackURL:i,...a}=t;if(!$.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 m=e.context.password.config.maxPasswordLength;if(n.length>m)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:"The email has already been taken"});let g=_e(e.context.options,a),f=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:s,...g,emailVerified:!1});if(!f)throw new D("BAD_REQUEST",{message:"Failed to create user"});let p=await e.context.password.hash(n);await e.context.internalAdapter.linkAccount({userId:f.id,providerId:"credential",accountId:f.id,password:p,expiresAt:Z(60*60*24*30,"sec")});let w=await e.context.internalAdapter.createSession(f.id,e.request);if(!w)throw new D("BAD_REQUEST",{message:"Failed to create session"});if(await v(e,w.id),e.context.options.emailAndPassword.sendEmailVerificationOnSignUp){let k=await te(e.context.secret,f.email),U=`${e.context.baseURL}/verify-email?token=${k}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailAndPassword.sendVerificationEmail?.(U,f,k)}return e.json({user:f,session:w,error:null},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:f,session:w}})});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 s=n.split(",")[0].trim();if(s)return s}}return null}function Ct(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function Bt(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 Dt(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function zt(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,s,i)=>{try{i?await o.update({model:t??"rateLimit",where:[{field:"key",value:n}],update:{count:s.count,lastRequest:s.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:n,count:s.count,lastRequest:s.lastRequest}})}catch(a){y.error("Error setting rate limit",a)}}}}var Xe=new Map;function $t(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)}}:zt(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,s=t.rateLimit.max,i=Ke(e)+o,d=jt().find(g=>g.pathMatcher(o));d&&(n=d.window,s=d.max);for(let g of t.options.plugins||[])if(g.rateLimit){let f=g.rateLimit.find(p=>p.pathMatcher(o));if(f){n=f.window,s=f.max;break}}if(t.rateLimit.customRules){let g=t.rateLimit.customRules[o];g&&(n=g.window,s=g.max)}let c=$t(t),m=await c.get(i),A=Date.now();if(!m)await c.set(i,{key:i,count:1,lastRequest:A});else{let g=A-m.lastRequest;if(Ct(s,n,m)){let f=Dt(m.lastRequest,n);return Bt(f)}else g>n*1e3?await c.set(i,{...m,count:1,lastRequest:A}):await c.set(i,{...m,count:m.count+1,lastRequest:A})}}function jt(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:7}]}import{APIError as Ei}from"better-call";function Mt(e,t){let r=t.plugins?.reduce((a,d)=>({...a,...d.endpoints}),{}),o=t.plugins?.map(a=>a.middlewares?.map(d=>{let c=async m=>d.middleware({...m,context:{...e,...m.context}});return c.path=d.path,c.options=d.middleware.options,c.headers=d.middleware.headers,{path:d.path,middleware:c}})).filter(a=>a!==void 0).flat()||[],s={...{signInOAuth:Te,callbackOAuth:Le,getCSRFToken:Ge,getSession:ee(),signOut:De,signUpEmail:Je(),signInEmail:Pe,forgetPassword:$e,resetPassword:qe,verifyEmail:Me,sendVerificationEmail:Ve,changePassword:Fe,setPassword:He,updateUser:Ne,deleteUser:Qe,forgetPasswordCallback:je,listSessions:Ie(),revokeSession:Ce,revokeSessions:Be},...r,ok:We,error:Ze},i={};for(let[a,d]of Object.entries(s))i[a]=async(c={})=>{let m=await e;for(let f of t.plugins||[])if(f.hooks?.before){for(let p of f.hooks.before)if(p.matcher({...d,...c,context:m})){let k=await p.handler({...c,context:{...m,...c?.context}});k&&"context"in k&&(m={...m,...k.context})}}let g=await d({...c,context:{...m,...c.context}});for(let f of t.plugins||[])if(f.hooks?.after){for(let p of f.hooks.after)if(p.matcher(c)){let k=Object.assign(c,{context:{...e,returned:g}}),U=await p.handler(k);U&&"response"in U&&(g=U.response)}}return g},i[a].path=d.path,i[a].method=d.method,i[a].options=d.options,i[a].headers=d.headers;return{api:i,middlewares:o}}var yi=(e,t)=>{let{api:r,middlewares:o}=Mt(e,t),n=new URL(e.baseURL).pathname;return Vt(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:ie},...o],async onRequest(s){for(let i of e.options.plugins||[])if(i.onRequest){let a=await i.onRequest(s,e);if(a)return a}return Ye(s,e)},async onResponse(s){for(let i of e.options.plugins||[])if(i.onResponse){let a=await i.onResponse(s,e);if(a)return a.response}return s},onError(s){if(t.onAPIError?.throw)throw s;if(t.onAPIError?.onError){t.onAPIError.onError(s,e);return}let i=t.logger?.verboseLogging?y:void 0;t.logger?.disabled!==!0&&(s instanceof qt?(s.status==="INTERNAL_SERVER_ERROR"&&y.error(s),i?.error(s.message)):y?.error(s))}})};export{Ei as APIError,Le as callbackOAuth,Fe as changePassword,u as createAuthEndpoint,z as createAuthMiddleware,te as createEmailVerificationToken,ie as csrfMiddleware,Qe as deleteUser,Ze as error,$e as forgetPassword,je as forgetPasswordCallback,Ge as getCSRFToken,Mt as getEndpoints,ee as getSession,xt as getSessionFromCtx,Ie as listSessions,We as ok,ne as optionsMiddleware,qe as resetPassword,Ce as revokeSession,Be as revokeSessions,yi as router,Ve as sendVerificationEmail,C as sessionMiddleware,He as setPassword,Pe as signInEmail,Te as signInOAuth,De as signOut,Je as signUpEmail,Ne as updateUser,Me as verifyEmail};
83
+ </html>`,Ze=u("/error",{method:"GET",metadata:I},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(It(t),{headers:{"Content-Type":"text/html"}})});var We=u("/ok",{method:"GET",metadata:I},async e=>e.json({ok:!0}));import{z as $}from"zod";import{APIError as D}from"better-call";var Je=()=>u("/sign-up/email",{method:"POST",query:$.object({currentURL:$.string().optional()}).optional(),body:$.record($.string(),$.any()),use:[x]},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:s,callbackURL:i,...a}=t;if(!$.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 m=e.context.password.config.maxPasswordLength;if(n.length>m)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:"The email has already been taken"});let g=_e(e.context.options,a),f=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:s,...g,emailVerified:!1});if(!f)throw new D("BAD_REQUEST",{message:"Failed to create user"});let l=await e.context.password.hash(n);await e.context.internalAdapter.linkAccount({userId:f.id,providerId:"credential",accountId:f.id,password:l,expiresAt:Z(60*60*24*30,"sec")});let w=await e.context.internalAdapter.createSession(f.id,e.request);if(!w)throw new D("BAD_REQUEST",{message:"Failed to create session"});if(await v(e,w.id),e.context.options.emailAndPassword.sendEmailVerificationOnSignUp){let k=await te(e.context.secret,f.email),U=`${e.context.baseURL}/verify-email?token=${k}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailAndPassword.sendVerificationEmail?.(U,f,k)}return e.json({user:f,session:w,error:null},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:f,session:w}})});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 s=n.split(",")[0].trim();if(s)return s}}return null}function Ct(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function Bt(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 Dt(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function zt(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,s,i)=>{try{i?await o.update({model:t??"rateLimit",where:[{field:"key",value:n}],update:{count:s.count,lastRequest:s.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:n,count:s.count,lastRequest:s.lastRequest}})}catch(a){y.error("Error setting rate limit",a)}}}}var Xe=new Map;function $t(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)}}:zt(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,s=t.rateLimit.max,i=Ke(e)+o,d=jt().find(g=>g.pathMatcher(o));d&&(n=d.window,s=d.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,s=f.max;break}}if(t.rateLimit.customRules){let g=t.rateLimit.customRules[o];g&&(n=g.window,s=g.max)}let c=$t(t),m=await c.get(i),A=Date.now();if(!m)await c.set(i,{key:i,count:1,lastRequest:A});else{let g=A-m.lastRequest;if(Ct(s,n,m)){let f=Dt(m.lastRequest,n);return Bt(f)}else g>n*1e3?await c.set(i,{...m,count:1,lastRequest:A}):await c.set(i,{...m,count:m.count+1,lastRequest:A})}}function jt(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:7}]}import{APIError as Ei}from"better-call";function Mt(e,t){let r=t.plugins?.reduce((a,d)=>({...a,...d.endpoints}),{}),o=t.plugins?.map(a=>a.middlewares?.map(d=>{let c=async m=>d.middleware({...m,context:{...e,...m.context}});return c.path=d.path,c.options=d.middleware.options,c.headers=d.middleware.headers,{path:d.path,middleware:c}})).filter(a=>a!==void 0).flat()||[],s={...{signInOAuth:Te,callbackOAuth:Le,getCSRFToken:Ge,getSession:ee(),signOut:De,signUpEmail:Je(),signInEmail:Pe,forgetPassword:$e,resetPassword:qe,verifyEmail:Me,sendVerificationEmail:Ve,changePassword:Fe,setPassword:He,updateUser:Ne,deleteUser:Qe,forgetPasswordCallback:je,listSessions:Ie(),revokeSession:Ce,revokeSessions:Be},...r,ok:We,error:Ze},i={};for(let[a,d]of Object.entries(s))i[a]=async(c={})=>{let m=await e;for(let f of t.plugins||[])if(f.hooks?.before){for(let l of f.hooks.before)if(l.matcher({...d,...c,context:m})){let k=await l.handler({...c,context:{...m,...c?.context}});k&&"context"in k&&(m={...m,...k.context})}}let g=await d({...c,context:{...m,...c.context}});for(let f of t.plugins||[])if(f.hooks?.after){for(let l of f.hooks.after)if(l.matcher(c)){let k=Object.assign(c,{context:{...e,returned:g}}),U=await l.handler(k);U&&"response"in U&&(g=U.response)}}return g},i[a].path=d.path,i[a].method=d.method,i[a].options=d.options,i[a].headers=d.headers;return{api:i,middlewares:o}}var yi=(e,t)=>{let{api:r,middlewares:o}=Mt(e,t),n=new URL(e.baseURL).pathname;return Vt(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:ie},...o],async onRequest(s){for(let i of e.options.plugins||[])if(i.onRequest){let a=await i.onRequest(s,e);if(a)return a}return Ye(s,e)},async onResponse(s){for(let i of e.options.plugins||[])if(i.onResponse){let a=await i.onResponse(s,e);if(a)return a.response}return s},onError(s){if(t.onAPIError?.throw)throw s;if(t.onAPIError?.onError){t.onAPIError.onError(s,e);return}let i=t.logger?.verboseLogging?y:void 0;t.logger?.disabled!==!0&&(s instanceof qt?(s.status==="INTERNAL_SERVER_ERROR"&&y.error(s),i?.error(s.message)):y?.error(s))}})};export{Ei as APIError,Le as callbackOAuth,Fe as changePassword,u as createAuthEndpoint,z as createAuthMiddleware,te as createEmailVerificationToken,ie as csrfMiddleware,Qe as deleteUser,Ze as error,$e as forgetPassword,je as forgetPasswordCallback,Ge as getCSRFToken,Mt as getEndpoints,ee as getSession,xt as getSessionFromCtx,Ie as listSessions,We as ok,ne as optionsMiddleware,qe as resetPassword,Ce as revokeSession,Be as revokeSessions,yi as router,Ve as sendVerificationEmail,C as sessionMiddleware,He as setPassword,Pe as signInEmail,Te as signInOAuth,De as signOut,Je as signUpEmail,Ne as updateUser,Me as verifyEmail};
@@ -1173,12 +1173,12 @@ declare const signInOAuth: {
1173
1173
  /**
1174
1174
  * OAuth2 provider to use`
1175
1175
  */
1176
- provider: z.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter")[]]>;
1176
+ provider: z.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
1177
1177
  }, "strip", z.ZodTypeAny, {
1178
- provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
1178
+ provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
1179
1179
  callbackURL?: string | undefined;
1180
1180
  }, {
1181
- provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
1181
+ provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
1182
1182
  callbackURL?: string | undefined;
1183
1183
  }>;
1184
1184
  use: better_call.Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
@@ -1216,12 +1216,12 @@ declare const signInOAuth: {
1216
1216
  /**
1217
1217
  * OAuth2 provider to use`
1218
1218
  */
1219
- provider: z.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter")[]]>;
1219
+ provider: z.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
1220
1220
  }, "strip", z.ZodTypeAny, {
1221
- provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
1221
+ provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
1222
1222
  callbackURL?: string | undefined;
1223
1223
  }, {
1224
- provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
1224
+ provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
1225
1225
  callbackURL?: string | undefined;
1226
1226
  }>;
1227
1227
  use: better_call.Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
@@ -2417,12 +2417,12 @@ declare function getEndpoints<C extends AuthContext, Option extends BetterAuthOp
2417
2417
  }>>;
2418
2418
  body: zod.ZodObject<{
2419
2419
  callbackURL: zod.ZodOptional<zod.ZodString>;
2420
- provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter")[]]>;
2420
+ provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
2421
2421
  }, "strip", zod.ZodTypeAny, {
2422
- provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
2422
+ provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
2423
2423
  callbackURL?: string | undefined;
2424
2424
  }, {
2425
- provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
2425
+ provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
2426
2426
  callbackURL?: string | undefined;
2427
2427
  }>;
2428
2428
  use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
@@ -2450,12 +2450,12 @@ declare function getEndpoints<C extends AuthContext, Option extends BetterAuthOp
2450
2450
  }>>;
2451
2451
  body: zod.ZodObject<{
2452
2452
  callbackURL: zod.ZodOptional<zod.ZodString>;
2453
- provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter")[]]>;
2453
+ provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
2454
2454
  }, "strip", zod.ZodTypeAny, {
2455
- provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
2455
+ provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
2456
2456
  callbackURL?: string | undefined;
2457
2457
  }, {
2458
- provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
2458
+ provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
2459
2459
  callbackURL?: string | undefined;
2460
2460
  }>;
2461
2461
  use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
@@ -3511,12 +3511,12 @@ declare const router: <C extends AuthContext, Option extends BetterAuthOptions>(
3511
3511
  }>>;
3512
3512
  body: zod.ZodObject<{
3513
3513
  callbackURL: zod.ZodOptional<zod.ZodString>;
3514
- provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter")[]]>;
3514
+ provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
3515
3515
  }, "strip", zod.ZodTypeAny, {
3516
- provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
3516
+ provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
3517
3517
  callbackURL?: string | undefined;
3518
3518
  }, {
3519
- provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
3519
+ provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
3520
3520
  callbackURL?: string | undefined;
3521
3521
  }>;
3522
3522
  use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
@@ -3544,12 +3544,12 @@ declare const router: <C extends AuthContext, Option extends BetterAuthOptions>(
3544
3544
  }>>;
3545
3545
  body: zod.ZodObject<{
3546
3546
  callbackURL: zod.ZodOptional<zod.ZodString>;
3547
- provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter")[]]>;
3547
+ provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
3548
3548
  }, "strip", zod.ZodTypeAny, {
3549
- provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
3549
+ provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
3550
3550
  callbackURL?: string | undefined;
3551
3551
  }, {
3552
- provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
3552
+ provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
3553
3553
  callbackURL?: string | undefined;
3554
3554
  }>;
3555
3555
  use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
@@ -4607,12 +4607,12 @@ declare const betterAuth: <O extends BetterAuthOptions>(options: O) => {
4607
4607
  }>>;
4608
4608
  body: zod.ZodObject<{
4609
4609
  callbackURL: zod.ZodOptional<zod.ZodString>;
4610
- provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter")[]]>;
4610
+ provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
4611
4611
  }, "strip", zod.ZodTypeAny, {
4612
- provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
4612
+ provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
4613
4613
  callbackURL?: string | undefined;
4614
4614
  }, {
4615
- provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
4615
+ provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
4616
4616
  callbackURL?: string | undefined;
4617
4617
  }>;
4618
4618
  use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
@@ -4640,12 +4640,12 @@ declare const betterAuth: <O extends BetterAuthOptions>(options: O) => {
4640
4640
  }>>;
4641
4641
  body: zod.ZodObject<{
4642
4642
  callbackURL: zod.ZodOptional<zod.ZodString>;
4643
- provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter")[]]>;
4643
+ provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
4644
4644
  }, "strip", zod.ZodTypeAny, {
4645
- provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
4645
+ provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
4646
4646
  callbackURL?: string | undefined;
4647
4647
  }, {
4648
- provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
4648
+ provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
4649
4649
  callbackURL?: string | undefined;
4650
4650
  }>;
4651
4651
  use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
@@ -2,10 +2,10 @@ import * as nanostores from 'nanostores';
2
2
  import { A as AccessControl, S as StatementsPrimitive, R as Role } from '../statement-CfnyN34h.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, k as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, e as anonymous, i as admin, j as genericOAuth } from '../index-bfF6ImVo.js';
6
- export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-bfF6ImVo.js';
5
+ import { o as organization, k as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, e as anonymous, i as admin, j as genericOAuth } from '../index-DhUJME0t.js';
6
+ export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-DhUJME0t.js';
7
7
  import { P as Prettify } from '../helper-DPDj8Nix.js';
8
- import { F as FieldAttribute, f as BetterAuthOptions, B as BetterAuthPlugin } from '../auth-2pRFLprr.js';
8
+ import { F as FieldAttribute, f as BetterAuthOptions, B as BetterAuthPlugin } from '../auth-Nmre53Xe.js';
9
9
  import 'zod';
10
10
  import '../schema-Dkt0LqYs.js';
11
11
  import 'better-call';
package/dist/client.d.ts CHANGED
@@ -6,7 +6,7 @@ import { BetterFetch, BetterFetchError, BetterFetchOption } from '@better-fetch/
6
6
  import { U as UnionToIntersection, P as Prettify, S as StripEmptyObjects } from './helper-DPDj8Nix.js';
7
7
  import { ClientOptions, InferClientAPI, InferActions, InferAdditionalFromClient, InferSessionFromClient, InferUserFromClient, BetterAuthClientPlugin, IsSignal } from './types.js';
8
8
  export { AtomListener, InferPluginsFromClient } from './types.js';
9
- import './auth-2pRFLprr.js';
9
+ import './auth-Nmre53Xe.js';
10
10
  import 'kysely';
11
11
  import './schema-Dkt0LqYs.js';
12
12
  import 'better-call';
package/dist/cookies.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import 'better-call';
2
- export { s as BetterAuthCookies, E as EligibleCookies, r as createCookieGetter, u as deleteSessionCookie, q as getCookies, v as parseSetCookieHeader, t as setSessionCookie } from './auth-2pRFLprr.js';
2
+ export { s as BetterAuthCookies, E as EligibleCookies, r as createCookieGetter, u as deleteSessionCookie, q as getCookies, v as parseSetCookieHeader, t as setSessionCookie } from './auth-Nmre53Xe.js';
3
3
  import 'zod';
4
4
  import 'kysely';
5
5
  import './schema-Dkt0LqYs.js';
package/dist/db.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as Adapter, f as BetterAuthOptions, W as Where, F as FieldAttribute, y as FieldType, K as KyselyDatabaseType } from './auth-2pRFLprr.js';
2
- export { V as BetterAuthDbSchema, D as FieldAttributeConfig, U as InferFieldsFromOptions, T as InferFieldsFromPlugins, N as InferFieldsInput, O as InferFieldsInputClient, M as InferFieldsOutput, L as InferValueType, C as InternalAdapter, Q as PluginFieldAttribute, J as createFieldAttribute, z as createInternalAdapter, X as getAuthTables } from './auth-2pRFLprr.js';
1
+ import { A as Adapter, f as BetterAuthOptions, W as Where, F as FieldAttribute, y as FieldType, K as KyselyDatabaseType } from './auth-Nmre53Xe.js';
2
+ export { V as BetterAuthDbSchema, D as FieldAttributeConfig, U as InferFieldsFromOptions, T as InferFieldsFromPlugins, N as InferFieldsInput, O as InferFieldsInputClient, M as InferFieldsOutput, L as InferValueType, C as InternalAdapter, Q as PluginFieldAttribute, J as createFieldAttribute, z as createInternalAdapter, X as getAuthTables } from './auth-Nmre53Xe.js';
3
3
  import { z } from 'zod';
4
4
  import 'kysely';
5
5
  import './schema-Dkt0LqYs.js';
@@ -5,7 +5,7 @@ import { P as Prettify } from './helper-DPDj8Nix.js';
5
5
  import { A as AccessControl, R as Role, S as StatementsPrimitive, g as defaultRoles } from './statement-CfnyN34h.js';
6
6
  import * as _better_fetch_fetch from '@better-fetch/fetch';
7
7
  import { BetterFetch, BetterFetchOption } from '@better-fetch/fetch';
8
- import { H as HookEndpointContext, p as AuthContext } from './auth-2pRFLprr.js';
8
+ import { H as HookEndpointContext, p as AuthContext } from './auth-Nmre53Xe.js';
9
9
  import * as nanostores from 'nanostores';
10
10
  import { atom } from 'nanostores';
11
11
  import * as _simplewebauthn_types from '@simplewebauthn/types';
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { A as Adapter, j as AdditionalSessionFieldsInput, k as AdditionalSessionFieldsOutput, h as AdditionalUserFieldsInput, i as AdditionalUserFieldsOutput, e as Auth, p as AuthContext, s as BetterAuthCookies, f as BetterAuthOptions, B as BetterAuthPlugin, E as EligibleCookies, G as GenericEndpointContext, H as HookEndpointContext, m as InferPluginTypes, l as InferSession, I as InferUser, P as PluginSchema, R as RateLimit, S as SecondaryStorage, W as Where, g as betterAuth, r as createCookieGetter, w as createLogger, u as deleteSessionCookie, q as getCookies, n as init, x as logger, v as parseSetCookieHeader, t as setSessionCookie } from './auth-2pRFLprr.js';
1
+ export { A as Adapter, j as AdditionalSessionFieldsInput, k as AdditionalSessionFieldsOutput, h as AdditionalUserFieldsInput, i as AdditionalUserFieldsOutput, e as Auth, p as AuthContext, s as BetterAuthCookies, f as BetterAuthOptions, B as BetterAuthPlugin, E as EligibleCookies, G as GenericEndpointContext, H as HookEndpointContext, m as InferPluginTypes, l as InferSession, I as InferUser, P as PluginSchema, R as RateLimit, S as SecondaryStorage, W as Where, g as betterAuth, r as createCookieGetter, w as createLogger, u as deleteSessionCookie, q as getCookies, n as init, x as logger, v as parseSetCookieHeader, t as setSessionCookie } from './auth-Nmre53Xe.js';
2
2
  export { D as DeepPartial, H as HasRequiredKeys, L as LiteralString, a as LiteralUnion, P as Prettify, R as RequiredKeysOf, S as StripEmptyObjects, U as UnionToIntersection, W as WithoutEmpty } from './helper-DPDj8Nix.js';
3
3
  export { AtomListener, BetterAuthClientPlugin, ClientOptions, InferActions, InferAdditionalFromClient, InferClientAPI, InferPluginsFromClient, InferSessionFromClient, InferUserFromClient, IsSignal } from './types.js';
4
4
  export { H as HIDE_METADATA } from './hide-metadata-DEHJp1rk.js';