better-auth 0.7.5-beta.9 → 0.7.5

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/plugins.cjs CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";var no=Object.create;var We=Object.defineProperty;var io=Object.getOwnPropertyDescriptor;var so=Object.getOwnPropertyNames;var ao=Object.getPrototypeOf,co=Object.prototype.hasOwnProperty;var uo=(e,t)=>{for(var r in t)We(e,r,{get:t[r],enumerable:!0})},xt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of so(t))!co.call(e,n)&&n!==r&&We(e,n,{get:()=>t[n],enumerable:!(o=io(t,n))||o.enumerable});return e};var Dt=(e,t,r)=>(r=e!=null?no(ao(e)):{},xt(t||!e||!e.__esModule?We(r,"default",{value:e,enumerable:!0}):r,e)),lo=e=>xt(We({},"__esModule",{value:!0}),e);var En={};uo(En,{HIDE_METADATA:()=>ge,admin:()=>hn,adminMiddleware:()=>J,anonymous:()=>gn,bearer:()=>ln,createAuthEndpoint:()=>c,createAuthMiddleware:()=>S,emailOTP:()=>kn,genericOAuth:()=>yn,getPasskeyActions:()=>Jr,jwt:()=>bn,magicLink:()=>pn,multiSession:()=>An,oAuthProxy:()=>Rn,oneTap:()=>On,optionsMiddleware:()=>pt,organization:()=>Ko,passkey:()=>un,passkeyClient:()=>cn,phoneNumber:()=>fn,twoFactor:()=>sn,twoFactorClient:()=>nn,username:()=>Ct});module.exports=lo(En);var At=require("better-call"),Pe=require("zod");var fe=require("better-call"),pt=(0,fe.createMiddleware)(async()=>({})),S=(0,fe.createMiddlewareCreator)({use:[pt,(0,fe.createMiddleware)(async()=>({}))]}),c=(0,fe.createEndpointCreator)({use:[pt]});var K=require("better-call"),q=require("zod");var fo=require("oslo");var W=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}};var Ge=Object.create(null),xe=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Ge:globalThis),G=new Proxy(Ge,{get(e,t){return xe()[t]??Ge[t]},has(e,t){let r=xe();return t in r||t in Ge},set(e,t,r){let o=xe(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=xe(!0);return delete r[t],!0},ownKeys(){let e=xe(!0);return Object.keys(e)}});function po(e){return e?e!=="false":!1}var mt=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var jt=mt==="dev"||mt==="development",mo=mt==="test"||po(G.TEST);async function w(e,t,r,o){let n=e.context.authCookies.sessionToken.options;n.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.id,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&await e.setSignedCookie(e.context.authCookies.sessionData.name,JSON.stringify(t),e.context.secret,e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.id,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function re(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}function Nt(e){let t=new Map;return e.split(", ").forEach(o=>{let[n,...i]=o.split("; "),[a,s]=n.split("="),d={value:s};i.forEach(u=>{let[l,p]=u.split("=");d[l.toLowerCase()]=p||!0}),t.set(a,d)}),t}function Ke(e){let t=e.split("; "),r=new Map;return t.forEach(o=>{let[n,i]=o.split("=");r.set(n,i)}),r}var Wt=require("oslo/jwt");var Ft=require("oslo/crypto"),Vt=require("oslo/encoding");var C=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function Mt(e){let t=await(0,Ft.sha256)(new TextEncoder().encode(e));return Vt.base64url.encode(new Uint8Array(t),{includePadding:!1})}function qt(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?C(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function U({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:a,redirectURI:s}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",i.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||s),n){let u=await Mt(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",u)}if(a){let u=a.reduce((l,p)=>(l[p]=null,l),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return d}var $t=require("@better-fetch/fetch");async function v({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:a,error:s}=await(0,$t.betterFetch)(n,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(s)throw s;return qt(a)}var Ze=require("oslo/oauth2"),oe=require("zod"),ft=require("better-call");var ge={isAction:!1};var Qt=require("nanoid"),z=e=>(0,Qt.nanoid)(e);var Ht=require("consola"),he=(0,Ht.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),go=e=>({log:(...t)=>{!e?.disabled&&he.log("",...t)},error:(...t)=>{!e?.disabled&&he.error("",...t)},warn:(...t)=>{!e?.disabled&&he.warn("",...t)},info:(...t)=>{!e?.disabled&&he.info("",...t)},debug:(...t)=>{!e?.disabled&&he.debug("",...t)},box:(...t)=>{!e?.disabled&&he.box("",...t)},success:(...t)=>{!e?.disabled&&he.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
2
- `)}}),y=go();function Je(e){try{return new URL(e).origin}catch{return null}}async function Re(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Je(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ft.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,Ze.generateCodeVerifier)(),n=(0,Ze.generateState)(),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),a=new Date;a.setMinutes(a.getMinutes()+10);let s=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:a});if(!s)throw y.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ft.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:s.identifier,codeVerifier:o}}async function Ye(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw y.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=oe.z.object({callbackURL:oe.z.string(),codeVerifier:oe.z.string(),errorURL:oe.z.string().optional(),expiresAt:oe.z.number(),link:oe.z.object({email:oe.z.string(),userId:oe.z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),y.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var Gt=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name","openid"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>v({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=(0,Wt.parseJWT)(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};var Kt=require("@better-fetch/fetch");var Jt=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>v({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,Kt.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var Zt=require("@better-fetch/fetch");var Yt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await U({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>v({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await(0,Zt.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});var gt=require("@better-fetch/fetch");var Xt=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let a=o||["user:email"];return e.scope&&a.push(...e.scope),U({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>v({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,gt.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:a,error:s}=await(0,gt.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});s||(o.email=(a.find(d=>d.primary)??a[0])?.email,i=a.find(d=>d.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};var er=require("oslo/jwt");var tr=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw y.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new W("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new W("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let a=await U({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});return e.accessType&&a.searchParams.set("access_type",e.accessType),e.prompt&&a.searchParams.set("prompt",e.prompt),a},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>v({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=(0,er.parseJWT)(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});var rr=require("@better-fetch/fetch"),or=require("oslo/jwt");var nr=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),U({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:a}){return v({code:n,codeVerifier:i,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=(0,or.parseJWT)(n.idToken)?.payload,a=e.profilePhotoSize||48;return await(0,rr.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(s){if(!(e.disableProfilePhoto||!s.response.ok))try{let u=await s.response.clone().arrayBuffer(),l=Buffer.from(u).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(d){y.error(d)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};var ir=require("@better-fetch/fetch");var sr=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),U({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>v({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,ir.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});var Ii=require("@better-fetch/fetch");var ar=require("oslo/jwt");var dr=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),U({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>v({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return y.error("No idToken found in token"),null;let o=(0,ar.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var cr=require("@better-fetch/fetch");var ur=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["account_info.read"];return e.scope&&r.push(...e.scope),U({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>v({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,cr.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var lr=require("@better-fetch/fetch");var pr=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let a=o||["account_info.read"];return e.scope&&a.push(...e.scope),await U({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await v({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,lr.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};var mr=require("@better-fetch/fetch");var fr=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let a=n||["profile","email","openid"];return e.scope&&a.push(...e.scope),await U({id:"linkedin",options:e,authorizationEndpoint:t,scopes:a,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await v({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await(0,mr.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};var gr=require("@better-fetch/fetch");var ht=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),ho=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ht(`${t}/oauth/authorize`),tokenEndpoint:ht(`${t}/oauth/token`),userinfoEndpoint:ht(`${t}/api/v4/user`)}},hr=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=ho(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:a,scopes:s,codeVerifier:d,redirectURI:u})=>{let l=s||["read_user"];return e.scope&&l.push(...e.scope),await U({id:n,options:e,authorizationEndpoint:t,scopes:l,state:a,redirectURI:u,codeVerifier:d})},validateAuthorizationCode:async({code:a,redirectURI:s,codeVerifier:d})=>v({code:a,redirectURI:e.redirectURI||s,options:e,codeVerifier:d,tokenEndpoint:r}),async getUserInfo(a){let{data:s,error:d}=await(0,gr.betterFetch)(o,{headers:{authorization:`Bearer ${a.accessToken}`}});return d||s.state!=="active"||s.locked?null:{user:{id:s.id.toString(),name:s.name??s.username,email:s.email,image:s.avatar_url,emailVerified:!0},data:s}}}};var wo={apple:Gt,discord:Jt,facebook:Yt,github:Xt,microsoft:nr,google:tr,spotify:sr,twitch:dr,twitter:ur,dropbox:pr,linkedin:fr,gitlab:hr},Xe=Object.keys(wo);var yr=require("oslo"),et=require("oslo/jwt"),M=require("zod");var we=require("better-call");var Ee=require("better-call");var Ue=require("zod"),wr=()=>c("/get-session",{method:"GET",query:Ue.z.optional(Ue.z.object({disableCookieCache:Ue.z.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.getSignedCookie(e.context.authCookies.sessionData.name,e.context.secret),o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(r&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let u=JSON.parse(r)?.session;if(u?.expiresAt>new Date)return e.json(u)}let n=await e.context.internalAdapter.findSession(t);if(!n||n.session.expiresAt<new Date)return re(e),n&&await e.context.internalAdapter.deleteSession(n.session.id),e.json(null,{status:401});if(o)return e.json(n);let i=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-i*1e3+a*1e3<=Date.now()){let u=await e.context.internalAdapter.updateSession(n.session.id,{expiresAt:C(e.context.sessionConfig.expiresIn,"sec")});if(!u)return re(e),e.json(null,{status:401});let l=(u.expiresAt.valueOf()-Date.now())/1e3;return await w(e,{session:u,user:n.user},!1,{maxAge:l}),e.json({session:u,user:n.user})}return e.json(n)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),x=async e=>await wr()({...e,_flag:"json",headers:e.headers}),A=S(async e=>{let t=await x(e);if(!t?.session)throw new Ee.APIError("UNAUTHORIZED");return{session:t}});var yo=c("/revoke-session",{method:"POST",body:Ue.z.object({id:Ue.z.string()}),use:[A],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new Ee.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new Ee.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new Ee.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),bo=c("/revoke-sessions",{method:"POST",use:[A],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new Ee.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function se(e,t,r){return await(0,et.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new yr.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Ao=c("/send-verification-email",{method:"POST",query:M.z.object({currentURL:M.z.string().optional()}).optional(),body:M.z.object({email:M.z.string().email(),callbackURL:M.z.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new we.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new we.APIError("BAD_REQUEST",{message:"User not found"});let o=await se(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,n,o),e.json({status:!0})}),ko=c("/verify-email",{method:"GET",query:M.z.object({token:M.z.string(),callbackURL:M.z.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await(0,et.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(a){throw e.context.logger.error("Failed to verify email",a),new we.APIError("BAD_REQUEST",{message:"Invalid token"})}let n=M.z.object({email:M.z.string().email(),updateTo:M.z.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new we.APIError("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let a=await x(e);if(!a)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new we.APIError("UNAUTHORIZED",{message:"Session not found"});if(a.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new we.APIError("UNAUTHORIZED",{message:"Invalid session"});let s=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(s,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:s,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var Oo=c("/sign-in/social",{method:"POST",query:q.z.object({currentURL:q.z.string().optional()}).optional(),body:q.z.object({callbackURL:q.z.string().optional(),provider:q.z.enum(Xe)})},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new K.APIError("NOT_FOUND",{message:"Provider not found"});let{codeVerifier:r,state:o}=await Re(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!0})}),vo=c("/sign-in/email",{method:"POST",body:q.z.object({email:q.z.string(),password:q.z.string(),callbackURL:q.z.string().optional(),dontRememberMe:q.z.boolean().default(!1).optional()})},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new K.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!q.z.string().email().safeParse(t).success)throw new K.APIError("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new K.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(u=>u.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new K.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let a=i?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new K.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new K.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw y.error("Email verification is required but no email verification handler is provided"),new K.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let u=await se(e.context.secret,n.user.email),l=`${e.context.options.baseURL}/verify-email?token=${u}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,l,u),e.context.logger.error("Email not verified",{email:t}),new K.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new K.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await w(e,{session:d,user:n.user},e.body.dontRememberMe),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var De=require("zod");var O=require("zod"),Rs=O.z.object({id:O.z.string(),providerId:O.z.string(),accountId:O.z.string(),userId:O.z.string(),accessToken:O.z.string().nullable().optional(),refreshToken:O.z.string().nullable().optional(),idToken:O.z.string().nullable().optional(),expiresAt:O.z.date().nullable().optional(),password:O.z.string().optional().nullable()}),tt=O.z.object({id:O.z.string(),email:O.z.string().transform(e=>e.toLowerCase()),emailVerified:O.z.boolean().default(!1),name:O.z.string(),image:O.z.string().optional(),createdAt:O.z.date().default(new Date),updatedAt:O.z.date().default(new Date)}),Es=O.z.object({id:O.z.string(),userId:O.z.string(),expiresAt:O.z.date(),ipAddress:O.z.string().optional(),userAgent:O.z.string().optional()}),Us=O.z.object({id:O.z.string(),value:O.z.string(),expiresAt:O.z.date(),identifier:O.z.string()});var Ro=c("/callback/:id",{method:"GET",query:De.z.object({state:De.z.string(),code:De.z.string().optional(),error:De.z.string().optional()}),metadata:ge},async e=>{if(!e.query.code)throw e.redirect(`${e.context.baseURL}/error?error=${e.query.error||"no_code"}`);let t=e.context.socialProviders.find(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{codeVerifier:r,callbackURL:o,link:n,errorURL:i}=await Ye(e),a;try{a=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(b){throw e.context.logger.error(b),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let s=await t.getUserInfo(a).then(b=>b?.user),d=z(),u=tt.safeParse({...s,id:d});if(!s||u.success===!1)throw y.error("Unable to get user info",u.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw y.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(n){if(n.email!==s.email.toLowerCase())return l("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:n.userId,providerId:t.id,accountId:s.id}))return l("unable_to_link_account");let h;try{h=new URL(o).toString()}catch{h=o}throw e.redirect(h)}function l(b){throw e.redirect(`${i||o||`${e.context.baseURL}/error`}?error=${b}`)}let p=await e.context.internalAdapter.findUserByEmail(s.email,{includeAccounts:!0}).catch(b=>{throw y.error(`Better auth was unable to query your database.
3
- Error: `,b),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),f=p?.user;if(p){let b=p.accounts.find(h=>h.providerId===t.id);if(b)await e.context.internalAdapter.updateAccount(b.id,{accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt});else{(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!s.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)&&(jt&&y.warn(`User already exist but account isn't linked to ${t.id}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),l("account_not_linked"));try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:s.id.toString(),id:`${t.id}:${s.id}`,userId:p.user.id,accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt})}catch(Oe){y.error("Unable to link account",Oe),l("unable_to_link_account")}}}else try{let b=s.emailVerified||!1;if(f=await e.context.internalAdapter.createOAuthUser({...u.data,emailVerified:b},{accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt,providerId:t.id,accountId:s.id.toString()}).then(h=>h?.user),!b&&f&&e.context.options.emailVerification?.sendOnSignUp){let h=await se(e.context.secret,f.email),_=`${e.context.baseURL}/verify-email?token=${h}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(f,_,h)}}catch(b){y.error("Unable to create user",b),l("unable_to_create_user")}if(!f)return l("unable_to_create_user");let m=await e.context.internalAdapter.createSession(f.id,e.request);m||l("unable_to_create_session"),await w(e,{session:m,user:f});let k;try{k=new URL(o).toString()}catch{k=o}throw e.redirect(k)});var js=require("zod");var br=require("better-call"),Eo=c("/sign-out",{method:"POST",requireHeaders:!0},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new br.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),re(e),e.json({success:!0})});var $=require("zod");var je=require("better-call");function Ar(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function Uo(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var Io=c("/forget-password",{method:"POST",body:$.z.object({email:$.z.string().email(),redirectTo:$.z.string()})},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new je.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n)),a=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${a}`,expiresAt:i});let s=`${e.context.baseURL}/reset-password/${a}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,s),e.json({status:!0})}),To=c("/reset-password/:token",{method:"GET",query:$.z.object({callbackURL:$.z.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(Ar(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Ar(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Uo(e.context,r,{token:t}))}),So=c("/reset-password",{query:$.z.optional($.z.object({token:$.z.string().optional(),currentURL:$.z.string().optional()})),method:"POST",body:$.z.object({newPassword:$.z.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new je.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new je.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,a=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(i)).find(l=>l.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:a,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(i,a))throw new je.APIError("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});var j=require("zod");var D=require("better-call");var _o=c("/change-password",{method:"POST",body:j.z.object({newPassword:j.z.string(),currentPassword:j.z.string(),revokeOtherSessions:j.z.boolean().optional()}),use:[A]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new D.APIError("BAD_REQUEST",{message:"Password is too short"});let a=e.context.password.config.maxPasswordLength;if(t.length>a)throw e.context.logger.error("Password is too long"),new D.APIError("BAD_REQUEST",{message:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(n.user.id)).find(p=>p.providerId==="credential"&&p.password);if(!d||!d.password)throw new D.APIError("BAD_REQUEST",{message:"User does not have a password"});let u=await e.context.password.hash(t);if(!await e.context.password.verify(d.password,r))throw new D.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:u}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let p=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!p)throw new D.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await w(e,{session:p,user:n.user})}return e.json(n.user)}),Co=c("/set-password",{method:"POST",body:j.z.object({newPassword:j.z.string()}),metadata:{SERVER_ONLY:!0},use:[A]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new D.APIError("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new D.APIError("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(d=>d.providerId==="credential"&&d.password),s=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:s}),e.json(r.user);throw new D.APIError("BAD_REQUEST",{message:"user already has a password"})}),zo=c("/delete-user",{method:"POST",body:j.z.object({password:j.z.string()}),use:[A]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password);if(!n||!n.password)throw new D.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new D.APIError("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),re(e),e.json(null)}),Bo=c("/change-email",{method:"POST",query:j.z.object({currentURL:j.z.string().optional()}).optional(),body:j.z.object({newEmail:j.z.string().email(),callbackURL:j.z.string().optional()}),use:[A]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new D.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new D.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new D.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new D.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await se(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification(e.context.session.user,e.body.newEmail,o,r),e.json({user:null,status:!0})});var Lo=(e="Unknown")=>`<!DOCTYPE html>
1
+ "use strict";var no=Object.create;var He=Object.defineProperty;var io=Object.getOwnPropertyDescriptor;var so=Object.getOwnPropertyNames;var ao=Object.getPrototypeOf,co=Object.prototype.hasOwnProperty;var uo=(e,t)=>{for(var r in t)He(e,r,{get:t[r],enumerable:!0})},xt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of so(t))!co.call(e,n)&&n!==r&&He(e,n,{get:()=>t[n],enumerable:!(o=io(t,n))||o.enumerable});return e};var Dt=(e,t,r)=>(r=e!=null?no(ao(e)):{},xt(t||!e||!e.__esModule?He(r,"default",{value:e,enumerable:!0}):r,e)),lo=e=>xt(He({},"__esModule",{value:!0}),e);var En={};uo(En,{HIDE_METADATA:()=>fe,admin:()=>hn,adminMiddleware:()=>J,anonymous:()=>gn,bearer:()=>ln,createAuthEndpoint:()=>c,createAuthMiddleware:()=>S,emailOTP:()=>kn,genericOAuth:()=>yn,getPasskeyActions:()=>Jr,jwt:()=>bn,magicLink:()=>pn,multiSession:()=>An,oAuthProxy:()=>vn,oneTap:()=>On,optionsMiddleware:()=>pt,organization:()=>Ko,passkey:()=>un,passkeyClient:()=>cn,phoneNumber:()=>fn,twoFactor:()=>sn,twoFactorClient:()=>nn,username:()=>Ct});module.exports=lo(En);var At=require("better-call"),Te=require("zod");var me=require("better-call"),pt=(0,me.createMiddleware)(async()=>({})),S=(0,me.createMiddlewareCreator)({use:[pt,(0,me.createMiddleware)(async()=>({}))]}),c=(0,me.createEndpointCreator)({use:[pt]});var K=require("better-call"),M=require("zod");var fo=require("oslo");var H=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}};var Ge=Object.create(null),Le=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Ge:globalThis),G=new Proxy(Ge,{get(e,t){return Le()[t]??Ge[t]},has(e,t){let r=Le();return t in r||t in Ge},set(e,t,r){let o=Le(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=Le(!0);return delete r[t],!0},ownKeys(){let e=Le(!0);return Object.keys(e)}});function po(e){return e?e!=="false":!1}var mt=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var jt=mt==="dev"||mt==="development",mo=mt==="test"||po(G.TEST);async function w(e,t,r,o){let n=e.context.authCookies.sessionToken.options;n.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.id,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&await e.setSignedCookie(e.context.authCookies.sessionData.name,JSON.stringify(t),e.context.secret,e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.id,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function re(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}function Nt(e){let t=new Map;return e.split(", ").forEach(o=>{let[n,...i]=o.split("; "),[a,s]=n.split("="),d={value:s};i.forEach(u=>{let[l,m]=u.split("=");d[l.toLowerCase()]=m||!0}),t.set(a,d)}),t}function Ke(e){let t=e.split("; "),r=new Map;return t.forEach(o=>{let[n,i]=o.split("=");r.set(n,i)}),r}var Ht=require("oslo/jwt");var Ft=require("oslo/crypto"),Vt=require("oslo/encoding");var C=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function qt(e){let t=await(0,Ft.sha256)(new TextEncoder().encode(e));return Vt.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Mt(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?C(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function U({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:a,redirectURI:s}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",i.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||s),n){let u=await qt(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",u)}if(a){let u=a.reduce((l,m)=>(l[m]=null,l),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return d}var $t=require("@better-fetch/fetch");async function R({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:a,error:s}=await(0,$t.betterFetch)(n,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(s)throw s;return Mt(a)}var Ze=require("oslo/oauth2"),oe=require("zod"),ft=require("better-call");var fe={isAction:!1};var Qt=require("nanoid"),z=e=>(0,Qt.nanoid)(e);var Wt=require("consola"),ge=(0,Wt.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),go=e=>({log:(...t)=>{!e?.disabled&&ge.log("",...t)},error:(...t)=>{!e?.disabled&&ge.error("",...t)},warn:(...t)=>{!e?.disabled&&ge.warn("",...t)},info:(...t)=>{!e?.disabled&&ge.info("",...t)},debug:(...t)=>{!e?.disabled&&ge.debug("",...t)},box:(...t)=>{!e?.disabled&&ge.box("",...t)},success:(...t)=>{!e?.disabled&&ge.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
2
+ `)}}),y=go();function Je(e){try{return new URL(e).origin}catch{return null}}async function Oe(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Je(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ft.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,Ze.generateCodeVerifier)(),n=(0,Ze.generateState)(),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),a=new Date;a.setMinutes(a.getMinutes()+10);let s=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:a});if(!s)throw y.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ft.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:s.identifier,codeVerifier:o}}async function Ye(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw y.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=oe.z.object({callbackURL:oe.z.string(),codeVerifier:oe.z.string(),errorURL:oe.z.string().optional(),expiresAt:oe.z.number(),link:oe.z.object({email:oe.z.string(),userId:oe.z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),y.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var Gt=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name","openid"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>R({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=(0,Ht.parseJWT)(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};var Kt=require("@better-fetch/fetch");var Jt=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>R({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,Kt.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var Zt=require("@better-fetch/fetch");var Yt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await U({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>R({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await(0,Zt.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});var gt=require("@better-fetch/fetch");var Xt=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let a=o||["user:email"];return e.scope&&a.push(...e.scope),U({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>R({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,gt.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:a,error:s}=await(0,gt.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});s||(o.email=(a.find(d=>d.primary)??a[0])?.email,i=a.find(d=>d.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};var er=require("oslo/jwt");var tr=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw y.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new H("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new H("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let a=await U({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});return e.accessType&&a.searchParams.set("access_type",e.accessType),e.prompt&&a.searchParams.set("prompt",e.prompt),a},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>R({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=(0,er.parseJWT)(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});var rr=require("@better-fetch/fetch"),or=require("oslo/jwt");var nr=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),U({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:a}){return R({code:n,codeVerifier:i,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=(0,or.parseJWT)(n.idToken)?.payload,a=e.profilePhotoSize||48;return await(0,rr.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(s){if(!(e.disableProfilePhoto||!s.response.ok))try{let u=await s.response.clone().arrayBuffer(),l=Buffer.from(u).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(d){y.error(d)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};var ir=require("@better-fetch/fetch");var sr=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),U({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>R({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,ir.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});var Ii=require("@better-fetch/fetch");var ar=require("oslo/jwt");var dr=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),U({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>R({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return y.error("No idToken found in token"),null;let o=(0,ar.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var cr=require("@better-fetch/fetch");var ur=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["account_info.read"];return e.scope&&r.push(...e.scope),U({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>R({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,cr.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var lr=require("@better-fetch/fetch");var pr=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let a=o||["account_info.read"];return e.scope&&a.push(...e.scope),await U({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await R({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,lr.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};var mr=require("@better-fetch/fetch");var fr=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let a=n||["profile","email","openid"];return e.scope&&a.push(...e.scope),await U({id:"linkedin",options:e,authorizationEndpoint:t,scopes:a,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await R({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await(0,mr.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};var gr=require("@better-fetch/fetch");var ht=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),ho=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ht(`${t}/oauth/authorize`),tokenEndpoint:ht(`${t}/oauth/token`),userinfoEndpoint:ht(`${t}/api/v4/user`)}},hr=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=ho(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:a,scopes:s,codeVerifier:d,redirectURI:u})=>{let l=s||["read_user"];return e.scope&&l.push(...e.scope),await U({id:n,options:e,authorizationEndpoint:t,scopes:l,state:a,redirectURI:u,codeVerifier:d})},validateAuthorizationCode:async({code:a,redirectURI:s,codeVerifier:d})=>R({code:a,redirectURI:e.redirectURI||s,options:e,codeVerifier:d,tokenEndpoint:r}),async getUserInfo(a){let{data:s,error:d}=await(0,gr.betterFetch)(o,{headers:{authorization:`Bearer ${a.accessToken}`}});return d||s.state!=="active"||s.locked?null:{user:{id:s.id.toString(),name:s.name??s.username,email:s.email,image:s.avatar_url,emailVerified:!0},data:s}}}};var wo={apple:Gt,discord:Jt,facebook:Yt,github:Xt,microsoft:nr,google:tr,spotify:sr,twitch:dr,twitter:ur,dropbox:pr,linkedin:fr,gitlab:hr},Xe=Object.keys(wo);var yr=require("oslo"),et=require("oslo/jwt"),q=require("zod");var he=require("better-call");var Re=require("better-call");var ve=require("zod"),wr=()=>c("/get-session",{method:"GET",query:ve.z.optional(ve.z.object({disableCookieCache:ve.z.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.getSignedCookie(e.context.authCookies.sessionData.name,e.context.secret),o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(r&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let u=JSON.parse(r)?.session;if(u?.expiresAt>new Date)return e.json(u)}let n=await e.context.internalAdapter.findSession(t);if(!n||n.session.expiresAt<new Date)return re(e),n&&await e.context.internalAdapter.deleteSession(n.session.id),e.json(null,{status:401});if(o)return e.json(n);let i=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-i*1e3+a*1e3<=Date.now()){let u=await e.context.internalAdapter.updateSession(n.session.id,{expiresAt:C(e.context.sessionConfig.expiresIn,"sec")});if(!u)return re(e),e.json(null,{status:401});let l=(u.expiresAt.valueOf()-Date.now())/1e3;return await w(e,{session:u,user:n.user},!1,{maxAge:l}),e.json({session:u,user:n.user})}return e.json(n)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),x=async e=>await wr()({...e,_flag:"json",headers:e.headers}),A=S(async e=>{let t=await x(e);if(!t?.session)throw new Re.APIError("UNAUTHORIZED");return{session:t}});var yo=c("/revoke-session",{method:"POST",body:ve.z.object({id:ve.z.string()}),use:[A],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new Re.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new Re.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new Re.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),bo=c("/revoke-sessions",{method:"POST",use:[A],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new Re.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function ie(e,t,r){return await(0,et.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new yr.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Ao=c("/send-verification-email",{method:"POST",query:q.z.object({currentURL:q.z.string().optional()}).optional(),body:q.z.object({email:q.z.string().email(),callbackURL:q.z.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new he.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new he.APIError("BAD_REQUEST",{message:"User not found"});let o=await ie(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,n,o),e.json({status:!0})}),ko=c("/verify-email",{method:"GET",query:q.z.object({token:q.z.string(),callbackURL:q.z.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await(0,et.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(a){throw e.context.logger.error("Failed to verify email",a),new he.APIError("BAD_REQUEST",{message:"Invalid token"})}let n=q.z.object({email:q.z.string().email(),updateTo:q.z.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new he.APIError("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let a=await x(e);if(!a)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new he.APIError("UNAUTHORIZED",{message:"Session not found"});if(a.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new he.APIError("UNAUTHORIZED",{message:"Invalid session"});let s=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(s,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:s,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var Oo=c("/sign-in/social",{method:"POST",query:M.z.object({currentURL:M.z.string().optional()}).optional(),body:M.z.object({callbackURL:M.z.string().optional(),provider:M.z.enum(Xe)})},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new K.APIError("NOT_FOUND",{message:"Provider not found"});let{codeVerifier:r,state:o}=await Oe(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!0})}),Ro=c("/sign-in/email",{method:"POST",body:M.z.object({email:M.z.string(),password:M.z.string(),callbackURL:M.z.string().optional(),dontRememberMe:M.z.boolean().default(!1).optional()})},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new K.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!M.z.string().email().safeParse(t).success)throw new K.APIError("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new K.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(u=>u.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new K.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let a=i?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new K.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new K.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw y.error("Email verification is required but no email verification handler is provided"),new K.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let u=await ie(e.context.secret,n.user.email),l=`${e.context.options.baseURL}/verify-email?token=${u}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,l,u),e.context.logger.error("Email not verified",{email:t}),new K.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new K.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await w(e,{session:d,user:n.user},e.body.dontRememberMe),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var xe=require("zod");var O=require("zod"),vs=O.z.object({id:O.z.string(),providerId:O.z.string(),accountId:O.z.string(),userId:O.z.string(),accessToken:O.z.string().nullable().optional(),refreshToken:O.z.string().nullable().optional(),idToken:O.z.string().nullable().optional(),expiresAt:O.z.date().nullable().optional(),password:O.z.string().optional().nullable()}),tt=O.z.object({id:O.z.string(),email:O.z.string().transform(e=>e.toLowerCase()),emailVerified:O.z.boolean().default(!1),name:O.z.string(),image:O.z.string().optional(),createdAt:O.z.date().default(new Date),updatedAt:O.z.date().default(new Date)}),Es=O.z.object({id:O.z.string(),userId:O.z.string(),expiresAt:O.z.date(),ipAddress:O.z.string().optional(),userAgent:O.z.string().optional()}),Us=O.z.object({id:O.z.string(),value:O.z.string(),expiresAt:O.z.date(),identifier:O.z.string()});var vo=c("/callback/:id",{method:"GET",query:xe.z.object({state:xe.z.string(),code:xe.z.string().optional(),error:xe.z.string().optional()}),metadata:fe},async e=>{if(!e.query.code)throw e.redirect(`${e.context.baseURL}/error?error=${e.query.error||"no_code"}`);let t=e.context.socialProviders.find(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{codeVerifier:r,callbackURL:o,link:n,errorURL:i}=await Ye(e),a;try{a=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(b){throw e.context.logger.error(b),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let s=await t.getUserInfo(a).then(b=>b?.user),d=z(),u=tt.safeParse({...s,id:d});if(!s||u.success===!1)throw y.error("Unable to get user info",u.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw y.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(n){if(n.email!==s.email.toLowerCase())return l("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:n.userId,providerId:t.id,accountId:s.id}))return l("unable_to_link_account");let h;try{h=new URL(o).toString()}catch{h=o}throw e.redirect(h)}function l(b){throw e.redirect(`${i||o||`${e.context.baseURL}/error`}?error=${b}`)}let m=await e.context.internalAdapter.findUserByEmail(s.email,{includeAccounts:!0}).catch(b=>{throw y.error(`Better auth was unable to query your database.
3
+ Error: `,b),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),f=m?.user;if(m){let b=m.accounts.find(h=>h.providerId===t.id);if(b)await e.context.internalAdapter.updateAccount(b.id,{accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt});else{(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!s.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)&&(jt&&y.warn(`User already exist but account isn't linked to ${t.id}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),l("account_not_linked"));try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:s.id.toString(),id:`${t.id}:${s.id}`,userId:m.user.id,accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt})}catch(Ae){y.error("Unable to link account",Ae),l("unable_to_link_account")}}}else try{let b=s.emailVerified||!1;if(f=await e.context.internalAdapter.createOAuthUser({...u.data,emailVerified:b},{accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt,providerId:t.id,accountId:s.id.toString()}).then(h=>h?.user),!b&&f&&e.context.options.emailVerification?.sendOnSignUp){let h=await ie(e.context.secret,f.email),_=`${e.context.baseURL}/verify-email?token=${h}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(f,_,h)}}catch(b){y.error("Unable to create user",b),l("unable_to_create_user")}if(!f)return l("unable_to_create_user");let p=await e.context.internalAdapter.createSession(f.id,e.request);p||l("unable_to_create_session"),await w(e,{session:p,user:f});let k;try{k=new URL(o).toString()}catch{k=o}throw e.redirect(k)});var js=require("zod");var br=require("better-call"),Eo=c("/sign-out",{method:"POST",requireHeaders:!0},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new br.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),re(e),e.json({success:!0})});var $=require("zod");var De=require("better-call");function Ar(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function Uo(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var Io=c("/forget-password",{method:"POST",body:$.z.object({email:$.z.string().email(),redirectTo:$.z.string()})},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new De.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n)),a=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${a}`,expiresAt:i});let s=`${e.context.baseURL}/reset-password/${a}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,s),e.json({status:!0})}),To=c("/reset-password/:token",{method:"GET",query:$.z.object({callbackURL:$.z.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(Ar(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Ar(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Uo(e.context,r,{token:t}))}),So=c("/reset-password",{query:$.z.optional($.z.object({token:$.z.string().optional(),currentURL:$.z.string().optional()})),method:"POST",body:$.z.object({newPassword:$.z.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new De.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new De.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,a=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(i)).find(l=>l.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:a,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(i,a))throw new De.APIError("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});var j=require("zod");var D=require("better-call");var _o=c("/change-password",{method:"POST",body:j.z.object({newPassword:j.z.string(),currentPassword:j.z.string(),revokeOtherSessions:j.z.boolean().optional()}),use:[A]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new D.APIError("BAD_REQUEST",{message:"Password is too short"});let a=e.context.password.config.maxPasswordLength;if(t.length>a)throw e.context.logger.error("Password is too long"),new D.APIError("BAD_REQUEST",{message:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(n.user.id)).find(m=>m.providerId==="credential"&&m.password);if(!d||!d.password)throw new D.APIError("BAD_REQUEST",{message:"User does not have a password"});let u=await e.context.password.hash(t);if(!await e.context.password.verify(d.password,r))throw new D.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:u}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let m=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!m)throw new D.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await w(e,{session:m,user:n.user})}return e.json(n.user)}),Co=c("/set-password",{method:"POST",body:j.z.object({newPassword:j.z.string()}),metadata:{SERVER_ONLY:!0},use:[A]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new D.APIError("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new D.APIError("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(d=>d.providerId==="credential"&&d.password),s=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:s}),e.json(r.user);throw new D.APIError("BAD_REQUEST",{message:"user already has a password"})}),zo=c("/delete-user",{method:"POST",body:j.z.object({password:j.z.string()}),use:[A]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password);if(!n||!n.password)throw new D.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new D.APIError("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),re(e),e.json(null)}),Bo=c("/change-email",{method:"POST",query:j.z.object({currentURL:j.z.string().optional()}).optional(),body:j.z.object({newEmail:j.z.string().email(),callbackURL:j.z.string().optional()}),use:[A]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new D.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new D.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new D.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new D.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await ie(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification(e.context.session.user,e.body.newEmail,o,r),e.json({user:null,status:!0})});var Lo=(e="Unknown")=>`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">
@@ -80,6 +80,6 @@ Error: `,b),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
80
80
  <div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
81
81
  </div>
82
82
  </body>
83
- </html>`,xo=c("/error",{method:"GET",metadata:ge},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Lo(t),{headers:{"Content-Type":"text/html"}})});var Do=c("/ok",{method:"GET",metadata:ge},async e=>e.json({ok:!0}));var jo=require("zod");var No=require("better-call");var Ie=require("zod");var wt=require("better-call");var Fo=c("/list-accounts",{method:"GET",use:[A]},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(o=>({id:o.id,provider:o.providerId})))}),Vo=c("/link-social",{method:"POST",requireHeaders:!0,query:Ie.z.object({currentURL:Ie.z.string().optional()}).optional(),body:Ie.z.object({callbackURL:Ie.z.string().optional(),provider:Ie.z.enum(Xe)}),use:[A]},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(s=>s.providerId===e.body.provider))throw new wt.APIError("BAD_REQUEST",{message:"Social Account is already linked."});let n=e.context.socialProviders.find(s=>s.id===e.body.provider);if(!n)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new wt.APIError("NOT_FOUND",{message:"Provider not found"});let i=await Re(e,{userId:t.user.id,email:t.user.email}),a=await n.createAuthorizationURL({state:i.state,codeVerifier:i.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${n.id}`});return e.json({url:a.toString(),redirect:!0})});var kr=(e,t)=>{let r={};for(let[o,n]of Object.entries(e))r[o]=i=>n({...i,context:{...t,...i.context}}),r[o].path=n.path,r[o].method=n.method,r[o].options=n.options,r[o].headers=n.headers;return r};var Te=class extends Error{path;constructor(t,r){super(t),this.path=r}},rt=class{constructor(t){this.s=t;this.statements=t}statements;newRole(t){return new ot(t)}},ot=class e{statements;constructor(t){this.statements=t}authorize(t,r){for(let[o,n]of Object.entries(t)){let i=this.statements[o];if(!i)return{success:!1,error:`You are not allowed to access resource: ${o}`};let a=r==="OR"?n.some(s=>i.includes(s)):n.every(s=>i.includes(s));return a?{success:a}:{success:!1,error:`unauthorized to access resource "${o}"`}}return{success:!1,error:"Not authorized"}}static fromString(t){let r=JSON.parse(t);if(typeof r!="object")throw new Te("statements is not an object",".");for(let[o,n]of Object.entries(r)){if(typeof o!="string")throw new Te("invalid resource identifier",o);if(!Array.isArray(n))throw new Te("actions is not an array",o);for(let i=0;i<n.length;i++)if(typeof n[i]!="string")throw new Te("action is not a string",`${o}[${i}]`)}return new e(r)}toString(){return JSON.stringify(this.statements)}};var Mo=e=>new rt(e),qo={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},yt=Mo(qo),$o=yt.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),Qo=yt.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),Ho=yt.newRole({organization:[],member:[],invitation:[]}),Or={admin:$o,owner:Qo,member:Ho};var P=(e,t)=>{let r=e.adapter;return{findOrganizationBySlug:async o=>await r.findOne({model:"organization",where:[{field:"slug",value:o}]}),createOrganization:async o=>{let n=await r.create({model:"organization",data:{...o.organization,metadata:o.organization.metadata?JSON.stringify(o.organization.metadata):void 0}}),i=await r.create({model:"member",data:{id:z(),organizationId:n.id,userId:o.user.id,createdAt:new Date,email:o.user.email,role:t?.creatorRole||"owner"}});return{...n,metadata:n.metadata?JSON.parse(n.metadata):void 0,members:[{...i,user:{id:o.user.id,name:o.user.name,email:o.user.email,image:o.user.image}}]}},findMemberByEmail:async o=>{let n=await r.findOne({model:"member",where:[{field:"email",value:o.email},{field:"organizationId",value:o.organizationId}]});if(!n)return null;let i=await r.findOne({model:e.tables.user.tableName,where:[{field:"id",value:n.userId}]});return i?{...n,user:{id:i.id,name:i.name,email:i.email,image:i.image}}:null},findMemberByOrgId:async o=>{let[n,i]=await Promise.all([await r.findOne({model:"member",where:[{field:"userId",value:o.userId},{field:"organizationId",value:o.organizationId}]}),await r.findOne({model:e.tables.user.tableName,where:[{field:"id",value:o.userId}]})]);return!i||!n?null:{...n,user:{id:i.id,name:i.name,email:i.email,image:i.image}}},findMemberById:async o=>{let n=await r.findOne({model:"member",where:[{field:"id",value:o}]});if(!n)return null;let i=await r.findOne({model:e.tables.user.tableName,where:[{field:"id",value:n.userId}]});return i?{...n,user:{id:i.id,name:i.name,email:i.email,image:i.image}}:null},createMember:async o=>await r.create({model:"member",data:o}),updateMember:async(o,n)=>await r.update({model:"member",where:[{field:"id",value:o}],update:{role:n}}),deleteMember:async o=>await r.delete({model:"member",where:[{field:"id",value:o}]}),updateOrganization:async(o,n)=>await r.update({model:"organization",where:[{field:"id",value:o}],update:n}),deleteOrganization:async o=>(await r.delete({model:"member",where:[{field:"organizationId",value:o}]}),await r.delete({model:"invitation",where:[{field:"organizationId",value:o}]}),await r.delete({model:"organization",where:[{field:"id",value:o}]}),o),setActiveOrganization:async(o,n)=>await r.update({model:e.tables.session.tableName,where:[{field:"id",value:o}],update:{activeOrganizationId:n}}),findOrganizationById:async o=>await r.findOne({model:"organization",where:[{field:"id",value:o}]}),findFullOrganization:async(o,n)=>{let[i,a,s]=await Promise.all([r.findOne({model:"organization",where:[{field:"id",value:o}]}),r.findMany({model:"invitation",where:[{field:"organizationId",value:o}]}),r.findMany({model:"member",where:[{field:"organizationId",value:o}]})]);if(!i)return null;let d=s.map(f=>f.userId),u=await r.findMany({model:e.tables.user.tableName,where:[{field:"id",value:d,operator:"in"}]}),l=new Map(u.map(f=>[f.id,f])),p=s.map(f=>{let m=l.get(f.userId);if(!m)throw new W("Unexpected error: User not found for member");return{...f,user:{id:m.id,name:m.name,email:m.email,image:m.image}}});return{...i,invitations:a,members:p}},listOrganizations:async o=>{let n=await r.findMany({model:"member",where:[{field:"userId",value:o}]});if(!n||n.length===0)return[];let i=n.map(s=>s.organizationId);return await r.findMany({model:"organization",where:[{field:"id",value:i,operator:"in"}]})},createInvitation:async({invitation:o,user:n})=>{let a=C(t?.invitationExpiresIn||1728e5);return await r.create({model:"invitation",data:{id:z(),email:o.email,role:o.role,organizationId:o.organizationId,status:"pending",expiresAt:a,inviterId:n.id}})},findInvitationById:async o=>await r.findOne({model:"invitation",where:[{field:"id",value:o}]}),findPendingInvitation:async o=>(await r.findMany({model:"invitation",where:[{field:"email",value:o.email},{field:"organizationId",value:o.organizationId},{field:"status",value:"pending"}]})).filter(i=>new Date(i.expiresAt)>new Date),updateInvitation:async o=>await r.update({model:"invitation",where:[{field:"id",value:o.invitationId}],update:{status:o.status}})}};var Ad=require("better-call");var bt=require("better-call");var vr=require("better-call");var Wo=S(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=t?.callbackURL||r?.callbackURL,a=t?.redirectTo,s=r?.currentURL,d=o.trustedOrigins,u=e.headers?.has("cookie"),l=(f,m)=>m.includes("*")?new RegExp("^"+m.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(f):f.startsWith(m),p=(f,m)=>{if(!f)return;if(!d.some(b=>l(f,b)||f?.startsWith("/")&&m!=="origin"&&!f.includes(":")))throw y.error(`Invalid ${m}: ${f}`),y.info(`If it's a valid URL, please add ${f} to trustedOrigins in your auth config
84
- `,`Current list of trustedOrigins: ${d}`),new vr.APIError("FORBIDDEN",{message:`Invalid ${m}`})};u&&!e.context.options.advanced?.disableCSRFCheck&&p(n,"origin"),i&&p(i,"callbackURL"),a&&p(a,"redirectURL"),s&&p(s,"currentURL")});var R=require("better-call");var B=S(async e=>({})),L=S({use:[A]},async e=>({session:e.context.session}));var N=require("zod");var E=require("zod"),nt=E.z.enum(["admin","member","owner"]),Go=E.z.enum(["pending","accepted","rejected","canceled"]).default("pending"),Rd=E.z.object({id:E.z.string(),name:E.z.string(),slug:E.z.string(),logo:E.z.string().optional(),metadata:E.z.record(E.z.string()).or(E.z.string().transform(e=>JSON.parse(e))).optional(),createdAt:E.z.date()}),Ed=E.z.object({id:E.z.string(),email:E.z.string(),organizationId:E.z.string(),userId:E.z.string(),role:nt,createdAt:E.z.date()}),Ud=E.z.object({id:E.z.string(),organizationId:E.z.string(),email:E.z.string(),role:nt,status:Go,inviterId:E.z.string(),expiresAt:E.z.date()});var I=require("better-call"),Rr=c("/organization/invite-member",{method:"POST",use:[B,L],body:N.z.object({email:N.z.string(),role:nt,organizationId:N.z.string().optional(),resend:N.z.boolean().optional()})},async e=>{if(!e.context.orgOptions.sendInvitationEmail)throw y.warn("Invitation email is not enabled. Pass `sendInvitationEmail` to the plugin options to enable it."),new I.APIError("BAD_REQUEST",{message:"Invitation email is not enabled"});let t=e.context.session,r=e.body.organizationId||t.session.activeOrganizationId;if(!r)throw new I.APIError("BAD_REQUEST",{message:"Organization not found"});let o=P(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!n)throw new I.APIError("BAD_REQUEST",{message:"Member not found!"});let i=e.context.roles[n.role];if(!i)throw new I.APIError("BAD_REQUEST",{message:"Role not found!"});if(i.authorize({invitation:["create"]}).error)throw new I.APIError("FORBIDDEN",{message:"You are not allowed to invite members"});if(await o.findMemberByEmail({email:e.body.email,organizationId:r}))throw new I.APIError("BAD_REQUEST",{message:"User is already a member of this organization"});if((await o.findPendingInvitation({email:e.body.email,organizationId:r})).length&&!e.body.resend)throw new I.APIError("BAD_REQUEST",{message:"User is already invited to this organization"});let u=await o.createInvitation({invitation:{role:e.body.role,email:e.body.email,organizationId:r},user:t.user}),l=await o.findOrganizationById(r);if(!l)throw new I.APIError("BAD_REQUEST",{message:"Organization not found"});return await e.context.orgOptions.sendInvitationEmail?.({id:u.id,role:u.role,email:u.email,organization:l,inviter:{...n,user:t.user}},e.request),e.json(u)}),Er=c("/organization/accept-invitation",{method:"POST",body:N.z.object({invitationId:N.z.string()}),use:[B,L]},async e=>{let t=e.context.session,r=P(e.context,e.context.orgOptions),o=await r.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new I.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==t.user.email)throw new I.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let n=await r.updateInvitation({invitationId:e.body.invitationId,status:"accepted"}),i=await r.createMember({id:z(),organizationId:o.organizationId,userId:t.user.id,email:o.email,role:o.role,createdAt:new Date});return await r.setActiveOrganization(t.session.id,o.organizationId),n?e.json({invitation:n,member:i}):e.json(null,{status:400,body:{message:"Invitation not found!"}})}),Ur=c("/organization/reject-invitation",{method:"POST",body:N.z.object({invitationId:N.z.string()}),use:[B,L]},async e=>{let t=e.context.session,r=P(e.context,e.context.orgOptions),o=await r.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new I.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==t.user.email)throw new I.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let n=await r.updateInvitation({invitationId:e.body.invitationId,status:"rejected"});return e.json({invitation:n,member:null})}),Ir=c("/organization/cancel-invitation",{method:"POST",body:N.z.object({invitationId:N.z.string()}),use:[B,L]},async e=>{let t=e.context.session,r=P(e.context,e.context.orgOptions),o=await r.findInvitationById(e.body.invitationId);if(!o)throw new I.APIError("BAD_REQUEST",{message:"Invitation not found!"});let n=await r.findMemberByOrgId({userId:t.user.id,organizationId:o.organizationId});if(!n)throw new I.APIError("BAD_REQUEST",{message:"Member not found!"});if(e.context.roles[n.role].authorize({invitation:["cancel"]}).error)throw new I.APIError("FORBIDDEN",{message:"You are not allowed to cancel this invitation"});let a=await r.updateInvitation({invitationId:e.body.invitationId,status:"canceled"});return e.json(a)}),Tr=c("/organization/get-invitation",{method:"GET",use:[B],requireHeaders:!0,query:N.z.object({id:N.z.string()})},async e=>{let t=await x(e);if(!t)throw new I.APIError("UNAUTHORIZED",{message:"Not authenticated"});let r=P(e.context,e.context.orgOptions),o=await r.findInvitationById(e.query.id);if(!o||o.status!=="pending"||o.expiresAt<new Date)throw new I.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==t.user.email)throw new I.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let n=await r.findOrganizationById(o.organizationId);if(!n)throw new I.APIError("BAD_REQUEST",{message:"Organization not found"});let i=await r.findMemberByOrgId({userId:o.inviterId,organizationId:o.organizationId});if(!i)throw new I.APIError("BAD_REQUEST",{message:"Inviter is no longer a member of the organization"});return e.json({...o,organizationName:n.name,organizationSlug:n.slug,inviterEmail:i.email})});var ae=require("zod");var Se=require("better-call"),Sr=c("/organization/remove-member",{method:"POST",body:ae.z.object({memberIdOrEmail:ae.z.string(),organizationId:ae.z.string().optional()}),use:[B,L]},async e=>{let t=e.context.session,r=e.body.organizationId||t.session.activeOrganizationId;if(!r)return e.json(null,{status:400,body:{message:"No active organization found!"}});let o=P(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!n)throw new Se.APIError("BAD_REQUEST",{message:"Member not found!"});let i=e.context.roles[n.role];if(!i)throw new Se.APIError("BAD_REQUEST",{message:"Role not found!"});let a=t.user.email===e.body.memberIdOrEmail||n.id===e.body.memberIdOrEmail;if(a&&n.role===(e.context.orgOptions?.creatorRole||"owner"))throw new Se.APIError("BAD_REQUEST",{message:"You cannot leave the organization as the owner"});if(!(a||i.authorize({member:["delete"]}).success))throw new Se.APIError("UNAUTHORIZED",{message:"You are not allowed to delete this member"});let u=null;if(e.body.memberIdOrEmail.includes("@")?u=await o.findMemberByEmail({email:e.body.memberIdOrEmail,organizationId:r}):u=await o.findMemberById(e.body.memberIdOrEmail),u?.organizationId!==r)throw new Se.APIError("BAD_REQUEST",{message:"Member not found!"});return await o.deleteMember(u.id),t.user.id===u.userId&&t.session.activeOrganizationId===u.organizationId&&await o.setActiveOrganization(t.session.id,null),e.json({member:u})}),Pr=c("/organization/update-member-role",{method:"POST",body:ae.z.object({role:ae.z.enum(["admin","member","owner"]),memberId:ae.z.string(),organizationId:ae.z.string().optional()}),use:[B,L]},async e=>{let t=e.context.session,r=e.body.organizationId||t.session.activeOrganizationId;if(!r)return e.json(null,{status:400,body:{message:"No active organization found!"}});let o=P(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!n)return e.json(null,{status:400,body:{message:"Member not found!"}});let i=e.context.roles[n.role];if(!i)return e.json(null,{status:400,body:{message:"Role not found!"}});if(i.authorize({member:["update"]}).error||e.body.role==="owner"&&n.role!=="owner")return e.json(null,{body:{message:"You are not allowed to update this member"},status:403});let s=await o.updateMember(e.body.memberId,e.body.role);return s?e.json(s):e.json(null,{status:400,body:{message:"Member not found!"}})}),_r=c("/organization/get-active-member",{method:"GET",use:[B,L]},async e=>{let t=e.context.session,r=t.session.activeOrganizationId;if(!r)return e.json(null,{status:400,body:{message:"No active organization found!"}});let n=await P(e.context,e.context.orgOptions).findMemberByOrgId({userId:t.user.id,organizationId:r});return n?e.json(n):e.json(null,{status:400,body:{message:"Member not found!"}})});var T=require("zod");var de=require("better-call"),Cr=c("/organization/create",{method:"POST",body:T.z.object({name:T.z.string(),slug:T.z.string(),userId:T.z.string().optional(),logo:T.z.string().optional(),metadata:T.z.record(T.z.string()).optional()}),use:[B,L]},async e=>{let t=e.context.session.user;if(!t)return e.json(null,{status:401});let r=e.context.orgOptions;if(!(typeof r?.allowUserToCreateOrganization=="function"?await r.allowUserToCreateOrganization(t):r?.allowUserToCreateOrganization===void 0?!0:r.allowUserToCreateOrganization))throw new de.APIError("FORBIDDEN",{message:"You are not allowed to create an organization"});let n=P(e.context,r),i=await n.listOrganizations(t.id);if(typeof r.organizationLimit=="number"?i.length>=r.organizationLimit:typeof r.organizationLimit=="function"?await r.organizationLimit(t):!1)throw new de.APIError("FORBIDDEN",{message:"You have reached the organization limit"});if(await n.findOrganizationBySlug(e.body.slug))throw new de.APIError("BAD_REQUEST",{message:"Organization with this slug already exists"});let d=await n.createOrganization({organization:{id:z(),slug:e.body.slug,name:e.body.name,logo:e.body.logo,createdAt:new Date,metadata:e.body.metadata},user:t});return e.json(d)}),zr=c("/organization/update",{method:"POST",body:T.z.object({data:T.z.object({name:T.z.string().optional(),slug:T.z.string().optional(),logo:T.z.string().optional()}).partial(),orgId:T.z.string().optional()}),requireHeaders:!0,use:[B]},async e=>{let t=await e.context.getSession(e);if(!t)throw new de.APIError("UNAUTHORIZED",{message:"User not found"});let r=e.body.orgId||t.session.activeOrganizationId;if(!r)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let o=P(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!n)return e.json(null,{status:400,body:{message:"User is not a member of this organization!"}});let i=e.context.roles[n.role];if(!i)return e.json(null,{status:400,body:{message:"Role not found!"}});if(i.authorize({organization:["update"]}).error)return e.json(null,{body:{message:"You are not allowed to update this organization"},status:403});let s=await o.updateOrganization(r,e.body.data);return e.json(s)}),Br=c("/organization/delete",{method:"POST",body:T.z.object({orgId:T.z.string()}),requireHeaders:!0,use:[B]},async e=>{let t=await e.context.getSession(e);if(!t)return e.json(null,{status:401});let r=e.body.orgId;if(!r)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let o=P(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!n)return e.json(null,{status:400,body:{message:"User is not a member of this organization!"}});let i=e.context.roles[n.role];if(!i)return e.json(null,{status:400,body:{message:"Role not found!"}});if(i.authorize({organization:["delete"]}).error)throw new de.APIError("FORBIDDEN",{message:"You are not allowed to delete this organization"});return r===t.session.activeOrganizationId&&await o.setActiveOrganization(t.session.id,null),await o.deleteOrganization(r),e.json(r)}),Lr=c("/organization/get-full",{method:"GET",query:T.z.optional(T.z.object({orgId:T.z.string().optional()})),requireHeaders:!0,use:[B,L]},async e=>{let t=e.context.session,r=e.query?.orgId||t.session.activeOrganizationId;if(!r)return e.json(null,{status:200});let n=await P(e.context,e.context.orgOptions).findFullOrganization(r,e.context.db||void 0);if(!n)throw new de.APIError("BAD_REQUEST",{message:"Organization not found"});return e.json(n)}),xr=c("/organization/set-active",{method:"POST",body:T.z.object({orgId:T.z.string().nullable().optional()}),use:[L,B]},async e=>{let t=P(e.context,e.context.orgOptions),r=e.context.session,o=e.body.orgId;if(o===null)return r.session.activeOrganizationId&&await t.setActiveOrganization(r.session.id,null),e.json(null);if(!o){let a=r.session.activeOrganizationId;if(!a)return e.json(null);o=a}if(!await t.findMemberByOrgId({userId:r.user.id,organizationId:o}))throw await t.setActiveOrganization(r.session.id,null),new de.APIError("FORBIDDEN",{message:"You are not a member of this organization"});await t.setActiveOrganization(r.session.id,o);let i=await t.findFullOrganization(o,e.context.db||void 0);return e.json(i)}),Dr=c("/organization/list",{method:"GET",use:[B,L]},async e=>{let r=await P(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(r)});var Ko=e=>{let t={createOrganization:Cr,updateOrganization:zr,deleteOrganization:Br,setActiveOrganization:xr,getFullOrganization:Lr,listOrganization:Dr,createInvitation:Rr,cancelInvitation:Ir,acceptInvitation:Er,getInvitation:Tr,rejectInvitation:Ur,removeMember:Sr,updateMemberRole:Pr,getActiveMember:_r},r={...Or,...e?.roles};return{id:"organization",endpoints:{...kr(t,{orgOptions:e||{},roles:r,getSession:async n=>await x(n)}),hasPermission:c("/organization/has-permission",{method:"POST",requireHeaders:!0,body:Pe.z.object({permission:Pe.z.record(Pe.z.string(),Pe.z.array(Pe.z.string()))}),use:[L]},async n=>{if(!n.context.session.session.activeOrganizationId)throw new At.APIError("BAD_REQUEST",{message:"No active organization"});let a=await P(n.context).findMemberByOrgId({userId:n.context.session.user.id,organizationId:n.context.session.session.activeOrganizationId||""});if(!a)throw new At.APIError("UNAUTHORIZED",{message:"You are not a member of this organization"});let d=r[a.role].authorize(n.body.permission);return d.error?n.json({error:d.error,success:!1},{status:403}):n.json({error:null,success:!0})})},schema:{session:{fields:{activeOrganizationId:{type:"string",required:!1}}},organization:{fields:{name:{type:"string",required:!0},slug:{type:"string",unique:!0},logo:{type:"string",required:!1},createdAt:{type:"date",required:!0},metadata:{type:"string",required:!1}}},member:{fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"}},userId:{type:"string",required:!0},email:{type:"string",required:!0},role:{type:"string",required:!0,defaultValue:"member"},createdAt:{type:"date",required:!0}}},invitation:{fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"}},email:{type:"string",required:!0},role:{type:"string",required:!1},status:{type:"string",required:!0,defaultValue:"pending"},expiresAt:{type:"date",required:!0},inviterId:{type:"string",references:{model:"user",field:"id"},required:!0}}}},$Infer:{Organization:{},Invitation:{},Member:{},ActiveOrganization:{}}}};var kt=Dt(require("uncrypto"),1);function Jo(e){return e.toString(2).padStart(8,"0")}function Zo(e){return[...e].map(t=>Jo(t)).join("")}function jr(e){return parseInt(Zo(e),2)}function Yo(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,o=new Uint8Array(Math.ceil(t/8));kt.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=jr(o);for(;n>=e;)kt.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=jr(o);return n}function F(e,t){let r="";for(let o=0;o<e;o++)r+=t[Yo(t.length)];return r}function V(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}var Me=require("zod");var vt=require("@noble/ciphers/chacha"),_e=require("@noble/ciphers/utils"),Rt=require("@noble/ciphers/webcrypto"),Et=require("oslo/crypto"),Ot=Dt(require("uncrypto"),1);var Nr=require("oslo/encoding");var Xo=require("@noble/hashes/scrypt"),en=require("uncrypto");async function ye(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},n=await Ot.default.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),i=await Ot.default.subtle.sign(o.name,n,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(i)))}var ce=async({key:e,data:t})=>{let r=await(0,Et.sha256)(new TextEncoder().encode(e)),o=(0,_e.utf8ToBytes)(t),n=(0,Rt.managedNonce)(vt.xchacha20poly1305)(new Uint8Array(r));return(0,_e.bytesToHex)(n.encrypt(o))},ue=async({key:e,data:t})=>{let r=await(0,Et.sha256)(new TextEncoder().encode(e)),o=(0,_e.hexToBytes)(t),n=(0,Rt.managedNonce)(vt.xchacha20poly1305)(new Uint8Array(r));return new TextDecoder().decode(n.decrypt(o))};var Z=require("zod");var ne=require("better-call");var it="two_factor";var st="trust_device";var Ut=require("zod");var be=S({body:Ut.z.object({trustDevice:Ut.z.boolean().optional()})},async e=>{let t=await x(e);if(!t){let r=e.context.createAuthCookie(it),o=await e.getSignedCookie(r.name,e.context.secret);if(!o)throw new ne.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let[n,i]=o.split("!");if(!n||!i)throw new ne.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let a=await e.context.adapter.findMany({model:e.context.tables.session.tableName,where:[{field:"userId",value:n}]});if(!a.length)throw new ne.APIError("UNAUTHORIZED",{message:"invalid session"});let s=a.filter(d=>d.expiresAt>new Date);if(!s)throw new ne.APIError("UNAUTHORIZED",{message:"invalid session"});for(let d of s){let u=await ye(e.context.secret,d.id),l=await e.context.adapter.findOne({model:e.context.tables.user.tableName,where:[{field:"id",value:d.userId}]});if(!l)throw new ne.APIError("UNAUTHORIZED",{message:"invalid session"});if(u===i)return{valid:async()=>{if(await w(e,{session:d,user:l},!1),e.body.trustDevice){let p=e.context.createAuthCookie(st,{maxAge:2592e3}),f=await ye(e.context.secret,`${l.id}!${d.id}`);await e.setSignedCookie(p.name,`${f}!${d.id}`,e.context.secret,p.attributes)}return e.json({session:d,user:l})},invalid:async()=>{throw new ne.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:{id:d.id,userId:d.userId,expiresAt:d.expiresAt,user:l}}}throw new ne.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"})}return{valid:async()=>e.json({session:t,user:t.user}),invalid:async()=>{throw new ne.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:t}});var Ce=require("better-call");function tn(e){return Array.from({length:e?.amount??10}).fill(null).map(()=>F(e?.length??10,V("a-z","0-9"))).map(t=>`${t.slice(0,5)}-${t.slice(5)}`)}async function It(e,t){let r=e,o=t?.customBackupCodesGenerate?t.customBackupCodesGenerate():tn(),n=await ce({data:JSON.stringify(o),key:r});return{backupCodes:o,encryptedBackupCodes:n}}async function rn(e,t){let r=await Fr(e.backupCodes,t);return r?r.includes(e.code):!1}async function Fr(e,t){let r=Buffer.from(await ue({key:t,data:e})).toString("utf-8"),o=JSON.parse(r),n=Z.z.array(Z.z.string()).safeParse(o);return n.success?n.data:null}var Vr=(e,t)=>({id:"backup_code",endpoints:{verifyBackupCode:c("/two-factor/verify-backup-code",{method:"POST",body:Z.z.object({code:Z.z.string(),disableSession:Z.z.boolean().optional()}),use:[be]},async r=>{let o=r.context.session.user,n=await r.context.adapter.findOne({model:t,where:[{field:"userId",value:o.id}]});if(!n)throw new Ce.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});if(!rn({backupCodes:n.backupCodes,code:r.body.code},r.context.secret))throw new Ce.APIError("BAD_REQUEST",{message:"Invalid backup code"});return r.body.disableSession||await w(r,{session:r.context.session,user:o}),r.json({user:o,session:r.context.session})}),generateBackupCodes:c("/two-factor/generate-backup-codes",{method:"POST",body:Z.z.object({password:Z.z.string()}),use:[A]},async r=>{let o=r.context.session.user;if(!o.twoFactorEnabled)throw new Ce.APIError("BAD_REQUEST",{message:"Two factor isn't enabled"});await r.context.password.checkPassword(o.id,r);let n=await It(r.context.secret,e);return await r.context.adapter.update({model:t,update:{backupCodes:n.encryptedBackupCodes},where:[{field:"userId",value:r.context.session.user.id}]}),r.json({status:!0,backupCodes:n.backupCodes})}),viewBackupCodes:c("/view/backup-codes",{method:"GET",body:Z.z.object({password:Z.z.string()}),use:[A]},async r=>{let o=r.context.session.user,n=await r.context.adapter.findOne({model:t,where:[{field:"userId",value:o.id}]});if(!n)throw new Ce.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});await r.context.password.checkPassword(o.id,r);let i=Fr(n.backupCodes,r.context.secret);if(!i)throw new Ce.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});return r.json({status:!0,backupCodes:i})})}});var Ne=require("better-call"),Mr=require("oslo/otp"),Tt=require("zod");var qr=require("oslo"),$r=(e,t)=>{let r={...e,period:new qr.TimeSpan(e?.period||3,"m")},o=new Mr.TOTPController({digits:6,period:r.period}),n=c("/two-factor/send-otp",{method:"POST",use:[be]},async a=>{if(!e||!e.sendOTP)throw a.context.logger.error("send otp isn't configured. Please configure the send otp function on otp options."),new Ne.APIError("BAD_REQUEST",{message:"otp isn't configured"});let s=a.context.session.user,d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d)throw new Ne.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});let u=await o.generate(Buffer.from(d.secret));return await e.sendOTP(s,u),a.json({status:!0})}),i=c("/two-factor/verify-otp",{method:"POST",body:Tt.z.object({code:Tt.z.string()}),use:[be]},async a=>{let s=a.context.session.user;if(!s.twoFactorEnabled)throw new Ne.APIError("BAD_REQUEST",{message:"two factor isn't enabled"});let d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d)throw new Ne.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});return await o.generate(Buffer.from(d.secret))===a.body.code?a.context.valid():a.context.invalid()});return{id:"otp",endpoints:{send2FaOTP:n,verifyOTP:i}}};var Ae=require("better-call"),Qr=require("oslo"),Ve=require("oslo/otp"),Fe=require("zod");var Hr=(e,t)=>{let r={...e,digits:6,period:new Qr.TimeSpan(e?.period||30,"s")},o=c("/totp/generate",{method:"POST",use:[A]},async a=>{if(!e)throw a.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new Ae.APIError("BAD_REQUEST",{message:"totp isn't configured"});let s=a.context.session.user,d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d)throw new Ae.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return{code:await new Ve.TOTPController(r).generate(Buffer.from(d.secret))}}),n=c("/two-factor/get-totp-uri",{method:"POST",use:[A],body:Fe.z.object({password:Fe.z.string()})},async a=>{if(!e)throw a.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new Ae.APIError("BAD_REQUEST",{message:"totp isn't configured"});let s=a.context.session.user,d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d||!s.twoFactorEnabled)throw new Ae.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return await a.context.password.checkPassword(s.id,a),{totpURI:(0,Ve.createTOTPKeyURI)(e?.issuer||"BetterAuth",s.email,Buffer.from(d.secret),r)}}),i=c("/two-factor/verify-totp",{method:"POST",body:Fe.z.object({code:Fe.z.string()}),use:[be]},async a=>{if(!e)throw a.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new Ae.APIError("BAD_REQUEST",{message:"totp isn't configured"});let s=a.context.session.user,d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d)throw new Ae.APIError("BAD_REQUEST",{message:"totp isn't enabled"});let u=new Ve.TOTPController(r),l=await ue({key:a.context.secret,data:d.secret}),p=Buffer.from(l);if(!await u.verify(a.body.code,p))return a.context.invalid();if(!s.twoFactorEnabled){let m=await a.context.internalAdapter.updateUser(s.id,{twoFactorEnabled:!0}),k=await a.context.internalAdapter.createSession(s.id,a.request);await w(a,{session:k,user:m})}return a.context.valid()});return{id:"totp",endpoints:{generateTOTP:o,viewTOTPURI:n,verifyTOTP:i}}};var on=require("better-call");async function St(e,t){let o=(await e.context.internalAdapter.findAccounts(t.userId))?.find(a=>a.providerId==="credential"),n=o?.password;return!o||!n?!1:await e.context.password.verify(n,t.password)}var Pt=require("better-call"),Wr=require("oslo/otp"),Gr=require("oslo");var nn=(e={redirect:!0,twoFactorPage:"/"})=>({id:"two-factor",$InferServerPlugin:{},atomListeners:[{matcher:t=>t.startsWith("/two-factor/"),signal:"$sessionSignal"}],pathMethods:{"/two-factor/disable":"POST","/two-factor/enable":"POST","/two-factor/send-otp":"POST","/two-factor/generate-backup-codes":"POST"},fetchPlugins:[{id:"two-factor",name:"two-factor",hooks:{async onSuccess(t){t.data?.twoFactorRedirect&&(e.redirect||e.twoFactorPage)&&typeof window<"u"&&(window.location.href=e.twoFactorPage)}}}]});var sn=e=>{let t={twoFactorTable:e?.twoFactorTable||"twoFactor"},r=Hr({issuer:e?.issuer||"better-auth",...e?.totpOptions},t.twoFactorTable),o=Vr({...e?.backupCodeOptions},t.twoFactorTable),n=$r({...e?.otpOptions},t.twoFactorTable);return{id:"two-factor",endpoints:{...r.endpoints,...n.endpoints,...o.endpoints,enableTwoFactor:c("/two-factor/enable",{method:"POST",body:Me.z.object({password:Me.z.string().min(8)}),use:[A]},async i=>{let a=i.context.session.user,{password:s}=i.body;if(!await St(i,{password:s,userId:a.id}))throw new Pt.APIError("BAD_REQUEST",{message:"Invalid password"});let u=F(16,V("a-z","0-9","-")),l=await ce({key:i.context.secret,data:u}),p=await It(i.context.secret,e?.backupCodeOptions);if(e?.skipVerificationOnEnable){let m=await i.context.internalAdapter.updateUser(a.id,{twoFactorEnabled:!0}),k=await i.context.internalAdapter.createSession(m.id,i.request);await w(i,{session:k,user:a})}await i.context.adapter.deleteMany({model:t.twoFactorTable,where:[{field:"userId",value:a.id}]}),await i.context.adapter.create({model:t.twoFactorTable,data:{id:i.context.uuid(),secret:l,backupCodes:p.encryptedBackupCodes,userId:a.id}});let f=(0,Wr.createTOTPKeyURI)(e?.issuer||"BetterAuth",a.email,Buffer.from(u),{digits:e?.totpOptions?.digits||6,period:new Gr.TimeSpan(e?.totpOptions?.period||30,"s")});return i.json({totpURI:f,backupCodes:p.backupCodes})}),disableTwoFactor:c("/two-factor/disable",{method:"POST",body:Me.z.object({password:Me.z.string().min(8)}),use:[A]},async i=>{let a=i.context.session.user,{password:s}=i.body;if(!await St(i,{password:s,userId:a.id}))throw new Pt.APIError("BAD_REQUEST",{message:"Invalid password"});return await i.context.internalAdapter.updateUser(a.id,{twoFactorEnabled:!1}),await i.context.adapter.delete({model:t.twoFactorTable,where:[{field:"userId",value:a.id}]}),i.json({status:!0})})},options:e,hooks:{after:[{matcher(i){return i.path==="/sign-in/email"||i.path==="/sign-in/username"},handler:S(async i=>{let a=i.context.returned;if(a?.status!==200)return;let s=await a.clone().json();if(!s.user.twoFactorEnabled)return;let d=i.context.createAuthCookie(st,{maxAge:30*24*60*60}),u=await i.getSignedCookie(d.name,i.context.secret);if(u){let[m,k]=u.split("!"),b=await ye(i.context.secret,`${s.user.id}!${k}`);if(m===b){let h=await ye(i.context.secret,`${s.user.id}!${s.session.id}`);await i.setSignedCookie(d.name,`${h}!${s.session.id}`,i.context.secret,d.attributes);return}}re(i);let l=await ye(i.context.secret,s.session.id),p=i.context.createAuthCookie(it,{maxAge:60*60*24});return await i.setSignedCookie(p.name,`${s.session.userId}!${l}`,i.context.secret,p.attributes),{response:new Response(JSON.stringify({twoFactorRedirect:!0}),{headers:i.responseHeader})}})}]},schema:{user:{fields:{twoFactorEnabled:{type:"boolean",required:!1,defaultValue:!1,input:!1}}},twoFactor:{tableName:t.twoFactorTable,fields:{secret:{type:"string",required:!0,returned:!1},backupCodes:{type:"string",required:!0,returned:!1},userId:{type:"string",required:!0,returned:!1,references:{model:"user",field:"id"}}}}},rateLimit:[{pathMatcher(i){return i.startsWith("/two-factor/")},window:10,max:3}]}};var le=require("@simplewebauthn/server"),Q=require("better-call");var Y=require("zod");var ze=require("@simplewebauthn/browser");var dn=require("@better-fetch/fetch");var du=require("nanostores");var Jc=require("@better-fetch/fetch");var an=require("nanostores");var Yc=require("@better-fetch/fetch"),at=require("nanostores"),_t=(e,t,r,o)=>{let n=(0,at.atom)({data:null,error:null,isPending:!0,isRefetching:!1}),i=()=>{let s=typeof o=="function"?o({data:n.get().data,error:n.get().error,isPending:n.get().isPending}):o;return r(t,{...s,onSuccess:async d=>{n.set({data:d.data,error:null,isPending:!1,isRefetching:!1}),await s?.onSuccess?.(d)},async onError(d){n.set({error:d.error,data:null,isPending:!1,isRefetching:!1}),await s?.onError?.(d)},async onRequest(d){let u=n.get();n.set({isPending:u.data===null,data:u.data,error:null,isRefetching:!0}),await s?.onRequest?.(d)}})};e=Array.isArray(e)?e:[e];let a=!1;for(let s of e)s.subscribe(()=>{a?i():(0,at.onMount)(n,()=>(i(),a=!0,()=>{n.off(),s.off()}))});return n};var Kr=require("nanostores"),Jr=(e,{$listPasskeys:t})=>({signIn:{passkey:async(n,i)=>{let a=await e("/passkey/generate-authenticate-options",{method:"POST",body:{email:n?.email}});if(!a.data)return a;try{let s=await(0,ze.startAuthentication)(a.data,n?.autoFill||!1),d=await e("/passkey/verify-authentication",{body:{response:s},...n?.fetchOptions,...i,method:"POST"});if(!d.data)return d}catch{return{data:null,error:{message:"auth cancelled",status:400,statusText:"BAD_REQUEST"}}}}},passkey:{addPasskey:async(n,i)=>{let a=await e("/passkey/generate-register-options",{method:"GET"});if(!a.data)return a;try{let s=await(0,ze.startRegistration)(a.data),d=await e("/passkey/verify-registration",{...n?.fetchOptions,...i,body:{response:s,name:n?.name},method:"POST"});if(!d.data)return d;t.set(Math.random())}catch(s){return s instanceof ze.WebAuthnError?s.code==="ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED"?{data:null,error:{message:"previously registered",status:400,statusText:"BAD_REQUEST"}}:s.code==="ERROR_CEREMONY_ABORTED"?{data:null,error:{message:"registration cancelled",status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:s.message,status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:s instanceof Error?s.message:"unknown error",status:500,statusText:"INTERNAL_SERVER_ERROR"}}}}},$Infer:{}}),cn=()=>{let e=(0,Kr.atom)();return{id:"passkey",$InferServerPlugin:{},getActions:t=>Jr(t,{$listPasskeys:e}),getAtoms(t){return{listPasskeys:_t(e,"/passkey/list-user-passkeys",t,{method:"GET"}),$listPasskeys:e}},pathMethods:{"/passkey/register":"POST","/passkey/authenticate":"POST"},atomListeners:[{matcher(t){return t==="/passkey/verify-registration"||t==="/passkey/delete-passkey"},signal:"_listPasskeys"}]}};var un=e=>{let t=G.BETTER_AUTH_URL,r=e?.rpID||t?.replace("http://","").replace("https://","").split(":")[0]||"localhost";if(!r)throw new W("passkey rpID not found. Please provide a rpID in the options or set the BETTER_AUTH_URL environment variable.");let o={origin:null,...e,rpID:r,advanced:{webAuthnChallengeCookie:"better-auth-passkey",...e?.advanced}},n=new Date(Date.now()+1e3*60*5),i=new Date,a=Math.floor((n.getTime()-i.getTime())/1e3);return{id:"passkey",endpoints:{generatePasskeyRegistrationOptions:c("/passkey/generate-register-options",{method:"GET",use:[A],metadata:{client:!1}},async s=>{let d=s.context.session,u=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}),l=new Uint8Array(Buffer.from(F(32,V("a-z","0-9")))),p;p=await(0,le.generateRegistrationOptions)({rpName:o.rpName||s.context.appName,rpID:o.rpID,userID:l,userName:d.user.email||d.user.id,attestationType:"none",excludeCredentials:u.map(m=>({id:m.id,transports:m.transports?.split(",")})),authenticatorSelection:{residentKey:"preferred",userVerification:"preferred",authenticatorAttachment:"platform"}});let f=z();return await s.setSignedCookie(o.advanced.webAuthnChallengeCookie,f,s.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:a}),await s.context.internalAdapter.createVerificationValue({identifier:f,value:JSON.stringify({expectedChallenge:p.challenge,userData:{id:d.user.id}}),expiresAt:n}),s.json(p,{status:200})}),generatePasskeyAuthenticationOptions:c("/passkey/generate-authenticate-options",{method:"POST",body:Y.z.object({email:Y.z.string().optional()}).optional()},async s=>{let d=await x(s),u=[];d&&(u=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}));let l=await(0,le.generateAuthenticationOptions)({rpID:o.rpID,userVerification:"preferred",...u.length?{allowCredentials:u.map(m=>({id:m.id,transports:m.transports?.split(",")}))}:{}}),p={expectedChallenge:l.challenge,userData:{id:d?.user.id||""}},f=z();return await s.setSignedCookie(o.advanced.webAuthnChallengeCookie,f,s.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:a}),await s.context.internalAdapter.createVerificationValue({identifier:f,value:JSON.stringify(p),expiresAt:n}),s.json(l,{status:200})}),verifyPasskeyRegistration:c("/passkey/verify-registration",{method:"POST",body:Y.z.object({response:Y.z.any(),name:Y.z.string().optional()}),use:[A]},async s=>{let d=e?.origin||s.headers?.get("origin")||"";if(!d)return s.json(null,{status:400});let u=s.body.response,l=await s.getSignedCookie(o.advanced.webAuthnChallengeCookie,s.context.secret);if(!l)throw new Q.APIError("BAD_REQUEST",{message:"Challenge not found"});let p=await s.context.internalAdapter.findVerificationValue(l);if(!p)return s.json(null,{status:400});let{expectedChallenge:f,userData:m}=JSON.parse(p.value);if(m.id!==s.context.session.user.id)throw new Q.APIError("UNAUTHORIZED",{message:"You are not authorized to register this passkey"});try{let k=await(0,le.verifyRegistrationResponse)({response:u,expectedChallenge:f,expectedOrigin:d,expectedRPID:e?.rpID}),{verified:b,registrationInfo:h}=k;if(!b||!h)return s.json(null,{status:400});let{credentialID:_,credentialPublicKey:Oe,counter:H,credentialDeviceType:He,credentialBackedUp:ve}=h,me=Buffer.from(Oe).toString("base64"),lt=z(),ro={name:s.body.name,userId:m.id,webauthnUserID:lt,id:_,publicKey:me,counter:H,deviceType:He,transports:u.response.transports.join(","),backedUp:ve,createdAt:new Date},oo=await s.context.adapter.create({model:"passkey",data:ro});return s.json(oo,{status:200})}catch(k){throw console.log(k),new Q.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to verify registration"})}}),verifyPasskeyAuthentication:c("/passkey/verify-authentication",{method:"POST",body:Y.z.object({response:Y.z.any()})},async s=>{let d=e?.origin||s.headers?.get("origin")||"";if(!d)throw new Q.APIError("BAD_REQUEST",{message:"origin missing"});let u=s.body.response,l=await s.getSignedCookie(o.advanced.webAuthnChallengeCookie,s.context.secret);if(!l)throw new Q.APIError("BAD_REQUEST",{message:"Challenge not found"});let p=await s.context.internalAdapter.findVerificationValue(l);if(!p)throw new Q.APIError("BAD_REQUEST",{message:"Challenge not found"});let{expectedChallenge:f}=JSON.parse(p.value),m=await s.context.adapter.findOne({model:"passkey",where:[{field:"id",value:u.id}]});if(!m)throw new Q.APIError("UNAUTHORIZED",{message:"Passkey not found"});try{let k=await(0,le.verifyAuthenticationResponse)({response:u,expectedChallenge:f,expectedOrigin:d,expectedRPID:o.rpID,authenticator:{credentialID:m.id,credentialPublicKey:new Uint8Array(Buffer.from(m.publicKey,"base64")),counter:m.counter,transports:m.transports?.split(",")}}),{verified:b}=k;if(!b)throw new Q.APIError("UNAUTHORIZED",{message:"Authentication failed"});await s.context.adapter.update({model:"passkey",where:[{field:"id",value:m.id}],update:{counter:k.authenticationInfo.newCounter}});let h=await s.context.internalAdapter.createSession(m.userId,s.request);if(!h)throw new Q.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});let _=await s.context.internalAdapter.findUserById(m.userId);if(!_)throw new Q.APIError("INTERNAL_SERVER_ERROR",{message:"User not found"});return await w(s,{session:h,user:_}),s.json({session:h},{status:200})}catch(k){throw s.context.logger.error(k),new Q.APIError("BAD_REQUEST",{message:"Failed to verify authentication"})}}),listPasskeys:c("/passkey/list-user-passkeys",{method:"GET",use:[A]},async s=>{let d=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:s.context.session.user.id}]});return s.json(d,{status:200})}),deletePasskey:c("/passkey/delete-passkey",{method:"POST",body:Y.z.object({id:Y.z.string()}),use:[A]},async s=>(await s.context.adapter.delete({model:"passkey",where:[{field:"id",value:s.body.id}]}),s.json(null,{status:200})))},schema:{passkey:{fields:{name:{type:"string",required:!1},publicKey:{type:"string",required:!0},userId:{type:"string",references:{model:"user",field:"id"},required:!0},webauthnUserID:{type:"string",required:!0},counter:{type:"number",required:!0},deviceType:{type:"string",required:!0},backedUp:{type:"boolean",required:!0},transports:{type:"string",required:!1},createdAt:{type:"date",defaultValue:new Date,required:!1}}}}}};var qe=require("zod");var $e=require("better-call"),Ct=()=>({id:"username",endpoints:{signInUsername:c("/sign-in/username",{method:"POST",body:qe.z.object({username:qe.z.string(),password:qe.z.string(),dontRememberMe:qe.z.boolean().optional()})},async e=>{let t=await e.context.adapter.findOne({model:e.context.tables.user.tableName,where:[{field:"username",value:e.body.username}]});if(!t)throw await e.context.password.hash(e.body.password),e.context.logger.error("User not found",{username:Ct}),new $e.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let r=await e.context.adapter.findOne({model:e.context.tables.account.tableName,where:[{field:e.context.tables.account.fields.userId.fieldName||"userId",value:t.id},{field:e.context.tables.account.fields.providerId.fieldName||"providerId",value:"credential"}]});if(!r)throw new $e.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let o=r?.password;if(!o)throw e.context.logger.error("Password not found",{username:Ct}),new $e.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(o,e.body.password))throw e.context.logger.error("Invalid password"),new $e.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let i=await e.context.internalAdapter.createSession(t.id,e.request);return i?(await e.setSignedCookie(e.context.authCookies.sessionToken.name,i.id,e.context.secret,e.body.dontRememberMe?{...e.context.authCookies.sessionToken.options,maxAge:void 0}:e.context.authCookies.sessionToken.options),e.json({user:t,session:i})):e.json(null,{status:500,body:{message:"Failed to create session",status:500}})})},schema:{user:{fields:{username:{type:"string",required:!1,unique:!0,returned:!0}}}}});var Zr=require("better-call"),ln=()=>({id:"bearer",hooks:{before:[{matcher(e){return!!(e.request?.headers.get("authorization")||e.headers?.get("authorization"))},handler:async e=>{let t=e.request?.headers.get("authorization")?.replace("Bearer ","")||e.headers?.get("authorization")?.replace("Bearer ","");if(!t)return;let r="";return t.includes(".")?r=t:r=await(0,Zr.serializeSigned)("",t,e.context.secret),e.request&&e.request.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${r.replace("=","")}`),e.headers&&e.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${r.replace("=","")}`),{context:e}}}]}});var ke=require("zod");var zt=require("better-call");var pn=e=>({id:"magic-link",endpoints:{signInMagicLink:c("/sign-in/magic-link",{method:"POST",requireHeaders:!0,body:ke.z.object({email:ke.z.string().email(),callbackURL:ke.z.string().optional()})},async t=>{let{email:r}=t.body;if(e.disableSignUp&&!await t.context.internalAdapter.findUserByEmail(r))throw new zt.APIError("BAD_REQUEST",{message:"User not found"});let o=F(32,V("a-z","A-Z"));await t.context.internalAdapter.createVerificationValue({identifier:o,value:r,expiresAt:new Date(Date.now()+(e.expiresIn||60*5)*1e3)});let n=`${t.context.baseURL}/magic-link/verify?token=${o}&callbackURL=${t.body.callbackURL||"/"}`;try{await e.sendMagicLink({email:r,url:n,token:o})}catch(i){throw t.context.logger.error("Failed to send magic link",i),new zt.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to send magic link"})}return t.json({status:!0})}),magicLinkVerify:c("/magic-link/verify",{method:"GET",query:ke.z.object({token:ke.z.string(),callbackURL:ke.z.string().optional()}),requireHeaders:!0},async t=>{let{token:r,callbackURL:o}=t.query,n=o?.startsWith("http")?o:o?`${t.context.options.baseURL}${o}`:t.context.options.baseURL,i=await t.context.internalAdapter.findVerificationValue(r);if(!i)throw t.redirect(`${n}?error=INVALID_TOKEN`);if(i.expiresAt<new Date)throw await t.context.internalAdapter.deleteVerificationValue(i.id),t.redirect(`${n}?error=EXPIRED_TOKEN`);await t.context.internalAdapter.deleteVerificationValue(i.id);let a=i.value,s=await t.context.internalAdapter.findUserByEmail(a),d=s?.user.id||"";if(!s){if(e.disableSignUp)throw t.redirect(`${n}?error=USER_NOT_FOUND`);if(d=(await t.context.internalAdapter.createUser({email:a,emailVerified:!0,name:a})).id,!d)throw t.redirect(`${n}?error=USER_NOT_CREATED`)}let u=await t.context.internalAdapter.createSession(d,t.headers);if(!u)throw t.redirect(`${n}?error=SESSION_NOT_CREATED`);if(await w(t,{session:u,user:s?.user}),!o)return t.json({status:!0});throw t.redirect(o)})},rateLimit:[{pathMatcher(t){return t.startsWith("/sign-in/magic-link")||t.startsWith("/magic-link/verify")},window:e.rateLimit?.window||60,max:e.rateLimit?.max||5}]});var pe=require("zod");var X=require("better-call");function mn(e){return F(e,V("0-9"))}var fn=e=>{let t={phoneNumber:"phoneNumber",phoneNumberVerified:"phoneNumberVerified",code:"code",createdAt:"createdAt",expiresIn:e?.expiresIn||300,otpLength:e?.otpLength||6};return{id:"phone-number",endpoints:{sendPhoneNumberOTP:c("/phone-number/send-otp",{method:"POST",body:pe.z.object({phoneNumber:pe.z.string()})},async r=>{if(!e?.sendOTP)throw y.warn("sendOTP not implemented"),new X.APIError("NOT_IMPLEMENTED",{message:"sendOTP not implemented"});let o=mn(t.otpLength);return await r.context.internalAdapter.createVerificationValue({value:o,identifier:r.body.phoneNumber,expiresAt:C(t.expiresIn,"sec")}),await e.sendOTP(r.body.phoneNumber,o),r.json({code:o},{body:{message:"Code sent"}})}),verifyPhoneNumber:c("/phone-number/verify",{method:"POST",body:pe.z.object({phoneNumber:pe.z.string(),code:pe.z.string(),disableSession:pe.z.boolean().optional(),updatePhoneNumber:pe.z.boolean().optional()})},async r=>{let o=await r.context.internalAdapter.findVerificationValue(r.body.phoneNumber);if(!o||o.expiresAt<new Date)throw o&&o.expiresAt<new Date?(await r.context.internalAdapter.deleteVerificationValue(o.id),new X.APIError("BAD_REQUEST",{message:"OTP expired"})):new X.APIError("BAD_REQUEST",{message:"OTP not found"});if(o.value!==r.body.code)throw new X.APIError("BAD_REQUEST",{message:"Invalid OTP"});if(await r.context.internalAdapter.deleteVerificationValue(o.id),r.body.updatePhoneNumber){let i=await x(r);if(!i)throw new X.APIError("UNAUTHORIZED",{message:"Session not found"});let a=await r.context.internalAdapter.updateUser(i.user.id,{[t.phoneNumber]:r.body.phoneNumber,[t.phoneNumberVerified]:!0});return r.json({user:a,session:i.session})}let n=await r.context.adapter.findOne({model:r.context.tables.user.tableName,where:[{value:r.body.phoneNumber,field:t.phoneNumber}]});if(n)n=await r.context.internalAdapter.updateUser(n.id,{[t.phoneNumberVerified]:!0});else if(e?.signUpOnVerification){if(n=await r.context.internalAdapter.createUser({email:e.signUpOnVerification.getTempEmail(r.body.phoneNumber),name:e.signUpOnVerification.getTempName?e.signUpOnVerification.getTempName(r.body.phoneNumber):r.body.phoneNumber,[t.phoneNumber]:r.body.phoneNumber,[t.phoneNumberVerified]:!0}),!n)throw new X.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"})}else throw new X.APIError("BAD_REQUEST",{message:"Phone number not found"});if(!n)throw new X.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to update user"});if(!r.body.disableSession){let i=await r.context.internalAdapter.createSession(n.id,r.request);if(!i)throw new X.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await w(r,{session:i,user:n}),r.json({user:n,session:i})}return r.json({user:n,session:null})})},schema:{user:{fields:{phoneNumber:{type:"string",required:!1,unique:!0,returned:!0},phoneNumberVerified:{type:"boolean",required:!1,returned:!0,input:!1}}}}}};var dt=require("zod");var gn=e=>({id:"anonymous",endpoints:{signInAnonymous:c("/sign-in/anonymous",{method:"POST"},async t=>{let{emailDomainName:r=Je(t.context.baseURL)}=e||{},o=z(),n=`temp-${o}@${r}`,i=await t.context.internalAdapter.createUser({id:o,email:n,emailVerified:!1,isAnonymous:!0,name:"Anonymous",createdAt:new Date,updatedAt:new Date});if(!i)return t.json(null,{status:500,body:{message:"Failed to create user",status:500}});let a=await t.context.internalAdapter.createSession(i.id,t.request);return a?(await w(t,{session:a,user:i}),t.json({user:i,session:a})):t.json(null,{status:400,body:{message:"Could not create session"}})}),linkAccount:c("/anonymous/link-account",{method:"POST",body:dt.z.object({email:dt.z.string().email().optional(),password:dt.z.string().min(6)}),use:[A]},async t=>{let r=t.context.session.user.id,{email:o,password:n}=t.body,i=null;if(o&&n&&(i=await t.context.internalAdapter.updateUser(r,{email:o,isAnonymous:!1})),!i)return t.json(null,{status:500,body:{message:"Failed to update user",status:500}});let a=await t.context.password.hash(n);if(!await t.context.internalAdapter.linkAccount({userId:i.id,providerId:"credential",password:a,accountId:i.id}))return t.json(null,{status:500,body:{message:"Failed to update account",status:500}});let d=await t.context.internalAdapter.createSession(i.id,t.request);return d?(await w(t,{session:d,user:i}),t.json({session:d,user:i})):t.json(null,{status:400,body:{message:"Could not create session"}})})},schema:{user:{fields:{isAnonymous:{type:"boolean",required:!1}}}}});var g=require("zod");var J=S(async e=>{let t=await x(e);if(!t?.session)throw new R.APIError("UNAUTHORIZED");let r=t.user;if(r.role!=="admin")throw new R.APIError("FORBIDDEN",{message:"Only admins can access this endpoint"});return{session:{user:r,session:t.session}}}),hn=e=>({id:"admin",init(t){return{options:{databaseHooks:{user:{create:{async before(r){if(e?.defaultRole!==!1)return{data:{role:e?.defaultRole??"user",...r}}}}},session:{create:{async before(r){let o=await t.internalAdapter.findUserById(r.userId);if(o.banned){if(o.banExpires&&o.banExpires<Date.now()){await t.internalAdapter.updateUser(r.userId,{banned:!1,banReason:null,banExpires:null});return}return!1}}}}}}}},hooks:{after:[{matcher(t){return t.path==="/list-sessions"},handler:S(async t=>{let r=t.context.returned;if(r){let n=(await r.json()).filter(a=>!a.impersonatedBy),i=new Response(JSON.stringify(n),{status:200,statusText:"OK",headers:r.headers});return t.json({response:i})}})}]},endpoints:{setRole:c("/admin/set-role",{method:"POST",body:g.z.object({userId:g.z.string(),role:g.z.string()}),use:[J]},async t=>{let r=await t.context.internalAdapter.updateUser(t.body.userId,{role:t.body.role});return t.json({user:r})}),createUser:c("/admin/create-user",{method:"POST",body:g.z.object({email:g.z.string(),password:g.z.string(),name:g.z.string(),role:g.z.string(),data:g.z.optional(g.z.record(g.z.any()))}),use:[J]},async t=>{if(await t.context.internalAdapter.findUserByEmail(t.body.email))throw new R.APIError("BAD_REQUEST",{message:"User already exists"});let o=await t.context.internalAdapter.createUser({email:t.body.email,name:t.body.name,role:t.body.role,...t.body.data});if(!o)throw new R.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"});let n=await t.context.password.hash(t.body.password);return await t.context.internalAdapter.linkAccount({accountId:o.id,providerId:"credential",password:n,userId:o.id}),t.json({user:o})}),listUsers:c("/admin/list-users",{method:"GET",use:[J],query:g.z.object({search:g.z.object({field:g.z.enum(["email","name"]),operator:g.z.enum(["contains","starts_with","ends_with"]).default("contains"),value:g.z.string()}).optional(),limit:g.z.string().or(g.z.number()).optional(),offset:g.z.string().or(g.z.number()).optional(),sortBy:g.z.string().optional(),sortDirection:g.z.enum(["asc","desc"]).optional(),filter:g.z.array(g.z.object({field:g.z.string(),value:g.z.string().or(g.z.number()).or(g.z.boolean()),operator:g.z.enum(["eq","ne","lt","lte","gt","gte"]),connector:g.z.enum(["AND","OR"]).optional()})).optional()})},async t=>{let r=[];t.query?.search&&r.push({field:t.query.search.field,operator:t.query.search.operator,value:t.query.search.value}),t.query?.filter&&r.push(...t.query.filter||[]);let o=await t.context.internalAdapter.listUsers(Number(t.query?.limit)||void 0,Number(t.query?.offset)||void 0,t.query?.sortBy?{field:t.query.sortBy,direction:t.query.sortDirection||"asc"}:void 0,r.length?r:void 0);return t.json({users:o})}),listUserSessions:c("/admin/list-user-sessions",{method:"POST",use:[J],body:g.z.object({userId:g.z.string()})},async t=>({sessions:await t.context.internalAdapter.listSessions(t.body.userId)})),unbanUser:c("/admin/unban-user",{method:"POST",body:g.z.object({userId:g.z.string()}),use:[J]},async t=>{let r=await t.context.internalAdapter.updateUser(t.body.userId,{banned:!1});return t.json({user:r})}),banUser:c("/admin/ban-user",{method:"POST",body:g.z.object({userId:g.z.string(),banReason:g.z.string().optional(),banExpiresIn:g.z.number().optional()}),use:[J]},async t=>{if(t.body.userId===t.context.session.user.id)throw new R.APIError("BAD_REQUEST",{message:"You cannot ban yourself"});let r=await t.context.internalAdapter.updateUser(t.body.userId,{banned:!0,banReason:t.body.banReason||e?.defaultBanReason||"No reason",banExpires:t.body.banExpiresIn?C(t.body.banExpiresIn,"sec"):e?.defaultBanExpiresIn?C(e.defaultBanExpiresIn,"sec"):void 0});return await t.context.internalAdapter.deleteSessions(t.body.userId),t.json({user:r})}),impersonateUser:c("/admin/impersonate-user",{method:"POST",body:g.z.object({userId:g.z.string()}),use:[J]},async t=>{let r=await t.context.internalAdapter.findUserById(t.body.userId);if(!r)throw new R.APIError("NOT_FOUND",{message:"User not found"});let o=await t.context.internalAdapter.createSession(r.id,void 0,!0,{impersonatedBy:t.context.session.user.id,expiresAt:e?.impersonationSessionDuration?C(e.impersonationSessionDuration,"sec"):C(60*60,"sec")});if(!o)throw new R.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await w(t,{session:o,user:r},!0),t.json({session:o,user:r})}),revokeUserSession:c("/admin/revoke-user-session",{method:"POST",body:g.z.object({sessionId:g.z.string()}),use:[J]},async t=>(await t.context.internalAdapter.deleteSession(t.body.sessionId),t.json({success:!0}))),revokeUserSessions:c("/admin/revoke-user-sessions",{method:"POST",body:g.z.object({userId:g.z.string()}),use:[J]},async t=>(await t.context.internalAdapter.deleteSessions(t.body.userId),t.json({success:!0}))),removeUser:c("/admin/remove-user",{method:"POST",body:g.z.object({userId:g.z.string()}),use:[J]},async t=>(await t.context.internalAdapter.deleteUser(t.body.userId),t.json({success:!0})))},schema:{user:{fields:{role:{type:"string",required:!1,input:!1},banned:{type:"boolean",defaultValue:!1,required:!1,input:!1},banReason:{type:"string",required:!1,input:!1},banExpires:{type:"date",required:!1,input:!1}}},session:{fields:{impersonatedBy:{type:"string",required:!1}}}}});var ee=require("zod"),Be=require("better-call");var ct=require("@better-fetch/fetch");var Yr=require("oslo/jwt");async function wn(e,t,r){if(t==="oidc"&&e.idToken){let n=(0,Yr.parseJWT)(e.idToken);if(n?.payload)return n.payload}return r?(await(0,ct.betterFetch)(r,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}})).data:null}var yn=e=>({id:"generic-oauth",endpoints:{signInWithOAuth2:c("/sign-in/oauth2",{method:"POST",query:ee.z.object({currentURL:ee.z.string().optional()}).optional(),body:ee.z.object({providerId:ee.z.string(),callbackURL:ee.z.string().optional()})},async t=>{let{providerId:r}=t.body,o=e.config.find(me=>me.providerId===r);if(!o)throw new Be.APIError("BAD_REQUEST",{message:`No config found for provider ${r}`});let{discoveryUrl:n,authorizationUrl:i,tokenUrl:a,clientId:s,clientSecret:d,scopes:u,redirectURI:l,responseType:p,pkce:f,prompt:m,accessType:k}=o,b=i,h=a;if(n){let me=await(0,ct.betterFetch)(n,{onError(lt){y.error(lt.error,{discoveryUrl:n})}});me.data&&(b=me.data.authorization_endpoint,h=me.data.token_endpoint)}if(!b||!h)throw new Be.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let _=t.query?.currentURL?new URL(t.query?.currentURL):null,Oe=t.body.callbackURL?.startsWith("http")?t.body.callbackURL:`${_?.origin}${t.body.callbackURL||""}`,{state:H,codeVerifier:He}=await Re(t),ve=await U({id:r,options:{clientId:s,clientSecret:d,redirectURI:l},authorizationEndpoint:b,state:H,codeVerifier:f?He:void 0,scopes:u||[],redirectURI:`${t.context.baseURL}/oauth2/callback/${r}`});return p&&p!=="code"&&ve.searchParams.set("response_type",p),m&&ve.searchParams.set("prompt",m),k&&ve.searchParams.set("access_type",k),t.json({url:ve.toString(),redirect:!0})}),oAuth2Callback:c("/oauth2/callback/:providerId",{method:"GET",query:ee.z.object({code:ee.z.string().optional(),error:ee.z.string().optional(),state:ee.z.string()})},async t=>{if(t.query.error||!t.query.code)throw t.redirect(`${t.context.baseURL}?error=${t.query.error||"oAuth_code_missing"}`);let r=e.config.find(h=>h.providerId===t.params.providerId);if(!r)throw new Be.APIError("BAD_REQUEST",{message:`No config found for provider ${t.params.providerId}`});let o,n=await Ye(t),{callbackURL:i,codeVerifier:a,errorURL:s}=n,d=t.query.code,u=r.tokenUrl,l=r.userInfoUrl;if(r.discoveryUrl){let h=await(0,ct.betterFetch)(r.discoveryUrl,{method:"GET"});h.data&&(u=h.data.token_endpoint,l=h.data.userinfo_endpoint)}try{if(!u)throw new Be.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});o=await v({code:d,codeVerifier:a,redirectURI:`${t.context.baseURL}/oauth2/callback/${r.providerId}`,options:{clientId:r.clientId,clientSecret:r.clientSecret},tokenEndpoint:u})}catch(h){throw t.context.logger.error(h),t.redirect(`${s}?error=oauth_code_verification_failed`)}if(!o)throw new Be.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let p=r.getUserInfo?await r.getUserInfo(o):await wn(o,r.type||"oauth2",l),f=z(),m=p?tt.safeParse({...p,id:f}):null;if(!m?.success)throw t.redirect(`${s}?error=oauth_user_info_invalid`);let k=await t.context.internalAdapter.findUserByEmail(m.data.email,{includeAccounts:!0}).catch(h=>{throw y.error(`Better auth was unable to query your database.
85
- Error: `,h),t.redirect(`${s}?error=internal_server_error`)}),b=k?.user.id||f;if(k){let h=k.accounts.find(H=>H.providerId===r.providerId),_=t.context.options.account?.accountLinking?.trustedProviders,Oe=_?_.includes(r.providerId):!0;if(!h&&(!m?.data.emailVerified||!Oe)){let H;try{H=new URL(s),H.searchParams.set("error","account_not_linked")}catch{throw t.redirect(`${s}?error=account_not_linked`)}throw t.redirect(H.toString())}if(h)await t.context.internalAdapter.updateAccount(h.id,{accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,expiresAt:o.accessTokenExpiresAt});else try{await t.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:m.data.id,id:`${r.providerId}:${m.data.id}`,userId:k.user.id,accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,expiresAt:o.accessTokenExpiresAt})}catch(H){throw console.log(H),t.redirect(`${s}?error=failed_linking_account`)}}else try{await t.context.internalAdapter.createOAuthUser(m.data,{id:`${r.providerId}:${m.data.id}`,providerId:r.providerId,accountId:m.data.id,accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,expiresAt:o.accessTokenExpiresAt})}catch{let _=new URL(s);throw _.searchParams.set("error","unable_to_create_user"),t.setHeader("Location",_.toString()),t.redirect(_.toString())}try{let h=await t.context.internalAdapter.createSession(b||f,t.request);if(!h)throw t.redirect(`${s}?error=unable_to_create_session`);await w(t,{session:h,user:m.data})}catch{throw t.redirect(`${s}?error=unable_to_create_session`)}throw t.redirect(i)})}});var Le=require("zod"),Xr={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0}}}},ml=Le.z.object({id:Le.z.string(),publicKey:Le.z.string(),privateKey:Le.z.string(),createdAt:Le.z.date()});var Bt=e=>({getAllKeys:async()=>await e.findMany({model:"jwks"}),getLatestKey:async()=>(await e.findMany({model:"jwks",sortBy:{field:"createdAt",direction:"desc"},limit:1}))[0],createJwk:async t=>await e.create({model:"jwks",data:{...t,createdAt:new Date}})});var ie=require("jose");var bn=e=>({id:"jwt",endpoints:{getJwks:c("/jwks",{method:"GET"},async t=>{let o=await Bt(t.context.adapter).getAllKeys();return t.json({keys:o.map(n=>({...JSON.parse(n.publicKey),kid:n.id}))})}),getToken:c("/token",{method:"GET",requireHeaders:!0,use:[A]},async t=>{let r=Bt(t.context.adapter),o=await r.getLatestKey(),n=!e?.jwks?.disablePrivateKeyEncryption;if(o===void 0){let{publicKey:u,privateKey:l}=await(0,ie.generateKeyPair)(e?.jwks?.keyPairConfig?.alg??"EdDSA",e?.jwks?.keyPairConfig??{crv:"Ed25519"}),p=await(0,ie.exportJWK)(u),f=await(0,ie.exportJWK)(l),m=JSON.stringify(f),k={id:crypto.randomUUID(),publicKey:JSON.stringify(p),privateKey:n?JSON.stringify(await ce({key:t.context.options.secret,data:m})):m,createdAt:new Date};o=await r.createJwk(k)}let i=n?await ue({key:t.context.options.secret,data:JSON.parse(o.privateKey)}):o.privateKey,a=await(0,ie.importJWK)(JSON.parse(i)),s=e?.jwt?.definePayload?await e?.jwt.definePayload(t.context.session.user):t.context.session.user,d=await new ie.SignJWT({...s,...t.context.session.session.impersonatedBy?{impersonatedBy:t.context.session.session.impersonatedBy}:{}}).setProtectedHeader({alg:e?.jwks?.keyPairConfig?.alg??"EdDSA",kid:o.id}).setIssuedAt().setIssuer(e?.jwt?.issuer??t.context.options.baseURL).setAudience(e?.jwt?.audience??t.context.options.baseURL).setExpirationTime(e?.jwt?.expirationTime??"15m").setSubject(t.context.session.user.id).sign(a);return t.json({token:d})})},schema:Xr});var Qe=require("zod");var An=e=>{let t={maximumSessions:5,...e},r=o=>o.includes("_multi-");return{id:"multi-session",endpoints:{listDeviceSessions:c("/multi-session/list-device-sessions",{method:"GET",requireHeaders:!0},async o=>{let n=o.headers?.get("cookie");if(!n)return o.json([]);let i=Object.fromEntries(Ke(n)),a=(await Promise.all(Object.entries(i).filter(([u])=>r(u)).map(async([u])=>await o.getSignedCookie(u,o.context.secret)))).filter(u=>u!==void 0);if(!a.length)return o.json([]);let d=(await o.context.internalAdapter.findSessions(a)).filter(u=>u&&u.session.expiresAt>new Date).filter((u,l,p)=>l===p.findIndex(f=>f.user.id===u.user.id));return Object.entries(i).filter(([u])=>r(u)).forEach(([u,l])=>{d.some(p=>p.session.id===l)||o.setCookie(u,"",{...o.context.authCookies.sessionToken.options,maxAge:0})}),o.json(d)}),setActiveSession:c("/multi-session/set-active",{method:"POST",body:Qe.z.object({sessionId:Qe.z.string()}),requireHeaders:!0,use:[A]},async o=>{let n=o.body.sessionId,i=`${o.context.authCookies.sessionToken.name}_multi-${n}`;if(!await o.getSignedCookie(i,o.context.secret))throw new R.APIError("UNAUTHORIZED",{message:"Invalid session id"});let s=await o.context.internalAdapter.findSession(n);if(!s||s.session.expiresAt<new Date)throw o.setCookie(i,"",{...o.context.authCookies.sessionToken.options,maxAge:0}),new R.APIError("UNAUTHORIZED",{message:"Invalid session id"});return await o.setSignedCookie(o.context.authCookies.sessionToken.name,n,o.context.secret,o.context.authCookies.sessionToken.options),o.json(s)}),revokeDeviceSession:c("/multi-session/revoke",{method:"POST",body:Qe.z.object({sessionId:Qe.z.string()}),requireHeaders:!0,use:[A]},async o=>{let n=o.body.sessionId,i=`${o.context.authCookies.sessionToken.name}_multi-${n}`;if(!await o.getSignedCookie(i,o.context.secret))throw new R.APIError("UNAUTHORIZED",{message:"Invalid session id"});let s=await o.context.internalAdapter.findSession(n);return o.setCookie(i,"",{...o.context.authCookies.sessionToken.options,maxAge:0}),s?(await o.context.internalAdapter.deleteSession(n),o.json({success:!0})):o.json({success:!0})})},hooks:{after:[{matcher:()=>!0,handler:S(async o=>{if(!o.context.returned||!(o.context.returned instanceof Response))return;let n=o.context.returned.headers.get("set-cookie");if(!n)return;let i=Nt(n),a=o.context.authCookies.sessionToken,s=i.get(a.name)?.value;if(!s)return;let d=Ke(o.headers?.get("cookie")||""),u=s.split(".")[0],l=`${a.name}_multi-${u}`;if(i.get(l)||d.get(l)||Object.keys(Object.fromEntries(d)).filter(r).length+(n.includes("session_token")?1:0)>t.maximumSessions)return;await o.setSignedCookie(l,u,o.context.secret,a.options);let f=o.context.returned;return f.headers.append("Set-Cookie",o.responseHeader.get("set-cookie")),{response:f}})},{matcher:o=>o.path==="/sign-out",handler:S(async o=>{let n=o.headers?.get("cookie");if(!n)return;let i=Object.fromEntries(Ke(n));await Promise.all(Object.entries(i).map(async([s,d])=>{if(r(s)){o.setCookie(s,"",{maxAge:0});let u=s.split("_multi-")[1];await o.context.internalAdapter.deleteSession(u)}}));let a=o.context.returned;return a?.headers.append("Set-Cookie",o.responseHeader.get("set-cookie")),{response:a}})}]}}};var te=require("zod");var kn=e=>{let t={expireIn:300,otpLength:6,...e};return{id:"email-otp",endpoints:{sendVerificationOTP:c("/email-otp/send-verification-otp",{method:"POST",body:te.z.object({email:te.z.string(),type:te.z.enum(["email-verification","sign-in"])})},async r=>{if(!e?.sendVerificationOTP)throw y.error("send email verification is not implemented"),new R.APIError("BAD_REQUEST",{message:"send email verification is not implemented"});let o=r.body.email,n=F(t.otpLength,V("0-9"));return await r.context.internalAdapter.createVerificationValue({value:n,identifier:`${r.body.type}-otp-${o}`,expiresAt:C(t.expireIn,"sec")}),await e.sendVerificationOTP({email:o,otp:n,type:r.body.type}),r.json({success:!0})}),verifyEmailOTP:c("/email-otp/verify-email",{method:"POST",body:te.z.object({email:te.z.string(),otp:te.z.string()})},async r=>{let o=r.body.email,n=await r.context.internalAdapter.findVerificationValue(`email-verification-otp-${o}`);if(!n||n.expiresAt<new Date)throw n&&await r.context.internalAdapter.deleteVerificationValue(n.id),new R.APIError("BAD_REQUEST",{message:"Invalid OTP"});let i=r.body.otp;if(n.value!==i)throw new R.APIError("BAD_REQUEST",{message:"Invalid OTP"});await r.context.internalAdapter.deleteVerificationValue(n.id);let a=await r.context.internalAdapter.findUserByEmail(o);if(!a)throw new R.APIError("BAD_REQUEST",{message:"User not found"});let s=await r.context.internalAdapter.updateUser(a.user.id,{email:o,emailVerified:!0});return r.json({user:s})}),signInEmailOTP:c("/sign-in/email-otp",{method:"POST",body:te.z.object({email:te.z.string(),otp:te.z.string()})},async r=>{let o=r.body.email,n=await r.context.internalAdapter.findVerificationValue(`sign-in-otp-${o}`);if(!n||n.expiresAt<new Date)throw n&&await r.context.internalAdapter.deleteVerificationValue(n.id),new R.APIError("BAD_REQUEST",{message:"Invalid OTP"});let i=r.body.otp;if(n.value!==i)throw new R.APIError("BAD_REQUEST",{message:"Invalid OTP"});await r.context.internalAdapter.deleteVerificationValue(n.id);let a=await r.context.internalAdapter.findUserByEmail(o);if(!a){if(t.disableSignUp)throw new R.APIError("BAD_REQUEST",{message:"User not found"});let d=await r.context.internalAdapter.createUser({email:o,emailVerified:!0,name:o}),u=await r.context.internalAdapter.createSession(d.id,r.request);return await w(r,{session:u,user:d}),r.json({user:d,session:u})}let s=await r.context.internalAdapter.createSession(a.user.id,r.request);return await w(r,{session:s,user:a.user}),r.json({session:s,user:a})})},hooks:{after:[{matcher(r){return!!(r.path?.startsWith("/sign-up")&&t.sendVerificationOnSignUp)},async handler(r){let o=r.context.returned;if(o?.status!==200)return;let n=await o.clone().json();if(n.user.email&&n.user.emailVerified===!1){let i=F(t.otpLength,V("0-9"));await r.context.internalAdapter.createVerificationValue({value:i,identifier:`email-verification-otp-${n.user.email}`,expiresAt:C(t.expireIn,"sec")}),await e.sendVerificationOTP({email:n.user.email,otp:i,type:"email-verification"})}}}]}}};var Lt=require("zod");var to=require("@better-fetch/fetch");function eo(e){return e==="true"||e===!0}var On=e=>({id:"one-tap",endpoints:{oneTapCallback:c("/one-tap/callback",{method:"POST",body:Lt.z.object({idToken:Lt.z.string()})},async t=>{let{idToken:r}=t.body,{data:o,error:n}=await(0,to.betterFetch)("https://oauth2.googleapis.com/tokeninfo?id_token="+r);if(n)return t.json({error:"Invalid token"});let i=await t.context.internalAdapter.findUserByEmail(o.email);if(!i){if(e?.disableSignup)throw new R.APIError("BAD_GATEWAY",{message:"User not found"});let s=await t.context.internalAdapter.createOAuthUser({email:o.email,emailVerified:eo(o.email_verified),name:o.name,image:o.picture},{providerId:"google",accountId:o.sub});if(!s)throw new R.APIError("INTERNAL_SERVER_ERROR",{message:"Could not create user"});let d=await t.context.internalAdapter.createSession(s?.user.id,t.request);return await w(t,{user:s.user,session:d}),t.json({session:d,user:s})}let a=await t.context.internalAdapter.createSession(i.user.id,t.request);return await w(t,{user:i.user,session:a}),t.json({session:a,user:i})})}});var ut=require("zod");function vn(){let e=G.VERCEL_URL,t=G.NETLIFY_URL,r=G.RENDER_URL,o=G.AWS_LAMBDA_FUNCTION_NAME,n=G.GOOGLE_CLOUD_FUNCTION_NAME,i=G.AZURE_FUNCTION_NAME;return e||t||r||o||n||i}var Rn=e=>({id:"oauth-proxy",endpoints:{oAuthProxy:c("/oauth-proxy-callback",{method:"GET",query:ut.z.object({callbackURL:ut.z.string(),cookies:ut.z.string()})},async t=>{let r=t.query.cookies,o=await ue({key:t.context.secret,data:r});throw t.setHeader("set-cookie",o),t.redirect(t.query.callbackURL)})},hooks:{after:[{matcher(t){return t.path?.startsWith("/callback")},handler:S(async t=>{let r=t.context.returned;if(!r)return;let o=r.headers.get("location");if(o?.includes("/oauth-proxy-callback?callbackURL")){if(!o.startsWith("http")||new URL(o).origin===t.context.baseURL)return;let i=r.headers.get("set-cookie");if(!i)return;let a=await ce({key:t.context.secret,data:i}),s=`${o}&cookies=${encodeURIComponent(a)}`;return r.headers.set("location",s),{response:r}}})}],before:[{matcher(t){return t.path?.startsWith("/sign-in/social")},async handler(t){let r=new URL(e?.currentURL||t.request?.url||vn()||t.context.baseURL);return t.body.callbackURL=`${r.origin}${t.context.options.basePath||"/api/auth"}/oauth-proxy-callback?callbackURL=${encodeURIComponent(t.body.callbackURL||t.context.baseURL)}`,{context:t}}}]}});0&&(module.exports={HIDE_METADATA,admin,adminMiddleware,anonymous,bearer,createAuthEndpoint,createAuthMiddleware,emailOTP,genericOAuth,getPasskeyActions,jwt,magicLink,multiSession,oAuthProxy,oneTap,optionsMiddleware,organization,passkey,passkeyClient,phoneNumber,twoFactor,twoFactorClient,username});
83
+ </html>`,xo=c("/error",{method:"GET",metadata:fe},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Lo(t),{headers:{"Content-Type":"text/html"}})});var Do=c("/ok",{method:"GET",metadata:fe},async e=>e.json({ok:!0}));var jo=require("zod");var No=require("better-call");var Ee=require("zod");var wt=require("better-call");var Fo=c("/list-accounts",{method:"GET",use:[A]},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(o=>({id:o.id,provider:o.providerId})))}),Vo=c("/link-social",{method:"POST",requireHeaders:!0,query:Ee.z.object({currentURL:Ee.z.string().optional()}).optional(),body:Ee.z.object({callbackURL:Ee.z.string().optional(),provider:Ee.z.enum(Xe)}),use:[A]},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(s=>s.providerId===e.body.provider))throw new wt.APIError("BAD_REQUEST",{message:"Social Account is already linked."});let n=e.context.socialProviders.find(s=>s.id===e.body.provider);if(!n)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new wt.APIError("NOT_FOUND",{message:"Provider not found"});let i=await Oe(e,{userId:t.user.id,email:t.user.email}),a=await n.createAuthorizationURL({state:i.state,codeVerifier:i.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${n.id}`});return e.json({url:a.toString(),redirect:!0})});var kr=(e,t)=>{let r={};for(let[o,n]of Object.entries(e))r[o]=i=>n({...i,context:{...t,...i.context}}),r[o].path=n.path,r[o].method=n.method,r[o].options=n.options,r[o].headers=n.headers;return r};var Ue=class extends Error{path;constructor(t,r){super(t),this.path=r}},rt=class{constructor(t){this.s=t;this.statements=t}statements;newRole(t){return new ot(t)}},ot=class e{statements;constructor(t){this.statements=t}authorize(t,r){for(let[o,n]of Object.entries(t)){let i=this.statements[o];if(!i)return{success:!1,error:`You are not allowed to access resource: ${o}`};let a=r==="OR"?n.some(s=>i.includes(s)):n.every(s=>i.includes(s));return a?{success:a}:{success:!1,error:`unauthorized to access resource "${o}"`}}return{success:!1,error:"Not authorized"}}static fromString(t){let r=JSON.parse(t);if(typeof r!="object")throw new Ue("statements is not an object",".");for(let[o,n]of Object.entries(r)){if(typeof o!="string")throw new Ue("invalid resource identifier",o);if(!Array.isArray(n))throw new Ue("actions is not an array",o);for(let i=0;i<n.length;i++)if(typeof n[i]!="string")throw new Ue("action is not a string",`${o}[${i}]`)}return new e(r)}toString(){return JSON.stringify(this.statements)}};var qo=e=>new rt(e),Mo={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},yt=qo(Mo),$o=yt.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),Qo=yt.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),Wo=yt.newRole({organization:[],member:[],invitation:[]}),Or={admin:$o,owner:Qo,member:Wo};var P=(e,t)=>{let r=e.adapter;return{findOrganizationBySlug:async o=>await r.findOne({model:"organization",where:[{field:"slug",value:o}]}),createOrganization:async o=>{let n=await r.create({model:"organization",data:{...o.organization,metadata:o.organization.metadata?JSON.stringify(o.organization.metadata):void 0}}),i=await r.create({model:"member",data:{id:z(),organizationId:n.id,userId:o.user.id,createdAt:new Date,email:o.user.email,role:t?.creatorRole||"owner"}});return{...n,metadata:n.metadata?JSON.parse(n.metadata):void 0,members:[{...i,user:{id:o.user.id,name:o.user.name,email:o.user.email,image:o.user.image}}]}},findMemberByEmail:async o=>{let n=await r.findOne({model:"member",where:[{field:"email",value:o.email},{field:"organizationId",value:o.organizationId}]});if(!n)return null;let i=await r.findOne({model:e.tables.user.tableName,where:[{field:"id",value:n.userId}]});return i?{...n,user:{id:i.id,name:i.name,email:i.email,image:i.image}}:null},findMemberByOrgId:async o=>{let[n,i]=await Promise.all([await r.findOne({model:"member",where:[{field:"userId",value:o.userId},{field:"organizationId",value:o.organizationId}]}),await r.findOne({model:e.tables.user.tableName,where:[{field:"id",value:o.userId}]})]);return!i||!n?null:{...n,user:{id:i.id,name:i.name,email:i.email,image:i.image}}},findMemberById:async o=>{let n=await r.findOne({model:"member",where:[{field:"id",value:o}]});if(!n)return null;let i=await r.findOne({model:e.tables.user.tableName,where:[{field:"id",value:n.userId}]});return i?{...n,user:{id:i.id,name:i.name,email:i.email,image:i.image}}:null},createMember:async o=>await r.create({model:"member",data:o}),updateMember:async(o,n)=>await r.update({model:"member",where:[{field:"id",value:o}],update:{role:n}}),deleteMember:async o=>await r.delete({model:"member",where:[{field:"id",value:o}]}),updateOrganization:async(o,n)=>await r.update({model:"organization",where:[{field:"id",value:o}],update:n}),deleteOrganization:async o=>(await r.delete({model:"member",where:[{field:"organizationId",value:o}]}),await r.delete({model:"invitation",where:[{field:"organizationId",value:o}]}),await r.delete({model:"organization",where:[{field:"id",value:o}]}),o),setActiveOrganization:async(o,n)=>await r.update({model:e.tables.session.tableName,where:[{field:"id",value:o}],update:{activeOrganizationId:n}}),findOrganizationById:async o=>await r.findOne({model:"organization",where:[{field:"id",value:o}]}),findFullOrganization:async(o,n)=>{let[i,a,s]=await Promise.all([r.findOne({model:"organization",where:[{field:"id",value:o}]}),r.findMany({model:"invitation",where:[{field:"organizationId",value:o}]}),r.findMany({model:"member",where:[{field:"organizationId",value:o}]})]);if(!i)return null;let d=s.map(f=>f.userId),u=await r.findMany({model:e.tables.user.tableName,where:[{field:"id",value:d,operator:"in"}]}),l=new Map(u.map(f=>[f.id,f])),m=s.map(f=>{let p=l.get(f.userId);if(!p)throw new H("Unexpected error: User not found for member");return{...f,user:{id:p.id,name:p.name,email:p.email,image:p.image}}});return{...i,invitations:a,members:m}},listOrganizations:async o=>{let n=await r.findMany({model:"member",where:[{field:"userId",value:o}]});if(!n||n.length===0)return[];let i=n.map(s=>s.organizationId);return await r.findMany({model:"organization",where:[{field:"id",value:i,operator:"in"}]})},createInvitation:async({invitation:o,user:n})=>{let a=C(t?.invitationExpiresIn||1728e5);return await r.create({model:"invitation",data:{id:z(),email:o.email,role:o.role,organizationId:o.organizationId,status:"pending",expiresAt:a,inviterId:n.id}})},findInvitationById:async o=>await r.findOne({model:"invitation",where:[{field:"id",value:o}]}),findPendingInvitation:async o=>(await r.findMany({model:"invitation",where:[{field:"email",value:o.email},{field:"organizationId",value:o.organizationId},{field:"status",value:"pending"}]})).filter(i=>new Date(i.expiresAt)>new Date),updateInvitation:async o=>await r.update({model:"invitation",where:[{field:"id",value:o.invitationId}],update:{status:o.status}})}};var Ad=require("better-call");var bt=require("better-call");var Rr=require("better-call");var Ho=S(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=t?.callbackURL||r?.callbackURL,a=t?.redirectTo,s=r?.currentURL,d=o.trustedOrigins,u=e.headers?.has("cookie"),l=(f,p)=>p.includes("*")?new RegExp("^"+p.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(f):f.startsWith(p),m=(f,p)=>{if(!f)return;if(!d.some(b=>l(f,b)||f?.startsWith("/")&&p!=="origin"&&!f.includes(":")))throw y.error(`Invalid ${p}: ${f}`),y.info(`If it's a valid URL, please add ${f} to trustedOrigins in your auth config
84
+ `,`Current list of trustedOrigins: ${d}`),new Rr.APIError("FORBIDDEN",{message:`Invalid ${p}`})};u&&!e.context.options.advanced?.disableCSRFCheck&&m(n,"origin"),i&&m(i,"callbackURL"),a&&m(a,"redirectURL"),s&&m(s,"currentURL")});var v=require("better-call");var B=S(async e=>({})),L=S({use:[A]},async e=>({session:e.context.session}));var N=require("zod");var E=require("zod"),nt=E.z.enum(["admin","member","owner"]),Go=E.z.enum(["pending","accepted","rejected","canceled"]).default("pending"),vd=E.z.object({id:E.z.string(),name:E.z.string(),slug:E.z.string(),logo:E.z.string().optional(),metadata:E.z.record(E.z.string()).or(E.z.string().transform(e=>JSON.parse(e))).optional(),createdAt:E.z.date()}),Ed=E.z.object({id:E.z.string(),email:E.z.string(),organizationId:E.z.string(),userId:E.z.string(),role:nt,createdAt:E.z.date()}),Ud=E.z.object({id:E.z.string(),organizationId:E.z.string(),email:E.z.string(),role:nt,status:Go,inviterId:E.z.string(),expiresAt:E.z.date()});var I=require("better-call"),vr=c("/organization/invite-member",{method:"POST",use:[B,L],body:N.z.object({email:N.z.string(),role:nt,organizationId:N.z.string().optional(),resend:N.z.boolean().optional()})},async e=>{if(!e.context.orgOptions.sendInvitationEmail)throw y.warn("Invitation email is not enabled. Pass `sendInvitationEmail` to the plugin options to enable it."),new I.APIError("BAD_REQUEST",{message:"Invitation email is not enabled"});let t=e.context.session,r=e.body.organizationId||t.session.activeOrganizationId;if(!r)throw new I.APIError("BAD_REQUEST",{message:"Organization not found"});let o=P(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!n)throw new I.APIError("BAD_REQUEST",{message:"Member not found!"});let i=e.context.roles[n.role];if(!i)throw new I.APIError("BAD_REQUEST",{message:"Role not found!"});if(i.authorize({invitation:["create"]}).error)throw new I.APIError("FORBIDDEN",{message:"You are not allowed to invite members"});if(await o.findMemberByEmail({email:e.body.email,organizationId:r}))throw new I.APIError("BAD_REQUEST",{message:"User is already a member of this organization"});if((await o.findPendingInvitation({email:e.body.email,organizationId:r})).length&&!e.body.resend)throw new I.APIError("BAD_REQUEST",{message:"User is already invited to this organization"});let u=await o.createInvitation({invitation:{role:e.body.role,email:e.body.email,organizationId:r},user:t.user}),l=await o.findOrganizationById(r);if(!l)throw new I.APIError("BAD_REQUEST",{message:"Organization not found"});return await e.context.orgOptions.sendInvitationEmail?.({id:u.id,role:u.role,email:u.email,organization:l,inviter:{...n,user:t.user}},e.request),e.json(u)}),Er=c("/organization/accept-invitation",{method:"POST",body:N.z.object({invitationId:N.z.string()}),use:[B,L]},async e=>{let t=e.context.session,r=P(e.context,e.context.orgOptions),o=await r.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new I.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==t.user.email)throw new I.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let n=await r.updateInvitation({invitationId:e.body.invitationId,status:"accepted"}),i=await r.createMember({id:z(),organizationId:o.organizationId,userId:t.user.id,email:o.email,role:o.role,createdAt:new Date});return await r.setActiveOrganization(t.session.id,o.organizationId),n?e.json({invitation:n,member:i}):e.json(null,{status:400,body:{message:"Invitation not found!"}})}),Ur=c("/organization/reject-invitation",{method:"POST",body:N.z.object({invitationId:N.z.string()}),use:[B,L]},async e=>{let t=e.context.session,r=P(e.context,e.context.orgOptions),o=await r.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new I.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==t.user.email)throw new I.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let n=await r.updateInvitation({invitationId:e.body.invitationId,status:"rejected"});return e.json({invitation:n,member:null})}),Ir=c("/organization/cancel-invitation",{method:"POST",body:N.z.object({invitationId:N.z.string()}),use:[B,L]},async e=>{let t=e.context.session,r=P(e.context,e.context.orgOptions),o=await r.findInvitationById(e.body.invitationId);if(!o)throw new I.APIError("BAD_REQUEST",{message:"Invitation not found!"});let n=await r.findMemberByOrgId({userId:t.user.id,organizationId:o.organizationId});if(!n)throw new I.APIError("BAD_REQUEST",{message:"Member not found!"});if(e.context.roles[n.role].authorize({invitation:["cancel"]}).error)throw new I.APIError("FORBIDDEN",{message:"You are not allowed to cancel this invitation"});let a=await r.updateInvitation({invitationId:e.body.invitationId,status:"canceled"});return e.json(a)}),Tr=c("/organization/get-invitation",{method:"GET",use:[B],requireHeaders:!0,query:N.z.object({id:N.z.string()})},async e=>{let t=await x(e);if(!t)throw new I.APIError("UNAUTHORIZED",{message:"Not authenticated"});let r=P(e.context,e.context.orgOptions),o=await r.findInvitationById(e.query.id);if(!o||o.status!=="pending"||o.expiresAt<new Date)throw new I.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==t.user.email)throw new I.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let n=await r.findOrganizationById(o.organizationId);if(!n)throw new I.APIError("BAD_REQUEST",{message:"Organization not found"});let i=await r.findMemberByOrgId({userId:o.inviterId,organizationId:o.organizationId});if(!i)throw new I.APIError("BAD_REQUEST",{message:"Inviter is no longer a member of the organization"});return e.json({...o,organizationName:n.name,organizationSlug:n.slug,inviterEmail:i.email})});var se=require("zod");var Ie=require("better-call"),Sr=c("/organization/remove-member",{method:"POST",body:se.z.object({memberIdOrEmail:se.z.string(),organizationId:se.z.string().optional()}),use:[B,L]},async e=>{let t=e.context.session,r=e.body.organizationId||t.session.activeOrganizationId;if(!r)return e.json(null,{status:400,body:{message:"No active organization found!"}});let o=P(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!n)throw new Ie.APIError("BAD_REQUEST",{message:"Member not found!"});let i=e.context.roles[n.role];if(!i)throw new Ie.APIError("BAD_REQUEST",{message:"Role not found!"});let a=t.user.email===e.body.memberIdOrEmail||n.id===e.body.memberIdOrEmail;if(a&&n.role===(e.context.orgOptions?.creatorRole||"owner"))throw new Ie.APIError("BAD_REQUEST",{message:"You cannot leave the organization as the owner"});if(!(a||i.authorize({member:["delete"]}).success))throw new Ie.APIError("UNAUTHORIZED",{message:"You are not allowed to delete this member"});let u=null;if(e.body.memberIdOrEmail.includes("@")?u=await o.findMemberByEmail({email:e.body.memberIdOrEmail,organizationId:r}):u=await o.findMemberById(e.body.memberIdOrEmail),u?.organizationId!==r)throw new Ie.APIError("BAD_REQUEST",{message:"Member not found!"});return await o.deleteMember(u.id),t.user.id===u.userId&&t.session.activeOrganizationId===u.organizationId&&await o.setActiveOrganization(t.session.id,null),e.json({member:u})}),Pr=c("/organization/update-member-role",{method:"POST",body:se.z.object({role:se.z.enum(["admin","member","owner"]),memberId:se.z.string(),organizationId:se.z.string().optional()}),use:[B,L]},async e=>{let t=e.context.session,r=e.body.organizationId||t.session.activeOrganizationId;if(!r)return e.json(null,{status:400,body:{message:"No active organization found!"}});let o=P(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!n)return e.json(null,{status:400,body:{message:"Member not found!"}});let i=e.context.roles[n.role];if(!i)return e.json(null,{status:400,body:{message:"Role not found!"}});if(i.authorize({member:["update"]}).error||e.body.role==="owner"&&n.role!=="owner")return e.json(null,{body:{message:"You are not allowed to update this member"},status:403});let s=await o.updateMember(e.body.memberId,e.body.role);return s?e.json(s):e.json(null,{status:400,body:{message:"Member not found!"}})}),_r=c("/organization/get-active-member",{method:"GET",use:[B,L]},async e=>{let t=e.context.session,r=t.session.activeOrganizationId;if(!r)return e.json(null,{status:400,body:{message:"No active organization found!"}});let n=await P(e.context,e.context.orgOptions).findMemberByOrgId({userId:t.user.id,organizationId:r});return n?e.json(n):e.json(null,{status:400,body:{message:"Member not found!"}})});var T=require("zod");var ae=require("better-call"),Cr=c("/organization/create",{method:"POST",body:T.z.object({name:T.z.string(),slug:T.z.string(),userId:T.z.string().optional(),logo:T.z.string().optional(),metadata:T.z.record(T.z.string()).optional()}),use:[B,L]},async e=>{let t=e.context.session.user;if(!t)return e.json(null,{status:401});let r=e.context.orgOptions;if(!(typeof r?.allowUserToCreateOrganization=="function"?await r.allowUserToCreateOrganization(t):r?.allowUserToCreateOrganization===void 0?!0:r.allowUserToCreateOrganization))throw new ae.APIError("FORBIDDEN",{message:"You are not allowed to create an organization"});let n=P(e.context,r),i=await n.listOrganizations(t.id);if(typeof r.organizationLimit=="number"?i.length>=r.organizationLimit:typeof r.organizationLimit=="function"?await r.organizationLimit(t):!1)throw new ae.APIError("FORBIDDEN",{message:"You have reached the organization limit"});if(await n.findOrganizationBySlug(e.body.slug))throw new ae.APIError("BAD_REQUEST",{message:"Organization with this slug already exists"});let d=await n.createOrganization({organization:{id:z(),slug:e.body.slug,name:e.body.name,logo:e.body.logo,createdAt:new Date,metadata:e.body.metadata},user:t});return e.json(d)}),zr=c("/organization/update",{method:"POST",body:T.z.object({data:T.z.object({name:T.z.string().optional(),slug:T.z.string().optional(),logo:T.z.string().optional()}).partial(),orgId:T.z.string().optional()}),requireHeaders:!0,use:[B]},async e=>{let t=await e.context.getSession(e);if(!t)throw new ae.APIError("UNAUTHORIZED",{message:"User not found"});let r=e.body.orgId||t.session.activeOrganizationId;if(!r)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let o=P(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!n)return e.json(null,{status:400,body:{message:"User is not a member of this organization!"}});let i=e.context.roles[n.role];if(!i)return e.json(null,{status:400,body:{message:"Role not found!"}});if(i.authorize({organization:["update"]}).error)return e.json(null,{body:{message:"You are not allowed to update this organization"},status:403});let s=await o.updateOrganization(r,e.body.data);return e.json(s)}),Br=c("/organization/delete",{method:"POST",body:T.z.object({orgId:T.z.string()}),requireHeaders:!0,use:[B]},async e=>{let t=await e.context.getSession(e);if(!t)return e.json(null,{status:401});let r=e.body.orgId;if(!r)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let o=P(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:t.user.id,organizationId:r});if(!n)return e.json(null,{status:400,body:{message:"User is not a member of this organization!"}});let i=e.context.roles[n.role];if(!i)return e.json(null,{status:400,body:{message:"Role not found!"}});if(i.authorize({organization:["delete"]}).error)throw new ae.APIError("FORBIDDEN",{message:"You are not allowed to delete this organization"});return r===t.session.activeOrganizationId&&await o.setActiveOrganization(t.session.id,null),await o.deleteOrganization(r),e.json(r)}),Lr=c("/organization/get-full",{method:"GET",query:T.z.optional(T.z.object({orgId:T.z.string().optional()})),requireHeaders:!0,use:[B,L]},async e=>{let t=e.context.session,r=e.query?.orgId||t.session.activeOrganizationId;if(!r)return e.json(null,{status:200});let n=await P(e.context,e.context.orgOptions).findFullOrganization(r,e.context.db||void 0);if(!n)throw new ae.APIError("BAD_REQUEST",{message:"Organization not found"});return e.json(n)}),xr=c("/organization/set-active",{method:"POST",body:T.z.object({orgId:T.z.string().nullable().optional()}),use:[L,B]},async e=>{let t=P(e.context,e.context.orgOptions),r=e.context.session,o=e.body.orgId;if(o===null)return r.session.activeOrganizationId&&await t.setActiveOrganization(r.session.id,null),e.json(null);if(!o){let a=r.session.activeOrganizationId;if(!a)return e.json(null);o=a}if(!await t.findMemberByOrgId({userId:r.user.id,organizationId:o}))throw await t.setActiveOrganization(r.session.id,null),new ae.APIError("FORBIDDEN",{message:"You are not a member of this organization"});await t.setActiveOrganization(r.session.id,o);let i=await t.findFullOrganization(o,e.context.db||void 0);return e.json(i)}),Dr=c("/organization/list",{method:"GET",use:[B,L]},async e=>{let r=await P(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(r)});var Ko=e=>{let t={createOrganization:Cr,updateOrganization:zr,deleteOrganization:Br,setActiveOrganization:xr,getFullOrganization:Lr,listOrganization:Dr,createInvitation:vr,cancelInvitation:Ir,acceptInvitation:Er,getInvitation:Tr,rejectInvitation:Ur,removeMember:Sr,updateMemberRole:Pr,getActiveMember:_r},r={...Or,...e?.roles};return{id:"organization",endpoints:{...kr(t,{orgOptions:e||{},roles:r,getSession:async n=>await x(n)}),hasPermission:c("/organization/has-permission",{method:"POST",requireHeaders:!0,body:Te.z.object({permission:Te.z.record(Te.z.string(),Te.z.array(Te.z.string()))}),use:[L]},async n=>{if(!n.context.session.session.activeOrganizationId)throw new At.APIError("BAD_REQUEST",{message:"No active organization"});let a=await P(n.context).findMemberByOrgId({userId:n.context.session.user.id,organizationId:n.context.session.session.activeOrganizationId||""});if(!a)throw new At.APIError("UNAUTHORIZED",{message:"You are not a member of this organization"});let d=r[a.role].authorize(n.body.permission);return d.error?n.json({error:d.error,success:!1},{status:403}):n.json({error:null,success:!0})})},schema:{session:{fields:{activeOrganizationId:{type:"string",required:!1}}},organization:{fields:{name:{type:"string",required:!0},slug:{type:"string",unique:!0},logo:{type:"string",required:!1},createdAt:{type:"date",required:!0},metadata:{type:"string",required:!1}}},member:{fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"}},userId:{type:"string",required:!0},email:{type:"string",required:!0},role:{type:"string",required:!0,defaultValue:"member"},createdAt:{type:"date",required:!0}}},invitation:{fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"}},email:{type:"string",required:!0},role:{type:"string",required:!1},status:{type:"string",required:!0,defaultValue:"pending"},expiresAt:{type:"date",required:!0},inviterId:{type:"string",references:{model:"user",field:"id"},required:!0}}}},$Infer:{Organization:{},Invitation:{},Member:{},ActiveOrganization:{}}}};var kt=Dt(require("uncrypto"),1);function Jo(e){return e.toString(2).padStart(8,"0")}function Zo(e){return[...e].map(t=>Jo(t)).join("")}function jr(e){return parseInt(Zo(e),2)}function Yo(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,o=new Uint8Array(Math.ceil(t/8));kt.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=jr(o);for(;n>=e;)kt.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=jr(o);return n}function F(e,t){let r="";for(let o=0;o<e;o++)r+=t[Yo(t.length)];return r}function V(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}var qe=require("zod");var Rt=require("@noble/ciphers/chacha"),Se=require("@noble/ciphers/utils"),vt=require("@noble/ciphers/webcrypto"),Et=require("oslo/crypto"),Ot=Dt(require("uncrypto"),1);var Nr=require("oslo/encoding");var Xo=require("@noble/hashes/scrypt"),en=require("uncrypto");async function je(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},n=await Ot.default.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),i=await Ot.default.subtle.sign(o.name,n,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(i)))}var de=async({key:e,data:t})=>{let r=await(0,Et.sha256)(new TextEncoder().encode(e)),o=(0,Se.utf8ToBytes)(t),n=(0,vt.managedNonce)(Rt.xchacha20poly1305)(new Uint8Array(r));return(0,Se.bytesToHex)(n.encrypt(o))},ce=async({key:e,data:t})=>{let r=await(0,Et.sha256)(new TextEncoder().encode(e)),o=(0,Se.hexToBytes)(t),n=(0,vt.managedNonce)(Rt.xchacha20poly1305)(new Uint8Array(r));return new TextDecoder().decode(n.decrypt(o))};var Z=require("zod");var Pe=require("better-call");var it="two_factor";var st="trust_device";var Ut=require("zod");var we=S({body:Ut.z.object({trustDevice:Ut.z.boolean().optional()})},async e=>{let t=await x(e);if(!t){let r=e.context.createAuthCookie(it),o=await e.getSignedCookie(r.name,e.context.secret);if(!o)throw new Pe.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let n=await e.context.internalAdapter.findUserById(o);if(!n)throw new Pe.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let i=await e.context.internalAdapter.createSession(o,e.request);if(!i)throw new Pe.APIError("INTERNAL_SERVER_ERROR",{message:"failed to create session"});return{valid:async()=>{if(await w(e,{session:i,user:n}),e.body.trustDevice){let a=e.context.createAuthCookie(st,{maxAge:2592e3}),s=await je(e.context.secret,`${n.id}!${i.id}`);await e.setSignedCookie(a.name,`${s}!${i.id}`,e.context.secret,a.attributes)}return e.json({session:i,user:n})},invalid:async()=>{throw new Pe.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:{id:i.id,userId:i.userId,expiresAt:i.expiresAt,user:n}}}return{valid:async()=>e.json({session:t,user:t.user}),invalid:async()=>{throw new Pe.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:t}});var _e=require("better-call");function tn(e){return Array.from({length:e?.amount??10}).fill(null).map(()=>F(e?.length??10,V("a-z","0-9"))).map(t=>`${t.slice(0,5)}-${t.slice(5)}`)}async function It(e,t){let r=e,o=t?.customBackupCodesGenerate?t.customBackupCodesGenerate():tn(),n=await de({data:JSON.stringify(o),key:r});return{backupCodes:o,encryptedBackupCodes:n}}async function rn(e,t){let r=await Fr(e.backupCodes,t);return r?r.includes(e.code):!1}async function Fr(e,t){let r=Buffer.from(await ce({key:t,data:e})).toString("utf-8"),o=JSON.parse(r),n=Z.z.array(Z.z.string()).safeParse(o);return n.success?n.data:null}var Vr=(e,t)=>({id:"backup_code",endpoints:{verifyBackupCode:c("/two-factor/verify-backup-code",{method:"POST",body:Z.z.object({code:Z.z.string(),disableSession:Z.z.boolean().optional()}),use:[we]},async r=>{let o=r.context.session.user,n=await r.context.adapter.findOne({model:t,where:[{field:"userId",value:o.id}]});if(!n)throw new _e.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});if(!rn({backupCodes:n.backupCodes,code:r.body.code},r.context.secret))throw new _e.APIError("BAD_REQUEST",{message:"Invalid backup code"});return r.body.disableSession||await w(r,{session:r.context.session,user:o}),r.json({user:o,session:r.context.session})}),generateBackupCodes:c("/two-factor/generate-backup-codes",{method:"POST",body:Z.z.object({password:Z.z.string()}),use:[A]},async r=>{let o=r.context.session.user;if(!o.twoFactorEnabled)throw new _e.APIError("BAD_REQUEST",{message:"Two factor isn't enabled"});await r.context.password.checkPassword(o.id,r);let n=await It(r.context.secret,e);return await r.context.adapter.update({model:t,update:{backupCodes:n.encryptedBackupCodes},where:[{field:"userId",value:r.context.session.user.id}]}),r.json({status:!0,backupCodes:n.backupCodes})}),viewBackupCodes:c("/view/backup-codes",{method:"GET",body:Z.z.object({password:Z.z.string()}),use:[A]},async r=>{let o=r.context.session.user,n=await r.context.adapter.findOne({model:t,where:[{field:"userId",value:o.id}]});if(!n)throw new _e.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});await r.context.password.checkPassword(o.id,r);let i=Fr(n.backupCodes,r.context.secret);if(!i)throw new _e.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});return r.json({status:!0,backupCodes:i})})}});var Ne=require("better-call"),qr=require("oslo/otp"),Tt=require("zod");var Mr=require("oslo"),$r=(e,t)=>{let r={...e,period:new Mr.TimeSpan(e?.period||3,"m")},o=new qr.TOTPController({digits:6,period:r.period}),n=c("/two-factor/send-otp",{method:"POST",use:[we]},async a=>{if(!e||!e.sendOTP)throw a.context.logger.error("send otp isn't configured. Please configure the send otp function on otp options."),new Ne.APIError("BAD_REQUEST",{message:"otp isn't configured"});let s=a.context.session.user,d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d)throw new Ne.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});let u=await o.generate(Buffer.from(d.secret));return await e.sendOTP(s,u),a.json({status:!0})}),i=c("/two-factor/verify-otp",{method:"POST",body:Tt.z.object({code:Tt.z.string()}),use:[we]},async a=>{let s=a.context.session.user;if(!s.twoFactorEnabled)throw new Ne.APIError("BAD_REQUEST",{message:"two factor isn't enabled"});let d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d)throw new Ne.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});return await o.generate(Buffer.from(d.secret))===a.body.code?a.context.valid():a.context.invalid()});return{id:"otp",endpoints:{send2FaOTP:n,verifyOTP:i}}};var ye=require("better-call"),Qr=require("oslo"),Ve=require("oslo/otp"),Fe=require("zod");var Wr=(e,t)=>{let r={...e,digits:6,period:new Qr.TimeSpan(e?.period||30,"s")},o=c("/totp/generate",{method:"POST",use:[A]},async a=>{if(!e)throw a.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new ye.APIError("BAD_REQUEST",{message:"totp isn't configured"});let s=a.context.session.user,d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d)throw new ye.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return{code:await new Ve.TOTPController(r).generate(Buffer.from(d.secret))}}),n=c("/two-factor/get-totp-uri",{method:"POST",use:[A],body:Fe.z.object({password:Fe.z.string()})},async a=>{if(!e)throw a.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new ye.APIError("BAD_REQUEST",{message:"totp isn't configured"});let s=a.context.session.user,d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d||!s.twoFactorEnabled)throw new ye.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return await a.context.password.checkPassword(s.id,a),{totpURI:(0,Ve.createTOTPKeyURI)(e?.issuer||"BetterAuth",s.email,Buffer.from(d.secret),r)}}),i=c("/two-factor/verify-totp",{method:"POST",body:Fe.z.object({code:Fe.z.string()}),use:[we]},async a=>{if(!e)throw a.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new ye.APIError("BAD_REQUEST",{message:"totp isn't configured"});let s=a.context.session.user,d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d)throw new ye.APIError("BAD_REQUEST",{message:"totp isn't enabled"});let u=new Ve.TOTPController(r),l=await ce({key:a.context.secret,data:d.secret}),m=Buffer.from(l);if(!await u.verify(a.body.code,m))return a.context.invalid();if(!s.twoFactorEnabled){let p=await a.context.internalAdapter.updateUser(s.id,{twoFactorEnabled:!0}),k=await a.context.internalAdapter.createSession(s.id,a.request);await w(a,{session:k,user:p})}return a.context.valid()});return{id:"totp",endpoints:{generateTOTP:o,viewTOTPURI:n,verifyTOTP:i}}};var on=require("better-call");async function St(e,t){let o=(await e.context.internalAdapter.findAccounts(t.userId))?.find(a=>a.providerId==="credential"),n=o?.password;return!o||!n?!1:await e.context.password.verify(n,t.password)}var Pt=require("better-call"),Hr=require("oslo/otp"),Gr=require("oslo");var nn=(e={redirect:!0,twoFactorPage:"/"})=>({id:"two-factor",$InferServerPlugin:{},atomListeners:[{matcher:t=>t.startsWith("/two-factor/"),signal:"$sessionSignal"}],pathMethods:{"/two-factor/disable":"POST","/two-factor/enable":"POST","/two-factor/send-otp":"POST","/two-factor/generate-backup-codes":"POST"},fetchPlugins:[{id:"two-factor",name:"two-factor",hooks:{async onSuccess(t){t.data?.twoFactorRedirect&&(e.redirect||e.twoFactorPage)&&typeof window<"u"&&(window.location.href=e.twoFactorPage)}}}]});var sn=e=>{let t={twoFactorTable:e?.twoFactorTable||"twoFactor"},r=Wr({issuer:e?.issuer||"better-auth",...e?.totpOptions},t.twoFactorTable),o=Vr({...e?.backupCodeOptions},t.twoFactorTable),n=$r({...e?.otpOptions},t.twoFactorTable);return{id:"two-factor",endpoints:{...r.endpoints,...n.endpoints,...o.endpoints,enableTwoFactor:c("/two-factor/enable",{method:"POST",body:qe.z.object({password:qe.z.string().min(8)}),use:[A]},async i=>{let a=i.context.session.user,{password:s}=i.body;if(!await St(i,{password:s,userId:a.id}))throw new Pt.APIError("BAD_REQUEST",{message:"Invalid password"});let u=F(16,V("a-z","0-9","-")),l=await de({key:i.context.secret,data:u}),m=await It(i.context.secret,e?.backupCodeOptions);if(e?.skipVerificationOnEnable){let p=await i.context.internalAdapter.updateUser(a.id,{twoFactorEnabled:!0}),k=await i.context.internalAdapter.createSession(p.id,i.request);await w(i,{session:k,user:a})}await i.context.adapter.deleteMany({model:t.twoFactorTable,where:[{field:"userId",value:a.id}]}),await i.context.adapter.create({model:t.twoFactorTable,data:{id:i.context.uuid(),secret:l,backupCodes:m.encryptedBackupCodes,userId:a.id}});let f=(0,Hr.createTOTPKeyURI)(e?.issuer||"BetterAuth",a.email,Buffer.from(u),{digits:e?.totpOptions?.digits||6,period:new Gr.TimeSpan(e?.totpOptions?.period||30,"s")});return i.json({totpURI:f,backupCodes:m.backupCodes})}),disableTwoFactor:c("/two-factor/disable",{method:"POST",body:qe.z.object({password:qe.z.string().min(8)}),use:[A]},async i=>{let a=i.context.session.user,{password:s}=i.body;if(!await St(i,{password:s,userId:a.id}))throw new Pt.APIError("BAD_REQUEST",{message:"Invalid password"});return await i.context.internalAdapter.updateUser(a.id,{twoFactorEnabled:!1}),await i.context.adapter.delete({model:t.twoFactorTable,where:[{field:"userId",value:a.id}]}),i.json({status:!0})})},options:e,hooks:{after:[{matcher(i){return i.path==="/sign-in/email"||i.path==="/sign-in/username"},handler:S(async i=>{let a=i.context.returned;if(a?.status!==200)return;let s=await a.clone().json();if(!s.user.twoFactorEnabled)return;let d=i.context.createAuthCookie(st,{maxAge:30*24*60*60}),u=await i.getSignedCookie(d.name,i.context.secret);if(u){let[f,p]=u.split("!"),k=await je(i.context.secret,`${s.user.id}!${p}`);if(f===k){let b=await je(i.context.secret,`${s.user.id}!${s.session.id}`);await i.setSignedCookie(d.name,`${b}!${s.session.id}`,i.context.secret,d.attributes);return}}re(i),await i.context.internalAdapter.deleteSession(s.session.id);let l=i.context.createAuthCookie(it,{maxAge:60*10});return await i.setSignedCookie(l.name,s.user.id,i.context.secret,l.attributes),{response:new Response(JSON.stringify({twoFactorRedirect:!0}),{headers:i.responseHeader})}})}]},schema:{user:{fields:{twoFactorEnabled:{type:"boolean",required:!1,defaultValue:!1,input:!1}}},twoFactor:{tableName:t.twoFactorTable,fields:{secret:{type:"string",required:!0,returned:!1},backupCodes:{type:"string",required:!0,returned:!1},userId:{type:"string",required:!0,returned:!1,references:{model:"user",field:"id"}}}}},rateLimit:[{pathMatcher(i){return i.startsWith("/two-factor/")},window:10,max:3}]}};var ue=require("@simplewebauthn/server"),Q=require("better-call");var Y=require("zod");var Ce=require("@simplewebauthn/browser");var dn=require("@better-fetch/fetch");var du=require("nanostores");var Jc=require("@better-fetch/fetch");var an=require("nanostores");var Yc=require("@better-fetch/fetch"),at=require("nanostores"),_t=(e,t,r,o)=>{let n=(0,at.atom)({data:null,error:null,isPending:!0,isRefetching:!1}),i=()=>{let s=typeof o=="function"?o({data:n.get().data,error:n.get().error,isPending:n.get().isPending}):o;return r(t,{...s,onSuccess:async d=>{n.set({data:d.data,error:null,isPending:!1,isRefetching:!1}),await s?.onSuccess?.(d)},async onError(d){n.set({error:d.error,data:null,isPending:!1,isRefetching:!1}),await s?.onError?.(d)},async onRequest(d){let u=n.get();n.set({isPending:u.data===null,data:u.data,error:null,isRefetching:!0}),await s?.onRequest?.(d)}})};e=Array.isArray(e)?e:[e];let a=!1;for(let s of e)s.subscribe(()=>{a?i():(0,at.onMount)(n,()=>(i(),a=!0,()=>{n.off(),s.off()}))});return n};var Kr=require("nanostores"),Jr=(e,{$listPasskeys:t})=>({signIn:{passkey:async(n,i)=>{let a=await e("/passkey/generate-authenticate-options",{method:"POST",body:{email:n?.email}});if(!a.data)return a;try{let s=await(0,Ce.startAuthentication)(a.data,n?.autoFill||!1),d=await e("/passkey/verify-authentication",{body:{response:s},...n?.fetchOptions,...i,method:"POST"});if(!d.data)return d}catch{return{data:null,error:{message:"auth cancelled",status:400,statusText:"BAD_REQUEST"}}}}},passkey:{addPasskey:async(n,i)=>{let a=await e("/passkey/generate-register-options",{method:"GET"});if(!a.data)return a;try{let s=await(0,Ce.startRegistration)(a.data),d=await e("/passkey/verify-registration",{...n?.fetchOptions,...i,body:{response:s,name:n?.name},method:"POST"});if(!d.data)return d;t.set(Math.random())}catch(s){return s instanceof Ce.WebAuthnError?s.code==="ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED"?{data:null,error:{message:"previously registered",status:400,statusText:"BAD_REQUEST"}}:s.code==="ERROR_CEREMONY_ABORTED"?{data:null,error:{message:"registration cancelled",status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:s.message,status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:s instanceof Error?s.message:"unknown error",status:500,statusText:"INTERNAL_SERVER_ERROR"}}}}},$Infer:{}}),cn=()=>{let e=(0,Kr.atom)();return{id:"passkey",$InferServerPlugin:{},getActions:t=>Jr(t,{$listPasskeys:e}),getAtoms(t){return{listPasskeys:_t(e,"/passkey/list-user-passkeys",t,{method:"GET"}),$listPasskeys:e}},pathMethods:{"/passkey/register":"POST","/passkey/authenticate":"POST"},atomListeners:[{matcher(t){return t==="/passkey/verify-registration"||t==="/passkey/delete-passkey"},signal:"_listPasskeys"}]}};var un=e=>{let t=G.BETTER_AUTH_URL,r=e?.rpID||t?.replace("http://","").replace("https://","").split(":")[0]||"localhost";if(!r)throw new H("passkey rpID not found. Please provide a rpID in the options or set the BETTER_AUTH_URL environment variable.");let o={origin:null,...e,rpID:r,advanced:{webAuthnChallengeCookie:"better-auth-passkey",...e?.advanced}},n=new Date(Date.now()+1e3*60*5),i=new Date,a=Math.floor((n.getTime()-i.getTime())/1e3);return{id:"passkey",endpoints:{generatePasskeyRegistrationOptions:c("/passkey/generate-register-options",{method:"GET",use:[A],metadata:{client:!1}},async s=>{let d=s.context.session,u=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}),l=new Uint8Array(Buffer.from(F(32,V("a-z","0-9")))),m;m=await(0,ue.generateRegistrationOptions)({rpName:o.rpName||s.context.appName,rpID:o.rpID,userID:l,userName:d.user.email||d.user.id,attestationType:"none",excludeCredentials:u.map(p=>({id:p.id,transports:p.transports?.split(",")})),authenticatorSelection:{residentKey:"preferred",userVerification:"preferred",authenticatorAttachment:"platform"}});let f=z();return await s.setSignedCookie(o.advanced.webAuthnChallengeCookie,f,s.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:a}),await s.context.internalAdapter.createVerificationValue({identifier:f,value:JSON.stringify({expectedChallenge:m.challenge,userData:{id:d.user.id}}),expiresAt:n}),s.json(m,{status:200})}),generatePasskeyAuthenticationOptions:c("/passkey/generate-authenticate-options",{method:"POST",body:Y.z.object({email:Y.z.string().optional()}).optional()},async s=>{let d=await x(s),u=[];d&&(u=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}));let l=await(0,ue.generateAuthenticationOptions)({rpID:o.rpID,userVerification:"preferred",...u.length?{allowCredentials:u.map(p=>({id:p.id,transports:p.transports?.split(",")}))}:{}}),m={expectedChallenge:l.challenge,userData:{id:d?.user.id||""}},f=z();return await s.setSignedCookie(o.advanced.webAuthnChallengeCookie,f,s.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:a}),await s.context.internalAdapter.createVerificationValue({identifier:f,value:JSON.stringify(m),expiresAt:n}),s.json(l,{status:200})}),verifyPasskeyRegistration:c("/passkey/verify-registration",{method:"POST",body:Y.z.object({response:Y.z.any(),name:Y.z.string().optional()}),use:[A]},async s=>{let d=e?.origin||s.headers?.get("origin")||"";if(!d)return s.json(null,{status:400});let u=s.body.response,l=await s.getSignedCookie(o.advanced.webAuthnChallengeCookie,s.context.secret);if(!l)throw new Q.APIError("BAD_REQUEST",{message:"Challenge not found"});let m=await s.context.internalAdapter.findVerificationValue(l);if(!m)return s.json(null,{status:400});let{expectedChallenge:f,userData:p}=JSON.parse(m.value);if(p.id!==s.context.session.user.id)throw new Q.APIError("UNAUTHORIZED",{message:"You are not authorized to register this passkey"});try{let k=await(0,ue.verifyRegistrationResponse)({response:u,expectedChallenge:f,expectedOrigin:d,expectedRPID:e?.rpID}),{verified:b,registrationInfo:h}=k;if(!b||!h)return s.json(null,{status:400});let{credentialID:_,credentialPublicKey:Ae,counter:W,credentialDeviceType:We,credentialBackedUp:ke}=h,pe=Buffer.from(Ae).toString("base64"),lt=z(),ro={name:s.body.name,userId:p.id,webauthnUserID:lt,id:_,publicKey:pe,counter:W,deviceType:We,transports:u.response.transports.join(","),backedUp:ke,createdAt:new Date},oo=await s.context.adapter.create({model:"passkey",data:ro});return s.json(oo,{status:200})}catch(k){throw console.log(k),new Q.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to verify registration"})}}),verifyPasskeyAuthentication:c("/passkey/verify-authentication",{method:"POST",body:Y.z.object({response:Y.z.any()})},async s=>{let d=e?.origin||s.headers?.get("origin")||"";if(!d)throw new Q.APIError("BAD_REQUEST",{message:"origin missing"});let u=s.body.response,l=await s.getSignedCookie(o.advanced.webAuthnChallengeCookie,s.context.secret);if(!l)throw new Q.APIError("BAD_REQUEST",{message:"Challenge not found"});let m=await s.context.internalAdapter.findVerificationValue(l);if(!m)throw new Q.APIError("BAD_REQUEST",{message:"Challenge not found"});let{expectedChallenge:f}=JSON.parse(m.value),p=await s.context.adapter.findOne({model:"passkey",where:[{field:"id",value:u.id}]});if(!p)throw new Q.APIError("UNAUTHORIZED",{message:"Passkey not found"});try{let k=await(0,ue.verifyAuthenticationResponse)({response:u,expectedChallenge:f,expectedOrigin:d,expectedRPID:o.rpID,authenticator:{credentialID:p.id,credentialPublicKey:new Uint8Array(Buffer.from(p.publicKey,"base64")),counter:p.counter,transports:p.transports?.split(",")}}),{verified:b}=k;if(!b)throw new Q.APIError("UNAUTHORIZED",{message:"Authentication failed"});await s.context.adapter.update({model:"passkey",where:[{field:"id",value:p.id}],update:{counter:k.authenticationInfo.newCounter}});let h=await s.context.internalAdapter.createSession(p.userId,s.request);if(!h)throw new Q.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});let _=await s.context.internalAdapter.findUserById(p.userId);if(!_)throw new Q.APIError("INTERNAL_SERVER_ERROR",{message:"User not found"});return await w(s,{session:h,user:_}),s.json({session:h},{status:200})}catch(k){throw s.context.logger.error(k),new Q.APIError("BAD_REQUEST",{message:"Failed to verify authentication"})}}),listPasskeys:c("/passkey/list-user-passkeys",{method:"GET",use:[A]},async s=>{let d=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:s.context.session.user.id}]});return s.json(d,{status:200})}),deletePasskey:c("/passkey/delete-passkey",{method:"POST",body:Y.z.object({id:Y.z.string()}),use:[A]},async s=>(await s.context.adapter.delete({model:"passkey",where:[{field:"id",value:s.body.id}]}),s.json(null,{status:200})))},schema:{passkey:{fields:{name:{type:"string",required:!1},publicKey:{type:"string",required:!0},userId:{type:"string",references:{model:"user",field:"id"},required:!0},webauthnUserID:{type:"string",required:!0},counter:{type:"number",required:!0},deviceType:{type:"string",required:!0},backedUp:{type:"boolean",required:!0},transports:{type:"string",required:!1},createdAt:{type:"date",defaultValue:new Date,required:!1}}}}}};var Me=require("zod");var $e=require("better-call"),Ct=()=>({id:"username",endpoints:{signInUsername:c("/sign-in/username",{method:"POST",body:Me.z.object({username:Me.z.string(),password:Me.z.string(),dontRememberMe:Me.z.boolean().optional()})},async e=>{let t=await e.context.adapter.findOne({model:e.context.tables.user.tableName,where:[{field:"username",value:e.body.username}]});if(!t)throw await e.context.password.hash(e.body.password),e.context.logger.error("User not found",{username:Ct}),new $e.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let r=await e.context.adapter.findOne({model:e.context.tables.account.tableName,where:[{field:e.context.tables.account.fields.userId.fieldName||"userId",value:t.id},{field:e.context.tables.account.fields.providerId.fieldName||"providerId",value:"credential"}]});if(!r)throw new $e.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let o=r?.password;if(!o)throw e.context.logger.error("Password not found",{username:Ct}),new $e.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(o,e.body.password))throw e.context.logger.error("Invalid password"),new $e.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let i=await e.context.internalAdapter.createSession(t.id,e.request);return i?(await e.setSignedCookie(e.context.authCookies.sessionToken.name,i.id,e.context.secret,e.body.dontRememberMe?{...e.context.authCookies.sessionToken.options,maxAge:void 0}:e.context.authCookies.sessionToken.options),e.json({user:t,session:i})):e.json(null,{status:500,body:{message:"Failed to create session",status:500}})})},schema:{user:{fields:{username:{type:"string",required:!1,unique:!0,returned:!0}}}}});var Zr=require("better-call"),ln=()=>({id:"bearer",hooks:{before:[{matcher(e){return!!(e.request?.headers.get("authorization")||e.headers?.get("authorization"))},handler:async e=>{let t=e.request?.headers.get("authorization")?.replace("Bearer ","")||e.headers?.get("authorization")?.replace("Bearer ","");if(!t)return;let r="";return t.includes(".")?r=t:r=await(0,Zr.serializeSigned)("",t,e.context.secret),e.request&&e.request.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${r.replace("=","")}`),e.headers&&e.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${r.replace("=","")}`),{context:e}}}]}});var be=require("zod");var zt=require("better-call");var pn=e=>({id:"magic-link",endpoints:{signInMagicLink:c("/sign-in/magic-link",{method:"POST",requireHeaders:!0,body:be.z.object({email:be.z.string().email(),callbackURL:be.z.string().optional()})},async t=>{let{email:r}=t.body;if(e.disableSignUp&&!await t.context.internalAdapter.findUserByEmail(r))throw new zt.APIError("BAD_REQUEST",{message:"User not found"});let o=F(32,V("a-z","A-Z"));await t.context.internalAdapter.createVerificationValue({identifier:o,value:r,expiresAt:new Date(Date.now()+(e.expiresIn||60*5)*1e3)});let n=`${t.context.baseURL}/magic-link/verify?token=${o}&callbackURL=${t.body.callbackURL||"/"}`;try{await e.sendMagicLink({email:r,url:n,token:o})}catch(i){throw t.context.logger.error("Failed to send magic link",i),new zt.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to send magic link"})}return t.json({status:!0})}),magicLinkVerify:c("/magic-link/verify",{method:"GET",query:be.z.object({token:be.z.string(),callbackURL:be.z.string().optional()}),requireHeaders:!0},async t=>{let{token:r,callbackURL:o}=t.query,n=o?.startsWith("http")?o:o?`${t.context.options.baseURL}${o}`:t.context.options.baseURL,i=await t.context.internalAdapter.findVerificationValue(r);if(!i)throw t.redirect(`${n}?error=INVALID_TOKEN`);if(i.expiresAt<new Date)throw await t.context.internalAdapter.deleteVerificationValue(i.id),t.redirect(`${n}?error=EXPIRED_TOKEN`);await t.context.internalAdapter.deleteVerificationValue(i.id);let a=i.value,s=await t.context.internalAdapter.findUserByEmail(a),d=s?.user.id||"";if(!s){if(e.disableSignUp)throw t.redirect(`${n}?error=USER_NOT_FOUND`);if(d=(await t.context.internalAdapter.createUser({email:a,emailVerified:!0,name:a})).id,!d)throw t.redirect(`${n}?error=USER_NOT_CREATED`)}let u=await t.context.internalAdapter.createSession(d,t.headers);if(!u)throw t.redirect(`${n}?error=SESSION_NOT_CREATED`);if(await w(t,{session:u,user:s?.user}),!o)return t.json({status:!0});throw t.redirect(o)})},rateLimit:[{pathMatcher(t){return t.startsWith("/sign-in/magic-link")||t.startsWith("/magic-link/verify")},window:e.rateLimit?.window||60,max:e.rateLimit?.max||5}]});var le=require("zod");var X=require("better-call");function mn(e){return F(e,V("0-9"))}var fn=e=>{let t={phoneNumber:"phoneNumber",phoneNumberVerified:"phoneNumberVerified",code:"code",createdAt:"createdAt",expiresIn:e?.expiresIn||300,otpLength:e?.otpLength||6};return{id:"phone-number",endpoints:{sendPhoneNumberOTP:c("/phone-number/send-otp",{method:"POST",body:le.z.object({phoneNumber:le.z.string()})},async r=>{if(!e?.sendOTP)throw y.warn("sendOTP not implemented"),new X.APIError("NOT_IMPLEMENTED",{message:"sendOTP not implemented"});let o=mn(t.otpLength);return await r.context.internalAdapter.createVerificationValue({value:o,identifier:r.body.phoneNumber,expiresAt:C(t.expiresIn,"sec")}),await e.sendOTP(r.body.phoneNumber,o),r.json({code:o},{body:{message:"Code sent"}})}),verifyPhoneNumber:c("/phone-number/verify",{method:"POST",body:le.z.object({phoneNumber:le.z.string(),code:le.z.string(),disableSession:le.z.boolean().optional(),updatePhoneNumber:le.z.boolean().optional()})},async r=>{let o=await r.context.internalAdapter.findVerificationValue(r.body.phoneNumber);if(!o||o.expiresAt<new Date)throw o&&o.expiresAt<new Date?(await r.context.internalAdapter.deleteVerificationValue(o.id),new X.APIError("BAD_REQUEST",{message:"OTP expired"})):new X.APIError("BAD_REQUEST",{message:"OTP not found"});if(o.value!==r.body.code)throw new X.APIError("BAD_REQUEST",{message:"Invalid OTP"});if(await r.context.internalAdapter.deleteVerificationValue(o.id),r.body.updatePhoneNumber){let i=await x(r);if(!i)throw new X.APIError("UNAUTHORIZED",{message:"Session not found"});let a=await r.context.internalAdapter.updateUser(i.user.id,{[t.phoneNumber]:r.body.phoneNumber,[t.phoneNumberVerified]:!0});return r.json({user:a,session:i.session})}let n=await r.context.adapter.findOne({model:r.context.tables.user.tableName,where:[{value:r.body.phoneNumber,field:t.phoneNumber}]});if(n)n=await r.context.internalAdapter.updateUser(n.id,{[t.phoneNumberVerified]:!0});else if(e?.signUpOnVerification){if(n=await r.context.internalAdapter.createUser({email:e.signUpOnVerification.getTempEmail(r.body.phoneNumber),name:e.signUpOnVerification.getTempName?e.signUpOnVerification.getTempName(r.body.phoneNumber):r.body.phoneNumber,[t.phoneNumber]:r.body.phoneNumber,[t.phoneNumberVerified]:!0}),!n)throw new X.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"})}else throw new X.APIError("BAD_REQUEST",{message:"Phone number not found"});if(!n)throw new X.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to update user"});if(!r.body.disableSession){let i=await r.context.internalAdapter.createSession(n.id,r.request);if(!i)throw new X.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await w(r,{session:i,user:n}),r.json({user:n,session:i})}return r.json({user:n,session:null})})},schema:{user:{fields:{phoneNumber:{type:"string",required:!1,unique:!0,returned:!0},phoneNumberVerified:{type:"boolean",required:!1,returned:!0,input:!1}}}}}};var dt=require("zod");var gn=e=>({id:"anonymous",endpoints:{signInAnonymous:c("/sign-in/anonymous",{method:"POST"},async t=>{let{emailDomainName:r=Je(t.context.baseURL)}=e||{},o=z(),n=`temp-${o}@${r}`,i=await t.context.internalAdapter.createUser({id:o,email:n,emailVerified:!1,isAnonymous:!0,name:"Anonymous",createdAt:new Date,updatedAt:new Date});if(!i)return t.json(null,{status:500,body:{message:"Failed to create user",status:500}});let a=await t.context.internalAdapter.createSession(i.id,t.request);return a?(await w(t,{session:a,user:i}),t.json({user:i,session:a})):t.json(null,{status:400,body:{message:"Could not create session"}})}),linkAccount:c("/anonymous/link-account",{method:"POST",body:dt.z.object({email:dt.z.string().email().optional(),password:dt.z.string().min(6)}),use:[A]},async t=>{let r=t.context.session.user.id,{email:o,password:n}=t.body,i=null;if(o&&n&&(i=await t.context.internalAdapter.updateUser(r,{email:o,isAnonymous:!1})),!i)return t.json(null,{status:500,body:{message:"Failed to update user",status:500}});let a=await t.context.password.hash(n);if(!await t.context.internalAdapter.linkAccount({userId:i.id,providerId:"credential",password:a,accountId:i.id}))return t.json(null,{status:500,body:{message:"Failed to update account",status:500}});let d=await t.context.internalAdapter.createSession(i.id,t.request);return d?(await w(t,{session:d,user:i}),t.json({session:d,user:i})):t.json(null,{status:400,body:{message:"Could not create session"}})})},schema:{user:{fields:{isAnonymous:{type:"boolean",required:!1}}}}});var g=require("zod");var J=S(async e=>{let t=await x(e);if(!t?.session)throw new v.APIError("UNAUTHORIZED");let r=t.user;if(r.role!=="admin")throw new v.APIError("FORBIDDEN",{message:"Only admins can access this endpoint"});return{session:{user:r,session:t.session}}}),hn=e=>({id:"admin",init(t){return{options:{databaseHooks:{user:{create:{async before(r){if(e?.defaultRole!==!1)return{data:{role:e?.defaultRole??"user",...r}}}}},session:{create:{async before(r){let o=await t.internalAdapter.findUserById(r.userId);if(o.banned){if(o.banExpires&&o.banExpires<Date.now()){await t.internalAdapter.updateUser(r.userId,{banned:!1,banReason:null,banExpires:null});return}return!1}}}}}}}},hooks:{after:[{matcher(t){return t.path==="/list-sessions"},handler:S(async t=>{let r=t.context.returned;if(r){let n=(await r.json()).filter(a=>!a.impersonatedBy),i=new Response(JSON.stringify(n),{status:200,statusText:"OK",headers:r.headers});return t.json({response:i})}})}]},endpoints:{setRole:c("/admin/set-role",{method:"POST",body:g.z.object({userId:g.z.string(),role:g.z.string()}),use:[J]},async t=>{let r=await t.context.internalAdapter.updateUser(t.body.userId,{role:t.body.role});return t.json({user:r})}),createUser:c("/admin/create-user",{method:"POST",body:g.z.object({email:g.z.string(),password:g.z.string(),name:g.z.string(),role:g.z.string(),data:g.z.optional(g.z.record(g.z.any()))}),use:[J]},async t=>{if(await t.context.internalAdapter.findUserByEmail(t.body.email))throw new v.APIError("BAD_REQUEST",{message:"User already exists"});let o=await t.context.internalAdapter.createUser({email:t.body.email,name:t.body.name,role:t.body.role,...t.body.data});if(!o)throw new v.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"});let n=await t.context.password.hash(t.body.password);return await t.context.internalAdapter.linkAccount({accountId:o.id,providerId:"credential",password:n,userId:o.id}),t.json({user:o})}),listUsers:c("/admin/list-users",{method:"GET",use:[J],query:g.z.object({search:g.z.object({field:g.z.enum(["email","name"]),operator:g.z.enum(["contains","starts_with","ends_with"]).default("contains"),value:g.z.string()}).optional(),limit:g.z.string().or(g.z.number()).optional(),offset:g.z.string().or(g.z.number()).optional(),sortBy:g.z.string().optional(),sortDirection:g.z.enum(["asc","desc"]).optional(),filter:g.z.array(g.z.object({field:g.z.string(),value:g.z.string().or(g.z.number()).or(g.z.boolean()),operator:g.z.enum(["eq","ne","lt","lte","gt","gte"]),connector:g.z.enum(["AND","OR"]).optional()})).optional()})},async t=>{let r=[];t.query?.search&&r.push({field:t.query.search.field,operator:t.query.search.operator,value:t.query.search.value}),t.query?.filter&&r.push(...t.query.filter||[]);let o=await t.context.internalAdapter.listUsers(Number(t.query?.limit)||void 0,Number(t.query?.offset)||void 0,t.query?.sortBy?{field:t.query.sortBy,direction:t.query.sortDirection||"asc"}:void 0,r.length?r:void 0);return t.json({users:o})}),listUserSessions:c("/admin/list-user-sessions",{method:"POST",use:[J],body:g.z.object({userId:g.z.string()})},async t=>({sessions:await t.context.internalAdapter.listSessions(t.body.userId)})),unbanUser:c("/admin/unban-user",{method:"POST",body:g.z.object({userId:g.z.string()}),use:[J]},async t=>{let r=await t.context.internalAdapter.updateUser(t.body.userId,{banned:!1});return t.json({user:r})}),banUser:c("/admin/ban-user",{method:"POST",body:g.z.object({userId:g.z.string(),banReason:g.z.string().optional(),banExpiresIn:g.z.number().optional()}),use:[J]},async t=>{if(t.body.userId===t.context.session.user.id)throw new v.APIError("BAD_REQUEST",{message:"You cannot ban yourself"});let r=await t.context.internalAdapter.updateUser(t.body.userId,{banned:!0,banReason:t.body.banReason||e?.defaultBanReason||"No reason",banExpires:t.body.banExpiresIn?C(t.body.banExpiresIn,"sec"):e?.defaultBanExpiresIn?C(e.defaultBanExpiresIn,"sec"):void 0});return await t.context.internalAdapter.deleteSessions(t.body.userId),t.json({user:r})}),impersonateUser:c("/admin/impersonate-user",{method:"POST",body:g.z.object({userId:g.z.string()}),use:[J]},async t=>{let r=await t.context.internalAdapter.findUserById(t.body.userId);if(!r)throw new v.APIError("NOT_FOUND",{message:"User not found"});let o=await t.context.internalAdapter.createSession(r.id,void 0,!0,{impersonatedBy:t.context.session.user.id,expiresAt:e?.impersonationSessionDuration?C(e.impersonationSessionDuration,"sec"):C(60*60,"sec")});if(!o)throw new v.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await w(t,{session:o,user:r},!0),t.json({session:o,user:r})}),revokeUserSession:c("/admin/revoke-user-session",{method:"POST",body:g.z.object({sessionId:g.z.string()}),use:[J]},async t=>(await t.context.internalAdapter.deleteSession(t.body.sessionId),t.json({success:!0}))),revokeUserSessions:c("/admin/revoke-user-sessions",{method:"POST",body:g.z.object({userId:g.z.string()}),use:[J]},async t=>(await t.context.internalAdapter.deleteSessions(t.body.userId),t.json({success:!0}))),removeUser:c("/admin/remove-user",{method:"POST",body:g.z.object({userId:g.z.string()}),use:[J]},async t=>(await t.context.internalAdapter.deleteUser(t.body.userId),t.json({success:!0})))},schema:{user:{fields:{role:{type:"string",required:!1,input:!1},banned:{type:"boolean",defaultValue:!1,required:!1,input:!1},banReason:{type:"string",required:!1,input:!1},banExpires:{type:"date",required:!1,input:!1}}},session:{fields:{impersonatedBy:{type:"string",required:!1}}}}});var ee=require("zod"),ze=require("better-call");var ct=require("@better-fetch/fetch");var Yr=require("oslo/jwt");async function wn(e,t,r){if(t==="oidc"&&e.idToken){let n=(0,Yr.parseJWT)(e.idToken);if(n?.payload)return n.payload}return r?(await(0,ct.betterFetch)(r,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}})).data:null}var yn=e=>({id:"generic-oauth",endpoints:{signInWithOAuth2:c("/sign-in/oauth2",{method:"POST",query:ee.z.object({currentURL:ee.z.string().optional()}).optional(),body:ee.z.object({providerId:ee.z.string(),callbackURL:ee.z.string().optional()})},async t=>{let{providerId:r}=t.body,o=e.config.find(pe=>pe.providerId===r);if(!o)throw new ze.APIError("BAD_REQUEST",{message:`No config found for provider ${r}`});let{discoveryUrl:n,authorizationUrl:i,tokenUrl:a,clientId:s,clientSecret:d,scopes:u,redirectURI:l,responseType:m,pkce:f,prompt:p,accessType:k}=o,b=i,h=a;if(n){let pe=await(0,ct.betterFetch)(n,{onError(lt){y.error(lt.error,{discoveryUrl:n})}});pe.data&&(b=pe.data.authorization_endpoint,h=pe.data.token_endpoint)}if(!b||!h)throw new ze.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let _=t.query?.currentURL?new URL(t.query?.currentURL):null,Ae=t.body.callbackURL?.startsWith("http")?t.body.callbackURL:`${_?.origin}${t.body.callbackURL||""}`,{state:W,codeVerifier:We}=await Oe(t),ke=await U({id:r,options:{clientId:s,clientSecret:d,redirectURI:l},authorizationEndpoint:b,state:W,codeVerifier:f?We:void 0,scopes:u||[],redirectURI:`${t.context.baseURL}/oauth2/callback/${r}`});return m&&m!=="code"&&ke.searchParams.set("response_type",m),p&&ke.searchParams.set("prompt",p),k&&ke.searchParams.set("access_type",k),t.json({url:ke.toString(),redirect:!0})}),oAuth2Callback:c("/oauth2/callback/:providerId",{method:"GET",query:ee.z.object({code:ee.z.string().optional(),error:ee.z.string().optional(),state:ee.z.string()})},async t=>{if(t.query.error||!t.query.code)throw t.redirect(`${t.context.baseURL}?error=${t.query.error||"oAuth_code_missing"}`);let r=e.config.find(h=>h.providerId===t.params.providerId);if(!r)throw new ze.APIError("BAD_REQUEST",{message:`No config found for provider ${t.params.providerId}`});let o,n=await Ye(t),{callbackURL:i,codeVerifier:a,errorURL:s}=n,d=t.query.code,u=r.tokenUrl,l=r.userInfoUrl;if(r.discoveryUrl){let h=await(0,ct.betterFetch)(r.discoveryUrl,{method:"GET"});h.data&&(u=h.data.token_endpoint,l=h.data.userinfo_endpoint)}try{if(!u)throw new ze.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});o=await R({code:d,codeVerifier:a,redirectURI:`${t.context.baseURL}/oauth2/callback/${r.providerId}`,options:{clientId:r.clientId,clientSecret:r.clientSecret},tokenEndpoint:u})}catch(h){throw t.context.logger.error(h),t.redirect(`${s}?error=oauth_code_verification_failed`)}if(!o)throw new ze.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let m=r.getUserInfo?await r.getUserInfo(o):await wn(o,r.type||"oauth2",l),f=z(),p=m?tt.safeParse({...m,id:f}):null;if(!p?.success)throw t.redirect(`${s}?error=oauth_user_info_invalid`);let k=await t.context.internalAdapter.findUserByEmail(p.data.email,{includeAccounts:!0}).catch(h=>{throw y.error(`Better auth was unable to query your database.
85
+ Error: `,h),t.redirect(`${s}?error=internal_server_error`)}),b=k?.user.id||f;if(k){let h=k.accounts.find(W=>W.providerId===r.providerId),_=t.context.options.account?.accountLinking?.trustedProviders,Ae=_?_.includes(r.providerId):!0;if(!h&&(!p?.data.emailVerified||!Ae)){let W;try{W=new URL(s),W.searchParams.set("error","account_not_linked")}catch{throw t.redirect(`${s}?error=account_not_linked`)}throw t.redirect(W.toString())}if(h)await t.context.internalAdapter.updateAccount(h.id,{accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,expiresAt:o.accessTokenExpiresAt});else try{await t.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:p.data.id,id:`${r.providerId}:${p.data.id}`,userId:k.user.id,accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,expiresAt:o.accessTokenExpiresAt})}catch(W){throw console.log(W),t.redirect(`${s}?error=failed_linking_account`)}}else try{await t.context.internalAdapter.createOAuthUser(p.data,{id:`${r.providerId}:${p.data.id}`,providerId:r.providerId,accountId:p.data.id,accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,expiresAt:o.accessTokenExpiresAt})}catch{let _=new URL(s);throw _.searchParams.set("error","unable_to_create_user"),t.setHeader("Location",_.toString()),t.redirect(_.toString())}try{let h=await t.context.internalAdapter.createSession(b||f,t.request);if(!h)throw t.redirect(`${s}?error=unable_to_create_session`);await w(t,{session:h,user:p.data})}catch{throw t.redirect(`${s}?error=unable_to_create_session`)}throw t.redirect(i)})}});var Be=require("zod"),Xr={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0}}}},ml=Be.z.object({id:Be.z.string(),publicKey:Be.z.string(),privateKey:Be.z.string(),createdAt:Be.z.date()});var Bt=e=>({getAllKeys:async()=>await e.findMany({model:"jwks"}),getLatestKey:async()=>(await e.findMany({model:"jwks",sortBy:{field:"createdAt",direction:"desc"},limit:1}))[0],createJwk:async t=>await e.create({model:"jwks",data:{...t,createdAt:new Date}})});var ne=require("jose");var bn=e=>({id:"jwt",endpoints:{getJwks:c("/jwks",{method:"GET"},async t=>{let o=await Bt(t.context.adapter).getAllKeys();return t.json({keys:o.map(n=>({...JSON.parse(n.publicKey),kid:n.id}))})}),getToken:c("/token",{method:"GET",requireHeaders:!0,use:[A]},async t=>{let r=Bt(t.context.adapter),o=await r.getLatestKey(),n=!e?.jwks?.disablePrivateKeyEncryption;if(o===void 0){let{publicKey:u,privateKey:l}=await(0,ne.generateKeyPair)(e?.jwks?.keyPairConfig?.alg??"EdDSA",e?.jwks?.keyPairConfig??{crv:"Ed25519"}),m=await(0,ne.exportJWK)(u),f=await(0,ne.exportJWK)(l),p=JSON.stringify(f),k={id:crypto.randomUUID(),publicKey:JSON.stringify(m),privateKey:n?JSON.stringify(await de({key:t.context.options.secret,data:p})):p,createdAt:new Date};o=await r.createJwk(k)}let i=n?await ce({key:t.context.options.secret,data:JSON.parse(o.privateKey)}):o.privateKey,a=await(0,ne.importJWK)(JSON.parse(i)),s=e?.jwt?.definePayload?await e?.jwt.definePayload(t.context.session.user):t.context.session.user,d=await new ne.SignJWT({...s,...t.context.session.session.impersonatedBy?{impersonatedBy:t.context.session.session.impersonatedBy}:{}}).setProtectedHeader({alg:e?.jwks?.keyPairConfig?.alg??"EdDSA",kid:o.id}).setIssuedAt().setIssuer(e?.jwt?.issuer??t.context.options.baseURL).setAudience(e?.jwt?.audience??t.context.options.baseURL).setExpirationTime(e?.jwt?.expirationTime??"15m").setSubject(t.context.session.user.id).sign(a);return t.json({token:d})})},schema:Xr});var Qe=require("zod");var An=e=>{let t={maximumSessions:5,...e},r=o=>o.includes("_multi-");return{id:"multi-session",endpoints:{listDeviceSessions:c("/multi-session/list-device-sessions",{method:"GET",requireHeaders:!0},async o=>{let n=o.headers?.get("cookie");if(!n)return o.json([]);let i=Object.fromEntries(Ke(n)),a=(await Promise.all(Object.entries(i).filter(([u])=>r(u)).map(async([u])=>await o.getSignedCookie(u,o.context.secret)))).filter(u=>u!==void 0);if(!a.length)return o.json([]);let d=(await o.context.internalAdapter.findSessions(a)).filter(u=>u&&u.session.expiresAt>new Date).filter((u,l,m)=>l===m.findIndex(f=>f.user.id===u.user.id));return Object.entries(i).filter(([u])=>r(u)).forEach(([u,l])=>{d.some(m=>m.session.id===l)||o.setCookie(u,"",{...o.context.authCookies.sessionToken.options,maxAge:0})}),o.json(d)}),setActiveSession:c("/multi-session/set-active",{method:"POST",body:Qe.z.object({sessionId:Qe.z.string()}),requireHeaders:!0,use:[A]},async o=>{let n=o.body.sessionId,i=`${o.context.authCookies.sessionToken.name}_multi-${n}`;if(!await o.getSignedCookie(i,o.context.secret))throw new v.APIError("UNAUTHORIZED",{message:"Invalid session id"});let s=await o.context.internalAdapter.findSession(n);if(!s||s.session.expiresAt<new Date)throw o.setCookie(i,"",{...o.context.authCookies.sessionToken.options,maxAge:0}),new v.APIError("UNAUTHORIZED",{message:"Invalid session id"});return await o.setSignedCookie(o.context.authCookies.sessionToken.name,n,o.context.secret,o.context.authCookies.sessionToken.options),o.json(s)}),revokeDeviceSession:c("/multi-session/revoke",{method:"POST",body:Qe.z.object({sessionId:Qe.z.string()}),requireHeaders:!0,use:[A]},async o=>{let n=o.body.sessionId,i=`${o.context.authCookies.sessionToken.name}_multi-${n}`;if(!await o.getSignedCookie(i,o.context.secret))throw new v.APIError("UNAUTHORIZED",{message:"Invalid session id"});let s=await o.context.internalAdapter.findSession(n);return o.setCookie(i,"",{...o.context.authCookies.sessionToken.options,maxAge:0}),s?(await o.context.internalAdapter.deleteSession(n),o.json({success:!0})):o.json({success:!0})})},hooks:{after:[{matcher:()=>!0,handler:S(async o=>{if(!o.context.returned||!(o.context.returned instanceof Response))return;let n=o.context.returned.headers.get("set-cookie");if(!n)return;let i=Nt(n),a=o.context.authCookies.sessionToken,s=i.get(a.name)?.value;if(!s)return;let d=Ke(o.headers?.get("cookie")||""),u=s.split(".")[0],l=`${a.name}_multi-${u}`;if(i.get(l)||d.get(l)||Object.keys(Object.fromEntries(d)).filter(r).length+(n.includes("session_token")?1:0)>t.maximumSessions)return;await o.setSignedCookie(l,u,o.context.secret,a.options);let f=o.context.returned;return f.headers.append("Set-Cookie",o.responseHeader.get("set-cookie")),{response:f}})},{matcher:o=>o.path==="/sign-out",handler:S(async o=>{let n=o.headers?.get("cookie");if(!n)return;let i=Object.fromEntries(Ke(n));await Promise.all(Object.entries(i).map(async([s,d])=>{if(r(s)){o.setCookie(s,"",{maxAge:0});let u=s.split("_multi-")[1];await o.context.internalAdapter.deleteSession(u)}}));let a=o.context.returned;return a?.headers.append("Set-Cookie",o.responseHeader.get("set-cookie")),{response:a}})}]}}};var te=require("zod");var kn=e=>{let t={expireIn:300,otpLength:6,...e};return{id:"email-otp",endpoints:{sendVerificationOTP:c("/email-otp/send-verification-otp",{method:"POST",body:te.z.object({email:te.z.string(),type:te.z.enum(["email-verification","sign-in"])})},async r=>{if(!e?.sendVerificationOTP)throw y.error("send email verification is not implemented"),new v.APIError("BAD_REQUEST",{message:"send email verification is not implemented"});let o=r.body.email,n=F(t.otpLength,V("0-9"));return await r.context.internalAdapter.createVerificationValue({value:n,identifier:`${r.body.type}-otp-${o}`,expiresAt:C(t.expireIn,"sec")}),await e.sendVerificationOTP({email:o,otp:n,type:r.body.type}),r.json({success:!0})}),verifyEmailOTP:c("/email-otp/verify-email",{method:"POST",body:te.z.object({email:te.z.string(),otp:te.z.string()})},async r=>{let o=r.body.email,n=await r.context.internalAdapter.findVerificationValue(`email-verification-otp-${o}`);if(!n||n.expiresAt<new Date)throw n&&await r.context.internalAdapter.deleteVerificationValue(n.id),new v.APIError("BAD_REQUEST",{message:"Invalid OTP"});let i=r.body.otp;if(n.value!==i)throw new v.APIError("BAD_REQUEST",{message:"Invalid OTP"});await r.context.internalAdapter.deleteVerificationValue(n.id);let a=await r.context.internalAdapter.findUserByEmail(o);if(!a)throw new v.APIError("BAD_REQUEST",{message:"User not found"});let s=await r.context.internalAdapter.updateUser(a.user.id,{email:o,emailVerified:!0});return r.json({user:s})}),signInEmailOTP:c("/sign-in/email-otp",{method:"POST",body:te.z.object({email:te.z.string(),otp:te.z.string()})},async r=>{let o=r.body.email,n=await r.context.internalAdapter.findVerificationValue(`sign-in-otp-${o}`);if(!n||n.expiresAt<new Date)throw n&&await r.context.internalAdapter.deleteVerificationValue(n.id),new v.APIError("BAD_REQUEST",{message:"Invalid OTP"});let i=r.body.otp;if(n.value!==i)throw new v.APIError("BAD_REQUEST",{message:"Invalid OTP"});await r.context.internalAdapter.deleteVerificationValue(n.id);let a=await r.context.internalAdapter.findUserByEmail(o);if(!a){if(t.disableSignUp)throw new v.APIError("BAD_REQUEST",{message:"User not found"});let d=await r.context.internalAdapter.createUser({email:o,emailVerified:!0,name:o}),u=await r.context.internalAdapter.createSession(d.id,r.request);return await w(r,{session:u,user:d}),r.json({user:d,session:u})}let s=await r.context.internalAdapter.createSession(a.user.id,r.request);return await w(r,{session:s,user:a.user}),r.json({session:s,user:a})})},hooks:{after:[{matcher(r){return!!(r.path?.startsWith("/sign-up")&&t.sendVerificationOnSignUp)},async handler(r){let o=r.context.returned;if(o?.status!==200)return;let n=await o.clone().json();if(n.user.email&&n.user.emailVerified===!1){let i=F(t.otpLength,V("0-9"));await r.context.internalAdapter.createVerificationValue({value:i,identifier:`email-verification-otp-${n.user.email}`,expiresAt:C(t.expireIn,"sec")}),await e.sendVerificationOTP({email:n.user.email,otp:i,type:"email-verification"})}}}]}}};var Lt=require("zod");var to=require("@better-fetch/fetch");function eo(e){return e==="true"||e===!0}var On=e=>({id:"one-tap",endpoints:{oneTapCallback:c("/one-tap/callback",{method:"POST",body:Lt.z.object({idToken:Lt.z.string()})},async t=>{let{idToken:r}=t.body,{data:o,error:n}=await(0,to.betterFetch)("https://oauth2.googleapis.com/tokeninfo?id_token="+r);if(n)return t.json({error:"Invalid token"});let i=await t.context.internalAdapter.findUserByEmail(o.email);if(!i){if(e?.disableSignup)throw new v.APIError("BAD_GATEWAY",{message:"User not found"});let s=await t.context.internalAdapter.createOAuthUser({email:o.email,emailVerified:eo(o.email_verified),name:o.name,image:o.picture},{providerId:"google",accountId:o.sub});if(!s)throw new v.APIError("INTERNAL_SERVER_ERROR",{message:"Could not create user"});let d=await t.context.internalAdapter.createSession(s?.user.id,t.request);return await w(t,{user:s.user,session:d}),t.json({session:d,user:s})}let a=await t.context.internalAdapter.createSession(i.user.id,t.request);return await w(t,{user:i.user,session:a}),t.json({session:a,user:i})})}});var ut=require("zod");function Rn(){let e=G.VERCEL_URL,t=G.NETLIFY_URL,r=G.RENDER_URL,o=G.AWS_LAMBDA_FUNCTION_NAME,n=G.GOOGLE_CLOUD_FUNCTION_NAME,i=G.AZURE_FUNCTION_NAME;return e||t||r||o||n||i}var vn=e=>({id:"oauth-proxy",endpoints:{oAuthProxy:c("/oauth-proxy-callback",{method:"GET",query:ut.z.object({callbackURL:ut.z.string(),cookies:ut.z.string()})},async t=>{let r=t.query.cookies,o=await ce({key:t.context.secret,data:r});throw t.setHeader("set-cookie",o),t.redirect(t.query.callbackURL)})},hooks:{after:[{matcher(t){return t.path?.startsWith("/callback")},handler:S(async t=>{let r=t.context.returned;if(!r)return;let o=r.headers.get("location");if(o?.includes("/oauth-proxy-callback?callbackURL")){if(!o.startsWith("http")||new URL(o).origin===t.context.baseURL)return;let i=r.headers.get("set-cookie");if(!i)return;let a=await de({key:t.context.secret,data:i}),s=`${o}&cookies=${encodeURIComponent(a)}`;return r.headers.set("location",s),{response:r}}})}],before:[{matcher(t){return t.path?.startsWith("/sign-in/social")},async handler(t){let r=new URL(e?.currentURL||t.request?.url||Rn()||t.context.baseURL);return t.body.callbackURL=`${r.origin}${t.context.options.basePath||"/api/auth"}/oauth-proxy-callback?callbackURL=${encodeURIComponent(t.body.callbackURL||t.context.baseURL)}`,{context:t}}}]}});0&&(module.exports={HIDE_METADATA,admin,adminMiddleware,anonymous,bearer,createAuthEndpoint,createAuthMiddleware,emailOTP,genericOAuth,getPasskeyActions,jwt,magicLink,multiSession,oAuthProxy,oneTap,optionsMiddleware,organization,passkey,passkeyClient,phoneNumber,twoFactor,twoFactorClient,username});