better-auth 0.1.0 → 0.1.1-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/api.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { d as AuthEndpoint, e as AuthMiddleware, y as callbackOAuth, X as changePassword, b as createAuthEndpoint, c as createAuthMiddleware, Q as createEmailVerificationToken, a1 as csrfMiddleware, _ as error, M as forgetPassword, N as forgetPasswordCallback, Z as getCSRFToken, u as getEndpoints, z as getSession, C as getSessionFromCtx, E as listSessions, $ as ok, o as optionsMiddleware, O as resetPassword, J as revokeSession, K as revokeSessions, v as router, T as sendVerificationEmail, D as sessionMiddleware, Y as setPassword, x as signInEmail, w as signInOAuth, L as signOut, a0 as signUpEmail, V as updateUser, U as verifyEmail } from './index-BMranMWG.js';
1
+ export { A as AuthEndpoint, b as AuthMiddleware, y as callbackOAuth, X as changePassword, a as createAuthEndpoint, c as createAuthMiddleware, Q as createEmailVerificationToken, a1 as csrfMiddleware, _ as error, M as forgetPassword, N as forgetPasswordCallback, Z as getCSRFToken, u as getEndpoints, z as getSession, C as getSessionFromCtx, E as listSessions, $ as ok, o as optionsMiddleware, O as resetPassword, J as revokeSession, K as revokeSessions, v as router, T as sendVerificationEmail, D as sessionMiddleware, Y as setPassword, x as signInEmail, w as signInOAuth, L as signOut, a0 as signUpEmail, V as updateUser, U as verifyEmail } from './index-BZTQCJvy.js';
2
2
  import 'zod';
3
3
  import './helper-C1ihmerM.js';
4
4
  import 'better-call';
