better-auth 0.8.2 → 0.8.3-beta.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 +5 -5
- package/dist/api.d.cts +1 -1
- package/dist/api.d.ts +1 -1
- package/dist/api.js +5 -5
- package/dist/{auth-Ch-bn7fQ.d.cts → auth-DBMdxK-M.d.cts} +93 -59
- package/dist/{auth-GUhdyLXq.d.ts → auth-ElLq7vmm.d.ts} +93 -59
- package/dist/client/plugins.d.cts +3 -3
- package/dist/client/plugins.d.ts +3 -3
- 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.d.cts +2 -2
- package/dist/db.d.ts +2 -2
- package/dist/{index-C-voMSyS.d.ts → index-DBaFH8g-.d.ts} +22 -9
- package/dist/{index-BkiNLLw-.d.cts → index-DdU1-vYD.d.cts} +22 -9
- package/dist/index.cjs +3 -3
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +3 -3
- package/dist/next-js.cjs +1 -84
- package/dist/next-js.d.cts +1 -1
- package/dist/next-js.d.ts +1 -1
- package/dist/next-js.js +1 -84
- 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 +5 -5
- package/dist/plugins.d.cts +3 -3
- package/dist/plugins.d.ts +3 -3
- package/dist/plugins.js +5 -5
- 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-BixlofB9.d.cts → state-CIhWbtNG.d.cts} +1 -1
- package/dist/{state-CqaXiikA.d.ts → state-El9PW_xP.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-DBMdxK-M.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-ElLq7vmm.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
|
-
"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:()=>
|
|
2
|
-
`)}}),m=Mt();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"),
|
|
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 E=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 T(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 H=require("jose"),rt=require("@better-fetch/fetch"),ot=require("better-call"),co=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,H.decodeProtectedHeader)(r),{kid:n,alg:s}=i;if(!n||!s)return!1;let a=await Jt(n),{payload:d}=await(0,H.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,H.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 _o=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 xt=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`)}},_t=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,xt.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:_t},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 M=require("zod");function Tt(e){try{return JSON.parse(e)}catch{return null}}var oe=()=>p("/get-session",{method:"GET",query:M.z.optional(M.z.object({disableCookieCache:M.z.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?Tt(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 T(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}),_=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:[_],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:M.z.object({id:M.z.string()}),use:[_],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:[_],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:[_]},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 O(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 O(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 O(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 E.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 E.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 E.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 E.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 E.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 E.APIError("UNAUTHORIZED",{message:c.error});return await T(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 E.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 E.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 E.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 E.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=n?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new E.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new E.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 E.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await O(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 E.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 E.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await T(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"),Si=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()}),Li=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)}),Ci=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()}),Bi=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(w=>w.id===e.params.id);if(!t)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:r,callbackURL:o,link:i,errorURL:n}=await Ge(e),s;try{s=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(w){throw e.context.logger.error(w),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(s).then(w=>w?.user),c={id:qe(),...a};function l(w){let y=n||o||`${e.context.baseURL}/error`;throw y.includes("?")?y=`${y}&error=${w}`:y=`${y}?error=${w}`,e.redirect(y)}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 y;try{y=new URL(o).toString()}catch{y=o}throw e.redirect(y)}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 T(e,{session:g,user:u});let R;try{R=new URL(o).toString()}catch{R=o}throw e.redirect(R)});var Qi=require("zod");var It=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 It.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),B(e),e.json({success:!0})});var I=require("zod");var W=require("better-call");function Ot(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 xe=p("/forget-password",{method:"POST",body:I.z.object({email:I.z.string().email(),redirectTo:I.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})}),_e=p("/reset-password/:token",{method:"GET",query:I.z.object({callbackURL:I.z.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(Ot(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Ot(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(er(e.context,r,{token:t}))}),Te=p("/reset-password",{query:I.z.optional(I.z.object({token:I.z.string().optional(),currentURL:I.z.string().optional()})),method:"POST",body:I.z.object({newPassword:I.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 v=require("zod");var x=require("better-call");var Pe=()=>p("/update-user",{method:"POST",body:v.z.record(v.z.string(),v.z.any()),use:[_]},async e=>{let t=e.body;if(t.email)throw new x.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 T(e,{session:n.session,user:a}),e.json({user:a})}),Ie=p("/change-password",{method:"POST",body:v.z.object({newPassword:v.z.string(),currentPassword:v.z.string(),revokeOtherSessions:v.z.boolean().optional()}),use:[_]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new x.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 x.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 x.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 x.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 x.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await T(e,{session:f,user:i.user})}return e.json(i.user)}),Oe=p("/set-password",{method:"POST",body:v.z.object({newPassword:v.z.string()}),metadata:{SERVER_ONLY:!0},use:[_]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new x.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 x.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 x.APIError("BAD_REQUEST",{message:"user already has a password"})}),Se=p("/delete-user",{method:"POST",body:v.z.object({password:v.z.string()}),use:[_]},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 x.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(i.password,t))throw new x.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:v.z.object({currentURL:v.z.string().optional()}).optional(),body:v.z.object({newEmail:v.z.string().email(),callbackURL:v.z.string().optional()}),use:[_]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new x.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 x.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 x.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 x.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await O(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>
|
|
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:()=>xe,forgetPasswordCallback:()=>_e,getEndpoints:()=>Bt,getSession:()=>oe,getSessionFromCtx:()=>ie,linkSocialAccount:()=>je,listSessions:()=>he,listUserAccounts:()=>ze,ok:()=>Be,optionsMiddleware:()=>ue,originCheckMiddleware:()=>me,resetPassword:()=>Te,revokeOtherSessions:()=>ye,revokeSession:()=>we,revokeSessions:()=>be,router:()=>dr,sendVerificationEmail:()=>Ae,sessionMiddleware:()=>_,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"),ue=(0,D.createMiddleware)(async()=>({})),Q=(0,D.createMiddlewareCreator)({use:[ue,(0,D.createMiddleware)(async()=>({}))]}),p=(0,D.createEndpointCreator)({use:[ue]});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 Ht(e){return e?e!=="false":!1}var le=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Fe=le==="dev"||le==="development",He=le==="test"||Ht(Ne.TEST);var V=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function Me(e){try{return new URL(e).origin}catch{return null}}async function X(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Me(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"}}),Mt=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
|
+
`)}}),m=Mt();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"),u=(g,l)=>l.includes("*")?new RegExp("^"+l.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(g):g.startsWith(l),f=(g,l)=>{if(!g)return;if(!d.some(w=>u(g,w)||g?.startsWith("/")&&l!=="origin"&&!g.includes(":")))throw m.error(`Invalid ${l}: ${g}`),m.info(`If it's a valid URL, please add ${g} to trustedOrigins in your auth config
|
|
3
|
+
`,`Current list of trustedOrigins: ${d}`),new Ze.APIError("FORBIDDEN",{message:`Invalid ${l}`})};c&&!e.context.options.advanced?.disableCSRFCheck&&f(i,"origin"),n&&f(n,"callbackURL"),s&&f(s,"redirectURL"),a&&f(a,"currentURL")});var E=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 T(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((u,f)=>(u[f]=null,u),{});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 H=require("jose"),rt=require("@better-fetch/fetch"),ot=require("better-call"),co=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,H.decodeProtectedHeader)(r),{kid:n,alg:s}=i;if(!n||!s)return!1;let a=await Jt(n),{payload:d}=await(0,H.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,H.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 ut=require("oslo/jwt");var lt=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,lt.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,ut.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(),u=Buffer.from(c).toString("base64");n.picture=`data:image/jpeg;base64, ${u}`}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 _o=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 xt=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`)}},_t=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 u=a||["read_user"];return e.scope&&u.push(...e.scope),await A({id:i,options:e,authorizationEndpoint:t,scopes:u,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,xt.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:_t},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 M=require("zod");function Tt(e){try{return JSON.parse(e)}catch{return null}}var oe=()=>p("/get-session",{method:"GET",query:M.z.optional(M.z.object({disableCookieCache:M.z.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?Tt(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 u=o.session;if(o.expiresAt<Date.now()||u.session.expiresAt<new Date){let g=e.context.authCookies.sessionData.name;e.setCookie(g,"",{maxAge:0})}else return e.json(u)}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 u=await e.context.internalAdapter.updateSession(n.session.id,{expiresAt:C(e.context.sessionConfig.expiresIn,"sec")});if(!u)return B(e),e.json(null,{status:401});let f=(u.expiresAt.valueOf()-Date.now())/1e3;return await T(e,{session:u,user:n.user},!1,{maxAge:f}),e.json({session:u,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}),_=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:[_],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:M.z.object({id:M.z.string()}),use:[_],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:[_],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:[_]},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({user:r.user,url:i,token:o},e.request),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?.({user:a,url:`${e.context.baseURL}/verify-email?token=${t}`,token:t},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.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(u){return m.error("Unable to link account",u),{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?.({user:n,url:c,token:d},e.request)}}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 E.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 E.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 E.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 E.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 E.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 E.APIError("UNAUTHORIZED",{message:c.error});return await T(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 E.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 E.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 E.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 E.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=n?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new E.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new E.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 E.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await S(e.context.secret,i.user.email),u=`${e.context.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:i.user,url:u,token:c},e.request),e.context.logger.error("Email not verified",{email:t}),new E.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 E.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await T(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"),Ii=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()}),Li=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)}),Ci=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()}),Bi=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","POST"],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(w=>w.id===e.params.id);if(!t)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:r,callbackURL:o,link:i,errorURL:n}=await Ge(e),s;try{s=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(w){throw e.context.logger.error(w),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(s).then(w=>w?.user),c={id:qe(),...a};function u(w){let y=n||o||`${e.context.baseURL}/error`;throw y.includes("?")?y=`${y}&error=${w}`:y=`${y}?error=${w}`,e.redirect(y)}if(!a)return m.error("Unable to get user info"),u("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."),u("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 u("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:i.userId,providerId:t.id,accountId:a.id}))return u("unable_to_link_account");let y;try{y=new URL(o).toString()}catch{y=o}throw e.redirect(y)}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 u(f.error.split(" ").join("_"));let{session:g,user:l}=f.data;await T(e,{session:g,user:l});let R;try{R=new URL(o).toString()}catch{R=o}throw e.redirect(R)});var Qi=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 xe=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({user:o.user,url:a},e.request),e.json({status:!0})}),_e=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}))}),Te=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(u=>u.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 v=require("zod");var x=require("better-call");var Pe=()=>p("/update-user",{method:"POST",body:v.z.record(v.z.string(),v.z.any()),use:[_]},async e=>{let t=e.body;if(t.email)throw new x.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 T(e,{session:n.session,user:a}),e.json({user:a})}),Oe=p("/change-password",{method:"POST",body:v.z.object({newPassword:v.z.string(),currentPassword:v.z.string(),revokeOtherSessions:v.z.boolean().optional()}),use:[_]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new x.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 x.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 x.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 x.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 x.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await T(e,{session:f,user:i.user})}return e.json(i.user)}),Se=p("/set-password",{method:"POST",body:v.z.object({newPassword:v.z.string()}),metadata:{SERVER_ONLY:!0},use:[_]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new x.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 x.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 x.APIError("BAD_REQUEST",{message:"user already has a password"})}),Ie=p("/delete-user",{method:"POST",body:v.z.object({password:v.z.string()}),use:[_]},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 x.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(i.password,t))throw new x.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:v.z.object({currentURL:v.z.string().optional()}).optional(),body:v.z.object({newEmail:v.z.string().email(),callbackURL:v.z.string().optional()}),use:[_]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new x.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 x.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 x.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 x.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({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),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">
|
|
@@ -81,4 +81,4 @@ Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
|
|
|
81
81
|
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
82
82
|
</div>
|
|
83
83
|
</body>
|
|
84
|
-
</html>`,Ce=p("/error",{method:"GET",metadata:F},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(tr(t),{headers:{"Content-Type":"text/html"}})});var Be=p("/ok",{method:"GET",metadata:F},async e=>e.json({ok:!0}));var q=require("zod");var
|
|
84
|
+
</html>`,Ce=p("/error",{method:"GET",metadata:F},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(tr(t),{headers:{"Content-Type":"text/html"}})});var Be=p("/ok",{method:"GET",metadata:F},async e=>e.json({ok:!0}));var q=require("zod");var I=require("better-call");var De=()=>p("/sign-up/email",{method:"POST",query:q.z.object({currentURL:q.z.string().optional()}).optional(),body:q.z.record(q.z.string(),q.z.any())},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new I.APIError("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:i,image:n,callbackURL:s,...a}=t;if(!q.z.string().email().safeParse(o).success)throw new I.APIError("BAD_REQUEST",{message:"Invalid email"});let c=e.context.password.config.minPasswordLength;if(i.length<c)throw e.context.logger.error("Password is too short"),new I.APIError("BAD_REQUEST",{message:"Password is too short"});let u=e.context.password.config.maxPasswordLength;if(i.length>u)throw e.context.logger.error("Password is too long"),new I.APIError("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new I.APIError("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let g=ae(e.context.options,a),l;try{if(l=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:n,...g,emailVerified:!1}),!l)throw new I.APIError("BAD_REQUEST",{message:"Failed to create user"})}catch(y){throw m.error("Failed to create user",y),new I.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:y})}if(!l)throw new I.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let R=await e.context.password.hash(i);if(await e.context.internalAdapter.linkAccount({userId:l.id,providerId:"credential",accountId:l.id,password:R,expiresAt:C(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let y=await S(e.context.secret,l.email),U=`${e.context.baseURL}/verify-email?token=${y}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:l,url:U,token:y},e.request)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:l,session:null},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:l,session:null}});let w=await e.context.internalAdapter.createSession(l.id,e.request);if(!w)throw new I.APIError("BAD_REQUEST",{message:"Failed to create session"});return await T(e,{session:w,user:l}),e.json({user:l,session:w})});var G=require("zod");var Ve=require("better-call");var ze=p("/list-accounts",{method:"GET",use:[_]},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(o=>({id:o.id,provider:o.providerId})))}),je=p("/link-social",{method:"POST",requireHeaders:!0,query:G.z.object({currentURL:G.z.string().optional()}).optional(),body:G.z.object({callbackURL:G.z.string().optional(),provider:G.z.enum(re)}),use:[_]},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(a=>a.providerId===e.body.provider))throw new Ve.APIError("BAD_REQUEST",{message:"Social Account is already linked."});let i=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Ve.APIError("NOT_FOUND",{message:"Provider not found"});let n=await X(e,{userId:t.user.id,email:t.user.email}),s=await i.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:s.toString(),redirect:!0})});function It(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let r="127.0.0.1";if(He)return r;let i=t.advanced?.ipAddress?.ipAddressHeaders||["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],n=e instanceof Request?e.headers:e;for(let s of i){let a=n.get(s);if(typeof a=="string"){let d=a.split(",")[0].trim();if(d)return d}}return null}function rr(e,t,r){let o=Date.now(),i=t*1e3;return o-r.lastRequest<i&&r.count>=e}function or(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":e.toString()}})}function ir(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function nr(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async i=>await o.findOne({model:r,where:[{field:"key",value:i}]}),set:async(i,n,s)=>{try{s?await o.update({model:t??"rateLimit",where:[{field:"key",value:i}],update:{count:n.count,lastRequest:n.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:i,count:n.count,lastRequest:n.lastRequest}})}catch(a){m.error("Error setting rate limit",a)}}}}var Lt=new Map;function sr(e){return e.rateLimit.storage==="secondary-storage"?{get:async r=>{let o=await e.options.secondaryStorage?.get(r);return o?JSON.parse(o):void 0},set:async(r,o)=>{await e.options.secondaryStorage?.set?.(r,JSON.stringify(o))}}:e.rateLimit.storage==="memory"?{async get(r){return Lt.get(r)},async set(r,o,i){Lt.set(r,o)}}:nr(e,e.rateLimit.tableName)}async function Ct(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),i=t.rateLimit.window,n=t.rateLimit.max,s=It(e,t.options)+o,d=ar().find(g=>g.pathMatcher(o));d&&(i=d.window,n=d.max);for(let g of t.options.plugins||[])if(g.rateLimit){let l=g.rateLimit.find(R=>R.pathMatcher(o));if(l){i=l.window,n=l.max;break}}if(t.rateLimit.customRules){let g=t.rateLimit.customRules[o];g&&(i=g.window,n=g.max)}let c=sr(t),u=await c.get(s),f=Date.now();if(!u)await c.set(s,{key:s,count:1,lastRequest:f});else{let g=f-u.lastRequest;if(rr(n,i,u)){let l=ir(u.lastRequest,i);return or(l)}else g>i*1e3?await c.set(s,{...u,count:1,lastRequest:f}):await c.set(s,{...u,count:u.count+1,lastRequest:f})}}function ar(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")||t.startsWith("/change-password")||t.startsWith("/change-email")},window:10,max:3}]}var Dt=require("better-call");function Bt(e,t){let r=t.plugins?.reduce((a,d)=>({...a,...d.endpoints}),{}),o=t.plugins?.map(a=>a.middlewares?.map(d=>{let c=async u=>d.middleware({...u,context:{...e,...u.context}});return c.path=d.path,c.options=d.middleware.options,c.headers=d.middleware.headers,{path:d.path,middleware:c}})).filter(a=>a!==void 0).flat()||[],n={...{signInSocial:Re,callbackOAuth:ve,getSession:oe(),signOut:Ee,signUpEmail:De(),signInEmail:Ue,forgetPassword:xe,resetPassword:Te,verifyEmail:ke,sendVerificationEmail:Ae,changeEmail:Le,changePassword:Oe,setPassword:Se,updateUser:Pe(),deleteUser:Ie,forgetPasswordCallback:_e,listSessions:he(),revokeSession:we,revokeSessions:be,revokeOtherSessions:ye,linkSocialAccount:je,listUserAccounts:ze},...r,ok:Be,error:Ce},s={};for(let[a,d]of Object.entries(n))s[a]=async(c={})=>{let u=await e;for(let l of t.plugins||[])if(l.hooks?.before)for(let R of l.hooks.before){let w={...d,...c,context:{...u,...c?.context}};if(R.matcher(w)){let U=await R.handler(w);U&&"context"in U&&(c={...U,...c})}}let f;try{f=await d({...c,context:{...u,...c.context}})}catch(l){if(l instanceof N.APIError){let R=t.plugins?.map(U=>{if(U.hooks?.after)return U.hooks.after}).filter(U=>U!==void 0).flat();if(!R?.length)throw l;let w=new Response(JSON.stringify(l.body),{status:N.statusCode[l.status],headers:l.headers}),y;for(let U of R||[])if(U.matcher(c)){u.returned=w;let Vt={...d,...c,context:u},de=await U.handler(Vt);de&&"response"in de&&(y=de.response)}if(y instanceof Response)return y;throw l}throw l}let g=f;for(let l of t.plugins||[])if(l.hooks?.after)for(let R of l.hooks.after){let w={...c,context:{...u,...c.context,endpoint:d,returned:g}};if(R.matcher(w)){let U=await R.handler(w);U&&"response"in U&&(g=U.response)}}return g},s[a].path=d.path,s[a].method=d.method,s[a].options=d.options,s[a].headers=d.headers;return{api:s,middlewares:o}}var dr=(e,t)=>{let{api:r,middlewares:o}=Bt(e,t),i=new URL(e.baseURL).pathname;return(0,N.createRouter)(r,{extraContext:e,basePath:i,routerMiddleware:[{path:"/**",middleware:me},...o],async onRequest(n){for(let s of e.options.plugins||[])if(s.onRequest){let a=await s.onRequest(n,e);if(a&&"response"in a)return a.response}return Ct(n,e)},async onResponse(n){for(let s of e.options.plugins||[])if(s.onResponse){let a=await s.onResponse(n,e);if(a)return a.response}return n},onError(n){if(t.onAPIError?.throw)throw n;if(t.onAPIError?.onError){t.onAPIError.onError(n,e);return}let s=t.logger?.verboseLogging?m:void 0;t.logger?.disabled!==!0&&(n instanceof N.APIError?(n.status==="INTERNAL_SERVER_ERROR"&&m.error(n),s?.error(n.message)):m?.error(n))}})};0&&(module.exports={APIError,callbackOAuth,changeEmail,changePassword,createAuthEndpoint,createAuthMiddleware,createEmailVerificationToken,deleteUser,error,forgetPassword,forgetPasswordCallback,getEndpoints,getSession,getSessionFromCtx,linkSocialAccount,listSessions,listUserAccounts,ok,optionsMiddleware,originCheckMiddleware,resetPassword,revokeOtherSessions,revokeSession,revokeSessions,router,sendVerificationEmail,sessionMiddleware,setPassword,signInEmail,signInSocial,signOut,signUpEmail,updateUser,verifyEmail});
|
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-DBMdxK-M.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-ElLq7vmm.js';
|
|
2
2
|
import './helper-DPDj8Nix.js';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|