better-auth 0.4.11 → 0.4.12-beta.1

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-BGQTSAwN.js';
1
+ import { A as Adapter } from '../auth-Cx7ibOvY.js';
2
2
  import 'zod';
3
3
  import 'kysely';
4
4
  import '../schema-Dkt0LqYs.js';
@@ -1,5 +1,5 @@
1
1
  import { Kysely } from 'kysely';
2
- import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-BGQTSAwN.js';
2
+ import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-Cx7ibOvY.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-BGQTSAwN.js';
2
+ import { W as Where } from '../auth-Cx7ibOvY.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-BGQTSAwN.js';
1
+ import { A as Adapter } from '../auth-Cx7ibOvY.js';
2
2
  import 'zod';
3
3
  import 'kysely';
4
4
  import '../schema-Dkt0LqYs.js';
package/dist/api.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { e as AuthEndpoint, f as AuthMiddleware, a0 as callbackOAuth, af as changePassword, d as createAuthEndpoint, c as createAuthMiddleware, ab as createEmailVerificationToken, am as csrfMiddleware, ah as deleteUser, aj as error, a8 as forgetPassword, a9 as forgetPasswordCallback, ai as getCSRFToken, Y as getEndpoints, a1 as getSession, a2 as getSessionFromCtx, a4 as listSessions, ak as ok, o as optionsMiddleware, aa as resetPassword, a5 as revokeSession, a6 as revokeSessions, Z as router, ac as sendVerificationEmail, a3 as sessionMiddleware, ag as setPassword, $ as signInEmail, _ as signInOAuth, a7 as signOut, al as signUpEmail, ae as updateUser, ad as verifyEmail } from './auth-BGQTSAwN.js';
1
+ export { e as AuthEndpoint, f as AuthMiddleware, a0 as callbackOAuth, af as changePassword, d as createAuthEndpoint, c as createAuthMiddleware, ab as createEmailVerificationToken, am as csrfMiddleware, ah as deleteUser, aj as error, a8 as forgetPassword, a9 as forgetPasswordCallback, ai as getCSRFToken, Y as getEndpoints, a1 as getSession, a2 as getSessionFromCtx, a4 as listSessions, ak as ok, o as optionsMiddleware, aa as resetPassword, a5 as revokeSession, a6 as revokeSessions, Z as router, ac as sendVerificationEmail, a3 as sessionMiddleware, ag as setPassword, $ as signInEmail, _ as signInOAuth, a7 as signOut, al as signUpEmail, ae as updateUser, ad as verifyEmail } from './auth-Cx7ibOvY.js';
2
2
  import './helper-DPDj8Nix.js';
3
3
  export { APIError } from 'better-call';
4
4
  import 'zod';
