better-auth 1.0.9 → 1.0.10-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.cjs +1 -1
- package/dist/api.js +1 -1
- package/dist/client/plugins.d.cts +2 -2
- package/dist/client/plugins.d.ts +2 -2
- package/dist/cookies.cjs +1 -1
- package/dist/cookies.js +1 -1
- package/dist/{index-Csy_I_xy.d.cts → index-0hpBrZ7U.d.cts} +90 -27
- package/dist/{index-BQgUxef7.d.ts → index-B7qPPh4o.d.ts} +90 -27
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/next-js.cjs +1 -1
- package/dist/next-js.js +1 -1
- package/dist/plugins.cjs +4 -4
- package/dist/plugins.d.cts +1 -1
- package/dist/plugins.d.ts +1 -1
- package/dist/plugins.js +5 -5
- package/package.json +2 -2
package/dist/api.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use strict";var Yt=Object.create;var X=Object.defineProperty;var Xt=Object.getOwnPropertyDescriptor;var er=Object.getOwnPropertyNames;var tr=Object.getPrototypeOf,rr=Object.prototype.hasOwnProperty;var or=(e,t)=>{for(var r in t)X(e,r,{get:t[r],enumerable:!0})},Ze=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of er(t))!rr.call(e,i)&&i!==r&&X(e,i,{get:()=>t[i],enumerable:!(o=Xt(t,i))||o.enumerable});return e};var Qe=(e,t,r)=>(r=e!=null?Yt(tr(e)):{},Ze(t||!e||!e.__esModule?X(r,"default",{value:e,enumerable:!0}):r,e)),nr=e=>Ze(X({},"__esModule",{value:!0}),e);var jr={};or(jr,{APIError:()=>Kt.APIError,callbackOAuth:()=>Pe,changeEmail:()=>Ne,changePassword:()=>je,createAuthEndpoint:()=>f,createAuthMiddleware:()=>G,createEmailVerificationToken:()=>j,deleteUser:()=>Ve,deleteUserCallback:()=>ze,error:()=>$e,forgetPassword:()=>Se,forgetPasswordCallback:()=>Ie,freshSessionMiddleware:()=>be,getEndpoints:()=>Wt,getSession:()=>se,getSessionFromCtx:()=>$,linkSocialAccount:()=>Ge,listSessions:()=>ke,listUserAccounts:()=>He,ok:()=>qe,optionsMiddleware:()=>ue,originCheckMiddleware:()=>me,resetPassword:()=>Le,revokeOtherSessions:()=>Re,revokeSession:()=>Ae,revokeSessions:()=>Ue,router:()=>Dr,sendVerificationEmail:()=>ve,sendVerificationEmailFn:()=>zt,sessionMiddleware:()=>_,setPassword:()=>Be,signInEmail:()=>xe,signInSocial:()=>Te,signOut:()=>_e,signUpEmail:()=>Fe,updateUser:()=>De,verifyEmail:()=>Ee});module.exports=nr(jr);var v=require("better-call");var Je=require("better-call");var q=require("better-call"),ue=(0,q.createMiddleware)(async()=>({})),G=(0,q.createMiddlewareCreator)({use:[ue,(0,q.createMiddleware)(async()=>({}))]}),f=(0,q.createEndpointCreator)({use:[ue]});var me=G(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,i=e.headers?.get("origin")||e.headers?.get("referer")||"",n=t?.callbackURL||r?.callbackURL,s=t?.redirectTo,c=r?.currentURL,a=o.trustedOrigins,d=e.headers?.has("cookie"),p=(l,w)=>w.includes("*")?new RegExp("^"+w.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(l):l.startsWith(w),m=(l,w)=>{if(!l)return;if(!a.some(I=>p(l,I)||l?.startsWith("/")&&w!=="origin"&&!l.includes(":")))throw e.context.logger.error(`Invalid ${w}: ${l}`),e.context.logger.info(`If it's a valid URL, please add ${l} to trustedOrigins in your auth config
|
|
2
|
-
`,`Current list of trustedOrigins: ${a}`),new Je.APIError("FORBIDDEN",{message:`Invalid ${w}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&m(i,"origin"),n&&m(n,"callbackURL"),s&&m(s,"redirectURL"),c&&m(c,"currentURL")});var T=require("better-call"),A=require("zod");var dr=require("oslo"),Xe=require("oslo/encoding");var ee=require("oslo/crypto");async function sr({value:e,secret:t}){return new ee.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function ar({value:e,signature:t,secret:r}){return new ee.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var te={sign:sr,verify:ar};var F=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};var N=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var re=Object.create(null),Y=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?re:globalThis),We=new Proxy(re,{get(e,t){return Y()[t]??re[t]},has(e,t){let r=Y();return t in r||t in re},set(e,t,r){let o=Y(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=Y(!0);return delete r[t],!0},ownKeys(){let e=Y(!0);return Object.keys(e)}});function cr(e){return e?e!=="false":!1}var fe=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Ke=fe==="dev"||fe==="development",Ye=fe==="test"||cr(We.TEST);async function x(e,t,r,o){let i=e.context.authCookies.sessionToken.options,n=r?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Xe.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:N(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await te.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3))}function C(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}var at=require("@better-fetch/fetch"),ct=require("better-call"),Z=require("jose"),dt=require("oslo/jwt");var et=require("oslo/crypto"),tt=require("oslo/encoding");async function rt(e){let t=await(0,et.sha256)(new TextEncoder().encode(e));return tt.base64url.encode(new Uint8Array(t),{includePadding:!1})}function ot(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?N(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function U({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:s,redirectURI:c}){let a=new URL(r);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",t.clientId),a.searchParams.set("state",o),a.searchParams.set("scope",n.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||c),i){let d=await rt(i);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",d)}if(s){let d=s.reduce((p,m)=>(p[m]=null,p),{});a.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...d}}))}return a}var nt=require("@better-fetch/fetch");async function b({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i,authentication:n}){let s=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),n==="basic"){let m=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${m}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await(0,nt.betterFetch)(i,{method:"POST",body:s,headers:c});if(d)throw d;return ot(a)}var oe=require("oslo/oauth2"),z=require("zod"),ge=require("better-call");function it(e){try{return new URL(e).origin}catch{return null}}async function ne(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?it(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ge.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,oe.generateCodeVerifier)(),i=(0,oe.generateState)(),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:s});if(!c)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ge.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function st(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=z.z.object({callbackURL:z.z.string(),codeVerifier:z.z.string(),errorURL:z.z.string().optional(),expiresAt:z.z.number(),link:z.z.object({email:z.z.string(),userId:z.z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var lt=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=o||["email","name"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let i=(0,Z.decodeProtectedHeader)(r),{kid:n,alg:s}=i;if(!n||!s)return!1;let c=await lr(n),{payload:a}=await(0,Z.jwtVerify)(r,c,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=(0,dt.parseJWT)(r.idToken)?.payload;if(!o)return null;let i=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:i,emailVerified:!1,email:o.email,...n},data:o}}}},lr=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,at.betterFetch)(`${t}${r}`);if(!o?.keys)throw new ct.APIError("BAD_REQUEST",{message:"Keys not found"});let i=o.keys.find(n=>n.kid===e);if(!i)throw new Error(`JWK with kid ${e} not found`);return await(0,Z.importJWK)(i,i.alg)};var pt=require("@better-fetch/fetch");var ut=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,pt.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...i},data:r}}});var mt=require("@better-fetch/fetch");var ft=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await U({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,mt.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...i},data:r}}});var he=require("@better-fetch/fetch");var gt=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),U({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>b({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await(0,he.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:c,error:a}=await(0,he.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(c.find(d=>d.primary)??c[0])?.email,n=c.find(d=>d.email===o.email)?.verified??!1)}let s=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n,...s},data:o}}}};var wt=require("oslo/jwt");var ht=require("consola"),we=["info","success","warn","error","debug"];function pr(e,t){return we.indexOf(t)<=we.indexOf(e)}var ur=(0,ht.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),mr=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(i,n,s=[])=>{if(!(!t||!pr(r,i))){if(!e||typeof e.log!="function"){ur[i]("",n,...s);return}e.log(i==="success"?"info":i,n,s)}};return Object.fromEntries(we.map(i=>[i,(...[n,...s])=>o(i,n,s)]))},P=mr();var yt=require("@better-fetch/fetch"),bt=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw P.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(!o)throw new F("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await U({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:i}=await(0,yt.betterFetch)(o);return i?i.aud===e.clientId&&i.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,wt.parseJWT)(t.idToken)?.payload,o=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...o},data:r}}});var kt=require("@better-fetch/fetch"),At=require("oslo/jwt");var Ut=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),U({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return b({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);if(!i.idToken)return null;let n=(0,At.parseJWT)(i.idToken)?.payload,s=e.profilePhotoSize||48;await(0,kt.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let p=await a.response.clone().arrayBuffer(),m=Buffer.from(p).toString("base64");n.picture=`data:image/jpeg;base64, ${m}`}catch(d){P.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0,...c},data:n}}}};var Rt=require("@better-fetch/fetch");var vt=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),U({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,Rt.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...i},data:r}}});var Q={isAction:!1};var Et=require("nanoid"),Tt=e=>(0,Et.nanoid)(e);var xt=require("oslo/jwt");var Pt=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),U({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return P.error("No idToken found in token"),null;let o=(0,xt.parseJWT)(r)?.payload,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...i},data:o}}});var _t=require("@better-fetch/fetch");var St=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),U({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,_t.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.data.id,name:r.data.name,email:r.data.username||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1,...i},data:r}}});var It=require("@better-fetch/fetch");var Lt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await U({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await b({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await(0,It.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...n},data:o}}}};var Ot=require("@better-fetch/fetch");var Ct=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await U({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await b({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await(0,Ot.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(n)return null;let s=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture,...s},data:i}}}};var Dt=require("@better-fetch/fetch");var ye=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),fr=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ye(`${t}/oauth/authorize`),tokenEndpoint:ye(`${t}/oauth/token`),userinfoEndpoint:ye(`${t}/api/v4/user`)}},jt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=fr(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let p=c||["read_user"];return e.scope&&p.push(...e.scope),await U({id:i,options:e,authorizationEndpoint:t,scopes:p,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>b({code:s,redirectURI:e.redirectURI||c,options:e,codeVerifier:a,tokenEndpoint:r}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:c,error:a}=await(0,Dt.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(a||c.state!=="active"||c.locked)return null;let d=await e.mapProfileToUser?.(c);return{user:{id:c.id.toString(),name:c.name??c.username,email:c.email,image:c.avatar_url,emailVerified:!0,...d},data:c}}}};var gr={apple:lt,discord:ut,facebook:ft,github:gt,microsoft:Ut,google:bt,spotify:vt,twitch:Pt,twitter:St,dropbox:Lt,linkedin:Ct,gitlab:jt},ie=Object.keys(gr);var Vt=require("oslo"),ae=require("oslo/jwt"),L=require("zod");var J=require("better-call");var D=require("better-call");var M=require("zod");function Bt(e){try{return JSON.parse(e)}catch{return null}}var se=()=>f("/get-session",{method:"GET",query:M.z.optional(M.z.object({disableCookieCache:M.z.boolean({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:M.z.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?Bt(Buffer.from(r,"base64").toString()):null;if(o&&!await te.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return C(e),e.json(null);let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let p=o.session;if(o.expiresAt<Date.now()||p.session.expiresAt<new Date){let l=e.context.authCookies.sessionData.name;e.setCookie(l,"",{maxAge:0})}else return e.json(p)}let n=await e.context.internalAdapter.findSession(t);if(e.context.session=n,!n||n.session.expiresAt<new Date)return C(e),n&&await e.context.internalAdapter.deleteSession(n.session.token),e.json(null);if(i||e.query?.disableRefresh)return e.json(n);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let p=await e.context.internalAdapter.updateSession(n.session.token,{expiresAt:N(e.context.sessionConfig.expiresIn,"sec")});if(!p)return C(e),e.json(null,{status:401});let m=(p.expiresAt.valueOf()-Date.now())/1e3;return await x(e,{session:p,user:n.user},!1,{maxAge:m}),e.json({session:p,user:n.user})}return e.json(n)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new D.APIError("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),$=async(e,t)=>{if(e.context.session)return e.context.session;e.query={...e.query,...t};let r=await se()({...e,_flag:"json",headers:e.headers});return e.context.session=r,r},_=G(async e=>{let t=await $(e);if(!t?.session)throw new D.APIError("UNAUTHORIZED");return{session:t}}),be=G(async e=>{let t=await $(e);if(!t?.session)throw new D.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),i=Date.now();if(!(o+r*1e3>i))throw new D.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),ke=()=>f("/list-sessions",{method:"GET",use:[_],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Ae=f("/revoke-session",{method:"POST",body:M.z.object({token:M.z.string({description:"The token to revoke"})}),use:[_],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let t=e.body.token,r=await e.context.internalAdapter.findSession(t);if(!r)throw new D.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new D.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new D.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Ue=f("/revoke-sessions",{method:"POST",use:[_],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new D.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Re=f("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[_],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw new D.APIError("UNAUTHORIZED");let i=(await e.context.internalAdapter.listSessions(t.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.token!==e.context.session.session.token);return await Promise.all(i.map(n=>e.context.internalAdapter.deleteSession(n.token))),e.json({status:!0})});async function j(e,t,r){return await(0,ae.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Vt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function zt(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(e.context.secret,t.email),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:r},e.request)}var ve=f("/send-verification-email",{method:"POST",query:L.z.object({currentURL:L.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:L.z.object({email:L.z.string({description:"The email to send the verification email to"}).email(),callbackURL:L.z.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new J.APIError("BAD_REQUEST",{message:"User not found"});return await zt(e,r.user),e.json({status:!0})}),Ee=f("/verify-email",{method:"GET",query:L.z.object({token:L.z.string({description:"The token to verify the email"}),callbackURL:L.z.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(c){throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=${c}`):new J.APIError("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await(0,ae.validateJWT)("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let n=L.z.object({email:L.z.string().email(),updateTo:L.z.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(n.email);if(!s)return t("user_not_found");if(n.updateTo){let c=await $(e);if(!c){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(c.user.email!==n.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${r}`,token:r},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await $(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new J.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await x(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function ce(e,{userInfo:t,account:r,callbackURL:o}){let i=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(c=>{throw P.error(`Better auth was unable to query your database.
|
|
2
|
+
`,`Current list of trustedOrigins: ${a}`),new Je.APIError("FORBIDDEN",{message:`Invalid ${w}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&m(i,"origin"),n&&m(n,"callbackURL"),s&&m(s,"redirectURL"),c&&m(c,"currentURL")});var T=require("better-call"),A=require("zod");var dr=require("oslo"),Xe=require("oslo/encoding");var ee=require("oslo/crypto");async function sr({value:e,secret:t}){return new ee.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function ar({value:e,signature:t,secret:r}){return new ee.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var te={sign:sr,verify:ar};var F=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};var N=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var re=Object.create(null),Y=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?re:globalThis),We=new Proxy(re,{get(e,t){return Y()[t]??re[t]},has(e,t){let r=Y();return t in r||t in re},set(e,t,r){let o=Y(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=Y(!0);return delete r[t],!0},ownKeys(){let e=Y(!0);return Object.keys(e)}});function cr(e){return e?e!=="false":!1}var fe=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Ke=fe==="dev"||fe==="development",Ye=fe==="test"||cr(We.TEST);async function x(e,t,r,o){let i=e.context.authCookies.sessionToken.options,n=r?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Xe.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:N(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await te.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3))}function C(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}var at=require("@better-fetch/fetch"),ct=require("better-call"),Z=require("jose"),dt=require("oslo/jwt");var et=require("oslo/crypto"),tt=require("oslo/encoding");async function rt(e){let t=await(0,et.sha256)(new TextEncoder().encode(e));return tt.base64url.encode(new Uint8Array(t),{includePadding:!1})}function ot(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?N(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function U({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:s,redirectURI:c}){let a=new URL(r);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",t.clientId),a.searchParams.set("state",o),a.searchParams.set("scope",n.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||c),i){let d=await rt(i);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",d)}if(s){let d=s.reduce((p,m)=>(p[m]=null,p),{});a.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...d}}))}return a}var nt=require("@better-fetch/fetch");async function b({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i,authentication:n}){let s=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),n==="basic"){let m=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${m}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await(0,nt.betterFetch)(i,{method:"POST",body:s,headers:c});if(d)throw d;return ot(a)}var oe=require("oslo/oauth2"),z=require("zod"),ge=require("better-call");function it(e){try{return new URL(e).origin}catch{return null}}async function ne(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?it(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ge.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,oe.generateCodeVerifier)(),i=(0,oe.generateState)(),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:s});if(!c)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ge.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function st(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=z.z.object({callbackURL:z.z.string(),codeVerifier:z.z.string(),errorURL:z.z.string().optional(),expiresAt:z.z.number(),link:z.z.object({email:z.z.string(),userId:z.z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var lt=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=o||["email","name"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let i=(0,Z.decodeProtectedHeader)(r),{kid:n,alg:s}=i;if(!n||!s)return!1;let c=await lr(n),{payload:a}=await(0,Z.jwtVerify)(r,c,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=(0,dt.parseJWT)(r.idToken)?.payload;if(!o)return null;let i=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:i,emailVerified:!1,email:o.email,...n},data:o}}}},lr=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,at.betterFetch)(`${t}${r}`);if(!o?.keys)throw new ct.APIError("BAD_REQUEST",{message:"Keys not found"});let i=o.keys.find(n=>n.kid===e);if(!i)throw new Error(`JWK with kid ${e} not found`);return await(0,Z.importJWK)(i,i.alg)};var pt=require("@better-fetch/fetch");var ut=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,pt.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...i},data:r}}});var mt=require("@better-fetch/fetch");var ft=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await U({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,mt.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...i},data:r}}});var he=require("@better-fetch/fetch");var gt=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),U({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>b({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await(0,he.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:c,error:a}=await(0,he.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(c.find(d=>d.primary)??c[0])?.email,n=c.find(d=>d.email===o.email)?.verified??!1)}let s=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n,...s},data:o}}}};var wt=require("oslo/jwt");var ht=require("consola"),we=["info","success","warn","error","debug"];function pr(e,t){return we.indexOf(t)<=we.indexOf(e)}var ur=(0,ht.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),mr=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(i,n,s=[])=>{if(!(!t||!pr(r,i))){if(!e||typeof e.log!="function"){ur[i]("",n,...s);return}e.log(i==="success"?"info":i,n,s)}};return Object.fromEntries(we.map(i=>[i,(...[n,...s])=>o(i,n,s)]))},P=mr();var yt=require("@better-fetch/fetch"),bt=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw P.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(!o)throw new F("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await U({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:i}=await(0,yt.betterFetch)(o);return i?i.aud===e.clientId&&i.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,wt.parseJWT)(t.idToken)?.payload,o=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...o},data:r}}});var kt=require("@better-fetch/fetch"),At=require("oslo/jwt");var Ut=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),U({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return b({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);if(!i.idToken)return null;let n=(0,At.parseJWT)(i.idToken)?.payload,s=e.profilePhotoSize||48;await(0,kt.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let p=await a.response.clone().arrayBuffer(),m=Buffer.from(p).toString("base64");n.picture=`data:image/jpeg;base64, ${m}`}catch(d){P.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0,...c},data:n}}}};var Rt=require("@better-fetch/fetch");var vt=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),U({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,Rt.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...i},data:r}}});var Q={isAction:!1};var Et=require("nanoid"),Tt=e=>(0,Et.nanoid)(e);var xt=require("oslo/jwt");var Pt=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),U({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return P.error("No idToken found in token"),null;let o=(0,xt.parseJWT)(r)?.payload,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...i},data:o}}});var _t=require("@better-fetch/fetch");var St=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),U({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,_t.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.data.id,name:r.data.name,email:r.data.username||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1,...i},data:r}}});var It=require("@better-fetch/fetch");var Lt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await U({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await b({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await(0,It.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...n},data:o}}}};var Ot=require("@better-fetch/fetch");var Ct=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await U({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await b({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await(0,Ot.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(n)return null;let s=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture,...s},data:i}}}};var Dt=require("@better-fetch/fetch");var ye=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),fr=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ye(`${t}/oauth/authorize`),tokenEndpoint:ye(`${t}/oauth/token`),userinfoEndpoint:ye(`${t}/api/v4/user`)}},jt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=fr(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let p=c||["read_user"];return e.scope&&p.push(...e.scope),await U({id:i,options:e,authorizationEndpoint:t,scopes:p,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>b({code:s,redirectURI:e.redirectURI||c,options:e,codeVerifier:a,tokenEndpoint:r}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:c,error:a}=await(0,Dt.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(a||c.state!=="active"||c.locked)return null;let d=await e.mapProfileToUser?.(c);return{user:{id:c.id.toString(),name:c.name??c.username,email:c.email,image:c.avatar_url,emailVerified:!0,...d},data:c}}}};var gr={apple:lt,discord:ut,facebook:ft,github:gt,microsoft:Ut,google:bt,spotify:vt,twitch:Pt,twitter:St,dropbox:Lt,linkedin:Ct,gitlab:jt},ie=Object.keys(gr);var Vt=require("oslo"),ae=require("oslo/jwt"),L=require("zod");var J=require("better-call");var D=require("better-call");var M=require("zod");function Bt(e){try{return JSON.parse(e)}catch{return null}}var se=()=>f("/get-session",{method:"GET",query:M.z.optional(M.z.object({disableCookieCache:M.z.boolean({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:M.z.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?Bt(Buffer.from(r,"base64").toString()):null;if(o&&!await te.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return C(e),e.json(null);let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let p=o.session;if(o.expiresAt<Date.now()||p.session.expiresAt<new Date){let l=e.context.authCookies.sessionData.name;e.setCookie(l,"",{maxAge:0})}else return e.json(p)}let n=await e.context.internalAdapter.findSession(t);if(e.context.session=n,!n||n.session.expiresAt<new Date)return C(e),n&&await e.context.internalAdapter.deleteSession(n.session.token),e.json(null);if(i||e.query?.disableRefresh)return e.json(n);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let p=await e.context.internalAdapter.updateSession(n.session.token,{expiresAt:N(e.context.sessionConfig.expiresIn,"sec")});if(!p)return C(e),e.json(null,{status:401});let m=(p.expiresAt.valueOf()-Date.now())/1e3;return await x(e,{session:p,user:n.user},!1,{maxAge:m}),e.json({session:p,user:n.user})}return e.json(n)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new D.APIError("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),$=async(e,t)=>{if(e.context.session)return e.context.session;let r=await se()({...e,_flag:"json",headers:e.headers,query:t});return e.context.session=r,r},_=G(async e=>{let t=await $(e);if(!t?.session)throw new D.APIError("UNAUTHORIZED");return{session:t}}),be=G(async e=>{let t=await $(e);if(!t?.session)throw new D.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),i=Date.now();if(!(o+r*1e3>i))throw new D.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),ke=()=>f("/list-sessions",{method:"GET",use:[_],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Ae=f("/revoke-session",{method:"POST",body:M.z.object({token:M.z.string({description:"The token to revoke"})}),use:[_],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let t=e.body.token,r=await e.context.internalAdapter.findSession(t);if(!r)throw new D.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new D.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new D.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Ue=f("/revoke-sessions",{method:"POST",use:[_],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new D.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Re=f("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[_],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw new D.APIError("UNAUTHORIZED");let i=(await e.context.internalAdapter.listSessions(t.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.token!==e.context.session.session.token);return await Promise.all(i.map(n=>e.context.internalAdapter.deleteSession(n.token))),e.json({status:!0})});async function j(e,t,r){return await(0,ae.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Vt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function zt(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(e.context.secret,t.email),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:r},e.request)}var ve=f("/send-verification-email",{method:"POST",query:L.z.object({currentURL:L.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:L.z.object({email:L.z.string({description:"The email to send the verification email to"}).email(),callbackURL:L.z.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new J.APIError("BAD_REQUEST",{message:"User not found"});return await zt(e,r.user),e.json({status:!0})}),Ee=f("/verify-email",{method:"GET",query:L.z.object({token:L.z.string({description:"The token to verify the email"}),callbackURL:L.z.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(c){throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=${c}`):new J.APIError("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await(0,ae.validateJWT)("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let n=L.z.object({email:L.z.string().email(),updateTo:L.z.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(n.email);if(!s)return t("user_not_found");if(n.updateTo){let c=await $(e);if(!c){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(c.user.email!==n.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${r}`,token:r},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await $(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new J.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await x(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function ce(e,{userInfo:t,account:r,callbackURL:o}){let i=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(c=>{throw P.error(`Better auth was unable to query your database.
|
|
3
3
|
Error: `,c),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=i?.user;if(i){let c=i.accounts.find(a=>a.providerId===r.providerId);if(c){let a=Object.fromEntries(Object.entries({accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([d,p])=>p!==void 0));Object.keys(a).length>0&&await e.context.internalAdapter.updateAccount(c.id,a)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Ke&&P.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),userId:i.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope})}catch(p){return P.error("Unable to link account",p),{error:"unable to link account",data:null}}}}else try{if(n=await e.context.internalAdapter.createOAuthUser({...t,id:void 0},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:t.id.toString()}).then(c=>c?.user),!t.emailVerified&&n&&e.context.options.emailVerification?.sendOnSignUp){let c=await j(e.context.secret,n.email),a=`${e.context.baseURL}/verify-email?token=${c}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:n,url:a,token:c},e.request)}}catch(c){return P.error("Unable to create user",c),{error:"unable to create user",data:null}}if(!n)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(n.id,e.request);return s?{data:{session:s,user:n},error:null}:{error:"unable to create session",data:null}}var Te=f("/sign-in/social",{method:"POST",query:A.z.object({currentURL:A.z.string().optional()}).optional(),body:A.z.object({callbackURL:A.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),errorCallbackURL:A.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:A.z.enum(ie,{description:"OAuth2 provider to use"}),disableRedirect:A.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:A.z.optional(A.z.object({token:A.z.string({description:"ID token from the provider"}),nonce:A.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:A.z.string({description:"Access token from the provider"}).optional(),refreshToken:A.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:A.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new T.APIError("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new T.APIError("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:n,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(n,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new T.APIError("UNAUTHORIZED",{message:"Invalid id token"});let a=await t.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new T.APIError("UNAUTHORIZED",{message:"Failed to get user info"});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new T.APIError("UNAUTHORIZED",{message:"User email not found"});let d=await ce(e,{userInfo:{email:a.user.email,id:a.user.id,name:a.user.name||"",image:a.user.image,emailVerified:a.user.emailVerified||!1},account:{providerId:t.id,accountId:a.user.id,accessToken:e.body.idToken.accessToken}});if(d.error)throw new T.APIError("UNAUTHORIZED",{message:d.error});return await x(e,d.data),e.json({session:d.data.session,user:d.data.user,url:void 0,redirect:!1})}let{codeVerifier:r,state:o}=await ne(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!e.body.disableRedirect})}),xe=f("/sign-in/email",{method:"POST",body:A.z.object({email:A.z.string({description:"Email of the user"}),password:A.z.string({description:"Password of the user"}),callbackURL:A.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:A.z.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new T.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!A.z.string().email().safeParse(t).success)throw new T.APIError("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new T.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let n=i.accounts.find(d=>d.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new T.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=n?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new T.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new T.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new T.APIError("UNAUTHORIZED",{message:"Email is not verified."});let d=await j(e.context.secret,i.user.email),p=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:i.user,url:p,token:d},e.request),e.context.logger.error("Email not verified",{email:t}),new T.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let a=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new T.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await x(e,{session:a,user:i.user},e.body.rememberMe===!1),e.json({user:i.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var W=require("zod");var de=W.z.object({code:W.z.string().optional(),error:W.z.string().optional(),errorMessage:W.z.string().optional(),state:W.z.string().optional()}),Pe=f("/callback/:id",{method:["GET","POST"],body:de.optional(),query:de.optional(),metadata:Q},async e=>{let t;try{if(e.method==="GET")t=de.parse(e.query);else if(e.method==="POST")t=de.parse(e.body);else throw new Error("Unsupported method")}catch(g){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",g),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:i}=t;if(!i)throw e.context.logger.error("State not found"),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}`);let n=e.context.socialProviders.find(g=>g.id===e.params.id);if(!n)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:s,callbackURL:c,link:a,errorURL:d}=await st(e),p;try{p=await n.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${n.id}`})}catch(g){throw e.context.logger.error("",g),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let m=await n.getUserInfo(p).then(g=>g?.user);function l(g){let y=d||c||`${e.context.baseURL}/error`;throw y.includes("?")?y=`${y}&error=${g}`:y=`${y}?error=${g}`,e.redirect(y)}if(!m)return e.context.logger.error("Unable to get user info"),l("unable_to_get_user_info");if(!m.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),l("email_not_found");if(!c)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(a){if(a.email!==m.email.toLowerCase())return l("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:a.userId,providerId:n.id,accountId:m.id}))return l("unable_to_link_account");let y;try{y=new URL(c).toString()}catch{y=c}throw e.redirect(y)}let w=await ce(e,{userInfo:{...m,email:m.email,name:m.name||m.email},account:{providerId:n.id,accountId:m.id,...p,scope:p.scopes?.join(",")},callbackURL:c});if(w.error)return e.context.logger.error(w.error.split(" ").join("_")),l(w.error.split(" ").join("_"));let{session:O,user:I}=w.data;await x(e,{session:O,user:I});let h;try{h=new URL(c).toString()}catch{h=c}throw e.redirect(h)});var si=require("zod");var Nt=require("better-call"),_e=f("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw C(e),new Nt.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),C(e),e.json({success:!0})});var S=require("zod");var le=require("better-call");function $t(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}function hr(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}var Se=f("/forget-password",{method:"POST",body:S.z.object({email:S.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:S.z.string({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new le.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let i=60*60*1,n=N(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||i,"sec"),s=Tt(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:n});let c=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:c,token:s},e.request),e.json({status:!0})}),Ie=f("/reset-password/:token",{method:"GET",query:S.z.object({callbackURL:S.z.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect($t(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect($t(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(hr(e.context,r,{token:t}))}),Le=f("/reset-password",{query:S.z.optional(S.z.object({token:S.z.string().optional(),currentURL:S.z.string().optional()})),method:"POST",body:S.z.object({newPassword:S.z.string({description:"The new password to set"}),token:S.z.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new le.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,i=await e.context.internalAdapter.findVerificationValue(o);if(!i||i.expiresAt<new Date)throw new le.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(i.id);let n=i.value,s=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(n)).find(d=>d.providerId==="credential")?(await e.context.internalAdapter.updatePassword(n,s),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:s,accountId:n}),e.json({status:!0}))});var E=require("zod");var R=require("better-call");var u=require("zod"),qt=require("better-call"),gi=u.z.object({id:u.z.string(),providerId:u.z.string(),accountId:u.z.string(),userId:u.z.string(),accessToken:u.z.string().nullish(),refreshToken:u.z.string().nullish(),idToken:u.z.string().nullish(),accessTokenExpiresAt:u.z.date().nullish(),refreshTokenExpiresAt:u.z.date().nullish(),scope:u.z.string().nullish(),password:u.z.string().nullish(),createdAt:u.z.date().default(()=>new Date),updatedAt:u.z.date().default(()=>new Date)}),hi=u.z.object({id:u.z.string(),email:u.z.string().transform(e=>e.toLowerCase()),emailVerified:u.z.boolean().default(!1),name:u.z.string(),image:u.z.string().nullish(),createdAt:u.z.date().default(()=>new Date),updatedAt:u.z.date().default(()=>new Date)}),wi=u.z.object({id:u.z.string(),userId:u.z.string(),expiresAt:u.z.date(),createdAt:u.z.date().default(()=>new Date),updatedAt:u.z.date().default(()=>new Date),token:u.z.string(),ipAddress:u.z.string().nullish(),userAgent:u.z.string().nullish()}),yi=u.z.object({id:u.z.string(),value:u.z.string(),createdAt:u.z.date().default(()=>new Date),updatedAt:u.z.date().default(()=>new Date),expiresAt:u.z.date(),identifier:u.z.string()});function wr(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function yr(e,t){let r=t.action||"create",o=t.fields,i={};for(let n in o){if(n in e){if(o[n].input===!1){if(o[n].defaultValue){i[n]=o[n].defaultValue;continue}continue}if(o[n].validator?.input&&e[n]!==void 0){i[n]=o[n].validator.input.parse(e[n]);continue}i[n]=e[n];continue}if(o[n].defaultValue&&r==="create"){i[n]=o[n].defaultValue;continue}if(o[n].required&&r==="create")throw new qt.APIError("BAD_REQUEST",{message:`${n} is required`})}return i}function pe(e,t,r){let o=wr(e,"user");return yr(t||{},{fields:o,action:r})}var vr=require("@noble/ciphers/chacha"),Ce=require("@noble/ciphers/utils"),Er=require("@noble/ciphers/webcrypto"),Tr=require("oslo/crypto"),xr=Qe(require("uncrypto"),1);var Ft=require("oslo/encoding");var br=require("@noble/hashes/scrypt"),kr=require("uncrypto");var Oe=Qe(require("uncrypto"),1);function Ar(e){return e.toString(2).padStart(8,"0")}function Ur(e){return[...e].map(t=>Ar(t)).join("")}function Mt(e){return parseInt(Ur(e),2)}function Rr(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,o=new Uint8Array(Math.ceil(t/8));Oe.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let i=Mt(o);for(;i>=e;)Oe.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),i=Mt(o);return i}function Ht(e,t){let r="";for(let o=0;o<e;o++)r+=t[Rr(t.length)];return r}function Gt(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}var De=()=>f("/update-user",{method:"POST",body:E.z.record(E.z.string(),E.z.any()),use:[_],metadata:{openapi:{description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"}}}}}}}}}},async e=>{let t=e.body;if(t.email)throw new R.APIError("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...i}=t,n=e.context.session;if(o===void 0&&!r&&Object.keys(i).length===0)return e.json({user:n.user});let s=pe(e.context.options,i,"update"),c=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:r,image:o,...s});return await x(e,{session:n.session,user:c}),e.json({user:c})}),je=f("/change-password",{method:"POST",body:E.z.object({newPassword:E.z.string({description:"The new password to set"}),currentPassword:E.z.string({description:"The current password"}),revokeOtherSessions:E.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[_],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new R.APIError("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new R.APIError("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(i.user.id)).find(m=>m.providerId==="credential"&&m.password);if(!a||!a.password)throw new R.APIError("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify({hash:a.password,password:r}))throw new R.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(a.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(i.user.id);let m=await e.context.internalAdapter.createSession(i.user.id,e.headers);if(!m)throw new R.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await x(e,{session:m,user:i.user})}return e.json(i.user)}),Be=f("/set-password",{method:"POST",body:E.z.object({newPassword:E.z.string()}),metadata:{SERVER_ONLY:!0},use:[_]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new R.APIError("BAD_REQUEST",{message:"Password is too short"});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new R.APIError("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password),c=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:c}),e.json(r.user);throw new R.APIError("BAD_REQUEST",{message:"user already has a password"})}),Ve=f("/delete-user",{method:"POST",use:[be],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options",{session:e.context.session}),new R.APIError("NOT_FOUND");let t=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let i=Ht(32,Gt("a-z","A-Z","0-9"));await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${i}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let n=`${e.context.baseURL}/delete-user/callback?token=${i}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:n,token:i},e.request),e.json({success:!0,message:"Verification email sent"})}let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),C(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})}),ze=f("/delete-user/callback",{method:"GET",query:E.z.object({token:E.z.string()})},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new R.APIError("NOT_FOUND");let t=await $(e);if(!t)throw new R.APIError("NOT_FOUND",{message:"No session found"});let r=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!r||r.expiresAt<new Date)throw r&&await e.context.internalAdapter.deleteVerificationValue(r.id),new R.APIError("NOT_FOUND",{message:"Invalid token"});if(r.value!==t.user.id)throw new R.APIError("NOT_FOUND",{message:"Invalid token"});let o=e.context.options.user.deleteUser?.beforeDelete;o&&await o(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),await e.context.internalAdapter.deleteVerificationValue(r.id),C(e);let i=e.context.options.user.deleteUser?.afterDelete;return i&&await i(t.user,e.request),e.json({success:!0,message:"User deleted"})}),Ne=f("/change-email",{method:"POST",query:E.z.object({currentURL:E.z.string().optional()}).optional(),body:E.z.object({newEmail:E.z.string({description:"The new email to set"}).email(),callbackURL:E.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[_],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new R.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new R.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new R.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let i=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:i,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new R.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),e.json({user:null,status:!0})});var Pr=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|
package/dist/api.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import{APIError as q,createRouter as kr,getCookie as Ar,getSignedCookie as Ur,setCookie as Rr,setSignedCookie as vr}from"better-call";import{APIError as yt}from"better-call";import{createEndpointCreator as ht,createMiddleware as de,createMiddlewareCreator as wt}from"better-call";var le=de(async()=>({})),G=wt({use:[le,de(async()=>({}))]}),g=ht({use:[le]});var pe=G(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,i=e.headers?.get("origin")||e.headers?.get("referer")||"",n=t?.callbackURL||r?.callbackURL,s=t?.redirectTo,c=r?.currentURL,a=o.trustedOrigins,d=e.headers?.has("cookie"),p=(l,w)=>w.includes("*")?new RegExp("^"+w.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(l):l.startsWith(w),u=(l,w)=>{if(!l)return;if(!a.some(P=>p(l,P)||l?.startsWith("/")&&w!=="origin"&&!l.includes(":")))throw e.context.logger.error(`Invalid ${w}: ${l}`),e.context.logger.info(`If it's a valid URL, please add ${l} to trustedOrigins in your auth config
|
|
2
|
-
`,`Current list of trustedOrigins: ${a}`),new yt("FORBIDDEN",{message:`Invalid ${w}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&u(i,"origin"),n&&u(n,"callbackURL"),s&&u(s,"redirectURL"),c&&u(c,"currentURL")});import{APIError as E}from"better-call";import{z as U}from"zod";import{TimeSpan as qr}from"oslo";import{base64url as Rt}from"oslo/encoding";import{HMAC as ue,sha256 as Or}from"oslo/crypto";async function kt({value:e,secret:t}){return new ue("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function At({value:e,signature:t,secret:r}){return new ue("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var K={sign:kt,verify:At};var N=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};var V=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var Y=Object.create(null),Z=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Y:globalThis),me=new Proxy(Y,{get(e,t){return Z()[t]??Y[t]},has(e,t){let r=Z();return t in r||t in Y},set(e,t,r){let o=Z(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=Z(!0);return delete r[t],!0},ownKeys(){let e=Z(!0);return Object.keys(e)}});function Ut(e){return e?e!=="false":!1}var ne=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var fe=ne==="dev"||ne==="development",ge=ne==="test"||Ut(me.TEST);async function T(e,t,r,o){let i=e.context.authCookies.sessionToken.options,n=r?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Rt.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:V(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await K.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3))}function O(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}import{betterFetch as _t}from"@better-fetch/fetch";import{APIError as St}from"better-call";import{decodeProtectedHeader as It,importJWK as Lt,jwtVerify as Ot}from"jose";import{parseJWT as Ct}from"oslo/jwt";import{sha256 as vt}from"oslo/crypto";import{base64url as Et}from"oslo/encoding";async function he(e){let t=await vt(new TextEncoder().encode(e));return Et.encode(new Uint8Array(t),{includePadding:!1})}function we(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?V(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:s,redirectURI:c}){let a=new URL(r);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",t.clientId),a.searchParams.set("state",o),a.searchParams.set("scope",n.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||c),i){let d=await he(i);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",d)}if(s){let d=s.reduce((p,u)=>(p[u]=null,p),{});a.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...d}}))}return a}import{betterFetch as Tt}from"@better-fetch/fetch";async function b({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i,authentication:n}){let s=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),n==="basic"){let u=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${u}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await Tt(i,{method:"POST",body:s,headers:c});if(d)throw d;return we(a)}import{generateCodeVerifier as xt,generateState as Pt}from"oslo/oauth2";import{z}from"zod";import{APIError as be}from"better-call";function ye(e){try{return new URL(e).origin}catch{return null}}async function X(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?ye(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new be("BAD_REQUEST",{message:"callbackURL is required"});let o=xt(),i=Pt(),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:s});if(!c)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new be("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function ke(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=z.object({callbackURL:z.string(),codeVerifier:z.string(),errorURL:z.string().optional(),expiresAt:z.number(),link:z.object({email:z.string(),userId:z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var Ae=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=o||["email","name"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let i=It(r),{kid:n,alg:s}=i;if(!n||!s)return!1;let c=await Dt(n),{payload:a}=await Ot(r,c,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=Ct(r.idToken)?.payload;if(!o)return null;let i=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:i,emailVerified:!1,email:o.email,...n},data:o}}}},Dt=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await _t(`${t}${r}`);if(!o?.keys)throw new St("BAD_REQUEST",{message:"Keys not found"});let i=o.keys.find(n=>n.kid===e);if(!i)throw new Error(`JWK with kid ${e} not found`);return await Lt(i,i.alg)};import{betterFetch as jt}from"@better-fetch/fetch";var Ue=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await jt("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...i},data:r}}});import{betterFetch as Bt}from"@better-fetch/fetch";var Re=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await Bt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...i},data:r}}});import{betterFetch as ve}from"@better-fetch/fetch";var Ee=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>b({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await ve("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:c,error:a}=await ve("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(c.find(d=>d.primary)??c[0])?.email,n=c.find(d=>d.email===o.email)?.verified??!1)}let s=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n,...s},data:o}}}};import{parseJWT as qt}from"oslo/jwt";import{createConsola as Vt}from"consola";var ie=["info","success","warn","error","debug"];function zt(e,t){return ie.indexOf(t)<=ie.indexOf(e)}var Nt=Vt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),$t=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(i,n,s=[])=>{if(!(!t||!zt(r,i))){if(!e||typeof e.log!="function"){Nt[i]("",n,...s);return}e.log(i==="success"?"info":i,n,s)}};return Object.fromEntries(ie.map(i=>[i,(...[n,...s])=>o(i,n,s)]))},x=$t();import{betterFetch as Ft}from"@better-fetch/fetch";var Te=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw x.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new N("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new N("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:i}=await Ft(o);return i?i.aud===e.clientId&&i.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=qt(t.idToken)?.payload,o=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...o},data:r}}});import{betterFetch as Mt}from"@better-fetch/fetch";import{parseJWT as Ht}from"oslo/jwt";var xe=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),A({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return b({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);if(!i.idToken)return null;let n=Ht(i.idToken)?.payload,s=e.profilePhotoSize||48;await Mt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let p=await a.response.clone().arrayBuffer(),u=Buffer.from(p).toString("base64");n.picture=`data:image/jpeg;base64, ${u}`}catch(d){x.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0,...c},data:n}}}};import{betterFetch as Gt}from"@better-fetch/fetch";var Pe=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await Gt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...i},data:r}}});var F={isAction:!1};import{nanoid as Zt}from"nanoid";var _e=e=>Zt(e);import{parseJWT as Qt}from"oslo/jwt";var Se=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return x.error("No idToken found in token"),null;let o=Qt(r)?.payload,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...i},data:o}}});import{betterFetch as Jt}from"@better-fetch/fetch";var Ie=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),A({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await Jt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.data.id,name:r.data.name,email:r.data.username||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1,...i},data:r}}});import{betterFetch as Wt}from"@better-fetch/fetch";var Le=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await b({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await Wt("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...n},data:o}}}};import{betterFetch as Kt}from"@better-fetch/fetch";var Oe=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await b({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await Kt("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(n)return null;let s=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture,...s},data:i}}}};import{betterFetch as Yt}from"@better-fetch/fetch";var se=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Xt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:se(`${t}/oauth/authorize`),tokenEndpoint:se(`${t}/oauth/token`),userinfoEndpoint:se(`${t}/api/v4/user`)}},Ce=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Xt(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let p=c||["read_user"];return e.scope&&p.push(...e.scope),await A({id:i,options:e,authorizationEndpoint:t,scopes:p,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>b({code:s,redirectURI:e.redirectURI||c,options:e,codeVerifier:a,tokenEndpoint:r}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:c,error:a}=await Yt(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(a||c.state!=="active"||c.locked)return null;let d=await e.mapProfileToUser?.(c);return{user:{id:c.id.toString(),name:c.name??c.username,email:c.email,image:c.avatar_url,emailVerified:!0,...d},data:c}}}};var er={apple:Ae,discord:Ue,facebook:Re,github:Ee,microsoft:xe,google:Te,spotify:Pe,twitch:Se,twitter:Ie,dropbox:Le,linkedin:Oe,gitlab:Ce},ee=Object.keys(er);import{TimeSpan as tr}from"oslo";import{createJWT as rr,validateJWT as or}from"oslo/jwt";import{z as I}from"zod";import{APIError as Q}from"better-call";import{APIError as D}from"better-call";import{z as M}from"zod";function De(e){try{return JSON.parse(e)}catch{return null}}var ae=()=>g("/get-session",{method:"GET",query:M.optional(M.object({disableCookieCache:M.boolean({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:M.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?De(Buffer.from(r,"base64").toString()):null;if(o&&!await K.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return O(e),e.json(null);let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let p=o.session;if(o.expiresAt<Date.now()||p.session.expiresAt<new Date){let l=e.context.authCookies.sessionData.name;e.setCookie(l,"",{maxAge:0})}else return e.json(p)}let n=await e.context.internalAdapter.findSession(t);if(e.context.session=n,!n||n.session.expiresAt<new Date)return O(e),n&&await e.context.internalAdapter.deleteSession(n.session.token),e.json(null);if(i||e.query?.disableRefresh)return e.json(n);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let p=await e.context.internalAdapter.updateSession(n.session.token,{expiresAt:V(e.context.sessionConfig.expiresIn,"sec")});if(!p)return O(e),e.json(null,{status:401});let u=(p.expiresAt.valueOf()-Date.now())/1e3;return await T(e,{session:p,user:n.user},!1,{maxAge:u}),e.json({session:p,user:n.user})}return e.json(n)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new D("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),$=async(e,t)=>{if(e.context.session)return e.context.session;e.query={...e.query,...t};let r=await ae()({...e,_flag:"json",headers:e.headers});return e.context.session=r,r},_=G(async e=>{let t=await $(e);if(!t?.session)throw new D("UNAUTHORIZED");return{session:t}}),je=G(async e=>{let t=await $(e);if(!t?.session)throw new D("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),i=Date.now();if(!(o+r*1e3>i))throw new D("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),Be=()=>g("/list-sessions",{method:"GET",use:[_],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Ve=g("/revoke-session",{method:"POST",body:M.object({token:M.string({description:"The token to revoke"})}),use:[_],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let t=e.body.token,r=await e.context.internalAdapter.findSession(t);if(!r)throw new D("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new D("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new D("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ze=g("/revoke-sessions",{method:"POST",use:[_],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new D("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Ne=g("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[_],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw new D("UNAUTHORIZED");let i=(await e.context.internalAdapter.listSessions(t.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.token!==e.context.session.session.token);return await Promise.all(i.map(n=>e.context.internalAdapter.deleteSession(n.token))),e.json({status:!0})});async function j(e,t,r){return await rr("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new tr(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function nr(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Q("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(e.context.secret,t.email),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:r},e.request)}var $e=g("/send-verification-email",{method:"POST",query:I.object({currentURL:I.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:I.object({email:I.string({description:"The email to send the verification email to"}).email(),callbackURL:I.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Q("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new Q("BAD_REQUEST",{message:"User not found"});return await nr(e,r.user),e.json({status:!0})}),qe=g("/verify-email",{method:"GET",query:I.object({token:I.string({description:"The token to verify the email"}),callbackURL:I.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(c){throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=${c}`):new Q("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await or("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let n=I.object({email:I.string().email(),updateTo:I.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(n.email);if(!s)return t("user_not_found");if(n.updateTo){let c=await $(e);if(!c){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(c.user.email!==n.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${r}`,token:r},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await $(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new Q("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await T(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function te(e,{userInfo:t,account:r,callbackURL:o}){let i=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(c=>{throw x.error(`Better auth was unable to query your database.
|
|
2
|
+
`,`Current list of trustedOrigins: ${a}`),new yt("FORBIDDEN",{message:`Invalid ${w}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&u(i,"origin"),n&&u(n,"callbackURL"),s&&u(s,"redirectURL"),c&&u(c,"currentURL")});import{APIError as E}from"better-call";import{z as U}from"zod";import{TimeSpan as qr}from"oslo";import{base64url as Rt}from"oslo/encoding";import{HMAC as ue,sha256 as Or}from"oslo/crypto";async function kt({value:e,secret:t}){return new ue("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function At({value:e,signature:t,secret:r}){return new ue("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var K={sign:kt,verify:At};var N=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};var V=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var Y=Object.create(null),Z=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Y:globalThis),me=new Proxy(Y,{get(e,t){return Z()[t]??Y[t]},has(e,t){let r=Z();return t in r||t in Y},set(e,t,r){let o=Z(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=Z(!0);return delete r[t],!0},ownKeys(){let e=Z(!0);return Object.keys(e)}});function Ut(e){return e?e!=="false":!1}var ne=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var fe=ne==="dev"||ne==="development",ge=ne==="test"||Ut(me.TEST);async function T(e,t,r,o){let i=e.context.authCookies.sessionToken.options,n=r?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Rt.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:V(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await K.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3))}function O(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}import{betterFetch as _t}from"@better-fetch/fetch";import{APIError as St}from"better-call";import{decodeProtectedHeader as It,importJWK as Lt,jwtVerify as Ot}from"jose";import{parseJWT as Ct}from"oslo/jwt";import{sha256 as vt}from"oslo/crypto";import{base64url as Et}from"oslo/encoding";async function he(e){let t=await vt(new TextEncoder().encode(e));return Et.encode(new Uint8Array(t),{includePadding:!1})}function we(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?V(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:s,redirectURI:c}){let a=new URL(r);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",t.clientId),a.searchParams.set("state",o),a.searchParams.set("scope",n.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||c),i){let d=await he(i);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",d)}if(s){let d=s.reduce((p,u)=>(p[u]=null,p),{});a.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...d}}))}return a}import{betterFetch as Tt}from"@better-fetch/fetch";async function b({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i,authentication:n}){let s=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),n==="basic"){let u=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${u}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await Tt(i,{method:"POST",body:s,headers:c});if(d)throw d;return we(a)}import{generateCodeVerifier as xt,generateState as Pt}from"oslo/oauth2";import{z}from"zod";import{APIError as be}from"better-call";function ye(e){try{return new URL(e).origin}catch{return null}}async function X(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?ye(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new be("BAD_REQUEST",{message:"callbackURL is required"});let o=xt(),i=Pt(),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:s});if(!c)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new be("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function ke(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=z.object({callbackURL:z.string(),codeVerifier:z.string(),errorURL:z.string().optional(),expiresAt:z.number(),link:z.object({email:z.string(),userId:z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var Ae=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=o||["email","name"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let i=It(r),{kid:n,alg:s}=i;if(!n||!s)return!1;let c=await Dt(n),{payload:a}=await Ot(r,c,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=Ct(r.idToken)?.payload;if(!o)return null;let i=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:i,emailVerified:!1,email:o.email,...n},data:o}}}},Dt=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await _t(`${t}${r}`);if(!o?.keys)throw new St("BAD_REQUEST",{message:"Keys not found"});let i=o.keys.find(n=>n.kid===e);if(!i)throw new Error(`JWK with kid ${e} not found`);return await Lt(i,i.alg)};import{betterFetch as jt}from"@better-fetch/fetch";var Ue=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await jt("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...i},data:r}}});import{betterFetch as Bt}from"@better-fetch/fetch";var Re=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await Bt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...i},data:r}}});import{betterFetch as ve}from"@better-fetch/fetch";var Ee=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>b({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await ve("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:c,error:a}=await ve("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(c.find(d=>d.primary)??c[0])?.email,n=c.find(d=>d.email===o.email)?.verified??!1)}let s=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n,...s},data:o}}}};import{parseJWT as qt}from"oslo/jwt";import{createConsola as Vt}from"consola";var ie=["info","success","warn","error","debug"];function zt(e,t){return ie.indexOf(t)<=ie.indexOf(e)}var Nt=Vt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),$t=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(i,n,s=[])=>{if(!(!t||!zt(r,i))){if(!e||typeof e.log!="function"){Nt[i]("",n,...s);return}e.log(i==="success"?"info":i,n,s)}};return Object.fromEntries(ie.map(i=>[i,(...[n,...s])=>o(i,n,s)]))},x=$t();import{betterFetch as Ft}from"@better-fetch/fetch";var Te=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw x.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new N("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new N("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:i}=await Ft(o);return i?i.aud===e.clientId&&i.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=qt(t.idToken)?.payload,o=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...o},data:r}}});import{betterFetch as Mt}from"@better-fetch/fetch";import{parseJWT as Ht}from"oslo/jwt";var xe=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),A({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return b({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);if(!i.idToken)return null;let n=Ht(i.idToken)?.payload,s=e.profilePhotoSize||48;await Mt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let p=await a.response.clone().arrayBuffer(),u=Buffer.from(p).toString("base64");n.picture=`data:image/jpeg;base64, ${u}`}catch(d){x.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0,...c},data:n}}}};import{betterFetch as Gt}from"@better-fetch/fetch";var Pe=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await Gt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...i},data:r}}});var F={isAction:!1};import{nanoid as Zt}from"nanoid";var _e=e=>Zt(e);import{parseJWT as Qt}from"oslo/jwt";var Se=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return x.error("No idToken found in token"),null;let o=Qt(r)?.payload,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...i},data:o}}});import{betterFetch as Jt}from"@better-fetch/fetch";var Ie=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),A({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await Jt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.data.id,name:r.data.name,email:r.data.username||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1,...i},data:r}}});import{betterFetch as Wt}from"@better-fetch/fetch";var Le=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await b({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await Wt("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...n},data:o}}}};import{betterFetch as Kt}from"@better-fetch/fetch";var Oe=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await b({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await Kt("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(n)return null;let s=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture,...s},data:i}}}};import{betterFetch as Yt}from"@better-fetch/fetch";var se=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Xt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:se(`${t}/oauth/authorize`),tokenEndpoint:se(`${t}/oauth/token`),userinfoEndpoint:se(`${t}/api/v4/user`)}},Ce=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Xt(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let p=c||["read_user"];return e.scope&&p.push(...e.scope),await A({id:i,options:e,authorizationEndpoint:t,scopes:p,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>b({code:s,redirectURI:e.redirectURI||c,options:e,codeVerifier:a,tokenEndpoint:r}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:c,error:a}=await Yt(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(a||c.state!=="active"||c.locked)return null;let d=await e.mapProfileToUser?.(c);return{user:{id:c.id.toString(),name:c.name??c.username,email:c.email,image:c.avatar_url,emailVerified:!0,...d},data:c}}}};var er={apple:Ae,discord:Ue,facebook:Re,github:Ee,microsoft:xe,google:Te,spotify:Pe,twitch:Se,twitter:Ie,dropbox:Le,linkedin:Oe,gitlab:Ce},ee=Object.keys(er);import{TimeSpan as tr}from"oslo";import{createJWT as rr,validateJWT as or}from"oslo/jwt";import{z as I}from"zod";import{APIError as Q}from"better-call";import{APIError as D}from"better-call";import{z as M}from"zod";function De(e){try{return JSON.parse(e)}catch{return null}}var ae=()=>g("/get-session",{method:"GET",query:M.optional(M.object({disableCookieCache:M.boolean({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:M.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?De(Buffer.from(r,"base64").toString()):null;if(o&&!await K.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return O(e),e.json(null);let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let p=o.session;if(o.expiresAt<Date.now()||p.session.expiresAt<new Date){let l=e.context.authCookies.sessionData.name;e.setCookie(l,"",{maxAge:0})}else return e.json(p)}let n=await e.context.internalAdapter.findSession(t);if(e.context.session=n,!n||n.session.expiresAt<new Date)return O(e),n&&await e.context.internalAdapter.deleteSession(n.session.token),e.json(null);if(i||e.query?.disableRefresh)return e.json(n);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let p=await e.context.internalAdapter.updateSession(n.session.token,{expiresAt:V(e.context.sessionConfig.expiresIn,"sec")});if(!p)return O(e),e.json(null,{status:401});let u=(p.expiresAt.valueOf()-Date.now())/1e3;return await T(e,{session:p,user:n.user},!1,{maxAge:u}),e.json({session:p,user:n.user})}return e.json(n)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new D("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),$=async(e,t)=>{if(e.context.session)return e.context.session;let r=await ae()({...e,_flag:"json",headers:e.headers,query:t});return e.context.session=r,r},_=G(async e=>{let t=await $(e);if(!t?.session)throw new D("UNAUTHORIZED");return{session:t}}),je=G(async e=>{let t=await $(e);if(!t?.session)throw new D("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),i=Date.now();if(!(o+r*1e3>i))throw new D("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),Be=()=>g("/list-sessions",{method:"GET",use:[_],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Ve=g("/revoke-session",{method:"POST",body:M.object({token:M.string({description:"The token to revoke"})}),use:[_],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let t=e.body.token,r=await e.context.internalAdapter.findSession(t);if(!r)throw new D("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new D("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new D("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ze=g("/revoke-sessions",{method:"POST",use:[_],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new D("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Ne=g("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[_],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw new D("UNAUTHORIZED");let i=(await e.context.internalAdapter.listSessions(t.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.token!==e.context.session.session.token);return await Promise.all(i.map(n=>e.context.internalAdapter.deleteSession(n.token))),e.json({status:!0})});async function j(e,t,r){return await rr("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new tr(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function nr(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Q("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(e.context.secret,t.email),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:r},e.request)}var $e=g("/send-verification-email",{method:"POST",query:I.object({currentURL:I.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:I.object({email:I.string({description:"The email to send the verification email to"}).email(),callbackURL:I.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Q("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new Q("BAD_REQUEST",{message:"User not found"});return await nr(e,r.user),e.json({status:!0})}),qe=g("/verify-email",{method:"GET",query:I.object({token:I.string({description:"The token to verify the email"}),callbackURL:I.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(c){throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=${c}`):new Q("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await or("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let n=I.object({email:I.string().email(),updateTo:I.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(n.email);if(!s)return t("user_not_found");if(n.updateTo){let c=await $(e);if(!c){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(c.user.email!==n.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${r}`,token:r},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await $(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new Q("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await T(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function te(e,{userInfo:t,account:r,callbackURL:o}){let i=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(c=>{throw x.error(`Better auth was unable to query your database.
|
|
3
3
|
Error: `,c),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=i?.user;if(i){let c=i.accounts.find(a=>a.providerId===r.providerId);if(c){let a=Object.fromEntries(Object.entries({accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([d,p])=>p!==void 0));Object.keys(a).length>0&&await e.context.internalAdapter.updateAccount(c.id,a)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return fe&&x.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),userId:i.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope})}catch(p){return x.error("Unable to link account",p),{error:"unable to link account",data:null}}}}else try{if(n=await e.context.internalAdapter.createOAuthUser({...t,id:void 0},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:t.id.toString()}).then(c=>c?.user),!t.emailVerified&&n&&e.context.options.emailVerification?.sendOnSignUp){let c=await j(e.context.secret,n.email),a=`${e.context.baseURL}/verify-email?token=${c}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:n,url:a,token:c},e.request)}}catch(c){return x.error("Unable to create user",c),{error:"unable to create user",data:null}}if(!n)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(n.id,e.request);return s?{data:{session:s,user:n},error:null}:{error:"unable to create session",data:null}}var Fe=g("/sign-in/social",{method:"POST",query:U.object({currentURL:U.string().optional()}).optional(),body:U.object({callbackURL:U.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),errorCallbackURL:U.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:U.enum(ee,{description:"OAuth2 provider to use"}),disableRedirect:U.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:U.optional(U.object({token:U.string({description:"ID token from the provider"}),nonce:U.string({description:"Nonce used to generate the token"}).optional(),accessToken:U.string({description:"Access token from the provider"}).optional(),refreshToken:U.string({description:"Refresh token from the provider"}).optional(),expiresAt:U.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new E("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new E("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:n,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(n,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new E("UNAUTHORIZED",{message:"Invalid id token"});let a=await t.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new E("UNAUTHORIZED",{message:"Failed to get user info"});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new E("UNAUTHORIZED",{message:"User email not found"});let d=await te(e,{userInfo:{email:a.user.email,id:a.user.id,name:a.user.name||"",image:a.user.image,emailVerified:a.user.emailVerified||!1},account:{providerId:t.id,accountId:a.user.id,accessToken:e.body.idToken.accessToken}});if(d.error)throw new E("UNAUTHORIZED",{message:d.error});return await T(e,d.data),e.json({session:d.data.session,user:d.data.user,url:void 0,redirect:!1})}let{codeVerifier:r,state:o}=await X(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!e.body.disableRedirect})}),Me=g("/sign-in/email",{method:"POST",body:U.object({email:U.string({description:"Email of the user"}),password:U.string({description:"Password of the user"}),callbackURL:U.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:U.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:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new E("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!U.string().email().safeParse(t).success)throw new E("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new E("UNAUTHORIZED",{message:"Invalid email or password"});let n=i.accounts.find(d=>d.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new E("UNAUTHORIZED",{message:"Invalid email or password"});let s=n?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new E("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new E("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new E("UNAUTHORIZED",{message:"Email is not verified."});let d=await j(e.context.secret,i.user.email),p=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:i.user,url:p,token:d},e.request),e.context.logger.error("Email not verified",{email:t}),new E("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let a=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new E("UNAUTHORIZED",{message:"Failed to create session"});return await T(e,{session:a,user:i.user},e.body.rememberMe===!1),e.json({user:i.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as J}from"zod";var re=J.object({code:J.string().optional(),error:J.string().optional(),errorMessage:J.string().optional(),state:J.string().optional()}),He=g("/callback/:id",{method:["GET","POST"],body:re.optional(),query:re.optional(),metadata:F},async e=>{let t;try{if(e.method==="GET")t=re.parse(e.query);else if(e.method==="POST")t=re.parse(e.body);else throw new Error("Unsupported method")}catch(f){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",f),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:i}=t;if(!i)throw e.context.logger.error("State not found"),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}`);let n=e.context.socialProviders.find(f=>f.id===e.params.id);if(!n)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:s,callbackURL:c,link:a,errorURL:d}=await ke(e),p;try{p=await n.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${n.id}`})}catch(f){throw e.context.logger.error("",f),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let u=await n.getUserInfo(p).then(f=>f?.user);function l(f){let y=d||c||`${e.context.baseURL}/error`;throw y.includes("?")?y=`${y}&error=${f}`:y=`${y}?error=${f}`,e.redirect(y)}if(!u)return e.context.logger.error("Unable to get user info"),l("unable_to_get_user_info");if(!u.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),l("email_not_found");if(!c)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(a){if(a.email!==u.email.toLowerCase())return l("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:a.userId,providerId:n.id,accountId:u.id}))return l("unable_to_link_account");let y;try{y=new URL(c).toString()}catch{y=c}throw e.redirect(y)}let w=await te(e,{userInfo:{...u,email:u.email,name:u.name||u.email},account:{providerId:n.id,accountId:u.id,...p,scope:p.scopes?.join(",")},callbackURL:c});if(w.error)return e.context.logger.error(w.error.split(" ").join("_")),l(w.error.split(" ").join("_"));let{session:L,user:P}=w.data;await T(e,{session:L,user:P});let h;try{h=new URL(c).toString()}catch{h=c}throw e.redirect(h)});import"zod";import{APIError as ir}from"better-call";var Ge=g("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw O(e),new ir("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),O(e),e.json({success:!0})});import{z as S}from"zod";import{APIError as ce}from"better-call";function Ze(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}function sr(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}var Qe=g("/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 e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new ce("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let i=60*60*1,n=V(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||i,"sec"),s=_e(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:n});let c=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:c,token:s},e.request),e.json({status:!0})}),Je=g("/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 e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(Ze(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Ze(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(sr(e.context,r,{token:t}))}),We=g("/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 e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new ce("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,i=await e.context.internalAdapter.findVerificationValue(o);if(!i||i.expiresAt<new Date)throw new ce("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(i.id);let n=i.value,s=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(n)).find(d=>d.providerId==="credential")?(await e.context.internalAdapter.updatePassword(n,s),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:s,accountId:n}),e.json({status:!0}))});import{z as v}from"zod";import{APIError as R}from"better-call";import{z as m}from"zod";import{APIError as ar}from"better-call";var Ji=m.object({id:m.string(),providerId:m.string(),accountId:m.string(),userId:m.string(),accessToken:m.string().nullish(),refreshToken:m.string().nullish(),idToken:m.string().nullish(),accessTokenExpiresAt:m.date().nullish(),refreshTokenExpiresAt:m.date().nullish(),scope:m.string().nullish(),password:m.string().nullish(),createdAt:m.date().default(()=>new Date),updatedAt:m.date().default(()=>new Date)}),Wi=m.object({id:m.string(),email:m.string().transform(e=>e.toLowerCase()),emailVerified:m.boolean().default(!1),name:m.string(),image:m.string().nullish(),createdAt:m.date().default(()=>new Date),updatedAt:m.date().default(()=>new Date)}),Ki=m.object({id:m.string(),userId:m.string(),expiresAt:m.date(),createdAt:m.date().default(()=>new Date),updatedAt:m.date().default(()=>new Date),token:m.string(),ipAddress:m.string().nullish(),userAgent:m.string().nullish()}),Yi=m.object({id:m.string(),value:m.string(),createdAt:m.date().default(()=>new Date),updatedAt:m.date().default(()=>new Date),expiresAt:m.date(),identifier:m.string()});function cr(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function dr(e,t){let r=t.action||"create",o=t.fields,i={};for(let n in o){if(n in e){if(o[n].input===!1){if(o[n].defaultValue){i[n]=o[n].defaultValue;continue}continue}if(o[n].validator?.input&&e[n]!==void 0){i[n]=o[n].validator.input.parse(e[n]);continue}i[n]=e[n];continue}if(o[n].defaultValue&&r==="create"){i[n]=o[n].defaultValue;continue}if(o[n].required&&r==="create")throw new ar("BAD_REQUEST",{message:`${n} is required`})}return i}function oe(e,t,r){let o=cr(e,"user");return dr(t||{},{fields:o,action:r})}import{xchacha20poly1305 as us}from"@noble/ciphers/chacha";import{bytesToHex as fs,hexToBytes as gs,utf8ToBytes as hs}from"@noble/ciphers/utils";import{managedNonce as ys}from"@noble/ciphers/webcrypto";import{sha256 as ks}from"oslo/crypto";import Us from"uncrypto";import{decodeHex as ts,encodeHex as rs}from"oslo/encoding";import{scryptAsync as is}from"@noble/hashes/scrypt";import{getRandomValues as as}from"uncrypto";import Ke from"uncrypto";function lr(e){return e.toString(2).padStart(8,"0")}function pr(e){return[...e].map(t=>lr(t)).join("")}function Ye(e){return parseInt(pr(e),2)}function ur(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,o=new Uint8Array(Math.ceil(t/8));Ke.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let i=Ye(o);for(;i>=e;)Ke.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),i=Ye(o);return i}function Xe(e,t){let r="";for(let o=0;o<e;o++)r+=t[ur(t.length)];return r}function et(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}var tt=()=>g("/update-user",{method:"POST",body:v.record(v.string(),v.any()),use:[_],metadata:{openapi:{description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"}}}}}}}}}},async e=>{let t=e.body;if(t.email)throw new R("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...i}=t,n=e.context.session;if(o===void 0&&!r&&Object.keys(i).length===0)return e.json({user:n.user});let s=oe(e.context.options,i,"update"),c=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:r,image:o,...s});return await T(e,{session:n.session,user:c}),e.json({user:c})}),rt=g("/change-password",{method:"POST",body:v.object({newPassword:v.string({description:"The new password to set"}),currentPassword:v.string({description:"The current password"}),revokeOtherSessions:v.boolean({description:"Revoke all other sessions"}).optional()}),use:[_],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new R("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new R("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(i.user.id)).find(u=>u.providerId==="credential"&&u.password);if(!a||!a.password)throw new R("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify({hash:a.password,password:r}))throw new R("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(a.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(i.user.id);let u=await e.context.internalAdapter.createSession(i.user.id,e.headers);if(!u)throw new R("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await T(e,{session:u,user:i.user})}return e.json(i.user)}),ot=g("/set-password",{method:"POST",body:v.object({newPassword:v.string()}),metadata:{SERVER_ONLY:!0},use:[_]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new R("BAD_REQUEST",{message:"Password is too short"});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new R("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password),c=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:c}),e.json(r.user);throw new R("BAD_REQUEST",{message:"user already has a password"})}),nt=g("/delete-user",{method:"POST",use:[je],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options",{session:e.context.session}),new R("NOT_FOUND");let t=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let i=Xe(32,et("a-z","A-Z","0-9"));await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${i}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let n=`${e.context.baseURL}/delete-user/callback?token=${i}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:n,token:i},e.request),e.json({success:!0,message:"Verification email sent"})}let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),O(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})}),it=g("/delete-user/callback",{method:"GET",query:v.object({token:v.string()})},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new R("NOT_FOUND");let t=await $(e);if(!t)throw new R("NOT_FOUND",{message:"No session found"});let r=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!r||r.expiresAt<new Date)throw r&&await e.context.internalAdapter.deleteVerificationValue(r.id),new R("NOT_FOUND",{message:"Invalid token"});if(r.value!==t.user.id)throw new R("NOT_FOUND",{message:"Invalid token"});let o=e.context.options.user.deleteUser?.beforeDelete;o&&await o(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),await e.context.internalAdapter.deleteVerificationValue(r.id),O(e);let i=e.context.options.user.deleteUser?.afterDelete;return i&&await i(t.user,e.request),e.json({success:!0,message:"User deleted"})}),st=g("/change-email",{method:"POST",query:v.object({currentURL:v.string().optional()}).optional(),body:v.object({newEmail:v.string({description:"The new email to set"}).email(),callbackURL:v.string({description:"The URL to redirect to after email verification"}).optional()}),use:[_],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new R("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new R("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new R("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let i=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:i,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new R("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),e.json({user:null,status:!0})});var mr=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|
|
@@ -2,8 +2,8 @@ import * as nanostores from 'nanostores';
|
|
|
2
2
|
import { AccessControl, StatementsPrimitive, Role } from '../plugins/access.cjs';
|
|
3
3
|
import * as _better_fetch_fetch from '@better-fetch/fetch';
|
|
4
4
|
import { BetterFetchOption } from '@better-fetch/fetch';
|
|
5
|
-
import { o as organization, q as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, f as anonymous, i as admin, j as genericOAuth, k as jwt, l as multiSession, n as emailOTP } from '../index-
|
|
6
|
-
export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-
|
|
5
|
+
import { o as organization, q as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, f as anonymous, i as admin, j as genericOAuth, k as jwt, l as multiSession, n as emailOTP } from '../index-0hpBrZ7U.cjs';
|
|
6
|
+
export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-0hpBrZ7U.cjs';
|
|
7
7
|
import { P as Prettify } from '../helper-D7-GCsit.cjs';
|
|
8
8
|
import { F as FieldAttribute, B as BetterAuthOptions, j as BetterAuthPlugin } from '../auth--x_9FmG7.cjs';
|
|
9
9
|
import { Store } from '../types.cjs';
|
package/dist/client/plugins.d.ts
CHANGED
|
@@ -2,8 +2,8 @@ import * as nanostores from 'nanostores';
|
|
|
2
2
|
import { AccessControl, StatementsPrimitive, Role } from '../plugins/access.js';
|
|
3
3
|
import * as _better_fetch_fetch from '@better-fetch/fetch';
|
|
4
4
|
import { BetterFetchOption } from '@better-fetch/fetch';
|
|
5
|
-
import { o as organization, q as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, f as anonymous, i as admin, j as genericOAuth, k as jwt, l as multiSession, n as emailOTP } from '../index-
|
|
6
|
-
export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-
|
|
5
|
+
import { o as organization, q as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, f as anonymous, i as admin, j as genericOAuth, k as jwt, l as multiSession, n as emailOTP } from '../index-B7qPPh4o.js';
|
|
6
|
+
export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-B7qPPh4o.js';
|
|
7
7
|
import { P as Prettify } from '../helper-D7-GCsit.js';
|
|
8
8
|
import { F as FieldAttribute, B as BetterAuthOptions, j as BetterAuthPlugin } from '../auth-CH6diQPX.js';
|
|
9
9
|
import { Store } from '../types.js';
|