better-auth 0.7.3-beta.7 → 0.7.3-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.cjs +1 -1
- package/dist/api.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/oauth2.cjs +1 -1
- package/dist/oauth2.js +1 -1
- package/dist/plugins.cjs +4 -4
- package/dist/plugins.js +4 -4
- package/package.json +1 -1
package/dist/api.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var ne=Object.defineProperty;var Ot=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var Lt=Object.prototype.hasOwnProperty;var It=(e,t)=>{for(var r in t)ne(e,r,{get:t[r],enumerable:!0})},Ct=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of St(t))!Lt.call(e,i)&&i!==r&&ne(e,i,{get:()=>t[i],enumerable:!(o=Ot(t,i))||o.enumerable});return e};var Dt=e=>Ct(ne({},"__esModule",{value:!0}),e);var Kt={};It(Kt,{APIError:()=>Pt.APIError,callbackOAuth:()=>ye,changeEmail:()=>Pe,changePassword:()=>ve,createAuthEndpoint:()=>p,createAuthMiddleware:()=>Q,createEmailVerificationToken:()=>S,deleteUser:()=>xe,error:()=>Te,forgetPassword:()=>ke,forgetPasswordCallback:()=>Re,getEndpoints:()=>xt,getSession:()=>ee,getSessionFromCtx:()=>te,linkSocialAccount:()=>Ce,listSessions:()=>pe,listUserAccounts:()=>Ie,ok:()=>Oe,optionsMiddleware:()=>se,originCheckMiddleware:()=>ce,resetPassword:()=>Ue,revokeSession:()=>me,revokeSessions:()=>fe,router:()=>Yt,sendVerificationEmail:()=>ge,sessionMiddleware:()=>v,setPassword:()=>_e,signInEmail:()=>be,signInSocial:()=>we,signOut:()=>Ae,signUpEmail:()=>Se,updateUser:()=>Ee,verifyEmail:()=>he});module.exports=Dt(Kt);var $=require("better-call");var Me=require("better-call");var C=require("better-call"),se=(0,C.createMiddleware)(async()=>({})),Q=(0,C.createMiddlewareCreator)({use:[se,(0,C.createMiddleware)(async()=>({}))]}),p=(0,C.createEndpointCreator)({use:[se]});var q={isAction:!1};var Be=require("nanoid"),ze=e=>(0,Be.nanoid)(e);var Y=require("oslo/oauth2"),I=require("zod"),de=require("better-call");var W=Object.create(null),H=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?W:globalThis),Ve=new Proxy(W,{get(e,t){return H()[t]??W[t]},has(e,t){let r=H();return t in r||t in W},set(e,t,r){let o=H(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=H(!0);return delete r[t],!0},ownKeys(){let e=H(!0);return Object.keys(e)}});function Bt(e){return e?e!=="false":!1}var ae=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var je=ae==="dev"||ae==="development",$e=ae==="test"||Bt(Ve.TEST);var D=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}};function qe(e){try{return new URL(e).origin}catch{return null}}async function K(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?qe(e.query?.currentURL):"");if(!r)throw new de.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,Y.generateCodeVerifier)(),i=(0,Y.generateState)(),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:s});if(!a)throw f.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new de.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function Ne(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw f.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),f.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 Fe=require("consola"),B=(0,Fe.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),zt=e=>({log:(...t)=>{!e?.disabled&&B.log("",...t)},error:(...t)=>{!e?.disabled&&B.error("",...t)},warn:(...t)=>{!e?.disabled&&B.warn("",...t)},info:(...t)=>{!e?.disabled&&B.info("",...t)},debug:(...t)=>{!e?.disabled&&B.debug("",...t)},box:(...t)=>{!e?.disabled&&B.box("",...t)},success:(...t)=>{!e?.disabled&&B.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
1
|
+
"use strict";var ne=Object.defineProperty;var Ot=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var Lt=Object.prototype.hasOwnProperty;var It=(e,t)=>{for(var r in t)ne(e,r,{get:t[r],enumerable:!0})},Ct=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of St(t))!Lt.call(e,i)&&i!==r&&ne(e,i,{get:()=>t[i],enumerable:!(o=Ot(t,i))||o.enumerable});return e};var Dt=e=>Ct(ne({},"__esModule",{value:!0}),e);var Kt={};It(Kt,{APIError:()=>Pt.APIError,callbackOAuth:()=>ye,changeEmail:()=>Pe,changePassword:()=>ve,createAuthEndpoint:()=>p,createAuthMiddleware:()=>Q,createEmailVerificationToken:()=>S,deleteUser:()=>xe,error:()=>Te,forgetPassword:()=>ke,forgetPasswordCallback:()=>Re,getEndpoints:()=>xt,getSession:()=>ee,getSessionFromCtx:()=>te,linkSocialAccount:()=>Ce,listSessions:()=>pe,listUserAccounts:()=>Ie,ok:()=>Oe,optionsMiddleware:()=>se,originCheckMiddleware:()=>ce,resetPassword:()=>Ue,revokeSession:()=>me,revokeSessions:()=>fe,router:()=>Yt,sendVerificationEmail:()=>ge,sessionMiddleware:()=>v,setPassword:()=>_e,signInEmail:()=>be,signInSocial:()=>we,signOut:()=>Ae,signUpEmail:()=>Se,updateUser:()=>Ee,verifyEmail:()=>he});module.exports=Dt(Kt);var $=require("better-call");var Me=require("better-call");var C=require("better-call"),se=(0,C.createMiddleware)(async()=>({})),Q=(0,C.createMiddlewareCreator)({use:[se,(0,C.createMiddleware)(async()=>({}))]}),p=(0,C.createEndpointCreator)({use:[se]});var q={isAction:!1};var Be=require("nanoid"),ze=e=>(0,Be.nanoid)(e);var Y=require("oslo/oauth2"),I=require("zod"),de=require("better-call");var W=Object.create(null),H=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?W:globalThis),Ve=new Proxy(W,{get(e,t){return H()[t]??W[t]},has(e,t){let r=H();return t in r||t in W},set(e,t,r){let o=H(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=H(!0);return delete r[t],!0},ownKeys(){let e=H(!0);return Object.keys(e)}});function Bt(e){return e?e!=="false":!1}var ae=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var je=ae==="dev"||ae==="development",$e=ae==="test"||Bt(Ve.TEST);var D=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}};function qe(e){try{return new URL(e).origin}catch{return null}}async function K(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?qe(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new de.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,Y.generateCodeVerifier)(),i=(0,Y.generateState)(),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:s});if(!a)throw f.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new de.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function Ne(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw f.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),f.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 Fe=require("consola"),B=(0,Fe.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),zt=e=>({log:(...t)=>{!e?.disabled&&B.log("",...t)},error:(...t)=>{!e?.disabled&&B.error("",...t)},warn:(...t)=>{!e?.disabled&&B.warn("",...t)},info:(...t)=>{!e?.disabled&&B.info("",...t)},debug:(...t)=>{!e?.disabled&&B.debug("",...t)},box:(...t)=>{!e?.disabled&&B.box("",...t)},success:(...t)=>{!e?.disabled&&B.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
2
|
`)}}),f=zt();var ce=Q(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,i=e.headers?.get("origin")||e.headers?.get("referer")||"",n=t?.callbackURL,s=t?.redirectTo,a=r?.currentURL,l=o.trustedOrigins,d=e.headers?.has("cookie"),c=(h,m)=>{if(!l.some(k=>h?.startsWith(k)||h?.startsWith("/")&&m!=="origin"))throw f.error(`Invalid ${m}: ${h}`),f.info(`If it's a valid URL, please add ${h} to trustedOrigins in your auth config
|
|
3
3
|
`,`Current list of trustedOrigins: ${l}`),new Me.APIError("FORBIDDEN",{message:`Invalid ${m}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&c(i,"origin"),n&&c(n,"callbackURL"),s&&c(s,"redirectURL"),a&&c(a,"currentURL")});var P=require("better-call"),_=require("zod");var Vt=require("oslo");async function O(e,t,r,o){let i=e.context.authCookies.sessionToken.options;i.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.id,e.context.secret,{...i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&await e.setSignedCookie(e.context.authCookies.sessionData.name,JSON.stringify(t),e.context.secret,e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.id,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function z(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}var We=require("oslo/jwt");var Ge=require("oslo/crypto"),Qe=require("oslo/encoding");var N=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function He(e){let t=await(0,Ge.sha256)(new TextEncoder().encode(e));return Qe.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Ze(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?N(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:s,disablePkce:a,redirectURI:l}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||l),!a&&i){let c=await He(i);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",c)}if(s){let c=s.reduce((h,m)=>(h[m]=null,h),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...c}}))}return d}var Je=require("@better-fetch/fetch");async function y({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i}){let n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),t&&n.set("code_verifier",t),n.set("redirect_uri",r),n.set("client_id",o.clientId),n.set("client_secret",o.clientSecret);let{data:s,error:a}=await(0,Je.betterFetch)(i,{method:"POST",body:n,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(a)throw a;return Ze(s)}var Ye=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=o||["email","name","openid"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>y({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=(0,We.parseJWT)(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};var Ke=require("@better-fetch/fetch");var Xe=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,Ke.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var et=require("@better-fetch/fetch");var tt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await(0,et.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});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 le=require("@better-fetch/fetch");var rt=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await(0,le.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:s,error:a}=await(0,le.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(l=>l.primary)??s[0])?.email,n=s.find(l=>l.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n},data:o}}}};var ot=require("oslo/jwt");var it=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw f.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new D("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new D("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=(0,ot.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 nt=require("@better-fetch/fetch"),st=require("oslo/jwt");var at=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),A({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return y({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(!i.idToken)return null;let n=(0,st.parseJWT)(i.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,nt.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let d=await a.response.clone().arrayBuffer(),c=Buffer.from(d).toString("base64");n.picture=`data:image/jpeg;base64, ${c}`}catch(l){f.error(l)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};var dt=require("@better-fetch/fetch");var ct=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,dt.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 oo=require("@better-fetch/fetch");var lt=require("oslo/jwt");var ut=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return f.error("No idToken found in token"),null;let o=(0,lt.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var pt=require("@better-fetch/fetch");var mt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["account_info.read"];return e.scope&&r.push(...e.scope),A({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,pt.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var ft=require("@better-fetch/fetch");var gt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await y({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await(0,ft.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return i?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 ht=require("@better-fetch/fetch");var wt=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await y({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await(0,ht.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return n?null:{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture},data:i}}}};var bt=require("@better-fetch/fetch");var ue=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),jt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ue(`${t}/oauth/authorize`),tokenEndpoint:ue(`${t}/oauth/token`),userinfoEndpoint:ue(`${t}/api/v4/user`)}},yt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=jt(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:l,redirectURI:d})=>{let c=a||["read_user"];return e.scope&&c.push(...e.scope),await A({id:i,options:e,authorizationEndpoint:t,scopes:c,state:s,redirectURI:d,codeVerifier:l})},validateAuthorizationCode:async({code:s,redirectURI:a})=>y({code:s,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:l}=await(0,bt.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return l||a.state!=="active"||a.locked?null:{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0},data:a}}}};var $t={apple:Ye,discord:Xe,facebook:tt,github:rt,microsoft:at,google:it,spotify:ct,twitch:ut,twitter:mt,dropbox:gt,linkedin:wt,gitlab:yt},X=Object.keys($t);var At=require("oslo"),re=require("oslo/jwt"),x=require("zod");var V=require("better-call");var F=require("better-call");var M=require("zod"),ee=()=>p("/get-session",{method:"GET",query:M.z.optional(M.z.object({disableCookieCache:M.z.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.getSignedCookie(e.context.authCookies.sessionData.name,e.context.secret),o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(r&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let d=JSON.parse(r)?.session;if(d?.expiresAt>new Date)return e.json(d)}let i=await e.context.internalAdapter.findSession(t);if(!i||i.session.expiresAt<new Date)return z(e),i&&await e.context.internalAdapter.deleteSession(i.session.id),e.json(null,{status:401});if(o)return e.json(i);let n=e.context.sessionConfig.expiresIn,s=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-n*1e3+s*1e3<=Date.now()){let d=await e.context.internalAdapter.updateSession(i.session.id,{expiresAt:N(e.context.sessionConfig.expiresIn,"sec")});if(!d)return z(e),e.json(null,{status:401});let c=(d.expiresAt.valueOf()-Date.now())/1e3;return await O(e,{session:d,user:i.user},!1,{maxAge:c}),e.json({session:d,user:i.user})}return e.json(i)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),te=async e=>await ee()({...e,_flag:"json",headers:e.headers}),v=Q(async e=>{let t=await te(e);if(!t?.session)throw new F.APIError("UNAUTHORIZED");return{session:t}}),pe=()=>p("/list-sessions",{method:"GET",use:[v],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),me=p("/revoke-session",{method:"POST",body:M.z.object({id:M.z.string()}),use:[v],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new F.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new F.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new F.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),fe=p("/revoke-sessions",{method:"POST",use:[v],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new F.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function S(e,t,r){return await(0,re.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new At.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var ge=p("/send-verification-email",{method:"POST",query:x.z.object({currentURL:x.z.string().optional()}).optional(),body:x.z.object({email:x.z.string().email(),callbackURL:x.z.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new V.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 V.APIError("BAD_REQUEST",{message:"User not found"});let o=await S(e.context.secret,t),i=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,i,o),e.json({status:!0})}),he=p("/verify-email",{method:"GET",query:x.z.object({token:x.z.string(),callbackURL:x.z.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await(0,re.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new V.APIError("BAD_REQUEST",{message:"Invalid token"})}let i=x.z.object({email:x.z.string().email(),updateTo:x.z.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(i.email))throw new V.APIError("BAD_REQUEST",{message:"User not found"});if(i.updateTo){let s=await te(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new V.APIError("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==i.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new V.APIError("UNAUTHORIZED",{message:"Invalid session"});let a=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(a,`${e.context.baseURL}/verify-email?token=${t}`,t),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.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var we=p("/sign-in/social",{method:"POST",query:_.z.object({currentURL:_.z.string().optional()}).optional(),body:_.z.object({callbackURL:_.z.string().optional(),provider:_.z.enum(X)})},async e=>{let t=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new P.APIError("NOT_FOUND",{message:"Provider not found"});let{codeVerifier:r,state:o}=await K(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!0})}),be=p("/sign-in/email",{method:"POST",body:_.z.object({email:_.z.string(),password:_.z.string(),callbackURL:_.z.string().optional(),dontRememberMe:_.z.boolean().default(!1).optional()})},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 P.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!_.z.string().email().safeParse(t).success)throw new P.APIError("BAD_REQUEST",{message:"Invalid email"});if(!_.z.string().email().safeParse(t).success)throw new P.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 P.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=n.accounts.find(c=>c.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let a=s?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new P.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw f.error("Email verification is required but no email verification handler is provided"),new P.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await S(e.context.secret,n.user.email),h=`${e.context.options.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,h,c),e.context.logger.error("Email not verified",{email:t}),new P.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new P.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await O(e,{session:d,user:n.user},e.body.dontRememberMe),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Z=require("zod");var g=require("zod"),ti=g.z.object({id:g.z.string(),providerId:g.z.string(),accountId:g.z.string(),userId:g.z.string(),accessToken:g.z.string().nullable().optional(),refreshToken:g.z.string().nullable().optional(),idToken:g.z.string().nullable().optional(),expiresAt:g.z.date().nullable().optional(),password:g.z.string().optional().nullable()}),kt=g.z.object({id:g.z.string(),email:g.z.string().transform(e=>e.toLowerCase()),emailVerified:g.z.boolean().default(!1),name:g.z.string(),image:g.z.string().optional(),createdAt:g.z.date().default(new Date),updatedAt:g.z.date().default(new Date)}),ri=g.z.object({id:g.z.string(),userId:g.z.string(),expiresAt:g.z.date(),ipAddress:g.z.string().optional(),userAgent:g.z.string().optional()}),oi=g.z.object({id:g.z.string(),value:g.z.string(),expiresAt:g.z.date(),identifier:g.z.string()});function qt(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function Nt(e,t){let r=t.action||"create",o=t.fields,i={};for(let n in o){if(n in e){if(o[n].input===!1){if(o[n].defaultValue){i[n]=o[n].defaultValue;continue}continue}i[n]=e[n];continue}if(o[n].defaultValue&&r==="create"){i[n]=o[n].defaultValue;continue}}return i}function oe(e,t,r){let o=qt(e,"user");return Nt(t||{},{fields:o,action:r})}var ye=p("/callback/:id",{method:"GET",query:Z.z.object({state:Z.z.string(),code:Z.z.string().optional(),error:Z.z.string().optional()}),metadata:q},async e=>{if(!e.query.code)throw e.redirect(`${e.context.baseURL}/error?error=${e.query.error||"no_code"}`);let t=e.context.socialProviders.find(w=>w.id===e.params.id);if(!t)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:r,callbackURL:o,link:i,errorURL:n}=await Ne(e),s;try{s=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(w){throw e.context.logger.error(w),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(s).then(w=>w?.user),l=ze(),d=kt.safeParse({...a,id:l});if(!a||d.success===!1)throw f.error("Unable to get user info",d.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw f.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(i){if(i.email!==a.email.toLowerCase())return c("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:i.userId,providerId:t.id,accountId:a.id}))return c("unable_to_link_account");let b;try{b=new URL(o).toString()}catch{b=o}throw e.redirect(b)}function c(w){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${w}`)}let h=await e.context.internalAdapter.findUserByEmail(a.email,{includeAccounts:!0}).catch(w=>{throw f.error(`Better auth was unable to query your database.
|
|
4
4
|
Error: `,w),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),m=h?.user;if(h){let w=h.accounts.find(b=>b.providerId===t.id);if(w)await e.context.internalAdapter.updateAccount(w.id,{accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt});else{(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!a.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)&&(je&&f.warn(`User already exist but account isn't linked to ${t.id}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),c("account_not_linked"));try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:a.id.toString(),id:`${t.id}:${a.id}`,userId:h.user.id,accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt})}catch(De){f.error("Unable to link account",De),c("unable_to_link_account")}}}else try{let w=a.emailVerified||!1;if(m=await e.context.internalAdapter.createOAuthUser({...d.data,emailVerified:w},{accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt,providerId:t.id,accountId:a.id.toString()}).then(b=>b?.user),!w&&m&&e.context.options.emailVerification?.sendOnSignUp){let b=await S(e.context.secret,m.email),R=`${e.context.baseURL}/verify-email?token=${b}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(m,R,b)}}catch(w){f.error("Unable to create user",w),c("unable_to_create_user")}if(!m)return c("unable_to_create_user");let u=await e.context.internalAdapter.createSession(m.id,e.request);u||c("unable_to_create_session"),await O(e,{session:u,user:m});let k;try{k=new URL(o).toString()}catch{k=o}throw e.redirect(k)});var gi=require("zod");var Rt=require("better-call"),Ae=p("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Rt.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),z(e),e.json({success:!0})});var T=require("zod");var J=require("better-call");function Ut(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}function Ft(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}var ke=p("/forget-password",{method:"POST",body:T.z.object({email:T.z.string().email(),redirectTo:T.z.string()})},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new J.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let i=60*60*1,n=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||i)),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:n});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,a),e.json({status:!0})}),Re=p("/reset-password/:token",{method:"GET",query:T.z.object({callbackURL:T.z.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(Ut(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Ut(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Ft(e.context,r,{token:t}))}),Ue=p("/reset-password",{query:T.z.optional(T.z.object({token:T.z.string().optional(),currentURL:T.z.string().optional()})),method:"POST",body:T.z.object({newPassword:T.z.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new J.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,i=await e.context.internalAdapter.findVerificationValue(o);if(!i||i.expiresAt<new Date)throw new J.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(i.id);let n=i.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(n)).find(c=>c.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(n,s))throw new J.APIError("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});var U=require("zod");var E=require("better-call");var Ee=()=>p("/update-user",{method:"POST",body:U.z.record(U.z.string(),U.z.any()),use:[v]},async e=>{let t=e.body;if(t.email)throw new E.APIError("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...i}=t,n=e.context.session;if(!o&&!r&&Object.keys(i).length===0)return e.json({user:n.user});let s=oe(e.context.options,i,"update"),a=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:r,image:o,...s});return await O(e,{session:n.session,user:a}),e.json({user:a})}),ve=p("/change-password",{method:"POST",body:U.z.object({newPassword:U.z.string(),currentPassword:U.z.string(),revokeOtherSessions:U.z.boolean().optional()}),use:[v]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new E.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 E.APIError("BAD_REQUEST",{message:"Password too long"});let l=(await e.context.internalAdapter.findAccounts(i.user.id)).find(h=>h.providerId==="credential"&&h.password);if(!l||!l.password)throw new E.APIError("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify(l.password,r))throw new E.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(l.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(i.user.id);let h=await e.context.internalAdapter.createSession(i.user.id,e.headers);if(!h)throw new E.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await O(e,{session:h,user:i.user})}return e.json(i.user)}),_e=p("/set-password",{method:"POST",body:U.z.object({newPassword:U.z.string()}),metadata:{SERVER_ONLY:!0},use:[v]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new E.APIError("BAD_REQUEST",{message:"Password is too short"});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new E.APIError("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(l=>l.providerId==="credential"&&l.password),a=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:a}),e.json(r.user);throw new E.APIError("BAD_REQUEST",{message:"user already has a password"})}),xe=p("/delete-user",{method:"POST",body:U.z.object({password:U.z.string()}),use:[v]},async e=>{let{password:t}=e.body,r=e.context.session,i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password);if(!i||!i.password)throw new E.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(i.password,t))throw new E.APIError("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),z(e),e.json(null)}),Pe=p("/change-email",{method:"POST",query:U.z.object({currentURL:U.z.string().optional()}).optional(),body:U.z.object({newEmail:U.z.string().email(),callbackURL:U.z.string().optional()}),use:[v]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new E.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new E.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new E.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let i=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:i,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await S(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(e.context.session.user,e.body.newEmail,o,r),e.json({user:null,status:!0})});var Mt=(e="Unknown")=>`<!DOCTYPE html>
|
package/dist/api.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{APIError as ot,createRouter as Gt,statusCode as Qt}from"better-call";import{APIError as mt}from"better-call";import{createEndpointCreator as nt,createMiddleware as ie,createMiddlewareCreator as st}from"better-call";var ne=ie(async()=>({})),G=st({use:[ne,ie(async()=>({}))]}),p=nt({use:[ne]});var z={isAction:!1};import{nanoid as at}from"nanoid";var se=e=>at(e);import{generateCodeVerifier as ct,generateState as lt}from"oslo/oauth2";import{z as I}from"zod";import{APIError as ue}from"better-call";var Q=Object.create(null),q=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Q:globalThis),ae=new Proxy(Q,{get(e,t){return q()[t]??Q[t]},has(e,t){let r=q();return t in r||t in Q},set(e,t,r){let o=q(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=q(!0);return delete r[t],!0},ownKeys(){let e=q(!0);return Object.keys(e)}});function dt(e){return e?e!=="false":!1}var X=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var de=X==="dev"||X==="development",ce=X==="test"||dt(ae.TEST);var C=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}};function le(e){try{return new URL(e).origin}catch{return null}}async function H(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?le(e.query?.currentURL):"");if(!r)throw new ue("BAD_REQUEST",{message:"callbackURL is required"});let o=ct(),i=lt(),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:s});if(!a)throw f.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ue("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function pe(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw f.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=I.object({callbackURL:I.string(),codeVerifier:I.string(),errorURL:I.string().optional(),expiresAt:I.number(),link:I.object({email:I.string(),userId:I.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),f.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}import{createConsola as ut}from"consola";var D=ut({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),pt=e=>({log:(...t)=>{!e?.disabled&&D.log("",...t)},error:(...t)=>{!e?.disabled&&D.error("",...t)},warn:(...t)=>{!e?.disabled&&D.warn("",...t)},info:(...t)=>{!e?.disabled&&D.info("",...t)},debug:(...t)=>{!e?.disabled&&D.debug("",...t)},box:(...t)=>{!e?.disabled&&D.box("",...t)},success:(...t)=>{!e?.disabled&&D.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
1
|
+
import{APIError as ot,createRouter as Gt,statusCode as Qt}from"better-call";import{APIError as mt}from"better-call";import{createEndpointCreator as nt,createMiddleware as ie,createMiddlewareCreator as st}from"better-call";var ne=ie(async()=>({})),G=st({use:[ne,ie(async()=>({}))]}),p=nt({use:[ne]});var z={isAction:!1};import{nanoid as at}from"nanoid";var se=e=>at(e);import{generateCodeVerifier as ct,generateState as lt}from"oslo/oauth2";import{z as I}from"zod";import{APIError as ue}from"better-call";var Q=Object.create(null),q=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Q:globalThis),ae=new Proxy(Q,{get(e,t){return q()[t]??Q[t]},has(e,t){let r=q();return t in r||t in Q},set(e,t,r){let o=q(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=q(!0);return delete r[t],!0},ownKeys(){let e=q(!0);return Object.keys(e)}});function dt(e){return e?e!=="false":!1}var X=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var de=X==="dev"||X==="development",ce=X==="test"||dt(ae.TEST);var C=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}};function le(e){try{return new URL(e).origin}catch{return null}}async function H(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?le(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ue("BAD_REQUEST",{message:"callbackURL is required"});let o=ct(),i=lt(),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:s});if(!a)throw f.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ue("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function pe(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw f.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=I.object({callbackURL:I.string(),codeVerifier:I.string(),errorURL:I.string().optional(),expiresAt:I.number(),link:I.object({email:I.string(),userId:I.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),f.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}import{createConsola as ut}from"consola";var D=ut({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),pt=e=>({log:(...t)=>{!e?.disabled&&D.log("",...t)},error:(...t)=>{!e?.disabled&&D.error("",...t)},warn:(...t)=>{!e?.disabled&&D.warn("",...t)},info:(...t)=>{!e?.disabled&&D.info("",...t)},debug:(...t)=>{!e?.disabled&&D.debug("",...t)},box:(...t)=>{!e?.disabled&&D.box("",...t)},success:(...t)=>{!e?.disabled&&D.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
2
|
`)}}),f=pt();var me=G(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,i=e.headers?.get("origin")||e.headers?.get("referer")||"",n=t?.callbackURL,s=t?.redirectTo,a=r?.currentURL,l=o.trustedOrigins,d=e.headers?.has("cookie"),c=(g,m)=>{if(!l.some(k=>g?.startsWith(k)||g?.startsWith("/")&&m!=="origin"))throw f.error(`Invalid ${m}: ${g}`),f.info(`If it's a valid URL, please add ${g} to trustedOrigins in your auth config
|
|
3
3
|
`,`Current list of trustedOrigins: ${l}`),new mt("FORBIDDEN",{message:`Invalid ${m}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&c(i,"origin"),n&&c(n,"callbackURL"),s&&c(s,"redirectURL"),a&&c(a,"currentURL")});import{APIError as T}from"better-call";import{z as _}from"zod";import{TimeSpan as _r}from"oslo";async function x(e,t,r,o){let i=e.context.authCookies.sessionToken.options;i.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.id,e.context.secret,{...i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&await e.setSignedCookie(e.context.authCookies.sessionData.name,JSON.stringify(t),e.context.secret,e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.id,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function B(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}import{parseJWT as wt}from"oslo/jwt";import{sha256 as ft}from"oslo/crypto";import{base64url as gt}from"oslo/encoding";var V=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function fe(e){let t=await ft(new TextEncoder().encode(e));return gt.encode(new Uint8Array(t),{includePadding:!1})}function ge(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?V(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:s,disablePkce:a,redirectURI:l}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||l),!a&&i){let c=await fe(i);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",c)}if(s){let c=s.reduce((g,m)=>(g[m]=null,g),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...c}}))}return d}import{betterFetch as ht}from"@better-fetch/fetch";async function y({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i}){let n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),t&&n.set("code_verifier",t),n.set("redirect_uri",r),n.set("client_id",o.clientId),n.set("client_secret",o.clientSecret);let{data:s,error:a}=await ht(i,{method:"POST",body:n,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(a)throw a;return ge(s)}var he=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=o||["email","name","openid"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>y({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=wt(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};import{betterFetch as bt}from"@better-fetch/fetch";var we=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await bt("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}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 yt}from"@better-fetch/fetch";var be=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await yt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});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 ye}from"@better-fetch/fetch";var Ae=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await ye("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:s,error:a}=await ye("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(l=>l.primary)??s[0])?.email,n=s.find(l=>l.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n},data:o}}}};import{parseJWT as At}from"oslo/jwt";var ke=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw f.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new C("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new C("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=At(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 kt}from"@better-fetch/fetch";import{parseJWT as Rt}from"oslo/jwt";var Re=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),A({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return y({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(!i.idToken)return null;let n=Rt(i.idToken)?.payload,s=e.profilePhotoSize||48;return await kt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let d=await a.response.clone().arrayBuffer(),c=Buffer.from(d).toString("base64");n.picture=`data:image/jpeg;base64, ${c}`}catch(l){f.error(l)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};import{betterFetch as Ut}from"@better-fetch/fetch";var Ue=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await Ut("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}}});import"@better-fetch/fetch";import{parseJWT as Et}from"oslo/jwt";var Ee=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return f.error("No idToken found in token"),null;let o=Et(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as vt}from"@better-fetch/fetch";var ve=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["account_info.read"];return e.scope&&r.push(...e.scope),A({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await vt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});import{betterFetch as _t}from"@better-fetch/fetch";var _e=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await y({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await _t("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return i?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 xt}from"@better-fetch/fetch";var xe=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await y({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await xt("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return n?null:{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture},data:i}}}};import{betterFetch as Pt}from"@better-fetch/fetch";var ee=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Tt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ee(`${t}/oauth/authorize`),tokenEndpoint:ee(`${t}/oauth/token`),userinfoEndpoint:ee(`${t}/api/v4/user`)}},Pe=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Tt(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:l,redirectURI:d})=>{let c=a||["read_user"];return e.scope&&c.push(...e.scope),await A({id:i,options:e,authorizationEndpoint:t,scopes:c,state:s,redirectURI:d,codeVerifier:l})},validateAuthorizationCode:async({code:s,redirectURI:a})=>y({code:s,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:l}=await Pt(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return l||a.state!=="active"||a.locked?null:{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0},data:a}}}};var Ot={apple:he,discord:we,facebook:be,github:Ae,microsoft:Re,google:ke,spotify:Ue,twitch:Ee,twitter:ve,dropbox:_e,linkedin:xe,gitlab:Pe},Z=Object.keys(Ot);import{TimeSpan as St}from"oslo";import{createJWT as Lt,validateJWT as It}from"oslo/jwt";import{z as P}from"zod";import{APIError as j}from"better-call";import{APIError as N}from"better-call";import{z as F}from"zod";var te=()=>p("/get-session",{method:"GET",query:F.optional(F.object({disableCookieCache:F.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.getSignedCookie(e.context.authCookies.sessionData.name,e.context.secret),o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(r&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let d=JSON.parse(r)?.session;if(d?.expiresAt>new Date)return e.json(d)}let i=await e.context.internalAdapter.findSession(t);if(!i||i.session.expiresAt<new Date)return B(e),i&&await e.context.internalAdapter.deleteSession(i.session.id),e.json(null,{status:401});if(o)return e.json(i);let n=e.context.sessionConfig.expiresIn,s=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-n*1e3+s*1e3<=Date.now()){let d=await e.context.internalAdapter.updateSession(i.session.id,{expiresAt:V(e.context.sessionConfig.expiresIn,"sec")});if(!d)return B(e),e.json(null,{status:401});let c=(d.expiresAt.valueOf()-Date.now())/1e3;return await x(e,{session:d,user:i.user},!1,{maxAge:c}),e.json({session:d,user:i.user})}return e.json(i)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),re=async e=>await te()({...e,_flag:"json",headers:e.headers}),v=G(async e=>{let t=await re(e);if(!t?.session)throw new N("UNAUTHORIZED");return{session:t}}),Te=()=>p("/list-sessions",{method:"GET",use:[v],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Oe=p("/revoke-session",{method:"POST",body:F.object({id:F.string()}),use:[v],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new N("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new N("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new N("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Se=p("/revoke-sessions",{method:"POST",use:[v],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new N("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function S(e,t,r){return await Lt("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new St(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Le=p("/send-verification-email",{method:"POST",query:P.object({currentURL:P.string().optional()}).optional(),body:P.object({email:P.string().email(),callbackURL:P.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new j("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new j("BAD_REQUEST",{message:"User not found"});let o=await S(e.context.secret,t),i=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,i,o),e.json({status:!0})}),Ie=p("/verify-email",{method:"GET",query:P.object({token:P.string(),callbackURL:P.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await It("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new j("BAD_REQUEST",{message:"Invalid token"})}let i=P.object({email:P.string().email(),updateTo:P.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(i.email))throw new j("BAD_REQUEST",{message:"User not found"});if(i.updateTo){let s=await re(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new j("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==i.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new j("UNAUTHORIZED",{message:"Invalid session"});let a=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(a,`${e.context.baseURL}/verify-email?token=${t}`,t),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.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var Ce=p("/sign-in/social",{method:"POST",query:_.object({currentURL:_.string().optional()}).optional(),body:_.object({callbackURL:_.string().optional(),provider:_.enum(Z)})},async e=>{let t=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new T("NOT_FOUND",{message:"Provider not found"});let{codeVerifier:r,state:o}=await H(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!0})}),De=p("/sign-in/email",{method:"POST",body:_.object({email:_.string(),password:_.string(),callbackURL:_.string().optional(),dontRememberMe:_.boolean().default(!1).optional()})},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new T("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!_.string().email().safeParse(t).success)throw new T("BAD_REQUEST",{message:"Invalid email"});if(!_.string().email().safeParse(t).success)throw new T("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 T("UNAUTHORIZED",{message:"Invalid email or password"});let s=n.accounts.find(c=>c.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new T("UNAUTHORIZED",{message:"Invalid email or password"});let a=s?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new T("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new T("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw f.error("Email verification is required but no email verification handler is provided"),new T("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await S(e.context.secret,n.user.email),g=`${e.context.options.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,g,c),e.context.logger.error("Email not verified",{email:t}),new T("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new T("UNAUTHORIZED",{message:"Failed to create session"});return await x(e,{session:d,user:n.user},e.body.dontRememberMe),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as W}from"zod";import{z as h}from"zod";var Ti=h.object({id:h.string(),providerId:h.string(),accountId:h.string(),userId:h.string(),accessToken:h.string().nullable().optional(),refreshToken:h.string().nullable().optional(),idToken:h.string().nullable().optional(),expiresAt:h.date().nullable().optional(),password:h.string().optional().nullable()}),Be=h.object({id:h.string(),email:h.string().transform(e=>e.toLowerCase()),emailVerified:h.boolean().default(!1),name:h.string(),image:h.string().optional(),createdAt:h.date().default(new Date),updatedAt:h.date().default(new Date)}),Oi=h.object({id:h.string(),userId:h.string(),expiresAt:h.date(),ipAddress:h.string().optional(),userAgent:h.string().optional()}),Si=h.object({id:h.string(),value:h.string(),expiresAt:h.date(),identifier:h.string()});function Ct(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function Dt(e,t){let r=t.action||"create",o=t.fields,i={};for(let n in o){if(n in e){if(o[n].input===!1){if(o[n].defaultValue){i[n]=o[n].defaultValue;continue}continue}i[n]=e[n];continue}if(o[n].defaultValue&&r==="create"){i[n]=o[n].defaultValue;continue}}return i}function J(e,t,r){let o=Ct(e,"user");return Dt(t||{},{fields:o,action:r})}var ze=p("/callback/:id",{method:"GET",query:W.object({state:W.string(),code:W.string().optional(),error:W.string().optional()}),metadata:z},async e=>{if(!e.query.code)throw e.redirect(`${e.context.baseURL}/error?error=${e.query.error||"no_code"}`);let t=e.context.socialProviders.find(w=>w.id===e.params.id);if(!t)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:r,callbackURL:o,link:i,errorURL:n}=await pe(e),s;try{s=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(w){throw e.context.logger.error(w),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(s).then(w=>w?.user),l=se(),d=Be.safeParse({...a,id:l});if(!a||d.success===!1)throw f.error("Unable to get user info",d.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw f.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(i){if(i.email!==a.email.toLowerCase())return c("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:i.userId,providerId:t.id,accountId:a.id}))return c("unable_to_link_account");let b;try{b=new URL(o).toString()}catch{b=o}throw e.redirect(b)}function c(w){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${w}`)}let g=await e.context.internalAdapter.findUserByEmail(a.email,{includeAccounts:!0}).catch(w=>{throw f.error(`Better auth was unable to query your database.
|
|
4
4
|
Error: `,w),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),m=g?.user;if(g){let w=g.accounts.find(b=>b.providerId===t.id);if(w)await e.context.internalAdapter.updateAccount(w.id,{accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt});else{(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!a.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)&&(de&&f.warn(`User already exist but account isn't linked to ${t.id}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),c("account_not_linked"));try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:a.id.toString(),id:`${t.id}:${a.id}`,userId:g.user.id,accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt})}catch(oe){f.error("Unable to link account",oe),c("unable_to_link_account")}}}else try{let w=a.emailVerified||!1;if(m=await e.context.internalAdapter.createOAuthUser({...d.data,emailVerified:w},{accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt,providerId:t.id,accountId:a.id.toString()}).then(b=>b?.user),!w&&m&&e.context.options.emailVerification?.sendOnSignUp){let b=await S(e.context.secret,m.email),R=`${e.context.baseURL}/verify-email?token=${b}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(m,R,b)}}catch(w){f.error("Unable to create user",w),c("unable_to_create_user")}if(!m)return c("unable_to_create_user");let u=await e.context.internalAdapter.createSession(m.id,e.request);u||c("unable_to_create_session"),await x(e,{session:u,user:m});let k;try{k=new URL(o).toString()}catch{k=o}throw e.redirect(k)});import"zod";import{APIError as Bt}from"better-call";var Ve=p("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Bt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),B(e),e.json({success:!0})});import{z as O}from"zod";import{APIError as Y}from"better-call";function je(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}function zt(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}var $e=p("/forget-password",{method:"POST",body:O.object({email:O.string().email(),redirectTo:O.string()})},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new Y("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let i=60*60*1,n=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||i)),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:n});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,a),e.json({status:!0})}),qe=p("/reset-password/:token",{method:"GET",query:O.object({callbackURL:O.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(je(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(je(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(zt(e.context,r,{token:t}))}),Ne=p("/reset-password",{query:O.optional(O.object({token:O.string().optional(),currentURL:O.string().optional()})),method:"POST",body:O.object({newPassword:O.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new Y("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,i=await e.context.internalAdapter.findVerificationValue(o);if(!i||i.expiresAt<new Date)throw new Y("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(i.id);let n=i.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(n)).find(c=>c.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(n,s))throw new Y("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as U}from"zod";import{APIError as E}from"better-call";var Fe=()=>p("/update-user",{method:"POST",body:U.record(U.string(),U.any()),use:[v]},async e=>{let t=e.body;if(t.email)throw new E("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...i}=t,n=e.context.session;if(!o&&!r&&Object.keys(i).length===0)return e.json({user:n.user});let s=J(e.context.options,i,"update"),a=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:r,image:o,...s});return await x(e,{session:n.session,user:a}),e.json({user:a})}),Me=p("/change-password",{method:"POST",body:U.object({newPassword:U.string(),currentPassword:U.string(),revokeOtherSessions:U.boolean().optional()}),use:[v]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new E("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 E("BAD_REQUEST",{message:"Password too long"});let l=(await e.context.internalAdapter.findAccounts(i.user.id)).find(g=>g.providerId==="credential"&&g.password);if(!l||!l.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify(l.password,r))throw new E("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(l.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(i.user.id);let g=await e.context.internalAdapter.createSession(i.user.id,e.headers);if(!g)throw new E("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await x(e,{session:g,user:i.user})}return e.json(i.user)}),Ge=p("/set-password",{method:"POST",body:U.object({newPassword:U.string()}),metadata:{SERVER_ONLY:!0},use:[v]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new E("BAD_REQUEST",{message:"Password is too short"});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new E("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(l=>l.providerId==="credential"&&l.password),a=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:a}),e.json(r.user);throw new E("BAD_REQUEST",{message:"user already has a password"})}),Qe=p("/delete-user",{method:"POST",body:U.object({password:U.string()}),use:[v]},async e=>{let{password:t}=e.body,r=e.context.session,i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password);if(!i||!i.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(i.password,t))throw new E("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),B(e),e.json(null)}),He=p("/change-email",{method:"POST",query:U.object({currentURL:U.string().optional()}).optional(),body:U.object({newEmail:U.string().email(),callbackURL:U.string().optional()}),use:[v]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new E("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new E("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new E("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let i=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:i,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await S(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(e.context.session.user,e.body.newEmail,o,r),e.json({user:null,status:!0})});var Vt=(e="Unknown")=>`<!DOCTYPE html>
|
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Ae=Object.defineProperty;var pr=Object.getOwnPropertyDescriptor;var fr=Object.getOwnPropertyNames;var mr=Object.prototype.hasOwnProperty;var gr=(e,t)=>{for(var r in t)Ae(e,r,{get:t[r],enumerable:!0})},hr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of fr(t))!mr.call(e,i)&&i!==r&&Ae(e,i,{get:()=>t[i],enumerable:!(o=pr(t,i))||o.enumerable});return e};var yr=e=>hr(Ae({},"__esModule",{value:!0}),e);var qr={};gr(qr,{BetterAuthError:()=>E,HIDE_METADATA:()=>$,MissingDependencyError:()=>ke,betterAuth:()=>Vr,capitalizeFirstLetter:()=>wr,createCookieGetter:()=>fe,createLogger:()=>pe,deleteSessionCookie:()=>j,generateId:()=>v,generateState:()=>te,getCookies:()=>ve,logger:()=>h,parseCookies:()=>Rr,parseSetCookieHeader:()=>kr,parseState:()=>Ue,setSessionCookie:()=>O});module.exports=yr(qr);var K=require("better-call");var Me=require("better-call");var z=require("better-call"),Fe=(0,z.createMiddleware)(async()=>({})),de=(0,z.createMiddlewareCreator)({use:[Fe,(0,z.createMiddleware)(async()=>({}))]}),y=(0,z.createEndpointCreator)({use:[Fe]});function wr(e){return e.charAt(0).toUpperCase()+e.slice(1)}var $={isAction:!1};var Ve=require("nanoid"),v=e=>(0,Ve.nanoid)(e);var ue=require("oslo/oauth2"),D=require("zod"),xe=require("better-call");var ce=Object.create(null),Y=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?ce:globalThis),I=new Proxy(ce,{get(e,t){return Y()[t]??ce[t]},has(e,t){let r=Y();return t in r||t in ce},set(e,t,r){let o=Y(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=Y(!0);return delete r[t],!0},ownKeys(){let e=Y(!0);return Object.keys(e)}});function br(e){return e?e!=="false":!1}var le=typeof process<"u"&&process.env&&process.env.NODE_ENV||"",X=le==="production",qe=le==="dev"||le==="development",je=le==="test"||br(I.TEST);var E=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}},ke=class extends E{constructor(t){super(`The package "${t}" is required. Make sure it is installed.`,t)}};function Ar(e){try{return new URL(e).pathname!=="/"}catch{throw new E(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function Re(e,t="/api/auth"){return Ar(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function ee(e,t){if(e)return Re(e,t);let r=I.BETTER_AUTH_URL||I.NEXT_PUBLIC_BETTER_AUTH_URL||I.PUBLIC_BETTER_AUTH_URL||I.NUXT_PUBLIC_BETTER_AUTH_URL||I.NUXT_PUBLIC_AUTH_URL||(I.BASE_URL!=="/"?I.BASE_URL:void 0);if(r)return Re(r,t);if(typeof window<"u")return Re(window.location.origin,t)}function ze(e){try{return new URL(e).origin}catch{return null}}async function te(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?ze(e.query?.currentURL):"");if(!r)throw new xe.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,ue.generateCodeVerifier)(),i=(0,ue.generateState)(),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),a=new Date;a.setMinutes(a.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:a});if(!c)throw h.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new xe.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function Ue(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw h.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=D.z.object({callbackURL:D.z.string(),codeVerifier:D.z.string(),errorURL:D.z.string().optional(),expiresAt:D.z.number(),link:D.z.object({email:D.z.string(),userId:D.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),h.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 $e=require("consola"),M=(0,$e.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),pe=e=>({log:(...t)=>{!e?.disabled&&M.log("",...t)},error:(...t)=>{!e?.disabled&&M.error("",...t)},warn:(...t)=>{!e?.disabled&&M.warn("",...t)},info:(...t)=>{!e?.disabled&&M.info("",...t)},debug:(...t)=>{!e?.disabled&&M.debug("",...t)},box:(...t)=>{!e?.disabled&&M.box("",...t)},success:(...t)=>{!e?.disabled&&M.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
1
|
+
"use strict";var Ae=Object.defineProperty;var pr=Object.getOwnPropertyDescriptor;var fr=Object.getOwnPropertyNames;var mr=Object.prototype.hasOwnProperty;var gr=(e,t)=>{for(var r in t)Ae(e,r,{get:t[r],enumerable:!0})},hr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of fr(t))!mr.call(e,i)&&i!==r&&Ae(e,i,{get:()=>t[i],enumerable:!(o=pr(t,i))||o.enumerable});return e};var yr=e=>hr(Ae({},"__esModule",{value:!0}),e);var qr={};gr(qr,{BetterAuthError:()=>E,HIDE_METADATA:()=>$,MissingDependencyError:()=>ke,betterAuth:()=>Vr,capitalizeFirstLetter:()=>wr,createCookieGetter:()=>fe,createLogger:()=>pe,deleteSessionCookie:()=>j,generateId:()=>v,generateState:()=>te,getCookies:()=>ve,logger:()=>h,parseCookies:()=>Rr,parseSetCookieHeader:()=>kr,parseState:()=>Ue,setSessionCookie:()=>O});module.exports=yr(qr);var K=require("better-call");var Me=require("better-call");var z=require("better-call"),Fe=(0,z.createMiddleware)(async()=>({})),de=(0,z.createMiddlewareCreator)({use:[Fe,(0,z.createMiddleware)(async()=>({}))]}),y=(0,z.createEndpointCreator)({use:[Fe]});function wr(e){return e.charAt(0).toUpperCase()+e.slice(1)}var $={isAction:!1};var Ve=require("nanoid"),v=e=>(0,Ve.nanoid)(e);var ue=require("oslo/oauth2"),D=require("zod"),xe=require("better-call");var ce=Object.create(null),Y=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?ce:globalThis),I=new Proxy(ce,{get(e,t){return Y()[t]??ce[t]},has(e,t){let r=Y();return t in r||t in ce},set(e,t,r){let o=Y(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=Y(!0);return delete r[t],!0},ownKeys(){let e=Y(!0);return Object.keys(e)}});function br(e){return e?e!=="false":!1}var le=typeof process<"u"&&process.env&&process.env.NODE_ENV||"",X=le==="production",qe=le==="dev"||le==="development",je=le==="test"||br(I.TEST);var E=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}},ke=class extends E{constructor(t){super(`The package "${t}" is required. Make sure it is installed.`,t)}};function Ar(e){try{return new URL(e).pathname!=="/"}catch{throw new E(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function Re(e,t="/api/auth"){return Ar(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function ee(e,t){if(e)return Re(e,t);let r=I.BETTER_AUTH_URL||I.NEXT_PUBLIC_BETTER_AUTH_URL||I.PUBLIC_BETTER_AUTH_URL||I.NUXT_PUBLIC_BETTER_AUTH_URL||I.NUXT_PUBLIC_AUTH_URL||(I.BASE_URL!=="/"?I.BASE_URL:void 0);if(r)return Re(r,t);if(typeof window<"u")return Re(window.location.origin,t)}function ze(e){try{return new URL(e).origin}catch{return null}}async function te(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?ze(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new xe.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,ue.generateCodeVerifier)(),i=(0,ue.generateState)(),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),a=new Date;a.setMinutes(a.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:a});if(!c)throw h.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new xe.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function Ue(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw h.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=D.z.object({callbackURL:D.z.string(),codeVerifier:D.z.string(),errorURL:D.z.string().optional(),expiresAt:D.z.number(),link:D.z.object({email:D.z.string(),userId:D.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),h.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 $e=require("consola"),M=(0,$e.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),pe=e=>({log:(...t)=>{!e?.disabled&&M.log("",...t)},error:(...t)=>{!e?.disabled&&M.error("",...t)},warn:(...t)=>{!e?.disabled&&M.warn("",...t)},info:(...t)=>{!e?.disabled&&M.info("",...t)},debug:(...t)=>{!e?.disabled&&M.debug("",...t)},box:(...t)=>{!e?.disabled&&M.box("",...t)},success:(...t)=>{!e?.disabled&&M.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
2
|
`)}}),h=pe();var He=de(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,i=e.headers?.get("origin")||e.headers?.get("referer")||"",n=t?.callbackURL,a=t?.redirectTo,c=r?.currentURL,s=o.trustedOrigins,d=e.headers?.has("cookie"),l=(f,u)=>{if(!s.some(g=>f?.startsWith(g)||f?.startsWith("/")&&u!=="origin"))throw h.error(`Invalid ${u}: ${f}`),h.info(`If it's a valid URL, please add ${f} to trustedOrigins in your auth config
|
|
3
3
|
`,`Current list of trustedOrigins: ${s}`),new Me.APIError("FORBIDDEN",{message:`Invalid ${u}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&l(i,"origin"),n&&l(n,"callbackURL"),a&&l(a,"redirectURL"),c&&l(c,"currentURL")});var L=require("better-call"),P=require("zod");var Ge=require("oslo");function fe(e){let r=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:e.baseURL!==void 0?!!e.baseURL.startsWith("https://"):X)?"__Secure-":"",o=!!e.advanced?.crossSubDomainCookies?.enabled,i=o?e.advanced?.crossSubDomainCookies?.domain||(e.baseURL?new URL(e.baseURL).hostname:void 0):void 0;if(o&&!i)throw new E("baseURL is required when crossSubdomainCookies are enabled");function n(a,c={}){let s=e.advanced?.cookiePrefix||e.appName||"better-auth",d=e.advanced?.cookies?.[a]?.name||`${s}.${a}`,l=e.advanced?.cookies?.[a]?.attributes;return{name:`${r}${d}`,attributes:{secure:!!r,sameSite:"lax",path:"/",httpOnly:!0,...o?{domain:i}:{},...e.advanced?.defaultCookieAttributes,...c,...l}}}return n}function ve(e){let t=fe(e),r=e.session?.expiresIn||new Ge.TimeSpan(7,"d").seconds(),o=t("session_token",{maxAge:r}),i=t("session_data",{maxAge:e.session?.cookieCache?.maxAge||60*5}),n=t("dont_remember");return{sessionToken:{name:o.name,options:o.attributes},sessionData:{name:i.name,options:i.attributes},dontRememberToken:{name:n.name,options:n.attributes}}}async function O(e,t,r,o){let i=e.context.authCookies.sessionToken.options;i.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.id,e.context.secret,{...i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&await e.setSignedCookie(e.context.authCookies.sessionData.name,JSON.stringify(t),e.context.secret,e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.id,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function j(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}function kr(e){let t=new Map;return e.split(", ").forEach(o=>{let[i,...n]=o.split("; "),[a,c]=i.split("="),s={value:c};n.forEach(d=>{let[l,f]=d.split("=");s[l.toLowerCase()]=f||!0}),t.set(a,s)}),t}function Rr(e){let t=e.split("; "),r=new Map;return t.forEach(o=>{let[i,n]=o.split("=");r.set(i,n)}),r}var Ye=require("oslo/jwt");var Ke=require("oslo/crypto"),Qe=require("oslo/encoding");var N=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function Ze(e){let t=await(0,Ke.sha256)(new TextEncoder().encode(e));return Qe.base64url.encode(new Uint8Array(t),{includePadding:!1})}function We(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?N(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function k({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:a,disablePkce:c,redirectURI:s}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||s),!c&&i){let l=await Ze(i);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",l)}if(a){let l=a.reduce((f,u)=>(f[u]=null,f),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return d}var Je=require("@better-fetch/fetch");async function A({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i}){let n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),t&&n.set("code_verifier",t),n.set("redirect_uri",r),n.set("client_id",o.clientId),n.set("client_secret",o.clientSecret);let{data:a,error:c}=await(0,Je.betterFetch)(i,{method:"POST",body:n,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(c)throw c;return We(a)}var Xe=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=o||["email","name","openid"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>A({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=(0,Ye.parseJWT)(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};var et=require("@better-fetch/fetch");var tt=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,et.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var rt=require("@better-fetch/fetch");var ot=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await k({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await(0,rt.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 Te=require("@better-fetch/fetch");var nt=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let a=o||["user:email"];return e.scope&&a.push(...e.scope),k({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>A({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await(0,Te.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:a,error:c}=await(0,Te.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});c||(o.email=(a.find(s=>s.primary)??a[0])?.email,n=a.find(s=>s.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n},data:o}}}};var it=require("oslo/jwt");var st=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw h.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new E("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new E("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let a=await k({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});return e.accessType&&a.searchParams.set("access_type",e.accessType),e.prompt&&a.searchParams.set("prompt",e.prompt),a},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>A({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=(0,it.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 at=require("@better-fetch/fetch"),dt=require("oslo/jwt");var ct=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),k({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:a}){return A({code:i,codeVerifier:n,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:o})},async getUserInfo(i){if(!i.idToken)return null;let n=(0,dt.parseJWT)(i.idToken)?.payload,a=e.profilePhotoSize||48;return await(0,at.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let d=await c.response.clone().arrayBuffer(),l=Buffer.from(d).toString("base64");n.picture=`data:image/jpeg;base64, ${l}`}catch(s){h.error(s)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};var lt=require("@better-fetch/fetch");var ut=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),k({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>A({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,lt.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 Ho=require("@better-fetch/fetch");var pt=require("oslo/jwt");var ft=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),k({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return h.error("No idToken found in token"),null;let o=(0,pt.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var mt=require("@better-fetch/fetch");var gt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["account_info.read"];return e.scope&&r.push(...e.scope),k({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>A({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,mt.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var ht=require("@better-fetch/fetch");var yt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let a=o||["account_info.read"];return e.scope&&a.push(...e.scope),await k({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await A({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await(0,ht.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return i?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 wt=require("@better-fetch/fetch");var bt=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:i,redirectURI:n})=>{let a=i||["profile","email","openid"];return e.scope&&a.push(...e.scope),await k({id:"linkedin",options:e,authorizationEndpoint:t,scopes:a,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await A({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await(0,wt.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return n?null:{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture},data:i}}}};var At=require("@better-fetch/fetch");var Ee=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),xr=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:Ee(`${t}/oauth/authorize`),tokenEndpoint:Ee(`${t}/oauth/token`),userinfoEndpoint:Ee(`${t}/api/v4/user`)}},kt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=xr(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:a,scopes:c,codeVerifier:s,redirectURI:d})=>{let l=c||["read_user"];return e.scope&&l.push(...e.scope),await k({id:i,options:e,authorizationEndpoint:t,scopes:l,state:a,redirectURI:d,codeVerifier:s})},validateAuthorizationCode:async({code:a,redirectURI:c})=>A({code:a,redirectURI:e.redirectURI||c,options:e,tokenEndpoint:r}),async getUserInfo(a){let{data:c,error:s}=await(0,At.betterFetch)(o,{headers:{authorization:`Bearer ${a.accessToken}`}});return s||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 Ie={apple:Xe,discord:tt,facebook:ot,github:nt,microsoft:ct,google:st,spotify:ut,twitch:ft,twitter:gt,dropbox:yt,linkedin:bt,gitlab:kt},me=Object.keys(Ie);var vt=require("oslo"),ge=require("oslo/jwt"),S=require("zod");var H=require("better-call");var Q=require("better-call");var Z=require("zod"),Pe=()=>y("/get-session",{method:"GET",query:Z.z.optional(Z.z.object({disableCookieCache:Z.z.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.getSignedCookie(e.context.authCookies.sessionData.name,e.context.secret),o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(r&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let d=JSON.parse(r)?.session;if(d?.expiresAt>new Date)return e.json(d)}let i=await e.context.internalAdapter.findSession(t);if(!i||i.session.expiresAt<new Date)return j(e),i&&await e.context.internalAdapter.deleteSession(i.session.id),e.json(null,{status:401});if(o)return e.json(i);let n=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-n*1e3+a*1e3<=Date.now()){let d=await e.context.internalAdapter.updateSession(i.session.id,{expiresAt:N(e.context.sessionConfig.expiresIn,"sec")});if(!d)return j(e),e.json(null,{status:401});let l=(d.expiresAt.valueOf()-Date.now())/1e3;return await O(e,{session:d,user:i.user},!1,{maxAge:l}),e.json({session:d,user:i.user})}return e.json(i)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),Oe=async e=>await Pe()({...e,_flag:"json",headers:e.headers}),_=de(async e=>{let t=await Oe(e);if(!t?.session)throw new Q.APIError("UNAUTHORIZED");return{session:t}}),Rt=()=>y("/list-sessions",{method:"GET",use:[_],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),xt=y("/revoke-session",{method:"POST",body:Z.z.object({id:Z.z.string()}),use:[_],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new Q.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new Q.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new Q.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Ut=y("/revoke-sessions",{method:"POST",use:[_],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new Q.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function F(e,t,r){return await(0,ge.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new vt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Tt=y("/send-verification-email",{method:"POST",query:S.z.object({currentURL:S.z.string().optional()}).optional(),body:S.z.object({email:S.z.string().email(),callbackURL:S.z.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new H.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 H.APIError("BAD_REQUEST",{message:"User not found"});let o=await F(e.context.secret,t),i=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,i,o),e.json({status:!0})}),Et=y("/verify-email",{method:"GET",query:S.z.object({token:S.z.string(),callbackURL:S.z.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await(0,ge.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(a){throw e.context.logger.error("Failed to verify email",a),new H.APIError("BAD_REQUEST",{message:"Invalid token"})}let i=S.z.object({email:S.z.string().email(),updateTo:S.z.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(i.email))throw new H.APIError("BAD_REQUEST",{message:"User not found"});if(i.updateTo){let a=await Oe(e);if(!a)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new H.APIError("UNAUTHORIZED",{message:"Session not found"});if(a.user.email!==i.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new H.APIError("UNAUTHORIZED",{message:"Invalid session"});let c=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(c,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:c,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var It=y("/sign-in/social",{method:"POST",query:P.z.object({currentURL:P.z.string().optional()}).optional(),body:P.z.object({callbackURL:P.z.string().optional(),provider:P.z.enum(me)})},async e=>{let t=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new L.APIError("NOT_FOUND",{message:"Provider not found"});let{codeVerifier:r,state:o}=await te(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!0})}),Pt=y("/sign-in/email",{method:"POST",body:P.z.object({email:P.z.string(),password:P.z.string(),callbackURL:P.z.string().optional(),dontRememberMe:P.z.boolean().default(!1).optional()})},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 L.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!P.z.string().email().safeParse(t).success)throw new L.APIError("BAD_REQUEST",{message:"Invalid email"});if(!P.z.string().email().safeParse(t).success)throw new L.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 L.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let a=n.accounts.find(l=>l.providerId==="credential");if(!a)throw e.context.logger.error("Credential account not found",{email:t}),new L.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let c=a?.password;if(!c)throw e.context.logger.error("Password not found",{email:t}),new L.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(c,r))throw e.context.logger.error("Invalid password"),new L.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw h.error("Email verification is required but no email verification handler is provided"),new L.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let l=await F(e.context.secret,n.user.email),f=`${e.context.options.baseURL}/verify-email?token=${l}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,f,l),e.context.logger.error("Email not verified",{email:t}),new L.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new L.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await O(e,{session:d,user:n.user},e.body.dontRememberMe),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var re=require("zod");var b=require("zod"),$n=b.z.object({id:b.z.string(),providerId:b.z.string(),accountId:b.z.string(),userId:b.z.string(),accessToken:b.z.string().nullable().optional(),refreshToken:b.z.string().nullable().optional(),idToken:b.z.string().nullable().optional(),expiresAt:b.z.date().nullable().optional(),password:b.z.string().optional().nullable()}),Ot=b.z.object({id:b.z.string(),email:b.z.string().transform(e=>e.toLowerCase()),emailVerified:b.z.boolean().default(!1),name:b.z.string(),image:b.z.string().optional(),createdAt:b.z.date().default(new Date),updatedAt:b.z.date().default(new Date)}),Mn=b.z.object({id:b.z.string(),userId:b.z.string(),expiresAt:b.z.date(),ipAddress:b.z.string().optional(),userAgent:b.z.string().optional()}),Hn=b.z.object({id:b.z.string(),value:b.z.string(),expiresAt:b.z.date(),identifier:b.z.string()});function Ur(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function vr(e,t){let r=t.action||"create",o=t.fields,i={};for(let n in o){if(n in e){if(o[n].input===!1){if(o[n].defaultValue){i[n]=o[n].defaultValue;continue}continue}i[n]=e[n];continue}if(o[n].defaultValue&&r==="create"){i[n]=o[n].defaultValue;continue}}return i}function he(e,t,r){let o=Ur(e,"user");return vr(t||{},{fields:o,action:r})}var _t=y("/callback/:id",{method:"GET",query:re.z.object({state:re.z.string(),code:re.z.string().optional(),error:re.z.string().optional()}),metadata:$},async e=>{if(!e.query.code)throw e.redirect(`${e.context.baseURL}/error?error=${e.query.error||"no_code"}`);let t=e.context.socialProviders.find(m=>m.id===e.params.id);if(!t)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:r,callbackURL:o,link:i,errorURL:n}=await Ue(e),a;try{a=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(m){throw e.context.logger.error(m),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let c=await t.getUserInfo(a).then(m=>m?.user),s=v(),d=Ot.safeParse({...c,id:s});if(!c||d.success===!1)throw h.error("Unable to get user info",d.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw h.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(i){if(i.email!==c.email.toLowerCase())return l("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:i.userId,providerId:t.id,accountId:c.id}))return l("unable_to_link_account");let w;try{w=new URL(o).toString()}catch{w=o}throw e.redirect(w)}function l(m){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${m}`)}let f=await e.context.internalAdapter.findUserByEmail(c.email,{includeAccounts:!0}).catch(m=>{throw h.error(`Better auth was unable to query your database.
|
|
4
4
|
Error: `,m),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),u=f?.user;if(f){let m=f.accounts.find(w=>w.providerId===t.id);if(m)await e.context.internalAdapter.updateAccount(m.id,{accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt});else{(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!c.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)&&(qe&&h.warn(`User already exist but account isn't linked to ${t.id}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),l("account_not_linked"));try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:c.id.toString(),id:`${t.id}:${c.id}`,userId:f.user.id,accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt})}catch(Ne){h.error("Unable to link account",Ne),l("unable_to_link_account")}}}else try{let m=c.emailVerified||!1;if(u=await e.context.internalAdapter.createOAuthUser({...d.data,emailVerified:m},{accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt,providerId:t.id,accountId:c.id.toString()}).then(w=>w?.user),!m&&u&&e.context.options.emailVerification?.sendOnSignUp){let w=await F(e.context.secret,u.email),R=`${e.context.baseURL}/verify-email?token=${w}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(u,R,w)}}catch(m){h.error("Unable to create user",m),l("unable_to_create_user")}if(!u)return l("unable_to_create_user");let p=await e.context.internalAdapter.createSession(u.id,e.request);p||l("unable_to_create_session"),await O(e,{session:p,user:u});let g;try{g=new URL(o).toString()}catch{g=o}throw e.redirect(g)});var oi=require("zod");var St=require("better-call"),Lt=y("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new St.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),j(e),e.json({success:!0})});var C=require("zod");var oe=require("better-call");function Ct(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}function Tr(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}var Bt=y("/forget-password",{method:"POST",body:C.z.object({email:C.z.string().email(),redirectTo:C.z.string()})},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 i=60*60*1,n=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||i)),a=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${a}`,expiresAt:n});let c=`${e.context.baseURL}/reset-password/${a}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,c),e.json({status:!0})}),Dt=y("/reset-password/:token",{method:"GET",query:C.z.object({callbackURL:C.z.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(Ct(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Ct(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Tr(e.context,r,{token:t}))}),Nt=y("/reset-password",{query:C.z.optional(C.z.object({token:C.z.string().optional(),currentURL:C.z.string().optional()})),method:"POST",body:C.z.object({newPassword:C.z.string()})},async e=>{let t=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}`,i=await e.context.internalAdapter.findVerificationValue(o);if(!i||i.expiresAt<new Date)throw new oe.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(i.id);let n=i.value,a=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(n)).find(l=>l.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:a,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(n,a))throw new oe.APIError("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});var x=require("zod");var U=require("better-call");var Ft=()=>y("/update-user",{method:"POST",body:x.z.record(x.z.string(),x.z.any()),use:[_]},async e=>{let t=e.body;if(t.email)throw new U.APIError("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...i}=t,n=e.context.session;if(!o&&!r&&Object.keys(i).length===0)return e.json({user:n.user});let a=he(e.context.options,i,"update"),c=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:r,image:o,...a});return await O(e,{session:n.session,user:c}),e.json({user:c})}),Vt=y("/change-password",{method:"POST",body:x.z.object({newPassword:x.z.string(),currentPassword:x.z.string(),revokeOtherSessions:x.z.boolean().optional()}),use:[_]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new U.APIError("BAD_REQUEST",{message:"Password is too short"});let a=e.context.password.config.maxPasswordLength;if(t.length>a)throw e.context.logger.error("Password is too long"),new U.APIError("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(i.user.id)).find(f=>f.providerId==="credential"&&f.password);if(!s||!s.password)throw new U.APIError("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify(s.password,r))throw new U.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(s.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(i.user.id);let f=await e.context.internalAdapter.createSession(i.user.id,e.headers);if(!f)throw new U.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await O(e,{session:f,user:i.user})}return e.json(i.user)}),qt=y("/set-password",{method:"POST",body:x.z.object({newPassword:x.z.string()}),metadata:{SERVER_ONLY:!0},use:[_]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new U.APIError("BAD_REQUEST",{message:"Password is too short"});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new U.APIError("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password),c=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:c}),e.json(r.user);throw new U.APIError("BAD_REQUEST",{message:"user already has a password"})}),jt=y("/delete-user",{method:"POST",body:x.z.object({password:x.z.string()}),use:[_]},async e=>{let{password:t}=e.body,r=e.context.session,i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password);if(!i||!i.password)throw new U.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(i.password,t))throw new U.APIError("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),j(e),e.json(null)}),zt=y("/change-email",{method:"POST",query:x.z.object({currentURL:x.z.string().optional()}).optional(),body:x.z.object({newEmail:x.z.string().email(),callbackURL:x.z.string().optional()}),use:[_]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new U.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 U.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 U.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let i=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:i,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new U.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await F(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(e.context.session.user,e.body.newEmail,o,r),e.json({user:null,status:!0})});var Er=(e="Unknown")=>`<!DOCTYPE html>
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{APIError as kt,createRouter as Er,statusCode as Ir}from"better-call";import{APIError as Zt}from"better-call";import{createEndpointCreator as jt,createMiddleware as xe,createMiddlewareCreator as zt}from"better-call";var Ue=xe(async()=>({})),ee=zt({use:[Ue,xe(async()=>({}))]}),h=jt({use:[Ue]});function Vr(e){return e.charAt(0).toUpperCase()+e.slice(1)}var z={isAction:!1};import{nanoid as $t}from"nanoid";var T=e=>$t(e);import{generateCodeVerifier as Gt,generateState as Kt}from"oslo/oauth2";import{z as V}from"zod";import{APIError as Pe}from"better-call";var te=Object.create(null),G=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?te:globalThis),E=new Proxy(te,{get(e,t){return G()[t]??te[t]},has(e,t){let r=G();return t in r||t in te},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 Mt(e){return e?e!=="false":!1}var re=typeof process<"u"&&process.env&&process.env.NODE_ENV||"",K=re==="production",ve=re==="dev"||re==="development",Te=re==="test"||Mt(E.TEST);var I=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}},Ee=class extends I{constructor(t){super(`The package "${t}" is required. Make sure it is installed.`,t)}};function Ht(e){try{return new URL(e).pathname!=="/"}catch{throw new I(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function ue(e,t="/api/auth"){return Ht(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function Q(e,t){if(e)return ue(e,t);let r=E.BETTER_AUTH_URL||E.NEXT_PUBLIC_BETTER_AUTH_URL||E.PUBLIC_BETTER_AUTH_URL||E.NUXT_PUBLIC_BETTER_AUTH_URL||E.NUXT_PUBLIC_AUTH_URL||(E.BASE_URL!=="/"?E.BASE_URL:void 0);if(r)return ue(r,t);if(typeof window<"u")return ue(window.location.origin,t)}function Ie(e){try{return new URL(e).origin}catch{return null}}async function oe(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Ie(e.query?.currentURL):"");if(!r)throw new Pe("BAD_REQUEST",{message:"callbackURL is required"});let o=Gt(),i=Kt(),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),a=new Date;a.setMinutes(a.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:a});if(!c)throw y.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 Oe(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw y.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=V.object({callbackURL:V.string(),codeVerifier:V.string(),errorURL:V.string().optional(),expiresAt:V.number(),link:V.object({email:V.string(),userId:V.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),y.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}import{createConsola as Qt}from"consola";var q=Qt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),pe=e=>({log:(...t)=>{!e?.disabled&&q.log("",...t)},error:(...t)=>{!e?.disabled&&q.error("",...t)},warn:(...t)=>{!e?.disabled&&q.warn("",...t)},info:(...t)=>{!e?.disabled&&q.info("",...t)},debug:(...t)=>{!e?.disabled&&q.debug("",...t)},box:(...t)=>{!e?.disabled&&q.box("",...t)},success:(...t)=>{!e?.disabled&&q.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
1
|
+
import{APIError as kt,createRouter as Er,statusCode as Ir}from"better-call";import{APIError as Zt}from"better-call";import{createEndpointCreator as jt,createMiddleware as xe,createMiddlewareCreator as zt}from"better-call";var Ue=xe(async()=>({})),ee=zt({use:[Ue,xe(async()=>({}))]}),h=jt({use:[Ue]});function Vr(e){return e.charAt(0).toUpperCase()+e.slice(1)}var z={isAction:!1};import{nanoid as $t}from"nanoid";var T=e=>$t(e);import{generateCodeVerifier as Gt,generateState as Kt}from"oslo/oauth2";import{z as V}from"zod";import{APIError as Pe}from"better-call";var te=Object.create(null),G=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?te:globalThis),E=new Proxy(te,{get(e,t){return G()[t]??te[t]},has(e,t){let r=G();return t in r||t in te},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 Mt(e){return e?e!=="false":!1}var re=typeof process<"u"&&process.env&&process.env.NODE_ENV||"",K=re==="production",ve=re==="dev"||re==="development",Te=re==="test"||Mt(E.TEST);var I=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}},Ee=class extends I{constructor(t){super(`The package "${t}" is required. Make sure it is installed.`,t)}};function Ht(e){try{return new URL(e).pathname!=="/"}catch{throw new I(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function ue(e,t="/api/auth"){return Ht(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function Q(e,t){if(e)return ue(e,t);let r=E.BETTER_AUTH_URL||E.NEXT_PUBLIC_BETTER_AUTH_URL||E.PUBLIC_BETTER_AUTH_URL||E.NUXT_PUBLIC_BETTER_AUTH_URL||E.NUXT_PUBLIC_AUTH_URL||(E.BASE_URL!=="/"?E.BASE_URL:void 0);if(r)return ue(r,t);if(typeof window<"u")return ue(window.location.origin,t)}function Ie(e){try{return new URL(e).origin}catch{return null}}async function oe(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Ie(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new Pe("BAD_REQUEST",{message:"callbackURL is required"});let o=Gt(),i=Kt(),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),a=new Date;a.setMinutes(a.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:a});if(!c)throw y.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 Oe(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw y.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=V.object({callbackURL:V.string(),codeVerifier:V.string(),errorURL:V.string().optional(),expiresAt:V.number(),link:V.object({email:V.string(),userId:V.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),y.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}import{createConsola as Qt}from"consola";var q=Qt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),pe=e=>({log:(...t)=>{!e?.disabled&&q.log("",...t)},error:(...t)=>{!e?.disabled&&q.error("",...t)},warn:(...t)=>{!e?.disabled&&q.warn("",...t)},info:(...t)=>{!e?.disabled&&q.info("",...t)},debug:(...t)=>{!e?.disabled&&q.debug("",...t)},box:(...t)=>{!e?.disabled&&q.box("",...t)},success:(...t)=>{!e?.disabled&&q.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
2
|
`)}}),y=pe();var _e=ee(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,i=e.headers?.get("origin")||e.headers?.get("referer")||"",n=t?.callbackURL,a=t?.redirectTo,c=r?.currentURL,s=o.trustedOrigins,d=e.headers?.has("cookie"),l=(f,u)=>{if(!s.some(g=>f?.startsWith(g)||f?.startsWith("/")&&u!=="origin"))throw y.error(`Invalid ${u}: ${f}`),y.info(`If it's a valid URL, please add ${f} to trustedOrigins in your auth config
|
|
3
3
|
`,`Current list of trustedOrigins: ${s}`),new Zt("FORBIDDEN",{message:`Invalid ${u}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&l(i,"origin"),n&&l(n,"callbackURL"),a&&l(a,"redirectURL"),c&&l(c,"currentURL")});import{APIError as L}from"better-call";import{z as O}from"zod";import{TimeSpan as Wt}from"oslo";function fe(e){let r=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:e.baseURL!==void 0?!!e.baseURL.startsWith("https://"):K)?"__Secure-":"",o=!!e.advanced?.crossSubDomainCookies?.enabled,i=o?e.advanced?.crossSubDomainCookies?.domain||(e.baseURL?new URL(e.baseURL).hostname:void 0):void 0;if(o&&!i)throw new I("baseURL is required when crossSubdomainCookies are enabled");function n(a,c={}){let s=e.advanced?.cookiePrefix||e.appName||"better-auth",d=e.advanced?.cookies?.[a]?.name||`${s}.${a}`,l=e.advanced?.cookies?.[a]?.attributes;return{name:`${r}${d}`,attributes:{secure:!!r,sameSite:"lax",path:"/",httpOnly:!0,...o?{domain:i}:{},...e.advanced?.defaultCookieAttributes,...c,...l}}}return n}function Se(e){let t=fe(e),r=e.session?.expiresIn||new Wt(7,"d").seconds(),o=t("session_token",{maxAge:r}),i=t("session_data",{maxAge:e.session?.cookieCache?.maxAge||60*5}),n=t("dont_remember");return{sessionToken:{name:o.name,options:o.attributes},sessionData:{name:i.name,options:i.attributes},dontRememberToken:{name:n.name,options:n.attributes}}}async function _(e,t,r,o){let i=e.context.authCookies.sessionToken.options;i.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.id,e.context.secret,{...i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&await e.setSignedCookie(e.context.authCookies.sessionData.name,JSON.stringify(t),e.context.secret,e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.id,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function j(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}function wo(e){let t=new Map;return e.split(", ").forEach(o=>{let[i,...n]=o.split("; "),[a,c]=i.split("="),s={value:c};n.forEach(d=>{let[l,f]=d.split("=");s[l.toLowerCase()]=f||!0}),t.set(a,s)}),t}function bo(e){let t=e.split("; "),r=new Map;return t.forEach(o=>{let[i,n]=o.split("=");r.set(i,n)}),r}import{parseJWT as er}from"oslo/jwt";import{sha256 as Jt}from"oslo/crypto";import{base64url as Yt}from"oslo/encoding";var B=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function Le(e){let t=await Jt(new TextEncoder().encode(e));return Yt.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?B(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function k({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:a,disablePkce:c,redirectURI:s}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||s),!c&&i){let l=await Le(i);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",l)}if(a){let l=a.reduce((f,u)=>(f[u]=null,f),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return d}import{betterFetch as Xt}from"@better-fetch/fetch";async function A({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i}){let n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),t&&n.set("code_verifier",t),n.set("redirect_uri",r),n.set("client_id",o.clientId),n.set("client_secret",o.clientSecret);let{data:a,error:c}=await Xt(i,{method:"POST",body:n,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(c)throw c;return Ce(a)}var Be=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=o||["email","name","openid"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>A({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=er(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};import{betterFetch as tr}from"@better-fetch/fetch";var De=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await tr("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}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 rr}from"@better-fetch/fetch";var Ne=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await k({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await rr("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 Fe}from"@better-fetch/fetch";var Ve=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let a=o||["user:email"];return e.scope&&a.push(...e.scope),k({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>A({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await Fe("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:a,error:c}=await Fe("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});c||(o.email=(a.find(s=>s.primary)??a[0])?.email,n=a.find(s=>s.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n},data:o}}}};import{parseJWT as or}from"oslo/jwt";var qe=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw y.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new I("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new I("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let a=await k({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});return e.accessType&&a.searchParams.set("access_type",e.accessType),e.prompt&&a.searchParams.set("prompt",e.prompt),a},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>A({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=or(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 nr}from"@better-fetch/fetch";import{parseJWT as ir}from"oslo/jwt";var je=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),k({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:a}){return A({code:i,codeVerifier:n,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:o})},async getUserInfo(i){if(!i.idToken)return null;let n=ir(i.idToken)?.payload,a=e.profilePhotoSize||48;return await nr(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let d=await c.response.clone().arrayBuffer(),l=Buffer.from(d).toString("base64");n.picture=`data:image/jpeg;base64, ${l}`}catch(s){y.error(s)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};import{betterFetch as sr}from"@better-fetch/fetch";var ze=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),k({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>A({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await sr("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}}});import"@better-fetch/fetch";import{parseJWT as ar}from"oslo/jwt";var $e=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),k({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return y.error("No idToken found in token"),null;let o=ar(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as dr}from"@better-fetch/fetch";var Me=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["account_info.read"];return e.scope&&r.push(...e.scope),k({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>A({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await dr("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});import{betterFetch as cr}from"@better-fetch/fetch";var He=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let a=o||["account_info.read"];return e.scope&&a.push(...e.scope),await k({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await A({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await cr("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return i?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 lr}from"@better-fetch/fetch";var Ge=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:i,redirectURI:n})=>{let a=i||["profile","email","openid"];return e.scope&&a.push(...e.scope),await k({id:"linkedin",options:e,authorizationEndpoint:t,scopes:a,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await A({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await lr("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return n?null:{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture},data:i}}}};import{betterFetch as ur}from"@better-fetch/fetch";var me=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),pr=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:me(`${t}/oauth/authorize`),tokenEndpoint:me(`${t}/oauth/token`),userinfoEndpoint:me(`${t}/api/v4/user`)}},Ke=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=pr(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:a,scopes:c,codeVerifier:s,redirectURI:d})=>{let l=c||["read_user"];return e.scope&&l.push(...e.scope),await k({id:i,options:e,authorizationEndpoint:t,scopes:l,state:a,redirectURI:d,codeVerifier:s})},validateAuthorizationCode:async({code:a,redirectURI:c})=>A({code:a,redirectURI:e.redirectURI||c,options:e,tokenEndpoint:r}),async getUserInfo(a){let{data:c,error:s}=await ur(o,{headers:{authorization:`Bearer ${a.accessToken}`}});return s||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 ge={apple:Be,discord:De,facebook:Ne,github:Ve,microsoft:je,google:qe,spotify:ze,twitch:$e,twitter:Me,dropbox:He,linkedin:Ge,gitlab:Ke},ne=Object.keys(ge);import{TimeSpan as fr}from"oslo";import{createJWT as mr,validateJWT as gr}from"oslo/jwt";import{z as S}from"zod";import{APIError as $}from"better-call";import{APIError as Z}from"better-call";import{z as W}from"zod";var he=()=>h("/get-session",{method:"GET",query:W.optional(W.object({disableCookieCache:W.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.getSignedCookie(e.context.authCookies.sessionData.name,e.context.secret),o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(r&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let d=JSON.parse(r)?.session;if(d?.expiresAt>new Date)return e.json(d)}let i=await e.context.internalAdapter.findSession(t);if(!i||i.session.expiresAt<new Date)return j(e),i&&await e.context.internalAdapter.deleteSession(i.session.id),e.json(null,{status:401});if(o)return e.json(i);let n=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-n*1e3+a*1e3<=Date.now()){let d=await e.context.internalAdapter.updateSession(i.session.id,{expiresAt:B(e.context.sessionConfig.expiresIn,"sec")});if(!d)return j(e),e.json(null,{status:401});let l=(d.expiresAt.valueOf()-Date.now())/1e3;return await _(e,{session:d,user:i.user},!1,{maxAge:l}),e.json({session:d,user:i.user})}return e.json(i)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),ye=async e=>await he()({...e,_flag:"json",headers:e.headers}),P=ee(async e=>{let t=await ye(e);if(!t?.session)throw new Z("UNAUTHORIZED");return{session:t}}),Qe=()=>h("/list-sessions",{method:"GET",use:[P],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Ze=h("/revoke-session",{method:"POST",body:W.object({id:W.string()}),use:[P],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new Z("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new Z("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new Z("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),We=h("/revoke-sessions",{method:"POST",use:[P],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new Z("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function D(e,t,r){return await mr("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new fr(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Je=h("/send-verification-email",{method:"POST",query:S.object({currentURL:S.string().optional()}).optional(),body:S.object({email:S.string().email(),callbackURL:S.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new $("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new $("BAD_REQUEST",{message:"User not found"});let o=await D(e.context.secret,t),i=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,i,o),e.json({status:!0})}),Ye=h("/verify-email",{method:"GET",query:S.object({token:S.string(),callbackURL:S.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await gr("HS256",Buffer.from(e.context.secret),t)}catch(a){throw e.context.logger.error("Failed to verify email",a),new $("BAD_REQUEST",{message:"Invalid token"})}let i=S.object({email:S.string().email(),updateTo:S.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(i.email))throw new $("BAD_REQUEST",{message:"User not found"});if(i.updateTo){let a=await ye(e);if(!a)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new $("UNAUTHORIZED",{message:"Session not found"});if(a.user.email!==i.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new $("UNAUTHORIZED",{message:"Invalid session"});let c=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(c,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:c,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var Xe=h("/sign-in/social",{method:"POST",query:O.object({currentURL:O.string().optional()}).optional(),body:O.object({callbackURL:O.string().optional(),provider:O.enum(ne)})},async e=>{let t=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new L("NOT_FOUND",{message:"Provider not found"});let{codeVerifier:r,state:o}=await oe(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!0})}),et=h("/sign-in/email",{method:"POST",body:O.object({email:O.string(),password:O.string(),callbackURL:O.string().optional(),dontRememberMe:O.boolean().default(!1).optional()})},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 L("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!O.string().email().safeParse(t).success)throw new L("BAD_REQUEST",{message:"Invalid email"});if(!O.string().email().safeParse(t).success)throw new L("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 L("UNAUTHORIZED",{message:"Invalid email or password"});let a=n.accounts.find(l=>l.providerId==="credential");if(!a)throw e.context.logger.error("Credential account not found",{email:t}),new L("UNAUTHORIZED",{message:"Invalid email or password"});let c=a?.password;if(!c)throw e.context.logger.error("Password not found",{email:t}),new L("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(c,r))throw e.context.logger.error("Invalid password"),new L("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw y.error("Email verification is required but no email verification handler is provided"),new L("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let l=await D(e.context.secret,n.user.email),f=`${e.context.options.baseURL}/verify-email?token=${l}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,f,l),e.context.logger.error("Email not verified",{email:t}),new L("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new L("UNAUTHORIZED",{message:"Failed to create session"});return await _(e,{session:d,user:n.user},e.body.dontRememberMe),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as se}from"zod";import{z as b}from"zod";var Ai=b.object({id:b.string(),providerId:b.string(),accountId:b.string(),userId:b.string(),accessToken:b.string().nullable().optional(),refreshToken:b.string().nullable().optional(),idToken:b.string().nullable().optional(),expiresAt:b.date().nullable().optional(),password:b.string().optional().nullable()}),tt=b.object({id:b.string(),email:b.string().transform(e=>e.toLowerCase()),emailVerified:b.boolean().default(!1),name:b.string(),image:b.string().optional(),createdAt:b.date().default(new Date),updatedAt:b.date().default(new Date)}),ki=b.object({id:b.string(),userId:b.string(),expiresAt:b.date(),ipAddress:b.string().optional(),userAgent:b.string().optional()}),Ri=b.object({id:b.string(),value:b.string(),expiresAt:b.date(),identifier:b.string()});function hr(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function yr(e,t){let r=t.action||"create",o=t.fields,i={};for(let n in o){if(n in e){if(o[n].input===!1){if(o[n].defaultValue){i[n]=o[n].defaultValue;continue}continue}i[n]=e[n];continue}if(o[n].defaultValue&&r==="create"){i[n]=o[n].defaultValue;continue}}return i}function ie(e,t,r){let o=hr(e,"user");return yr(t||{},{fields:o,action:r})}var rt=h("/callback/:id",{method:"GET",query:se.object({state:se.string(),code:se.string().optional(),error:se.string().optional()}),metadata:z},async e=>{if(!e.query.code)throw e.redirect(`${e.context.baseURL}/error?error=${e.query.error||"no_code"}`);let t=e.context.socialProviders.find(m=>m.id===e.params.id);if(!t)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:r,callbackURL:o,link:i,errorURL:n}=await Oe(e),a;try{a=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(m){throw e.context.logger.error(m),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let c=await t.getUserInfo(a).then(m=>m?.user),s=T(),d=tt.safeParse({...c,id:s});if(!c||d.success===!1)throw y.error("Unable to get user info",d.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw y.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(i){if(i.email!==c.email.toLowerCase())return l("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:i.userId,providerId:t.id,accountId:c.id}))return l("unable_to_link_account");let w;try{w=new URL(o).toString()}catch{w=o}throw e.redirect(w)}function l(m){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${m}`)}let f=await e.context.internalAdapter.findUserByEmail(c.email,{includeAccounts:!0}).catch(m=>{throw y.error(`Better auth was unable to query your database.
|
|
4
4
|
Error: `,m),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),u=f?.user;if(f){let m=f.accounts.find(w=>w.providerId===t.id);if(m)await e.context.internalAdapter.updateAccount(m.id,{accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt});else{(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!c.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)&&(ve&&y.warn(`User already exist but account isn't linked to ${t.id}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),l("account_not_linked"));try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:c.id.toString(),id:`${t.id}:${c.id}`,userId:f.user.id,accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt})}catch(Re){y.error("Unable to link account",Re),l("unable_to_link_account")}}}else try{let m=c.emailVerified||!1;if(u=await e.context.internalAdapter.createOAuthUser({...d.data,emailVerified:m},{accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt,providerId:t.id,accountId:c.id.toString()}).then(w=>w?.user),!m&&u&&e.context.options.emailVerification?.sendOnSignUp){let w=await D(e.context.secret,u.email),R=`${e.context.baseURL}/verify-email?token=${w}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(u,R,w)}}catch(m){y.error("Unable to create user",m),l("unable_to_create_user")}if(!u)return l("unable_to_create_user");let p=await e.context.internalAdapter.createSession(u.id,e.request);p||l("unable_to_create_session"),await _(e,{session:p,user:u});let g;try{g=new URL(o).toString()}catch{g=o}throw e.redirect(g)});import"zod";import{APIError as wr}from"better-call";var ot=h("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new wr("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),j(e),e.json({success:!0})});import{z as C}from"zod";import{APIError as ae}from"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(([i,n])=>o.searchParams.set(i,n)),o.href}function br(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}var it=h("/forget-password",{method:"POST",body:C.object({email:C.string().email(),redirectTo:C.string()})},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 ae("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let i=60*60*1,n=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||i)),a=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${a}`,expiresAt:n});let c=`${e.context.baseURL}/reset-password/${a}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,c),e.json({status:!0})}),st=h("/reset-password/:token",{method:"GET",query:C.object({callbackURL:C.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(br(e.context,r,{token:t}))}),at=h("/reset-password",{query:C.optional(C.object({token:C.string().optional(),currentURL:C.string().optional()})),method:"POST",body:C.object({newPassword:C.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new ae("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,i=await e.context.internalAdapter.findVerificationValue(o);if(!i||i.expiresAt<new Date)throw new ae("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(i.id);let n=i.value,a=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(n)).find(l=>l.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:a,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(n,a))throw new ae("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as x}from"zod";import{APIError as U}from"better-call";var dt=()=>h("/update-user",{method:"POST",body:x.record(x.string(),x.any()),use:[P]},async e=>{let t=e.body;if(t.email)throw new U("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...i}=t,n=e.context.session;if(!o&&!r&&Object.keys(i).length===0)return e.json({user:n.user});let a=ie(e.context.options,i,"update"),c=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:r,image:o,...a});return await _(e,{session:n.session,user:c}),e.json({user:c})}),ct=h("/change-password",{method:"POST",body:x.object({newPassword:x.string(),currentPassword:x.string(),revokeOtherSessions:x.boolean().optional()}),use:[P]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new U("BAD_REQUEST",{message:"Password is too short"});let a=e.context.password.config.maxPasswordLength;if(t.length>a)throw e.context.logger.error("Password is too long"),new U("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(i.user.id)).find(f=>f.providerId==="credential"&&f.password);if(!s||!s.password)throw new U("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify(s.password,r))throw new U("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(s.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(i.user.id);let f=await e.context.internalAdapter.createSession(i.user.id,e.headers);if(!f)throw new U("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await _(e,{session:f,user:i.user})}return e.json(i.user)}),lt=h("/set-password",{method:"POST",body:x.object({newPassword:x.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 U("BAD_REQUEST",{message:"Password is too short"});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new U("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password),c=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:c}),e.json(r.user);throw new U("BAD_REQUEST",{message:"user already has a password"})}),ut=h("/delete-user",{method:"POST",body:x.object({password:x.string()}),use:[P]},async e=>{let{password:t}=e.body,r=e.context.session,i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password);if(!i||!i.password)throw new U("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(i.password,t))throw new U("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),j(e),e.json(null)}),pt=h("/change-email",{method:"POST",query:x.object({currentURL:x.string().optional()}).optional(),body:x.object({newEmail:x.string().email(),callbackURL:x.string().optional()}),use:[P]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new U("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 U("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 U("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let i=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:i,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new U("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await D(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(e.context.session.user,e.body.newEmail,o,r),e.json({user:null,status:!0})});var Ar=(e="Unknown")=>`<!DOCTYPE html>
|
package/dist/oauth2.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use strict";var h=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var S=Object.prototype.hasOwnProperty;var C=(e,t)=>{for(var r in t)h(e,r,{get:t[r],enumerable:!0})},I=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of O(t))!S.call(e,o)&&o!==r&&h(e,o,{get:()=>t[o],enumerable:!(n=P(t,o))||n.enumerable});return e};var V=e=>I(h({},"__esModule",{value:!0}),e);var M={};C(M,{createAuthorizationURL:()=>B,generateCodeChallenge:()=>x,generateState:()=>q,getOAuth2Tokens:()=>_,parseState:()=>z,validateAuthorizationCode:()=>D});module.exports=V(M);var w=require("oslo/crypto"),L=require("oslo/encoding");var R=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function x(e){let t=await(0,w.sha256)(new TextEncoder().encode(e));return L.base64url.encode(new Uint8Array(t),{includePadding:!1})}function _(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?R(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function B({id:e,options:t,authorizationEndpoint:r,state:n,codeVerifier:o,scopes:s,claims:c,disablePkce:d,redirectURI:U}){let i=new URL(r);if(i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t.clientId),i.searchParams.set("state",n),i.searchParams.set("scope",s.join(" ")),i.searchParams.set("redirect_uri",t.redirectURI||U),!d&&o){let m=await x(o);i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("code_challenge",m)}if(c){let m=c.reduce((y,k)=>(y[k]=null,y),{});i.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...m}}))}return i}var T=require("@better-fetch/fetch");async function D({code:e,codeVerifier:t,redirectURI:r,options:n,tokenEndpoint:o}){let s=new URLSearchParams;s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),s.set("client_id",n.clientId),s.set("client_secret",n.clientSecret);let{data:c,error:d}=await(0,T.betterFetch)(o,{method:"POST",body:s,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(d)throw d;return _(c)}var g=require("oslo/oauth2"),a=require("zod"),b=require("better-call");var j=require("nanoid");var v=require("consola"),l=(0,v.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),N=e=>({log:(...t)=>{!e?.disabled&&l.log("",...t)},error:(...t)=>{!e?.disabled&&l.error("",...t)},warn:(...t)=>{!e?.disabled&&l.warn("",...t)},info:(...t)=>{!e?.disabled&&l.info("",...t)},debug:(...t)=>{!e?.disabled&&l.debug("",...t)},box:(...t)=>{!e?.disabled&&l.box("",...t)},success:(...t)=>{!e?.disabled&&l.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
|
-
`)}}),u=N();var f=Object.create(null),p=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?f:globalThis),E=new Proxy(f,{get(e,t){return p()[t]??f[t]},has(e,t){let r=p();return t in r||t in f},set(e,t,r){let n=p(!0);return n[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=p(!0);return delete r[t],!0},ownKeys(){let e=p(!0);return Object.keys(e)}});function $(e){return e?e!=="false":!1}var H=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var le=H==="test"||$(E.TEST);function A(e){try{return new URL(e).origin}catch{return null}}async function q(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?A(e.query?.currentURL):"");if(!r)throw new b.APIError("BAD_REQUEST",{message:"callbackURL is required"});let n=(0,g.generateCodeVerifier)(),o=(0,g.generateState)(),s=JSON.stringify({callbackURL:r,codeVerifier:n,errorURL:e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),c=new Date;c.setMinutes(c.getMinutes()+10);let d=await e.context.internalAdapter.createVerificationValue({value:s,identifier:o,expiresAt:c});if(!d)throw u.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new b.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:d.identifier,codeVerifier:n}}async function z(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw u.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let n=a.z.object({callbackURL:a.z.string(),codeVerifier:a.z.string(),errorURL:a.z.string().optional(),expiresAt:a.z.number(),link:a.z.object({email:a.z.string(),userId:a.z.string()}).optional()}).parse(JSON.parse(r.value));if(n.errorURL||(n.errorURL=`${e.context.baseURL}/error`),n.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),u.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),n}0&&(module.exports={createAuthorizationURL,generateCodeChallenge,generateState,getOAuth2Tokens,parseState,validateAuthorizationCode});
|
|
2
|
+
`)}}),u=N();var f=Object.create(null),p=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?f:globalThis),E=new Proxy(f,{get(e,t){return p()[t]??f[t]},has(e,t){let r=p();return t in r||t in f},set(e,t,r){let n=p(!0);return n[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=p(!0);return delete r[t],!0},ownKeys(){let e=p(!0);return Object.keys(e)}});function $(e){return e?e!=="false":!1}var H=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var le=H==="test"||$(E.TEST);function A(e){try{return new URL(e).origin}catch{return null}}async function q(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?A(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new b.APIError("BAD_REQUEST",{message:"callbackURL is required"});let n=(0,g.generateCodeVerifier)(),o=(0,g.generateState)(),s=JSON.stringify({callbackURL:r,codeVerifier:n,errorURL:e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),c=new Date;c.setMinutes(c.getMinutes()+10);let d=await e.context.internalAdapter.createVerificationValue({value:s,identifier:o,expiresAt:c});if(!d)throw u.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new b.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:d.identifier,codeVerifier:n}}async function z(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw u.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let n=a.z.object({callbackURL:a.z.string(),codeVerifier:a.z.string(),errorURL:a.z.string().optional(),expiresAt:a.z.number(),link:a.z.object({email:a.z.string(),userId:a.z.string()}).optional()}).parse(JSON.parse(r.value));if(n.errorURL||(n.errorURL=`${e.context.baseURL}/error`),n.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),u.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),n}0&&(module.exports={createAuthorizationURL,generateCodeChallenge,generateState,getOAuth2Tokens,parseState,validateAuthorizationCode});
|
package/dist/oauth2.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{sha256 as L}from"oslo/crypto";import{base64url as T}from"oslo/encoding";var x=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function _(e){let t=await L(new TextEncoder().encode(e));return T.encode(new Uint8Array(t),{includePadding:!1})}function b(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?x(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function N({id:e,options:t,authorizationEndpoint:r,state:n,codeVerifier:l,scopes:o,claims:i,disablePkce:c,redirectURI:m}){let s=new URL(r);if(s.searchParams.set("response_type","code"),s.searchParams.set("client_id",t.clientId),s.searchParams.set("state",n),s.searchParams.set("scope",o.join(" ")),s.searchParams.set("redirect_uri",t.redirectURI||m),!c&&l){let g=await _(l);s.searchParams.set("code_challenge_method","S256"),s.searchParams.set("code_challenge",g)}if(i){let g=i.reduce((h,w)=>(h[w]=null,h),{});s.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...g}}))}return s}import{betterFetch as v}from"@better-fetch/fetch";async function z({code:e,codeVerifier:t,redirectURI:r,options:n,tokenEndpoint:l}){let o=new URLSearchParams;o.set("grant_type","authorization_code"),o.set("code",e),t&&o.set("code_verifier",t),o.set("redirect_uri",r),o.set("client_id",n.clientId),o.set("client_secret",n.clientSecret);let{data:i,error:c}=await v(l,{method:"POST",body:o,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(c)throw c;return b(i)}import{generateCodeVerifier as O,generateState as S}from"oslo/oauth2";import{z as a}from"zod";import{APIError as R}from"better-call";import{nanoid as F}from"nanoid";import{createConsola as E}from"consola";var d=E({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),A=e=>({log:(...t)=>{!e?.disabled&&d.log("",...t)},error:(...t)=>{!e?.disabled&&d.error("",...t)},warn:(...t)=>{!e?.disabled&&d.warn("",...t)},info:(...t)=>{!e?.disabled&&d.info("",...t)},debug:(...t)=>{!e?.disabled&&d.debug("",...t)},box:(...t)=>{!e?.disabled&&d.box("",...t)},success:(...t)=>{!e?.disabled&&d.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
|
-
`)}}),u=A();var f=Object.create(null),p=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?f:globalThis),U=new Proxy(f,{get(e,t){return p()[t]??f[t]},has(e,t){let r=p();return t in r||t in f},set(e,t,r){let n=p(!0);return n[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=p(!0);return delete r[t],!0},ownKeys(){let e=p(!0);return Object.keys(e)}});function k(e){return e?e!=="false":!1}var P=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var se=P==="test"||k(U.TEST);function y(e){try{return new URL(e).origin}catch{return null}}async function xe(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?y(e.query?.currentURL):"");if(!r)throw new R("BAD_REQUEST",{message:"callbackURL is required"});let n=O(),l=S(),o=JSON.stringify({callbackURL:r,codeVerifier:n,errorURL:e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),i=new Date;i.setMinutes(i.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:o,identifier:l,expiresAt:i});if(!c)throw u.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new R("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:n}}async function _e(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw u.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let n=a.object({callbackURL:a.string(),codeVerifier:a.string(),errorURL:a.string().optional(),expiresAt:a.number(),link:a.object({email:a.string(),userId:a.string()}).optional()}).parse(JSON.parse(r.value));if(n.errorURL||(n.errorURL=`${e.context.baseURL}/error`),n.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),u.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),n}export{N as createAuthorizationURL,_ as generateCodeChallenge,xe as generateState,b as getOAuth2Tokens,_e as parseState,z as validateAuthorizationCode};
|
|
2
|
+
`)}}),u=A();var f=Object.create(null),p=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?f:globalThis),U=new Proxy(f,{get(e,t){return p()[t]??f[t]},has(e,t){let r=p();return t in r||t in f},set(e,t,r){let n=p(!0);return n[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=p(!0);return delete r[t],!0},ownKeys(){let e=p(!0);return Object.keys(e)}});function k(e){return e?e!=="false":!1}var P=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var se=P==="test"||k(U.TEST);function y(e){try{return new URL(e).origin}catch{return null}}async function xe(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?y(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new R("BAD_REQUEST",{message:"callbackURL is required"});let n=O(),l=S(),o=JSON.stringify({callbackURL:r,codeVerifier:n,errorURL:e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),i=new Date;i.setMinutes(i.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:o,identifier:l,expiresAt:i});if(!c)throw u.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new R("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:n}}async function _e(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw u.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let n=a.object({callbackURL:a.string(),codeVerifier:a.string(),errorURL:a.string().optional(),expiresAt:a.number(),link:a.object({email:a.string(),userId:a.string()}).optional()}).parse(JSON.parse(r.value));if(n.errorURL||(n.errorURL=`${e.context.baseURL}/error`),n.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),u.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),n}export{N as createAuthorizationURL,_ as generateCodeChallenge,xe as generateState,b as getOAuth2Tokens,_e as parseState,z as validateAuthorizationCode};
|