package/dist/api.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import{APIError as Lt,createRouter as It}from"better-call";import{APIError as W}from"better-call";import{z as oe}from"zod";import{xchacha20poly1305 as Qt}from"@noble/ciphers/chacha";import{bytesToHex as Zt,hexToBytes as Wt,utf8ToBytes as Jt}from"@noble/ciphers/utils";import{managedNonce as Xt}from"@noble/ciphers/webcrypto";import{sha256 as er}from"oslo/crypto";function Z(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let n=0;for(let s=0;s<r.length;s++)n|=r[s]^o[s];return n===0}import{decodeHex as zt,encodeHex as Vt}from"oslo/encoding";import{scryptAsync as Nt}from"@noble/hashes/scrypt";function Je(e){return e.toString(2).padStart(8,"0")}function Ke(e){return[...e].map(t=>Je(t)).join("")}function ee(e){return parseInt(Ke(e),2)}function Xe(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,o=new Uint8Array(Math.ceil(t/8));crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=ee(o);for(;n>=e;)crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=ee(o);return n}function q(e,t){let r="";for(let o=0;o<e;o++)r+=t[Xe(t.length)];return r}function N(...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 M(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 Ye,createMiddleware as te,createMiddlewareCreator as et}from"better-call";var re=te(async()=>({})),D=et({use:[re,te(async()=>({}))]}),p=Ye({use:[re]});var ne=D({body:oe.object({csrfToken:oe.string().optional()}).optional()},async e=>{if(e.request?.method!=="POST"||e.context.options.advanced?.disableCSRFCheck)return;let t=new URL(e.request.url);if(e.context.trustedOrigins.includes(t.origin))return;let r=e.body?.csrfToken;if(!r)throw new W("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 W("UNAUTHORIZED",{message:"Invalid CSRF Token"});let i=await M(e.context.secret,n);if(s!==i)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new W("UNAUTHORIZED",{message:"Invalid CSRF Token"})});import{APIError as O}from"better-call";import{generateCodeVerifier as wt}from"oslo/oauth2";import{z as E}from"zod";import{generateState as tt}from"oslo/oauth2";import{z as F}from"zod";import{sha256 as se}from"oslo/crypto";async function ie(e){let t=await se(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function ae(e,t){let r=await se(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return Z(r,o)}async function ce(e){let t=tt(),r=JSON.stringify({code:t,callbackURL:e}),o=await ie(r);return{raw:r,hash:o}}function J(e){return F.object({code:F.string(),callbackURL:F.string().optional(),currentURL:F.string().optional()}).safeParse(JSON.parse(e))}import{TimeSpan as Ur}from"oslo";var I=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};async function P(e,t,r,o){let n=e.context.authCookies.sessionToken.options;n.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options)}function z(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}import{APIError as de}from"better-call";import{createConsola as rt}from"consola";var C=rt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),ot=e=>({log:(...t)=>{!e?.disabled&&C.log("",...t)},error:(...t)=>{!e?.disabled&&C.error("",...t)},warn:(...t)=>{!e?.disabled&&C.warn("",...t)},info:(...t)=>{!e?.disabled&&C.info("",...t)},debug:(...t)=>{!e?.disabled&&C.debug("",...t)},box:(...t)=>{!e?.disabled&&C.box("",...t)},success:(...t)=>{!e?.disabled&&C.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
2
- `)}}),w=ot();var U=D(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 w.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new de("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let s=new URL(o).origin;if(!n.includes(s))throw w.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new de("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as at}from"oslo/jwt";import{sha256 as nt}from"oslo/crypto";import{base64url as st}from"oslo/encoding";async function ue(e){let t=await nt(new TextEncoder().encode(e));return st.encode(new Uint8Array(t),{includePadding:!1})}function pe(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_at?new Date((Date.now()+e.expires_in)*1e3):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:s,claims:i,disablePkce:c,redirectURI:a}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",s.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||a),!c&&n){let u=await ue(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",u)}if(i){let u=i.reduce((y,f)=>(y[f]=null,y),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return d}import{betterFetch as it}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:c}=await it(n,{method:"POST",body:s,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(c)throw c;return pe(i)}function K(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var le=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let 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({code:r,codeVerifier:o,redirectURI:n})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=at(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};import{betterFetch as ct}from"@better-fetch/fetch";var me=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await ct("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});import{betterFetch as dt}from"@better-fetch/fetch";var fe=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let s=e.scope||r||["email","public_profile"];return await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:s,state:t,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await dt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,emailVerified:r.email_verified},data:r}}});import{betterFetch as ge}from"@better-fetch/fetch";var he=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:s}){let i=e.scope||o||["user:email"];return A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:i,state:r,redirectURI:s,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>b({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await ge("https://api.github.com/user",{auth:{type:"Bearer",token:r.accessToken}});if(n)return null;let s=!1;if(!o.email){let{data:i,error:c}=await ge("https://api.github.com/user/emails",{auth:{type:"Bearer",token:r.accessToken}});c||(o.email=(i.find(a=>a.primary)??i[0])?.email,s=i.find(a=>a.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:s},data:o}}}};import{parseJWT as ut}from"oslo/jwt";var we=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw w.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new I("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new I("codeVerifier is required for Google");let s=e.scope||r||["email","profile"];return A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:s,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=ut(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});import{betterFetch as pt}from"@better-fetch/fetch";import{parseJWT as lt}from"oslo/jwt";var ye=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let s=e.scope||n.scopes||["openid","profile","email","User.Read"];return A({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:s,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:s,redirectURI:i}){return b({code:n,codeVerifier:s,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let s=lt(n.idToken)?.payload,i=e.profilePhotoSize||48;return await pt(`https://graph.microsoft.com/v1.0/me/photos/${i}x${i}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let d=await c.response.clone().arrayBuffer(),u=Buffer.from(d).toString("base64");s.picture=`data:image/jpeg;base64, ${u}`}catch(a){w.error(a)}}}),{user:{id:s.sub,name:s.name,email:s.email,image:s.picture,emailVerified:!0},data:s}}}};import{betterFetch as mt}from"@better-fetch/fetch";var be=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let s=e.scope||r||["user-read-email"];return A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:s,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await mt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";var S={isAction:!1};var Ae=e=>q(e||21,N("a-z","0-9","A-Z"));import{parseJWT as ft}from"oslo/jwt";var Re=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return w.error("No idToken found in token"),null;let o=ft(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as gt}from"@better-fetch/fetch";var ke=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return A({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await gt("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 ht={apple:le,discord:me,facebook:fe,github:he,microsoft:ye,google:we,spotify:be,twitch:Re,twitter:ke},Ue=Object.keys(ht);var Ee=p("/sign-in/social",{method:"POST",requireHeaders:!0,query:E.object({currentURL:E.string().optional()}).optional(),body:E.object({callbackURL:E.string().optional(),provider:E.enum(Ue)}),use:[U]},async e=>{let t=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new 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 ce(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,s.hash,e.context.secret,r.state.options);let i=wt();await e.setSignedCookie(r.pkCodeVerifier.name,i,e.context.secret,r.pkCodeVerifier.options);let c=await t.createAuthorizationURL({state:s.raw,codeVerifier:i,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:c.toString(),state:s,codeVerifier:i,redirect:!0})}),xe=p("/sign-in/email",{method:"POST",body:E.object({email:E.string().email(),password:E.string(),callbackURL:E.string().optional(),dontRememberMe:E.boolean().default(!1).optional()}),use:[U]},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new O("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!E.string().email().safeParse(t).success)throw new 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(d=>d.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 a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!a)throw e.context.logger.error("Failed to create session"),new O("UNAUTHORIZED",{message:"Failed to create session"});return await P(e,a.id,e.body.dontRememberMe),e.json({user:n.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{APIError as bt}from"better-call";import{z as H}from"zod";import{z as l}from"zod";var An=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()}),Pe=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)}),Rn=l.object({id:l.string(),userId:l.string(),expiresAt:l.date(),ipAddress:l.string().optional(),userAgent:l.string().optional()}),kn=l.object({id:l.string(),value:l.string(),expiresAt:l.date(),identifier:l.string()});function yt(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 Te(e,t){let r={...e.user?.additionalFields};return yt(t||{},{fields:r})}var ve=p("/callback/:id",{method:"GET",query:H.object({state:H.string(),code:H.string().optional(),error:H.string().optional()}),metadata:S},async e=>{if(e.query.error||!e.query.code){let h=J(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${h}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(m=>m.id===e.params.id);if(!t)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let r=J(e.query.state);if(!r.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:n}}=r,s=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!s)throw w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await ae(e.query.state,s))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let c=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),a;try{a=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(m){throw e.context.logger.error(m),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let d=await t.getUserInfo(a).then(m=>m?.user),u=Ae(),y=Pe.safeParse({...d,id:u});if(!d||y.success===!1)throw w.error("Unable to get user info",y.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let f=await e.context.internalAdapter.findUserByEmail(d.email,{includeAccounts:!0}).catch(m=>{throw w.error(`Better auth was unable to query your database.
2
+ `)}}),w=ot();var U=D(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 w.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new de("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let s=new URL(o).origin;if(!n.includes(s))throw w.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new de("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as at}from"oslo/jwt";import{sha256 as nt}from"oslo/crypto";import{base64url as st}from"oslo/encoding";async function ue(e){let t=await nt(new TextEncoder().encode(e));return st.encode(new Uint8Array(t),{includePadding:!1})}function pe(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_at?new Date((Date.now()+e.expires_in)*1e3):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:s,claims:i,disablePkce:c,redirectURI:a}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",s.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||a),!c&&n){let u=await ue(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",u)}if(i){let u=i.reduce((y,f)=>(y[f]=null,y),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return d}import{betterFetch as it}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:c}=await it(n,{method:"POST",body:s,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(c)throw c;return pe(i)}function K(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var le=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let 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({code:r,codeVerifier:o,redirectURI:n})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=at(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};import{betterFetch as ct}from"@better-fetch/fetch";var me=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await ct("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});import{betterFetch as dt}from"@better-fetch/fetch";var fe=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["email","public_profile"];return await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await dt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,emailVerified:r.email_verified},data:r}}});import{betterFetch as ge}from"@better-fetch/fetch";var he=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:s}){let i=e.scope||o||["user:email"];return A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:i,state:r,redirectURI:s,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>b({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await ge("https://api.github.com/user",{auth:{type:"Bearer",token:r.accessToken}});if(n)return null;let s=!1;if(!o.email){let{data:i,error:c}=await ge("https://api.github.com/user/emails",{auth:{type:"Bearer",token:r.accessToken}});c||(o.email=(i.find(a=>a.primary)??i[0])?.email,s=i.find(a=>a.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:s},data:o}}}};import{parseJWT as ut}from"oslo/jwt";var we=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw w.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new I("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new I("codeVerifier is required for Google");let s=e.scope||r||["email","profile"];return A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:s,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=ut(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});import{betterFetch as pt}from"@better-fetch/fetch";import{parseJWT as lt}from"oslo/jwt";var ye=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let s=e.scope||n.scopes||["openid","profile","email","User.Read"];return A({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:s,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:s,redirectURI:i}){return b({code:n,codeVerifier:s,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let s=lt(n.idToken)?.payload,i=e.profilePhotoSize||48;return await pt(`https://graph.microsoft.com/v1.0/me/photos/${i}x${i}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let d=await c.response.clone().arrayBuffer(),u=Buffer.from(d).toString("base64");s.picture=`data:image/jpeg;base64, ${u}`}catch(a){w.error(a)}}}),{user:{id:s.sub,name:s.name,email:s.email,image:s.picture,emailVerified:!0},data:s}}}};import{betterFetch as mt}from"@better-fetch/fetch";var be=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let s=e.scope||r||["user-read-email"];return A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:s,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await mt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";var S={isAction:!1};var Ae=e=>q(e||21,N("a-z","0-9","A-Z"));import{parseJWT as ft}from"oslo/jwt";var Re=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return w.error("No idToken found in token"),null;let o=ft(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as gt}from"@better-fetch/fetch";var ke=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return A({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await gt("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 ht={apple:le,discord:me,facebook:fe,github:he,microsoft:ye,google:we,spotify:be,twitch:Re,twitter:ke},Ue=Object.keys(ht);var Ee=p("/sign-in/social",{method:"POST",requireHeaders:!0,query:E.object({currentURL:E.string().optional()}).optional(),body:E.object({callbackURL:E.string().optional(),provider:E.enum(Ue)}),use:[U]},async e=>{let t=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new 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 ce(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,s.hash,e.context.secret,r.state.options);let i=wt();await e.setSignedCookie(r.pkCodeVerifier.name,i,e.context.secret,r.pkCodeVerifier.options);let c=await t.createAuthorizationURL({state:s.raw,codeVerifier:i,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:c.toString(),state:s,codeVerifier:i,redirect:!0})}),xe=p("/sign-in/email",{method:"POST",body:E.object({email:E.string().email(),password:E.string(),callbackURL:E.string().optional(),dontRememberMe:E.boolean().default(!1).optional()}),use:[U]},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new O("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!E.string().email().safeParse(t).success)throw new 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(d=>d.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 a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!a)throw e.context.logger.error("Failed to create session"),new O("UNAUTHORIZED",{message:"Failed to create session"});return await P(e,a.id,e.body.dontRememberMe),e.json({user:n.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{APIError as bt}from"better-call";import{z as H}from"zod";import{z as l}from"zod";var An=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()}),Pe=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)}),Rn=l.object({id:l.string(),userId:l.string(),expiresAt:l.date(),ipAddress:l.string().optional(),userAgent:l.string().optional()}),kn=l.object({id:l.string(),value:l.string(),expiresAt:l.date(),identifier:l.string()});function yt(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 Te(e,t){let r={...e.user?.additionalFields};return yt(t||{},{fields:r})}var ve=p("/callback/:id",{method:"GET",query:H.object({state:H.string(),code:H.string().optional(),error:H.string().optional()}),metadata:S},async e=>{if(e.query.error||!e.query.code){let h=J(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${h}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(m=>m.id===e.params.id);if(!t)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let r=J(e.query.state);if(!r.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:n}}=r,s=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!s)throw w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await ae(e.query.state,s))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let c=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),a;try{a=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(m){throw e.context.logger.error(m),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let d=await t.getUserInfo(a).then(m=>m?.user),u=Ae(),y=Pe.safeParse({...d,id:u});if(!d||y.success===!1)throw w.error("Unable to get user info",y.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let f=await e.context.internalAdapter.findUserByEmail(d.email,{includeAccounts:!0}).catch(m=>{throw w.error(`Better auth was unable to query your database.
3
3
  Error: `,m),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),g=f?.user.id;if(f){let m=f.accounts.find(k=>k.providerId===t.id),h=e.context.options.account?.accountLinking?.trustedProviders,R=h?h.includes(t.id):!0;if(!m&&(!d.emailVerified||!R)){let k;try{k=new URL(n||o),k.searchParams.set("error","account_not_linked")}catch{throw e.redirect(`${e.context.baseURL}/error?error=account_not_linked`)}throw e.redirect(k.toString())}if(!m)try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:d.id.toString(),id:`${t.id}:${d.id}`,userId:f.user.id,...K(a)})}catch(k){throw console.log(k),e.redirect(`${e.context.baseURL}/error?error=failed_linking_account`)}}else try{await e.context.internalAdapter.createOAuthUser(y.data,{...K(a),id:`${t.id}:${d.id}`,providerId:t.id,accountId:d.id.toString(),userId:u})}catch{let h=new URL(n||o);throw h.searchParams.set("error","unable_to_create_user"),e.setHeader("Location",h.toString()),e.redirect(h.toString())}if(!g&&!u)throw new bt("INTERNAL_SERVER_ERROR",{message:"Unable to create user"});try{let m=await e.context.internalAdapter.createSession(g||u,e.request);if(!m){let h=new URL(n||o);throw h.searchParams.set("error","unable_to_create_session"),e.redirect(h.toString())}try{await P(e,m.id)}catch(h){e.context.logger.error("Unable to set session cookie",h);let R=new URL(n||o);throw R.searchParams.set("error","unable_to_create_session"),e.redirect(R.toString())}}catch{let m=new URL(n||o||"");throw m.searchParams.set("error","unable_to_create_session"),e.redirect(m.toString())}throw e.redirect(o)});import{APIError as V}from"better-call";var Q=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as _e}from"zod";var X=()=>p("/session",{method:"GET",requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return z(e),r&&await e.context.internalAdapter.deleteSession(r.session.id),e.json(null,{status:401});if(await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(r);let n=e.context.sessionConfig.expiresIn,s=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+s*1e3<=Date.now()){let a=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:Q(e.context.sessionConfig.expiresIn,"sec")});if(!a)return z(e),e.json(null,{status:401});let d=(a.expiresAt.valueOf()-Date.now())/1e3;return await P(e,a.id,!1,{maxAge:d}),e.json({session:a,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),At=async e=>await X()({...e,_flag:"json",headers:e.headers}),L=D(async e=>{let t=await At(e);if(!t?.session)throw new V("UNAUTHORIZED");return{session:t}}),Se=()=>p("/user/list-sessions",{method:"GET",use:[L],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Oe=p("/user/revoke-session",{method:"POST",body:_e.object({id:_e.string()}),use:[L],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new V("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new V("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new V("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Le=p("/user/revoke-sessions",{method:"POST",use:[L],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new V("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});import"zod";import{APIError as Rt}from"better-call";var Ie=p("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Rt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),z(e),e.json({success:!0})});import{z as _}from"zod";import{APIError as G}from"better-call";var Ce=p("/forget-password",{method:"POST",body:_.object({email:_.string().email(),redirectTo:_.string()}),use:[U]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new G("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,s=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n)),i=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${i}`,expiresAt:s});let c=`${e.context.baseURL}/reset-password/${i}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(c,o.user),e.json({status:!0})}),Be=p("/reset-password/:token",{method:"GET",query:_.object({callbackURL:_.string()}),use:[U]},async e=>{let{token:t}=e.params,r=e.query.callbackURL,o=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}?token=${t}`)}),De=p("/reset-password",{query:_.object({token:_.string()}).optional(),method:"POST",body:_.object({newPassword:_.string()})},async e=>{let t=e.query?.token;if(!t)throw new G("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new G("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let s=n.value,i=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(s)).find(u=>u.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:s,providerId:"credential",password:i,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(s,i))throw new G("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{TimeSpan as kt}from"oslo";import{createJWT as Ut,validateJWT as Et}from"oslo/jwt";import{z as T}from"zod";import{APIError as j}from"better-call";async function Y(e,t){return await Ut("HS256",Buffer.from(e),{email:t.toLowerCase()},{expiresIn:new kt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var $e=p("/send-verification-email",{method:"POST",query:T.object({currentURL:T.string().optional()}).optional(),body:T.object({email:T.string().email(),callbackURL:T.string().optional()}),use:[U]},async e=>{if(!e.context.options.emailAndPassword?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled. Pass `sendVerificationEmail` in `emailAndPassword` options to enable it."),new j("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new j("BAD_REQUEST",{message:"User not found"});let o=await Y(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})}),ze=p("/verify-email",{method:"GET",query:T.object({token:T.string(),callbackURL:T.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await Et("HS256",Buffer.from(e.context.secret),t)}catch(c){throw e.context.logger.error("Failed to verify email",c),new j("BAD_REQUEST",{message:"Invalid token"})}let n=T.object({email:T.string().email()}).parse(r.payload),s=await e.context.internalAdapter.findUserByEmail(n.email,{includeAccounts:!0});if(!s)throw new j("BAD_REQUEST",{message:"User not found"});if(!s.accounts.find(c=>c.providerId==="credential"))throw new j("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 x}from"zod";import{APIError as v}from"better-call";var Ve=p("/user/update",{method:"POST",body:x.object({name:x.string().optional(),image:x.string().optional()}),use:[L,U]},async e=>{let{name:t,image:r}=e.body,o=e.context.session;if(!r&&!t)return e.json({user:o.user});let n=await e.context.internalAdapter.updateUserByEmail(o.user.email,{name:t,image:r});return e.json({user:n})}),je=p("/user/change-password",{method:"POST",body:x.object({newPassword:x.string(),currentPassword:x.string(),revokeOtherSessions:x.boolean().optional()}),use:[L]},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 v("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 v("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(y=>y.providerId==="credential"&&y.password);if(!a||!a.password)throw new v("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify(a.password,r))throw new v("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(a.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let y=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!y)throw new v("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await P(e,y.id)}return e.json(n.user)}),qe=p("/user/set-password",{method:"POST",body:x.object({newPassword:x.string()}),use:[L]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new v("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 v("BAD_REQUEST",{message:"Password too long"});let i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password),c=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:c}),e.json(r.user);throw new v("BAD_REQUEST",{message:"user already has a password"})}),Ne=p("/user/delete",{method:"POST",body:x.object({password:x.string()}),use:[L]},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 v("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new v("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),e.json(null)});var Me=p("/csrf",{method:"GET",metadata:S},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t)return{csrfToken:t};let r=q(32,N("a-z","0-9","A-Z")),o=await M(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 xt=(e="Unknown")=>`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
@@ -1190,12 +1190,12 @@ declare const signInOAuth: {
1190
1190
  /**
1191
1191
  * OAuth2 provider to use`
1192
1192
  */
1193
- provider: z.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
1193
+ provider: z.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter")[]]>;
1194
1194
  }, "strip", z.ZodTypeAny, {
1195
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
1195
+ provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
1196
1196
  callbackURL?: string | undefined;
1197
1197
  }, {
1198
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
1198
+ provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
1199
1199
  callbackURL?: string | undefined;
1200
1200
  }>;
1201
1201
  use: better_call.Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
@@ -1233,12 +1233,12 @@ declare const signInOAuth: {
1233
1233
  /**
1234
1234
  * OAuth2 provider to use`
1235
1235
  */
1236
- provider: z.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
1236
+ provider: z.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter")[]]>;
1237
1237
  }, "strip", z.ZodTypeAny, {
1238
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
1238
+ provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
1239
1239
  callbackURL?: string | undefined;
1240
1240
  }, {
1241
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
1241
+ provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
1242
1242
  callbackURL?: string | undefined;
1243
1243
  }>;
1244
1244
  use: better_call.Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
@@ -2435,12 +2435,12 @@ declare function getEndpoints<C extends AuthContext, Option extends BetterAuthOp
2435
2435
  }>>;
2436
2436
  body: zod.ZodObject<{
2437
2437
  callbackURL: zod.ZodOptional<zod.ZodString>;
2438
- provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
2438
+ provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter")[]]>;
2439
2439
  }, "strip", zod.ZodTypeAny, {
2440
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
2440
+ provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
2441
2441
  callbackURL?: string | undefined;
2442
2442
  }, {
2443
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
2443
+ provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
2444
2444
  callbackURL?: string | undefined;
2445
2445
  }>;
2446
2446
  use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
@@ -2468,12 +2468,12 @@ declare function getEndpoints<C extends AuthContext, Option extends BetterAuthOp
2468
2468
  }>>;
2469
2469
  body: zod.ZodObject<{
2470
2470
  callbackURL: zod.ZodOptional<zod.ZodString>;
2471
- provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
2471
+ provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter")[]]>;
2472
2472
  }, "strip", zod.ZodTypeAny, {
2473
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
2473
+ provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
2474
2474
  callbackURL?: string | undefined;
2475
2475
  }, {
2476
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
2476
+ provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
2477
2477
  callbackURL?: string | undefined;
2478
2478
  }>;
