better-auth 1.0.9-beta.2 → 1.0.9-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/adapters/drizzle.d.cts +1 -1
  2. package/dist/adapters/drizzle.d.ts +1 -1
  3. package/dist/adapters/kysely.d.cts +1 -1
  4. package/dist/adapters/kysely.d.ts +1 -1
  5. package/dist/adapters/memory.d.cts +1 -1
  6. package/dist/adapters/memory.d.ts +1 -1
  7. package/dist/adapters/mongodb.d.cts +1 -1
  8. package/dist/adapters/mongodb.d.ts +1 -1
  9. package/dist/adapters/prisma.d.cts +1 -1
  10. package/dist/adapters/prisma.d.ts +1 -1
  11. package/dist/api.cjs +4 -4
  12. package/dist/api.d.cts +1 -1
  13. package/dist/api.d.ts +1 -1
  14. package/dist/api.js +4 -4
  15. package/dist/{auth-XMAxn5Ae.d.cts → auth-CRbxCgiW.d.cts} +80 -0
  16. package/dist/{auth-DFawWk0e.d.ts → auth-CnCuVMLa.d.ts} +80 -0
  17. package/dist/client/plugins.d.cts +3 -3
  18. package/dist/client/plugins.d.ts +3 -3
  19. package/dist/client.d.cts +1 -1
  20. package/dist/client.d.ts +1 -1
  21. package/dist/cookies.cjs +4 -4
  22. package/dist/cookies.d.cts +1 -1
  23. package/dist/cookies.d.ts +1 -1
  24. package/dist/cookies.js +4 -4
  25. package/dist/db.d.cts +2 -2
  26. package/dist/db.d.ts +2 -2
  27. package/dist/{index-C7crAQ7s.d.cts → index-BAg8-2P7.d.cts} +1 -1
  28. package/dist/{index-CWprSsao.d.ts → index-tjkytDIw.d.ts} +1 -1
  29. package/dist/index.cjs +4 -4
  30. package/dist/index.d.cts +2 -2
  31. package/dist/index.d.ts +2 -2
  32. package/dist/index.js +3 -3
  33. package/dist/next-js.cjs +1 -1
  34. package/dist/next-js.d.cts +1 -1
  35. package/dist/next-js.d.ts +1 -1
  36. package/dist/next-js.js +1 -1
  37. package/dist/node.d.cts +1 -1
  38. package/dist/node.d.ts +1 -1
  39. package/dist/oauth2.d.cts +2 -2
  40. package/dist/oauth2.d.ts +2 -2
  41. package/dist/plugins.cjs +2 -2
  42. package/dist/plugins.d.cts +3 -3
  43. package/dist/plugins.d.ts +3 -3
  44. package/dist/plugins.js +4 -4
  45. package/dist/react.d.cts +1 -1
  46. package/dist/react.d.ts +1 -1
  47. package/dist/solid-start.d.cts +1 -1
  48. package/dist/solid-start.d.ts +1 -1
  49. package/dist/solid.d.cts +1 -1
  50. package/dist/solid.d.ts +1 -1
  51. package/dist/{state-BsON3MFE.d.ts → state-CwZsNu9d.d.ts} +1 -1
  52. package/dist/{state-BkCnjHc0.d.cts → state-DLdB9N6W.d.cts} +1 -1
  53. package/dist/svelte-kit.d.cts +1 -1
  54. package/dist/svelte-kit.d.ts +1 -1
  55. package/dist/svelte.d.cts +1 -1
  56. package/dist/svelte.d.ts +1 -1
  57. package/dist/types.d.cts +2 -2
  58. package/dist/types.d.ts +2 -2
  59. package/dist/vue.d.cts +1 -1
  60. package/dist/vue.d.ts +1 -1
  61. package/package.json +1 -1
