better-auth 0.5.2-beta.13 → 0.5.2-beta.15

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