better-auth 0.7.3 → 0.7.4

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 (53) 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 +5 -5
  10. package/dist/api.d.cts +1 -1
  11. package/dist/api.d.ts +1 -1
  12. package/dist/api.js +5 -5
  13. package/dist/{auth-BkJnc76F.d.cts → auth-B5ozNy5X.d.cts} +1 -1
  14. package/dist/{auth-G61_RA8H.d.ts → auth-BBUjEh9D.d.ts} +1 -1
  15. package/dist/client/plugins.d.cts +4 -4
  16. package/dist/client/plugins.d.ts +4 -4
  17. package/dist/client.d.cts +1 -1
  18. package/dist/client.d.ts +1 -1
  19. package/dist/cookies.d.cts +1 -1
  20. package/dist/cookies.d.ts +1 -1
  21. package/dist/db.d.cts +2 -2
  22. package/dist/db.d.ts +2 -2
  23. package/dist/{index-cKD4sHma.d.ts → index-CQluFeIi.d.ts} +2 -2
  24. package/dist/{index-KdWDL1fo.d.cts → index-DK55nobk.d.cts} +2 -2
  25. package/dist/index.cjs +4 -4
  26. package/dist/index.d.cts +2 -2
  27. package/dist/index.d.ts +2 -2
  28. package/dist/index.js +5 -5
  29. package/dist/node.d.cts +1 -1
  30. package/dist/node.d.ts +1 -1
  31. package/dist/oauth2.d.cts +2 -2
  32. package/dist/oauth2.d.ts +2 -2
  33. package/dist/plugins.cjs +6 -6
  34. package/dist/plugins.d.cts +73 -4
  35. package/dist/plugins.d.ts +73 -4
  36. package/dist/plugins.js +6 -6
  37. package/dist/react.d.cts +1 -1
  38. package/dist/react.d.ts +1 -1
  39. package/dist/solid-start.d.cts +1 -1
  40. package/dist/solid-start.d.ts +1 -1
  41. package/dist/solid.d.cts +1 -1
  42. package/dist/solid.d.ts +1 -1
  43. package/dist/{state-UgidHWa5.d.cts → state-8Gh7gmo8.d.cts} +1 -1
  44. package/dist/{state-CTWPRYsC.d.ts → state-BU1iZb12.d.ts} +1 -1
  45. package/dist/svelte-kit.d.cts +1 -1
  46. package/dist/svelte-kit.d.ts +1 -1
  47. package/dist/svelte.d.cts +1 -1
  48. package/dist/svelte.d.ts +1 -1
  49. package/dist/types.d.cts +2 -2
  50. package/dist/types.d.ts +2 -2
  51. package/dist/vue.d.cts +1 -1
  52. package/dist/vue.d.ts +1 -1
  53. package/package.json +1 -1