package/dist/api.js CHANGED
@@ -1,5 +1,5 @@
1
- var Ze=Object.defineProperty,Ke=Object.defineProperties;var Qe=Object.getOwnPropertyDescriptors;var re=Object.getOwnPropertySymbols;var Xe=Object.prototype.hasOwnProperty,Ye=Object.prototype.propertyIsEnumerable;var oe=(e,t,n)=>t in e?Ze(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,g=(e,t)=>{for(var n in t||(t={}))Xe.call(t,n)&&oe(e,n,t[n]);if(re)for(var n of re(t))Ye.call(t,n)&&oe(e,n,t[n]);return e},k=(e,t)=>Ke(e,Qe(t));var a=(e,t,n)=>new Promise((o,r)=>{var s=c=>{try{d(n.next(c))}catch(u){r(u)}},i=c=>{try{d(n.throw(c))}catch(u){r(u)}},d=c=>c.done?o(c.value):Promise.resolve(c.value).then(s,i);d((n=n.apply(e,t)).next())});import{APIError as Gt,createRouter as Wt}from"better-call";import{APIError as ie}from"better-call";import{z as ae}from"zod";import{xchacha20poly1305 as Xt}from"@noble/ciphers/chacha";import{bytesToHex as er,hexToBytes as tr,utf8ToBytes as rr}from"@noble/ciphers/utils";import{managedNonce as nr}from"@noble/ciphers/webcrypto";import{sha256 as ir}from"@noble/hashes/sha256";function M(e,t){return a(this,null,function*(){let n=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},r=yield crypto.subtle.importKey("raw",n.encode(e),o,!1,["sign","verify"]),s=yield crypto.subtle.sign(o.name,r,n.encode(t));return btoa(String.fromCharCode(...new Uint8Array(s)))})}import{createEndpointCreator as et,createMiddleware as ne,createMiddlewareCreator as tt}from"better-call";var se=ne(()=>a(void 0,null,function*(){return{}})),H=tt({use:[se,ne(()=>a(void 0,null,function*(){return{}}))]}),f=et({use:[se]});var de=H({body:ae.object({csrfToken:ae.string().optional()}).optional()},e=>a(void 0,null,function*(){var d,c,u,l;if(((d=e.request)==null?void 0:d.method)!=="POST"||(c=e.context.options.advanced)!=null&&c.disableCSRFCheck)return;let t=new URL(e.request.url);if(t.origin===new URL(e.context.baseURL).origin||(u=e.context.options.trustedOrigins)!=null&&u.includes(t.origin))return;let n=(l=e.body)==null?void 0:l.csrfToken,o=yield e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[r,s]=(o==null?void 0:o.split("!"))||[null,null];if(!n||!o||!r||!s||o!==n)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new ie("UNAUTHORIZED",{message:"Invalid CSRF Token"});let i=yield M(e.context.secret,r);if(s!==i)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new ie("UNAUTHORIZED",{message:"Invalid CSRF Token"})}));import{APIError as E}from"better-call";import{generateCodeVerifier as vt}from"oslo/oauth2";import{z as v}from"zod";import"arctic";import{parseJWT as st}from"oslo/jwt";import"@better-fetch/fetch";var D=class extends Error{constructor(t,n,o){super(t),this.name="BetterAuthError",this.message=t,this.cause=n}};import{OAuth2Tokens as ot}from"arctic";function rt(e){try{return new URL(e).pathname!=="/"}catch(t){throw new D(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function G(e,t="/api/auth"){return rt(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function ce(e,t){if(e)return G(e,t);let n=(process==null?void 0:process.env)||{},o=n.BETTER_AUTH_URL||n.NEXT_PUBLIC_BETTER_AUTH_URL||n.PUBLIC_BETTER_AUTH_URL||n.NUXT_PUBLIC_BETTER_AUTH_URL||n.NUXT_PUBLIC_AUTH_URL||(n.BASE_URL!=="/"?n.BASE_URL:void 0);if(o)return G(o,t);if(typeof window!="undefined")return G(window.location.origin,t)}import{betterFetch as nt}from"@better-fetch/fetch";function y(e,t){return t||`${ce()}/callback/${e}`}function A(s){return a(this,arguments,function*({code:e,codeVerifier:t,redirectURI:n,options:o,tokenEndpoint:r}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",n),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:d,error:c}=yield nt(r,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(c)throw c;return new ot(d)})}var le=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:o,scopes:r,redirectURI:s}){let i=r||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${s||e.redirectURI}&scope=${i.join(" ")}&state=${o}`)},validateAuthorizationCode:(o,r,s)=>a(void 0,null,function*(){return A({code:o,codeVerifier:r,redirectURI:s||y("apple",e.redirectURI),options:e,tokenEndpoint:t})}),getUserInfo(o){return a(this,null,function*(){var s;let r=(s=st(o.idToken()))==null?void 0:s.payload;return r?{user:{id:r.sub,name:r.name,email:r.email,emailVerified:r.email_verified==="true"},data:r}:null})}}};import{betterFetch as it}from"@better-fetch/fetch";import{Discord as at}from"arctic";var ue=e=>{let t=new at(e.clientId,e.clientSecret,y("discord",e.redirectURI));return{id:"discord",name:"Discord",createAuthorizationURL({state:o,scopes:r}){let s=r||["email"];return t.createAuthorizationURL(o,s)},validateAuthorizationCode:(o,r,s)=>a(void 0,null,function*(){return A({code:o,codeVerifier:r,redirectURI:s||y("discord",e.redirectURI),options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"})}),getUserInfo(o){return a(this,null,function*(){let{data:r,error:s}=yield it("https://discord.com/api/users/@me",{auth:{type:"Bearer",token:o.accessToken()}});return s?null:{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified},data:r}})}}};import{betterFetch as dt}from"@better-fetch/fetch";import{Facebook as ct}from"arctic";var pe=e=>{let t=new ct(e.clientId,e.clientSecret,y("facebook",e.redirectURI));return{id:"facebook",name:"Facebook",createAuthorizationURL({state:o,scopes:r}){let s=r||["email","public_profile"];return t.createAuthorizationURL(o,s)},validateAuthorizationCode:(o,r,s)=>a(void 0,null,function*(){return A({code:o,codeVerifier:r,redirectURI:s||y("facebook",e.redirectURI),options:e,tokenEndpoint:"https://graph.facebook.com/v16.0/oauth/access_token"})}),getUserInfo(o){return a(this,null,function*(){let{data:r,error:s}=yield dt("https://graph.facebook.com/me",{auth:{type:"Bearer",token:o.accessToken()}});return s?null:{user:{id:r.id,name:r.name,email:r.email,emailVerified:r.email_verified},data:r}})}}};import{betterFetch as me}from"@better-fetch/fetch";import{GitHub as lt}from"arctic";var fe=({clientId:e,clientSecret:t,redirectURI:n})=>{let o=new lt(e,t,y("github",n));return{id:"github",name:"Github",createAuthorizationURL({state:s,scopes:i}){let d=i||["user:email"];return o.createAuthorizationURL(s,d)},validateAuthorizationCode:s=>a(void 0,null,function*(){return yield o.validateAuthorizationCode(s)}),getUserInfo(s){return a(this,null,function*(){var u,l,p,m;let{data:i,error:d}=yield me("https://api.github.com/user",{auth:{type:"Bearer",token:s.accessToken()}});if(d)return null;let c=!1;if(!i.email){let{data:w,error:U}=yield me("https://api.github.com/user/emails",{auth:{type:"Bearer",token:s.accessToken()}});U||(i.email=(l=(u=w.find(T=>T.primary))!=null?u:w[0])==null?void 0:l.email,c=(m=(p=w.find(T=>T.email===i.email))==null?void 0:p.verified)!=null?m:!1)}return{user:{id:i.id,name:i.name,email:i.email,image:i.avatar_url,emailVerified:c,createdAt:new Date,updatedAt:new Date},data:i}})}}};import{Google as mt}from"arctic";import{parseJWT as ft}from"oslo/jwt";import{createConsola as ut}from"consola";var $=ut({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),pt=e=>({log:(...t)=>{!(e!=null&&e.disabled)&&$.log("",...t)},error:(...t)=>{!(e!=null&&e.disabled)&&$.error("",...t)},warn:(...t)=>{!(e!=null&&e.disabled)&&$.warn("",...t)},info:(...t)=>{!(e!=null&&e.disabled)&&$.info("",...t)},debug:(...t)=>{!(e!=null&&e.disabled)&&$.debug("",...t)},box:(...t)=>{!(e!=null&&e.disabled)&&$.box("",...t)},success:(...t)=>{!(e!=null&&e.disabled)&&$.success("",...t)},break:(...t)=>{!(e!=null&&e.disabled)&&console.log(`
2
- `)}}),_=pt();var ge=e=>{let t=new mt(e.clientId,e.clientSecret,y("google",e.redirectURI));return{id:"google",name:"Google",createAuthorizationURL({state:o,scopes:r,codeVerifier:s,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw _.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new D("CLIENT_ID_AND_SECRET_REQUIRED");if(!s)throw new D("codeVerifier is required for Google");let d=r||["email","profile"];return t.createAuthorizationURL(o,s,d)},validateAuthorizationCode:(o,r,s)=>a(void 0,null,function*(){return A({code:o,codeVerifier:r,redirectURI:s||y("google",e.redirectURI),options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"})}),getUserInfo(o){return a(this,null,function*(){var s;if(!o.idToken)return null;let r=(s=ft(o.idToken()))==null?void 0:s.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}})}}};import{betterFetch as gt}from"@better-fetch/fetch";import{Spotify as ht}from"arctic";var he=e=>{let t=new ht(e.clientId,e.clientSecret,y("spotify",e.redirectURI));return{id:"spotify",name:"Spotify",createAuthorizationURL({state:o,scopes:r}){let s=r||["user-read-email"];return t.createAuthorizationURL(o,s)},validateAuthorizationCode:(o,r,s)=>a(void 0,null,function*(){return A({code:o,codeVerifier:r,redirectURI:s||y("spotify",e.redirectURI),options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"})}),getUserInfo(o){return a(this,null,function*(){var i;let{data:r,error:s}=yield gt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken()}`}});return s?null:{user:{id:r.id,name:r.display_name,email:r.email,image:(i=r.images[0])==null?void 0:i.url,emailVerified:!1},data:r}})}}};import{betterFetch as yt}from"@better-fetch/fetch";import{Twitch as wt}from"arctic";var ye=e=>{let t=new wt(e.clientId,e.clientSecret,y("twitch",e.redirectURI));return{id:"twitch",name:"Twitch",createAuthorizationURL({state:o,scopes:r}){let s=r||["activity:write","read"];return t.createAuthorizationURL(o,s)},validateAuthorizationCode:(o,r,s)=>a(void 0,null,function*(){return A({code:o,codeVerifier:r,redirectURI:s||y("twitch",e.redirectURI),options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"})}),getUserInfo(o){return a(this,null,function*(){let{data:r,error:s}=yield yt("https://api.twitch.tv/helix/users",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken()}`}});return s?null:{user:{id:r.sub,name:r.preferred_username,email:r.email,image:r.picture,emailVerified:!1},data:r}})}}};import{betterFetch as bt}from"@better-fetch/fetch";import{Twitter as kt}from"arctic";var we=e=>{let t=new kt(e.clientId,e.clientSecret,y("twitter",e.redirectURI));return{id:"twitter",name:"Twitter",createAuthorizationURL(o){let r=o.scopes||["account_info.read"];return t.createAuthorizationURL(o.state,o.codeVerifier,r)},validateAuthorizationCode:(o,r,s)=>a(void 0,null,function*(){return A({code:o,codeVerifier:r,redirectURI:s||y("twitch",e.redirectURI),options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"})}),getUserInfo(o){return a(this,null,function*(){let{data:r,error:s}=yield bt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken()}`}});return s||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}})}}};import"arctic";var At={apple:le,discord:ue,facebook:pe,github:fe,google:ge,spotify:he,twitch:ye,twitter:we},be=Object.keys(At);import{generateState as Rt}from"oslo/oauth2";import{z as q}from"zod";function ke(e,t,n){let o=Rt();return{state:JSON.stringify({code:o,callbackURL:e,currentURL:t,dontRememberMe:n}),code:o}}function W(e){return q.object({code:q.string(),callbackURL:q.string().optional(),currentURL:q.string().optional(),dontRememberMe:q.boolean().optional()}).safeParse(JSON.parse(e))}import{APIError as Ut}from"better-call";var Ae=(e,t=!1)=>{let n=new Date;return new Date(n.getTime()+(t?e*1e3:e))};import{TimeSpan as Zo}from"oslo";function P(e,t,n,o){return a(this,null,function*(){let r=e.context.authCookies.sessionToken.options;r.maxAge=n?void 0:r.maxAge,yield e.setSignedCookie(e.context.authCookies.sessionToken.name,t,e.context.secret,r),n&&(yield e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options))})}function V(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}import{z as Re}from"zod";function N(e){let t="127.0.0.1";if(process.env.NODE_ENV==="test")return t;let n=["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 n){let r=e.headers.get(o);if(typeof r=="string"){let s=r.split(",")[0].trim();if(s)return s}}return null}var J=new Map;function Tt(e,t){if(!e.request)return"";let{method:n,url:o,headers:r}=e.request,s=e.request.headers.get("User-Agent")||"",i=N(e.request)||"",d=JSON.stringify(r);return`${n}:${o}:${d}:${s}:${i}:${t}`}var Z=()=>f("/session",{method:"GET",requireHeaders:!0},e=>a(void 0,null,function*(){try{let t=yield e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let n=Tt(e,t),o=J.get(n);if(o){if(o.expiresAt>Date.now())return e.json(o.data);J.delete(n)}let r=yield e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return V(e),r&&(yield e.context.internalAdapter.deleteSession(r.session.id)),e.json(null,{status:401});if(yield e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(r);let i=e.context.sessionConfig.expiresIn,d=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-i*1e3+d*1e3<=Date.now()){let l=yield e.context.internalAdapter.updateSession(r.session.id,{expiresAt:Ae(e.context.sessionConfig.expiresIn,!0)});if(!l)return V(e),e.json(null,{status:401});let p=(l.expiresAt.valueOf()-Date.now())/1e3;return yield P(e,l.id,!1,{maxAge:p}),e.json({session:l,user:r.user})}return J.set(n,{data:r,expiresAt:Date.now()+5e3}),e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}})),K=e=>a(void 0,null,function*(){return yield Z()(k(g({},e),{_flag:void 0}))}),B=H(e=>a(void 0,null,function*(){let t=yield K(e);if(!(t!=null&&t.session))throw new Ut("UNAUTHORIZED");return{session:t}})),Ue=()=>f("/user/list-sessions",{method:"GET",use:[B],requireHeaders:!0},e=>a(void 0,null,function*(){let n=(yield e.context.adapter.findMany({model:e.context.tables.session.tableName,where:[{field:"userId",value:e.context.session.user.id}]})).filter(o=>o.expiresAt>new Date);return e.json(n)})),Te=f("/user/revoke-session",{method:"POST",body:Re.object({id:Re.string()}),use:[B],requireHeaders:!0},e=>a(void 0,null,function*(){let t=e.body.id,n=yield e.context.internalAdapter.findSession(t);if(!n)return e.json(null,{status:400});if(n.session.userId!==e.context.session.user.id)return e.json(null,{status:403});try{yield e.context.internalAdapter.deleteSession(t)}catch(o){return e.context.logger.error(o),e.json(null,{status:500})}return e.json({status:!0})})),ve=f("/user/revoke-sessions",{method:"POST",use:[B],requireHeaders:!0},e=>a(void 0,null,function*(){try{yield e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}return e.json({status:!0})}));var xe=f("/sign-in/social",{method:"POST",requireHeaders:!0,query:v.object({currentURL:v.string().optional()}).optional(),body:v.object({callbackURL:v.string().optional(),provider:v.enum(be),dontRememberMe:v.boolean().default(!1).optional()})},e=>a(void 0,null,function*(){var i,d,c,u;let t=e.context.socialProviders.find(l=>l.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider to your auth config",{provider:e.body.provider}),new E("NOT_FOUND",{message:"Provider not found"});let n=e.context.authCookies,o=(i=e.query)!=null&&i.currentURL?new URL((d=e.query)==null?void 0:d.currentURL):null,r=(c=e.body.callbackURL)!=null&&c.startsWith("http")?e.body.callbackURL:`${o==null?void 0:o.origin}${e.body.callbackURL||""}`,s=ke(r||(o==null?void 0:o.origin)||e.context.baseURL,(u=e.query)==null?void 0:u.currentURL);try{yield e.setSignedCookie(n.state.name,s.code,e.context.secret,n.state.options);let l=vt();yield e.setSignedCookie(n.pkCodeVerifier.name,l,e.context.secret,n.pkCodeVerifier.options);let p=t.createAuthorizationURL({state:s.state,codeVerifier:l});return p.searchParams.set("redirect_uri",`${e.context.baseURL}/callback/${e.body.provider}`),{url:p.toString(),state:s.state,codeVerifier:l,redirect:!0}}catch(l){throw new E("INTERNAL_SERVER_ERROR")}})),Pe=f("/sign-in/email",{method:"POST",body:v.object({email:v.string().email(),password:v.string(),callbackURL:v.string().optional(),dontRememberMe:v.boolean().default(!1).optional()})},e=>a(void 0,null,function*(){var l,p;if(!((p=(l=e.context.options)==null?void 0:l.emailAndPassword)!=null&&p.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("BAD_REQUEST",{message:"Email and password is not enabled"});let t=yield K(e);t&&(yield e.context.internalAdapter.deleteSession(t.session.id));let{email:n,password:o}=e.body;if(!v.string().email().safeParse(n).success)throw new E("BAD_REQUEST",{message:"Invalid email"});let s=yield e.context.internalAdapter.findUserByEmail(n);if(!s)throw yield e.context.password.hash(o),e.context.logger.error("User not found",{email:n}),new E("UNAUTHORIZED",{message:"Invalid email or password"});let i=s.accounts.find(m=>m.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:n}),new E("UNAUTHORIZED",{message:"Invalid email or password"});let d=i==null?void 0:i.password;if(!d)throw e.context.logger.error("Password not found",{email:n}),new E("UNAUTHORIZED",{message:"Unexpected error"});if(!(yield e.context.password.verify(d,o)))throw e.context.logger.error("Invalid password"),new E("UNAUTHORIZED",{message:"Invalid email or password"});let u=yield e.context.internalAdapter.createSession(s.user.id,e.headers,e.body.dontRememberMe);return yield P(e,u.id,e.body.dontRememberMe),e.json({user:s.user,session:u,redirect:!!e.body.callbackURL,url:e.body.callbackURL})}));import{APIError as St}from"better-call";import{z as F}from"zod";import{z as h}from"zod";var bn=h.object({id:h.string(),providerId:h.string(),accountId:h.string(),userId:h.string(),accessToken:h.string().nullable().optional(),refreshToken:h.string().nullable().optional(),idToken:h.string().nullable().optional(),expiresAt:h.date().nullable().optional(),password:h.string().optional().nullable()}),Se=h.object({id:h.string(),email:h.string().transform(e=>e.toLowerCase()),emailVerified:h.boolean().default(!1),name:h.string(),image:h.string().optional(),createdAt:h.date().default(new Date),updatedAt:h.date().default(new Date)}),kn=h.object({id:h.string(),userId:h.string(),expiresAt:h.date(),ipAddress:h.string().optional(),userAgent:h.string().optional()});import{alphabet as xt,generateRandomString as Pt}from"oslo/crypto";var _e=()=>Pt(36,xt("a-z","0-9"));var C={isAction:!1};function Q(e){let t=e.accessToken(),n=e.hasRefreshToken()?e.refreshToken():void 0,o;try{o=e.accessTokenExpiresAt()}catch(r){}return{accessToken:t,refreshToken:n,expiresAt:o}}var Ie=f("/callback/:id",{method:"GET",query:F.object({state:F.string(),code:F.string().optional(),error:F.string().optional()}),metadata:C},e=>a(void 0,null,function*(){var U,T,O;if(e.query.error||!e.query.code){let R=((U=W(e.query.state).data)==null?void 0:U.callbackURL)||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${R}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(b=>b.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 n=yield e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),o;try{o=yield t.validateAuthorizationCode(e.query.code,n,`${e.context.baseURL}/callback/${t.id}`)}catch(b){throw e.context.logger.error(b),e.redirect(`${e.context.baseURL}/error?error=oauth_code_verification_failed`)}let r=yield t.getUserInfo(o).then(b=>b==null?void 0:b.user),s=_e(),i=Se.safeParse(k(g({},r),{id:s})),d=W(e.query.state);if(!d.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=invalid_state_parameter`);let{callbackURL:c,currentURL:u,dontRememberMe:l}=d.data;if(!r||i.success===!1)throw e.redirect(`${e.context.baseURL}/error?error=oauth_validation_failed`);if(!c)throw e.redirect(`${e.context.baseURL}/error?error=oauth_callback_url_not_found`);let p=yield e.context.internalAdapter.findUserByEmail(r.email),m=p==null?void 0:p.user.id;if(p){let b=p.accounts.find(j=>j.providerId===t.id),R=(O=(T=e.context.options.account)==null?void 0:T.accountLinking)==null?void 0:O.trustedProviders,z=R?R.includes(t.id):!0,te=!b&&r.emailVerified&&z;if(!te){let j;try{j=new URL(u||c),j.searchParams.set("error","account_not_linked")}catch(Zt){throw e.redirect(`${e.context.baseURL}/error?error=account_not_linked`)}throw e.redirect(j.toString())}if(te)try{yield e.context.internalAdapter.linkAccount(g({providerId:t.id,accountId:r.id,id:`${t.id}:${r.id}`,userId:p.user.id},Q(o)))}catch(j){throw console.log(j),e.redirect(`${e.context.baseURL}/error?error=failed_linking_account`)}}else try{yield e.context.internalAdapter.createOAuthUser(i.data,k(g({},Q(o)),{id:`${t.id}:${r.id}`,providerId:t.id,accountId:r.id,userId:s}))}catch(b){let R=new URL(u||c);throw R.searchParams.set("error","unable_to_create_user"),e.setHeader("Location",R.toString()),e.redirect(R.toString())}if(!m&&!s)throw new St("INTERNAL_SERVER_ERROR",{message:"Unable to create user"});let w=yield e.context.internalAdapter.createSession(m||s,e.request,l);try{yield P(e,w.id,l)}catch(b){e.context.logger.error("Unable to set session cookie",b);let R=new URL(u||c);throw R.searchParams.set("error","unable_to_create_session"),e.redirect(R.toString())}throw e.redirect(c)}));import{z as X}from"zod";var Le=f("/sign-out",{method:"POST",body:X.optional(X.object({callbackURL:X.string().optional()}))},e=>a(void 0,null,function*(){var n,o;let t=yield e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);return t?(yield e.context.internalAdapter.deleteSession(t),V(e),e.json(null,{body:{redirect:!!((n=e.body)!=null&&n.callbackURL),url:(o=e.body)==null?void 0:o.callbackURL}})):e.json(null)}));import{TimeSpan as _t}from"oslo";import{createJWT as It,parseJWT as Lt}from"oslo/jwt";import{validateJWT as Oe}from"oslo/jwt";import{z as x}from"zod";var Ee=f("/forget-password",{method:"POST",body:x.object({email:x.string().email(),redirectTo:x.string()})},e=>a(void 0,null,function*(){var s;if(!((s=e.context.options.emailAndPassword)!=null&&s.sendResetPassword))return e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function to your auth config!"),e.json(null,{status:400,statusText:"RESET_PASSWORD_EMAIL_NOT_SENT",body:{message:"Reset password isn't enabled"}});let{email:t}=e.body,n=yield e.context.internalAdapter.findUserByEmail(t);if(!n)return e.json({status:!1},{body:{status:!0}});let o=yield It("HS256",Buffer.from(e.context.secret),{email:n.user.email,redirectTo:e.body.redirectTo},{expiresIn:new _t(1,"h"),issuer:"better-auth",subject:"forget-password",audiences:[n.user.email],includeIssuedTimestamp:!0}),r=`${e.context.baseURL}/reset-password/${o}`;return yield e.context.options.emailAndPassword.sendResetPassword(r,n.user),e.json({status:!0})})),Ce=f("/reset-password/:token",{method:"GET"},e=>a(void 0,null,function*(){var s;let{token:t}=e.params,n,o=x.object({email:x.string(),redirectTo:x.string()});try{if(n=yield Oe("HS256",Buffer.from(e.context.secret),t),!n.expiresAt||n.expiresAt<new Date)throw Error("Token expired")}catch(i){let d=Lt(t),c=o.safeParse(d==null?void 0:d.payload);throw c.success?e.redirect(`${(s=c.data)==null?void 0:s.redirectTo}?error=invalid_token`):e.redirect(`${e.context.baseURL}/error?error=invalid_token`)}let{redirectTo:r}=o.parse(n.payload);throw e.redirect(`${r}?token=${t}`)})),je=f("/reset-password",{method:"POST",query:x.object({currentURL:x.string()}).optional(),body:x.object({newPassword:x.string(),callbackURL:x.string().optional()})},e=>a(void 0,null,function*(){var o,r,s;let t=(o=e.query)==null?void 0:o.currentURL.split("?token=")[1];if(!t)return e.json({error:"Invalid token",data:null},{status:400,statusText:"INVALID_TOKEN",body:{message:"Invalid token"}});let{newPassword:n}=e.body;try{let i=yield Oe("HS256",Buffer.from(e.context.secret),t),d=x.string().email().parse(i.payload.email),c=yield e.context.internalAdapter.findUserByEmail(d);if(!c)return e.json({error:"User not found",data:null},{status:400,body:{message:"failed to reset password"}});if(n.length<(((r=e.context.options.emailAndPassword)==null?void 0:r.minPasswordLength)||8)||n.length>(((s=e.context.options.emailAndPassword)==null?void 0:s.maxPasswordLength)||32))return e.json({data:null,error:"password is too short or too long"},{status:400,statusText:"INVALID_PASSWORD_LENGTH",body:{message:"password is too short or too long"}});let u=yield e.context.password.hash(n);return(yield e.context.internalAdapter.updatePassword(c.user.id,u))?e.json({error:null,data:{status:!0,url:e.body.callbackURL,redirect:!!e.body.callbackURL}},{body:{status:!0,url:e.body.callbackURL,redirect:!!e.body.callbackURL}}):e.json(null,{status:400,statusText:"USER_NOT_FOUND",body:{message:"User doesn't have a credential account"}})}catch(i){return console.log(i),e.json({error:"Invalid token",data:null},{status:400,statusText:"INVALID_TOKEN",body:{message:"Invalid token"}})}}));import{TimeSpan as Ot}from"oslo";import{createJWT as Et,validateJWT as Ct}from"oslo/jwt";import{z as S}from"zod";function Y(e,t){return a(this,null,function*(){return yield Et("HS256",Buffer.from(e),{email:t.toLowerCase()},{expiresIn:new Ot(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})})}var De=f("/send-verification-email",{method:"POST",query:S.object({currentURL:S.string().optional()}).optional(),body:S.object({email:S.string().email(),callbackURL:S.string().optional()})},e=>a(void 0,null,function*(){var r,s;if(!((r=e.context.options.emailAndPassword)!=null&&r.sendVerificationEmail))return e.context.logger.error("Verification email isn't enabled. Pass `sendVerificationEmail` in `emailAndPassword` options to enable it."),e.json(null,{status:400,statusText:"VERIFICATION_EMAIL_NOT_SENT",body:{message:"Verification email isn't enabled"}});let{email:t}=e.body,n=yield Y(e.context.secret,t),o=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${e.body.callbackURL||((s=e.query)==null?void 0:s.currentURL)||"/"}`;return yield e.context.options.emailAndPassword.sendVerificationEmail(t,o,n),e.json({status:!0})})),$e=f("/verify-email",{method:"GET",query:S.object({token:S.string(),callbackURL:S.string().optional()})},e=>a(void 0,null,function*(){let{token:t}=e.query,n;try{n=yield Ct("HS256",Buffer.from(e.context.secret),t)}catch(d){return e.context.logger.error("Failed to verify email",d),e.json(null,{status:400,statusText:"INVALID_TOKEN",body:{message:"Invalid token"}})}let r=S.object({email:S.string().email()}).parse(n.payload),s=yield e.context.internalAdapter.findUserByEmail(r.email);if(!s)return e.json(null,{status:400,statusText:"USER_NOT_FOUND",body:{message:"User not found"}});if(!s.accounts.find(d=>d.providerId==="credential"))throw e.redirect;if(yield e.context.internalAdapter.updateUserByEmail(r.email,{emailVerified:!0}),e.query.callbackURL)throw console.log("Redirecting to",e.query.callbackURL),e.redirect("/");return e.json({status:!0})}));import{z as I}from"zod";import{alphabet as jt,generateRandomString as Dt}from"oslo/crypto";import"better-call";var Be=f("/user/update",{method:"POST",body:I.object({name:I.string().optional(),image:I.string().optional()}),use:[B]},e=>a(void 0,null,function*(){let{name:t,image:n}=e.body,o=e.context.session;if(!n&&!t)return e.json(o.user);let r=yield e.context.internalAdapter.updateUserByEmail(o.user.email,{name:t,image:n});return e.json(r)})),ze=f("/user/change-password",{method:"POST",body:I.object({newPassword:I.string(),currentPassword:I.string(),revokeOtherSessions:I.boolean().optional()}),use:[B]},e=>a(void 0,null,function*(){let{newPassword:t,currentPassword:n,revokeOtherSessions:o}=e.body,r=e.context.session,s=e.context.password.config.minPasswordLength;if(t.length<s)return e.context.logger.error("Password is too short"),e.json(null,{status:400,body:{message:"Password is too short"}});let i=e.context.password.config.maxPasswordLength;if(t.length>i)return e.context.logger.error("Password is too long"),e.json(null,{status:400,body:{message:"Password is too long"}});let c=(yield e.context.internalAdapter.findAccounts(r.user.id)).find(p=>p.providerId==="credential"&&p.password);if(!c||!c.password)return e.json(null,{status:400,body:{message:"User does not have a password"}});let u=yield e.context.password.hash(t);if(!(yield e.context.password.verify(c.password,n)))return e.json(null,{status:400,body:{message:"Invalid password"}});if(yield e.context.internalAdapter.updateAccount(c.id,{password:u}),o){yield e.context.internalAdapter.deleteSessions(r.user.id);let p=yield e.context.internalAdapter.createSession(r.user.id,e.headers);yield P(e,p.id)}return e.json(r.user)})),qe=f("/user/set-password",{method:"POST",body:I.object({newPassword:I.string()}),use:[B]},e=>a(void 0,null,function*(){let{newPassword:t}=e.body,n=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)return e.context.logger.error("Password is too short"),e.json(null,{status:400,body:{message:"Password is too short"}});let r=e.context.password.config.maxPasswordLength;if(t.length>r)return e.context.logger.error("Password is too long"),e.json(null,{status:400,body:{message:"Password is too long"}});let i=(yield e.context.internalAdapter.findAccounts(n.user.id)).find(c=>c.providerId==="credential"&&c.password),d=yield e.context.password.hash(t);return i?e.json(null,{status:400,body:{message:"User already has a password"}}):(yield e.context.internalAdapter.linkAccount({id:Dt(32,jt("a-z","0-9","A-Z")),userId:n.user.id,providerId:"credential",accountId:n.user.id,password:d}),e.json(n.user))}));import{alphabet as $t,generateRandomString as Bt}from"oslo/crypto";var Ve=f("/csrf",{method:"GET",metadata:C},e=>a(void 0,null,function*(){let t=yield e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t)return{csrfToken:t};let n=Bt(32,$t("a-z","0-9","A-Z")),o=yield M(e.context.secret,n),r=`${n}!${o}`;return yield e.setSignedCookie(e.context.authCookies.csrfToken.name,r,e.context.secret,e.context.authCookies.csrfToken.options),{csrfToken:n}}));var zt=(e="Unknown")=>`<!DOCTYPE html>
1
+ var Je=Object.defineProperty,Ze=Object.defineProperties;var Ke=Object.getOwnPropertyDescriptors;var te=Object.getOwnPropertySymbols;var Qe=Object.prototype.hasOwnProperty,Xe=Object.prototype.propertyIsEnumerable;var re=(e,t,n)=>t in e?Je(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,g=(e,t)=>{for(var n in t||(t={}))Qe.call(t,n)&&re(e,n,t[n]);if(te)for(var n of te(t))Xe.call(t,n)&&re(e,n,t[n]);return e},k=(e,t)=>Ze(e,Ke(t));var a=(e,t,n)=>new Promise((o,r)=>{var s=c=>{try{d(n.next(c))}catch(u){r(u)}},i=c=>{try{d(n.throw(c))}catch(u){r(u)}},d=c=>c.done?o(c.value):Promise.resolve(c.value).then(s,i);d((n=n.apply(e,t)).next())});import{APIError as Ft,createRouter as Gt}from"better-call";import{APIError as se}from"better-call";import{z as ie}from"zod";import{xchacha20poly1305 as Qt}from"@noble/ciphers/chacha";import{bytesToHex as Yt,hexToBytes as er,utf8ToBytes as tr}from"@noble/ciphers/utils";import{managedNonce as or}from"@noble/ciphers/webcrypto";import{sha256 as sr}from"@noble/hashes/sha256";function M(e,t){return a(this,null,function*(){let n=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},r=yield crypto.subtle.importKey("raw",n.encode(e),o,!1,["sign","verify"]),s=yield crypto.subtle.sign(o.name,r,n.encode(t));return btoa(String.fromCharCode(...new Uint8Array(s)))})}import{createEndpointCreator as Ye,createMiddleware as oe,createMiddlewareCreator as et}from"better-call";var ne=oe(()=>a(void 0,null,function*(){return{}})),H=et({use:[ne,oe(()=>a(void 0,null,function*(){return{}}))]}),f=Ye({use:[ne]});var ae=H({body:ie.object({csrfToken:ie.string().optional()}).optional()},e=>a(void 0,null,function*(){var d,c,u,l;if(((d=e.request)==null?void 0:d.method)!=="POST"||(c=e.context.options.advanced)!=null&&c.disableCSRFCheck)return;let t=new URL(e.request.url);if(t.origin===new URL(e.context.baseURL).origin||(u=e.context.options.trustedOrigins)!=null&&u.includes(t.origin))return;let n=(l=e.body)==null?void 0:l.csrfToken,o=yield e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[r,s]=(o==null?void 0:o.split("!"))||[null,null];if(!n||!o||!r||!s||o!==n)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new se("UNAUTHORIZED",{message:"Invalid CSRF Token"});let i=yield M(e.context.secret,r);if(s!==i)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new se("UNAUTHORIZED",{message:"Invalid CSRF Token"})}));import{APIError as E}from"better-call";import{generateCodeVerifier as Tt}from"oslo/oauth2";import{z as v}from"zod";import"arctic";import{parseJWT as nt}from"oslo/jwt";import"@better-fetch/fetch";var D=class extends Error{constructor(t,n,o){super(t),this.name="BetterAuthError",this.message=t,this.cause=n}};import{OAuth2Tokens as rt}from"arctic";function tt(e){try{return new URL(e).pathname!=="/"}catch(t){throw new D(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function G(e,t="/api/auth"){return tt(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function de(e,t){if(e)return G(e,t);let n=(process==null?void 0:process.env)||{},o=n.BETTER_AUTH_URL||n.NEXT_PUBLIC_BETTER_AUTH_URL||n.PUBLIC_BETTER_AUTH_URL||n.NUXT_PUBLIC_BETTER_AUTH_URL||n.NUXT_PUBLIC_AUTH_URL||(n.BASE_URL!=="/"?n.BASE_URL:void 0);if(o)return G(o,t);if(typeof window!="undefined")return G(window.location.origin,t)}import{betterFetch as ot}from"@better-fetch/fetch";function y(e,t){return t||`${de()}/callback/${e}`}function A(s){return a(this,arguments,function*({code:e,codeVerifier:t,redirectURI:n,options:o,tokenEndpoint:r}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",n),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:d,error:c}=yield ot(r,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(c)throw c;return new rt(d)})}var ce=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:o,scopes:r,redirectURI:s}){let i=r||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${s||e.redirectURI}&scope=${i.join(" ")}&state=${o}`)},validateAuthorizationCode:(o,r,s)=>a(void 0,null,function*(){return A({code:o,codeVerifier:r,redirectURI:s||y("apple",e.redirectURI),options:e,tokenEndpoint:t})}),getUserInfo(o){return a(this,null,function*(){var s;let r=(s=nt(o.idToken()))==null?void 0:s.payload;return r?{user:{id:r.sub,name:r.name,email:r.email,emailVerified:r.email_verified==="true"},data:r}:null})}}};import{betterFetch as st}from"@better-fetch/fetch";import{Discord as it}from"arctic";var le=e=>{let t=new it(e.clientId,e.clientSecret,y("discord",e.redirectURI));return{id:"discord",name:"Discord",createAuthorizationURL({state:o,scopes:r}){let s=r||["email"];return t.createAuthorizationURL(o,s)},validateAuthorizationCode:(o,r,s)=>a(void 0,null,function*(){return A({code:o,codeVerifier:r,redirectURI:s||y("discord",e.redirectURI),options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"})}),getUserInfo(o){return a(this,null,function*(){let{data:r,error:s}=yield st("https://discord.com/api/users/@me",{auth:{type:"Bearer",token:o.accessToken()}});return s?null:{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified},data:r}})}}};import{betterFetch as at}from"@better-fetch/fetch";import{Facebook as dt}from"arctic";var ue=e=>{let t=new dt(e.clientId,e.clientSecret,y("facebook",e.redirectURI));return{id:"facebook",name:"Facebook",createAuthorizationURL({state:o,scopes:r}){let s=r||["email","public_profile"];return t.createAuthorizationURL(o,s)},validateAuthorizationCode:(o,r,s)=>a(void 0,null,function*(){return A({code:o,codeVerifier:r,redirectURI:s||y("facebook",e.redirectURI),options:e,tokenEndpoint:"https://graph.facebook.com/v16.0/oauth/access_token"})}),getUserInfo(o){return a(this,null,function*(){let{data:r,error:s}=yield at("https://graph.facebook.com/me",{auth:{type:"Bearer",token:o.accessToken()}});return s?null:{user:{id:r.id,name:r.name,email:r.email,emailVerified:r.email_verified},data:r}})}}};import{betterFetch as pe}from"@better-fetch/fetch";import{GitHub as ct}from"arctic";var me=({clientId:e,clientSecret:t,redirectURI:n})=>{let o=new ct(e,t,y("github",n));return{id:"github",name:"Github",createAuthorizationURL({state:s,scopes:i}){let d=i||["user:email"];return o.createAuthorizationURL(s,d)},validateAuthorizationCode:s=>a(void 0,null,function*(){return yield o.validateAuthorizationCode(s)}),getUserInfo(s){return a(this,null,function*(){var u,l,p,m;let{data:i,error:d}=yield pe("https://api.github.com/user",{auth:{type:"Bearer",token:s.accessToken()}});if(d)return null;let c=!1;if(!i.email){let{data:w,error:U}=yield pe("https://api.github.com/user/emails",{auth:{type:"Bearer",token:s.accessToken()}});U||(i.email=(l=(u=w.find(T=>T.primary))!=null?u:w[0])==null?void 0:l.email,c=(m=(p=w.find(T=>T.email===i.email))==null?void 0:p.verified)!=null?m:!1)}return{user:{id:i.id,name:i.name,email:i.email,image:i.avatar_url,emailVerified:c,createdAt:new Date,updatedAt:new Date},data:i}})}}};import{Google as pt}from"arctic";import{parseJWT as mt}from"oslo/jwt";import{createConsola as lt}from"consola";var $=lt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),ut=e=>({log:(...t)=>{!(e!=null&&e.disabled)&&$.log("",...t)},error:(...t)=>{!(e!=null&&e.disabled)&&$.error("",...t)},warn:(...t)=>{!(e!=null&&e.disabled)&&$.warn("",...t)},info:(...t)=>{!(e!=null&&e.disabled)&&$.info("",...t)},debug:(...t)=>{!(e!=null&&e.disabled)&&$.debug("",...t)},box:(...t)=>{!(e!=null&&e.disabled)&&$.box("",...t)},success:(...t)=>{!(e!=null&&e.disabled)&&$.success("",...t)},break:(...t)=>{!(e!=null&&e.disabled)&&console.log(`
2
+ `)}}),_=ut();var fe=e=>{let t=new pt(e.clientId,e.clientSecret,y("google",e.redirectURI));return{id:"google",name:"Google",createAuthorizationURL({state:o,scopes:r,codeVerifier:s,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw _.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new D("CLIENT_ID_AND_SECRET_REQUIRED");if(!s)throw new D("codeVerifier is required for Google");let d=r||["email","profile"];return t.createAuthorizationURL(o,s,d)},validateAuthorizationCode:(o,r,s)=>a(void 0,null,function*(){return A({code:o,codeVerifier:r,redirectURI:s||y("google",e.redirectURI),options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"})}),getUserInfo(o){return a(this,null,function*(){var s;if(!o.idToken)return null;let r=(s=mt(o.idToken()))==null?void 0:s.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}})}}};import{betterFetch as ft}from"@better-fetch/fetch";import{Spotify as gt}from"arctic";var ge=e=>{let t=new gt(e.clientId,e.clientSecret,y("spotify",e.redirectURI));return{id:"spotify",name:"Spotify",createAuthorizationURL({state:o,scopes:r}){let s=r||["user-read-email"];return t.createAuthorizationURL(o,s)},validateAuthorizationCode:(o,r,s)=>a(void 0,null,function*(){return A({code:o,codeVerifier:r,redirectURI:s||y("spotify",e.redirectURI),options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"})}),getUserInfo(o){return a(this,null,function*(){var i;let{data:r,error:s}=yield ft("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken()}`}});return s?null:{user:{id:r.id,name:r.display_name,email:r.email,image:(i=r.images[0])==null?void 0:i.url,emailVerified:!1},data:r}})}}};import{betterFetch as ht}from"@better-fetch/fetch";import{Twitch as yt}from"arctic";var he=e=>{let t=new yt(e.clientId,e.clientSecret,y("twitch",e.redirectURI));return{id:"twitch",name:"Twitch",createAuthorizationURL({state:o,scopes:r}){let s=r||["activity:write","read"];return t.createAuthorizationURL(o,s)},validateAuthorizationCode:(o,r,s)=>a(void 0,null,function*(){return A({code:o,codeVerifier:r,redirectURI:s||y("twitch",e.redirectURI),options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"})}),getUserInfo(o){return a(this,null,function*(){let{data:r,error:s}=yield ht("https://api.twitch.tv/helix/users",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken()}`}});return s?null:{user:{id:r.sub,name:r.preferred_username,email:r.email,image:r.picture,emailVerified:!1},data:r}})}}};import{betterFetch as wt}from"@better-fetch/fetch";import{Twitter as bt}from"arctic";var ye=e=>{let t=new bt(e.clientId,e.clientSecret,y("twitter",e.redirectURI));return{id:"twitter",name:"Twitter",createAuthorizationURL(o){let r=o.scopes||["account_info.read"];return t.createAuthorizationURL(o.state,o.codeVerifier,r)},validateAuthorizationCode:(o,r,s)=>a(void 0,null,function*(){return A({code:o,codeVerifier:r,redirectURI:s||y("twitch",e.redirectURI),options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"})}),getUserInfo(o){return a(this,null,function*(){let{data:r,error:s}=yield wt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken()}`}});return s||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}})}}};import"arctic";var kt={apple:ce,discord:le,facebook:ue,github:me,google:fe,spotify:ge,twitch:he,twitter:ye},we=Object.keys(kt);import{generateState as At}from"oslo/oauth2";import{z as q}from"zod";function be(e,t,n){let o=At();return{state:JSON.stringify({code:o,callbackURL:e,currentURL:t,dontRememberMe:n}),code:o}}function W(e){return q.object({code:q.string(),callbackURL:q.string().optional(),currentURL:q.string().optional(),dontRememberMe:q.boolean().optional()}).safeParse(JSON.parse(e))}import{APIError as Rt}from"better-call";var ke=(e,t=!1)=>{let n=new Date;return new Date(n.getTime()+(t?e*1e3:e))};import{TimeSpan as Jo}from"oslo";function x(e,t,n,o){return a(this,null,function*(){let r=e.context.authCookies.sessionToken.options;r.maxAge=n?void 0:r.maxAge,yield e.setSignedCookie(e.context.authCookies.sessionToken.name,t,e.context.secret,r),n&&(yield e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options))})}function V(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}import{z as Ae}from"zod";function N(e){let t="127.0.0.1";if(process.env.NODE_ENV==="test")return t;let n=["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 n){let r=e.headers.get(o);if(typeof r=="string"){let s=r.split(",")[0].trim();if(s)return s}}return null}var J=new Map;function Ut(e,t){if(!e.request)return"";let{method:n,url:o,headers:r}=e.request,s=e.request.headers.get("User-Agent")||"",i=N(e.request)||"",d=JSON.stringify(r);return`${n}:${o}:${d}:${s}:${i}:${t}`}var Z=()=>f("/session",{method:"GET",requireHeaders:!0},e=>a(void 0,null,function*(){try{let t=yield e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let n=Ut(e,t),o=J.get(n);if(o){if(o.expiresAt>Date.now())return e.json(o.data);J.delete(n)}let r=yield e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return V(e),r&&(yield e.context.internalAdapter.deleteSession(r.session.id)),e.json(null,{status:401});if(yield e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(r);let i=e.context.sessionConfig.expiresIn,d=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-i*1e3+d*1e3<=Date.now()){let l=yield e.context.internalAdapter.updateSession(r.session.id,{expiresAt:ke(e.context.sessionConfig.expiresIn,!0)});if(!l)return V(e),e.json(null,{status:401});let p=(l.expiresAt.valueOf()-Date.now())/1e3;return yield x(e,l.id,!1,{maxAge:p}),e.json({session:l,user:r.user})}return J.set(n,{data:r,expiresAt:Date.now()+5e3}),e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}})),K=e=>a(void 0,null,function*(){return yield Z()(k(g({},e),{_flag:void 0}))}),B=H(e=>a(void 0,null,function*(){let t=yield K(e);if(!(t!=null&&t.session))throw new Rt("UNAUTHORIZED");return{session:t}})),Re=()=>f("/user/list-sessions",{method:"GET",use:[B],requireHeaders:!0},e=>a(void 0,null,function*(){let n=(yield e.context.adapter.findMany({model:e.context.tables.session.tableName,where:[{field:"userId",value:e.context.session.user.id}]})).filter(o=>o.expiresAt>new Date);return e.json(n)})),Ue=f("/user/revoke-session",{method:"POST",body:Ae.object({id:Ae.string()}),use:[B],requireHeaders:!0},e=>a(void 0,null,function*(){let t=e.body.id,n=yield e.context.internalAdapter.findSession(t);if(!n)return e.json(null,{status:400});if(n.session.userId!==e.context.session.user.id)return e.json(null,{status:403});try{yield e.context.internalAdapter.deleteSession(t)}catch(o){return e.context.logger.error(o),e.json(null,{status:500})}return e.json({status:!0})})),Te=f("/user/revoke-sessions",{method:"POST",use:[B],requireHeaders:!0},e=>a(void 0,null,function*(){try{yield e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}return e.json({status:!0})}));var ve=f("/sign-in/social",{method:"POST",requireHeaders:!0,query:v.object({currentURL:v.string().optional()}).optional(),body:v.object({callbackURL:v.string().optional(),provider:v.enum(we),dontRememberMe:v.boolean().default(!1).optional()})},e=>a(void 0,null,function*(){var i,d,c,u;let t=e.context.socialProviders.find(l=>l.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider to your auth config",{provider:e.body.provider}),new E("NOT_FOUND",{message:"Provider not found"});let n=e.context.authCookies,o=(i=e.query)!=null&&i.currentURL?new URL((d=e.query)==null?void 0:d.currentURL):null,r=(c=e.body.callbackURL)!=null&&c.startsWith("http")?e.body.callbackURL:`${o==null?void 0:o.origin}${e.body.callbackURL||""}`,s=be(r||(o==null?void 0:o.origin)||e.context.baseURL,(u=e.query)==null?void 0:u.currentURL);try{yield e.setSignedCookie(n.state.name,s.code,e.context.secret,n.state.options);let l=Tt();yield e.setSignedCookie(n.pkCodeVerifier.name,l,e.context.secret,n.pkCodeVerifier.options);let p=t.createAuthorizationURL({state:s.state,codeVerifier:l});return p.searchParams.set("redirect_uri",`${e.context.baseURL}/callback/${e.body.provider}`),{url:p.toString(),state:s.state,codeVerifier:l,redirect:!0}}catch(l){throw new E("INTERNAL_SERVER_ERROR")}})),Pe=f("/sign-in/email",{method:"POST",body:v.object({email:v.string().email(),password:v.string(),callbackURL:v.string().optional(),dontRememberMe:v.boolean().default(!1).optional()})},e=>a(void 0,null,function*(){var l,p;if(!((p=(l=e.context.options)==null?void 0:l.emailAndPassword)!=null&&p.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("BAD_REQUEST",{message:"Email and password is not enabled"});let t=yield K(e);t&&(yield e.context.internalAdapter.deleteSession(t.session.id));let{email:n,password:o}=e.body;if(!v.string().email().safeParse(n).success)throw new E("BAD_REQUEST",{message:"Invalid email"});let s=yield e.context.internalAdapter.findUserByEmail(n);if(!s)throw yield e.context.password.hash(o),e.context.logger.error("User not found",{email:n}),new E("UNAUTHORIZED",{message:"Invalid email or password"});let i=s.accounts.find(m=>m.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:n}),new E("UNAUTHORIZED",{message:"Invalid email or password"});let d=i==null?void 0:i.password;if(!d)throw e.context.logger.error("Password not found",{email:n}),new E("UNAUTHORIZED",{message:"Unexpected error"});if(!(yield e.context.password.verify(d,o)))throw e.context.logger.error("Invalid password"),new E("UNAUTHORIZED",{message:"Invalid email or password"});let u=yield e.context.internalAdapter.createSession(s.user.id,e.headers,e.body.dontRememberMe);return yield x(e,u.id,e.body.dontRememberMe),e.json({user:s.user,session:u,redirect:!!e.body.callbackURL,url:e.body.callbackURL})}));import{APIError as xt}from"better-call";import{z as F}from"zod";import{z as h}from"zod";var wn=h.object({id:h.string(),providerId:h.string(),accountId:h.string(),userId:h.string(),accessToken:h.string().nullable().optional(),refreshToken:h.string().nullable().optional(),idToken:h.string().nullable().optional(),expiresAt:h.date().nullable().optional(),password:h.string().optional().nullable()}),xe=h.object({id:h.string(),email:h.string().transform(e=>e.toLowerCase()),emailVerified:h.boolean().default(!1),name:h.string(),image:h.string().optional(),createdAt:h.date().default(new Date),updatedAt:h.date().default(new Date)}),bn=h.object({id:h.string(),userId:h.string(),expiresAt:h.date(),ipAddress:h.string().optional(),userAgent:h.string().optional()});import{alphabet as vt,generateRandomString as Pt}from"oslo/crypto";var Se=()=>Pt(36,vt("a-z","0-9"));var C={isAction:!1};function Q(e){let t=e.accessToken(),n=e.hasRefreshToken()?e.refreshToken():void 0,o;try{o=e.accessTokenExpiresAt()}catch(r){}return{accessToken:t,refreshToken:n,expiresAt:o}}var _e=f("/callback/:id",{method:"GET",query:F.object({state:F.string(),code:F.string().optional(),error:F.string().optional()}),metadata:C},e=>a(void 0,null,function*(){var U,T,L;if(e.query.error||!e.query.code){let R=((U=W(e.query.state).data)==null?void 0:U.callbackURL)||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${R}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(b=>b.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 n=yield e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),o;try{o=yield t.validateAuthorizationCode(e.query.code,n,`${e.context.baseURL}/callback/${t.id}`)}catch(b){throw e.context.logger.error(b),e.redirect(`${e.context.baseURL}/error?error=oauth_code_verification_failed`)}let r=yield t.getUserInfo(o).then(b=>b==null?void 0:b.user),s=Se(),i=xe.safeParse(k(g({},r),{id:s})),d=W(e.query.state);if(!d.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=invalid_state_parameter`);let{callbackURL:c,currentURL:u,dontRememberMe:l}=d.data;if(!r||i.success===!1)throw e.redirect(`${e.context.baseURL}/error?error=oauth_validation_failed`);if(!c)throw e.redirect(`${e.context.baseURL}/error?error=oauth_callback_url_not_found`);let p=yield e.context.internalAdapter.findUserByEmail(r.email),m=p==null?void 0:p.user.id;if(p){let b=p.accounts.find(j=>j.providerId===t.id),R=(L=(T=e.context.options.account)==null?void 0:T.accountLinking)==null?void 0:L.trustedProviders,z=R?R.includes(t.id):!0;if(!b&&(!r.emailVerified||!z)){let j;try{j=new URL(u||c),j.searchParams.set("error","account_not_linked")}catch(Jt){throw e.redirect(`${e.context.baseURL}/error?error=account_not_linked`)}throw e.redirect(j.toString())}if(!b)try{yield e.context.internalAdapter.linkAccount(g({providerId:t.id,accountId:r.id,id:`${t.id}:${r.id}`,userId:p.user.id},Q(o)))}catch(j){throw console.log(j),e.redirect(`${e.context.baseURL}/error?error=failed_linking_account`)}}else try{yield e.context.internalAdapter.createOAuthUser(i.data,k(g({},Q(o)),{id:`${t.id}:${r.id}`,providerId:t.id,accountId:r.id,userId:s}))}catch(b){let R=new URL(u||c);throw R.searchParams.set("error","unable_to_create_user"),e.setHeader("Location",R.toString()),e.redirect(R.toString())}if(!m&&!s)throw new xt("INTERNAL_SERVER_ERROR",{message:"Unable to create user"});let w=yield e.context.internalAdapter.createSession(m||s,e.request,l);try{yield x(e,w.id,l)}catch(b){e.context.logger.error("Unable to set session cookie",b);let R=new URL(u||c);throw R.searchParams.set("error","unable_to_create_session"),e.redirect(R.toString())}throw e.redirect(c)}));import{z as X}from"zod";var Ie=f("/sign-out",{method:"POST",body:X.optional(X.object({callbackURL:X.string().optional()}))},e=>a(void 0,null,function*(){var n,o;let t=yield e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);return t?(yield e.context.internalAdapter.deleteSession(t),V(e),e.json(null,{body:{redirect:!!((n=e.body)!=null&&n.callbackURL),url:(o=e.body)==null?void 0:o.callbackURL}})):e.json(null)}));import{TimeSpan as St}from"oslo";import{createJWT as _t,parseJWT as It}from"oslo/jwt";import{validateJWT as Oe}from"oslo/jwt";import{z as P}from"zod";var Le=f("/forget-password",{method:"POST",body:P.object({email:P.string().email(),redirectTo:P.string()})},e=>a(void 0,null,function*(){var s;if(!((s=e.context.options.emailAndPassword)!=null&&s.sendResetPassword))return e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function to your auth config!"),e.json(null,{status:400,statusText:"RESET_PASSWORD_EMAIL_NOT_SENT",body:{message:"Reset password isn't enabled"}});let{email:t}=e.body,n=yield e.context.internalAdapter.findUserByEmail(t);if(!n)return e.json({status:!1},{body:{status:!0}});let o=yield _t("HS256",Buffer.from(e.context.secret),{email:n.user.email,redirectTo:e.body.redirectTo},{expiresIn:new St(1,"h"),issuer:"better-auth",subject:"forget-password",audiences:[n.user.email],includeIssuedTimestamp:!0}),r=`${e.context.baseURL}/reset-password/${o}`;return yield e.context.options.emailAndPassword.sendResetPassword(r,n.user),e.json({status:!0})})),Ee=f("/reset-password/:token",{method:"GET"},e=>a(void 0,null,function*(){var s;let{token:t}=e.params,n,o=P.object({email:P.string(),redirectTo:P.string()});try{if(n=yield Oe("HS256",Buffer.from(e.context.secret),t),!n.expiresAt||n.expiresAt<new Date)throw Error("Token expired")}catch(i){let d=It(t),c=o.safeParse(d==null?void 0:d.payload);throw c.success?e.redirect(`${(s=c.data)==null?void 0:s.redirectTo}?error=invalid_token`):e.redirect(`${e.context.baseURL}/error?error=invalid_token`)}let{redirectTo:r}=o.parse(n.payload);throw e.redirect(`${r}?token=${t}`)})),Ce=f("/reset-password",{method:"POST",query:P.object({currentURL:P.string()}).optional(),body:P.object({newPassword:P.string(),callbackURL:P.string().optional()})},e=>a(void 0,null,function*(){var o,r,s;let t=(o=e.query)==null?void 0:o.currentURL.split("?token=")[1];if(!t)return e.json({error:"Invalid token",data:null},{status:400,statusText:"INVALID_TOKEN",body:{message:"Invalid token"}});let{newPassword:n}=e.body;try{let i=yield Oe("HS256",Buffer.from(e.context.secret),t),d=P.string().email().parse(i.payload.email),c=yield e.context.internalAdapter.findUserByEmail(d);if(!c)return e.json({error:"User not found",data:null},{status:400,body:{message:"failed to reset password"}});if(n.length<(((r=e.context.options.emailAndPassword)==null?void 0:r.minPasswordLength)||8)||n.length>(((s=e.context.options.emailAndPassword)==null?void 0:s.maxPasswordLength)||32))return e.json({data:null,error:"password is too short or too long"},{status:400,statusText:"INVALID_PASSWORD_LENGTH",body:{message:"password is too short or too long"}});let u=yield e.context.password.hash(n);return(yield e.context.internalAdapter.updatePassword(c.user.id,u))?e.json({error:null,data:{status:!0,url:e.body.callbackURL,redirect:!!e.body.callbackURL}},{body:{status:!0,url:e.body.callbackURL,redirect:!!e.body.callbackURL}}):e.json(null,{status:400,statusText:"USER_NOT_FOUND",body:{message:"User doesn't have a credential account"}})}catch(i){return console.log(i),e.json({error:"Invalid token",data:null},{status:400,statusText:"INVALID_TOKEN",body:{message:"Invalid token"}})}}));import{TimeSpan as Ot}from"oslo";import{createJWT as Lt,validateJWT as Et}from"oslo/jwt";import{z as S}from"zod";function Y(e,t){return a(this,null,function*(){return yield Lt("HS256",Buffer.from(e),{email:t.toLowerCase()},{expiresIn:new Ot(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})})}var je=f("/send-verification-email",{method:"POST",query:S.object({currentURL:S.string().optional()}).optional(),body:S.object({email:S.string().email(),callbackURL:S.string().optional()})},e=>a(void 0,null,function*(){var r,s;if(!((r=e.context.options.emailAndPassword)!=null&&r.sendVerificationEmail))return e.context.logger.error("Verification email isn't enabled. Pass `sendVerificationEmail` in `emailAndPassword` options to enable it."),e.json(null,{status:400,statusText:"VERIFICATION_EMAIL_NOT_SENT",body:{message:"Verification email isn't enabled"}});let{email:t}=e.body,n=yield Y(e.context.secret,t),o=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${e.body.callbackURL||((s=e.query)==null?void 0:s.currentURL)||"/"}`;return yield e.context.options.emailAndPassword.sendVerificationEmail(t,o,n),e.json({status:!0})})),De=f("/verify-email",{method:"GET",query:S.object({token:S.string(),callbackURL:S.string().optional()})},e=>a(void 0,null,function*(){let{token:t}=e.query,n;try{n=yield Et("HS256",Buffer.from(e.context.secret),t)}catch(d){return e.context.logger.error("Failed to verify email",d),e.json(null,{status:400,statusText:"INVALID_TOKEN",body:{message:"Invalid token"}})}let r=S.object({email:S.string().email()}).parse(n.payload),s=yield e.context.internalAdapter.findUserByEmail(r.email);if(!s)return e.json(null,{status:400,statusText:"USER_NOT_FOUND",body:{message:"User not found"}});if(!s.accounts.find(d=>d.providerId==="credential"))throw e.redirect;if(yield e.context.internalAdapter.updateUserByEmail(r.email,{emailVerified:!0}),e.query.callbackURL)throw console.log("Redirecting to",e.query.callbackURL),e.redirect("/");return e.json({status:!0})}));import{z as I}from"zod";import{alphabet as Ct,generateRandomString as jt}from"oslo/crypto";import"better-call";var $e=f("/user/update",{method:"POST",body:I.object({name:I.string().optional(),image:I.string().optional()}),use:[B]},e=>a(void 0,null,function*(){let{name:t,image:n}=e.body,o=e.context.session;if(!n&&!t)return e.json(o.user);let r=yield e.context.internalAdapter.updateUserByEmail(o.user.email,{name:t,image:n});return e.json(r)})),Be=f("/user/change-password",{method:"POST",body:I.object({newPassword:I.string(),currentPassword:I.string(),revokeOtherSessions:I.boolean().optional()}),use:[B]},e=>a(void 0,null,function*(){let{newPassword:t,currentPassword:n,revokeOtherSessions:o}=e.body,r=e.context.session,s=e.context.password.config.minPasswordLength;if(t.length<s)return e.context.logger.error("Password is too short"),e.json(null,{status:400,body:{message:"Password is too short"}});let i=e.context.password.config.maxPasswordLength;if(t.length>i)return e.context.logger.error("Password is too long"),e.json(null,{status:400,body:{message:"Password is too long"}});let c=(yield e.context.internalAdapter.findAccounts(r.user.id)).find(p=>p.providerId==="credential"&&p.password);if(!c||!c.password)return e.json(null,{status:400,body:{message:"User does not have a password"}});let u=yield e.context.password.hash(t);if(!(yield e.context.password.verify(c.password,n)))return e.json(null,{status:400,body:{message:"Invalid password"}});if(yield e.context.internalAdapter.updateAccount(c.id,{password:u}),o){yield e.context.internalAdapter.deleteSessions(r.user.id);let p=yield e.context.internalAdapter.createSession(r.user.id,e.headers);yield x(e,p.id)}return e.json(r.user)})),ze=f("/user/set-password",{method:"POST",body:I.object({newPassword:I.string()}),use:[B]},e=>a(void 0,null,function*(){let{newPassword:t}=e.body,n=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)return e.context.logger.error("Password is too short"),e.json(null,{status:400,body:{message:"Password is too short"}});let r=e.context.password.config.maxPasswordLength;if(t.length>r)return e.context.logger.error("Password is too long"),e.json(null,{status:400,body:{message:"Password is too long"}});let i=(yield e.context.internalAdapter.findAccounts(n.user.id)).find(c=>c.providerId==="credential"&&c.password),d=yield e.context.password.hash(t);return i?e.json(null,{status:400,body:{message:"User already has a password"}}):(yield e.context.internalAdapter.linkAccount({id:jt(32,Ct("a-z","0-9","A-Z")),userId:n.user.id,providerId:"credential",accountId:n.user.id,password:d}),e.json(n.user))}));import{alphabet as Dt,generateRandomString as $t}from"oslo/crypto";var qe=f("/csrf",{method:"GET",metadata:C},e=>a(void 0,null,function*(){let t=yield e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t)return{csrfToken:t};let n=$t(32,Dt("a-z","0-9","A-Z")),o=yield M(e.context.secret,n),r=`${n}!${o}`;return yield e.setSignedCookie(e.context.authCookies.csrfToken.name,r,e.context.secret,e.context.authCookies.csrfToken.options),{csrfToken:n}}));var Bt=(e="Unknown")=>`<!DOCTYPE html>
3
3
  <html lang="en">
4
4
  <head>
5
5
  <meta charset="UTF-8">
@@ -79,4 +79,4 @@ var Ze=Object.defineProperty,Ke=Object.defineProperties;var Qe=Object.getOwnProp
79
79
  <div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
80
80
  </div>
81
81
  </body>
82
- </html>`,Me=f("/error",{method:"GET",metadata:C},e=>a(void 0,null,function*(){var n;let t=new URL(((n=e.request)==null?void 0:n.url)||"").searchParams.get("error")||"Unknown";return new Response(zt(t),{headers:{"Content-Type":"text/html"}})}));var He=f("/ok",{method:"GET",metadata:C},e=>a(void 0,null,function*(){return e.json({ok:!0})}));import{alphabet as Ne,generateRandomString as Fe}from"oslo/crypto";import{z as L}from"zod";var Ge=f("/sign-up/email",{method:"POST",query:L.object({currentURL:L.string().optional()}).optional(),body:L.object({name:L.string(),email:L.string(),password:L.string(),image:L.string().optional(),callbackURL:L.string().optional()})},e=>a(void 0,null,function*(){var m,w,U,T;if(!((m=e.context.options.emailAndPassword)!=null&&m.enabled))return e.json(null,{status:400,body:{message:"Email and password is not enabled"}});let{name:t,email:n,password:o,image:r}=e.body;if(!L.string().email().safeParse(n).success)return e.json(null,{status:400,body:{message:"Invalid email address"}});let i=e.context.password.config.minPasswordLength;if(o.length<i)return e.context.logger.error("Password is too short"),e.json(null,{status:400,body:{message:"Password is too short"}});let d=e.context.password.config.maxPasswordLength;if(o.length>d)return e.context.logger.error("Password is too long"),e.json(null,{status:400,body:{message:"Password is too long"}});let c=yield e.context.internalAdapter.findUserByEmail(n),u=yield e.context.password.hash(o);if(c!=null&&c.user)return e.json(null,{status:400,body:{message:"User already exists"}});let l=yield e.context.internalAdapter.createUser({id:Fe(32,Ne("a-z","0-9","A-Z")),email:n.toLowerCase(),name:t,image:r,emailVerified:!1,createdAt:new Date,updatedAt:new Date});yield e.context.internalAdapter.linkAccount({id:Fe(32,Ne("a-z","0-9","A-Z")),userId:l.id,providerId:"credential",accountId:l.id,password:u});let p=yield e.context.internalAdapter.createSession(l.id,e.request);if(yield P(e,p.id),e.context.options.emailAndPassword.sendEmailVerificationOnSignUp){let O=yield Y(e.context.secret,l.email),b=`${e.context.baseURL}/verify-email?token=${O}&callbackURL=${e.body.callbackURL||((w=e.query)==null?void 0:w.currentURL)||"/"}`;yield(T=(U=e.context.options.emailAndPassword).sendVerificationEmail)==null?void 0:T.call(U,l.email,b,O)}return e.json({user:l,session:p},{body:e.body.callbackURL?{url:e.body.callbackURL,redirect:!0}:{user:l,session:p}})}));import ee from"chalk";function qt(e,t,n){let o=Date.now(),r=t*1e3;return o-n.lastRequest<r&&n.count>=e}function Vt(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 Mt(e,t){let n=Date.now(),o=t*1e3;return Math.ceil((e+o-n)/1e3)}function Ht(e,t){let n=t!=null?t:"rateLimit",o=e.adapter;return{get:r=>a(this,null,function*(){return yield o.findOne({model:n,where:[{field:"key",value:r}]})}),set:(r,s,i)=>a(this,null,function*(){try{i?yield o.update({model:t!=null?t:"rateLimit",where:[{field:"key",value:r}],update:{count:s.count,lastRequest:s.lastRequest}}):yield o.create({model:t!=null?t:"rateLimit",data:{key:r,count:s.count,lastRequest:s.lastRequest}})}catch(d){_.error("Error setting rate limit",d)}})}}var We=new Map;function Nt(e){if(e.rateLimit.customStorage)return e.rateLimit.customStorage;if(e.rateLimit.storage==="memory"){let n;return{get(o){return a(this,null,function*(){return We.get(o)})},set(o,r,s){return a(this,null,function*(){We.set(o,r)})}}}return Ht(e,e.rateLimit.tableName)}function Je(e,t){return a(this,null,function*(){if(!t.rateLimit.enabled)return;let n=t.baseURL,o=e.url.replace(n,""),r=t.rateLimit.window,s=t.rateLimit.max,i=N(e)+o,c=Ft().find(m=>m.pathMatcher(o));c&&(r=c.window,s=c.max);for(let m of t.options.plugins||[])if(m.rateLimit){let w=m.rateLimit.find(U=>U.pathMatcher(o));if(w){r=w.window,s=w.max;break}}if(t.rateLimit.customRules){let m=t.rateLimit.customRules[o];m&&(r=m.window,s=m.max)}let u=Nt(t),l=yield u.get(i),p=Date.now();if(!l)yield u.set(i,{key:i,count:1,lastRequest:p});else{let m=p-l.lastRequest;if(qt(s,r,l)){let w=Mt(l.lastRequest,r);return Vt(w)}else m>r*1e3?yield u.set(i,k(g({},l),{count:1,lastRequest:p})):yield u.set(i,k(g({},l),{count:l.count+1,lastRequest:p}))}})}function Ft(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:7}]}function Jt(e,t){var d,c;let n=(d=e.options.plugins)==null?void 0:d.reduce((u,l)=>g(g({},u),l.endpoints),{}),o=((c=e.options.plugins)==null?void 0:c.map(u=>{var l;return(l=u.middlewares)==null?void 0:l.map(p=>{let m=w=>a(this,null,function*(){return p.middleware(k(g({},w),{context:g(g({},e),w.context)}))});return m.path=p.path,m.options=p.middleware.options,m.headers=p.middleware.headers,{path:p.path,middleware:m}})}).filter(u=>u!==void 0).flat())||[],r={signInOAuth:xe,callbackOAuth:Ie,getCSRFToken:Ve,getSession:Z(),signOut:Le,signUpEmail:Ge,signInEmail:Pe,forgetPassword:Ee,resetPassword:je,verifyEmail:$e,sendVerificationEmail:De,changePassword:ze,setPassword:qe,updateUser:Be,forgetPasswordCallback:Ce,listSessions:Ue(),revokeSession:Te,revokeSessions:ve},s=k(g(g({},r),n),{ok:He,error:Me}),i={};for(let[u,l]of Object.entries(s))i[u]=p=>a(this,null,function*(){var U;let w=yield l(k(g({},p),{context:g(g({},e),p.context)}));for(let T of e.options.plugins||[])if((U=T.hooks)!=null&&U.after){for(let O of T.hooks.after)if(O.matcher(p)){let R=Object.assign(p,{context:k(g({},e),{returned:w})}),z=yield O.handler(R);z&&"response"in z&&(w=z.response)}}return w}),i[u].path=l.path,i[u].method=l.method,i[u].options=l.options,i[u].headers=l.headers;return{api:i,middlewares:o}}var Li=(e,t)=>{let{api:n,middlewares:o}=Jt(e,t),r=new URL(e.baseURL).pathname;return Wt(n,{extraContext:e,basePath:r,routerMiddleware:[{path:"/**",middleware:de},...o],onRequest(i){return a(this,null,function*(){return Je(i,e)})},onError(i){var c,u,l,p;let d=(c=t.logger)!=null&&c.verboseLogging?_:void 0;if(((u=t.logger)==null?void 0:u.disabled)!==!0)if(i instanceof Gt)d==null||d.warn(i);else if(typeof i=="object"&&i!==null&&"message"in i){let m=i.message;if(!m||typeof m!="string"){d==null||d.error(i);return}m.includes("no such table")?(l=_)==null||l.error(`Please run ${ee.green("npx better-auth migrate")} to create the tables. There are missing tables in your SQLite database.`):m.includes("relation")&&m.includes("does not exist")?_.error(`Please run ${ee.green("npx better-auth migrate")} to create the tables. There are missing tables in your PostgreSQL database.`):m.includes("Table")&&m.includes("doesn't exist")?(p=_)==null||p.error(`Please run ${ee.green("npx better-auth migrate")} to create the tables. There are missing tables in your MySQL database.`):d==null||d.error(i)}else d==null||d.error(i)}})};export{Ie as callbackOAuth,ze as changePassword,f as createAuthEndpoint,H as createAuthMiddleware,Y as createEmailVerificationToken,de as csrfMiddleware,Me as error,Ee as forgetPassword,Ce as forgetPasswordCallback,Ve as getCSRFToken,Jt as getEndpoints,Z as getSession,K as getSessionFromCtx,Ue as listSessions,He as ok,se as optionsMiddleware,je as resetPassword,Te as revokeSession,ve as revokeSessions,Li as router,De as sendVerificationEmail,B as sessionMiddleware,qe as setPassword,Pe as signInEmail,xe as signInOAuth,Le as signOut,Ge as signUpEmail,Be as updateUser,$e as verifyEmail};
82
+ </html>`,Ve=f("/error",{method:"GET",metadata:C},e=>a(void 0,null,function*(){var n;let t=new URL(((n=e.request)==null?void 0:n.url)||"").searchParams.get("error")||"Unknown";return new Response(Bt(t),{headers:{"Content-Type":"text/html"}})}));var Me=f("/ok",{method:"GET",metadata:C},e=>a(void 0,null,function*(){return e.json({ok:!0})}));import{alphabet as He,generateRandomString as Ne}from"oslo/crypto";import{z as O}from"zod";var Fe=f("/sign-up/email",{method:"POST",query:O.object({currentURL:O.string().optional()}).optional(),body:O.object({name:O.string(),email:O.string(),password:O.string(),image:O.string().optional(),callbackURL:O.string().optional()})},e=>a(void 0,null,function*(){var m,w,U,T;if(!((m=e.context.options.emailAndPassword)!=null&&m.enabled))return e.json(null,{status:400,body:{message:"Email and password is not enabled"}});let{name:t,email:n,password:o,image:r}=e.body;if(!O.string().email().safeParse(n).success)return e.json(null,{status:400,body:{message:"Invalid email address"}});let i=e.context.password.config.minPasswordLength;if(o.length<i)return e.context.logger.error("Password is too short"),e.json(null,{status:400,body:{message:"Password is too short"}});let d=e.context.password.config.maxPasswordLength;if(o.length>d)return e.context.logger.error("Password is too long"),e.json(null,{status:400,body:{message:"Password is too long"}});let c=yield e.context.internalAdapter.findUserByEmail(n),u=yield e.context.password.hash(o);if(c!=null&&c.user)return e.json(null,{status:400,body:{message:"User already exists"}});let l=yield e.context.internalAdapter.createUser({id:Ne(32,He("a-z","0-9","A-Z")),email:n.toLowerCase(),name:t,image:r,emailVerified:!1,createdAt:new Date,updatedAt:new Date});yield e.context.internalAdapter.linkAccount({id:Ne(32,He("a-z","0-9","A-Z")),userId:l.id,providerId:"credential",accountId:l.id,password:u});let p=yield e.context.internalAdapter.createSession(l.id,e.request);if(yield x(e,p.id),e.context.options.emailAndPassword.sendEmailVerificationOnSignUp){let L=yield Y(e.context.secret,l.email),b=`${e.context.baseURL}/verify-email?token=${L}&callbackURL=${e.body.callbackURL||((w=e.query)==null?void 0:w.currentURL)||"/"}`;yield(T=(U=e.context.options.emailAndPassword).sendVerificationEmail)==null?void 0:T.call(U,l.email,b,L)}return e.json({user:l,session:p},{body:e.body.callbackURL?{url:e.body.callbackURL,redirect:!0}:{user:l,session:p}})}));import ee from"chalk";function zt(e,t,n){let o=Date.now(),r=t*1e3;return o-n.lastRequest<r&&n.count>=e}function qt(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 n=Date.now(),o=t*1e3;return Math.ceil((e+o-n)/1e3)}function Mt(e,t){let n=t!=null?t:"rateLimit",o=e.adapter;return{get:r=>a(this,null,function*(){return yield o.findOne({model:n,where:[{field:"key",value:r}]})}),set:(r,s,i)=>a(this,null,function*(){try{i?yield o.update({model:t!=null?t:"rateLimit",where:[{field:"key",value:r}],update:{count:s.count,lastRequest:s.lastRequest}}):yield o.create({model:t!=null?t:"rateLimit",data:{key:r,count:s.count,lastRequest:s.lastRequest}})}catch(d){_.error("Error setting rate limit",d)}})}}var Ge=new Map;function Ht(e){if(e.rateLimit.customStorage)return e.rateLimit.customStorage;if(e.rateLimit.storage==="memory"){let n;return{get(o){return a(this,null,function*(){return Ge.get(o)})},set(o,r,s){return a(this,null,function*(){Ge.set(o,r)})}}}return Mt(e,e.rateLimit.tableName)}function We(e,t){return a(this,null,function*(){if(!t.rateLimit.enabled)return;let n=t.baseURL,o=e.url.replace(n,""),r=t.rateLimit.window,s=t.rateLimit.max,i=N(e)+o,c=Nt().find(m=>m.pathMatcher(o));c&&(r=c.window,s=c.max);for(let m of t.options.plugins||[])if(m.rateLimit){let w=m.rateLimit.find(U=>U.pathMatcher(o));if(w){r=w.window,s=w.max;break}}if(t.rateLimit.customRules){let m=t.rateLimit.customRules[o];m&&(r=m.window,s=m.max)}let u=Ht(t),l=yield u.get(i),p=Date.now();if(!l)yield u.set(i,{key:i,count:1,lastRequest:p});else{let m=p-l.lastRequest;if(zt(s,r,l)){let w=Vt(l.lastRequest,r);return qt(w)}else m>r*1e3?yield u.set(i,k(g({},l),{count:1,lastRequest:p})):yield u.set(i,k(g({},l),{count:l.count+1,lastRequest:p}))}})}function Nt(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:7}]}function Wt(e,t){var d,c;let n=(d=e.options.plugins)==null?void 0:d.reduce((u,l)=>g(g({},u),l.endpoints),{}),o=((c=e.options.plugins)==null?void 0:c.map(u=>{var l;return(l=u.middlewares)==null?void 0:l.map(p=>{let m=w=>a(this,null,function*(){return p.middleware(k(g({},w),{context:g(g({},e),w.context)}))});return m.path=p.path,m.options=p.middleware.options,m.headers=p.middleware.headers,{path:p.path,middleware:m}})}).filter(u=>u!==void 0).flat())||[],r={signInOAuth:ve,callbackOAuth:_e,getCSRFToken:qe,getSession:Z(),signOut:Ie,signUpEmail:Fe,signInEmail:Pe,forgetPassword:Le,resetPassword:Ce,verifyEmail:De,sendVerificationEmail:je,changePassword:Be,setPassword:ze,updateUser:$e,forgetPasswordCallback:Ee,listSessions:Re(),revokeSession:Ue,revokeSessions:Te},s=k(g(g({},r),n),{ok:Me,error:Ve}),i={};for(let[u,l]of Object.entries(s))i[u]=p=>a(this,null,function*(){var U;let w=yield l(k(g({},p),{context:g(g({},e),p.context)}));for(let T of e.options.plugins||[])if((U=T.hooks)!=null&&U.after){for(let L of T.hooks.after)if(L.matcher(p)){let R=Object.assign(p,{context:k(g({},e),{returned:w})}),z=yield L.handler(R);z&&"response"in z&&(w=z.response)}}return w}),i[u].path=l.path,i[u].method=l.method,i[u].options=l.options,i[u].headers=l.headers;return{api:i,middlewares:o}}var Ii=(e,t)=>{let{api:n,middlewares:o}=Wt(e,t),r=new URL(e.baseURL).pathname;return Gt(n,{extraContext:e,basePath:r,routerMiddleware:[{path:"/**",middleware:ae},...o],onRequest(i){return a(this,null,function*(){return We(i,e)})},onError(i){var c,u,l,p;let d=(c=t.logger)!=null&&c.verboseLogging?_:void 0;if(((u=t.logger)==null?void 0:u.disabled)!==!0)if(i instanceof Ft)d==null||d.warn(i);else if(typeof i=="object"&&i!==null&&"message"in i){let m=i.message;if(!m||typeof m!="string"){d==null||d.error(i);return}m.includes("no such table")?(l=_)==null||l.error(`Please run ${ee.green("npx better-auth migrate")} to create the tables. There are missing tables in your SQLite database.`):m.includes("relation")&&m.includes("does not exist")?_.error(`Please run ${ee.green("npx better-auth migrate")} to create the tables. There are missing tables in your PostgreSQL database.`):m.includes("Table")&&m.includes("doesn't exist")?(p=_)==null||p.error(`Please run ${ee.green("npx better-auth migrate")} to create the tables. There are missing tables in your MySQL database.`):d==null||d.error(i)}else d==null||d.error(i)}})};export{_e as callbackOAuth,Be as changePassword,f as createAuthEndpoint,H as createAuthMiddleware,Y as createEmailVerificationToken,ae as csrfMiddleware,Ve as error,Le as forgetPassword,Ee as forgetPasswordCallback,qe as getCSRFToken,Wt as getEndpoints,Z as getSession,K as getSessionFromCtx,Re as listSessions,Me as ok,ne as optionsMiddleware,Ce as resetPassword,Ue as revokeSession,Te as revokeSessions,Ii as router,je as sendVerificationEmail,B as sessionMiddleware,ze as setPassword,Pe as signInEmail,ve as signInOAuth,Ie as signOut,Fe as signUpEmail,$e as updateUser,De as verifyEmail};
@@ -2,14 +2,14 @@ import * as nanostores from 'nanostores';
2
2
  import { A as AccessControl, S as StatementsPrimitive, R as Role } from '../statement-CU-fdHXK.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, d as Organization, M as Member, I as Invitation, u as username } from '../index-D-u2S_Fl.js';
6
- export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-D-u2S_Fl.js';
5
+ import { o as organization, d as Organization, M as Member, I as Invitation, u as username, m as magicLink } from '../index-CMQfBjoY.js';
6
+ export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-CMQfBjoY.js';
7
7
  import { P as Prettify } from '../helper-C1ihmerM.js';
8
8
  import '../index-C8A40nOX.js';
9
9
  import 'arctic';
10
10
  import 'zod';
11
11
  import 'better-call';
12
- import '../index-BMranMWG.js';
12
+ import '../index-BZTQCJvy.js';
13
13
  import 'kysely';
14
14
  import '@simplewebauthn/types';
15
15
 
@@ -132,4 +132,9 @@ declare const usernameClient: () => {
132
132
  $InferServerPlugin: ReturnType<typeof username>;
133
133
  };
134
134
 
135
- export { organizationClient, usernameClient };
135
+ declare const magicLinkClient: () => {
136
+ id: "magic-link";
137
+ $InferServerPlugin: ReturnType<typeof magicLink>;
138
+ };
139
+
140
+ export { magicLinkClient, organizationClient, usernameClient };
@@ -1,2 +1,2 @@
1
- var w=Object.defineProperty,x=Object.defineProperties;var k=Object.getOwnPropertyDescriptors;var T=Object.getOwnPropertySymbols;var C=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var b=(e,t,s)=>t in e?w(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,u=(e,t)=>{for(var s in t||(t={}))C.call(t,s)&&b(e,s,t[s]);if(T)for(var s of T(t))B.call(t,s)&&b(e,s,t[s]);return e},d=(e,t)=>x(e,k(t));var p=(e,t,s)=>b(e,typeof t!="symbol"?t+"":t,s);var l=(e,t,s)=>new Promise((a,r)=>{var i=c=>{try{n(s.next(c))}catch(f){r(f)}},o=c=>{try{n(s.throw(c))}catch(f){r(f)}},n=c=>c.done?a(c.value):Promise.resolve(c.value).then(i,o);n((s=s.apply(e,t)).next())});import{atom as O}from"nanostores";var y=class extends Error{constructor(s,a){super(s);p(this,"path");this.path=a}},P=class{constructor(t){this.s=t;p(this,"statements");this.statements=t}newRole(t){return new S(t)}},S=class e{constructor(t){p(this,"statements");this.statements=t}authorize(t,s){for(let[a,r]of Object.entries(t)){let i=this.statements[a];if(!i)return{success:!1,error:`You are not allowed to access resource: ${a}`};let o=s==="OR"?r.some(n=>i.includes(n)):r.every(n=>i.includes(n));return o?{success:o}:{success:!1,error:`unauthorized to access resource "${a}"`}}return{success:!1,error:"Not authorized"}}static fromString(t){let s=JSON.parse(t);if(typeof s!="object")throw new y("statements is not an object",".");for(let[a,r]of Object.entries(s)){if(typeof a!="string")throw new y("invalid resource identifier",a);if(!Array.isArray(r))throw new y("actions is not an array",a);for(let i=0;i<r.length;i++)if(typeof r[i]!="string")throw new y("action is not a string",`${a}[${i}]`)}return new e(s)}toString(){return JSON.stringify(this.statements)}};var F=e=>new P(e),U={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},A=F(U),K=A.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),H=A.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),J=A.newRole({organization:[],member:[],invitation:[]});import{createFetch as he}from"@better-fetch/fetch";import"nanostores";import{betterFetch as oe}from"@better-fetch/fetch";import{atom as ve}from"nanostores";import"@better-fetch/fetch";import{atom as E,onMount as I}from"nanostores";var h=(e,t,s,a)=>{let r=E({data:null,error:null,isPending:!1}),i=()=>{let n=typeof a=="function"?a({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):a;return s(t,d(u({},n),{onSuccess:f=>l(void 0,null,function*(){var m;r.set({data:f.data,error:null,isPending:!1}),yield(m=n==null?void 0:n.onSuccess)==null?void 0:m.call(n,f)}),onError(f){return l(this,null,function*(){var m;r.set({error:f.error,data:null,isPending:!1}),yield(m=n==null?void 0:n.onError)==null?void 0:m.call(n,f)})},onRequest(f){return l(this,null,function*(){var R;let m=r.get();r.set({isPending:!0,data:m.data,error:m.error}),yield(R=n==null?void 0:n.onRequest)==null?void 0:R.call(n,f)})}}))};e=Array.isArray(e)?e:[e];let o=!1;for(let n of e)n.subscribe(()=>{o?i():I(r,()=>(i(),o=!0,()=>{r.off(),n.off()}))});return r};var Ze=e=>{let t=O(void 0),s=O(!1),a=O(!1);return{id:"organization",$InferServerPlugin:{},getActions:r=>({$Infer:{ActiveOrganization:{},Organization:{},Invitation:{},Member:{}},organization:{setActive(i){t.set(i)},hasPermission:i=>l(void 0,null,function*(){return yield r("/organization/has-permission",u({method:"POST",body:{permission:i.permission}},i.fetchOptions))})}}),getAtoms:r=>{let i=h(s,"/organization/list",r,{method:"GET"}),o=h([t,a],"/organization/activate",r,()=>({method:"POST",credentials:"include",body:{orgId:t.get()}}));return{_listOrg:s,_activeOrgSignal:a,activeOrganization:o,listOrganizations:i}},atomListeners:[{matcher(r){return r==="/organization/create"||r==="/organization/delete"},signal:"_listOrg"},{matcher(r){return r.startsWith("/organization")},signal:"_activeOrgSignal"}]}};var rt=()=>({id:"username",$InferServerPlugin:{}});import{WebAuthnError as z,startAuthentication as $,startRegistration as M}from"@simplewebauthn/browser";import{createConsola as L}from"consola";var g=L({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),_=e=>({log:(...t)=>{!(e!=null&&e.disabled)&&g.log("",...t)},error:(...t)=>{!(e!=null&&e.disabled)&&g.error("",...t)},warn:(...t)=>{!(e!=null&&e.disabled)&&g.warn("",...t)},info:(...t)=>{!(e!=null&&e.disabled)&&g.info("",...t)},debug:(...t)=>{!(e!=null&&e.disabled)&&g.debug("",...t)},box:(...t)=>{!(e!=null&&e.disabled)&&g.box("",...t)},success:(...t)=>{!(e!=null&&e.disabled)&&g.success("",...t)},break:(...t)=>{!(e!=null&&e.disabled)&&console.log(`
2
- `)}}),it=_();import{atom as N}from"nanostores";var q=(e,{_listPasskeys:t})=>({signIn:{passkey:(r,i)=>l(void 0,null,function*(){let o=yield e("/passkey/generate-authenticate-options",{method:"POST",body:{email:r==null?void 0:r.email,callbackURL:r==null?void 0:r.callbackURL}});if(!o.data)return o;try{let n=yield $(o.data,(r==null?void 0:r.autoFill)||!1),c=yield e("/passkey/verify-authentication",u(u({body:{response:n}},r==null?void 0:r.fetchOptions),i));if(!c.data)return c}catch(n){console.log(n)}})},passkey:{addPasskey:(r,i)=>l(void 0,null,function*(){let o=yield e("/passkey/generate-register-options",{method:"GET"});if(!o.data)return o;try{let n=yield M(o.data),c=yield e("/passkey/verify-registration",d(u(u({},r==null?void 0:r.fetchOptions),i),{body:{response:n,name:r==null?void 0:r.name}}));if(!c.data)return c;t.set(Math.random())}catch(n){return n instanceof z?n.code==="ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED"?{data:null,error:{message:"previously registered",status:400,statusText:"BAD_REQUEST"}}:n.code==="ERROR_CEREMONY_ABORTED"?{data:null,error:{message:"registration cancelled",status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:n.message,status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:n instanceof Error?n.message:"unknown error",status:500,statusText:"INTERNAL_SERVER_ERROR"}}}})},$Infer:{}}),mt=()=>{let e=N();return{id:"passkey",$InferServerPlugin:{},getActions:t=>q(t,{_listPasskeys:e}),getAtoms(t){return{listPasskeys:h(e,"/passkey/list-user-passkeys",t,{method:"GET",credentials:"include"}),_listPasskeys:e}},pathMethods:{"/passkey/register":"POST","/passkey/authenticate":"POST"},atomListeners:[{matcher(t){return t==="/passkey/verify-registration"||t==="/passkey/delete-passkey"},signal:"_listPasskeys"}]}};var yt=(e={redirect:!0,twoFactorPage:"/"})=>({id:"two-factor",$InferServerPlugin:{},atomListeners:[{matcher:s=>s==="/two-factor/enable"||s==="/two-factor/send-otp"||s==="/two-factor/disable",signal:"_sessionSignal"}],pathMethods:{"/two-factor/disable":"POST","/two-factor/enable":"POST","/two-factor/send-otp":"POST"},fetchPlugins:[{id:"two-factor",name:"two-factor",hooks:{onSuccess(s){return l(this,null,function*(){var a;(a=s.data)!=null&&a.twoFactorRedirect&&(e.redirect||e.twoFactorPage)&&typeof window!="undefined"&&(window.location.href=e.twoFactorPage)})}}}]});export{q as getPasskeyActions,Ze as organizationClient,mt as passkeyClient,yt as twoFactorClient,rt as usernameClient};
1
+ var w=Object.defineProperty,x=Object.defineProperties;var k=Object.getOwnPropertyDescriptors;var T=Object.getOwnPropertySymbols;var C=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var A=(e,t,s)=>t in e?w(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,l=(e,t)=>{for(var s in t||(t={}))C.call(t,s)&&A(e,s,t[s]);if(T)for(var s of T(t))B.call(t,s)&&A(e,s,t[s]);return e},d=(e,t)=>x(e,k(t));var h=(e,t,s)=>A(e,typeof t!="symbol"?t+"":t,s);var u=(e,t,s)=>new Promise((a,r)=>{var i=c=>{try{n(s.next(c))}catch(f){r(f)}},o=c=>{try{n(s.throw(c))}catch(f){r(f)}},n=c=>c.done?a(c.value):Promise.resolve(c.value).then(i,o);n((s=s.apply(e,t)).next())});import{atom as O}from"nanostores";var y=class extends Error{constructor(s,a){super(s);h(this,"path");this.path=a}},P=class{constructor(t){this.s=t;h(this,"statements");this.statements=t}newRole(t){return new S(t)}},S=class e{constructor(t){h(this,"statements");this.statements=t}authorize(t,s){for(let[a,r]of Object.entries(t)){let i=this.statements[a];if(!i)return{success:!1,error:`You are not allowed to access resource: ${a}`};let o=s==="OR"?r.some(n=>i.includes(n)):r.every(n=>i.includes(n));return o?{success:o}:{success:!1,error:`unauthorized to access resource "${a}"`}}return{success:!1,error:"Not authorized"}}static fromString(t){let s=JSON.parse(t);if(typeof s!="object")throw new y("statements is not an object",".");for(let[a,r]of Object.entries(s)){if(typeof a!="string")throw new y("invalid resource identifier",a);if(!Array.isArray(r))throw new y("actions is not an array",a);for(let i=0;i<r.length;i++)if(typeof r[i]!="string")throw new y("action is not a string",`${a}[${i}]`)}return new e(s)}toString(){return JSON.stringify(this.statements)}};var F=e=>new P(e),U={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},b=F(U),K=b.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),H=b.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),J=b.newRole({organization:[],member:[],invitation:[]});import{createFetch as pe}from"@better-fetch/fetch";import"nanostores";import{betterFetch as oe}from"@better-fetch/fetch";import{atom as ve}from"nanostores";import"@better-fetch/fetch";import{atom as E,onMount as I}from"nanostores";var p=(e,t,s,a)=>{let r=E({data:null,error:null,isPending:!1}),i=()=>{let n=typeof a=="function"?a({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):a;return s(t,d(l({},n),{onSuccess:f=>u(void 0,null,function*(){var m;r.set({data:f.data,error:null,isPending:!1}),yield(m=n==null?void 0:n.onSuccess)==null?void 0:m.call(n,f)}),onError(f){return u(this,null,function*(){var m;r.set({error:f.error,data:null,isPending:!1}),yield(m=n==null?void 0:n.onError)==null?void 0:m.call(n,f)})},onRequest(f){return u(this,null,function*(){var R;let m=r.get();r.set({isPending:!0,data:m.data,error:m.error}),yield(R=n==null?void 0:n.onRequest)==null?void 0:R.call(n,f)})}}))};e=Array.isArray(e)?e:[e];let o=!1;for(let n of e)n.subscribe(()=>{o?i():I(r,()=>(i(),o=!0,()=>{r.off(),n.off()}))});return r};var Ze=e=>{let t=O(void 0),s=O(!1),a=O(!1);return{id:"organization",$InferServerPlugin:{},getActions:r=>({$Infer:{ActiveOrganization:{},Organization:{},Invitation:{},Member:{}},organization:{setActive(i){t.set(i)},hasPermission:i=>u(void 0,null,function*(){return yield r("/organization/has-permission",l({method:"POST",body:{permission:i.permission}},i.fetchOptions))})}}),getAtoms:r=>{let i=p(s,"/organization/list",r,{method:"GET"}),o=p([t,a],"/organization/activate",r,()=>({method:"POST",credentials:"include",body:{orgId:t.get()}}));return{_listOrg:s,_activeOrgSignal:a,activeOrganization:o,listOrganizations:i}},atomListeners:[{matcher(r){return r==="/organization/create"||r==="/organization/delete"},signal:"_listOrg"},{matcher(r){return r.startsWith("/organization")},signal:"_activeOrgSignal"}]}};var rt=()=>({id:"username",$InferServerPlugin:{}});import{WebAuthnError as z,startAuthentication as $,startRegistration as M}from"@simplewebauthn/browser";import{createConsola as L}from"consola";var g=L({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),_=e=>({log:(...t)=>{!(e!=null&&e.disabled)&&g.log("",...t)},error:(...t)=>{!(e!=null&&e.disabled)&&g.error("",...t)},warn:(...t)=>{!(e!=null&&e.disabled)&&g.warn("",...t)},info:(...t)=>{!(e!=null&&e.disabled)&&g.info("",...t)},debug:(...t)=>{!(e!=null&&e.disabled)&&g.debug("",...t)},box:(...t)=>{!(e!=null&&e.disabled)&&g.box("",...t)},success:(...t)=>{!(e!=null&&e.disabled)&&g.success("",...t)},break:(...t)=>{!(e!=null&&e.disabled)&&console.log(`
2
+ `)}}),it=_();import{atom as N}from"nanostores";var q=(e,{_listPasskeys:t})=>({signIn:{passkey:(r,i)=>u(void 0,null,function*(){let o=yield e("/passkey/generate-authenticate-options",{method:"POST",body:{email:r==null?void 0:r.email,callbackURL:r==null?void 0:r.callbackURL}});if(!o.data)return o;try{let n=yield $(o.data,(r==null?void 0:r.autoFill)||!1),c=yield e("/passkey/verify-authentication",l(l({body:{response:n}},r==null?void 0:r.fetchOptions),i));if(!c.data)return c}catch(n){console.log(n)}})},passkey:{addPasskey:(r,i)=>u(void 0,null,function*(){let o=yield e("/passkey/generate-register-options",{method:"GET"});if(!o.data)return o;try{let n=yield M(o.data),c=yield e("/passkey/verify-registration",d(l(l({},r==null?void 0:r.fetchOptions),i),{body:{response:n,name:r==null?void 0:r.name}}));if(!c.data)return c;t.set(Math.random())}catch(n){return n instanceof z?n.code==="ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED"?{data:null,error:{message:"previously registered",status:400,statusText:"BAD_REQUEST"}}:n.code==="ERROR_CEREMONY_ABORTED"?{data:null,error:{message:"registration cancelled",status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:n.message,status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:n instanceof Error?n.message:"unknown error",status:500,statusText:"INTERNAL_SERVER_ERROR"}}}})},$Infer:{}}),mt=()=>{let e=N();return{id:"passkey",$InferServerPlugin:{},getActions:t=>q(t,{_listPasskeys:e}),getAtoms(t){return{listPasskeys:p(e,"/passkey/list-user-passkeys",t,{method:"GET",credentials:"include"}),_listPasskeys:e}},pathMethods:{"/passkey/register":"POST","/passkey/authenticate":"POST"},atomListeners:[{matcher(t){return t==="/passkey/verify-registration"||t==="/passkey/delete-passkey"},signal:"_listPasskeys"}]}};var yt=(e={redirect:!0,twoFactorPage:"/"})=>({id:"two-factor",$InferServerPlugin:{},atomListeners:[{matcher:s=>s==="/two-factor/enable"||s==="/two-factor/send-otp"||s==="/two-factor/disable",signal:"_sessionSignal"}],pathMethods:{"/two-factor/disable":"POST","/two-factor/enable":"POST","/two-factor/send-otp":"POST"},fetchPlugins:[{id:"two-factor",name:"two-factor",hooks:{onSuccess(s){return u(this,null,function*(){var a;(a=s.data)!=null&&a.twoFactorRedirect&&(e.redirect||e.twoFactorPage)&&typeof window!="undefined"&&(window.location.href=e.twoFactorPage)})}}}]});var Pt=()=>({id:"magic-link",$InferServerPlugin:{}});export{q as getPasskeyActions,Pt as magicLinkClient,Ze as organizationClient,mt as passkeyClient,yt as twoFactorClient,rt as usernameClient};
package/dist/client.d.ts CHANGED
@@ -3,7 +3,7 @@ import * as nanostores from 'nanostores';
3
3
  import { PreinitializedWritableAtom } from 'nanostores';
4
4
  import * as _better_fetch_fetch from '@better-fetch/fetch';
5
5
  import { BetterFetch, BetterFetchError, BetterFetchOption } from '@better-fetch/fetch';
6
- import { B as BetterAuthPlugin, F as FieldAttribute, I as InferFieldOutput } from './index-BMranMWG.js';
6
+ import { B as BetterAuthPlugin, F as FieldAttribute, I as InferFieldOutput } from './index-BZTQCJvy.js';
7
7
  import { U as UnionToIntersection, P as Prettify } from './helper-C1ihmerM.js';
8
8
  import { ClientOptions, InferClientAPI, InferActions, BetterAuthClientPlugin, InferSessionFromClient, InferUserFromClient, IsSignal } from './types.js';
9
9
  export { AtomListener, InferPluginsFromClient } from './types.js';
@@ -1594,17 +1594,17 @@ declare const signInOAuth: {
1594
1594
  /**
1595
1595
  * OAuth2 provider to use`
1596
1596
  */
1597
- provider: z.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter")[]]>;
1597
+ provider: z.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter")[]]>;
1598
1598
  /**
1599
1599
  * If this is true the session will only be valid for the current browser session
1600
1600
  */
1601
1601
  dontRememberMe: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
1602
1602
  }, "strip", z.ZodTypeAny, {
1603
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter";
1603
+ provider: "github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter";
1604
1604
  callbackURL?: string | undefined;
1605
1605
  dontRememberMe?: boolean | undefined;
1606
1606
  }, {
1607
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter";
1607
+ provider: "github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter";
1608
1608
  callbackURL?: string | undefined;
1609
1609
  dontRememberMe?: boolean | undefined;
1610
1610
  }>;
@@ -1637,17 +1637,17 @@ declare const signInOAuth: {
1637
1637
  /**
1638
1638
  * OAuth2 provider to use`
1639
1639
  */
1640
- provider: z.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter")[]]>;
1640
+ provider: z.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter")[]]>;
1641
1641
  /**
1642
1642
  * If this is true the session will only be valid for the current browser session
1643
1643
  */
1644
1644
  dontRememberMe: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
1645
1645
  }, "strip", z.ZodTypeAny, {
1646
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter";
1646
+ provider: "github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter";
1647
1647
  callbackURL?: string | undefined;
1648
1648
  dontRememberMe?: boolean | undefined;
1649
1649
  }, {
1650
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter";
1650
+ provider: "github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter";
1651
1651
  callbackURL?: string | undefined;
1652
1652
  dontRememberMe?: boolean | undefined;
1653
1653
  }>;
@@ -2731,14 +2731,14 @@ declare function getEndpoints<C extends AuthContext, Option extends BetterAuthOp
2731
2731
  }>>;
