better-auth 0.8.6-beta.2 → 0.8.6-beta.3

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 (57) 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/memory.d.cts +1 -1
  6. package/dist/adapters/memory.d.ts +1 -1
  7. package/dist/adapters/mongodb.d.cts +1 -1
  8. package/dist/adapters/mongodb.d.ts +1 -1
  9. package/dist/adapters/prisma.d.cts +1 -1
  10. package/dist/adapters/prisma.d.ts +1 -1
  11. package/dist/api.cjs +1 -1
  12. package/dist/api.d.cts +1 -1
  13. package/dist/api.d.ts +1 -1
  14. package/dist/api.js +1 -1
  15. package/dist/{auth-BuIGx3uf.d.cts → auth-Dypsi529.d.cts} +18 -0
  16. package/dist/{auth-DuGk-eor.d.ts → auth-HkH2WNGO.d.ts} +18 -0
  17. package/dist/client/plugins.d.cts +3 -3
  18. package/dist/client/plugins.d.ts +3 -3
  19. package/dist/client.d.cts +1 -1
  20. package/dist/client.d.ts +1 -1
  21. package/dist/cookies.d.cts +1 -1
  22. package/dist/cookies.d.ts +1 -1
  23. package/dist/db.d.cts +2 -2
  24. package/dist/db.d.ts +2 -2
  25. package/dist/{index-CNdeepb4.d.cts → index-CgOpTl0Z.d.cts} +1 -1
  26. package/dist/{index-CQbHCAKV.d.ts → index-HDtKSOFR.d.ts} +1 -1
  27. package/dist/index.cjs +1 -1
  28. package/dist/index.d.cts +2 -2
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.js +1 -1
  31. package/dist/next-js.d.cts +1 -1
  32. package/dist/next-js.d.ts +1 -1
  33. package/dist/node.d.cts +1 -1
  34. package/dist/node.d.ts +1 -1
  35. package/dist/oauth2.d.cts +2 -2
  36. package/dist/oauth2.d.ts +2 -2
  37. package/dist/plugins.cjs +1 -1
  38. package/dist/plugins.d.cts +3 -3
  39. package/dist/plugins.d.ts +3 -3
  40. package/dist/plugins.js +1 -1
  41. package/dist/react.d.cts +1 -1
  42. package/dist/react.d.ts +1 -1
  43. package/dist/solid-start.d.cts +1 -1
  44. package/dist/solid-start.d.ts +1 -1
  45. package/dist/solid.d.cts +1 -1
  46. package/dist/solid.d.ts +1 -1
  47. package/dist/{state-IlvxGtaJ.d.cts → state-DF9HQUYb.d.cts} +1 -1
  48. package/dist/{state-COjWhnF6.d.ts → state-NIJS8iY8.d.ts} +1 -1
  49. package/dist/svelte-kit.d.cts +1 -1
  50. package/dist/svelte-kit.d.ts +1 -1
  51. package/dist/svelte.d.cts +1 -1
  52. package/dist/svelte.d.ts +1 -1
  53. package/dist/types.d.cts +2 -2
  54. package/dist/types.d.ts +2 -2
  55. package/dist/vue.d.cts +1 -1
  56. package/dist/vue.d.ts +1 -1
  57. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- import { B as BetterAuthOptions, W as Where } from '../auth-BuIGx3uf.cjs';
1
+ import { B as BetterAuthOptions, W as Where } from '../auth-Dypsi529.cjs';
2
2
  import 'kysely';
3
3
  import 'zod';
4
4
  import 'better-call';
@@ -1,4 +1,4 @@
1
- import { B as BetterAuthOptions, W as Where } from '../auth-DuGk-eor.js';
1
+ import { B as BetterAuthOptions, W as Where } from '../auth-HkH2WNGO.js';
2
2
  import 'kysely';
3
3
  import 'zod';
4
4
  import 'better-call';
@@ -1,5 +1,5 @@
1
1
  import { Kysely } from 'kysely';
2
- import { B as BetterAuthOptions, K as KyselyDatabaseType, W as Where } from '../auth-BuIGx3uf.cjs';
2
+ import { B as BetterAuthOptions, K as KyselyDatabaseType, W as Where } from '../auth-Dypsi529.cjs';
3
3
  import 'zod';
4
4
  import 'better-call';
5
5
  import '../helper-DrEEwdyQ.cjs';
@@ -1,5 +1,5 @@
1
1
  import { Kysely } from 'kysely';
2
- import { B as BetterAuthOptions, K as KyselyDatabaseType, W as Where } from '../auth-DuGk-eor.js';
2
+ import { B as BetterAuthOptions, K as KyselyDatabaseType, W as Where } from '../auth-HkH2WNGO.js';
3
3
  import 'zod';
4
4
  import 'better-call';
5
5
  import '../helper-DrEEwdyQ.js';
@@ -1,4 +1,4 @@
1
- import { B as BetterAuthOptions, W as Where } from '../auth-BuIGx3uf.cjs';
1
+ import { B as BetterAuthOptions, W as Where } from '../auth-Dypsi529.cjs';
2
2
  import 'kysely';
3
3
  import 'zod';
4
4
  import 'better-call';
@@ -1,4 +1,4 @@
1
- import { B as BetterAuthOptions, W as Where } from '../auth-DuGk-eor.js';
1
+ import { B as BetterAuthOptions, W as Where } from '../auth-HkH2WNGO.js';
2
2
  import 'kysely';
3
3
  import 'zod';
4
4
  import 'better-call';
@@ -1,5 +1,5 @@
1
1
  import { Db } from 'mongodb';
2
- import { B as BetterAuthOptions, W as Where } from '../auth-BuIGx3uf.cjs';
2
+ import { B as BetterAuthOptions, W as Where } from '../auth-Dypsi529.cjs';
3
3
  import 'kysely';
4
4
  import 'zod';
5
5
  import 'better-call';
@@ -1,5 +1,5 @@
1
1
  import { Db } from 'mongodb';
2
- import { B as BetterAuthOptions, W as Where } from '../auth-DuGk-eor.js';
2
+ import { B as BetterAuthOptions, W as Where } from '../auth-HkH2WNGO.js';
3
3
  import 'kysely';
4
4
  import 'zod';
5
5
  import 'better-call';
@@ -1,4 +1,4 @@
1
- import { B as BetterAuthOptions, W as Where } from '../auth-BuIGx3uf.cjs';
1
+ import { B as BetterAuthOptions, W as Where } from '../auth-Dypsi529.cjs';
2
2
  import 'kysely';
3
3
  import 'zod';
4
4
  import 'better-call';
@@ -1,4 +1,4 @@
1
- import { B as BetterAuthOptions, W as Where } from '../auth-DuGk-eor.js';
1
+ import { B as BetterAuthOptions, W as Where } from '../auth-HkH2WNGO.js';
2
2
  import 'kysely';
3
3
  import 'zod';
4
4
  import 'better-call';
package/dist/api.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";var pe=Object.defineProperty;var jt=Object.getOwnPropertyDescriptor;var qt=Object.getOwnPropertyNames;var Nt=Object.prototype.hasOwnProperty;var Ft=(e,t)=>{for(var r in t)pe(e,r,{get:t[r],enumerable:!0})},Ht=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of qt(t))!Nt.call(e,n)&&n!==r&&pe(e,n,{get:()=>t[n],enumerable:!(o=jt(t,n))||o.enumerable});return e};var Mt=e=>Ht(pe({},"__esModule",{value:!0}),e);var lr={};Ft(lr,{APIError:()=>$t.APIError,callbackOAuth:()=>xe,changeEmail:()=>De,changePassword:()=>Le,createAuthEndpoint:()=>p,createAuthMiddleware:()=>J,createEmailVerificationToken:()=>C,deleteUser:()=>Be,error:()=>Ve,forgetPassword:()=>Pe,forgetPasswordCallback:()=>Se,getEndpoints:()=>zt,getSession:()=>ae,getSessionFromCtx:()=>K,linkSocialAccount:()=>Ne,listSessions:()=>ye,listUserAccounts:()=>qe,ok:()=>ze,optionsMiddleware:()=>me,originCheckMiddleware:()=>he,resetPassword:()=>Oe,revokeOtherSessions:()=>Re,revokeSession:()=>Ae,revokeSessions:()=>ke,router:()=>ur,sendVerificationEmail:()=>Ue,sessionMiddleware:()=>P,setPassword:()=>Ce,signInEmail:()=>_e,signInSocial:()=>Ee,signOut:()=>Te,signUpEmail:()=>$e,updateUser:()=>Ie,verifyEmail:()=>ve});module.exports=Mt(lr);var j=require("better-call");var Ke=require("better-call");var q=require("better-call"),me=(0,q.createMiddleware)(async()=>({})),J=(0,q.createMiddlewareCreator)({use:[me,(0,q.createMiddleware)(async()=>({}))]}),p=(0,q.createEndpointCreator)({use:[me]});var M={isAction:!1};var Fe=require("nanoid"),He=e=>(0,Fe.nanoid)(e);var ge=require("better-call"),re=require("oslo/oauth2"),D=require("zod");var te=Object.create(null),W=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?te:globalThis),Me=new Proxy(te,{get(e,t){return W()[t]??te[t]},has(e,t){let r=W();return t in r||t in te},set(e,t,r){let o=W(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=W(!0);return delete r[t],!0},ownKeys(){let e=W(!0);return Object.keys(e)}});function Gt(e){return e?e!=="false":!1}var fe=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Ge=fe==="dev"||fe==="development",Qe=fe==="test"||Gt(Me.TEST);var N=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function Ze(e){try{return new URL(e).origin}catch{return null}}async function oe(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Ze(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ge.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,re.generateCodeVerifier)(),n=(0,re.generateState)(),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:s});if(!a)throw m.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ge.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function Je(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw m.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=D.z.object({callbackURL:D.z.string(),codeVerifier:D.z.string(),errorURL:D.z.string().optional(),expiresAt:D.z.number(),link:D.z.object({email:D.z.string(),userId:D.z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),m.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var We=require("consola"),F=(0,We.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Qt=e=>({log:(...t)=>{!e?.disabled&&F.log("",...t)},error:(...t)=>{!e?.disabled&&F.error("",...t)},warn:(...t)=>{!e?.disabled&&F.warn("",...t)},info:(...t)=>{!e?.disabled&&F.info("",...t)},debug:(...t)=>{!e?.disabled&&F.debug("",...t)},box:(...t)=>{!e?.disabled&&F.box("",...t)},success:(...t)=>{!e?.disabled&&F.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
2
2
  `)}}),m=Qt();var he=J(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=t?.callbackURL||r?.callbackURL,s=t?.redirectTo,a=r?.currentURL,d=o.trustedOrigins,c=e.headers?.has("cookie"),u=(h,l)=>l.includes("*")?new RegExp("^"+l.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(h):h.startsWith(l),f=(h,l)=>{if(!h)return;if(!d.some(R=>u(h,R)||h?.startsWith("/")&&l!=="origin"&&!h.includes(":")))throw m.error(`Invalid ${l}: ${h}`),m.info(`If it's a valid URL, please add ${h} to trustedOrigins in your auth config
