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/passkey.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use strict";var Bt=Object.create;var se=Object.defineProperty;var jt=Object.getOwnPropertyDescriptor;var Vt=Object.getOwnPropertyNames;var $t=Object.getPrototypeOf,Ft=Object.prototype.hasOwnProperty;var qt=(e,t)=>{for(var r in t)se(e,r,{get:t[r],enumerable:!0})},De=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Vt(t))!Ft.call(e,n)&&n!==r&&se(e,n,{get:()=>t[n],enumerable:!(o=jt(t,n))||o.enumerable});return e};var Ae=(e,t,r)=>(r=e!=null?Bt($t(e)):{},De(t||!e||!e.__esModule?se(r,"default",{value:e,enumerable:!0}):r,e)),zt=e=>De(se({},"__esModule",{value:!0}),e);var Qr={};qt(Qr,{getPasskeyActions:()=>xt,passkey:()=>Wr,passkeyClient:()=>Gr});module.exports=zt(Qr);var M=require("@simplewebauthn/server"),T=require("better-call");var Re=Ae(require("uncrypto"),1);function Mt(e){return e.toString(2).padStart(8,"0")}function Ht(e){return[...e].map(t=>Mt(t)).join("")}function Ne(e){return parseInt(Ht(e),2)}function Gt(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));Re.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=Ne(o);for(;n>=e;)Re.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=Ne(o);return n}function ie(e,t){let r="";for(let o=0;o<e;o++)r+=t[Gt(t.length)];return r}function ae(...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 I=require("zod");var H=require("better-call"),Be=(0,H.createMiddleware)(async()=>({})),te=(0,H.createMiddlewareCreator)({use:[Be,(0,H.createMiddleware)(async()=>({}))]}),u=(0,H.createEndpointCreator)({use:[Be]});var X=require("better-call");var Fe=require("better-call");function Ee(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function Wt(e){let t="";for(let r=0;r<e.length;r++)t+=Ee(e[r]);return t}function je(e,t=!0){if(Array.isArray(e))return`(?:${e.map(p=>`^${je(p,t)}$`).join("|")})`;let r="",o="",n=".";t===!0?(r="/",o="[/\\\\]",n="[^/\\\\]"):t&&(r=t,o=Wt(r),o.length>1?(o=`(?:${o})`,n=`((?!${o}).)`):n=`[^${o}]`);let i=t?`${o}+?`:"",a=t?`${o}*?`:"",c=t?e.split(r):[e],s="";for(let d=0;d<c.length;d++){let p=c[d],m=c[d+1],y="";if(!(!p&&d>0)){if(t&&(d===c.length-1?y=a:m!=="**"?y=i:y=""),t&&p==="**"){y&&(s+=d===0?"":y,s+=`(?:${n}*?${y})*?`);continue}for(let h=0;h<p.length;h++){let f=p[h];f==="\\"?h<p.length-1&&(s+=Ee(p[h+1]),h++):f==="?"?s+=n:f==="*"?s+=`${n}*?`:s+=Ee(f)}s+=y}}return s}function Kt(e,t){if(typeof t!="string")throw new TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function ke(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=je(e,t.separator),o=new RegExp(`^${r}$`,t.flags),n=Kt.bind(null,o);return n.options=t,n.pattern=e,n.regexp=o,n}var ce=Object.create(null),re=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?ce:globalThis),de=new Proxy(ce,{get(e,t){return re()[t]??ce[t]},has(e,t){let r=re();return t in r||t in ce},set(e,t,r){let o=re(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=re(!0);return delete r[t],!0},ownKeys(){let e=re(!0);return Object.keys(e)}});function Qt(e){return e?e!=="false":!1}var Te=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var _e=Te==="dev"||Te==="development",Zt=Te==="test"||Qt(de.TEST);var D=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function Ve(e){try{return new URL(e).origin}catch{return null}}function $e(e){return e.includes("://")?new URL(e).host:e}var Jt=te(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=t?.callbackURL||r?.callbackURL,a=t?.redirectTo,c=r?.currentURL,s=t?.errorCallbackURL,d=t?.newUserCallbackURL,p=o.trustedOrigins,m=e.headers?.has("cookie"),y=(f,b)=>f.startsWith("/")?!1:b.includes("*")?ke(b)($e(f)):f.startsWith(b),h=(f,b)=>{if(!f)return;if(!p.some(C=>y(f,C)||f?.startsWith("/")&&b!=="origin"&&!f.includes(":")))throw e.context.logger.error(`Invalid ${b}: ${f}`),e.context.logger.info(`If it's a valid URL, please add ${f} to trustedOrigins in your auth config
|
|
2
|
-
`,`Current list of trustedOrigins: ${p}`),new Fe.APIError("FORBIDDEN",{message:`Invalid ${b}`})};m&&!e.context.options.advanced?.disableCSRFCheck&&h(n,"origin"),i&&h(i,"callbackURL"),a&&h(a,"redirectURL"),c&&h(c,"currentURL"),s&&h(s,"errorCallbackURL"),d&&h(a,"newUserCallbackURL")});var k=require("better-call"),R=require("zod");var tr=require("oslo"),qe=require("oslo/encoding");var pe=require("oslo/crypto");async function Xt({value:e,secret:t}){return new pe.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function er({value:e,signature:t,secret:r}){return new pe.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var ue={sign:Xt,verify:er};var q=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function O(e,t,r,o){let n=e.context.authCookies.sessionToken.options,i=r?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...n,maxAge:i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled){let c=qe.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:q(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await ue.sign({value:JSON.stringify(t),secret:e.context.secret})})),{includePadding:!1});if(c.length>4093)throw new D("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 N(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})}var Ke=require("@better-fetch/fetch"),Qe=require("better-call"),W=require("jose"),Ze=require("oslo/jwt");var ze=require("oslo/crypto"),Me=require("oslo/encoding");async function He(e){let t=await(0,ze.sha256)(new TextEncoder().encode(e));return Me.base64url.encode(new Uint8Array(t),{includePadding:!1})}function le(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?q(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:a,redirectURI:c,duration:s}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",i.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),n){let p=await He(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",p)}if(a){let p=a.reduce((m,y)=>(m[y]=null,m),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...p}}))}return s&&d.searchParams.set("duration",s),d}var Ge=require("@better-fetch/fetch");async function w({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n,authentication:i}){let a=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(a.set("grant_type","authorization_code"),a.set("code",e),t&&a.set("code_verifier",t),a.set("redirect_uri",r),i==="basic"){let m=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${m}`}else a.set("client_id",o.clientId),a.set("client_secret",o.clientSecret);let{data:s,error:d}=await(0,Ge.betterFetch)(n,{method:"POST",body:a,headers:c});if(d)throw d;return le(s)}var me=require("oslo/oauth2"),B=require("zod"),Oe=require("better-call");async function fe(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Ve(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new Oe.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,me.generateCodeVerifier)(),n=(0,me.generateState)(),i=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}),a=new Date;a.setMinutes(a.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:a});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 Oe.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function We(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=B.z.object({callbackURL:B.z.string(),codeVerifier:B.z.string(),errorURL:B.z.string().optional(),newUserURL:B.z.string().optional(),expiresAt:B.z.number(),link:B.z.object({email:B.z.string(),userId:B.z.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 Je=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let n=(0,W.decodeProtectedHeader)(r),{kid:i,alg:a}=n;if(!i||!a)return!1;let c=await rr(i),{payload:s}=await(0,W.jwtVerify)(r,c,{algorithms:[a],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{s[d]!==void 0&&(s[d]=!!s[d])}),o&&s.nonce!==o?!1:!!s},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=(0,Ze.parseJWT)(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email,...i},data:o}}}},rr=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,Ke.betterFetch)(`${t}${r}`);if(!o?.keys)throw new Qe.APIError("BAD_REQUEST",{message:"Keys not found"});let n=o.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await(0,W.importJWK)(n,n.alg)};var Ye=require("@better-fetch/fetch");var Xe=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({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(0,Ye.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}let n=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,...n},data:r}}});var et=require("@better-fetch/fetch");var tt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({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(0,et.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...n},data:r}}});var Ue=require("@better-fetch/fetch");var rt=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let a=o||["user:email"];return e.scope&&a.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>w({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await(0,Ue.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:c,error:s}=await(0,Ue.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});s||(o.email=(c.find(d=>d.primary)??c[0])?.email,i=c.find(d=>d.email===o.email)?.verified??!1)}let a=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i,...a},data:o}}}};var nt=require("oslo/jwt");var ot=require("consola"),Se=["info","success","warn","error","debug"];function or(e,t){return Se.indexOf(t)<=Se.indexOf(e)}var nr=(0,ot.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),sr=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,a=[])=>{if(!(!t||!or(r,n))){if(!e||typeof e.log!="function"){nr[n]("",i,...a);return}e.log(n==="success"?"info":n,i,a)}};return Object.fromEntries(Se.map(n=>[n,(...[i,...a])=>o(n,i,a)]))},L=sr();var st=require("@better-fetch/fetch"),it=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw L.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new D("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new D("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let a=await A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});return e.accessType&&a.searchParams.set("access_type",e.accessType),e.prompt&&a.searchParams.set("prompt",e.prompt),a},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({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:n}=await(0,st.betterFetch)(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,nt.parseJWT)(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}}});var at=require("@better-fetch/fetch"),ct=require("oslo/jwt");var dt=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),A({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:a}){return w({code:n,codeVerifier:i,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=(0,ct.parseJWT)(n.idToken)?.payload,a=e.profilePhotoSize||48;await(0,at.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(s){if(!(e.disableProfilePhoto||!s.response.ok))try{let p=await s.response.clone().arrayBuffer(),m=Buffer.from(p).toString("base64");i.picture=`data:image/jpeg;base64, ${m}`}catch(d){L.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0,...c},data:i}}}};var pt=require("@better-fetch/fetch");var ut=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({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(0,pt.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...n},data:r}}});var K={isAction:!1};var lt=require("nanoid"),oe=e=>(0,lt.nanoid)(e);var mt=require("oslo/jwt");var ft=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({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 L.error("No idToken found in token"),null;let o=(0,mt.parseJWT)(r)?.payload,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...n},data:o}}});var gt=require("@better-fetch/fetch");var ht=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),A({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})=>w({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(0,gt.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=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,...n},data:r}}});var yt=require("@better-fetch/fetch");var wt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let a=o||["account_info.read"];return e.scope&&a.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await(0,yt.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=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,...i},data:o}}}};var bt=require("@better-fetch/fetch");var At=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:n,redirectURI:i})=>{let a=n||["profile","email","openid"];return e.scope&&a.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:a,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await w({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await(0,bt.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture,...a},data:n}}}};var Rt=require("@better-fetch/fetch");var Pe=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),ir=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:Pe(`${t}/oauth/authorize`),tokenEndpoint:Pe(`${t}/oauth/token`),userinfoEndpoint:Pe(`${t}/api/v4/user`)}},Et=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=ir(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:a,scopes:c,codeVerifier:s,redirectURI:d})=>{let p=c||["read_user"];return e.scope&&p.push(...e.scope),await A({id:n,options:e,authorizationEndpoint:t,scopes:p,state:a,redirectURI:d,codeVerifier:s})},validateAuthorizationCode:async({code:a,redirectURI:c,codeVerifier:s})=>w({code:a,redirectURI:e.redirectURI||c,options:e,codeVerifier:s,tokenEndpoint:r}),async getUserInfo(a){if(e.getUserInfo)return e.getUserInfo(a);let{data:c,error:s}=await(0,Rt.betterFetch)(o,{headers:{authorization:`Bearer ${a.accessToken}`}});if(s||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}}}};var Ie=require("@better-fetch/fetch");var kt=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identity"];return e.scope&&n.push(...e.scope),A({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:n,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}),n={"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:i,error:a}=await(0,Ie.betterFetch)("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:n,body:o.toString()});if(a)throw a;return le(i)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,Ie.betterFetch)("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let n=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],...n},data:r}}});var ar={apple:Je,discord:Xe,facebook:tt,github:rt,microsoft:dt,google:it,spotify:ut,twitch:ft,twitter:ht,dropbox:wt,linkedin:At,gitlab:Et,reddit:kt},ge=Object.keys(ar);var Ot=require("oslo"),he=require("oslo/jwt"),x=require("zod");var Q=require("better-call");var j=require("better-call");var z=require("zod");function Tt(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 _t=()=>u("/get-session",{method:"GET",query:z.z.optional(z.z.object({disableCookieCache:z.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(z.z.string().transform(e=>e==="true")).optional(),disableRefresh:z.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 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?Tt(Buffer.from(r,"base64").toString()):null;if(o&&!await ue.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return N(e),e.json(null);let n=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 y=e.context.authCookies.sessionData.name;e.setCookie(y,"",{maxAge:0})}else return e.json(p)}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return N(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n||e.query?.disableRefresh)return e.json(i);let a=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-a*1e3+c*1e3<=Date.now()){let p=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:q(e.context.sessionConfig.expiresIn,"sec")});if(!p)return N(e),e.json(null,{status:401});let m=(p.expiresAt.valueOf()-Date.now())/1e3;return await O(e,{session:p,user:i.user},!1,{maxAge:m}),e.json({session:p,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new j.APIError("INTERNAL_SERVER_ERROR",{message:l.FAILED_TO_GET_SESSION})}}),V=async(e,t)=>{if(e.context.session)return e.context.session;let r=await _t()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},U=te(async e=>{let t=await V(e);if(!t?.session)throw new j.APIError("UNAUTHORIZED");return{session:t}}),ne=te(async e=>{let t=await V(e);if(!t?.session)throw new j.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),n=Date.now();if(!(o+r*1e3>n))throw new j.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}});var cr=u("/revoke-session",{method:"POST",body:z.z.object({token:z.z.string({description:"The token to revoke"})}),use:[U],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 j.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new j.APIError("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 j.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),dr=u("/revoke-sessions",{method:"POST",use:[U],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 j.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),pr=u("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[U],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 j.APIError("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});async function $(e,t,r){return await(0,he.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Ot.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function ur(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Q.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await $(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 lr=u("/send-verification-email",{method:"POST",query:x.z.object({currentURL:x.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:x.z.object({email:x.z.string({description:"The email to send the verification email to"}).email(),callbackURL:x.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 e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Q.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new Q.APIError("BAD_REQUEST",{message:l.USER_NOT_FOUND});return await ur(e,r.user),e.json({status:!0})}),mr=u("/verify-email",{method:"GET",query:x.z.object({token:x.z.string({description:"The token to verify the email"}),callbackURL:x.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 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 Q.APIError("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await(0,he.validateJWT)("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let i=x.z.object({email:x.z.string().email(),updateTo:x.z.string().optional()}).parse(o.payload),a=await e.context.internalAdapter.findUserByEmail(i.email);if(!a)return t("user_not_found");if(i.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!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let s=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),d=await $(e.context.secret,i.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:s,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:s,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await V(e)){let s=await e.context.internalAdapter.createSession(a.user.id,e.request);if(!s)throw new Q.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await O(e,{session:s,user:a.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function ye(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(s=>{throw L.error(`Better auth was unable to query your database.
|
|
2
|
+
`,`Current list of trustedOrigins: ${p}`),new Fe.APIError("FORBIDDEN",{message:`Invalid ${b}`})};m&&!e.context.options.advanced?.disableCSRFCheck&&h(n,"origin"),i&&h(i,"callbackURL"),a&&h(a,"redirectURL"),c&&h(c,"currentURL"),s&&h(s,"errorCallbackURL"),d&&h(a,"newUserCallbackURL")});var k=require("better-call"),R=require("zod");var tr=require("oslo"),qe=require("oslo/encoding");var pe=require("oslo/crypto");async function Xt({value:e,secret:t}){return new pe.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function er({value:e,signature:t,secret:r}){return new pe.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var ue={sign:Xt,verify:er};var q=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function O(e,t,r,o){let n=e.context.authCookies.sessionToken.options,i=r?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...n,maxAge:i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled){let c=qe.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:q(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await ue.sign({value:JSON.stringify(t),secret:e.context.secret})})),{includePadding:!1});if(c.length>4093)throw new D("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 N(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})}var Ke=require("@better-fetch/fetch"),Qe=require("better-call"),W=require("jose"),Ze=require("oslo/jwt");var ze=require("oslo/crypto"),Me=require("oslo/encoding");async function He(e){let t=await(0,ze.sha256)(new TextEncoder().encode(e));return Me.base64url.encode(new Uint8Array(t),{includePadding:!1})}function le(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?q(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:a,redirectURI:c,duration:s}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",i.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),n){let p=await He(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",p)}if(a){let p=a.reduce((m,y)=>(m[y]=null,m),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...p}}))}return s&&d.searchParams.set("duration",s),d}var Ge=require("@better-fetch/fetch");async function w({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n,authentication:i}){let a=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(a.set("grant_type","authorization_code"),a.set("code",e),t&&a.set("code_verifier",t),a.set("redirect_uri",r),i==="basic"){let m=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${m}`}else a.set("client_id",o.clientId),a.set("client_secret",o.clientSecret);let{data:s,error:d}=await(0,Ge.betterFetch)(n,{method:"POST",body:a,headers:c});if(d)throw d;return le(s)}var me=require("oslo/oauth2"),B=require("zod"),Oe=require("better-call");async function fe(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Ve(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new Oe.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,me.generateCodeVerifier)(),n=(0,me.generateState)(),i=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}),a=new Date;a.setMinutes(a.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:a});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 Oe.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function We(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=B.z.object({callbackURL:B.z.string(),codeVerifier:B.z.string(),errorURL:B.z.string().optional(),newUserURL:B.z.string().optional(),expiresAt:B.z.number(),link:B.z.object({email:B.z.string(),userId:B.z.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 Je=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let n=(0,W.decodeProtectedHeader)(r),{kid:i,alg:a}=n;if(!i||!a)return!1;let c=await rr(i),{payload:s}=await(0,W.jwtVerify)(r,c,{algorithms:[a],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{s[d]!==void 0&&(s[d]=!!s[d])}),o&&s.nonce!==o?!1:!!s},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=(0,Ze.parseJWT)(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email,...i},data:o}}}},rr=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,Ke.betterFetch)(`${t}${r}`);if(!o?.keys)throw new Qe.APIError("BAD_REQUEST",{message:"Keys not found"});let n=o.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await(0,W.importJWK)(n,n.alg)};var Ye=require("@better-fetch/fetch");var Xe=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({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(0,Ye.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}let n=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,...n},data:r}}});var et=require("@better-fetch/fetch");var tt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({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(0,et.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...n},data:r}}});var Ue=require("@better-fetch/fetch");var rt=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let a=o||["user:email"];return e.scope&&a.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>w({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await(0,Ue.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:c,error:s}=await(0,Ue.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});s||(o.email=(c.find(d=>d.primary)??c[0])?.email,i=c.find(d=>d.email===o.email)?.verified??!1)}let a=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i,...a},data:o}}}};var nt=require("oslo/jwt");var ot=require("consola"),Se=["info","success","warn","error","debug"];function or(e,t){return Se.indexOf(t)<=Se.indexOf(e)}var nr=(0,ot.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),sr=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,a=[])=>{if(!(!t||!or(r,n))){if(!e||typeof e.log!="function"){nr[n]("",i,...a);return}e.log(n==="success"?"info":n,i,a)}};return Object.fromEntries(Se.map(n=>[n,(...[i,...a])=>o(n,i,a)]))},L=sr();var st=require("@better-fetch/fetch"),it=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw L.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new D("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new D("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let a=await A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});return e.accessType&&a.searchParams.set("access_type",e.accessType),e.prompt&&a.searchParams.set("prompt",e.prompt),a},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({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:n}=await(0,st.betterFetch)(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,nt.parseJWT)(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}}});var at=require("@better-fetch/fetch"),ct=require("oslo/jwt");var dt=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),A({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:a}){return w({code:n,codeVerifier:i,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=(0,ct.parseJWT)(n.idToken)?.payload,a=e.profilePhotoSize||48;await(0,at.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(s){if(!(e.disableProfilePhoto||!s.response.ok))try{let p=await s.response.clone().arrayBuffer(),m=Buffer.from(p).toString("base64");i.picture=`data:image/jpeg;base64, ${m}`}catch(d){L.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0,...c},data:i}}}};var pt=require("@better-fetch/fetch");var ut=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({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(0,pt.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...n},data:r}}});var K={isAction:!1};var lt=require("nanoid"),oe=e=>(0,lt.nanoid)(e);var mt=require("oslo/jwt");var ft=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({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 L.error("No idToken found in token"),null;let o=(0,mt.parseJWT)(r)?.payload,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...n},data:o}}});var gt=require("@better-fetch/fetch");var ht=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),A({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})=>w({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(0,gt.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=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,...n},data:r}}});var yt=require("@better-fetch/fetch");var wt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let a=o||["account_info.read"];return e.scope&&a.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await(0,yt.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=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,...i},data:o}}}};var bt=require("@better-fetch/fetch");var At=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:n,redirectURI:i})=>{let a=n||["profile","email","openid"];return e.scope&&a.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:a,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await w({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await(0,bt.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture,...a},data:n}}}};var Rt=require("@better-fetch/fetch");var Pe=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),ir=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:Pe(`${t}/oauth/authorize`),tokenEndpoint:Pe(`${t}/oauth/token`),userinfoEndpoint:Pe(`${t}/api/v4/user`)}},Et=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=ir(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:a,scopes:c,codeVerifier:s,redirectURI:d})=>{let p=c||["read_user"];return e.scope&&p.push(...e.scope),await A({id:n,options:e,authorizationEndpoint:t,scopes:p,state:a,redirectURI:d,codeVerifier:s})},validateAuthorizationCode:async({code:a,redirectURI:c,codeVerifier:s})=>w({code:a,redirectURI:e.redirectURI||c,options:e,codeVerifier:s,tokenEndpoint:r}),async getUserInfo(a){if(e.getUserInfo)return e.getUserInfo(a);let{data:c,error:s}=await(0,Rt.betterFetch)(o,{headers:{authorization:`Bearer ${a.accessToken}`}});if(s||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}}}};var Ie=require("@better-fetch/fetch");var kt=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identity"];return e.scope&&n.push(...e.scope),A({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:n,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}),n={"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:i,error:a}=await(0,Ie.betterFetch)("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:n,body:o.toString()});if(a)throw a;return le(i)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,Ie.betterFetch)("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let n=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],...n},data:r}}});var ar={apple:Je,discord:Xe,facebook:tt,github:rt,microsoft:dt,google:it,spotify:ut,twitch:ft,twitter:ht,dropbox:wt,linkedin:At,gitlab:Et,reddit:kt},ge=Object.keys(ar);var Ot=require("oslo"),he=require("oslo/jwt"),x=require("zod");var Q=require("better-call");var j=require("better-call");var z=require("zod");function Tt(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 _t=()=>u("/get-session",{method:"GET",query:z.z.optional(z.z.object({disableCookieCache:z.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(z.z.string().transform(e=>e==="true")).optional(),disableRefresh:z.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 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?Tt(Buffer.from(r,"base64").toString()):null;if(o&&!await ue.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return N(e),e.json(null);let n=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 y=e.context.authCookies.sessionData.name;e.setCookie(y,"",{maxAge:0})}else return e.json(p)}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return N(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n||e.query?.disableRefresh)return e.json(i);let a=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-a*1e3+c*1e3<=Date.now()){let p=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:q(e.context.sessionConfig.expiresIn,"sec")});if(!p)return N(e),e.json(null,{status:401});let m=(p.expiresAt.valueOf()-Date.now())/1e3;return await O(e,{session:p,user:i.user},!1,{maxAge:m}),e.json({session:p,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new j.APIError("INTERNAL_SERVER_ERROR",{message:l.FAILED_TO_GET_SESSION})}}),V=async(e,t)=>{if(e.context.session)return e.context.session;let r=await _t()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},U=te(async e=>{let t=await V(e);if(!t?.session)throw new j.APIError("UNAUTHORIZED");return{session:t}}),ne=te(async e=>{let t=await V(e);if(!t?.session)throw new j.APIError("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 j.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}});var cr=u("/revoke-session",{method:"POST",body:z.z.object({token:z.z.string({description:"The token to revoke"})}),use:[U],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 j.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new j.APIError("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 j.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),dr=u("/revoke-sessions",{method:"POST",use:[U],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 j.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),pr=u("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[U],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 j.APIError("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});async function $(e,t,r){return await(0,he.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Ot.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function ur(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Q.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await $(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 lr=u("/send-verification-email",{method:"POST",query:x.z.object({currentURL:x.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:x.z.object({email:x.z.string({description:"The email to send the verification email to"}).email(),callbackURL:x.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 e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Q.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new Q.APIError("BAD_REQUEST",{message:l.USER_NOT_FOUND});return await ur(e,r.user),e.json({status:!0})}),mr=u("/verify-email",{method:"GET",query:x.z.object({token:x.z.string({description:"The token to verify the email"}),callbackURL:x.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 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 Q.APIError("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await(0,he.validateJWT)("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let i=x.z.object({email:x.z.string().email(),updateTo:x.z.string().optional()}).parse(o.payload),a=await e.context.internalAdapter.findUserByEmail(i.email);if(!a)return t("user_not_found");if(i.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!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let s=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),d=await $(e.context.secret,i.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:s,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:s,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await V(e)){let s=await e.context.internalAdapter.createSession(a.user.id,e.request);if(!s)throw new Q.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await O(e,{session:s,user:a.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function ye(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(s=>{throw L.error(`Better auth was unable to query your database.
|
|
3
3
|
Error: `,s),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user,a=!i;if(n){let s=n.accounts.find(d=>d.providerId===r.providerId);if(s){let d=Object.fromEntries(Object.entries({accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([p,m])=>m!==void 0));Object.keys(d).length>0&&await e.context.internalAdapter.updateAccount(s.id,d)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return _e&&L.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:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope})}catch(m){return L.error("Unable to link account",m),{error:"unable to link account",data:null}}i=await e.context.internalAdapter.updateUser(n.user.id,{...t,updatedAt:new Date})}}else if(i=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(s=>s?.user),!t.emailVerified&&i&&e.context.options.emailVerification?.sendOnSignUp){let s=await $(e.context.secret,i.email),d=`${e.context.baseURL}/verify-email?token=${s}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:d,token:s},e.request)}if(!i)return{error:"unable to create user",data:null,isRegister:!1};let c=await e.context.internalAdapter.createSession(i.id,e.request);return c?{data:{session:c,user:i},error:null,isRegister:a}:{error:"unable to create session",data:null,isRegister:!1}}var fr=u("/sign-in/social",{method:"POST",query:R.z.object({currentURL:R.z.string().optional()}).optional(),body:R.z.object({callbackURL:R.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:R.z.string().optional(),errorCallbackURL:R.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:R.z.enum(ge,{description:"OAuth2 provider to use"}),disableRedirect:R.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:R.z.optional(R.z.object({token:R.z.string({description:"ID token from the provider"}),nonce:R.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:R.z.string({description:"Access token from the provider"}).optional(),refreshToken:R.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:R.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 e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new k.APIError("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 k.APIError("NOT_FOUND",{message:l.ID_TOKEN_NOT_SUPPORTED});let{token:i,nonce:a}=e.body.idToken;if(!await t.verifyIdToken(i,a))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new k.APIError("UNAUTHORIZED",{message:l.INVALID_TOKEN});let s=await t.getUserInfo({idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!s||!s?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new k.APIError("UNAUTHORIZED",{message:l.FAILED_TO_GET_USER_INFO});if(!s.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new k.APIError("UNAUTHORIZED",{message:l.USER_EMAIL_NOT_FOUND});let d=await ye(e,{userInfo:{email:s.user.email,id:s.user.id,name:s.user.name||"",image:s.user.image,emailVerified:s.user.emailVerified||!1},account:{providerId:t.id,accountId:s.user.id,accessToken:e.body.idToken.accessToken}});if(d.error)throw new k.APIError("UNAUTHORIZED",{message:d.error});return await O(e,d.data),e.json({session:d.data.session,user:d.data.user,url:void 0,redirect:!1})}let{codeVerifier:r,state:o}=await fe(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),gr=u("/sign-in/email",{method:"POST",body:R.z.object({email:R.z.string({description:"Email of the user"}),password:R.z.string({description:"Password of the user"}),callbackURL:R.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:R.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 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 k.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!R.z.string().email().safeParse(t).success)throw new k.APIError("BAD_REQUEST",{message:l.INVALID_EMAIL});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new k.APIError("UNAUTHORIZED",{message:l.INVALID_EMAIL_OR_PASSWORD});let i=n.accounts.find(d=>d.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new k.APIError("UNAUTHORIZED",{message:l.INVALID_EMAIL_OR_PASSWORD});let a=i?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new k.APIError("UNAUTHORIZED",{message:l.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:a,password:r}))throw e.context.logger.error("Invalid password"),new k.APIError("UNAUTHORIZED",{message:l.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new k.APIError("UNAUTHORIZED",{message:l.EMAIL_NOT_VERIFIED});let d=await $(e.context.secret,n.user.email),p=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:p,token:d},e.request),e.context.logger.error("Email not verified",{email:t}),new k.APIError("FORBIDDEN",{message:l.EMAIL_NOT_VERIFIED})}let s=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!s)throw e.context.logger.error("Failed to create session"),new k.APIError("UNAUTHORIZED",{message:l.FAILED_TO_CREATE_SESSION});return await O(e,{session:s,user:n.user},e.body.rememberMe===!1),e.json({user:{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},redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Z=require("zod");var we=Z.z.object({code:Z.z.string().optional(),error:Z.z.string().optional(),error_description:Z.z.string().optional(),state:Z.z.string().optional()}),hr=u("/callback/:id",{method:["GET","POST"],body:we.optional(),query:we.optional(),metadata:K},async e=>{let t;try{if(e.method==="GET")t=we.parse(e.query);else if(e.method==="POST")t=we.parse(e.body);else throw new Error("Unsupported method")}catch(_){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",_),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n,error_description:i}=t;if(!n)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=${i}`);let a=e.context.socialProviders.find(_=>_.id===e.params.id);if(!a)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:s,link:d,errorURL:p,newUserURL:m}=await We(e),y;try{y=await a.validateAuthorizationCode({code:r,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${a.id}`})}catch(_){throw e.context.logger.error("",_),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let h=await a.getUserInfo(y).then(_=>_?.user);function f(_){let v=p||s||`${e.context.baseURL}/error`;throw v.includes("?")?v=`${v}&error=${_}`:v=`${v}?error=${_}`,e.redirect(v)}if(!h)return e.context.logger.error("Unable to get user info"),f("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."),f("email_not_found");if(!s)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 f("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:a.id,accountId:h.id}))return f("unable_to_link_account");let v;try{v=s.toString()}catch{v=s}throw e.redirect(v)}let b=await ye(e,{userInfo:{...h,email:h.email,name:h.name||h.email},account:{providerId:a.id,accountId:h.id,...y,scope:y.scopes?.join(",")},callbackURL:s});if(b.error)return e.context.logger.error(b.error.split(" ").join("_")),f(b.error.split(" ").join("_"));let{session:G,user:C}=b.data;await O(e,{session:G,user:C});let F;try{F=(b.isRegister&&m||s).toString()}catch{F=b.isRegister&&m||s}throw e.redirect(F)});var Is=require("zod");var Ut=require("better-call");var yr=u("/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 N(e),new Ut.APIError("BAD_REQUEST",{message:l.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(t),N(e),e.json({success:!0})});var P=require("zod");var J=require("better-call");function St(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function wr(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var br=u("/forget-password",{method:"POST",body:P.z.object({email:P.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:P.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 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 J.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=q(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),a=oe(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${a}`,expiresAt:i});let c=`${e.context.baseURL}/reset-password/${a}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:c,token:a},e.request),e.json({status:!0})}),Ar=u("/reset-password/:token",{method:"GET",query:P.z.object({callbackURL:P.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 e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(St(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(St(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(wr(e.context,r,{token:t}))}),Rr=u("/reset-password",{query:P.z.optional(P.z.object({token:P.z.string().optional(),currentURL:P.z.string().optional()})),method:"POST",body:P.z.object({newPassword:P.z.string({description:"The new password to set"}),token:P.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 e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new J.APIError("BAD_REQUEST",{message:l.INVALID_TOKEN});let{newPassword:r}=e.body,o=e.context.password?.config.minPasswordLength,n=e.context.password?.config.maxPasswordLength;if(r.length<o)throw new J.APIError("BAD_REQUEST",{message:l.PASSWORD_TOO_SHORT});if(r.length>n)throw new J.APIError("BAD_REQUEST",{message:l.PASSWORD_TOO_LONG});let i=`reset-password:${t}`,a=await e.context.internalAdapter.findVerificationValue(i);if(!a||a.expiresAt<new Date)throw new J.APIError("BAD_REQUEST",{message:l.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(a.id);let c=a.value,s=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(c)).find(m=>m.providerId==="credential")?(await e.context.internalAdapter.updatePassword(c,s),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:c,providerId:"credential",password:s,accountId:c}),e.json({status:!0}))});var S=require("zod");var E=require("better-call");var g=require("zod"),Er=require("better-call"),Fs=g.z.object({id:g.z.string(),providerId:g.z.string(),accountId:g.z.string(),userId:g.z.string(),accessToken:g.z.string().nullish(),refreshToken:g.z.string().nullish(),idToken:g.z.string().nullish(),accessTokenExpiresAt:g.z.date().nullish(),refreshTokenExpiresAt:g.z.date().nullish(),scope:g.z.string().nullish(),password:g.z.string().nullish(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date)}),qs=g.z.object({id:g.z.string(),email:g.z.string().transform(e=>e.toLowerCase()),emailVerified:g.z.boolean().default(!1),name:g.z.string(),image:g.z.string().nullish(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date)}),zs=g.z.object({id:g.z.string(),userId:g.z.string(),expiresAt:g.z.date(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date),token:g.z.string(),ipAddress:g.z.string().nullish(),userAgent:g.z.string().nullish()}),Ms=g.z.object({id:g.z.string(),value:g.z.string(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date),expiresAt:g.z.date(),identifier:g.z.string()});function Pt(e,t){if(!t)return e;for(let r in t){let o=t[r]?.modelName;o&&(e[r].modelName=o);for(let n in e[r].fields){let i=t[r]?.fields?.[n];i&&(e[r].fields[n].fieldName=i)}}return e}var _r=require("@noble/ciphers/chacha"),ve=require("@noble/ciphers/utils"),Or=require("@noble/ciphers/webcrypto"),Ur=require("oslo/crypto"),Sr=Ae(require("uncrypto"),1);var It=require("oslo/encoding");var kr=require("@noble/hashes/scrypt"),Tr=require("uncrypto");var Ir=u("/change-password",{method:"POST",body:S.z.object({newPassword:S.z.string({description:"The new password to set"}),currentPassword:S.z.string({description:"The current password"}),revokeOtherSessions:S.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[U],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,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new E.APIError("BAD_REQUEST",{message:l.PASSWORD_TOO_SHORT});let a=e.context.password.config.maxPasswordLength;if(t.length>a)throw e.context.logger.error("Password is too long"),new E.APIError("BAD_REQUEST",{message:l.PASSWORD_TOO_LONG});let s=(await e.context.internalAdapter.findAccounts(n.user.id)).find(m=>m.providerId==="credential"&&m.password);if(!s||!s.password)throw new E.APIError("BAD_REQUEST",{message:l.CREDENTIAL_ACCOUNT_NOT_FOUND});let d=await e.context.password.hash(t);if(!await e.context.password.verify({hash:s.password,password:r}))throw new E.APIError("BAD_REQUEST",{message:l.INVALID_PASSWORD});if(await e.context.internalAdapter.updateAccount(s.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let m=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!m)throw new E.APIError("INTERNAL_SERVER_ERROR",{message:l.FAILED_TO_GET_SESSION});await O(e,{session:m,user:n.user})}return e.json(n.user)}),vr=u("/set-password",{method:"POST",body:S.z.object({newPassword:S.z.string()}),metadata:{SERVER_ONLY:!0},use:[U]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new E.APIError("BAD_REQUEST",{message:l.PASSWORD_TOO_SHORT});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new E.APIError("BAD_REQUEST",{message:l.PASSWORD_TOO_LONG});let a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password),c=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:c}),e.json(r.user);throw new E.APIError("BAD_REQUEST",{message:"user already has a password"})}),xr=u("/delete-user",{method:"POST",use:[ne],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 E.APIError("NOT_FOUND");let t=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=ie(32,ae("a-z","A-Z","0-9"));await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${n}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let i=`${e.context.baseURL}/delete-user/callback?token=${n}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:i,token:n},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),N(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})}),Lr=u("/delete-user/callback",{method:"GET",query:S.z.object({token:S.z.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 E.APIError("NOT_FOUND");let t=await V(e);if(!t)throw new E.APIError("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 E.APIError("NOT_FOUND",{message:l.INVALID_TOKEN});if(r.value!==t.user.id)throw new E.APIError("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),N(e);let n=e.context.options.user.deleteUser?.afterDelete;return n&&await n(t.user,e.request),e.json({success:!0,message:"User deleted"})}),Cr=u("/change-email",{method:"POST",query:S.z.object({currentURL:S.z.string().optional()}).optional(),body:S.z.object({newEmail:S.z.string({description:"The new email to set"}).email(),callbackURL:S.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[U],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 E.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new E.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new E.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await $(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>
|
package/dist/plugins/passkey.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import{generateAuthenticationOptions as Ur,generateRegistrationOptions as Sr,verifyAuthenticationResponse as Pr,verifyRegistrationResponse as Ir}from"@simplewebauthn/server";import{APIError as U}from"better-call";import we from"uncrypto";function Xe(e){return e.toString(2).padStart(8,"0")}function et(e){return[...e].map(t=>Xe(t)).join("")}function be(e){return parseInt(et(e),2)}function tt(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));we.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=be(o);for(;n>=e;)we.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=be(o);return n}function ee(e,t){let r="";for(let o=0;o<e;o++)r+=t[tt(t.length)];return r}function te(...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}import{z as v}from"zod";import{createEndpointCreator as rt,createMiddleware as Ae,createMiddlewareCreator as ot}from"better-call";var Re=Ae(async()=>({})),G=ot({use:[Re,Ae(async()=>({}))]}),u=rt({use:[Re]});import{APIError as ic,createRouter as ac,getCookie as cc,getSignedCookie as dc,setCookie as pc,setSignedCookie as uc}from"better-call";import{APIError as ct}from"better-call";function pe(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function nt(e){let t="";for(let r=0;r<e.length;r++)t+=pe(e[r]);return t}function Ee(e,t=!0){if(Array.isArray(e))return`(?:${e.map(p=>`^${Ee(p,t)}$`).join("|")})`;let r="",o="",n=".";t===!0?(r="/",o="[/\\\\]",n="[^/\\\\]"):t&&(r=t,o=nt(r),o.length>1?(o=`(?:${o})`,n=`((?!${o}).)`):n=`[^${o}]`);let i=t?`${o}+?`:"",a=t?`${o}*?`:"",c=t?e.split(r):[e],s="";for(let d=0;d<c.length;d++){let p=c[d],m=c[d+1],y="";if(!(!p&&d>0)){if(t&&(d===c.length-1?y=a:m!=="**"?y=i:y=""),t&&p==="**"){y&&(s+=d===0?"":y,s+=`(?:${n}*?${y})*?`);continue}for(let h=0;h<p.length;h++){let f=p[h];f==="\\"?h<p.length-1&&(s+=pe(p[h+1]),h++):f==="?"?s+=n:f==="*"?s+=`${n}*?`:s+=pe(f)}s+=y}}return s}function st(e,t){if(typeof t!="string")throw new TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function ue(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=Ee(e,t.separator),o=new RegExp(`^${r}$`,t.flags),n=st.bind(null,o);return n.options=t,n.pattern=e,n.regexp=o,n}var re=Object.create(null),W=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?re:globalThis),oe=new Proxy(re,{get(e,t){return W()[t]??re[t]},has(e,t){let r=W();return t in r||t in re},set(e,t,r){let o=W(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=W(!0);return delete r[t],!0},ownKeys(){let e=W(!0);return Object.keys(e)}});function it(e){return e?e!=="false":!1}var le=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var me=le==="dev"||le==="development",at=le==="test"||it(oe.TEST);var D=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function ke(e){try{return new URL(e).origin}catch{return null}}function Te(e){return e.includes("://")?new URL(e).host:e}var dt=G(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=t?.callbackURL||r?.callbackURL,a=t?.redirectTo,c=r?.currentURL,s=t?.errorCallbackURL,d=t?.newUserCallbackURL,p=o.trustedOrigins,m=e.headers?.has("cookie"),y=(f,b)=>f.startsWith("/")?!1:b.includes("*")?ue(b)(Te(f)):f.startsWith(b),h=(f,b)=>{if(!f)return;if(!p.some(C=>y(f,C)||f?.startsWith("/")&&b!=="origin"&&!f.includes(":")))throw e.context.logger.error(`Invalid ${b}: ${f}`),e.context.logger.info(`If it's a valid URL, please add ${f} to trustedOrigins in your auth config
|
|
2
|
-
`,`Current list of trustedOrigins: ${p}`),new ct("FORBIDDEN",{message:`Invalid ${b}`})};m&&!e.context.options.advanced?.disableCSRFCheck&&h(n,"origin"),i&&h(i,"callbackURL"),a&&h(a,"redirectURL"),c&&h(c,"currentURL"),s&&h(s,"errorCallbackURL"),d&&h(a,"newUserCallbackURL")});import{APIError as k}from"better-call";import{z as R}from"zod";import{TimeSpan as ro}from"oslo";import{base64url as mt}from"oslo/encoding";import{HMAC as _e,sha256 as Qr}from"oslo/crypto";async function ut({value:e,secret:t}){return new _e("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function lt({value:e,signature:t,secret:r}){return new _e("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var ne={sign:ut,verify:lt};var q=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function _(e,t,r,o){let n=e.context.authCookies.sessionToken.options,i=r?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...n,maxAge:i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled){let c=mt.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:q(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await ne.sign({value:JSON.stringify(t),secret:e.context.secret})})),{includePadding:!1});if(c.length>4093)throw new D("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 N(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 bt}from"@better-fetch/fetch";import{APIError as At}from"better-call";import{decodeProtectedHeader as Rt,importJWK as Et,jwtVerify as kt}from"jose";import{parseJWT as Tt}from"oslo/jwt";import{sha256 as ft}from"oslo/crypto";import{base64url as gt}from"oslo/encoding";async function Oe(e){let t=await ft(new TextEncoder().encode(e));return gt.encode(new Uint8Array(t),{includePadding:!1})}function se(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?q(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:a,redirectURI:c,duration:s}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",i.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),n){let p=await Oe(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",p)}if(a){let p=a.reduce((m,y)=>(m[y]=null,m),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...p}}))}return s&&d.searchParams.set("duration",s),d}import{betterFetch as ht}from"@better-fetch/fetch";async function w({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n,authentication:i}){let a=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(a.set("grant_type","authorization_code"),a.set("code",e),t&&a.set("code_verifier",t),a.set("redirect_uri",r),i==="basic"){let m=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${m}`}else a.set("client_id",o.clientId),a.set("client_secret",o.clientSecret);let{data:s,error:d}=await ht(n,{method:"POST",body:a,headers:c});if(d)throw d;return se(s)}import{generateCodeVerifier as yt,generateState as wt}from"oslo/oauth2";import{z as B}from"zod";import{APIError as Ue}from"better-call";async function ie(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?ke(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new Ue("BAD_REQUEST",{message:"callbackURL is required"});let o=yt(),n=wt(),i=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}),a=new Date;a.setMinutes(a.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:a});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 Ue("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function Se(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=B.object({callbackURL:B.string(),codeVerifier:B.string(),errorURL:B.string().optional(),newUserURL:B.string().optional(),expiresAt:B.number(),link:B.object({email:B.string(),userId:B.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 Pe=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let n=Rt(r),{kid:i,alg:a}=n;if(!i||!a)return!1;let c=await _t(i),{payload:s}=await kt(r,c,{algorithms:[a],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{s[d]!==void 0&&(s[d]=!!s[d])}),o&&s.nonce!==o?!1:!!s},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=Tt(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email,...i},data:o}}}},_t=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await bt(`${t}${r}`);if(!o?.keys)throw new At("BAD_REQUEST",{message:"Keys not found"});let n=o.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await Et(n,n.alg)};import{betterFetch as Ot}from"@better-fetch/fetch";var Ie=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({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 Ot("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}let n=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,...n},data:r}}});import{betterFetch as Ut}from"@better-fetch/fetch";var ve=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({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 Ut("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...n},data:r}}});import{betterFetch as xe}from"@better-fetch/fetch";var Le=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let a=o||["user:email"];return e.scope&&a.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>w({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await xe("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:c,error:s}=await xe("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});s||(o.email=(c.find(d=>d.primary)??c[0])?.email,i=c.find(d=>d.email===o.email)?.verified??!1)}let a=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i,...a},data:o}}}};import{parseJWT as xt}from"oslo/jwt";import{createConsola as St}from"consola";var fe=["info","success","warn","error","debug"];function Pt(e,t){return fe.indexOf(t)<=fe.indexOf(e)}var It=St({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),vt=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,a=[])=>{if(!(!t||!Pt(r,n))){if(!e||typeof e.log!="function"){It[n]("",i,...a);return}e.log(n==="success"?"info":n,i,a)}};return Object.fromEntries(fe.map(n=>[n,(...[i,...a])=>o(n,i,a)]))},x=vt();import{betterFetch as Lt}from"@better-fetch/fetch";var Ce=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw x.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new D("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new D("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let a=await A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});return e.accessType&&a.searchParams.set("access_type",e.accessType),e.prompt&&a.searchParams.set("prompt",e.prompt),a},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({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:n}=await Lt(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=xt(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 Ct}from"@better-fetch/fetch";import{parseJWT as Dt}from"oslo/jwt";var De=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),A({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:a}){return w({code:n,codeVerifier:i,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=Dt(n.idToken)?.payload,a=e.profilePhotoSize||48;await Ct(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(s){if(!(e.disableProfilePhoto||!s.response.ok))try{let p=await s.response.clone().arrayBuffer(),m=Buffer.from(p).toString("base64");i.picture=`data:image/jpeg;base64, ${m}`}catch(d){x.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0,...c},data:i}}}};import{betterFetch as Nt}from"@better-fetch/fetch";var Ne=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({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 Nt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...n},data:r}}});var H={isAction:!1};import{nanoid as Bt}from"nanoid";var K=e=>Bt(e);import{parseJWT as jt}from"oslo/jwt";var Be=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({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 x.error("No idToken found in token"),null;let o=jt(r)?.payload,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...n},data:o}}});import{betterFetch as Vt}from"@better-fetch/fetch";var je=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),A({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})=>w({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 Vt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=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,...n},data:r}}});import{betterFetch as $t}from"@better-fetch/fetch";var Ve=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let a=o||["account_info.read"];return e.scope&&a.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await $t("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=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,...i},data:o}}}};import{betterFetch as Ft}from"@better-fetch/fetch";var $e=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:n,redirectURI:i})=>{let a=n||["profile","email","openid"];return e.scope&&a.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:a,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await w({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await Ft("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture,...a},data:n}}}};import{betterFetch as qt}from"@better-fetch/fetch";var ge=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),zt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ge(`${t}/oauth/authorize`),tokenEndpoint:ge(`${t}/oauth/token`),userinfoEndpoint:ge(`${t}/api/v4/user`)}},Fe=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=zt(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:a,scopes:c,codeVerifier:s,redirectURI:d})=>{let p=c||["read_user"];return e.scope&&p.push(...e.scope),await A({id:n,options:e,authorizationEndpoint:t,scopes:p,state:a,redirectURI:d,codeVerifier:s})},validateAuthorizationCode:async({code:a,redirectURI:c,codeVerifier:s})=>w({code:a,redirectURI:e.redirectURI||c,options:e,codeVerifier:s,tokenEndpoint:r}),async getUserInfo(a){if(e.getUserInfo)return e.getUserInfo(a);let{data:c,error:s}=await qt(o,{headers:{authorization:`Bearer ${a.accessToken}`}});if(s||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 qe}from"@better-fetch/fetch";var ze=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identity"];return e.scope&&n.push(...e.scope),A({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:n,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}),n={"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:i,error:a}=await qe("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:n,body:o.toString()});if(a)throw a;return se(i)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await qe("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let n=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],...n},data:r}}});var Mt={apple:Pe,discord:Ie,facebook:ve,github:Le,microsoft:De,google:Ce,spotify:Ne,twitch:Be,twitter:je,dropbox:Ve,linkedin:$e,gitlab:Fe,reddit:ze},ae=Object.keys(Mt);import{TimeSpan as Kt}from"oslo";import{createJWT as Qt,validateJWT as Zt}from"oslo/jwt";import{z as L}from"zod";import{APIError as Z}from"better-call";import{APIError as j}from"better-call";import{z}from"zod";function Me(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 He=()=>u("/get-session",{method:"GET",query:z.optional(z.object({disableCookieCache:z.boolean({description:"Disable cookie cache and fetch session from database"}).or(z.string().transform(e=>e==="true")).optional(),disableRefresh: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 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?Me(Buffer.from(r,"base64").toString()):null;if(o&&!await ne.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return N(e),e.json(null);let n=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 y=e.context.authCookies.sessionData.name;e.setCookie(y,"",{maxAge:0})}else return e.json(p)}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return N(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n||e.query?.disableRefresh)return e.json(i);let a=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-a*1e3+c*1e3<=Date.now()){let p=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:q(e.context.sessionConfig.expiresIn,"sec")});if(!p)return N(e),e.json(null,{status:401});let m=(p.expiresAt.valueOf()-Date.now())/1e3;return await _(e,{session:p,user:i.user},!1,{maxAge:m}),e.json({session:p,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new j("INTERNAL_SERVER_ERROR",{message:l.FAILED_TO_GET_SESSION})}}),V=async(e,t)=>{if(e.context.session)return e.context.session;let r=await He()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},O=G(async e=>{let t=await V(e);if(!t?.session)throw new j("UNAUTHORIZED");return{session:t}}),Q=G(async e=>{let t=await V(e);if(!t?.session)throw new j("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),n=Date.now();if(!(o+r*1e3>n))throw new j("FORBIDDEN",{message:"Session is not fresh"});return{session:t}});var Ht=u("/revoke-session",{method:"POST",body:z.object({token:z.string({description:"The token to revoke"})}),use:[O],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 j("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new j("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 j("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Gt=u("/revoke-sessions",{method:"POST",use:[O],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 j("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Wt=u("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[O],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 j("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});async function $(e,t,r){return await Qt("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Kt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Jt(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Z("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await $(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 Yt=u("/send-verification-email",{method:"POST",query:L.object({currentURL:L.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:L.object({email:L.string({description:"The email to send the verification email to"}).email(),callbackURL:L.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 Z("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new Z("BAD_REQUEST",{message:l.USER_NOT_FOUND});return await Jt(e,r.user),e.json({status:!0})}),Xt=u("/verify-email",{method:"GET",query:L.object({token:L.string({description:"The token to verify the email"}),callbackURL:L.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 Z("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 i=L.object({email:L.string().email(),updateTo:L.string().optional()}).parse(o.payload),a=await e.context.internalAdapter.findUserByEmail(i.email);if(!a)return t("user_not_found");if(i.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!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let s=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),d=await $(e.context.secret,i.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:s,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:s,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await V(e)){let s=await e.context.internalAdapter.createSession(a.user.id,e.request);if(!s)throw new Z("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await _(e,{session:s,user:a.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function ce(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(s=>{throw x.error(`Better auth was unable to query your database.
|
|
2
|
+
`,`Current list of trustedOrigins: ${p}`),new ct("FORBIDDEN",{message:`Invalid ${b}`})};m&&!e.context.options.advanced?.disableCSRFCheck&&h(n,"origin"),i&&h(i,"callbackURL"),a&&h(a,"redirectURL"),c&&h(c,"currentURL"),s&&h(s,"errorCallbackURL"),d&&h(a,"newUserCallbackURL")});import{APIError as k}from"better-call";import{z as R}from"zod";import{TimeSpan as ro}from"oslo";import{base64url as mt}from"oslo/encoding";import{HMAC as _e,sha256 as Qr}from"oslo/crypto";async function ut({value:e,secret:t}){return new _e("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function lt({value:e,signature:t,secret:r}){return new _e("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var ne={sign:ut,verify:lt};var q=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function _(e,t,r,o){let n=e.context.authCookies.sessionToken.options,i=r?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...n,maxAge:i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled){let c=mt.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:q(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await ne.sign({value:JSON.stringify(t),secret:e.context.secret})})),{includePadding:!1});if(c.length>4093)throw new D("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 N(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 bt}from"@better-fetch/fetch";import{APIError as At}from"better-call";import{decodeProtectedHeader as Rt,importJWK as Et,jwtVerify as kt}from"jose";import{parseJWT as Tt}from"oslo/jwt";import{sha256 as ft}from"oslo/crypto";import{base64url as gt}from"oslo/encoding";async function Oe(e){let t=await ft(new TextEncoder().encode(e));return gt.encode(new Uint8Array(t),{includePadding:!1})}function se(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?q(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:a,redirectURI:c,duration:s}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",i.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),n){let p=await Oe(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",p)}if(a){let p=a.reduce((m,y)=>(m[y]=null,m),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...p}}))}return s&&d.searchParams.set("duration",s),d}import{betterFetch as ht}from"@better-fetch/fetch";async function w({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n,authentication:i}){let a=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(a.set("grant_type","authorization_code"),a.set("code",e),t&&a.set("code_verifier",t),a.set("redirect_uri",r),i==="basic"){let m=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${m}`}else a.set("client_id",o.clientId),a.set("client_secret",o.clientSecret);let{data:s,error:d}=await ht(n,{method:"POST",body:a,headers:c});if(d)throw d;return se(s)}import{generateCodeVerifier as yt,generateState as wt}from"oslo/oauth2";import{z as B}from"zod";import{APIError as Ue}from"better-call";async function ie(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?ke(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new Ue("BAD_REQUEST",{message:"callbackURL is required"});let o=yt(),n=wt(),i=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}),a=new Date;a.setMinutes(a.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:a});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 Ue("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function Se(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=B.object({callbackURL:B.string(),codeVerifier:B.string(),errorURL:B.string().optional(),newUserURL:B.string().optional(),expiresAt:B.number(),link:B.object({email:B.string(),userId:B.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 Pe=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let n=Rt(r),{kid:i,alg:a}=n;if(!i||!a)return!1;let c=await _t(i),{payload:s}=await kt(r,c,{algorithms:[a],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{s[d]!==void 0&&(s[d]=!!s[d])}),o&&s.nonce!==o?!1:!!s},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=Tt(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email,...i},data:o}}}},_t=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await bt(`${t}${r}`);if(!o?.keys)throw new At("BAD_REQUEST",{message:"Keys not found"});let n=o.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await Et(n,n.alg)};import{betterFetch as Ot}from"@better-fetch/fetch";var Ie=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({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 Ot("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}let n=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,...n},data:r}}});import{betterFetch as Ut}from"@better-fetch/fetch";var ve=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({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 Ut("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...n},data:r}}});import{betterFetch as xe}from"@better-fetch/fetch";var Le=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let a=o||["user:email"];return e.scope&&a.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>w({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await xe("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:c,error:s}=await xe("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});s||(o.email=(c.find(d=>d.primary)??c[0])?.email,i=c.find(d=>d.email===o.email)?.verified??!1)}let a=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i,...a},data:o}}}};import{parseJWT as xt}from"oslo/jwt";import{createConsola as St}from"consola";var fe=["info","success","warn","error","debug"];function Pt(e,t){return fe.indexOf(t)<=fe.indexOf(e)}var It=St({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),vt=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,a=[])=>{if(!(!t||!Pt(r,n))){if(!e||typeof e.log!="function"){It[n]("",i,...a);return}e.log(n==="success"?"info":n,i,a)}};return Object.fromEntries(fe.map(n=>[n,(...[i,...a])=>o(n,i,a)]))},x=vt();import{betterFetch as Lt}from"@better-fetch/fetch";var Ce=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw x.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new D("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new D("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let a=await A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});return e.accessType&&a.searchParams.set("access_type",e.accessType),e.prompt&&a.searchParams.set("prompt",e.prompt),a},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({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:n}=await Lt(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=xt(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 Ct}from"@better-fetch/fetch";import{parseJWT as Dt}from"oslo/jwt";var De=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),A({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:a}){return w({code:n,codeVerifier:i,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=Dt(n.idToken)?.payload,a=e.profilePhotoSize||48;await Ct(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(s){if(!(e.disableProfilePhoto||!s.response.ok))try{let p=await s.response.clone().arrayBuffer(),m=Buffer.from(p).toString("base64");i.picture=`data:image/jpeg;base64, ${m}`}catch(d){x.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0,...c},data:i}}}};import{betterFetch as Nt}from"@better-fetch/fetch";var Ne=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>w({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 Nt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...n},data:r}}});var H={isAction:!1};import{nanoid as Bt}from"nanoid";var K=e=>Bt(e);import{parseJWT as jt}from"oslo/jwt";var Be=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({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 x.error("No idToken found in token"),null;let o=jt(r)?.payload,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...n},data:o}}});import{betterFetch as Vt}from"@better-fetch/fetch";var je=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),A({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})=>w({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 Vt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=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,...n},data:r}}});import{betterFetch as $t}from"@better-fetch/fetch";var Ve=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let a=o||["account_info.read"];return e.scope&&a.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await $t("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=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,...i},data:o}}}};import{betterFetch as Ft}from"@better-fetch/fetch";var $e=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:n,redirectURI:i})=>{let a=n||["profile","email","openid"];return e.scope&&a.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:a,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await w({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await Ft("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(i)return null;let a=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture,...a},data:n}}}};import{betterFetch as qt}from"@better-fetch/fetch";var ge=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),zt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ge(`${t}/oauth/authorize`),tokenEndpoint:ge(`${t}/oauth/token`),userinfoEndpoint:ge(`${t}/api/v4/user`)}},Fe=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=zt(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:a,scopes:c,codeVerifier:s,redirectURI:d})=>{let p=c||["read_user"];return e.scope&&p.push(...e.scope),await A({id:n,options:e,authorizationEndpoint:t,scopes:p,state:a,redirectURI:d,codeVerifier:s})},validateAuthorizationCode:async({code:a,redirectURI:c,codeVerifier:s})=>w({code:a,redirectURI:e.redirectURI||c,options:e,codeVerifier:s,tokenEndpoint:r}),async getUserInfo(a){if(e.getUserInfo)return e.getUserInfo(a);let{data:c,error:s}=await qt(o,{headers:{authorization:`Bearer ${a.accessToken}`}});if(s||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 qe}from"@better-fetch/fetch";var ze=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identity"];return e.scope&&n.push(...e.scope),A({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:n,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}),n={"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:i,error:a}=await qe("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:n,body:o.toString()});if(a)throw a;return se(i)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await qe("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let n=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],...n},data:r}}});var Mt={apple:Pe,discord:Ie,facebook:ve,github:Le,microsoft:De,google:Ce,spotify:Ne,twitch:Be,twitter:je,dropbox:Ve,linkedin:$e,gitlab:Fe,reddit:ze},ae=Object.keys(Mt);import{TimeSpan as Kt}from"oslo";import{createJWT as Qt,validateJWT as Zt}from"oslo/jwt";import{z as L}from"zod";import{APIError as Z}from"better-call";import{APIError as j}from"better-call";import{z}from"zod";function Me(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 He=()=>u("/get-session",{method:"GET",query:z.optional(z.object({disableCookieCache:z.boolean({description:"Disable cookie cache and fetch session from database"}).or(z.string().transform(e=>e==="true")).optional(),disableRefresh: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 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?Me(Buffer.from(r,"base64").toString()):null;if(o&&!await ne.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return N(e),e.json(null);let n=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 y=e.context.authCookies.sessionData.name;e.setCookie(y,"",{maxAge:0})}else return e.json(p)}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return N(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n||e.query?.disableRefresh)return e.json(i);let a=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-a*1e3+c*1e3<=Date.now()){let p=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:q(e.context.sessionConfig.expiresIn,"sec")});if(!p)return N(e),e.json(null,{status:401});let m=(p.expiresAt.valueOf()-Date.now())/1e3;return await _(e,{session:p,user:i.user},!1,{maxAge:m}),e.json({session:p,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new j("INTERNAL_SERVER_ERROR",{message:l.FAILED_TO_GET_SESSION})}}),V=async(e,t)=>{if(e.context.session)return e.context.session;let r=await He()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},O=G(async e=>{let t=await V(e);if(!t?.session)throw new j("UNAUTHORIZED");return{session:t}}),Q=G(async e=>{let t=await V(e);if(!t?.session)throw new j("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 j("FORBIDDEN",{message:"Session is not fresh"});return{session:t}});var Ht=u("/revoke-session",{method:"POST",body:z.object({token:z.string({description:"The token to revoke"})}),use:[O],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 j("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new j("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 j("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Gt=u("/revoke-sessions",{method:"POST",use:[O],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 j("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Wt=u("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[O],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 j("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});async function $(e,t,r){return await Qt("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Kt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Jt(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Z("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await $(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 Yt=u("/send-verification-email",{method:"POST",query:L.object({currentURL:L.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:L.object({email:L.string({description:"The email to send the verification email to"}).email(),callbackURL:L.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 Z("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new Z("BAD_REQUEST",{message:l.USER_NOT_FOUND});return await Jt(e,r.user),e.json({status:!0})}),Xt=u("/verify-email",{method:"GET",query:L.object({token:L.string({description:"The token to verify the email"}),callbackURL:L.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 Z("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 i=L.object({email:L.string().email(),updateTo:L.string().optional()}).parse(o.payload),a=await e.context.internalAdapter.findUserByEmail(i.email);if(!a)return t("user_not_found");if(i.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!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let s=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),d=await $(e.context.secret,i.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:s,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:s,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await V(e)){let s=await e.context.internalAdapter.createSession(a.user.id,e.request);if(!s)throw new Z("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await _(e,{session:s,user:a.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function ce(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(s=>{throw x.error(`Better auth was unable to query your database.
|
|
3
3
|
Error: `,s),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user,a=!i;if(n){let s=n.accounts.find(d=>d.providerId===r.providerId);if(s){let d=Object.fromEntries(Object.entries({accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([p,m])=>m!==void 0));Object.keys(d).length>0&&await e.context.internalAdapter.updateAccount(s.id,d)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return me&&x.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:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope})}catch(m){return x.error("Unable to link account",m),{error:"unable to link account",data:null}}i=await e.context.internalAdapter.updateUser(n.user.id,{...t,updatedAt:new Date})}}else if(i=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(s=>s?.user),!t.emailVerified&&i&&e.context.options.emailVerification?.sendOnSignUp){let s=await $(e.context.secret,i.email),d=`${e.context.baseURL}/verify-email?token=${s}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:d,token:s},e.request)}if(!i)return{error:"unable to create user",data:null,isRegister:!1};let c=await e.context.internalAdapter.createSession(i.id,e.request);return c?{data:{session:c,user:i},error:null,isRegister:a}:{error:"unable to create session",data:null,isRegister:!1}}var er=u("/sign-in/social",{method:"POST",query:R.object({currentURL:R.string().optional()}).optional(),body:R.object({callbackURL:R.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:R.string().optional(),errorCallbackURL:R.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:R.enum(ae,{description:"OAuth2 provider to use"}),disableRedirect:R.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:R.optional(R.object({token:R.string({description:"ID token from the provider"}),nonce:R.string({description:"Nonce used to generate the token"}).optional(),accessToken:R.string({description:"Access token from the provider"}).optional(),refreshToken:R.string({description:"Refresh token from the provider"}).optional(),expiresAt:R.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(i=>i.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 k("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 k("NOT_FOUND",{message:l.ID_TOKEN_NOT_SUPPORTED});let{token:i,nonce:a}=e.body.idToken;if(!await t.verifyIdToken(i,a))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new k("UNAUTHORIZED",{message:l.INVALID_TOKEN});let s=await t.getUserInfo({idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!s||!s?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new k("UNAUTHORIZED",{message:l.FAILED_TO_GET_USER_INFO});if(!s.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new k("UNAUTHORIZED",{message:l.USER_EMAIL_NOT_FOUND});let d=await ce(e,{userInfo:{email:s.user.email,id:s.user.id,name:s.user.name||"",image:s.user.image,emailVerified:s.user.emailVerified||!1},account:{providerId:t.id,accountId:s.user.id,accessToken:e.body.idToken.accessToken}});if(d.error)throw new k("UNAUTHORIZED",{message:d.error});return await _(e,d.data),e.json({session:d.data.session,user:d.data.user,url:void 0,redirect:!1})}let{codeVerifier:r,state:o}=await ie(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),tr=u("/sign-in/email",{method:"POST",body:R.object({email:R.string({description:"Email of the user"}),password:R.string({description:"Password of the user"}),callbackURL:R.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:R.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 k("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!R.string().email().safeParse(t).success)throw new k("BAD_REQUEST",{message:l.INVALID_EMAIL});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new k("UNAUTHORIZED",{message:l.INVALID_EMAIL_OR_PASSWORD});let i=n.accounts.find(d=>d.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new k("UNAUTHORIZED",{message:l.INVALID_EMAIL_OR_PASSWORD});let a=i?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new k("UNAUTHORIZED",{message:l.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:a,password:r}))throw e.context.logger.error("Invalid password"),new k("UNAUTHORIZED",{message:l.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new k("UNAUTHORIZED",{message:l.EMAIL_NOT_VERIFIED});let d=await $(e.context.secret,n.user.email),p=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:p,token:d},e.request),e.context.logger.error("Email not verified",{email:t}),new k("FORBIDDEN",{message:l.EMAIL_NOT_VERIFIED})}let s=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!s)throw e.context.logger.error("Failed to create session"),new k("UNAUTHORIZED",{message:l.FAILED_TO_CREATE_SESSION});return await _(e,{session:s,user:n.user},e.body.rememberMe===!1),e.json({user:{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},redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as J}from"zod";var de=J.object({code:J.string().optional(),error:J.string().optional(),error_description:J.string().optional(),state:J.string().optional()}),rr=u("/callback/:id",{method:["GET","POST"],body:de.optional(),query:de.optional(),metadata:H},async e=>{let t;try{if(e.method==="GET")t=de.parse(e.query);else if(e.method==="POST")t=de.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:n,error_description:i}=t;if(!n)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=${i}`);let a=e.context.socialProviders.find(T=>T.id===e.params.id);if(!a)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:s,link:d,errorURL:p,newUserURL:m}=await Se(e),y;try{y=await a.validateAuthorizationCode({code:r,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${a.id}`})}catch(T){throw e.context.logger.error("",T),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let h=await a.getUserInfo(y).then(T=>T?.user);function f(T){let P=p||s||`${e.context.baseURL}/error`;throw P.includes("?")?P=`${P}&error=${T}`:P=`${P}?error=${T}`,e.redirect(P)}if(!h)return e.context.logger.error("Unable to get user info"),f("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."),f("email_not_found");if(!s)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 f("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:a.id,accountId:h.id}))return f("unable_to_link_account");let P;try{P=s.toString()}catch{P=s}throw e.redirect(P)}let b=await ce(e,{userInfo:{...h,email:h.email,name:h.name||h.email},account:{providerId:a.id,accountId:h.id,...y,scope:y.scopes?.join(",")},callbackURL:s});if(b.error)return e.context.logger.error(b.error.split(" ").join("_")),f(b.error.split(" ").join("_"));let{session:M,user:C}=b.data;await _(e,{session:M,user:C});let F;try{F=(b.isRegister&&m||s).toString()}catch{F=b.isRegister&&m||s}throw e.redirect(F)});import"zod";import{APIError as or}from"better-call";var nr=u("/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 N(e),new or("BAD_REQUEST",{message:l.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(t),N(e),e.json({success:!0})});import{z as I}from"zod";import{APIError as Y}from"better-call";function Ge(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function sr(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var ir=u("/forget-password",{method:"POST",body:I.object({email:I.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:I.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 Y("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=q(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),a=K(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${a}`,expiresAt:i});let c=`${e.context.baseURL}/reset-password/${a}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:c,token:a},e.request),e.json({status:!0})}),ar=u("/reset-password/:token",{method:"GET",query:I.object({callbackURL:I.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(Ge(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Ge(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(sr(e.context,r,{token:t}))}),cr=u("/reset-password",{query:I.optional(I.object({token:I.string().optional(),currentURL:I.string().optional()})),method:"POST",body:I.object({newPassword:I.string({description:"The new password to set"}),token:I.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 Y("BAD_REQUEST",{message:l.INVALID_TOKEN});let{newPassword:r}=e.body,o=e.context.password?.config.minPasswordLength,n=e.context.password?.config.maxPasswordLength;if(r.length<o)throw new Y("BAD_REQUEST",{message:l.PASSWORD_TOO_SHORT});if(r.length>n)throw new Y("BAD_REQUEST",{message:l.PASSWORD_TOO_LONG});let i=`reset-password:${t}`,a=await e.context.internalAdapter.findVerificationValue(i);if(!a||a.expiresAt<new Date)throw new Y("BAD_REQUEST",{message:l.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(a.id);let c=a.value,s=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(c)).find(m=>m.providerId==="credential")?(await e.context.internalAdapter.updatePassword(c,s),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:c,providerId:"credential",password:s,accountId:c}),e.json({status:!0}))});import{z as S}from"zod";import{APIError as E}from"better-call";import{z as g}from"zod";import{APIError as hi}from"better-call";var yi=g.object({id:g.string(),providerId:g.string(),accountId:g.string(),userId:g.string(),accessToken:g.string().nullish(),refreshToken:g.string().nullish(),idToken:g.string().nullish(),accessTokenExpiresAt:g.date().nullish(),refreshTokenExpiresAt:g.date().nullish(),scope:g.string().nullish(),password:g.string().nullish(),createdAt:g.date().default(()=>new Date),updatedAt:g.date().default(()=>new Date)}),wi=g.object({id:g.string(),email:g.string().transform(e=>e.toLowerCase()),emailVerified:g.boolean().default(!1),name:g.string(),image:g.string().nullish(),createdAt:g.date().default(()=>new Date),updatedAt:g.date().default(()=>new Date)}),bi=g.object({id:g.string(),userId:g.string(),expiresAt:g.date(),createdAt:g.date().default(()=>new Date),updatedAt:g.date().default(()=>new Date),token:g.string(),ipAddress:g.string().nullish(),userAgent:g.string().nullish()}),Ai=g.object({id:g.string(),value:g.string(),createdAt:g.date().default(()=>new Date),updatedAt:g.date().default(()=>new Date),expiresAt:g.date(),identifier:g.string()});function We(e,t){if(!t)return e;for(let r in t){let o=t[r]?.modelName;o&&(e[r].modelName=o);for(let n in e[r].fields){let i=t[r]?.fields?.[n];i&&(e[r].fields[n].fieldName=i)}}return e}import{xchacha20poly1305 as xi}from"@noble/ciphers/chacha";import{bytesToHex as Ci,hexToBytes as Di,utf8ToBytes as Ni}from"@noble/ciphers/utils";import{managedNonce as ji}from"@noble/ciphers/webcrypto";import{sha256 as $i}from"oslo/crypto";import qi from"uncrypto";import{decodeHex as ki,encodeHex as Ti}from"oslo/encoding";import{scryptAsync as Ui}from"@noble/hashes/scrypt";import{getRandomValues as Pi}from"uncrypto";var pr=u("/change-password",{method:"POST",body:S.object({newPassword:S.string({description:"The new password to set"}),currentPassword:S.string({description:"The current password"}),revokeOtherSessions:S.boolean({description:"Revoke all other sessions"}).optional()}),use:[O],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,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new E("BAD_REQUEST",{message:l.PASSWORD_TOO_SHORT});let a=e.context.password.config.maxPasswordLength;if(t.length>a)throw e.context.logger.error("Password is too long"),new E("BAD_REQUEST",{message:l.PASSWORD_TOO_LONG});let s=(await e.context.internalAdapter.findAccounts(n.user.id)).find(m=>m.providerId==="credential"&&m.password);if(!s||!s.password)throw new E("BAD_REQUEST",{message:l.CREDENTIAL_ACCOUNT_NOT_FOUND});let d=await e.context.password.hash(t);if(!await e.context.password.verify({hash:s.password,password:r}))throw new E("BAD_REQUEST",{message:l.INVALID_PASSWORD});if(await e.context.internalAdapter.updateAccount(s.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let m=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!m)throw new E("INTERNAL_SERVER_ERROR",{message:l.FAILED_TO_GET_SESSION});await _(e,{session:m,user:n.user})}return e.json(n.user)}),ur=u("/set-password",{method:"POST",body:S.object({newPassword:S.string()}),metadata:{SERVER_ONLY:!0},use:[O]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new E("BAD_REQUEST",{message:l.PASSWORD_TOO_SHORT});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new E("BAD_REQUEST",{message:l.PASSWORD_TOO_LONG});let a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password),c=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:c}),e.json(r.user);throw new E("BAD_REQUEST",{message:"user already has a password"})}),lr=u("/delete-user",{method:"POST",use:[Q],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 E("NOT_FOUND");let t=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=ee(32,te("a-z","A-Z","0-9"));await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${n}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let i=`${e.context.baseURL}/delete-user/callback?token=${n}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:i,token:n},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),N(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})}),mr=u("/delete-user/callback",{method:"GET",query:S.object({token:S.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 E("NOT_FOUND");let t=await V(e);if(!t)throw new E("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 E("NOT_FOUND",{message:l.INVALID_TOKEN});if(r.value!==t.user.id)throw new E("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),N(e);let n=e.context.options.user.deleteUser?.afterDelete;return n&&await n(t.user,e.request),e.json({success:!0,message:"User deleted"})}),fr=u("/change-email",{method:"POST",query:S.object({currentURL:S.string().optional()}).optional(),body:S.object({newEmail:S.string({description:"The new email to set"}).email(),callbackURL:S.string({description:"The URL to redirect to after email verification"}).optional()}),use:[O],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 E("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new E("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new E("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await $(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 gr=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|