2732
2732
  body: zod.ZodObject<{
2733
2733
  callbackURL: zod.ZodOptional<zod.ZodString>;
2734
- provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter")[]]>;
2734
+ provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter")[]]>;
2735
2735
  dontRememberMe: zod.ZodOptional<zod.ZodDefault<zod.ZodBoolean>>;
2736
2736
  }, "strip", zod.ZodTypeAny, {
2737
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter";
2737
+ provider: "github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter";
2738
2738
  callbackURL?: string | undefined;
2739
2739
  dontRememberMe?: boolean | undefined;
2740
2740
  }, {
2741
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter";
2741
+ provider: "github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter";
2742
2742
  callbackURL?: string | undefined;
2743
2743
  dontRememberMe?: boolean | undefined;
2744
2744
  }>;
@@ -2761,14 +2761,14 @@ declare function getEndpoints<C extends AuthContext, Option extends BetterAuthOp
2761
2761
  }>>;
2762
2762
  body: zod.ZodObject<{
2763
2763
  callbackURL: zod.ZodOptional<zod.ZodString>;
2764
- provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter")[]]>;
2764
+ provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter")[]]>;
2765
2765
  dontRememberMe: zod.ZodOptional<zod.ZodDefault<zod.ZodBoolean>>;
2766
2766
  }, "strip", zod.ZodTypeAny, {
2767
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter";
2767
+ provider: "github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter";
2768
2768
  callbackURL?: string | undefined;
2769
2769
  dontRememberMe?: boolean | undefined;
2770
2770
  }, {
2771
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter";
2771
+ provider: "github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter";
2772
2772
  callbackURL?: string | undefined;
2773
2773
  dontRememberMe?: boolean | undefined;
2774
2774
  }>;
