better-auth 0.8.1-beta.4 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/drizzle.d.cts +1 -1
- package/dist/adapters/drizzle.d.ts +1 -1
- package/dist/adapters/kysely.d.cts +1 -1
- package/dist/adapters/kysely.d.ts +1 -1
- package/dist/adapters/memory.d.cts +1 -1
- package/dist/adapters/memory.d.ts +1 -1
- package/dist/adapters/mongodb.d.cts +1 -1
- package/dist/adapters/mongodb.d.ts +1 -1
- package/dist/adapters/prisma.d.cts +1 -1
- package/dist/adapters/prisma.d.ts +1 -1
- package/dist/api.cjs +1 -1
- package/dist/api.d.cts +1 -1
- package/dist/api.d.ts +1 -1
- package/dist/api.js +1 -1
- package/dist/{auth-CRDJtWaN.d.cts → auth-BgN7MPT5.d.cts} +28 -28
- package/dist/{auth-DP-ZFlGK.d.ts → auth-CzfMT2af.d.ts} +28 -28
- package/dist/client/plugins.d.cts +3 -4
- package/dist/client/plugins.d.ts +3 -4
- package/dist/client.d.cts +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/cookies.d.cts +1 -1
- package/dist/cookies.d.ts +1 -1
- package/dist/db.cjs +3 -3
- package/dist/db.d.cts +2 -2
- package/dist/db.d.ts +2 -2
- package/dist/db.js +3 -3
- package/dist/{index-CENJlACM.d.cts → index-DHt0QBT2.d.cts} +7 -21
- package/dist/{index-BH4FVjl_.d.ts → index-mkmshQaW.d.ts} +7 -21
- package/dist/index.cjs +5 -5
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +5 -5
- package/dist/node.d.cts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/oauth2.d.cts +2 -2
- package/dist/oauth2.d.ts +2 -2
- package/dist/plugins.cjs +3 -3
- package/dist/plugins.d.cts +3 -3
- package/dist/plugins.d.ts +3 -3
- package/dist/plugins.js +3 -3
- package/dist/react.d.cts +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/solid-start.d.cts +1 -1
- package/dist/solid-start.d.ts +1 -1
- package/dist/solid.d.cts +1 -1
- package/dist/solid.d.ts +1 -1
- package/dist/{state-CfvqSQJk.d.cts → state-BbRjpTGS.d.cts} +1 -1
- package/dist/{state-_22Ngsc7.d.ts → state-DzyzU-V_.d.ts} +1 -1
- package/dist/svelte-kit.d.cts +1 -1
- package/dist/svelte-kit.d.ts +1 -1
- package/dist/svelte.d.cts +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/types.d.cts +2 -2
- package/dist/types.d.ts +2 -2
- package/dist/vue.d.cts +1 -1
- package/dist/vue.d.ts +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Kysely } from 'kysely';
|
|
2
|
-
import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-
|
|
2
|
+
import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-BgN7MPT5.cjs';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'better-call';
|
|
5
5
|
import '../index-cqC7BcV_.cjs';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Kysely } from 'kysely';
|
|
2
|
-
import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-
|
|
2
|
+
import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-CzfMT2af.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'better-call';
|
|
5
5
|
import '../index-DN9ozDRm.js';
|
package/dist/api.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";var ce=Object.defineProperty;var zt=Object.getOwnPropertyDescriptor;var jt=Object.getOwnPropertyNames;var $t=Object.prototype.hasOwnProperty;var qt=(e,t)=>{for(var r in t)ce(e,r,{get:t[r],enumerable:!0})},Nt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of jt(t))!$t.call(e,i)&&i!==r&&ce(e,i,{get:()=>t[i],enumerable:!(o=zt(t,i))||o.enumerable});return e};var Ft=e=>Nt(ce({},"__esModule",{value:!0}),e);var cr={};qt(cr,{APIError:()=>Dt.APIError,callbackOAuth:()=>ve,changeEmail:()=>Le,changePassword:()=>Oe,createAuthEndpoint:()=>p,createAuthMiddleware:()=>Q,createEmailVerificationToken:()=>S,deleteUser:()=>Ie,error:()=>Ce,forgetPassword:()=>_e,forgetPasswordCallback:()=>Te,getEndpoints:()=>Bt,getSession:()=>oe,getSessionFromCtx:()=>ie,linkSocialAccount:()=>je,listSessions:()=>he,listUserAccounts:()=>ze,ok:()=>Be,optionsMiddleware:()=>le,originCheckMiddleware:()=>me,resetPassword:()=>xe,revokeOtherSessions:()=>ye,revokeSession:()=>we,revokeSessions:()=>be,router:()=>dr,sendVerificationEmail:()=>Ae,sessionMiddleware:()=>T,setPassword:()=>Se,signInEmail:()=>Ue,signInSocial:()=>Re,signOut:()=>Ee,signUpEmail:()=>De,updateUser:()=>Pe,verifyEmail:()=>ke});module.exports=Ft(cr);var N=require("better-call");var Ze=require("better-call");var D=require("better-call"),le=(0,D.createMiddleware)(async()=>({})),Q=(0,D.createMiddlewareCreator)({use:[le,(0,D.createMiddleware)(async()=>({}))]}),p=(0,D.createEndpointCreator)({use:[le]});var F={isAction:!1};var $e=require("nanoid"),qe=e=>(0,$e.nanoid)(e);var Y=require("oslo/oauth2"),L=require("zod"),pe=require("better-call");var K=Object.create(null),Z=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?K:globalThis),Ne=new Proxy(K,{get(e,t){return Z()[t]??K[t]},has(e,t){let r=Z();return t in r||t in K},set(e,t,r){let o=Z(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=Z(!0);return delete r[t],!0},ownKeys(){let e=Z(!0);return Object.keys(e)}});function Mt(e){return e?e!=="false":!1}var ue=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Fe=ue==="dev"||ue==="development",Me=ue==="test"||Mt(Ne.TEST);var V=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}};function He(e){try{return new URL(e).origin}catch{return null}}async function X(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?He(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new pe.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 m.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new pe.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function Ge(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw m.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=L.z.object({callbackURL:L.z.string(),codeVerifier:L.z.string(),errorURL:L.z.string().optional(),expiresAt:L.z.number(),link:L.z.object({email:L.z.string(),userId:L.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),m.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 Qe=require("consola"),z=(0,Qe.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Ht=e=>({log:(...t)=>{!e?.disabled&&z.log("",...t)},error:(...t)=>{!e?.disabled&&z.error("",...t)},warn:(...t)=>{!e?.disabled&&z.warn("",...t)},info:(...t)=>{!e?.disabled&&z.info("",...t)},debug:(...t)=>{!e?.disabled&&z.debug("",...t)},box:(...t)=>{!e?.disabled&&z.box("",...t)},success:(...t)=>{!e?.disabled&&z.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
2
|
`)}}),m=Ht();var me=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||r?.callbackURL,s=t?.redirectTo,a=r?.currentURL,d=o.trustedOrigins,c=e.headers?.has("cookie"),l=(g,u)=>u.includes("*")?new RegExp("^"+u.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(g):g.startsWith(u),f=(g,u)=>{if(!g)return;if(!d.some(y=>l(g,y)||g?.startsWith("/")&&u!=="origin"&&!g.includes(":")))throw m.error(`Invalid ${u}: ${g}`),m.info(`If it's a valid URL, please add ${g} to trustedOrigins in your auth config
|
|
3
3
|
`,`Current list of trustedOrigins: ${d}`),new Ze.APIError("FORBIDDEN",{message:`Invalid ${u}`})};c&&!e.context.options.advanced?.disableCSRFCheck&&f(i,"origin"),n&&f(n,"callbackURL"),s&&f(s,"redirectURL"),a&&f(a,"currentURL")});var v=require("better-call"),k=require("zod");var Zt=require("oslo");var ee=require("oslo/crypto");async function Gt({value:e,secret:t}){return new ee.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function Qt({value:e,signature:t,secret:r}){return new ee.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var te={sign:Gt,verify:Qt};var Je=require("oslo/encoding");var C=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));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&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Je.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:C(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await te.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.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})}var tt=require("oslo/jwt");var We=require("oslo/crypto"),Ke=require("oslo/encoding");async function Ye(e){let t=await(0,We.sha256)(new TextEncoder().encode(e));return Ke.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Xe(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?C(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:s,redirectURI:a}){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||a),i){let c=await Ye(i);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",c)}if(s){let c=s.reduce((l,f)=>(l[f]=null,l),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...c}}))}return d}var et=require("@better-fetch/fetch");async function b({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i,authentication:n}){let s=new URLSearchParams,a={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),n==="basic"){let f=btoa(`${o.clientId}:${o.clientSecret}`);a.authorization=`Basic ${f}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:d,error:c}=await(0,et.betterFetch)(i,{method:"POST",body:s,headers:a});if(c)throw c;return Xe(d)}var M=require("jose"),rt=require("@better-fetch/fetch"),ot=require("better-call"),so=require("zod"),it=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})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let i=(0,M.decodeJwt)(r),{kid:n,alg:s}=i.header,a=await Jt(n),{payload:d}=await(0,M.jwtVerify)(r,a,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(c=>{d[c]!==void 0&&(d[c]=!!d[c])}),o&&d.nonce!==o?!1:!!d},async getUserInfo(r){if(!r.idToken)return null;let o=(0,tt.parseJWT)(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true",image:o.picture},data:o}:null}}},Jt=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,rt.betterFetch)(`${t}${r}`);if(!o?.keys)throw new ot.APIError("BAD_REQUEST",{message:"Keys not found"});let i=o.keys.find(n=>n.kid===e);if(!i)throw new Error(`JWK with kid ${e} not found`);return await(0,M.importJWK)(i,i.alg)};var nt=require("@better-fetch/fetch");var st=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})=>b({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,nt.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 at=require("@better-fetch/fetch");var dt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await(0,at.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 fe=require("@better-fetch/fetch");var ct=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>b({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await(0,fe.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,fe.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(d=>d.primary)??s[0])?.email,n=s.find(d=>d.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 lt=require("oslo/jwt");var ut=require("@better-fetch/fetch"),pt=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw m.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new V("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new V("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:i}=await(0,ut.betterFetch)(o);return i?i.aud===e.clientId&&i.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(!t.idToken)return null;let r=(0,lt.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 mt=require("@better-fetch/fetch"),ft=require("oslo/jwt");var gt=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),A({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return b({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(!i.idToken)return null;let n=(0,ft.parseJWT)(i.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,mt.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 c=await a.response.clone().arrayBuffer(),l=Buffer.from(c).toString("base64");n.picture=`data:image/jpeg;base64, ${l}`}catch(d){m.error(d)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};var ht=require("@better-fetch/fetch");var wt=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,ht.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 Eo=require("@better-fetch/fetch");var bt=require("oslo/jwt");var yt=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return m.error("No idToken found in token"),null;let o=(0,bt.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var At=require("@better-fetch/fetch");var kt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),A({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,At.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var Rt=require("@better-fetch/fetch");var Ut=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await b({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await(0,Rt.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 vt=require("@better-fetch/fetch");var Et=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await b({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await(0,vt.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 _t=require("@better-fetch/fetch");var ge=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Wt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ge(`${t}/oauth/authorize`),tokenEndpoint:ge(`${t}/oauth/token`),userinfoEndpoint:ge(`${t}/api/v4/user`)}},Tt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Wt(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:d,redirectURI:c})=>{let l=a||["read_user"];return e.scope&&l.push(...e.scope),await A({id:i,options:e,authorizationEndpoint:t,scopes:l,state:s,redirectURI:c,codeVerifier:d})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:d})=>b({code:s,redirectURI:e.redirectURI||a,options:e,codeVerifier:d,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:d}=await(0,_t.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return d||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 Kt={apple:it,discord:st,facebook:dt,github:ct,microsoft:gt,google:pt,spotify:wt,twitch:yt,twitter:kt,dropbox:Ut,linkedin:Et,gitlab:Tt},re=Object.keys(Kt);var Pt=require("oslo"),ne=require("oslo/jwt"),P=require("zod");var $=require("better-call");var j=require("better-call");var H=require("zod");function xt(e){try{return JSON.parse(e)}catch{return null}}var oe=()=>p("/get-session",{method:"GET",query:H.z.optional(H.z.object({disableCookieCache:H.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=e.getCookie(e.context.authCookies.sessionData.name),o=r?xt(Buffer.from(r,"base64").toString()):null;if(o&&!await te.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return B(e),e.json(null,{status:401});let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let l=o.session;if(o.expiresAt<Date.now()||l.session.expiresAt<new Date){let g=e.context.authCookies.sessionData.name;e.setCookie(g,"",{maxAge:0})}else return e.json(l)}let n=await e.context.internalAdapter.findSession(t);if(!n||n.session.expiresAt<new Date)return B(e),n&&await e.context.internalAdapter.deleteSession(n.session.id),e.json(null,{status:401});if(i)return e.json(n);let s=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-s*1e3+a*1e3<=Date.now()){let l=await e.context.internalAdapter.updateSession(n.session.id,{expiresAt:C(e.context.sessionConfig.expiresIn,"sec")});if(!l)return B(e),e.json(null,{status:401});let f=(l.expiresAt.valueOf()-Date.now())/1e3;return await x(e,{session:l,user:n.user},!1,{maxAge:f}),e.json({session:l,user:n.user})}return e.json(n)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),ie=async e=>await oe()({...e,_flag:"json",headers:e.headers}),T=Q(async e=>{let t=await ie(e);if(!t?.session)throw new j.APIError("UNAUTHORIZED");return{session:t}}),he=()=>p("/list-sessions",{method:"GET",use:[T],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)}),we=p("/revoke-session",{method:"POST",body:H.z.object({id:H.z.string()}),use:[T],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new j.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new j.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new j.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),be=p("/revoke-sessions",{method:"POST",use:[T],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new j.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ye=p("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[T]},async e=>{let t=e.context.session;if(!t.user)throw new j.APIError("UNAUTHORIZED");let i=(await e.context.internalAdapter.listSessions(t.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.id!==e.context.session.session.id);return await Promise.all(i.map(n=>e.context.internalAdapter.deleteSession(n.id))),e.json({status:!0})});async function S(e,t,r){return await(0,ne.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Pt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Ae=p("/send-verification-email",{method:"POST",query:P.z.object({currentURL:P.z.string().optional()}).optional(),body:P.z.object({email:P.z.string().email(),callbackURL:P.z.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new $.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 $.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})}),ke=p("/verify-email",{method:"GET",query:P.z.object({token:P.z.string(),callbackURL:P.z.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await(0,ne.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new $.APIError("BAD_REQUEST",{message:"Invalid token"})}let i=P.z.object({email:P.z.string().email(),updateTo:P.z.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(i.email))throw new $.APIError("BAD_REQUEST",{message:"User not found"});if(i.updateTo){let s=await ie(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new $.APIError("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==i.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new $.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})});async function se(e,{userInfo:t,account:r,callbackURL:o}){let i=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw m.error(`Better auth was unable to query your database.
|
|
4
|
-
Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=i?.user;if(i){let a=i.accounts.find(d=>d.providerId===r.providerId);if(a)await e.context.internalAdapter.updateAccount(a.id,{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt});else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Fe&&m.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),id:e.context.uuid(),userId:i.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt})}catch(l){return m.error("Unable to link account",l),{error:"unable to link account",data:null}}}}else try{let a=t.emailVerified||!1;if(n=await e.context.internalAdapter.createOAuthUser({...t,id:e.context.uuid(),emailVerified:a,email:t.email.toLowerCase()},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,providerId:r.providerId,accountId:t.id.toString()}).then(d=>d?.user),!a&&n&&e.context.options.emailVerification?.sendOnSignUp){let d=await S(e.context.secret,n.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(n,c,d)}}catch(a){return m.error("Unable to create user",a),{error:"unable to create user",data:null}}if(!n)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(n.id,e.request);return s?{data:{session:s,user:n},error:null}:{error:"unable to create session",data:null}}var Re=p("/sign-in/social",{method:"POST",query:k.z.object({currentURL:k.z.string().optional()}).optional(),body:k.z.object({callbackURL:k.z.string().optional(),provider:k.z.enum(re),idToken:k.z.optional(k.z.object({token:k.z.string(),nonce:k.z.string().optional(),accessToken:k.z.string().optional(),refreshToken:k.z.string().optional(),expiresAt:k.z.number().optional()}))})},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 v.APIError("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new v.APIError("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:n,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(n,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:"Invalid id token"});let d=await t.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!d||!d?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:"Failed to get user info"});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:"User email not found"});let c=await se(e,{userInfo:{email:d.user.email,id:d.user.id,name:d.user.name||"",image:d.user.image,emailVerified:d.user.emailVerified||!1},account:{providerId:t.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new v.APIError("UNAUTHORIZED",{message:c.error});return await x(e,c.data),e.json({session:c.data.session,user:c.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:r,state:o}=await X(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!0})}),Ue=p("/sign-in/email",{method:"POST",body:k.z.object({email:k.z.string(),password:k.z.string(),callbackURL:k.z.string().optional(),dontRememberMe:k.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 v.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!k.z.string().email().safeParse(t).success)throw new v.APIError("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let n=i.accounts.find(c=>c.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=n?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw m.error("Email verification is required but no email verification handler is provided"),new v.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await S(e.context.secret,i.user.email),l=`${e.context.options.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,l,c),e.context.logger.error("Email not verified",{email:t}),new v.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new v.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await x(e,{session:d,user:i.user},e.body.dontRememberMe),e.json({user:i.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var J=require("zod");var h=require("zod"),Oi=h.z.object({id:h.z.string(),providerId:h.z.string(),accountId:h.z.string(),userId:h.z.string(),accessToken:h.z.string().nullable().optional(),refreshToken:h.z.string().nullable().optional(),idToken:h.z.string().nullable().optional(),expiresAt:h.z.date().nullable().optional(),password:h.z.string().optional().nullable()}),Si=h.z.object({id:h.z.string(),email:h.z.string().transform(e=>e.toLowerCase()),emailVerified:h.z.boolean().default(!1),name:h.z.string(),image:h.z.string().optional(),createdAt:h.z.date().default(new Date),updatedAt:h.z.date().default(new Date)}),Ii=h.z.object({id:h.z.string(),userId:h.z.string(),expiresAt:h.z.date(),ipAddress:h.z.string().optional(),userAgent:h.z.string().optional()}),Li=h.z.object({id:h.z.string(),value:h.z.string(),expiresAt:h.z.date(),identifier:h.z.string()});function Yt(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 Xt(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 ae(e,t,r){let o=Yt(e,"user");return Xt(t||{},{fields:o,action:r})}var ve=p("/callback/:id",{method:"GET",query:J.z.object({state:J.z.string(),code:J.z.string().optional(),error:J.z.string().optional()}),metadata:F},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(y=>y.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 Ge(e),s;try{s=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(y){throw e.context.logger.error(y),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(s).then(y=>y?.user),c={id:qe(),...a};function l(y){let w=n||o||`${e.context.baseURL}/error`;throw w.includes("?")?w=`${w}&error=${y}`:w=`${w}?error=${y}`,e.redirect(w)}if(!a)return m.error("Unable to get user info"),l("unable_to_get_user_info");if(!c.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),l("email_not_found");if(!o)throw m.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:a.id}))return l("unable_to_link_account");let w;try{w=new URL(o).toString()}catch{w=o}throw e.redirect(w)}let f=await se(e,{userInfo:{email:c.email,id:c.id,name:c.name||"",image:c.image,emailVerified:c.emailVerified||!1},account:{providerId:t.id,accountId:a.id,accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt},callbackURL:o});if(f.error)return l(f.error.split(" ").join("_"));let{session:g,user:u}=f.data;await x(e,{session:g,user:u});let R;try{R=new URL(o).toString()}catch{R=o}throw e.redirect(R)});var Hi=require("zod");var Ot=require("better-call"),Ee=p("/sign-out",{method:"POST",requireHeaders:!0},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Ot.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),B(e),e.json({success:!0})});var O=require("zod");var W=require("better-call");function St(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}function er(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.z.object({email:O.z.string().email(),redirectTo:O.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 W.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})}),Te=p("/reset-password/:token",{method:"GET",query:O.z.object({callbackURL:O.z.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(St(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(St(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(er(e.context,r,{token:t}))}),xe=p("/reset-password",{query:O.z.optional(O.z.object({token:O.z.string().optional(),currentURL:O.z.string().optional()})),method:"POST",body:O.z.object({newPassword:O.z.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new W.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 W.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(l=>l.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 W.APIError("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});var U=require("zod");var E=require("better-call");var Pe=()=>p("/update-user",{method:"POST",body:U.z.record(U.z.string(),U.z.any()),use:[T]},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=ae(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})}),Oe=p("/change-password",{method:"POST",body:U.z.object({newPassword:U.z.string(),currentPassword:U.z.string(),revokeOtherSessions:U.z.boolean().optional()}),use:[T]},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 d=(await e.context.internalAdapter.findAccounts(i.user.id)).find(f=>f.providerId==="credential"&&f.password);if(!d||!d.password)throw new E.APIError("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(d.password,r))throw new E.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),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 E.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await x(e,{session:f,user:i.user})}return e.json(i.user)}),Se=p("/set-password",{method:"POST",body:U.z.object({newPassword:U.z.string()}),metadata:{SERVER_ONLY:!0},use:[T]},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(d=>d.providerId==="credential"&&d.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"})}),Ie=p("/delete-user",{method:"POST",body:U.z.object({password:U.z.string()}),use:[T]},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),B(e),e.json(null)}),Le=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:[T]},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 tr=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
|
+
Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=i?.user;if(i){let a=i.accounts.find(d=>d.providerId===r.providerId);if(a)await e.context.internalAdapter.updateAccount(a.id,{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt});else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Fe&&m.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),id:e.context.uuid(),userId:i.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt})}catch(l){return m.error("Unable to link account",l),{error:"unable to link account",data:null}}}}else try{let a=t.emailVerified||!1;if(n=await e.context.internalAdapter.createOAuthUser({...t,id:e.context.uuid(),emailVerified:a,email:t.email.toLowerCase()},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,providerId:r.providerId,accountId:t.id.toString()}).then(d=>d?.user),!a&&n&&e.context.options.emailVerification?.sendOnSignUp){let d=await S(e.context.secret,n.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(n,c,d)}}catch(a){return m.error("Unable to create user",a),{error:"unable to create user",data:null}}if(!n)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(n.id,e.request);return s?{data:{session:s,user:n},error:null}:{error:"unable to create session",data:null}}var Re=p("/sign-in/social",{method:"POST",query:k.z.object({currentURL:k.z.string().optional()}).optional(),body:k.z.object({callbackURL:k.z.string().optional(),provider:k.z.enum(re),idToken:k.z.optional(k.z.object({token:k.z.string(),nonce:k.z.string().optional(),accessToken:k.z.string().optional(),refreshToken:k.z.string().optional(),expiresAt:k.z.number().optional()}))})},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 v.APIError("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new v.APIError("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:n,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(n,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:"Invalid id token"});let d=await t.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!d||!d?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:"Failed to get user info"});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:"User email not found"});let c=await se(e,{userInfo:{email:d.user.email,id:d.user.id,name:d.user.name||"",image:d.user.image,emailVerified:d.user.emailVerified||!1},account:{providerId:t.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new v.APIError("UNAUTHORIZED",{message:c.error});return await x(e,c.data),e.json({session:c.data.session,user:c.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:r,state:o}=await X(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!0})}),Ue=p("/sign-in/email",{method:"POST",body:k.z.object({email:k.z.string(),password:k.z.string(),callbackURL:k.z.string().optional(),rememberMe:k.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 v.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!k.z.string().email().safeParse(t).success)throw new v.APIError("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let n=i.accounts.find(c=>c.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=n?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw m.error("Email verification is required but no email verification handler is provided"),new v.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await S(e.context.secret,i.user.email),l=`${e.context.options.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,l,c),e.context.logger.error("Email not verified",{email:t}),new v.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.rememberMe===!1);if(!d)throw e.context.logger.error("Failed to create session"),new v.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await x(e,{session:d,user:i.user},e.body.rememberMe===!1),e.json({user:i.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var J=require("zod");var h=require("zod"),Oi=h.z.object({id:h.z.string(),providerId:h.z.string(),accountId:h.z.string(),userId:h.z.string(),accessToken:h.z.string().nullable().optional(),refreshToken:h.z.string().nullable().optional(),idToken:h.z.string().nullable().optional(),expiresAt:h.z.date().nullable().optional(),password:h.z.string().optional().nullable()}),Si=h.z.object({id:h.z.string(),email:h.z.string().transform(e=>e.toLowerCase()),emailVerified:h.z.boolean().default(!1),name:h.z.string(),image:h.z.string().optional(),createdAt:h.z.date().default(new Date),updatedAt:h.z.date().default(new Date)}),Ii=h.z.object({id:h.z.string(),userId:h.z.string(),expiresAt:h.z.date(),ipAddress:h.z.string().optional(),userAgent:h.z.string().optional()}),Li=h.z.object({id:h.z.string(),value:h.z.string(),expiresAt:h.z.date(),identifier:h.z.string()});function Yt(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 Xt(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 ae(e,t,r){let o=Yt(e,"user");return Xt(t||{},{fields:o,action:r})}var ve=p("/callback/:id",{method:"GET",query:J.z.object({state:J.z.string(),code:J.z.string().optional(),error:J.z.string().optional()}),metadata:F},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(y=>y.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 Ge(e),s;try{s=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(y){throw e.context.logger.error(y),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(s).then(y=>y?.user),c={id:qe(),...a};function l(y){let w=n||o||`${e.context.baseURL}/error`;throw w.includes("?")?w=`${w}&error=${y}`:w=`${w}?error=${y}`,e.redirect(w)}if(!a)return m.error("Unable to get user info"),l("unable_to_get_user_info");if(!c.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),l("email_not_found");if(!o)throw m.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:a.id}))return l("unable_to_link_account");let w;try{w=new URL(o).toString()}catch{w=o}throw e.redirect(w)}let f=await se(e,{userInfo:{email:c.email,id:c.id,name:c.name||"",image:c.image,emailVerified:c.emailVerified||!1},account:{providerId:t.id,accountId:a.id,accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt},callbackURL:o});if(f.error)return l(f.error.split(" ").join("_"));let{session:g,user:u}=f.data;await x(e,{session:g,user:u});let R;try{R=new URL(o).toString()}catch{R=o}throw e.redirect(R)});var Hi=require("zod");var Ot=require("better-call"),Ee=p("/sign-out",{method:"POST",requireHeaders:!0},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Ot.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),B(e),e.json({success:!0})});var O=require("zod");var W=require("better-call");function St(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}function er(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.z.object({email:O.z.string().email(),redirectTo:O.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 W.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})}),Te=p("/reset-password/:token",{method:"GET",query:O.z.object({callbackURL:O.z.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(St(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(St(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(er(e.context,r,{token:t}))}),xe=p("/reset-password",{query:O.z.optional(O.z.object({token:O.z.string().optional(),currentURL:O.z.string().optional()})),method:"POST",body:O.z.object({newPassword:O.z.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new W.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 W.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(l=>l.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 W.APIError("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});var U=require("zod");var E=require("better-call");var Pe=()=>p("/update-user",{method:"POST",body:U.z.record(U.z.string(),U.z.any()),use:[T]},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=ae(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})}),Oe=p("/change-password",{method:"POST",body:U.z.object({newPassword:U.z.string(),currentPassword:U.z.string(),revokeOtherSessions:U.z.boolean().optional()}),use:[T]},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 d=(await e.context.internalAdapter.findAccounts(i.user.id)).find(f=>f.providerId==="credential"&&f.password);if(!d||!d.password)throw new E.APIError("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(d.password,r))throw new E.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),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 E.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await x(e,{session:f,user:i.user})}return e.json(i.user)}),Se=p("/set-password",{method:"POST",body:U.z.object({newPassword:U.z.string()}),metadata:{SERVER_ONLY:!0},use:[T]},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(d=>d.providerId==="credential"&&d.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"})}),Ie=p("/delete-user",{method:"POST",body:U.z.object({password:U.z.string()}),use:[T]},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),B(e),e.json(null)}),Le=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:[T]},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 tr=(e="Unknown")=>`<!DOCTYPE html>
|
|
5
5
|
<html lang="en">
|
|
6
6
|
<head>
|
|
7
7
|
<meta charset="UTF-8">
|
package/dist/api.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { y as AuthEndpoint, z as AuthMiddleware, a3 as callbackOAuth, am as changeEmail, aj as changePassword, x as createAuthEndpoint, w as createAuthMiddleware, af as createEmailVerificationToken, al as deleteUser, an as error, ac as forgetPassword, ad as forgetPasswordCallback, $ as getEndpoints, a4 as getSession, a5 as getSessionFromCtx, ar as linkSocialAccount, a7 as listSessions, aq as listUserAccounts, ao as ok, v as optionsMiddleware, as as originCheckMiddleware, ae as resetPassword, aa as revokeOtherSessions, a8 as revokeSession, a9 as revokeSessions, a0 as router, ag as sendVerificationEmail, a6 as sessionMiddleware, ak as setPassword, a2 as signInEmail, a1 as signInSocial, ab as signOut, ap as signUpEmail, ai as updateUser, ah as verifyEmail } from './auth-
|
|
1
|
+
export { y as AuthEndpoint, z as AuthMiddleware, a3 as callbackOAuth, am as changeEmail, aj as changePassword, x as createAuthEndpoint, w as createAuthMiddleware, af as createEmailVerificationToken, al as deleteUser, an as error, ac as forgetPassword, ad as forgetPasswordCallback, $ as getEndpoints, a4 as getSession, a5 as getSessionFromCtx, ar as linkSocialAccount, a7 as listSessions, aq as listUserAccounts, ao as ok, v as optionsMiddleware, as as originCheckMiddleware, ae as resetPassword, aa as revokeOtherSessions, a8 as revokeSession, a9 as revokeSessions, a0 as router, ag as sendVerificationEmail, a6 as sessionMiddleware, ak as setPassword, a2 as signInEmail, a1 as signInSocial, ab as signOut, ap as signUpEmail, ai as updateUser, ah as verifyEmail } from './auth-BgN7MPT5.cjs';
|
|
2
2
|
import './helper-DPDj8Nix.cjs';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|
package/dist/api.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { y as AuthEndpoint, z as AuthMiddleware, a3 as callbackOAuth, am as changeEmail, aj as changePassword, x as createAuthEndpoint, w as createAuthMiddleware, af as createEmailVerificationToken, al as deleteUser, an as error, ac as forgetPassword, ad as forgetPasswordCallback, $ as getEndpoints, a4 as getSession, a5 as getSessionFromCtx, ar as linkSocialAccount, a7 as listSessions, aq as listUserAccounts, ao as ok, v as optionsMiddleware, as as originCheckMiddleware, ae as resetPassword, aa as revokeOtherSessions, a8 as revokeSession, a9 as revokeSessions, a0 as router, ag as sendVerificationEmail, a6 as sessionMiddleware, ak as setPassword, a2 as signInEmail, a1 as signInSocial, ab as signOut, ap as signUpEmail, ai as updateUser, ah as verifyEmail } from './auth-
|
|
1
|
+
export { y as AuthEndpoint, z as AuthMiddleware, a3 as callbackOAuth, am as changeEmail, aj as changePassword, x as createAuthEndpoint, w as createAuthMiddleware, af as createEmailVerificationToken, al as deleteUser, an as error, ac as forgetPassword, ad as forgetPasswordCallback, $ as getEndpoints, a4 as getSession, a5 as getSessionFromCtx, ar as linkSocialAccount, a7 as listSessions, aq as listUserAccounts, ao as ok, v as optionsMiddleware, as as originCheckMiddleware, ae as resetPassword, aa as revokeOtherSessions, a8 as revokeSession, a9 as revokeSessions, a0 as router, ag as sendVerificationEmail, a6 as sessionMiddleware, ak as setPassword, a2 as signInEmail, a1 as signInSocial, ab as signOut, ap as signUpEmail, ai as updateUser, ah as verifyEmail } from './auth-CzfMT2af.js';
|
|
2
2
|
import './helper-DPDj8Nix.js';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|
package/dist/api.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import{APIError as st,createRouter as ir,statusCode as nr}from"better-call";import{APIError as ht}from"better-call";import{createEndpointCreator as dt,createMiddleware as ne,createMiddlewareCreator as ct}from"better-call";var se=ne(async()=>({})),H=ct({use:[se,ne(async()=>({}))]}),p=dt({use:[se]});var z={isAction:!1};import{nanoid as lt}from"nanoid";var ae=e=>lt(e);import{generateCodeVerifier as pt,generateState as mt}from"oslo/oauth2";import{z as L}from"zod";import{APIError as pe}from"better-call";var G=Object.create(null),N=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?G:globalThis),de=new Proxy(G,{get(e,t){return N()[t]??G[t]},has(e,t){let r=N();return t in r||t in G},set(e,t,r){let o=N(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=N(!0);return delete r[t],!0},ownKeys(){let e=N(!0);return Object.keys(e)}});function ut(e){return e?e!=="false":!1}var te=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var ce=te==="dev"||te==="development",le=te==="test"||ut(de.TEST);var D=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}};function ue(e){try{return new URL(e).origin}catch{return null}}async function Q(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?ue(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new pe("BAD_REQUEST",{message:"callbackURL is required"});let o=pt(),i=mt(),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 m.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:a.identifier,codeVerifier:o}}async function me(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw m.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=L.object({callbackURL:L.string(),codeVerifier:L.string(),errorURL:L.string().optional(),expiresAt:L.number(),link:L.object({email:L.string(),userId:L.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),m.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 ft}from"consola";var V=ft({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),gt=e=>({log:(...t)=>{!e?.disabled&&V.log("",...t)},error:(...t)=>{!e?.disabled&&V.error("",...t)},warn:(...t)=>{!e?.disabled&&V.warn("",...t)},info:(...t)=>{!e?.disabled&&V.info("",...t)},debug:(...t)=>{!e?.disabled&&V.debug("",...t)},box:(...t)=>{!e?.disabled&&V.box("",...t)},success:(...t)=>{!e?.disabled&&V.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
2
|
`)}}),m=gt();var fe=H(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,i=e.headers?.get("origin")||e.headers?.get("referer")||"",n=t?.callbackURL||r?.callbackURL,s=t?.redirectTo,a=r?.currentURL,d=o.trustedOrigins,c=e.headers?.has("cookie"),l=(g,u)=>u.includes("*")?new RegExp("^"+u.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(g):g.startsWith(u),f=(g,u)=>{if(!g)return;if(!d.some(y=>l(g,y)||g?.startsWith("/")&&u!=="origin"&&!g.includes(":")))throw m.error(`Invalid ${u}: ${g}`),m.info(`If it's a valid URL, please add ${g} to trustedOrigins in your auth config
|
|
3
3
|
`,`Current list of trustedOrigins: ${d}`),new ht("FORBIDDEN",{message:`Invalid ${u}`})};c&&!e.context.options.advanced?.disableCSRFCheck&&f(i,"origin"),n&&f(n,"callbackURL"),s&&f(s,"redirectURL"),a&&f(a,"currentURL")});import{APIError as v}from"better-call";import{z as R}from"zod";import{TimeSpan as Qr}from"oslo";import{HMAC as ge,sha256 as qr}from"oslo/crypto";async function wt({value:e,secret:t}){return new ge("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function bt({value:e,signature:t,secret:r}){return new ge("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var Z={sign:wt,verify:bt};import{base64url as yt}from"oslo/encoding";var C=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));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&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(yt.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:C(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await Z.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.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 Ut}from"oslo/jwt";import{sha256 as At}from"oslo/crypto";import{base64url as kt}from"oslo/encoding";async function he(e){let t=await At(new TextEncoder().encode(e));return kt.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?C(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:s,redirectURI:a}){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||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((l,f)=>(l[f]=null,l),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...c}}))}return d}import{betterFetch as Rt}from"@better-fetch/fetch";async function b({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i,authentication:n}){let s=new URLSearchParams,a={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),n==="basic"){let f=btoa(`${o.clientId}:${o.clientSecret}`);a.authorization=`Basic ${f}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:d,error:c}=await Rt(i,{method:"POST",body:s,headers:a});if(c)throw c;return we(d)}import{decodeJwt as vt,importJWK as Et,jwtVerify as _t}from"jose";import{betterFetch as Tt}from"@better-fetch/fetch";import{APIError as xt}from"better-call";import"zod";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})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let i=vt(r),{kid:n,alg:s}=i.header,a=await Pt(n),{payload:d}=await _t(r,a,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(c=>{d[c]!==void 0&&(d[c]=!!d[c])}),o&&d.nonce!==o?!1:!!d},async getUserInfo(r){if(!r.idToken)return null;let o=Ut(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true",image:o.picture},data:o}:null}}},Pt=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await Tt(`${t}${r}`);if(!o?.keys)throw new xt("BAD_REQUEST",{message:"Keys not found"});let i=o.keys.find(n=>n.kid===e);if(!i)throw new Error(`JWK with kid ${e} not found`);return await Et(i,i.alg)};import{betterFetch as Ot}from"@better-fetch/fetch";var ye=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})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await Ot("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}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 St}from"@better-fetch/fetch";var Ae=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await St("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 ke}from"@better-fetch/fetch";var Re=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>b({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await ke("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 ke("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(d=>d.primary)??s[0])?.email,n=s.find(d=>d.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 It}from"oslo/jwt";import{betterFetch as Lt}from"@better-fetch/fetch";var Ue=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw m.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})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:i}=await Lt(o);return i?i.aud===e.clientId&&i.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(!t.idToken)return null;let r=It(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 Ct}from"@better-fetch/fetch";import{parseJWT as Bt}from"oslo/jwt";var ve=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),A({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return b({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(!i.idToken)return null;let n=Bt(i.idToken)?.payload,s=e.profilePhotoSize||48;return await Ct(`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 c=await a.response.clone().arrayBuffer(),l=Buffer.from(c).toString("base64");n.picture=`data:image/jpeg;base64, ${l}`}catch(d){m.error(d)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};import{betterFetch as Dt}from"@better-fetch/fetch";var Ee=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await Dt("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 Vt}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),A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return m.error("No idToken found in token"),null;let o=Vt(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as zt}from"@better-fetch/fetch";var Te=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),A({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await zt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});import{betterFetch as jt}from"@better-fetch/fetch";var xe=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await b({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await jt("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 $t}from"@better-fetch/fetch";var Pe=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await b({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await $t("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 qt}from"@better-fetch/fetch";var re=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Nt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:re(`${t}/oauth/authorize`),tokenEndpoint:re(`${t}/oauth/token`),userinfoEndpoint:re(`${t}/api/v4/user`)}},Oe=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Nt(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:d,redirectURI:c})=>{let l=a||["read_user"];return e.scope&&l.push(...e.scope),await A({id:i,options:e,authorizationEndpoint:t,scopes:l,state:s,redirectURI:c,codeVerifier:d})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:d})=>b({code:s,redirectURI:e.redirectURI||a,options:e,codeVerifier:d,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:d}=await qt(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return d||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 Ft={apple:be,discord:ye,facebook:Ae,github:Re,microsoft:ve,google:Ue,spotify:Ee,twitch:_e,twitter:Te,dropbox:xe,linkedin:Pe,gitlab:Oe},J=Object.keys(Ft);import{TimeSpan as Mt}from"oslo";import{createJWT as Ht,validateJWT as Gt}from"oslo/jwt";import{z as P}from"zod";import{APIError as $}from"better-call";import{APIError as j}from"better-call";import{z as F}from"zod";function Se(e){try{return JSON.parse(e)}catch{return null}}var oe=()=>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=e.getCookie(e.context.authCookies.sessionData.name),o=r?Se(Buffer.from(r,"base64").toString()):null;if(o&&!await Z.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return B(e),e.json(null,{status:401});let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let l=o.session;if(o.expiresAt<Date.now()||l.session.expiresAt<new Date){let g=e.context.authCookies.sessionData.name;e.setCookie(g,"",{maxAge:0})}else return e.json(l)}let n=await e.context.internalAdapter.findSession(t);if(!n||n.session.expiresAt<new Date)return B(e),n&&await e.context.internalAdapter.deleteSession(n.session.id),e.json(null,{status:401});if(i)return e.json(n);let s=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-s*1e3+a*1e3<=Date.now()){let l=await e.context.internalAdapter.updateSession(n.session.id,{expiresAt:C(e.context.sessionConfig.expiresIn,"sec")});if(!l)return B(e),e.json(null,{status:401});let f=(l.expiresAt.valueOf()-Date.now())/1e3;return await x(e,{session:l,user:n.user},!1,{maxAge:f}),e.json({session:l,user:n.user})}return e.json(n)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),ie=async e=>await oe()({...e,_flag:"json",headers:e.headers}),T=H(async e=>{let t=await ie(e);if(!t?.session)throw new j("UNAUTHORIZED");return{session:t}}),Ie=()=>p("/list-sessions",{method:"GET",use:[T],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)}),Le=p("/revoke-session",{method:"POST",body:F.object({id:F.string()}),use:[T],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new j("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new j("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new j("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Ce=p("/revoke-sessions",{method:"POST",use:[T],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new j("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Be=p("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[T]},async e=>{let t=e.context.session;if(!t.user)throw new j("UNAUTHORIZED");let i=(await e.context.internalAdapter.listSessions(t.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.id!==e.context.session.session.id);return await Promise.all(i.map(n=>e.context.internalAdapter.deleteSession(n.id))),e.json({status:!0})});async function S(e,t,r){return await Ht("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Mt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var De=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 $("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 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})}),Ve=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 Gt("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new $("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 $("BAD_REQUEST",{message:"User not found"});if(i.updateTo){let s=await ie(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new $("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==i.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new $("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})});async function W(e,{userInfo:t,account:r,callbackURL:o}){let i=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw m.error(`Better auth was unable to query your database.
|
|
4
|
-
Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=i?.user;if(i){let a=i.accounts.find(d=>d.providerId===r.providerId);if(a)await e.context.internalAdapter.updateAccount(a.id,{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt});else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return ce&&m.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),id:e.context.uuid(),userId:i.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt})}catch(l){return m.error("Unable to link account",l),{error:"unable to link account",data:null}}}}else try{let a=t.emailVerified||!1;if(n=await e.context.internalAdapter.createOAuthUser({...t,id:e.context.uuid(),emailVerified:a,email:t.email.toLowerCase()},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,providerId:r.providerId,accountId:t.id.toString()}).then(d=>d?.user),!a&&n&&e.context.options.emailVerification?.sendOnSignUp){let d=await S(e.context.secret,n.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(n,c,d)}}catch(a){return m.error("Unable to create user",a),{error:"unable to create user",data:null}}if(!n)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(n.id,e.request);return s?{data:{session:s,user:n},error:null}:{error:"unable to create session",data:null}}var ze=p("/sign-in/social",{method:"POST",query:R.object({currentURL:R.string().optional()}).optional(),body:R.object({callbackURL:R.string().optional(),provider:R.enum(J),idToken:R.optional(R.object({token:R.string(),nonce:R.string().optional(),accessToken:R.string().optional(),refreshToken:R.string().optional(),expiresAt:R.number().optional()}))})},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 v("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new v("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:n,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(n,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new v("UNAUTHORIZED",{message:"Invalid id token"});let d=await t.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!d||!d?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new v("UNAUTHORIZED",{message:"Failed to get user info"});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new v("UNAUTHORIZED",{message:"User email not found"});let c=await W(e,{userInfo:{email:d.user.email,id:d.user.id,name:d.user.name||"",image:d.user.image,emailVerified:d.user.emailVerified||!1},account:{providerId:t.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new v("UNAUTHORIZED",{message:c.error});return await x(e,c.data),e.json({session:c.data.session,user:c.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:r,state:o}=await Q(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!0})}),je=p("/sign-in/email",{method:"POST",body:R.object({email:R.string(),password:R.string(),callbackURL:R.string().optional(),dontRememberMe:R.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 v("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!R.string().email().safeParse(t).success)throw new v("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new v("UNAUTHORIZED",{message:"Invalid email or password"});let n=i.accounts.find(c=>c.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new v("UNAUTHORIZED",{message:"Invalid email or password"});let s=n?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new v("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new v("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw m.error("Email verification is required but no email verification handler is provided"),new v("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await S(e.context.secret,i.user.email),l=`${e.context.options.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,l,c),e.context.logger.error("Email not verified",{email:t}),new v("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new v("UNAUTHORIZED",{message:"Failed to create session"});return await x(e,{session:d,user:i.user},e.body.dontRememberMe),e.json({user:i.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as Y}from"zod";import{z as h}from"zod";var fn=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()}),gn=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)}),hn=h.object({id:h.string(),userId:h.string(),expiresAt:h.date(),ipAddress:h.string().optional(),userAgent:h.string().optional()}),wn=h.object({id:h.string(),value:h.string(),expiresAt:h.date(),identifier:h.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 Zt(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 K(e,t,r){let o=Qt(e,"user");return Zt(t||{},{fields:o,action:r})}var $e=p("/callback/:id",{method:"GET",query:Y.object({state:Y.string(),code:Y.string().optional(),error:Y.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(y=>y.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 me(e),s;try{s=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(y){throw e.context.logger.error(y),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(s).then(y=>y?.user),c={id:ae(),...a};function l(y){let w=n||o||`${e.context.baseURL}/error`;throw w.includes("?")?w=`${w}&error=${y}`:w=`${w}?error=${y}`,e.redirect(w)}if(!a)return m.error("Unable to get user info"),l("unable_to_get_user_info");if(!c.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),l("email_not_found");if(!o)throw m.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:a.id}))return l("unable_to_link_account");let w;try{w=new URL(o).toString()}catch{w=o}throw e.redirect(w)}let f=await W(e,{userInfo:{email:c.email,id:c.id,name:c.name||"",image:c.image,emailVerified:c.emailVerified||!1},account:{providerId:t.id,accountId:a.id,accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt},callbackURL:o});if(f.error)return l(f.error.split(" ").join("_"));let{session:g,user:u}=f.data;await x(e,{session:g,user:u});let k;try{k=new URL(o).toString()}catch{k=o}throw e.redirect(k)});import"zod";import{APIError as Jt}from"better-call";var qe=p("/sign-out",{method:"POST",requireHeaders:!0},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Jt("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 X}from"better-call";function Ne(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 Wt(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 Fe=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 X("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})}),Me=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(Ne(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Ne(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Wt(e.context,r,{token:t}))}),He=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 X("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 X("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(l=>l.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 X("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 Ge=()=>p("/update-user",{method:"POST",body:U.record(U.string(),U.any()),use:[T]},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=K(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})}),Qe=p("/change-password",{method:"POST",body:U.object({newPassword:U.string(),currentPassword:U.string(),revokeOtherSessions:U.boolean().optional()}),use:[T]},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 d=(await e.context.internalAdapter.findAccounts(i.user.id)).find(f=>f.providerId==="credential"&&f.password);if(!d||!d.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(d.password,r))throw new E("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),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 E("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await x(e,{session:f,user:i.user})}return e.json(i.user)}),Ze=p("/set-password",{method:"POST",body:U.object({newPassword:U.string()}),metadata:{SERVER_ONLY:!0},use:[T]},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(d=>d.providerId==="credential"&&d.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"})}),Je=p("/delete-user",{method:"POST",body:U.object({password:U.string()}),use:[T]},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)}),We=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:[T]},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 Kt=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
|
+
Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=i?.user;if(i){let a=i.accounts.find(d=>d.providerId===r.providerId);if(a)await e.context.internalAdapter.updateAccount(a.id,{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt});else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return ce&&m.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),id:e.context.uuid(),userId:i.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt})}catch(l){return m.error("Unable to link account",l),{error:"unable to link account",data:null}}}}else try{let a=t.emailVerified||!1;if(n=await e.context.internalAdapter.createOAuthUser({...t,id:e.context.uuid(),emailVerified:a,email:t.email.toLowerCase()},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,providerId:r.providerId,accountId:t.id.toString()}).then(d=>d?.user),!a&&n&&e.context.options.emailVerification?.sendOnSignUp){let d=await S(e.context.secret,n.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(n,c,d)}}catch(a){return m.error("Unable to create user",a),{error:"unable to create user",data:null}}if(!n)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(n.id,e.request);return s?{data:{session:s,user:n},error:null}:{error:"unable to create session",data:null}}var ze=p("/sign-in/social",{method:"POST",query:R.object({currentURL:R.string().optional()}).optional(),body:R.object({callbackURL:R.string().optional(),provider:R.enum(J),idToken:R.optional(R.object({token:R.string(),nonce:R.string().optional(),accessToken:R.string().optional(),refreshToken:R.string().optional(),expiresAt:R.number().optional()}))})},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 v("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new v("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:n,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(n,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new v("UNAUTHORIZED",{message:"Invalid id token"});let d=await t.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!d||!d?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new v("UNAUTHORIZED",{message:"Failed to get user info"});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new v("UNAUTHORIZED",{message:"User email not found"});let c=await W(e,{userInfo:{email:d.user.email,id:d.user.id,name:d.user.name||"",image:d.user.image,emailVerified:d.user.emailVerified||!1},account:{providerId:t.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new v("UNAUTHORIZED",{message:c.error});return await x(e,c.data),e.json({session:c.data.session,user:c.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:r,state:o}=await Q(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!0})}),je=p("/sign-in/email",{method:"POST",body:R.object({email:R.string(),password:R.string(),callbackURL:R.string().optional(),rememberMe:R.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 v("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!R.string().email().safeParse(t).success)throw new v("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new v("UNAUTHORIZED",{message:"Invalid email or password"});let n=i.accounts.find(c=>c.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new v("UNAUTHORIZED",{message:"Invalid email or password"});let s=n?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new v("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new v("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw m.error("Email verification is required but no email verification handler is provided"),new v("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await S(e.context.secret,i.user.email),l=`${e.context.options.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,l,c),e.context.logger.error("Email not verified",{email:t}),new v("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.rememberMe===!1);if(!d)throw e.context.logger.error("Failed to create session"),new v("UNAUTHORIZED",{message:"Failed to create session"});return await x(e,{session:d,user:i.user},e.body.rememberMe===!1),e.json({user:i.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as Y}from"zod";import{z as h}from"zod";var fn=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()}),gn=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)}),hn=h.object({id:h.string(),userId:h.string(),expiresAt:h.date(),ipAddress:h.string().optional(),userAgent:h.string().optional()}),wn=h.object({id:h.string(),value:h.string(),expiresAt:h.date(),identifier:h.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 Zt(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 K(e,t,r){let o=Qt(e,"user");return Zt(t||{},{fields:o,action:r})}var $e=p("/callback/:id",{method:"GET",query:Y.object({state:Y.string(),code:Y.string().optional(),error:Y.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(y=>y.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 me(e),s;try{s=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(y){throw e.context.logger.error(y),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(s).then(y=>y?.user),c={id:ae(),...a};function l(y){let w=n||o||`${e.context.baseURL}/error`;throw w.includes("?")?w=`${w}&error=${y}`:w=`${w}?error=${y}`,e.redirect(w)}if(!a)return m.error("Unable to get user info"),l("unable_to_get_user_info");if(!c.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),l("email_not_found");if(!o)throw m.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:a.id}))return l("unable_to_link_account");let w;try{w=new URL(o).toString()}catch{w=o}throw e.redirect(w)}let f=await W(e,{userInfo:{email:c.email,id:c.id,name:c.name||"",image:c.image,emailVerified:c.emailVerified||!1},account:{providerId:t.id,accountId:a.id,accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt},callbackURL:o});if(f.error)return l(f.error.split(" ").join("_"));let{session:g,user:u}=f.data;await x(e,{session:g,user:u});let k;try{k=new URL(o).toString()}catch{k=o}throw e.redirect(k)});import"zod";import{APIError as Jt}from"better-call";var qe=p("/sign-out",{method:"POST",requireHeaders:!0},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Jt("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 X}from"better-call";function Ne(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 Wt(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 Fe=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 X("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})}),Me=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(Ne(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Ne(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Wt(e.context,r,{token:t}))}),He=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 X("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 X("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(l=>l.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 X("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 Ge=()=>p("/update-user",{method:"POST",body:U.record(U.string(),U.any()),use:[T]},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=K(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})}),Qe=p("/change-password",{method:"POST",body:U.object({newPassword:U.string(),currentPassword:U.string(),revokeOtherSessions:U.boolean().optional()}),use:[T]},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 d=(await e.context.internalAdapter.findAccounts(i.user.id)).find(f=>f.providerId==="credential"&&f.password);if(!d||!d.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(d.password,r))throw new E("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),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 E("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await x(e,{session:f,user:i.user})}return e.json(i.user)}),Ze=p("/set-password",{method:"POST",body:U.object({newPassword:U.string()}),metadata:{SERVER_ONLY:!0},use:[T]},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(d=>d.providerId==="credential"&&d.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"})}),Je=p("/delete-user",{method:"POST",body:U.object({password:U.string()}),use:[T]},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)}),We=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:[T]},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 Kt=(e="Unknown")=>`<!DOCTYPE html>
|
|
5
5
|
<html lang="en">
|
|
6
6
|
<head>
|
|
7
7
|
<meta charset="UTF-8">
|