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