@@ -3728,14 +3728,14 @@ declare const router: <C extends AuthContext, Option extends BetterAuthOptions>(
3728
3728
  }>>;
3729
3729
  body: zod.ZodObject<{
3730
3730
  callbackURL: zod.ZodOptional<zod.ZodString>;
3731
- provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter")[]]>;
3731
+ provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter")[]]>;
3732
3732
  dontRememberMe: zod.ZodOptional<zod.ZodDefault<zod.ZodBoolean>>;
3733
3733
  }, "strip", zod.ZodTypeAny, {
3734
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter";
3734
+ provider: "github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter";
3735
3735
  callbackURL?: string | undefined;
3736
3736
  dontRememberMe?: boolean | undefined;
3737
3737
  }, {
3738
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter";
3738
+ provider: "github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter";
3739
3739
  callbackURL?: string | undefined;
3740
3740
  dontRememberMe?: boolean | undefined;
3741
3741
  }>;
@@ -3758,14 +3758,14 @@ declare const router: <C extends AuthContext, Option extends BetterAuthOptions>(
3758
3758
  }>>;
3759
3759
  body: zod.ZodObject<{
3760
3760
  callbackURL: zod.ZodOptional<zod.ZodString>;
3761
- provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter")[]]>;
3761
+ provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter")[]]>;
3762
3762
  dontRememberMe: zod.ZodOptional<zod.ZodDefault<zod.ZodBoolean>>;
3763
3763
  }, "strip", zod.ZodTypeAny, {
3764
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter";
3764
+ provider: "github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter";
3765
3765
  callbackURL?: string | undefined;
3766
3766
  dontRememberMe?: boolean | undefined;
3767
3767
  }, {
3768
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter";
3768
+ provider: "github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter";
3769
3769
  callbackURL?: string | undefined;
3770
3770
  dontRememberMe?: boolean | undefined;
3771
3771
  }>;