3
3
  `,`Current list of trustedOrigins: ${d}`),new Ke.APIError("FORBIDDEN",{message:`Invalid ${l}`})};c&&!e.context.options.advanced?.disableCSRFCheck&&f(n,"origin"),i&&f(i,"callbackURL"),s&&f(s,"redirectURL"),a&&f(a,"currentURL")});var v=require("better-call"),A=require("zod");var Wt=require("oslo"),Ye=require("oslo/encoding");var ne=require("oslo/crypto");async function Zt({value:e,secret:t}){return new ne.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function Jt({value:e,signature:t,secret:r}){return new ne.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var ie={sign:Zt,verify:Jt};var L=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function T(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.session.id,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Ye.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:L(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await ie.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.id,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function V(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}var nt=require("@better-fetch/fetch"),it=require("better-call"),G=require("jose"),st=require("oslo/jwt");var Xe=require("oslo/crypto"),et=require("oslo/encoding");async function tt(e){let t=await(0,Xe.sha256)(new TextEncoder().encode(e));return et.base64url.encode(new Uint8Array(t),{includePadding:!1})}function rt(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?L(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function y({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,redirectURI:a}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",i.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||a),n){let c=await tt(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",c)}if(s){let c=s.reduce((u,f)=>(u[f]=null,u),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...c}}))}return d}var ot=require("@better-fetch/fetch");async function w({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n,authentication:i}){let s=new URLSearchParams,a={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),i==="basic"){let f=btoa(`${o.clientId}:${o.clientSecret}`);a.authorization=`Basic ${f}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:d,error:c}=await(0,ot.betterFetch)(n,{method:"POST",body:s,headers:a});if(c)throw c;return rt(d)}var at=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let n=(0,G.decodeProtectedHeader)(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let a=await Kt(i),{payload:d}=await(0,G.jwtVerify)(r,a,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(c=>{d[c]!==void 0&&(d[c]=!!d[c])}),o&&d.nonce!==o?!1:!!d},async getUserInfo(r){if(!r.idToken)return null;let o=(0,st.parseJWT)(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email;return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email},data:o}}}},Kt=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,nt.betterFetch)(`${t}${r}`);if(!o?.keys)throw new it.APIError("BAD_REQUEST",{message:"Keys not found"});let n=o.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await(0,G.importJWK)(n,n.alg)};var dt=require("@better-fetch/fetch");var ct=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({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,dt.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 ut=require("@better-fetch/fetch");var lt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await y({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})=>w({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,ut.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,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});var we=require("@better-fetch/fetch");var pt=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),y({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>w({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,we.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:a}=await(0,we.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(d=>d.primary)??s[0])?.email,i=s.find(d=>d.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};var mt=require("oslo/jwt");var ft=require("@better-fetch/fetch"),gt=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw m.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new N("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new N("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await y({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:n}=await(0,ft.betterFetch)(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(!t.idToken)return null;let r=(0,mt.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 ht=require("@better-fetch/fetch"),wt=require("oslo/jwt");var bt=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),y({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 w({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=(0,wt.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,ht.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let c=await a.response.clone().arrayBuffer(),u=Buffer.from(c).toString("base64");i.picture=`data:image/jpeg;base64, ${u}`}catch(d){m.error(d)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};var yt=require("@better-fetch/fetch");var At=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),y({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})=>w({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,yt.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 _o=require("@better-fetch/fetch");var kt=require("oslo/jwt");var Rt=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),y({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})=>w({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 m.error("No idToken found in token"),null;let o=(0,kt.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var Ut=require("@better-fetch/fetch");var vt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),y({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,Ut.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var Et=require("@better-fetch/fetch");var _t=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await y({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,Et.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};var xt=require("@better-fetch/fetch");var Tt=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await y({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await w({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await(0,xt.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};var Pt=require("@better-fetch/fetch");var be=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Yt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:be(`${t}/oauth/authorize`),tokenEndpoint:be(`${t}/oauth/token`),userinfoEndpoint:be(`${t}/api/v4/user`)}},St=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Yt(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:d,redirectURI:c})=>{let u=a||["read_user"];return e.scope&&u.push(...e.scope),await y({id:n,options:e,authorizationEndpoint:t,scopes:u,state:s,redirectURI:c,codeVerifier:d})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:d})=>w({code:s,redirectURI:e.redirectURI||a,options:e,codeVerifier:d,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:d}=await(0,Pt.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return d||a.state!=="active"||a.locked?null:{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0},data:a}}}};var Xt={apple:at,discord:ct,facebook:lt,github:pt,microsoft:bt,google:gt,spotify:At,twitch:Rt,twitter:vt,dropbox:_t,linkedin:Tt,gitlab:St},se=Object.keys(Xt);var It=require("oslo"),de=require("oslo/jwt"),I=require("zod");var $=require("better-call");var z=require("better-call");var Q=require("zod");function Ot(e){try{return JSON.parse(e)}catch{return null}}var ae=()=>p("/get-session",{method:"GET",query:Q.z.optional(Q.z.object({disableCookieCache:Q.z.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?Ot(Buffer.from(r,"base64").toString()):null;if(o&&!await ie.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return V(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let u=o.session;if(o.expiresAt<Date.now()||u.session.expiresAt<new Date){let h=e.context.authCookies.sessionData.name;e.setCookie(h,"",{maxAge:0})}else return e.json(u)}let i=await e.context.internalAdapter.findSession(t);if(!i||i.session.expiresAt<new Date)return V(e),i&&await e.context.internalAdapter.deleteSession(i.session.id),e.json(null);if(n)return e.json(i);let s=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+a*1e3<=Date.now()){let u=await e.context.internalAdapter.updateSession(i.session.id,{expiresAt:L(e.context.sessionConfig.expiresIn,"sec")});if(!u)return V(e),e.json(null,{status:401});let f=(u.expiresAt.valueOf()-Date.now())/1e3;return await T(e,{session:u,user:i.user},!1,{maxAge:f}),e.json({session:u,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error(t),new z.APIError("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),K=async e=>{if(e.context.session)return e.context.session;let t=await ae()({...e,_flag:"json",headers:e.headers});return e.context.session=t,t},P=J(async e=>{let t=await K(e);if(!t?.session)throw new z.APIError("UNAUTHORIZED");return{session:t}}),ye=()=>p("/list-sessions",{method:"GET",use:[P],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)}),Ae=p("/revoke-session",{method:"POST",body:Q.z.object({id:Q.z.string()}),use:[P],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new z.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new z.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new z.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ke=p("/revoke-sessions",{method:"POST",use:[P],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new z.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Re=p("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[P]},async e=>{let t=e.context.session;if(!t.user)throw new z.APIError("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.id!==e.context.session.session.id);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.id))),e.json({status:!0})});async function C(e,t,r){return await(0,de.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new It.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Ue=p("/send-verification-email",{method:"POST",query:I.z.object({currentURL:I.z.string().optional()}).optional(),body:I.z.object({email:I.z.string().email(),callbackURL:I.z.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new $.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 $.APIError("BAD_REQUEST",{message:"User not found"});let o=await C(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({user:r.user,url:n,token:o},e.request),e.json({status:!0})}),ve=p("/verify-email",{method:"GET",query:I.z.object({token:I.z.string(),callbackURL:I.z.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await(0,de.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new $.APIError("BAD_REQUEST",{message:"Invalid token"})}let n=I.z.object({email:I.z.string().email(),updateTo:I.z.string().optional()}).parse(r.payload),i=await e.context.internalAdapter.findUserByEmail(n.email);if(!i)throw new $.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 $.APIError("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new $.APIError("UNAUTHORIZED",{message:"Invalid session"});let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${t}`,token:t},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await K(e)){let a=await e.context.internalAdapter.createSession(i.user.id,e.request);if(!a)throw new $.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await T(e,{session:a,user:i.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function ce(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw m.error(`Better auth was unable to query your database.
4
- Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user;if(n){let a=n.accounts.find(d=>d.providerId===r.providerId);if(a)await e.context.internalAdapter.updateAccount(a.id,{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt});else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Ge&&m.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),id:e.context.uuid(),userId:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt})}catch(u){return m.error("Unable to link account",u),{error:"unable to link account",data:null}}}}else try{let a=t.emailVerified||!1;if(i=await e.context.internalAdapter.createOAuthUser({...t,id:e.context.uuid(),emailVerified:a,email:t.email.toLowerCase()},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,providerId:r.providerId,accountId:t.id.toString()}).then(d=>d?.user),!a&&i&&e.context.options.emailVerification?.sendOnSignUp){let d=await C(e.context.secret,i.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:c,token:d},e.request)}}catch(a){return m.error("Unable to create user",a),{error:"unable to create user",data:null}}if(!i)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(i.id,e.request);return s?{data:{session:s,user:i},error:null}:{error:"unable to create session",data:null}}var Ee=p("/sign-in/social",{method:"POST",query:A.z.object({currentURL:A.z.string().optional()}).optional(),body:A.z.object({callbackURL:A.z.string().optional(),errorCallbackURL:A.z.string().optional(),provider:A.z.enum(se),idToken:A.z.optional(A.z.object({token:A.z.string(),nonce:A.z.string().optional(),accessToken:A.z.string().optional(),refreshToken:A.z.string().optional(),expiresAt:A.z.number().optional()}))})},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new v.APIError("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new v.APIError("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:i,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:"Invalid id token"});let d=await t.getUserInfo({idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!d||!d?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:"Failed to get user info"});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:"User email not found"});let c=await ce(e,{userInfo:{email:d.user.email,id:d.user.id,name:d.user.name||"",image:d.user.image,emailVerified:d.user.emailVerified||!1},account:{providerId:t.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new v.APIError("UNAUTHORIZED",{message:c.error});return await T(e,c.data),e.json({session:c.data.session,user:c.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:r,state:o}=await oe(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!0})}),_e=p("/sign-in/email",{method:"POST",body:A.z.object({email:A.z.string(),password:A.z.string(),callbackURL:A.z.string().optional(),rememberMe:A.z.boolean().default(!1).optional()})},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new v.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!A.z.string().email().safeParse(t).success)throw new v.APIError("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(c=>c.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw m.error("Email verification is required but no email verification handler is provided"),new v.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await C(e.context.secret,n.user.email),u=`${e.context.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:u,token:c},e.request),e.context.logger.error("Email not verified",{email:t}),new v.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!d)throw e.context.logger.error("Failed to create session"),new v.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await T(e,{session:d,user:n.user},e.body.rememberMe===!1),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Y=require("zod");var ue=Y.z.object({code:Y.z.string().optional(),error:Y.z.string().optional(),state:Y.z.string().optional()}),xe=p("/callback/:id",{method:["GET","POST"],body:ue.optional(),query:ue.optional(),metadata:M},async e=>{let t;try{if(e.method==="GET")t=ue.parse(e.query);else if(e.method==="POST")t=ue.parse(e.body);else throw new Error("Unsupported method")}catch(_){throw e.context.logger.error(_),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n}=t;if(!n)throw e.context.logger.error("State not found"),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}`);let i=e.context.socialProviders.find(_=>_.id===e.params.id);if(!i)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:s,callbackURL:a,link:d,errorURL:c}=await Je(e),u;try{u=await i.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${i.id}`})}catch(_){throw e.context.logger.error(_),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let f=await i.getUserInfo(u).then(_=>_?.user),l={id:He(),...f};function b(_){let x=c||a||`${e.context.baseURL}/error`;throw x.includes("?")?x=`${x}&error=${_}`:x=`${x}?error=${_}`,e.redirect(x)}if(!f)return m.error("Unable to get user info"),b("unable_to_get_user_info");if(!l.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),b("email_not_found");if(!a)throw m.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(d){if(d.email!==l.email.toLowerCase())return b("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:i.id,accountId:f.id}))return b("unable_to_link_account");let x;try{x=new URL(a).toString()}catch{x=a}throw e.redirect(x)}let R=await ce(e,{userInfo:{email:l.email,id:l.id,name:l.name||"",image:l.image,emailVerified:l.emailVerified||!1},account:{providerId:i.id,accountId:f.id,accessToken:u.accessToken,refreshToken:u.refreshToken,expiresAt:u.accessTokenExpiresAt},callbackURL:a});if(R.error)return b(R.error.split(" ").join("_"));let{session:S,user:k}=R.data;await T(e,{session:S,user:k});let ee;try{ee=new URL(a).toString()}catch{ee=a}throw e.redirect(ee)});var qn=require("zod");var Lt=require("better-call"),Te=p("/sign-out",{method:"POST",requireHeaders:!0},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw V(e),new Lt.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),V(e),e.json({success:!0})});var O=require("zod");var X=require("better-call");function Ct(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function er(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var Pe=p("/forget-password",{method:"POST",body:O.z.object({email:O.z.string().email(),redirectTo:O.z.string()})},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new X.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=L(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:a,token:s},e.request),e.json({status:!0})}),Se=p("/reset-password/:token",{method:"GET",query:O.z.object({callbackURL:O.z.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(Ct(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Ct(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(er(e.context,r,{token:t}))}),Oe=p("/reset-password",{query:O.z.optional(O.z.object({token:O.z.string().optional(),currentURL:O.z.string().optional()})),method:"POST",body:O.z.object({newPassword:O.z.string(),token:O.z.string().optional()})},async e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new X.APIError("BAD_REQUEST",{message:"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 X.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(u=>u.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(i,s))throw new X.APIError("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});var U=require("zod");var E=require("better-call");var g=require("zod"),Jn=g.z.object({id:g.z.string(),providerId:g.z.string(),accountId:g.z.string(),userId:g.z.string(),accessToken:g.z.string().nullish(),refreshToken:g.z.string().nullish(),idToken:g.z.string().nullish(),expiresAt:g.z.date().nullish(),password:g.z.string().nullish()}),Wn=g.z.object({id:g.z.string(),email:g.z.string().transform(e=>e.toLowerCase()),emailVerified:g.z.boolean().default(!1),name:g.z.string(),image:g.z.string().nullish(),createdAt:g.z.date().default(new Date),updatedAt:g.z.date().default(new Date)}),Kn=g.z.object({id:g.z.string(),userId:g.z.string(),expiresAt:g.z.date(),ipAddress:g.z.string().nullish(),userAgent:g.z.string().nullish()}),Yn=g.z.object({id:g.z.string(),value:g.z.string(),createdAt:g.z.date(),expiresAt:g.z.date(),identifier:g.z.string()});function tr(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function rr(e,t){let r=t.action||"create",o=t.fields,n={};for(let i in o){if(i in e){if(o[i].input===!1){if(o[i].defaultValue){n[i]=o[i].defaultValue;continue}continue}n[i]=e[i];continue}if(o[i].defaultValue&&r==="create"){n[i]=o[i].defaultValue;continue}}return n}function le(e,t,r){let o=tr(e,"user");return rr(t||{},{fields:o,action:r})}var Ie=()=>p("/update-user",{method:"POST",body:U.z.record(U.z.string(),U.z.any()),use:[P]},async e=>{let t=e.body;if(t.email)throw new E.APIError("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...n}=t,i=e.context.session;if(!o&&!r&&Object.keys(n).length===0)return e.json({user:i.user});let s=le(e.context.options,n,"update"),a=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await T(e,{session:i.session,user:a}),e.json({user:a})}),Le=p("/change-password",{method:"POST",body:U.z.object({newPassword:U.z.string(),currentPassword:U.z.string(),revokeOtherSessions:U.z.boolean().optional()}),use:[P]},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 E.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 E.APIError("BAD_REQUEST",{message:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(n.user.id)).find(f=>f.providerId==="credential"&&f.password);if(!d||!d.password)throw new E.APIError("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(d.password,r))throw new E.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let f=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!f)throw new E.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await T(e,{session:f,user:n.user})}return e.json(n.user)}),Ce=p("/set-password",{method:"POST",body:U.z.object({newPassword:U.z.string()}),metadata:{SERVER_ONLY:!0},use:[P]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new E.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 E.APIError("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(d=>d.providerId==="credential"&&d.password),a=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:a}),e.json(r.user);throw new E.APIError("BAD_REQUEST",{message:"user already has a password"})}),Be=p("/delete-user",{method:"POST",body:U.z.object({password:U.z.string()}),use:[P]},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 E.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new E.APIError("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),V(e),e.json(null)}),De=p("/change-email",{method:"POST",query:U.z.object({currentURL:U.z.string().optional()}).optional(),body:U.z.object({newEmail:U.z.string().email(),callbackURL:U.z.string().optional()}),use:[P]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new E.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 E.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 E.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.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await C(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),e.json({user:null,status:!0})});var or=(e="Unknown")=>`<!DOCTYPE html>
4
+ Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user;if(n){let a=n.accounts.find(d=>d.providerId===r.providerId);if(a)await e.context.internalAdapter.updateAccount(a.id,{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt});else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Ge&&m.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),id:e.context.uuid(),userId:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt})}catch(u){return m.error("Unable to link account",u),{error:"unable to link account",data:null}}}}else try{let a=t.emailVerified||!1;if(i=await e.context.internalAdapter.createOAuthUser({...t,id:e.context.uuid(),emailVerified:a,email:t.email.toLowerCase()},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,providerId:r.providerId,accountId:t.id.toString()}).then(d=>d?.user),!a&&i&&e.context.options.emailVerification?.sendOnSignUp){let d=await C(e.context.secret,i.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:c,token:d},e.request)}}catch(a){return m.error("Unable to create user",a),{error:"unable to create user",data:null}}if(!i)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(i.id,e.request);return s?{data:{session:s,user:i},error:null}:{error:"unable to create session",data:null}}var Ee=p("/sign-in/social",{method:"POST",query:A.z.object({currentURL:A.z.string().optional()}).optional(),body:A.z.object({callbackURL:A.z.string().optional(),errorCallbackURL:A.z.string().optional(),provider:A.z.enum(se),idToken:A.z.optional(A.z.object({token:A.z.string(),nonce:A.z.string().optional(),accessToken:A.z.string().optional(),refreshToken:A.z.string().optional(),expiresAt:A.z.number().optional()}))})},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new v.APIError("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new v.APIError("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:i,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:"Invalid id token"});let d=await t.getUserInfo({idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!d||!d?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:"Failed to get user info"});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:"User email not found"});let c=await ce(e,{userInfo:{email:d.user.email,id:d.user.id,name:d.user.name||"",image:d.user.image,emailVerified:d.user.emailVerified||!1},account:{providerId:t.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new v.APIError("UNAUTHORIZED",{message:c.error});return await T(e,c.data),e.json({session:c.data.session,user:c.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:r,state:o}=await oe(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!0})}),_e=p("/sign-in/email",{method:"POST",body:A.z.object({email:A.z.string(),password:A.z.string(),callbackURL:A.z.string().optional(),rememberMe:A.z.boolean().default(!0).optional()})},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new v.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!A.z.string().email().safeParse(t).success)throw new v.APIError("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(c=>c.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw m.error("Email verification is required but no email verification handler is provided"),new v.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await C(e.context.secret,n.user.email),u=`${e.context.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:u,token:c},e.request),e.context.logger.error("Email not verified",{email:t}),new v.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!d)throw e.context.logger.error("Failed to create session"),new v.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await T(e,{session:d,user:n.user},e.body.rememberMe===!1),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Y=require("zod");var ue=Y.z.object({code:Y.z.string().optional(),error:Y.z.string().optional(),state:Y.z.string().optional()}),xe=p("/callback/:id",{method:["GET","POST"],body:ue.optional(),query:ue.optional(),metadata:M},async e=>{let t;try{if(e.method==="GET")t=ue.parse(e.query);else if(e.method==="POST")t=ue.parse(e.body);else throw new Error("Unsupported method")}catch(_){throw e.context.logger.error(_),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n}=t;if(!n)throw e.context.logger.error("State not found"),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}`);let i=e.context.socialProviders.find(_=>_.id===e.params.id);if(!i)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:s,callbackURL:a,link:d,errorURL:c}=await Je(e),u;try{u=await i.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${i.id}`})}catch(_){throw e.context.logger.error(_),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let f=await i.getUserInfo(u).then(_=>_?.user),l={id:He(),...f};function b(_){let x=c||a||`${e.context.baseURL}/error`;throw x.includes("?")?x=`${x}&error=${_}`:x=`${x}?error=${_}`,e.redirect(x)}if(!f)return m.error("Unable to get user info"),b("unable_to_get_user_info");if(!l.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),b("email_not_found");if(!a)throw m.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(d){if(d.email!==l.email.toLowerCase())return b("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:i.id,accountId:f.id}))return b("unable_to_link_account");let x;try{x=new URL(a).toString()}catch{x=a}throw e.redirect(x)}let R=await ce(e,{userInfo:{email:l.email,id:l.id,name:l.name||"",image:l.image,emailVerified:l.emailVerified||!1},account:{providerId:i.id,accountId:f.id,accessToken:u.accessToken,refreshToken:u.refreshToken,expiresAt:u.accessTokenExpiresAt},callbackURL:a});if(R.error)return b(R.error.split(" ").join("_"));let{session:S,user:k}=R.data;await T(e,{session:S,user:k});let ee;try{ee=new URL(a).toString()}catch{ee=a}throw e.redirect(ee)});var qn=require("zod");var Lt=require("better-call"),Te=p("/sign-out",{method:"POST",requireHeaders:!0},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw V(e),new Lt.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),V(e),e.json({success:!0})});var O=require("zod");var X=require("better-call");function Ct(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function er(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var Pe=p("/forget-password",{method:"POST",body:O.z.object({email:O.z.string().email(),redirectTo:O.z.string()})},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new X.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=L(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:a,token:s},e.request),e.json({status:!0})}),Se=p("/reset-password/:token",{method:"GET",query:O.z.object({callbackURL:O.z.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(Ct(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Ct(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(er(e.context,r,{token:t}))}),Oe=p("/reset-password",{query:O.z.optional(O.z.object({token:O.z.string().optional(),currentURL:O.z.string().optional()})),method:"POST",body:O.z.object({newPassword:O.z.string(),token:O.z.string().optional()})},async e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new X.APIError("BAD_REQUEST",{message:"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 X.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(u=>u.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(i,s))throw new X.APIError("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});var U=require("zod");var E=require("better-call");var g=require("zod"),Jn=g.z.object({id:g.z.string(),providerId:g.z.string(),accountId:g.z.string(),userId:g.z.string(),accessToken:g.z.string().nullish(),refreshToken:g.z.string().nullish(),idToken:g.z.string().nullish(),expiresAt:g.z.date().nullish(),password:g.z.string().nullish()}),Wn=g.z.object({id:g.z.string(),email:g.z.string().transform(e=>e.toLowerCase()),emailVerified:g.z.boolean().default(!1),name:g.z.string(),image:g.z.string().nullish(),createdAt:g.z.date().default(new Date),updatedAt:g.z.date().default(new Date)}),Kn=g.z.object({id:g.z.string(),userId:g.z.string(),expiresAt:g.z.date(),ipAddress:g.z.string().nullish(),userAgent:g.z.string().nullish()}),Yn=g.z.object({id:g.z.string(),value:g.z.string(),createdAt:g.z.date(),expiresAt:g.z.date(),identifier:g.z.string()});function tr(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function rr(e,t){let r=t.action||"create",o=t.fields,n={};for(let i in o){if(i in e){if(o[i].input===!1){if(o[i].defaultValue){n[i]=o[i].defaultValue;continue}continue}n[i]=e[i];continue}if(o[i].defaultValue&&r==="create"){n[i]=o[i].defaultValue;continue}}return n}function le(e,t,r){let o=tr(e,"user");return rr(t||{},{fields:o,action:r})}var Ie=()=>p("/update-user",{method:"POST",body:U.z.record(U.z.string(),U.z.any()),use:[P]},async e=>{let t=e.body;if(t.email)throw new E.APIError("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...n}=t,i=e.context.session;if(!o&&!r&&Object.keys(n).length===0)return e.json({user:i.user});let s=le(e.context.options,n,"update"),a=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await T(e,{session:i.session,user:a}),e.json({user:a})}),Le=p("/change-password",{method:"POST",body:U.z.object({newPassword:U.z.string(),currentPassword:U.z.string(),revokeOtherSessions:U.z.boolean().optional()}),use:[P]},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 E.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 E.APIError("BAD_REQUEST",{message:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(n.user.id)).find(f=>f.providerId==="credential"&&f.password);if(!d||!d.password)throw new E.APIError("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(d.password,r))throw new E.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let f=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!f)throw new E.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await T(e,{session:f,user:n.user})}return e.json(n.user)}),Ce=p("/set-password",{method:"POST",body:U.z.object({newPassword:U.z.string()}),metadata:{SERVER_ONLY:!0},use:[P]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new E.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 E.APIError("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(d=>d.providerId==="credential"&&d.password),a=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:a}),e.json(r.user);throw new E.APIError("BAD_REQUEST",{message:"user already has a password"})}),Be=p("/delete-user",{method:"POST",body:U.z.object({password:U.z.string()}),use:[P]},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 E.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new E.APIError("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),V(e),e.json(null)}),De=p("/change-email",{method:"POST",query:U.z.object({currentURL:U.z.string().optional()}).optional(),body:U.z.object({newEmail:U.z.string().email(),callbackURL:U.z.string().optional()}),use:[P]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new E.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 E.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 E.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.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await C(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),e.json({user:null,status:!0})});var or=(e="Unknown")=>`<!DOCTYPE html>
5
5
  <html lang="en">
6
6
  <head>
7
7
  <meta charset="UTF-8">
package/dist/api.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- export { z as AuthEndpoint, C as AuthMiddleware, a4 as callbackOAuth, an as changeEmail, ak as changePassword, y as createAuthEndpoint, x as createAuthMiddleware, ag as createEmailVerificationToken, am as deleteUser, ao as error, ad as forgetPassword, ae as forgetPasswordCallback, a0 as getEndpoints, a5 as getSession, a6 as getSessionFromCtx, as as linkSocialAccount, a8 as listSessions, ar as listUserAccounts, ap as ok, w as optionsMiddleware, at as originCheckMiddleware, af as resetPassword, ab as revokeOtherSessions, a9 as revokeSession, aa as revokeSessions, a1 as router, ah as sendVerificationEmail, a7 as sessionMiddleware, al as setPassword, a3 as signInEmail, a2 as signInSocial, ac as signOut, aq as signUpEmail, aj as updateUser, ai as verifyEmail } from './auth-BuIGx3uf.cjs';
1
+ export { z as AuthEndpoint, C as AuthMiddleware, a4 as callbackOAuth, an as changeEmail, ak as changePassword, y as createAuthEndpoint, x as createAuthMiddleware, ag as createEmailVerificationToken, am as deleteUser, ao as error, ad as forgetPassword, ae as forgetPasswordCallback, a0 as getEndpoints, a5 as getSession, a6 as getSessionFromCtx, as as linkSocialAccount, a8 as listSessions, ar as listUserAccounts, ap as ok, w as optionsMiddleware, at as originCheckMiddleware, af as resetPassword, ab as revokeOtherSessions, a9 as revokeSession, aa as revokeSessions, a1 as router, ah as sendVerificationEmail, a7 as sessionMiddleware, al as setPassword, a3 as signInEmail, a2 as signInSocial, ac as signOut, aq as signUpEmail, aj as updateUser, ai as verifyEmail } from './auth-Dypsi529.cjs';
2
2
  import './helper-DrEEwdyQ.cjs';
3
3
  export { APIError } from 'better-call';
4
4
  import 'zod';
package/dist/api.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { z as AuthEndpoint, C as AuthMiddleware, a4 as callbackOAuth, an as changeEmail, ak as changePassword, y as createAuthEndpoint, x as createAuthMiddleware, ag as createEmailVerificationToken, am as deleteUser, ao as error, ad as forgetPassword, ae as forgetPasswordCallback, a0 as getEndpoints, a5 as getSession, a6 as getSessionFromCtx, as as linkSocialAccount, a8 as listSessions, ar as listUserAccounts, ap as ok, w as optionsMiddleware, at as originCheckMiddleware, af as resetPassword, ab as revokeOtherSessions, a9 as revokeSession, aa as revokeSessions, a1 as router, ah as sendVerificationEmail, a7 as sessionMiddleware, al as setPassword, a3 as signInEmail, a2 as signInSocial, ac as signOut, aq as signUpEmail, aj as updateUser, ai as verifyEmail } from './auth-DuGk-eor.js';
1
+ export { z as AuthEndpoint, C as AuthMiddleware, a4 as callbackOAuth, an as changeEmail, ak as changePassword, y as createAuthEndpoint, x as createAuthMiddleware, ag as createEmailVerificationToken, am as deleteUser, ao as error, ad as forgetPassword, ae as forgetPasswordCallback, a0 as getEndpoints, a5 as getSession, a6 as getSessionFromCtx, as as linkSocialAccount, a8 as listSessions, ar as listUserAccounts, ap as ok, w as optionsMiddleware, at as originCheckMiddleware, af as resetPassword, ab as revokeOtherSessions, a9 as revokeSession, aa as revokeSessions, a1 as router, ah as sendVerificationEmail, a7 as sessionMiddleware, al as setPassword, a3 as signInEmail, a2 as signInSocial, ac as signOut, aq as signUpEmail, aj as updateUser, ai as verifyEmail } from './auth-HkH2WNGO.js';
2
2
  import './helper-DrEEwdyQ.js';
3
3
  export { APIError } from 'better-call';
4
4
  import 'zod';
package/dist/api.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import{APIError as de,createRouter as sr,statusCode as ar}from"better-call";import{APIError as bt}from"better-call";import{createEndpointCreator as ut,createMiddleware as ce,createMiddlewareCreator as lt}from"better-call";var ue=ce(async()=>({})),Z=lt({use:[ue,ce(async()=>({}))]}),p=ut({use:[ue]});var N={isAction:!1};import{nanoid as pt}from"nanoid";var le=e=>pt(e);import{APIError as he}from"better-call";import{generateCodeVerifier as ft,generateState as gt}from"oslo/oauth2";import{z as V}from"zod";var J=Object.create(null),H=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?J:globalThis),pe=new Proxy(J,{get(e,t){return H()[t]??J[t]},has(e,t){let r=H();return t in r||t in J},set(e,t,r){let o=H(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=H(!0);return delete r[t],!0},ownKeys(){let e=H(!0);return Object.keys(e)}});function mt(e){return e?e!=="false":!1}var ie=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var me=ie==="dev"||ie==="development",fe=ie==="test"||mt(pe.TEST);var z=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function ge(e){try{return new URL(e).origin}catch{return null}}async function W(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?ge(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new he("BAD_REQUEST",{message:"callbackURL is required"});let o=ft(),n=gt(),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:s});if(!a)throw m.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new he("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function we(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw m.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=V.object({callbackURL:V.string(),codeVerifier:V.string(),errorURL:V.string().optional(),expiresAt:V.number(),link:V.object({email:V.string(),userId:V.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),m.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}import{createConsola as ht}from"consola";var $=ht({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),wt=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
2
  `)}}),m=wt();var be=Z(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=t?.callbackURL||r?.callbackURL,s=t?.redirectTo,a=r?.currentURL,d=o.trustedOrigins,c=e.headers?.has("cookie"),u=(h,l)=>l.includes("*")?new RegExp("^"+l.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(h):h.startsWith(l),f=(h,l)=>{if(!h)return;if(!d.some(R=>u(h,R)||h?.startsWith("/")&&l!=="origin"&&!h.includes(":")))throw m.error(`Invalid ${l}: ${h}`),m.info(`If it's a valid URL, please add ${h} to trustedOrigins in your auth config
3
3
  `,`Current list of trustedOrigins: ${d}`),new bt("FORBIDDEN",{message:`Invalid ${l}`})};c&&!e.context.options.advanced?.disableCSRFCheck&&f(n,"origin"),i&&f(i,"callbackURL"),s&&f(s,"redirectURL"),a&&f(a,"currentURL")});import{APIError as v}from"better-call";import{z as k}from"zod";import{TimeSpan as Wr}from"oslo";import{base64url as kt}from"oslo/encoding";import{HMAC as ye,sha256 as Fr}from"oslo/crypto";async function yt({value:e,secret:t}){return new ye("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function At({value:e,signature:t,secret:r}){return new ye("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var K={sign:yt,verify:At};var L=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function T(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.session.id,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(kt.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:L(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await K.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.id,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function C(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}import{betterFetch as Et}from"@better-fetch/fetch";import{APIError as _t}from"better-call";import{decodeProtectedHeader as xt,importJWK as Tt,jwtVerify as Pt}from"jose";import{parseJWT as St}from"oslo/jwt";import{sha256 as Rt}from"oslo/crypto";import{base64url as Ut}from"oslo/encoding";async function Ae(e){let t=await Rt(new TextEncoder().encode(e));return Ut.encode(new Uint8Array(t),{includePadding:!1})}function ke(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?L(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function y({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,redirectURI:a}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",i.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||a),n){let c=await Ae(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",c)}if(s){let c=s.reduce((u,f)=>(u[f]=null,u),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...c}}))}return d}import{betterFetch as vt}from"@better-fetch/fetch";async function w({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n,authentication:i}){let s=new URLSearchParams,a={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),i==="basic"){let f=btoa(`${o.clientId}:${o.clientSecret}`);a.authorization=`Basic ${f}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:d,error:c}=await vt(n,{method:"POST",body:s,headers:a});if(c)throw c;return ke(d)}var Re=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let n=xt(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let a=await Ot(i),{payload:d}=await Pt(r,a,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(c=>{d[c]!==void 0&&(d[c]=!!d[c])}),o&&d.nonce!==o?!1:!!d},async getUserInfo(r){if(!r.idToken)return null;let o=St(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email;return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email},data:o}}}},Ot=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await Et(`${t}${r}`);if(!o?.keys)throw new _t("BAD_REQUEST",{message:"Keys not found"});let n=o.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await Tt(n,n.alg)};import{betterFetch as It}from"@better-fetch/fetch";var Ue=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await It("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 Lt}from"@better-fetch/fetch";var ve=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await y({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})=>w({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 Lt("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,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});import{betterFetch as Ee}from"@better-fetch/fetch";var _e=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),y({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>w({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await Ee("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:a}=await Ee("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(d=>d.primary)??s[0])?.email,i=s.find(d=>d.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};import{parseJWT as Ct}from"oslo/jwt";import{betterFetch as Bt}from"@better-fetch/fetch";var xe=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw m.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new z("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new z("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await y({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:n}=await Bt(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(!t.idToken)return null;let r=Ct(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 Dt}from"@better-fetch/fetch";import{parseJWT as Vt}from"oslo/jwt";var Te=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),y({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 w({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=Vt(n.idToken)?.payload,s=e.profilePhotoSize||48;return await Dt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let c=await a.response.clone().arrayBuffer(),u=Buffer.from(c).toString("base64");i.picture=`data:image/jpeg;base64, ${u}`}catch(d){m.error(d)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as zt}from"@better-fetch/fetch";var Pe=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),y({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})=>w({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await zt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";import{parseJWT as $t}from"oslo/jwt";var Se=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),y({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})=>w({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 m.error("No idToken found in token"),null;let o=$t(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as jt}from"@better-fetch/fetch";var Oe=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),y({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await jt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});import{betterFetch as qt}from"@better-fetch/fetch";var Ie=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await y({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await qt("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};import{betterFetch as Nt}from"@better-fetch/fetch";var Le=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await y({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await w({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await Nt("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};import{betterFetch as Ft}from"@better-fetch/fetch";var se=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Ht=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:se(`${t}/oauth/authorize`),tokenEndpoint:se(`${t}/oauth/token`),userinfoEndpoint:se(`${t}/api/v4/user`)}},Ce=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Ht(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:d,redirectURI:c})=>{let u=a||["read_user"];return e.scope&&u.push(...e.scope),await y({id:n,options:e,authorizationEndpoint:t,scopes:u,state:s,redirectURI:c,codeVerifier:d})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:d})=>w({code:s,redirectURI:e.redirectURI||a,options:e,codeVerifier:d,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:d}=await Ft(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return d||a.state!=="active"||a.locked?null:{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0},data:a}}}};var Mt={apple:Re,discord:Ue,facebook:ve,github:_e,microsoft:Te,google:xe,spotify:Pe,twitch:Se,twitter:Oe,dropbox:Ie,linkedin:Le,gitlab:Ce},Y=Object.keys(Mt);import{TimeSpan as Gt}from"oslo";import{createJWT as Qt,validateJWT as Zt}from"oslo/jwt";import{z as I}from"zod";import{APIError as q}from"better-call";import{APIError as j}from"better-call";import{z as M}from"zod";function Be(e){try{return JSON.parse(e)}catch{return null}}var ae=()=>p("/get-session",{method:"GET",query:M.optional(M.object({disableCookieCache:M.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?Be(Buffer.from(r,"base64").toString()):null;if(o&&!await K.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return C(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let u=o.session;if(o.expiresAt<Date.now()||u.session.expiresAt<new Date){let h=e.context.authCookies.sessionData.name;e.setCookie(h,"",{maxAge:0})}else return e.json(u)}let i=await e.context.internalAdapter.findSession(t);if(!i||i.session.expiresAt<new Date)return C(e),i&&await e.context.internalAdapter.deleteSession(i.session.id),e.json(null);if(n)return e.json(i);let s=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+a*1e3<=Date.now()){let u=await e.context.internalAdapter.updateSession(i.session.id,{expiresAt:L(e.context.sessionConfig.expiresIn,"sec")});if(!u)return C(e),e.json(null,{status:401});let f=(u.expiresAt.valueOf()-Date.now())/1e3;return await T(e,{session:u,user:i.user},!1,{maxAge:f}),e.json({session:u,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error(t),new j("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),X=async e=>{if(e.context.session)return e.context.session;let t=await ae()({...e,_flag:"json",headers:e.headers});return e.context.session=t,t},S=Z(async e=>{let t=await X(e);if(!t?.session)throw new j("UNAUTHORIZED");return{session:t}}),De=()=>p("/list-sessions",{method:"GET",use:[S],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)}),Ve=p("/revoke-session",{method:"POST",body:M.object({id:M.string()}),use:[S],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new j("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new j("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new j("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ze=p("/revoke-sessions",{method:"POST",use:[S],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new j("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),$e=p("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[S]},async e=>{let t=e.context.session;if(!t.user)throw new j("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.id!==e.context.session.session.id);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.id))),e.json({status:!0})});async function B(e,t,r){return await Qt("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Gt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var je=p("/send-verification-email",{method:"POST",query:I.object({currentURL:I.string().optional()}).optional(),body:I.object({email:I.string().email(),callbackURL:I.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new q("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new q("BAD_REQUEST",{message:"User not found"});let o=await B(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail({user:r.user,url:n,token:o},e.request),e.json({status:!0})}),qe=p("/verify-email",{method:"GET",query:I.object({token:I.string(),callbackURL:I.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await Zt("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new q("BAD_REQUEST",{message:"Invalid token"})}let n=I.object({email:I.string().email(),updateTo:I.string().optional()}).parse(r.payload),i=await e.context.internalAdapter.findUserByEmail(n.email);if(!i)throw new q("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await X(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new q("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new q("UNAUTHORIZED",{message:"Invalid session"});let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${t}`,token:t},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await X(e)){let a=await e.context.internalAdapter.createSession(i.user.id,e.request);if(!a)throw new q("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await T(e,{session:a,user:i.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function ee(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw m.error(`Better auth was unable to query your database.
4
- Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user;if(n){let a=n.accounts.find(d=>d.providerId===r.providerId);if(a)await e.context.internalAdapter.updateAccount(a.id,{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt});else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return me&&m.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),id:e.context.uuid(),userId:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt})}catch(u){return m.error("Unable to link account",u),{error:"unable to link account",data:null}}}}else try{let a=t.emailVerified||!1;if(i=await e.context.internalAdapter.createOAuthUser({...t,id:e.context.uuid(),emailVerified:a,email:t.email.toLowerCase()},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,providerId:r.providerId,accountId:t.id.toString()}).then(d=>d?.user),!a&&i&&e.context.options.emailVerification?.sendOnSignUp){let d=await B(e.context.secret,i.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:c,token:d},e.request)}}catch(a){return m.error("Unable to create user",a),{error:"unable to create user",data:null}}if(!i)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(i.id,e.request);return s?{data:{session:s,user:i},error:null}:{error:"unable to create session",data:null}}var Ne=p("/sign-in/social",{method:"POST",query:k.object({currentURL:k.string().optional()}).optional(),body:k.object({callbackURL:k.string().optional(),errorCallbackURL:k.string().optional(),provider:k.enum(Y),idToken:k.optional(k.object({token:k.string(),nonce:k.string().optional(),accessToken:k.string().optional(),refreshToken:k.string().optional(),expiresAt:k.number().optional()}))})},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new v("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new v("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:i,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new v("UNAUTHORIZED",{message:"Invalid id token"});let d=await t.getUserInfo({idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!d||!d?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new v("UNAUTHORIZED",{message:"Failed to get user info"});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new v("UNAUTHORIZED",{message:"User email not found"});let c=await ee(e,{userInfo:{email:d.user.email,id:d.user.id,name:d.user.name||"",image:d.user.image,emailVerified:d.user.emailVerified||!1},account:{providerId:t.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new v("UNAUTHORIZED",{message:c.error});return await T(e,c.data),e.json({session:c.data.session,user:c.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:r,state:o}=await W(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!0})}),Fe=p("/sign-in/email",{method:"POST",body:k.object({email:k.string(),password:k.string(),callbackURL:k.string().optional(),rememberMe:k.boolean().default(!1).optional()})},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new v("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!k.string().email().safeParse(t).success)throw new v("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new v("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(c=>c.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new v("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new v("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new v("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw m.error("Email verification is required but no email verification handler is provided"),new v("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await B(e.context.secret,n.user.email),u=`${e.context.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:u,token:c},e.request),e.context.logger.error("Email not verified",{email:t}),new v("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!d)throw e.context.logger.error("Failed to create session"),new v("UNAUTHORIZED",{message:"Failed to create session"});return await T(e,{session:d,user:n.user},e.body.rememberMe===!1),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as te}from"zod";var re=te.object({code:te.string().optional(),error:te.string().optional(),state:te.string().optional()}),He=p("/callback/:id",{method:["GET","POST"],body:re.optional(),query:re.optional(),metadata:N},async e=>{let t;try{if(e.method==="GET")t=re.parse(e.query);else if(e.method==="POST")t=re.parse(e.body);else throw new Error("Unsupported method")}catch(_){throw e.context.logger.error(_),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n}=t;if(!n)throw e.context.logger.error("State not found"),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}`);let i=e.context.socialProviders.find(_=>_.id===e.params.id);if(!i)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:s,callbackURL:a,link:d,errorURL:c}=await we(e),u;try{u=await i.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${i.id}`})}catch(_){throw e.context.logger.error(_),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let f=await i.getUserInfo(u).then(_=>_?.user),l={id:le(),...f};function b(_){let x=c||a||`${e.context.baseURL}/error`;throw x.includes("?")?x=`${x}&error=${_}`:x=`${x}?error=${_}`,e.redirect(x)}if(!f)return m.error("Unable to get user info"),b("unable_to_get_user_info");if(!l.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),b("email_not_found");if(!a)throw m.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(d){if(d.email!==l.email.toLowerCase())return b("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:i.id,accountId:f.id}))return b("unable_to_link_account");let x;try{x=new URL(a).toString()}catch{x=a}throw e.redirect(x)}let R=await ee(e,{userInfo:{email:l.email,id:l.id,name:l.name||"",image:l.image,emailVerified:l.emailVerified||!1},account:{providerId:i.id,accountId:f.id,accessToken:u.accessToken,refreshToken:u.refreshToken,expiresAt:u.accessTokenExpiresAt},callbackURL:a});if(R.error)return b(R.error.split(" ").join("_"));let{session:P,user:A}=R.data;await T(e,{session:P,user:A});let Q;try{Q=new URL(a).toString()}catch{Q=a}throw e.redirect(Q)});import"zod";import{APIError as Jt}from"better-call";var Me=p("/sign-out",{method:"POST",requireHeaders:!0},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw C(e),new Jt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),C(e),e.json({success:!0})});import{z as O}from"zod";import{APIError as oe}from"better-call";function Ge(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function Wt(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var Qe=p("/forget-password",{method:"POST",body:O.object({email:O.string().email(),redirectTo:O.string()})},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 oe("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=L(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:a,token:s},e.request),e.json({status:!0})}),Ze=p("/reset-password/:token",{method:"GET",query:O.object({callbackURL:O.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(Ge(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Ge(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Wt(e.context,r,{token:t}))}),Je=p("/reset-password",{query:O.optional(O.object({token:O.string().optional(),currentURL:O.string().optional()})),method:"POST",body:O.object({newPassword:O.string(),token:O.string().optional()})},async e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new oe("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 oe("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(i)).find(u=>u.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(i,s))throw new oe("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as U}from"zod";import{APIError as E}from"better-call";import{z as g}from"zod";var Di=g.object({id:g.string(),providerId:g.string(),accountId:g.string(),userId:g.string(),accessToken:g.string().nullish(),refreshToken:g.string().nullish(),idToken:g.string().nullish(),expiresAt:g.date().nullish(),password:g.string().nullish()}),Vi=g.object({id:g.string(),email:g.string().transform(e=>e.toLowerCase()),emailVerified:g.boolean().default(!1),name:g.string(),image:g.string().nullish(),createdAt:g.date().default(new Date),updatedAt:g.date().default(new Date)}),zi=g.object({id:g.string(),userId:g.string(),expiresAt:g.date(),ipAddress:g.string().nullish(),userAgent:g.string().nullish()}),$i=g.object({id:g.string(),value:g.string(),createdAt:g.date(),expiresAt:g.date(),identifier:g.string()});function Kt(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function Yt(e,t){let r=t.action||"create",o=t.fields,n={};for(let i in o){if(i in e){if(o[i].input===!1){if(o[i].defaultValue){n[i]=o[i].defaultValue;continue}continue}n[i]=e[i];continue}if(o[i].defaultValue&&r==="create"){n[i]=o[i].defaultValue;continue}}return n}function ne(e,t,r){let o=Kt(e,"user");return Yt(t||{},{fields:o,action:r})}var We=()=>p("/update-user",{method:"POST",body:U.record(U.string(),U.any()),use:[S]},async e=>{let t=e.body;if(t.email)throw new E("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...n}=t,i=e.context.session;if(!o&&!r&&Object.keys(n).length===0)return e.json({user:i.user});let s=ne(e.context.options,n,"update"),a=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await T(e,{session:i.session,user:a}),e.json({user:a})}),Ke=p("/change-password",{method:"POST",body:U.object({newPassword:U.string(),currentPassword:U.string(),revokeOtherSessions:U.boolean().optional()}),use:[S]},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 E("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 E("BAD_REQUEST",{message:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(n.user.id)).find(f=>f.providerId==="credential"&&f.password);if(!d||!d.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(d.password,r))throw new E("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let f=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!f)throw new E("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await T(e,{session:f,user:n.user})}return e.json(n.user)}),Ye=p("/set-password",{method:"POST",body:U.object({newPassword:U.string()}),metadata:{SERVER_ONLY:!0},use:[S]},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 E("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 E("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(d=>d.providerId==="credential"&&d.password),a=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:a}),e.json(r.user);throw new E("BAD_REQUEST",{message:"user already has a password"})}),Xe=p("/delete-user",{method:"POST",body:U.object({password:U.string()}),use:[S]},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 E("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new E("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),C(e),e.json(null)}),et=p("/change-email",{method:"POST",query:U.object({currentURL:U.string().optional()}).optional(),body:U.object({newEmail:U.string().email(),callbackURL:U.string().optional()}),use:[S]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new E("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 E("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 E("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await B(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),e.json({user:null,status:!0})});var Xt=(e="Unknown")=>`<!DOCTYPE html>
4
+ Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user;if(n){let a=n.accounts.find(d=>d.providerId===r.providerId);if(a)await e.context.internalAdapter.updateAccount(a.id,{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt});else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return me&&m.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),id:e.context.uuid(),userId:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt})}catch(u){return m.error("Unable to link account",u),{error:"unable to link account",data:null}}}}else try{let a=t.emailVerified||!1;if(i=await e.context.internalAdapter.createOAuthUser({...t,id:e.context.uuid(),emailVerified:a,email:t.email.toLowerCase()},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,providerId:r.providerId,accountId:t.id.toString()}).then(d=>d?.user),!a&&i&&e.context.options.emailVerification?.sendOnSignUp){let d=await B(e.context.secret,i.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:c,token:d},e.request)}}catch(a){return m.error("Unable to create user",a),{error:"unable to create user",data:null}}if(!i)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(i.id,e.request);return s?{data:{session:s,user:i},error:null}:{error:"unable to create session",data:null}}var Ne=p("/sign-in/social",{method:"POST",query:k.object({currentURL:k.string().optional()}).optional(),body:k.object({callbackURL:k.string().optional(),errorCallbackURL:k.string().optional(),provider:k.enum(Y),idToken:k.optional(k.object({token:k.string(),nonce:k.string().optional(),accessToken:k.string().optional(),refreshToken:k.string().optional(),expiresAt:k.number().optional()}))})},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new v("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new v("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:i,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new v("UNAUTHORIZED",{message:"Invalid id token"});let d=await t.getUserInfo({idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!d||!d?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new v("UNAUTHORIZED",{message:"Failed to get user info"});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new v("UNAUTHORIZED",{message:"User email not found"});let c=await ee(e,{userInfo:{email:d.user.email,id:d.user.id,name:d.user.name||"",image:d.user.image,emailVerified:d.user.emailVerified||!1},account:{providerId:t.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new v("UNAUTHORIZED",{message:c.error});return await T(e,c.data),e.json({session:c.data.session,user:c.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:r,state:o}=await W(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!0})}),Fe=p("/sign-in/email",{method:"POST",body:k.object({email:k.string(),password:k.string(),callbackURL:k.string().optional(),rememberMe:k.boolean().default(!0).optional()})},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new v("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!k.string().email().safeParse(t).success)throw new v("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new v("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(c=>c.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new v("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new v("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new v("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw m.error("Email verification is required but no email verification handler is provided"),new v("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await B(e.context.secret,n.user.email),u=`${e.context.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:u,token:c},e.request),e.context.logger.error("Email not verified",{email:t}),new v("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!d)throw e.context.logger.error("Failed to create session"),new v("UNAUTHORIZED",{message:"Failed to create session"});return await T(e,{session:d,user:n.user},e.body.rememberMe===!1),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as te}from"zod";var re=te.object({code:te.string().optional(),error:te.string().optional(),state:te.string().optional()}),He=p("/callback/:id",{method:["GET","POST"],body:re.optional(),query:re.optional(),metadata:N},async e=>{let t;try{if(e.method==="GET")t=re.parse(e.query);else if(e.method==="POST")t=re.parse(e.body);else throw new Error("Unsupported method")}catch(_){throw e.context.logger.error(_),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n}=t;if(!n)throw e.context.logger.error("State not found"),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}`);let i=e.context.socialProviders.find(_=>_.id===e.params.id);if(!i)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:s,callbackURL:a,link:d,errorURL:c}=await we(e),u;try{u=await i.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${i.id}`})}catch(_){throw e.context.logger.error(_),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let f=await i.getUserInfo(u).then(_=>_?.user),l={id:le(),...f};function b(_){let x=c||a||`${e.context.baseURL}/error`;throw x.includes("?")?x=`${x}&error=${_}`:x=`${x}?error=${_}`,e.redirect(x)}if(!f)return m.error("Unable to get user info"),b("unable_to_get_user_info");if(!l.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),b("email_not_found");if(!a)throw m.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(d){if(d.email!==l.email.toLowerCase())return b("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:i.id,accountId:f.id}))return b("unable_to_link_account");let x;try{x=new URL(a).toString()}catch{x=a}throw e.redirect(x)}let R=await ee(e,{userInfo:{email:l.email,id:l.id,name:l.name||"",image:l.image,emailVerified:l.emailVerified||!1},account:{providerId:i.id,accountId:f.id,accessToken:u.accessToken,refreshToken:u.refreshToken,expiresAt:u.accessTokenExpiresAt},callbackURL:a});if(R.error)return b(R.error.split(" ").join("_"));let{session:P,user:A}=R.data;await T(e,{session:P,user:A});let Q;try{Q=new URL(a).toString()}catch{Q=a}throw e.redirect(Q)});import"zod";import{APIError as Jt}from"better-call";var Me=p("/sign-out",{method:"POST",requireHeaders:!0},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw C(e),new Jt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),C(e),e.json({success:!0})});import{z as O}from"zod";import{APIError as oe}from"better-call";function Ge(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function Wt(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var Qe=p("/forget-password",{method:"POST",body:O.object({email:O.string().email(),redirectTo:O.string()})},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 oe("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=L(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:a,token:s},e.request),e.json({status:!0})}),Ze=p("/reset-password/:token",{method:"GET",query:O.object({callbackURL:O.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(Ge(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Ge(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Wt(e.context,r,{token:t}))}),Je=p("/reset-password",{query:O.optional(O.object({token:O.string().optional(),currentURL:O.string().optional()})),method:"POST",body:O.object({newPassword:O.string(),token:O.string().optional()})},async e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new oe("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 oe("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(i)).find(u=>u.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(i,s))throw new oe("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as U}from"zod";import{APIError as E}from"better-call";import{z as g}from"zod";var Di=g.object({id:g.string(),providerId:g.string(),accountId:g.string(),userId:g.string(),accessToken:g.string().nullish(),refreshToken:g.string().nullish(),idToken:g.string().nullish(),expiresAt:g.date().nullish(),password:g.string().nullish()}),Vi=g.object({id:g.string(),email:g.string().transform(e=>e.toLowerCase()),emailVerified:g.boolean().default(!1),name:g.string(),image:g.string().nullish(),createdAt:g.date().default(new Date),updatedAt:g.date().default(new Date)}),zi=g.object({id:g.string(),userId:g.string(),expiresAt:g.date(),ipAddress:g.string().nullish(),userAgent:g.string().nullish()}),$i=g.object({id:g.string(),value:g.string(),createdAt:g.date(),expiresAt:g.date(),identifier:g.string()});function Kt(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function Yt(e,t){let r=t.action||"create",o=t.fields,n={};for(let i in o){if(i in e){if(o[i].input===!1){if(o[i].defaultValue){n[i]=o[i].defaultValue;continue}continue}n[i]=e[i];continue}if(o[i].defaultValue&&r==="create"){n[i]=o[i].defaultValue;continue}}return n}function ne(e,t,r){let o=Kt(e,"user");return Yt(t||{},{fields:o,action:r})}var We=()=>p("/update-user",{method:"POST",body:U.record(U.string(),U.any()),use:[S]},async e=>{let t=e.body;if(t.email)throw new E("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...n}=t,i=e.context.session;if(!o&&!r&&Object.keys(n).length===0)return e.json({user:i.user});let s=ne(e.context.options,n,"update"),a=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await T(e,{session:i.session,user:a}),e.json({user:a})}),Ke=p("/change-password",{method:"POST",body:U.object({newPassword:U.string(),currentPassword:U.string(),revokeOtherSessions:U.boolean().optional()}),use:[S]},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 E("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 E("BAD_REQUEST",{message:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(n.user.id)).find(f=>f.providerId==="credential"&&f.password);if(!d||!d.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(d.password,r))throw new E("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let f=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!f)throw new E("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await T(e,{session:f,user:n.user})}return e.json(n.user)}),Ye=p("/set-password",{method:"POST",body:U.object({newPassword:U.string()}),metadata:{SERVER_ONLY:!0},use:[S]},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 E("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 E("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(d=>d.providerId==="credential"&&d.password),a=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:a}),e.json(r.user);throw new E("BAD_REQUEST",{message:"user already has a password"})}),Xe=p("/delete-user",{method:"POST",body:U.object({password:U.string()}),use:[S]},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 E("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new E("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),C(e),e.json(null)}),et=p("/change-email",{method:"POST",query:U.object({currentURL:U.string().optional()}).optional(),body:U.object({newEmail:U.string().email(),callbackURL:U.string().optional()}),use:[S]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new E("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 E("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 E("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await B(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),e.json({user:null,status:!0})});var Xt=(e="Unknown")=>`<!DOCTYPE html>
5
5
  <html lang="en">
6
6
  <head>
7
7
  <meta charset="UTF-8">
@@ -1704,8 +1704,17 @@ declare const signInEmail: {
1704
1704
  <C extends [better_call.Context<"/sign-in/email", {
1705
1705
  method: "POST";
1706
1706
  body: z.ZodObject<{
1707
+ /**
1708
+ * Email of the user
1709
+ */
1707
1710
  email: z.ZodString;
1711
+ /**
1712
+ * Password of the user
1713
+ */
1708
1714
  password: z.ZodString;
1715
+ /**
1716
+ * Callback URL to redirect to after the user has signed in.
1717
+ */
1709
1718
  callbackURL: z.ZodOptional<z.ZodString>;
1710
1719
  /**
1711
1720
  * If this is false, the session will not be remembered
@@ -1749,8 +1758,17 @@ declare const signInEmail: {
1749
1758
  options: {
1750
1759
  method: "POST";
1751
1760
  body: z.ZodObject<{
1761
+ /**
1762
+ * Email of the user
1763
+ */
1752
1764
  email: z.ZodString;
1765
+ /**
1766
+ * Password of the user
1767
+ */
1753
1768
  password: z.ZodString;
1769
+ /**
1770
+ * Callback URL to redirect to after the user has signed in.
1771
+ */
1754
1772
  callbackURL: z.ZodOptional<z.ZodString>;
1755
1773
  /**
1756
1774
  * If this is false, the session will not be remembered
@@ -1704,8 +1704,17 @@ declare const signInEmail: {
1704
1704
  <C extends [better_call.Context<"/sign-in/email", {
1705
1705
  method: "POST";
1706
1706
  body: z.ZodObject<{
1707
+ /**
1708
+ * Email of the user
1709
+ */
1707
1710
  email: z.ZodString;
1711
+ /**
1712
+ * Password of the user
1713
+ */
1708
1714
  password: z.ZodString;
1715
+ /**
1716
+ * Callback URL to redirect to after the user has signed in.
1717
+ */
1709
1718
  callbackURL: z.ZodOptional<z.ZodString>;
1710
1719
  /**
1711
1720
  * If this is false, the session will not be remembered
@@ -1749,8 +1758,17 @@ declare const signInEmail: {
1749
1758
  options: {
1750
1759
  method: "POST";
1751
1760
  body: z.ZodObject<{
1761
+ /**
1762
+ * Email of the user
1763
+ */
1752
1764
  email: z.ZodString;
1765
+ /**
1766
+ * Password of the user
1767
+ */
1753
1768
  password: z.ZodString;
1769
+ /**
1770
+ * Callback URL to redirect to after the user has signed in.
1771
+ */
1754
1772
  callbackURL: z.ZodOptional<z.ZodString>;
1755
1773
  /**
1756
1774
  * If this is false, the session will not be remembered
@@ -2,10 +2,10 @@ import * as nanostores from 'nanostores';
2
2
  import { A as AccessControl, S as StatementsPrimitive, R as Role } from '../statement-BJB0VRQQ.cjs';
3
3
  import * as _better_fetch_fetch from '@better-fetch/fetch';
4
4
  import { BetterFetchOption } from '@better-fetch/fetch';
5
- import { o as organization, q as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, f as anonymous, i as admin, j as genericOAuth, k as jwt, l as multiSession, n as emailOTP } from '../index-CNdeepb4.cjs';
6
- export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-CNdeepb4.cjs';
5
+ import { o as organization, q as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, f as anonymous, i as admin, j as genericOAuth, k as jwt, l as multiSession, n as emailOTP } from '../index-CgOpTl0Z.cjs';
6
+ export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-CgOpTl0Z.cjs';
7
7
  import { P as Prettify } from '../helper-DrEEwdyQ.cjs';
8
- import { F as FieldAttribute, B as BetterAuthOptions, j as BetterAuthPlugin } from '../auth-BuIGx3uf.cjs';
8
+ import { F as FieldAttribute, B as BetterAuthOptions, j as BetterAuthPlugin } from '../auth-Dypsi529.cjs';
9
9
  import { Store } from '../types.cjs';
10
10
  import 'better-call';
11
11
  import 'zod';
@@ -2,10 +2,10 @@ import * as nanostores from 'nanostores';
2
2
  import { A as AccessControl, S as StatementsPrimitive, R as Role } from '../statement-Cu1w5Vf2.js';
3
3
  import * as _better_fetch_fetch from '@better-fetch/fetch';
4
4
  import { BetterFetchOption } from '@better-fetch/fetch';
5
- import { o as organization, q as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, f as anonymous, i as admin, j as genericOAuth, k as jwt, l as multiSession, n as emailOTP } from '../index-CQbHCAKV.js';
6
- export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-CQbHCAKV.js';
5
+ import { o as organization, q as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, f as anonymous, i as admin, j as genericOAuth, k as jwt, l as multiSession, n as emailOTP } from '../index-HDtKSOFR.js';
6
+ export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-HDtKSOFR.js';
7
7
  import { P as Prettify } from '../helper-DrEEwdyQ.js';
8
- import { F as FieldAttribute, B as BetterAuthOptions, j as BetterAuthPlugin } from '../auth-DuGk-eor.js';
8
+ import { F as FieldAttribute, B as BetterAuthOptions, j as BetterAuthPlugin } from '../auth-HkH2WNGO.js';
9
9
  import { Store } from '../types.js';
10
10
  import 'better-call';
11
11
  import 'zod';
package/dist/client.d.cts CHANGED
@@ -6,7 +6,7 @@ import { BetterFetchError, BetterFetch, BetterFetchOption } from '@better-fetch/
6
6
  import { ClientOptions, InferClientAPI, InferActions, InferSessionFromClient, InferUserFromClient, BetterAuthClientPlugin, IsSignal } from './types.cjs';
7
7
  export { AtomListener, InferAdditionalFromClient, InferPluginsFromClient, Store } from './types.cjs';
8
8
  import { U as UnionToIntersection } from './helper-DrEEwdyQ.cjs';
9
- import './auth-BuIGx3uf.cjs';
9
+ import './auth-Dypsi529.cjs';
10
10
  import 'kysely';
11
11
  import 'better-call';
12
12
  import './index-BNVrpPYq.cjs';
package/dist/client.d.ts CHANGED
@@ -6,7 +6,7 @@ import { BetterFetchError, BetterFetch, BetterFetchOption } from '@better-fetch/
6
6
  import { ClientOptions, InferClientAPI, InferActions, InferSessionFromClient, InferUserFromClient, BetterAuthClientPlugin, IsSignal } from './types.js';
7
7
  export { AtomListener, InferAdditionalFromClient, InferPluginsFromClient, Store } from './types.js';
8
8
  import { U as UnionToIntersection } from './helper-DrEEwdyQ.js';
9
- import './auth-DuGk-eor.js';
9
+ import './auth-HkH2WNGO.js';
10
10
  import 'kysely';
11
11
  import 'better-call';
12
12
  import './index-eyp1LeN0.js';
@@ -1,5 +1,5 @@
1
1
  import 'better-call';
2
- export { p as BetterAuthCookies, E as EligibleCookies, n as createCookieGetter, q as deleteSessionCookie, o as getCookies, r as parseCookies, t as parseSetCookieHeader, s as setSessionCookie } from './auth-BuIGx3uf.cjs';
2
+ export { p as BetterAuthCookies, E as EligibleCookies, n as createCookieGetter, q as deleteSessionCookie, o as getCookies, r as parseCookies, t as parseSetCookieHeader, s as setSessionCookie } from './auth-Dypsi529.cjs';
3
3
  import 'kysely';
4
4
  import 'zod';
5
5
  import './helper-DrEEwdyQ.cjs';
package/dist/cookies.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import 'better-call';
2
- export { p as BetterAuthCookies, E as EligibleCookies, n as createCookieGetter, q as deleteSessionCookie, o as getCookies, r as parseCookies, t as parseSetCookieHeader, s as setSessionCookie } from './auth-DuGk-eor.js';
2
+ export { p as BetterAuthCookies, E as EligibleCookies, n as createCookieGetter, q as deleteSessionCookie, o as getCookies, r as parseCookies, t as parseSetCookieHeader, s as setSessionCookie } from './auth-HkH2WNGO.js';
3
3
  import 'kysely';
4
4
  import 'zod';
5
5
  import './helper-DrEEwdyQ.js';
package/dist/db.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { k as Adapter, B as BetterAuthOptions, W as Where, F as FieldAttribute, D as FieldType, K as KyselyDatabaseType } from './auth-BuIGx3uf.cjs';
2
- export { _ as BetterAuthDbSchema, M as FieldAttributeConfig, Z as InferFieldsFromOptions, Y as InferFieldsFromPlugins, T as InferFieldsInput, V as InferFieldsInputClient, Q as InferFieldsOutput, O as InferValueType, L as InternalAdapter, X as PluginFieldAttribute, N as createFieldAttribute, J as createInternalAdapter, $ as getAuthTables } from './auth-BuIGx3uf.cjs';
1
+ import { k as Adapter, B as BetterAuthOptions, W as Where, F as FieldAttribute, D as FieldType, K as KyselyDatabaseType } from './auth-Dypsi529.cjs';
2
+ export { _ as BetterAuthDbSchema, M as FieldAttributeConfig, Z as InferFieldsFromOptions, Y as InferFieldsFromPlugins, T as InferFieldsInput, V as InferFieldsInputClient, Q as InferFieldsOutput, O as InferValueType, L as InternalAdapter, X as PluginFieldAttribute, N as createFieldAttribute, J as createInternalAdapter, $ as getAuthTables } from './auth-Dypsi529.cjs';
3
3
  import { z } from 'zod';
4
4
  import 'kysely';
5
5
  import 'better-call';