better-auth 0.4.10-beta.1 → 0.4.10-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/adapters/drizzle.d.ts +1 -1
- package/dist/adapters/kysely.d.ts +1 -1
- package/dist/adapters/mongodb.d.ts +1 -1
- package/dist/adapters/prisma.d.ts +1 -1
- package/dist/api.d.ts +1 -1
- package/dist/api.js +3 -3
- package/dist/{auth-2pRFLprr.d.ts → auth-Nmre53Xe.d.ts} +24 -24
- package/dist/client/plugins.d.ts +3 -3
- package/dist/client.d.ts +1 -1
- package/dist/cookies.d.ts +1 -1
- package/dist/db.d.ts +2 -2
- package/dist/{index-bfF6ImVo.d.ts → index-DhUJME0t.d.ts} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/plugins.d.ts +3 -3
- package/dist/plugins.js +3 -3
- package/dist/react.d.ts +1 -1
- package/dist/solid-start.d.ts +1 -1
- package/dist/solid.d.ts +1 -1
- package/dist/svelte-kit.d.ts +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/types.d.ts +2 -2
- package/dist/vue.d.ts +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import{APIError as yr,createRouter as wr}from"better-call";import{APIError as oe}from"better-call";import{z as xe}from"zod";import{xchacha20poly1305 as Lr}from"@noble/ciphers/chacha";import{bytesToHex as Cr,hexToBytes as Br,utf8ToBytes as Dr}from"@noble/ciphers/utils";import{managedNonce as Nr}from"@noble/ciphers/webcrypto";import{sha256 as Vr}from"oslo/crypto";function Q(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let s=0;for(let n=0;n<r.length;n++)s|=r[n]^o[n];return s===0}import{decodeHex as Ot,encodeHex as he}from"oslo/encoding";import{scryptAsync as It}from"@noble/hashes/scrypt";var $={N:16384,r:16,p:1,dkLen:64};async function ye(e,t){return await It(e.normalize("NFKC"),t,{N:$.N,p:$.p,r:$.r,dkLen:$.dkLen,maxmem:128*$.N*$.r*2})}var we=async e=>{let t=he(crypto.getRandomValues(new Uint8Array(16))),r=await ye(e,t);return`${t}:${he(r)}`},be=async(e,t)=>{let[r,o]=e.split(":"),s=await ye(t,r);return Q(s,Ot(o))};function Lt(e){return e.toString(2).padStart(8,"0")}function _t(e){return[...e].map(t=>Lt(t)).join("")}function Ae(e){return parseInt(_t(e),2)}function Ct(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 s=Ae(o);for(;s>=e;)crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),s=Ae(o);return s}function Z(e,t){let r="";for(let o=0;o<e;o++)r+=t[Ct(t.length)];return r}function J(...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 X(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},s=await crypto.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),n=await crypto.subtle.sign(o.name,s,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(n)))}import{createEndpointCreator as Bt,createMiddleware as Re,createMiddlewareCreator as Dt}from"better-call";var ke=Re(async()=>({})),j=Dt({use:[ke,Re(async()=>({}))]}),h=Bt({use:[ke]});var Te=j({body:xe.object({csrfToken:xe.string().optional()}).optional()},async e=>{if(e.request?.method!=="POST"||e.context.options.advanced?.disableCSRFCheck)return;let t=new URL(e.request.url);if(e.context.trustedOrigins.includes(t.origin))return;let r=e.body?.csrfToken;if(!r)throw new oe("UNAUTHORIZED",{message:"CSRF Token is required"});let o=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[s,n]=o?.split("!")||[null,null];if(!r||!o||!s||!n||o!==r)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new oe("UNAUTHORIZED",{message:"Invalid CSRF Token"});let a=await X(e.context.secret,s);if(n!==a)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new oe("UNAUTHORIZED",{message:"Invalid CSRF Token"})});import{APIError as C}from"better-call";import{generateCodeVerifier as Yt}from"oslo/oauth2";import{z as E}from"zod";import{generateState as Ft}from"oslo/oauth2";import{z as Y}from"zod";import{sha256 as Ue}from"oslo/crypto";async function ve(e){let t=await Ue(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function Ee(e,t){let r=await Ue(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return Q(r,o)}async function Pe(e){let t=Ft(),r=JSON.stringify({code:t,callbackURL:e}),o=await ve(r);return{raw:r,hash:o}}function ne(e){return Y.object({code:Y.string(),callbackURL:Y.string().optional(),currentURL:Y.string().optional()}).safeParse(JSON.parse(e))}import{TimeSpan as Nt}from"oslo";var k=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}},Se=class extends k{constructor(t){super(`The package "${t}" is required. Make sure it is installed.`,t)}};function Oe(e){let r=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:e.baseURL?.startsWith("https://")||process.env.NODE_ENV==="production")?"__Secure-":"",o="better-auth",s=e.session?.expiresIn||new Nt(7,"d").seconds(),n=!!e.advanced?.crossSubDomainCookies?.enabled,a=n?e.advanced?.crossSubDomainCookies?.domain||(e.baseURL?new URL(e.baseURL).hostname:void 0):void 0;if(n&&!a)throw new k("baseURL is required when crossSubdomainCookies are enabled");let c=n?"none":"lax";return{sessionToken:{name:`${r}${o}.session_token`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:s,...n?{domain:a}:{}}},csrfToken:{name:`${r}${o}.csrf_token`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:60*60*24*7,...n?{domain:a}:{}}},state:{name:`${r}${o}.state`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:60*15,...n?{domain:a}:{}}},pkCodeVerifier:{name:`${r}${o}.pk_code_verifier`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:60*15,...n?{domain:a}:{}}},dontRememberToken:{name:`${r}${o}.dont_remember`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,...n?{domain:a}:{}}},nonce:{name:`${r}${o}.nonce`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:60*15,...n?{domain:a}:{}}}}}function Ie(e){let r=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:e.baseURL?.startsWith("https://")||process.env.NODE_ENV==="production")?"__Secure-":"",o="better-auth",s=e.advanced?.crossSubDomainCookies?.domain||(e.baseURL?new URL(e.baseURL).hostname:void 0);function n(a,c){let i=e.advanced?.crossSubDomainCookies?.enabled?e.advanced.crossSubDomainCookies.additionalCookies?.includes(a):void 0;return{name:process.env.NODE_ENV==="production"?`${r}${o}.${a}`:`${o}.${a}`,options:{secure:!!r,sameSite:"lax",path:"/",maxAge:60*15,...c,...i?{domain:s}:{}}}}return n}async function S(e,t,r,o){let s=e.context.authCookies.sessionToken.options;s.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t,e.context.secret,{...s,...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})}function uo(e){let t=new Map;return e.split(", ").forEach(o=>{let[s,...n]=o.split("; "),[a,c]=s.split("="),i={value:c};n.forEach(d=>{let[l,p]=d.split("=");i[l.toLowerCase()]=p||!0}),t.set(a,i)}),t}import{APIError as Le}from"better-call";import{createConsola as qt}from"consola";var F=qt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),se=e=>({log:(...t)=>{!e?.disabled&&F.log("",...t)},error:(...t)=>{!e?.disabled&&F.error("",...t)},warn:(...t)=>{!e?.disabled&&F.warn("",...t)},info:(...t)=>{!e?.disabled&&F.info("",...t)},debug:(...t)=>{!e?.disabled&&F.debug("",...t)},box:(...t)=>{!e?.disabled&&F.box("",...t)},success:(...t)=>{!e?.disabled&&F.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
|
-
`)}}),w=se();var v=j(async e=>{let t=e.body?.callbackURL||e.query?.callbackURL||e.query?.redirectTo||e.body?.redirectTo,r=e.headers?.get("referer"),o=e.query?.currentURL||r||e.context.baseURL,s=e.context.trustedOrigins;if(t?.includes("http")){let n=new URL(t).origin;if(!s.includes(n))throw w.error("Invalid callback URL",{callbackURL:t,trustedOrigins:s}),new Le("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let n=new URL(o).origin;if(!s.includes(n))throw w.error("Invalid current URL",{currentURL:o,trustedOrigins:s}),new Le("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as Mt}from"oslo/jwt";import{sha256 as $t}from"oslo/crypto";function Vt(e){try{return new URL(e).pathname!=="/"}catch{throw new k(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function ie(e,t="/api/auth"){return Vt(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function N(e,t){if(e)return ie(e,t);let r=typeof process<"u"?process.env:{},o=r.BETTER_AUTH_URL||r.NEXT_PUBLIC_BETTER_AUTH_URL||r.PUBLIC_BETTER_AUTH_URL||r.NUXT_PUBLIC_BETTER_AUTH_URL||r.NUXT_PUBLIC_AUTH_URL||(r.BASE_URL!=="/"?r.BASE_URL:void 0);if(o)return ie(o,t);if(typeof window<"u")return ie(window.location.origin,t)}import{base64url as jt}from"oslo/encoding";function b(e,t){return t||`${N()}/callback/${e}`}async function _e(e){let t=await $t(new TextEncoder().encode(e));return jt.encode(new Uint8Array(t),{includePadding:!1})}function Ce(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?.split(" ")||[],idToken:e.id_token}}async function x({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:s,scopes:n,disablePkce:a}){let c=new URL(r);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",t.clientId),c.searchParams.set("state",o),c.searchParams.set("scope",n.join(" ")),c.searchParams.set("redirect_uri",t.redirectURI||b(e)),!a&&s){let i=await _e(s);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",i)}return c}import{betterFetch as zt}from"@better-fetch/fetch";async function A({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:s}){let n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),t&&n.set("code_verifier",t),n.set("redirect_uri",r),n.set("client_id",o.clientId),n.set("client_secret",o.clientSecret);let{data:a,error:c}=await zt(s,{method:"POST",body:n,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(c)throw c;return Ce(a)}function ae(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var Be=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:s}){let n=e.scope||o||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${s||e.redirectURI}&scope=${n.join(" ")}&state=${r}`)},validateAuthorizationCode:async(r,o,s)=>A({code:r,codeVerifier:o,redirectURI:s||b("apple",e.redirectURI),options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=Mt(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 Ht}from"@better-fetch/fetch";var De=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r}){let o=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${o.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(b("discord",e.redirectURI))}&state=${t}`)},validateAuthorizationCode:async(t,r,o)=>A({code:t,redirectURI:o||b("discord",e.redirectURI),options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await Ht("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let s=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${s}.png`}else{let s=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${s}`}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 Kt}from"@better-fetch/fetch";var Fe=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o}){let s=e.scope||r||["email","public_profile"];return await x({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v16.0/dialog/oauth",scopes:s,state:t,codeVerifier:o})},validateAuthorizationCode:async(t,r,o)=>A({code:t,codeVerifier:r,redirectURI:o||b("facebook",e.redirectURI),options:e,tokenEndpoint:"https://graph.facebook.com/v16.0/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await Kt("https://graph.facebook.com/me",{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 Ne}from"@better-fetch/fetch";var qe=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:r,scopes:o,codeVerifier:s}){let n=e.scope||o||["user:email"];return x({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:n,state:r,codeVerifier:s})},validateAuthorizationCode:async(r,o,s)=>A({code:r,redirectURI:e.redirectURI||b("google",s),options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:s}=await Ne("https://api.github.com/user",{auth:{type:"Bearer",token:r.accessToken}});if(s)return null;let n=!1;if(!o.email){let{data:a,error:c}=await Ne("https://api.github.com/user/emails",{auth:{type:"Bearer",token:r.accessToken}});c||(o.email=(a.find(i=>i.primary)??a[0])?.email,n=a.find(i=>i.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n},data:o}}}};import{parseJWT as Gt}from"oslo/jwt";var Ve=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:s}){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 k("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new k("codeVerifier is required for Google");let n=e.scope||r||["email","profile"];return x({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o})},validateAuthorizationCode:async(t,r,o)=>A({code:t,codeVerifier:r,redirectURI:o||b("google",e.redirectURI),options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=Gt(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});import{betterFetch as Wt}from"@better-fetch/fetch";import{parseJWT as Qt}from"oslo/jwt";var $e=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(s){let n=e.scope||s.scopes||["openid","profile","email","User.Read"];return x({id:"microsoft",options:e,authorizationEndpoint:r,state:s.state,codeVerifier:s.codeVerifier,scopes:n})},validateAuthorizationCode(s,n,a){return A({code:s,codeVerifier:n,redirectURI:a||b("microsoft",e.redirectURI),options:e,tokenEndpoint:o})},async getUserInfo(s){if(!s.idToken)return null;let n=Qt(s.idToken)?.payload,a=e.profilePhotoSize||48;return await Wt(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${s.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let d=await c.response.clone().arrayBuffer(),l=Buffer.from(d).toString("base64");n.picture=`data:image/jpeg;base64, ${l}`}catch(i){w.error(i)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};import{betterFetch as Zt}from"@better-fetch/fetch";var je=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o}){let s=e.scope||r||["user-read-email"];return x({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:s,state:t,codeVerifier:o})},validateAuthorizationCode:async(t,r,o)=>A({code:t,codeVerifier:r,redirectURI:o||b("spotify",e.redirectURI),options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await Zt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import{betterFetch as Jt}from"@better-fetch/fetch";var ze=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r}){let o=e.scope||r||["activity:write","read"];return x({id:"twitch",options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:t})},validateAuthorizationCode:async(t,r,o)=>A({code:t,redirectURI:o||b("twitch",e.redirectURI),options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await Jt("https://api.twitch.tv/helix/users",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.sub,name:r.preferred_username,email:r.email,image:r.picture,emailVerified:!1},data:r}}});import{betterFetch as Xt}from"@better-fetch/fetch";var Me=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return x({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier})},validateAuthorizationCode:async(t,r,o)=>A({code:t,codeVerifier:r,redirectURI:o||b("twitch",e.redirectURI),options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await Xt("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 de={apple:Be,discord:De,facebook:Fe,github:qe,microsoft:$e,google:Ve,spotify:je,twitch:ze,twitter:Me},He=Object.keys(de);var Ke=h("/sign-in/social",{method:"POST",requireHeaders:!0,query:E.object({currentURL:E.string().optional()}).optional(),body:E.object({callbackURL:E.string().optional(),provider:E.enum(He)}),use:[v]},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider to your auth config",{provider:e.body.provider}),new C("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,s=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,n=await Pe(s||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,n.hash,e.context.secret,r.state.options);let a=Yt();await e.setSignedCookie(r.pkCodeVerifier.name,a,e.context.secret,r.pkCodeVerifier.options);let c=await t.createAuthorizationURL({state:n.raw,codeVerifier:a});return c.searchParams.set("redirect_uri",`${e.context.baseURL}/callback/${e.body.provider}`),e.json({url:c.toString(),state:n,codeVerifier:a,redirect:!0})}),Ge=h("/sign-in/email",{method:"POST",body:E.object({email:E.string().email(),password:E.string(),callbackURL:E.string().optional(),dontRememberMe:E.boolean().default(!1).optional()}),use:[v]},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 C("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!E.string().email().safeParse(t).success)throw new C("BAD_REQUEST",{message:"Invalid email"});let s=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!s)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new C("UNAUTHORIZED",{message:"Invalid email or password"});let n=s.accounts.find(d=>d.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new C("UNAUTHORIZED",{message:"Invalid email or password"});let a=n?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new C("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new C("UNAUTHORIZED",{message:"Invalid email or password"});let i=await e.context.internalAdapter.createSession(s.user.id,e.headers,e.body.dontRememberMe);if(!i)throw e.context.logger.error("Failed to create session"),new C("UNAUTHORIZED",{message:"Failed to create session"});return await S(e,i.id,e.body.dontRememberMe),e.json({user:s.user,session:i,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{APIError as tr}from"better-call";import{z as ee}from"zod";import{z as y}from"zod";var Hn=y.object({id:y.string(),providerId:y.string(),accountId:y.string(),userId:y.string(),accessToken:y.string().nullable().optional(),refreshToken:y.string().nullable().optional(),idToken:y.string().nullable().optional(),expiresAt:y.date().nullable().optional(),password:y.string().optional().nullable()}),We=y.object({id:y.string(),email:y.string().transform(e=>e.toLowerCase()),emailVerified:y.boolean().default(!1),name:y.string(),image:y.string().optional(),createdAt:y.date().default(new Date),updatedAt:y.date().default(new Date)}),Kn=y.object({id:y.string(),userId:y.string(),expiresAt:y.date(),ipAddress:y.string().optional(),userAgent:y.string().optional()}),Gn=y.object({id:y.string(),value:y.string(),expiresAt:y.date(),identifier:y.string()});function er(e,t){let r=t.fields,o={};for(let s in r){if(s in e){if(r[s].input===!1){if(r[s].defaultValue){o[s]=r[s].defaultValue;continue}continue}o[s]=e[s];continue}if(r[s].defaultValue){o[s]=r[s].defaultValue;continue}}return o}function Qe(e,t){let r={...e.user?.additionalFields};return er(t||{},{fields:r})}var L=e=>Z(e||21,J("a-z","0-9","A-Z"));var B={isAction:!1};var Ze=h("/callback/:id",{method:"GET",query:ee.object({state:ee.string(),code:ee.string().optional(),error:ee.string().optional()}),metadata:B},async e=>{if(e.query.error||!e.query.code){let g=ne(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${g}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(f=>f.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=ne(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:s}}=r,n=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!n)throw w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await Ee(e.query.state,n))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let c=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),i;try{i=await t.validateAuthorizationCode(e.query.code,c,`${e.context.baseURL}/callback/${t.id}`)}catch(f){throw console.log(f),e.context.logger.error(f),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let d=await t.getUserInfo(i).then(f=>f?.user),l=L(),p=We.safeParse({...d,id:l});if(!d||p.success===!1)throw w.error("Unable to get user info",p.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let u=await e.context.internalAdapter.findUserByEmail(d.email,{includeAccounts:!0}).catch(f=>{throw w.error(`Better auth was unable to query your database.
|
|
2
|
+
`)}}),w=se();var v=j(async e=>{let t=e.body?.callbackURL||e.query?.callbackURL||e.query?.redirectTo||e.body?.redirectTo,r=e.headers?.get("referer"),o=e.query?.currentURL||r||e.context.baseURL,s=e.context.trustedOrigins;if(t?.includes("http")){let n=new URL(t).origin;if(!s.includes(n))throw w.error("Invalid callback URL",{callbackURL:t,trustedOrigins:s}),new Le("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let n=new URL(o).origin;if(!s.includes(n))throw w.error("Invalid current URL",{currentURL:o,trustedOrigins:s}),new Le("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as Mt}from"oslo/jwt";import{sha256 as $t}from"oslo/crypto";function Vt(e){try{return new URL(e).pathname!=="/"}catch{throw new k(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function ie(e,t="/api/auth"){return Vt(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function N(e,t){if(e)return ie(e,t);let r=typeof process<"u"?process.env:{},o=r.BETTER_AUTH_URL||r.NEXT_PUBLIC_BETTER_AUTH_URL||r.PUBLIC_BETTER_AUTH_URL||r.NUXT_PUBLIC_BETTER_AUTH_URL||r.NUXT_PUBLIC_AUTH_URL||(r.BASE_URL!=="/"?r.BASE_URL:void 0);if(o)return ie(o,t);if(typeof window<"u")return ie(window.location.origin,t)}import{base64url as jt}from"oslo/encoding";function b(e,t){return t||`${N()}/callback/${e}`}async function _e(e){let t=await $t(new TextEncoder().encode(e));return jt.encode(new Uint8Array(t),{includePadding:!1})}function Ce(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?.split(" ")||[],idToken:e.id_token}}async function x({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:s,scopes:n,disablePkce:a}){let c=new URL(r);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",t.clientId),c.searchParams.set("state",o),c.searchParams.set("scope",n.join(" ")),c.searchParams.set("redirect_uri",t.redirectURI||b(e)),!a&&s){let i=await _e(s);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",i)}return c}import{betterFetch as zt}from"@better-fetch/fetch";async function A({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:s}){let n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),t&&n.set("code_verifier",t),n.set("redirect_uri",r),n.set("client_id",o.clientId),n.set("client_secret",o.clientSecret);let{data:a,error:c}=await zt(s,{method:"POST",body:n,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(c)throw c;return Ce(a)}function ae(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var Be=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:s}){let n=e.scope||o||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${s||e.redirectURI}&scope=${n.join(" ")}&state=${r}`)},validateAuthorizationCode:async(r,o,s)=>A({code:r,codeVerifier:o,redirectURI:s||b("apple",e.redirectURI),options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=Mt(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 Ht}from"@better-fetch/fetch";var De=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r}){let o=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${o.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(b("discord",e.redirectURI))}&state=${t}`)},validateAuthorizationCode:async(t,r,o)=>A({code:t,redirectURI:o||b("discord",e.redirectURI),options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await Ht("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let s=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${s}.png`}else{let s=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${s}`}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 Kt}from"@better-fetch/fetch";var Fe=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o}){let s=e.scope||r||["email","public_profile"];return await x({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v16.0/dialog/oauth",scopes:s,state:t,codeVerifier:o})},validateAuthorizationCode:async(t,r,o)=>A({code:t,codeVerifier:r,redirectURI:o||b("facebook",e.redirectURI),options:e,tokenEndpoint:"https://graph.facebook.com/v16.0/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await Kt("https://graph.facebook.com/me",{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 Ne}from"@better-fetch/fetch";var qe=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:r,scopes:o,codeVerifier:s}){let n=e.scope||o||["user:email"];return x({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:n,state:r,codeVerifier:s})},validateAuthorizationCode:async(r,o,s)=>A({code:r,redirectURI:e.redirectURI||b("google",s),options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:s}=await Ne("https://api.github.com/user",{auth:{type:"Bearer",token:r.accessToken}});if(s)return null;let n=!1;if(!o.email){let{data:a,error:c}=await Ne("https://api.github.com/user/emails",{auth:{type:"Bearer",token:r.accessToken}});c||(o.email=(a.find(i=>i.primary)??a[0])?.email,n=a.find(i=>i.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n},data:o}}}};import{parseJWT as Gt}from"oslo/jwt";var Ve=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:s}){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 k("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new k("codeVerifier is required for Google");let n=e.scope||r||["email","profile"];return x({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o})},validateAuthorizationCode:async(t,r,o)=>A({code:t,codeVerifier:r,redirectURI:o||b("google",e.redirectURI),options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=Gt(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});import{betterFetch as Wt}from"@better-fetch/fetch";import{parseJWT as Qt}from"oslo/jwt";var $e=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(s){let n=e.scope||s.scopes||["openid","profile","email","User.Read"];return x({id:"microsoft",options:e,authorizationEndpoint:r,state:s.state,codeVerifier:s.codeVerifier,scopes:n})},validateAuthorizationCode(s,n,a){return A({code:s,codeVerifier:n,redirectURI:a||b("microsoft",e.redirectURI),options:e,tokenEndpoint:o})},async getUserInfo(s){if(!s.idToken)return null;let n=Qt(s.idToken)?.payload,a=e.profilePhotoSize||48;return await Wt(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${s.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let d=await c.response.clone().arrayBuffer(),l=Buffer.from(d).toString("base64");n.picture=`data:image/jpeg;base64, ${l}`}catch(i){w.error(i)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};import{betterFetch as Zt}from"@better-fetch/fetch";var je=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o}){let s=e.scope||r||["user-read-email"];return x({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:s,state:t,codeVerifier:o})},validateAuthorizationCode:async(t,r,o)=>A({code:t,codeVerifier:r,redirectURI:o||b("spotify",e.redirectURI),options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await Zt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import{betterFetch as Jt}from"@better-fetch/fetch";var ze=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r}){let o=e.scope||r||["activity:write","read"];return x({id:"twitch",options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:t})},validateAuthorizationCode:async(t,r,o)=>A({code:t,redirectURI:o||b("twitch",e.redirectURI),options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await Jt("https://api.twitch.tv/helix/users",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.sub,name:r.preferred_username,email:r.email,image:r.picture,emailVerified:!1},data:r}}});import{betterFetch as Xt}from"@better-fetch/fetch";var Me=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return x({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier})},validateAuthorizationCode:async(t,r,o)=>A({code:t,codeVerifier:r,redirectURI:o||b("twitch",e.redirectURI),options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await Xt("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 de={apple:Be,discord:De,facebook:Fe,github:qe,microsoft:$e,google:Ve,spotify:je,twitch:ze,twitter:Me},He=Object.keys(de);var Ke=h("/sign-in/social",{method:"POST",requireHeaders:!0,query:E.object({currentURL:E.string().optional()}).optional(),body:E.object({callbackURL:E.string().optional(),provider:E.enum(He)}),use:[v]},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider to your auth config",{provider:e.body.provider}),new C("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,s=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,n=await Pe(s||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,n.hash,e.context.secret,r.state.options);let a=Yt();await e.setSignedCookie(r.pkCodeVerifier.name,a,e.context.secret,r.pkCodeVerifier.options);let c=await t.createAuthorizationURL({state:n.raw,codeVerifier:a});return c.searchParams.set("redirect_uri",`${e.context.baseURL}/callback/${e.body.provider}`),e.json({url:c.toString(),state:n,codeVerifier:a,redirect:!0})}),Ge=h("/sign-in/email",{method:"POST",body:E.object({email:E.string().email(),password:E.string(),callbackURL:E.string().optional(),dontRememberMe:E.boolean().default(!1).optional()}),use:[v]},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 C("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!E.string().email().safeParse(t).success)throw new C("BAD_REQUEST",{message:"Invalid email"});let s=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!s)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new C("UNAUTHORIZED",{message:"Invalid email or password"});let n=s.accounts.find(d=>d.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new C("UNAUTHORIZED",{message:"Invalid email or password"});let a=n?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new C("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new C("UNAUTHORIZED",{message:"Invalid email or password"});let i=await e.context.internalAdapter.createSession(s.user.id,e.headers,e.body.dontRememberMe);if(!i)throw e.context.logger.error("Failed to create session"),new C("UNAUTHORIZED",{message:"Failed to create session"});return await S(e,i.id,e.body.dontRememberMe),e.json({user:s.user,session:i,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{APIError as tr}from"better-call";import{z as ee}from"zod";import{z as y}from"zod";var Hn=y.object({id:y.string(),providerId:y.string(),accountId:y.string(),userId:y.string(),accessToken:y.string().nullable().optional(),refreshToken:y.string().nullable().optional(),idToken:y.string().nullable().optional(),expiresAt:y.date().nullable().optional(),password:y.string().optional().nullable()}),We=y.object({id:y.string(),email:y.string().transform(e=>e.toLowerCase()),emailVerified:y.boolean().default(!1),name:y.string(),image:y.string().optional(),createdAt:y.date().default(new Date),updatedAt:y.date().default(new Date)}),Kn=y.object({id:y.string(),userId:y.string(),expiresAt:y.date(),ipAddress:y.string().optional(),userAgent:y.string().optional()}),Gn=y.object({id:y.string(),value:y.string(),expiresAt:y.date(),identifier:y.string()});function er(e,t){let r=t.fields,o={};for(let s in r){if(s in e){if(r[s].input===!1){if(r[s].defaultValue){o[s]=r[s].defaultValue;continue}continue}o[s]=e[s];continue}if(r[s].defaultValue){o[s]=r[s].defaultValue;continue}}return o}function Qe(e,t){let r={...e.user?.additionalFields};return er(t||{},{fields:r})}var L=e=>Z(e||21,J("a-z","0-9","A-Z"));var B={isAction:!1};var Ze=h("/callback/:id",{method:"GET",query:ee.object({state:ee.string(),code:ee.string().optional(),error:ee.string().optional()}),metadata:B},async e=>{if(e.query.error||!e.query.code){let g=ne(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${g}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(f=>f.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=ne(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:s}}=r,n=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!n)throw w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await Ee(e.query.state,n))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let c=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),i;try{i=await t.validateAuthorizationCode(e.query.code,c,`${e.context.baseURL}/callback/${t.id}`)}catch(f){throw e.context.logger.error(f),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let d=await t.getUserInfo(i).then(f=>f?.user),l=L(),p=We.safeParse({...d,id:l});if(!d||p.success===!1)throw w.error("Unable to get user info",p.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let u=await e.context.internalAdapter.findUserByEmail(d.email,{includeAccounts:!0}).catch(f=>{throw w.error(`Better auth was unable to query your database.
|
|
3
3
|
Error: `,f),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),m=u?.user.id;if(u){let f=u.accounts.find(T=>T.providerId===t.id),g=e.context.options.account?.accountLinking?.trustedProviders,R=g?g.includes(t.id):!0;if(!f&&(!d.emailVerified||!R)){let T;try{T=new URL(s||o),T.searchParams.set("error","account_not_linked")}catch{throw e.redirect(`${e.context.baseURL}/error?error=account_not_linked`)}throw e.redirect(T.toString())}if(!f)try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:d.id.toString(),id:`${t.id}:${d.id}`,userId:u.user.id,...ae(i)})}catch(T){throw console.log(T),e.redirect(`${e.context.baseURL}/error?error=failed_linking_account`)}}else try{await e.context.internalAdapter.createOAuthUser(p.data,{...ae(i),id:`${t.id}:${d.id}`,providerId:t.id,accountId:d.id.toString(),userId:l})}catch{let g=new URL(s||o);throw g.searchParams.set("error","unable_to_create_user"),e.setHeader("Location",g.toString()),e.redirect(g.toString())}if(!m&&!l)throw new tr("INTERNAL_SERVER_ERROR",{message:"Unable to create user"});try{let f=await e.context.internalAdapter.createSession(m||l,e.request);if(!f){let g=new URL(s||o);throw g.searchParams.set("error","unable_to_create_session"),e.redirect(g.toString())}try{await S(e,f.id)}catch(g){e.context.logger.error("Unable to set session cookie",g);let R=new URL(s||o);throw R.searchParams.set("error","unable_to_create_session"),e.redirect(R.toString())}}catch{let f=new URL(s||o||"");throw f.searchParams.set("error","unable_to_create_session"),e.redirect(f.toString())}throw e.redirect(o)});import{APIError as H}from"better-call";var q=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as Je}from"zod";var ce=()=>h("/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 s=e.context.sessionConfig.expiresIn,n=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-s*1e3+n*1e3<=Date.now()){let i=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:q(e.context.sessionConfig.expiresIn,"sec")});if(!i)return M(e),e.json(null,{status:401});let d=(i.expiresAt.valueOf()-Date.now())/1e3;return await S(e,i.id,!1,{maxAge:d}),e.json({session:i,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),rr=async e=>await ce()({...e,_flag:"json",headers:e.headers}),D=j(async e=>{let t=await rr(e);if(!t?.session)throw new H("UNAUTHORIZED");return{session:t}}),Xe=()=>h("/user/list-sessions",{method:"GET",use:[D],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)}),Ye=h("/user/revoke-session",{method:"POST",body:Je.object({id:Je.string()}),use:[D],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new H("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new H("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new H("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),et=h("/user/revoke-sessions",{method:"POST",use:[D],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new H("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});import"zod";import{APIError as or}from"better-call";var tt=h("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new or("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),M(e),e.json({success:!0})});import{TimeSpan as nr}from"oslo";import{createJWT as sr,parseJWT as ir}from"oslo/jwt";import{validateJWT as rt}from"oslo/jwt";import{z as U}from"zod";import{APIError as K}from"better-call";var ot=h("/forget-password",{method:"POST",body:U.object({email:U.string().email(),redirectTo:U.string()}),use:[v]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function to your auth config!"),new K("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 s=await sr("HS256",Buffer.from(e.context.secret),{email:o.user.email,redirectTo:r},{expiresIn:new nr(1,"h"),issuer:"better-auth",subject:"forget-password",audiences:[o.user.email],includeIssuedTimestamp:!0}),n=`${e.context.baseURL}/reset-password/${s}`;return await e.context.options.emailAndPassword.sendResetPassword(n,o.user),e.json({status:!0})}),nt=h("/reset-password/:token",{method:"GET"},async e=>{let{token:t}=e.params,r,o=U.object({email:U.string(),redirectTo:U.string()});try{if(r=await rt("HS256",Buffer.from(e.context.secret),t),!r.expiresAt||r.expiresAt<new Date)throw Error("Token expired")}catch{let a=ir(t),c=o.safeParse(a?.payload);throw c.success?e.redirect(`${c.data?.redirectTo}?error=invalid_token`):e.redirect(`${e.context.baseURL}/error?error=invalid_token`)}let{redirectTo:s}=o.parse(r.payload);throw e.redirect(`${s}?token=${t}`)}),st=h("/reset-password",{method:"POST",query:U.object({currentURL:U.string()}).optional(),body:U.object({newPassword:U.string(),callbackURL:U.string().optional()})},async e=>{let t=e.query?.currentURL.split("?token=")[1];if(!t)throw new K("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body;try{let o=await rt("HS256",Buffer.from(e.context.secret),t),s=U.string().email().parse(o.payload.email),n=await e.context.internalAdapter.findUserByEmail(s);if(!n)return e.json({error:"User not found",data:null},{status:400,body:{message:"failed to reset password"}});if(r.length<(e.context.options.emailAndPassword?.minPasswordLength||8)||r.length>(e.context.options.emailAndPassword?.maxPasswordLength||32))throw new K("BAD_REQUEST",{message:"Password is too short or too long"});let a=await e.context.password.hash(r);if(!await e.context.internalAdapter.updatePassword(n.user.id,a))throw new K("BAD_REQUEST",{message:"Failed to update password"});return e.json({error:null,data:{status:!0,url:e.body.callbackURL,redirect:!!e.body.callbackURL}},{body:{status:!0,url:e.body.callbackURL,redirect:!!e.body.callbackURL}})}catch(o){throw e.context.logger.error("Failed to reset password",o),new K("BAD_REQUEST",{message:"Failed to reset password"})}});import{TimeSpan as ar}from"oslo";import{createJWT as dr,validateJWT as cr}from"oslo/jwt";import{z as O}from"zod";import{APIError as G}from"better-call";async function le(e,t){return await dr("HS256",Buffer.from(e),{email:t.toLowerCase()},{expiresIn:new ar(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var it=h("/send-verification-email",{method:"POST",query:O.object({currentURL:O.string().optional()}).optional(),body:O.object({email:O.string().email(),callbackURL:O.string().optional()}),use:[v]},async e=>{if(!e.context.options.emailAndPassword?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled. Pass `sendVerificationEmail` in `emailAndPassword` options to enable it."),new G("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new G("BAD_REQUEST",{message:"User not found"});let o=await le(e.context.secret,t),s=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailAndPassword.sendVerificationEmail(s,r.user,o),e.json({status:!0})}),at=h("/verify-email",{method:"GET",query:O.object({token:O.string(),callbackURL:O.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await cr("HS256",Buffer.from(e.context.secret),t)}catch(c){throw e.context.logger.error("Failed to verify email",c),new G("BAD_REQUEST",{message:"Invalid token"})}let s=O.object({email:O.string().email()}).parse(r.payload),n=await e.context.internalAdapter.findUserByEmail(s.email,{includeAccounts:!0});if(!n)throw new G("BAD_REQUEST",{message:"User not found"});if(!n.accounts.find(c=>c.providerId==="credential"))throw new G("BAD_REQUEST",{message:"Account not found"});if(await e.context.internalAdapter.updateUserByEmail(s.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})});import{z as P}from"zod";import{APIError as I}from"better-call";var dt=h("/user/update",{method:"POST",body:P.object({name:P.string().optional(),image:P.string().optional()}),use:[D,v]},async e=>{let{name:t,image:r}=e.body,o=e.context.session;if(!r&&!t)return e.json({user:o.user});let s=await e.context.internalAdapter.updateUserByEmail(o.user.email,{name:t,image:r});return e.json({user:s})}),ct=h("/user/change-password",{method:"POST",body:P.object({newPassword:P.string(),currentPassword:P.string(),revokeOtherSessions:P.boolean().optional()}),use:[D]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,s=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new I("BAD_REQUEST",{message:"Password is too short"});let a=e.context.password.config.maxPasswordLength;if(t.length>a)throw e.context.logger.error("Password is too long"),new I("BAD_REQUEST",{message:"Password too long"});let i=(await e.context.internalAdapter.findAccounts(s.user.id)).find(p=>p.providerId==="credential"&&p.password);if(!i||!i.password)throw new I("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify(i.password,r))throw new I("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(i.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(s.user.id);let p=await e.context.internalAdapter.createSession(s.user.id,e.headers);if(!p)throw new I("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await S(e,p.id)}return e.json(s.user)}),lt=h("/user/set-password",{method:"POST",body:P.object({newPassword:P.string()}),use:[D]},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 I("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 I("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(i=>i.providerId==="credential"&&i.password),c=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:c}),e.json(r.user);throw new I("BAD_REQUEST",{message:"user already has a password"})}),ut=h("/user/delete",{method:"POST",body:P.object({password:P.string()}),use:[D]},async e=>{let{password:t}=e.body,r=e.context.session,s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password);if(!s||!s.password)throw new I("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(s.password,t))throw new I("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),e.json(null)});var pt=h("/csrf",{method:"GET",metadata:B},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t)return{csrfToken:t};let r=Z(32,J("a-z","0-9","A-Z")),o=await X(e.context.secret,r),s=`${r}!${o}`;return await e.setSignedCookie(e.context.authCookies.csrfToken.name,s,e.context.secret,e.context.authCookies.csrfToken.options),{csrfToken:r}});var lr=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|
package/dist/node.d.ts
CHANGED
package/dist/plugins.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { A as AnonymousOptions, O as OrganizationOptions, b as Passkey, P as PasskeyOptions, U as UserWithPhoneNumber, f as UserWithRole, i as admin, h as adminMiddleware, e as anonymous, j as genericOAuth, g as getPasskeyActions, m as magicLink, o as organization, p as passkey, c as passkeyClient, d as phoneNumber, t as twoFactor, a as twoFactorClient, u as username } from './index-
|
|
1
|
+
export { A as AnonymousOptions, O as OrganizationOptions, b as Passkey, P as PasskeyOptions, U as UserWithPhoneNumber, f as UserWithRole, i as admin, h as adminMiddleware, e as anonymous, j as genericOAuth, g as getPasskeyActions, m as magicLink, o as organization, p as passkey, c as passkeyClient, d as phoneNumber, t as twoFactor, a as twoFactorClient, u as username } from './index-DhUJME0t.js';
|
|
2
2
|
export { i as ac } from './index-DfAHOgpj.js';
|
|
3
|
-
import { H as HookEndpointContext } from './auth-
|
|
4
|
-
export { b as AuthEndpoint, d as AuthMiddleware, B as BetterAuthPlugin, P as PluginSchema, a as createAuthEndpoint, c as createAuthMiddleware, o as optionsMiddleware } from './auth-
|
|
3
|
+
import { H as HookEndpointContext } from './auth-Nmre53Xe.js';
|
|
4
|
+
export { b as AuthEndpoint, d as AuthMiddleware, B as BetterAuthPlugin, P as PluginSchema, a as createAuthEndpoint, c as createAuthMiddleware, o as optionsMiddleware } from './auth-Nmre53Xe.js';
|
|
5
5
|
export { H as HIDE_METADATA } from './hide-metadata-DEHJp1rk.js';
|
|
6
6
|
import 'zod';
|
|
7
7
|
import './schema-Dkt0LqYs.js';
|