@@ -4727,14 +4727,14 @@ declare const betterAuth: <O extends BetterAuthOptions>(options: O) => {
4727
4727
  }>>;
4728
4728
  body: zod.ZodObject<{
4729
4729
  callbackURL: zod.ZodOptional<zod.ZodString>;
4730
- provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter")[]]>;
4730
+ provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter")[]]>;
4731
4731
  dontRememberMe: zod.ZodOptional<zod.ZodDefault<zod.ZodBoolean>>;
4732
4732
  }, "strip", zod.ZodTypeAny, {
4733
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter";
4733
+ provider: "github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter";
4734
4734
  callbackURL?: string | undefined;
4735
4735
  dontRememberMe?: boolean | undefined;
4736
4736
  }, {
4737
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter";
4737
+ provider: "github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter";
4738
4738
  callbackURL?: string | undefined;
4739
4739
  dontRememberMe?: boolean | undefined;
4740
4740
  }>;
@@ -4757,14 +4757,14 @@ declare const betterAuth: <O extends BetterAuthOptions>(options: O) => {
4757
4757
  }>>;
4758
4758
  body: zod.ZodObject<{
4759
4759
  callbackURL: zod.ZodOptional<zod.ZodString>;
4760
- provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter")[]]>;
4760
+ provider: zod.ZodEnum<["github", ...("github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter")[]]>;
4761
4761
  dontRememberMe: zod.ZodOptional<zod.ZodDefault<zod.ZodBoolean>>;
4762
4762
  }, "strip", zod.ZodTypeAny, {
4763
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter";
4763
+ provider: "github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter";
4764
4764
  callbackURL?: string | undefined;
4765
4765
  dontRememberMe?: boolean | undefined;
4766
4766
  }, {
4767
- provider: "apple" | "discord" | "facebook" | "github" | "google" | "spotify" | "twitch" | "twitter";
4767
+ provider: "github" | "apple" | "discord" | "facebook" | "google" | "spotify" | "twitch" | "twitter";
4768
4768
  callbackURL?: string | undefined;
4769
4769
  dontRememberMe?: boolean | undefined;
4770
4770
  }>;
