better-auth 0.5.2 → 0.5.3-beta.2

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.
package/dist/api.js CHANGED
@@ -1,6 +1,6 @@
1
- import{APIError as ot,createRouter as jt,statusCode as qt}from"better-call";import{APIError as J}from"better-call";import{z as ae}from"zod";import{xchacha20poly1305 as or}from"@noble/ciphers/chacha";import{bytesToHex as ir,hexToBytes as sr,utf8ToBytes as ar}from"@noble/ciphers/utils";import{managedNonce as cr}from"@noble/ciphers/webcrypto";import{sha256 as ur}from"oslo/crypto";import ne from"crypto";function W(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let n=0;for(let i=0;i<r.length;i++)n|=r[i]^o[i];return n===0}import{decodeHex as Ht,encodeHex as Zt}from"oslo/encoding";import{scryptAsync as Wt}from"@noble/hashes/scrypt";import{getRandomValues as Kt}from"crypto";import{getRandomValues as er}from"crypto";function nt(e){return e.toString(2).padStart(8,"0")}function it(e){return[...e].map(t=>nt(t)).join("")}function te(e){return parseInt(it(e),2)}function st(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,o=new Uint8Array(Math.ceil(t/8));crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=te(o);for(;n>=e;)crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=te(o);return n}function re(e,t){let r="";for(let o=0;o<e;o++)r+=t[st(t.length)];return r}function oe(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}async function F(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},n=await ne.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),i=await ne.subtle.sign(o.name,n,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(i)))}import{createEndpointCreator as at,createMiddleware as ie,createMiddlewareCreator as dt}from"better-call";var se=ie(async()=>({})),V=dt({use:[se,ie(async()=>({}))]}),m=at({use:[se]});var de=V({body:ae.object({csrfToken:ae.string().optional()}).optional()},async e=>{if(e.request?.method!=="POST"||e.context.options.advanced?.disableCSRFCheck)return;let t=e.headers?.get("origin")||"";if(t){let a=new URL(t).origin;if(e.context.trustedOrigins.includes(a))return}let r=e.body?.csrfToken;if(!r)throw new J("UNAUTHORIZED",{message:"CSRF Token is required"});let o=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[n,i]=o?.split("!")||[null,null];if(!r||!n||!i||n!==r)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new J("UNAUTHORIZED",{message:"Invalid CSRF Token"});let s=await F(e.context.secret,n);if(i!==s)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new J("UNAUTHORIZED",{message:"Invalid CSRF Token"})});import{APIError as P}from"better-call";import{generateCodeVerifier as St}from"oslo/oauth2";import{z as x}from"zod";import{generateState as ct}from"oslo/oauth2";import{z as H}from"zod";import{sha256 as ce}from"oslo/crypto";async function le(e){let t=await ce(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function ue(e,t){let r=await ce(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return W(r,o)}import"better-call";async function pe(e){let t=ct(),r=JSON.stringify({code:t,callbackURL:e}),o=await le(r);return{raw:r,hash:o}}function K(e){return H.object({code:H.string(),callbackURL:H.string().optional(),currentURL:H.string().optional()}).safeParse(JSON.parse(e))}import{TimeSpan as $r}from"oslo";var B=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};import{env as jr,isProduction as qr}from"std-env";async function _(e,t,r,o){let n=e.context.authCookies.sessionToken.options;n.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options)}function M(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}import{APIError as pt}from"better-call";import{createConsola as lt}from"consola";var D=lt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),ut=e=>({log:(...t)=>{!e?.disabled&&D.log("",...t)},error:(...t)=>{!e?.disabled&&D.error("",...t)},warn:(...t)=>{!e?.disabled&&D.warn("",...t)},info:(...t)=>{!e?.disabled&&D.info("",...t)},debug:(...t)=>{!e?.disabled&&D.debug("",...t)},box:(...t)=>{!e?.disabled&&D.box("",...t)},success:(...t)=>{!e?.disabled&&D.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
2
- `)}}),w=ut();var U=V(async e=>{let{body:t,query:r,headers:o,context:n}=e,i=t?.callbackURL||r?.callbackURL||r?.redirectTo||t?.redirectTo,s=r?.currentURL||o?.get("referer")||n.baseURL,a=n.trustedOrigins,c=(d,l)=>{if(d?.startsWith("http")&&!a.some(g=>d.startsWith(g)))throw w.error(`Invalid ${l}`,{[l]:d,trustedOrigins:a}),new pt("FORBIDDEN",{message:`Invalid ${l}`})};c(i,"callbackURL"),c(s,"currentURL")});import{parseJWT as ht}from"oslo/jwt";import{sha256 as mt}from"oslo/crypto";import{env as Jr}from"std-env";import{base64url as ft}from"oslo/encoding";async function me(e){let t=await mt(new TextEncoder().encode(e));return ft.encode(new Uint8Array(t),{includePadding:!1})}function fe(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_at?new Date((Date.now()+e.expires_in)*1e3):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function E({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,disablePkce: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",i.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),!a&&n){let l=await me(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((h,g)=>(h[g]=null,h),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return d}import{betterFetch as gt}from"@better-fetch/fetch";async function y({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:s,error:a}=await gt(n,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(a)throw a;return fe(s)}function X(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var ge=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=e.scope||o||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>y({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=ht(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 wt}from"@better-fetch/fetch";var he=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await wt("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});import{betterFetch as yt}from"@better-fetch/fetch";var we=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["email","public_profile"];return await E({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>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,emailVerified:r.email_verified},data:r}}});import{betterFetch as ye}from"@better-fetch/fetch";var be=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let s=e.scope||o||["user:email"];return E({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await ye("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error: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,i=s.find(c=>c.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};import{parseJWT as bt}from"oslo/jwt";var Ae=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw w.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new B("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new B("codeVerifier is required for Google");let i=e.scope||r||["email","profile"];return E({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=bt(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 At}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(n){let i=e.scope||n.scopes||["openid","profile","email","User.Read"];return E({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return y({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=kt(n.idToken)?.payload,s=e.profilePhotoSize||48;return await At(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let d=await a.response.clone().arrayBuffer(),l=Buffer.from(d).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(c){w.error(c)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as Rt}from"@better-fetch/fetch";var Re=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=e.scope||r||["user-read-email"];return E({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await Rt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";var I={isAction:!1};import{nanoid as Ut}from"nanoid";var Ue=e=>Ut(e);import{parseJWT as Et}from"oslo/jwt";var Ee=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return E({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return w.error("No idToken found in token"),null;let o=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 Tt}from"@better-fetch/fetch";var Te=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return E({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>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 Tt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var xt={apple:ge,discord:he,facebook:we,github:be,microsoft:ke,google:Ae,spotify:Re,twitch:Ee,twitter:Te},xe=Object.keys(xt);import{TimeSpan as vt}from"oslo";import{createJWT as Pt,validateJWT as _t}from"oslo/jwt";import{z as v}from"zod";import{APIError as z}from"better-call";import{APIError as N}from"better-call";var Z=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as ve}from"zod";var Y=()=>m("/session",{method:"GET",requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return M(e),r&&await e.context.internalAdapter.deleteSession(r.session.id),e.json(null,{status:401});if(await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(r);let n=e.context.sessionConfig.expiresIn,i=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+i*1e3<=Date.now()){let c=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:Z(e.context.sessionConfig.expiresIn,"sec")});if(!c)return M(e),e.json(null,{status:401});let d=(c.expiresAt.valueOf()-Date.now())/1e3;return await _(e,c.id,!1,{maxAge:d}),e.json({session:c,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),ee=async e=>await Y()({...e,_flag:"json",headers:e.headers}),O=V(async e=>{let t=await ee(e);if(!t?.session)throw new N("UNAUTHORIZED");return{session:t}}),Pe=()=>m("/user/list-sessions",{method:"GET",use:[O],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),_e=m("/user/revoke-session",{method:"POST",body:ve.object({id:ve.string()}),use:[O],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("/user/revoke-sessions",{method:"POST",use:[O],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 L(e,t,r){return await Pt("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new vt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Oe=m("/send-verification-email",{method:"POST",query:v.object({currentURL:v.string().optional()}).optional(),body:v.object({email:v.string().email(),callbackURL:v.string().optional()}),use:[U]},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new z("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new z("BAD_REQUEST",{message:"User not found"});let o=await L(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,n,o),e.json({status:!0})}),Le=m("/verify-email",{method:"GET",query:v.object({token:v.string(),callbackURL:v.string().optional()}),use:[U]},async e=>{let{token:t}=e.query,r;try{r=await _t("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new z("BAD_REQUEST",{message:"Invalid token"})}let n=v.object({email:v.string().email(),updateTo:v.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new z("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await ee(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new z("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new z("UNAUTHORIZED",{message:"Invalid session"});let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.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(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var Ie=m("/sign-in/social",{method:"POST",requireHeaders:!0,query:x.object({currentURL:x.string().optional()}).optional(),body:x.object({callbackURL:x.string().optional(),provider:x.enum(xe)}),use:[U]},async e=>{let t=e.context.socialProviders.find(c=>c.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new P("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,n=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,i=await pe(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,i.hash,e.context.secret,r.state.options);let s=St();await e.setSignedCookie(r.pkCodeVerifier.name,s,e.context.secret,r.pkCodeVerifier.options);let a=await t.createAuthorizationURL({state:i.raw,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:a.toString(),state:i,codeVerifier:s,redirect:!0})}),Ce=m("/sign-in/email",{method:"POST",body:x.object({email:x.string(),password:x.string(),callbackURL:x.string().optional(),dontRememberMe:x.boolean().default(!1).optional()}),use:[U]},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new P("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!x.string().email().safeParse(t).success)throw new P("BAD_REQUEST",{message:"Invalid email"});if(!x.string().email().safeParse(t).success)throw new P("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new P("UNAUTHORIZED",{message:"Invalid email or password"});let s=i.accounts.find(l=>l.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new P("UNAUTHORIZED",{message:"Invalid email or password"});let a=s?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new P("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new P("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw w.error("Email verification is required but no email verification handler is provided"),new P("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let l=await L(e.context.secret,i.user.email),h=`${e.context.options.baseURL}/verify-email?token=${l}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,h,l),e.context.logger.error("Email not verified",{email:t}),new P("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new P("UNAUTHORIZED",{message:"Failed to create session"});return await _(e,d.id,e.body.dontRememberMe),e.json({user:i.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as Q}from"zod";import{z as f}from"zod";var ri=f.object({id:f.string(),providerId:f.string(),accountId:f.string(),userId:f.string(),accessToken:f.string().nullable().optional(),refreshToken:f.string().nullable().optional(),idToken:f.string().nullable().optional(),expiresAt:f.date().nullable().optional(),password:f.string().optional().nullable()}),Be=f.object({id:f.string(),email:f.string().transform(e=>e.toLowerCase()),emailVerified:f.boolean().default(!1),name:f.string(),image:f.string().optional(),createdAt:f.date().default(new Date),updatedAt:f.date().default(new Date)}),oi=f.object({id:f.string(),userId:f.string(),expiresAt:f.date(),ipAddress:f.string().optional(),userAgent:f.string().optional()}),ni=f.object({id:f.string(),value:f.string(),expiresAt:f.date(),identifier:f.string()});function De(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 $e(e,t){let r=t.fields,o={};for(let n in r){if(n in e){if(r[n].input===!1){if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}continue}o[n]=e[n];continue}if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}}return o}function Ve(e,t){let r=De(e,"user");return $e(t||{},{fields:r})}function ze(e,t){let r=De(e,"user");return $e(t||{},{fields:r})}var je=m("/callback/:id",{method:"GET",query:Q.object({state:Q.string(),code:Q.string().optional(),error:Q.string().optional()}),metadata:I},async e=>{if(e.query.error||!e.query.code){let k=K(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${k}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(p=>p.id===e.params.id);if(!t)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let r=K(e.query.state);if(!r.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:n}}=r,i=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!i)throw w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await ue(e.query.state,i))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let a=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),c;try{c=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(p){throw e.context.logger.error(p),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let d=await t.getUserInfo(c).then(p=>p?.user),l=Ue(),h=Be.safeParse({...d,id:l});if(!d||h.success===!1)throw w.error("Unable to get user info",h.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);function g(p){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${p}`)}let u=await e.context.internalAdapter.findUserByEmail(d.email,{includeAccounts:!0}).catch(p=>{throw w.error(`Better auth was unable to query your database.
3
- Error: `,p),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),b=u?.user.id;if(u){if(!u.accounts.find(k=>k.providerId===t.id)){(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!d.emailVerified||!e.context.options.account?.accountLinking?.enabled)&&g("account_not_linked");try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:d.id.toString(),id:`${t.id}:${d.id}`,userId:u.user.id,...X(c)})}catch(C){w.error("Unable to link account",C),g("unable_to_link_account")}}}else try{let p=d.emailVerified||!1,k=await e.context.internalAdapter.createOAuthUser({...h.data,emailVerified:p},{...X(c),providerId:t.id,accountId:d.id.toString()});if(b=k?.user.id,!p&&k&&e.context.options.emailVerification?.sendOnSignUp){let q=await L(e.context.secret,d.email),C=`${e.context.baseURL}/verify-email?token=${q}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(k.user,C,q)}}catch(p){w.error("Unable to create user",p),g("unable_to_create_user")}b||g("unable_to_create_user");let T=await e.context.internalAdapter.createSession(b,e.request);throw T||g("unable_to_create_session"),await _(e,T.id),e.redirect(o)});import"zod";import{APIError as Ot}from"better-call";var qe=m("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Ot("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),M(e),e.json({success:!0})});import{z as S}from"zod";import{APIError as G}from"better-call";var Me=m("/forget-password",{method:"POST",body:S.object({email:S.string().email(),redirectTo:S.string()}),use:[U]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new G("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n)),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,a),e.json({status:!0})}),Ne=m("/reset-password/:token",{method:"GET",query:S.object({callbackURL:S.string()}),use:[U]},async e=>{let{token:t}=e.params,r=e.query.callbackURL,o=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}?token=${t}`)}),Fe=m("/reset-password",{query:S.optional(S.object({token:S.string()})),method:"POST",body:S.object({newPassword:S.string()})},async e=>{let t=e.query?.token;if(!t)throw new G("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new G("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(i)).find(l=>l.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(i,s))throw new G("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as A}from"zod";import{APIError as R}from"better-call";var He=()=>m("/user/update",{method:"POST",body:A.record(A.string(),A.any()),use:[O,U]},async e=>{let t=e.body;if(t.email)throw new R("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...n}=t,i=e.context.session;if(!o&&!r&&Object.keys(n).length===0)return e.json({user:i.user});let s=Ve(e.context.options,n);console.log({additionalFields:s});let a=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return e.json({user:a})}),Ze=m("/user/change-password",{method:"POST",body:A.object({newPassword:A.string(),currentPassword:A.string(),revokeOtherSessions:A.boolean().optional()}),use:[O]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new R("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new R("BAD_REQUEST",{message:"Password too long"});let c=(await e.context.internalAdapter.findAccounts(n.user.id)).find(h=>h.providerId==="credential"&&h.password);if(!c||!c.password)throw new R("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 R("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(c.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let h=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!h)throw new R("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await _(e,h.id)}return e.json(n.user)}),Qe=m("/user/set-password",{method:"POST",body:A.object({newPassword:A.string()}),use:[O]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new R("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new R("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 R("BAD_REQUEST",{message:"user already has a password"})}),Ge=m("/user/delete",{method:"POST",body:A.object({password:A.string()}),use:[O]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password);if(!n||!n.password)throw new R("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new R("BAD_REQUEST",{message:"Incorrect password"});await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id);let s=e.context.authCookies.sessionToken;return e.setCookie(s.name,"",{maxAge:0}),e.json(null)}),We=m("/user/change-email",{method:"POST",query:A.object({currentURL:A.string().optional()}).optional(),body:A.object({newEmail:A.string().email(),callbackURL:A.string().optional()}),use:[O,U]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new R("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new R("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new R("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new R("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await L(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 Je=m("/csrf",{method:"GET",metadata:I},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t){let[i,s]=t.split("!")||[null,null];return e.json({csrfToken:i})}let r=re(32,oe("a-z","0-9","A-Z")),o=await F(e.context.secret,r),n=`${r}!${o}`;return await e.setSignedCookie(e.context.authCookies.csrfToken.name,n,e.context.secret,e.context.authCookies.csrfToken.options),e.json({csrfToken:r})});var Lt=(e="Unknown")=>`<!DOCTYPE html>
1
+ import{APIError as nt,createRouter as qt,statusCode as Mt}from"better-call";import{APIError as J}from"better-call";import{z as de}from"zod";import{xchacha20poly1305 as or}from"@noble/ciphers/chacha";import{bytesToHex as ir,hexToBytes as sr,utf8ToBytes as ar}from"@noble/ciphers/utils";import{managedNonce as cr}from"@noble/ciphers/webcrypto";import{sha256 as ur}from"oslo/crypto";import ie from"uncrypto";function W(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let n=0;for(let i=0;i<r.length;i++)n|=r[i]^o[i];return n===0}import{decodeHex as Zt,encodeHex as Qt}from"oslo/encoding";import{scryptAsync as Jt}from"@noble/hashes/scrypt";import{getRandomValues as Yt}from"uncrypto";import te from"uncrypto";function it(e){return e.toString(2).padStart(8,"0")}function st(e){return[...e].map(t=>it(t)).join("")}function re(e){return parseInt(st(e),2)}function at(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,o=new Uint8Array(Math.ceil(t/8));te.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=re(o);for(;n>=e;)te.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=re(o);return n}function oe(e,t){let r="";for(let o=0;o<e;o++)r+=t[at(t.length)];return r}function ne(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}async function F(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},n=await ie.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),i=await ie.subtle.sign(o.name,n,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(i)))}import{createEndpointCreator as dt,createMiddleware as se,createMiddlewareCreator as ct}from"better-call";var ae=se(async()=>({})),$=ct({use:[ae,se(async()=>({}))]}),m=dt({use:[ae]});var ce=$({body:de.object({csrfToken:de.string().optional()}).optional()},async e=>{if(e.request?.method!=="POST"||e.context.options.advanced?.disableCSRFCheck)return;let t=e.headers?.get("origin")||"";if(t){let a=new URL(t).origin;if(e.context.trustedOrigins.includes(a))return}let r=e.body?.csrfToken;if(!r)throw new J("UNAUTHORIZED",{message:"CSRF Token is required"});let o=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[n,i]=o?.split("!")||[null,null];if(!r||!n||!i||n!==r)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new J("UNAUTHORIZED",{message:"Invalid CSRF Token"});let s=await F(e.context.secret,n);if(i!==s)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new J("UNAUTHORIZED",{message:"Invalid CSRF Token"})});import{APIError as S}from"better-call";import{generateCodeVerifier as _t}from"oslo/oauth2";import{z as v}from"zod";import{generateState as lt}from"oslo/oauth2";import{z as H}from"zod";import{sha256 as le}from"oslo/crypto";async function ue(e){let t=await le(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function pe(e,t){let r=await le(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return W(r,o)}import"better-call";async function me(e){let t=lt(),r=JSON.stringify({code:t,callbackURL:e}),o=await ue(r);return{raw:r,hash:o}}function K(e){return H.object({code:H.string(),callbackURL:H.string().optional(),currentURL:H.string().optional()}).safeParse(JSON.parse(e))}import{TimeSpan as $r}from"oslo";var V=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};import{env as jr,isProduction as qr}from"std-env";async function P(e,t,r,o){let n=e.context.authCookies.sessionToken.options;n.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options)}function M(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}import{APIError as mt}from"better-call";import{createConsola as ut}from"consola";var B=ut({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),pt=e=>({log:(...t)=>{!e?.disabled&&B.log("",...t)},error:(...t)=>{!e?.disabled&&B.error("",...t)},warn:(...t)=>{!e?.disabled&&B.warn("",...t)},info:(...t)=>{!e?.disabled&&B.info("",...t)},debug:(...t)=>{!e?.disabled&&B.debug("",...t)},box:(...t)=>{!e?.disabled&&B.box("",...t)},success:(...t)=>{!e?.disabled&&B.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
2
+ `)}}),w=pt();var U=$(async e=>{let{body:t,query:r,headers:o,context:n}=e,i=t?.callbackURL||r?.callbackURL||r?.redirectTo||t?.redirectTo,s=r?.currentURL||o?.get("referer")||n.baseURL,a=n.trustedOrigins,c=(d,l)=>{if(d?.startsWith("http")&&!a.some(g=>d.startsWith(g)))throw w.error(`Invalid ${l}`,{[l]:d,trustedOrigins:a}),new mt("FORBIDDEN",{message:`Invalid ${l}`})};c(i,"callbackURL"),c(s,"currentURL")});import{parseJWT as wt}from"oslo/jwt";import{sha256 as ft}from"oslo/crypto";import{base64url as gt}from"oslo/encoding";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_at?new Date((Date.now()+e.expires_in)*1e3):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function E({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,disablePkce: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",i.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),!a&&n){let l=await fe(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((h,g)=>(h[g]=null,h),{});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:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:s,error:a}=await ht(n,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(a)throw a;return ge(s)}function Y(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var he=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=e.scope||o||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>y({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=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 yt}from"@better-fetch/fetch";var we=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await yt("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});import{betterFetch as bt}from"@better-fetch/fetch";var ye=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["email","public_profile"];return await E({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await bt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,emailVerified:r.email_verified},data:r}}});import{betterFetch as be}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:n,redirectURI:i}){let s=e.scope||o||["user:email"];return E({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await be("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:a}=await be("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,i=s.find(c=>c.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};import{parseJWT as At}from"oslo/jwt";var ke=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw w.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new V("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new V("codeVerifier is required for Google");let i=e.scope||r||["email","profile"];return E({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=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(n){let i=e.scope||n.scopes||["openid","profile","email","User.Read"];return E({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return y({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=Rt(n.idToken)?.payload,s=e.profilePhotoSize||48;return await kt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let d=await a.response.clone().arrayBuffer(),l=Buffer.from(d).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(c){w.error(c)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as Ut}from"@better-fetch/fetch";var Ue=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=e.scope||r||["user-read-email"];return E({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await 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";var I={isAction:!1};import{nanoid as Et}from"nanoid";var Ee=e=>Et(e);import{parseJWT as xt}from"oslo/jwt";var xe=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return E({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return w.error("No idToken found in token"),null;let o=xt(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=e.scope||t.scopes||["account_info.read"];return E({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await 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}}});var Tt={apple:he,discord:we,facebook:ye,github:Ae,microsoft:Re,google:ke,spotify:Ue,twitch:xe,twitter:ve},Te=Object.keys(Tt);import{TimeSpan as St}from"oslo";import{createJWT as Pt,validateJWT as Ot}from"oslo/jwt";import{z as T}from"zod";import{APIError as z}from"better-call";import{APIError as N}from"better-call";var Z=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as Se}from"zod";var X=()=>m("/session",{method:"GET",requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return M(e),r&&await e.context.internalAdapter.deleteSession(r.session.id),e.json(null,{status:401});if(await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(r);let n=e.context.sessionConfig.expiresIn,i=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+i*1e3<=Date.now()){let c=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:Z(e.context.sessionConfig.expiresIn,"sec")});if(!c)return M(e),e.json(null,{status:401});let d=(c.expiresAt.valueOf()-Date.now())/1e3;return await P(e,c.id,!1,{maxAge:d}),e.json({session:c,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),ee=async e=>await X()({...e,_flag:"json",headers:e.headers}),_=$(async e=>{let t=await ee(e);if(!t?.session)throw new N("UNAUTHORIZED");return{session:t}}),Pe=()=>m("/user/list-sessions",{method:"GET",use:[_],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("/user/revoke-session",{method:"POST",body:Se.object({id:Se.string()}),use:[_],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new N("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new N("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new N("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),_e=m("/user/revoke-sessions",{method:"POST",use:[_],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 L(e,t,r){return await Pt("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:T.object({currentURL:T.string().optional()}).optional(),body:T.object({email:T.string().email(),callbackURL:T.string().optional()}),use:[U]},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new z("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new z("BAD_REQUEST",{message:"User not found"});let o=await L(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,n,o),e.json({status:!0})}),Ie=m("/verify-email",{method:"GET",query:T.object({token:T.string(),callbackURL:T.string().optional()}),use:[U]},async e=>{let{token:t}=e.query,r;try{r=await Ot("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new z("BAD_REQUEST",{message:"Invalid token"})}let n=T.object({email:T.string().email(),updateTo:T.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new z("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await ee(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new z("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new z("UNAUTHORIZED",{message:"Invalid session"});let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.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(n.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",requireHeaders:!0,query:v.object({currentURL:v.string().optional()}).optional(),body:v.object({callbackURL:v.string().optional(),provider:v.enum(Te)}),use:[U]},async e=>{let t=e.context.socialProviders.find(c=>c.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new S("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,n=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,i=await me(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,i.hash,e.context.secret,r.state.options);let s=_t();await e.setSignedCookie(r.pkCodeVerifier.name,s,e.context.secret,r.pkCodeVerifier.options);let a=await t.createAuthorizationURL({state:i.raw,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:a.toString(),state:i,codeVerifier:s,redirect:!0})}),Be=m("/sign-in/email",{method:"POST",body:v.object({email:v.string(),password:v.string(),callbackURL:v.string().optional(),dontRememberMe:v.boolean().default(!1).optional()}),use:[U]},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new S("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!v.string().email().safeParse(t).success)throw new S("BAD_REQUEST",{message:"Invalid email"});if(!v.string().email().safeParse(t).success)throw new S("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new S("UNAUTHORIZED",{message:"Invalid email or password"});let s=i.accounts.find(l=>l.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new S("UNAUTHORIZED",{message:"Invalid email or password"});let a=s?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new S("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new S("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw w.error("Email verification is required but no email verification handler is provided"),new S("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let l=await L(e.context.secret,i.user.email),h=`${e.context.options.baseURL}/verify-email?token=${l}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,h,l),e.context.logger.error("Email not verified",{email:t}),new S("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new S("UNAUTHORIZED",{message:"Failed to create session"});return await P(e,d.id,e.body.dontRememberMe),e.json({user:i.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as Q}from"zod";import{z as f}from"zod";var Jn=f.object({id:f.string(),providerId:f.string(),accountId:f.string(),userId:f.string(),accessToken:f.string().nullable().optional(),refreshToken:f.string().nullable().optional(),idToken:f.string().nullable().optional(),expiresAt:f.date().nullable().optional(),password:f.string().optional().nullable()}),De=f.object({id:f.string(),email:f.string().transform(e=>e.toLowerCase()),emailVerified:f.boolean().default(!1),name:f.string(),image:f.string().optional(),createdAt:f.date().default(new Date),updatedAt:f.date().default(new Date)}),Kn=f.object({id:f.string(),userId:f.string(),expiresAt:f.date(),ipAddress:f.string().optional(),userAgent:f.string().optional()}),Yn=f.object({id:f.string(),value:f.string(),expiresAt:f.date(),identifier:f.string()});function $e(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 Ve(e,t){let r=t.fields,o={};for(let n in r){if(n in e){if(r[n].input===!1){if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}continue}o[n]=e[n];continue}if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}}return o}function ze(e,t){let r=$e(e,"user");return Ve(t||{},{fields:r})}function je(e,t){let r=$e(e,"user");return Ve(t||{},{fields:r})}var qe=m("/callback/:id",{method:"GET",query:Q.object({state:Q.string(),code:Q.string().optional(),error:Q.string().optional()}),metadata:I},async e=>{if(e.query.error||!e.query.code){let k=K(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${k}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(p=>p.id===e.params.id);if(!t)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let r=K(e.query.state);if(!r.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:n}}=r,i=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!i)throw w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await pe(e.query.state,i))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let a=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),c;try{c=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(p){throw e.context.logger.error(p),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let d=await t.getUserInfo(c).then(p=>p?.user),l=Ee(),h=De.safeParse({...d,id:l});if(!d||h.success===!1)throw w.error("Unable to get user info",h.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);function g(p){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${p}`)}let u=await e.context.internalAdapter.findUserByEmail(d.email,{includeAccounts:!0}).catch(p=>{throw w.error(`Better auth was unable to query your database.
3
+ Error: `,p),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),b=u?.user.id;if(u){if(!u.accounts.find(k=>k.providerId===t.id)){(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!d.emailVerified||!e.context.options.account?.accountLinking?.enabled)&&g("account_not_linked");try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:d.id.toString(),id:`${t.id}:${d.id}`,userId:u.user.id,...Y(c)})}catch(C){w.error("Unable to link account",C),g("unable_to_link_account")}}}else try{let p=d.emailVerified||!1,k=await e.context.internalAdapter.createOAuthUser({...h.data,emailVerified:p},{...Y(c),providerId:t.id,accountId:d.id.toString()});if(b=k?.user.id,!p&&k&&e.context.options.emailVerification?.sendOnSignUp){let q=await L(e.context.secret,d.email),C=`${e.context.baseURL}/verify-email?token=${q}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(k.user,C,q)}}catch(p){w.error("Unable to create user",p),g("unable_to_create_user")}b||g("unable_to_create_user");let x=await e.context.internalAdapter.createSession(b,e.request);throw x||g("unable_to_create_session"),await P(e,x.id),e.redirect(o)});import"zod";import{APIError as Lt}from"better-call";var Me=m("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Lt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),M(e),e.json({success:!0})});import{z as O}from"zod";import{APIError as G}from"better-call";var Ne=m("/forget-password",{method:"POST",body:O.object({email:O.string().email(),redirectTo:O.string()}),use:[U]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new G("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n)),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,a),e.json({status:!0})}),Fe=m("/reset-password/:token",{method:"GET",query:O.object({callbackURL:O.string()}),use:[U]},async e=>{let{token:t}=e.params,r=e.query.callbackURL,o=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}?token=${t}`)}),He=m("/reset-password",{query:O.optional(O.object({token:O.string()})),method:"POST",body:O.object({newPassword:O.string()})},async e=>{let t=e.query?.token;if(!t)throw new G("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new G("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(i)).find(l=>l.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(i,s))throw new G("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as A}from"zod";import{APIError as R}from"better-call";var Ze=()=>m("/user/update",{method:"POST",body:A.record(A.string(),A.any()),use:[_,U]},async e=>{let t=e.body;if(t.email)throw new R("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...n}=t,i=e.context.session;if(!o&&!r&&Object.keys(n).length===0)return e.json({user:i.user});let s=ze(e.context.options,n);console.log({additionalFields:s});let a=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return e.json({user:a})}),Qe=m("/user/change-password",{method:"POST",body:A.object({newPassword:A.string(),currentPassword:A.string(),revokeOtherSessions:A.boolean().optional()}),use:[_]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new R("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new R("BAD_REQUEST",{message:"Password too long"});let c=(await e.context.internalAdapter.findAccounts(n.user.id)).find(h=>h.providerId==="credential"&&h.password);if(!c||!c.password)throw new R("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 R("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(c.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let h=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!h)throw new R("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await P(e,h.id)}return e.json(n.user)}),Ge=m("/user/set-password",{method:"POST",body:A.object({newPassword:A.string()}),use:[_]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new R("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new R("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 R("BAD_REQUEST",{message:"user already has a password"})}),We=m("/user/delete",{method:"POST",body:A.object({password:A.string()}),use:[_]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password);if(!n||!n.password)throw new R("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new R("BAD_REQUEST",{message:"Incorrect password"});await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id);let s=e.context.authCookies.sessionToken;return e.setCookie(s.name,"",{maxAge:0}),e.json(null)}),Je=m("/user/change-email",{method:"POST",query:A.object({currentURL:A.string().optional()}).optional(),body:A.object({newEmail:A.string().email(),callbackURL:A.string().optional()}),use:[_,U]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new R("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new R("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new R("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new R("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await L(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 Ke=m("/csrf",{method:"GET",metadata:I},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t){let[i,s]=t.split("!")||[null,null];return e.json({csrfToken:i})}let r=oe(32,ne("a-z","0-9","A-Z")),o=await F(e.context.secret,r),n=`${r}!${o}`;return await e.setSignedCookie(e.context.authCookies.csrfToken.name,n,e.context.secret,e.context.authCookies.csrfToken.options),e.json({csrfToken:r})});var It=(e="Unknown")=>`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">
@@ -80,4 +80,4 @@ Error: `,p),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
80
80
  <div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
81
81
  </div>
82
82
  </body>
83
- </html>`,Ke=m("/error",{method:"GET",metadata:I},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Lt(t),{headers:{"Content-Type":"text/html"}})});var Xe=m("/ok",{method:"GET",metadata:I},async e=>e.json({ok:!0}));import{z as j}from"zod";import{APIError as $}from"better-call";var Ye=()=>m("/sign-up/email",{method:"POST",query:j.object({currentURL:j.string().optional()}).optional(),body:j.record(j.string(),j.any()),use:[U]},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new $("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:n,image:i,callbackURL:s,...a}=t;if(!j.string().email().safeParse(o).success)throw new $("BAD_REQUEST",{message:"Invalid email"});let d=e.context.password.config.minPasswordLength;if(n.length<d)throw e.context.logger.error("Password is too short"),new $("BAD_REQUEST",{message:"Password is too short"});let l=e.context.password.config.maxPasswordLength;if(n.length>l)throw e.context.logger.error("Password is too long"),new $("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new $("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let g=ze(e.context.options,a),u=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...g,emailVerified:!1});if(!u)throw new $("BAD_REQUEST",{message:"Failed to create user"});let b=await e.context.password.hash(n);if(await e.context.internalAdapter.linkAccount({userId:u.id,providerId:"credential",accountId:u.id,password:b,expiresAt:Z(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let p=await L(e.context.secret,u.email),k=`${e.context.baseURL}/verify-email?token=${p}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(u,k,p)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:u,session:null},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:u,session:null}});let T=await e.context.internalAdapter.createSession(u.id,e.request);if(!T)throw new $("BAD_REQUEST",{message:"Failed to create session"});return await _(e,T.id),e.json({user:u,session:T},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:u,session:T}})});import{isTest as It}from"std-env";function et(e){let t="127.0.0.1";if(It)return t;let r=["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],o=e instanceof Request?e.headers:e;for(let n of r){let i=o.get(n);if(typeof i=="string"){let s=i.split(",")[0].trim();if(s)return s}}return null}function Ct(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function Bt(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 Dt(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function $t(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async n=>await o.findOne({model:r,where:[{field:"key",value:n}]}),set:async(n,i,s)=>{try{s?await o.update({model:t??"rateLimit",where:[{field:"key",value:n}],update:{count:i.count,lastRequest:i.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:n,count:i.count,lastRequest:i.lastRequest}})}catch(a){w.error("Error setting rate limit",a)}}}}var tt=new Map;function Vt(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,n){tt.set(r,o)}}:$t(e,e.rateLimit.tableName)}async function rt(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),n=t.rateLimit.window,i=t.rateLimit.max,s=et(e)+o,c=zt().find(g=>g.pathMatcher(o));c&&(n=c.window,i=c.max);for(let g of t.options.plugins||[])if(g.rateLimit){let u=g.rateLimit.find(b=>b.pathMatcher(o));if(u){n=u.window,i=u.max;break}}if(t.rateLimit.customRules){let g=t.rateLimit.customRules[o];g&&(n=g.window,i=g.max)}let d=Vt(t),l=await d.get(s),h=Date.now();if(!l)await d.set(s,{key:s,count:1,lastRequest:h});else{let g=h-l.lastRequest;if(Ct(i,n,l)){let u=Dt(l.lastRequest,n);return Bt(u)}else g>n*1e3?await d.set(s,{...l,count:1,lastRequest:h}):await d.set(s,{...l,count:l.count+1,lastRequest:h})}}function zt(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:3}]}import{APIError as Js}from"better-call";function Mt(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()||[],i={...{signInOAuth:Ie,callbackOAuth:je,getCSRFToken:Je,getSession:Y(),signOut:qe,signUpEmail:Ye(),signInEmail:Ce,forgetPassword:Me,resetPassword:Fe,verifyEmail:Le,sendVerificationEmail:Oe,changeEmail:We,changePassword:Ze,setPassword:Qe,updateUser:He(),deleteUser:Ge,forgetPasswordCallback:Ne,listSessions:Pe(),revokeSession:_e,revokeSessions:Se},...r,ok:Xe,error:Ke},s={};for(let[a,c]of Object.entries(i))s[a]=async(d={})=>{let l=await e;for(let u of t.plugins||[])if(u.hooks?.before){for(let b of u.hooks.before)if(b.matcher({...c,...d,context:l})){let p=await b.handler({...d,context:{...l,...d?.context}});p&&"context"in p&&(l={...l,...p.context})}}let h;try{h=await c({...d,context:{...l,...d.context}})}catch(u){if(u instanceof ot){let b=t.plugins?.map(p=>{if(p.hooks?.after)return p.hooks.after}).filter(p=>p!==void 0).flat();if(!b?.length)throw u;let T=new Response(JSON.stringify(u.body),{status:qt[u.status],headers:u.headers});for(let p of b||[])if(p.matcher(d)){let q=Object.assign(d,{context:{...e,returned:T}}),C=await p.handler(q);C&&"response"in C&&(T=C.response)}return T}throw u}let g=h;for(let u of t.plugins||[])if(u.hooks?.after){for(let b of u.hooks.after)if(b.matcher(d)){let p=Object.assign(d,{context:{...e,returned:g}}),k=await b.handler(p);k&&"response"in k&&(g=k.response)}}return g},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 Fs=(e,t)=>{let{api:r,middlewares:o}=Mt(e,t),n=new URL(e.baseURL).pathname;return jt(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:de},...o],async onRequest(i){for(let s of e.options.plugins||[])if(s.onRequest){let a=await s.onRequest(i,e);if(a)return a}return rt(i,e)},async onResponse(i){for(let s of e.options.plugins||[])if(s.onResponse){let a=await s.onResponse(i,e);if(a)return a.response}return i},onError(i){if(t.onAPIError?.throw)throw i;if(t.onAPIError?.onError){t.onAPIError.onError(i,e);return}let s=t.logger?.verboseLogging?w:void 0;t.logger?.disabled!==!0&&(i instanceof ot?(i.status==="INTERNAL_SERVER_ERROR"&&w.error(i),s?.error(i.message)):w?.error(i))}})};export{Js as APIError,je as callbackOAuth,We as changeEmail,Ze as changePassword,m as createAuthEndpoint,V as createAuthMiddleware,L as createEmailVerificationToken,de as csrfMiddleware,Ge as deleteUser,Ke as error,Me as forgetPassword,Ne as forgetPasswordCallback,Je as getCSRFToken,Mt as getEndpoints,Y as getSession,ee as getSessionFromCtx,Pe as listSessions,Xe as ok,se as optionsMiddleware,Fe as resetPassword,_e as revokeSession,Se as revokeSessions,Fs as router,Oe as sendVerificationEmail,O as sessionMiddleware,Qe as setPassword,Ce as signInEmail,Ie as signInOAuth,qe as signOut,Ye as signUpEmail,He as updateUser,Le as verifyEmail};
83
+ </html>`,Ye=m("/error",{method:"GET",metadata:I},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(It(t),{headers:{"Content-Type":"text/html"}})});var Xe=m("/ok",{method:"GET",metadata:I},async e=>e.json({ok:!0}));import{z as j}from"zod";import{APIError as D}from"better-call";var et=()=>m("/sign-up/email",{method:"POST",query:j.object({currentURL:j.string().optional()}).optional(),body:j.record(j.string(),j.any()),use:[U]},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new D("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:n,image:i,callbackURL:s,...a}=t;if(!j.string().email().safeParse(o).success)throw new D("BAD_REQUEST",{message:"Invalid email"});let d=e.context.password.config.minPasswordLength;if(n.length<d)throw e.context.logger.error("Password is too short"),new D("BAD_REQUEST",{message:"Password is too short"});let l=e.context.password.config.maxPasswordLength;if(n.length>l)throw e.context.logger.error("Password is too long"),new D("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new D("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let g=je(e.context.options,a),u=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...g,emailVerified:!1});if(!u)throw new D("BAD_REQUEST",{message:"Failed to create user"});let b=await e.context.password.hash(n);if(await e.context.internalAdapter.linkAccount({userId:u.id,providerId:"credential",accountId:u.id,password:b,expiresAt:Z(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let p=await L(e.context.secret,u.email),k=`${e.context.baseURL}/verify-email?token=${p}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(u,k,p)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:u,session:null},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:u,session:null}});let x=await e.context.internalAdapter.createSession(u.id,e.request);if(!x)throw new D("BAD_REQUEST",{message:"Failed to create session"});return await P(e,x.id),e.json({user:u,session:x},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:u,session:x}})});import{isTest as Ct}from"std-env";function tt(e){let t="127.0.0.1";if(Ct)return t;let r=["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],o=e instanceof Request?e.headers:e;for(let n of r){let i=o.get(n);if(typeof i=="string"){let s=i.split(",")[0].trim();if(s)return s}}return null}function Bt(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function Dt(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 $t(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function Vt(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async n=>await o.findOne({model:r,where:[{field:"key",value:n}]}),set:async(n,i,s)=>{try{s?await o.update({model:t??"rateLimit",where:[{field:"key",value:n}],update:{count:i.count,lastRequest:i.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:n,count:i.count,lastRequest:i.lastRequest}})}catch(a){w.error("Error setting rate limit",a)}}}}var rt=new Map;function zt(e){return e.rateLimit.storage==="secondary-storage"?{get:async r=>{let o=await e.options.secondaryStorage?.get(r);return o?JSON.parse(o):void 0},set:async(r,o)=>{await e.options.secondaryStorage?.set?.(r,JSON.stringify(o))}}:e.rateLimit.storage==="memory"?{async get(r){return rt.get(r)},async set(r,o,n){rt.set(r,o)}}:Vt(e,e.rateLimit.tableName)}async function ot(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),n=t.rateLimit.window,i=t.rateLimit.max,s=tt(e)+o,c=jt().find(g=>g.pathMatcher(o));c&&(n=c.window,i=c.max);for(let g of t.options.plugins||[])if(g.rateLimit){let u=g.rateLimit.find(b=>b.pathMatcher(o));if(u){n=u.window,i=u.max;break}}if(t.rateLimit.customRules){let g=t.rateLimit.customRules[o];g&&(n=g.window,i=g.max)}let d=zt(t),l=await d.get(s),h=Date.now();if(!l)await d.set(s,{key:s,count:1,lastRequest:h});else{let g=h-l.lastRequest;if(Bt(i,n,l)){let u=$t(l.lastRequest,n);return Dt(u)}else g>n*1e3?await d.set(s,{...l,count:1,lastRequest:h}):await d.set(s,{...l,count:l.count+1,lastRequest:h})}}function jt(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:3}]}import{APIError as Fs}from"better-call";function Nt(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()||[],i={...{signInOAuth:Ce,callbackOAuth:qe,getCSRFToken:Ke,getSession:X(),signOut:Me,signUpEmail:et(),signInEmail:Be,forgetPassword:Ne,resetPassword:He,verifyEmail:Ie,sendVerificationEmail:Le,changeEmail:Je,changePassword:Qe,setPassword:Ge,updateUser:Ze(),deleteUser:We,forgetPasswordCallback:Fe,listSessions:Pe(),revokeSession:Oe,revokeSessions:_e},...r,ok:Xe,error:Ye},s={};for(let[a,c]of Object.entries(i))s[a]=async(d={})=>{let l=await e;for(let u of t.plugins||[])if(u.hooks?.before){for(let b of u.hooks.before)if(b.matcher({...c,...d,context:l})){let p=await b.handler({...d,context:{...l,...d?.context}});p&&"context"in p&&(l={...l,...p.context})}}let h;try{h=await c({...d,context:{...l,...d.context}})}catch(u){if(u instanceof nt){let b=t.plugins?.map(p=>{if(p.hooks?.after)return p.hooks.after}).filter(p=>p!==void 0).flat();if(!b?.length)throw u;let x=new Response(JSON.stringify(u.body),{status:Mt[u.status],headers:u.headers});for(let p of b||[])if(p.matcher(d)){let q=Object.assign(d,{context:{...e,returned:x}}),C=await p.handler(q);C&&"response"in C&&(x=C.response)}return x}throw u}let g=h;for(let u of t.plugins||[])if(u.hooks?.after){for(let b of u.hooks.after)if(b.matcher(d)){let p=Object.assign(d,{context:{...e,returned:g}}),k=await b.handler(p);k&&"response"in k&&(g=k.response)}}return g},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 Vs=(e,t)=>{let{api:r,middlewares:o}=Nt(e,t),n=new URL(e.baseURL).pathname;return qt(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:ce},...o],async onRequest(i){for(let s of e.options.plugins||[])if(s.onRequest){let a=await s.onRequest(i,e);if(a)return a}return ot(i,e)},async onResponse(i){for(let s of e.options.plugins||[])if(s.onResponse){let a=await s.onResponse(i,e);if(a)return a.response}return i},onError(i){if(t.onAPIError?.throw)throw i;if(t.onAPIError?.onError){t.onAPIError.onError(i,e);return}let s=t.logger?.verboseLogging?w:void 0;t.logger?.disabled!==!0&&(i instanceof nt?(i.status==="INTERNAL_SERVER_ERROR"&&w.error(i),s?.error(i.message)):w?.error(i))}})};export{Fs as APIError,qe as callbackOAuth,Je as changeEmail,Qe as changePassword,m as createAuthEndpoint,$ as createAuthMiddleware,L as createEmailVerificationToken,ce as csrfMiddleware,We as deleteUser,Ye as error,Ne as forgetPassword,Fe as forgetPasswordCallback,Ke as getCSRFToken,Nt as getEndpoints,X as getSession,ee as getSessionFromCtx,Pe as listSessions,Xe as ok,ae as optionsMiddleware,He as resetPassword,Oe as revokeSession,_e as revokeSessions,Vs as router,Le as sendVerificationEmail,_ as sessionMiddleware,Ge as setPassword,Be as signInEmail,Ce as signInOAuth,Me as signOut,et as signUpEmail,Ze as updateUser,Ie as verifyEmail};
@@ -2,8 +2,8 @@ import * as nanostores from 'nanostores';
2
2
  import { A as AccessControl, S as StatementsPrimitive, R as Role } from '../statement-CfnyN34h.js';
3
3
  import * as _better_fetch_fetch from '@better-fetch/fetch';
4
4
  import { BetterFetchOption } from '@better-fetch/fetch';
5
- import { o as organization, l as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, e as anonymous, i as admin, j as genericOAuth, k as multiSession } from '../index-BSzofgdu.js';
6
- export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-BSzofgdu.js';
5
+ import { o as organization, l as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, e as anonymous, i as admin, j as genericOAuth, k as multiSession } from '../index-C5jX2KrN.js';
6
+ export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-C5jX2KrN.js';
7
7
  import { P as Prettify } from '../helper-DPDj8Nix.js';
8
8
  import { F as FieldAttribute, B as BetterAuthOptions, b as BetterAuthPlugin } from '../auth-DFDxqxWC.js';
9
9
  import 'zod';
@@ -1 +1 @@
1
- import{atom as d}from"nanostores";var c=class extends Error{path;constructor(t,a){super(t),this.path=a}},p=class{constructor(t){this.s=t;this.statements=t}statements;newRole(t){return new m(t)}},m=class n{statements;constructor(t){this.statements=t}authorize(t,a){for(let[i,e]of Object.entries(t)){let s=this.statements[i];if(!s)return{success:!1,error:`You are not allowed to access resource: ${i}`};let o=a==="OR"?e.some(r=>s.includes(r)):e.every(r=>s.includes(r));return o?{success:o}:{success:!1,error:`unauthorized to access resource "${i}"`}}return{success:!1,error:"Not authorized"}}static fromString(t){let a=JSON.parse(t);if(typeof a!="object")throw new c("statements is not an object",".");for(let[i,e]of Object.entries(a)){if(typeof i!="string")throw new c("invalid resource identifier",i);if(!Array.isArray(e))throw new c("actions is not an array",i);for(let s=0;s<e.length;s++)if(typeof e[s]!="string")throw new c("action is not a string",`${i}[${s}]`)}return new n(a)}toString(){return JSON.stringify(this.statements)}};var y=n=>new p(n),h={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},f=y(h),k=f.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),B=f.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),F=f.newRole({organization:[],member:[],invitation:[]});import{createFetch as Z}from"@better-fetch/fetch";import{env as q}from"std-env";import"nanostores";import{betterFetch as D}from"@better-fetch/fetch";import{atom as pe}from"nanostores";import"@better-fetch/fetch";import{atom as S,onMount as O}from"nanostores";var l=(n,t,a,i)=>{let e=S({data:null,error:null,isPending:!1,isRefetching:!1}),s=()=>{let r=typeof i=="function"?i({data:e.get().data,error:e.get().error,isPending:e.get().isPending}):i;return a(t,{...r,onSuccess:async u=>{e.set({data:u.data,error:null,isPending:!1,isRefetching:!1}),await r?.onSuccess?.(u)},async onError(u){e.set({error:u.error,data:null,isPending:!1,isRefetching:!1}),await r?.onError?.(u)},async onRequest(u){let g=e.get();e.set({isPending:g.data===null,data:g.data,error:null,isRefetching:!0}),await r?.onRequest?.(u)}})};n=Array.isArray(n)?n:[n];let o=!1;for(let r of n)r.subscribe(()=>{o?s():O(e,()=>(s(),o=!0,()=>{e.off(),r.off()}))});return e};var ve=n=>{let t=d(void 0),a=d(!1),i=d(!1);return{id:"organization",$InferServerPlugin:{},getActions:e=>({$Infer:{ActiveOrganization:{},Organization:{},Invitation:{},Member:{}},organization:{setActive(s){t.set(s)},hasPermission:async s=>await e("/organization/has-permission",{method:"POST",body:{permission:s.permission},...s.fetchOptions})}}),getAtoms:e=>{let s=l(a,"/organization/list",e,{method:"GET"}),o=l([t,i],"/organization/activate",e,()=>({method:"POST",credentials:"include",body:{orgId:t.get()}}));return{_listOrg:a,_activeOrgSignal:i,activeOrganization:o,listOrganizations:s}},atomListeners:[{matcher(e){return e==="/organization/create"||e==="/organization/delete"},signal:"_listOrg"},{matcher(e){return e.startsWith("/organization")},signal:"_activeOrgSignal"}]}};var Ie=()=>({id:"username",$InferServerPlugin:{}});import{WebAuthnError as A,startAuthentication as T,startRegistration as b}from"@simplewebauthn/browser";import{atom as R}from"nanostores";var x=(n,{_listPasskeys:t})=>({signIn:{passkey:async(e,s)=>{let o=await n("/passkey/generate-authenticate-options",{method:"POST",body:{email:e?.email}});if(!o.data)return o;try{let r=await T(o.data,e?.autoFill||!1),u=await n("/passkey/verify-authentication",{body:{response:r},...e?.fetchOptions,...s,method:"POST"});if(!u.data)return u}catch(r){console.log(r)}}},passkey:{addPasskey:async(e,s)=>{let o=await n("/passkey/generate-register-options",{method:"GET"});if(!o.data)return o;try{let r=await b(o.data),u=await n("/passkey/verify-registration",{...e?.fetchOptions,...s,body:{response:r,name:e?.name},method:"POST"});if(!u.data)return u;t.set(Math.random())}catch(r){return r instanceof A?r.code==="ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED"?{data:null,error:{message:"previously registered",status:400,statusText:"BAD_REQUEST"}}:r.code==="ERROR_CEREMONY_ABORTED"?{data:null,error:{message:"registration cancelled",status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:r.message,status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:r instanceof Error?r.message:"unknown error",status:500,statusText:"INTERNAL_SERVER_ERROR"}}}}},$Infer:{}}),$e=()=>{let n=R();return{id:"passkey",$InferServerPlugin:{},getActions:t=>x(t,{_listPasskeys:n}),getAtoms(t){return{listPasskeys:l(n,"/passkey/list-user-passkeys",t,{method:"GET",credentials:"include"}),_listPasskeys:n}},pathMethods:{"/passkey/register":"POST","/passkey/authenticate":"POST"},atomListeners:[{matcher(t){return t==="/passkey/verify-registration"||t==="/passkey/delete-passkey"},signal:"_listPasskeys"}]}};var Ne=(n={redirect:!0,twoFactorPage:"/"})=>({id:"two-factor",$InferServerPlugin:{},atomListeners:[{matcher:t=>t==="/two-factor/enable"||t==="/two-factor/send-otp"||t==="/two-factor/disable",signal:"_sessionSignal"}],pathMethods:{"/two-factor/disable":"POST","/two-factor/enable":"POST","/two-factor/send-otp":"POST","/two-factor/generate-backup-codes":"POST"},fetchPlugins:[{id:"two-factor",name:"two-factor",hooks:{async onSuccess(t){t.data?.twoFactorRedirect&&(n.redirect||n.twoFactorPage)&&typeof window<"u"&&(window.location.href=n.twoFactorPage)}}}]});var We=()=>({id:"magic-link",$InferServerPlugin:{}});var Ge=()=>({id:"phoneNumber",$InferServerPlugin:{},atomListeners:[{matcher(n){return n==="/phone-number/update"||n==="/phone-number/verify"},signal:"_sessionSignal"}]});var He=()=>({id:"anonymous",$InferServerPlugin:{},pathMethods:{"/sign-in/anonymous":"POST"}});var Je=n=>({id:"additional-fields-client",$InferServerPlugin:{}});var Ve=()=>({id:"better-auth-client",$InferServerPlugin:{},pathMethods:{"/admin/list-users":"GET"}});var Ye=()=>({id:"generic-oauth-client",$InferServerPlugin:{}});var et=()=>({id:"multi-session",$InferServerPlugin:{},pathMethods:{"/multi-session/sign-out-device-sessions":"POST"},atomListeners:[{matcher(n){return n==="/multi-session/set-active"},signal:"_sessionSignal"}]});export{Ve as adminClient,He as anonymousClient,Ye as genericOAuthClient,x as getPasskeyActions,Je as inferAdditionalFields,We as magicLinkClient,et as multiSessionClient,ve as organizationClient,$e as passkeyClient,Ge as phoneNumberClient,Ne as twoFactorClient,Ie as usernameClient};
1
+ import{atom as d}from"nanostores";var c=class extends Error{path;constructor(n,a){super(n),this.path=a}},p=class{constructor(n){this.s=n;this.statements=n}statements;newRole(n){return new m(n)}},m=class t{statements;constructor(n){this.statements=n}authorize(n,a){for(let[i,e]of Object.entries(n)){let s=this.statements[i];if(!s)return{success:!1,error:`You are not allowed to access resource: ${i}`};let o=a==="OR"?e.some(r=>s.includes(r)):e.every(r=>s.includes(r));return o?{success:o}:{success:!1,error:`unauthorized to access resource "${i}"`}}return{success:!1,error:"Not authorized"}}static fromString(n){let a=JSON.parse(n);if(typeof a!="object")throw new c("statements is not an object",".");for(let[i,e]of Object.entries(a)){if(typeof i!="string")throw new c("invalid resource identifier",i);if(!Array.isArray(e))throw new c("actions is not an array",i);for(let s=0;s<e.length;s++)if(typeof e[s]!="string")throw new c("action is not a string",`${i}[${s}]`)}return new t(a)}toString(){return JSON.stringify(this.statements)}};var y=t=>new p(t),h={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},f=y(h),k=f.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),B=f.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),F=f.newRole({organization:[],member:[],invitation:[]});import{createFetch as Z}from"@better-fetch/fetch";import{env as q}from"std-env";import"nanostores";import{betterFetch as D}from"@better-fetch/fetch";import{atom as pe}from"nanostores";import"@better-fetch/fetch";import{atom as S,onMount as O}from"nanostores";var l=(t,n,a,i)=>{let e=S({data:null,error:null,isPending:!1,isRefetching:!1}),s=()=>{let r=typeof i=="function"?i({data:e.get().data,error:e.get().error,isPending:e.get().isPending}):i;return a(n,{...r,onSuccess:async u=>{e.set({data:u.data,error:null,isPending:!1,isRefetching:!1}),await r?.onSuccess?.(u)},async onError(u){e.set({error:u.error,data:null,isPending:!1,isRefetching:!1}),await r?.onError?.(u)},async onRequest(u){let g=e.get();e.set({isPending:g.data===null,data:g.data,error:null,isRefetching:!0}),await r?.onRequest?.(u)}})};t=Array.isArray(t)?t:[t];let o=!1;for(let r of t)r.subscribe(()=>{o?s():O(e,()=>(s(),o=!0,()=>{e.off(),r.off()}))});return e};var ve=t=>{let n=d(void 0),a=d(!1),i=d(!1);return{id:"organization",$InferServerPlugin:{},getActions:e=>({$Infer:{ActiveOrganization:{},Organization:{},Invitation:{},Member:{}},organization:{setActive(s){n.set(s)},hasPermission:async s=>await e("/organization/has-permission",{method:"POST",body:{permission:s.permission},...s.fetchOptions})}}),getAtoms:e=>{let s=l(a,"/organization/list",e,{method:"GET"}),o=l([n,i],"/organization/activate",e,()=>({method:"POST",credentials:"include",body:{orgId:n.get()}}));return{_listOrg:a,_activeOrgSignal:i,activeOrganization:o,listOrganizations:s}},atomListeners:[{matcher(e){return e==="/organization/create"||e==="/organization/delete"},signal:"_listOrg"},{matcher(e){return e.startsWith("/organization")},signal:"_activeOrgSignal"}]}};var Ie=()=>({id:"username",$InferServerPlugin:{}});import{WebAuthnError as A,startAuthentication as T,startRegistration as b}from"@simplewebauthn/browser";import{atom as R}from"nanostores";var x=(t,{_listPasskeys:n})=>({signIn:{passkey:async(e,s)=>{let o=await t("/passkey/generate-authenticate-options",{method:"POST",body:{email:e?.email}});if(!o.data)return o;try{let r=await T(o.data,e?.autoFill||!1),u=await t("/passkey/verify-authentication",{body:{response:r},...e?.fetchOptions,...s,method:"POST"});if(!u.data)return u}catch(r){console.log(r)}}},passkey:{addPasskey:async(e,s)=>{let o=await t("/passkey/generate-register-options",{method:"GET"});if(!o.data)return o;try{let r=await b(o.data),u=await t("/passkey/verify-registration",{...e?.fetchOptions,...s,body:{response:r,name:e?.name},method:"POST"});if(!u.data)return u;n.set(Math.random())}catch(r){return r instanceof A?r.code==="ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED"?{data:null,error:{message:"previously registered",status:400,statusText:"BAD_REQUEST"}}:r.code==="ERROR_CEREMONY_ABORTED"?{data:null,error:{message:"registration cancelled",status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:r.message,status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:r instanceof Error?r.message:"unknown error",status:500,statusText:"INTERNAL_SERVER_ERROR"}}}}},$Infer:{}}),$e=()=>{let t=R();return{id:"passkey",$InferServerPlugin:{},getActions:n=>x(n,{_listPasskeys:t}),getAtoms(n){return{listPasskeys:l(t,"/passkey/list-user-passkeys",n,{method:"GET",credentials:"include"}),_listPasskeys:t}},pathMethods:{"/passkey/register":"POST","/passkey/authenticate":"POST"},atomListeners:[{matcher(n){return n==="/passkey/verify-registration"||n==="/passkey/delete-passkey"},signal:"_listPasskeys"}]}};var Ne=(t={redirect:!0,twoFactorPage:"/"})=>({id:"two-factor",$InferServerPlugin:{},atomListeners:[{matcher:n=>n.startsWith("/two-factor/"),signal:"_sessionSignal"}],pathMethods:{"/two-factor/disable":"POST","/two-factor/enable":"POST","/two-factor/send-otp":"POST","/two-factor/generate-backup-codes":"POST"},fetchPlugins:[{id:"two-factor",name:"two-factor",hooks:{async onSuccess(n){n.data?.twoFactorRedirect&&(t.redirect||t.twoFactorPage)&&typeof window<"u"&&(window.location.href=t.twoFactorPage)}}}]});var We=()=>({id:"magic-link",$InferServerPlugin:{}});var Ge=()=>({id:"phoneNumber",$InferServerPlugin:{},atomListeners:[{matcher(t){return t==="/phone-number/update"||t==="/phone-number/verify"},signal:"_sessionSignal"}]});var He=()=>({id:"anonymous",$InferServerPlugin:{},pathMethods:{"/sign-in/anonymous":"POST"}});var Je=t=>({id:"additional-fields-client",$InferServerPlugin:{}});var Ve=()=>({id:"better-auth-client",$InferServerPlugin:{},pathMethods:{"/admin/list-users":"GET"}});var Ye=()=>({id:"generic-oauth-client",$InferServerPlugin:{}});var et=()=>({id:"multi-session",$InferServerPlugin:{},pathMethods:{"/multi-session/sign-out-device-sessions":"POST"},atomListeners:[{matcher(t){return t==="/multi-session/set-active"},signal:"_sessionSignal"}]});export{Ve as adminClient,He as anonymousClient,Ye as genericOAuthClient,x as getPasskeyActions,Je as inferAdditionalFields,We as magicLinkClient,et as multiSessionClient,ve as organizationClient,$e as passkeyClient,Ge as phoneNumberClient,Ne as twoFactorClient,Ie as usernameClient};
package/dist/crypto.js CHANGED
@@ -1 +1 @@
1
- import{xchacha20poly1305 as f}from"@noble/ciphers/chacha";import{bytesToHex as B,hexToBytes as S,utf8ToBytes as T}from"@noble/ciphers/utils";import{managedNonce as u}from"@noble/ciphers/webcrypto";import{sha256 as g}from"oslo/crypto";import p from"crypto";function i(t,e){let r=new Uint8Array(t),n=new Uint8Array(e);if(r.length!==n.length)return!1;let o=0;for(let a=0;a<r.length;a++)o|=r[a]^n[a];return o===0}import{decodeHex as l,encodeHex as c}from"oslo/encoding";import{scryptAsync as d}from"@noble/hashes/scrypt";import{getRandomValues as h}from"crypto";var s={N:16384,r:16,p:1,dkLen:64};async function y(t,e){return await d(t.normalize("NFKC"),e,{N:s.N,p:s.p,r:s.r,dkLen:s.dkLen,maxmem:128*s.N*s.r*2})}var D=async t=>{let e=c(h(new Uint8Array(16))),r=await y(t,e);return`${e}:${c(r)}`},H=async(t,e)=>{let[r,n]=t.split(":"),o=await y(e,r);return i(o,l(n))};import{getRandomValues as w}from"crypto";function A(t){return t.toString(2).padStart(8,"0")}function x(t){return[...t].map(e=>A(e)).join("")}function m(t){return parseInt(x(t),2)}function C(){let t=new ArrayBuffer(8),e=w(new Uint8Array(t));return e[0]=63,e[1]=e[1]|240,new DataView(t).getFloat64(0)-1}function b(t){if(t<0||!Number.isInteger(t))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let e=(t-1).toString(2).length,r=e%8,n=new Uint8Array(Math.ceil(e/8));crypto.getRandomValues(n),r!==0&&(n[0]&=(1<<r)-1);let o=m(n);for(;o>=t;)crypto.getRandomValues(n),r!==0&&(n[0]&=(1<<r)-1),o=m(n);return o}function I(t,e){let r="";for(let n=0;n<t;n++)r+=e[b(e.length)];return r}function K(...t){let e=new Set(t),r="";for(let n of e)n==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":n==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":n==="0-9"?r+="0123456789":r+=n;return r}async function M(t,e){let r=new TextEncoder,n={name:"HMAC",hash:"SHA-256"},o=await p.subtle.importKey("raw",r.encode(t),n,!1,["sign","verify"]),a=await p.subtle.sign(n.name,o,r.encode(e));return btoa(String.fromCharCode(...new Uint8Array(a)))}var Z=async({key:t,data:e})=>{let r=await g(new TextEncoder().encode(t)),n=T(e),o=u(f)(new Uint8Array(r));return B(o.encrypt(n))},j=async({key:t,data:e})=>{let r=await g(new TextEncoder().encode(t)),n=S(e),o=u(f)(new Uint8Array(r));return new TextDecoder().decode(o.decrypt(n))};export{K as alphabet,A as byteToBinary,x as bytesToBinary,m as bytesToInteger,i as constantTimeEqual,b as generateRandomInteger,I as generateRandomString,D as hashPassword,M as hs256,C as random,j as symmetricDecrypt,Z as symmetricEncrypt,H as verifyPassword};
1
+ import{xchacha20poly1305 as u}from"@noble/ciphers/chacha";import{bytesToHex as B,hexToBytes as S,utf8ToBytes as T}from"@noble/ciphers/utils";import{managedNonce as g}from"@noble/ciphers/webcrypto";import{sha256 as l}from"oslo/crypto";import f from"uncrypto";function c(t,e){let r=new Uint8Array(t),n=new Uint8Array(e);if(r.length!==n.length)return!1;let o=0;for(let a=0;a<r.length;a++)o|=r[a]^n[a];return o===0}import{decodeHex as d,encodeHex as y}from"oslo/encoding";import{scryptAsync as h}from"@noble/hashes/scrypt";import{getRandomValues as w}from"uncrypto";var s={N:16384,r:16,p:1,dkLen:64};async function m(t,e){return await h(t.normalize("NFKC"),e,{N:s.N,p:s.p,r:s.r,dkLen:s.dkLen,maxmem:128*s.N*s.r*2})}var D=async t=>{let e=y(w(new Uint8Array(16))),r=await m(t,e);return`${e}:${y(r)}`},H=async(t,e)=>{let[r,n]=t.split(":"),o=await m(e,r);return c(o,d(n))};import i from"uncrypto";function A(t){return t.toString(2).padStart(8,"0")}function x(t){return[...t].map(e=>A(e)).join("")}function p(t){return parseInt(x(t),2)}function C(){let t=new ArrayBuffer(8),e=i.getRandomValues(new Uint8Array(t));return e[0]=63,e[1]=e[1]|240,new DataView(t).getFloat64(0)-1}function b(t){if(t<0||!Number.isInteger(t))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let e=(t-1).toString(2).length,r=e%8,n=new Uint8Array(Math.ceil(e/8));i.getRandomValues(n),r!==0&&(n[0]&=(1<<r)-1);let o=p(n);for(;o>=t;)i.getRandomValues(n),r!==0&&(n[0]&=(1<<r)-1),o=p(n);return o}function I(t,e){let r="";for(let n=0;n<t;n++)r+=e[b(e.length)];return r}function K(...t){let e=new Set(t),r="";for(let n of e)n==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":n==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":n==="0-9"?r+="0123456789":r+=n;return r}async function M(t,e){let r=new TextEncoder,n={name:"HMAC",hash:"SHA-256"},o=await f.subtle.importKey("raw",r.encode(t),n,!1,["sign","verify"]),a=await f.subtle.sign(n.name,o,r.encode(e));return btoa(String.fromCharCode(...new Uint8Array(a)))}var Z=async({key:t,data:e})=>{let r=await l(new TextEncoder().encode(t)),n=T(e),o=g(u)(new Uint8Array(r));return B(o.encrypt(n))},j=async({key:t,data:e})=>{let r=await l(new TextEncoder().encode(t)),n=S(e),o=g(u)(new Uint8Array(r));return new TextDecoder().decode(o.decrypt(n))};export{K as alphabet,A as byteToBinary,x as bytesToBinary,p as bytesToInteger,c as constantTimeEqual,b as generateRandomInteger,I as generateRandomString,D as hashPassword,M as hs256,C as random,j as symmetricDecrypt,Z as symmetricEncrypt,H as verifyPassword};
package/dist/db.js CHANGED
@@ -1,4 +1,4 @@
1
- var q=(e,s="ms")=>new Date(Date.now()+(s==="sec"?e*1e3:e));var h=e=>{let s=e.plugins?.reduce((t,i)=>{let o=i.schema;if(!o)return t;for(let[l,u]of Object.entries(o))t[l]={fields:{...t[l]?.fields,...u.fields},tableName:u.tableName||l};return t},{}),a=e.rateLimit?.storage==="database",n={rateLimit:{tableName:e.rateLimit?.tableName||"rateLimit",fields:{key:{type:"string",fieldName:e.rateLimit?.fields?.key||"key"},count:{type:"number",fieldName:e.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",fieldName:e.rateLimit?.fields?.lastRequest||"lastRequest"}}}},{user:d,session:r,account:c,...f}=s||{};return{user:{tableName:e.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:e.user?.fields?.name||"name"},email:{type:"string",unique:!0,required:!0,fieldName:e.user?.fields?.email||"email"},emailVerified:{type:"boolean",defaultValue:()=>!1,required:!0,fieldName:e.user?.fields?.emailVerified||"emailVerified"},image:{type:"string",required:!1,fieldName:e.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.updatedAt||"updatedAt"},...d?.fields,...e.user?.additionalFields},order:1},session:{tableName:e.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:e.session?.fields?.expiresAt||"expiresAt"},ipAddress:{type:"string",required:!1,fieldName:e.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:e.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:e.session?.fields?.userId||"userId",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0},...r?.fields,...e.session?.additionalFields},order:2},account:{tableName:e.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:e.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:e.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:e.account?.fields?.userId||"userId"},accessToken:{type:"string",required:!1,fieldName:e.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,fieldName:e.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,fieldName:e.account?.fields?.idToken||"idToken"},expiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.expiresAt||"expiresAt"},password:{type:"string",required:!1,fieldName:e.account?.fields?.password||"password"},...c?.fields},order:3},verification:{tableName:e.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:e.verification?.fields?.identifier||"identifier"},value:{type:"string",required:!0,fieldName:e.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:e.verification?.fields?.expiresAt||"expiresAt"}},order:4},...f,...a?n:{}}};import{nanoid as E}from"nanoid";var A=e=>E(e);var F=class extends Error{constructor(s,a){super(s),this.name="BetterAuthError",this.message=s,this.cause=a,this.stack=""}};import{Kysely as S,MssqlDialect as L}from"kysely";import{MysqlDialect as R,PostgresDialect as B,SqliteDialect as V}from"kysely";function M(e){if("dialect"in e)return M(e.dialect);if("createDriver"in e){if(e instanceof V)return"sqlite";if(e instanceof R)return"mysql";if(e instanceof B)return"postgres";if(e instanceof L)return"mssql"}return"aggregate"in e?"sqlite":"getConnection"in e?"mysql":"connect"in e?"postgres":null}var k=async e=>{let s=e.database;if("db"in s)return{kysely:s.db,databaseType:s.type};if("dialect"in s)return{kysely:new S({dialect:s.dialect}),databaseType:s.type};let a,n=M(s);return"createDriver"in s&&(a=s),"aggregate"in s&&(a=new V({database:s})),"getConnection"in s&&(a=new R({pool:s})),"connect"in s&&(a=new B({pool:s})),{kysely:a?new S({dialect:a}):null,databaseType:n}};function N(e){if(!e)return{and:null,or:null};let s={and:[],or:[]};return e.forEach(a=>{let{field:n,value:d,operator:r="=",connector:c="AND"}=a,f=t=>r.toLowerCase()==="in"?t(n,"in",Array.isArray(d)?d:[d]):r==="contains"?t(n,"like",`%${d}%`):r==="starts_with"?t(n,"like",`${d}%`):r==="ends_with"?t(n,"like",`%${d}`):t(n,r,d);c==="OR"?s.or.push(f):s.and.push(f)}),{and:s.and.length?s.and:null,or:s.or.length?s.or:null}}function v(e,s,a){for(let n in e){let d=s[n]||Object.values(s).find(r=>r.fieldName===n);e[n]===0&&d.type==="boolean"&&a?.boolean&&(e[n]=!1),e[n]===1&&d?.type==="boolean"&&a?.boolean&&(e[n]=!0),d?.type==="date"&&(e[n]instanceof Date||(e[n]=new Date(e[n])))}return e}function U(e,s){for(let a in e)typeof e[a]=="boolean"&&s?.boolean&&(e[a]=e[a]?1:0),e[a]instanceof Date&&(e[a]=e[a].toISOString());return e}var K=(e,s)=>({id:"kysely",async create(a){let{model:n,data:d,select:r}=a;s?.transform&&(d=U(d,s.transform)),s?.generateId!==void 0&&(d.id=s.generateId?s.generateId():void 0);let c=await e.insertInto(n).values(d).returningAll().executeTakeFirst();if(s?.transform){let f=s.transform.schema[n];c=f?v(d,f,s.transform):c}return r?.length&&(c=c?r.reduce((t,i)=>c?.[i]?{...t,[i]:c[i]}:t,{}):null),c},async findOne(a){let{model:n,where:d,select:r}=a,{and:c,or:f}=N(d),t=e.selectFrom(n).selectAll();c&&(t=t.where(o=>o.and(c.map(l=>l(o))))),f&&(t=t.where(o=>o.or(f.map(l=>l(o)))));let i=await t.executeTakeFirst();if(r?.length&&(i=i?r.reduce((l,u)=>i?.[u]?{...l,[u]:i[u]}:l,{}):null),s?.transform){let o=s.transform.schema[n];return i=i&&o?v(i,o,s.transform):i,i||null}return i||null},async findMany(a){let{model:n,where:d,limit:r,offset:c,sortBy:f}=a,t=e.selectFrom(n),{and:i,or:o}=N(d);i&&(t=t.where(u=>u.and(i.map(m=>m(u))))),o&&(t=t.where(u=>u.or(o.map(m=>m(u))))),t=t.limit(r||100),c&&(t=t.offset(c)),f&&(t=t.orderBy(f.field,f.direction));let l=await t.selectAll().execute();if(s?.transform){let u=s.transform.schema[n];return u?l.map(m=>v(m,u,s.transform)):l}return l},async update(a){let{model:n,where:d,update:r}=a,{and:c,or:f}=N(d);s?.transform&&(r=U(r,s.transform)),r.id&&(r.id=void 0);let t=e.updateTable(n).set(r);c&&(t=t.where(o=>o.and(c.map(l=>l(o))))),f&&(t=t.where(o=>o.or(f.map(l=>l(o)))));let i=await t.returningAll().executeTakeFirst()||null;if(s?.transform){let o=s.transform.schema[n];return o?v(i,o,s.transform):i}return i},async delete(a){let{model:n,where:d}=a,{and:r,or:c}=N(d),f=e.deleteFrom(n);r&&(f=f.where(t=>t.and(r.map(i=>i(t))))),c&&(f=f.where(t=>t.or(c.map(i=>i(t))))),await f.execute()},async deleteMany(a){let{model:n,where:d}=a,{and:r,or:c}=N(d),f=e.deleteFrom(n);r&&(f=f.where(t=>t.and(r.map(i=>i(t))))),c&&(f=f.where(t=>t.or(c.map(i=>i(t))))),await f.execute()}});async function me(e){if(!e.database)throw new F("Database configuration is required");if("create"in e.database)return e.database;let{kysely:s,databaseType:a}=await k(e);if(!s)throw new F("Failed to initialize database adapter");let n=h(e),d={};for(let r of Object.values(n))d[r.tableName]=r.fields;return K(s,{transform:{schema:d,date:!0,boolean:a==="sqlite"},generateId:"generateId"in e.database?e.database.generateId:void 0})}function D(e,s){let a={id:s.id};for(let n in e){let d=e[n],r=s[n];a[d.fieldName||n]=r}return a}function g(e,s){if(!s)return null;let a={id:s.id};for(let[n,d]of Object.entries(e))a[n]=s[d.fieldName||n];return a}function C(e,s){let a=s.hooks,n=h(s.options);async function d(c,f,t){let i=c,o=n[f];for(let m of a||[]){let p=m[f]?.create?.before;if(p){let y=await p(c);if(y===!1)return null;typeof y=="object"&&"data"in y&&(i=y.data)}}let l=t?await t.fn(i):null,u=!t||t.executeMainFn?await e.create({model:o.tableName,data:{...D(o.fields,i),id:i.id||A()}}):l;for(let m of a||[]){let p=m[f]?.create?.after;p&&await p(u)}return g(o.fields,u)}async function r(c,f,t,i){let o=c;for(let m of a||[]){let p=m[t]?.update?.before;if(p){let y=await p(c);if(y===!1)return null;o=typeof y=="object"?y.data:y}}let l=i?await i.fn(o):null,u=!i||i.executeMainFn?await e.update({model:n[t].tableName,update:D(n[t].fields,o),where:f}):l;for(let m of a||[]){let p=m[t]?.update?.after;p&&await p(u)}return g(n[t].fields,u)}return{createWithHooks:d,updateWithHooks:r}}import{isTest as $}from"std-env";function j(e){let s="127.0.0.1";if($)return s;let a=["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],n=e instanceof Request?e.headers:e;for(let d of a){let r=n.get(d);if(typeof r=="string"){let c=r.split(",")[0].trim();if(c)return c}}return null}var ve=(e,s)=>{let a=s.options,n=a.secondaryStorage,d=a.session?.expiresIn||60*60*24*7,r=h(a),{createWithHooks:c,updateWithHooks:f}=C(e,s);return{createOAuthUser:async(t,i)=>{try{let o=await c({id:A(),createdAt:new Date,updatedAt:new Date,...t},"user"),l=await c({id:A(),...i,userId:o.id||t.id},"account");return{user:o,account:l}}catch(o){return console.log(o),null}},createUser:async t=>await c({id:A(),createdAt:new Date,updatedAt:new Date,emailVerified:!1,...t},"user"),createAccount:async t=>await c({id:A(),createdAt:new Date,updatedAt:new Date,...t},"account"),listSessions:async t=>await e.findMany({model:r.session.tableName,where:[{field:r.session.fields.userId.fieldName||"userId",value:t}]}),listUsers:async(t,i,o,l)=>(await e.findMany({model:r.user.tableName,limit:t,offset:i,sortBy:o,where:l})).map(m=>g(r.user.fields,m)),deleteUser:async t=>{await e.delete({model:r.account.tableName,where:[{field:r.account.fields.userId.fieldName||"userId",value:t}]}),await e.deleteMany({model:r.session.tableName,where:[{field:r.session.fields.userId.fieldName||"userId",value:t}]}),await e.deleteMany({model:r.user.tableName,where:[{field:"id",value:t}]})},createSession:async(t,i,o,l)=>{let u=i instanceof Request?i.headers:i,m={id:A(),userId:t,expiresAt:o?q(60*60*24,"sec"):q(d,"sec"),ipAddress:i&&j(i)||"",userAgent:u?.get("user-agent")||"",...l};return await c(m,"session",n?{fn:async y=>{let b=await e.findOne({model:r.user.tableName,where:[{field:"id",value:t}]});return n.set(y.id,JSON.stringify({session:y,user:b}),d),y},executeMainFn:a.session?.storeSessionInDatabase}:void 0)},findSession:async t=>{if(n){let l=await n.get(t);if(l){let u=JSON.parse(l);return{session:{...u.session,expiresAt:new Date(u.session.expiresAt)},user:{...u.user,createdAt:new Date(u.user.createdAt),updatedAt:new Date(u.user.updatedAt)}}}}let i=await e.findOne({model:r.session.tableName,where:[{value:t,field:"id"}]});if(!i)return null;let o=await e.findOne({model:r.user.tableName,where:[{value:i.userId,field:"id"}]});return o?{session:g(r.session.fields,i),user:g(r.user.fields,o)}:null},findSessions:async t=>{if(n){let u=[];for(let m of t){let p=await n.get(m);if(p){let y=JSON.parse(p),b={session:{...y.session,expiresAt:new Date(y.session.expiresAt)},user:{...y.user,createdAt:new Date(y.user.createdAt),updatedAt:new Date(y.user.updatedAt)}};u.push(b)}}return u}let i=await e.findMany({model:r.session.tableName,where:[{field:"id",value:t,operator:"in"}]}),o=i.map(u=>u.userId),l=await e.findMany({model:r.user.tableName,where:[{field:"id",value:o,operator:"in"}]});return i.map(u=>{let m=l.find(p=>p.id===u.userId);return m?{session:g(r.session.fields,u),user:g(r.user.fields,m)}:null})},updateSession:async(t,i)=>await f(i,[{field:"id",value:t}],"session",n?{async fn(l){let u=await n.get(t),m=null;if(u){let p=JSON.parse(u);m={...p.session,...l},await n.set(t,JSON.stringify({session:m,user:p.user}),p.session.expiresAt?new Date(p.session.expiresAt).getTime():void 0)}else return null},executeMainFn:a.session?.storeSessionInDatabase}:void 0),deleteSession:async t=>{if(n){await n.delete(t),a.session?.storeSessionInDatabase&&await e.delete({model:r.session.tableName,where:[{field:"id",value:t}]});return}await e.delete({model:r.session.tableName,where:[{field:"id",value:t}]})},deleteSessions:async t=>{if(n){let i=await e.findMany({model:r.session.tableName,where:[{field:r.session.fields.userId.fieldName||"userId",value:t}]});for(let o of i)await n.delete(o.id);a.session?.storeSessionInDatabase&&await e.delete({model:r.session.tableName,where:[{field:r.session.fields.userId.fieldName||"userId",value:t}]});return}await e.delete({model:r.session.tableName,where:[{field:r.session.fields.userId.fieldName||"userId",value:t}]})},findUserByEmail:async(t,i)=>{let o=await e.findOne({model:r.user.tableName,where:[{value:t.toLowerCase(),field:r.user.fields.email.fieldName||"email"}]});if(!o)return null;if(i?.includeAccounts){let l=await e.findMany({model:r.account.tableName,where:[{value:o.id,field:r.account.fields.userId.fieldName||"userId"}]});return{user:g(r.user.fields,o),accounts:l.map(u=>g(r.account.fields,u))}}return{user:g(r.user.fields,o),accounts:[]}},findUserById:async t=>await e.findOne({model:r.user.tableName,where:[{field:"id",value:t}]}),linkAccount:async t=>await c({id:A(),...t},"account"),updateUser:async(t,i)=>await f(i,[{field:"id",value:t}],"user"),updateUserByEmail:async(t,i)=>await f(i,[{field:r.user.fields.email.fieldName||"email",value:t}],"user"),updatePassword:async(t,i)=>await f({password:i},[{field:r.account.fields.userId.fieldName||"userId",value:t},{field:r.account.fields.providerId.fieldName||"providerId",value:"credential"}],"account"),findAccounts:async t=>(await e.findMany({model:r.account.tableName,where:[{field:r.account.fields.userId.fieldName||"userId",value:t}]})).map(o=>g(r.account.fields,o)),updateAccount:async(t,i)=>await f(i,[{field:"id",value:t}],"account"),createVerificationValue:async t=>await c({id:A(),...t},"verification"),findVerificationValue:async t=>{let i=await e.findOne({model:r.verification.tableName,where:[{field:r.verification.fields.identifier.fieldName||"identifier",value:t}]});return g(r.verification.fields,i)},deleteVerificationValue:async t=>{await e.delete({model:r.verification.tableName,where:[{field:"id",value:t}]})},updateVerificationValue:async(t,i)=>await f(i,[{field:"id",value:t}],"verification")}};var qe=(e,s)=>({type:e,...s});import{z as I}from"zod";function Re(e){return I.object({...Object.keys(e).reduce((a,n)=>{let d=e[n];if(!d)return a;if(d.type==="string[]"||d.type==="number[]")return{...a,[n]:I.array(d.type==="string[]"?I.string():I.number())};let r=I[d.type]();return d?.required===!1&&(r=r.optional()),d?.returned===!1?a:{...a,[n]:r}},{})})}import"kysely";import{createConsola as W}from"consola";var w=W({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),H=e=>({log:(...s)=>{!e?.disabled&&w.log("",...s)},error:(...s)=>{!e?.disabled&&w.error("",...s)},warn:(...s)=>{!e?.disabled&&w.warn("",...s)},info:(...s)=>{!e?.disabled&&w.info("",...s)},debug:(...s)=>{!e?.disabled&&w.debug("",...s)},box:(...s)=>{!e?.disabled&&w.box("",...s)},success:(...s)=>{!e?.disabled&&w.success("",...s)},break:(...s)=>{!e?.disabled&&console.log(`
1
+ var q=(e,s="ms")=>new Date(Date.now()+(s==="sec"?e*1e3:e));var h=e=>{let s=e.plugins?.reduce((t,i)=>{let o=i.schema;if(!o)return t;for(let[l,u]of Object.entries(o))t[l]={fields:{...t[l]?.fields,...u.fields},tableName:u.tableName||l};return t},{}),a=e.rateLimit?.storage==="database",n={rateLimit:{tableName:e.rateLimit?.tableName||"rateLimit",fields:{key:{type:"string",fieldName:e.rateLimit?.fields?.key||"key"},count:{type:"number",fieldName:e.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",fieldName:e.rateLimit?.fields?.lastRequest||"lastRequest"}}}},{user:d,session:r,account:c,...f}=s||{};return{user:{tableName:e.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:e.user?.fields?.name||"name"},email:{type:"string",unique:!0,required:!0,fieldName:e.user?.fields?.email||"email"},emailVerified:{type:"boolean",defaultValue:()=>!1,required:!0,fieldName:e.user?.fields?.emailVerified||"emailVerified"},image:{type:"string",required:!1,fieldName:e.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.updatedAt||"updatedAt"},...d?.fields,...e.user?.additionalFields},order:1},session:{tableName:e.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:e.session?.fields?.expiresAt||"expiresAt"},ipAddress:{type:"string",required:!1,fieldName:e.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:e.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:e.session?.fields?.userId||"userId",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0},...r?.fields,...e.session?.additionalFields},order:2},account:{tableName:e.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:e.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:e.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:e.account?.fields?.userId||"userId"},accessToken:{type:"string",required:!1,fieldName:e.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,fieldName:e.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,fieldName:e.account?.fields?.idToken||"idToken"},expiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.expiresAt||"expiresAt"},password:{type:"string",required:!1,fieldName:e.account?.fields?.password||"password"},...c?.fields},order:3},verification:{tableName:e.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:e.verification?.fields?.identifier||"identifier"},value:{type:"string",required:!0,fieldName:e.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:e.verification?.fields?.expiresAt||"expiresAt"}},order:4},...f,...a?n:{}}};import{nanoid as E}from"nanoid";var A=e=>E(e);var F=class extends Error{constructor(s,a){super(s),this.name="BetterAuthError",this.message=s,this.cause=a,this.stack=""}};import{Kysely as S,MssqlDialect as L}from"kysely";import{MysqlDialect as R,PostgresDialect as B,SqliteDialect as V}from"kysely";function M(e){if("dialect"in e)return M(e.dialect);if("createDriver"in e){if(e instanceof V)return"sqlite";if(e instanceof R)return"mysql";if(e instanceof B)return"postgres";if(e instanceof L)return"mssql"}return"aggregate"in e?"sqlite":"getConnection"in e?"mysql":"connect"in e?"postgres":null}var k=async e=>{let s=e.database;if("db"in s)return{kysely:s.db,databaseType:s.type};if("dialect"in s)return{kysely:new S({dialect:s.dialect}),databaseType:s.type};let a,n=M(s);return"createDriver"in s&&(a=s),"aggregate"in s&&(a=new V({database:s})),"getConnection"in s&&(a=new R({pool:s})),"connect"in s&&(a=new B({pool:s})),{kysely:a?new S({dialect:a}):null,databaseType:n}};function N(e){if(!e)return{and:null,or:null};let s={and:[],or:[]};return e.forEach(a=>{let{field:n,value:d,operator:r="=",connector:c="AND"}=a,f=t=>r.toLowerCase()==="in"?t(n,"in",Array.isArray(d)?d:[d]):r==="contains"?t(n,"like",`%${d}%`):r==="starts_with"?t(n,"like",`${d}%`):r==="ends_with"?t(n,"like",`%${d}`):t(n,r,d);c==="OR"?s.or.push(f):s.and.push(f)}),{and:s.and.length?s.and:null,or:s.or.length?s.or:null}}function v(e,s,a){for(let n in e){let d=s[n]||Object.values(s).find(r=>r.fieldName===n);e[n]===0&&d.type==="boolean"&&a?.boolean&&(e[n]=!1),e[n]===1&&d?.type==="boolean"&&a?.boolean&&(e[n]=!0),d?.type==="date"&&(e[n]instanceof Date||(e[n]=new Date(e[n])))}return e}function U(e,s){for(let a in e)typeof e[a]=="boolean"&&s?.boolean&&(e[a]=e[a]?1:0),e[a]instanceof Date&&(e[a]=e[a].toISOString());return e}var K=(e,s)=>({id:"kysely",async create(a){let{model:n,data:d,select:r}=a;s?.transform&&(d=U(d,s.transform)),s?.generateId!==void 0&&(d.id=s.generateId?s.generateId():void 0);let c=await e.insertInto(n).values(d).returningAll().executeTakeFirst();if(s?.transform){let f=s.transform.schema[n];c=f?v(d,f,s.transform):c}return r?.length&&(c=c?r.reduce((t,i)=>c?.[i]?{...t,[i]:c[i]}:t,{}):null),c},async findOne(a){let{model:n,where:d,select:r}=a,{and:c,or:f}=N(d),t=e.selectFrom(n).selectAll();c&&(t=t.where(o=>o.and(c.map(l=>l(o))))),f&&(t=t.where(o=>o.or(f.map(l=>l(o)))));let i=await t.executeTakeFirst();if(r?.length&&(i=i?r.reduce((l,u)=>i?.[u]?{...l,[u]:i[u]}:l,{}):null),s?.transform){let o=s.transform.schema[n];return i=i&&o?v(i,o,s.transform):i,i||null}return i||null},async findMany(a){let{model:n,where:d,limit:r,offset:c,sortBy:f}=a,t=e.selectFrom(n),{and:i,or:o}=N(d);i&&(t=t.where(u=>u.and(i.map(m=>m(u))))),o&&(t=t.where(u=>u.or(o.map(m=>m(u))))),t=t.limit(r||100),c&&(t=t.offset(c)),f&&(t=t.orderBy(f.field,f.direction));let l=await t.selectAll().execute();if(s?.transform){let u=s.transform.schema[n];return u?l.map(m=>v(m,u,s.transform)):l}return l},async update(a){let{model:n,where:d,update:r}=a,{and:c,or:f}=N(d);s?.transform&&(r=U(r,s.transform)),r.id&&(r.id=void 0);let t=e.updateTable(n).set(r);c&&(t=t.where(o=>o.and(c.map(l=>l(o))))),f&&(t=t.where(o=>o.or(f.map(l=>l(o)))));let i=await t.returningAll().executeTakeFirst()||null;if(s?.transform){let o=s.transform.schema[n];return o?v(i,o,s.transform):i}return i},async delete(a){let{model:n,where:d}=a,{and:r,or:c}=N(d),f=e.deleteFrom(n);r&&(f=f.where(t=>t.and(r.map(i=>i(t))))),c&&(f=f.where(t=>t.or(c.map(i=>i(t))))),await f.execute()},async deleteMany(a){let{model:n,where:d}=a,{and:r,or:c}=N(d),f=e.deleteFrom(n);r&&(f=f.where(t=>t.and(r.map(i=>i(t))))),c&&(f=f.where(t=>t.or(c.map(i=>i(t))))),await f.execute()}});async function me(e){if(!e.database)throw new F("Database configuration is required");if("create"in e.database)return e.database;let{kysely:s,databaseType:a}=await k(e);if(!s)throw new F("Failed to initialize database adapter");let n=h(e),d={};for(let r of Object.values(n))d[r.tableName]=r.fields;return K(s,{transform:{schema:d,date:!0,boolean:a==="sqlite"},generateId:"generateId"in e.database?e.database.generateId:void 0})}function D(e,s){let a={id:s.id};for(let n in e){let d=e[n],r=s[n];a[d.fieldName||n]=r}return a}function g(e,s){if(!s)return null;let a={id:s.id};for(let[n,d]of Object.entries(e))a[n]=s[d.fieldName||n];return a}function C(e,s){let a=s.hooks,n=h(s.options);async function d(c,f,t){let i=c,o=n[f];for(let m of a||[]){let p=m[f]?.create?.before;if(p){let y=await p(c);if(y===!1)return null;typeof y=="object"&&"data"in y&&(i=y.data)}}let l=t?await t.fn(i):null,u=!t||t.executeMainFn?await e.create({model:o.tableName,data:{...D(o.fields,i),id:i.id||A()}}):l;for(let m of a||[]){let p=m[f]?.create?.after;p&&await p(u)}return g(o.fields,u)}async function r(c,f,t,i){let o=c;for(let m of a||[]){let p=m[t]?.update?.before;if(p){let y=await p(c);if(y===!1)return null;o=typeof y=="object"?y.data:y}}let l=i?await i.fn(o):null,u=!i||i.executeMainFn?await e.update({model:n[t].tableName,update:D(n[t].fields,o),where:f}):l;for(let m of a||[]){let p=m[t]?.update?.after;p&&await p(u)}return g(n[t].fields,u)}return{createWithHooks:d,updateWithHooks:r}}import{isTest as $}from"std-env";function j(e){let s="127.0.0.1";if($)return s;let a=["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],n=e instanceof Request?e.headers:e;for(let d of a){let r=n.get(d);if(typeof r=="string"){let c=r.split(",")[0].trim();if(c)return c}}return null}var ve=(e,s)=>{let a=s.options,n=a.secondaryStorage,d=a.session?.expiresIn||60*60*24*7,r=h(a),{createWithHooks:c,updateWithHooks:f}=C(e,s);return{createOAuthUser:async(t,i)=>{try{let o=await c({id:A(),createdAt:new Date,updatedAt:new Date,...t},"user"),l=await c({id:A(),...i,userId:o.id||t.id},"account");return{user:o,account:l}}catch(o){return console.log(o),null}},createUser:async t=>await c({id:A(),createdAt:new Date,updatedAt:new Date,emailVerified:!1,...t},"user"),createAccount:async t=>await c({id:A(),createdAt:new Date,updatedAt:new Date,...t},"account"),listSessions:async t=>await e.findMany({model:r.session.tableName,where:[{field:r.session.fields.userId.fieldName||"userId",value:t}]}),listUsers:async(t,i,o,l)=>(await e.findMany({model:r.user.tableName,limit:t,offset:i,sortBy:o,where:l})).map(m=>g(r.user.fields,m)),deleteUser:async t=>{await e.delete({model:r.account.tableName,where:[{field:r.account.fields.userId.fieldName||"userId",value:t}]}),await e.deleteMany({model:r.session.tableName,where:[{field:r.session.fields.userId.fieldName||"userId",value:t}]}),await e.deleteMany({model:r.user.tableName,where:[{field:"id",value:t}]})},createSession:async(t,i,o,l)=>{let u=i instanceof Request?i.headers:i,m={id:A(),userId:t,expiresAt:o?q(60*60*24,"sec"):q(d,"sec"),ipAddress:i&&j(i)||"",userAgent:u?.get("user-agent")||"",...l};return await c(m,"session",n?{fn:async y=>{let b=await e.findOne({model:r.user.tableName,where:[{field:"id",value:t}]});return n.set(y.id,JSON.stringify({session:y,user:b}),d),y},executeMainFn:a.session?.storeSessionInDatabase}:void 0)},findSession:async t=>{if(n){let l=await n.get(t);if(l){let u=JSON.parse(l);return{session:{...u.session,expiresAt:new Date(u.session.expiresAt)},user:{...u.user,createdAt:new Date(u.user.createdAt),updatedAt:new Date(u.user.updatedAt)}}}}let i=await e.findOne({model:r.session.tableName,where:[{value:t,field:"id"}]});if(!i)return null;let o=await e.findOne({model:r.user.tableName,where:[{value:i.userId,field:"id"}]});return o?{session:g(r.session.fields,i),user:g(r.user.fields,o)}:null},findSessions:async t=>{if(n){let u=[];for(let m of t){let p=await n.get(m);if(p){let y=JSON.parse(p),b={session:{...y.session,expiresAt:new Date(y.session.expiresAt)},user:{...y.user,createdAt:new Date(y.user.createdAt),updatedAt:new Date(y.user.updatedAt)}};u.push(b)}}return u}let i=await e.findMany({model:r.session.tableName,where:[{field:"id",value:t,operator:"in"}]}),o=i.map(u=>u.userId);if(!o.length)return[];let l=await e.findMany({model:r.user.tableName,where:[{field:"id",value:o,operator:"in"}]});return i.map(u=>{let m=l.find(p=>p.id===u.userId);return m?{session:g(r.session.fields,u),user:g(r.user.fields,m)}:null})},updateSession:async(t,i)=>await f(i,[{field:"id",value:t}],"session",n?{async fn(l){let u=await n.get(t),m=null;if(u){let p=JSON.parse(u);m={...p.session,...l},await n.set(t,JSON.stringify({session:m,user:p.user}),p.session.expiresAt?new Date(p.session.expiresAt).getTime():void 0)}else return null},executeMainFn:a.session?.storeSessionInDatabase}:void 0),deleteSession:async t=>{if(n){await n.delete(t),a.session?.storeSessionInDatabase&&await e.delete({model:r.session.tableName,where:[{field:"id",value:t}]});return}await e.delete({model:r.session.tableName,where:[{field:"id",value:t}]})},deleteSessions:async t=>{if(n){let i=await e.findMany({model:r.session.tableName,where:[{field:r.session.fields.userId.fieldName||"userId",value:t}]});for(let o of i)await n.delete(o.id);a.session?.storeSessionInDatabase&&await e.delete({model:r.session.tableName,where:[{field:r.session.fields.userId.fieldName||"userId",value:t}]});return}await e.delete({model:r.session.tableName,where:[{field:r.session.fields.userId.fieldName||"userId",value:t}]})},findUserByEmail:async(t,i)=>{let o=await e.findOne({model:r.user.tableName,where:[{value:t.toLowerCase(),field:r.user.fields.email.fieldName||"email"}]});if(!o)return null;if(i?.includeAccounts){let l=await e.findMany({model:r.account.tableName,where:[{value:o.id,field:r.account.fields.userId.fieldName||"userId"}]});return{user:g(r.user.fields,o),accounts:l.map(u=>g(r.account.fields,u))}}return{user:g(r.user.fields,o),accounts:[]}},findUserById:async t=>await e.findOne({model:r.user.tableName,where:[{field:"id",value:t}]}),linkAccount:async t=>await c({id:A(),...t},"account"),updateUser:async(t,i)=>await f(i,[{field:"id",value:t}],"user"),updateUserByEmail:async(t,i)=>await f(i,[{field:r.user.fields.email.fieldName||"email",value:t}],"user"),updatePassword:async(t,i)=>await f({password:i},[{field:r.account.fields.userId.fieldName||"userId",value:t},{field:r.account.fields.providerId.fieldName||"providerId",value:"credential"}],"account"),findAccounts:async t=>(await e.findMany({model:r.account.tableName,where:[{field:r.account.fields.userId.fieldName||"userId",value:t}]})).map(o=>g(r.account.fields,o)),updateAccount:async(t,i)=>await f(i,[{field:"id",value:t}],"account"),createVerificationValue:async t=>await c({id:A(),...t},"verification"),findVerificationValue:async t=>{let i=await e.findOne({model:r.verification.tableName,where:[{field:r.verification.fields.identifier.fieldName||"identifier",value:t}]});return g(r.verification.fields,i)},deleteVerificationValue:async t=>{await e.delete({model:r.verification.tableName,where:[{field:"id",value:t}]})},updateVerificationValue:async(t,i)=>await f(i,[{field:"id",value:t}],"verification")}};var qe=(e,s)=>({type:e,...s});import{z as I}from"zod";function Re(e){return I.object({...Object.keys(e).reduce((a,n)=>{let d=e[n];if(!d)return a;if(d.type==="string[]"||d.type==="number[]")return{...a,[n]:I.array(d.type==="string[]"?I.string():I.number())};let r=I[d.type]();return d?.required===!1&&(r=r.optional()),d?.returned===!1?a:{...a,[n]:r}},{})})}import"kysely";import{createConsola as W}from"consola";var w=W({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),H=e=>({log:(...s)=>{!e?.disabled&&w.log("",...s)},error:(...s)=>{!e?.disabled&&w.error("",...s)},warn:(...s)=>{!e?.disabled&&w.warn("",...s)},info:(...s)=>{!e?.disabled&&w.info("",...s)},debug:(...s)=>{!e?.disabled&&w.debug("",...s)},box:(...s)=>{!e?.disabled&&w.box("",...s)},success:(...s)=>{!e?.disabled&&w.success("",...s)},break:(...s)=>{!e?.disabled&&console.log(`
2
2
  `)}}),O=H();function P(e){let s=h(e),a={};for(let n in s){let d=s[n],r=d.fields,c={};if(Object.entries(r).forEach(([f,t])=>{c[t.fieldName||f]=t}),a[d.tableName]){a[d.tableName].fields={...a[d.tableName].fields,...c};continue}a[d.tableName]={fields:c,order:d.order||1/0}}return a}var J={string:["character varying","text"],number:["int4","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamp","date"]},Z={string:["varchar","text"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean"],date:["date","datetime"]},z={string:["TEXT"],number:["INTEGER","REAL"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"]},_={string:["nvarchar","varchar"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","boolean"],date:["datetime","date"]},G={postgres:J,mysql:Z,sqlite:z,mssql:_};function X(e,s,a){return s==="string[]"||s==="number[]"?e.toLowerCase().includes("json"):G[a][s].map(c=>c.toLowerCase()).includes(e.toLowerCase())}async function Le(e){let s=P(e),{kysely:a,databaseType:n}=await k(e);n||(O.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),n="sqlite"),a||(O.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1));let d=await a.introspection.getTables(),r=[],c=[];for(let[l,u]of Object.entries(s)){let m=d.find(y=>y.name===l);if(!m){let y=r.findIndex(T=>T.table===l),b={table:l,fields:u.fields,order:u.order||1/0},x=r.findIndex(T=>(T.order||1/0)>b.order);x===-1?y===-1?r.push(b):r[y].fields={...r[y].fields,...u.fields}:r.splice(x,0,b);continue}let p={};for(let[y,b]of Object.entries(u.fields)){let x=m.columns.find(T=>T.name===y);if(!x){p[y]=b;continue}X(x.dataType,b.type,n)||O.warn(`Field ${y} in table ${l} has a different type in the database. Expected ${b.type} but got ${x.dataType}.`)}Object.keys(p).length>0&&c.push({table:l,fields:p,order:u.order||1/0})}let f=[];function t(l){let u={string:"text",boolean:"boolean",number:"integer",date:"date"};return n==="mysql"&&l==="string"?"varchar(255)":n==="sqlite"&&(l==="string[]"||l==="number[]")?"text":l==="string[]"||l==="number[]"?"jsonb":u[l]}if(c.length)for(let l of c)for(let[u,m]of Object.entries(l.fields)){let p=t(m.type),y=a.schema.alterTable(l.table).addColumn(u,p,b=>(b=m.required!==!1?b.notNull():b,m.references&&(b=b.references(`${m.references.model}.${m.references.field}`)),b));f.push(y)}if(r.length)for(let l of r){let u=a.schema.createTable(l.table).addColumn("id",t("string"),m=>m.primaryKey().notNull());for(let[m,p]of Object.entries(l.fields)){let y=t(p.type);u=u.addColumn(m,y,b=>(b=p.required!==!1?b.notNull():b,p.references&&(b=b.references(`${p.references.model}.${p.references.field}`)),p.unique&&(b=b.unique()),b))}f.push(u)}async function i(){for(let l of f)await l.execute()}async function o(){return f.map(u=>u.compile().sql).join(`;
3
3
 
4
4
  `)}return{toBeCreated:r,toBeAdded:c,runMigrations:i,compileMigrations:o}}export{g as convertFromDB,D as convertToDB,qe as createFieldAttribute,ve as createInternalAdapter,me as getAdapter,h as getAuthTables,Le as getMigrations,P as getSchema,C as getWithHooks,X as matchType,Re as toZodSchema};