package/dist/api.js CHANGED
@@ -1,7 +1,7 @@
1
- import{APIError as ot,createRouter as Gt,statusCode as Qt}from"better-call";import{APIError as mt}from"better-call";import{createEndpointCreator as nt,createMiddleware as ie,createMiddlewareCreator as st}from"better-call";var ne=ie(async()=>({})),G=st({use:[ne,ie(async()=>({}))]}),p=nt({use:[ne]});var z={isAction:!1};import{nanoid as at}from"nanoid";var se=e=>at(e);import{generateCodeVerifier as ct,generateState as lt}from"oslo/oauth2";import{z as I}from"zod";import{APIError as ue}from"better-call";var Q=Object.create(null),q=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Q:globalThis),ae=new Proxy(Q,{get(e,t){return q()[t]??Q[t]},has(e,t){let r=q();return t in r||t in Q},set(e,t,r){let o=q(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=q(!0);return delete r[t],!0},ownKeys(){let e=q(!0);return Object.keys(e)}});function dt(e){return e?e!=="false":!1}var X=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var de=X==="dev"||X==="development",ce=X==="test"||dt(ae.TEST);var C=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}};function le(e){try{return new URL(e).origin}catch{return null}}async function H(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?le(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ue("BAD_REQUEST",{message:"callbackURL is required"});let o=ct(),i=lt(),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:s});if(!a)throw f.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ue("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function pe(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw f.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=I.object({callbackURL:I.string(),codeVerifier:I.string(),errorURL:I.string().optional(),expiresAt:I.number(),link:I.object({email:I.string(),userId:I.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),f.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}import{createConsola as ut}from"consola";var D=ut({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),pt=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
- `)}}),f=pt();var me=G(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,i=e.headers?.get("origin")||e.headers?.get("referer")||"",n=t?.callbackURL,s=t?.redirectTo,a=r?.currentURL,l=o.trustedOrigins,d=e.headers?.has("cookie"),c=(g,m)=>{if(!l.some(k=>g?.startsWith(k)||g?.startsWith("/")&&m!=="origin"))throw f.error(`Invalid ${m}: ${g}`),f.info(`If it's a valid URL, please add ${g} to trustedOrigins in your auth config
3
- `,`Current list of trustedOrigins: ${l}`),new mt("FORBIDDEN",{message:`Invalid ${m}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&c(i,"origin"),n&&c(n,"callbackURL"),s&&c(s,"redirectURL"),a&&c(a,"currentURL")});import{APIError as T}from"better-call";import{z as _}from"zod";import{TimeSpan as _r}from"oslo";async function x(e,t,r,o){let i=e.context.authCookies.sessionToken.options;i.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.id,e.context.secret,{...i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&await e.setSignedCookie(e.context.authCookies.sessionData.name,JSON.stringify(t),e.context.secret,e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.id,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function B(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}import{parseJWT as wt}from"oslo/jwt";import{sha256 as ft}from"oslo/crypto";import{base64url as gt}from"oslo/encoding";var V=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function fe(e){let t=await ft(new TextEncoder().encode(e));return gt.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_in?V(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:s,disablePkce:a,redirectURI:l}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||l),!a&&i){let c=await fe(i);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",c)}if(s){let c=s.reduce((g,m)=>(g[m]=null,g),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...c}}))}return d}import{betterFetch as ht}from"@better-fetch/fetch";async function y({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i}){let n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),t&&n.set("code_verifier",t),n.set("redirect_uri",r),n.set("client_id",o.clientId),n.set("client_secret",o.clientSecret);let{data:s,error:a}=await ht(i,{method:"POST",body:n,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(a)throw a;return ge(s)}var he=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=o||["email","name","openid"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>y({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=wt(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 bt}from"@better-fetch/fetch";var we=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.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 bt("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}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 yt}from"@better-fetch/fetch";var be=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,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 yt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});import{betterFetch as ye}from"@better-fetch/fetch";var Ae=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await ye("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:s,error:a}=await ye("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(l=>l.primary)??s[0])?.email,n=s.find(l=>l.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n},data:o}}}};import{parseJWT as At}from"oslo/jwt";var ke=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw f.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new C("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new C("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>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=At(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});import{betterFetch as kt}from"@better-fetch/fetch";import{parseJWT as Rt}from"oslo/jwt";var Re=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),A({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return y({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(!i.idToken)return null;let n=Rt(i.idToken)?.payload,s=e.profilePhotoSize||48;return await kt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let d=await a.response.clone().arrayBuffer(),c=Buffer.from(d).toString("base64");n.picture=`data:image/jpeg;base64, ${c}`}catch(l){f.error(l)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};import{betterFetch as Ut}from"@better-fetch/fetch";var Ue=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},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 Ut("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";import{parseJWT as Et}from"oslo/jwt";var Ee=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,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 f.error("No idToken found in token"),null;let o=Et(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as vt}from"@better-fetch/fetch";var ve=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["account_info.read"];return e.scope&&r.push(...e.scope),A({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>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 vt("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}}});import{betterFetch as _t}from"@better-fetch/fetch";var _e=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await y({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await _t("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return i?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};import{betterFetch as xt}from"@better-fetch/fetch";var xe=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await y({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await xt("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return n?null:{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture},data:i}}}};import{betterFetch as Pt}from"@better-fetch/fetch";var ee=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Tt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ee(`${t}/oauth/authorize`),tokenEndpoint:ee(`${t}/oauth/token`),userinfoEndpoint:ee(`${t}/api/v4/user`)}},Pe=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Tt(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:l,redirectURI:d})=>{let c=a||["read_user"];return e.scope&&c.push(...e.scope),await A({id:i,options:e,authorizationEndpoint:t,scopes:c,state:s,redirectURI:d,codeVerifier:l})},validateAuthorizationCode:async({code:s,redirectURI:a})=>y({code:s,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:l}=await Pt(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return l||a.state!=="active"||a.locked?null:{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0},data:a}}}};var Ot={apple:he,discord:we,facebook:be,github:Ae,microsoft:Re,google:ke,spotify:Ue,twitch:Ee,twitter:ve,dropbox:_e,linkedin:xe,gitlab:Pe},Z=Object.keys(Ot);import{TimeSpan as St}from"oslo";import{createJWT as Lt,validateJWT as It}from"oslo/jwt";import{z as P}from"zod";import{APIError as j}from"better-call";import{APIError as N}from"better-call";import{z as F}from"zod";var te=()=>p("/get-session",{method:"GET",query:F.optional(F.object({disableCookieCache:F.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.getSignedCookie(e.context.authCookies.sessionData.name,e.context.secret),o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(r&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let d=JSON.parse(r)?.session;if(d?.expiresAt>new Date)return e.json(d)}let i=await e.context.internalAdapter.findSession(t);if(!i||i.session.expiresAt<new Date)return B(e),i&&await e.context.internalAdapter.deleteSession(i.session.id),e.json(null,{status:401});if(o)return e.json(i);let n=e.context.sessionConfig.expiresIn,s=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-n*1e3+s*1e3<=Date.now()){let d=await e.context.internalAdapter.updateSession(i.session.id,{expiresAt:V(e.context.sessionConfig.expiresIn,"sec")});if(!d)return B(e),e.json(null,{status:401});let c=(d.expiresAt.valueOf()-Date.now())/1e3;return await x(e,{session:d,user:i.user},!1,{maxAge:c}),e.json({session:d,user:i.user})}return e.json(i)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),re=async e=>await te()({...e,_flag:"json",headers:e.headers}),v=G(async e=>{let t=await re(e);if(!t?.session)throw new N("UNAUTHORIZED");return{session:t}}),Te=()=>p("/list-sessions",{method:"GET",use:[v],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Oe=p("/revoke-session",{method:"POST",body:F.object({id:F.string()}),use:[v],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})}),Se=p("/revoke-sessions",{method:"POST",use:[v],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 S(e,t,r){return await Lt("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new St(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Le=p("/send-verification-email",{method:"POST",query:P.object({currentURL:P.string().optional()}).optional(),body:P.object({email:P.string().email(),callbackURL:P.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new j("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new j("BAD_REQUEST",{message:"User not found"});let o=await S(e.context.secret,t),i=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,i,o),e.json({status:!0})}),Ie=p("/verify-email",{method:"GET",query:P.object({token:P.string(),callbackURL:P.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await It("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new j("BAD_REQUEST",{message:"Invalid token"})}let i=P.object({email:P.string().email(),updateTo:P.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(i.email))throw new j("BAD_REQUEST",{message:"User not found"});if(i.updateTo){let s=await re(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new j("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==i.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new j("UNAUTHORIZED",{message:"Invalid session"});let a=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(a,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var Ce=p("/sign-in/social",{method:"POST",query:_.object({currentURL:_.string().optional()}).optional(),body:_.object({callbackURL:_.string().optional(),provider:_.enum(Z)})},async e=>{let t=e.context.socialProviders.find(n=>n.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 T("NOT_FOUND",{message:"Provider not found"});let{codeVerifier:r,state:o}=await H(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!0})}),De=p("/sign-in/email",{method:"POST",body:_.object({email:_.string(),password:_.string(),callbackURL:_.string().optional(),dontRememberMe:_.boolean().default(!1).optional()})},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new T("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!_.string().email().safeParse(t).success)throw new T("BAD_REQUEST",{message:"Invalid email"});if(!_.string().email().safeParse(t).success)throw new T("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new T("UNAUTHORIZED",{message:"Invalid email or password"});let s=n.accounts.find(c=>c.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new T("UNAUTHORIZED",{message:"Invalid email or password"});let a=s?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new T("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new T("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw f.error("Email verification is required but no email verification handler is provided"),new T("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await S(e.context.secret,n.user.email),g=`${e.context.options.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,g,c),e.context.logger.error("Email not verified",{email:t}),new T("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new T("UNAUTHORIZED",{message:"Failed to create session"});return await x(e,{session:d,user:n.user},e.body.dontRememberMe),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as W}from"zod";import{z as h}from"zod";var Ti=h.object({id:h.string(),providerId:h.string(),accountId:h.string(),userId:h.string(),accessToken:h.string().nullable().optional(),refreshToken:h.string().nullable().optional(),idToken:h.string().nullable().optional(),expiresAt:h.date().nullable().optional(),password:h.string().optional().nullable()}),Be=h.object({id:h.string(),email:h.string().transform(e=>e.toLowerCase()),emailVerified:h.boolean().default(!1),name:h.string(),image:h.string().optional(),createdAt:h.date().default(new Date),updatedAt:h.date().default(new Date)}),Oi=h.object({id:h.string(),userId:h.string(),expiresAt:h.date(),ipAddress:h.string().optional(),userAgent:h.string().optional()}),Si=h.object({id:h.string(),value:h.string(),expiresAt:h.date(),identifier:h.string()});function Ct(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function Dt(e,t){let r=t.action||"create",o=t.fields,i={};for(let n in o){if(n in e){if(o[n].input===!1){if(o[n].defaultValue){i[n]=o[n].defaultValue;continue}continue}i[n]=e[n];continue}if(o[n].defaultValue&&r==="create"){i[n]=o[n].defaultValue;continue}}return i}function J(e,t,r){let o=Ct(e,"user");return Dt(t||{},{fields:o,action:r})}var ze=p("/callback/:id",{method:"GET",query:W.object({state:W.string(),code:W.string().optional(),error:W.string().optional()}),metadata:z},async e=>{if(!e.query.code)throw e.redirect(`${e.context.baseURL}/error?error=${e.query.error||"no_code"}`);let t=e.context.socialProviders.find(w=>w.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{codeVerifier:r,callbackURL:o,link:i,errorURL:n}=await pe(e),s;try{s=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(w){throw e.context.logger.error(w),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(s).then(w=>w?.user),l=se(),d=Be.safeParse({...a,id:l});if(!a||d.success===!1)throw f.error("Unable to get user info",d.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw f.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(i){if(i.email!==a.email.toLowerCase())return c("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:i.userId,providerId:t.id,accountId:a.id}))return c("unable_to_link_account");let b;try{b=new URL(o).toString()}catch{b=o}throw e.redirect(b)}function c(w){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${w}`)}let g=await e.context.internalAdapter.findUserByEmail(a.email,{includeAccounts:!0}).catch(w=>{throw f.error(`Better auth was unable to query your database.
4
- Error: `,w),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),m=g?.user;if(g){let w=g.accounts.find(b=>b.providerId===t.id);if(w)await e.context.internalAdapter.updateAccount(w.id,{accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt});else{(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!a.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)&&(de&&f.warn(`User already exist but account isn't linked to ${t.id}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),c("account_not_linked"));try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:a.id.toString(),id:`${t.id}:${a.id}`,userId:g.user.id,accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt})}catch(oe){f.error("Unable to link account",oe),c("unable_to_link_account")}}}else try{let w=a.emailVerified||!1;if(m=await e.context.internalAdapter.createOAuthUser({...d.data,emailVerified:w},{accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt,providerId:t.id,accountId:a.id.toString()}).then(b=>b?.user),!w&&m&&e.context.options.emailVerification?.sendOnSignUp){let b=await S(e.context.secret,m.email),R=`${e.context.baseURL}/verify-email?token=${b}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(m,R,b)}}catch(w){f.error("Unable to create user",w),c("unable_to_create_user")}if(!m)return c("unable_to_create_user");let u=await e.context.internalAdapter.createSession(m.id,e.request);u||c("unable_to_create_session"),await x(e,{session:u,user:m});let k;try{k=new URL(o).toString()}catch{k=o}throw e.redirect(k)});import"zod";import{APIError as Bt}from"better-call";var Ve=p("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Bt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),B(e),e.json({success:!0})});import{z as O}from"zod";import{APIError as Y}from"better-call";function je(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}function zt(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}var $e=p("/forget-password",{method:"POST",body:O.object({email:O.string().email(),redirectTo:O.string()})},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new Y("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let i=60*60*1,n=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||i)),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:n});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,a),e.json({status:!0})}),qe=p("/reset-password/:token",{method:"GET",query:O.object({callbackURL:O.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(je(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(je(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(zt(e.context,r,{token:t}))}),Ne=p("/reset-password",{query:O.optional(O.object({token:O.string().optional(),currentURL:O.string().optional()})),method:"POST",body:O.object({newPassword:O.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new Y("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,i=await e.context.internalAdapter.findVerificationValue(o);if(!i||i.expiresAt<new Date)throw new Y("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(i.id);let n=i.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(n)).find(c=>c.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(n,s))throw new Y("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as U}from"zod";import{APIError as E}from"better-call";var Fe=()=>p("/update-user",{method:"POST",body:U.record(U.string(),U.any()),use:[v]},async e=>{let t=e.body;if(t.email)throw new E("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...i}=t,n=e.context.session;if(!o&&!r&&Object.keys(i).length===0)return e.json({user:n.user});let s=J(e.context.options,i,"update"),a=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:r,image:o,...s});return await x(e,{session:n.session,user:a}),e.json({user:a})}),Me=p("/change-password",{method:"POST",body:U.object({newPassword:U.string(),currentPassword:U.string(),revokeOtherSessions:U.boolean().optional()}),use:[v]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)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 l=(await e.context.internalAdapter.findAccounts(i.user.id)).find(g=>g.providerId==="credential"&&g.password);if(!l||!l.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify(l.password,r))throw new E("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(l.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(i.user.id);let g=await e.context.internalAdapter.createSession(i.user.id,e.headers);if(!g)throw new E("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await x(e,{session:g,user:i.user})}return e.json(i.user)}),Ge=p("/set-password",{method:"POST",body:U.object({newPassword:U.string()}),metadata:{SERVER_ONLY:!0},use:[v]},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 i=e.context.password.config.maxPasswordLength;if(t.length>i)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(l=>l.providerId==="credential"&&l.password),a=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:a}),e.json(r.user);throw new E("BAD_REQUEST",{message:"user already has a password"})}),Qe=p("/delete-user",{method:"POST",body:U.object({password:U.string()}),use:[v]},async e=>{let{password:t}=e.body,r=e.context.session,i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password);if(!i||!i.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(i.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),B(e),e.json(null)}),He=p("/change-email",{method:"POST",query:U.object({currentURL:U.string().optional()}).optional(),body:U.object({newEmail:U.string().email(),callbackURL:U.string().optional()}),use:[v]},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 i=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:i,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await S(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification(e.context.session.user,e.body.newEmail,o,r),e.json({user:null,status:!0})});var Vt=(e="Unknown")=>`<!DOCTYPE html>
1
+ import{APIError as ot,createRouter as Gt,statusCode as Qt}from"better-call";import{APIError as mt}from"better-call";import{createEndpointCreator as nt,createMiddleware as ie,createMiddlewareCreator as st}from"better-call";var ne=ie(async()=>({})),G=st({use:[ne,ie(async()=>({}))]}),m=nt({use:[ne]});var z={isAction:!1};import{nanoid as at}from"nanoid";var se=e=>at(e);import{generateCodeVerifier as ct,generateState as lt}from"oslo/oauth2";import{z as I}from"zod";import{APIError as ue}from"better-call";var Q=Object.create(null),q=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Q:globalThis),ae=new Proxy(Q,{get(e,t){return q()[t]??Q[t]},has(e,t){let r=q();return t in r||t in Q},set(e,t,r){let o=q(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=q(!0);return delete r[t],!0},ownKeys(){let e=q(!0);return Object.keys(e)}});function dt(e){return e?e!=="false":!1}var X=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var de=X==="dev"||X==="development",ce=X==="test"||dt(ae.TEST);var C=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}};function le(e){try{return new URL(e).origin}catch{return null}}async function H(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?le(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ue("BAD_REQUEST",{message:"callbackURL is required"});let o=ct(),i=lt(),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:s});if(!a)throw f.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ue("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function pe(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw f.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=I.object({callbackURL:I.string(),codeVerifier:I.string(),errorURL:I.string().optional(),expiresAt:I.number(),link:I.object({email:I.string(),userId:I.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),f.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}import{createConsola as ut}from"consola";var D=ut({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),pt=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
+ `)}}),f=pt();var me=G(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,i=e.headers?.get("origin")||e.headers?.get("referer")||"",n=t?.callbackURL||r?.callbackURL,s=t?.redirectTo,a=r?.currentURL,c=o.trustedOrigins,d=e.headers?.has("cookie"),l=(p,u)=>u.includes("*")?new RegExp("^"+u.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(p):p.startsWith(u),g=(p,u)=>{if(!p)return;if(!c.some(h=>l(p,h)||p?.startsWith("/")&&u!=="origin"&&!p.includes(":")))throw f.error(`Invalid ${u}: ${p}`),f.info(`If it's a valid URL, please add ${p} to trustedOrigins in your auth config
3
+ `,`Current list of trustedOrigins: ${c}`),new mt("FORBIDDEN",{message:`Invalid ${u}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&g(i,"origin"),n&&g(n,"callbackURL"),s&&g(s,"redirectURL"),a&&g(a,"currentURL")});import{APIError as T}from"better-call";import{z as _}from"zod";import{TimeSpan as _r}from"oslo";async function x(e,t,r,o){let i=e.context.authCookies.sessionToken.options;i.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.id,e.context.secret,{...i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&await e.setSignedCookie(e.context.authCookies.sessionData.name,JSON.stringify(t),e.context.secret,e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.id,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function B(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}import{parseJWT as wt}from"oslo/jwt";import{sha256 as ft}from"oslo/crypto";import{base64url as gt}from"oslo/encoding";var V=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function fe(e){let t=await ft(new TextEncoder().encode(e));return gt.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_in?V(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:s,disablePkce:a,redirectURI:c}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),!a&&i){let l=await fe(i);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((g,p)=>(g[p]=null,g),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return d}import{betterFetch as ht}from"@better-fetch/fetch";async function y({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i}){let n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),t&&n.set("code_verifier",t),n.set("redirect_uri",r),n.set("client_id",o.clientId),n.set("client_secret",o.clientSecret);let{data:s,error:a}=await ht(i,{method:"POST",body:n,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(a)throw a;return ge(s)}var he=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=o||["email","name","openid"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>y({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=wt(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 bt}from"@better-fetch/fetch";var we=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.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 bt("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}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 yt}from"@better-fetch/fetch";var be=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,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 yt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});import{betterFetch as ye}from"@better-fetch/fetch";var Ae=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await ye("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:s,error:a}=await ye("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(c=>c.primary)??s[0])?.email,n=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:n},data:o}}}};import{parseJWT as At}from"oslo/jwt";var Re=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw f.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new C("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new C("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>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=At(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 Rt}from"@better-fetch/fetch";import{parseJWT as kt}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(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),A({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return y({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(!i.idToken)return null;let n=kt(i.idToken)?.payload,s=e.profilePhotoSize||48;return await Rt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let d=await a.response.clone().arrayBuffer(),l=Buffer.from(d).toString("base64");n.picture=`data:image/jpeg;base64, ${l}`}catch(c){f.error(c)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};import{betterFetch as Ut}from"@better-fetch/fetch";var Ue=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},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 Ut("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";import{parseJWT as Et}from"oslo/jwt";var Ee=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,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 f.error("No idToken found in token"),null;let o=Et(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as vt}from"@better-fetch/fetch";var ve=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["account_info.read"];return e.scope&&r.push(...e.scope),A({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>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 vt("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}}});import{betterFetch as _t}from"@better-fetch/fetch";var _e=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await y({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await _t("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return i?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};import{betterFetch as xt}from"@better-fetch/fetch";var xe=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await y({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await xt("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return n?null:{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture},data:i}}}};import{betterFetch as Pt}from"@better-fetch/fetch";var ee=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Tt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ee(`${t}/oauth/authorize`),tokenEndpoint:ee(`${t}/oauth/token`),userinfoEndpoint:ee(`${t}/api/v4/user`)}},Pe=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Tt(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:c,redirectURI:d})=>{let l=a||["read_user"];return e.scope&&l.push(...e.scope),await A({id:i,options:e,authorizationEndpoint:t,scopes:l,state:s,redirectURI:d,codeVerifier:c})},validateAuthorizationCode:async({code:s,redirectURI:a})=>y({code:s,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:c}=await Pt(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return c||a.state!=="active"||a.locked?null:{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0},data:a}}}};var Ot={apple:he,discord:we,facebook:be,github:Ae,microsoft:ke,google:Re,spotify:Ue,twitch:Ee,twitter:ve,dropbox:_e,linkedin:xe,gitlab:Pe},Z=Object.keys(Ot);import{TimeSpan as St}from"oslo";import{createJWT as Lt,validateJWT as It}from"oslo/jwt";import{z as P}from"zod";import{APIError as j}from"better-call";import{APIError as N}from"better-call";import{z as F}from"zod";var te=()=>m("/get-session",{method:"GET",query:F.optional(F.object({disableCookieCache:F.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.getSignedCookie(e.context.authCookies.sessionData.name,e.context.secret),o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(r&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let d=JSON.parse(r)?.session;if(d?.expiresAt>new Date)return e.json(d)}let i=await e.context.internalAdapter.findSession(t);if(!i||i.session.expiresAt<new Date)return B(e),i&&await e.context.internalAdapter.deleteSession(i.session.id),e.json(null,{status:401});if(o)return e.json(i);let n=e.context.sessionConfig.expiresIn,s=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-n*1e3+s*1e3<=Date.now()){let d=await e.context.internalAdapter.updateSession(i.session.id,{expiresAt:V(e.context.sessionConfig.expiresIn,"sec")});if(!d)return B(e),e.json(null,{status:401});let l=(d.expiresAt.valueOf()-Date.now())/1e3;return await x(e,{session:d,user:i.user},!1,{maxAge:l}),e.json({session:d,user:i.user})}return e.json(i)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),re=async e=>await te()({...e,_flag:"json",headers:e.headers}),v=G(async e=>{let t=await re(e);if(!t?.session)throw new N("UNAUTHORIZED");return{session:t}}),Te=()=>m("/list-sessions",{method:"GET",use:[v],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Oe=m("/revoke-session",{method:"POST",body:F.object({id:F.string()}),use:[v],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})}),Se=m("/revoke-sessions",{method:"POST",use:[v],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 S(e,t,r){return await Lt("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new St(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Le=m("/send-verification-email",{method:"POST",query:P.object({currentURL:P.string().optional()}).optional(),body:P.object({email:P.string().email(),callbackURL:P.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new j("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new j("BAD_REQUEST",{message:"User not found"});let o=await S(e.context.secret,t),i=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,i,o),e.json({status:!0})}),Ie=m("/verify-email",{method:"GET",query:P.object({token:P.string(),callbackURL:P.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await It("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new j("BAD_REQUEST",{message:"Invalid token"})}let i=P.object({email:P.string().email(),updateTo:P.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(i.email))throw new j("BAD_REQUEST",{message:"User not found"});if(i.updateTo){let s=await re(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new j("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==i.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new j("UNAUTHORIZED",{message:"Invalid session"});let a=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(a,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var Ce=m("/sign-in/social",{method:"POST",query:_.object({currentURL:_.string().optional()}).optional(),body:_.object({callbackURL:_.string().optional(),provider:_.enum(Z)})},async e=>{let t=e.context.socialProviders.find(n=>n.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 T("NOT_FOUND",{message:"Provider not found"});let{codeVerifier:r,state:o}=await H(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!0})}),De=m("/sign-in/email",{method:"POST",body:_.object({email:_.string(),password:_.string(),callbackURL:_.string().optional(),dontRememberMe:_.boolean().default(!1).optional()})},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new T("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!_.string().email().safeParse(t).success)throw new T("BAD_REQUEST",{message:"Invalid email"});if(!_.string().email().safeParse(t).success)throw new T("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new T("UNAUTHORIZED",{message:"Invalid email or password"});let s=n.accounts.find(l=>l.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new T("UNAUTHORIZED",{message:"Invalid email or password"});let a=s?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new T("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new T("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw f.error("Email verification is required but no email verification handler is provided"),new T("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let l=await S(e.context.secret,n.user.email),g=`${e.context.options.baseURL}/verify-email?token=${l}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,g,l),e.context.logger.error("Email not verified",{email:t}),new T("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new T("UNAUTHORIZED",{message:"Failed to create session"});return await x(e,{session:d,user:n.user},e.body.dontRememberMe),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as W}from"zod";import{z as w}from"zod";var Ti=w.object({id:w.string(),providerId:w.string(),accountId:w.string(),userId:w.string(),accessToken:w.string().nullable().optional(),refreshToken:w.string().nullable().optional(),idToken:w.string().nullable().optional(),expiresAt:w.date().nullable().optional(),password:w.string().optional().nullable()}),Be=w.object({id:w.string(),email:w.string().transform(e=>e.toLowerCase()),emailVerified:w.boolean().default(!1),name:w.string(),image:w.string().optional(),createdAt:w.date().default(new Date),updatedAt:w.date().default(new Date)}),Oi=w.object({id:w.string(),userId:w.string(),expiresAt:w.date(),ipAddress:w.string().optional(),userAgent:w.string().optional()}),Si=w.object({id:w.string(),value:w.string(),expiresAt:w.date(),identifier:w.string()});function Ct(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function Dt(e,t){let r=t.action||"create",o=t.fields,i={};for(let n in o){if(n in e){if(o[n].input===!1){if(o[n].defaultValue){i[n]=o[n].defaultValue;continue}continue}i[n]=e[n];continue}if(o[n].defaultValue&&r==="create"){i[n]=o[n].defaultValue;continue}}return i}function J(e,t,r){let o=Ct(e,"user");return Dt(t||{},{fields:o,action:r})}var ze=m("/callback/:id",{method:"GET",query:W.object({state:W.string(),code:W.string().optional(),error:W.string().optional()}),metadata:z},async e=>{if(!e.query.code)throw e.redirect(`${e.context.baseURL}/error?error=${e.query.error||"no_code"}`);let t=e.context.socialProviders.find(h=>h.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{codeVerifier:r,callbackURL:o,link:i,errorURL:n}=await pe(e),s;try{s=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(h){throw e.context.logger.error(h),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(s).then(h=>h?.user),c=se(),d=Be.safeParse({...a,id:c});if(!a||d.success===!1)throw f.error("Unable to get user info",d.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw f.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(i){if(i.email!==a.email.toLowerCase())return l("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:i.userId,providerId:t.id,accountId:a.id}))return l("unable_to_link_account");let b;try{b=new URL(o).toString()}catch{b=o}throw e.redirect(b)}function l(h){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${h}`)}let g=await e.context.internalAdapter.findUserByEmail(a.email,{includeAccounts:!0}).catch(h=>{throw f.error(`Better auth was unable to query your database.
4
+ Error: `,h),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),p=g?.user;if(g){let h=g.accounts.find(b=>b.providerId===t.id);if(h)await e.context.internalAdapter.updateAccount(h.id,{accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt});else{(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!a.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)&&(de&&f.warn(`User already exist but account isn't linked to ${t.id}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),l("account_not_linked"));try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:a.id.toString(),id:`${t.id}:${a.id}`,userId:g.user.id,accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt})}catch(oe){f.error("Unable to link account",oe),l("unable_to_link_account")}}}else try{let h=a.emailVerified||!1;if(p=await e.context.internalAdapter.createOAuthUser({...d.data,emailVerified:h},{accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt,providerId:t.id,accountId:a.id.toString()}).then(b=>b?.user),!h&&p&&e.context.options.emailVerification?.sendOnSignUp){let b=await S(e.context.secret,p.email),k=`${e.context.baseURL}/verify-email?token=${b}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(p,k,b)}}catch(h){f.error("Unable to create user",h),l("unable_to_create_user")}if(!p)return l("unable_to_create_user");let u=await e.context.internalAdapter.createSession(p.id,e.request);u||l("unable_to_create_session"),await x(e,{session:u,user:p});let R;try{R=new URL(o).toString()}catch{R=o}throw e.redirect(R)});import"zod";import{APIError as Bt}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 Bt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),B(e),e.json({success:!0})});import{z as O}from"zod";import{APIError as Y}from"better-call";function je(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}function zt(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}var $e=m("/forget-password",{method:"POST",body:O.object({email:O.string().email(),redirectTo:O.string()})},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new Y("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let i=60*60*1,n=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||i)),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:n});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,a),e.json({status:!0})}),qe=m("/reset-password/:token",{method:"GET",query:O.object({callbackURL:O.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(je(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(je(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(zt(e.context,r,{token:t}))}),Ne=m("/reset-password",{query:O.optional(O.object({token:O.string().optional(),currentURL:O.string().optional()})),method:"POST",body:O.object({newPassword:O.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new Y("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,i=await e.context.internalAdapter.findVerificationValue(o);if(!i||i.expiresAt<new Date)throw new Y("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(i.id);let n=i.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(n)).find(l=>l.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(n,s))throw new Y("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as U}from"zod";import{APIError as E}from"better-call";var Fe=()=>m("/update-user",{method:"POST",body:U.record(U.string(),U.any()),use:[v]},async e=>{let t=e.body;if(t.email)throw new E("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...i}=t,n=e.context.session;if(!o&&!r&&Object.keys(i).length===0)return e.json({user:n.user});let s=J(e.context.options,i,"update"),a=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:r,image:o,...s});return await x(e,{session:n.session,user:a}),e.json({user:a})}),Me=m("/change-password",{method:"POST",body:U.object({newPassword:U.string(),currentPassword:U.string(),revokeOtherSessions:U.boolean().optional()}),use:[v]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)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(i.user.id)).find(g=>g.providerId==="credential"&&g.password);if(!c||!c.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});let d=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:d}),o){await e.context.internalAdapter.deleteSessions(i.user.id);let g=await e.context.internalAdapter.createSession(i.user.id,e.headers);if(!g)throw new E("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await x(e,{session:g,user:i.user})}return e.json(i.user)}),Ge=m("/set-password",{method:"POST",body:U.object({newPassword:U.string()}),metadata:{SERVER_ONLY:!0},use:[v]},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 i=e.context.password.config.maxPasswordLength;if(t.length>i)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),a=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:a}),e.json(r.user);throw new E("BAD_REQUEST",{message:"user already has a password"})}),Qe=m("/delete-user",{method:"POST",body:U.object({password:U.string()}),use:[v]},async e=>{let{password:t}=e.body,r=e.context.session,i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password);if(!i||!i.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(i.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),B(e),e.json(null)}),He=m("/change-email",{method:"POST",query:U.object({currentURL:U.string().optional()}).optional(),body:U.object({newEmail:U.string().email(),callbackURL:U.string().optional()}),use:[v]},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 i=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:i,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await S(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification(e.context.session.user,e.body.newEmail,o,r),e.json({user:null,status:!0})});var Vt=(e="Unknown")=>`<!DOCTYPE html>
5
5
  <html lang="en">
6
6
  <head>
7
7
  <meta charset="UTF-8">
@@ -81,4 +81,4 @@ Error: `,w),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
81
81
  <div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
82
82
  </div>
83
83
  </body>
84
- </html>`,Ze=p("/error",{method:"GET",metadata:z},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Vt(t),{headers:{"Content-Type":"text/html"}})});var Je=p("/ok",{method:"GET",metadata:z},async e=>e.json({ok:!0}));import{z as $}from"zod";import{APIError as L}from"better-call";var We=()=>p("/sign-up/email",{method:"POST",query:$.object({currentURL:$.string().optional()}).optional(),body:$.record($.string(),$.any())},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new L("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:i,image:n,callbackURL:s,...a}=t;if(!$.string().email().safeParse(o).success)throw new L("BAD_REQUEST",{message:"Invalid email"});let d=e.context.password.config.minPasswordLength;if(i.length<d)throw e.context.logger.error("Password is too short"),new L("BAD_REQUEST",{message:"Password is too short"});let c=e.context.password.config.maxPasswordLength;if(i.length>c)throw e.context.logger.error("Password is too long"),new L("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 L("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let m=J(e.context.options,a),u;try{if(u=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:n,...m,emailVerified:!1}),!u)throw new L("BAD_REQUEST",{message:"Failed to create user"})}catch(b){throw f.error("Failed to create user",b),new L("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:b})}if(!u)throw new L("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let k=await e.context.password.hash(i);if(await e.context.internalAdapter.linkAccount({userId:u.id,providerId:"credential",accountId:u.id,password:k,expiresAt:V(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let b=await S(e.context.secret,u.email),R=`${e.context.baseURL}/verify-email?token=${b}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(u,R,b)}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 w=await e.context.internalAdapter.createSession(u.id,e.request);if(!w)throw new L("BAD_REQUEST",{message:"Failed to create session"});return await x(e,{session:w,user:u}),e.json({user:u,session:w})});import{z as M}from"zod";import{APIError as Ye}from"better-call";var Ke=p("/list-accounts",{method:"GET",use:[v]},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r)}),Xe=p("/link-social",{method:"POST",requireHeaders:!0,query:M.object({currentURL:M.string().optional()}).optional(),body:M.object({callbackURL:M.string().optional(),provider:M.enum(Z)}),use:[v]},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(a=>a.providerId===e.body.provider))throw new Ye("BAD_REQUEST",{message:"Social Account is already linked."});let i=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Ye("NOT_FOUND",{message:"Provider not found"});let n=await H(e,{userId:t.user.id,email:t.user.email}),s=await i.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:s.toString(),redirect:!0})});function et(e){let t="127.0.0.1";if(ce)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 i of r){let n=o.get(i);if(typeof n=="string"){let s=n.split(",")[0].trim();if(s)return s}}return null}function jt(e,t,r){let o=Date.now(),i=t*1e3;return o-r.lastRequest<i&&r.count>=e}function $t(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":e.toString()}})}function qt(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function Nt(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async i=>await o.findOne({model:r,where:[{field:"key",value:i}]}),set:async(i,n,s)=>{try{s?await o.update({model:t??"rateLimit",where:[{field:"key",value:i}],update:{count:n.count,lastRequest:n.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:i,count:n.count,lastRequest:n.lastRequest}})}catch(a){f.error("Error setting rate limit",a)}}}}var tt=new Map;function Ft(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 tt.get(r)},async set(r,o,i){tt.set(r,o)}}:Nt(e,e.rateLimit.tableName)}async function rt(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),i=t.rateLimit.window,n=t.rateLimit.max,s=et(e)+o,l=Mt().find(m=>m.pathMatcher(o));l&&(i=l.window,n=l.max);for(let m of t.options.plugins||[])if(m.rateLimit){let u=m.rateLimit.find(k=>k.pathMatcher(o));if(u){i=u.window,n=u.max;break}}if(t.rateLimit.customRules){let m=t.rateLimit.customRules[o];m&&(i=m.window,n=m.max)}let d=Ft(t),c=await d.get(s),g=Date.now();if(!c)await d.set(s,{key:s,count:1,lastRequest:g});else{let m=g-c.lastRequest;if(jt(n,i,c)){let u=qt(c.lastRequest,i);return $t(u)}else m>i*1e3?await d.set(s,{...c,count:1,lastRequest:g}):await d.set(s,{...c,count:c.count+1,lastRequest:g})}}function Mt(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:3}]}import{APIError as hs}from"better-call";function Ht(e,t){let r=t.plugins?.reduce((a,l)=>({...a,...l.endpoints}),{}),o=t.plugins?.map(a=>a.middlewares?.map(l=>{let d=async c=>l.middleware({...c,context:{...e,...c.context}});return d.path=l.path,d.options=l.middleware.options,d.headers=l.middleware.headers,{path:l.path,middleware:d}})).filter(a=>a!==void 0).flat()||[],n={...{signInSocial:Ce,callbackOAuth:ze,getSession:te(),signOut:Ve,signUpEmail:We(),signInEmail:De,forgetPassword:$e,resetPassword:Ne,verifyEmail:Ie,sendVerificationEmail:Le,changeEmail:He,changePassword:Me,setPassword:Ge,updateUser:Fe(),deleteUser:Qe,forgetPasswordCallback:qe,listSessions:Te(),revokeSession:Oe,revokeSessions:Se,linkSocialAccount:Xe,listUserAccounts:Ke},...r,ok:Je,error:Ze},s={};for(let[a,l]of Object.entries(n))s[a]=async(d={})=>{let c=await e;for(let u of t.plugins||[])if(u.hooks?.before){for(let k of u.hooks.before)if(k.matcher({...l,...d,context:c})){let b=await k.handler({...d,context:{...c,...d?.context}});b&&"context"in b&&(c={...c,...b.context})}}let g;try{g=await l({...d,context:{...c,...d.context}})}catch(u){if(u instanceof ot){let k=t.plugins?.map(R=>{if(R.hooks?.after)return R.hooks.after}).filter(R=>R!==void 0).flat();if(!k?.length)throw u;let w=new Response(JSON.stringify(u.body),{status:Qt[u.status],headers:u.headers}),b;for(let R of k||[])if(R.matcher(d)){let it=Object.assign(d,{context:{...e,returned:w}}),K=await R.handler(it);K&&"response"in K&&(b=K.response)}if(b instanceof Response)return b;throw u}throw u}let m=g;for(let u of t.plugins||[])if(u.hooks?.after){for(let k of u.hooks.after)if(k.matcher(d)){let b=Object.assign(d,{context:{...e,returned:m}}),R=await k.handler(b);R&&"response"in R&&(m=R.response)}}return m},s[a].path=l.path,s[a].method=l.method,s[a].options=l.options,s[a].headers=l.headers;return{api:s,middlewares:o}}var ls=(e,t)=>{let{api:r,middlewares:o}=Ht(e,t),i=new URL(e.baseURL).pathname;return Gt(r,{extraContext:e,basePath:i,routerMiddleware:[{path:"/**",middleware:me},...o],async onRequest(n){for(let s of e.options.plugins||[])if(s.onRequest){let a=await s.onRequest(n,e);if(a)return a}return rt(n,e)},async onResponse(n){for(let s of e.options.plugins||[])if(s.onResponse){let a=await s.onResponse(n,e);if(a)return a.response}return n},onError(n){if(t.onAPIError?.throw)throw n;if(t.onAPIError?.onError){t.onAPIError.onError(n,e);return}let s=t.logger?.verboseLogging?f:void 0;t.logger?.disabled!==!0&&(n instanceof ot?(n.status==="INTERNAL_SERVER_ERROR"&&f.error(n),s?.error(n.message)):f?.error(n))}})};export{hs as APIError,ze as callbackOAuth,He as changeEmail,Me as changePassword,p as createAuthEndpoint,G as createAuthMiddleware,S as createEmailVerificationToken,Qe as deleteUser,Ze as error,$e as forgetPassword,qe as forgetPasswordCallback,Ht as getEndpoints,te as getSession,re as getSessionFromCtx,Xe as linkSocialAccount,Te as listSessions,Ke as listUserAccounts,Je as ok,ne as optionsMiddleware,me as originCheckMiddleware,Ne as resetPassword,Oe as revokeSession,Se as revokeSessions,ls as router,Le as sendVerificationEmail,v as sessionMiddleware,Ge as setPassword,De as signInEmail,Ce as signInSocial,Ve as signOut,We as signUpEmail,Fe as updateUser,Ie as verifyEmail};
84
+ </html>`,Ze=m("/error",{method:"GET",metadata:z},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Vt(t),{headers:{"Content-Type":"text/html"}})});var Je=m("/ok",{method:"GET",metadata:z},async e=>e.json({ok:!0}));import{z as $}from"zod";import{APIError as L}from"better-call";var We=()=>m("/sign-up/email",{method:"POST",query:$.object({currentURL:$.string().optional()}).optional(),body:$.record($.string(),$.any())},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new L("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:i,image:n,callbackURL:s,...a}=t;if(!$.string().email().safeParse(o).success)throw new L("BAD_REQUEST",{message:"Invalid email"});let d=e.context.password.config.minPasswordLength;if(i.length<d)throw e.context.logger.error("Password is too short"),new L("BAD_REQUEST",{message:"Password is too short"});let l=e.context.password.config.maxPasswordLength;if(i.length>l)throw e.context.logger.error("Password is too long"),new L("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 L("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let p=J(e.context.options,a),u;try{if(u=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:n,...p,emailVerified:!1}),!u)throw new L("BAD_REQUEST",{message:"Failed to create user"})}catch(b){throw f.error("Failed to create user",b),new L("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:b})}if(!u)throw new L("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let R=await e.context.password.hash(i);if(await e.context.internalAdapter.linkAccount({userId:u.id,providerId:"credential",accountId:u.id,password:R,expiresAt:V(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let b=await S(e.context.secret,u.email),k=`${e.context.baseURL}/verify-email?token=${b}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(u,k,b)}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 h=await e.context.internalAdapter.createSession(u.id,e.request);if(!h)throw new L("BAD_REQUEST",{message:"Failed to create session"});return await x(e,{session:h,user:u}),e.json({user:u,session:h})});import{z as M}from"zod";import{APIError as Ye}from"better-call";var Ke=m("/list-accounts",{method:"GET",use:[v]},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r)}),Xe=m("/link-social",{method:"POST",requireHeaders:!0,query:M.object({currentURL:M.string().optional()}).optional(),body:M.object({callbackURL:M.string().optional(),provider:M.enum(Z)}),use:[v]},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(a=>a.providerId===e.body.provider))throw new Ye("BAD_REQUEST",{message:"Social Account is already linked."});let i=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Ye("NOT_FOUND",{message:"Provider not found"});let n=await H(e,{userId:t.user.id,email:t.user.email}),s=await i.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:s.toString(),redirect:!0})});function et(e){let t="127.0.0.1";if(ce)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 i of r){let n=o.get(i);if(typeof n=="string"){let s=n.split(",")[0].trim();if(s)return s}}return null}function jt(e,t,r){let o=Date.now(),i=t*1e3;return o-r.lastRequest<i&&r.count>=e}function $t(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":e.toString()}})}function qt(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function Nt(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async i=>await o.findOne({model:r,where:[{field:"key",value:i}]}),set:async(i,n,s)=>{try{s?await o.update({model:t??"rateLimit",where:[{field:"key",value:i}],update:{count:n.count,lastRequest:n.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:i,count:n.count,lastRequest:n.lastRequest}})}catch(a){f.error("Error setting rate limit",a)}}}}var tt=new Map;function Ft(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 tt.get(r)},async set(r,o,i){tt.set(r,o)}}:Nt(e,e.rateLimit.tableName)}async function rt(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),i=t.rateLimit.window,n=t.rateLimit.max,s=et(e)+o,c=Mt().find(p=>p.pathMatcher(o));c&&(i=c.window,n=c.max);for(let p of t.options.plugins||[])if(p.rateLimit){let u=p.rateLimit.find(R=>R.pathMatcher(o));if(u){i=u.window,n=u.max;break}}if(t.rateLimit.customRules){let p=t.rateLimit.customRules[o];p&&(i=p.window,n=p.max)}let d=Ft(t),l=await d.get(s),g=Date.now();if(!l)await d.set(s,{key:s,count:1,lastRequest:g});else{let p=g-l.lastRequest;if(jt(n,i,l)){let u=qt(l.lastRequest,i);return $t(u)}else p>i*1e3?await d.set(s,{...l,count:1,lastRequest:g}):await d.set(s,{...l,count:l.count+1,lastRequest:g})}}function Mt(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:3}]}import{APIError as hs}from"better-call";function Ht(e,t){let r=t.plugins?.reduce((a,c)=>({...a,...c.endpoints}),{}),o=t.plugins?.map(a=>a.middlewares?.map(c=>{let d=async l=>c.middleware({...l,context:{...e,...l.context}});return d.path=c.path,d.options=c.middleware.options,d.headers=c.middleware.headers,{path:c.path,middleware:d}})).filter(a=>a!==void 0).flat()||[],n={...{signInSocial:Ce,callbackOAuth:ze,getSession:te(),signOut:Ve,signUpEmail:We(),signInEmail:De,forgetPassword:$e,resetPassword:Ne,verifyEmail:Ie,sendVerificationEmail:Le,changeEmail:He,changePassword:Me,setPassword:Ge,updateUser:Fe(),deleteUser:Qe,forgetPasswordCallback:qe,listSessions:Te(),revokeSession:Oe,revokeSessions:Se,linkSocialAccount:Xe,listUserAccounts:Ke},...r,ok:Je,error:Ze},s={};for(let[a,c]of Object.entries(n))s[a]=async(d={})=>{let l=await e;for(let u of t.plugins||[])if(u.hooks?.before){for(let R of u.hooks.before)if(R.matcher({...c,...d,context:l})){let b=await R.handler({...d,context:{...l,...d?.context}});b&&"context"in b&&(l={...l,...b.context})}}let g;try{g=await c({...d,context:{...l,...d.context}})}catch(u){if(u instanceof ot){let R=t.plugins?.map(k=>{if(k.hooks?.after)return k.hooks.after}).filter(k=>k!==void 0).flat();if(!R?.length)throw u;let h=new Response(JSON.stringify(u.body),{status:Qt[u.status],headers:u.headers}),b;for(let k of R||[])if(k.matcher(d)){let it=Object.assign(d,{context:{...e,returned:h}}),K=await k.handler(it);K&&"response"in K&&(b=K.response)}if(b instanceof Response)return b;throw u}throw u}let p=g;for(let u of t.plugins||[])if(u.hooks?.after){for(let R of u.hooks.after)if(R.matcher(d)){let b=Object.assign(d,{context:{...e,returned:p}}),k=await R.handler(b);k&&"response"in k&&(p=k.response)}}return p},s[a].path=c.path,s[a].method=c.method,s[a].options=c.options,s[a].headers=c.headers;return{api:s,middlewares:o}}var ls=(e,t)=>{let{api:r,middlewares:o}=Ht(e,t),i=new URL(e.baseURL).pathname;return Gt(r,{extraContext:e,basePath:i,routerMiddleware:[{path:"/**",middleware:me},...o],async onRequest(n){for(let s of e.options.plugins||[])if(s.onRequest){let a=await s.onRequest(n,e);if(a)return a}return rt(n,e)},async onResponse(n){for(let s of e.options.plugins||[])if(s.onResponse){let a=await s.onResponse(n,e);if(a)return a.response}return n},onError(n){if(t.onAPIError?.throw)throw n;if(t.onAPIError?.onError){t.onAPIError.onError(n,e);return}let s=t.logger?.verboseLogging?f:void 0;t.logger?.disabled!==!0&&(n instanceof ot?(n.status==="INTERNAL_SERVER_ERROR"&&f.error(n),s?.error(n.message)):f?.error(n))}})};export{hs as APIError,ze as callbackOAuth,He as changeEmail,Me as changePassword,m as createAuthEndpoint,G as createAuthMiddleware,S as createEmailVerificationToken,Qe as deleteUser,Ze as error,$e as forgetPassword,qe as forgetPasswordCallback,Ht as getEndpoints,te as getSession,re as getSessionFromCtx,Xe as linkSocialAccount,Te as listSessions,Ke as listUserAccounts,Je as ok,ne as optionsMiddleware,me as originCheckMiddleware,Ne as resetPassword,Oe as revokeSession,Se as revokeSessions,ls as router,Le as sendVerificationEmail,v as sessionMiddleware,Ge as setPassword,De as signInEmail,Ce as signInSocial,Ve as signOut,We as signUpEmail,Fe as updateUser,Ie as verifyEmail};
@@ -6949,4 +6949,4 @@ type Auth = {
6949
6949
  options: BetterAuthOptions;
6950
6950
  };
6951
6951
 
6952
- export { signInSocial as $, type Adapter as A, type BetterAuthOptions as B, createInternalAdapter as C, type InternalAdapter as D, type EligibleCookies as E, type FieldAttribute as F, type GenericEndpointContext as G, type HookEndpointContext as H, type InferUser as I, type FieldAttributeConfig as J, type KyselyDatabaseType as K, createFieldAttribute as L, type InferValueType as M, type InferFieldsOutput as N, type InferFieldsInput as O, type PluginSchema as P, type InferFieldsInputClient as Q, type RateLimit as R, type SecondaryStorage as S, type PluginFieldAttribute as T, type InferFieldsFromPlugins as U, type InferFieldsFromOptions as V, type Where as W, type BetterAuthDbSchema as X, getAuthTables as Y, getEndpoints as Z, router as _, type Auth as a, signInEmail as a0, callbackOAuth as a1, getSession as a2, getSessionFromCtx as a3, sessionMiddleware as a4, listSessions as a5, revokeSession as a6, revokeSessions as a7, signOut as a8, forgetPassword as a9, forgetPasswordCallback as aa, resetPassword as ab, createEmailVerificationToken as ac, sendVerificationEmail as ad, verifyEmail as ae, updateUser as af, changePassword as ag, setPassword as ah, deleteUser as ai, changeEmail as aj, error as ak, ok as al, signUpEmail as am, listUserAccounts as an, linkSocialAccount as ao, originCheckMiddleware as ap, type BetterAuthPlugin as b, createAuthMiddleware as c, createAuthEndpoint as d, type AuthEndpoint as e, type AuthMiddleware as f, betterAuth as g, type AdditionalUserFieldsInput as h, type AdditionalUserFieldsOutput as i, type AdditionalSessionFieldsInput as j, type AdditionalSessionFieldsOutput as k, type InferSession as l, type InferPluginTypes as m, init as n, optionsMiddleware as o, type AuthContext as p, createCookieGetter as q, getCookies as r, type BetterAuthCookies as s, setSessionCookie as t, deleteSessionCookie as u, parseSetCookieHeader as v, parseCookies as w, createLogger as x, logger as y, type FieldType as z };
6952
+ export { signInSocial as $, type Adapter as A, type BetterAuthOptions as B, createInternalAdapter as C, type InternalAdapter as D, type EligibleCookies as E, type FieldAttribute as F, type GenericEndpointContext as G, type HookEndpointContext as H, type InferUser as I, type FieldAttributeConfig as J, type KyselyDatabaseType as K, createFieldAttribute as L, type InferValueType as M, type InferFieldsOutput as N, type InferFieldsInput as O, type PluginSchema as P, type InferFieldsInputClient as Q, type RateLimit as R, type SecondaryStorage as S, type PluginFieldAttribute as T, type InferFieldsFromPlugins as U, type InferFieldsFromOptions as V, type Where as W, type BetterAuthDbSchema as X, getAuthTables as Y, getEndpoints as Z, router as _, type Auth as a, signInEmail as a0, callbackOAuth as a1, getSession as a2, getSessionFromCtx as a3, sessionMiddleware as a4, listSessions as a5, revokeSession as a6, revokeSessions as a7, signOut as a8, forgetPassword as a9, forgetPasswordCallback as aa, resetPassword as ab, createEmailVerificationToken as ac, sendVerificationEmail as ad, verifyEmail as ae, updateUser as af, changePassword as ag, setPassword as ah, deleteUser as ai, changeEmail as aj, error as ak, ok as al, signUpEmail as am, listUserAccounts as an, linkSocialAccount as ao, originCheckMiddleware as ap, betterAuth as b, type AdditionalUserFieldsInput as c, type AdditionalUserFieldsOutput as d, type AdditionalSessionFieldsInput as e, type AdditionalSessionFieldsOutput as f, type InferSession as g, type InferPluginTypes as h, init as i, type AuthContext as j, type BetterAuthPlugin as k, createCookieGetter as l, getCookies as m, type BetterAuthCookies as n, deleteSessionCookie as o, parseSetCookieHeader as p, parseCookies as q, createLogger as r, setSessionCookie as s, logger as t, optionsMiddleware as u, createAuthMiddleware as v, createAuthEndpoint as w, type AuthEndpoint as x, type AuthMiddleware as y, type FieldType as z };
@@ -6949,4 +6949,4 @@ type Auth = {
6949
6949
  options: BetterAuthOptions;
6950
6950
  };
6951
6951
 
6952
- export { signInSocial as $, type Adapter as A, type BetterAuthOptions as B, createInternalAdapter as C, type InternalAdapter as D, type EligibleCookies as E, type FieldAttribute as F, type GenericEndpointContext as G, type HookEndpointContext as H, type InferUser as I, type FieldAttributeConfig as J, type KyselyDatabaseType as K, createFieldAttribute as L, type InferValueType as M, type InferFieldsOutput as N, type InferFieldsInput as O, type PluginSchema as P, type InferFieldsInputClient as Q, type RateLimit as R, type SecondaryStorage as S, type PluginFieldAttribute as T, type InferFieldsFromPlugins as U, type InferFieldsFromOptions as V, type Where as W, type BetterAuthDbSchema as X, getAuthTables as Y, getEndpoints as Z, router as _, type Auth as a, signInEmail as a0, callbackOAuth as a1, getSession as a2, getSessionFromCtx as a3, sessionMiddleware as a4, listSessions as a5, revokeSession as a6, revokeSessions as a7, signOut as a8, forgetPassword as a9, forgetPasswordCallback as aa, resetPassword as ab, createEmailVerificationToken as ac, sendVerificationEmail as ad, verifyEmail as ae, updateUser as af, changePassword as ag, setPassword as ah, deleteUser as ai, changeEmail as aj, error as ak, ok as al, signUpEmail as am, listUserAccounts as an, linkSocialAccount as ao, originCheckMiddleware as ap, type BetterAuthPlugin as b, createAuthMiddleware as c, createAuthEndpoint as d, type AuthEndpoint as e, type AuthMiddleware as f, betterAuth as g, type AdditionalUserFieldsInput as h, type AdditionalUserFieldsOutput as i, type AdditionalSessionFieldsInput as j, type AdditionalSessionFieldsOutput as k, type InferSession as l, type InferPluginTypes as m, init as n, optionsMiddleware as o, type AuthContext as p, createCookieGetter as q, getCookies as r, type BetterAuthCookies as s, setSessionCookie as t, deleteSessionCookie as u, parseSetCookieHeader as v, parseCookies as w, createLogger as x, logger as y, type FieldType as z };
6952
+ export { signInSocial as $, type Adapter as A, type BetterAuthOptions as B, createInternalAdapter as C, type InternalAdapter as D, type EligibleCookies as E, type FieldAttribute as F, type GenericEndpointContext as G, type HookEndpointContext as H, type InferUser as I, type FieldAttributeConfig as J, type KyselyDatabaseType as K, createFieldAttribute as L, type InferValueType as M, type InferFieldsOutput as N, type InferFieldsInput as O, type PluginSchema as P, type InferFieldsInputClient as Q, type RateLimit as R, type SecondaryStorage as S, type PluginFieldAttribute as T, type InferFieldsFromPlugins as U, type InferFieldsFromOptions as V, type Where as W, type BetterAuthDbSchema as X, getAuthTables as Y, getEndpoints as Z, router as _, type Auth as a, signInEmail as a0, callbackOAuth as a1, getSession as a2, getSessionFromCtx as a3, sessionMiddleware as a4, listSessions as a5, revokeSession as a6, revokeSessions as a7, signOut as a8, forgetPassword as a9, forgetPasswordCallback as aa, resetPassword as ab, createEmailVerificationToken as ac, sendVerificationEmail as ad, verifyEmail as ae, updateUser as af, changePassword as ag, setPassword as ah, deleteUser as ai, changeEmail as aj, error as ak, ok as al, signUpEmail as am, listUserAccounts as an, linkSocialAccount as ao, originCheckMiddleware as ap, betterAuth as b, type AdditionalUserFieldsInput as c, type AdditionalUserFieldsOutput as d, type AdditionalSessionFieldsInput as e, type AdditionalSessionFieldsOutput as f, type InferSession as g, type InferPluginTypes as h, init as i, type AuthContext as j, type BetterAuthPlugin as k, createCookieGetter as l, getCookies as m, type BetterAuthCookies as n, deleteSessionCookie as o, parseSetCookieHeader as p, parseCookies as q, createLogger as r, setSessionCookie as s, logger as t, optionsMiddleware as u, createAuthMiddleware as v, createAuthEndpoint as w, type AuthEndpoint as x, type AuthMiddleware as y, type FieldType as z };
@@ -1,10 +1,10 @@
1
1
  import * as nanostores from 'nanostores';
2
- import { o as organization, q as Organization, M as Member, I as Invitation, r as AccessControl, S as StatementsPrimitive, R as Role, u as username, m as magicLink, d as phoneNumber, e as anonymous, i as admin, j as genericOAuth, k as jwt, l as multiSession, n as emailOTP } from '../index-KdWDL1fo.cjs';
3
- export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-KdWDL1fo.cjs';
2
+ import { o as organization, q as Organization, M as Member, I as Invitation, r as AccessControl, S as StatementsPrimitive, R as Role, u as username, m as magicLink, d as phoneNumber, e as anonymous, i as admin, j as genericOAuth, k as jwt, l as multiSession, n as emailOTP } from '../index-DK55nobk.cjs';
3
+ export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-DK55nobk.cjs';
4
4
  import * as _better_fetch_fetch from '@better-fetch/fetch';
5
5
  import { BetterFetchOption } from '@better-fetch/fetch';
6
6
  import { P as Prettify } from '../index-DUqGSAH3.cjs';
7
- import { F as FieldAttribute, B as BetterAuthOptions, b as BetterAuthPlugin } from '../auth-BkJnc76F.cjs';
7
+ import { F as FieldAttribute, B as BetterAuthOptions, k as BetterAuthPlugin } from '../auth-B5ozNy5X.cjs';
8
8
  import { Store } from '../types.cjs';
9
9
  import 'zod';
10
10
  import 'better-call';
@@ -100,7 +100,7 @@ declare const organizationClient: <O extends OrganizationClientOptions>(options?
100
100
  id: string;
101
101
  name: string;
102
102
  email: string;
103
- image: string;
103
+ image: string | undefined;
104
104
  };
105
105
  })[];
106
106
  invitations: Invitation[];
@@ -1,10 +1,10 @@
1
1
  import * as nanostores from 'nanostores';
2
- import { o as organization, q as Organization, M as Member, I as Invitation, r as AccessControl, S as StatementsPrimitive, R as Role, u as username, m as magicLink, d as phoneNumber, e as anonymous, i as admin, j as genericOAuth, k as jwt, l as multiSession, n as emailOTP } from '../index-cKD4sHma.js';
3
- export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-cKD4sHma.js';
2
+ import { o as organization, q as Organization, M as Member, I as Invitation, r as AccessControl, S as StatementsPrimitive, R as Role, u as username, m as magicLink, d as phoneNumber, e as anonymous, i as admin, j as genericOAuth, k as jwt, l as multiSession, n as emailOTP } from '../index-CQluFeIi.js';
3
+ export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-CQluFeIi.js';
4
4
  import * as _better_fetch_fetch from '@better-fetch/fetch';
5
5
  import { BetterFetchOption } from '@better-fetch/fetch';
6
6
  import { P as Prettify } from '../index-DUqGSAH3.js';
7
- import { F as FieldAttribute, B as BetterAuthOptions, b as BetterAuthPlugin } from '../auth-G61_RA8H.js';
7
+ import { F as FieldAttribute, B as BetterAuthOptions, k as BetterAuthPlugin } from '../auth-BBUjEh9D.js';
8
8
  import { Store } from '../types.js';
9
9
  import 'zod';
10
10
  import 'better-call';
@@ -100,7 +100,7 @@ declare const organizationClient: <O extends OrganizationClientOptions>(options?
100
100
  id: string;
101
101
  name: string;
102
102
  email: string;
103
- image: string;
103
+ image: string | undefined;
104
104
  };
105
105
  })[];
106
106
  invitations: Invitation[];
package/dist/client.d.cts CHANGED
@@ -6,7 +6,7 @@ import { BetterFetchError, BetterFetch, BetterFetchOption } from '@better-fetch/
6
6
  import { ClientOptions, InferClientAPI, InferActions, InferSessionFromClient, InferUserFromClient, BetterAuthClientPlugin, IsSignal } from './types.cjs';
7
7
  export { AtomListener, InferAdditionalFromClient, InferPluginsFromClient, Store } from './types.cjs';
8
8
  import { U as UnionToIntersection } from './index-DUqGSAH3.cjs';
9
- import './auth-BkJnc76F.cjs';
9
+ import './auth-B5ozNy5X.cjs';
10
10
  import 'node_modules/better-call/dist/router-Bn7zn81P';
11
11
  import 'kysely';
12
12
  import 'better-call';
package/dist/client.d.ts CHANGED
@@ -6,7 +6,7 @@ import { BetterFetchError, BetterFetch, BetterFetchOption } from '@better-fetch/
6
6
  import { ClientOptions, InferClientAPI, InferActions, InferSessionFromClient, InferUserFromClient, BetterAuthClientPlugin, IsSignal } from './types.js';
7
7
  export { AtomListener, InferAdditionalFromClient, InferPluginsFromClient, Store } from './types.js';
8
8
  import { U as UnionToIntersection } from './index-DUqGSAH3.js';
9
- import './auth-G61_RA8H.js';
9
+ import './auth-BBUjEh9D.js';
10
10
  import 'node_modules/better-call/dist/router-Bn7zn81P';
11
11
  import 'kysely';
12
12
  import 'better-call';
@@ -1,5 +1,5 @@
1
1
  import 'better-call';
2
- export { s as BetterAuthCookies, E as EligibleCookies, q as createCookieGetter, u as deleteSessionCookie, r as getCookies, w as parseCookies, v as parseSetCookieHeader, t as setSessionCookie } from './auth-BkJnc76F.cjs';
2
+ export { n as BetterAuthCookies, E as EligibleCookies, l as createCookieGetter, o as deleteSessionCookie, m as getCookies, q as parseCookies, p as parseSetCookieHeader, s as setSessionCookie } from './auth-B5ozNy5X.cjs';
3
3
  import './index-DUqGSAH3.cjs';
4
4
  import 'node_modules/better-call/dist/router-Bn7zn81P';
5
5
  import 'zod';
package/dist/cookies.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import 'better-call';
2
- export { s as BetterAuthCookies, E as EligibleCookies, q as createCookieGetter, u as deleteSessionCookie, r as getCookies, w as parseCookies, v as parseSetCookieHeader, t as setSessionCookie } from './auth-G61_RA8H.js';
2
+ export { n as BetterAuthCookies, E as EligibleCookies, l as createCookieGetter, o as deleteSessionCookie, m as getCookies, q as parseCookies, p as parseSetCookieHeader, s as setSessionCookie } from './auth-BBUjEh9D.js';
3
3
  import './index-DUqGSAH3.js';
4
4
  import 'node_modules/better-call/dist/router-Bn7zn81P';
5
5
  import 'zod';
package/dist/db.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as Adapter, B as BetterAuthOptions, W as Where, F as FieldAttribute, z as FieldType, K as KyselyDatabaseType } from './auth-BkJnc76F.cjs';
2
- export { X as BetterAuthDbSchema, J as FieldAttributeConfig, V as InferFieldsFromOptions, U as InferFieldsFromPlugins, O as InferFieldsInput, Q as InferFieldsInputClient, N as InferFieldsOutput, M as InferValueType, D as InternalAdapter, T as PluginFieldAttribute, L as createFieldAttribute, C as createInternalAdapter, Y as getAuthTables } from './auth-BkJnc76F.cjs';
1
+ import { A as Adapter, B as BetterAuthOptions, W as Where, F as FieldAttribute, z as FieldType, K as KyselyDatabaseType } from './auth-B5ozNy5X.cjs';
2
+ export { X as BetterAuthDbSchema, J as FieldAttributeConfig, V as InferFieldsFromOptions, U as InferFieldsFromPlugins, O as InferFieldsInput, Q as InferFieldsInputClient, N as InferFieldsOutput, M as InferValueType, D as InternalAdapter, T as PluginFieldAttribute, L as createFieldAttribute, C as createInternalAdapter, Y as getAuthTables } from './auth-B5ozNy5X.cjs';
3
3
  import { z } from 'zod';
4
4
  import 'node_modules/better-call/dist/router-Bn7zn81P';
5
5
  import 'kysely';
package/dist/db.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as Adapter, B as BetterAuthOptions, W as Where, F as FieldAttribute, z as FieldType, K as KyselyDatabaseType } from './auth-G61_RA8H.js';
2
- export { X as BetterAuthDbSchema, J as FieldAttributeConfig, V as InferFieldsFromOptions, U as InferFieldsFromPlugins, O as InferFieldsInput, Q as InferFieldsInputClient, N as InferFieldsOutput, M as InferValueType, D as InternalAdapter, T as PluginFieldAttribute, L as createFieldAttribute, C as createInternalAdapter, Y as getAuthTables } from './auth-G61_RA8H.js';
1
+ import { A as Adapter, B as BetterAuthOptions, W as Where, F as FieldAttribute, z as FieldType, K as KyselyDatabaseType } from './auth-BBUjEh9D.js';
2
+ export { X as BetterAuthDbSchema, J as FieldAttributeConfig, V as InferFieldsFromOptions, U as InferFieldsFromPlugins, O as InferFieldsInput, Q as InferFieldsInputClient, N as InferFieldsOutput, M as InferValueType, D as InternalAdapter, T as PluginFieldAttribute, L as createFieldAttribute, C as createInternalAdapter, Y as getAuthTables } from './auth-BBUjEh9D.js';
3
3
  import { z } from 'zod';
4
4
  import 'node_modules/better-call/dist/router-Bn7zn81P';
5
5
  import 'kysely';
@@ -3,7 +3,7 @@ import { L as LiteralString, a as User, S as Session, P as Prettify, O as OAuth2
3
3
  import * as better_call from 'better-call';
4
4
  import * as _better_fetch_fetch from '@better-fetch/fetch';
5
5
  import { BetterFetch, BetterFetchOption } from '@better-fetch/fetch';
6
- import { H as HookEndpointContext, p as AuthContext, P as PluginSchema } from './auth-G61_RA8H.js';
6
+ import { H as HookEndpointContext, j as AuthContext, P as PluginSchema } from './auth-BBUjEh9D.js';
7
7
  import * as nanostores from 'nanostores';
8
8
  import { atom } from 'nanostores';
9
9
  import { PublicKeyCredentialRpEntity, PublicKeyCredentialParameters, AuthenticatorSelectionCriteria, AttestationConveyancePreference, AuthenticationExtensionsClientInputs, UserVerificationRequirement, PublicKeyCredentialType } from './dom.js';
@@ -2527,7 +2527,7 @@ declare const organization: <O extends OrganizationOptions>(options?: O) => {
2527
2527
  id: string;
2528
2528
  name: string;
2529
2529
  email: string;
2530
- image: string;
2530
+ image: string | undefined;
2531
2531
  };
2532
2532
  }>[];
2533
2533
  invitations: Invitation[];
@@ -3,7 +3,7 @@ import { L as LiteralString, a as User, S as Session, P as Prettify, O as OAuth2
3
3
  import * as better_call from 'better-call';
4
4
  import * as _better_fetch_fetch from '@better-fetch/fetch';
5
5
  import { BetterFetch, BetterFetchOption } from '@better-fetch/fetch';
6
- import { H as HookEndpointContext, p as AuthContext, P as PluginSchema } from './auth-BkJnc76F.cjs';
6
+ import { H as HookEndpointContext, j as AuthContext, P as PluginSchema } from './auth-B5ozNy5X.cjs';
7
7
  import * as nanostores from 'nanostores';
8
8
  import { atom } from 'nanostores';
9
9
  import { PublicKeyCredentialRpEntity, PublicKeyCredentialParameters, AuthenticatorSelectionCriteria, AttestationConveyancePreference, AuthenticationExtensionsClientInputs, UserVerificationRequirement, PublicKeyCredentialType } from './dom.js';
@@ -2527,7 +2527,7 @@ declare const organization: <O extends OrganizationOptions>(options?: O) => {
2527
2527
  id: string;
2528
2528
  name: string;
2529
2529
  email: string;
2530
- image: string;
2530
+ image: string | undefined;
2531
2531
  };
2532
2532
  }>[];
2533
2533
  invitations: Invitation[];