@@ -5681,4 +5681,4 @@ type Auth = {
5681
5681
  options: BetterAuthOptions;
5682
5682
  };
5683
5683
 
5684
- export { ok as $, type Auth as A, type BetterAuthPlugin as B, getSessionFromCtx as C, sessionMiddleware as D, listSessions as E, type FieldAttribute as F, type GenericEndpointContext as G, type HookEndpointContext as H, type InferFieldOutput as I, revokeSession as J, revokeSessions as K, signOut as L, forgetPassword as M, forgetPasswordCallback as N, resetPassword as O, type PluginSchema as P, createEmailVerificationToken as Q, type RateLimit as R, type SessionAdapter as S, sendVerificationEmail as T, verifyEmail as U, updateUser as V, type Where as W, changePassword as X, setPassword as Y, getCSRFToken as Z, error as _, type BetterAuthOptions as a, signUpEmail as a0, csrfMiddleware as a1, betterAuth as a2, createAuthEndpoint as b, createAuthMiddleware as c, type AuthEndpoint as d, type AuthMiddleware as e, type AuthContext as f, getCookies as g, createCookieGetter as h, type BetterAuthCookies as i, deleteSessionCookie as j, createLogger as k, logger as l, type InferSession as m, type InferUser as n, optionsMiddleware as o, parseSetCookieHeader as p, type InferPluginTypes as q, init as r, setSessionCookie as s, type Adapter as t, getEndpoints as u, router as v, signInOAuth as w, signInEmail as x, callbackOAuth as y, getSession as z };
5684
+ export { ok as $, type AuthEndpoint as A, type BetterAuthPlugin as B, getSessionFromCtx as C, sessionMiddleware as D, listSessions as E, type FieldAttribute as F, type GenericEndpointContext as G, type HookEndpointContext as H, type InferFieldOutput as I, revokeSession as J, revokeSessions as K, signOut as L, forgetPassword as M, forgetPasswordCallback as N, resetPassword as O, type PluginSchema as P, createEmailVerificationToken as Q, type RateLimit as R, type SessionAdapter as S, sendVerificationEmail as T, verifyEmail as U, updateUser as V, type Where as W, changePassword as X, setPassword as Y, getCSRFToken as Z, error as _, createAuthEndpoint as a, signUpEmail as a0, csrfMiddleware as a1, betterAuth as a2, type AuthMiddleware as b, createAuthMiddleware as c, type Auth as d, type BetterAuthOptions as e, type AuthContext as f, getCookies as g, createCookieGetter as h, type BetterAuthCookies as i, deleteSessionCookie as j, createLogger as k, logger as l, type InferSession as m, type InferUser as n, optionsMiddleware as o, parseSetCookieHeader as p, type InferPluginTypes as q, init as r, setSessionCookie as s, type Adapter as t, getEndpoints as u, router as v, signInOAuth as w, signInEmail as x, callbackOAuth as y, getSession as z };
@@ -5,7 +5,7 @@ import { P as Prettify } from './helper-C1ihmerM.js';
5
5
  import { A as AccessControl, R as Role, S as StatementsPrimitive, g as defaultRoles } from './statement-CU-fdHXK.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 } from './index-BMranMWG.js';
