better-auth 1.0.21 → 1.0.22-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/prisma.d.cts +1 -1
- package/dist/adapters/prisma.d.ts +1 -1
- package/dist/api.cjs +1 -1
- package/dist/api.js +1 -1
- package/dist/client/plugins.d.cts +1 -1
- package/dist/client/plugins.d.ts +1 -1
- package/dist/{index-Dt4lZbQi.d.ts → index-Dd3_WG87.d.ts} +105 -103
- package/dist/{index-CgaJXZ9u.d.cts → index-Dp04oxSM.d.cts} +105 -103
- package/dist/index.cjs +2 -2
- package/dist/index.js +2 -2
- package/dist/plugin/custom-session.cjs +4 -4
- package/dist/plugin/custom-session.js +2 -2
- package/dist/plugins/admin.cjs +1 -1
- package/dist/plugins/admin.js +1 -1
- package/dist/plugins/anonymous.cjs +1 -1
- package/dist/plugins/anonymous.js +1 -1
- package/dist/plugins/bearer.cjs +1 -1
- package/dist/plugins/bearer.js +1 -1
- package/dist/plugins/email-otp.cjs +1 -1
- package/dist/plugins/email-otp.js +1 -1
- package/dist/plugins/generic-oauth.cjs +1 -1
- package/dist/plugins/generic-oauth.js +1 -1
- package/dist/plugins/jwt.cjs +2 -2
- package/dist/plugins/jwt.js +2 -2
- package/dist/plugins/multi-session.cjs +1 -1
- package/dist/plugins/multi-session.js +1 -1
- package/dist/plugins/one-tap.cjs +1 -1
- package/dist/plugins/one-tap.js +1 -1
- package/dist/plugins/open-api.cjs +1 -1
- package/dist/plugins/open-api.js +1 -1
- package/dist/plugins/organization.cjs +4 -4
- package/dist/plugins/organization.d.cts +1 -1
- package/dist/plugins/organization.d.ts +1 -1
- package/dist/plugins/organization.js +2 -2
- package/dist/plugins/passkey.cjs +1 -1
- package/dist/plugins/passkey.js +1 -1
- package/dist/plugins/phone-number.cjs +1 -1
- package/dist/plugins/phone-number.js +1 -1
- package/dist/plugins/two-factor.cjs +1 -1
- package/dist/plugins/two-factor.js +1 -1
- package/dist/plugins/username.cjs +1 -1
- package/dist/plugins/username.js +1 -1
- package/dist/plugins.cjs +3 -3
- package/dist/plugins.d.cts +1 -1
- package/dist/plugins.d.ts +1 -1
- package/dist/plugins.js +4 -4
- package/package.json +1 -1
package/dist/plugins/one-tap.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import{z as Ge}from"zod";import{APIError as Ma,createRouter as Ha,getCookie as Ga,getSignedCookie as Wa,setCookie as Za,setSignedCookie as Qa}from"better-call";import{APIError as Xe}from"better-call";import{createEndpointCreator as We,createMiddleware as le,createMiddlewareCreator as Ze}from"better-call";var pe=le(async()=>({})),z=Ze({use:[pe,le(async()=>({}))]}),m=We({use:[pe]});function re(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function Qe(e){let t="";for(let r=0;r<e.length;r++)t+=re(e[r]);return t}function ue(e,t=!0){if(Array.isArray(e))return`(?:${e.map(p=>`^${ue(p,t)}$`).join("|")})`;let r="",o="",i=".";t===!0?(r="/",o="[/\\\\]",i="[^/\\\\]"):t&&(r=t,o=Qe(r),o.length>1?(o=`(?:${o})`,i=`((?!${o}).)`):i=`[^${o}]`);let n=t?`${o}+?`:"",s=t?`${o}*?`:"",c=t?e.split(r):[e],a="";for(let d=0;d<c.length;d++){let p=c[d],f=c[d+1],A="";if(!(!p&&d>0)){if(t&&(d===c.length-1?A=s:f!=="**"?A=n:A=""),t&&p==="**"){A&&(a+=d===0?"":A,a+=`(?:${i}*?${A})*?`);continue}for(let h=0;h<p.length;h++){let y=p[h];y==="\\"?h<p.length-1&&(a+=re(p[h+1]),h++):y==="?"?a+=i:y==="*"?a+=`${i}*?`:a+=re(y)}a+=A}}return a}function Ke(e,t){if(typeof t!="string")throw new TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function oe(e,t){if(typeof e!="string"&&!Array.isArray(e))throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if((typeof t=="string"||typeof t=="boolean")&&(t={separator:t}),arguments.length===2&&!(typeof t>"u"||typeof t=="object"&&t!==null&&!Array.isArray(t)))throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if(t=t||{},t.separator==="\\")throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let r=ue(e,t.separator),o=new RegExp(`^${r}$`,t.flags),i=Ke.bind(null,o);return i.options=t,i.pattern=e,i.regexp=o,i}var W=Object.create(null),q=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?W:globalThis),me=new Proxy(W,{get(e,t){return q()[t]??W[t]},has(e,t){let r=q();return t in r||t in W},set(e,t,r){let o=q(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=q(!0);return delete r[t],!0},ownKeys(){let e=q(!0);return Object.keys(e)}});function Je(e){return e?e!=="false":!1}var ie=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var ne=ie==="dev"||ie==="development",Ye=ie==="test"||Je(me.TEST);var N=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function fe(e){try{return new URL(e).origin}catch{return null}}function ge(e){return e.includes("://")?new URL(e).host:e}var et=z(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,i=e.headers?.get("origin")||e.headers?.get("referer")||"",n=t?.callbackURL||r?.callbackURL,s=t?.redirectTo,c=r?.currentURL,a=t?.errorCallbackURL,d=t?.newUserCallbackURL,p=o.trustedOrigins,f=e.headers?.has("cookie"),A=(y,U)=>y.startsWith("/")?!1:U.includes("*")?oe(U)(ge(y)):y.startsWith(U),h=(y,U)=>{if(!y)return;if(!p.some(ee=>A(y,ee)||y?.startsWith("/")&&U!=="origin"&&!y.includes(":")))throw e.context.logger.error(`Invalid ${U}: ${y}`),e.context.logger.info(`If it's a valid URL, please add ${y} to trustedOrigins in your auth config
|
|
2
|
-
`,`Current list of trustedOrigins: ${p}`),new Xe("FORBIDDEN",{message:`Invalid ${U}`})};f&&!e.context.options.advanced?.disableCSRFCheck&&h(i,"origin"),n&&h(n,"callbackURL"),s&&h(s,"redirectURL"),c&&h(c,"currentURL"),a&&h(a,"errorCallbackURL"),d&&h(s,"newUserCallbackURL")});import{APIError as E}from"better-call";import{z as b}from"zod";import{TimeSpan as Br}from"oslo";import{base64url as it}from"oslo/encoding";import{HMAC as he,sha256 as Ir}from"oslo/crypto";async function rt({value:e,secret:t}){return new he("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function ot({value:e,signature:t,secret:r}){return new he("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var Z={sign:rt,verify:ot};var j=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function k(e,t,r,o){let i=e.context.authCookies.sessionToken.options,n=r?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled){let c=it.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:j(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await Z.sign({value:JSON.stringify(t),secret:e.context.secret})})),{includePadding:!1});if(c.length>4093)throw new N("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");e.setCookie(e.context.authCookies.sessionData.name,c,e.context.authCookies.sessionData.options)}e.context.setNewSession(t),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3))}function I(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}import{betterFetch as lt}from"@better-fetch/fetch";import{APIError as pt}from"better-call";import{decodeProtectedHeader as ut,importJWK as mt,jwtVerify as ft}from"jose";import{parseJWT as gt}from"oslo/jwt";import{sha256 as nt}from"oslo/crypto";import{base64url as st}from"oslo/encoding";async function we(e){let t=await nt(new TextEncoder().encode(e));return st.encode(new Uint8Array(t),{includePadding:!1})}function Q(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?j(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function w({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:s,redirectURI:c,duration:a}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),i){let p=await we(i);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",p)}if(s){let p=s.reduce((f,A)=>(f[A]=null,f),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...p}}))}return a&&d.searchParams.set("duration",a),d}import{betterFetch as at}from"@better-fetch/fetch";async function g({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i,authentication:n}){let s=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),n==="basic"){let f=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${f}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await at(i,{method:"POST",body:s,headers:c});if(d)throw d;return Q(a)}import{generateCodeVerifier as ct,generateState as dt}from"oslo/oauth2";import{z as P}from"zod";import{APIError as ye}from"better-call";async function K(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?fe(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ye("BAD_REQUEST",{message:"callbackURL is required"});let o=ct(),i=dt(),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,newUserURL:e.body?.newUserCallbackURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:s});if(!c)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ye("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function be(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=P.object({callbackURL:P.string(),codeVerifier:P.string(),errorURL:P.string().optional(),newUserURL:P.string().optional(),expiresAt:P.number(),link:P.object({email:P.string(),userId:P.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var Ae=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=o||["email","name"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>g({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let i=ut(r),{kid:n,alg:s}=i;if(!n||!s)return!1;let c=await ht(n),{payload:a}=await ft(r,c,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=gt(r.idToken)?.payload;if(!o)return null;let i=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:i,emailVerified:!1,email:o.email,...n},data:o}}}},ht=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await lt(`${t}${r}`);if(!o?.keys)throw new pt("BAD_REQUEST",{message:"Keys not found"});let i=o.keys.find(n=>n.kid===e);if(!i)throw new Error(`JWK with kid ${e} not found`);return await mt(i,i.alg)};import{betterFetch as wt}from"@better-fetch/fetch";var Re=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>g({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.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}`}let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...i},data:r}}});import{betterFetch as yt}from"@better-fetch/fetch";var ke=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await w({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>g({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.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}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...i},data:r}}});import{betterFetch as Ee}from"@better-fetch/fetch";var Ue=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),w({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>g({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await Ee("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:c,error:a}=await Ee("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(c.find(d=>d.primary)??c[0])?.email,n=c.find(d=>d.email===o.email)?.verified??!1)}let s=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n,...s},data:o}}}};import{parseJWT as Et}from"oslo/jwt";import{createConsola as bt}from"consola";var se=["info","success","warn","error","debug"];function At(e,t){return se.indexOf(t)<=se.indexOf(e)}var Rt=bt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),kt=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(i,n,s=[])=>{if(!(!t||!At(r,i))){if(!e||typeof e.log!="function"){Rt[i]("",n,...s);return}e.log(i==="success"?"info":i,n,s)}};return Object.fromEntries(se.map(i=>[i,(...[n,...s])=>o(i,n,s)]))},S=kt();import{betterFetch as Ut}from"@better-fetch/fetch";var _e=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw S.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new N("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new N("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await w({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>g({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:i}=await Ut(o);return i?i.aud===e.clientId&&i.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=Et(t.idToken)?.payload,o=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...o},data:r}}});import{betterFetch as _t}from"@better-fetch/fetch";import{parseJWT as Tt}from"oslo/jwt";var Te=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),w({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return g({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);if(!i.idToken)return null;let n=Tt(i.idToken)?.payload,s=e.profilePhotoSize||48;await _t(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let p=await a.response.clone().arrayBuffer(),f=Buffer.from(p).toString("base64");n.picture=`data:image/jpeg;base64, ${f}`}catch(d){S.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0,...c},data:n}}}};import{betterFetch as Ot}from"@better-fetch/fetch";var Oe=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),w({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>g({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await Ot("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...i},data:r}}});var $={isAction:!1};import{nanoid as St}from"nanoid";var Se=e=>St(e);import{parseJWT as vt}from"oslo/jwt";var ve=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),w({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>g({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return S.error("No idToken found in token"),null;let o=vt(r)?.payload,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...i},data:o}}});import{betterFetch as xt}from"@better-fetch/fetch";var xe=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),w({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>g({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.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}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.data.id,name:r.data.name,email:r.data.username||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1,...i},data:r}}});import{betterFetch as It}from"@better-fetch/fetch";var Ie=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await w({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await g({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await It("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...n},data:o}}}};import{betterFetch as Lt}from"@better-fetch/fetch";var Le=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await w({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await g({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await Lt("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(n)return null;let s=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture,...s},data:i}}}};import{betterFetch as Pt}from"@better-fetch/fetch";var ae=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Dt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ae(`${t}/oauth/authorize`),tokenEndpoint:ae(`${t}/oauth/token`),userinfoEndpoint:ae(`${t}/api/v4/user`)}},Pe=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Dt(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let p=c||["read_user"];return e.scope&&p.push(...e.scope),await w({id:i,options:e,authorizationEndpoint:t,scopes:p,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>g({code:s,redirectURI:e.redirectURI||c,options:e,codeVerifier:a,tokenEndpoint:r}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:c,error:a}=await Pt(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(a||c.state!=="active"||c.locked)return null;let d=await e.mapProfileToUser?.(c);return{user:{id:c.id.toString(),name:c.name??c.username,email:c.email,image:c.avatar_url,emailVerified:!0,...d},data:c}}}};import{betterFetch as De}from"@better-fetch/fetch";var Ce=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identity"];return e.scope&&i.push(...e.scope),w({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:i,state:t,redirectURI:o,duration:e.duration})},validateAuthorizationCode:async({code:t,redirectURI:r})=>{let o=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:e.redirectURI||r}),i={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`},{data:n,error:s}=await De("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:i,body:o.toString()});if(s)throw s;return Q(n)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await De("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.oauth_client_id,emailVerified:r.has_verified_email,image:r.icon_img?.split("?")[0],...i},data:r}}});var Ct={apple:Ae,discord:Re,facebook:ke,github:Ue,microsoft:Te,google:_e,spotify:Oe,twitch:ve,twitter:xe,dropbox:Ie,linkedin:Le,gitlab:Pe,reddit:Ce},J=Object.keys(Ct);import{TimeSpan as Vt}from"oslo";import{createJWT as $t,validateJWT as zt}from"oslo/jwt";import{z as v}from"zod";import{APIError as F}from"better-call";import{APIError as D}from"better-call";import{z as B}from"zod";function Ne(e){try{return JSON.parse(e)}catch{return null}}var l={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found"};var je=()=>m("/get-session",{method:"GET",query:B.optional(B.object({disableCookieCache:B.boolean({description:"Disable cookie cache and fetch session from database"}).or(B.string().transform(e=>e==="true")).optional(),disableRefresh:B.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?Ne(Buffer.from(r,"base64").toString()):null;if(o&&!await Z.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return I(e),e.json(null);let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let p=o.session;if(o.expiresAt<Date.now()||p.session.expiresAt<new Date){let A=e.context.authCookies.sessionData.name;e.setCookie(A,"",{maxAge:0})}else return e.json(p)}let n=await e.context.internalAdapter.findSession(t);if(e.context.session=n,!n||n.session.expiresAt<new Date)return I(e),n&&await e.context.internalAdapter.deleteSession(n.session.token),e.json(null);if(i||e.query?.disableRefresh)return e.json(n);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let p=await e.context.internalAdapter.updateSession(n.session.token,{expiresAt:j(e.context.sessionConfig.expiresIn,"sec")});if(!p)return I(e),e.json(null,{status:401});let f=(p.expiresAt.valueOf()-Date.now())/1e3;return await k(e,{session:p,user:n.user},!1,{maxAge:f}),e.json({session:p,user:n.user})}return e.json(n)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new D("INTERNAL_SERVER_ERROR",{message:l.FAILED_TO_GET_SESSION})}}),V=async(e,t)=>{if(e.context.session)return e.context.session;let r=await je()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},L=z(async e=>{let t=await V(e);if(!t?.session)throw new D("UNAUTHORIZED");return{session:t}}),Be=z(async e=>{let t=await V(e);if(!t?.session)throw new D("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),i=Date.now();if(!(o+r*1e3>i))throw new D("FORBIDDEN",{message:"Session is not fresh"});return{session:t}});var Nt=m("/revoke-session",{method:"POST",body:B.object({token:B.string({description:"The token to revoke"})}),use:[L],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let t=e.body.token,r=await e.context.internalAdapter.findSession(t);if(!r)throw new D("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new D("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new D("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),jt=m("/revoke-sessions",{method:"POST",use:[L],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new D("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Bt=m("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[L],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw new D("UNAUTHORIZED");let i=(await e.context.internalAdapter.listSessions(t.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.token!==e.context.session.session.token);return await Promise.all(i.map(n=>e.context.internalAdapter.deleteSession(n.token))),e.json({status:!0})});async function C(e,t,r){return await $t("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Vt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function qt(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new F("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await C(e.context.secret,t.email),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:r},e.request)}var Ft=m("/send-verification-email",{method:"POST",query:v.object({currentURL:v.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:v.object({email:v.string({description:"The email to send the verification email to"}).email(),callbackURL:v.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new F("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new F("BAD_REQUEST",{message:l.USER_NOT_FOUND});return await qt(e,r.user),e.json({status:!0})}),Mt=m("/verify-email",{method:"GET",query:v.object({token:v.string({description:"The token to verify the email"}),callbackURL:v.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(c){throw e.query.callbackURL?e.query.callbackURL.includes("?")?e.redirect(`${e.query.callbackURL}&error=${c}`):e.redirect(`${e.query.callbackURL}?error=${c}`):new F("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await zt("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let n=v.object({email:v.string().email(),updateTo:v.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(n.email);if(!s)return t("user_not_found");if(n.updateTo){let c=await V(e);if(!c){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(c.user.email!==n.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo,emailVerified:!1}),d=await C(e.context.secret,n.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${d}`,token:d},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await V(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new F("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await k(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function Y(e,{userInfo:t,account:r,callbackURL:o}){let i=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw S.error(`Better auth was unable to query your database.
|
|
2
|
+
`,`Current list of trustedOrigins: ${p}`),new Xe("FORBIDDEN",{message:`Invalid ${U}`})};f&&!e.context.options.advanced?.disableCSRFCheck&&h(i,"origin"),n&&h(n,"callbackURL"),s&&h(s,"redirectURL"),c&&h(c,"currentURL"),a&&h(a,"errorCallbackURL"),d&&h(s,"newUserCallbackURL")});import{APIError as E}from"better-call";import{z as b}from"zod";import{TimeSpan as Br}from"oslo";import{base64url as it}from"oslo/encoding";import{HMAC as he,sha256 as Ir}from"oslo/crypto";async function rt({value:e,secret:t}){return new he("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function ot({value:e,signature:t,secret:r}){return new he("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var Z={sign:rt,verify:ot};var j=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function k(e,t,r,o){let i=e.context.authCookies.sessionToken.options,n=r?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled){let c=it.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:j(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await Z.sign({value:JSON.stringify(t),secret:e.context.secret})})),{includePadding:!1});if(c.length>4093)throw new N("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");e.setCookie(e.context.authCookies.sessionData.name,c,e.context.authCookies.sessionData.options)}e.context.setNewSession(t),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3))}function I(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}import{betterFetch as lt}from"@better-fetch/fetch";import{APIError as pt}from"better-call";import{decodeProtectedHeader as ut,importJWK as mt,jwtVerify as ft}from"jose";import{parseJWT as gt}from"oslo/jwt";import{sha256 as nt}from"oslo/crypto";import{base64url as st}from"oslo/encoding";async function we(e){let t=await nt(new TextEncoder().encode(e));return st.encode(new Uint8Array(t),{includePadding:!1})}function Q(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?j(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function w({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:s,redirectURI:c,duration:a}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),i){let p=await we(i);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",p)}if(s){let p=s.reduce((f,A)=>(f[A]=null,f),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...p}}))}return a&&d.searchParams.set("duration",a),d}import{betterFetch as at}from"@better-fetch/fetch";async function g({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i,authentication:n}){let s=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),n==="basic"){let f=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${f}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await at(i,{method:"POST",body:s,headers:c});if(d)throw d;return Q(a)}import{generateCodeVerifier as ct,generateState as dt}from"oslo/oauth2";import{z as P}from"zod";import{APIError as ye}from"better-call";async function K(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?fe(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ye("BAD_REQUEST",{message:"callbackURL is required"});let o=ct(),i=dt(),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,newUserURL:e.body?.newUserCallbackURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:s});if(!c)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ye("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function be(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=P.object({callbackURL:P.string(),codeVerifier:P.string(),errorURL:P.string().optional(),newUserURL:P.string().optional(),expiresAt:P.number(),link:P.object({email:P.string(),userId:P.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var Ae=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=o||["email","name"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>g({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let i=ut(r),{kid:n,alg:s}=i;if(!n||!s)return!1;let c=await ht(n),{payload:a}=await ft(r,c,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=gt(r.idToken)?.payload;if(!o)return null;let i=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:i,emailVerified:!1,email:o.email,...n},data:o}}}},ht=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await lt(`${t}${r}`);if(!o?.keys)throw new pt("BAD_REQUEST",{message:"Keys not found"});let i=o.keys.find(n=>n.kid===e);if(!i)throw new Error(`JWK with kid ${e} not found`);return await mt(i,i.alg)};import{betterFetch as wt}from"@better-fetch/fetch";var Re=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>g({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.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}`}let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...i},data:r}}});import{betterFetch as yt}from"@better-fetch/fetch";var ke=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await w({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>g({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.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}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...i},data:r}}});import{betterFetch as Ee}from"@better-fetch/fetch";var Ue=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),w({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>g({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await Ee("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:c,error:a}=await Ee("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(c.find(d=>d.primary)??c[0])?.email,n=c.find(d=>d.email===o.email)?.verified??!1)}let s=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n,...s},data:o}}}};import{parseJWT as Et}from"oslo/jwt";import{createConsola as bt}from"consola";var se=["info","success","warn","error","debug"];function At(e,t){return se.indexOf(t)<=se.indexOf(e)}var Rt=bt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),kt=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(i,n,s=[])=>{if(!(!t||!At(r,i))){if(!e||typeof e.log!="function"){Rt[i]("",n,...s);return}e.log(i==="success"?"info":i,n,s)}};return Object.fromEntries(se.map(i=>[i,(...[n,...s])=>o(i,n,s)]))},S=kt();import{betterFetch as Ut}from"@better-fetch/fetch";var _e=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw S.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new N("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new N("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await w({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>g({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:i}=await Ut(o);return i?i.aud===e.clientId&&i.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=Et(t.idToken)?.payload,o=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...o},data:r}}});import{betterFetch as _t}from"@better-fetch/fetch";import{parseJWT as Tt}from"oslo/jwt";var Te=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),w({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return g({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);if(!i.idToken)return null;let n=Tt(i.idToken)?.payload,s=e.profilePhotoSize||48;await _t(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let p=await a.response.clone().arrayBuffer(),f=Buffer.from(p).toString("base64");n.picture=`data:image/jpeg;base64, ${f}`}catch(d){S.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0,...c},data:n}}}};import{betterFetch as Ot}from"@better-fetch/fetch";var Oe=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),w({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>g({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await Ot("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...i},data:r}}});var $={isAction:!1};import{nanoid as St}from"nanoid";var Se=e=>St(e);import{parseJWT as vt}from"oslo/jwt";var ve=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),w({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>g({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return S.error("No idToken found in token"),null;let o=vt(r)?.payload,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...i},data:o}}});import{betterFetch as xt}from"@better-fetch/fetch";var xe=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),w({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>g({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.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}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.data.id,name:r.data.name,email:r.data.username||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1,...i},data:r}}});import{betterFetch as It}from"@better-fetch/fetch";var Ie=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await w({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await g({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await It("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...n},data:o}}}};import{betterFetch as Lt}from"@better-fetch/fetch";var Le=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await w({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await g({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await Lt("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(n)return null;let s=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture,...s},data:i}}}};import{betterFetch as Pt}from"@better-fetch/fetch";var ae=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Dt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ae(`${t}/oauth/authorize`),tokenEndpoint:ae(`${t}/oauth/token`),userinfoEndpoint:ae(`${t}/api/v4/user`)}},Pe=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Dt(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let p=c||["read_user"];return e.scope&&p.push(...e.scope),await w({id:i,options:e,authorizationEndpoint:t,scopes:p,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>g({code:s,redirectURI:e.redirectURI||c,options:e,codeVerifier:a,tokenEndpoint:r}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:c,error:a}=await Pt(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(a||c.state!=="active"||c.locked)return null;let d=await e.mapProfileToUser?.(c);return{user:{id:c.id.toString(),name:c.name??c.username,email:c.email,image:c.avatar_url,emailVerified:!0,...d},data:c}}}};import{betterFetch as De}from"@better-fetch/fetch";var Ce=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identity"];return e.scope&&i.push(...e.scope),w({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:i,state:t,redirectURI:o,duration:e.duration})},validateAuthorizationCode:async({code:t,redirectURI:r})=>{let o=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:e.redirectURI||r}),i={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`},{data:n,error:s}=await De("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:i,body:o.toString()});if(s)throw s;return Q(n)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await De("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.oauth_client_id,emailVerified:r.has_verified_email,image:r.icon_img?.split("?")[0],...i},data:r}}});var Ct={apple:Ae,discord:Re,facebook:ke,github:Ue,microsoft:Te,google:_e,spotify:Oe,twitch:ve,twitter:xe,dropbox:Ie,linkedin:Le,gitlab:Pe,reddit:Ce},J=Object.keys(Ct);import{TimeSpan as Vt}from"oslo";import{createJWT as $t,validateJWT as zt}from"oslo/jwt";import{z as v}from"zod";import{APIError as F}from"better-call";import{APIError as D}from"better-call";import{z as B}from"zod";function Ne(e){try{return JSON.parse(e)}catch{return null}}var l={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found"};var je=()=>m("/get-session",{method:"GET",query:B.optional(B.object({disableCookieCache:B.boolean({description:"Disable cookie cache and fetch session from database"}).or(B.string().transform(e=>e==="true")).optional(),disableRefresh:B.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?Ne(Buffer.from(r,"base64").toString()):null;if(o&&!await Z.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return I(e),e.json(null);let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let p=o.session;if(o.expiresAt<Date.now()||p.session.expiresAt<new Date){let A=e.context.authCookies.sessionData.name;e.setCookie(A,"",{maxAge:0})}else return e.json(p)}let n=await e.context.internalAdapter.findSession(t);if(e.context.session=n,!n||n.session.expiresAt<new Date)return I(e),n&&await e.context.internalAdapter.deleteSession(n.session.token),e.json(null);if(i||e.query?.disableRefresh)return e.json(n);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let p=await e.context.internalAdapter.updateSession(n.session.token,{expiresAt:j(e.context.sessionConfig.expiresIn,"sec")});if(!p)return I(e),e.json(null,{status:401});let f=(p.expiresAt.valueOf()-Date.now())/1e3;return await k(e,{session:p,user:n.user},!1,{maxAge:f}),e.json({session:p,user:n.user})}return e.json(n)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new D("INTERNAL_SERVER_ERROR",{message:l.FAILED_TO_GET_SESSION})}}),V=async(e,t)=>{if(e.context.session)return e.context.session;let r=await je()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},L=z(async e=>{let t=await V(e);if(!t?.session)throw new D("UNAUTHORIZED");return{session:t}}),Be=z(async e=>{let t=await V(e);if(!t?.session)throw new D("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.updatedAt?.valueOf()||t.session.createdAt.valueOf();if(!(Date.now()-o<r*1e3))throw new D("FORBIDDEN",{message:"Session is not fresh"});return{session:t}});var Nt=m("/revoke-session",{method:"POST",body:B.object({token:B.string({description:"The token to revoke"})}),use:[L],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let t=e.body.token,r=await e.context.internalAdapter.findSession(t);if(!r)throw new D("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new D("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new D("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),jt=m("/revoke-sessions",{method:"POST",use:[L],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new D("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Bt=m("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[L],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw new D("UNAUTHORIZED");let i=(await e.context.internalAdapter.listSessions(t.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.token!==e.context.session.session.token);return await Promise.all(i.map(n=>e.context.internalAdapter.deleteSession(n.token))),e.json({status:!0})});async function C(e,t,r){return await $t("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Vt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function qt(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new F("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await C(e.context.secret,t.email),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:r},e.request)}var Ft=m("/send-verification-email",{method:"POST",query:v.object({currentURL:v.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:v.object({email:v.string({description:"The email to send the verification email to"}).email(),callbackURL:v.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new F("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new F("BAD_REQUEST",{message:l.USER_NOT_FOUND});return await qt(e,r.user),e.json({status:!0})}),Mt=m("/verify-email",{method:"GET",query:v.object({token:v.string({description:"The token to verify the email"}),callbackURL:v.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(c){throw e.query.callbackURL?e.query.callbackURL.includes("?")?e.redirect(`${e.query.callbackURL}&error=${c}`):e.redirect(`${e.query.callbackURL}?error=${c}`):new F("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await zt("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let n=v.object({email:v.string().email(),updateTo:v.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(n.email);if(!s)return t("user_not_found");if(n.updateTo){let c=await V(e);if(!c){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(c.user.email!==n.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo,emailVerified:!1}),d=await C(e.context.secret,n.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${d}`,token:d},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await V(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new F("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await k(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function Y(e,{userInfo:t,account:r,callbackURL:o}){let i=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw S.error(`Better auth was unable to query your database.
|
|
3
3
|
Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=i?.user,s=!n;if(i){let a=i.accounts.find(d=>d.providerId===r.providerId);if(a){let d=Object.fromEntries(Object.entries({accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([p,f])=>f!==void 0));Object.keys(d).length>0&&await e.context.internalAdapter.updateAccount(a.id,d)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return ne&&S.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),userId:i.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope})}catch(f){return S.error("Unable to link account",f),{error:"unable to link account",data:null}}n=await e.context.internalAdapter.updateUser(i.user.id,{...t,updatedAt:new Date})}}else if(n=await e.context.internalAdapter.createOAuthUser({...t,email:t.email.toLowerCase(),id:void 0},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:t.id.toString()}).then(a=>a?.user),!t.emailVerified&&n&&e.context.options.emailVerification?.sendOnSignUp){let a=await C(e.context.secret,n.email),d=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:n,url:d,token:a},e.request)}if(!n)return{error:"unable to create user",data:null,isRegister:!1};let c=await e.context.internalAdapter.createSession(n.id,e.request);return c?{data:{session:c,user:n},error:null,isRegister:s}:{error:"unable to create session",data:null,isRegister:!1}}var Ht=m("/sign-in/social",{method:"POST",query:b.object({currentURL:b.string().optional()}).optional(),body:b.object({callbackURL:b.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:b.string().optional(),errorCallbackURL:b.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:b.enum(J,{description:"OAuth2 provider to use"}),disableRedirect:b.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:b.optional(b.object({token:b.string({description:"ID token from the provider"}),nonce:b.string({description:"Nonce used to generate the token"}).optional(),accessToken:b.string({description:"Access token from the provider"}).optional(),refreshToken:b.string({description:"Refresh token from the provider"}).optional(),expiresAt:b.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new E("NOT_FOUND",{message:l.PROVIDER_NOT_FOUND});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new E("NOT_FOUND",{message:l.ID_TOKEN_NOT_SUPPORTED});let{token:n,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(n,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new E("UNAUTHORIZED",{message:l.INVALID_TOKEN});let a=await t.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new E("UNAUTHORIZED",{message:l.FAILED_TO_GET_USER_INFO});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new E("UNAUTHORIZED",{message:l.USER_EMAIL_NOT_FOUND});let d=await Y(e,{userInfo:{email:a.user.email,id:a.user.id,name:a.user.name||"",image:a.user.image,emailVerified:a.user.emailVerified||!1},account:{providerId:t.id,accountId:a.user.id,accessToken:e.body.idToken.accessToken}});if(d.error)throw new E("UNAUTHORIZED",{message:d.error});return await k(e,d.data),e.json({session:d.data.session,user:d.data.user,url:void 0,redirect:!1})}let{codeVerifier:r,state:o}=await K(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!e.body.disableRedirect})}),Gt=m("/sign-in/email",{method:"POST",body:b.object({email:b.string({description:"Email of the user"}),password:b.string({description:"Password of the user"}),callbackURL:b.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:b.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},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 E("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!b.string().email().safeParse(t).success)throw new E("BAD_REQUEST",{message:l.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 E("UNAUTHORIZED",{message:l.INVALID_EMAIL_OR_PASSWORD});let n=i.accounts.find(d=>d.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new E("UNAUTHORIZED",{message:l.INVALID_EMAIL_OR_PASSWORD});let s=n?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new E("UNAUTHORIZED",{message:l.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new E("UNAUTHORIZED",{message:l.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new E("UNAUTHORIZED",{message:l.EMAIL_NOT_VERIFIED});let d=await C(e.context.secret,i.user.email),p=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:i.user,url:p,token:d},e.request),e.context.logger.error("Email not verified",{email:t}),new E("FORBIDDEN",{message:l.EMAIL_NOT_VERIFIED})}let a=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new E("UNAUTHORIZED",{message:l.FAILED_TO_CREATE_SESSION});return await k(e,{session:a,user:i.user},e.body.rememberMe===!1),e.json({user:{id:i.user.id,email:i.user.email,name:i.user.name,image:i.user.image,emailVerified:i.user.emailVerified,createdAt:i.user.createdAt,updatedAt:i.user.updatedAt},redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as M}from"zod";var X=M.object({code:M.string().optional(),error:M.string().optional(),error_description:M.string().optional(),state:M.string().optional()}),Wt=m("/callback/:id",{method:["GET","POST"],body:X.optional(),query:X.optional(),metadata:$},async e=>{let t;try{if(e.method==="GET")t=X.parse(e.query);else if(e.method==="POST")t=X.parse(e.body);else throw new Error("Unsupported method")}catch(T){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",T),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:i,error_description:n}=t;if(!i)throw e.context.logger.error("State not found",o),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}&error_description=${n}`);let s=e.context.socialProviders.find(T=>T.id===e.params.id);if(!s)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:c,callbackURL:a,link:d,errorURL:p,newUserURL:f}=await be(e),A;try{A=await s.validateAuthorizationCode({code:r,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${s.id}`})}catch(T){throw e.context.logger.error("",T),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let h=await s.getUserInfo(A).then(T=>T?.user);function y(T){let x=p||a||`${e.context.baseURL}/error`;throw x.includes("?")?x=`${x}&error=${T}`:x=`${x}?error=${T}`,e.redirect(x)}if(!h)return e.context.logger.error("Unable to get user info"),y("unable_to_get_user_info");if(!h.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),y("email_not_found");if(!a)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(d){if(d.email!==h.email.toLowerCase())return y("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:s.id,accountId:h.id}))return y("unable_to_link_account");let x;try{x=a.toString()}catch{x=a}throw e.redirect(x)}let U=await Y(e,{userInfo:{...h,email:h.email,name:h.name||h.email},account:{providerId:s.id,accountId:h.id,...A,scope:A.scopes?.join(",")},callbackURL:a});if(U.error)return e.context.logger.error(U.error.split(" ").join("_")),y(U.error.split(" ").join("_"));let{session:de,user:ee}=U.data;await k(e,{session:de,user:ee});let te;try{te=(U.isRegister&&f||a).toString()}catch{te=U.isRegister&&f||a}throw e.redirect(te)});import"zod";import{APIError as Zt}from"better-call";var Qt=m("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw I(e),new Zt("BAD_REQUEST",{message:l.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(t),I(e),e.json({success:!0})});import{z as O}from"zod";import{APIError as H}from"better-call";function Ve(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}function Kt(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}var Jt=m("/forget-password",{method:"POST",body:O.object({email:O.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:O.string({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},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 H("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let i=60*60*1,n=j(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||i,"sec"),s=Se(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:n});let c=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:c,token:s},e.request),e.json({status:!0})}),Yt=m("/reset-password/:token",{method:"GET",query:O.object({callbackURL:O.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(Ve(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Ve(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Kt(e.context,r,{token:t}))}),Xt=m("/reset-password",{query:O.optional(O.object({token:O.string().optional(),currentURL:O.string().optional()})),method:"POST",body:O.object({newPassword:O.string({description:"The new password to set"}),token:O.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new H("BAD_REQUEST",{message:l.INVALID_TOKEN});let{newPassword:r}=e.body,o=e.context.password?.config.minPasswordLength,i=e.context.password?.config.maxPasswordLength;if(r.length<o)throw new H("BAD_REQUEST",{message:l.PASSWORD_TOO_SHORT});if(r.length>i)throw new H("BAD_REQUEST",{message:l.PASSWORD_TOO_LONG});let n=`reset-password:${t}`,s=await e.context.internalAdapter.findVerificationValue(n);if(!s||s.expiresAt<new Date)throw new H("BAD_REQUEST",{message:l.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(s.id);let c=s.value,a=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(c)).find(f=>f.providerId==="credential")?(await e.context.internalAdapter.updatePassword(c,a),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:c,providerId:"credential",password:a,accountId:c}),e.json({status:!0}))});import{z as _}from"zod";import{APIError as R}from"better-call";import{z as u}from"zod";import{APIError as Yn}from"better-call";var Xn=u.object({id:u.string(),providerId:u.string(),accountId:u.string(),userId:u.string(),accessToken:u.string().nullish(),refreshToken:u.string().nullish(),idToken:u.string().nullish(),accessTokenExpiresAt:u.date().nullish(),refreshTokenExpiresAt:u.date().nullish(),scope:u.string().nullish(),password:u.string().nullish(),createdAt:u.date().default(()=>new Date),updatedAt:u.date().default(()=>new Date)}),es=u.object({id:u.string(),email:u.string().transform(e=>e.toLowerCase()),emailVerified:u.boolean().default(!1),name:u.string(),image:u.string().nullish(),createdAt:u.date().default(()=>new Date),updatedAt:u.date().default(()=>new Date)}),ts=u.object({id:u.string(),userId:u.string(),expiresAt:u.date(),createdAt:u.date().default(()=>new Date),updatedAt:u.date().default(()=>new Date),token:u.string(),ipAddress:u.string().nullish(),userAgent:u.string().nullish()}),rs=u.object({id:u.string(),value:u.string(),createdAt:u.date().default(()=>new Date),updatedAt:u.date().default(()=>new Date),expiresAt:u.date(),identifier:u.string()});import{xchacha20poly1305 as hs}from"@noble/ciphers/chacha";import{bytesToHex as ys,hexToBytes as bs,utf8ToBytes as As}from"@noble/ciphers/utils";import{managedNonce as ks}from"@noble/ciphers/webcrypto";import{sha256 as Us}from"oslo/crypto";import Ts from"uncrypto";import{decodeHex as ns,encodeHex as ss}from"oslo/encoding";import{scryptAsync as ds}from"@noble/hashes/scrypt";import{getRandomValues as ps}from"uncrypto";import $e from"uncrypto";function er(e){return e.toString(2).padStart(8,"0")}function tr(e){return[...e].map(t=>er(t)).join("")}function ze(e){return parseInt(tr(e),2)}function rr(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));$e.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let i=ze(o);for(;i>=e;)$e.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),i=ze(o);return i}function qe(e,t){let r="";for(let o=0;o<e;o++)r+=t[rr(t.length)];return r}function Fe(...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}var ir=m("/change-password",{method:"POST",body:_.object({newPassword:_.string({description:"The new password to set"}),currentPassword:_.string({description:"The current password"}),revokeOtherSessions:_.boolean({description:"Revoke all other sessions"}).optional()}),use:[L],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new R("BAD_REQUEST",{message:l.PASSWORD_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:l.PASSWORD_TOO_LONG});let a=(await e.context.internalAdapter.findAccounts(i.user.id)).find(f=>f.providerId==="credential"&&f.password);if(!a||!a.password)throw new R("BAD_REQUEST",{message:l.CREDENTIAL_ACCOUNT_NOT_FOUND});let d=await e.context.password.hash(t);if(!await e.context.password.verify({hash:a.password,password:r}))throw new R("BAD_REQUEST",{message:l.INVALID_PASSWORD});if(await e.context.internalAdapter.updateAccount(a.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(i.user.id);let f=await e.context.internalAdapter.createSession(i.user.id,e.headers);if(!f)throw new R("INTERNAL_SERVER_ERROR",{message:l.FAILED_TO_GET_SESSION});await k(e,{session:f,user:i.user})}return e.json(i.user)}),nr=m("/set-password",{method:"POST",body:_.object({newPassword:_.string()}),metadata:{SERVER_ONLY:!0},use:[L]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new R("BAD_REQUEST",{message:l.PASSWORD_TOO_SHORT});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new R("BAD_REQUEST",{message:l.PASSWORD_TOO_LONG});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password),c=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:c}),e.json(r.user);throw new R("BAD_REQUEST",{message:"user already has a password"})}),sr=m("/delete-user",{method:"POST",use:[Be],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options",{session:e.context.session}),new R("NOT_FOUND");let t=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let i=qe(32,Fe("a-z","A-Z","0-9"));await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${i}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let n=`${e.context.baseURL}/delete-user/callback?token=${i}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:n,token:i},e.request),e.json({success:!0,message:"Verification email sent"})}let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),I(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})}),ar=m("/delete-user/callback",{method:"GET",query:_.object({token:_.string()})},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new R("NOT_FOUND");let t=await V(e);if(!t)throw new R("NOT_FOUND",{message:l.FAILED_TO_GET_USER_INFO});let r=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!r||r.expiresAt<new Date)throw r&&await e.context.internalAdapter.deleteVerificationValue(r.id),new R("NOT_FOUND",{message:l.INVALID_TOKEN});if(r.value!==t.user.id)throw new R("NOT_FOUND",{message:l.INVALID_TOKEN});let o=e.context.options.user.deleteUser?.beforeDelete;o&&await o(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),await e.context.internalAdapter.deleteVerificationValue(r.id),I(e);let i=e.context.options.user.deleteUser?.afterDelete;return i&&await i(t.user,e.request),e.json({success:!0,message:"User deleted"})}),cr=m("/change-email",{method:"POST",query:_.object({currentURL:_.string().optional()}).optional(),body:_.object({newEmail:_.string({description:"The new email to set"}).email(),callbackURL:_.string({description:"The URL to redirect to after email verification"}).optional()}),use:[L],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},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 i=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:i,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new R("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await C(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),e.json({user:null,status:!0})});var dr=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use strict";var ui=Object.create;var so=Object.defineProperty;var pi=Object.getOwnPropertyDescriptor;var fi=Object.getOwnPropertyNames;var mi=Object.getPrototypeOf,Ci=Object.prototype.hasOwnProperty;var hi=(o,e)=>{for(var i in e)so(o,i,{get:e[i],enumerable:!0})},jo=(o,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of fi(e))!Ci.call(o,r)&&r!==i&&so(o,r,{get:()=>e[r],enumerable:!(t=pi(e,r))||t.enumerable});return o};var bo=(o,e,i)=>(i=o!=null?ui(mi(o)):{},jo(e||!o||!o.__esModule?so(i,"default",{value:o,enumerable:!0}):i,o)),yi=o=>jo(so({},"__esModule",{value:!0}),o);var et={};hi(et,{openAPI:()=>ot});module.exports=yi(et);var M=require("zod");var z=(o,e="ms")=>new Date(Date.now()+(e==="sec"?o*1e3:o));var p=require("zod"),Vo=require("better-call"),rt=p.z.object({id:p.z.string(),providerId:p.z.string(),accountId:p.z.string(),userId:p.z.string(),accessToken:p.z.string().nullish(),refreshToken:p.z.string().nullish(),idToken:p.z.string().nullish(),accessTokenExpiresAt:p.z.date().nullish(),refreshTokenExpiresAt:p.z.date().nullish(),scope:p.z.string().nullish(),password:p.z.string().nullish(),createdAt:p.z.date().default(()=>new Date),updatedAt:p.z.date().default(()=>new Date)}),nt=p.z.object({id:p.z.string(),email:p.z.string().transform(o=>o.toLowerCase()),emailVerified:p.z.boolean().default(!1),name:p.z.string(),image:p.z.string().nullish(),createdAt:p.z.date().default(()=>new Date),updatedAt:p.z.date().default(()=>new Date)}),st=p.z.object({id:p.z.string(),userId:p.z.string(),expiresAt:p.z.date(),createdAt:p.z.date().default(()=>new Date),updatedAt:p.z.date().default(()=>new Date),token:p.z.string(),ipAddress:p.z.string().nullish(),userAgent:p.z.string().nullish()}),at=p.z.object({id:p.z.string(),value:p.z.string(),createdAt:p.z.date().default(()=>new Date),updatedAt:p.z.date().default(()=>new Date),expiresAt:p.z.date(),identifier:p.z.string()});function wi(o,e){let i={...e==="user"?o.user?.additionalFields:{},...e==="session"?o.session?.additionalFields:{}};for(let t of o.plugins||[])t.schema&&t.schema[e]&&(i={...i,...t.schema[e].fields});return i}function bi(o,e){let i=e.action||"create",t=e.fields,r={};for(let n in t){if(n in o){if(t[n].input===!1){if(t[n].defaultValue){r[n]=t[n].defaultValue;continue}continue}if(t[n].validator?.input&&o[n]!==void 0){r[n]=t[n].validator.input.parse(o[n]);continue}if(t[n].transform?.input&&o[n]!==void 0){r[n]=t[n].transform?.input(o[n]);continue}r[n]=o[n];continue}if(t[n].defaultValue&&i==="create"){r[n]=t[n].defaultValue;continue}if(t[n].required&&i==="create")throw new Vo.APIError("BAD_REQUEST",{message:`${n} is required`})}return r}function ao(o,e,i){let t=wi(o,"user");return bi(e||{},{fields:t,action:i})}var Ao=Object.create(null),io=o=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(o?Ao:globalThis),Mo=new Proxy(Ao,{get(o,e){return io()[e]??Ao[e]},has(o,e){let i=io();return e in i||e in Ao},set(o,e,i){let t=io(!0);return t[e]=i,!0},deleteProperty(o,e){if(!e)return!1;let i=io(!0);return delete i[e],!0},ownKeys(){let o=io(!0);return Object.keys(o)}});function Ri(o){return o?o!=="false":!1}var Ro=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Ko=Ro==="dev"||Ro==="development",vi=Ro==="test"||Ri(Mo.TEST);function vo(o){try{return JSON.parse(o)}catch{return null}}var $={isAction:!1};var zo=require("nanoid"),to=o=>(0,zo.nanoid)(o);var co=require("oslo/oauth2"),N=require("zod"),ko=require("better-call");var q=class extends Error{constructor(e,i){super(e),this.name="BetterAuthError",this.message=e,this.cause=i,this.stack=""}};function qo(o){try{return new URL(o).origin}catch{return null}}function Ho(o){return o.includes("://")?new URL(o).host:o}async function go(o,e){let i=o.body?.callbackURL||(o.query?.currentURL?qo(o.query?.currentURL):"")||o.context.options.baseURL;if(!i)throw new ko.APIError("BAD_REQUEST",{message:"callbackURL is required"});let t=(0,co.generateCodeVerifier)(),r=(0,co.generateState)(),n=JSON.stringify({callbackURL:i,codeVerifier:t,errorURL:o.body?.errorCallbackURL||o.query?.currentURL,newUserURL:o.body?.newUserCallbackURL,link:e,expiresAt:Date.now()+10*60*1e3}),a=new Date;a.setMinutes(a.getMinutes()+10);let A=await o.context.internalAdapter.createVerificationValue({value:n,identifier:r,expiresAt:a});if(!A)throw o.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ko.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:A.identifier,codeVerifier:t}}async function Qo(o){let e=o.query.state||o.body.state,i=await o.context.internalAdapter.findVerificationValue(e);if(!i)throw o.context.logger.error("State Mismatch. Verification not found",{state:e}),o.redirect(`${o.context.baseURL}/error?error=please_restart_the_process`);let t=N.z.object({callbackURL:N.z.string(),codeVerifier:N.z.string(),errorURL:N.z.string().optional(),newUserURL:N.z.string().optional(),expiresAt:N.z.number(),link:N.z.object({email:N.z.string(),userId:N.z.string()}).optional()}).parse(JSON.parse(i.value));if(t.errorURL||(t.errorURL=`${o.context.baseURL}/error`),t.expiresAt<Date.now())throw await o.context.internalAdapter.deleteVerificationValue(i.id),o.context.logger.error("State expired.",{state:e}),o.redirect(`${o.context.baseURL}/error?error=please_restart_the_process`);return await o.context.internalAdapter.deleteVerificationValue(i.id),t}var Zo=require("consola"),To=["info","success","warn","error","debug"];function ki(o,e){return To.indexOf(e)<=To.indexOf(o)}var Ti=(0,Zo.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Go=o=>{let e=o?.disabled!==!0,i=o?.level??"error",t=(r,n,a=[])=>{if(!(!e||!ki(i,r))){if(!o||typeof o.log!="function"){Ti[r]("",n,...a);return}o.log(r==="success"?"info":r,n,a)}};return Object.fromEntries(To.map(r=>[r,(...[n,...a])=>t(r,n,a)]))},S=Go();var W=o=>{let e=o.plugins?.reduce((s,K)=>{let c=K.schema;if(!c)return s;for(let[u,l]of Object.entries(c))s[u]={fields:{...s[u]?.fields,...l.fields},modelName:l.modelName||u};return s},{}),i=o.rateLimit?.storage==="database",t={rateLimit:{modelName:o.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",fieldName:o.rateLimit?.fields?.key||"key"},count:{type:"number",fieldName:o.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",fieldName:o.rateLimit?.fields?.lastRequest||"lastRequest"}}}},{user:r,session:n,account:a,...A}=e||{};return{user:{modelName:o.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:o.user?.fields?.name||"name"},email:{type:"string",unique:!0,required:!0,fieldName:o.user?.fields?.email||"email"},emailVerified:{type:"boolean",defaultValue:()=>!1,required:!0,fieldName:o.user?.fields?.emailVerified||"emailVerified"},image:{type:"string",required:!1,fieldName:o.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:o.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:o.user?.fields?.updatedAt||"updatedAt"},...r?.fields,...o.user?.additionalFields},order:1},session:{modelName:o.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:o.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:o.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:o.session?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,fieldName:o.session?.fields?.updatedAt||"updatedAt"},ipAddress:{type:"string",required:!1,fieldName:o.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:o.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:o.session?.fields?.userId||"userId",references:{model:o.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0},...n?.fields,...o.session?.additionalFields},order:2},account:{modelName:o.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:o.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:o.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:o.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:o.account?.fields?.userId||"userId"},accessToken:{type:"string",required:!1,fieldName:o.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,fieldName:o.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,fieldName:o.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,fieldName:o.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,fieldName:o.account?.fields?.accessTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:o.account?.fields?.scope||"scope"},password:{type:"string",required:!1,fieldName:o.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:o.account?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,fieldName:o.account?.fields?.updatedAt||"updatedAt"},...a?.fields},order:3},verification:{modelName:o.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:o.verification?.fields?.identifier||"identifier"},value:{type:"string",required:!0,fieldName:o.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:o.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!1,defaultValue:()=>new Date,fieldName:o.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!1,defaultValue:()=>new Date,fieldName:o.verification?.fields?.updatedAt||"updatedAt"}},order:4},...A,...i?t:{}}};var Ei=require("zod");var $o=require("kysely"),Uo=require("kysely");var P=require("better-call");var Jo=require("better-call");var Q=require("better-call"),Wo=(0,Q.createMiddleware)(async()=>({})),ro=(0,Q.createMiddlewareCreator)({use:[Wo,(0,Q.createMiddleware)(async()=>({}))]}),f=(0,Q.createEndpointCreator)({use:[Wo]});function Eo(o){return o==="-"||o==="^"||o==="$"||o==="+"||o==="."||o==="("||o===")"||o==="|"||o==="["||o==="]"||o==="{"||o==="}"||o==="*"||o==="?"||o==="\\"?`\\${o}`:o}function xi(o){let e="";for(let i=0;i<o.length;i++)e+=Eo(o[i]);return e}function Xo(o,e=!0){if(Array.isArray(o))return`(?:${o.map(c=>`^${Xo(c,e)}$`).join("|")})`;let i="",t="",r=".";e===!0?(i="/",t="[/\\\\]",r="[^/\\\\]"):e&&(i=e,t=xi(i),t.length>1?(t=`(?:${t})`,r=`((?!${t}).)`):r=`[^${t}]`);let n=e?`${t}+?`:"",a=e?`${t}*?`:"",A=e?o.split(i):[o],s="";for(let K=0;K<A.length;K++){let c=A[K],u=A[K+1],l="";if(!(!c&&K>0)){if(e&&(K===A.length-1?l=a:u!=="**"?l=n:l=""),e&&c==="**"){l&&(s+=K===0?"":l,s+=`(?:${r}*?${l})*?`);continue}for(let d=0;d<c.length;d++){let y=c[d];y==="\\"?d<c.length-1&&(s+=Eo(c[d+1]),d++):y==="?"?s+=r:y==="*"?s+=`${r}*?`:s+=Eo(y)}s+=l}}return s}function Di(o,e){if(typeof e!="string")throw new TypeError(`Sample must be a string, but ${typeof e} given`);return o.test(e)}function Po(o,e){if(typeof o!="string"&&!Array.isArray(o))throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof o} given`);if((typeof e=="string"||typeof e=="boolean")&&(e={separator:e}),arguments.length===2&&!(typeof e>"u"||typeof e=="object"&&e!==null&&!Array.isArray(e)))throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof e} given`);if(e=e||{},e.separator==="\\")throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let i=Xo(o,e.separator),t=new RegExp(`^${i}$`,e.flags),r=Di.bind(null,t);return r.options=e,r.pattern=o,r.regexp=t,r}var Ii=ro(async o=>{if(o.request?.method!=="POST")return;let{body:e,query:i,context:t}=o,r=o.headers?.get("origin")||o.headers?.get("referer")||"",n=e?.callbackURL||i?.callbackURL,a=e?.redirectTo,A=i?.currentURL,s=e?.errorCallbackURL,K=e?.newUserCallbackURL,c=t.trustedOrigins,u=o.headers?.has("cookie"),l=(y,k)=>y.startsWith("/")?!1:k.includes("*")?Po(k)(Ho(y)):y.startsWith(k),d=(y,k)=>{if(!y)return;if(!c.some(m=>l(y,m)||y?.startsWith("/")&&k!=="origin"&&!y.includes(":")))throw o.context.logger.error(`Invalid ${k}: ${y}`),o.context.logger.info(`If it's a valid URL, please add ${y} to trustedOrigins in your auth config
|
|
2
|
-
`,`Current list of trustedOrigins: ${c}`),new Jo.APIError("FORBIDDEN",{message:`Invalid ${k}`})};u&&!o.context.options.advanced?.disableCSRFCheck&&d(r,"origin"),n&&d(n,"callbackURL"),a&&d(a,"redirectURL"),A&&d(A,"currentURL"),s&&d(s,"errorCallbackURL"),K&&d(a,"newUserCallbackURL")});var E=require("better-call"),v=require("zod");var Ni=require("oslo"),Yo=require("oslo/encoding");var lo=require("oslo/crypto");async function _i({value:o,secret:e}){return new lo.HMAC("SHA-256").sign(new TextEncoder().encode(e),new TextEncoder().encode(o)).then(t=>Buffer.from(t).toString("base64"))}function Li({value:o,signature:e,secret:i}){return new lo.HMAC("SHA-256").verify(new TextEncoder().encode(i),Buffer.from(e,"base64"),new TextEncoder().encode(o))}var uo={sign:_i,verify:Li};async function O(o,e,i,t){let r=o.context.authCookies.sessionToken.options,n=i?void 0:o.context.sessionConfig.expiresIn;if(await o.setSignedCookie(o.context.authCookies.sessionToken.name,e.session.token,o.context.secret,{...r,maxAge:n,...t}),i&&await o.setSignedCookie(o.context.authCookies.dontRememberToken.name,"true",o.context.secret,o.context.authCookies.dontRememberToken.options),o.context.options.session?.cookieCache?.enabled){let A=Yo.base64url.encode(new TextEncoder().encode(JSON.stringify({session:e,expiresAt:z(o.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await uo.sign({value:JSON.stringify(e),secret:o.context.secret})})),{includePadding:!1});if(A.length>4093)throw new q("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");o.setCookie(o.context.authCookies.sessionData.name,A,o.context.authCookies.sessionData.options)}o.context.setNewSession(e),o.context.options.secondaryStorage&&await o.context.secondaryStorage?.set(e.session.token,JSON.stringify({user:e.user,session:e.session}),Math.floor((new Date(e.session.expiresAt).getTime()-Date.now())/1e3))}function B(o){o.setCookie(o.context.authCookies.sessionToken.name,"",{...o.context.authCookies.sessionToken.options,maxAge:0}),o.setCookie(o.context.authCookies.sessionData.name,"",{...o.context.authCookies.sessionData.options,maxAge:0}),o.setCookie(o.context.authCookies.dontRememberToken.name,"",{...o.context.authCookies.dontRememberToken.options,maxAge:0})}var re=require("@better-fetch/fetch"),ne=require("better-call"),X=require("jose"),se=require("oslo/jwt");var oe=require("oslo/crypto"),ee=require("oslo/encoding");async function ie(o){let e=await(0,oe.sha256)(new TextEncoder().encode(o));return ee.base64url.encode(new Uint8Array(e),{includePadding:!1})}function po(o){return{tokenType:o.token_type,accessToken:o.access_token,refreshToken:o.refresh_token,accessTokenExpiresAt:o.expires_in?z(o.expires_in,"sec"):void 0,scopes:o?.scope?typeof o.scope=="string"?o.scope.split(" "):o.scope:[],idToken:o.id_token}}async function R({id:o,options:e,authorizationEndpoint:i,state:t,codeVerifier:r,scopes:n,claims:a,redirectURI:A,duration:s}){let K=new URL(i);if(K.searchParams.set("response_type","code"),K.searchParams.set("client_id",e.clientId),K.searchParams.set("state",t),K.searchParams.set("scope",n.join(" ")),K.searchParams.set("redirect_uri",e.redirectURI||A),r){let c=await ie(r);K.searchParams.set("code_challenge_method","S256"),K.searchParams.set("code_challenge",c)}if(a){let c=a.reduce((u,l)=>(u[l]=null,u),{});K.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...c}}))}return s&&K.searchParams.set("duration",s),K}var te=require("@better-fetch/fetch");async function b({code:o,codeVerifier:e,redirectURI:i,options:t,tokenEndpoint:r,authentication:n}){let a=new URLSearchParams,A={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(a.set("grant_type","authorization_code"),a.set("code",o),e&&a.set("code_verifier",e),a.set("redirect_uri",i),n==="basic"){let u=btoa(`${t.clientId}:${t.clientSecret}`);A.authorization=`Basic ${u}`}else a.set("client_id",t.clientId),a.set("client_secret",t.clientSecret);let{data:s,error:K}=await(0,te.betterFetch)(r,{method:"POST",body:a,headers:A});if(K)throw K;return po(s)}var ae=o=>{let e="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:i,scopes:t,redirectURI:r}){let n=t||["email","name"];return o.scope&&n.push(...o.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${o.clientId}&response_type=code&redirect_uri=${r||o.redirectURI}&scope=${n.join(" ")}&state=${i}&response_mode=form_post`)},validateAuthorizationCode:async({code:i,codeVerifier:t,redirectURI:r})=>b({code:i,codeVerifier:t,redirectURI:o.redirectURI||r,options:o,tokenEndpoint:e}),async verifyIdToken(i,t){if(o.disableIdTokenSignIn)return!1;if(o.verifyIdToken)return o.verifyIdToken(i,t);let r=(0,X.decodeProtectedHeader)(i),{kid:n,alg:a}=r;if(!n||!a)return!1;let A=await Bi(n),{payload:s}=await(0,X.jwtVerify)(i,A,{algorithms:[a],issuer:"https://appleid.apple.com",audience:o.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(K=>{s[K]!==void 0&&(s[K]=!!s[K])}),t&&s.nonce!==t?!1:!!s},async getUserInfo(i){if(o.getUserInfo)return o.getUserInfo(i);if(!i.idToken)return null;let t=(0,se.parseJWT)(i.idToken)?.payload;if(!t)return null;let r=t.user?`${t.user.name.firstName} ${t.user.name.lastName}`:t.email,n=await o.mapProfileToUser?.(t);return{user:{id:t.sub,name:r,emailVerified:!1,email:t.email,...n},data:t}}}},Bi=async o=>{let e="https://appleid.apple.com",i="/auth/keys",{data:t}=await(0,re.betterFetch)(`${e}${i}`);if(!t?.keys)throw new ne.APIError("BAD_REQUEST",{message:"Keys not found"});let r=t.keys.find(n=>n.kid===o);if(!r)throw new Error(`JWK with kid ${o} not found`);return await(0,X.importJWK)(r,r.alg)};var Ae=require("@better-fetch/fetch");var Ke=o=>({id:"discord",name:"Discord",createAuthorizationURL({state:e,scopes:i,redirectURI:t}){let r=i||["identify","email"];return o.scope&&r.push(...o.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${r.join("+")}&response_type=code&client_id=${o.clientId}&redirect_uri=${encodeURIComponent(o.redirectURI||t)}&state=${e}&prompt=${o.prompt||"none"}`)},validateAuthorizationCode:async({code:e,redirectURI:i})=>b({code:e,redirectURI:o.redirectURI||i,options:o,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(e){if(o.getUserInfo)return o.getUserInfo(e);let{data:i,error:t}=await(0,Ae.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${e.accessToken}`}});if(t)return null;if(i.avatar===null){let n=i.discriminator==="0"?Number(BigInt(i.id)>>BigInt(22))%6:parseInt(i.discriminator)%5;i.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=i.avatar.startsWith("a_")?"gif":"png";i.image_url=`https://cdn.discordapp.com/avatars/${i.id}/${i.avatar}.${n}`}let r=await o.mapProfileToUser?.(i);return{user:{id:i.id,name:i.display_name||i.username||"",email:i.email,emailVerified:i.verified,image:i.image_url,...r},data:i}}});var de=require("@better-fetch/fetch");var ce=o=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:e,scopes:i,redirectURI:t}){let r=i||["email","public_profile"];return o.scope&&r.push(...o.scope),await R({id:"facebook",options:o,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:r,state:e,redirectURI:t})},validateAuthorizationCode:async({code:e,redirectURI:i})=>b({code:e,redirectURI:o.redirectURI||i,options:o,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(e){if(o.getUserInfo)return o.getUserInfo(e);let{data:i,error:t}=await(0,de.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:e.accessToken}});if(t)return null;let r=await o.mapProfileToUser?.(i);return{user:{id:i.id,name:i.name,email:i.email,image:i.picture.data.url,emailVerified:i.email_verified,...r},data:i}}});var Oo=require("@better-fetch/fetch");var ge=o=>{let e="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:i,scopes:t,codeVerifier:r,redirectURI:n}){let a=t||["user:email"];return o.scope&&a.push(...o.scope),R({id:"github",options:o,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:i,redirectURI:n})},validateAuthorizationCode:async({code:i,redirectURI:t})=>b({code:i,redirectURI:o.redirectURI||t,options:o,tokenEndpoint:e}),async getUserInfo(i){if(o.getUserInfo)return o.getUserInfo(i);let{data:t,error:r}=await(0,Oo.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${i.accessToken}`}});if(r)return null;let n=!1;if(!t.email){let{data:A,error:s}=await(0,Oo.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${i.accessToken}`,"User-Agent":"better-auth"}});s||(t.email=(A.find(K=>K.primary)??A[0])?.email,n=A.find(K=>K.email===t.email)?.verified??!1)}let a=await o.mapProfileToUser?.(t);return{user:{id:t.id.toString(),name:t.name||t.login,email:t.email,image:t.avatar_url,emailVerified:n,...a},data:t}}}};var le=require("oslo/jwt");var ue=require("@better-fetch/fetch"),pe=o=>({id:"google",name:"Google",async createAuthorizationURL({state:e,scopes:i,codeVerifier:t,redirectURI:r}){if(!o.clientId||!o.clientSecret)throw S.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new q("CLIENT_ID_AND_SECRET_REQUIRED");if(!t)throw new q("codeVerifier is required for Google");let n=i||["email","profile","openid"];o.scope&&n.push(...o.scope);let a=await R({id:"google",options:o,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:e,codeVerifier:t,redirectURI:r});return o.accessType&&a.searchParams.set("access_type",o.accessType),o.prompt&&a.searchParams.set("prompt",o.prompt),a},validateAuthorizationCode:async({code:e,codeVerifier:i,redirectURI:t})=>b({code:e,codeVerifier:i,redirectURI:o.redirectURI||t,options:o,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(e,i){if(o.disableIdTokenSignIn)return!1;if(o.verifyIdToken)return o.verifyIdToken(e,i);let t=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${e}`,{data:r}=await(0,ue.betterFetch)(t);return r?r.aud===o.clientId&&r.iss==="https://accounts.google.com":!1},async getUserInfo(e){if(o.getUserInfo)return o.getUserInfo(e);if(!e.idToken)return null;let i=(0,le.parseJWT)(e.idToken)?.payload,t=await o.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:i.email_verified,...t},data:i}}});var fe=require("@better-fetch/fetch"),me=require("oslo/jwt");var Ce=o=>{let e=o.tenantId||"common",i=`https://login.microsoftonline.com/${e}/oauth2/v2.0/authorize`,t=`https://login.microsoftonline.com/${e}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(r){let n=r.scopes||["openid","profile","email","User.Read"];return o.scope&&n.push(...o.scope),R({id:"microsoft",options:o,authorizationEndpoint:i,state:r.state,codeVerifier:r.codeVerifier,scopes:n,redirectURI:r.redirectURI})},validateAuthorizationCode({code:r,codeVerifier:n,redirectURI:a}){return b({code:r,codeVerifier:n,redirectURI:o.redirectURI||a,options:o,tokenEndpoint:t})},async getUserInfo(r){if(o.getUserInfo)return o.getUserInfo(r);if(!r.idToken)return null;let n=(0,me.parseJWT)(r.idToken)?.payload,a=o.profilePhotoSize||48;await(0,fe.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${r.accessToken}`},async onResponse(s){if(!(o.disableProfilePhoto||!s.response.ok))try{let c=await s.response.clone().arrayBuffer(),u=Buffer.from(c).toString("base64");n.picture=`data:image/jpeg;base64, ${u}`}catch(K){S.error(K&&typeof K=="object"&&"name"in K?K.name:"",K)}}});let A=await o.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0,...A},data:n}}}};var he=require("@better-fetch/fetch");var ye=o=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:e,scopes:i,codeVerifier:t,redirectURI:r}){let n=i||["user-read-email"];return o.scope&&n.push(...o.scope),R({id:"spotify",options:o,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:e,codeVerifier:t,redirectURI:r})},validateAuthorizationCode:async({code:e,codeVerifier:i,redirectURI:t})=>b({code:e,codeVerifier:i,redirectURI:o.redirectURI||t,options:o,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(e){if(o.getUserInfo)return o.getUserInfo(e);let{data:i,error:t}=await(0,he.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});if(t)return null;let r=await o.mapProfileToUser?.(i);return{user:{id:i.id,name:i.display_name,email:i.email,image:i.images[0]?.url,emailVerified:!1,...r},data:i}}});var we=require("oslo/jwt");var be=o=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:e,scopes:i,redirectURI:t}){let r=i||["user:read:email","openid"];return o.scope&&r.push(...o.scope),R({id:"twitch",redirectURI:t,options:o,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:r,state:e,claims:o.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:e,redirectURI:i})=>b({code:e,redirectURI:o.redirectURI||i,options:o,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(e){if(o.getUserInfo)return o.getUserInfo(e);let i=e.idToken;if(!i)return S.error("No idToken found in token"),null;let t=(0,we.parseJWT)(i)?.payload,r=await o.mapProfileToUser?.(t);return{user:{id:t.sub,name:t.preferred_username,email:t.email,image:t.picture,emailVerified:!1,...r},data:t}}});var Re=require("@better-fetch/fetch");var ve=o=>({id:"twitter",name:"Twitter",createAuthorizationURL(e){let i=e.scopes||["users.read","tweet.read","offline.access"];return o.scope&&i.push(...o.scope),R({id:"twitter",options:o,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:i,state:e.state,codeVerifier:e.codeVerifier,redirectURI:e.redirectURI})},validateAuthorizationCode:async({code:e,codeVerifier:i,redirectURI:t})=>b({code:e,codeVerifier:i,authentication:"basic",redirectURI:o.redirectURI||t,options:o,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(e){if(o.getUserInfo)return o.getUserInfo(e);let{data:i,error:t}=await(0,Re.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});if(t)return null;let r=await o.mapProfileToUser?.(i);return{user:{id:i.data.id,name:i.data.name,email:i.data.username||null,image:i.data.profile_image_url,emailVerified:i.data.verified||!1,...r},data:i}}});var ke=require("@better-fetch/fetch");var Te=o=>{let e="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:i,scopes:t,codeVerifier:r,redirectURI:n})=>{let a=t||["account_info.read"];return o.scope&&a.push(...o.scope),await R({id:"dropbox",options:o,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:i,redirectURI:n,codeVerifier:r})},validateAuthorizationCode:async({code:i,codeVerifier:t,redirectURI:r})=>await b({code:i,codeVerifier:t,redirectURI:o.redirectURI||r,options:o,tokenEndpoint:e}),async getUserInfo(i){if(o.getUserInfo)return o.getUserInfo(i);let{data:t,error:r}=await(0,ke.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${i.accessToken}`}});if(r)return null;let n=await o.mapProfileToUser?.(t);return{user:{id:t.account_id,name:t.name?.display_name,email:t.email,emailVerified:t.email_verified||!1,image:t.profile_photo_url,...n},data:t}}}};var Ue=require("@better-fetch/fetch");var Ee=o=>{let e="https://www.linkedin.com/oauth/v2/authorization",i="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:t,scopes:r,redirectURI:n})=>{let a=r||["profile","email","openid"];return o.scope&&a.push(...o.scope),await R({id:"linkedin",options:o,authorizationEndpoint:e,scopes:a,state:t,redirectURI:n})},validateAuthorizationCode:async({code:t,redirectURI:r})=>await b({code:t,redirectURI:o.redirectURI||r,options:o,tokenEndpoint:i}),async getUserInfo(t){let{data:r,error:n}=await(0,Ue.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let a=await o.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,emailVerified:r.email_verified||!1,image:r.picture,...a},data:r}}}};var Pe=require("@better-fetch/fetch");var xo=(o="")=>o.split("://").map(e=>e.replace(/\/{2,}/g,"/")).join("://"),Fi=o=>{let e=o||"https://gitlab.com";return{authorizationEndpoint:xo(`${e}/oauth/authorize`),tokenEndpoint:xo(`${e}/oauth/token`),userinfoEndpoint:xo(`${e}/api/v4/user`)}},Oe=o=>{let{authorizationEndpoint:e,tokenEndpoint:i,userinfoEndpoint:t}=Fi(o.issuer),r="gitlab";return{id:r,name:"Gitlab",createAuthorizationURL:async({state:a,scopes:A,codeVerifier:s,redirectURI:K})=>{let c=A||["read_user"];return o.scope&&c.push(...o.scope),await R({id:r,options:o,authorizationEndpoint:e,scopes:c,state:a,redirectURI:K,codeVerifier:s})},validateAuthorizationCode:async({code:a,redirectURI:A,codeVerifier:s})=>b({code:a,redirectURI:o.redirectURI||A,options:o,codeVerifier:s,tokenEndpoint:i}),async getUserInfo(a){if(o.getUserInfo)return o.getUserInfo(a);let{data:A,error:s}=await(0,Pe.betterFetch)(t,{headers:{authorization:`Bearer ${a.accessToken}`}});if(s||A.state!=="active"||A.locked)return null;let K=await o.mapProfileToUser?.(A);return{user:{id:A.id.toString(),name:A.name??A.username,email:A.email,image:A.avatar_url,emailVerified:!0,...K},data:A}}}};var Do=require("@better-fetch/fetch");var xe=o=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:e,scopes:i,redirectURI:t}){let r=i||["identity"];return o.scope&&r.push(...o.scope),R({id:"reddit",options:o,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:r,state:e,redirectURI:t,duration:o.duration})},validateAuthorizationCode:async({code:e,redirectURI:i})=>{let t=new URLSearchParams({grant_type:"authorization_code",code:e,redirect_uri:o.redirectURI||i}),r={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${o.clientId}:${o.clientSecret}`).toString("base64")}`},{data:n,error:a}=await(0,Do.betterFetch)("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:r,body:t.toString()});if(a)throw a;return po(n)},async getUserInfo(e){if(o.getUserInfo)return o.getUserInfo(e);let{data:i,error:t}=await(0,Do.betterFetch)("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${e.accessToken}`,"User-Agent":"better-auth"}});if(t)return null;let r=await o.mapProfileToUser?.(i);return{user:{id:i.id,name:i.name,email:i.oauth_client_id,emailVerified:i.has_verified_email,image:i.icon_img?.split("?")[0],...r},data:i}}});var ji={apple:ae,discord:Ke,facebook:ce,github:ge,microsoft:Ce,google:pe,spotify:ye,twitch:be,twitter:ve,dropbox:Te,linkedin:Ee,gitlab:Oe,reddit:xe},fo=Object.keys(ji);var Ne=require("oslo"),mo=require("oslo/jwt"),L=require("zod");var J=require("better-call");var F=require("better-call");var H=require("zod");var g={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found"};var Io=()=>f("/get-session",{method:"GET",query:H.z.optional(H.z.object({disableCookieCache:H.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(H.z.string().transform(o=>o==="true")).optional(),disableRefresh:H.z.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async o=>{try{let e=await o.getSignedCookie(o.context.authCookies.sessionToken.name,o.context.secret);if(!e)return o.json(null);let i=o.getCookie(o.context.authCookies.sessionData.name),t=i?vo(Buffer.from(i,"base64").toString()):null;if(t&&!await uo.verify({value:JSON.stringify(t.session),signature:t?.signature,secret:o.context.secret}))return B(o),o.json(null);let r=await o.getSignedCookie(o.context.authCookies.dontRememberToken.name,o.context.secret);if(t?.session&&o.context.options.session?.cookieCache?.enabled&&!o.query?.disableCookieCache){let c=t.session;if(t.expiresAt<Date.now()||c.session.expiresAt<new Date){let l=o.context.authCookies.sessionData.name;o.setCookie(l,"",{maxAge:0})}else return o.json(c)}let n=await o.context.internalAdapter.findSession(e);if(o.context.session=n,!n||n.session.expiresAt<new Date)return B(o),n&&await o.context.internalAdapter.deleteSession(n.session.token),o.json(null);if(r||o.query?.disableRefresh)return o.json(n);let a=o.context.sessionConfig.expiresIn,A=o.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-a*1e3+A*1e3<=Date.now()){let c=await o.context.internalAdapter.updateSession(n.session.token,{expiresAt:z(o.context.sessionConfig.expiresIn,"sec")});if(!c)return B(o),o.json(null,{status:401});let u=(c.expiresAt.valueOf()-Date.now())/1e3;return await O(o,{session:c,user:n.user},!1,{maxAge:u}),o.json({session:c,user:n.user})}return o.json(n)}catch(e){throw o.context.logger.error("INTERNAL_SERVER_ERROR",e),new F.APIError("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_GET_SESSION})}}),Z=async(o,e)=>{if(o.context.session)return o.context.session;let i=await Io()({...o,_flag:"json",headers:o.headers,query:e}).catch(t=>null);return o.context.session=i,i},_=ro(async o=>{let e=await Z(o);if(!e?.session)throw new F.APIError("UNAUTHORIZED");return{session:e}}),De=ro(async o=>{let e=await Z(o);if(!e?.session)throw new F.APIError("UNAUTHORIZED");if(o.context.sessionConfig.freshAge===0)return{session:e};let i=o.context.sessionConfig.freshAge,t=e.session.createdAt.valueOf(),r=Date.now();if(!(t+i*1e3>r))throw new F.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:e}}),Ie=()=>f("/list-sessions",{method:"GET",use:[_],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async o=>{let i=(await o.context.internalAdapter.listSessions(o.context.session.user.id)).filter(t=>t.expiresAt>new Date);return o.json(i)}),Se=f("/revoke-session",{method:"POST",body:H.z.object({token:H.z.string({description:"The token to revoke"})}),use:[_],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async o=>{let e=o.body.token,i=await o.context.internalAdapter.findSession(e);if(!i)throw new F.APIError("BAD_REQUEST",{message:"Session not found"});if(i.session.userId!==o.context.session.user.id)throw new F.APIError("UNAUTHORIZED");try{await o.context.internalAdapter.deleteSession(e)}catch(t){throw o.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new F.APIError("INTERNAL_SERVER_ERROR")}return o.json({status:!0})}),_e=f("/revoke-sessions",{method:"POST",use:[_],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async o=>{try{await o.context.internalAdapter.deleteSessions(o.context.session.user.id)}catch(e){throw o.context.logger.error(e&&typeof e=="object"&&"name"in e?e.name:"",e),new F.APIError("INTERNAL_SERVER_ERROR")}return o.json({status:!0})}),Le=f("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[_],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async o=>{let e=o.context.session;if(!e.user)throw new F.APIError("UNAUTHORIZED");let r=(await o.context.internalAdapter.listSessions(e.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.token!==o.context.session.session.token);return await Promise.all(r.map(n=>o.context.internalAdapter.deleteSession(n.token))),o.json({status:!0})});async function j(o,e,i){return await(0,mo.createJWT)("HS256",Buffer.from(o),{email:e.toLowerCase(),updateTo:i},{expiresIn:new Ne.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[e],includeIssuedTimestamp:!0})}async function Vi(o,e){if(!o.context.options.emailVerification?.sendVerificationEmail)throw o.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let i=await j(o.context.secret,e.email),t=`${o.context.baseURL}/verify-email?token=${i}&callbackURL=${o.body.callbackURL||o.query?.currentURL||"/"}`;await o.context.options.emailVerification.sendVerificationEmail({user:e,url:t,token:i},o.request)}var Be=f("/send-verification-email",{method:"POST",query:L.z.object({currentURL:L.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:L.z.object({email:L.z.string({description:"The email to send the verification email to"}).email(),callbackURL:L.z.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async o=>{if(!o.context.options.emailVerification?.sendVerificationEmail)throw o.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:e}=o.body,i=await o.context.internalAdapter.findUserByEmail(e);if(!i)throw new J.APIError("BAD_REQUEST",{message:g.USER_NOT_FOUND});return await Vi(o,i.user),o.json({status:!0})}),Fe=f("/verify-email",{method:"GET",query:L.z.object({token:L.z.string({description:"The token to verify the email"}),callbackURL:L.z.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async o=>{function e(A){throw o.query.callbackURL?o.query.callbackURL.includes("?")?o.redirect(`${o.query.callbackURL}&error=${A}`):o.redirect(`${o.query.callbackURL}?error=${A}`):new J.APIError("UNAUTHORIZED",{message:A})}let{token:i}=o.query,t;try{t=await(0,mo.validateJWT)("HS256",Buffer.from(o.context.secret),i)}catch(A){return o.context.logger.error("Failed to verify email",A),e("invalid_token")}let n=L.z.object({email:L.z.string().email(),updateTo:L.z.string().optional()}).parse(t.payload),a=await o.context.internalAdapter.findUserByEmail(n.email);if(!a)return e("user_not_found");if(n.updateTo){let A=await Z(o);if(!A){if(o.query.callbackURL)throw o.redirect(`${o.query.callbackURL}?error=unauthorized`);return e("unauthorized")}if(A.user.email!==n.email){if(o.query.callbackURL)throw o.redirect(`${o.query.callbackURL}?error=unauthorized`);return e("unauthorized")}let s=await o.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo,emailVerified:!1}),K=await j(o.context.secret,n.updateTo);if(await o.context.options.emailVerification?.sendVerificationEmail?.({user:s,url:`${o.context.baseURL}/verify-email?token=${K}`,token:K},o.request),o.query.callbackURL)throw o.redirect(o.query.callbackURL);return o.json({user:s,status:!0})}if(await o.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),o.context.options.emailVerification?.autoSignInAfterVerification&&!await Z(o)){let s=await o.context.internalAdapter.createSession(a.user.id,o.request);if(!s)throw new J.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await O(o,{session:s,user:a.user})}if(o.query.callbackURL)throw o.redirect(o.query.callbackURL);return o.json({user:null,status:!0})});async function Co(o,{userInfo:e,account:i,callbackURL:t}){let r=await o.context.internalAdapter.findUserByEmail(e.email.toLowerCase(),{includeAccounts:!0}).catch(s=>{throw S.error(`Better auth was unable to query your database.
|
|
2
|
+
`,`Current list of trustedOrigins: ${c}`),new Jo.APIError("FORBIDDEN",{message:`Invalid ${k}`})};u&&!o.context.options.advanced?.disableCSRFCheck&&d(r,"origin"),n&&d(n,"callbackURL"),a&&d(a,"redirectURL"),A&&d(A,"currentURL"),s&&d(s,"errorCallbackURL"),K&&d(a,"newUserCallbackURL")});var E=require("better-call"),v=require("zod");var Ni=require("oslo"),Yo=require("oslo/encoding");var lo=require("oslo/crypto");async function _i({value:o,secret:e}){return new lo.HMAC("SHA-256").sign(new TextEncoder().encode(e),new TextEncoder().encode(o)).then(t=>Buffer.from(t).toString("base64"))}function Li({value:o,signature:e,secret:i}){return new lo.HMAC("SHA-256").verify(new TextEncoder().encode(i),Buffer.from(e,"base64"),new TextEncoder().encode(o))}var uo={sign:_i,verify:Li};async function O(o,e,i,t){let r=o.context.authCookies.sessionToken.options,n=i?void 0:o.context.sessionConfig.expiresIn;if(await o.setSignedCookie(o.context.authCookies.sessionToken.name,e.session.token,o.context.secret,{...r,maxAge:n,...t}),i&&await o.setSignedCookie(o.context.authCookies.dontRememberToken.name,"true",o.context.secret,o.context.authCookies.dontRememberToken.options),o.context.options.session?.cookieCache?.enabled){let A=Yo.base64url.encode(new TextEncoder().encode(JSON.stringify({session:e,expiresAt:z(o.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await uo.sign({value:JSON.stringify(e),secret:o.context.secret})})),{includePadding:!1});if(A.length>4093)throw new q("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");o.setCookie(o.context.authCookies.sessionData.name,A,o.context.authCookies.sessionData.options)}o.context.setNewSession(e),o.context.options.secondaryStorage&&await o.context.secondaryStorage?.set(e.session.token,JSON.stringify({user:e.user,session:e.session}),Math.floor((new Date(e.session.expiresAt).getTime()-Date.now())/1e3))}function B(o){o.setCookie(o.context.authCookies.sessionToken.name,"",{...o.context.authCookies.sessionToken.options,maxAge:0}),o.setCookie(o.context.authCookies.sessionData.name,"",{...o.context.authCookies.sessionData.options,maxAge:0}),o.setCookie(o.context.authCookies.dontRememberToken.name,"",{...o.context.authCookies.dontRememberToken.options,maxAge:0})}var re=require("@better-fetch/fetch"),ne=require("better-call"),X=require("jose"),se=require("oslo/jwt");var oe=require("oslo/crypto"),ee=require("oslo/encoding");async function ie(o){let e=await(0,oe.sha256)(new TextEncoder().encode(o));return ee.base64url.encode(new Uint8Array(e),{includePadding:!1})}function po(o){return{tokenType:o.token_type,accessToken:o.access_token,refreshToken:o.refresh_token,accessTokenExpiresAt:o.expires_in?z(o.expires_in,"sec"):void 0,scopes:o?.scope?typeof o.scope=="string"?o.scope.split(" "):o.scope:[],idToken:o.id_token}}async function R({id:o,options:e,authorizationEndpoint:i,state:t,codeVerifier:r,scopes:n,claims:a,redirectURI:A,duration:s}){let K=new URL(i);if(K.searchParams.set("response_type","code"),K.searchParams.set("client_id",e.clientId),K.searchParams.set("state",t),K.searchParams.set("scope",n.join(" ")),K.searchParams.set("redirect_uri",e.redirectURI||A),r){let c=await ie(r);K.searchParams.set("code_challenge_method","S256"),K.searchParams.set("code_challenge",c)}if(a){let c=a.reduce((u,l)=>(u[l]=null,u),{});K.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...c}}))}return s&&K.searchParams.set("duration",s),K}var te=require("@better-fetch/fetch");async function b({code:o,codeVerifier:e,redirectURI:i,options:t,tokenEndpoint:r,authentication:n}){let a=new URLSearchParams,A={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(a.set("grant_type","authorization_code"),a.set("code",o),e&&a.set("code_verifier",e),a.set("redirect_uri",i),n==="basic"){let u=btoa(`${t.clientId}:${t.clientSecret}`);A.authorization=`Basic ${u}`}else a.set("client_id",t.clientId),a.set("client_secret",t.clientSecret);let{data:s,error:K}=await(0,te.betterFetch)(r,{method:"POST",body:a,headers:A});if(K)throw K;return po(s)}var ae=o=>{let e="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:i,scopes:t,redirectURI:r}){let n=t||["email","name"];return o.scope&&n.push(...o.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${o.clientId}&response_type=code&redirect_uri=${r||o.redirectURI}&scope=${n.join(" ")}&state=${i}&response_mode=form_post`)},validateAuthorizationCode:async({code:i,codeVerifier:t,redirectURI:r})=>b({code:i,codeVerifier:t,redirectURI:o.redirectURI||r,options:o,tokenEndpoint:e}),async verifyIdToken(i,t){if(o.disableIdTokenSignIn)return!1;if(o.verifyIdToken)return o.verifyIdToken(i,t);let r=(0,X.decodeProtectedHeader)(i),{kid:n,alg:a}=r;if(!n||!a)return!1;let A=await Bi(n),{payload:s}=await(0,X.jwtVerify)(i,A,{algorithms:[a],issuer:"https://appleid.apple.com",audience:o.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(K=>{s[K]!==void 0&&(s[K]=!!s[K])}),t&&s.nonce!==t?!1:!!s},async getUserInfo(i){if(o.getUserInfo)return o.getUserInfo(i);if(!i.idToken)return null;let t=(0,se.parseJWT)(i.idToken)?.payload;if(!t)return null;let r=t.user?`${t.user.name.firstName} ${t.user.name.lastName}`:t.email,n=await o.mapProfileToUser?.(t);return{user:{id:t.sub,name:r,emailVerified:!1,email:t.email,...n},data:t}}}},Bi=async o=>{let e="https://appleid.apple.com",i="/auth/keys",{data:t}=await(0,re.betterFetch)(`${e}${i}`);if(!t?.keys)throw new ne.APIError("BAD_REQUEST",{message:"Keys not found"});let r=t.keys.find(n=>n.kid===o);if(!r)throw new Error(`JWK with kid ${o} not found`);return await(0,X.importJWK)(r,r.alg)};var Ae=require("@better-fetch/fetch");var Ke=o=>({id:"discord",name:"Discord",createAuthorizationURL({state:e,scopes:i,redirectURI:t}){let r=i||["identify","email"];return o.scope&&r.push(...o.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${r.join("+")}&response_type=code&client_id=${o.clientId}&redirect_uri=${encodeURIComponent(o.redirectURI||t)}&state=${e}&prompt=${o.prompt||"none"}`)},validateAuthorizationCode:async({code:e,redirectURI:i})=>b({code:e,redirectURI:o.redirectURI||i,options:o,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(e){if(o.getUserInfo)return o.getUserInfo(e);let{data:i,error:t}=await(0,Ae.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${e.accessToken}`}});if(t)return null;if(i.avatar===null){let n=i.discriminator==="0"?Number(BigInt(i.id)>>BigInt(22))%6:parseInt(i.discriminator)%5;i.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=i.avatar.startsWith("a_")?"gif":"png";i.image_url=`https://cdn.discordapp.com/avatars/${i.id}/${i.avatar}.${n}`}let r=await o.mapProfileToUser?.(i);return{user:{id:i.id,name:i.display_name||i.username||"",email:i.email,emailVerified:i.verified,image:i.image_url,...r},data:i}}});var de=require("@better-fetch/fetch");var ce=o=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:e,scopes:i,redirectURI:t}){let r=i||["email","public_profile"];return o.scope&&r.push(...o.scope),await R({id:"facebook",options:o,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:r,state:e,redirectURI:t})},validateAuthorizationCode:async({code:e,redirectURI:i})=>b({code:e,redirectURI:o.redirectURI||i,options:o,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(e){if(o.getUserInfo)return o.getUserInfo(e);let{data:i,error:t}=await(0,de.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:e.accessToken}});if(t)return null;let r=await o.mapProfileToUser?.(i);return{user:{id:i.id,name:i.name,email:i.email,image:i.picture.data.url,emailVerified:i.email_verified,...r},data:i}}});var Oo=require("@better-fetch/fetch");var ge=o=>{let e="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:i,scopes:t,codeVerifier:r,redirectURI:n}){let a=t||["user:email"];return o.scope&&a.push(...o.scope),R({id:"github",options:o,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:i,redirectURI:n})},validateAuthorizationCode:async({code:i,redirectURI:t})=>b({code:i,redirectURI:o.redirectURI||t,options:o,tokenEndpoint:e}),async getUserInfo(i){if(o.getUserInfo)return o.getUserInfo(i);let{data:t,error:r}=await(0,Oo.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${i.accessToken}`}});if(r)return null;let n=!1;if(!t.email){let{data:A,error:s}=await(0,Oo.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${i.accessToken}`,"User-Agent":"better-auth"}});s||(t.email=(A.find(K=>K.primary)??A[0])?.email,n=A.find(K=>K.email===t.email)?.verified??!1)}let a=await o.mapProfileToUser?.(t);return{user:{id:t.id.toString(),name:t.name||t.login,email:t.email,image:t.avatar_url,emailVerified:n,...a},data:t}}}};var le=require("oslo/jwt");var ue=require("@better-fetch/fetch"),pe=o=>({id:"google",name:"Google",async createAuthorizationURL({state:e,scopes:i,codeVerifier:t,redirectURI:r}){if(!o.clientId||!o.clientSecret)throw S.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new q("CLIENT_ID_AND_SECRET_REQUIRED");if(!t)throw new q("codeVerifier is required for Google");let n=i||["email","profile","openid"];o.scope&&n.push(...o.scope);let a=await R({id:"google",options:o,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:e,codeVerifier:t,redirectURI:r});return o.accessType&&a.searchParams.set("access_type",o.accessType),o.prompt&&a.searchParams.set("prompt",o.prompt),a},validateAuthorizationCode:async({code:e,codeVerifier:i,redirectURI:t})=>b({code:e,codeVerifier:i,redirectURI:o.redirectURI||t,options:o,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(e,i){if(o.disableIdTokenSignIn)return!1;if(o.verifyIdToken)return o.verifyIdToken(e,i);let t=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${e}`,{data:r}=await(0,ue.betterFetch)(t);return r?r.aud===o.clientId&&r.iss==="https://accounts.google.com":!1},async getUserInfo(e){if(o.getUserInfo)return o.getUserInfo(e);if(!e.idToken)return null;let i=(0,le.parseJWT)(e.idToken)?.payload,t=await o.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:i.email_verified,...t},data:i}}});var fe=require("@better-fetch/fetch"),me=require("oslo/jwt");var Ce=o=>{let e=o.tenantId||"common",i=`https://login.microsoftonline.com/${e}/oauth2/v2.0/authorize`,t=`https://login.microsoftonline.com/${e}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(r){let n=r.scopes||["openid","profile","email","User.Read"];return o.scope&&n.push(...o.scope),R({id:"microsoft",options:o,authorizationEndpoint:i,state:r.state,codeVerifier:r.codeVerifier,scopes:n,redirectURI:r.redirectURI})},validateAuthorizationCode({code:r,codeVerifier:n,redirectURI:a}){return b({code:r,codeVerifier:n,redirectURI:o.redirectURI||a,options:o,tokenEndpoint:t})},async getUserInfo(r){if(o.getUserInfo)return o.getUserInfo(r);if(!r.idToken)return null;let n=(0,me.parseJWT)(r.idToken)?.payload,a=o.profilePhotoSize||48;await(0,fe.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${r.accessToken}`},async onResponse(s){if(!(o.disableProfilePhoto||!s.response.ok))try{let c=await s.response.clone().arrayBuffer(),u=Buffer.from(c).toString("base64");n.picture=`data:image/jpeg;base64, ${u}`}catch(K){S.error(K&&typeof K=="object"&&"name"in K?K.name:"",K)}}});let A=await o.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0,...A},data:n}}}};var he=require("@better-fetch/fetch");var ye=o=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:e,scopes:i,codeVerifier:t,redirectURI:r}){let n=i||["user-read-email"];return o.scope&&n.push(...o.scope),R({id:"spotify",options:o,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:e,codeVerifier:t,redirectURI:r})},validateAuthorizationCode:async({code:e,codeVerifier:i,redirectURI:t})=>b({code:e,codeVerifier:i,redirectURI:o.redirectURI||t,options:o,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(e){if(o.getUserInfo)return o.getUserInfo(e);let{data:i,error:t}=await(0,he.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});if(t)return null;let r=await o.mapProfileToUser?.(i);return{user:{id:i.id,name:i.display_name,email:i.email,image:i.images[0]?.url,emailVerified:!1,...r},data:i}}});var we=require("oslo/jwt");var be=o=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:e,scopes:i,redirectURI:t}){let r=i||["user:read:email","openid"];return o.scope&&r.push(...o.scope),R({id:"twitch",redirectURI:t,options:o,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:r,state:e,claims:o.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:e,redirectURI:i})=>b({code:e,redirectURI:o.redirectURI||i,options:o,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(e){if(o.getUserInfo)return o.getUserInfo(e);let i=e.idToken;if(!i)return S.error("No idToken found in token"),null;let t=(0,we.parseJWT)(i)?.payload,r=await o.mapProfileToUser?.(t);return{user:{id:t.sub,name:t.preferred_username,email:t.email,image:t.picture,emailVerified:!1,...r},data:t}}});var Re=require("@better-fetch/fetch");var ve=o=>({id:"twitter",name:"Twitter",createAuthorizationURL(e){let i=e.scopes||["users.read","tweet.read","offline.access"];return o.scope&&i.push(...o.scope),R({id:"twitter",options:o,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:i,state:e.state,codeVerifier:e.codeVerifier,redirectURI:e.redirectURI})},validateAuthorizationCode:async({code:e,codeVerifier:i,redirectURI:t})=>b({code:e,codeVerifier:i,authentication:"basic",redirectURI:o.redirectURI||t,options:o,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(e){if(o.getUserInfo)return o.getUserInfo(e);let{data:i,error:t}=await(0,Re.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});if(t)return null;let r=await o.mapProfileToUser?.(i);return{user:{id:i.data.id,name:i.data.name,email:i.data.username||null,image:i.data.profile_image_url,emailVerified:i.data.verified||!1,...r},data:i}}});var ke=require("@better-fetch/fetch");var Te=o=>{let e="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:i,scopes:t,codeVerifier:r,redirectURI:n})=>{let a=t||["account_info.read"];return o.scope&&a.push(...o.scope),await R({id:"dropbox",options:o,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:i,redirectURI:n,codeVerifier:r})},validateAuthorizationCode:async({code:i,codeVerifier:t,redirectURI:r})=>await b({code:i,codeVerifier:t,redirectURI:o.redirectURI||r,options:o,tokenEndpoint:e}),async getUserInfo(i){if(o.getUserInfo)return o.getUserInfo(i);let{data:t,error:r}=await(0,ke.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${i.accessToken}`}});if(r)return null;let n=await o.mapProfileToUser?.(t);return{user:{id:t.account_id,name:t.name?.display_name,email:t.email,emailVerified:t.email_verified||!1,image:t.profile_photo_url,...n},data:t}}}};var Ue=require("@better-fetch/fetch");var Ee=o=>{let e="https://www.linkedin.com/oauth/v2/authorization",i="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:t,scopes:r,redirectURI:n})=>{let a=r||["profile","email","openid"];return o.scope&&a.push(...o.scope),await R({id:"linkedin",options:o,authorizationEndpoint:e,scopes:a,state:t,redirectURI:n})},validateAuthorizationCode:async({code:t,redirectURI:r})=>await b({code:t,redirectURI:o.redirectURI||r,options:o,tokenEndpoint:i}),async getUserInfo(t){let{data:r,error:n}=await(0,Ue.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let a=await o.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,emailVerified:r.email_verified||!1,image:r.picture,...a},data:r}}}};var Pe=require("@better-fetch/fetch");var xo=(o="")=>o.split("://").map(e=>e.replace(/\/{2,}/g,"/")).join("://"),Fi=o=>{let e=o||"https://gitlab.com";return{authorizationEndpoint:xo(`${e}/oauth/authorize`),tokenEndpoint:xo(`${e}/oauth/token`),userinfoEndpoint:xo(`${e}/api/v4/user`)}},Oe=o=>{let{authorizationEndpoint:e,tokenEndpoint:i,userinfoEndpoint:t}=Fi(o.issuer),r="gitlab";return{id:r,name:"Gitlab",createAuthorizationURL:async({state:a,scopes:A,codeVerifier:s,redirectURI:K})=>{let c=A||["read_user"];return o.scope&&c.push(...o.scope),await R({id:r,options:o,authorizationEndpoint:e,scopes:c,state:a,redirectURI:K,codeVerifier:s})},validateAuthorizationCode:async({code:a,redirectURI:A,codeVerifier:s})=>b({code:a,redirectURI:o.redirectURI||A,options:o,codeVerifier:s,tokenEndpoint:i}),async getUserInfo(a){if(o.getUserInfo)return o.getUserInfo(a);let{data:A,error:s}=await(0,Pe.betterFetch)(t,{headers:{authorization:`Bearer ${a.accessToken}`}});if(s||A.state!=="active"||A.locked)return null;let K=await o.mapProfileToUser?.(A);return{user:{id:A.id.toString(),name:A.name??A.username,email:A.email,image:A.avatar_url,emailVerified:!0,...K},data:A}}}};var Do=require("@better-fetch/fetch");var xe=o=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:e,scopes:i,redirectURI:t}){let r=i||["identity"];return o.scope&&r.push(...o.scope),R({id:"reddit",options:o,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:r,state:e,redirectURI:t,duration:o.duration})},validateAuthorizationCode:async({code:e,redirectURI:i})=>{let t=new URLSearchParams({grant_type:"authorization_code",code:e,redirect_uri:o.redirectURI||i}),r={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${o.clientId}:${o.clientSecret}`).toString("base64")}`},{data:n,error:a}=await(0,Do.betterFetch)("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:r,body:t.toString()});if(a)throw a;return po(n)},async getUserInfo(e){if(o.getUserInfo)return o.getUserInfo(e);let{data:i,error:t}=await(0,Do.betterFetch)("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${e.accessToken}`,"User-Agent":"better-auth"}});if(t)return null;let r=await o.mapProfileToUser?.(i);return{user:{id:i.id,name:i.name,email:i.oauth_client_id,emailVerified:i.has_verified_email,image:i.icon_img?.split("?")[0],...r},data:i}}});var ji={apple:ae,discord:Ke,facebook:ce,github:ge,microsoft:Ce,google:pe,spotify:ye,twitch:be,twitter:ve,dropbox:Te,linkedin:Ee,gitlab:Oe,reddit:xe},fo=Object.keys(ji);var Ne=require("oslo"),mo=require("oslo/jwt"),L=require("zod");var J=require("better-call");var F=require("better-call");var H=require("zod");var g={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found"};var Io=()=>f("/get-session",{method:"GET",query:H.z.optional(H.z.object({disableCookieCache:H.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(H.z.string().transform(o=>o==="true")).optional(),disableRefresh:H.z.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async o=>{try{let e=await o.getSignedCookie(o.context.authCookies.sessionToken.name,o.context.secret);if(!e)return o.json(null);let i=o.getCookie(o.context.authCookies.sessionData.name),t=i?vo(Buffer.from(i,"base64").toString()):null;if(t&&!await uo.verify({value:JSON.stringify(t.session),signature:t?.signature,secret:o.context.secret}))return B(o),o.json(null);let r=await o.getSignedCookie(o.context.authCookies.dontRememberToken.name,o.context.secret);if(t?.session&&o.context.options.session?.cookieCache?.enabled&&!o.query?.disableCookieCache){let c=t.session;if(t.expiresAt<Date.now()||c.session.expiresAt<new Date){let l=o.context.authCookies.sessionData.name;o.setCookie(l,"",{maxAge:0})}else return o.json(c)}let n=await o.context.internalAdapter.findSession(e);if(o.context.session=n,!n||n.session.expiresAt<new Date)return B(o),n&&await o.context.internalAdapter.deleteSession(n.session.token),o.json(null);if(r||o.query?.disableRefresh)return o.json(n);let a=o.context.sessionConfig.expiresIn,A=o.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-a*1e3+A*1e3<=Date.now()){let c=await o.context.internalAdapter.updateSession(n.session.token,{expiresAt:z(o.context.sessionConfig.expiresIn,"sec")});if(!c)return B(o),o.json(null,{status:401});let u=(c.expiresAt.valueOf()-Date.now())/1e3;return await O(o,{session:c,user:n.user},!1,{maxAge:u}),o.json({session:c,user:n.user})}return o.json(n)}catch(e){throw o.context.logger.error("INTERNAL_SERVER_ERROR",e),new F.APIError("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_GET_SESSION})}}),Z=async(o,e)=>{if(o.context.session)return o.context.session;let i=await Io()({...o,_flag:"json",headers:o.headers,query:e}).catch(t=>null);return o.context.session=i,i},_=ro(async o=>{let e=await Z(o);if(!e?.session)throw new F.APIError("UNAUTHORIZED");return{session:e}}),De=ro(async o=>{let e=await Z(o);if(!e?.session)throw new F.APIError("UNAUTHORIZED");if(o.context.sessionConfig.freshAge===0)return{session:e};let i=o.context.sessionConfig.freshAge,t=e.session.updatedAt?.valueOf()||e.session.createdAt.valueOf();if(!(Date.now()-t<i*1e3))throw new F.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:e}}),Ie=()=>f("/list-sessions",{method:"GET",use:[_],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async o=>{let i=(await o.context.internalAdapter.listSessions(o.context.session.user.id)).filter(t=>t.expiresAt>new Date);return o.json(i)}),Se=f("/revoke-session",{method:"POST",body:H.z.object({token:H.z.string({description:"The token to revoke"})}),use:[_],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async o=>{let e=o.body.token,i=await o.context.internalAdapter.findSession(e);if(!i)throw new F.APIError("BAD_REQUEST",{message:"Session not found"});if(i.session.userId!==o.context.session.user.id)throw new F.APIError("UNAUTHORIZED");try{await o.context.internalAdapter.deleteSession(e)}catch(t){throw o.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new F.APIError("INTERNAL_SERVER_ERROR")}return o.json({status:!0})}),_e=f("/revoke-sessions",{method:"POST",use:[_],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async o=>{try{await o.context.internalAdapter.deleteSessions(o.context.session.user.id)}catch(e){throw o.context.logger.error(e&&typeof e=="object"&&"name"in e?e.name:"",e),new F.APIError("INTERNAL_SERVER_ERROR")}return o.json({status:!0})}),Le=f("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[_],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async o=>{let e=o.context.session;if(!e.user)throw new F.APIError("UNAUTHORIZED");let r=(await o.context.internalAdapter.listSessions(e.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.token!==o.context.session.session.token);return await Promise.all(r.map(n=>o.context.internalAdapter.deleteSession(n.token))),o.json({status:!0})});async function j(o,e,i){return await(0,mo.createJWT)("HS256",Buffer.from(o),{email:e.toLowerCase(),updateTo:i},{expiresIn:new Ne.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[e],includeIssuedTimestamp:!0})}async function Vi(o,e){if(!o.context.options.emailVerification?.sendVerificationEmail)throw o.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let i=await j(o.context.secret,e.email),t=`${o.context.baseURL}/verify-email?token=${i}&callbackURL=${o.body.callbackURL||o.query?.currentURL||"/"}`;await o.context.options.emailVerification.sendVerificationEmail({user:e,url:t,token:i},o.request)}var Be=f("/send-verification-email",{method:"POST",query:L.z.object({currentURL:L.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:L.z.object({email:L.z.string({description:"The email to send the verification email to"}).email(),callbackURL:L.z.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async o=>{if(!o.context.options.emailVerification?.sendVerificationEmail)throw o.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:e}=o.body,i=await o.context.internalAdapter.findUserByEmail(e);if(!i)throw new J.APIError("BAD_REQUEST",{message:g.USER_NOT_FOUND});return await Vi(o,i.user),o.json({status:!0})}),Fe=f("/verify-email",{method:"GET",query:L.z.object({token:L.z.string({description:"The token to verify the email"}),callbackURL:L.z.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async o=>{function e(A){throw o.query.callbackURL?o.query.callbackURL.includes("?")?o.redirect(`${o.query.callbackURL}&error=${A}`):o.redirect(`${o.query.callbackURL}?error=${A}`):new J.APIError("UNAUTHORIZED",{message:A})}let{token:i}=o.query,t;try{t=await(0,mo.validateJWT)("HS256",Buffer.from(o.context.secret),i)}catch(A){return o.context.logger.error("Failed to verify email",A),e("invalid_token")}let n=L.z.object({email:L.z.string().email(),updateTo:L.z.string().optional()}).parse(t.payload),a=await o.context.internalAdapter.findUserByEmail(n.email);if(!a)return e("user_not_found");if(n.updateTo){let A=await Z(o);if(!A){if(o.query.callbackURL)throw o.redirect(`${o.query.callbackURL}?error=unauthorized`);return e("unauthorized")}if(A.user.email!==n.email){if(o.query.callbackURL)throw o.redirect(`${o.query.callbackURL}?error=unauthorized`);return e("unauthorized")}let s=await o.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo,emailVerified:!1}),K=await j(o.context.secret,n.updateTo);if(await o.context.options.emailVerification?.sendVerificationEmail?.({user:s,url:`${o.context.baseURL}/verify-email?token=${K}`,token:K},o.request),o.query.callbackURL)throw o.redirect(o.query.callbackURL);return o.json({user:s,status:!0})}if(await o.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),o.context.options.emailVerification?.autoSignInAfterVerification&&!await Z(o)){let s=await o.context.internalAdapter.createSession(a.user.id,o.request);if(!s)throw new J.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await O(o,{session:s,user:a.user})}if(o.query.callbackURL)throw o.redirect(o.query.callbackURL);return o.json({user:null,status:!0})});async function Co(o,{userInfo:e,account:i,callbackURL:t}){let r=await o.context.internalAdapter.findUserByEmail(e.email.toLowerCase(),{includeAccounts:!0}).catch(s=>{throw S.error(`Better auth was unable to query your database.
|
|
3
3
|
Error: `,s),o.redirect(`${o.context.baseURL}/error?error=internal_server_error`)}),n=r?.user,a=!n;if(r){let s=r.accounts.find(K=>K.providerId===i.providerId);if(s){let K=Object.fromEntries(Object.entries({accessToken:i.accessToken,idToken:i.idToken,refreshToken:i.refreshToken,accessTokenExpiresAt:i.accessTokenExpiresAt,refreshTokenExpiresAt:i.refreshTokenExpiresAt}).filter(([c,u])=>u!==void 0));Object.keys(K).length>0&&await o.context.internalAdapter.updateAccount(s.id,K)}else{if(!o.context.options.account?.accountLinking?.trustedProviders?.includes(i.providerId)&&!e.emailVerified||o.context.options.account?.accountLinking?.enabled===!1)return Ko&&S.warn(`User already exist but account isn't linked to ${i.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await o.context.internalAdapter.linkAccount({providerId:i.providerId,accountId:e.id.toString(),userId:r.user.id,accessToken:i.accessToken,idToken:i.idToken,refreshToken:i.refreshToken,accessTokenExpiresAt:i.accessTokenExpiresAt,refreshTokenExpiresAt:i.refreshTokenExpiresAt,scope:i.scope})}catch(u){return S.error("Unable to link account",u),{error:"unable to link account",data:null}}n=await o.context.internalAdapter.updateUser(r.user.id,{...e,updatedAt:new Date})}}else if(n=await o.context.internalAdapter.createOAuthUser({...e,email:e.email.toLowerCase(),id:void 0},{accessToken:i.accessToken,idToken:i.idToken,refreshToken:i.refreshToken,accessTokenExpiresAt:i.accessTokenExpiresAt,refreshTokenExpiresAt:i.refreshTokenExpiresAt,scope:i.scope,providerId:i.providerId,accountId:e.id.toString()}).then(s=>s?.user),!e.emailVerified&&n&&o.context.options.emailVerification?.sendOnSignUp){let s=await j(o.context.secret,n.email),K=`${o.context.baseURL}/verify-email?token=${s}&callbackURL=${t}`;await o.context.options.emailVerification?.sendVerificationEmail?.({user:n,url:K,token:s},o.request)}if(!n)return{error:"unable to create user",data:null,isRegister:!1};let A=await o.context.internalAdapter.createSession(n.id,o.request);return A?{data:{session:A,user:n},error:null,isRegister:a}:{error:"unable to create session",data:null,isRegister:!1}}var je=f("/sign-in/social",{method:"POST",query:v.z.object({currentURL:v.z.string().optional()}).optional(),body:v.z.object({callbackURL:v.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:v.z.string().optional(),errorCallbackURL:v.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:v.z.enum(fo,{description:"OAuth2 provider to use"}),disableRedirect:v.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:v.z.optional(v.z.object({token:v.z.string({description:"ID token from the provider"}),nonce:v.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:v.z.string({description:"Access token from the provider"}).optional(),refreshToken:v.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:v.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async o=>{let e=o.context.socialProviders.find(n=>n.id===o.body.provider);if(!e)throw o.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:o.body.provider}),new E.APIError("NOT_FOUND",{message:g.PROVIDER_NOT_FOUND});if(o.body.idToken){if(!e.verifyIdToken)throw o.context.logger.error("Provider does not support id token verification",{provider:o.body.provider}),new E.APIError("NOT_FOUND",{message:g.ID_TOKEN_NOT_SUPPORTED});let{token:n,nonce:a}=o.body.idToken;if(!await e.verifyIdToken(n,a))throw o.context.logger.error("Invalid id token",{provider:o.body.provider}),new E.APIError("UNAUTHORIZED",{message:g.INVALID_TOKEN});let s=await e.getUserInfo({idToken:n,accessToken:o.body.idToken.accessToken,refreshToken:o.body.idToken.refreshToken});if(!s||!s?.user)throw o.context.logger.error("Failed to get user info",{provider:o.body.provider}),new E.APIError("UNAUTHORIZED",{message:g.FAILED_TO_GET_USER_INFO});if(!s.user.email)throw o.context.logger.error("User email not found",{provider:o.body.provider}),new E.APIError("UNAUTHORIZED",{message:g.USER_EMAIL_NOT_FOUND});let K=await Co(o,{userInfo:{email:s.user.email,id:s.user.id,name:s.user.name||"",image:s.user.image,emailVerified:s.user.emailVerified||!1},account:{providerId:e.id,accountId:s.user.id,accessToken:o.body.idToken.accessToken}});if(K.error)throw new E.APIError("UNAUTHORIZED",{message:K.error});return await O(o,K.data),o.json({session:K.data.session,user:K.data.user,url:void 0,redirect:!1})}let{codeVerifier:i,state:t}=await go(o),r=await e.createAuthorizationURL({state:t,codeVerifier:i,redirectURI:`${o.context.baseURL}/callback/${e.id}`});return o.json({url:r.toString(),redirect:!o.body.disableRedirect})}),Ve=f("/sign-in/email",{method:"POST",body:v.z.object({email:v.z.string({description:"Email of the user"}),password:v.z.string({description:"Password of the user"}),callbackURL:v.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:v.z.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async o=>{if(!o.context.options?.emailAndPassword?.enabled)throw o.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 E.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:e,password:i}=o.body;if(!v.z.string().email().safeParse(e).success)throw new E.APIError("BAD_REQUEST",{message:g.INVALID_EMAIL});let r=await o.context.internalAdapter.findUserByEmail(e,{includeAccounts:!0});if(!r)throw await o.context.password.hash(i),o.context.logger.error("User not found",{email:e}),new E.APIError("UNAUTHORIZED",{message:g.INVALID_EMAIL_OR_PASSWORD});let n=r.accounts.find(K=>K.providerId==="credential");if(!n)throw o.context.logger.error("Credential account not found",{email:e}),new E.APIError("UNAUTHORIZED",{message:g.INVALID_EMAIL_OR_PASSWORD});let a=n?.password;if(!a)throw o.context.logger.error("Password not found",{email:e}),new E.APIError("UNAUTHORIZED",{message:g.INVALID_EMAIL_OR_PASSWORD});if(!await o.context.password.verify({hash:a,password:i}))throw o.context.logger.error("Invalid password"),new E.APIError("UNAUTHORIZED",{message:g.INVALID_EMAIL_OR_PASSWORD});if(o.context.options?.emailAndPassword?.requireEmailVerification&&!r.user.emailVerified){if(!o.context.options?.emailVerification?.sendVerificationEmail)throw new E.APIError("UNAUTHORIZED",{message:g.EMAIL_NOT_VERIFIED});let K=await j(o.context.secret,r.user.email),c=`${o.context.baseURL}/verify-email?token=${K}&callbackURL=${o.body.callbackURL||"/"}`;throw await o.context.options.emailVerification.sendVerificationEmail({user:r.user,url:c,token:K},o.request),o.context.logger.error("Email not verified",{email:e}),new E.APIError("FORBIDDEN",{message:g.EMAIL_NOT_VERIFIED})}let s=await o.context.internalAdapter.createSession(r.user.id,o.headers,o.body.rememberMe===!1);if(!s)throw o.context.logger.error("Failed to create session"),new E.APIError("UNAUTHORIZED",{message:g.FAILED_TO_CREATE_SESSION});return await O(o,{session:s,user:r.user},o.body.rememberMe===!1),o.json({user:{id:r.user.id,email:r.user.email,name:r.user.name,image:r.user.image,emailVerified:r.user.emailVerified,createdAt:r.user.createdAt,updatedAt:r.user.updatedAt},redirect:!!o.body.callbackURL,url:o.body.callbackURL})});var Y=require("zod");var ho=Y.z.object({code:Y.z.string().optional(),error:Y.z.string().optional(),error_description:Y.z.string().optional(),state:Y.z.string().optional()}),Me=f("/callback/:id",{method:["GET","POST"],body:ho.optional(),query:ho.optional(),metadata:$},async o=>{let e;try{if(o.method==="GET")e=ho.parse(o.query);else if(o.method==="POST")e=ho.parse(o.body);else throw new Error("Unsupported method")}catch(h){throw o.context.logger.error("INVALID_CALLBACK_REQUEST",h),o.redirect(`${o.context.baseURL}/error?error=invalid_callback_request`)}let{code:i,error:t,state:r,error_description:n}=e;if(!r)throw o.context.logger.error("State not found",t),o.redirect(`${o.context.baseURL}/error?error=state_not_found`);if(!i)throw o.context.logger.error("Code not found"),o.redirect(`${o.context.baseURL}/error?error=${t||"no_code"}&error_description=${n}`);let a=o.context.socialProviders.find(h=>h.id===o.params.id);if(!a)throw o.context.logger.error("Oauth provider with id",o.params.id,"not found"),o.redirect(`${o.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:A,callbackURL:s,link:K,errorURL:c,newUserURL:u}=await Qo(o),l;try{l=await a.validateAuthorizationCode({code:i,codeVerifier:A,redirectURI:`${o.context.baseURL}/callback/${a.id}`})}catch(h){throw o.context.logger.error("",h),o.redirect(`${o.context.baseURL}/error?error=please_restart_the_process`)}let d=await a.getUserInfo(l).then(h=>h?.user);function y(h){let C=c||s||`${o.context.baseURL}/error`;throw C.includes("?")?C=`${C}&error=${h}`:C=`${C}?error=${h}`,o.redirect(C)}if(!d)return o.context.logger.error("Unable to get user info"),y("unable_to_get_user_info");if(!d.email)return o.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),y("email_not_found");if(!s)throw o.context.logger.error("No callback URL found"),o.redirect(`${o.context.baseURL}/error?error=please_restart_the_process`);if(K){if(K.email!==d.email.toLowerCase())return y("email_doesn't_match");if(!await o.context.internalAdapter.createAccount({userId:K.userId,providerId:a.id,accountId:d.id}))return y("unable_to_link_account");let C;try{C=s.toString()}catch{C=s}throw o.redirect(C)}let k=await Co(o,{userInfo:{...d,email:d.email,name:d.name||d.email},account:{providerId:a.id,accountId:d.id,...l,scope:l.scopes?.join(",")},callbackURL:s});if(k.error)return o.context.logger.error(k.error.split(" ").join("_")),y(k.error.split(" ").join("_"));let{session:x,user:m}=k.data;await O(o,{session:x,user:m});let w;try{w=(k.isRegister&&u||s).toString()}catch{w=k.isRegister&&u||s}throw o.redirect(w)});var Ms=require("zod");var ze=require("better-call");var qe=f("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{let e=await o.getSignedCookie(o.context.authCookies.sessionToken.name,o.context.secret);if(!e)throw B(o),new ze.APIError("BAD_REQUEST",{message:g.FAILED_TO_GET_SESSION});return await o.context.internalAdapter.deleteSession(e),B(o),o.json({success:!0})});var D=require("zod");var oo=require("better-call");function He(o,e,i){let t=e?new URL(e,o.baseURL):new URL(`${o.baseURL}/error`);return i&&Object.entries(i).forEach(([r,n])=>t.searchParams.set(r,n)),t.href}function Mi(o,e,i){let t=new URL(e,o.baseURL);return i&&Object.entries(i).forEach(([r,n])=>t.searchParams.set(r,n)),t.href}var Qe=f("/forget-password",{method:"POST",body:D.z.object({email:D.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:D.z.string({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async o=>{if(!o.context.options.emailAndPassword?.sendResetPassword)throw o.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new oo.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:e,redirectTo:i}=o.body,t=await o.context.internalAdapter.findUserByEmail(e,{includeAccounts:!0});if(!t)return o.context.logger.error("Reset Password: User not found",{email:e}),o.json({status:!1},{body:{status:!0}});let r=60*60*1,n=z(o.context.options.emailAndPassword.resetPasswordTokenExpiresIn||r,"sec"),a=to(24);await o.context.internalAdapter.createVerificationValue({value:t.user.id.toString(),identifier:`reset-password:${a}`,expiresAt:n});let A=`${o.context.baseURL}/reset-password/${a}?callbackURL=${i}`;return await o.context.options.emailAndPassword.sendResetPassword({user:t.user,url:A,token:a},o.request),o.json({status:!0})}),Ze=f("/reset-password/:token",{method:"GET",query:D.z.object({callbackURL:D.z.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async o=>{let{token:e}=o.params,{callbackURL:i}=o.query;if(!e||!i)throw o.redirect(He(o.context,i,{error:"INVALID_TOKEN"}));let t=await o.context.internalAdapter.findVerificationValue(`reset-password:${e}`);throw!t||t.expiresAt<new Date?o.redirect(He(o.context,i,{error:"INVALID_TOKEN"})):o.redirect(Mi(o.context,i,{token:e}))}),Ge=f("/reset-password",{query:D.z.optional(D.z.object({token:D.z.string().optional(),currentURL:D.z.string().optional()})),method:"POST",body:D.z.object({newPassword:D.z.string({description:"The new password to set"}),token:D.z.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async o=>{let e=o.body.token||o.query?.token||(o.query?.currentURL?new URL(o.query.currentURL).searchParams.get("token"):"");if(!e)throw new oo.APIError("BAD_REQUEST",{message:g.INVALID_TOKEN});let{newPassword:i}=o.body,t=o.context.password?.config.minPasswordLength,r=o.context.password?.config.maxPasswordLength;if(i.length<t)throw new oo.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_SHORT});if(i.length>r)throw new oo.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_LONG});let n=`reset-password:${e}`,a=await o.context.internalAdapter.findVerificationValue(n);if(!a||a.expiresAt<new Date)throw new oo.APIError("BAD_REQUEST",{message:g.INVALID_TOKEN});await o.context.internalAdapter.deleteVerificationValue(a.id);let A=a.value,s=await o.context.password.hash(i);return(await o.context.internalAdapter.findAccounts(A)).find(u=>u.providerId==="credential")?(await o.context.internalAdapter.updatePassword(A,s),o.json({status:!0})):(await o.context.internalAdapter.createAccount({userId:A,providerId:"credential",password:s,accountId:A}),o.json({status:!0}))});var U=require("zod");var T=require("better-call");var Gi=require("@noble/ciphers/chacha"),_o=require("@noble/ciphers/utils"),$i=require("@noble/ciphers/webcrypto"),Wi=require("oslo/crypto"),Xi=bo(require("uncrypto"),1);var $e=require("oslo/encoding");var zi=require("@noble/hashes/scrypt"),qi=require("uncrypto");var So=bo(require("uncrypto"),1);function Hi(o){return o.toString(2).padStart(8,"0")}function Qi(o){return[...o].map(e=>Hi(e)).join("")}function We(o){return parseInt(Qi(o),2)}function Zi(o){if(o<0||!Number.isInteger(o))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let e=(o-1).toString(2).length,i=e%8,t=new Uint8Array(Math.ceil(e/8));So.default.getRandomValues(t),i!==0&&(t[0]&=(1<<i)-1);let r=We(t);for(;r>=o;)So.default.getRandomValues(t),i!==0&&(t[0]&=(1<<i)-1),r=We(t);return r}function Xe(o,e){let i="";for(let t=0;t<o;t++)i+=e[Zi(e.length)];return i}function Je(...o){let e=new Set(o),i="";for(let t of e)t==="a-z"?i+="abcdefghijklmnopqrstuvwxyz":t==="A-Z"?i+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":t==="0-9"?i+="0123456789":i+=t;return i}var Ye=()=>f("/update-user",{method:"POST",body:U.z.record(U.z.string(),U.z.any()),use:[_],metadata:{openapi:{description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"}}}}}}}}}},async o=>{let e=o.body;if(e.email)throw new T.APIError("BAD_REQUEST",{message:g.EMAIL_CAN_NOT_BE_UPDATED});let{name:i,image:t,...r}=e,n=o.context.session;if(t===void 0&&i===void 0&&Object.keys(r).length===0)return o.json({id:n.user.id,email:n.user.email,name:n.user.name,image:n.user.image,emailVerified:n.user.emailVerified,createdAt:n.user.createdAt,updatedAt:n.user.updatedAt});let a=ao(o.context.options,r,"update"),A=await o.context.internalAdapter.updateUserByEmail(n.user.email,{name:i,image:t,...a});return await O(o,{session:n.session,user:A}),o.json({id:A.id,email:A.email,name:A.name,image:A.image,emailVerified:A.emailVerified,createdAt:A.createdAt,updatedAt:A.updatedAt})}),oi=f("/change-password",{method:"POST",body:U.z.object({newPassword:U.z.string({description:"The new password to set"}),currentPassword:U.z.string({description:"The current password"}),revokeOtherSessions:U.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[_],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async o=>{let{newPassword:e,currentPassword:i,revokeOtherSessions:t}=o.body,r=o.context.session,n=o.context.password.config.minPasswordLength;if(e.length<n)throw o.context.logger.error("Password is too short"),new T.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_SHORT});let a=o.context.password.config.maxPasswordLength;if(e.length>a)throw o.context.logger.error("Password is too long"),new T.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_LONG});let s=(await o.context.internalAdapter.findAccounts(r.user.id)).find(u=>u.providerId==="credential"&&u.password);if(!s||!s.password)throw new T.APIError("BAD_REQUEST",{message:g.CREDENTIAL_ACCOUNT_NOT_FOUND});let K=await o.context.password.hash(e);if(!await o.context.password.verify({hash:s.password,password:i}))throw new T.APIError("BAD_REQUEST",{message:g.INVALID_PASSWORD});if(await o.context.internalAdapter.updateAccount(s.id,{password:K}),t){await o.context.internalAdapter.deleteSessions(r.user.id);let u=await o.context.internalAdapter.createSession(r.user.id,o.headers);if(!u)throw new T.APIError("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_GET_SESSION});await O(o,{session:u,user:r.user})}return o.json(r.user)}),ei=f("/set-password",{method:"POST",body:U.z.object({newPassword:U.z.string()}),metadata:{SERVER_ONLY:!0},use:[_]},async o=>{let{newPassword:e}=o.body,i=o.context.session,t=o.context.password.config.minPasswordLength;if(e.length<t)throw o.context.logger.error("Password is too short"),new T.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_SHORT});let r=o.context.password.config.maxPasswordLength;if(e.length>r)throw o.context.logger.error("Password is too long"),new T.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_LONG});let a=(await o.context.internalAdapter.findAccounts(i.user.id)).find(s=>s.providerId==="credential"&&s.password),A=await o.context.password.hash(e);if(!a)return await o.context.internalAdapter.linkAccount({userId:i.user.id,providerId:"credential",accountId:i.user.id,password:A}),o.json(i.user);throw new T.APIError("BAD_REQUEST",{message:"user already has a password"})}),ii=f("/delete-user",{method:"POST",use:[De],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async o=>{if(!o.context.options.user?.deleteUser?.enabled)throw o.context.logger.error("Delete user is disabled. Enable it in the options",{session:o.context.session}),new T.APIError("NOT_FOUND");let e=o.context.session;if(o.context.options.user.deleteUser?.sendDeleteAccountVerification){let r=Xe(32,Je("a-z","A-Z","0-9"));await o.context.internalAdapter.createVerificationValue({value:e.user.id,identifier:`delete-account-${r}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let n=`${o.context.baseURL}/delete-user/callback?token=${r}`;return await o.context.options.user.deleteUser.sendDeleteAccountVerification({user:e.user,url:n,token:r},o.request),o.json({success:!0,message:"Verification email sent"})}let i=o.context.options.user.deleteUser?.beforeDelete;i&&await i(e.user,o.request),await o.context.internalAdapter.deleteUser(e.user.id),await o.context.internalAdapter.deleteSessions(e.user.id),await o.context.internalAdapter.deleteAccounts(e.user.id),B(o);let t=o.context.options.user.deleteUser?.afterDelete;return t&&await t(e.user,o.request),o.json({success:!0,message:"User deleted"})}),ti=f("/delete-user/callback",{method:"GET",query:U.z.object({token:U.z.string()})},async o=>{if(!o.context.options.user?.deleteUser?.enabled)throw o.context.logger.error("Delete user is disabled. Enable it in the options"),new T.APIError("NOT_FOUND");let e=await Z(o);if(!e)throw new T.APIError("NOT_FOUND",{message:g.FAILED_TO_GET_USER_INFO});let i=await o.context.internalAdapter.findVerificationValue(`delete-account-${o.query.token}`);if(!i||i.expiresAt<new Date)throw i&&await o.context.internalAdapter.deleteVerificationValue(i.id),new T.APIError("NOT_FOUND",{message:g.INVALID_TOKEN});if(i.value!==e.user.id)throw new T.APIError("NOT_FOUND",{message:g.INVALID_TOKEN});let t=o.context.options.user.deleteUser?.beforeDelete;t&&await t(e.user,o.request),await o.context.internalAdapter.deleteUser(e.user.id),await o.context.internalAdapter.deleteSessions(e.user.id),await o.context.internalAdapter.deleteAccounts(e.user.id),await o.context.internalAdapter.deleteVerificationValue(i.id),B(o);let r=o.context.options.user.deleteUser?.afterDelete;return r&&await r(e.user,o.request),o.json({success:!0,message:"User deleted"})}),ri=f("/change-email",{method:"POST",query:U.z.object({currentURL:U.z.string().optional()}).optional(),body:U.z.object({newEmail:U.z.string({description:"The new email to set"}).email(),callbackURL:U.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[_],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},async o=>{if(!o.context.options.user?.changeEmail?.enabled)throw o.context.logger.error("Change email is disabled."),new T.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(o.body.newEmail===o.context.session.user.email)throw o.context.logger.error("Email is the same"),new T.APIError("BAD_REQUEST",{message:"Email is the same"});if(await o.context.internalAdapter.findUserByEmail(o.body.newEmail))throw o.context.logger.error("Email already exists"),new T.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(o.context.session.user.emailVerified!==!0){let r=await o.context.internalAdapter.updateUserByEmail(o.context.session.user.email,{email:o.body.newEmail});return o.json({user:r,status:!0})}if(!o.context.options.user.changeEmail.sendChangeEmailVerification)throw o.context.logger.error("Verification email isn't enabled."),new T.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let i=await j(o.context.secret,o.context.session.user.email,o.body.newEmail),t=`${o.context.baseURL}/verify-email?token=${i}&callbackURL=${o.body.callbackURL||o.query?.currentURL||"/"}`;return await o.context.options.user.changeEmail.sendChangeEmailVerification({user:o.context.session.user,newEmail:o.body.newEmail,url:t,token:i},o.request),o.json({user:null,status:!0})});var Ji=(o="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|