better-auth 0.4.12-beta.1 → 0.4.12-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/drizzle.d.ts +1 -1
- package/dist/adapters/kysely.d.ts +1 -1
- package/dist/adapters/mongodb.d.ts +1 -1
- package/dist/adapters/prisma.d.ts +1 -1
- package/dist/api.d.ts +1 -1
- package/dist/api.js +4 -4
- package/dist/{auth-Cx7ibOvY.d.ts → auth-BGQTSAwN.d.ts} +24 -24
- package/dist/client/plugins.d.ts +3 -3
- package/dist/client.d.ts +1 -1
- package/dist/cookies.d.ts +1 -1
- package/dist/db.d.ts +2 -2
- package/dist/{index-e73K5key.d.ts → index-DgJ3JDtV.d.ts} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +4 -4
- package/dist/node.d.ts +1 -1
- package/dist/plugins.d.ts +3 -3
- package/dist/plugins.js +5 -5
- package/dist/react.d.ts +1 -1
- package/dist/solid-start.d.ts +1 -1
- package/dist/solid.d.ts +1 -1
- package/dist/svelte-kit.d.ts +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/types.d.ts +2 -2
- 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-BGQTSAwN.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import '../schema-Dkt0LqYs.js';
|
|
5
5
|
import 'better-call';
|
package/dist/api.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { e as AuthEndpoint, f as AuthMiddleware, a0 as callbackOAuth, af as changePassword, d as createAuthEndpoint, c as createAuthMiddleware, ab as createEmailVerificationToken, am as csrfMiddleware, ah as deleteUser, aj as error, a8 as forgetPassword, a9 as forgetPasswordCallback, ai as getCSRFToken, Y as getEndpoints, a1 as getSession, a2 as getSessionFromCtx, a4 as listSessions, ak as ok, o as optionsMiddleware, aa as resetPassword, a5 as revokeSession, a6 as revokeSessions, Z as router, ac as sendVerificationEmail, a3 as sessionMiddleware, ag as setPassword, $ as signInEmail, _ as signInOAuth, a7 as signOut, al as signUpEmail, ae as updateUser, ad as verifyEmail } from './auth-
|
|
1
|
+
export { e as AuthEndpoint, f as AuthMiddleware, a0 as callbackOAuth, af as changePassword, d as createAuthEndpoint, c as createAuthMiddleware, ab as createEmailVerificationToken, am as csrfMiddleware, ah as deleteUser, aj as error, a8 as forgetPassword, a9 as forgetPasswordCallback, ai as getCSRFToken, Y as getEndpoints, a1 as getSession, a2 as getSessionFromCtx, a4 as listSessions, ak as ok, o as optionsMiddleware, aa as resetPassword, a5 as revokeSession, a6 as revokeSessions, Z as router, ac as sendVerificationEmail, a3 as sessionMiddleware, ag as setPassword, $ as signInEmail, _ as signInOAuth, a7 as signOut, al as signUpEmail, ae as updateUser, ad as verifyEmail } from './auth-BGQTSAwN.js';
|
|
2
2
|
import './helper-DPDj8Nix.js';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|
package/dist/api.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{APIError as Lt,createRouter as It}from"better-call";import{APIError as W}from"better-call";import{z as oe}from"zod";import{xchacha20poly1305 as
|
|
2
|
-
`)}}),w=ot();var U=D(async e=>{let t=e.body?.callbackURL||e.query?.callbackURL||e.query?.redirectTo||e.body?.redirectTo,r=e.headers?.get("referer"),o=e.query?.currentURL||r||e.context.baseURL,n=e.context.trustedOrigins;if(t?.includes("http")){let s=new URL(t).origin;if(!n.includes(s))throw w.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new de("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let s=new URL(o).origin;if(!n.includes(s))throw w.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new de("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as at}from"oslo/jwt";import{sha256 as nt}from"oslo/crypto";import{base64url as st}from"oslo/encoding";async function ue(e){let t=await nt(new TextEncoder().encode(e));return st.encode(new Uint8Array(t),{includePadding:!1})}function pe(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_at?new Date((Date.now()+e.expires_in)*1e3):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:n,scopes:s,claims:i,disablePkce:c,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",s.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||a),!c&&n){let u=await ue(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",u)}if(i){let u=i.reduce((y,f)=>(y[f]=null,y),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return d}import{betterFetch as it}from"@better-fetch/fetch";async function b({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let s=new URLSearchParams;s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:i,error:c}=await it(n,{method:"POST",body:s,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(c)throw c;return pe(i)}function K(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var le=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let s=e.scope||o||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${s.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=at(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};import{betterFetch as ct}from"@better-fetch/fetch";var me=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>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 ct("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});import{betterFetch as dt}from"@better-fetch/fetch";var fe=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["email","public_profile"];return await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>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 dt("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,emailVerified:r.email_verified},data:r}}});import{betterFetch as ge}from"@better-fetch/fetch";var he=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:s}){let i=e.scope||o||["user:email"];return A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:i,state:r,redirectURI:s,codeVerifier: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:n}=await ge("https://api.github.com/user",{auth:{type:"Bearer",token:r.accessToken}});if(n)return null;let s=!1;if(!o.email){let{data:i,error:c}=await ge("https://api.github.com/user/emails",{auth:{type:"Bearer",token:r.accessToken}});c||(o.email=(i.find(a=>a.primary)??i[0])?.email,s=i.find(a=>a.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:s},data:o}}}};import{parseJWT as ut}from"oslo/jwt";var we=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw w.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new I("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new I("codeVerifier is required for Google");let s=e.scope||r||["email","profile"];return A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:s,state:t,codeVerifier:o,redirectURI:n})},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 getUserInfo(t){if(!t.idToken)return null;let r=ut(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});import{betterFetch as pt}from"@better-fetch/fetch";import{parseJWT as lt}from"oslo/jwt";var ye=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let s=e.scope||n.scopes||["openid","profile","email","User.Read"];return A({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:s,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:s,redirectURI:i}){return b({code:n,codeVerifier:s,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let s=lt(n.idToken)?.payload,i=e.profilePhotoSize||48;return await pt(`https://graph.microsoft.com/v1.0/me/photos/${i}x${i}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let d=await c.response.clone().arrayBuffer(),u=Buffer.from(d).toString("base64");s.picture=`data:image/jpeg;base64, ${u}`}catch(a){w.error(a)}}}),{user:{id:s.sub,name:s.name,email:s.email,image:s.picture,emailVerified:!0},data:s}}}};import{betterFetch as mt}from"@better-fetch/fetch";var be=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let s=e.scope||r||["user-read-email"];return A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:s,state:t,codeVerifier:o,redirectURI:n})},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 mt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";var S={isAction:!1};var Ae=e=>q(e||21,N("a-z","0-9","A-Z"));import{parseJWT as ft}from"oslo/jwt";var Re=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username"]})},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 w.error("No idToken found in token"),null;let o=ft(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as gt}from"@better-fetch/fetch";var ke=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return A({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await gt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var ht={apple:le,discord:me,facebook:fe,github:he,microsoft:ye,google:we,spotify:be,twitch:Re,twitter:ke},Ue=Object.keys(ht);var Ee=p("/sign-in/social",{method:"POST",requireHeaders:!0,query:E.object({currentURL:E.string().optional()}).optional(),body:E.object({callbackURL:E.string().optional(),provider:E.enum(Ue)}),use:[U]},async e=>{let t=e.context.socialProviders.find(a=>a.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 O("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,n=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,s=await ce(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,s.hash,e.context.secret,r.state.options);let i=wt();await e.setSignedCookie(r.pkCodeVerifier.name,i,e.context.secret,r.pkCodeVerifier.options);let c=await t.createAuthorizationURL({state:s.raw,codeVerifier:i,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:c.toString(),state:s,codeVerifier:i,redirect:!0})}),xe=p("/sign-in/email",{method:"POST",body:E.object({email:E.string().email(),password:E.string(),callbackURL:E.string().optional(),dontRememberMe:E.boolean().default(!1).optional()}),use:[U]},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 O("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!E.string().email().safeParse(t).success)throw new O("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new O("UNAUTHORIZED",{message:"Invalid email or password"});let s=n.accounts.find(d=>d.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new O("UNAUTHORIZED",{message:"Invalid email or password"});let i=s?.password;if(!i)throw e.context.logger.error("Password not found",{email:t}),new O("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(i,r))throw e.context.logger.error("Invalid password"),new O("UNAUTHORIZED",{message:"Invalid email or password"});let a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!a)throw e.context.logger.error("Failed to create session"),new O("UNAUTHORIZED",{message:"Failed to create session"});return await P(e,a.id,e.body.dontRememberMe),e.json({user:n.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{APIError as bt}from"better-call";import{z as H}from"zod";import{z as l}from"zod";var An=l.object({id:l.string(),providerId:l.string(),accountId:l.string(),userId:l.string(),accessToken:l.string().nullable().optional(),refreshToken:l.string().nullable().optional(),idToken:l.string().nullable().optional(),expiresAt:l.date().nullable().optional(),password:l.string().optional().nullable()}),Pe=l.object({id:l.string(),email:l.string().transform(e=>e.toLowerCase()),emailVerified:l.boolean().default(!1),name:l.string(),image:l.string().optional(),createdAt:l.date().default(new Date),updatedAt:l.date().default(new Date)}),Rn=l.object({id:l.string(),userId:l.string(),expiresAt:l.date(),ipAddress:l.string().optional(),userAgent:l.string().optional()}),kn=l.object({id:l.string(),value:l.string(),expiresAt:l.date(),identifier:l.string()});function yt(e,t){let r=t.fields,o={};for(let n in r){if(n in e){if(r[n].input===!1){if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}continue}o[n]=e[n];continue}if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}}return o}function Te(e,t){let r={...e.user?.additionalFields};return yt(t||{},{fields:r})}var ve=p("/callback/:id",{method:"GET",query:H.object({state:H.string(),code:H.string().optional(),error:H.string().optional()}),metadata:S},async e=>{if(e.query.error||!e.query.code){let h=J(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${h}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(m=>m.id===e.params.id);if(!t)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let r=J(e.query.state);if(!r.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:n}}=r,s=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!s)throw w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await ae(e.query.state,s))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let c=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),a;try{a=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(m){throw e.context.logger.error(m),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let d=await t.getUserInfo(a).then(m=>m?.user),u=Ae(),y=Pe.safeParse({...d,id:u});if(!d||y.success===!1)throw w.error("Unable to get user info",y.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let f=await e.context.internalAdapter.findUserByEmail(d.email,{includeAccounts:!0}).catch(m=>{throw w.error(`Better auth was unable to query your database.
|
|
3
|
-
Error: `,m),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),g=f?.user.id;if(f){let m=f.accounts.find(k=>k.providerId===t.id),h=e.context.options.account?.accountLinking?.trustedProviders,R=h?h.includes(t.id):!0;if(!m&&(!d.emailVerified||!R)){let k;try{k=new URL(n||o),k.searchParams.set("error","account_not_linked")}catch{throw e.redirect(`${e.context.baseURL}/error?error=account_not_linked`)}throw e.redirect(k.toString())}if(!m)try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:d.id.toString(),id:`${t.id}:${d.id}`,userId:f.user.id,...K(a)})}catch(k){throw console.log(k),e.redirect(`${e.context.baseURL}/error?error=failed_linking_account`)}}else try{await e.context.internalAdapter.createOAuthUser(y.data,{...K(a),id:`${t.id}:${d.id}`,providerId:t.id,accountId:d.id.toString(),userId:u})}catch{let h=new URL(n||o);throw h.searchParams.set("error","unable_to_create_user"),e.setHeader("Location",h.toString()),e.redirect(h.toString())}if(!g&&!u)throw new bt("INTERNAL_SERVER_ERROR",{message:"Unable to create user"});try{let m=await e.context.internalAdapter.createSession(g||u,e.request);if(!m){let h=new URL(n||o);throw h.searchParams.set("error","unable_to_create_session"),e.redirect(h.toString())}try{await P(e,m.id)}catch(h){e.context.logger.error("Unable to set session cookie",h);let R=new URL(n||o);throw R.searchParams.set("error","unable_to_create_session"),e.redirect(R.toString())}}catch{let m=new URL(n||o||"");throw m.searchParams.set("error","unable_to_create_session"),e.redirect(m.toString())}throw e.redirect(o)});import{APIError as V}from"better-call";var Q=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as _e}from"zod";var X=()=>p("/session",{method:"GET",requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return z(e),r&&await e.context.internalAdapter.deleteSession(r.session.id),e.json(null,{status:401});if(await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(r);let n=e.context.sessionConfig.expiresIn,s=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+s*1e3<=Date.now()){let a=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:Q(e.context.sessionConfig.expiresIn,"sec")});if(!a)return z(e),e.json(null,{status:401});let d=(a.expiresAt.valueOf()-Date.now())/1e3;return await P(e,a.id,!1,{maxAge:d}),e.json({session:a,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),At=async e=>await X()({...e,_flag:"json",headers:e.headers}),L=D(async e=>{let t=await At(e);if(!t?.session)throw new V("UNAUTHORIZED");return{session:t}}),Se=()=>p("/user/list-sessions",{method:"GET",use:[L],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Oe=p("/user/revoke-session",{method:"POST",body:_e.object({id:_e.string()}),use:[L],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new V("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new V("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new V("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Le=p("/user/revoke-sessions",{method:"POST",use:[L],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new V("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});import"zod";import{APIError as Rt}from"better-call";var Ie=p("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Rt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),z(e),e.json({success:!0})});import{z as _}from"zod";import{APIError as G}from"better-call";var Ce=p("/forget-password",{method:"POST",body:_.object({email:_.string().email(),redirectTo:_.string()}),use:[U]},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 G("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,s=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n)),i=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${i}`,expiresAt:s});let c=`${e.context.baseURL}/reset-password/${i}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(c,o.user),e.json({status:!0})}),Be=p("/reset-password/:token",{method:"GET",query:_.object({callbackURL:_.string()}),use:[U]},async e=>{let{token:t}=e.params,r=e.query.callbackURL,o=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}?token=${t}`)}),De=p("/reset-password",{query:_.object({token:_.string()}).optional(),method:"POST",body:_.object({newPassword:_.string()})},async e=>{let t=e.query?.token;if(!t)throw new G("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new G("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let s=n.value,i=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(s)).find(u=>u.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:s,providerId:"credential",password:i,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(s,i))throw new G("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{TimeSpan as kt}from"oslo";import{createJWT as Ut,validateJWT as Et}from"oslo/jwt";import{z as T}from"zod";import{APIError as j}from"better-call";async function Y(e,t){return await Ut("HS256",Buffer.from(e),{email:t.toLowerCase()},{expiresIn:new kt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var $e=p("/send-verification-email",{method:"POST",query:T.object({currentURL:T.string().optional()}).optional(),body:T.object({email:T.string().email(),callbackURL:T.string().optional()}),use:[U]},async e=>{if(!e.context.options.emailAndPassword?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled. Pass `sendVerificationEmail` in `emailAndPassword` options to enable it."),new j("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new j("BAD_REQUEST",{message:"User not found"});let o=await Y(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailAndPassword.sendVerificationEmail(n,r.user,o),e.json({status:!0})}),ze=p("/verify-email",{method:"GET",query:T.object({token:T.string(),callbackURL:T.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await Et("HS256",Buffer.from(e.context.secret),t)}catch(c){throw e.context.logger.error("Failed to verify email",c),new j("BAD_REQUEST",{message:"Invalid token"})}let n=T.object({email:T.string().email()}).parse(r.payload),s=await e.context.internalAdapter.findUserByEmail(n.email,{includeAccounts:!0});if(!s)throw new j("BAD_REQUEST",{message:"User not found"});if(!s.accounts.find(c=>c.providerId==="credential"))throw new j("BAD_REQUEST",{message:"Account not found"});if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})});import{z as x}from"zod";import{APIError as v}from"better-call";var Ve=p("/user/update",{method:"POST",body:x.object({name:x.string().optional(),image:x.string().optional()}),use:[L,U]},async e=>{let{name:t,image:r}=e.body,o=e.context.session;if(!r&&!t)return e.json({user:o.user});let n=await e.context.internalAdapter.updateUserByEmail(o.user.email,{name:t,image:r});return e.json({user:n})}),je=p("/user/change-password",{method:"POST",body:x.object({newPassword:x.string(),currentPassword:x.string(),revokeOtherSessions:x.boolean().optional()}),use:[L]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,s=e.context.password.config.minPasswordLength;if(t.length<s)throw e.context.logger.error("Password is too short"),new v("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 v("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(y=>y.providerId==="credential"&&y.password);if(!a||!a.password)throw new v("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify(a.password,r))throw new v("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(a.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let y=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!y)throw new v("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await P(e,y.id)}return e.json(n.user)}),qe=p("/user/set-password",{method:"POST",body:x.object({newPassword:x.string()}),use:[L]},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 v("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new v("BAD_REQUEST",{message:"Password too long"});let i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password),c=await e.context.password.hash(t);if(!i)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:c}),e.json(r.user);throw new v("BAD_REQUEST",{message:"user already has a password"})}),Ne=p("/user/delete",{method:"POST",body:x.object({password:x.string()}),use:[L]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(i=>i.providerId==="credential"&&i.password);if(!n||!n.password)throw new v("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new v("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),e.json(null)});var Me=p("/csrf",{method:"GET",metadata:S},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t)return{csrfToken:t};let r=q(32,N("a-z","0-9","A-Z")),o=await M(e.context.secret,r),n=`${r}!${o}`;return await e.setSignedCookie(e.context.authCookies.csrfToken.name,n,e.context.secret,e.context.authCookies.csrfToken.options),{csrfToken:r}});var xt=(e="Unknown")=>`<!DOCTYPE html>
|
|
1
|
+
import{APIError as Lt,createRouter as It}from"better-call";import{APIError as W}from"better-call";import{z as oe}from"zod";import{xchacha20poly1305 as Gt}from"@noble/ciphers/chacha";import{bytesToHex as Zt,hexToBytes as Wt,utf8ToBytes as Jt}from"@noble/ciphers/utils";import{managedNonce as Xt}from"@noble/ciphers/webcrypto";import{sha256 as er}from"oslo/crypto";function Z(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let n=0;for(let s=0;s<r.length;s++)n|=r[s]^o[s];return n===0}import{decodeHex as zt,encodeHex as Vt}from"oslo/encoding";import{scryptAsync as Nt}from"@noble/hashes/scrypt";function Je(e){return e.toString(2).padStart(8,"0")}function Ke(e){return[...e].map(t=>Je(t)).join("")}function ee(e){return parseInt(Ke(e),2)}function Xe(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,o=new Uint8Array(Math.ceil(t/8));crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=ee(o);for(;n>=e;)crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=ee(o);return n}function j(e,t){let r="";for(let o=0;o<e;o++)r+=t[Xe(t.length)];return r}function q(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}async function N(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),s=await crypto.subtle.sign(o.name,n,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(s)))}import{createEndpointCreator as Ye,createMiddleware as te,createMiddlewareCreator as et}from"better-call";var re=te(async()=>({})),D=et({use:[re,te(async()=>({}))]}),u=Ye({use:[re]});var ne=D({body:oe.object({csrfToken:oe.string().optional()}).optional()},async e=>{if(e.request?.method!=="POST"||e.context.options.advanced?.disableCSRFCheck)return;let t=new URL(e.request.url);if(e.context.trustedOrigins.includes(t.origin))return;let r=e.body?.csrfToken;if(!r)throw new W("UNAUTHORIZED",{message:"CSRF Token is required"});let o=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[n,s]=o?.split("!")||[null,null];if(!r||!o||!n||!s||o!==r)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new W("UNAUTHORIZED",{message:"Invalid CSRF Token"});let i=await N(e.context.secret,n);if(s!==i)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new W("UNAUTHORIZED",{message:"Invalid CSRF Token"})});import{APIError as O}from"better-call";import{generateCodeVerifier as wt}from"oslo/oauth2";import{z as E}from"zod";import{generateState as tt}from"oslo/oauth2";import{z as M}from"zod";import{sha256 as se}from"oslo/crypto";async function ie(e){let t=await se(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function ae(e,t){let r=await se(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return Z(r,o)}async function ce(e){let t=tt(),r=JSON.stringify({code:t,callbackURL:e}),o=await ie(r);return{raw:r,hash:o}}function J(e){return M.object({code:M.string(),callbackURL:M.string().optional(),currentURL:M.string().optional()}).safeParse(JSON.parse(e))}import{TimeSpan as Ur}from"oslo";var I=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};async function P(e,t,r,o){let n=e.context.authCookies.sessionToken.options;n.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options)}function z(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}import{APIError as de}from"better-call";import{createConsola as rt}from"consola";var C=rt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),ot=e=>({log:(...t)=>{!e?.disabled&&C.log("",...t)},error:(...t)=>{!e?.disabled&&C.error("",...t)},warn:(...t)=>{!e?.disabled&&C.warn("",...t)},info:(...t)=>{!e?.disabled&&C.info("",...t)},debug:(...t)=>{!e?.disabled&&C.debug("",...t)},box:(...t)=>{!e?.disabled&&C.box("",...t)},success:(...t)=>{!e?.disabled&&C.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
|
+
`)}}),w=ot();var U=D(async e=>{let t=e.body?.callbackURL||e.query?.callbackURL||e.query?.redirectTo||e.body?.redirectTo,r=e.headers?.get("referer"),o=e.query?.currentURL||r||e.context.baseURL,n=e.context.trustedOrigins;if(t?.includes("http")){let s=new URL(t).origin;if(!n.includes(s))throw w.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new de("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let s=new URL(o).origin;if(!n.includes(s))throw w.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new de("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as at}from"oslo/jwt";import{sha256 as nt}from"oslo/crypto";import{base64url as st}from"oslo/encoding";async function pe(e){let t=await nt(new TextEncoder().encode(e));return st.encode(new Uint8Array(t),{includePadding:!1})}function ue(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_at?new Date((Date.now()+e.expires_in)*1e3):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:n,scopes:s,claims:i,disablePkce:d,redirectURI:a}){let c=new URL(r);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",t.clientId),c.searchParams.set("state",o),c.searchParams.set("scope",s.join(" ")),c.searchParams.set("redirect_uri",t.redirectURI||a),!d&&n){let p=await pe(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",p)}if(i){let p=i.reduce((y,f)=>(y[f]=null,y),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...p}}))}return c}import{betterFetch as it}from"@better-fetch/fetch";async function b({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let s=new URLSearchParams;s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:i,error:d}=await it(n,{method:"POST",body:s,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(d)throw d;return ue(i)}function K(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var le=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let s=e.scope||o||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${s.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=at(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};import{betterFetch as ct}from"@better-fetch/fetch";var me=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>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 ct("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});import{betterFetch as dt}from"@better-fetch/fetch";var fe=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["email","public_profile"];return await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>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 dt("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,emailVerified:r.email_verified},data:r}}});import{betterFetch as ge}from"@better-fetch/fetch";var he=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:s}){let i=e.scope||o||["user:email"];return A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:i,state:r,redirectURI:s,codeVerifier: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:n}=await ge("https://api.github.com/user",{auth:{type:"Bearer",token:r.accessToken}});if(n)return null;let s=!1;if(!o.email){let{data:i,error:d}=await ge("https://api.github.com/user/emails",{auth:{type:"Bearer",token:r.accessToken}});d||(o.email=(i.find(a=>a.primary)??i[0])?.email,s=i.find(a=>a.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:s},data:o}}}};import{parseJWT as pt}from"oslo/jwt";var we=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw w.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new I("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new I("codeVerifier is required for Google");let s=e.scope||r||["email","profile"];return A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:s,state:t,codeVerifier:o,redirectURI:n})},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 getUserInfo(t){if(!t.idToken)return null;let r=pt(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});import{betterFetch as ut}from"@better-fetch/fetch";import{parseJWT as lt}from"oslo/jwt";var ye=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let s=e.scope||n.scopes||["openid","profile","email","User.Read"];return A({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:s,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:s,redirectURI:i}){return b({code:n,codeVerifier:s,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let s=lt(n.idToken)?.payload,i=e.profilePhotoSize||48;return await ut(`https://graph.microsoft.com/v1.0/me/photos/${i}x${i}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(d){if(!(e.disableProfilePhoto||!d.response.ok))try{let c=await d.response.clone().arrayBuffer(),p=Buffer.from(c).toString("base64");s.picture=`data:image/jpeg;base64, ${p}`}catch(a){w.error(a)}}}),{user:{id:s.sub,name:s.name,email:s.email,image:s.picture,emailVerified:!0},data:s}}}};import{betterFetch as mt}from"@better-fetch/fetch";var be=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let s=e.scope||r||["user-read-email"];return A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:s,state:t,codeVerifier:o,redirectURI:n})},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 mt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";var S={isAction:!1};var Ae=e=>j(e||21,q("a-z","0-9","A-Z"));import{parseJWT as ft}from"oslo/jwt";var Re=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username"]})},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 w.error("No idToken found in token"),null;let o=ft(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as gt}from"@better-fetch/fetch";var ke=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return A({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await gt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var ht={apple:le,discord:me,facebook:fe,github:he,microsoft:ye,google:we,spotify:be,twitch:Re,twitter:ke},Ue=Object.keys(ht);var Ee=u("/sign-in/social",{method:"POST",requireHeaders:!0,query:E.object({currentURL:E.string().optional()}).optional(),body:E.object({callbackURL:E.string().optional(),provider:E.enum(Ue)}),use:[U]},async e=>{let t=e.context.socialProviders.find(a=>a.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 O("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,n=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,s=await ce(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,s.hash,e.context.secret,r.state.options);let i=wt();await e.setSignedCookie(r.pkCodeVerifier.name,i,e.context.secret,r.pkCodeVerifier.options);let d=await t.createAuthorizationURL({state:s.raw,codeVerifier:i,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:d.toString(),state:s,codeVerifier:i,redirect:!0})}),xe=u("/sign-in/email",{method:"POST",body:E.object({email:E.string().email(),password:E.string(),callbackURL:E.string().optional(),dontRememberMe:E.boolean().default(!1).optional()}),use:[U]},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 O("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!E.string().email().safeParse(t).success)throw new O("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new O("UNAUTHORIZED",{message:"Invalid email or password"});let s=n.accounts.find(c=>c.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new O("UNAUTHORIZED",{message:"Invalid email or password"});let i=s?.password;if(!i)throw e.context.logger.error("Password not found",{email:t}),new O("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(i,r))throw e.context.logger.error("Invalid password"),new O("UNAUTHORIZED",{message:"Invalid email or password"});let a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!a)throw e.context.logger.error("Failed to create session"),new O("UNAUTHORIZED",{message:"Failed to create session"});return await P(e,a.id,e.body.dontRememberMe),e.json({user:n.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{APIError as bt}from"better-call";import{z as F}from"zod";import{z as l}from"zod";var An=l.object({id:l.string(),providerId:l.string(),accountId:l.string(),userId:l.string(),accessToken:l.string().nullable().optional(),refreshToken:l.string().nullable().optional(),idToken:l.string().nullable().optional(),expiresAt:l.date().nullable().optional(),password:l.string().optional().nullable()}),Pe=l.object({id:l.string(),email:l.string().transform(e=>e.toLowerCase()),emailVerified:l.boolean().default(!1),name:l.string(),image:l.string().optional(),createdAt:l.date().default(new Date),updatedAt:l.date().default(new Date)}),Rn=l.object({id:l.string(),userId:l.string(),expiresAt:l.date(),ipAddress:l.string().optional(),userAgent:l.string().optional()}),kn=l.object({id:l.string(),value:l.string(),expiresAt:l.date(),identifier:l.string()});function yt(e,t){let r=t.fields,o={};for(let n in r){if(n in e){if(r[n].input===!1){if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}continue}o[n]=e[n];continue}if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}}return o}function Te(e,t){let r={...e.user?.additionalFields};return yt(t||{},{fields:r})}var ve=u("/callback/:id",{method:"GET",query:F.object({state:F.string(),code:F.string().optional(),error:F.string().optional()}),metadata:S},async e=>{if(e.query.error||!e.query.code){let h=J(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${h}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(m=>m.id===e.params.id);if(!t)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let r=J(e.query.state);if(!r.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:n}}=r,s=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!s)throw w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await ae(e.query.state,s))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let d=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),a;try{a=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:d,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(m){throw e.context.logger.error(m),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let c=await t.getUserInfo(a).then(m=>m?.user),p=Ae(),y=Pe.safeParse({...c,id:p});if(!c||y.success===!1)throw w.error("Unable to get user info",y.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let f=await e.context.internalAdapter.findUserByEmail(c.email,{includeAccounts:!0}).catch(m=>{throw w.error(`Better auth was unable to query your database.
|
|
3
|
+
Error: `,m),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),g=f?.user.id;if(f){let m=f.accounts.find(k=>k.providerId===t.id),h=e.context.options.account?.accountLinking?.trustedProviders,R=h?h.includes(t.id):!0;if(!m&&(!c.emailVerified||!R)){let k;try{k=new URL(n||o),k.searchParams.set("error","account_not_linked")}catch{throw e.redirect(`${e.context.baseURL}/error?error=account_not_linked`)}throw e.redirect(k.toString())}if(!m)try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:c.id.toString(),id:`${t.id}:${c.id}`,userId:f.user.id,...K(a)})}catch(k){throw console.log(k),e.redirect(`${e.context.baseURL}/error?error=failed_linking_account`)}}else try{await e.context.internalAdapter.createOAuthUser(y.data,{...K(a),id:`${t.id}:${c.id}`,providerId:t.id,accountId:c.id.toString(),userId:p})}catch{let h=new URL(n||o);throw h.searchParams.set("error","unable_to_create_user"),e.setHeader("Location",h.toString()),e.redirect(h.toString())}if(!g&&!p)throw new bt("INTERNAL_SERVER_ERROR",{message:"Unable to create user"});try{let m=await e.context.internalAdapter.createSession(g||p,e.request);if(!m){let h=new URL(n||o);throw h.searchParams.set("error","unable_to_create_session"),e.redirect(h.toString())}try{await P(e,m.id)}catch(h){e.context.logger.error("Unable to set session cookie",h);let R=new URL(n||o);throw R.searchParams.set("error","unable_to_create_session"),e.redirect(R.toString())}}catch{let m=new URL(n||o||"");throw m.searchParams.set("error","unable_to_create_session"),e.redirect(m.toString())}throw e.redirect(o)});import{APIError as V}from"better-call";var H=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as _e}from"zod";var X=()=>u("/session",{method:"GET",requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return z(e),r&&await e.context.internalAdapter.deleteSession(r.session.id),e.json(null,{status:401});if(await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(r);let n=e.context.sessionConfig.expiresIn,s=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+s*1e3<=Date.now()){let a=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:H(e.context.sessionConfig.expiresIn,"sec")});if(!a)return z(e),e.json(null,{status:401});let c=(a.expiresAt.valueOf()-Date.now())/1e3;return await P(e,a.id,!1,{maxAge:c}),e.json({session:a,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),At=async e=>await X()({...e,_flag:"json",headers:e.headers}),L=D(async e=>{let t=await At(e);if(!t?.session)throw new V("UNAUTHORIZED");return{session:t}}),Se=()=>u("/user/list-sessions",{method:"GET",use:[L],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Oe=u("/user/revoke-session",{method:"POST",body:_e.object({id:_e.string()}),use:[L],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new V("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new V("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new V("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Le=u("/user/revoke-sessions",{method:"POST",use:[L],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new V("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});import"zod";import{APIError as Rt}from"better-call";var Ie=u("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Rt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),z(e),e.json({success:!0})});import{z as _}from"zod";import{APIError as G}from"better-call";var Ce=u("/forget-password",{method:"POST",body:_.object({email:_.string().email(),redirectTo:_.string()}),use:[U]},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 G("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,s=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n)),i=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${i}`,expiresAt:s});let d=`${e.context.baseURL}/reset-password/${i}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(d,o.user),e.json({status:!0})}),Be=u("/reset-password/:token",{method:"GET",query:_.object({callbackURL:_.string()}),use:[U]},async e=>{let{token:t}=e.params,r=e.query.callbackURL,o=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}?token=${t}`)}),De=u("/reset-password",{query:_.object({token:_.string()}).optional(),method:"POST",body:_.object({newPassword:_.string()})},async e=>{let t=e.query?.token;if(!t)throw new G("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new G("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let s=n.value,i=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(s)).find(p=>p.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:s,providerId:"credential",password:i,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(s,i))throw new G("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{TimeSpan as kt}from"oslo";import{createJWT as Ut,validateJWT as Et}from"oslo/jwt";import{z as T}from"zod";import{APIError as Q}from"better-call";async function Y(e,t){return await Ut("HS256",Buffer.from(e),{email:t.toLowerCase()},{expiresIn:new kt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var $e=u("/send-verification-email",{method:"POST",query:T.object({currentURL:T.string().optional()}).optional(),body:T.object({email:T.string().email(),callbackURL:T.string().optional()}),use:[U]},async e=>{if(!e.context.options.emailAndPassword?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled. Pass `sendVerificationEmail` in `emailAndPassword` options to enable it."),new Q("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new Q("BAD_REQUEST",{message:"User not found"});let o=await Y(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailAndPassword.sendVerificationEmail(n,r.user,o),e.json({status:!0})}),ze=u("/verify-email",{method:"GET",query:T.object({token:T.string(),callbackURL:T.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await Et("HS256",Buffer.from(e.context.secret),t)}catch(i){throw e.context.logger.error("Failed to verify email",i),new Q("BAD_REQUEST",{message:"Invalid token"})}let n=T.object({email:T.string().email()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new Q("BAD_REQUEST",{message:"User not found"});if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})});import{z as x}from"zod";import{APIError as v}from"better-call";var Ve=u("/user/update",{method:"POST",body:x.object({name:x.string().optional(),image:x.string().optional()}),use:[L,U]},async e=>{let{name:t,image:r}=e.body,o=e.context.session;if(!r&&!t)return e.json({user:o.user});let n=await e.context.internalAdapter.updateUserByEmail(o.user.email,{name:t,image:r});return e.json({user:n})}),je=u("/user/change-password",{method:"POST",body:x.object({newPassword:x.string(),currentPassword:x.string(),revokeOtherSessions:x.boolean().optional()}),use:[L]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,s=e.context.password.config.minPasswordLength;if(t.length<s)throw e.context.logger.error("Password is too short"),new v("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 v("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(y=>y.providerId==="credential"&&y.password);if(!a||!a.password)throw new v("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(a.password,r))throw new v("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(a.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let y=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!y)throw new v("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await P(e,y.id)}return e.json(n.user)}),qe=u("/user/set-password",{method:"POST",body:x.object({newPassword:x.string()}),use:[L]},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 v("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new v("BAD_REQUEST",{message:"Password too long"});let i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password),d=await e.context.password.hash(t);if(!i)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:d}),e.json(r.user);throw new v("BAD_REQUEST",{message:"user already has a password"})}),Ne=u("/user/delete",{method:"POST",body:x.object({password:x.string()}),use:[L]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(i=>i.providerId==="credential"&&i.password);if(!n||!n.password)throw new v("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new v("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),e.json(null)});var Me=u("/csrf",{method:"GET",metadata:S},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t)return{csrfToken:t};let r=j(32,q("a-z","0-9","A-Z")),o=await N(e.context.secret,r),n=`${r}!${o}`;return await e.setSignedCookie(e.context.authCookies.csrfToken.name,n,e.context.secret,e.context.authCookies.csrfToken.options),{csrfToken:r}});var xt=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|
|
6
6
|
<meta charset="UTF-8">
|
|
@@ -80,4 +80,4 @@ Error: `,m),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
|
|
|
80
80
|
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
81
81
|
</div>
|
|
82
82
|
</body>
|
|
83
|
-
</html>`,Fe=
|
|
83
|
+
</html>`,Fe=u("/error",{method:"GET",metadata:S},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(xt(t),{headers:{"Content-Type":"text/html"}})});var He=u("/ok",{method:"GET",metadata:S},async e=>e.json({ok:!0}));import{z as $}from"zod";import{APIError as B}from"better-call";var Ge=()=>u("/sign-up/email",{method:"POST",query:$.object({currentURL:$.string().optional()}).optional(),body:$.record($.string(),$.any()),use:[U]},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new B("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:n,image:s,callbackURL:i,...d}=t;if(!$.string().email().safeParse(o).success)throw new B("BAD_REQUEST",{message:"Invalid email"});let c=e.context.password.config.minPasswordLength;if(n.length<c)throw e.context.logger.error("Password is too short"),new B("BAD_REQUEST",{message:"Password is too short"});let p=e.context.password.config.maxPasswordLength;if(n.length>p)throw e.context.logger.error("Password is too long"),new B("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 B("UNPROCESSABLE_ENTITY",{message:"The email has already been taken"});let f=Te(e.context.options,d),g=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:s,...f,emailVerified:!1});if(!g)throw new B("BAD_REQUEST",{message:"Failed to create user"});let m=await e.context.password.hash(n);await e.context.internalAdapter.linkAccount({userId:g.id,providerId:"credential",accountId:g.id,password:m,expiresAt:H(60*60*24*30,"sec")});let h=await e.context.internalAdapter.createSession(g.id,e.request);if(!h)throw new B("BAD_REQUEST",{message:"Failed to create session"});if(await P(e,h.id),e.context.options.emailAndPassword.sendEmailVerificationOnSignUp){let R=await Y(e.context.secret,g.email),k=`${e.context.baseURL}/verify-email?token=${R}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailAndPassword.sendVerificationEmail?.(k,g,R)}return e.json({user:g,session:h},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:g,session:h}})});function Qe(e){let t="127.0.0.1";if(process.env.NODE_ENV==="test")return t;let r=["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"];for(let o of r){let n=e.headers.get(o);if(typeof n=="string"){let s=n.split(",")[0].trim();if(s)return s}}return null}function Pt(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function Tt(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 vt(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function _t(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async n=>await o.findOne({model:r,where:[{field:"key",value:n}]}),set:async(n,s,i)=>{try{i?await o.update({model:t??"rateLimit",where:[{field:"key",value:n}],update:{count:s.count,lastRequest:s.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:n,count:s.count,lastRequest:s.lastRequest}})}catch(d){w.error("Error setting rate limit",d)}}}}var Ze=new Map;function St(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 Ze.get(r)},async set(r,o,n){Ze.set(r,o)}}:_t(e,e.rateLimit.tableName)}async function We(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),n=t.rateLimit.window,s=t.rateLimit.max,i=Qe(e)+o,a=Ot().find(f=>f.pathMatcher(o));a&&(n=a.window,s=a.max);for(let f of t.options.plugins||[])if(f.rateLimit){let g=f.rateLimit.find(m=>m.pathMatcher(o));if(g){n=g.window,s=g.max;break}}if(t.rateLimit.customRules){let f=t.rateLimit.customRules[o];f&&(n=f.window,s=f.max)}let c=St(t),p=await c.get(i),y=Date.now();if(!p)await c.set(i,{key:i,count:1,lastRequest:y});else{let f=y-p.lastRequest;if(Pt(s,n,p)){let g=vt(p.lastRequest,n);return Tt(g)}else f>n*1e3?await c.set(i,{...p,count:1,lastRequest:y}):await c.set(i,{...p,count:p.count+1,lastRequest:y})}}function Ot(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:7}]}import{APIError as xi}from"better-call";function Ct(e,t){let r=t.plugins?.reduce((d,a)=>({...d,...a.endpoints}),{}),o=t.plugins?.map(d=>d.middlewares?.map(a=>{let c=async p=>a.middleware({...p,context:{...e,...p.context}});return c.path=a.path,c.options=a.middleware.options,c.headers=a.middleware.headers,{path:a.path,middleware:c}})).filter(d=>d!==void 0).flat()||[],s={...{signInOAuth:Ee,callbackOAuth:ve,getCSRFToken:Me,getSession:X(),signOut:Ie,signUpEmail:Ge(),signInEmail:xe,forgetPassword:Ce,resetPassword:De,verifyEmail:ze,sendVerificationEmail:$e,changePassword:je,setPassword:qe,updateUser:Ve,deleteUser:Ne,forgetPasswordCallback:Be,listSessions:Se(),revokeSession:Oe,revokeSessions:Le},...r,ok:He,error:Fe},i={};for(let[d,a]of Object.entries(s))i[d]=async(c={})=>{let p=await e;for(let g of t.plugins||[])if(g.hooks?.before){for(let m of g.hooks.before)if(m.matcher({...a,...c,context:p})){let R=await m.handler({...c,context:{...p,...c?.context}});R&&"context"in R&&(p={...p,...R.context})}}let f=await a({...c,context:{...p,...c.context}});for(let g of t.plugins||[])if(g.hooks?.after){for(let m of g.hooks.after)if(m.matcher(c)){let R=Object.assign(c,{context:{...e,returned:f}}),k=await m.handler(R);k&&"response"in k&&(f=k.response)}}return f},i[d].path=a.path,i[d].method=a.method,i[d].options=a.options,i[d].headers=a.headers;return{api:i,middlewares:o}}var bi=(e,t)=>{let{api:r,middlewares:o}=Ct(e,t),n=new URL(e.baseURL).pathname;return It(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:ne},...o],async onRequest(s){for(let i of e.options.plugins||[])if(i.onRequest){let d=await i.onRequest(s,e);if(d)return d}return We(s,e)},async onResponse(s){for(let i of e.options.plugins||[])if(i.onResponse){let d=await i.onResponse(s,e);if(d)return d.response}return s},onError(s){if(t.onAPIError?.throw)throw s;if(t.onAPIError?.onError){t.onAPIError.onError(s,e);return}let i=t.logger?.verboseLogging?w:void 0;t.logger?.disabled!==!0&&(s instanceof Lt?(s.status==="INTERNAL_SERVER_ERROR"&&w.error(s),i?.error(s.message)):w?.error(s))}})};export{xi as APIError,ve as callbackOAuth,je as changePassword,u as createAuthEndpoint,D as createAuthMiddleware,Y as createEmailVerificationToken,ne as csrfMiddleware,Ne as deleteUser,Fe as error,Ce as forgetPassword,Be as forgetPasswordCallback,Me as getCSRFToken,Ct as getEndpoints,X as getSession,At as getSessionFromCtx,Se as listSessions,He as ok,re as optionsMiddleware,De as resetPassword,Oe as revokeSession,Le as revokeSessions,bi as router,$e as sendVerificationEmail,L as sessionMiddleware,qe as setPassword,xe as signInEmail,Ee as signInOAuth,Ie as signOut,Ge as signUpEmail,Ve as updateUser,ze as verifyEmail};
|
|
@@ -1190,12 +1190,12 @@ declare const signInOAuth: {
|
|
|
1190
1190
|
/**
|
|
1191
1191
|
* OAuth2 provider to use`
|
|
1192
1192
|
*/
|
|
1193
|
-
provider: z.ZodEnum<["github", ...("
|
|
1193
|
+
provider: z.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
1194
1194
|
}, "strip", z.ZodTypeAny, {
|
|
1195
|
-
provider: "
|
|
1195
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
1196
1196
|
callbackURL?: string | undefined;
|
|
1197
1197
|
}, {
|
|
1198
|
-
provider: "
|
|
1198
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
1199
1199
|
callbackURL?: string | undefined;
|
|
1200
1200
|
}>;
|
|
1201
1201
|
use: better_call.Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -1233,12 +1233,12 @@ declare const signInOAuth: {
|
|
|
1233
1233
|
/**
|
|
1234
1234
|
* OAuth2 provider to use`
|
|
1235
1235
|
*/
|
|
1236
|
-
provider: z.ZodEnum<["github", ...("
|
|
1236
|
+
provider: z.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
1237
1237
|
}, "strip", z.ZodTypeAny, {
|
|
1238
|
-
provider: "
|
|
1238
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
1239
1239
|
callbackURL?: string | undefined;
|
|
1240
1240
|
}, {
|
|
1241
|
-
provider: "
|
|
1241
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
1242
1242
|
callbackURL?: string | undefined;
|
|
1243
1243
|
}>;
|
|
1244
1244
|
use: better_call.Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -2435,12 +2435,12 @@ declare function getEndpoints<C extends AuthContext, Option extends BetterAuthOp
|
|
|
2435
2435
|
}>>;
|
|
2436
2436
|
body: zod.ZodObject<{
|
|
2437
2437
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
2438
|
-
provider: zod.ZodEnum<["github", ...("
|
|
2438
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
2439
2439
|
}, "strip", zod.ZodTypeAny, {
|
|
2440
|
-
provider: "
|
|
2440
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
2441
2441
|
callbackURL?: string | undefined;
|
|
2442
2442
|
}, {
|
|
2443
|
-
provider: "
|
|
2443
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
2444
2444
|
callbackURL?: string | undefined;
|
|
2445
2445
|
}>;
|
|
2446
2446
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -2468,12 +2468,12 @@ declare function getEndpoints<C extends AuthContext, Option extends BetterAuthOp
|
|
|
2468
2468
|
}>>;
|
|
2469
2469
|
body: zod.ZodObject<{
|
|
2470
2470
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
2471
|
-
provider: zod.ZodEnum<["github", ...("
|
|
2471
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
2472
2472
|
}, "strip", zod.ZodTypeAny, {
|
|
2473
|
-
provider: "
|
|
2473
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
2474
2474
|
callbackURL?: string | undefined;
|
|
2475
2475
|
}, {
|
|
2476
|
-
provider: "
|
|
2476
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
2477
2477
|
callbackURL?: string | undefined;
|
|
2478
2478
|
}>;
|
|
2479
2479
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -3530,12 +3530,12 @@ declare const router: <C extends AuthContext, Option extends BetterAuthOptions>(
|
|
|
3530
3530
|
}>>;
|
|
3531
3531
|
body: zod.ZodObject<{
|
|
3532
3532
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
3533
|
-
provider: zod.ZodEnum<["github", ...("
|
|
3533
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
3534
3534
|
}, "strip", zod.ZodTypeAny, {
|
|
3535
|
-
provider: "
|
|
3535
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
3536
3536
|
callbackURL?: string | undefined;
|
|
3537
3537
|
}, {
|
|
3538
|
-
provider: "
|
|
3538
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
3539
3539
|
callbackURL?: string | undefined;
|
|
3540
3540
|
}>;
|
|
3541
3541
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -3563,12 +3563,12 @@ declare const router: <C extends AuthContext, Option extends BetterAuthOptions>(
|
|
|
3563
3563
|
}>>;
|
|
3564
3564
|
body: zod.ZodObject<{
|
|
3565
3565
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
3566
|
-
provider: zod.ZodEnum<["github", ...("
|
|
3566
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
3567
3567
|
}, "strip", zod.ZodTypeAny, {
|
|
3568
|
-
provider: "
|
|
3568
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
3569
3569
|
callbackURL?: string | undefined;
|
|
3570
3570
|
}, {
|
|
3571
|
-
provider: "
|
|
3571
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
3572
3572
|
callbackURL?: string | undefined;
|
|
3573
3573
|
}>;
|
|
3574
3574
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -4627,12 +4627,12 @@ declare const betterAuth: <O extends BetterAuthOptions>(options: O) => {
|
|
|
4627
4627
|
}>>;
|
|
4628
4628
|
body: zod.ZodObject<{
|
|
4629
4629
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
4630
|
-
provider: zod.ZodEnum<["github", ...("
|
|
4630
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
4631
4631
|
}, "strip", zod.ZodTypeAny, {
|
|
4632
|
-
provider: "
|
|
4632
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
4633
4633
|
callbackURL?: string | undefined;
|
|
4634
4634
|
}, {
|
|
4635
|
-
provider: "
|
|
4635
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
4636
4636
|
callbackURL?: string | undefined;
|
|
4637
4637
|
}>;
|
|
4638
4638
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -4660,12 +4660,12 @@ declare const betterAuth: <O extends BetterAuthOptions>(options: O) => {
|
|
|
4660
4660
|
}>>;
|
|
4661
4661
|
body: zod.ZodObject<{
|
|
4662
4662
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
4663
|
-
provider: zod.ZodEnum<["github", ...("
|
|
4663
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
4664
4664
|
}, "strip", zod.ZodTypeAny, {
|
|
4665
|
-
provider: "
|
|
4665
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
4666
4666
|
callbackURL?: string | undefined;
|
|
4667
4667
|
}, {
|
|
4668
|
-
provider: "
|
|
4668
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
4669
4669
|
callbackURL?: string | undefined;
|
|
4670
4670
|
}>;
|
|
4671
4671
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
package/dist/client/plugins.d.ts
CHANGED
|
@@ -2,10 +2,10 @@ import * as nanostores from 'nanostores';
|
|
|
2
2
|
import { A as AccessControl, S as StatementsPrimitive, R as Role } from '../statement-CfnyN34h.js';
|
|
3
3
|
import * as _better_fetch_fetch from '@better-fetch/fetch';
|
|
4
4
|
import { BetterFetchOption } from '@better-fetch/fetch';
|
|
5
|
-
import { o as organization, k as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, e as anonymous, i as admin, j as genericOAuth } from '../index-
|
|
6
|
-
export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-
|
|
5
|
+
import { o as organization, k as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, e as anonymous, i as admin, j as genericOAuth } from '../index-DgJ3JDtV.js';
|
|
6
|
+
export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-DgJ3JDtV.js';
|
|
7
7
|
import { P as Prettify } from '../helper-DPDj8Nix.js';
|
|
8
|
-
import { F as FieldAttribute, B as BetterAuthOptions, b as BetterAuthPlugin } from '../auth-
|
|
8
|
+
import { F as FieldAttribute, B as BetterAuthOptions, b as BetterAuthPlugin } from '../auth-BGQTSAwN.js';
|
|
9
9
|
import 'zod';
|
|
10
10
|
import '../schema-Dkt0LqYs.js';
|
|
11
11
|
import 'better-call';
|
package/dist/client.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { BetterFetch, BetterFetchError, BetterFetchOption } from '@better-fetch/
|
|
|
6
6
|
import { U as UnionToIntersection, P as Prettify, S as StripEmptyObjects } from './helper-DPDj8Nix.js';
|
|
7
7
|
import { ClientOptions, InferClientAPI, InferActions, InferAdditionalFromClient, InferSessionFromClient, InferUserFromClient, BetterAuthClientPlugin, IsSignal } from './types.js';
|
|
8
8
|
export { AtomListener, InferPluginsFromClient } from './types.js';
|
|
9
|
-
import './auth-
|
|
9
|
+
import './auth-BGQTSAwN.js';
|
|
10
10
|
import 'kysely';
|
|
11
11
|
import './schema-Dkt0LqYs.js';
|
|
12
12
|
import 'better-call';
|
package/dist/cookies.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import 'better-call';
|
|
2
|
-
export { s as BetterAuthCookies, E as EligibleCookies, r as createCookieGetter, u as deleteSessionCookie, q as getCookies, v as parseSetCookieHeader, t as setSessionCookie } from './auth-
|
|
2
|
+
export { s as BetterAuthCookies, E as EligibleCookies, r as createCookieGetter, u as deleteSessionCookie, q as getCookies, v as parseSetCookieHeader, t as setSessionCookie } from './auth-BGQTSAwN.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
5
|
import './schema-Dkt0LqYs.js';
|
package/dist/db.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as Adapter, B as BetterAuthOptions, W as Where, F as FieldAttribute, y as FieldType, K as KyselyDatabaseType } from './auth-
|
|
2
|
-
export { V as BetterAuthDbSchema, D as FieldAttributeConfig, U as InferFieldsFromOptions, T as InferFieldsFromPlugins, N as InferFieldsInput, O as InferFieldsInputClient, M as InferFieldsOutput, L as InferValueType, C as InternalAdapter, Q as PluginFieldAttribute, J as createFieldAttribute, z as createInternalAdapter, X as getAuthTables } from './auth-
|
|
1
|
+
import { A as Adapter, B as BetterAuthOptions, W as Where, F as FieldAttribute, y as FieldType, K as KyselyDatabaseType } from './auth-BGQTSAwN.js';
|
|
2
|
+
export { V as BetterAuthDbSchema, D as FieldAttributeConfig, U as InferFieldsFromOptions, T as InferFieldsFromPlugins, N as InferFieldsInput, O as InferFieldsInputClient, M as InferFieldsOutput, L as InferValueType, C as InternalAdapter, Q as PluginFieldAttribute, J as createFieldAttribute, z as createInternalAdapter, X as getAuthTables } from './auth-BGQTSAwN.js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
5
|
import './schema-Dkt0LqYs.js';
|
|
@@ -5,7 +5,7 @@ import { P as Prettify } from './helper-DPDj8Nix.js';
|
|
|
5
5
|
import { A as AccessControl, R as Role, S as StatementsPrimitive, g as defaultRoles } from './statement-CfnyN34h.js';
|
|
6
6
|
import * as _better_fetch_fetch from '@better-fetch/fetch';
|
|
7
7
|
import { BetterFetch, BetterFetchOption } from '@better-fetch/fetch';
|
|
8
|
-
import { H as HookEndpointContext, p as AuthContext } from './auth-
|
|
8
|
+
import { H as HookEndpointContext, p as AuthContext } from './auth-BGQTSAwN.js';
|
|
9
9
|
import * as nanostores from 'nanostores';
|
|
10
10
|
import { atom } from 'nanostores';
|
|
11
11
|
import * as _simplewebauthn_types from '@simplewebauthn/types';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { A as Adapter, j as AdditionalSessionFieldsInput, k as AdditionalSessionFieldsOutput, h as AdditionalUserFieldsInput, i as AdditionalUserFieldsOutput, a as Auth, p as AuthContext, s as BetterAuthCookies, B as BetterAuthOptions, b as BetterAuthPlugin, E as EligibleCookies, G as GenericEndpointContext, H as HookEndpointContext, m as InferPluginTypes, l as InferSession, I as InferUser, P as PluginSchema, R as RateLimit, S as SecondaryStorage, W as Where, g as betterAuth, r as createCookieGetter, w as createLogger, u as deleteSessionCookie, q as getCookies, n as init, x as logger, v as parseSetCookieHeader, t as setSessionCookie } from './auth-
|
|
1
|
+
export { A as Adapter, j as AdditionalSessionFieldsInput, k as AdditionalSessionFieldsOutput, h as AdditionalUserFieldsInput, i as AdditionalUserFieldsOutput, a as Auth, p as AuthContext, s as BetterAuthCookies, B as BetterAuthOptions, b as BetterAuthPlugin, E as EligibleCookies, G as GenericEndpointContext, H as HookEndpointContext, m as InferPluginTypes, l as InferSession, I as InferUser, P as PluginSchema, R as RateLimit, S as SecondaryStorage, W as Where, g as betterAuth, r as createCookieGetter, w as createLogger, u as deleteSessionCookie, q as getCookies, n as init, x as logger, v as parseSetCookieHeader, t as setSessionCookie } from './auth-BGQTSAwN.js';
|
|
2
2
|
export { D as DeepPartial, H as HasRequiredKeys, L as LiteralString, a as LiteralUnion, P as Prettify, R as RequiredKeysOf, S as StripEmptyObjects, U as UnionToIntersection, W as WithoutEmpty } from './helper-DPDj8Nix.js';
|
|
3
3
|
export { AtomListener, BetterAuthClientPlugin, ClientOptions, InferActions, InferAdditionalFromClient, InferClientAPI, InferPluginsFromClient, InferSessionFromClient, InferUserFromClient, IsSignal } from './types.js';
|
|
4
4
|
export { H as HIDE_METADATA } from './hide-metadata-DEHJp1rk.js';
|