8
+ import { H as HookEndpointContext } from './index-BZTQCJvy.js';
9
9
  import * as nanostores from 'nanostores';
10
10
  import { atom } from 'nanostores';
11
11
  import * as _simplewebauthn_types from '@simplewebauthn/types';
@@ -4195,4 +4195,101 @@ declare const username: () => {
4195
4195
  };
4196
4196
  };
4197
4197
 
4198
- export { type Invitation as I, type Member as M, type OrganizationOptions as O, type PasskeyOptions as P, type WebAuthnCookieType as W, twoFactorClient as a, type Passkey as b, passkeyClient as c, type Organization as d, getPasskeyActions as g, organization as o, passkey as p, twoFactor as t, username as u };
4198
+ interface MagicLinkOptions {
4199
+ /**
4200
+ * Time in seconds until the magic link expires.
4201
+ * @default (60 * 5) // 5 minutes
4202
+ */
4203
+ expiresIn?: number;
4204
+ /**
4205
+ * Send magic link implementation.
4206
+ */
4207
+ sendMagicLink: (data: {
4208
+ email: string;
4209
+ url: string;
4210
+ token: string;
4211
+ }) => Promise<void> | void;
4212
+ }
4213
+ declare const magicLink: (options: MagicLinkOptions) => {
4214
+ id: "magic-link";
4215
+ endpoints: {
4216
+ signInMagicLink: {
4217
+ (ctx_0: better_call.Context<"/sign-in/magic-link", {
4218
+ method: "POST";
4219
+ requireHeaders: true;
4220
+ body: z.ZodObject<{
4221
+ email: z.ZodString;
4222
+ callbackURL: z.ZodOptional<z.ZodString>;
4223
+ currentURL: z.ZodOptional<z.ZodString>;
4224
+ }, "strip", z.ZodTypeAny, {
4225
+ email: string;
4226
+ currentURL?: string | undefined;
4227
+ callbackURL?: string | undefined;
4228
+ }, {
4229
+ email: string;
4230
+ currentURL?: string | undefined;
4231
+ callbackURL?: string | undefined;
4232
+ }>;
4233
+ }>): Promise<{
4234
+ status: boolean;
4235
+ }>;
4236
+ path: "/sign-in/magic-link";
4237
+ options: {
4238
+ method: "POST";
4239
+ requireHeaders: true;
4240
+ body: z.ZodObject<{
4241
+ email: z.ZodString;
4242
+ callbackURL: z.ZodOptional<z.ZodString>;
4243
+ currentURL: z.ZodOptional<z.ZodString>;
4244
+ }, "strip", z.ZodTypeAny, {
4245
+ email: string;
4246
+ currentURL?: string | undefined;
4247
+ callbackURL?: string | undefined;
4248
+ }, {
4249
+ email: string;
4250
+ currentURL?: string | undefined;
4251
+ callbackURL?: string | undefined;
4252
+ }>;
4253
+ };
4254
+ method: better_call.Method | better_call.Method[];
4255
+ headers: Headers;
4256
+ };
4257
+ magicLinkVerify: {
4258
+ (ctx_0: better_call.Context<"/magic-link/verify", {
4259
+ method: "GET";
4260
+ query: z.ZodObject<{
4261
+ token: z.ZodString;
4262
+ callbackURL: z.ZodOptional<z.ZodString>;
4263
+ }, "strip", z.ZodTypeAny, {
4264
+ token: string;
4265
+ callbackURL?: string | undefined;
4266
+ }, {
4267
+ token: string;
4268
+ callbackURL?: string | undefined;
4269
+ }>;
4270
+ requireHeaders: true;
4271
+ }>): Promise<{
4272
+ status: boolean;
4273
+ } | null>;
4274
+ path: "/magic-link/verify";
4275
+ options: {
4276
+ method: "GET";
4277
+ query: z.ZodObject<{
4278
+ token: z.ZodString;
4279
+ callbackURL: z.ZodOptional<z.ZodString>;
4280
+ }, "strip", z.ZodTypeAny, {
4281
+ token: string;
4282
+ callbackURL?: string | undefined;
4283
+ }, {
4284
+ token: string;
4285
+ callbackURL?: string | undefined;
4286
+ }>;
4287
+ requireHeaders: true;
4288
+ };
4289
+ method: better_call.Method | better_call.Method[];
4290
+ headers: Headers;
4291
+ };
4292
+ };
4293
+ };
4294
+
4295
+ export { type Invitation as I, type Member as M, type OrganizationOptions as O, type PasskeyOptions as P, type WebAuthnCookieType as W, twoFactorClient as a, type Passkey as b, passkeyClient as c, type Organization as d, getPasskeyActions as g, magicLink as m, organization as o, passkey as p, twoFactor as t, username as u };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { A as Auth, a2 as betterAuth } from './index-BMranMWG.js';
1
+ export { d as Auth, a2 as betterAuth } from './index-BZTQCJvy.js';
2
2
  import 'kysely';
3
3
  import './index-C8A40nOX.js';
4
4
  import 'arctic';