2479
2479
  use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
@@ -3530,12 +3530,12 @@ declare const router: <C extends AuthContext, Option extends BetterAuthOptions>(
3530
3530
  }>>;
3531
3531
  body: zod.ZodObject<{
3532
3532
  callbackURL: zod.ZodOptional<zod.ZodString>;
3533
- provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
3533
+ provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter")[]]>;
3534
3534
  }, "strip", zod.ZodTypeAny, {
3535
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
3535
+ provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
3536
3536
  callbackURL?: string | undefined;
3537
3537
  }, {
3538
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
3538
+ provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
3539
3539
  callbackURL?: string | undefined;
3540
3540
  }>;
3541
3541
  use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
@@ -3563,12 +3563,12 @@ declare const router: <C extends AuthContext, Option extends BetterAuthOptions>(
3563
3563
  }>>;
3564
3564
  body: zod.ZodObject<{
3565
3565
  callbackURL: zod.ZodOptional<zod.ZodString>;
3566
- provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
3566
+ provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter")[]]>;
3567
3567
  }, "strip", zod.ZodTypeAny, {
3568
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
3568
+ provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
3569
3569
  callbackURL?: string | undefined;
3570
3570
  }, {
3571
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
3571
+ provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
3572
3572
  callbackURL?: string | undefined;
3573
3573
  }>;
3574
3574
  use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
@@ -4627,12 +4627,12 @@ declare const betterAuth: <O extends BetterAuthOptions>(options: O) => {
4627
4627
  }>>;
4628
4628
  body: zod.ZodObject<{
4629
4629
  callbackURL: zod.ZodOptional<zod.ZodString>;
4630
- provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
4630
+ provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter")[]]>;
4631
4631
  }, "strip", zod.ZodTypeAny, {
4632
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
4632
+ provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
4633
4633
  callbackURL?: string | undefined;
4634
4634
  }, {
4635
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
4635
+ provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
4636
4636
  callbackURL?: string | undefined;
4637
4637
  }>;
4638
4638
  use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
@@ -4660,12 +4660,12 @@ declare const betterAuth: <O extends BetterAuthOptions>(options: O) => {
4660
4660
  }>>;
4661
4661
  body: zod.ZodObject<{
4662
4662
  callbackURL: zod.ZodOptional<zod.ZodString>;
4663
- provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
4663
+ provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter")[]]>;
4664
4664
  }, "strip", zod.ZodTypeAny, {
4665
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
4665
+ provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
4666
4666
  callbackURL?: string | undefined;
4667
4667
  }, {
4668
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
4668
+ provider: "github" | "apple" | "discord" | "facebook" | "microsoft" | "google" | "spotify" | "twitch" | "twitter";
4669
4669
  callbackURL?: string | undefined;
4670
4670
  }>;
4671
4671
  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-DgJ3JDtV.js';
6
- export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-DgJ3JDtV.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-e73K5key.js';
6
+ export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-e73K5key.js';
7
7
  import { P as Prettify } from '../helper-DPDj8Nix.js';
