better-auth 0.5.2-beta.6 → 0.5.2-beta.7

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