package/dist/next-js.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";var ie=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var pt=Object.prototype.hasOwnProperty;var ut=(e,t)=>{for(var r in t)ie(e,r,{get:t[r],enumerable:!0})},lt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of dt(t))!pt.call(e,n)&&n!==r&&ie(e,n,{get:()=>t[n],enumerable:!(o=ct(t,n))||o.enumerable});return e};var mt=e=>lt(ie({},"__esModule",{value:!0}),e);var rr={};ut(rr,{nextCookies:()=>tr,toNextJsHandler:()=>er});module.exports=mt(rr);var at=require("next/headers");var Xt=require("oslo"),st=require("oslo/encoding");var Q=require("oslo/crypto");async function ft({value:e,secret:t}){return new Q.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function gt({value:e,signature:t,secret:r}){return new Q.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var J={sign:ft,verify:gt};var j=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};var O=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var W=Object.create(null),G=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?W:globalThis),le=new Proxy(W,{get(e,t){return G()[t]??W[t]},has(e,t){let r=G();return t in r||t in W},set(e,t,r){let o=G(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=G(!0);return delete r[t],!0},ownKeys(){let e=G(!0);return Object.keys(e)}});function ht(e){return e?e!=="false":!1}var se=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var me=se==="dev"||se==="development",wt=se==="test"||ht(le.TEST);var M=require("better-call");var ge=require("better-call");var D=require("better-call"),fe=(0,D.createMiddleware)(async()=>({})),Z=(0,D.createMiddlewareCreator)({use:[fe,(0,D.createMiddleware)(async()=>({}))]}),m=(0,D.createEndpointCreator)({use:[fe]});var yt=Z(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=t?.callbackURL||r?.callbackURL,s=t?.redirectTo,c=r?.currentURL,a=o.trustedOrigins,d=e.headers?.has("cookie"),p=(w,k)=>k.includes("*")?new RegExp("^"+k.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(w):w.startsWith(k),l=(w,k)=>{if(!w)return;if(!a.some(V=>p(w,V)||w?.startsWith("/")&&k!=="origin"&&!w.includes(":")))throw e.context.logger.error(`Invalid ${k}: ${w}`),e.context.logger.info(`If it's a valid URL, please add ${w} to trustedOrigins in your auth config
2
2
  `,`Current list of trustedOrigins: ${a}`),new ge.APIError("FORBIDDEN",{message:`Invalid ${k}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&l(n,"origin"),i&&l(i,"callbackURL"),s&&l(s,"redirectURL"),c&&l(c,"currentURL")});var b=require("better-call"),g=require("zod");var Re=require("@better-fetch/fetch"),ve=require("better-call"),z=require("jose"),Ee=require("oslo/jwt");var he=require("oslo/crypto"),we=require("oslo/encoding");async function ye(e){let t=await(0,he.sha256)(new TextEncoder().encode(e));return we.base64url.encode(new Uint8Array(t),{includePadding:!1})}function be(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?O(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function h({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,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",i.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||c),n){let d=await ye(n);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",d)}if(s){let d=s.reduce((p,l)=>(p[l]=null,p),{});a.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...d}}))}return a}var ke=require("@better-fetch/fetch");async function f({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n,authentication:i}){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),i==="basic"){let l=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${l}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await(0,ke.betterFetch)(n,{method:"POST",body:s,headers:c});if(d)throw d;return be(a)}var K=require("oslo/oauth2"),I=require("zod"),ae=require("better-call");function Ae(e){try{return new URL(e).origin}catch{return null}}async function Y(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Ae(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ae.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,K.generateCodeVerifier)(),n=(0,K.generateState)(),i=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:i,identifier:n,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 ae.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function Ue(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=I.z.object({callbackURL:I.z.string(),codeVerifier:I.z.string(),errorURL:I.z.string().optional(),expiresAt:I.z.number(),link:I.z.object({email:I.z.string(),userId:I.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 xe=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>f({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let n=(0,z.decodeProtectedHeader)(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let c=await bt(i),{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,Ee.parseJWT)(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email;return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email},data:o}}}},bt=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,Re.betterFetch)(`${t}${r}`);if(!o?.keys)throw new ve.APIError("BAD_REQUEST",{message:"Keys not found"});let n=o.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await(0,z.importJWK)(n,n.alg)};var Te=require("@better-fetch/fetch");var _e=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>f({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,Te.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}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var Se=require("@better-fetch/fetch");var Pe=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await h({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>f({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,Se.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});var ce=require("@better-fetch/fetch");var Ie=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),h({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>f({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await(0,ce.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:c}=await(0,ce.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});c||(o.email=(s.find(a=>a.primary)??s[0])?.email,i=s.find(a=>a.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};var Oe=require("oslo/jwt");var Le=require("consola"),de=["info","success","warn","error","debug"];function kt(e,t){return de.indexOf(t)<=de.indexOf(e)}var At=(0,Le.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Ut=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,s=[])=>{if(!(!t||!kt(r,n))){if(!e||typeof e.log!="function"){At[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(de.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},E=Ut();var Ce=require("@better-fetch/fetch"),je=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw E.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new j("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new j("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await h({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});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})=>f({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:n}=await(0,Ce.betterFetch)(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,Oe.parseJWT)(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});var De=require("@better-fetch/fetch"),Be=require("oslo/jwt");var Ve=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),h({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return f({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=(0,Be.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,De.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let d=await c.response.clone().arrayBuffer(),p=Buffer.from(d).toString("base64");i.picture=`data:image/jpeg;base64, ${p}`}catch(a){E.error(a&&typeof a=="object"&&"name"in a?a.name:"",a)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};var ze=require("@better-fetch/fetch");var $e=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),h({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>f({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,ze.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});var $={isAction:!1};var qe=require("nanoid"),Ne=e=>(0,qe.nanoid)(e);var He=require("oslo/jwt");var Fe=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),h({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>f({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 E.error("No idToken found in token"),null;let o=(0,He.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var Me=require("@better-fetch/fetch");var Ge=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),h({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})=>f({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,Me.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{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},data:r}}});var Ze=require("@better-fetch/fetch");var Qe=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await h({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await f({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await(0,Ze.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};var Je=require("@better-fetch/fetch");var We=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await h({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await f({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await(0,Je.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};var Ke=require("@better-fetch/fetch");var pe=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Rt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:pe(`${t}/oauth/authorize`),tokenEndpoint:pe(`${t}/oauth/token`),userinfoEndpoint:pe(`${t}/api/v4/user`)}},Ye=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Rt(e.issuer),n="gitlab";return{id:n,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 h({id:n,options:e,authorizationEndpoint:t,scopes:p,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>f({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,Ke.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return a||c.state!=="active"||c.locked?null:{user:{id:c.id.toString(),name:c.name??c.username,email:c.email,image:c.avatar_url,emailVerified:!0},data:c}}}};var vt={apple:xe,discord:_e,facebook:Pe,github:Ie,microsoft:Ve,google:je,spotify:$e,twitch:Fe,twitter:Ge,dropbox:Qe,linkedin:We,gitlab:Ye},X=Object.keys(vt);var rt=require("oslo"),ee=require("oslo/jwt"),T=require("zod");var N=require("better-call");var S=require("better-call");var q=require("zod");function Xe(e){try{return JSON.parse(e)}catch{return null}}var et=()=>m("/get-session",{method:"GET",query:q.z.optional(q.z.object({disableCookieCache:q.z.boolean({description:"Disable cookie cache and fetch session from database"}).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?Xe(Buffer.from(r,"base64").toString()):null;if(o&&!await J.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return L(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let p=o.session;if(o.expiresAt<Date.now()||p.session.expiresAt<new Date){let w=e.context.authCookies.sessionData.name;e.setCookie(w,"",{maxAge:0})}else return e.json(p)}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return L(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n)return e.json(i);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let p=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:O(e.context.sessionConfig.expiresIn,"sec")});if(!p)return L(e),e.json(null,{status:401});let l=(p.expiresAt.valueOf()-Date.now())/1e3;return await x(e,{session:p,user:i.user},!1,{maxAge:l}),e.json({session:p,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new S.APIError("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),B=async e=>{if(e.context.session)return e.context.session;let t=await et()({...e,_flag:"json",headers:e.headers});return e.context.session=t,t},P=Z(async e=>{let t=await B(e);if(!t?.session)throw new S.APIError("UNAUTHORIZED");return{session:t}}),tt=Z(async e=>{let t=await B(e);if(!t?.session)throw new S.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),n=Date.now();if(!(o+r*1e3>n))throw new S.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}});var Et=m("/revoke-session",{method:"POST",body:q.z.object({token:q.z.string({description:"The token to revoke"})}),use:[P],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 S.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new S.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 S.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),xt=m("/revoke-sessions",{method:"POST",use:[P],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 S.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Tt=m("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[P],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 S.APIError("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});async function C(e,t,r){return await(0,ee.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new rt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function _t(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new N.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await C(e.context.secret,t.email),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:r},e.request)}var St=m("/send-verification-email",{method:"POST",query:T.z.object({currentURL:T.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:T.z.object({email:T.z.string({description:"The email to send the verification email to"}).email(),callbackURL:T.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 N.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 N.APIError("BAD_REQUEST",{message:"User not found"});return await _t(e,r.user),e.json({status:!0})}),Pt=m("/verify-email",{method:"GET",query:T.z.object({token:T.z.string({description:"The token to verify the email"}),callbackURL:T.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 N.APIError("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await(0,ee.validateJWT)("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let i=T.z.object({email:T.z.string().email(),updateTo:T.z.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(i.email);if(!s)return t("user_not_found");if(i.updateTo){let c=await B(e);if(!c){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(c.user.email!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.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(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await B(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new N.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 te(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(c=>{throw E.error(`Better auth was unable to query your database.
3
- Error: `,c),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user;if(n){let c=n.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 me&&E.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),userId:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope})}catch(p){return E.error("Unable to link account",p),{error:"unable to link account",data:null}}}}else try{let c=t.emailVerified||!1;if(i=await e.context.internalAdapter.createOAuthUser({...t,id:void 0,emailVerified:c,email:t.email.toLowerCase()},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:t.id.toString()}).then(a=>a?.user),!c&&i&&e.context.options.emailVerification?.sendOnSignUp){let a=await C(e.context.secret,i.email),d=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:d,token:a},e.request)}}catch(c){return E.error("Unable to create user",c),{error:"unable to create user",data:null}}if(!i)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(i.id,e.request);return s?{data:{session:s,user:i},error:null}:{error:"unable to create session",data:null}}var It=m("/sign-in/social",{method:"POST",query:g.z.object({currentURL:g.z.string().optional()}).optional(),body:g.z.object({callbackURL:g.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),errorCallbackURL:g.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:g.z.enum(X,{description:"OAuth2 provider to use"}),disableRedirect:g.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:g.z.optional(g.z.object({token:g.z.string({description:"ID token from the provider"}),nonce:g.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:g.z.string({description:"Access token from the provider"}).optional(),refreshToken:g.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:g.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new b.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 b.APIError("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:i,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new b.APIError("UNAUTHORIZED",{message:"Invalid id token"});let a=await t.getUserInfo({idToken:i,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 b.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 b.APIError("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 b.APIError("UNAUTHORIZED",{message:d.error});return await x(e,d.data),e.json({session:d.data.session,user:d.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:r,state:o}=await Y(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),Lt=m("/sign-in/email",{method:"POST",body:g.z.object({email:g.z.string({description:"Email of the user"}),password:g.z.string({description:"Password of the user"}),callbackURL:g.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:g.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 b.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!g.z.string().email().safeParse(t).success)throw new b.APIError("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new b.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(d=>d.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new b.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new b.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new b.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new b.APIError("UNAUTHORIZED",{message:"Email is not verified."});let d=await C(e.context.secret,n.user.email),p=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:p,token:d},e.request),e.context.logger.error("Email not verified",{email:t}),new b.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new b.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await x(e,{session:a,user:n.user},e.body.rememberMe===!1),e.json({user:n.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var H=require("zod");var re=H.z.object({code:H.z.string().optional(),error:H.z.string().optional(),errorMessage:H.z.string().optional(),state:H.z.string().optional()}),Ot=m("/callback/:id",{method:["GET","POST"],body:re.optional(),query:re.optional(),metadata:$},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(v){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",v),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n}=t;if(!n)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 i=e.context.socialProviders.find(v=>v.id===e.params.id);if(!i)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 Ue(e),p;try{p=await i.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${i.id}`})}catch(v){throw e.context.logger.error("",v),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let l=await i.getUserInfo(p).then(v=>v?.user);function w(v){let _=d||c||`${e.context.baseURL}/error`;throw _.includes("?")?_=`${_}&error=${v}`:_=`${_}?error=${v}`,e.redirect(_)}if(!l)return e.context.logger.error("Unable to get user info"),w("unable_to_get_user_info");if(!l.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),w("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!==l.email.toLowerCase())return w("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:a.userId,providerId:i.id,accountId:l.id}))return w("unable_to_link_account");let _;try{_=new URL(c).toString()}catch{_=c}throw e.redirect(_)}let k=await te(e,{userInfo:{id:l.id,email:l.email,name:l.name||"",image:l.image,emailVerified:l.emailVerified||!1},account:{providerId:i.id,accountId:l.id,...p,scope:p.scopes?.join(",")},callbackURL:c});if(k.error)return e.context.logger.error(k.error.split(" ").join("_")),w(k.error.split(" ").join("_"));let{session:y,user:V}=k.data;await x(e,{session:y,user:V});let ne;try{ne=new URL(c).toString()}catch{ne=c}throw e.redirect(ne)});var yn=require("zod");var ot=require("better-call"),Ct=m("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw L(e),new ot.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),L(e),e.json({success:!0})});var U=require("zod");var oe=require("better-call");function nt(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function jt(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var Dt=m("/forget-password",{method:"POST",body:U.z.object({email:U.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:U.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 oe.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=O(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=Ne(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:i});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})}),Bt=m("/reset-password/:token",{method:"GET",query:U.z.object({callbackURL:U.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(nt(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(nt(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(jt(e.context,r,{token:t}))}),Vt=m("/reset-password",{query:U.z.optional(U.z.object({token:U.z.string().optional(),currentURL:U.z.string().optional()})),method:"POST",body:U.z.object({newPassword:U.z.string({description:"The new password to set"}),token:U.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 oe.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new oe.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(i)).find(d=>d.providerId==="credential")?(await e.context.internalAdapter.updatePassword(i,s),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:i}),e.json({status:!0}))});var A=require("zod");var R=require("better-call");var u=require("zod"),zt=require("better-call"),Tn=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)}),_n=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)}),Sn=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()}),Pn=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()});var qt=m("/change-password",{method:"POST",body:A.z.object({newPassword:A.z.string({description:"The new password to set"}),currentPassword:A.z.string({description:"The current password"}),revokeOtherSessions:A.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[P],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new 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(n.user.id)).find(l=>l.providerId==="credential"&&l.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(n.user.id);let l=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!l)throw new R.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await x(e,{session:l,user:n.user})}return e.json(n.user)}),Nt=m("/set-password",{method:"POST",body:A.z.object({newPassword:A.z.string()}),metadata:{SERVER_ONLY:!0},use:[P]},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 n=e.context.password.config.maxPasswordLength;if(t.length>n)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"})}),Ht=m("/delete-user",{method:"POST",body:A.z.object({password:A.z.string({description:"The password of the user"})}),use:[tt],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{let t=e.context.session;return await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),L(e),e.json(null)}),Ft=m("/change-email",{method:"POST",query:A.z.object({currentURL:A.z.string().optional()}).optional(),body:A.z.object({newEmail:A.z.string({description:"The new email to set"}).email(),callbackURL:A.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[P],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 n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new R.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await C(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),e.json({user:null,status:!0})});var Mt=(e="Unknown")=>`<!DOCTYPE html>
3
+ Error: `,c),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user;if(n){let c=n.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 me&&E.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),userId:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope})}catch(p){return E.error("Unable to link account",p),{error:"unable to link account",data:null}}}}else try{let c=t.emailVerified||!1;if(i=await e.context.internalAdapter.createOAuthUser({...t,id:void 0,emailVerified:c,email:t.email.toLowerCase()},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:t.id.toString()}).then(a=>a?.user),!c&&i&&e.context.options.emailVerification?.sendOnSignUp){let a=await C(e.context.secret,i.email),d=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:d,token:a},e.request)}}catch(c){return E.error("Unable to create user",c),{error:"unable to create user",data:null}}if(!i)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(i.id,e.request);return s?{data:{session:s,user:i},error:null}:{error:"unable to create session",data:null}}var It=m("/sign-in/social",{method:"POST",query:g.z.object({currentURL:g.z.string().optional()}).optional(),body:g.z.object({callbackURL:g.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),errorCallbackURL:g.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:g.z.enum(X,{description:"OAuth2 provider to use"}),disableRedirect:g.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:g.z.optional(g.z.object({token:g.z.string({description:"ID token from the provider"}),nonce:g.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:g.z.string({description:"Access token from the provider"}).optional(),refreshToken:g.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:g.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new b.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 b.APIError("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:i,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new b.APIError("UNAUTHORIZED",{message:"Invalid id token"});let a=await t.getUserInfo({idToken:i,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 b.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 b.APIError("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 b.APIError("UNAUTHORIZED",{message:d.error});return await x(e,d.data),e.json({session:d.data.session,user:d.data.user})}let{codeVerifier:r,state:o}=await Y(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),Lt=m("/sign-in/email",{method:"POST",body:g.z.object({email:g.z.string({description:"Email of the user"}),password:g.z.string({description:"Password of the user"}),callbackURL:g.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:g.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 b.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!g.z.string().email().safeParse(t).success)throw new b.APIError("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new b.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(d=>d.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new b.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new b.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new b.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new b.APIError("UNAUTHORIZED",{message:"Email is not verified."});let d=await C(e.context.secret,n.user.email),p=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:p,token:d},e.request),e.context.logger.error("Email not verified",{email:t}),new b.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new b.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await x(e,{session:a,user:n.user},e.body.rememberMe===!1),e.json({user:n.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var H=require("zod");var re=H.z.object({code:H.z.string().optional(),error:H.z.string().optional(),errorMessage:H.z.string().optional(),state:H.z.string().optional()}),Ot=m("/callback/:id",{method:["GET","POST"],body:re.optional(),query:re.optional(),metadata:$},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(v){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",v),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n}=t;if(!n)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 i=e.context.socialProviders.find(v=>v.id===e.params.id);if(!i)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 Ue(e),p;try{p=await i.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${i.id}`})}catch(v){throw e.context.logger.error("",v),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let l=await i.getUserInfo(p).then(v=>v?.user);function w(v){let _=d||c||`${e.context.baseURL}/error`;throw _.includes("?")?_=`${_}&error=${v}`:_=`${_}?error=${v}`,e.redirect(_)}if(!l)return e.context.logger.error("Unable to get user info"),w("unable_to_get_user_info");if(!l.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),w("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!==l.email.toLowerCase())return w("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:a.userId,providerId:i.id,accountId:l.id}))return w("unable_to_link_account");let _;try{_=new URL(c).toString()}catch{_=c}throw e.redirect(_)}let k=await te(e,{userInfo:{id:l.id,email:l.email,name:l.name||"",image:l.image,emailVerified:l.emailVerified||!1},account:{providerId:i.id,accountId:l.id,...p,scope:p.scopes?.join(",")},callbackURL:c});if(k.error)return e.context.logger.error(k.error.split(" ").join("_")),w(k.error.split(" ").join("_"));let{session:y,user:V}=k.data;await x(e,{session:y,user:V});let ne;try{ne=new URL(c).toString()}catch{ne=c}throw e.redirect(ne)});var yn=require("zod");var ot=require("better-call"),Ct=m("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw L(e),new ot.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),L(e),e.json({success:!0})});var U=require("zod");var oe=require("better-call");function nt(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function jt(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var Dt=m("/forget-password",{method:"POST",body:U.z.object({email:U.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:U.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 oe.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=O(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=Ne(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:i});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})}),Bt=m("/reset-password/:token",{method:"GET",query:U.z.object({callbackURL:U.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(nt(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(nt(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(jt(e.context,r,{token:t}))}),Vt=m("/reset-password",{query:U.z.optional(U.z.object({token:U.z.string().optional(),currentURL:U.z.string().optional()})),method:"POST",body:U.z.object({newPassword:U.z.string({description:"The new password to set"}),token:U.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 oe.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new oe.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(i)).find(d=>d.providerId==="credential")?(await e.context.internalAdapter.updatePassword(i,s),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:i}),e.json({status:!0}))});var A=require("zod");var R=require("better-call");var u=require("zod"),zt=require("better-call"),Tn=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)}),_n=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)}),Sn=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()}),Pn=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()});var qt=m("/change-password",{method:"POST",body:A.z.object({newPassword:A.z.string({description:"The new password to set"}),currentPassword:A.z.string({description:"The current password"}),revokeOtherSessions:A.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[P],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new 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(n.user.id)).find(l=>l.providerId==="credential"&&l.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(n.user.id);let l=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!l)throw new R.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await x(e,{session:l,user:n.user})}return e.json(n.user)}),Nt=m("/set-password",{method:"POST",body:A.z.object({newPassword:A.z.string()}),metadata:{SERVER_ONLY:!0},use:[P]},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 n=e.context.password.config.maxPasswordLength;if(t.length>n)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"})}),Ht=m("/delete-user",{method:"POST",body:A.z.object({password:A.z.string({description:"The password of the user"})}),use:[tt],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{let t=e.context.session;return await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),L(e),e.json(null)}),Ft=m("/change-email",{method:"POST",query:A.z.object({currentURL:A.z.string().optional()}).optional(),body:A.z.object({newEmail:A.z.string({description:"The new email to set"}).email(),callbackURL:A.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[P],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 n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new R.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await C(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),e.json({user:null,status:!0})});var Mt=(e="Unknown")=>`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">
@@ -1,5 +1,5 @@
1
1
  import * as better_call from 'better-call';
2
- import { H as HookEndpointContext } from './auth-XMAxn5Ae.cjs';
2
+ import { H as HookEndpointContext } from './auth-CRbxCgiW.cjs';
3
3
  import 'kysely';
4
4
  import 'zod';
5
5
  import './helper-D7-GCsit.cjs';
package/dist/next-js.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as better_call from 'better-call';
2
- import { H as HookEndpointContext } from './auth-DFawWk0e.js';
2
+ import { H as HookEndpointContext } from './auth-CnCuVMLa.js';
3
3
  import 'kysely';
4
4
  import 'zod';
5
5
  import './helper-D7-GCsit.js';
package/dist/next-js.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import{cookies as Gt}from"next/headers";import{TimeSpan as zs}from"oslo";import{base64url as Mt}from"oslo/encoding";import{HMAC as re,sha256 as Kt}from"oslo/crypto";async function Le({value:e,secret:t}){return new re("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function Oe({value:e,signature:t,secret:r}){return new re("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var M={sign:Le,verify:Oe};var j=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};var L=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var G=Object.create(null),z=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?G:globalThis),oe=new Proxy(G,{get(e,t){return z()[t]??G[t]},has(e,t){let r=z();return t in r||t in G},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 Ce(e){return e?e!=="false":!1}var Y=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var ne=Y==="dev"||Y==="development",je=Y==="test"||Ce(oe.TEST);import{APIError as ws,createRouter as ys,getCookie as bs,getSignedCookie as ks,setCookie as As,setSignedCookie as Us}from"better-call";import{APIError as Ve}from"better-call";import{createEndpointCreator as De,createMiddleware as ie,createMiddlewareCreator as Be}from"better-call";var se=ie(async()=>({})),$=Be({use:[se,ie(async()=>({}))]}),m=De({use:[se]});var ze=$(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=t?.callbackURL||r?.callbackURL,s=t?.redirectTo,c=r?.currentURL,a=o.trustedOrigins,d=e.headers?.has("cookie"),p=(w,k)=>k.includes("*")?new RegExp("^"+k.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(w):w.startsWith(k),l=(w,k)=>{if(!w)return;if(!a.some(B=>p(w,B)||w?.startsWith("/")&&k!=="origin"&&!w.includes(":")))throw e.context.logger.error(`Invalid ${k}: ${w}`),e.context.logger.info(`If it's a valid URL, please add ${w} to trustedOrigins in your auth config
2
2
  `,`Current list of trustedOrigins: ${a}`),new Ve("FORBIDDEN",{message:`Invalid ${k}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&l(n,"origin"),i&&l(i,"callbackURL"),s&&l(s,"redirectURL"),c&&l(c,"currentURL")});import{APIError as b}from"better-call";import{z as h}from"zod";import{betterFetch as Me}from"@better-fetch/fetch";import{APIError as Ge}from"better-call";import{decodeProtectedHeader as Ze,importJWK as Qe,jwtVerify as Je}from"jose";import{parseJWT as We}from"oslo/jwt";import{sha256 as $e}from"oslo/crypto";import{base64url as qe}from"oslo/encoding";async function ae(e){let t=await $e(new TextEncoder().encode(e));return qe.encode(new Uint8Array(t),{includePadding:!1})}function ce(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?L(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function g({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,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",i.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||c),n){let d=await ae(n);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",d)}if(s){let d=s.reduce((p,l)=>(p[l]=null,p),{});a.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...d}}))}return a}import{betterFetch as Ne}from"@better-fetch/fetch";async function f({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n,authentication:i}){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),i==="basic"){let l=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${l}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await Ne(n,{method:"POST",body:s,headers:c});if(d)throw d;return ce(a)}import{generateCodeVerifier as He,generateState as Fe}from"oslo/oauth2";import{z as O}from"zod";import{APIError as pe}from"better-call";function de(e){try{return new URL(e).origin}catch{return null}}async function Z(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?de(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new pe("BAD_REQUEST",{message:"callbackURL is required"});let o=He(),n=Fe(),i=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:i,identifier:n,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 pe("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function ue(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=O.object({callbackURL:O.string(),codeVerifier:O.string(),errorURL:O.string().optional(),expiresAt:O.number(),link:O.object({email:O.string(),userId:O.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 le=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>f({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let n=Ze(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let c=await Ke(i),{payload:a}=await Je(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=We(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email;return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email},data:o}}}},Ke=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await Me(`${t}${r}`);if(!o?.keys)throw new Ge("BAD_REQUEST",{message:"Keys not found"});let n=o.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await Qe(n,n.alg)};import{betterFetch as Ye}from"@better-fetch/fetch";var me=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>f({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 Ye("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}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});import{betterFetch as Xe}from"@better-fetch/fetch";var fe=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await g({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>f({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 Xe("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});import{betterFetch as ge}from"@better-fetch/fetch";var he=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),g({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>f({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await ge("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:c}=await ge("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});c||(o.email=(s.find(a=>a.primary)??s[0])?.email,i=s.find(a=>a.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};import{parseJWT as nt}from"oslo/jwt";import{createConsola as et}from"consola";var X=["info","success","warn","error","debug"];function tt(e,t){return X.indexOf(t)<=X.indexOf(e)}var rt=et({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),ot=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,s=[])=>{if(!(!t||!tt(r,n))){if(!e||typeof e.log!="function"){rt[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(X.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},R=ot();import{betterFetch as it}from"@better-fetch/fetch";var we=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw R.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new j("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new j("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await g({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});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})=>f({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:n}=await it(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=nt(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});import{betterFetch as st}from"@better-fetch/fetch";import{parseJWT as at}from"oslo/jwt";var ye=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),g({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return f({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=at(n.idToken)?.payload,s=e.profilePhotoSize||48;return await st(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let d=await c.response.clone().arrayBuffer(),p=Buffer.from(d).toString("base64");i.picture=`data:image/jpeg;base64, ${p}`}catch(a){R.error(a&&typeof a=="object"&&"name"in a?a.name:"",a)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as ct}from"@better-fetch/fetch";var be=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),g({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>f({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 ct("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});var V={isAction:!1};import{nanoid as dt}from"nanoid";var ke=e=>dt(e);import{parseJWT as pt}from"oslo/jwt";var Ae=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),g({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>f({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 R.error("No idToken found in token"),null;let o=pt(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as ut}from"@better-fetch/fetch";var Ue=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),g({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})=>f({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 ut("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{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},data:r}}});import{betterFetch as lt}from"@better-fetch/fetch";var Re=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await g({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await f({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await lt("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};import{betterFetch as mt}from"@better-fetch/fetch";var ve=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await g({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await f({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await mt("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};import{betterFetch as ft}from"@better-fetch/fetch";var ee=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),gt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ee(`${t}/oauth/authorize`),tokenEndpoint:ee(`${t}/oauth/token`),userinfoEndpoint:ee(`${t}/api/v4/user`)}},Ee=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=gt(e.issuer),n="gitlab";return{id:n,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 g({id:n,options:e,authorizationEndpoint:t,scopes:p,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>f({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 ft(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return a||c.state!=="active"||c.locked?null:{user:{id:c.id.toString(),name:c.name??c.username,email:c.email,image:c.avatar_url,emailVerified:!0},data:c}}}};var ht={apple:le,discord:me,facebook:fe,github:he,microsoft:ye,google:we,spotify:be,twitch:Ae,twitter:Ue,dropbox:Re,linkedin:ve,gitlab:Ee},Q=Object.keys(ht);import{TimeSpan as kt}from"oslo";import{createJWT as At,validateJWT as Ut}from"oslo/jwt";import{z as T}from"zod";import{APIError as N}from"better-call";import{APIError as P}from"better-call";import{z as q}from"zod";function xe(e){try{return JSON.parse(e)}catch{return null}}var Te=()=>m("/get-session",{method:"GET",query:q.optional(q.object({disableCookieCache:q.boolean({description:"Disable cookie cache and fetch session from database"}).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?xe(Buffer.from(r,"base64").toString()):null;if(o&&!await M.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return I(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let p=o.session;if(o.expiresAt<Date.now()||p.session.expiresAt<new Date){let w=e.context.authCookies.sessionData.name;e.setCookie(w,"",{maxAge:0})}else return e.json(p)}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return I(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n)return e.json(i);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let p=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:L(e.context.sessionConfig.expiresIn,"sec")});if(!p)return I(e),e.json(null,{status:401});let l=(p.expiresAt.valueOf()-Date.now())/1e3;return await v(e,{session:p,user:i.user},!1,{maxAge:l}),e.json({session:p,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new P("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),D=async e=>{if(e.context.session)return e.context.session;let t=await Te()({...e,_flag:"json",headers:e.headers});return e.context.session=t,t},S=$(async e=>{let t=await D(e);if(!t?.session)throw new P("UNAUTHORIZED");return{session:t}}),_e=$(async e=>{let t=await D(e);if(!t?.session)throw new P("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),n=Date.now();if(!(o+r*1e3>n))throw new P("FORBIDDEN",{message:"Session is not fresh"});return{session:t}});var wt=m("/revoke-session",{method:"POST",body:q.object({token:q.string({description:"The token to revoke"})}),use:[S],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 P("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new P("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 P("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),yt=m("/revoke-sessions",{method:"POST",use:[S],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 P("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),bt=m("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[S],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 P("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});async function C(e,t,r){return await At("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new kt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Rt(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new N("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await C(e.context.secret,t.email),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:r},e.request)}var vt=m("/send-verification-email",{method:"POST",query:T.object({currentURL:T.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:T.object({email:T.string({description:"The email to send the verification email to"}).email(),callbackURL:T.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 N("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new N("BAD_REQUEST",{message:"User not found"});return await Rt(e,r.user),e.json({status:!0})}),Et=m("/verify-email",{method:"GET",query:T.object({token:T.string({description:"The token to verify the email"}),callbackURL:T.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 N("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await Ut("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let i=T.object({email:T.string().email(),updateTo:T.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(i.email);if(!s)return t("user_not_found");if(i.updateTo){let c=await D(e);if(!c){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(c.user.email!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.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(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await D(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new N("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await v(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 J(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(c=>{throw R.error(`Better auth was unable to query your database.
3
- Error: `,c),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user;if(n){let c=n.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 ne&&R.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),userId:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope})}catch(p){return R.error("Unable to link account",p),{error:"unable to link account",data:null}}}}else try{let c=t.emailVerified||!1;if(i=await e.context.internalAdapter.createOAuthUser({...t,id:void 0,emailVerified:c,email:t.email.toLowerCase()},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:t.id.toString()}).then(a=>a?.user),!c&&i&&e.context.options.emailVerification?.sendOnSignUp){let a=await C(e.context.secret,i.email),d=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:d,token:a},e.request)}}catch(c){return R.error("Unable to create user",c),{error:"unable to create user",data:null}}if(!i)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(i.id,e.request);return s?{data:{session:s,user:i},error:null}:{error:"unable to create session",data:null}}var xt=m("/sign-in/social",{method:"POST",query:h.object({currentURL:h.string().optional()}).optional(),body:h.object({callbackURL:h.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),errorCallbackURL:h.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:h.enum(Q,{description:"OAuth2 provider to use"}),disableRedirect:h.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:h.optional(h.object({token:h.string({description:"ID token from the provider"}),nonce:h.string({description:"Nonce used to generate the token"}).optional(),accessToken:h.string({description:"Access token from the provider"}).optional(),refreshToken:h.string({description:"Refresh token from the provider"}).optional(),expiresAt:h.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new b("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 b("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:i,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new b("UNAUTHORIZED",{message:"Invalid id token"});let a=await t.getUserInfo({idToken:i,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 b("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 b("UNAUTHORIZED",{message:"User email not found"});let d=await J(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 b("UNAUTHORIZED",{message:d.error});return await v(e,d.data),e.json({session:d.data.session,user:d.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:r,state:o}=await Z(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),Tt=m("/sign-in/email",{method:"POST",body:h.object({email:h.string({description:"Email of the user"}),password:h.string({description:"Password of the user"}),callbackURL:h.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:h.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 b("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!h.string().email().safeParse(t).success)throw new b("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new b("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(d=>d.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new b("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new b("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new b("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new b("UNAUTHORIZED",{message:"Email is not verified."});let d=await C(e.context.secret,n.user.email),p=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:p,token:d},e.request),e.context.logger.error("Email not verified",{email:t}),new b("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new b("UNAUTHORIZED",{message:"Failed to create session"});return await v(e,{session:a,user:n.user},e.body.rememberMe===!1),e.json({user:n.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as H}from"zod";var W=H.object({code:H.string().optional(),error:H.string().optional(),errorMessage:H.string().optional(),state:H.string().optional()}),_t=m("/callback/:id",{method:["GET","POST"],body:W.optional(),query:W.optional(),metadata:V},async e=>{let t;try{if(e.method==="GET")t=W.parse(e.query);else if(e.method==="POST")t=W.parse(e.body);else throw new Error("Unsupported method")}catch(U){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",U),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n}=t;if(!n)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 i=e.context.socialProviders.find(U=>U.id===e.params.id);if(!i)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 ue(e),p;try{p=await i.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${i.id}`})}catch(U){throw e.context.logger.error("",U),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let l=await i.getUserInfo(p).then(U=>U?.user);function w(U){let _=d||c||`${e.context.baseURL}/error`;throw _.includes("?")?_=`${_}&error=${U}`:_=`${_}?error=${U}`,e.redirect(_)}if(!l)return e.context.logger.error("Unable to get user info"),w("unable_to_get_user_info");if(!l.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),w("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!==l.email.toLowerCase())return w("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:a.userId,providerId:i.id,accountId:l.id}))return w("unable_to_link_account");let _;try{_=new URL(c).toString()}catch{_=c}throw e.redirect(_)}let k=await J(e,{userInfo:{id:l.id,email:l.email,name:l.name||"",image:l.image,emailVerified:l.emailVerified||!1},account:{providerId:i.id,accountId:l.id,...p,scope:p.scopes?.join(",")},callbackURL:c});if(k.error)return e.context.logger.error(k.error.split(" ").join("_")),w(k.error.split(" ").join("_"));let{session:y,user:B}=k.data;await v(e,{session:y,user:B});let K;try{K=new URL(c).toString()}catch{K=c}throw e.redirect(K)});import"zod";import{APIError as St}from"better-call";var Pt=m("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw I(e),new St("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),I(e),e.json({success:!0})});import{z as E}from"zod";import{APIError as te}from"better-call";function Se(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function It(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var Lt=m("/forget-password",{method:"POST",body:E.object({email:E.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:E.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 te("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=L(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=ke(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:i});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})}),Ot=m("/reset-password/:token",{method:"GET",query:E.object({callbackURL:E.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(Se(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Se(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(It(e.context,r,{token:t}))}),Ct=m("/reset-password",{query:E.optional(E.object({token:E.string().optional(),currentURL:E.string().optional()})),method:"POST",body:E.object({newPassword:E.string({description:"The new password to set"}),token:E.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 te("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new te("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(i)).find(d=>d.providerId==="credential")?(await e.context.internalAdapter.updatePassword(i,s),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:i}),e.json({status:!0}))});import{z as A}from"zod";import{APIError as x}from"better-call";import{z as u}from"zod";import{APIError as ii}from"better-call";var si=u.object({id:u.string(),providerId:u.string(),accountId:u.string(),userId:u.string(),accessToken:u.string().nullish(),refreshToken:u.string().nullish(),idToken:u.string().nullish(),accessTokenExpiresAt:u.date().nullish(),refreshTokenExpiresAt:u.date().nullish(),scope:u.string().nullish(),password:u.string().nullish(),createdAt:u.date().default(()=>new Date),updatedAt:u.date().default(()=>new Date)}),ai=u.object({id:u.string(),email:u.string().transform(e=>e.toLowerCase()),emailVerified:u.boolean().default(!1),name:u.string(),image:u.string().nullish(),createdAt:u.date().default(()=>new Date),updatedAt:u.date().default(()=>new Date)}),ci=u.object({id:u.string(),userId:u.string(),expiresAt:u.date(),createdAt:u.date().default(()=>new Date),updatedAt:u.date().default(()=>new Date),token:u.string(),ipAddress:u.string().nullish(),userAgent:u.string().nullish()}),di=u.object({id:u.string(),value:u.string(),createdAt:u.date().default(()=>new Date),updatedAt:u.date().default(()=>new Date),expiresAt:u.date(),identifier:u.string()});var Dt=m("/change-password",{method:"POST",body:A.object({newPassword:A.string({description:"The new password to set"}),currentPassword:A.string({description:"The current password"}),revokeOtherSessions:A.boolean({description:"Revoke all other sessions"}).optional()}),use:[S],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new x("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 x("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(l=>l.providerId==="credential"&&l.password);if(!a||!a.password)throw new x("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 x("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(a.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let l=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!l)throw new x("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await v(e,{session:l,user:n.user})}return e.json(n.user)}),Bt=m("/set-password",{method:"POST",body:A.object({newPassword:A.string()}),metadata:{SERVER_ONLY:!0},use:[S]},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 x("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new x("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 x("BAD_REQUEST",{message:"user already has a password"})}),Vt=m("/delete-user",{method:"POST",body:A.object({password:A.string({description:"The password of the user"})}),use:[_e],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{let t=e.context.session;return await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),I(e),e.json(null)}),zt=m("/change-email",{method:"POST",query:A.object({currentURL:A.string().optional()}).optional(),body:A.object({newEmail:A.string({description:"The new email to set"}).email(),callbackURL:A.string({description:"The URL to redirect to after email verification"}).optional()}),use:[S],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 x("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 x("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 x("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new x("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await C(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),e.json({user:null,status:!0})});var $t=(e="Unknown")=>`<!DOCTYPE html>
3
+ Error: `,c),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user;if(n){let c=n.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 ne&&R.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),userId:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope})}catch(p){return R.error("Unable to link account",p),{error:"unable to link account",data:null}}}}else try{let c=t.emailVerified||!1;if(i=await e.context.internalAdapter.createOAuthUser({...t,id:void 0,emailVerified:c,email:t.email.toLowerCase()},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:t.id.toString()}).then(a=>a?.user),!c&&i&&e.context.options.emailVerification?.sendOnSignUp){let a=await C(e.context.secret,i.email),d=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:d,token:a},e.request)}}catch(c){return R.error("Unable to create user",c),{error:"unable to create user",data:null}}if(!i)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(i.id,e.request);return s?{data:{session:s,user:i},error:null}:{error:"unable to create session",data:null}}var xt=m("/sign-in/social",{method:"POST",query:h.object({currentURL:h.string().optional()}).optional(),body:h.object({callbackURL:h.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),errorCallbackURL:h.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:h.enum(Q,{description:"OAuth2 provider to use"}),disableRedirect:h.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:h.optional(h.object({token:h.string({description:"ID token from the provider"}),nonce:h.string({description:"Nonce used to generate the token"}).optional(),accessToken:h.string({description:"Access token from the provider"}).optional(),refreshToken:h.string({description:"Refresh token from the provider"}).optional(),expiresAt:h.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new b("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 b("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:i,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new b("UNAUTHORIZED",{message:"Invalid id token"});let a=await t.getUserInfo({idToken:i,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 b("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 b("UNAUTHORIZED",{message:"User email not found"});let d=await J(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 b("UNAUTHORIZED",{message:d.error});return await v(e,d.data),e.json({session:d.data.session,user:d.data.user})}let{codeVerifier:r,state:o}=await Z(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),Tt=m("/sign-in/email",{method:"POST",body:h.object({email:h.string({description:"Email of the user"}),password:h.string({description:"Password of the user"}),callbackURL:h.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:h.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 b("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!h.string().email().safeParse(t).success)throw new b("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new b("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(d=>d.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new b("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new b("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new b("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new b("UNAUTHORIZED",{message:"Email is not verified."});let d=await C(e.context.secret,n.user.email),p=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:p,token:d},e.request),e.context.logger.error("Email not verified",{email:t}),new b("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new b("UNAUTHORIZED",{message:"Failed to create session"});return await v(e,{session:a,user:n.user},e.body.rememberMe===!1),e.json({user:n.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as H}from"zod";var W=H.object({code:H.string().optional(),error:H.string().optional(),errorMessage:H.string().optional(),state:H.string().optional()}),_t=m("/callback/:id",{method:["GET","POST"],body:W.optional(),query:W.optional(),metadata:V},async e=>{let t;try{if(e.method==="GET")t=W.parse(e.query);else if(e.method==="POST")t=W.parse(e.body);else throw new Error("Unsupported method")}catch(U){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",U),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n}=t;if(!n)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 i=e.context.socialProviders.find(U=>U.id===e.params.id);if(!i)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 ue(e),p;try{p=await i.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${i.id}`})}catch(U){throw e.context.logger.error("",U),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let l=await i.getUserInfo(p).then(U=>U?.user);function w(U){let _=d||c||`${e.context.baseURL}/error`;throw _.includes("?")?_=`${_}&error=${U}`:_=`${_}?error=${U}`,e.redirect(_)}if(!l)return e.context.logger.error("Unable to get user info"),w("unable_to_get_user_info");if(!l.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),w("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!==l.email.toLowerCase())return w("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:a.userId,providerId:i.id,accountId:l.id}))return w("unable_to_link_account");let _;try{_=new URL(c).toString()}catch{_=c}throw e.redirect(_)}let k=await J(e,{userInfo:{id:l.id,email:l.email,name:l.name||"",image:l.image,emailVerified:l.emailVerified||!1},account:{providerId:i.id,accountId:l.id,...p,scope:p.scopes?.join(",")},callbackURL:c});if(k.error)return e.context.logger.error(k.error.split(" ").join("_")),w(k.error.split(" ").join("_"));let{session:y,user:B}=k.data;await v(e,{session:y,user:B});let K;try{K=new URL(c).toString()}catch{K=c}throw e.redirect(K)});import"zod";import{APIError as St}from"better-call";var Pt=m("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw I(e),new St("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),I(e),e.json({success:!0})});import{z as E}from"zod";import{APIError as te}from"better-call";function Se(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function It(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var Lt=m("/forget-password",{method:"POST",body:E.object({email:E.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:E.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 te("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=L(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=ke(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:i});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})}),Ot=m("/reset-password/:token",{method:"GET",query:E.object({callbackURL:E.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(Se(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Se(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(It(e.context,r,{token:t}))}),Ct=m("/reset-password",{query:E.optional(E.object({token:E.string().optional(),currentURL:E.string().optional()})),method:"POST",body:E.object({newPassword:E.string({description:"The new password to set"}),token:E.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 te("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new te("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(i)).find(d=>d.providerId==="credential")?(await e.context.internalAdapter.updatePassword(i,s),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:i}),e.json({status:!0}))});import{z as A}from"zod";import{APIError as x}from"better-call";import{z as u}from"zod";import{APIError as ii}from"better-call";var si=u.object({id:u.string(),providerId:u.string(),accountId:u.string(),userId:u.string(),accessToken:u.string().nullish(),refreshToken:u.string().nullish(),idToken:u.string().nullish(),accessTokenExpiresAt:u.date().nullish(),refreshTokenExpiresAt:u.date().nullish(),scope:u.string().nullish(),password:u.string().nullish(),createdAt:u.date().default(()=>new Date),updatedAt:u.date().default(()=>new Date)}),ai=u.object({id:u.string(),email:u.string().transform(e=>e.toLowerCase()),emailVerified:u.boolean().default(!1),name:u.string(),image:u.string().nullish(),createdAt:u.date().default(()=>new Date),updatedAt:u.date().default(()=>new Date)}),ci=u.object({id:u.string(),userId:u.string(),expiresAt:u.date(),createdAt:u.date().default(()=>new Date),updatedAt:u.date().default(()=>new Date),token:u.string(),ipAddress:u.string().nullish(),userAgent:u.string().nullish()}),di=u.object({id:u.string(),value:u.string(),createdAt:u.date().default(()=>new Date),updatedAt:u.date().default(()=>new Date),expiresAt:u.date(),identifier:u.string()});var Dt=m("/change-password",{method:"POST",body:A.object({newPassword:A.string({description:"The new password to set"}),currentPassword:A.string({description:"The current password"}),revokeOtherSessions:A.boolean({description:"Revoke all other sessions"}).optional()}),use:[S],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new x("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 x("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(l=>l.providerId==="credential"&&l.password);if(!a||!a.password)throw new x("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 x("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(a.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let l=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!l)throw new x("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await v(e,{session:l,user:n.user})}return e.json(n.user)}),Bt=m("/set-password",{method:"POST",body:A.object({newPassword:A.string()}),metadata:{SERVER_ONLY:!0},use:[S]},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 x("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new x("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 x("BAD_REQUEST",{message:"user already has a password"})}),Vt=m("/delete-user",{method:"POST",body:A.object({password:A.string({description:"The password of the user"})}),use:[_e],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{let t=e.context.session;return await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),I(e),e.json(null)}),zt=m("/change-email",{method:"POST",query:A.object({currentURL:A.string().optional()}).optional(),body:A.object({newEmail:A.string({description:"The new email to set"}).email(),callbackURL:A.string({description:"The URL to redirect to after email verification"}).optional()}),use:[S],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 x("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 x("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 x("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new x("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await C(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),e.json({user:null,status:!0})});var $t=(e="Unknown")=>`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">
package/dist/node.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as http from 'http';
2
2
  import { IncomingHttpHeaders } from 'http';
3
- import { A as Auth } from './auth-XMAxn5Ae.cjs';
3
+ import { A as Auth } from './auth-CRbxCgiW.cjs';
4
4
  import 'kysely';
5
5
  import 'zod';
6
6
  import 'better-call';
package/dist/node.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as http from 'http';
2
2
  import { IncomingHttpHeaders } from 'http';
3
- import { A as Auth } from './auth-DFawWk0e.js';
3
+ import { A as Auth } from './auth-CnCuVMLa.js';
4
4
  import 'kysely';
5
5
  import 'zod';
6
6
  import 'better-call';
package/dist/oauth2.d.cts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { P as ProviderOptions, O as OAuth2Tokens } from './index-BSB3JIBV.cjs';
2
2
  export { a as OAuthProvider } from './index-BSB3JIBV.cjs';
3
- export { g as generateState, p as parseState } from './state-BkCnjHc0.cjs';
3
+ export { g as generateState, p as parseState } from './state-DLdB9N6W.cjs';
4
4
  import './helper-D7-GCsit.cjs';
5
5
  import 'zod';
6
6
  import 'jose';
7
- import './auth-XMAxn5Ae.cjs';
7
+ import './auth-CRbxCgiW.cjs';
8
8
  import 'kysely';
9
9
  import 'better-call';
10
10
  import 'better-sqlite3';
package/dist/oauth2.d.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { P as ProviderOptions, O as OAuth2Tokens } from './index-CHOS4Wd2.js';
2
2
  export { a as OAuthProvider } from './index-CHOS4Wd2.js';
3
- export { g as generateState, p as parseState } from './state-BsON3MFE.js';
3
+ export { g as generateState, p as parseState } from './state-CwZsNu9d.js';
4
4
  import './helper-D7-GCsit.js';
5
5
  import 'zod';
6
6
  import 'jose';
7
- import './auth-DFawWk0e.js';
7
+ import './auth-CnCuVMLa.js';
8
8
  import 'kysely';
9
9
  import 'better-call';
10
10
  import 'better-sqlite3';