8
- import { F as FieldAttribute, B as BetterAuthOptions, b as BetterAuthPlugin } from '../auth-BGQTSAwN.js';
8
+ import { F as FieldAttribute, B as BetterAuthOptions, b as BetterAuthPlugin } from '../auth-Cx7ibOvY.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-BGQTSAwN.js';
9
+ import './auth-Cx7ibOvY.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-BGQTSAwN.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-Cx7ibOvY.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, B as BetterAuthOptions, W as Where, F as FieldAttribute, y as FieldType, K as KyselyDatabaseType } from './auth-BGQTSAwN.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-BGQTSAwN.js';
1
+ import { A as Adapter, B as BetterAuthOptions, W as Where, F as FieldAttribute, y as FieldType, K as KyselyDatabaseType } from './auth-Cx7ibOvY.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-Cx7ibOvY.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-BGQTSAwN.js';
8
+ import { H as HookEndpointContext, p as AuthContext } from './auth-Cx7ibOvY.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, a as Auth, p as AuthContext, s as BetterAuthCookies, B 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-BGQTSAwN.js';
1
+ export { A as Adapter, j as AdditionalSessionFieldsInput, k as AdditionalSessionFieldsOutput, h as AdditionalUserFieldsInput, i as AdditionalUserFieldsOutput, a as Auth, p as AuthContext, s as BetterAuthCookies, B 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-Cx7ibOvY.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';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import{APIError as pr,createRouter as fr}from"better-call";import{APIError as re}from"better-call";import{z as ke}from"zod";import{xchacha20poly1305 as Er}from"@noble/ciphers/chacha";import{bytesToHex as Or,hexToBytes as Sr,utf8ToBytes as Ir}from"@noble/ciphers/utils";import{managedNonce as _r}from"@noble/ciphers/webcrypto";import{sha256 as Br}from"oslo/crypto";function G(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 Pt,encodeHex as ge}from"oslo/encoding";import{scryptAsync as Ot}from"@noble/hashes/scrypt";var q={N:16384,r:16,p:1,dkLen:64};async function he(e,t){return await Ot(e.normalize("NFKC"),t,{N:q.N,p:q.p,r:q.r,dkLen:q.dkLen,maxmem:128*q.N*q.r*2})}var ye=async e=>{let t=ge(crypto.getRandomValues(new Uint8Array(16))),r=await he(e,t);return`${t}:${ge(r)}`},we=async(e,t)=>{let[r,o]=e.split(":"),n=await he(t,r);return G(n,Pt(o))};function St(e){return e.toString(2).padStart(8,"0")}function It(e){return[...e].map(t=>St(t)).join("")}function be(e){return parseInt(It(e),2)}function Lt(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=be(o);for(;n>=e;)crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=be(o);return n}function Z(e,t){let r="";for(let o=0;o<e;o++)r+=t[Lt(t.length)];return r}function Q(...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 W(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 _t,createMiddleware as Ae,createMiddlewareCreator as Ct}from"better-call";var Re=Ae(async()=>({})),V=Ct({use:[Re,Ae(async()=>({}))]}),h=_t({use:[Re]});var xe=V({body:ke.object({csrfToken:ke.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 re("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 re("UNAUTHORIZED",{message:"Invalid CSRF Token"});let a=await W(e.context.secret,n);if(s!==a)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new re("UNAUTHORIZED",{message:"Invalid CSRF Token"})});import{APIError as C}from"better-call";import{generateCodeVerifier as Jt}from"oslo/oauth2";import{z as v}from"zod";import{generateState as Bt}from"oslo/oauth2";import{z as J}from"zod";import{sha256 as Te}from"oslo/crypto";async function Ue(e){let t=await Te(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function ve(e,t){let r=await Te(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return G(r,o)}async function Ee(e){let t=Bt(),r=JSON.stringify({code:t,callbackURL:e}),o=await Ue(r);return{raw:r,hash:o}}function oe(e){return J.object({code:J.string(),callbackURL:J.string().optional(),currentURL:J.string().optional()}).safeParse(JSON.parse(e))}import{TimeSpan as Dt}from"oslo";var R=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}},Pe=class extends R{constructor(t){super(`The package "${t}" is required. Make sure it is installed.`,t)}};function Oe(e){let r=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:(e.baseURL?e.baseURL.startsWith("https://"):!1)||process.env.NODE_ENV==="production")?"__Secure-":"",o="better-auth",n=e.session?.expiresIn||new Dt(7,"d").seconds(),s=!!e.advanced?.crossSubDomainCookies?.enabled,a=s?e.advanced?.crossSubDomainCookies?.domain||(e.baseURL?new URL(e.baseURL).hostname:void 0):void 0;if(s&&!a)throw new R("baseURL is required when crossSubdomainCookies are enabled");let c=s?"none":"lax";return{sessionToken:{name:`${r}${o}.session_token`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:n,...s?{domain:a}:{}}},csrfToken:{name:`${r}${o}.csrf_token`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:60*60*24*7,...s?{domain:a}:{}}},state:{name:`${r}${o}.state`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:60*15,...s?{domain:a}:{}}},pkCodeVerifier:{name:`${r}${o}.pk_code_verifier`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:60*15,...s?{domain:a}:{}}},dontRememberToken:{name:`${r}${o}.dont_remember`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,...s?{domain:a}:{}}},nonce:{name:`${r}${o}.nonce`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:60*15,...s?{domain:a}:{}}}}}function Se(e){let r=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:e.baseURL?.startsWith("https://")||process.env.NODE_ENV==="production")?"__Secure-":"",o="better-auth",n=e.advanced?.crossSubDomainCookies?.domain||(e.baseURL?new URL(e.baseURL).hostname:void 0);function s(a,c){let i=e.advanced?.crossSubDomainCookies?.enabled?e.advanced.crossSubDomainCookies.additionalCookies?.includes(a):void 0;return{name:process.env.NODE_ENV==="production"?`${r}${o}.${a}`:`${o}.${a}`,options:{secure:!!r,sameSite:"lax",path:"/",maxAge:60*15,...c,...i?{domain:n}:{}}}}return s}async function P(e,t,r,o){let n=e.context.authCookies.sessionToken.options;n.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options)}function j(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}function so(e){let t=new Map;return e.split(", ").forEach(o=>{let[n,...s]=o.split("; "),[a,c]=n.split("="),i={value:c};s.forEach(d=>{let[l,p]=d.split("=");i[l.toLowerCase()]=p||!0}),t.set(a,i)}),t}import{APIError as Ie}from"better-call";import{createConsola as Nt}from"consola";var D=Nt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),ne=e=>({log:(...t)=>{!e?.disabled&&D.log("",...t)},error:(...t)=>{!e?.disabled&&D.error("",...t)},warn:(...t)=>{!e?.disabled&&D.warn("",...t)},info:(...t)=>{!e?.disabled&&D.info("",...t)},debug:(...t)=>{!e?.disabled&&D.debug("",...t)},box:(...t)=>{!e?.disabled&&D.box("",...t)},success:(...t)=>{!e?.disabled&&D.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
2
- `)}}),w=ne();var T=V(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 w.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new Ie("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let s=new URL(o).origin;if(!n.includes(s))throw w.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new Ie("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as jt}from"oslo/jwt";import{sha256 as qt}from"oslo/crypto";function Ft(e){try{return new URL(e).pathname!=="/"}catch{throw new R(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function se(e,t="/api/auth"){return Ft(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function z(e,t){if(e)return se(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 se(o,t);if(typeof window<"u")return se(window.location.origin,t)}import{base64url as Vt}from"oslo/encoding";async function Le(e){let t=await qt(new TextEncoder().encode(e));return Vt.encode(new Uint8Array(t),{includePadding:!1})}function _e(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_at?new Date((Date.now()+e.expires_in)*1e3):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function k({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:s,claims:a,disablePkce:c,redirectURI:i}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",s.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||i),!c&&n){let l=await Le(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",l)}if(a){let l=a.reduce((p,u)=>(p[u]=null,p),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return d}import{betterFetch as $t}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:a,error:c}=await $t(n,{method:"POST",body:s,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(c)throw c;return _e(a)}function ie(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var Ce=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({code:r,codeVerifier:o,redirectURI:n})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=jt(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 zt}from"@better-fetch/fetch";var Be=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await zt("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 Mt}from"@better-fetch/fetch";var De=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let s=e.scope||r||["email","public_profile"];return await k({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:s,state:t,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await Mt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,emailVerified:r.email_verified},data:r}}});import{betterFetch as Ne}from"@better-fetch/fetch";var Fe=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:s}){let a=e.scope||o||["user:email"];return k({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:r,redirectURI:s,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>b({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await Ne("https://api.github.com/user",{auth:{type:"Bearer",token:r.accessToken}});if(n)return null;let s=!1;if(!o.email){let{data:a,error:c}=await Ne("https://api.github.com/user/emails",{auth:{type:"Bearer",token:r.accessToken}});c||(o.email=(a.find(i=>i.primary)??a[0])?.email,s=a.find(i=>i.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 Ht}from"oslo/jwt";var qe=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw w.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new R("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new R("codeVerifier is required for Google");let s=e.scope||r||["email","profile"];return k({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:s,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=Ht(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 Kt}from"@better-fetch/fetch";import{parseJWT as Gt}from"oslo/jwt";var Ve=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 k({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:s,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:s,redirectURI:a}){return b({code:n,codeVerifier:s,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let s=Gt(n.idToken)?.payload,a=e.profilePhotoSize||48;return await Kt(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let d=await c.response.clone().arrayBuffer(),l=Buffer.from(d).toString("base64");s.picture=`data:image/jpeg;base64, ${l}`}catch(i){w.error(i)}}}),{user:{id:s.sub,name:s.name,email:s.email,image:s.picture,emailVerified:!0},data:s}}}};import{betterFetch as Zt}from"@better-fetch/fetch";var $e=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let s=e.scope||r||["user-read-email"];return k({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:s,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await Zt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";function sn(e){return e.charAt(0).toUpperCase()+e.slice(1)}var _={isAction:!1};var U=e=>Z(e||21,Q("a-z","0-9","A-Z"));import{parseJWT as Qt}from"oslo/jwt";var je=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return k({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return w.error("No idToken found in token"),null;let o=Qt(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as Wt}from"@better-fetch/fetch";var ze=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return k({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await Wt("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 ae={apple:Ce,discord:Be,facebook:De,github:Fe,microsoft:Ve,google:qe,spotify:$e,twitch:je,twitter:ze},Me=Object.keys(ae);var He=h("/sign-in/social",{method:"POST",requireHeaders:!0,query:v.object({currentURL:v.string().optional()}).optional(),body:v.object({callbackURL:v.string().optional(),provider:v.enum(Me)}),use:[T]},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new C("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 Ee(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,s.hash,e.context.secret,r.state.options);let a=Jt();await e.setSignedCookie(r.pkCodeVerifier.name,a,e.context.secret,r.pkCodeVerifier.options);let c=await t.createAuthorizationURL({state:s.raw,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:c.toString(),state:s,codeVerifier:a,redirect:!0})}),Ke=h("/sign-in/email",{method:"POST",body:v.object({email:v.string().email(),password:v.string(),callbackURL:v.string().optional(),dontRememberMe:v.boolean().default(!1).optional()}),use:[T]},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 C("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!v.string().email().safeParse(t).success)throw new C("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 C("UNAUTHORIZED",{message:"Invalid email or password"});let s=n.accounts.find(d=>d.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new C("UNAUTHORIZED",{message:"Invalid email or password"});let a=s?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new C("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new C("UNAUTHORIZED",{message:"Invalid email or password"});let i=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!i)throw e.context.logger.error("Failed to create session"),new C("UNAUTHORIZED",{message:"Failed to create session"});return await P(e,i.id,e.body.dontRememberMe),e.json({user:n.user,session:i,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{APIError as Yt}from"better-call";import{z as X}from"zod";import{z as y}from"zod";var rs=y.object({id:y.string(),providerId:y.string(),accountId:y.string(),userId:y.string(),accessToken:y.string().nullable().optional(),refreshToken:y.string().nullable().optional(),idToken:y.string().nullable().optional(),expiresAt:y.date().nullable().optional(),password:y.string().optional().nullable()}),Ge=y.object({id:y.string(),email:y.string().transform(e=>e.toLowerCase()),emailVerified:y.boolean().default(!1),name:y.string(),image:y.string().optional(),createdAt:y.date().default(new Date),updatedAt:y.date().default(new Date)}),os=y.object({id:y.string(),userId:y.string(),expiresAt:y.date(),ipAddress:y.string().optional(),userAgent:y.string().optional()}),ns=y.object({id:y.string(),value:y.string(),expiresAt:y.date(),identifier:y.string()});function Xt(e,t){let r=t.fields,o={};for(let n in r){if(n in e){if(r[n].input===!1){if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}continue}o[n]=e[n];continue}if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}}return o}function Ze(e,t){let r={...e.user?.additionalFields};return Xt(t||{},{fields:r})}var Qe=h("/callback/:id",{method:"GET",query:X.object({state:X.string(),code:X.string().optional(),error:X.string().optional()}),metadata:_},async e=>{if(e.query.error||!e.query.code){let g=oe(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${g}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(f=>f.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=oe(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 w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await ve(e.query.state,s))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let c=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),i;try{i=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(f){throw e.context.logger.error(f),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let d=await t.getUserInfo(i).then(f=>f?.user),l=U(),p=Ge.safeParse({...d,id:l});if(!d||p.success===!1)throw w.error("Unable to get user info",p.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 u=await e.context.internalAdapter.findUserByEmail(d.email,{includeAccounts:!0}).catch(f=>{throw w.error(`Better auth was unable to query your database.
2
+ `)}}),w=ne();var T=V(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 w.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new Ie("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let s=new URL(o).origin;if(!n.includes(s))throw w.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new Ie("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as jt}from"oslo/jwt";import{sha256 as qt}from"oslo/crypto";function Ft(e){try{return new URL(e).pathname!=="/"}catch{throw new R(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function se(e,t="/api/auth"){return Ft(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function z(e,t){if(e)return se(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 se(o,t);if(typeof window<"u")return se(window.location.origin,t)}import{base64url as Vt}from"oslo/encoding";async function Le(e){let t=await qt(new TextEncoder().encode(e));return Vt.encode(new Uint8Array(t),{includePadding:!1})}function _e(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_at?new Date((Date.now()+e.expires_in)*1e3):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function k({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:s,claims:a,disablePkce:c,redirectURI:i}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",s.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||i),!c&&n){let l=await Le(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",l)}if(a){let l=a.reduce((p,u)=>(p[u]=null,p),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return d}import{betterFetch as $t}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:a,error:c}=await $t(n,{method:"POST",body:s,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(c)throw c;return _e(a)}function ie(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var Ce=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({code:r,codeVerifier:o,redirectURI:n})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=jt(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 zt}from"@better-fetch/fetch";var Be=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await zt("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 Mt}from"@better-fetch/fetch";var De=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["email","public_profile"];return await k({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await Mt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,emailVerified:r.email_verified},data:r}}});import{betterFetch as Ne}from"@better-fetch/fetch";var Fe=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:s}){let a=e.scope||o||["user:email"];return k({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:r,redirectURI:s,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>b({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await Ne("https://api.github.com/user",{auth:{type:"Bearer",token:r.accessToken}});if(n)return null;let s=!1;if(!o.email){let{data:a,error:c}=await Ne("https://api.github.com/user/emails",{auth:{type:"Bearer",token:r.accessToken}});c||(o.email=(a.find(i=>i.primary)??a[0])?.email,s=a.find(i=>i.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 Ht}from"oslo/jwt";var qe=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw w.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new R("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new R("codeVerifier is required for Google");let s=e.scope||r||["email","profile"];return k({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:s,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=Ht(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 Kt}from"@better-fetch/fetch";import{parseJWT as Gt}from"oslo/jwt";var Ve=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 k({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:s,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:s,redirectURI:a}){return b({code:n,codeVerifier:s,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let s=Gt(n.idToken)?.payload,a=e.profilePhotoSize||48;return await Kt(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let d=await c.response.clone().arrayBuffer(),l=Buffer.from(d).toString("base64");s.picture=`data:image/jpeg;base64, ${l}`}catch(i){w.error(i)}}}),{user:{id:s.sub,name:s.name,email:s.email,image:s.picture,emailVerified:!0},data:s}}}};import{betterFetch as Zt}from"@better-fetch/fetch";var $e=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let s=e.scope||r||["user-read-email"];return k({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:s,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await Zt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";function sn(e){return e.charAt(0).toUpperCase()+e.slice(1)}var _={isAction:!1};var U=e=>Z(e||21,Q("a-z","0-9","A-Z"));import{parseJWT as Qt}from"oslo/jwt";var je=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return k({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return w.error("No idToken found in token"),null;let o=Qt(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as Wt}from"@better-fetch/fetch";var ze=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return k({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await Wt("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 ae={apple:Ce,discord:Be,facebook:De,github:Fe,microsoft:Ve,google:qe,spotify:$e,twitch:je,twitter:ze},Me=Object.keys(ae);var He=h("/sign-in/social",{method:"POST",requireHeaders:!0,query:v.object({currentURL:v.string().optional()}).optional(),body:v.object({callbackURL:v.string().optional(),provider:v.enum(Me)}),use:[T]},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new C("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 Ee(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,s.hash,e.context.secret,r.state.options);let a=Jt();await e.setSignedCookie(r.pkCodeVerifier.name,a,e.context.secret,r.pkCodeVerifier.options);let c=await t.createAuthorizationURL({state:s.raw,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:c.toString(),state:s,codeVerifier:a,redirect:!0})}),Ke=h("/sign-in/email",{method:"POST",body:v.object({email:v.string().email(),password:v.string(),callbackURL:v.string().optional(),dontRememberMe:v.boolean().default(!1).optional()}),use:[T]},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 C("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!v.string().email().safeParse(t).success)throw new C("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 C("UNAUTHORIZED",{message:"Invalid email or password"});let s=n.accounts.find(d=>d.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new C("UNAUTHORIZED",{message:"Invalid email or password"});let a=s?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new C("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new C("UNAUTHORIZED",{message:"Invalid email or password"});let i=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!i)throw e.context.logger.error("Failed to create session"),new C("UNAUTHORIZED",{message:"Failed to create session"});return await P(e,i.id,e.body.dontRememberMe),e.json({user:n.user,session:i,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{APIError as Yt}from"better-call";import{z as X}from"zod";import{z as y}from"zod";var rs=y.object({id:y.string(),providerId:y.string(),accountId:y.string(),userId:y.string(),accessToken:y.string().nullable().optional(),refreshToken:y.string().nullable().optional(),idToken:y.string().nullable().optional(),expiresAt:y.date().nullable().optional(),password:y.string().optional().nullable()}),Ge=y.object({id:y.string(),email:y.string().transform(e=>e.toLowerCase()),emailVerified:y.boolean().default(!1),name:y.string(),image:y.string().optional(),createdAt:y.date().default(new Date),updatedAt:y.date().default(new Date)}),os=y.object({id:y.string(),userId:y.string(),expiresAt:y.date(),ipAddress:y.string().optional(),userAgent:y.string().optional()}),ns=y.object({id:y.string(),value:y.string(),expiresAt:y.date(),identifier:y.string()});function Xt(e,t){let r=t.fields,o={};for(let n in r){if(n in e){if(r[n].input===!1){if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}continue}o[n]=e[n];continue}if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}}return o}function Ze(e,t){let r={...e.user?.additionalFields};return Xt(t||{},{fields:r})}var Qe=h("/callback/:id",{method:"GET",query:X.object({state:X.string(),code:X.string().optional(),error:X.string().optional()}),metadata:_},async e=>{if(e.query.error||!e.query.code){let g=oe(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${g}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(f=>f.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=oe(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 w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await ve(e.query.state,s))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let c=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),i;try{i=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(f){throw e.context.logger.error(f),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let d=await t.getUserInfo(i).then(f=>f?.user),l=U(),p=Ge.safeParse({...d,id:l});if(!d||p.success===!1)throw w.error("Unable to get user info",p.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 u=await e.context.internalAdapter.findUserByEmail(d.email,{includeAccounts:!0}).catch(f=>{throw w.error(`Better auth was unable to query your database.
3
3
  Error: `,f),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),m=u?.user.id;if(u){let f=u.accounts.find(x=>x.providerId===t.id),g=e.context.options.account?.accountLinking?.trustedProviders,A=g?g.includes(t.id):!0;if(!f&&(!d.emailVerified||!A)){let x;try{x=new URL(n||o),x.searchParams.set("error","account_not_linked")}catch{throw e.redirect(`${e.context.baseURL}/error?error=account_not_linked`)}throw e.redirect(x.toString())}if(!f)try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:d.id.toString(),id:`${t.id}:${d.id}`,userId:u.user.id,...ie(i)})}catch(x){throw console.log(x),e.redirect(`${e.context.baseURL}/error?error=failed_linking_account`)}}else try{await e.context.internalAdapter.createOAuthUser(p.data,{...ie(i),id:`${t.id}:${d.id}`,providerId:t.id,accountId:d.id.toString(),userId:l})}catch{let g=new URL(n||o);throw g.searchParams.set("error","unable_to_create_user"),e.setHeader("Location",g.toString()),e.redirect(g.toString())}if(!m&&!l)throw new Yt("INTERNAL_SERVER_ERROR",{message:"Unable to create user"});try{let f=await e.context.internalAdapter.createSession(m||l,e.request);if(!f){let g=new URL(n||o);throw g.searchParams.set("error","unable_to_create_session"),e.redirect(g.toString())}try{await P(e,f.id)}catch(g){e.context.logger.error("Unable to set session cookie",g);let A=new URL(n||o);throw A.searchParams.set("error","unable_to_create_session"),e.redirect(A.toString())}}catch{let f=new URL(n||o||"");throw f.searchParams.set("error","unable_to_create_session"),e.redirect(f.toString())}throw e.redirect(o)});import{APIError as M}from"better-call";var N=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as We}from"zod";var de=()=>h("/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 i=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:N(e.context.sessionConfig.expiresIn,"sec")});if(!i)return j(e),e.json(null,{status:401});let d=(i.expiresAt.valueOf()-Date.now())/1e3;return await P(e,i.id,!1,{maxAge:d}),e.json({session:i,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),er=async e=>await de()({...e,_flag:"json",headers:e.headers}),B=V(async e=>{let t=await er(e);if(!t?.session)throw new M("UNAUTHORIZED");return{session:t}}),Je=()=>h("/user/list-sessions",{method:"GET",use:[B],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)}),Xe=h("/user/revoke-session",{method:"POST",body:We.object({id:We.string()}),use:[B],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new M("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new M("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new M("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Ye=h("/user/revoke-sessions",{method:"POST",use:[B],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new M("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});import"zod";import{APIError as tr}from"better-call";var et=h("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new tr("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),j(e),e.json({success:!0})});import{z as I}from"zod";import{APIError as Y}from"better-call";var tt=h("/forget-password",{method:"POST",body:I.object({email:I.string().email(),redirectTo:I.string()}),use:[T]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new Y("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,s=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n)),a=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${a}`,expiresAt:s});let c=`${e.context.baseURL}/reset-password/${a}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(c,o.user),e.json({status:!0})}),rt=h("/reset-password/:token",{method:"GET",query:I.object({callbackURL:I.string()}),use:[T]},async e=>{let{token:t}=e.params,r=e.query.callbackURL,o=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}?token=${t}`)}),ot=h("/reset-password",{query:I.object({token:I.string()}).optional(),method:"POST",body:I.object({newPassword:I.string()})},async e=>{let t=e.query?.token;if(!t)throw new Y("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new Y("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let s=n.value,a=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(s)).find(l=>l.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:s,providerId:"credential",password:a,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(s,a))throw new Y("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{TimeSpan as rr}from"oslo";import{createJWT as or,validateJWT as nr}from"oslo/jwt";import{z as O}from"zod";import{APIError as H}from"better-call";async function ce(e,t){return await or("HS256",Buffer.from(e),{email:t.toLowerCase()},{expiresIn:new rr(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var nt=h("/send-verification-email",{method:"POST",query:O.object({currentURL:O.string().optional()}).optional(),body:O.object({email:O.string().email(),callbackURL:O.string().optional()}),use:[T]},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 H("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new H("BAD_REQUEST",{message:"User not found"});let o=await ce(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})}),st=h("/verify-email",{method:"GET",query:O.object({token:O.string(),callbackURL:O.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await nr("HS256",Buffer.from(e.context.secret),t)}catch(c){throw e.context.logger.error("Failed to verify email",c),new H("BAD_REQUEST",{message:"Invalid token"})}let n=O.object({email:O.string().email()}).parse(r.payload),s=await e.context.internalAdapter.findUserByEmail(n.email,{includeAccounts:!0});if(!s)throw new H("BAD_REQUEST",{message:"User not found"});if(!s.accounts.find(c=>c.providerId==="credential"))throw new H("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 E}from"zod";import{APIError as S}from"better-call";var it=h("/user/update",{method:"POST",body:E.object({name:E.string().optional(),image:E.string().optional()}),use:[B,T]},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})}),at=h("/user/change-password",{method:"POST",body:E.object({newPassword:E.string(),currentPassword:E.string(),revokeOtherSessions:E.boolean().optional()}),use:[B]},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 a=e.context.password.config.maxPasswordLength;if(t.length>a)throw e.context.logger.error("Password is too long"),new S("BAD_REQUEST",{message:"Password too long"});let i=(await e.context.internalAdapter.findAccounts(n.user.id)).find(p=>p.providerId==="credential"&&p.password);if(!i||!i.password)throw new S("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify(i.password,r))throw new S("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(i.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let p=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!p)throw new S("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await P(e,p.id)}return e.json(n.user)}),dt=h("/user/set-password",{method:"POST",body:E.object({newPassword:E.string()}),use:[B]},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 a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(i=>i.providerId==="credential"&&i.password),c=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:c}),e.json(r.user);throw new S("BAD_REQUEST",{message:"user already has a password"})}),ct=h("/user/delete",{method:"POST",body:E.object({password:E.string()}),use:[B]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.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 lt=h("/csrf",{method:"GET",metadata:_},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t)return{csrfToken:t};let r=Z(32,Q("a-z","0-9","A-Z")),o=await W(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 sr=(e="Unknown")=>`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
package/dist/node.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as http from 'http';
2
- import { a as Auth } from './auth-BGQTSAwN.js';
2
+ import { a as Auth } from './auth-Cx7ibOvY.js';
3
3
  import 'zod';
4
4
  import 'kysely';
5
5
  import './schema-Dkt0LqYs.js';
package/dist/plugins.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- export { A as AnonymousOptions, O as OrganizationOptions, b as Passkey, P as PasskeyOptions, U as UserWithPhoneNumber, f as UserWithRole, i as admin, h as adminMiddleware, e as anonymous, j as genericOAuth, g as getPasskeyActions, m as magicLink, o as organization, p as passkey, c as passkeyClient, d as phoneNumber, t as twoFactor, a as twoFactorClient, u as username } from './index-DgJ3JDtV.js';
1
+ export { A as AnonymousOptions, O as OrganizationOptions, b as Passkey, P as PasskeyOptions, U as UserWithPhoneNumber, f as UserWithRole, i as admin, h as adminMiddleware, e as anonymous, j as genericOAuth, g as getPasskeyActions, m as magicLink, o as organization, p as passkey, c as passkeyClient, d as phoneNumber, t as twoFactor, a as twoFactorClient, u as username } from './index-e73K5key.js';
2
2
  export { i as ac } from './index-DfAHOgpj.js';
3
- import { H as HookEndpointContext, P as PluginSchema } from './auth-BGQTSAwN.js';
4
- export { e as AuthEndpoint, f as AuthMiddleware, b as BetterAuthPlugin, d as createAuthEndpoint, c as createAuthMiddleware, o as optionsMiddleware } from './auth-BGQTSAwN.js';
3
+ import { H as HookEndpointContext, P as PluginSchema } from './auth-Cx7ibOvY.js';
4
+ export { e as AuthEndpoint, f as AuthMiddleware, b as BetterAuthPlugin, d as createAuthEndpoint, c as createAuthMiddleware, o as optionsMiddleware } from './auth-Cx7ibOvY.js';
5
5
  export { H as HIDE_METADATA } from './hide-metadata-DEHJp1rk.js';
6
6
  import { U as User } from './schema-Dkt0LqYs.js';
7
7
  import * as better_call from 'better-call';
package/dist/plugins.js CHANGED
@@ -1,5 +1,5 @@
1
1
  var hr=Object.defineProperty;var wr=(e,t)=>{for(var r in t)hr(e,r,{get:t[r],enumerable:!0})};import{APIError as Xt}from"better-call";import{z as Ee}from"zod";import{createEndpointCreator as yr,createMiddleware as st,createMiddlewareCreator as br}from"better-call";var at=st(async()=>({})),C=br({use:[at,st(async()=>({}))]}),c=yr({use:[at]});import{APIError as ae}from"better-call";import{generateCodeVerifier as Nr}from"oslo/oauth2";import{z as Q}from"zod";import{generateState as Ar}from"oslo/oauth2";import{z as Le}from"zod";import{sha256 as dt}from"oslo/crypto";function Je(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let n=0;for(let i=0;i<r.length;i++)n|=r[i]^o[i];return n===0}async function ct(e){let t=await dt(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function Be(e,t){let r=await dt(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return Je(r,o)}async function xe(e){let t=Ar(),r=JSON.stringify({code:t,callbackURL:e}),o=await ct(r);return{raw:r,hash:o}}function he(e){return Le.object({code:Le.string(),callbackURL:Le.string().optional(),currentURL:Le.string().optional()}).safeParse(JSON.parse(e))}import{TimeSpan as dn}from"oslo";var $=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};async function b(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 Oe(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}import{APIError as ut}from"better-call";import{createConsola as kr}from"consola";var ce=kr({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Or=e=>({log:(...t)=>{!e?.disabled&&ce.log("",...t)},error:(...t)=>{!e?.disabled&&ce.error("",...t)},warn:(...t)=>{!e?.disabled&&ce.warn("",...t)},info:(...t)=>{!e?.disabled&&ce.info("",...t)},debug:(...t)=>{!e?.disabled&&ce.debug("",...t)},box:(...t)=>{!e?.disabled&&ce.box("",...t)},success:(...t)=>{!e?.disabled&&ce.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
2
- `)}}),A=Or();var z=C(async e=>{let t=e.body?.callbackURL||e.query?.callbackURL||e.query?.redirectTo||e.body?.redirectTo,r=e.headers?.get("referer"),o=e.query?.currentURL||r||e.context.baseURL,n=e.context.trustedOrigins;if(t?.includes("http")){let i=new URL(t).origin;if(!n.includes(i))throw A.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new ut("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let i=new URL(o).origin;if(!n.includes(i))throw A.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new ut("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as Ur}from"oslo/jwt";import{sha256 as Rr}from"oslo/crypto";function lt(e){return new URL(e).origin.replace("http://","").replace("https://","")}import{base64url as Ir}from"oslo/encoding";async function pt(e){let t=await Rr(new TextEncoder().encode(e));return Ir.encode(new Uint8Array(t),{includePadding:!1})}function mt(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_at?new Date((Date.now()+e.expires_in)*1e3):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function B({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:a,disablePkce:s,redirectURI:d}){let u=new URL(r);if(u.searchParams.set("response_type","code"),u.searchParams.set("client_id",t.clientId),u.searchParams.set("state",o),u.searchParams.set("scope",i.join(" ")),u.searchParams.set("redirect_uri",t.redirectURI||d),!s&&n){let l=await pt(n);u.searchParams.set("code_challenge_method","S256"),u.searchParams.set("code_challenge",l)}if(a){let l=a.reduce((p,k)=>(p[k]=null,p),{});u.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return u}import{betterFetch as vr}from"@better-fetch/fetch";async function U({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:a,error:s}=await vr(n,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(s)throw s;return mt(a)}function we(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var ft=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=e.scope||o||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>U({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=Ur(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 Tr}from"@better-fetch/fetch";var gt=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>U({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await Tr("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 Er}from"@better-fetch/fetch";var ht=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=e.scope||r||["email","public_profile"];return await B({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>U({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await Er("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,emailVerified:r.email_verified},data:r}}});import{betterFetch as wt}from"@better-fetch/fetch";var yt=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let a=e.scope||o||["user:email"];return B({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>U({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await wt("https://api.github.com/user",{auth:{type:"Bearer",token:r.accessToken}});if(n)return null;let i=!1;if(!o.email){let{data:a,error:s}=await wt("https://api.github.com/user/emails",{auth:{type:"Bearer",token:r.accessToken}});s||(o.email=(a.find(d=>d.primary)??a[0])?.email,i=a.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:i},data:o}}}};import{parseJWT as Sr}from"oslo/jwt";var bt=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw A.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new $("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new $("codeVerifier is required for Google");let i=e.scope||r||["email","profile"];return B({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>U({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=Sr(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 Pr}from"@better-fetch/fetch";import{parseJWT as _r}from"oslo/jwt";var At=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=e.scope||n.scopes||["openid","profile","email","User.Read"];return B({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:a}){return U({code:n,codeVerifier:i,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=_r(n.idToken)?.payload,a=e.profilePhotoSize||48;return await Pr(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(s){if(!(e.disableProfilePhoto||!s.response.ok))try{let u=await s.response.clone().arrayBuffer(),l=Buffer.from(u).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(d){A.error(d)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as Cr}from"@better-fetch/fetch";var kt=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=e.scope||r||["user-read-email"];return B({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>U({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await Cr("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";var se={isAction:!1};function zr(e){return e.toString(2).padStart(8,"0")}function Br(e){return[...e].map(t=>zr(t)).join("")}function Ot(e){return parseInt(Br(e),2)}function Lr(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=Ot(o);for(;n>=e;)crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=Ot(o);return n}function F(e,t){let r="";for(let o=0;o<e;o++)r+=t[Lr(t.length)];return r}function M(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}var P=e=>F(e||21,M("a-z","0-9","A-Z"));import{parseJWT as xr}from"oslo/jwt";var Rt=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return B({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>U({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return A.error("No idToken found in token"),null;let o=xr(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as Dr}from"@better-fetch/fetch";var It=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return B({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>U({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await Dr("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 jr={apple:ft,discord:gt,facebook:ht,github:yt,microsoft:At,google:bt,spotify:kt,twitch:Rt,twitter:It},vt=Object.keys(jr);var Fr=c("/sign-in/social",{method:"POST",requireHeaders:!0,query:Q.object({currentURL:Q.string().optional()}).optional(),body:Q.object({callbackURL:Q.string().optional(),provider:Q.enum(vt)}),use:[z]},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 in your auth config",{provider:e.body.provider}),new ae("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,n=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,i=await xe(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,i.hash,e.context.secret,r.state.options);let a=Nr();await e.setSignedCookie(r.pkCodeVerifier.name,a,e.context.secret,r.pkCodeVerifier.options);let s=await t.createAuthorizationURL({state:i.raw,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:s.toString(),state:i,codeVerifier:a,redirect:!0})}),Mr=c("/sign-in/email",{method:"POST",body:Q.object({email:Q.string().email(),password:Q.string(),callbackURL:Q.string().optional(),dontRememberMe:Q.boolean().default(!1).optional()}),use:[z]},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 ae("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!Q.string().email().safeParse(t).success)throw new ae("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 ae("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(u=>u.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new ae("UNAUTHORIZED",{message:"Invalid email or password"});let a=i?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new ae("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new ae("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 ae("UNAUTHORIZED",{message:"Failed to create session"});return await b(e,d.id,e.body.dontRememberMe),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{APIError as $r}from"better-call";import{z as je}from"zod";import{z as w}from"zod";var ns=w.object({id:w.string(),providerId:w.string(),accountId:w.string(),userId:w.string(),accessToken:w.string().nullable().optional(),refreshToken:w.string().nullable().optional(),idToken:w.string().nullable().optional(),expiresAt:w.date().nullable().optional(),password:w.string().optional().nullable()}),De=w.object({id:w.string(),email:w.string().transform(e=>e.toLowerCase()),emailVerified:w.boolean().default(!1),name:w.string(),image:w.string().optional(),createdAt:w.date().default(new Date),updatedAt:w.date().default(new Date)}),is=w.object({id:w.string(),userId:w.string(),expiresAt:w.date(),ipAddress:w.string().optional(),userAgent:w.string().optional()}),ss=w.object({id:w.string(),value:w.string(),expiresAt:w.date(),identifier:w.string()});function qr(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 Ut(e,t){let r={...e.user?.additionalFields};return qr(t||{},{fields:r})}var Vr=c("/callback/:id",{method:"GET",query:je.object({state:je.string(),code:je.string().optional(),error:je.string().optional()}),metadata:se},async e=>{if(e.query.error||!e.query.code){let h=he(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${h}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(f=>f.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=he(e.query.state);if(!r.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:n}}=r,i=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!i)throw A.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await Be(e.query.state,i))throw A.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let s=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),d;try{d=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(f){throw e.context.logger.error(f),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let u=await t.getUserInfo(d).then(f=>f?.user),l=P(),p=De.safeParse({...u,id:l});if(!u||p.success===!1)throw A.error("Unable to get user info",p.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 k=await e.context.internalAdapter.findUserByEmail(u.email,{includeAccounts:!0}).catch(f=>{throw A.error(`Better auth was unable to query your database.
2
+ `)}}),A=Or();var z=C(async e=>{let t=e.body?.callbackURL||e.query?.callbackURL||e.query?.redirectTo||e.body?.redirectTo,r=e.headers?.get("referer"),o=e.query?.currentURL||r||e.context.baseURL,n=e.context.trustedOrigins;if(t?.includes("http")){let i=new URL(t).origin;if(!n.includes(i))throw A.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new ut("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let i=new URL(o).origin;if(!n.includes(i))throw A.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new ut("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as Ur}from"oslo/jwt";import{sha256 as Rr}from"oslo/crypto";function lt(e){return new URL(e).origin.replace("http://","").replace("https://","")}import{base64url as Ir}from"oslo/encoding";async function pt(e){let t=await Rr(new TextEncoder().encode(e));return Ir.encode(new Uint8Array(t),{includePadding:!1})}function mt(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_at?new Date((Date.now()+e.expires_in)*1e3):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function B({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:a,disablePkce:s,redirectURI:d}){let u=new URL(r);if(u.searchParams.set("response_type","code"),u.searchParams.set("client_id",t.clientId),u.searchParams.set("state",o),u.searchParams.set("scope",i.join(" ")),u.searchParams.set("redirect_uri",t.redirectURI||d),!s&&n){let l=await pt(n);u.searchParams.set("code_challenge_method","S256"),u.searchParams.set("code_challenge",l)}if(a){let l=a.reduce((p,k)=>(p[k]=null,p),{});u.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return u}import{betterFetch as vr}from"@better-fetch/fetch";async function U({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:a,error:s}=await vr(n,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(s)throw s;return mt(a)}function we(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var ft=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=e.scope||o||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>U({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=Ur(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 Tr}from"@better-fetch/fetch";var gt=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>U({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await Tr("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 Er}from"@better-fetch/fetch";var ht=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["email","public_profile"];return await B({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>U({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await Er("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,emailVerified:r.email_verified},data:r}}});import{betterFetch as wt}from"@better-fetch/fetch";var yt=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let a=e.scope||o||["user:email"];return B({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>U({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await wt("https://api.github.com/user",{auth:{type:"Bearer",token:r.accessToken}});if(n)return null;let i=!1;if(!o.email){let{data:a,error:s}=await wt("https://api.github.com/user/emails",{auth:{type:"Bearer",token:r.accessToken}});s||(o.email=(a.find(d=>d.primary)??a[0])?.email,i=a.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:i},data:o}}}};import{parseJWT as Sr}from"oslo/jwt";var bt=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw A.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new $("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new $("codeVerifier is required for Google");let i=e.scope||r||["email","profile"];return B({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>U({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=Sr(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 Pr}from"@better-fetch/fetch";import{parseJWT as _r}from"oslo/jwt";var At=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=e.scope||n.scopes||["openid","profile","email","User.Read"];return B({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:a}){return U({code:n,codeVerifier:i,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=_r(n.idToken)?.payload,a=e.profilePhotoSize||48;return await Pr(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(s){if(!(e.disableProfilePhoto||!s.response.ok))try{let u=await s.response.clone().arrayBuffer(),l=Buffer.from(u).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(d){A.error(d)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as Cr}from"@better-fetch/fetch";var kt=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=e.scope||r||["user-read-email"];return B({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>U({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await Cr("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";var se={isAction:!1};function zr(e){return e.toString(2).padStart(8,"0")}function Br(e){return[...e].map(t=>zr(t)).join("")}function Ot(e){return parseInt(Br(e),2)}function Lr(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=Ot(o);for(;n>=e;)crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=Ot(o);return n}function F(e,t){let r="";for(let o=0;o<e;o++)r+=t[Lr(t.length)];return r}function M(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}var P=e=>F(e||21,M("a-z","0-9","A-Z"));import{parseJWT as xr}from"oslo/jwt";var Rt=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return B({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>U({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return A.error("No idToken found in token"),null;let o=xr(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as Dr}from"@better-fetch/fetch";var It=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return B({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>U({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await Dr("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 jr={apple:ft,discord:gt,facebook:ht,github:yt,microsoft:At,google:bt,spotify:kt,twitch:Rt,twitter:It},vt=Object.keys(jr);var Fr=c("/sign-in/social",{method:"POST",requireHeaders:!0,query:Q.object({currentURL:Q.string().optional()}).optional(),body:Q.object({callbackURL:Q.string().optional(),provider:Q.enum(vt)}),use:[z]},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 in your auth config",{provider:e.body.provider}),new ae("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,n=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,i=await xe(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,i.hash,e.context.secret,r.state.options);let a=Nr();await e.setSignedCookie(r.pkCodeVerifier.name,a,e.context.secret,r.pkCodeVerifier.options);let s=await t.createAuthorizationURL({state:i.raw,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:s.toString(),state:i,codeVerifier:a,redirect:!0})}),Mr=c("/sign-in/email",{method:"POST",body:Q.object({email:Q.string().email(),password:Q.string(),callbackURL:Q.string().optional(),dontRememberMe:Q.boolean().default(!1).optional()}),use:[z]},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 ae("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!Q.string().email().safeParse(t).success)throw new ae("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 ae("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(u=>u.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new ae("UNAUTHORIZED",{message:"Invalid email or password"});let a=i?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new ae("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new ae("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 ae("UNAUTHORIZED",{message:"Failed to create session"});return await b(e,d.id,e.body.dontRememberMe),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{APIError as $r}from"better-call";import{z as je}from"zod";import{z as w}from"zod";var ns=w.object({id:w.string(),providerId:w.string(),accountId:w.string(),userId:w.string(),accessToken:w.string().nullable().optional(),refreshToken:w.string().nullable().optional(),idToken:w.string().nullable().optional(),expiresAt:w.date().nullable().optional(),password:w.string().optional().nullable()}),De=w.object({id:w.string(),email:w.string().transform(e=>e.toLowerCase()),emailVerified:w.boolean().default(!1),name:w.string(),image:w.string().optional(),createdAt:w.date().default(new Date),updatedAt:w.date().default(new Date)}),is=w.object({id:w.string(),userId:w.string(),expiresAt:w.date(),ipAddress:w.string().optional(),userAgent:w.string().optional()}),ss=w.object({id:w.string(),value:w.string(),expiresAt:w.date(),identifier:w.string()});function qr(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 Ut(e,t){let r={...e.user?.additionalFields};return qr(t||{},{fields:r})}var Vr=c("/callback/:id",{method:"GET",query:je.object({state:je.string(),code:je.string().optional(),error:je.string().optional()}),metadata:se},async e=>{if(e.query.error||!e.query.code){let h=he(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${h}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(f=>f.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=he(e.query.state);if(!r.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:n}}=r,i=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!i)throw A.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await Be(e.query.state,i))throw A.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let s=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),d;try{d=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(f){throw e.context.logger.error(f),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let u=await t.getUserInfo(d).then(f=>f?.user),l=P(),p=De.safeParse({...u,id:l});if(!u||p.success===!1)throw A.error("Unable to get user info",p.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 k=await e.context.internalAdapter.findUserByEmail(u.email,{includeAccounts:!0}).catch(f=>{throw A.error(`Better auth was unable to query your database.
3
3
  Error: `,f),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),m=k?.user.id;if(k){let f=k.accounts.find(I=>I.providerId===t.id),h=e.context.options.account?.accountLinking?.trustedProviders,R=h?h.includes(t.id):!0;if(!f&&(!u.emailVerified||!R)){let I;try{I=new URL(n||o),I.searchParams.set("error","account_not_linked")}catch{throw e.redirect(`${e.context.baseURL}/error?error=account_not_linked`)}throw e.redirect(I.toString())}if(!f)try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:u.id.toString(),id:`${t.id}:${u.id}`,userId:k.user.id,...we(d)})}catch(I){throw console.log(I),e.redirect(`${e.context.baseURL}/error?error=failed_linking_account`)}}else try{await e.context.internalAdapter.createOAuthUser(p.data,{...we(d),id:`${t.id}:${u.id}`,providerId:t.id,accountId:u.id.toString(),userId:l})}catch{let h=new URL(n||o);throw h.searchParams.set("error","unable_to_create_user"),e.setHeader("Location",h.toString()),e.redirect(h.toString())}if(!m&&!l)throw new $r("INTERNAL_SERVER_ERROR",{message:"Unable to create user"});try{let f=await e.context.internalAdapter.createSession(m||l,e.request);if(!f){let h=new URL(n||o);throw h.searchParams.set("error","unable_to_create_session"),e.redirect(h.toString())}try{await b(e,f.id)}catch(h){e.context.logger.error("Unable to set session cookie",h);let R=new URL(n||o);throw R.searchParams.set("error","unable_to_create_session"),e.redirect(R.toString())}}catch{let f=new URL(n||o||"");throw f.searchParams.set("error","unable_to_create_session"),e.redirect(f.toString())}throw e.redirect(o)});import{APIError as Re}from"better-call";var q=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as Tt}from"zod";var Et=()=>c("/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 Oe(e),r&&await e.context.internalAdapter.deleteSession(r.session.id),e.json(null,{status:401});if(await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(r);let n=e.context.sessionConfig.expiresIn,i=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+i*1e3<=Date.now()){let d=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:q(e.context.sessionConfig.expiresIn,"sec")});if(!d)return Oe(e),e.json(null,{status:401});let u=(d.expiresAt.valueOf()-Date.now())/1e3;return await b(e,d.id,!1,{maxAge:u}),e.json({session:d,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),H=async e=>await Et()({...e,_flag:"json",headers:e.headers}),y=C(async e=>{let t=await H(e);if(!t?.session)throw new Re("UNAUTHORIZED");return{session:t}});var Qr=c("/user/revoke-session",{method:"POST",body:Tt.object({id:Tt.string()}),use:[y],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new Re("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new Re("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new Re("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Hr=c("/user/revoke-sessions",{method:"POST",use:[y],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new Re("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});import"zod";import{APIError as Wr}from"better-call";var Kr=c("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Wr("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),Oe(e),e.json({success:!0})});import{z as te}from"zod";import{APIError as Ne}from"better-call";var Jr=c("/forget-password",{method:"POST",body:te.object({email:te.string().email(),redirectTo:te.string()}),use:[z]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new Ne("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n)),a=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${a}`,expiresAt:i});let s=`${e.context.baseURL}/reset-password/${a}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(s,o.user),e.json({status:!0})}),Gr=c("/reset-password/:token",{method:"GET",query:te.object({callbackURL:te.string()}),use:[z]},async e=>{let{token:t}=e.params,r=e.query.callbackURL,o=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}?token=${t}`)}),Zr=c("/reset-password",{query:te.object({token:te.string()}).optional(),method:"POST",body:te.object({newPassword:te.string()})},async e=>{let t=e.query?.token;if(!t)throw new Ne("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new Ne("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,a=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(i)).find(l=>l.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:a,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(i,a))throw new Ne("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{TimeSpan as Yr}from"oslo";import{createJWT as Xr,validateJWT as eo}from"oslo/jwt";import{z as J}from"zod";import{APIError as Ie}from"better-call";async function Ge(e,t){return await Xr("HS256",Buffer.from(e),{email:t.toLowerCase()},{expiresIn:new Yr(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var to=c("/send-verification-email",{method:"POST",query:J.object({currentURL:J.string().optional()}).optional(),body:J.object({email:J.string().email(),callbackURL:J.string().optional()}),use:[z]},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 Ie("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new Ie("BAD_REQUEST",{message:"User not found"});let o=await Ge(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})}),ro=c("/verify-email",{method:"GET",query:J.object({token:J.string(),callbackURL:J.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await eo("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new Ie("BAD_REQUEST",{message:"Invalid token"})}let n=J.object({email:J.string().email()}).parse(r.payload),i=await e.context.internalAdapter.findUserByEmail(n.email,{includeAccounts:!0});if(!i)throw new Ie("BAD_REQUEST",{message:"User not found"});if(!i.accounts.find(s=>s.providerId==="credential"))throw new Ie("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 W}from"zod";import{APIError as G}from"better-call";var oo=c("/user/update",{method:"POST",body:W.object({name:W.string().optional(),image:W.string().optional()}),use:[y,z]},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})}),no=c("/user/change-password",{method:"POST",body:W.object({newPassword:W.string(),currentPassword:W.string(),revokeOtherSessions:W.boolean().optional()}),use:[y]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new G("BAD_REQUEST",{message:"Password is too short"});let a=e.context.password.config.maxPasswordLength;if(t.length>a)throw e.context.logger.error("Password is too long"),new G("BAD_REQUEST",{message:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(n.user.id)).find(p=>p.providerId==="credential"&&p.password);if(!d||!d.password)throw new G("BAD_REQUEST",{message:"User does not have a password"});let u=await e.context.password.hash(t);if(!await e.context.password.verify(d.password,r))throw new G("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:u}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let p=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!p)throw new G("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await b(e,p.id)}return e.json(n.user)}),io=c("/user/set-password",{method:"POST",body:W.object({newPassword:W.string()}),use:[y]},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 G("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 G("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(d=>d.providerId==="credential"&&d.password),s=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:s}),e.json(r.user);throw new G("BAD_REQUEST",{message:"user already has a password"})}),so=c("/user/delete",{method:"POST",body:W.object({password:W.string()}),use:[y]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password);if(!n||!n.password)throw new G("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new G("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)});import{xchacha20poly1305 as St}from"@noble/ciphers/chacha";import{bytesToHex as ao,hexToBytes as co,utf8ToBytes as uo}from"@noble/ciphers/utils";import{managedNonce as Pt}from"@noble/ciphers/webcrypto";import{sha256 as _t}from"oslo/crypto";import{decodeHex as na,encodeHex as ia}from"oslo/encoding";import{scryptAsync as da}from"@noble/hashes/scrypt";async function K(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),i=await crypto.subtle.sign(o.name,n,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(i)))}var Fe=async({key:e,data:t})=>{let r=await _t(new TextEncoder().encode(e)),o=uo(t),n=Pt(St)(new Uint8Array(r));return ao(n.encrypt(o))},Me=async({key:e,data:t})=>{let r=await _t(new TextEncoder().encode(e)),o=co(t),n=Pt(St)(new Uint8Array(r));return new TextDecoder().decode(n.decrypt(o))};var lo=c("/csrf",{method:"GET",metadata:se},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t)return{csrfToken:t};let r=F(32,M("a-z","0-9","A-Z")),o=await K(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 po=(e="Unknown")=>`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
package/dist/react.d.ts CHANGED
@@ -3,7 +3,7 @@ import * as _better_fetch_fetch from '@better-fetch/fetch';
3
3
  import { U as UnionToIntersection, P as Prettify, S as StripEmptyObjects } from './helper-DPDj8Nix.js';
4
4
  import { ClientOptions, InferClientAPI, InferActions, InferAdditionalFromClient, BetterAuthClientPlugin, IsSignal } from './types.js';
5
5
  import { useStore } from '@nanostores/react';
6
- import './auth-BGQTSAwN.js';
6
+ import './auth-Cx7ibOvY.js';
7
7
  import 'kysely';
8
8
  import './schema-Dkt0LqYs.js';
9
9
  import 'better-call';
package/dist/social.d.ts CHANGED
@@ -395,13 +395,13 @@ interface FacebookOptions extends ProviderOptions {
395
395
  declare const facebook: (options: FacebookOptions) => {
396
396
  id: "facebook";
397
397
  name: string;
398
- createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }: {
398
+ createAuthorizationURL({ state, scopes, redirectURI }: {
399
399
  state: string;
400
400
  codeVerifier: string;
401
401
  scopes?: string[];
402
402
  redirectURI: string;
403
403
  }): Promise<URL>;
404
- validateAuthorizationCode: ({ code, codeVerifier, redirectURI }: {
404
+ validateAuthorizationCode: ({ code, redirectURI }: {
405
405
  code: string;
406
406
  redirectURI: string;
407
407
  codeVerifier?: string;
@@ -636,13 +636,13 @@ declare const socialProviders: {
636
636
  facebook: (options: FacebookOptions) => {
637
637
  id: "facebook";
638
638
  name: string;
639
- createAuthorizationURL({ state, scopes, codeVerifier, redirectURI }: {
639
+ createAuthorizationURL({ state, scopes, redirectURI }: {
640
640
  state: string;
641
641
  codeVerifier: string;
642
642
  scopes?: string[];
643
643
  redirectURI: string;
644
644
  }): Promise<URL>;
645
- validateAuthorizationCode: ({ code, codeVerifier, redirectURI }: {
645
+ validateAuthorizationCode: ({ code, redirectURI }: {
646
646
  code: string;
647
647
  redirectURI: string;
648
648
  codeVerifier?: string;
package/dist/social.js CHANGED
@@ -1,2 +1,2 @@
1
- import{parseJWT as L}from"oslo/jwt";import{sha256 as z}from"oslo/crypto";var m=class extends Error{constructor(r,e){super(r),this.name="BetterAuthError",this.message=r,this.cause=e,this.stack=""}};import{base64url as I}from"oslo/encoding";async function b(t){let r=await z(new TextEncoder().encode(t));return I.encode(new Uint8Array(r),{includePadding:!1})}function y(t){return{tokenType:t.token_type,accessToken:t.access_token,refreshToken:t.refresh_token,accessTokenExpiresAt:t.expires_at?new Date((Date.now()+t.expires_in)*1e3):void 0,scopes:t?.scope?typeof t.scope=="string"?t.scope.split(" "):t.scope:[],idToken:t.id_token}}async function c({id:t,options:r,authorizationEndpoint:e,state:i,codeVerifier:o,scopes:n,claims:s,disablePkce:l,redirectURI:d}){let p=new URL(e);if(p.searchParams.set("response_type","code"),p.searchParams.set("client_id",r.clientId),p.searchParams.set("state",i),p.searchParams.set("scope",n.join(" ")),p.searchParams.set("redirect_uri",r.redirectURI||d),!l&&o){let g=await b(o);p.searchParams.set("code_challenge_method","S256"),p.searchParams.set("code_challenge",g)}if(s){let g=s.reduce((h,O)=>(h[O]=null,h),{});p.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...g}}))}return p}import{betterFetch as E}from"@better-fetch/fetch";async function a({code:t,codeVerifier:r,redirectURI:e,options:i,tokenEndpoint:o}){let n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t),r&&n.set("code_verifier",r),n.set("redirect_uri",e),n.set("client_id",i.clientId),n.set("client_secret",i.clientSecret);let{data:s,error:l}=await E(o,{method:"POST",body:n,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(l)throw l;return y(s)}import{generateState as ue}from"oslo/oauth2";import{z as fe}from"zod";import{sha256 as se}from"oslo/crypto";var _=t=>{let r="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:e,scopes:i,redirectURI:o}){let n=t.scope||i||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${t.clientId}&response_type=code&redirect_uri=${o||t.redirectURI}&scope=${n.join(" ")}&state=${e}`)},validateAuthorizationCode:async({code:e,codeVerifier:i,redirectURI:o})=>a({code:e,codeVerifier:i,redirectURI:t.redirectURI||o,options:t,tokenEndpoint:r}),async getUserInfo(e){if(!e.idToken)return null;let i=L(e.idToken)?.payload;return i?{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified==="true"},data:i}:null}}};import{betterFetch as B}from"@better-fetch/fetch";var v=t=>({id:"discord",name:"Discord",createAuthorizationURL({state:r,scopes:e,redirectURI:i}){let o=t.scope||e||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${o.join("+")}&response_type=code&client_id=${t.clientId}&redirect_uri=${encodeURIComponent(t.redirectURI||i)}&state=${r}`)},validateAuthorizationCode:async({code:r,redirectURI:e})=>a({code:r,redirectURI:t.redirectURI||e,options:t,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(r){let{data:e,error:i}=await B("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${r.accessToken}`}});if(i)return null;if(e.avatar===null){let o=e.discriminator==="0"?Number(BigInt(e.id)>>BigInt(22))%6:parseInt(e.discriminator)%5;e.image_url=`https://cdn.discordapp.com/embed/avatars/${o}.png`}else{let o=e.avatar.startsWith("a_")?"gif":"png";e.image_url=`https://cdn.discordapp.com/avatars/${e.id}/${e.avatar}.${o}`}return{user:{id:e.id,name:e.display_name||e.username||"",email:e.email,emailVerified:e.verified,image:e.image_url},data:e}}});import{betterFetch as S}from"@better-fetch/fetch";var A=t=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:r,scopes:e,codeVerifier:i,redirectURI:o}){let n=t.scope||e||["email","public_profile"];return await c({id:"facebook",options:t,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:r,redirectURI:o})},validateAuthorizationCode:async({code:r,codeVerifier:e,redirectURI:i})=>a({code:r,codeVerifier:e,redirectURI:t.redirectURI||i,options:t,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(r){let{data:e,error:i}=await S("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:r.accessToken}});return i?null:{user:{id:e.id,name:e.name,email:e.email,emailVerified:e.email_verified},data:e}}});import{betterFetch as P}from"@better-fetch/fetch";var x=t=>{let r="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:e,scopes:i,codeVerifier:o,redirectURI:n}){let s=t.scope||i||["user:email"];return c({id:"github",options:t,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:e,redirectURI:n,codeVerifier:o})},validateAuthorizationCode:async({code:e,redirectURI:i})=>a({code:e,redirectURI:t.redirectURI||i,options:t,tokenEndpoint:r}),async getUserInfo(e){let{data:i,error:o}=await P("https://api.github.com/user",{auth:{type:"Bearer",token:e.accessToken}});if(o)return null;let n=!1;if(!i.email){let{data:s,error:l}=await P("https://api.github.com/user/emails",{auth:{type:"Bearer",token:e.accessToken}});l||(i.email=(s.find(d=>d.primary)??s[0])?.email,n=s.find(d=>d.email===i.email)?.verified??!1)}return{user:{id:i.id.toString(),name:i.name||i.login,email:i.email,image:i.avatar_url,emailVerified:n},data:i}}}};import{parseJWT as V}from"oslo/jwt";import{createConsola as C}from"consola";var u=C({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),$=t=>({log:(...r)=>{!t?.disabled&&u.log("",...r)},error:(...r)=>{!t?.disabled&&u.error("",...r)},warn:(...r)=>{!t?.disabled&&u.warn("",...r)},info:(...r)=>{!t?.disabled&&u.info("",...r)},debug:(...r)=>{!t?.disabled&&u.debug("",...r)},box:(...r)=>{!t?.disabled&&u.box("",...r)},success:(...r)=>{!t?.disabled&&u.success("",...r)},break:(...r)=>{!t?.disabled&&console.log(`
1
+ import{parseJWT as L}from"oslo/jwt";import{sha256 as z}from"oslo/crypto";var m=class extends Error{constructor(r,e){super(r),this.name="BetterAuthError",this.message=r,this.cause=e,this.stack=""}};import{base64url as I}from"oslo/encoding";async function b(t){let r=await z(new TextEncoder().encode(t));return I.encode(new Uint8Array(r),{includePadding:!1})}function y(t){return{tokenType:t.token_type,accessToken:t.access_token,refreshToken:t.refresh_token,accessTokenExpiresAt:t.expires_at?new Date((Date.now()+t.expires_in)*1e3):void 0,scopes:t?.scope?typeof t.scope=="string"?t.scope.split(" "):t.scope:[],idToken:t.id_token}}async function c({id:t,options:r,authorizationEndpoint:e,state:i,codeVerifier:o,scopes:n,claims:s,disablePkce:l,redirectURI:d}){let p=new URL(e);if(p.searchParams.set("response_type","code"),p.searchParams.set("client_id",r.clientId),p.searchParams.set("state",i),p.searchParams.set("scope",n.join(" ")),p.searchParams.set("redirect_uri",r.redirectURI||d),!l&&o){let g=await b(o);p.searchParams.set("code_challenge_method","S256"),p.searchParams.set("code_challenge",g)}if(s){let g=s.reduce((h,O)=>(h[O]=null,h),{});p.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...g}}))}return p}import{betterFetch as E}from"@better-fetch/fetch";async function a({code:t,codeVerifier:r,redirectURI:e,options:i,tokenEndpoint:o}){let n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t),r&&n.set("code_verifier",r),n.set("redirect_uri",e),n.set("client_id",i.clientId),n.set("client_secret",i.clientSecret);let{data:s,error:l}=await E(o,{method:"POST",body:n,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(l)throw l;return y(s)}import{generateState as ue}from"oslo/oauth2";import{z as fe}from"zod";import{sha256 as se}from"oslo/crypto";var _=t=>{let r="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:e,scopes:i,redirectURI:o}){let n=t.scope||i||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${t.clientId}&response_type=code&redirect_uri=${o||t.redirectURI}&scope=${n.join(" ")}&state=${e}`)},validateAuthorizationCode:async({code:e,codeVerifier:i,redirectURI:o})=>a({code:e,codeVerifier:i,redirectURI:t.redirectURI||o,options:t,tokenEndpoint:r}),async getUserInfo(e){if(!e.idToken)return null;let i=L(e.idToken)?.payload;return i?{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified==="true"},data:i}:null}}};import{betterFetch as B}from"@better-fetch/fetch";var v=t=>({id:"discord",name:"Discord",createAuthorizationURL({state:r,scopes:e,redirectURI:i}){let o=t.scope||e||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${o.join("+")}&response_type=code&client_id=${t.clientId}&redirect_uri=${encodeURIComponent(t.redirectURI||i)}&state=${r}`)},validateAuthorizationCode:async({code:r,redirectURI:e})=>a({code:r,redirectURI:t.redirectURI||e,options:t,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(r){let{data:e,error:i}=await B("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${r.accessToken}`}});if(i)return null;if(e.avatar===null){let o=e.discriminator==="0"?Number(BigInt(e.id)>>BigInt(22))%6:parseInt(e.discriminator)%5;e.image_url=`https://cdn.discordapp.com/embed/avatars/${o}.png`}else{let o=e.avatar.startsWith("a_")?"gif":"png";e.image_url=`https://cdn.discordapp.com/avatars/${e.id}/${e.avatar}.${o}`}return{user:{id:e.id,name:e.display_name||e.username||"",email:e.email,emailVerified:e.verified,image:e.image_url},data:e}}});import{betterFetch as S}from"@better-fetch/fetch";var A=t=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:r,scopes:e,redirectURI:i}){let o=t.scope||e||["email","public_profile"];return await c({id:"facebook",options:t,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:o,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:e})=>a({code:r,redirectURI:t.redirectURI||e,options:t,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(r){let{data:e,error:i}=await S("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:r.accessToken}});return i?null:{user:{id:e.id,name:e.name,email:e.email,emailVerified:e.email_verified},data:e}}});import{betterFetch as P}from"@better-fetch/fetch";var x=t=>{let r="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:e,scopes:i,codeVerifier:o,redirectURI:n}){let s=t.scope||i||["user:email"];return c({id:"github",options:t,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:e,redirectURI:n,codeVerifier:o})},validateAuthorizationCode:async({code:e,redirectURI:i})=>a({code:e,redirectURI:t.redirectURI||i,options:t,tokenEndpoint:r}),async getUserInfo(e){let{data:i,error:o}=await P("https://api.github.com/user",{auth:{type:"Bearer",token:e.accessToken}});if(o)return null;let n=!1;if(!i.email){let{data:s,error:l}=await P("https://api.github.com/user/emails",{auth:{type:"Bearer",token:e.accessToken}});l||(i.email=(s.find(d=>d.primary)??s[0])?.email,n=s.find(d=>d.email===i.email)?.verified??!1)}return{user:{id:i.id.toString(),name:i.name||i.login,email:i.email,image:i.avatar_url,emailVerified:n},data:i}}}};import{parseJWT as V}from"oslo/jwt";import{createConsola as C}from"consola";var u=C({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),$=t=>({log:(...r)=>{!t?.disabled&&u.log("",...r)},error:(...r)=>{!t?.disabled&&u.error("",...r)},warn:(...r)=>{!t?.disabled&&u.warn("",...r)},info:(...r)=>{!t?.disabled&&u.info("",...r)},debug:(...r)=>{!t?.disabled&&u.debug("",...r)},box:(...r)=>{!t?.disabled&&u.box("",...r)},success:(...r)=>{!t?.disabled&&u.success("",...r)},break:(...r)=>{!t?.disabled&&console.log(`
2
2
  `)}}),f=$();var U=t=>({id:"google",name:"Google",createAuthorizationURL({state:r,scopes:e,codeVerifier:i,redirectURI:o}){if(!t.clientId||!t.clientSecret)throw f.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new m("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new m("codeVerifier is required for Google");let n=t.scope||e||["email","profile"];return c({id:"google",options:t,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:r,codeVerifier:i,redirectURI:o})},validateAuthorizationCode:async({code:r,codeVerifier:e,redirectURI:i})=>a({code:r,codeVerifier:e,redirectURI:t.redirectURI||i,options:t,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(r){if(!r.idToken)return null;let e=V(r.idToken)?.payload;return{user:{id:e.sub,name:e.name,email:e.email,image:e.picture,emailVerified:e.email_verified},data:e}}});import{betterFetch as D}from"@better-fetch/fetch";import{parseJWT as F}from"oslo/jwt";var w=t=>{let r=t.tenantId||"common",e=`https://login.microsoftonline.com/${r}/oauth2/v2.0/authorize`,i=`https://login.microsoftonline.com/${r}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(o){let n=t.scope||o.scopes||["openid","profile","email","User.Read"];return c({id:"microsoft",options:t,authorizationEndpoint:e,state:o.state,codeVerifier:o.codeVerifier,scopes:n,redirectURI:o.redirectURI})},validateAuthorizationCode({code:o,codeVerifier:n,redirectURI:s}){return a({code:o,codeVerifier:n,redirectURI:t.redirectURI||s,options:t,tokenEndpoint:i})},async getUserInfo(o){if(!o.idToken)return null;let n=F(o.idToken)?.payload,s=t.profilePhotoSize||48;return await D(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${o.accessToken}`},async onResponse(l){if(!(t.disableProfilePhoto||!l.response.ok))try{let p=await l.response.clone().arrayBuffer(),g=Buffer.from(p).toString("base64");n.picture=`data:image/jpeg;base64, ${g}`}catch(d){f.error(d)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};import{betterFetch as G}from"@better-fetch/fetch";var R=t=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:r,scopes:e,codeVerifier:i,redirectURI:o}){let n=t.scope||e||["user-read-email"];return c({id:"spotify",options:t,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:r,codeVerifier:i,redirectURI:o})},validateAuthorizationCode:async({code:r,codeVerifier:e,redirectURI:i})=>a({code:r,codeVerifier:e,redirectURI:t.redirectURI||i,options:t,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(r){let{data:e,error:i}=await G("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});return i?null:{user:{id:e.id,name:e.display_name,email:e.email,image:e.images[0]?.url,emailVerified:!1},data:e}}});import"@better-fetch/fetch";import{parseJWT as j}from"oslo/jwt";var T=t=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:r,scopes:e,redirectURI:i}){let o=t.scope||e||["user:read:email","openid"];return c({id:"twitch",redirectURI:i,options:t,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:r,claims:t.claims||["email","email_verified","preferred_username"]})},validateAuthorizationCode:async({code:r,redirectURI:e})=>a({code:r,redirectURI:t.redirectURI||e,options:t,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(r){let e=r.idToken;if(!e)return f.error("No idToken found in token"),null;let i=j(e)?.payload;return{user:{id:i.sub,name:i.preferred_username,email:i.email,image:i.picture,emailVerified:!1},data:i}}});import{betterFetch as N}from"@better-fetch/fetch";var k=t=>({id:"twitter",name:"Twitter",createAuthorizationURL(r){let e=t.scope||r.scopes||["account_info.read"];return c({id:"twitter",options:t,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:e,state:r.state,codeVerifier:r.codeVerifier,redirectURI:r.redirectURI})},validateAuthorizationCode:async({code:r,codeVerifier:e,redirectURI:i})=>a({code:r,codeVerifier:e,redirectURI:t.redirectURI||i,options:t,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(r){let{data:e,error:i}=await N("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});return i||!e.data.email?null:{user:{id:e.data.id,name:e.data.name,email:e.data.email,image:e.data.profile_image_url,emailVerified:e.data.verified||!1},data:e}}});var H={apple:_,discord:v,facebook:A,github:x,microsoft:w,google:U,spotify:R,twitch:T,twitter:k},zt=Object.keys(H);export{_ as apple,v as discord,A as facebook,x as github,U as google,w as microsoft,zt as socialProviderList,H as socialProviders,R as spotify,T as twitch,k as twitter};
@@ -1,4 +1,4 @@
1
- import { a as Auth } from './auth-BGQTSAwN.js';
1
+ import { a as Auth } from './auth-Cx7ibOvY.js';
2
2
  import 'zod';
3
3
  import 'kysely';
4
4
  import './schema-Dkt0LqYs.js';
package/dist/solid.d.ts CHANGED
@@ -3,7 +3,7 @@ import * as _better_fetch_fetch from '@better-fetch/fetch';
3
3
  import { U as UnionToIntersection, P as Prettify, S as StripEmptyObjects } from './helper-DPDj8Nix.js';
4
4
  import { ClientOptions, InferClientAPI, InferActions, InferAdditionalFromClient, BetterAuthClientPlugin, IsSignal } from './types.js';
5
5
  import { Accessor } from 'solid-js';
6
- import './auth-BGQTSAwN.js';
6
+ import './auth-Cx7ibOvY.js';
7
7
  import 'kysely';
8
8
  import './schema-Dkt0LqYs.js';
9
9
  import 'better-call';
@@ -1,4 +1,4 @@
1
- import { a as Auth, B as BetterAuthOptions } from './auth-BGQTSAwN.js';
1
+ import { a as Auth, B as BetterAuthOptions } from './auth-Cx7ibOvY.js';
2
2
  import 'zod';
3
3
  import 'kysely';
4
4
  import './schema-Dkt0LqYs.js';
package/dist/svelte.d.ts CHANGED
@@ -3,7 +3,7 @@ import * as nanostores from 'nanostores';
3
3
  import * as _better_fetch_fetch from '@better-fetch/fetch';
4
4
  import { U as UnionToIntersection, P as Prettify, S as StripEmptyObjects } from './helper-DPDj8Nix.js';
5
5
  import { ClientOptions, InferClientAPI, InferActions, InferAdditionalFromClient, BetterAuthClientPlugin, IsSignal } from './types.js';
6
- import './auth-BGQTSAwN.js';
6
+ import './auth-Cx7ibOvY.js';
7
7
  import 'kysely';
8
8
  import './schema-Dkt0LqYs.js';
9
9
  import 'better-call';
package/dist/types.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { b as BetterAuthPlugin, a as Auth, O as InferFieldsInputClient, M as InferFieldsOutput } from './auth-BGQTSAwN.js';
2
- export { A as Adapter, j as AdditionalSessionFieldsInput, k as AdditionalSessionFieldsOutput, h as AdditionalUserFieldsInput, i as AdditionalUserFieldsOutput, p as AuthContext, B as BetterAuthOptions, 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, n as init } from './auth-BGQTSAwN.js';
1
+ import { b as BetterAuthPlugin, a as Auth, O as InferFieldsInputClient, M as InferFieldsOutput } from './auth-Cx7ibOvY.js';
2
+ export { A as Adapter, j as AdditionalSessionFieldsInput, k as AdditionalSessionFieldsOutput, h as AdditionalUserFieldsInput, i as AdditionalUserFieldsOutput, p as AuthContext, B as BetterAuthOptions, 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, n as init } from './auth-Cx7ibOvY.js';
3
3
  import { U as UnionToIntersection, H as HasRequiredKeys, P as Prettify, S as StripEmptyObjects, L as LiteralString } from './helper-DPDj8Nix.js';
4
4
  export { D as DeepPartial, a as LiteralUnion, R as RequiredKeysOf, W as WithoutEmpty } from './helper-DPDj8Nix.js';
5
5
  import { BetterFetchOption, BetterFetchResponse, BetterFetch, BetterFetchPlugin } from '@better-fetch/fetch';
package/dist/vue.d.ts CHANGED
@@ -3,7 +3,7 @@ import * as _better_fetch_fetch from '@better-fetch/fetch';
3
3
  import { U as UnionToIntersection, P as Prettify, S as StripEmptyObjects } from './helper-DPDj8Nix.js';
4
4
  import { ClientOptions, InferClientAPI, InferActions, InferAdditionalFromClient, BetterAuthClientPlugin, IsSignal } from './types.js';
5
5
  import { Ref, DeepReadonly } from 'vue';
6
- import './auth-BGQTSAwN.js';
6
+ import './auth-Cx7ibOvY.js';
7
7
  import 'kysely';
8
8
  import './schema-Dkt0LqYs.js';
9
9
  import 'better-call';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "better-auth",
3
- "version": "0.4.11",
3
+ "version": "0.4.12-beta.1",
4
4
  "description": "The most comprehensive authentication library for TypeScript.",
5
5
  "type": "module",
6
6
  "repository": {