better-auth 1.0.9-beta.2 → 1.0.9-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/drizzle.d.cts +1 -1
- package/dist/adapters/drizzle.d.ts +1 -1
- package/dist/adapters/kysely.d.cts +1 -1
- package/dist/adapters/kysely.d.ts +1 -1
- package/dist/adapters/memory.d.cts +1 -1
- package/dist/adapters/memory.d.ts +1 -1
- package/dist/adapters/mongodb.d.cts +1 -1
- package/dist/adapters/mongodb.d.ts +1 -1
- package/dist/adapters/prisma.d.cts +1 -1
- package/dist/adapters/prisma.d.ts +1 -1
- package/dist/api.cjs +4 -4
- package/dist/api.d.cts +1 -1
- package/dist/api.d.ts +1 -1
- package/dist/api.js +4 -4
- package/dist/{auth-XMAxn5Ae.d.cts → auth-CRbxCgiW.d.cts} +80 -0
- package/dist/{auth-DFawWk0e.d.ts → auth-CnCuVMLa.d.ts} +80 -0
- package/dist/client/plugins.d.cts +3 -3
- package/dist/client/plugins.d.ts +3 -3
- package/dist/client.d.cts +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/cookies.cjs +4 -4
- package/dist/cookies.d.cts +1 -1
- package/dist/cookies.d.ts +1 -1
- package/dist/cookies.js +4 -4
- package/dist/db.d.cts +2 -2
- package/dist/db.d.ts +2 -2
- package/dist/{index-C7crAQ7s.d.cts → index-BAg8-2P7.d.cts} +1 -1
- package/dist/{index-CWprSsao.d.ts → index-tjkytDIw.d.ts} +1 -1
- package/dist/index.cjs +4 -4
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +3 -3
- package/dist/next-js.cjs +1 -1
- package/dist/next-js.d.cts +1 -1
- package/dist/next-js.d.ts +1 -1
- package/dist/next-js.js +1 -1
- package/dist/node.d.cts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/oauth2.d.cts +2 -2
- package/dist/oauth2.d.ts +2 -2
- package/dist/plugins.cjs +2 -2
- package/dist/plugins.d.cts +3 -3
- package/dist/plugins.d.ts +3 -3
- package/dist/plugins.js +4 -4
- package/dist/react.d.cts +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/solid-start.d.cts +1 -1
- package/dist/solid-start.d.ts +1 -1
- package/dist/solid.d.cts +1 -1
- package/dist/solid.d.ts +1 -1
- package/dist/{state-BsON3MFE.d.ts → state-CwZsNu9d.d.ts} +1 -1
- package/dist/{state-BkCnjHc0.d.cts → state-DLdB9N6W.d.cts} +1 -1
- package/dist/svelte-kit.d.cts +1 -1
- package/dist/svelte-kit.d.ts +1 -1
- package/dist/svelte.d.cts +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/types.d.cts +2 -2
- package/dist/types.d.ts +2 -2
- package/dist/vue.d.cts +1 -1
- package/dist/vue.d.ts +1 -1
- package/package.json +1 -1
package/dist/plugins.cjs
CHANGED
|
@@ -79,8 +79,8 @@
|
|
|
79
79
|
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
80
80
|
</div>
|
|
81
81
|
</body>
|
|
82
|
-
</html>`,pi=c("/error",{method:"GET",metadata:{...we,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string"}}}}}}}},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(wr(t),{headers:{"Content-Type":"text/html"}})});var ui=require("consola"),Io=["info","success","warn","error","debug"];function Cr(e,t){return Io.indexOf(t)<=Io.indexOf(e)}var br=(0,ui.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),li=e=>{let t=e?.disabled!==!0,o=e?.level??"error",i=(r,n,a=[])=>{if(!(!t||!Cr(o,r))){if(!e||typeof e.log!="function"){br[r]("",n,...a);return}e.log(r==="success"?"info":r,n,a)}};return Object.fromEntries(Io.map(r=>[r,(...[n,...a])=>i(r,n,a)]))},J=li();var C=require("better-call");function Uo(e,t){let o=t.plugins?.reduce((s,d)=>({...s,...d.endpoints}),{}),i=t.plugins?.map(s=>s.middlewares?.map(d=>{let A=async K=>d.middleware({...K,context:{...e,...K.context}});return A.path=d.path,A.options=d.middleware.options,A.headers=d.middleware.headers,{path:d.path,middleware:A}})).filter(s=>s!==void 0).flat()||[],n={...{signInSocial:gi,callbackOAuth:fi,getSession:To(),signOut:hi,signUpEmail:Ki(),signInEmail:mi,forgetPassword:yi,resetPassword:Ci,verifyEmail:Ai,sendVerificationEmail:di,changeEmail:Oi,changePassword:vi,setPassword:ki,updateUser:bi(),deleteUser:Ti,forgetPasswordCallback:wi,listSessions:ti(),revokeSession:ri,revokeSessions:ni,revokeOtherSessions:si,linkSocialAccount:Ui,listUserAccounts:Ii},...o,ok:ii,error:pi},a={};for(let[s,d]of Object.entries(n))a[s]=async(A={})=>{d.headers=new Headers;let K={setHeader(f,g){d.headers.set(f,g)},setCookie(f,g,b){(0,$.setCookie)(d.headers,f,g,b)},getCookie(f,g){let T=A.headers?.get("cookie");return(0,$.getCookie)(T||"",f,g)},getSignedCookie(f,g,b){let T=A.headers;return T?(0,$.getSignedCookie)(T,g,f,b):null},async setSignedCookie(f,g,b,T){await(0,$.setSignedCookie)(d.headers,f,g,b,T)},redirect(f){return d.headers.set("Location",f),new $.APIError("FOUND")},responseHeader:d.headers},u=await e,p={...K,...A,path:d.path,context:{...u,...A.context,endpoint:d}};u.session=null;let l=t.plugins||[];for(let f of l){let g=f.hooks?.before??[];for(let b of g){if(!b.matcher(p))continue;let T=await b.handler(p);if(T&&"context"in T){p={...p,...T.context};continue}if(T)return T}}let h;try{h=await d(p)}catch(f){if(f instanceof $.APIError){let g=t.plugins?.map(b=>{if(b.hooks?.after)return b.hooks.after}).filter(b=>b!==void 0).flat();if(!g?.length)throw f.headers=d.headers,f;p.context.returned=f,p.context.returned.headers=d.headers;for(let b of g||[])if(b.matcher(p))try{let N=await b.handler(p);N&&"response"in N&&(p.context.returned=N.response)}catch(N){if(N instanceof $.APIError){p.context.returned=N;continue}throw N}if(p.context.returned instanceof $.APIError)throw p.context.returned.headers=d.headers,p.context.returned;return p.context.returned}throw f}p.context.returned=h,p.responseHeader=d.headers;for(let f of t.plugins||[])if(f.hooks?.after){for(let g of f.hooks.after)if(g.matcher(p))try{let T=await g.handler(p);T&&(p.context.returned=T)}catch(T){if(T instanceof $.APIError){p.context.returned=T;continue}throw T}}let k=p.context.returned;return k instanceof Response&&d.headers.forEach((f,g)=>{g==="set-cookie"?k.headers.append(g,f):k.headers.set(g,f)}),k},a[s].path=d.path,a[s].method=d.method,a[s].options=d.options,a[s].headers=d.headers;return{api:a,middlewares:i}}function ao(e){let t=new Map;return e.split(", ").forEach(i=>{let r=i.split(";").map(u=>u.trim()),[n,...a]=r,[s,...d]=n.split("="),A=d.join("=");if(!s||A===void 0){console.warn(`Malformed cookie: ${i}`);return}let K={value:A};a.forEach(u=>{let[p,...l]=u.split("="),h=l.join("="),k=p.trim().toLowerCase();switch(k){case"max-age":K["max-age"]=h?parseInt(h.trim(),10):void 0;break;case"expires":K.expires=h?new Date(h.trim()):void 0;break;case"domain":K.domain=h?h.trim():void 0;break;case"path":K.path=h?h.trim():void 0;break;case"secure":K.secure=!0;break;case"httponly":K.httponly=!0;break;case"samesite":K.samesite=h?h.trim().toLowerCase():void 0;break;default:K[k]=h?h.trim():!0;break}}),t.set(s,K)}),t}async function m(e,t,o,i){let r=e.context.authCookies.sessionToken.options,n=o?void 0:e.context.sessionConfig.expiresIn,a=await U(e).catch(()=>null);a&&a.session.userId===t.session.userId&&a.session.token!==t.session.token&&await e.context.internalAdapter.deleteSession(a.session.token),await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...r,maxAge:n,...i}),o&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Ri.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:R(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await to.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3))}function Q(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}function Qe(e){let t=e.split("; "),o=new Map;return t.forEach(i=>{let[r,n]=i.split("=");o.set(r,n)}),o}var ji=require("@better-fetch/fetch"),zi=require("better-call"),Re=require("jose"),Bi=require("oslo/jwt");var Pi=require("oslo/crypto"),Ei=require("oslo/encoding");async function Si(e){let t=await(0,Pi.sha256)(new TextEncoder().encode(e));return Ei.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Di(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?R(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function S({id:e,options:t,authorizationEndpoint:o,state:i,codeVerifier:r,scopes:n,claims:a,redirectURI:s}){let d=new URL(o);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",i),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||s),r){let A=await Si(r);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",A)}if(a){let A=a.reduce((K,u)=>(K[u]=null,K),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...A}}))}return d}var xi=require("@better-fetch/fetch");async function I({code:e,codeVerifier:t,redirectURI:o,options:i,tokenEndpoint:r,authentication:n}){let a=new URLSearchParams,s={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(a.set("grant_type","authorization_code"),a.set("code",e),t&&a.set("code_verifier",t),a.set("redirect_uri",o),n==="basic"){let u=btoa(`${i.clientId}:${i.clientSecret}`);s.authorization=`Basic ${u}`}else a.set("client_id",i.clientId),a.set("client_secret",i.clientSecret);let{data:d,error:A}=await(0,xi.betterFetch)(r,{method:"POST",body:a,headers:s});if(A)throw A;return Di(d)}var Ao=require("oslo/oauth2"),pe=require("zod"),Ro=require("better-call");function Ie(e){try{return new URL(e).origin}catch{return null}}async function Ue(e,t){let o=e.body?.callbackURL||(e.query?.currentURL?Ie(e.query?.currentURL):"")||e.context.options.baseURL;if(!o)throw new Ro.APIError("BAD_REQUEST",{message:"callbackURL is required"});let i=(0,Ao.generateCodeVerifier)(),r=(0,Ao.generateState)(),n=JSON.stringify({callbackURL:o,codeVerifier:i,errorURL:e.body?.errorCallbackURL||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:n,identifier:r,expiresAt:a});if(!s)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new Ro.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:s.identifier,codeVerifier:i}}async function co(e){let t=e.query.state||e.body.state,o=await e.context.internalAdapter.findVerificationValue(t);if(!o)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let i=pe.z.object({callbackURL:pe.z.string(),codeVerifier:pe.z.string(),errorURL:pe.z.string().optional(),expiresAt:pe.z.number(),link:pe.z.object({email:pe.z.string(),userId:pe.z.string()}).optional()}).parse(JSON.parse(o.value));if(i.errorURL||(i.errorURL=`${e.context.baseURL}/error`),i.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(o.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(o.id),i}var Ni=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:o,scopes:i,redirectURI:r}){let n=i||["email","name"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${r||e.redirectURI}&scope=${n.join(" ")}&state=${o}&response_mode=form_post`)},validateAuthorizationCode:async({code:o,codeVerifier:i,redirectURI:r})=>I({code:o,codeVerifier:i,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t}),async verifyIdToken(o,i){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(o,i);let r=(0,Re.decodeProtectedHeader)(o),{kid:n,alg:a}=r;if(!n||!a)return!1;let s=await Tr(n),{payload:d}=await(0,Re.jwtVerify)(o,s,{algorithms:[a],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(A=>{d[A]!==void 0&&(d[A]=!!d[A])}),i&&d.nonce!==i?!1:!!d},async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);if(!o.idToken)return null;let i=(0,Bi.parseJWT)(o.idToken)?.payload;if(!i)return null;let r=i.user?`${i.user.name.firstName} ${i.user.name.lastName}`:i.email;return{user:{id:i.sub,name:r,emailVerified:!1,email:i.email},data:i}}}},Tr=async e=>{let t="https://appleid.apple.com",o="/auth/keys",{data:i}=await(0,ji.betterFetch)(`${t}${o}`);if(!i?.keys)throw new zi.APIError("BAD_REQUEST",{message:"Keys not found"});let r=i.keys.find(n=>n.kid===e);if(!r)throw new Error(`JWK with kid ${e} not found`);return await(0,Re.importJWK)(r,r.alg)};var Li=require("@better-fetch/fetch");var _i=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:o,redirectURI:i}){let r=o||["identify","email"];return e.scope&&r.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${r.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||i)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:o})=>I({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:i}=await(0,Li.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;if(o.avatar===null){let r=o.discriminator==="0"?Number(BigInt(o.id)>>BigInt(22))%6:parseInt(o.discriminator)%5;o.image_url=`https://cdn.discordapp.com/embed/avatars/${r}.png`}else{let r=o.avatar.startsWith("a_")?"gif":"png";o.image_url=`https://cdn.discordapp.com/avatars/${o.id}/${o.avatar}.${r}`}return{user:{id:o.id,name:o.display_name||o.username||"",email:o.email,emailVerified:o.verified,image:o.image_url},data:o}}});var Fi=require("@better-fetch/fetch");var Vi=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:o,redirectURI:i}){let r=o||["email","public_profile"];return e.scope&&r.push(...e.scope),await S({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:r,state:t,redirectURI:i})},validateAuthorizationCode:async({code:t,redirectURI:o})=>I({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:i}=await(0,Fi.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return i?null:{user:{id:o.id,name:o.name,email:o.email,image:o.picture.data.url,emailVerified:o.email_verified},data:o}}});var Po=require("@better-fetch/fetch");var qi=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:o,scopes:i,codeVerifier:r,redirectURI:n}){let a=i||["user:email"];return e.scope&&a.push(...e.scope),S({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>I({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);let{data:i,error:r}=await(0,Po.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${o.accessToken}`}});if(r)return null;let n=!1;if(!i.email){let{data:a,error:s}=await(0,Po.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${o.accessToken}`,"User-Agent":"better-auth"}});s||(i.email=(a.find(d=>d.primary)??a[0])?.email,n=a.find(d=>d.email===i.email)?.verified??!1)}return{user:{id:i.id.toString(),name:i.name||i.login,email:i.email,image:i.avatar_url,emailVerified:n},data:i}}}};var Mi=require("oslo/jwt");var Hi=require("@better-fetch/fetch"),Qi=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:o,codeVerifier:i,redirectURI:r}){if(!e.clientId||!e.clientSecret)throw J.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new ee("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new ee("codeVerifier is required for Google");let n=o||["email","profile","openid"];e.scope&&n.push(...e.scope);let a=await S({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:i,redirectURI:r});return e.accessType&&a.searchParams.set("access_type",e.accessType),e.prompt&&a.searchParams.set("prompt",e.prompt),a},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:i})=>I({code:t,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,o);let i=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:r}=await(0,Hi.betterFetch)(i);return r?r.aud===e.clientId&&r.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let o=(0,Mi.parseJWT)(t.idToken)?.payload;return{user:{id:o.sub,name:o.name,email:o.email,image:o.picture,emailVerified:o.email_verified},data:o}}});var $i=require("@better-fetch/fetch"),Zi=require("oslo/jwt");var Gi=e=>{let t=e.tenantId||"common",o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,i=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(r){let n=r.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),S({id:"microsoft",options:e,authorizationEndpoint:o,state:r.state,codeVerifier:r.codeVerifier,scopes:n,redirectURI:r.redirectURI})},validateAuthorizationCode({code:r,codeVerifier:n,redirectURI:a}){return I({code:r,codeVerifier:n,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:i})},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let n=(0,Zi.parseJWT)(r.idToken)?.payload,a=e.profilePhotoSize||48;return await(0,$i.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${r.accessToken}`},async onResponse(s){if(!(e.disableProfilePhoto||!s.response.ok))try{let A=await s.response.clone().arrayBuffer(),K=Buffer.from(A).toString("base64");n.picture=`data:image/jpeg;base64, ${K}`}catch(d){J.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};var Wi=require("@better-fetch/fetch");var Ji=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:o,codeVerifier:i,redirectURI:r}){let n=o||["user-read-email"];return e.scope&&n.push(...e.scope),S({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:r})},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:i})=>I({code:t,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:i}=await(0,Wi.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{id:o.id,name:o.display_name,email:o.email,image:o.images[0]?.url,emailVerified:!1},data:o}}});var Xi=require("nanoid"),V=e=>(0,Xi.nanoid)(e);var Yi=require("oslo/jwt");var et=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:o,redirectURI:i}){let r=o||["user:read:email","openid"];return e.scope&&r.push(...e.scope),S({id:"twitch",redirectURI:i,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:r,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:o})=>I({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let o=t.idToken;if(!o)return J.error("No idToken found in token"),null;let i=(0,Yi.parseJWT)(o)?.payload;return{user:{id:i.sub,name:i.preferred_username,email:i.email,image:i.picture,emailVerified:!1},data:i}}});var ot=require("@better-fetch/fetch");var it=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let o=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&o.push(...e.scope),S({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:o,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:i})=>I({code:t,codeVerifier:o,authentication:"basic",redirectURI:e.redirectURI||i,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:i}=await(0,ot.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{id:o.data.id,name:o.data.name,email:o.data.username||null,image:o.data.profile_image_url,emailVerified:o.data.verified||!1},data:o}}});var tt=require("@better-fetch/fetch");var rt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:o,scopes:i,codeVerifier:r,redirectURI:n})=>{let a=i||["account_info.read"];return e.scope&&a.push(...e.scope),await S({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:o,redirectURI:n,codeVerifier:r})},validateAuthorizationCode:async({code:o,codeVerifier:i,redirectURI:r})=>await I({code:o,codeVerifier:i,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t}),async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);let{data:i,error:r}=await(0,tt.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${o.accessToken}`}});return r?null:{user:{id:i.account_id,name:i.name?.display_name,email:i.email,emailVerified:i.email_verified||!1,image:i.profile_photo_url},data:i}}}};var nt=require("@better-fetch/fetch");var st=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",o="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:i,scopes:r,redirectURI:n})=>{let a=r||["profile","email","openid"];return e.scope&&a.push(...e.scope),await S({id:"linkedin",options:e,authorizationEndpoint:t,scopes:a,state:i,redirectURI:n})},validateAuthorizationCode:async({code:i,redirectURI:r})=>await I({code:i,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:o}),async getUserInfo(i){let{data:r,error:n}=await(0,nt.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});return n?null:{user:{id:r.sub,name:r.name,email:r.email,emailVerified:r.email_verified||!1,image:r.picture},data:r}}}};var at=require("@better-fetch/fetch");var Eo=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Or=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:Eo(`${t}/oauth/authorize`),tokenEndpoint:Eo(`${t}/oauth/token`),userinfoEndpoint:Eo(`${t}/api/v4/user`)}},dt=e=>{let{authorizationEndpoint:t,tokenEndpoint:o,userinfoEndpoint:i}=Or(e.issuer),r="gitlab";return{id:r,name:"Gitlab",createAuthorizationURL:async({state:a,scopes:s,codeVerifier:d,redirectURI:A})=>{let K=s||["read_user"];return e.scope&&K.push(...e.scope),await S({id:r,options:e,authorizationEndpoint:t,scopes:K,state:a,redirectURI:A,codeVerifier:d})},validateAuthorizationCode:async({code:a,redirectURI:s,codeVerifier:d})=>I({code:a,redirectURI:e.redirectURI||s,options:e,codeVerifier:d,tokenEndpoint:o}),async getUserInfo(a){if(e.getUserInfo)return e.getUserInfo(a);let{data:s,error:d}=await(0,at.betterFetch)(i,{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 Ir={apple:Ni,discord:_i,facebook:Vi,github:qi,microsoft:Gi,google:Qi,spotify:Ji,twitch:et,twitter:it,dropbox:rt,linkedin:st,gitlab:dt},Ko=Object.keys(Ir);async function Pe(e,{userInfo:t,account:o,callbackURL:i}){let r=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(s=>{throw J.error(`Better auth was unable to query your database.
|
|
83
|
-
Error: `,s),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=r?.user;if(r){let s=r.accounts.find(d=>d.providerId===o.providerId);if(s){let d=Object.fromEntries(Object.entries({accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt}).filter(([A,K])=>K!==void 0));Object.keys(d).length>0&&await e.context.internalAdapter.updateAccount(s.id,d)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(o.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return ei&&J.warn(`User already exist but account isn't linked to ${o.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:o.providerId,accountId:t.id.toString(),userId:r.user.id,accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt,scope:o.scope})}catch(K){return J.error("Unable to link account",K),{error:"unable to link account",data:null}}}}else try{let s=t.emailVerified||!1;if(n=await e.context.internalAdapter.createOAuthUser({...t,id:void 0,emailVerified:s,email:t.email.toLowerCase()},{accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt,scope:o.scope,providerId:o.providerId,accountId:t.id.toString()}).then(d=>d?.user),!s&&n&&e.context.options.emailVerification?.sendOnSignUp){let d=await Ke(e.context.secret,n.email),A=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${i}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:n,url:A,token:d},e.request)}}catch(s){return J.error("Unable to create user",s),{error:"unable to create user",data:null}}if(!n)return{error:"unable to create user",data:null};let a=await e.context.internalAdapter.createSession(n.id,e.request);return a?{data:{session:a,user:n},error:null}:{error:"unable to create session",data:null}}var gi=c("/sign-in/social",{method:"POST",query:x.z.object({currentURL:x.z.string().optional()}).optional(),body:x.z.object({callbackURL:x.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),errorCallbackURL:x.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:x.z.enum(Ko,{description:"OAuth2 provider to use"}),disableRedirect:x.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:x.z.optional(x.z.object({token:x.z.string({description:"ID token from the provider"}),nonce:x.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:x.z.string({description:"Access token from the provider"}).optional(),refreshToken:x.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:x.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new q.APIError("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new q.APIError("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:n,nonce:a}=e.body.idToken;if(!await t.verifyIdToken(n,a))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new q.APIError("UNAUTHORIZED",{message:"Invalid id token"});let d=await t.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!d||!d?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new q.APIError("UNAUTHORIZED",{message:"Failed to get user info"});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new q.APIError("UNAUTHORIZED",{message:"User email not found"});let A=await Pe(e,{userInfo:{email:d.user.email,id:d.user.id,name:d.user.name||"",image:d.user.image,emailVerified:d.user.emailVerified||!1},account:{providerId:t.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(A.error)throw new q.APIError("UNAUTHORIZED",{message:A.error});return await m(e,A.data),e.json({session:A.data.session,user:A.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:o,state:i}=await Ue(e),r=await t.createAuthorizationURL({state:i,codeVerifier:o,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:r.toString(),redirect:!e.body.disableRedirect})}),mi=c("/sign-in/email",{method:"POST",body:x.z.object({email:x.z.string({description:"Email of the user"}),password:x.z.string({description:"Password of the user"}),callbackURL:x.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:x.z.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},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 q.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:o}=e.body;if(!x.z.string().email().safeParse(t).success)throw new q.APIError("BAD_REQUEST",{message:"Invalid email"});let r=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!r)throw await e.context.password.hash(o),e.context.logger.error("User not found",{email:t}),new q.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let n=r.accounts.find(A=>A.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new q.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let a=n?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new q.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify({hash:a,password:o}))throw e.context.logger.error("Invalid password"),new q.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!r.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new q.APIError("UNAUTHORIZED",{message:"Email is not verified."});let A=await Ke(e.context.secret,r.user.email),K=`${e.context.baseURL}/verify-email?token=${A}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:r.user,url:K,token:A},e.request),e.context.logger.error("Email not verified",{email:t}),new q.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(r.user.id,e.headers,e.body.rememberMe===!1);if(!d)throw e.context.logger.error("Failed to create session"),new q.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await m(e,{session:d,user:r.user},e.body.rememberMe===!1),e.json({user:r.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Ee=require("zod");var po=Ee.z.object({code:Ee.z.string().optional(),error:Ee.z.string().optional(),errorMessage:Ee.z.string().optional(),state:Ee.z.string().optional()}),fi=c("/callback/:id",{method:["GET","POST"],body:po.optional(),query:po.optional(),metadata:we},async e=>{let t;try{if(e.method==="GET")t=po.parse(e.query);else if(e.method==="POST")t=po.parse(e.body);else throw new Error("Unsupported method")}catch(g){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",g),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:o,error:i,state:r}=t;if(!r)throw e.context.logger.error("State not found"),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!o)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${i||"no_code"}`);let n=e.context.socialProviders.find(g=>g.id===e.params.id);if(!n)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:a,callbackURL:s,link:d,errorURL:A}=await co(e),K;try{K=await n.validateAuthorizationCode({code:o,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${n.id}`})}catch(g){throw e.context.logger.error("",g),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let u=await n.getUserInfo(K).then(g=>g?.user);function p(g){let b=A||s||`${e.context.baseURL}/error`;throw b.includes("?")?b=`${b}&error=${g}`:b=`${b}?error=${g}`,e.redirect(b)}if(!u)return e.context.logger.error("Unable to get user info"),p("unable_to_get_user_info");if(!u.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),p("email_not_found");if(!s)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(d){if(d.email!==u.email.toLowerCase())return p("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:n.id,accountId:u.id}))return p("unable_to_link_account");let b;try{b=new URL(s).toString()}catch{b=s}throw e.redirect(b)}let l=await Pe(e,{userInfo:{id:u.id,email:u.email,name:u.name||"",image:u.image,emailVerified:u.emailVerified||!1},account:{providerId:n.id,accountId:u.id,...K,scope:K.scopes?.join(",")},callbackURL:s});if(l.error)return e.context.logger.error(l.error.split(" ").join("_")),p(l.error.split(" ").join("_"));let{session:h,user:k}=l.data;await m(e,{session:h,user:k});let f;try{f=new URL(s).toString()}catch{f=s}throw e.redirect(f)});var Ed=require("zod");var At=require("better-call"),hi=c("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw Q(e),new At.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),Q(e),e.json({success:!0})});var X=require("zod");var uo=require("better-call");function ct(e,t,o){let i=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return o&&Object.entries(o).forEach(([r,n])=>i.searchParams.set(r,n)),i.href}function Ur(e,t,o){let i=new URL(t,e.baseURL);return o&&Object.entries(o).forEach(([r,n])=>i.searchParams.set(r,n)),i.href}var yi=c("/forget-password",{method:"POST",body:X.z.object({email:X.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:X.z.string({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},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 uo.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:o}=e.body,i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let r=60*60*1,n=R(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||r,"sec"),a=V(24);await e.context.internalAdapter.createVerificationValue({value:i.user.id.toString(),identifier:`reset-password:${a}`,expiresAt:n});let s=`${e.context.baseURL}/reset-password/${a}?callbackURL=${o}`;return await e.context.options.emailAndPassword.sendResetPassword({user:i.user,url:s,token:a},e.request),e.json({status:!0})}),wi=c("/reset-password/:token",{method:"GET",query:X.z.object({callbackURL:X.z.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:o}=e.query;if(!t||!o)throw e.redirect(ct(e.context,o,{error:"INVALID_TOKEN"}));let i=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!i||i.expiresAt<new Date?e.redirect(ct(e.context,o,{error:"INVALID_TOKEN"})):e.redirect(Ur(e.context,o,{token:t}))}),Ci=c("/reset-password",{query:X.z.optional(X.z.object({token:X.z.string().optional(),currentURL:X.z.string().optional()})),method:"POST",body:X.z.object({newPassword:X.z.string({description:"The new password to set"}),token:X.z.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new uo.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:o}=e.body,i=`reset-password:${t}`,r=await e.context.internalAdapter.findVerificationValue(i);if(!r||r.expiresAt<new Date)throw new uo.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(r.id);let n=r.value,a=await e.context.password.hash(o);return(await e.context.internalAdapter.findAccounts(n)).find(A=>A.providerId==="credential")?(await e.context.internalAdapter.updatePassword(n,a),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:a,accountId:n}),e.json({status:!0}))});var L=require("zod");var G=require("better-call");var bi=()=>c("/update-user",{method:"POST",body:L.z.record(L.z.string(),L.z.any()),use:[v],metadata:{openapi:{description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"}}}}}}}}}},async e=>{let t=e.body;if(t.email)throw new G.APIError("BAD_REQUEST",{message:"You can't update email"});let{name:o,image:i,...r}=t,n=e.context.session;if(i===void 0&&!o&&Object.keys(r).length===0)return e.json({user:n.user});let a=so(e.context.options,r,"update"),s=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:o,image:i,...a});return await m(e,{session:n.session,user:s}),e.json({user:s})}),vi=c("/change-password",{method:"POST",body:L.z.object({newPassword:L.z.string({description:"The new password to set"}),currentPassword:L.z.string({description:"The current password"}),revokeOtherSessions:L.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[v],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:o,revokeOtherSessions:i}=e.body,r=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new G.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 G.APIError("BAD_REQUEST",{message:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(r.user.id)).find(u=>u.providerId==="credential"&&u.password);if(!d||!d.password)throw new G.APIError("BAD_REQUEST",{message:"User does not have a password"});let A=await e.context.password.hash(t);if(!await e.context.password.verify({hash:d.password,password:o}))throw new G.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:A}),i){await e.context.internalAdapter.deleteSessions(r.user.id);let u=await e.context.internalAdapter.createSession(r.user.id,e.headers);if(!u)throw new G.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await m(e,{session:u,user:r.user})}return e.json(r.user)}),ki=c("/set-password",{method:"POST",body:L.z.object({newPassword:L.z.string()}),metadata:{SERVER_ONLY:!0},use:[v]},async e=>{let{newPassword:t}=e.body,o=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new G.APIError("BAD_REQUEST",{message:"Password is too short"});let r=e.context.password.config.maxPasswordLength;if(t.length>r)throw e.context.logger.error("Password is too long"),new G.APIError("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(o.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:o.user.id,providerId:"credential",accountId:o.user.id,password:s}),e.json(o.user);throw new G.APIError("BAD_REQUEST",{message:"user already has a password"})}),Ti=c("/delete-user",{method:"POST",body:L.z.object({password:L.z.string({description:"The password of the user"})}),use:[He],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{let t=e.context.session;return await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),Q(e),e.json(null)}),Oi=c("/change-email",{method:"POST",query:L.z.object({currentURL:L.z.string().optional()}).optional(),body:L.z.object({newEmail:L.z.string({description:"The new email to set"}).email(),callbackURL:L.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[v],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new G.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 G.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 G.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let r=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:r,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new G.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let o=await Ke(e.context.secret,e.context.session.user.email,e.body.newEmail),i=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:i,token:o},e.request),e.json({user:null,status:!0})});var Se=require("zod");var So=require("better-call");var Ii=c("/list-accounts",{method:"GET",use:[v],metadata:{openapi:{description:"List all accounts linked to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},provider:{type:"string"}}}}}}}}}}},async e=>{let t=e.context.session,o=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(o.map(i=>({id:i.id,provider:i.providerId})))}),Ui=c("/link-social",{method:"POST",requireHeaders:!0,query:Se.z.object({currentURL:Se.z.string().optional()}).optional(),body:Se.z.object({callbackURL:Se.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:Se.z.enum(Ko,{description:"The OAuth2 provider to use"})}),use:[v],metadata:{openapi:{description:"Link a social account to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}},required:["url","redirect"]}}}}}}}},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 So.APIError("BAD_REQUEST",{message:"Social Account is already linked."});let r=e.context.socialProviders.find(s=>s.id===e.body.provider);if(!r)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new So.APIError("NOT_FOUND",{message:"Provider not found"});let n=await Ue(e,{userId:t.user.id,email:t.user.email}),a=await r.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${r.id}`});return e.json({url:a.toString(),redirect:!0})});var Kt=(e,t)=>{let o={};for(let[i,r]of Object.entries(e))o[i]=n=>r({...n,context:{...t,...n.context}}),o[i].path=r.path,o[i].method=r.method,o[i].options=r.options,o[i].headers=r.headers;return o};function lo(e){let t=e;return{newRole(o){return Rr(o)}}}function Rr(e){return{statements:e,authorize(t,o){for(let[i,r]of Object.entries(t)){let n=e[i];return n?(o==="OR"?r.some(s=>n.includes(s)):r.every(s=>n.includes(s)))?{success:!0}:{success:!1,error:`Unauthorized to access resource "${i}"`}:{success:!1,error:`You are not allowed to access resource: ${i}`}}return{success:!1,error:"Not authorized"}}}}var Pr={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},Do=lo(Pr),Er=Do.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),Sr=Do.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),Dr=Do.newRole({organization:[],member:[],invitation:[]}),pt={admin:Er,owner:Sr,member:Dr};var xr={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},jr=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,ut={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},zr=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Br(e){return e instanceof Date&&!isNaN(e.getTime())}function Nr(e){let t=zr.exec(e);if(!t)return null;let[,o,i,r,n,a,s,d,A,K,u]=t,p=new Date(Date.UTC(parseInt(o,10),parseInt(i,10)-1,parseInt(r,10),parseInt(n,10),parseInt(a,10),parseInt(s,10),d?parseInt(d.padEnd(3,"0"),10):0));if(A){let l=(parseInt(K,10)*60+parseInt(u,10))*(A==="+"?-1:1);p.setUTCMinutes(p.getUTCMinutes()+l)}return Br(p)?p:null}function Lr(e,t={}){let{strict:o=!1,warnings:i=!1,reviver:r,parseDates:n=!0}=t;if(typeof e!="string")return e;let a=e.trim();if(a[0]==='"'&&a.endsWith('"')&&!a.slice(1,-1).includes('"'))return a.slice(1,-1);let s=a.toLowerCase();if(s.length<=9&&s in ut)return ut[s];if(!jr.test(a)){if(o)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(xr).some(([A,K])=>{let u=K.test(a);return u&&i&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${A} pattern`),u})&&o)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(a,(K,u)=>{if(K==="__proto__"||K==="constructor"&&u&&typeof u=="object"&&"prototype"in u){i&&console.warn(`[better-json] Dropping "${K}" key to prevent prototype pollution`);return}if(n&&typeof u=="string"){let p=Nr(u);if(p)return p}return r?r(K,u):u})}catch(A){if(o)throw A;return e}}function lt(e,t={strict:!0}){return Lr(e,t)}var gt=lt;var z=(e,t)=>{let o=e.adapter;return{findOrganizationBySlug:async i=>await o.findOne({model:"organization",where:[{field:"slug",value:i}]}),createOrganization:async i=>{let r=await o.create({model:"organization",data:{...i.organization,metadata:i.organization.metadata?JSON.stringify(i.organization.metadata):void 0}}),n=await o.create({model:"member",data:{organizationId:r.id,userId:i.user.id,createdAt:new Date,role:t?.creatorRole||"owner"}});return{...r,metadata:r.metadata?JSON.parse(r.metadata):void 0,members:[{...n,user:{id:i.user.id,name:i.user.name,email:i.user.email,image:i.user.image}}]}},findMemberByEmail:async i=>{let r=await o.findOne({model:"user",where:[{field:"email",value:i.email}]});if(!r)return null;let n=await o.findOne({model:"member",where:[{field:"organizationId",value:i.organizationId},{field:"userId",value:r.id}]});return n?{...n,user:{id:r.id,name:r.name,email:r.email,image:r.image}}:null},findMemberByOrgId:async i=>{let[r,n]=await Promise.all([await o.findOne({model:"member",where:[{field:"userId",value:i.userId},{field:"organizationId",value:i.organizationId}]}),await o.findOne({model:"user",where:[{field:"id",value:i.userId}]})]);return!n||!r?null:{...r,user:{id:n.id,name:n.name,email:n.email,image:n.image}}},findMemberById:async i=>{let r=await o.findOne({model:"member",where:[{field:"id",value:i}]});if(!r)return null;let n=await o.findOne({model:"user",where:[{field:"id",value:r.userId}]});return n?{...r,user:{id:n.id,name:n.name,email:n.email,image:n.image}}:null},createMember:async i=>await o.create({model:"member",data:i}),updateMember:async(i,r)=>await o.update({model:"member",where:[{field:"id",value:i}],update:{role:r}}),deleteMember:async i=>await o.delete({model:"member",where:[{field:"id",value:i}]}),updateOrganization:async(i,r)=>{let n=await o.update({model:"organization",where:[{field:"id",value:i}],update:{...r,metadata:typeof r.metadata=="object"?JSON.stringify(r.metadata):r.metadata}});return n?{...n,metadata:n.metadata?gt(n.metadata):void 0}:null},deleteOrganization:async i=>(await o.delete({model:"member",where:[{field:"organizationId",value:i}]}),await o.delete({model:"invitation",where:[{field:"organizationId",value:i}]}),await o.delete({model:"organization",where:[{field:"id",value:i}]}),i),setActiveOrganization:async(i,r)=>await e.internalAdapter.updateSession(i,{activeOrganizationId:r}),findOrganizationById:async i=>await o.findOne({model:"organization",where:[{field:"id",value:i}]}),findFullOrganization:async({organizationId:i,isSlug:r})=>{let n=await o.findOne({model:"organization",where:[{field:r?"slug":"id",value:i}]});if(!n)return null;let[a,s]=await Promise.all([o.findMany({model:"invitation",where:[{field:"organizationId",value:n.id}]}),o.findMany({model:"member",where:[{field:"organizationId",value:n.id}]})]);if(!n)return null;let d=s.map(p=>p.userId),A=await o.findMany({model:"user",where:[{field:"id",value:d,operator:"in"}]}),K=new Map(A.map(p=>[p.id,p])),u=s.map(p=>{let l=K.get(p.userId);if(!l)throw new ee("Unexpected error: User not found for member");return{...p,user:{id:l.id,name:l.name,email:l.email,image:l.image}}});return{...n,invitations:a,members:u}},listOrganizations:async i=>{let r=await o.findMany({model:"member",where:[{field:"userId",value:i}]});if(!r||r.length===0)return[];let n=r.map(s=>s.organizationId);return await o.findMany({model:"organization",where:[{field:"id",value:n,operator:"in"}]})},createInvitation:async({invitation:i,user:r})=>{let a=R(t?.invitationExpiresIn||1728e5);return await o.create({model:"invitation",data:{email:i.email,role:i.role,organizationId:i.organizationId,status:"pending",expiresAt:a,inviterId:r.id}})},findInvitationById:async i=>await o.findOne({model:"invitation",where:[{field:"id",value:i}]}),findPendingInvitation:async i=>(await o.findMany({model:"invitation",where:[{field:"email",value:i.email},{field:"organizationId",value:i.organizationId},{field:"status",value:"pending"}]})).filter(n=>new Date(n.expiresAt)>new Date),updateInvitation:async i=>await o.update({model:"invitation",where:[{field:"id",value:i.invitationId}],update:{status:i.status}})}};var OA=require("better-call");var B=P(async e=>({})),M=P({use:[v]},async e=>({session:e.context.session}));var W=require("zod");var E=require("zod");var mt=E.z.string(),_r=E.z.enum(["pending","accepted","rejected","canceled"]).default("pending"),SA=E.z.object({id:E.z.string().default(V),name:E.z.string(),slug:E.z.string(),logo:E.z.string().nullish(),metadata:E.z.record(E.z.string()).or(E.z.string().transform(e=>JSON.parse(e))).nullish(),createdAt:E.z.date()}),DA=E.z.object({id:E.z.string().default(V),organizationId:E.z.string(),userId:E.z.string(),role:mt,createdAt:E.z.date()}),xA=E.z.object({id:E.z.string().default(V),organizationId:E.z.string(),email:E.z.string(),role:mt,status:_r,inviterId:E.z.string(),expiresAt:E.z.date()});var j=require("better-call"),ft=e=>c("/organization/invite-member",{method:"POST",use:[B,M],body:W.z.object({email:W.z.string({description:"The email address of the user to invite"}),role:W.z.string({description:"The role to assign to the user"}),organizationId:W.z.string({description:"The organization ID to invite the user to"}).optional(),resend:W.z.boolean({description:"Resend the invitation email, if the user is already invited"}).optional()}),metadata:{openapi:{description:"Invite a user to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt"]}}}}}}}},async t=>{if(!t.context.orgOptions.sendInvitationEmail)throw t.context.logger.warn("Invitation email is not enabled. Pass `sendInvitationEmail` to the plugin options to enable it."),new j.APIError("BAD_REQUEST",{message:"Invitation email is not enabled"});let o=t.context.session,i=t.body.organizationId||o.session.activeOrganizationId;if(!i)throw new j.APIError("BAD_REQUEST",{message:"Organization not found"});let r=z(t.context,t.context.orgOptions),n=await r.findMemberByOrgId({userId:o.user.id,organizationId:i});if(!n)throw new j.APIError("BAD_REQUEST",{message:"Member not found!"});let a=t.context.roles[n.role];if(!a)throw new j.APIError("BAD_REQUEST",{message:"Role not found!"});if(a.authorize({invitation:["create"]}).error)throw new j.APIError("FORBIDDEN",{message:"You are not allowed to invite members"});if(await r.findMemberByEmail({email:t.body.email,organizationId:i}))throw new j.APIError("BAD_REQUEST",{message:"User is already a member of this organization"});if((await r.findPendingInvitation({email:t.body.email,organizationId:i})).length&&!t.body.resend)throw new j.APIError("BAD_REQUEST",{message:"User is already invited to this organization"});let K=await r.createInvitation({invitation:{role:t.body.role,email:t.body.email,organizationId:i},user:o.user}),u=await r.findOrganizationById(i);if(!u)throw new j.APIError("BAD_REQUEST",{message:"Organization not found"});return await t.context.orgOptions.sendInvitationEmail?.({id:K.id,role:K.role,email:K.email,organization:u,inviter:{...n,user:o.user}},t.request),t.json(K)}),ht=c("/organization/accept-invitation",{method:"POST",body:W.z.object({invitationId:W.z.string({description:"The ID of the invitation to accept"})}),use:[B,M],metadata:{openapi:{description:"Accept an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"},member:{type:"object"}}}}}}}}}},async e=>{let t=e.context.session,o=z(e.context,e.context.orgOptions),i=await o.findInvitationById(e.body.invitationId);if(!i||i.expiresAt<new Date||i.status!=="pending")throw new j.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(i.email!==t.user.email)throw new j.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let r=await o.updateInvitation({invitationId:e.body.invitationId,status:"accepted"}),n=await o.createMember({organizationId:i.organizationId,userId:t.user.id,role:i.role,createdAt:new Date});return await o.setActiveOrganization(t.session.token,i.organizationId),r?e.json({invitation:r,member:n}):e.json(null,{status:400,body:{message:"Invitation not found!"}})}),yt=c("/organization/reject-invitation",{method:"POST",body:W.z.object({invitationId:W.z.string({description:"The ID of the invitation to reject"})}),use:[B,M],metadata:{openapi:{description:"Reject an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"},member:{type:"null"}}}}}}}}}},async e=>{let t=e.context.session,o=z(e.context,e.context.orgOptions),i=await o.findInvitationById(e.body.invitationId);if(!i||i.expiresAt<new Date||i.status!=="pending")throw new j.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(i.email!==t.user.email)throw new j.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let r=await o.updateInvitation({invitationId:e.body.invitationId,status:"rejected"});return e.json({invitation:r,member:null})}),wt=c("/organization/cancel-invitation",{method:"POST",body:W.z.object({invitationId:W.z.string({description:"The ID of the invitation to cancel"})}),use:[B,M],openapi:{description:"Cancel an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"}}}}}}}}},async e=>{let t=e.context.session,o=z(e.context,e.context.orgOptions),i=await o.findInvitationById(e.body.invitationId);if(!i)throw new j.APIError("BAD_REQUEST",{message:"Invitation not found!"});let r=await o.findMemberByOrgId({userId:t.user.id,organizationId:i.organizationId});if(!r)throw new j.APIError("BAD_REQUEST",{message:"Member not found!"});if(e.context.roles[r.role].authorize({invitation:["cancel"]}).error)throw new j.APIError("FORBIDDEN",{message:"You are not allowed to cancel this invitation"});let a=await o.updateInvitation({invitationId:e.body.invitationId,status:"canceled"});return e.json(a)}),Ct=c("/organization/get-invitation",{method:"GET",use:[B],requireHeaders:!0,query:W.z.object({id:W.z.string({description:"The ID of the invitation to get"})}),metadata:{openapi:{description:"Get an invitation by ID",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"},organizationName:{type:"string"},organizationSlug:{type:"string"},inviterEmail:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt","organizationName","organizationSlug","inviterEmail"]}}}}}}}},async e=>{let t=await U(e);if(!t)throw new j.APIError("UNAUTHORIZED",{message:"Not authenticated"});let o=z(e.context,e.context.orgOptions),i=await o.findInvitationById(e.query.id);if(!i||i.status!=="pending"||i.expiresAt<new Date)throw new j.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(i.email!==t.user.email)throw new j.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let r=await o.findOrganizationById(i.organizationId);if(!r)throw new j.APIError("BAD_REQUEST",{message:"Organization not found"});let n=await o.findMemberByOrgId({userId:i.inviterId,organizationId:i.organizationId});if(!n)throw new j.APIError("BAD_REQUEST",{message:"Inviter is no longer a member of the organization"});return e.json({...i,organizationName:r.name,organizationSlug:r.slug,inviterEmail:n.user.email})});var te=require("zod");var ge=require("better-call");var bt=()=>c("/organization/add-member",{method:"POST",body:te.z.object({userId:te.z.string(),role:te.z.string(),organizationId:te.z.string().optional()}),use:[B],metadata:{SERVER_ONLY:!0}},async e=>{let t=e.body.userId?await U(e).catch(s=>null):null,o=e.body.organizationId||t?.session.activeOrganizationId;if(!o)return e.json(null,{status:400,body:{message:"No active organization found!"}});let i=z(e.context,e.context.orgOptions),r=await e.context.internalAdapter.findUserById(e.body.userId);if(!r)throw new ge.APIError("BAD_REQUEST",{message:"User not found!"});if(await i.findMemberByEmail({email:r.email,organizationId:o}))throw new ge.APIError("BAD_REQUEST",{message:"User is already a member of this organization"});let a=await i.createMember({id:V(),organizationId:o,userId:r.id,role:e.body.role,createdAt:new Date});return e.json(a)}),vt=c("/organization/remove-member",{method:"POST",body:te.z.object({memberIdOrEmail:te.z.string({description:"The ID or email of the member to remove"}),organizationId:te.z.string({description:"The ID of the organization to remove the member from. If not provided, the active organization will be used"}).optional()}),use:[B,M],metadata:{openapi:{description:"Remove a member from an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{member:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}},required:["member"]}}}}}}}},async e=>{let t=e.context.session,o=e.body.organizationId||t.session.activeOrganizationId;if(!o)return e.json(null,{status:400,body:{message:"No active organization found!"}});let i=z(e.context,e.context.orgOptions),r=await i.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!r)throw new ge.APIError("BAD_REQUEST",{message:"Member not found!"});let n=e.context.roles[r.role];if(!n)throw new ge.APIError("BAD_REQUEST",{message:"Role not found!"});let a=t.user.email===e.body.memberIdOrEmail||r.id===e.body.memberIdOrEmail;if(a&&r.role===(e.context.orgOptions?.creatorRole||"owner"))throw new ge.APIError("BAD_REQUEST",{message:"You cannot leave the organization as the owner"});if(!(a||n.authorize({member:["delete"]}).success))throw new ge.APIError("UNAUTHORIZED",{message:"You are not allowed to delete this member"});let A=null;if(e.body.memberIdOrEmail.includes("@")?A=await i.findMemberByEmail({email:e.body.memberIdOrEmail,organizationId:o}):A=await i.findMemberById(e.body.memberIdOrEmail),A?.organizationId!==o)throw new ge.APIError("BAD_REQUEST",{message:"Member not found!"});return await i.deleteMember(A.id),t.user.id===A.userId&&t.session.activeOrganizationId===A.organizationId&&await i.setActiveOrganization(t.session.token,null),e.json({member:A})}),kt=e=>c("/organization/update-member-role",{method:"POST",body:te.z.object({role:te.z.string(),memberId:te.z.string(),organizationId:te.z.string().optional()}),use:[B,M],metadata:{openapi:{description:"Update the role of a member in an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{member:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}},required:["member"]}}}}}}}},async t=>{let o=t.context.session,i=t.body.organizationId||o.session.activeOrganizationId;if(!i)return t.json(null,{status:400,body:{message:"No active organization found!"}});let r=z(t.context,t.context.orgOptions),n=await r.findMemberByOrgId({userId:o.user.id,organizationId:i});if(!n)return t.json(null,{status:400,body:{message:"Member not found!"}});let a=t.context.roles[n.role];if(!a)return t.json(null,{status:400,body:{message:"Role not found!"}});if(a.authorize({member:["update"]}).error||t.body.role==="owner"&&n.role!=="owner")return t.json(null,{body:{message:"You are not allowed to update this member"},status:403});let d=await r.updateMember(t.body.memberId,t.body.role);return d?t.json(d):t.json(null,{status:400,body:{message:"Member not found!"}})}),Tt=c("/organization/get-active-member",{method:"GET",use:[B,M],metadata:{openapi:{description:"Get the active member in the organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}}}}}}}},async e=>{let t=e.context.session,o=t.session.activeOrganizationId;if(!o)return e.json(null,{status:400,body:{message:"No active organization found!"}});let r=await z(e.context,e.context.orgOptions).findMemberByOrgId({userId:t.user.id,organizationId:o});return r?e.json(r):e.json(null,{status:400,body:{message:"Member not found!"}})});var O=require("zod");var me=require("better-call");var Ot=c("/organization/create",{method:"POST",body:O.z.object({name:O.z.string({description:"The name of the organization"}),slug:O.z.string({description:"The slug of the organization"}),userId:O.z.string({description:"The user id of the organization creator. If not provided, the current user will be used. Should only be used by admins or when called by the server."}).optional(),logo:O.z.string({description:"The logo of the organization"}).optional(),metadata:O.z.record(O.z.string(),O.z.any(),{description:"The metadata of the organization"}).optional()}),use:[B,M],metadata:{openapi:{description:"Create an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization that was created",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=e.context.session.user;if(!t)return e.json(null,{status:401});let o=e.context.orgOptions;if(!(typeof o?.allowUserToCreateOrganization=="function"?await o.allowUserToCreateOrganization(t):o?.allowUserToCreateOrganization===void 0?!0:o.allowUserToCreateOrganization))throw new me.APIError("FORBIDDEN",{message:"You are not allowed to create an organization"});let r=z(e.context,o),n=await r.listOrganizations(t.id);if(typeof o.organizationLimit=="number"?n.length>=o.organizationLimit:typeof o.organizationLimit=="function"?await o.organizationLimit(t):!1)throw new me.APIError("FORBIDDEN",{message:"You have reached the organization limit"});if(await r.findOrganizationBySlug(e.body.slug))throw new me.APIError("BAD_REQUEST",{message:"Organization with this slug already exists"});let d=await r.createOrganization({organization:{id:V(),slug:e.body.slug,name:e.body.name,logo:e.body.logo,createdAt:new Date,metadata:e.body.metadata},user:t});return await r.setActiveOrganization(e.context.session.session.token,d.id),e.json(d)}),It=c("/organization/update",{method:"POST",body:O.z.object({data:O.z.object({name:O.z.string({description:"The name of the organization"}).optional(),slug:O.z.string({description:"The slug of the organization"}).optional(),logo:O.z.string({description:"The logo of the organization"}).optional(),metadata:O.z.record(O.z.string(),O.z.any(),{description:"The metadata of the organization"}).optional()}).partial(),organizationId:O.z.string().optional()}),requireHeaders:!0,use:[B],metadata:{openapi:{description:"Update an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The updated organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=await e.context.getSession(e);if(!t)throw new me.APIError("UNAUTHORIZED",{message:"User not found"});let o=e.body.organizationId||t.session.activeOrganizationId;if(!o)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let i=z(e.context,e.context.orgOptions),r=await i.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!r)return e.json(null,{status:400,body:{message:"User is not a member of this organization!"}});let n=e.context.roles[r.role];if(!n)return e.json(null,{status:400,body:{message:"Role not found!"}});if(n.authorize({organization:["update"]}).error)return e.json(null,{body:{message:"You are not allowed to update this organization"},status:403});let s=await i.updateOrganization(o,e.body.data);return e.json(s)}),Ut=c("/organization/delete",{method:"POST",body:O.z.object({organizationId:O.z.string({description:"The organization id to delete"})}),requireHeaders:!0,use:[B],metadata:{openapi:{description:"Delete an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string",description:"The organization id that was deleted"}}}}}}}},async e=>{let t=await e.context.getSession(e);if(!t)return e.json(null,{status:401});let o=e.body.organizationId;if(!o)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let i=z(e.context,e.context.orgOptions),r=await i.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!r)return e.json(null,{status:400,body:{message:"User is not a member of this organization!"}});let n=e.context.roles[r.role];if(!n)return e.json(null,{status:400,body:{message:"Role not found!"}});if(n.authorize({organization:["delete"]}).error)throw new me.APIError("FORBIDDEN",{message:"You are not allowed to delete this organization"});return o===t.session.activeOrganizationId&&await i.setActiveOrganization(t.session.token,null),await i.deleteOrganization(o),e.json(o)}),Rt=c("/organization/get-full-organization",{method:"GET",query:O.z.optional(O.z.object({organizationId:O.z.string({description:"The organization id to get"}).optional(),organizationSlug:O.z.string({description:"The organization slug to get"}).optional()})),requireHeaders:!0,use:[B,M],metadata:{openapi:{description:"Get the full organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=e.context.session,o=e.query?.organizationSlug||e.query?.organizationId||t.session.activeOrganizationId;if(!o)return e.json(null,{status:200});let r=await z(e.context,e.context.orgOptions).findFullOrganization({organizationId:o,isSlug:!!e.query?.organizationSlug});if(!r)throw new me.APIError("BAD_REQUEST",{message:"Organization not found"});return e.json(r)}),Pt=c("/organization/set-active",{method:"POST",body:O.z.object({organizationId:O.z.string({description:"The organization id to set as active. It can be null to unset the active organization"}).nullable().optional(),organizationSlug:O.z.string({description:"The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided"}).optional()}),use:[M,B],metadata:{openapi:{description:"Set the active organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=z(e.context,e.context.orgOptions),o=e.context.session,i=e.body.organizationSlug||e.body.organizationId;if(i===null){if(!o.session.activeOrganizationId)return e.json(null);let d=await t.setActiveOrganization(o.session.token,null);return await m(e,{session:d,user:o.user}),e.json(null)}if(!i){let s=o.session.activeOrganizationId;if(!s)return e.json(null);i=s}let r=await t.findFullOrganization({organizationId:i,isSlug:!!e.body.organizationSlug});if(!r?.members.find(s=>s.userId===o.user.id))throw await t.setActiveOrganization(o.session.token,null),new me.APIError("FORBIDDEN",{message:"You are not a member of this organization"});let a=await t.setActiveOrganization(o.session.token,i);return await m(e,{session:a,user:o.user}),e.json(r)}),Et=c("/organization/list",{method:"GET",use:[B,M],metadata:{openapi:{description:"List all organizations",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Organization"}}}}}}}}},async e=>{let o=await z(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(o)});var Fr=lo({name:["action"]}),Ac=Fr.newRole({name:["action"]}),Vr=e=>{let t={createOrganization:Ot,updateOrganization:It,deleteOrganization:Ut,setActiveOrganization:Pt,getFullOrganization:Rt,listOrganizations:Et,createInvitation:ft(e),cancelInvitation:wt,acceptInvitation:ht,getInvitation:Ct,rejectInvitation:yt,addMember:bt(),removeMember:vt,updateMemberRole:kt(e),getActiveMember:Tt},o={...pt,...e?.roles};return{id:"organization",endpoints:{...Kt(t,{orgOptions:e||{},roles:o,getSession:async r=>await U(r)}),hasPermission:c("/organization/has-permission",{method:"POST",requireHeaders:!0,body:De.z.object({permission:De.z.record(De.z.string(),De.z.array(De.z.string()))}),use:[M],metadata:{openapi:{description:"Check if the user has permission",requestBody:{content:{"application/json":{schema:{type:"object",properties:{permission:{type:"object",description:"The permission to check"}},required:["permission"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},success:{type:"boolean"}},required:["success"]}}}}}}}},async r=>{if(!r.context.session.session.activeOrganizationId)throw new xo.APIError("BAD_REQUEST",{message:"No active organization"});let a=await z(r.context).findMemberByOrgId({userId:r.context.session.user.id,organizationId:r.context.session.session.activeOrganizationId||""});if(!a)throw new xo.APIError("UNAUTHORIZED",{message:"You are not a member of this organization"});let d=o[a.role].authorize(r.body.permission);return d.error?r.json({error:d.error,success:!1},{status:403}):r.json({error:null,success:!0})})},schema:{session:{fields:{activeOrganizationId:{type:"string",required:!1,fieldName:e?.schema?.session?.fields?.activeOrganizationId}}},organization:{modelName:e?.schema?.organization?.modelName,fields:{name:{type:"string",required:!0,fieldName:e?.schema?.organization?.fields?.name},slug:{type:"string",unique:!0,fieldName:e?.schema?.organization?.fields?.slug},logo:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.logo},createdAt:{type:"date",required:!0,fieldName:e?.schema?.organization?.fields?.createdAt},metadata:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.metadata}}},member:{modelName:e?.schema?.member?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.member?.fields?.organizationId},userId:{type:"string",required:!0,fieldName:e?.schema?.member?.fields?.userId,references:{model:"user",field:"id"}},role:{type:"string",required:!0,defaultValue:"member",fieldName:e?.schema?.member?.fields?.role},createdAt:{type:"date",required:!0,fieldName:e?.schema?.member?.fields?.createdAt}}},invitation:{modelName:e?.schema?.invitation?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.invitation?.fields?.organizationId},email:{type:"string",required:!0,fieldName:e?.schema?.invitation?.fields?.email},role:{type:"string",required:!1,fieldName:e?.schema?.invitation?.fields?.role},status:{type:"string",required:!0,defaultValue:"pending",fieldName:e?.schema?.invitation?.fields?.status},expiresAt:{type:"date",required:!0,fieldName:e?.schema?.invitation?.fields?.expiresAt},inviterId:{type:"string",references:{model:"user",field:"id"},fieldName:e?.schema?.invitation?.fields?.inviterId,required:!0}}}},$Infer:{Organization:{},Invitation:{},Member:{},ActiveOrganization:{}}}};var jo=Yo(require("uncrypto"),1);function qr(e){return e.toString(2).padStart(8,"0")}function Mr(e){return[...e].map(t=>qr(t)).join("")}function St(e){return parseInt(Mr(e),2)}function Hr(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,o=t%8,i=new Uint8Array(Math.ceil(t/8));jo.default.getRandomValues(i),o!==0&&(i[0]&=(1<<o)-1);let r=St(i);for(;r>=e;)jo.default.getRandomValues(i),o!==0&&(i[0]&=(1<<o)-1),r=St(i);return r}function _(e,t){let o="";for(let i=0;i<e;i++)o+=t[Hr(t.length)];return o}function F(...e){let t=new Set(e),o="";for(let i of t)i==="a-z"?o+="abcdefghijklmnopqrstuvwxyz":i==="A-Z"?o+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":i==="0-9"?o+="0123456789":o+=i;return o}var We=require("zod");var Bo=require("@noble/ciphers/chacha"),xe=require("@noble/ciphers/utils"),No=require("@noble/ciphers/webcrypto"),Lo=require("oslo/crypto"),zo=Yo(require("uncrypto"),1);var Dt=require("oslo/encoding");var Qr=require("@noble/hashes/scrypt"),$r=require("uncrypto");async function $e(e,t){let o=new TextEncoder,i={name:"HMAC",hash:"SHA-256"},r=await zo.default.subtle.importKey("raw",o.encode(e),i,!1,["sign","verify"]),n=await zo.default.subtle.sign(i.name,r,o.encode(t));return btoa(String.fromCharCode(...new Uint8Array(n)))}var ue=async({key:e,data:t})=>{let o=await(0,Lo.sha256)(new TextEncoder().encode(e)),i=(0,xe.utf8ToBytes)(t),r=(0,No.managedNonce)(Bo.xchacha20poly1305)(new Uint8Array(o));return(0,xe.bytesToHex)(r.encrypt(i))},fe=async({key:e,data:t})=>{let o=await(0,Lo.sha256)(new TextEncoder().encode(e)),i=(0,xe.hexToBytes)(t),r=(0,No.managedNonce)(Bo.xchacha20poly1305)(new Uint8Array(o));return new TextDecoder().decode(r.decrypt(i))};var Ae=require("zod");var je=require("better-call");var go="two_factor";var mo="trust_device";var _o=require("zod");var be=P({body:_o.z.object({trustDevice:_o.z.boolean().optional()})},async e=>{let t=await U(e);if(!t){let o=e.context.createAuthCookie(go),i=await e.getSignedCookie(o.name,e.context.secret);if(!i)throw new je.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let r=await e.context.internalAdapter.findUserById(i);if(!r)throw new je.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let n=await e.context.internalAdapter.createSession(i,e.request);if(!n)throw new je.APIError("INTERNAL_SERVER_ERROR",{message:"failed to create session"});return{valid:async()=>{if(await m(e,{session:n,user:r}),e.body.trustDevice){let a=e.context.createAuthCookie(mo,{maxAge:2592e3}),s=await $e(e.context.secret,`${r.id}!${n.token}`);await e.setSignedCookie(a.name,`${s}!${n.token}`,e.context.secret,a.attributes)}return e.json({session:n,user:r})},invalid:async()=>{throw new je.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:{id:n.token,userId:n.userId,expiresAt:n.expiresAt,user:r}}}return{valid:async()=>e.json({session:t,user:t.user}),invalid:async()=>{throw new je.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:t}});var ze=require("better-call");function Zr(e){return Array.from({length:e?.amount??10}).fill(null).map(()=>_(e?.length??10,F("a-z","0-9"))).map(t=>`${t.slice(0,5)}-${t.slice(5)}`)}async function Fo(e,t){let o=e,i=t?.customBackupCodesGenerate?t.customBackupCodesGenerate():Zr(),r=await ue({data:JSON.stringify(i),key:o});return{backupCodes:i,encryptedBackupCodes:r}}async function Gr(e,t){let o=await xt(e.backupCodes,t);return o?{status:o.includes(e.code),updated:o.filter(i=>i!==e.code)}:{status:!1,updated:null}}async function xt(e,t){let o=Buffer.from(await fe({key:t,data:e})).toString("utf-8"),i=JSON.parse(o),r=Ae.z.array(Ae.z.string()).safeParse(i);return r.success?r.data:null}var jt=(e,t)=>({id:"backup_code",endpoints:{verifyBackupCode:c("/two-factor/verify-backup-code",{method:"POST",body:Ae.z.object({code:Ae.z.string(),disableSession:Ae.z.boolean().optional()}),use:[be]},async o=>{let i=o.context.session.user,r=await o.context.adapter.findOne({model:t,where:[{field:"userId",value:i.id}]});if(!r)throw new ze.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let n=await Gr({backupCodes:r.backupCodes,code:o.body.code},o.context.secret);if(!n.status)throw new ze.APIError("UNAUTHORIZED",{message:"Invalid backup code"});let a=await ue({key:o.context.secret,data:JSON.stringify(n.updated)});return await o.context.adapter.update({model:t,update:{backupCodes:a},where:[{field:"userId",value:i.id}]}),o.body.disableSession||await m(o,{session:o.context.session.session,user:i}),o.json({user:i,session:o.context.session})}),generateBackupCodes:c("/two-factor/generate-backup-codes",{method:"POST",body:Ae.z.object({password:Ae.z.string()}),use:[v]},async o=>{let i=o.context.session.user;if(!i.twoFactorEnabled)throw new ze.APIError("BAD_REQUEST",{message:"Two factor isn't enabled"});await o.context.password.checkPassword(i.id,o);let r=await Fo(o.context.secret,e);return await o.context.adapter.update({model:t,update:{backupCodes:r.encryptedBackupCodes},where:[{field:"userId",value:o.context.session.user.id}]}),o.json({status:!0,backupCodes:r.backupCodes})}),viewBackupCodes:c("/two-factor/view-backup-codes",{method:"GET",body:Ae.z.object({userId:Ae.z.string()}),metadata:{SERVER_ONLY:!0}},async o=>{let i=await o.context.adapter.findOne({model:t,where:[{field:"userId",value:o.body.userId}]});if(!i)throw new ze.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let r=await xt(i.backupCodes,o.context.secret);if(!r)throw new ze.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});return o.json({status:!0,backupCodes:r})})}});var Be=require("better-call"),Vo=require("zod");var zt=require("oslo");var Bt=(e,t)=>{let o={...e,digits:e?.digits||6,period:new zt.TimeSpan(e?.period||3,"m")},i=c("/two-factor/send-otp",{method:"POST",use:[be],metadata:{openapi:{summary:"Send two factor OTP",description:"Send two factor OTP to the user",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async n=>{if(!e||!e.sendOTP)throw n.context.logger.error("send otp isn't configured. Please configure the send otp function on otp options."),new Be.APIError("BAD_REQUEST",{message:"otp isn't configured"});let a=n.context.session.user;if(!await n.context.adapter.findOne({model:t,where:[{field:"userId",value:a.id}]}))throw new Be.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});let d=_(o.digits,F("0-9"));return await n.context.internalAdapter.createVerificationValue({value:d,identifier:`2fa-otp-${a.id}`,expiresAt:new Date(Date.now()+o.period.milliseconds())}),await e.sendOTP({user:a,otp:d},n.request),n.json({status:!0})}),r=c("/two-factor/verify-otp",{method:"POST",body:Vo.z.object({code:Vo.z.string({description:"The otp code to verify"})}),use:[be],metadata:{openapi:{summary:"Verify two factor OTP",description:"Verify two factor OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async n=>{let a=n.context.session.user;if(!a.twoFactorEnabled)throw new Be.APIError("BAD_REQUEST",{message:"two factor isn't enabled"});if(!await n.context.adapter.findOne({model:t,where:[{field:"userId",value:a.id}]}))throw new Be.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});let d=await n.context.internalAdapter.findVerificationValue(`2fa-otp-${a.id}`);if(!d||d.expiresAt<new Date)throw new Be.APIError("BAD_REQUEST",{message:"OTP has expired"});return d.value===n.body.code?n.context.valid():n.context.invalid()});return{id:"otp",endpoints:{sendTwoFactorOTP:i,verifyTwoFactorOTP:r}}};var ve=require("better-call"),Nt=require("oslo"),Ge=require("oslo/otp"),Ze=require("zod");var Lt=(e,t)=>{let o={...e,digits:e?.digits||6,period:new Nt.TimeSpan(e?.period||30,"s")},i=c("/totp/generate",{method:"POST",use:[v],metadata:{openapi:{summary:"Generate TOTP code",description:"Use this endpoint to generate a TOTP code",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{code:{type:"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 ve.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 ve.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return{code:await new Ge.TOTPController(o).generate(Buffer.from(d.secret))}}),r=c("/two-factor/get-totp-uri",{method:"POST",use:[v],body:Ze.z.object({password:Ze.z.string({description:"User password"})}),metadata:{openapi:{summary:"Get TOTP URI",description:"Use this endpoint to get the TOTP URI",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{totpURI:{type:"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 ve.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 ve.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return await a.context.password.checkPassword(s.id,a),{totpURI:(0,Ge.createTOTPKeyURI)(e.issuer||a.context.appName,s.email,Buffer.from(d.secret),o)}}),n=c("/two-factor/verify-totp",{method:"POST",body:Ze.z.object({code:Ze.z.string({description:"The otp code to verify"})}),use:[be],metadata:{openapi:{summary:"Verify two factor TOTP",description:"Verify two factor TOTP",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},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 ve.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 ve.APIError("BAD_REQUEST",{message:"totp isn't enabled"});let A=new Ge.TOTPController(o),K=await fe({key:a.context.secret,data:d.secret}),u=Buffer.from(K);if(!await A.verify(a.body.code,u))return a.context.invalid();if(!s.twoFactorEnabled){let l=await a.context.internalAdapter.updateUser(s.id,{twoFactorEnabled:!0}),h=await a.context.internalAdapter.createSession(s.id,a.request,!1,a.context.session.session).catch(k=>{throw console.log(k),k});await a.context.internalAdapter.deleteSession(a.context.session.session.token),await m(a,{session:h,user:l})}return a.context.valid()});return{id:"totp",endpoints:{generateTOTP:i,getTOTPURI:r,verifyTOTP:n}}};var Wr=require("better-call");async function qo(e,t){let i=(await e.context.internalAdapter.findAccounts(t.userId))?.find(a=>a.providerId==="credential"),r=i?.password;return!i||!r?!1:await e.context.password.verify({hash:r,password:t.password})}var Mo=require("better-call"),Vt=require("oslo/otp"),qt=require("oslo");var _t=require("better-call"),Ne=async e=>{let t=e.context.returned;return t?t instanceof Response?t.status!==200?null:await t.clone().json():t instanceof _t.APIError?null:t:null};var Ft={user:{fields:{twoFactorEnabled:{type:"boolean",required:!1,defaultValue:!1,input:!1}}},twoFactor:{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"}}}}};var Jr=e=>({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?.onTwoFactorRedirect&&await e.onTwoFactorRedirect()}}}]});var Xr=e=>{let t={twoFactorTable:"twoFactor"},o=Lt({issuer:e?.issuer,...e?.totpOptions},t.twoFactorTable),i=jt({...e?.backupCodeOptions},t.twoFactorTable),r=Bt({...e?.otpOptions},t.twoFactorTable);return{id:"two-factor",endpoints:{...o.endpoints,...r.endpoints,...i.endpoints,enableTwoFactor:c("/two-factor/enable",{method:"POST",body:We.z.object({password:We.z.string({description:"User password"}).min(8)}),use:[v],metadata:{openapi:{summary:"Enable two factor authentication",description:"Use this endpoint to enable two factor authentication. This will generate a TOTP URI and backup codes. Once the user verifies the TOTP URI, the two factor authentication will be enabled.",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{totpURI:{type:"string",description:"TOTP URI"},backupCodes:{type:"array",items:{type:"string"},description:"Backup codes"}}}}}}}}}},async n=>{let a=n.context.session.user,{password:s}=n.body;if(!await qo(n,{password:s,userId:a.id}))throw new Mo.APIError("BAD_REQUEST",{message:"Invalid password"});let A=_(16,F("a-z","0-9","-")),K=await ue({key:n.context.secret,data:A}),u=await Fo(n.context.secret,e?.backupCodeOptions);if(e?.skipVerificationOnEnable){let l=await n.context.internalAdapter.updateUser(a.id,{twoFactorEnabled:!0}),h=await n.context.internalAdapter.createSession(l.id,n.request,!1,n.context.session.session);await m(n,{session:h,user:a}),await n.context.internalAdapter.deleteSession(n.context.session.session.token)}await n.context.adapter.deleteMany({model:t.twoFactorTable,where:[{field:"userId",value:a.id}]}),await n.context.adapter.create({model:t.twoFactorTable,data:{secret:K,backupCodes:u.encryptedBackupCodes,userId:a.id}});let p=(0,Vt.createTOTPKeyURI)(e?.issuer||"BetterAuth",a.email,Buffer.from(A),{digits:e?.totpOptions?.digits||6,period:new qt.TimeSpan(e?.totpOptions?.period||30,"s")});return n.json({totpURI:p,backupCodes:u.backupCodes})}),disableTwoFactor:c("/two-factor/disable",{method:"POST",body:We.z.object({password:We.z.string({description:"User password"}).min(8)}),use:[v],metadata:{openapi:{summary:"Disable two factor authentication",description:"Use this endpoint to disable two factor authentication.",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async n=>{let a=n.context.session.user,{password:s}=n.body;if(!await qo(n,{password:s,userId:a.id}))throw new Mo.APIError("BAD_REQUEST",{message:"Invalid password"});await n.context.internalAdapter.updateUser(a.id,{twoFactorEnabled:!1}),await n.context.adapter.delete({model:t.twoFactorTable,where:[{field:"userId",value:a.id}]});let A=await n.context.internalAdapter.createSession(a.id,n.request,!1,n.context.session.session);return await m(n,{session:A,user:a}),await n.context.internalAdapter.deleteSession(n.context.session.session.token),n.json({status:!0})})},options:e,hooks:{after:[{matcher(n){return n.path==="/sign-in/email"||n.path==="/sign-in/username"},handler:P(async n=>{let a=await Ne(n);if(!a||!a.user.twoFactorEnabled)return;let s=n.context.createAuthCookie(mo),d=await n.getSignedCookie(s.name,n.context.secret);if(d){let[K,u]=d.split("!"),p=await $e(n.context.secret,`${a.user.id}!${u}`);if(K===p){let l=await $e(n.context.secret,`${a.user.id}!${a.session.token}`);await n.setSignedCookie(s.name,`${l}!${a.session.token}`,n.context.secret,s.attributes);return}}Q(n),await n.context.internalAdapter.deleteSession(a.session.token);let A=n.context.createAuthCookie(go,{maxAge:60*10});return await n.setSignedCookie(A.name,a.user.id,n.context.secret,A.attributes),n.json({twoFactorRedirect:!0})})}]},schema:ie(Ft,e?.schema),rateLimit:[{pathMatcher(n){return n.startsWith("/two-factor/")},window:10,max:3}]}};var he=require("@simplewebauthn/server"),Z=require("better-call");var Y=require("zod");var Le=require("@simplewebauthn/browser");var en=require("@better-fetch/fetch");var bK=require("nanostores");var cK=require("@better-fetch/fetch");var Yr=require("nanostores");var pK=require("@better-fetch/fetch"),fo=require("nanostores"),Ho=(e,t,o,i)=>{let r=(0,fo.atom)({data:null,error:null,isPending:!0,isRefetching:!1}),n=()=>{let s=typeof i=="function"?i({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):i;return o(t,{...s,async onSuccess(d){r.set({data:d.data,error:null,isPending:!1,isRefetching:!1}),await s?.onSuccess?.(d)},async onError(d){r.set({error:d.error,data:null,isPending:!1,isRefetching:!1}),await s?.onError?.(d)},async onRequest(d){let A=r.get();r.set({isPending:A.data===null,data:A.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?n():(0,fo.onMount)(r,()=>(n(),a=!0,()=>{r.off(),s.off()}))});return r};var Mt=require("nanostores"),Ht=(e,{$listPasskeys:t})=>({signIn:{passkey:async(r,n)=>{let a=await e("/passkey/generate-authenticate-options",{method:"POST",body:{email:r?.email}});if(!a.data)return a;try{let s=await(0,Le.startAuthentication)(a.data,r?.autoFill||!1),d=await e("/passkey/verify-authentication",{body:{response:s},...r?.fetchOptions,...n,method:"POST"});if(!d.data)return d}catch{return{data:null,error:{message:"auth cancelled",status:400,statusText:"BAD_REQUEST"}}}}},passkey:{addPasskey:async(r,n)=>{let a=await e("/passkey/generate-register-options",{method:"GET"});if(!a.data)return a;try{let s=await(0,Le.startRegistration)(a.data),d=await e("/passkey/verify-registration",{...r?.fetchOptions,...n,body:{response:s,name:r?.name},method:"POST"});if(!d.data)return d;t.set(Math.random())}catch(s){return s instanceof Le.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:{}}),on=()=>{let e=(0,Mt.atom)();return{id:"passkey",$InferServerPlugin:{},getActions:t=>Ht(t,{$listPasskeys:e}),getAtoms(t){return{listPasskeys:Ho(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"||t==="/passkey/update-passkey"},signal:"_listPasskeys"}]}};var tn=e=>{let t=ne.BETTER_AUTH_URL,o=e?.rpID||t?.replace("http://","").replace("https://","").split(":")[0]||"localhost";if(!o)throw new ee("passkey rpID not found. Please provide a rpID in the options or set the BETTER_AUTH_URL environment variable.");let i={origin:null,...e,rpID:o,advanced:{webAuthnChallengeCookie:"better-auth-passkey",...e?.advanced}},r=new Date(Date.now()+1e3*60*5),n=new Date,a=Math.floor((r.getTime()-n.getTime())/1e3);return{id:"passkey",endpoints:{generatePasskeyRegistrationOptions:c("/passkey/generate-register-options",{method:"GET",use:[He],metadata:{client:!1,openapi:{description:"Generate registration options for a new passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{challenge:{type:"string"},rp:{type:"object",properties:{name:{type:"string"},id:{type:"string"}}},user:{type:"object",properties:{id:{type:"string"},name:{type:"string"},displayName:{type:"string"}}},pubKeyCredParams:{type:"array",items:{type:"object",properties:{type:{type:"string"},alg:{type:"number"}}}},timeout:{type:"number"},excludeCredentials:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string"},transports:{type:"array",items:{type:"string"}}}}},authenticatorSelection:{type:"object",properties:{authenticatorAttachment:{type:"string"},requireResidentKey:{type:"boolean"},userVerification:{type:"string"}}},attestation:{type:"string"},extensions:{type:"object"}}}}}}}}}},async s=>{let d=s.context.session,A=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}),K=new Uint8Array(Buffer.from(_(32,F("a-z","0-9")))),u;u=await(0,he.generateRegistrationOptions)({rpName:i.rpName||s.context.appName,rpID:i.rpID,userID:K,userName:d.user.email||d.user.id,attestationType:"none",excludeCredentials:A.map(l=>({id:l.id,transports:l.transports?.split(",")})),authenticatorSelection:{residentKey:"preferred",userVerification:"preferred",authenticatorAttachment:"platform"}});let p=V(32);return await s.setSignedCookie(i.advanced.webAuthnChallengeCookie,p,s.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:a}),await s.context.internalAdapter.createVerificationValue({identifier:p,value:JSON.stringify({expectedChallenge:u.challenge,userData:{id:d.user.id}}),expiresAt:r}),s.json(u,{status:200})}),generatePasskeyAuthenticationOptions:c("/passkey/generate-authenticate-options",{method:"POST",body:Y.z.object({email:Y.z.string({description:"The email address of the user"}).optional()}).optional(),metadata:{openapi:{description:"Generate authentication options for a passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{challenge:{type:"string"},rp:{type:"object",properties:{name:{type:"string"},id:{type:"string"}}},user:{type:"object",properties:{id:{type:"string"},name:{type:"string"},displayName:{type:"string"}}},timeout:{type:"number"},allowCredentials:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string"},transports:{type:"array",items:{type:"string"}}}}},userVerification:{type:"string"},authenticatorSelection:{type:"object",properties:{authenticatorAttachment:{type:"string"},requireResidentKey:{type:"boolean"},userVerification:{type:"string"}}},extensions:{type:"object"}}}}}}}}}},async s=>{let d=await U(s),A=[];d&&(A=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}));let K=await(0,he.generateAuthenticationOptions)({rpID:i.rpID,userVerification:"preferred",...A.length?{allowCredentials:A.map(l=>({id:l.id,transports:l.transports?.split(",")}))}:{}}),u={expectedChallenge:K.challenge,userData:{id:d?.user.id||""}},p=V(32);return await s.setSignedCookie(i.advanced.webAuthnChallengeCookie,p,s.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:a}),await s.context.internalAdapter.createVerificationValue({identifier:p,value:JSON.stringify(u),expiresAt:r}),s.json(K,{status:200})}),verifyPasskeyRegistration:c("/passkey/verify-registration",{method:"POST",body:Y.z.object({response:Y.z.any({description:"The response from the authenticator"}),name:Y.z.string({description:"Name of the passkey"}).optional()}),use:[He],metadata:{openapi:{description:"Verify registration of a new passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{$ref:"#/components/schemas/Passkey"}}}},400:{description:"Bad request"}}}}},async s=>{let d=e?.origin||s.headers?.get("origin")||"";if(!d)return s.json(null,{status:400});let A=s.body.response,K=await s.getSignedCookie(i.advanced.webAuthnChallengeCookie,s.context.secret);if(!K)throw new Z.APIError("BAD_REQUEST",{message:"Challenge not found"});let u=await s.context.internalAdapter.findVerificationValue(K);if(!u)return s.json(null,{status:400});let{expectedChallenge:p,userData:l}=JSON.parse(u.value);if(l.id!==s.context.session.user.id)throw new Z.APIError("UNAUTHORIZED",{message:"You are not authorized to register this passkey"});try{let h=await(0,he.verifyRegistrationResponse)({response:A,expectedChallenge:p,expectedOrigin:d,expectedRPID:e?.rpID}),{verified:k,registrationInfo:f}=h;if(!k||!f)return s.json(null,{status:400});let{credentialID:g,credentialPublicKey:b,counter:T,credentialDeviceType:N,credentialBackedUp:eo}=f,ir=Buffer.from(b).toString("base64"),tr={name:s.body.name,userId:l.id,webauthnUserID:s.context.generateId({model:"passkey"}),id:g,publicKey:ir,counter:T,deviceType:N,transports:A.response.transports.join(","),backedUp:eo,createdAt:new Date},rr=await s.context.adapter.create({model:"passkey",data:tr});return s.json(rr,{status:200})}catch(h){throw console.log(h),new Z.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to verify registration"})}}),verifyPasskeyAuthentication:c("/passkey/verify-authentication",{method:"POST",body:Y.z.object({response:Y.z.any()}),metadata:{openapi:{description:"Verify authentication of a passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async s=>{let d=e?.origin||s.headers?.get("origin")||"";if(!d)throw new Z.APIError("BAD_REQUEST",{message:"origin missing"});let A=s.body.response,K=await s.getSignedCookie(i.advanced.webAuthnChallengeCookie,s.context.secret);if(!K)throw new Z.APIError("BAD_REQUEST",{message:"Challenge not found"});let u=await s.context.internalAdapter.findVerificationValue(K);if(!u)throw new Z.APIError("BAD_REQUEST",{message:"Challenge not found"});let{expectedChallenge:p}=JSON.parse(u.value),l=await s.context.adapter.findOne({model:"passkey",where:[{field:"id",value:A.id}]});if(!l)throw new Z.APIError("UNAUTHORIZED",{message:"Passkey not found"});try{let h=await(0,he.verifyAuthenticationResponse)({response:A,expectedChallenge:p,expectedOrigin:d,expectedRPID:i.rpID,authenticator:{credentialID:l.id,credentialPublicKey:new Uint8Array(Buffer.from(l.publicKey,"base64")),counter:l.counter,transports:l.transports?.split(",")},requireUserVerification:!1}),{verified:k}=h;if(!k)throw new Z.APIError("UNAUTHORIZED",{message:"Authentication failed"});await s.context.adapter.update({model:"passkey",where:[{field:"id",value:l.id}],update:{counter:h.authenticationInfo.newCounter}});let f=await s.context.internalAdapter.createSession(l.userId,s.request);if(!f)throw new Z.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});let g=await s.context.internalAdapter.findUserById(l.userId);if(!g)throw new Z.APIError("INTERNAL_SERVER_ERROR",{message:"User not found"});return await m(s,{session:f,user:g}),s.json({session:f},{status:200})}catch(h){throw s.context.logger.error("Failed to verify authentication",h),new Z.APIError("BAD_REQUEST",{message:"Failed to verify authentication"})}}),listPasskeys:c("/passkey/list-user-passkeys",{method:"GET",use:[v]},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:[v]},async s=>(await s.context.adapter.delete({model:"passkey",where:[{field:"id",value:s.body.id}]}),s.json(null,{status:200}))),updatePasskey:c("/passkey/update-passkey",{method:"POST",body:Y.z.object({id:Y.z.string(),name:Y.z.string()}),use:[v]},async s=>{let d=await s.context.adapter.findOne({model:"passkey",where:[{field:"id",value:s.body.id}]});if(!d)throw new Z.APIError("NOT_FOUND",{message:"Passkey not found"});if(d.userId!==s.context.session.user.id)throw new Z.APIError("UNAUTHORIZED",{message:"You are not authorized to update this passkey"});let A=await s.context.adapter.update({model:"passkey",where:[{field:"id",value:s.body.id}],update:{name:s.body.name}});if(!A)throw new Z.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to update passkey"});return s.json({passkey:A},{status:200})})},schema:ie(rn,e?.schema)}},rn={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",required:!1}}}};var Je=require("zod");var _e=require("better-call");var Qo=()=>({id:"username",endpoints:{signInUsername:c("/sign-in/username",{method:"POST",body:Je.z.object({username:Je.z.string({description:"The username of the user"}),password:Je.z.string({description:"The password of the user"}),rememberMe:Je.z.boolean({description:"Remember the user session"}).optional()}),metadata:{openapi:{summary:"Sign in with username",description:"Sign in with username",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async e=>{let t=await e.context.adapter.findOne({model:"user",where:[{field:"username",value:e.body.username.toLowerCase()}]});if(!t)throw await e.context.password.hash(e.body.password),e.context.logger.error("User not found",{username:Qo}),new _e.APIError("UNAUTHORIZED",{message:"Invalid username or password"});if(!t.emailVerified&&e.context.options.emailAndPassword?.requireEmailVerification)throw await Oo(e,t),new _e.APIError("UNAUTHORIZED",{message:"Email not verified"});let o=await e.context.adapter.findOne({model:"account",where:[{field:"userId",value:t.id},{field:"providerId",value:"credential"}]});if(!o)throw new _e.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let i=o?.password;if(!i)throw e.context.logger.error("Password not found",{username:Qo}),new _e.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify({hash:i,password:e.body.password}))throw e.context.logger.error("Invalid password"),new _e.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let n=await e.context.internalAdapter.createSession(t.id,e.request,e.body.rememberMe===!1);return n?(await m(e,{session:n,user:t},e.body.rememberMe===!1),e.json({user:t,session:n})):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 Qt=require("better-call"),nn=()=>({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 o="";return t.includes(".")?o=t:o=await(0,Qt.serializeSigned)("",t,e.context.secret),e.request&&e.request.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${o.replace("=","")}`),e.headers&&e.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${o.replace("=","")}`),{context:e}}}]}});var ke=require("zod");var $t=require("better-call");var sn=e=>({id:"magic-link",endpoints:{signInMagicLink:c("/sign-in/magic-link",{method:"POST",requireHeaders:!0,body:ke.z.object({email:ke.z.string({description:"Email address to send the magic link"}).email(),callbackURL:ke.z.string({description:"URL to redirect after magic link verification"}).optional()}),metadata:{openapi:{description:"Sign in with magic link",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async t=>{let{email:o}=t.body;if(e.disableSignUp&&!await t.context.internalAdapter.findUserByEmail(o))throw new $t.APIError("BAD_REQUEST",{message:"User not found"});let i=_(32,F("a-z","A-Z"));await t.context.internalAdapter.createVerificationValue({identifier:i,value:o,expiresAt:new Date(Date.now()+(e.expiresIn||60*5)*1e3)});let r=`${t.context.baseURL}/magic-link/verify?token=${i}&callbackURL=${t.body.callbackURL||"/"}`;return await e.sendMagicLink({email:o,url:r,token:i},t.request),t.json({status:!0})}),magicLinkVerify:c("/magic-link/verify",{method:"GET",query:ke.z.object({token:ke.z.string({description:"Verification token"}),callbackURL:ke.z.string({description:"URL to redirect after magic link verification, if not provided will return session"}).optional()}),requireHeaders:!0,metadata:{openapi:{description:"Verify magic link",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async t=>{let{token:o,callbackURL:i}=t.query,r=i?.startsWith("http")?i:i?`${t.context.options.baseURL}${i}`:t.context.options.baseURL,n=await t.context.internalAdapter.findVerificationValue(o);if(!n)throw t.redirect(`${r}?error=INVALID_TOKEN`);if(n.expiresAt<new Date)throw await t.context.internalAdapter.deleteVerificationValue(n.id),t.redirect(`${r}?error=EXPIRED_TOKEN`);await t.context.internalAdapter.deleteVerificationValue(n.id);let a=n.value,s=await t.context.internalAdapter.findUserByEmail(a),d=s?.user.id||"";if(!s){if(e.disableSignUp)throw t.redirect(`${r}?error=USER_NOT_FOUND`);if(d=(await t.context.internalAdapter.createUser({email:a,emailVerified:!0,name:a})).id,!d)throw t.redirect(`${r}?error=USER_NOT_CREATED`)}let A=await t.context.internalAdapter.createSession(d,t.headers);if(!A)throw t.redirect(`${r}?error=SESSION_NOT_CREATED`);if(await m(t,{session:A,user:s?.user}),!i)return t.json({session:A,user:s?.user});throw t.redirect(i)})},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 re=require("zod");var H=require("better-call");function an(e){return _(e,F("0-9"))}var dn=e=>{let t={expiresIn:e?.expiresIn||300,otpLength:e?.otpLength||6,...e,phoneNumber:"phoneNumber",phoneNumberVerified:"phoneNumberVerified",code:"code",createdAt:"createdAt"};return{id:"phone-number",endpoints:{signInPhoneNumber:c("/sign-in/phone-number",{method:"POST",body:re.z.object({phoneNumber:re.z.string({description:"Phone number to sign in"}),password:re.z.string({description:"Password to use for sign in"}),rememberMe:re.z.boolean({description:"Remember the session"}).optional()}),metadata:{openapi:{summary:"Sign in with phone number",description:"Use this endpoint to sign in with phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}},400:{description:"Invalid phone number or password"}}}}},async o=>{let{password:i,phoneNumber:r}=o.body;if(t.phoneNumberValidator&&!await t.phoneNumberValidator(o.body.phoneNumber))throw new H.APIError("BAD_REQUEST",{message:"Invalid phone number!"});let n=await o.context.adapter.findOne({model:"user",where:[{field:"phoneNumber",value:r}]});if(!n)throw new H.APIError("UNAUTHORIZED",{message:"Invalid phone number or password"});let s=(await o.context.internalAdapter.findAccountByUserId(n.id)).find(u=>u.providerId==="credential");if(!s)throw o.context.logger.error("Credential account not found",{phoneNumber:r}),new H.APIError("UNAUTHORIZED",{message:"Invalid password or password"});let d=s?.password;if(!d)throw o.context.logger.error("Password not found",{phoneNumber:r}),new H.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await o.context.password.verify({hash:d,password:i}))throw o.context.logger.error("Invalid password"),new H.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let K=await o.context.internalAdapter.createSession(n.id,o.headers,o.body.rememberMe===!1);if(!K)throw o.context.logger.error("Failed to create session"),new H.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await m(o,{session:K,user:n},o.body.rememberMe===!1),o.json({user:n,session:K})}),sendPhoneNumberOTP:c("/phone-number/send-otp",{method:"POST",body:re.z.object({phoneNumber:re.z.string({description:"Phone number to send OTP"})}),metadata:{openapi:{summary:"Send OTP to phone number",description:"Use this endpoint to send OTP to phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async o=>{if(!e?.sendOTP)throw o.context.logger.warn("sendOTP not implemented"),new H.APIError("NOT_IMPLEMENTED",{message:"sendOTP not implemented"});if(t.phoneNumberValidator&&!await t.phoneNumberValidator(o.body.phoneNumber))throw new H.APIError("BAD_REQUEST",{message:"Invalid phone number!"});let i=an(t.otpLength);return await o.context.internalAdapter.createVerificationValue({value:i,identifier:o.body.phoneNumber,expiresAt:R(t.expiresIn,"sec")}),await e.sendOTP({phoneNumber:o.body.phoneNumber,code:i},o.request),o.json({code:i},{body:{message:"Code sent"}})}),verifyPhoneNumber:c("/phone-number/verify",{method:"POST",body:re.z.object({phoneNumber:re.z.string({description:"Phone number to verify"}),code:re.z.string({description:"OTP code"}),disableSession:re.z.boolean({description:"Disable session creation after verification"}).optional(),updatePhoneNumber:re.z.boolean({description:"Check if there is a session and update the phone number"}).optional()}),metadata:{openapi:{summary:"Verify phone number",description:"Use this endpoint to verify phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}},400:{description:"Invalid OTP"}}}}},async o=>{let i=await o.context.internalAdapter.findVerificationValue(o.body.phoneNumber);if(!i||i.expiresAt<new Date)throw i&&i.expiresAt<new Date?(await o.context.internalAdapter.deleteVerificationValue(i.id),new H.APIError("BAD_REQUEST",{message:"OTP expired"})):new H.APIError("BAD_REQUEST",{message:"OTP not found"});if(i.value!==o.body.code)throw new H.APIError("BAD_REQUEST",{message:"Invalid OTP"});if(await o.context.internalAdapter.deleteVerificationValue(i.id),o.body.updatePhoneNumber){let n=await U(o);if(!n)throw new H.APIError("UNAUTHORIZED",{message:"Session not found"});let a=await o.context.internalAdapter.updateUser(n.user.id,{[t.phoneNumber]:o.body.phoneNumber,[t.phoneNumberVerified]:!0});return o.json({user:a,session:n.session})}let r=await o.context.adapter.findOne({model:"user",where:[{value:o.body.phoneNumber,field:t.phoneNumber}]});if(await e?.callbackOnVerification?.({phoneNumber:o.body.phoneNumber,user:r},o.request),r)r=await o.context.internalAdapter.updateUser(r.id,{[t.phoneNumberVerified]:!0});else if(e?.signUpOnVerification){if(r=await o.context.internalAdapter.createUser({email:e.signUpOnVerification.getTempEmail(o.body.phoneNumber),name:e.signUpOnVerification.getTempName?e.signUpOnVerification.getTempName(o.body.phoneNumber):o.body.phoneNumber,[t.phoneNumber]:o.body.phoneNumber,[t.phoneNumberVerified]:!0}),!r)throw new H.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"})}else return o.json(null);if(!r)throw new H.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to update user"});if(!o.body.disableSession){let n=await o.context.internalAdapter.createSession(r.id,o.request);if(!n)throw new H.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await m(o,{session:n,user:r}),o.json({user:r,session:n})}return o.json({user:r,session:null})})},schema:ie(An,e?.schema)}},An={user:{fields:{phoneNumber:{type:"string",required:!1,unique:!0,returned:!0},phoneNumberVerified:{type:"boolean",required:!1,returned:!0,input:!1}}}};var mp=require("zod");var cn={user:{fields:{isAnonymous:{type:"boolean",required:!1}}}},Kn=e=>({id:"anonymous",endpoints:{signInAnonymous:c("/sign-in/anonymous",{method:"POST",metadata:{openapi:{description:"Sign in anonymously",responses:{200:{description:"Sign in anonymously",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async t=>{let{emailDomainName:o=Ie(t.context.baseURL)}=e||{},i=t.context.generateId({model:"user"}),r=`temp-${i}@${o}`,n=await t.context.internalAdapter.createUser({id:i,email:r,emailVerified:!1,isAnonymous:!0,name:"Anonymous",createdAt:new Date,updatedAt:new Date});if(!n)return t.json(null,{status:500,body:{message:"Failed to create user",status:500}});let a=await t.context.internalAdapter.createSession(n.id,t.request);return a?(await m(t,{session:a,user:n}),t.json({user:n,session:a})):t.json(null,{status:400,body:{message:"Could not create session"}})})},hooks:{after:[{matcher(t){return t.path?.startsWith("/sign-in")||t.path?.startsWith("/sign-up")},handler:P(async t=>{let i=t.responseHeader.get("set-cookie"),r=t.context.authCookies.sessionToken.name,n=ao(i||"").get(r)?.value.split(".")[0];if(!n)return;let a=await U(t);if(!(!a||!a.user.isAnonymous)){if(t.path==="/sign-in/anonymous")throw new C.APIError("BAD_REQUEST",{message:"Anonymous users cannot sign in again anonymously"});if(e?.onLinkAccount){let s=await t.context.internalAdapter.findSession(n);if(!s)return;await e?.onLinkAccount?.({anonymousUser:a,newUser:s})}e?.disableDeleteAnonymousUser||await t.context.internalAdapter.deleteUser(a.user.id)}})}]},schema:ie(cn,e?.schema)});var y=require("zod");var pn=e=>{let t={defaultRole:"user",adminRole:"admin",...e},o=P(async i=>{let r=await U(i);if(!r?.session)throw new C.APIError("UNAUTHORIZED");let n=r.user;if(!n.role||(Array.isArray(t.adminRole)?!t.adminRole.includes(n.role):n.role!==t.adminRole))throw new C.APIError("FORBIDDEN",{message:"Only admins can access this endpoint"});return{session:{user:n,session:r.session}}});return{id:"admin",init(i){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 n=await i.internalAdapter.findUserById(r.userId);if(n.banned){if(n.banExpires&&n.banExpires.getTime()<Date.now()){await i.internalAdapter.updateUser(r.userId,{banned:!1,banReason:null,banExpires:null});return}return!1}}}}}}}},hooks:{after:[{matcher(i){return i.path==="/list-sessions"},handler:P(async i=>{let r=await Ne(i);if(!r)return;let n=r.filter(a=>!a.impersonatedBy);return i.json(n)})}]},endpoints:{setRole:c("/admin/set-role",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"}),role:y.z.string({description:"The role to set. `admin` or `user` by default"})}),use:[o],metadata:{openapi:{operationId:"setRole",summary:"Set the role of a user",description:"Set the role of a user",responses:{200:{description:"User role updated",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{let r=await i.context.internalAdapter.updateUser(i.body.userId,{role:i.body.role});return i.json({user:r})}),createUser:c("/admin/create-user",{method:"POST",body:y.z.object({email:y.z.string({description:"The email of the user"}),password:y.z.string({description:"The password of the user"}),name:y.z.string({description:"The name of the user"}),role:y.z.string({description:"The role of the user"}),data:y.z.optional(y.z.record(y.z.any(),{description:"Extra fields for the user. Including custom additional fields."}))}),use:[o],metadata:{openapi:{operationId:"createUser",summary:"Create a new user",description:"Create a new user",responses:{200:{description:"User created",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{if(await i.context.internalAdapter.findUserByEmail(i.body.email))throw new C.APIError("BAD_REQUEST",{message:"User already exists"});let n=await i.context.internalAdapter.createUser({email:i.body.email,name:i.body.name,role:i.body.role,...i.body.data});if(!n)throw new C.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"});let a=await i.context.password.hash(i.body.password);return await i.context.internalAdapter.linkAccount({accountId:n.id,providerId:"credential",password:a,userId:n.id}),i.json({user:n})}),listUsers:c("/admin/list-users",{method:"GET",use:[o],query:y.z.object({searchValue:y.z.string({description:"The value to search for"}).optional(),searchField:y.z.enum(["email","name"],{description:"The field to search in, defaults to email. Can be `email` or `name`"}).optional(),searchOperator:y.z.enum(["contains","starts_with","ends_with"],{description:"The operator to use for the search. Can be `contains`, `starts_with` or `ends_with`"}).optional(),limit:y.z.string({description:"The number of users to return"}).or(y.z.number()).optional(),offset:y.z.string({description:"The offset to start from"}).or(y.z.number()).optional(),sortBy:y.z.string({description:"The field to sort by"}).optional(),sortDirection:y.z.enum(["asc","desc"],{description:"The direction to sort by"}).optional(),filterField:y.z.string({description:"The field to filter by"}).optional(),filterValue:y.z.string({description:"The value to filter by"}).or(y.z.number()).or(y.z.boolean()).optional(),filterOperator:y.z.enum(["eq","ne","lt","lte","gt","gte"],{description:"The operator to use for the filter"}).optional()}),metadata:{openapi:{operationId:"listUsers",summary:"List users",description:"List users",responses:{200:{description:"List of users",content:{"application/json":{schema:{type:"object",properties:{users:{type:"array",items:{$ref:"#/components/schemas/User"}}}}}}}}}}},async i=>{let r=[];i.query?.searchValue&&r.push({field:i.query.searchField||"email",operator:i.query.searchOperator||"contains",value:i.query.searchValue}),i.query?.filterValue&&r.push({field:i.query.filterField||"email",operator:i.query.filterOperator||"eq",value:i.query.filterValue});try{let n=await i.context.internalAdapter.listUsers(Number(i.query?.limit)||void 0,Number(i.query?.offset)||void 0,i.query?.sortBy?{field:i.query.sortBy,direction:i.query.sortDirection||"asc"}:void 0,r.length?r:void 0);return i.json({users:n})}catch(n){return console.log(n),i.json({users:[]})}}),listUserSessions:c("/admin/list-user-sessions",{method:"POST",use:[o],body:y.z.object({userId:y.z.string({description:"The user id"})}),metadata:{openapi:{operationId:"listUserSessions",summary:"List user sessions",description:"List user sessions",responses:{200:{description:"List of user sessions",content:{"application/json":{schema:{type:"object",properties:{sessions:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}}}}}}}},async i=>({sessions:await i.context.internalAdapter.listSessions(i.body.userId)})),unbanUser:c("/admin/unban-user",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"unbanUser",summary:"Unban a user",description:"Unban a user",responses:{200:{description:"User unbanned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{let r=await i.context.internalAdapter.updateUser(i.body.userId,{banned:!1});return i.json({user:r})}),banUser:c("/admin/ban-user",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"}),banReason:y.z.string({description:"The reason for the ban"}).optional(),banExpiresIn:y.z.number({description:"The number of seconds until the ban expires"}).optional()}),use:[o],metadata:{openapi:{operationId:"banUser",summary:"Ban a user",description:"Ban a user",responses:{200:{description:"User banned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{if(i.body.userId===i.context.session.user.id)throw new C.APIError("BAD_REQUEST",{message:"You cannot ban yourself"});let r=await i.context.internalAdapter.updateUser(i.body.userId,{banned:!0,banReason:i.body.banReason||e?.defaultBanReason||"No reason",banExpires:i.body.banExpiresIn?R(i.body.banExpiresIn,"sec"):e?.defaultBanExpiresIn?R(e.defaultBanExpiresIn,"sec"):void 0});return await i.context.internalAdapter.deleteSessions(i.body.userId),i.json({user:r})}),impersonateUser:c("/admin/impersonate-user",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"impersonateUser",summary:"Impersonate a user",description:"Impersonate a user",responses:{200:{description:"Impersonation session created",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{let r=await i.context.internalAdapter.findUserById(i.body.userId);if(!r)throw new C.APIError("NOT_FOUND",{message:"User not found"});let n=await i.context.internalAdapter.createSession(r.id,void 0,!0,{impersonatedBy:i.context.session.user.id,expiresAt:e?.impersonationSessionDuration?R(e.impersonationSessionDuration,"sec"):R(60*60,"sec")});if(!n)throw new C.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await m(i,{session:n,user:r},!0),i.json({session:n,user:r})}),revokeUserSession:c("/admin/revoke-user-session",{method:"POST",body:y.z.object({sessionToken:y.z.string({description:"The session token"})}),use:[o],metadata:{openapi:{operationId:"revokeUserSession",summary:"Revoke a user session",description:"Revoke a user session",responses:{200:{description:"Session revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async i=>(await i.context.internalAdapter.deleteSession(i.body.sessionToken),i.json({success:!0}))),revokeUserSessions:c("/admin/revoke-user-sessions",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"revokeUserSessions",summary:"Revoke all user sessions",description:"Revoke all user sessions",responses:{200:{description:"Sessions revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async i=>(await i.context.internalAdapter.deleteSessions(i.body.userId),i.json({success:!0}))),removeUser:c("/admin/remove-user",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"removeUser",summary:"Remove a user",description:"Delete a user and all their sessions and accounts. Cannot be undone.",responses:{200:{description:"User removed",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async i=>(await i.context.internalAdapter.deleteUser(i.body.userId),i.json({success:!0})))},schema:ie(un,t.schema)}},un={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 se=require("zod"),Fe=require("better-call");var ho=require("@better-fetch/fetch");var Zt=require("oslo/jwt");async function ln(e,t,o){if(t==="oidc"&&e.idToken){let r=(0,Zt.parseJWT)(e.idToken);if(r?.payload)return{id:r.payload.sub,emailVerified:r.payload.email_verified,...r.payload}}if(!o)return null;let i=await(0,ho.betterFetch)(o,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});return{id:i.data?.sub,emailVerified:i.data?.email_verified,email:i.data?.email,...i.data}}var gn=e=>({id:"generic-oauth",endpoints:{signInWithOAuth2:c("/sign-in/oauth2",{method:"POST",query:se.z.object({currentURL:se.z.string({description:"Redirect to the current URL after sign in"}).optional()}).optional(),body:se.z.object({providerId:se.z.string({description:"The provider ID for the OAuth provider"}),callbackURL:se.z.string({description:"The URL to redirect to after sign in"}).optional(),errorCallbackURL:se.z.string({description:"The URL to redirect to if an error occurs"}).optional()}),metadata:{openapi:{description:"Sign in with OAuth2",responses:{200:{description:"Sign in with OAuth2",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}}}}}}}}}},async t=>{let{providerId:o}=t.body,i=e.config.find(N=>N.providerId===o);if(!i)throw new Fe.APIError("BAD_REQUEST",{message:`No config found for provider ${o}`});let{discoveryUrl:r,authorizationUrl:n,tokenUrl:a,clientId:s,clientSecret:d,scopes:A,redirectURI:K,responseType:u,pkce:p,prompt:l,accessType:h}=i,k=n,f=a;if(r){let N=await(0,ho.betterFetch)(r,{onError(eo){t.context.logger.error(eo.error.message,eo.error,{discoveryUrl:r})}});N.data&&(k=N.data.authorization_endpoint,f=N.data.token_endpoint)}if(!k||!f)throw new Fe.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let{state:g,codeVerifier:b}=await Ue(t),T=await S({id:o,options:{clientId:s,clientSecret:d,redirectURI:K},authorizationEndpoint:k,state:g,codeVerifier:p?b:void 0,scopes:A||[],redirectURI:`${t.context.baseURL}/oauth2/callback/${o}`});return u&&u!=="code"&&T.searchParams.set("response_type",u),l&&T.searchParams.set("prompt",l),h&&T.searchParams.set("access_type",h),t.json({url:T.toString(),redirect:!0})}),oAuth2Callback:c("/oauth2/callback/:providerId",{method:"GET",query:se.z.object({code:se.z.string({description:"The OAuth2 code"}).optional(),error:se.z.string({description:"The error message, if any"}).optional(),state:se.z.string({description:"The state parameter from the OAuth2 request"})}),metadata:{openapi:{description:"OAuth2 callback",responses:{200:{description:"OAuth2 callback",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"}}}}}}}}}},async t=>{if(t.query.error||!t.query.code)throw t.redirect(`${t.context.baseURL}?error=${t.query.error||"oAuth_code_missing"}`);let o=e.config.find(g=>g.providerId===t.params.providerId);if(!o)throw new Fe.APIError("BAD_REQUEST",{message:`No config found for provider ${t.params.providerId}`});let i,r=await co(t),{callbackURL:n,codeVerifier:a,errorURL:s}=r,d=t.query.code,A=o.tokenUrl,K=o.userInfoUrl;if(o.discoveryUrl){let g=await(0,ho.betterFetch)(o.discoveryUrl,{method:"GET"});g.data&&(A=g.data.token_endpoint,K=g.data.userinfo_endpoint)}try{if(!A)throw new Fe.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});i=await I({code:d,codeVerifier:a,redirectURI:`${t.context.baseURL}/oauth2/callback/${o.providerId}`,options:{clientId:o.clientId,clientSecret:o.clientSecret},tokenEndpoint:A})}catch(g){throw t.context.logger.error(g&&typeof g=="object"&&"name"in g?g.name:"",g),t.redirect(`${s}?error=oauth_code_verification_failed`)}if(!i)throw new Fe.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let u=o.getUserInfo?await o.getUserInfo(i):await ln(i,o.type||"oauth2",K);if(!u?.email)throw t.context.logger.error("Unable to get user info",u),t.redirect(`${t.context.baseURL}/error?error=email_is_missing`);let p=await Pe(t,{userInfo:u,account:{providerId:o.providerId,accountId:u.id,accessToken:i.accessToken}});function l(g){throw t.redirect(`${s||n||`${t.context.baseURL}/error`}?error=${g}`)}if(p.error)return l(p.error.split(" ").join("_"));let{session:h,user:k}=p.data;await m(t,{session:h,user:k});let f;try{f=new URL(n).toString()}catch{f=n}throw t.redirect(f)})}});var Ve=require("zod"),Gt={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0}}}},Bp=Ve.z.object({id:Ve.z.string(),publicKey:Ve.z.string(),privateKey:Ve.z.string(),createdAt:Ve.z.date()});var $o=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 le=require("jose");var mn=e=>({id:"jwt",endpoints:{getJwks:c("/jwks",{method:"GET",metadata:{openapi:{description:"Get the JSON Web Key Set",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{keys:{type:"array",items:{type:"object",properties:{kid:{type:"string"},kty:{type:"string"},use:{type:"string"},alg:{type:"string"},n:{type:"string"},e:{type:"string"}}}}}}}}}}}}},async t=>{let i=await $o(t.context.adapter).getAllKeys();return t.json({keys:i.map(r=>({...JSON.parse(r.publicKey),kid:r.id}))})}),getToken:c("/token",{method:"GET",requireHeaders:!0,use:[v],metadata:{openapi:{description:"Get a JWT token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async t=>{let o=$o(t.context.adapter),i=await o.getLatestKey(),r=!e?.jwks?.disablePrivateKeyEncryption;if(i===void 0){let{publicKey:A,privateKey:K}=await(0,le.generateKeyPair)(e?.jwks?.keyPairConfig?.alg??"EdDSA",e?.jwks?.keyPairConfig??{crv:"Ed25519"}),u=await(0,le.exportJWK)(A),p=await(0,le.exportJWK)(K),l=JSON.stringify(p),h={id:crypto.randomUUID(),publicKey:JSON.stringify(u),privateKey:r?JSON.stringify(await ue({key:t.context.options.secret,data:l})):l,createdAt:new Date};i=await o.createJwk(h)}let n=r?await fe({key:t.context.options.secret,data:JSON.parse(i.privateKey)}):i.privateKey,a=await(0,le.importJWK)(JSON.parse(n)),s=e?.jwt?.definePayload?await e?.jwt.definePayload(t.context.session.user):t.context.session.user,d=await new le.SignJWT({...s,...t.context.session.session.impersonatedBy?{impersonatedBy:t.context.session.session.impersonatedBy}:{}}).setProtectedHeader({alg:e?.jwks?.keyPairConfig?.alg??"EdDSA",kid:i.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:ie(Gt,e?.schema)});var Xe=require("zod");var fn=e=>{let t={maximumSessions:5,...e},o=i=>i.includes("_multi-");return{id:"multi-session",endpoints:{listDeviceSessions:c("/multi-session/list-device-sessions",{method:"GET",requireHeaders:!0},async i=>{let r=i.headers?.get("cookie");if(!r)return i.json([]);let n=Object.fromEntries(Qe(r)),a=(await Promise.all(Object.entries(n).filter(([A])=>o(A)).map(async([A])=>await i.getSignedCookie(A,i.context.secret)))).filter(A=>A!==void 0);if(!a.length)return i.json([]);let d=(await i.context.internalAdapter.findSessions(a)).filter(A=>A&&A.session.expiresAt>new Date);return i.json(d)}),setActiveSession:c("/multi-session/set-active",{method:"POST",body:Xe.z.object({sessionToken:Xe.z.string({description:"The session token to set as active"})}),requireHeaders:!0,use:[v],metadata:{openapi:{description:"Set the active session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async i=>{let r=i.body.sessionToken,n=`${i.context.authCookies.sessionToken.name}_multi-${r}`;if(!await i.getSignedCookie(n,i.context.secret))throw new C.APIError("UNAUTHORIZED",{message:"Invalid session token"});let s=await i.context.internalAdapter.findSession(r);if(!s||s.session.expiresAt<new Date)throw i.setCookie(n,"",{...i.context.authCookies.sessionToken.options,maxAge:0}),new C.APIError("UNAUTHORIZED",{message:"Invalid session token"});return await m(i,s),i.json(s)}),revokeDeviceSession:c("/multi-session/revoke",{method:"POST",body:Xe.z.object({sessionToken:Xe.z.string({description:"The session token to revoke"})}),requireHeaders:!0,use:[v],metadata:{openapi:{description:"Revoke a device session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async i=>{let r=i.body.sessionToken,n=`${i.context.authCookies.sessionToken.name}_multi-${r}`;if(!await i.getSignedCookie(n,i.context.secret))throw new C.APIError("UNAUTHORIZED",{message:"Invalid session token"});if(await i.context.internalAdapter.deleteSession(r),i.setCookie(n,"",{...i.context.authCookies.sessionToken.options,maxAge:0}),!(i.context.session?.session.token===r))return i.json({success:!0});let d=i.headers?.get("cookie");if(d){let A=Object.fromEntries(Qe(d)),K=(await Promise.all(Object.entries(A).filter(([p])=>o(p)).map(async([p])=>await i.getSignedCookie(p,i.context.secret)))).filter(p=>p!==void 0),u=i.context.internalAdapter;if(K.length>0){let l=(await u.findSessions(K)).filter(h=>h&&h.session.expiresAt>new Date);if(l.length>0){let h=l[0];await m(i,h)}else Q(i)}else Q(i)}else Q(i);return i.json({success:!0})})},hooks:{after:[{matcher:()=>!0,handler:P(async i=>{let r=i.responseHeader.get("set-cookie");if(!r)return;let n=ao(r),a=i.context.authCookies.sessionToken,s=n.get(a.name)?.value;if(!s)return;let d=Qe(i.headers?.get("cookie")||""),A=s.split(".")[0];if(!A)return;let K=`${a.name}_multi-${A}`;n.get(K)||d.get(K)||Object.keys(Object.fromEntries(d)).filter(o).length+(r.includes("session_token")?1:0)>t.maximumSessions||await i.setSignedCookie(K,A,i.context.secret,a.options)})},{matcher:i=>i.path==="/sign-out",handler:P(async i=>{let r=i.headers?.get("cookie");if(!r)return;let n=Object.fromEntries(Qe(r)),a=Object.keys(n).map(s=>o(s)?(i.setCookie(s,"",{maxAge:0}),s.split("_multi-")[1]):null).filter(s=>s!==null);await i.context.internalAdapter.deleteSessions(a)})}]}}};var D=require("zod");var Zo=["email-verification","sign-in","forget-password"],hn=e=>{let t={expireIn:300,otpLength:6,...e};return{id:"email-otp",endpoints:{sendVerificationOTP:c("/email-otp/send-verification-otp",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to send the OTP"}),type:D.z.enum(Zo,{description:"Type of the OTP"})}),metadata:{openapi:{description:"Send verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{if(!e?.sendVerificationOTP)throw o.context.logger.error("send email verification is not implemented"),new C.APIError("BAD_REQUEST",{message:"send email verification is not implemented"});let i=o.body.email,r=_(t.otpLength,F("0-9"));return await o.context.internalAdapter.createVerificationValue({value:r,identifier:`${o.body.type}-otp-${i}`,expiresAt:R(t.expireIn,"sec")}).catch(async n=>{await o.context.internalAdapter.deleteVerificationByIdentifier(`${o.body.type}-otp-${i}`),await o.context.internalAdapter.createVerificationValue({value:r,identifier:`${o.body.type}-otp-${i}`,expiresAt:R(t.expireIn,"sec")})}),await e.sendVerificationOTP({email:i,otp:r,type:o.body.type},o.request),o.json({success:!0})}),createVerificationOTP:c("/email-otp/create-verification-otp",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to send the OTP"}),type:D.z.enum(Zo,{description:"Type of the OTP"})}),metadata:{SERVER_ONLY:!0,openapi:{description:"Create verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string"}}}}}}}},async o=>{let i=o.body.email,r=_(t.otpLength,F("0-9"));return await o.context.internalAdapter.createVerificationValue({value:r,identifier:`${o.body.type}-otp-${i}`,expiresAt:R(t.expireIn,"sec")}),r}),getVerificationOTP:c("/email-otp/get-verification-otp",{method:"GET",query:D.z.object({email:D.z.string({description:"Email address to get the OTP"}),type:D.z.enum(Zo)}),metadata:{SERVER_ONLY:!0,openapi:{description:"Get verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{otp:{type:"string"}}}}}}}}}},async o=>{let i=o.query.email,r=await o.context.internalAdapter.findVerificationValue(`${o.query.type}-otp-${i}`);return!r||r.expiresAt<new Date?o.json({otp:null}):o.json({otp:r.value})}),verifyEmailOTP:c("/email-otp/verify-email",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to verify"}),otp:D.z.string({description:"OTP to verify"})}),metadata:{openapi:{description:"Verify email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async o=>{let i=o.body.email,r=await o.context.internalAdapter.findVerificationValue(`email-verification-otp-${i}`);if(!r||r.expiresAt<new Date)throw r&&await o.context.internalAdapter.deleteVerificationValue(r.id),new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});let n=o.body.otp;if(r.value!==n)throw new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});await o.context.internalAdapter.deleteVerificationValue(r.id);let a=await o.context.internalAdapter.findUserByEmail(i);if(!a)throw new C.APIError("BAD_REQUEST",{message:"User not found"});let s=await o.context.internalAdapter.updateUser(a.user.id,{email:i,emailVerified:!0});return o.json({user:s})}),signInEmailOTP:c("/sign-in/email-otp",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to sign in"}),otp:D.z.string({description:"OTP sent to the email"})}),metadata:{openapi:{description:"Sign in with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async o=>{let i=o.body.email,r=await o.context.internalAdapter.findVerificationValue(`sign-in-otp-${i}`);if(!r||r.expiresAt<new Date)throw r&&await o.context.internalAdapter.deleteVerificationValue(r.id),new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});let n=o.body.otp;if(r.value!==n)throw new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});await o.context.internalAdapter.deleteVerificationValue(r.id);let a=await o.context.internalAdapter.findUserByEmail(i);if(!a){if(t.disableSignUp)throw new C.APIError("BAD_REQUEST",{message:"User not found"});let d=await o.context.internalAdapter.createUser({email:i,emailVerified:!0,name:i}),A=await o.context.internalAdapter.createSession(d.id,o.request);return await m(o,{session:A,user:d}),o.json({user:d,session:A})}a.user.emailVerified||await o.context.internalAdapter.updateUser(a.user.id,{emailVerified:!0});let s=await o.context.internalAdapter.createSession(a.user.id,o.request);return await m(o,{session:s,user:a.user}),o.json({session:s,user:a})}),forgetPasswordEmailOTP:c("/forget-password/email-otp",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to send the OTP"})}),metadata:{openapi:{description:"Forget password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{let i=o.body.email;if(!await o.context.internalAdapter.findUserByEmail(i))throw new C.APIError("BAD_REQUEST",{message:"User not found"});let n=_(t.otpLength,F("0-9"));return await o.context.internalAdapter.createVerificationValue({value:n,identifier:`forget-password-otp-${i}`,expiresAt:R(t.expireIn,"sec")}),await e.sendVerificationOTP({email:i,otp:n,type:"forget-password"},o.request),o.json({success:!0})}),resetPasswordEmailOTP:c("/email-otp/reset-password",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to reset the password"}),otp:D.z.string({description:"OTP sent to the email"}),password:D.z.string({description:"New password"})}),metadata:{openapi:{description:"Reset password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{let i=o.body.email,r=await o.context.internalAdapter.findUserByEmail(i);if(!r)throw new C.APIError("BAD_REQUEST",{message:"User not found"});let n=await o.context.internalAdapter.findVerificationValue(`forget-password-otp-${i}`);if(!n||n.expiresAt<new Date)throw n&&await o.context.internalAdapter.deleteVerificationValue(n.id),new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});let a=o.body.otp;if(n.value!==a)throw new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});await o.context.internalAdapter.deleteVerificationValue(n.id);let s=await o.context.password.hash(o.body.password);return await o.context.internalAdapter.updatePassword(r.user.id,s),o.json({success:!0})})},hooks:{after:[{matcher(o){return!!(o.path?.startsWith("/sign-up")&&t.sendVerificationOnSignUp)},async handler(o){let i=await Ne(o);if(i&&i.user.email&&i.user.emailVerified===!1){let r=_(t.otpLength,F("0-9"));await o.context.internalAdapter.createVerificationValue({value:r,identifier:`email-verification-otp-${i.user.email}`,expiresAt:R(t.expireIn,"sec")}),await e.sendVerificationOTP({email:i.user.email,otp:r,type:"email-verification"},o.request)}}}]}}};var Go=require("zod");var Jt=require("@better-fetch/fetch");function Wt(e){return e==="true"||e===!0}var yn=e=>({id:"one-tap",endpoints:{oneTapCallback:c("/one-tap/callback",{method:"POST",body:Go.z.object({idToken:Go.z.string({description:"Google ID token, which the client obtains from the One Tap API"})}),metadata:{openapi:{summary:"One tap callback",description:"Use this endpoint to authenticate with Google One Tap",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}},400:{description:"Invalid token"}}}}},async t=>{let{idToken:o}=t.body,{data:i,error:r}=await(0,Jt.betterFetch)("https://oauth2.googleapis.com/tokeninfo?id_token="+o);if(r)return t.json({error:"Invalid token"});let n=await t.context.internalAdapter.findUserByEmail(i.email);if(!n){if(e?.disableSignup)throw new C.APIError("BAD_GATEWAY",{message:"User not found"});let s=await t.context.internalAdapter.createOAuthUser({email:i.email,emailVerified:Wt(i.email_verified),name:i.name,image:i.picture},{providerId:"google",accountId:i.sub});if(!s)throw new C.APIError("INTERNAL_SERVER_ERROR",{message:"Could not create user"});let d=await t.context.internalAdapter.createSession(s?.user.id,t.request);return await m(t,{user:s.user,session:d}),t.json({session:d,user:s})}let a=await t.context.internalAdapter.createSession(n.user.id,t.request);return await m(t,{user:n.user,session:a}),t.json({session:a,user:n})})}});var yo=require("zod");function wn(){let e=ne.VERCEL_URL,t=ne.NETLIFY_URL,o=ne.RENDER_URL,i=ne.AWS_LAMBDA_FUNCTION_NAME,r=ne.GOOGLE_CLOUD_FUNCTION_NAME,n=ne.AZURE_FUNCTION_NAME;return e||t||o||i||r||n}var Cn=e=>({id:"oauth-proxy",endpoints:{oAuthProxy:c("/oauth-proxy-callback",{method:"GET",query:yo.z.object({callbackURL:yo.z.string({description:"The URL to redirect to after the proxy"}),cookies:yo.z.string({description:"The cookies to set after the proxy"})}),metadata:{openapi:{description:"OAuth Proxy Callback",parameters:[{in:"query",name:"callbackURL",required:!0,description:"The URL to redirect to after the proxy"},{in:"query",name:"cookies",required:!0,description:"The cookies to set after the proxy"}],responses:{302:{description:"Redirect",headers:{Location:{description:"The URL to redirect to",schema:{type:"string"}}}}}}}},async t=>{let o=t.query.cookies,i=await fe({key:t.context.secret,data:o});throw t.setHeader("set-cookie",i),t.redirect(t.query.callbackURL)})},hooks:{after:[{matcher(t){return t.path?.startsWith("/callback")},handler:P(async t=>{let o=t.context.returned,i=o instanceof C.APIError?o.headers:null,r=i?.get("location");if(r?.includes("/oauth-proxy-callback?callbackURL")){if(!r.startsWith("http"))return;let n=new URL(r);if(n.origin===Ie(t.context.baseURL)){let K=n.searchParams.get("callbackURL");if(!K)return;t.setHeader("location",K);return}let s=i?.get("set-cookie");if(!s)return;let d=await ue({key:t.context.secret,data:s}),A=`${r}&cookies=${encodeURIComponent(d)}`;t.setHeader("location",A)}})}],before:[{matcher(t){return t.path?.startsWith("/sign-in/social")},async handler(t){let o=new URL(e?.currentURL||t.request?.url||wn()||t.context.baseURL);return t.body.callbackURL=`${o.origin}${t.context.options.basePath||"/api/auth"}/oauth-proxy-callback?callbackURL=${encodeURIComponent(t.body.callbackURL||t.context.baseURL)}`,{context:t}}}]}});var bn=(e,t)=>({id:"custom-session",endpoints:{getSession:c("/get-session",{method:"GET",metadata:{CUSTOM_SESSION:!0}},async o=>{let i=await U(o);if(!i)return o.json(null);let r=await e(i);return o.json(r)})}});var ce=require("zod");var qe=e=>{let t=e.plugins?.reduce((d,A)=>{let K=A.schema;if(!K)return d;for(let[u,p]of Object.entries(K))d[u]={fields:{...d[u]?.fields,...p.fields},modelName:p.modelName||u};return d},{}),o=e.rateLimit?.storage==="database",i={rateLimit:{modelName:e.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",fieldName:e.rateLimit?.fields?.key||"key"},count:{type:"number",fieldName:e.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",fieldName:e.rateLimit?.fields?.lastRequest||"lastRequest"}}}},{user:r,session:n,account:a,...s}=t||{};return{user:{modelName:e.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:e.user?.fields?.name||"name"},email:{type:"string",unique:!0,required:!0,fieldName:e.user?.fields?.email||"email"},emailVerified:{type:"boolean",defaultValue:()=>!1,required:!0,fieldName:e.user?.fields?.emailVerified||"emailVerified"},image:{type:"string",required:!1,fieldName:e.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.updatedAt||"updatedAt"},...r?.fields,...e.user?.additionalFields},order:1},session:{modelName:e.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:e.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:e.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:e.session?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,fieldName:e.session?.fields?.updatedAt||"updatedAt"},ipAddress:{type:"string",required:!1,fieldName:e.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:e.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:e.session?.fields?.userId||"userId",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0},...n?.fields,...e.session?.additionalFields},order:2},account:{modelName:e.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:e.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:e.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:e.account?.fields?.userId||"userId"},accessToken:{type:"string",required:!1,fieldName:e.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,fieldName:e.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,fieldName:e.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.accessTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:e.account?.fields?.scope||"scope"},password:{type:"string",required:!1,fieldName:e.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:e.account?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,fieldName:e.account?.fields?.updatedAt||"updatedAt"},...a?.fields},order:3},verification:{modelName:e.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:e.verification?.fields?.identifier||"identifier"},value:{type:"string",required:!0,fieldName:e.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:e.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!1,defaultValue:()=>new Date,fieldName:e.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!1,defaultValue:()=>new Date,fieldName:e.verification?.fields?.updatedAt||"updatedAt"}},order:4},...s,...o?i:{}}};var vn=require("zod");var Xt=require("kysely"),Wo=require("kysely");var Ye={};function er(e){switch(e.constructor.name){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array";default:return"string"}}function wo(e){let t=[];return e.metadata?.openapi?.parameters?(t.push(...e.metadata.openapi.parameters),t):(e.query instanceof ce.ZodObject&&Object.entries(e.query.shape).forEach(([o,i])=>{i instanceof ce.ZodSchema&&t.push({name:o,in:"query",schema:{type:er(i),..."minLength"in i&&i.minLength?{minLength:i.minLength}:{},description:i.description}})}),t)}function Yt(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof ce.ZodObject||e.body instanceof ce.ZodOptional)){let t=e.body.shape;if(!t)return;let o={},i=[];return Object.entries(t).forEach(([r,n])=>{n instanceof ce.ZodSchema&&(o[r]={type:er(n),description:n.description},n instanceof ce.ZodOptional||i.push(r))}),{required:e.body instanceof ce.ZodOptional?!1:!!e.body,content:{"application/json":{schema:{type:"object",properties:o,required:i}}}}}}function Co(e){return{400:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Bad Request. Usually due to missing parameters, or invalid parameters."},401:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Unauthorized. Due to missing or invalid authentication."},403:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Forbidden. You do not have permission to access this resource or to perform this action."},404:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Not Found. The requested resource was not found."},429:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Too Many Requests. You have exceeded the rate limit. Try again later."},500:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Internal Server Error. This is a problem with the server that you cannot fix."},...e}}async function Jo(e,t){let o=Uo(e,{...t,plugins:[]}),i=qe(t),n={schemas:{...Object.entries(i).reduce((s,[d,A])=>{let K=d.charAt(0).toUpperCase()+d.slice(1);return s[K]={type:"object",properties:Object.entries(A.fields).reduce((u,[p,l])=>(u[p]={type:l.type},u),{})},s},{})}};Object.entries(o.api).forEach(([s,d])=>{let A=d.options;if(!A.metadata?.SERVER_ONLY&&(A.method==="GET"&&(Ye[d.path]={get:{tags:["Default",...A.metadata?.openapi?.tags||[]],description:A.metadata?.openapi?.description,operationId:A.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(A),responses:Co(A.metadata?.openapi?.responses)}}),A.method==="POST")){let K=Yt(A);Ye[d.path]={post:{tags:["Default",...A.metadata?.openapi?.tags||[]],description:A.metadata?.openapi?.description,operationId:A.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(A),...K?{requestBody:K}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:Co(A.metadata?.openapi?.responses)}}}});for(let s of t.plugins||[]){if(s.id==="open-api")continue;let d=Uo(e,{...t,plugins:[s]}),A=Object.keys(d.api).map(K=>o.api[K]===void 0?d.api[K]:null).filter(K=>K!==null);Object.entries(A).forEach(([K,u])=>{let p=u.options;p.metadata?.SERVER_ONLY||(p.method==="GET"&&(Ye[u.path]={get:{tags:p.metadata?.openapi?.tags||[s.id.charAt(0).toUpperCase()+s.id.slice(1)],description:p.metadata?.openapi?.description,operationId:p.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(p),responses:Co(p.metadata?.openapi?.responses)}}),p.method==="POST"&&(Ye[u.path]={post:{tags:p.metadata?.openapi?.tags||[s.id.charAt(0).toUpperCase()+s.id.slice(1)],description:p.metadata?.openapi?.description,operationId:p.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(p),requestBody:Yt(p),responses:Co(p.metadata?.openapi?.responses)}}))})}return{openapi:"3.1.1",info:{title:"Better Auth",description:"API Reference for your Better Auth Instance"},components:n,security:[{apiKeyCookie:[]}],servers:[{url:e.baseURL}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:Ye}}var or=`<svg width="75" height="75" viewBox="0 0 75 75" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
|
82
|
+
</html>`,pi=c("/error",{method:"GET",metadata:{...we,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string"}}}}}}}},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(wr(t),{headers:{"Content-Type":"text/html"}})});var ui=require("consola"),Io=["info","success","warn","error","debug"];function Cr(e,t){return Io.indexOf(t)<=Io.indexOf(e)}var br=(0,ui.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),li=e=>{let t=e?.disabled!==!0,o=e?.level??"error",i=(r,n,a=[])=>{if(!(!t||!Cr(o,r))){if(!e||typeof e.log!="function"){br[r]("",n,...a);return}e.log(r==="success"?"info":r,n,a)}};return Object.fromEntries(Io.map(r=>[r,(...[n,...a])=>i(r,n,a)]))},J=li();var C=require("better-call");function Uo(e,t){let o=t.plugins?.reduce((s,d)=>({...s,...d.endpoints}),{}),i=t.plugins?.map(s=>s.middlewares?.map(d=>{let A=async K=>d.middleware({...K,context:{...e,...K.context}});return A.path=d.path,A.options=d.middleware.options,A.headers=d.middleware.headers,{path:d.path,middleware:A}})).filter(s=>s!==void 0).flat()||[],n={...{signInSocial:gi,callbackOAuth:fi,getSession:To(),signOut:hi,signUpEmail:Ki(),signInEmail:mi,forgetPassword:yi,resetPassword:Ci,verifyEmail:Ai,sendVerificationEmail:di,changeEmail:Oi,changePassword:vi,setPassword:ki,updateUser:bi(),deleteUser:Ti,forgetPasswordCallback:wi,listSessions:ti(),revokeSession:ri,revokeSessions:ni,revokeOtherSessions:si,linkSocialAccount:Ui,listUserAccounts:Ii},...o,ok:ii,error:pi},a={};for(let[s,d]of Object.entries(n))a[s]=async(A={})=>{d.headers=new Headers;let K={setHeader(f,g){d.headers.set(f,g)},setCookie(f,g,b){(0,$.setCookie)(d.headers,f,g,b)},getCookie(f,g){let T=A.headers?.get("cookie");return(0,$.getCookie)(T||"",f,g)},getSignedCookie(f,g,b){let T=A.headers;return T?(0,$.getSignedCookie)(T,g,f,b):null},async setSignedCookie(f,g,b,T){await(0,$.setSignedCookie)(d.headers,f,g,b,T)},redirect(f){return d.headers.set("Location",f),new $.APIError("FOUND")},responseHeader:d.headers},u=await e,p={...K,...A,path:d.path,context:{...u,...A.context,endpoint:d}};u.session=null;let l=t.plugins||[];for(let f of l){let g=f.hooks?.before??[];for(let b of g){if(!b.matcher(p))continue;let T=await b.handler(p);if(T&&"context"in T){p={...p,...T.context};continue}if(T)return T}}let h;try{h=await d(p)}catch(f){if(f instanceof $.APIError){let g=t.plugins?.map(b=>{if(b.hooks?.after)return b.hooks.after}).filter(b=>b!==void 0).flat();if(!g?.length)throw f.headers=d.headers,f;p.context.returned=f,p.context.returned.headers=d.headers;for(let b of g||[])if(b.matcher(p))try{let N=await b.handler(p);N&&"response"in N&&(p.context.returned=N.response)}catch(N){if(N instanceof $.APIError){p.context.returned=N;continue}throw N}if(p.context.returned instanceof $.APIError)throw p.context.returned.headers=d.headers,p.context.returned;return p.context.returned}throw f}p.context.returned=h,p.responseHeader=d.headers;for(let f of t.plugins||[])if(f.hooks?.after){for(let g of f.hooks.after)if(g.matcher(p))try{let T=await g.handler(p);T&&(p.context.returned=T)}catch(T){if(T instanceof $.APIError){p.context.returned=T;continue}throw T}}let k=p.context.returned;return k instanceof Response&&d.headers.forEach((f,g)=>{g==="set-cookie"?k.headers.append(g,f):k.headers.set(g,f)}),k},a[s].path=d.path,a[s].method=d.method,a[s].options=d.options,a[s].headers=d.headers;return{api:a,middlewares:i}}function ao(e){let t=new Map;return e.split(", ").forEach(i=>{let r=i.split(";").map(u=>u.trim()),[n,...a]=r,[s,...d]=n.split("="),A=d.join("=");if(!s||A===void 0){console.warn(`Malformed cookie: ${i}`);return}let K={value:A};a.forEach(u=>{let[p,...l]=u.split("="),h=l.join("="),k=p.trim().toLowerCase();switch(k){case"max-age":K["max-age"]=h?parseInt(h.trim(),10):void 0;break;case"expires":K.expires=h?new Date(h.trim()):void 0;break;case"domain":K.domain=h?h.trim():void 0;break;case"path":K.path=h?h.trim():void 0;break;case"secure":K.secure=!0;break;case"httponly":K.httponly=!0;break;case"samesite":K.samesite=h?h.trim().toLowerCase():void 0;break;default:K[k]=h?h.trim():!0;break}}),t.set(s,K)}),t}async function m(e,t,o,i){let r=e.context.authCookies.sessionToken.options,n=o?void 0:e.context.sessionConfig.expiresIn,a=await U(e).catch(()=>null);a&&a.session.userId===t.session.userId&&a.session.token!==t.session.token&&await e.context.internalAdapter.deleteSession(a.session.token),await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...r,maxAge:n,...i}),o&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Ri.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:R(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await to.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3))}function Q(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}function Qe(e){let t=e.split("; "),o=new Map;return t.forEach(i=>{let[r,n]=i.split("=");o.set(r,n)}),o}var ji=require("@better-fetch/fetch"),zi=require("better-call"),Re=require("jose"),Bi=require("oslo/jwt");var Pi=require("oslo/crypto"),Ei=require("oslo/encoding");async function Si(e){let t=await(0,Pi.sha256)(new TextEncoder().encode(e));return Ei.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Di(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?R(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function S({id:e,options:t,authorizationEndpoint:o,state:i,codeVerifier:r,scopes:n,claims:a,redirectURI:s}){let d=new URL(o);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",i),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||s),r){let A=await Si(r);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",A)}if(a){let A=a.reduce((K,u)=>(K[u]=null,K),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...A}}))}return d}var xi=require("@better-fetch/fetch");async function I({code:e,codeVerifier:t,redirectURI:o,options:i,tokenEndpoint:r,authentication:n}){let a=new URLSearchParams,s={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(a.set("grant_type","authorization_code"),a.set("code",e),t&&a.set("code_verifier",t),a.set("redirect_uri",o),n==="basic"){let u=btoa(`${i.clientId}:${i.clientSecret}`);s.authorization=`Basic ${u}`}else a.set("client_id",i.clientId),a.set("client_secret",i.clientSecret);let{data:d,error:A}=await(0,xi.betterFetch)(r,{method:"POST",body:a,headers:s});if(A)throw A;return Di(d)}var Ao=require("oslo/oauth2"),pe=require("zod"),Ro=require("better-call");function Ie(e){try{return new URL(e).origin}catch{return null}}async function Ue(e,t){let o=e.body?.callbackURL||(e.query?.currentURL?Ie(e.query?.currentURL):"")||e.context.options.baseURL;if(!o)throw new Ro.APIError("BAD_REQUEST",{message:"callbackURL is required"});let i=(0,Ao.generateCodeVerifier)(),r=(0,Ao.generateState)(),n=JSON.stringify({callbackURL:o,codeVerifier:i,errorURL:e.body?.errorCallbackURL||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:n,identifier:r,expiresAt:a});if(!s)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new Ro.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:s.identifier,codeVerifier:i}}async function co(e){let t=e.query.state||e.body.state,o=await e.context.internalAdapter.findVerificationValue(t);if(!o)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let i=pe.z.object({callbackURL:pe.z.string(),codeVerifier:pe.z.string(),errorURL:pe.z.string().optional(),expiresAt:pe.z.number(),link:pe.z.object({email:pe.z.string(),userId:pe.z.string()}).optional()}).parse(JSON.parse(o.value));if(i.errorURL||(i.errorURL=`${e.context.baseURL}/error`),i.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(o.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(o.id),i}var Ni=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:o,scopes:i,redirectURI:r}){let n=i||["email","name"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${r||e.redirectURI}&scope=${n.join(" ")}&state=${o}&response_mode=form_post`)},validateAuthorizationCode:async({code:o,codeVerifier:i,redirectURI:r})=>I({code:o,codeVerifier:i,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t}),async verifyIdToken(o,i){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(o,i);let r=(0,Re.decodeProtectedHeader)(o),{kid:n,alg:a}=r;if(!n||!a)return!1;let s=await Tr(n),{payload:d}=await(0,Re.jwtVerify)(o,s,{algorithms:[a],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(A=>{d[A]!==void 0&&(d[A]=!!d[A])}),i&&d.nonce!==i?!1:!!d},async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);if(!o.idToken)return null;let i=(0,Bi.parseJWT)(o.idToken)?.payload;if(!i)return null;let r=i.user?`${i.user.name.firstName} ${i.user.name.lastName}`:i.email;return{user:{id:i.sub,name:r,emailVerified:!1,email:i.email},data:i}}}},Tr=async e=>{let t="https://appleid.apple.com",o="/auth/keys",{data:i}=await(0,ji.betterFetch)(`${t}${o}`);if(!i?.keys)throw new zi.APIError("BAD_REQUEST",{message:"Keys not found"});let r=i.keys.find(n=>n.kid===e);if(!r)throw new Error(`JWK with kid ${e} not found`);return await(0,Re.importJWK)(r,r.alg)};var _i=require("@better-fetch/fetch");var Li=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:o,redirectURI:i}){let r=o||["identify","email"];return e.scope&&r.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${r.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||i)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:o})=>I({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:i}=await(0,_i.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;if(o.avatar===null){let r=o.discriminator==="0"?Number(BigInt(o.id)>>BigInt(22))%6:parseInt(o.discriminator)%5;o.image_url=`https://cdn.discordapp.com/embed/avatars/${r}.png`}else{let r=o.avatar.startsWith("a_")?"gif":"png";o.image_url=`https://cdn.discordapp.com/avatars/${o.id}/${o.avatar}.${r}`}return{user:{id:o.id,name:o.display_name||o.username||"",email:o.email,emailVerified:o.verified,image:o.image_url},data:o}}});var Fi=require("@better-fetch/fetch");var Vi=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:o,redirectURI:i}){let r=o||["email","public_profile"];return e.scope&&r.push(...e.scope),await S({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:r,state:t,redirectURI:i})},validateAuthorizationCode:async({code:t,redirectURI:o})=>I({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:i}=await(0,Fi.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return i?null:{user:{id:o.id,name:o.name,email:o.email,image:o.picture.data.url,emailVerified:o.email_verified},data:o}}});var Po=require("@better-fetch/fetch");var qi=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:o,scopes:i,codeVerifier:r,redirectURI:n}){let a=i||["user:email"];return e.scope&&a.push(...e.scope),S({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>I({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);let{data:i,error:r}=await(0,Po.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${o.accessToken}`}});if(r)return null;let n=!1;if(!i.email){let{data:a,error:s}=await(0,Po.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${o.accessToken}`,"User-Agent":"better-auth"}});s||(i.email=(a.find(d=>d.primary)??a[0])?.email,n=a.find(d=>d.email===i.email)?.verified??!1)}return{user:{id:i.id.toString(),name:i.name||i.login,email:i.email,image:i.avatar_url,emailVerified:n},data:i}}}};var Mi=require("oslo/jwt");var Hi=require("@better-fetch/fetch"),Qi=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:o,codeVerifier:i,redirectURI:r}){if(!e.clientId||!e.clientSecret)throw J.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new ee("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new ee("codeVerifier is required for Google");let n=o||["email","profile","openid"];e.scope&&n.push(...e.scope);let a=await S({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:i,redirectURI:r});return e.accessType&&a.searchParams.set("access_type",e.accessType),e.prompt&&a.searchParams.set("prompt",e.prompt),a},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:i})=>I({code:t,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,o);let i=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:r}=await(0,Hi.betterFetch)(i);return r?r.aud===e.clientId&&r.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let o=(0,Mi.parseJWT)(t.idToken)?.payload;return{user:{id:o.sub,name:o.name,email:o.email,image:o.picture,emailVerified:o.email_verified},data:o}}});var $i=require("@better-fetch/fetch"),Zi=require("oslo/jwt");var Gi=e=>{let t=e.tenantId||"common",o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,i=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(r){let n=r.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),S({id:"microsoft",options:e,authorizationEndpoint:o,state:r.state,codeVerifier:r.codeVerifier,scopes:n,redirectURI:r.redirectURI})},validateAuthorizationCode({code:r,codeVerifier:n,redirectURI:a}){return I({code:r,codeVerifier:n,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:i})},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let n=(0,Zi.parseJWT)(r.idToken)?.payload,a=e.profilePhotoSize||48;return await(0,$i.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${r.accessToken}`},async onResponse(s){if(!(e.disableProfilePhoto||!s.response.ok))try{let A=await s.response.clone().arrayBuffer(),K=Buffer.from(A).toString("base64");n.picture=`data:image/jpeg;base64, ${K}`}catch(d){J.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};var Wi=require("@better-fetch/fetch");var Ji=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:o,codeVerifier:i,redirectURI:r}){let n=o||["user-read-email"];return e.scope&&n.push(...e.scope),S({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:r})},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:i})=>I({code:t,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:i}=await(0,Wi.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{id:o.id,name:o.display_name,email:o.email,image:o.images[0]?.url,emailVerified:!1},data:o}}});var Xi=require("nanoid"),V=e=>(0,Xi.nanoid)(e);var Yi=require("oslo/jwt");var et=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:o,redirectURI:i}){let r=o||["user:read:email","openid"];return e.scope&&r.push(...e.scope),S({id:"twitch",redirectURI:i,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:r,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:o})=>I({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let o=t.idToken;if(!o)return J.error("No idToken found in token"),null;let i=(0,Yi.parseJWT)(o)?.payload;return{user:{id:i.sub,name:i.preferred_username,email:i.email,image:i.picture,emailVerified:!1},data:i}}});var ot=require("@better-fetch/fetch");var it=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let o=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&o.push(...e.scope),S({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:o,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:i})=>I({code:t,codeVerifier:o,authentication:"basic",redirectURI:e.redirectURI||i,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:i}=await(0,ot.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{id:o.data.id,name:o.data.name,email:o.data.username||null,image:o.data.profile_image_url,emailVerified:o.data.verified||!1},data:o}}});var tt=require("@better-fetch/fetch");var rt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:o,scopes:i,codeVerifier:r,redirectURI:n})=>{let a=i||["account_info.read"];return e.scope&&a.push(...e.scope),await S({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:o,redirectURI:n,codeVerifier:r})},validateAuthorizationCode:async({code:o,codeVerifier:i,redirectURI:r})=>await I({code:o,codeVerifier:i,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t}),async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);let{data:i,error:r}=await(0,tt.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${o.accessToken}`}});return r?null:{user:{id:i.account_id,name:i.name?.display_name,email:i.email,emailVerified:i.email_verified||!1,image:i.profile_photo_url},data:i}}}};var nt=require("@better-fetch/fetch");var st=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",o="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:i,scopes:r,redirectURI:n})=>{let a=r||["profile","email","openid"];return e.scope&&a.push(...e.scope),await S({id:"linkedin",options:e,authorizationEndpoint:t,scopes:a,state:i,redirectURI:n})},validateAuthorizationCode:async({code:i,redirectURI:r})=>await I({code:i,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:o}),async getUserInfo(i){let{data:r,error:n}=await(0,nt.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});return n?null:{user:{id:r.sub,name:r.name,email:r.email,emailVerified:r.email_verified||!1,image:r.picture},data:r}}}};var at=require("@better-fetch/fetch");var Eo=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Or=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:Eo(`${t}/oauth/authorize`),tokenEndpoint:Eo(`${t}/oauth/token`),userinfoEndpoint:Eo(`${t}/api/v4/user`)}},dt=e=>{let{authorizationEndpoint:t,tokenEndpoint:o,userinfoEndpoint:i}=Or(e.issuer),r="gitlab";return{id:r,name:"Gitlab",createAuthorizationURL:async({state:a,scopes:s,codeVerifier:d,redirectURI:A})=>{let K=s||["read_user"];return e.scope&&K.push(...e.scope),await S({id:r,options:e,authorizationEndpoint:t,scopes:K,state:a,redirectURI:A,codeVerifier:d})},validateAuthorizationCode:async({code:a,redirectURI:s,codeVerifier:d})=>I({code:a,redirectURI:e.redirectURI||s,options:e,codeVerifier:d,tokenEndpoint:o}),async getUserInfo(a){if(e.getUserInfo)return e.getUserInfo(a);let{data:s,error:d}=await(0,at.betterFetch)(i,{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 Ir={apple:Ni,discord:Li,facebook:Vi,github:qi,microsoft:Gi,google:Qi,spotify:Ji,twitch:et,twitter:it,dropbox:rt,linkedin:st,gitlab:dt},Ko=Object.keys(Ir);async function Pe(e,{userInfo:t,account:o,callbackURL:i}){let r=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(s=>{throw J.error(`Better auth was unable to query your database.
|
|
83
|
+
Error: `,s),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=r?.user;if(r){let s=r.accounts.find(d=>d.providerId===o.providerId);if(s){let d=Object.fromEntries(Object.entries({accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt}).filter(([A,K])=>K!==void 0));Object.keys(d).length>0&&await e.context.internalAdapter.updateAccount(s.id,d)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(o.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return ei&&J.warn(`User already exist but account isn't linked to ${o.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:o.providerId,accountId:t.id.toString(),userId:r.user.id,accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt,scope:o.scope})}catch(K){return J.error("Unable to link account",K),{error:"unable to link account",data:null}}}}else try{let s=t.emailVerified||!1;if(n=await e.context.internalAdapter.createOAuthUser({...t,id:void 0,emailVerified:s,email:t.email.toLowerCase()},{accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt,scope:o.scope,providerId:o.providerId,accountId:t.id.toString()}).then(d=>d?.user),!s&&n&&e.context.options.emailVerification?.sendOnSignUp){let d=await Ke(e.context.secret,n.email),A=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${i}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:n,url:A,token:d},e.request)}}catch(s){return J.error("Unable to create user",s),{error:"unable to create user",data:null}}if(!n)return{error:"unable to create user",data:null};let a=await e.context.internalAdapter.createSession(n.id,e.request);return a?{data:{session:a,user:n},error:null}:{error:"unable to create session",data:null}}var gi=c("/sign-in/social",{method:"POST",query:x.z.object({currentURL:x.z.string().optional()}).optional(),body:x.z.object({callbackURL:x.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),errorCallbackURL:x.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:x.z.enum(Ko,{description:"OAuth2 provider to use"}),disableRedirect:x.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:x.z.optional(x.z.object({token:x.z.string({description:"ID token from the provider"}),nonce:x.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:x.z.string({description:"Access token from the provider"}).optional(),refreshToken:x.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:x.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new q.APIError("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new q.APIError("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:n,nonce:a}=e.body.idToken;if(!await t.verifyIdToken(n,a))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new q.APIError("UNAUTHORIZED",{message:"Invalid id token"});let d=await t.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!d||!d?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new q.APIError("UNAUTHORIZED",{message:"Failed to get user info"});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new q.APIError("UNAUTHORIZED",{message:"User email not found"});let A=await Pe(e,{userInfo:{email:d.user.email,id:d.user.id,name:d.user.name||"",image:d.user.image,emailVerified:d.user.emailVerified||!1},account:{providerId:t.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(A.error)throw new q.APIError("UNAUTHORIZED",{message:A.error});return await m(e,A.data),e.json({session:A.data.session,user:A.data.user})}let{codeVerifier:o,state:i}=await Ue(e),r=await t.createAuthorizationURL({state:i,codeVerifier:o,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:r.toString(),redirect:!e.body.disableRedirect})}),mi=c("/sign-in/email",{method:"POST",body:x.z.object({email:x.z.string({description:"Email of the user"}),password:x.z.string({description:"Password of the user"}),callbackURL:x.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:x.z.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},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 q.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:o}=e.body;if(!x.z.string().email().safeParse(t).success)throw new q.APIError("BAD_REQUEST",{message:"Invalid email"});let r=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!r)throw await e.context.password.hash(o),e.context.logger.error("User not found",{email:t}),new q.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let n=r.accounts.find(A=>A.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new q.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let a=n?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new q.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify({hash:a,password:o}))throw e.context.logger.error("Invalid password"),new q.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!r.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new q.APIError("UNAUTHORIZED",{message:"Email is not verified."});let A=await Ke(e.context.secret,r.user.email),K=`${e.context.baseURL}/verify-email?token=${A}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:r.user,url:K,token:A},e.request),e.context.logger.error("Email not verified",{email:t}),new q.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(r.user.id,e.headers,e.body.rememberMe===!1);if(!d)throw e.context.logger.error("Failed to create session"),new q.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await m(e,{session:d,user:r.user},e.body.rememberMe===!1),e.json({user:r.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Ee=require("zod");var po=Ee.z.object({code:Ee.z.string().optional(),error:Ee.z.string().optional(),errorMessage:Ee.z.string().optional(),state:Ee.z.string().optional()}),fi=c("/callback/:id",{method:["GET","POST"],body:po.optional(),query:po.optional(),metadata:we},async e=>{let t;try{if(e.method==="GET")t=po.parse(e.query);else if(e.method==="POST")t=po.parse(e.body);else throw new Error("Unsupported method")}catch(g){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",g),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:o,error:i,state:r}=t;if(!r)throw e.context.logger.error("State not found"),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!o)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${i||"no_code"}`);let n=e.context.socialProviders.find(g=>g.id===e.params.id);if(!n)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:a,callbackURL:s,link:d,errorURL:A}=await co(e),K;try{K=await n.validateAuthorizationCode({code:o,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${n.id}`})}catch(g){throw e.context.logger.error("",g),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let u=await n.getUserInfo(K).then(g=>g?.user);function p(g){let b=A||s||`${e.context.baseURL}/error`;throw b.includes("?")?b=`${b}&error=${g}`:b=`${b}?error=${g}`,e.redirect(b)}if(!u)return e.context.logger.error("Unable to get user info"),p("unable_to_get_user_info");if(!u.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),p("email_not_found");if(!s)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(d){if(d.email!==u.email.toLowerCase())return p("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:n.id,accountId:u.id}))return p("unable_to_link_account");let b;try{b=new URL(s).toString()}catch{b=s}throw e.redirect(b)}let l=await Pe(e,{userInfo:{id:u.id,email:u.email,name:u.name||"",image:u.image,emailVerified:u.emailVerified||!1},account:{providerId:n.id,accountId:u.id,...K,scope:K.scopes?.join(",")},callbackURL:s});if(l.error)return e.context.logger.error(l.error.split(" ").join("_")),p(l.error.split(" ").join("_"));let{session:h,user:k}=l.data;await m(e,{session:h,user:k});let f;try{f=new URL(s).toString()}catch{f=s}throw e.redirect(f)});var Ed=require("zod");var At=require("better-call"),hi=c("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw Q(e),new At.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),Q(e),e.json({success:!0})});var X=require("zod");var uo=require("better-call");function ct(e,t,o){let i=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return o&&Object.entries(o).forEach(([r,n])=>i.searchParams.set(r,n)),i.href}function Ur(e,t,o){let i=new URL(t,e.baseURL);return o&&Object.entries(o).forEach(([r,n])=>i.searchParams.set(r,n)),i.href}var yi=c("/forget-password",{method:"POST",body:X.z.object({email:X.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:X.z.string({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},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 uo.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:o}=e.body,i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let r=60*60*1,n=R(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||r,"sec"),a=V(24);await e.context.internalAdapter.createVerificationValue({value:i.user.id.toString(),identifier:`reset-password:${a}`,expiresAt:n});let s=`${e.context.baseURL}/reset-password/${a}?callbackURL=${o}`;return await e.context.options.emailAndPassword.sendResetPassword({user:i.user,url:s,token:a},e.request),e.json({status:!0})}),wi=c("/reset-password/:token",{method:"GET",query:X.z.object({callbackURL:X.z.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:o}=e.query;if(!t||!o)throw e.redirect(ct(e.context,o,{error:"INVALID_TOKEN"}));let i=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!i||i.expiresAt<new Date?e.redirect(ct(e.context,o,{error:"INVALID_TOKEN"})):e.redirect(Ur(e.context,o,{token:t}))}),Ci=c("/reset-password",{query:X.z.optional(X.z.object({token:X.z.string().optional(),currentURL:X.z.string().optional()})),method:"POST",body:X.z.object({newPassword:X.z.string({description:"The new password to set"}),token:X.z.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new uo.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:o}=e.body,i=`reset-password:${t}`,r=await e.context.internalAdapter.findVerificationValue(i);if(!r||r.expiresAt<new Date)throw new uo.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(r.id);let n=r.value,a=await e.context.password.hash(o);return(await e.context.internalAdapter.findAccounts(n)).find(A=>A.providerId==="credential")?(await e.context.internalAdapter.updatePassword(n,a),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:a,accountId:n}),e.json({status:!0}))});var _=require("zod");var G=require("better-call");var bi=()=>c("/update-user",{method:"POST",body:_.z.record(_.z.string(),_.z.any()),use:[v],metadata:{openapi:{description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"}}}}}}}}}},async e=>{let t=e.body;if(t.email)throw new G.APIError("BAD_REQUEST",{message:"You can't update email"});let{name:o,image:i,...r}=t,n=e.context.session;if(i===void 0&&!o&&Object.keys(r).length===0)return e.json({user:n.user});let a=so(e.context.options,r,"update"),s=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:o,image:i,...a});return await m(e,{session:n.session,user:s}),e.json({user:s})}),vi=c("/change-password",{method:"POST",body:_.z.object({newPassword:_.z.string({description:"The new password to set"}),currentPassword:_.z.string({description:"The current password"}),revokeOtherSessions:_.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[v],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:o,revokeOtherSessions:i}=e.body,r=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new G.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 G.APIError("BAD_REQUEST",{message:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(r.user.id)).find(u=>u.providerId==="credential"&&u.password);if(!d||!d.password)throw new G.APIError("BAD_REQUEST",{message:"User does not have a password"});let A=await e.context.password.hash(t);if(!await e.context.password.verify({hash:d.password,password:o}))throw new G.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:A}),i){await e.context.internalAdapter.deleteSessions(r.user.id);let u=await e.context.internalAdapter.createSession(r.user.id,e.headers);if(!u)throw new G.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await m(e,{session:u,user:r.user})}return e.json(r.user)}),ki=c("/set-password",{method:"POST",body:_.z.object({newPassword:_.z.string()}),metadata:{SERVER_ONLY:!0},use:[v]},async e=>{let{newPassword:t}=e.body,o=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new G.APIError("BAD_REQUEST",{message:"Password is too short"});let r=e.context.password.config.maxPasswordLength;if(t.length>r)throw e.context.logger.error("Password is too long"),new G.APIError("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(o.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:o.user.id,providerId:"credential",accountId:o.user.id,password:s}),e.json(o.user);throw new G.APIError("BAD_REQUEST",{message:"user already has a password"})}),Ti=c("/delete-user",{method:"POST",body:_.z.object({password:_.z.string({description:"The password of the user"})}),use:[He],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{let t=e.context.session;return await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),Q(e),e.json(null)}),Oi=c("/change-email",{method:"POST",query:_.z.object({currentURL:_.z.string().optional()}).optional(),body:_.z.object({newEmail:_.z.string({description:"The new email to set"}).email(),callbackURL:_.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[v],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new G.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 G.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 G.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let r=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:r,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new G.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let o=await Ke(e.context.secret,e.context.session.user.email,e.body.newEmail),i=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:i,token:o},e.request),e.json({user:null,status:!0})});var Se=require("zod");var So=require("better-call");var Ii=c("/list-accounts",{method:"GET",use:[v],metadata:{openapi:{description:"List all accounts linked to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},provider:{type:"string"}}}}}}}}}}},async e=>{let t=e.context.session,o=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(o.map(i=>({id:i.id,provider:i.providerId})))}),Ui=c("/link-social",{method:"POST",requireHeaders:!0,query:Se.z.object({currentURL:Se.z.string().optional()}).optional(),body:Se.z.object({callbackURL:Se.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:Se.z.enum(Ko,{description:"The OAuth2 provider to use"})}),use:[v],metadata:{openapi:{description:"Link a social account to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}},required:["url","redirect"]}}}}}}}},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 So.APIError("BAD_REQUEST",{message:"Social Account is already linked."});let r=e.context.socialProviders.find(s=>s.id===e.body.provider);if(!r)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new So.APIError("NOT_FOUND",{message:"Provider not found"});let n=await Ue(e,{userId:t.user.id,email:t.user.email}),a=await r.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${r.id}`});return e.json({url:a.toString(),redirect:!0})});var Kt=(e,t)=>{let o={};for(let[i,r]of Object.entries(e))o[i]=n=>r({...n,context:{...t,...n.context}}),o[i].path=r.path,o[i].method=r.method,o[i].options=r.options,o[i].headers=r.headers;return o};function lo(e){let t=e;return{newRole(o){return Rr(o)}}}function Rr(e){return{statements:e,authorize(t,o){for(let[i,r]of Object.entries(t)){let n=e[i];return n?(o==="OR"?r.some(s=>n.includes(s)):r.every(s=>n.includes(s)))?{success:!0}:{success:!1,error:`Unauthorized to access resource "${i}"`}:{success:!1,error:`You are not allowed to access resource: ${i}`}}return{success:!1,error:"Not authorized"}}}}var Pr={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},Do=lo(Pr),Er=Do.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),Sr=Do.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),Dr=Do.newRole({organization:[],member:[],invitation:[]}),pt={admin:Er,owner:Sr,member:Dr};var xr={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},jr=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,ut={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},zr=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Br(e){return e instanceof Date&&!isNaN(e.getTime())}function Nr(e){let t=zr.exec(e);if(!t)return null;let[,o,i,r,n,a,s,d,A,K,u]=t,p=new Date(Date.UTC(parseInt(o,10),parseInt(i,10)-1,parseInt(r,10),parseInt(n,10),parseInt(a,10),parseInt(s,10),d?parseInt(d.padEnd(3,"0"),10):0));if(A){let l=(parseInt(K,10)*60+parseInt(u,10))*(A==="+"?-1:1);p.setUTCMinutes(p.getUTCMinutes()+l)}return Br(p)?p:null}function _r(e,t={}){let{strict:o=!1,warnings:i=!1,reviver:r,parseDates:n=!0}=t;if(typeof e!="string")return e;let a=e.trim();if(a[0]==='"'&&a.endsWith('"')&&!a.slice(1,-1).includes('"'))return a.slice(1,-1);let s=a.toLowerCase();if(s.length<=9&&s in ut)return ut[s];if(!jr.test(a)){if(o)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(xr).some(([A,K])=>{let u=K.test(a);return u&&i&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${A} pattern`),u})&&o)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(a,(K,u)=>{if(K==="__proto__"||K==="constructor"&&u&&typeof u=="object"&&"prototype"in u){i&&console.warn(`[better-json] Dropping "${K}" key to prevent prototype pollution`);return}if(n&&typeof u=="string"){let p=Nr(u);if(p)return p}return r?r(K,u):u})}catch(A){if(o)throw A;return e}}function lt(e,t={strict:!0}){return _r(e,t)}var gt=lt;var z=(e,t)=>{let o=e.adapter;return{findOrganizationBySlug:async i=>await o.findOne({model:"organization",where:[{field:"slug",value:i}]}),createOrganization:async i=>{let r=await o.create({model:"organization",data:{...i.organization,metadata:i.organization.metadata?JSON.stringify(i.organization.metadata):void 0}}),n=await o.create({model:"member",data:{organizationId:r.id,userId:i.user.id,createdAt:new Date,role:t?.creatorRole||"owner"}});return{...r,metadata:r.metadata?JSON.parse(r.metadata):void 0,members:[{...n,user:{id:i.user.id,name:i.user.name,email:i.user.email,image:i.user.image}}]}},findMemberByEmail:async i=>{let r=await o.findOne({model:"user",where:[{field:"email",value:i.email}]});if(!r)return null;let n=await o.findOne({model:"member",where:[{field:"organizationId",value:i.organizationId},{field:"userId",value:r.id}]});return n?{...n,user:{id:r.id,name:r.name,email:r.email,image:r.image}}:null},findMemberByOrgId:async i=>{let[r,n]=await Promise.all([await o.findOne({model:"member",where:[{field:"userId",value:i.userId},{field:"organizationId",value:i.organizationId}]}),await o.findOne({model:"user",where:[{field:"id",value:i.userId}]})]);return!n||!r?null:{...r,user:{id:n.id,name:n.name,email:n.email,image:n.image}}},findMemberById:async i=>{let r=await o.findOne({model:"member",where:[{field:"id",value:i}]});if(!r)return null;let n=await o.findOne({model:"user",where:[{field:"id",value:r.userId}]});return n?{...r,user:{id:n.id,name:n.name,email:n.email,image:n.image}}:null},createMember:async i=>await o.create({model:"member",data:i}),updateMember:async(i,r)=>await o.update({model:"member",where:[{field:"id",value:i}],update:{role:r}}),deleteMember:async i=>await o.delete({model:"member",where:[{field:"id",value:i}]}),updateOrganization:async(i,r)=>{let n=await o.update({model:"organization",where:[{field:"id",value:i}],update:{...r,metadata:typeof r.metadata=="object"?JSON.stringify(r.metadata):r.metadata}});return n?{...n,metadata:n.metadata?gt(n.metadata):void 0}:null},deleteOrganization:async i=>(await o.delete({model:"member",where:[{field:"organizationId",value:i}]}),await o.delete({model:"invitation",where:[{field:"organizationId",value:i}]}),await o.delete({model:"organization",where:[{field:"id",value:i}]}),i),setActiveOrganization:async(i,r)=>await e.internalAdapter.updateSession(i,{activeOrganizationId:r}),findOrganizationById:async i=>await o.findOne({model:"organization",where:[{field:"id",value:i}]}),findFullOrganization:async({organizationId:i,isSlug:r})=>{let n=await o.findOne({model:"organization",where:[{field:r?"slug":"id",value:i}]});if(!n)return null;let[a,s]=await Promise.all([o.findMany({model:"invitation",where:[{field:"organizationId",value:n.id}]}),o.findMany({model:"member",where:[{field:"organizationId",value:n.id}]})]);if(!n)return null;let d=s.map(p=>p.userId),A=await o.findMany({model:"user",where:[{field:"id",value:d,operator:"in"}]}),K=new Map(A.map(p=>[p.id,p])),u=s.map(p=>{let l=K.get(p.userId);if(!l)throw new ee("Unexpected error: User not found for member");return{...p,user:{id:l.id,name:l.name,email:l.email,image:l.image}}});return{...n,invitations:a,members:u}},listOrganizations:async i=>{let r=await o.findMany({model:"member",where:[{field:"userId",value:i}]});if(!r||r.length===0)return[];let n=r.map(s=>s.organizationId);return await o.findMany({model:"organization",where:[{field:"id",value:n,operator:"in"}]})},createInvitation:async({invitation:i,user:r})=>{let a=R(t?.invitationExpiresIn||1728e5);return await o.create({model:"invitation",data:{email:i.email,role:i.role,organizationId:i.organizationId,status:"pending",expiresAt:a,inviterId:r.id}})},findInvitationById:async i=>await o.findOne({model:"invitation",where:[{field:"id",value:i}]}),findPendingInvitation:async i=>(await o.findMany({model:"invitation",where:[{field:"email",value:i.email},{field:"organizationId",value:i.organizationId},{field:"status",value:"pending"}]})).filter(n=>new Date(n.expiresAt)>new Date),updateInvitation:async i=>await o.update({model:"invitation",where:[{field:"id",value:i.invitationId}],update:{status:i.status}})}};var OA=require("better-call");var B=P(async e=>({})),M=P({use:[v]},async e=>({session:e.context.session}));var W=require("zod");var E=require("zod");var mt=E.z.string(),Lr=E.z.enum(["pending","accepted","rejected","canceled"]).default("pending"),SA=E.z.object({id:E.z.string().default(V),name:E.z.string(),slug:E.z.string(),logo:E.z.string().nullish(),metadata:E.z.record(E.z.string()).or(E.z.string().transform(e=>JSON.parse(e))).nullish(),createdAt:E.z.date()}),DA=E.z.object({id:E.z.string().default(V),organizationId:E.z.string(),userId:E.z.string(),role:mt,createdAt:E.z.date()}),xA=E.z.object({id:E.z.string().default(V),organizationId:E.z.string(),email:E.z.string(),role:mt,status:Lr,inviterId:E.z.string(),expiresAt:E.z.date()});var j=require("better-call"),ft=e=>c("/organization/invite-member",{method:"POST",use:[B,M],body:W.z.object({email:W.z.string({description:"The email address of the user to invite"}),role:W.z.string({description:"The role to assign to the user"}),organizationId:W.z.string({description:"The organization ID to invite the user to"}).optional(),resend:W.z.boolean({description:"Resend the invitation email, if the user is already invited"}).optional()}),metadata:{openapi:{description:"Invite a user to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt"]}}}}}}}},async t=>{if(!t.context.orgOptions.sendInvitationEmail)throw t.context.logger.warn("Invitation email is not enabled. Pass `sendInvitationEmail` to the plugin options to enable it."),new j.APIError("BAD_REQUEST",{message:"Invitation email is not enabled"});let o=t.context.session,i=t.body.organizationId||o.session.activeOrganizationId;if(!i)throw new j.APIError("BAD_REQUEST",{message:"Organization not found"});let r=z(t.context,t.context.orgOptions),n=await r.findMemberByOrgId({userId:o.user.id,organizationId:i});if(!n)throw new j.APIError("BAD_REQUEST",{message:"Member not found!"});let a=t.context.roles[n.role];if(!a)throw new j.APIError("BAD_REQUEST",{message:"Role not found!"});if(a.authorize({invitation:["create"]}).error)throw new j.APIError("FORBIDDEN",{message:"You are not allowed to invite members"});if(await r.findMemberByEmail({email:t.body.email,organizationId:i}))throw new j.APIError("BAD_REQUEST",{message:"User is already a member of this organization"});if((await r.findPendingInvitation({email:t.body.email,organizationId:i})).length&&!t.body.resend)throw new j.APIError("BAD_REQUEST",{message:"User is already invited to this organization"});let K=await r.createInvitation({invitation:{role:t.body.role,email:t.body.email,organizationId:i},user:o.user}),u=await r.findOrganizationById(i);if(!u)throw new j.APIError("BAD_REQUEST",{message:"Organization not found"});return await t.context.orgOptions.sendInvitationEmail?.({id:K.id,role:K.role,email:K.email,organization:u,inviter:{...n,user:o.user}},t.request),t.json(K)}),ht=c("/organization/accept-invitation",{method:"POST",body:W.z.object({invitationId:W.z.string({description:"The ID of the invitation to accept"})}),use:[B,M],metadata:{openapi:{description:"Accept an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"},member:{type:"object"}}}}}}}}}},async e=>{let t=e.context.session,o=z(e.context,e.context.orgOptions),i=await o.findInvitationById(e.body.invitationId);if(!i||i.expiresAt<new Date||i.status!=="pending")throw new j.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(i.email!==t.user.email)throw new j.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let r=await o.updateInvitation({invitationId:e.body.invitationId,status:"accepted"}),n=await o.createMember({organizationId:i.organizationId,userId:t.user.id,role:i.role,createdAt:new Date});return await o.setActiveOrganization(t.session.token,i.organizationId),r?e.json({invitation:r,member:n}):e.json(null,{status:400,body:{message:"Invitation not found!"}})}),yt=c("/organization/reject-invitation",{method:"POST",body:W.z.object({invitationId:W.z.string({description:"The ID of the invitation to reject"})}),use:[B,M],metadata:{openapi:{description:"Reject an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"},member:{type:"null"}}}}}}}}}},async e=>{let t=e.context.session,o=z(e.context,e.context.orgOptions),i=await o.findInvitationById(e.body.invitationId);if(!i||i.expiresAt<new Date||i.status!=="pending")throw new j.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(i.email!==t.user.email)throw new j.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let r=await o.updateInvitation({invitationId:e.body.invitationId,status:"rejected"});return e.json({invitation:r,member:null})}),wt=c("/organization/cancel-invitation",{method:"POST",body:W.z.object({invitationId:W.z.string({description:"The ID of the invitation to cancel"})}),use:[B,M],openapi:{description:"Cancel an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"}}}}}}}}},async e=>{let t=e.context.session,o=z(e.context,e.context.orgOptions),i=await o.findInvitationById(e.body.invitationId);if(!i)throw new j.APIError("BAD_REQUEST",{message:"Invitation not found!"});let r=await o.findMemberByOrgId({userId:t.user.id,organizationId:i.organizationId});if(!r)throw new j.APIError("BAD_REQUEST",{message:"Member not found!"});if(e.context.roles[r.role].authorize({invitation:["cancel"]}).error)throw new j.APIError("FORBIDDEN",{message:"You are not allowed to cancel this invitation"});let a=await o.updateInvitation({invitationId:e.body.invitationId,status:"canceled"});return e.json(a)}),Ct=c("/organization/get-invitation",{method:"GET",use:[B],requireHeaders:!0,query:W.z.object({id:W.z.string({description:"The ID of the invitation to get"})}),metadata:{openapi:{description:"Get an invitation by ID",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"},organizationName:{type:"string"},organizationSlug:{type:"string"},inviterEmail:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt","organizationName","organizationSlug","inviterEmail"]}}}}}}}},async e=>{let t=await U(e);if(!t)throw new j.APIError("UNAUTHORIZED",{message:"Not authenticated"});let o=z(e.context,e.context.orgOptions),i=await o.findInvitationById(e.query.id);if(!i||i.status!=="pending"||i.expiresAt<new Date)throw new j.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(i.email!==t.user.email)throw new j.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let r=await o.findOrganizationById(i.organizationId);if(!r)throw new j.APIError("BAD_REQUEST",{message:"Organization not found"});let n=await o.findMemberByOrgId({userId:i.inviterId,organizationId:i.organizationId});if(!n)throw new j.APIError("BAD_REQUEST",{message:"Inviter is no longer a member of the organization"});return e.json({...i,organizationName:r.name,organizationSlug:r.slug,inviterEmail:n.user.email})});var te=require("zod");var ge=require("better-call");var bt=()=>c("/organization/add-member",{method:"POST",body:te.z.object({userId:te.z.string(),role:te.z.string(),organizationId:te.z.string().optional()}),use:[B],metadata:{SERVER_ONLY:!0}},async e=>{let t=e.body.userId?await U(e).catch(s=>null):null,o=e.body.organizationId||t?.session.activeOrganizationId;if(!o)return e.json(null,{status:400,body:{message:"No active organization found!"}});let i=z(e.context,e.context.orgOptions),r=await e.context.internalAdapter.findUserById(e.body.userId);if(!r)throw new ge.APIError("BAD_REQUEST",{message:"User not found!"});if(await i.findMemberByEmail({email:r.email,organizationId:o}))throw new ge.APIError("BAD_REQUEST",{message:"User is already a member of this organization"});let a=await i.createMember({id:V(),organizationId:o,userId:r.id,role:e.body.role,createdAt:new Date});return e.json(a)}),vt=c("/organization/remove-member",{method:"POST",body:te.z.object({memberIdOrEmail:te.z.string({description:"The ID or email of the member to remove"}),organizationId:te.z.string({description:"The ID of the organization to remove the member from. If not provided, the active organization will be used"}).optional()}),use:[B,M],metadata:{openapi:{description:"Remove a member from an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{member:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}},required:["member"]}}}}}}}},async e=>{let t=e.context.session,o=e.body.organizationId||t.session.activeOrganizationId;if(!o)return e.json(null,{status:400,body:{message:"No active organization found!"}});let i=z(e.context,e.context.orgOptions),r=await i.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!r)throw new ge.APIError("BAD_REQUEST",{message:"Member not found!"});let n=e.context.roles[r.role];if(!n)throw new ge.APIError("BAD_REQUEST",{message:"Role not found!"});let a=t.user.email===e.body.memberIdOrEmail||r.id===e.body.memberIdOrEmail;if(a&&r.role===(e.context.orgOptions?.creatorRole||"owner"))throw new ge.APIError("BAD_REQUEST",{message:"You cannot leave the organization as the owner"});if(!(a||n.authorize({member:["delete"]}).success))throw new ge.APIError("UNAUTHORIZED",{message:"You are not allowed to delete this member"});let A=null;if(e.body.memberIdOrEmail.includes("@")?A=await i.findMemberByEmail({email:e.body.memberIdOrEmail,organizationId:o}):A=await i.findMemberById(e.body.memberIdOrEmail),A?.organizationId!==o)throw new ge.APIError("BAD_REQUEST",{message:"Member not found!"});return await i.deleteMember(A.id),t.user.id===A.userId&&t.session.activeOrganizationId===A.organizationId&&await i.setActiveOrganization(t.session.token,null),e.json({member:A})}),kt=e=>c("/organization/update-member-role",{method:"POST",body:te.z.object({role:te.z.string(),memberId:te.z.string(),organizationId:te.z.string().optional()}),use:[B,M],metadata:{openapi:{description:"Update the role of a member in an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{member:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}},required:["member"]}}}}}}}},async t=>{let o=t.context.session,i=t.body.organizationId||o.session.activeOrganizationId;if(!i)return t.json(null,{status:400,body:{message:"No active organization found!"}});let r=z(t.context,t.context.orgOptions),n=await r.findMemberByOrgId({userId:o.user.id,organizationId:i});if(!n)return t.json(null,{status:400,body:{message:"Member not found!"}});let a=t.context.roles[n.role];if(!a)return t.json(null,{status:400,body:{message:"Role not found!"}});if(a.authorize({member:["update"]}).error||t.body.role==="owner"&&n.role!=="owner")return t.json(null,{body:{message:"You are not allowed to update this member"},status:403});let d=await r.updateMember(t.body.memberId,t.body.role);return d?t.json(d):t.json(null,{status:400,body:{message:"Member not found!"}})}),Tt=c("/organization/get-active-member",{method:"GET",use:[B,M],metadata:{openapi:{description:"Get the active member in the organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}}}}}}}},async e=>{let t=e.context.session,o=t.session.activeOrganizationId;if(!o)return e.json(null,{status:400,body:{message:"No active organization found!"}});let r=await z(e.context,e.context.orgOptions).findMemberByOrgId({userId:t.user.id,organizationId:o});return r?e.json(r):e.json(null,{status:400,body:{message:"Member not found!"}})});var O=require("zod");var me=require("better-call");var Ot=c("/organization/create",{method:"POST",body:O.z.object({name:O.z.string({description:"The name of the organization"}),slug:O.z.string({description:"The slug of the organization"}),userId:O.z.string({description:"The user id of the organization creator. If not provided, the current user will be used. Should only be used by admins or when called by the server."}).optional(),logo:O.z.string({description:"The logo of the organization"}).optional(),metadata:O.z.record(O.z.string(),O.z.any(),{description:"The metadata of the organization"}).optional()}),use:[B,M],metadata:{openapi:{description:"Create an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization that was created",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=e.context.session.user;if(!t)return e.json(null,{status:401});let o=e.context.orgOptions;if(!(typeof o?.allowUserToCreateOrganization=="function"?await o.allowUserToCreateOrganization(t):o?.allowUserToCreateOrganization===void 0?!0:o.allowUserToCreateOrganization))throw new me.APIError("FORBIDDEN",{message:"You are not allowed to create an organization"});let r=z(e.context,o),n=await r.listOrganizations(t.id);if(typeof o.organizationLimit=="number"?n.length>=o.organizationLimit:typeof o.organizationLimit=="function"?await o.organizationLimit(t):!1)throw new me.APIError("FORBIDDEN",{message:"You have reached the organization limit"});if(await r.findOrganizationBySlug(e.body.slug))throw new me.APIError("BAD_REQUEST",{message:"Organization with this slug already exists"});let d=await r.createOrganization({organization:{id:V(),slug:e.body.slug,name:e.body.name,logo:e.body.logo,createdAt:new Date,metadata:e.body.metadata},user:t});return await r.setActiveOrganization(e.context.session.session.token,d.id),e.json(d)}),It=c("/organization/update",{method:"POST",body:O.z.object({data:O.z.object({name:O.z.string({description:"The name of the organization"}).optional(),slug:O.z.string({description:"The slug of the organization"}).optional(),logo:O.z.string({description:"The logo of the organization"}).optional(),metadata:O.z.record(O.z.string(),O.z.any(),{description:"The metadata of the organization"}).optional()}).partial(),organizationId:O.z.string().optional()}),requireHeaders:!0,use:[B],metadata:{openapi:{description:"Update an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The updated organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=await e.context.getSession(e);if(!t)throw new me.APIError("UNAUTHORIZED",{message:"User not found"});let o=e.body.organizationId||t.session.activeOrganizationId;if(!o)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let i=z(e.context,e.context.orgOptions),r=await i.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!r)return e.json(null,{status:400,body:{message:"User is not a member of this organization!"}});let n=e.context.roles[r.role];if(!n)return e.json(null,{status:400,body:{message:"Role not found!"}});if(n.authorize({organization:["update"]}).error)return e.json(null,{body:{message:"You are not allowed to update this organization"},status:403});let s=await i.updateOrganization(o,e.body.data);return e.json(s)}),Ut=c("/organization/delete",{method:"POST",body:O.z.object({organizationId:O.z.string({description:"The organization id to delete"})}),requireHeaders:!0,use:[B],metadata:{openapi:{description:"Delete an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string",description:"The organization id that was deleted"}}}}}}}},async e=>{let t=await e.context.getSession(e);if(!t)return e.json(null,{status:401});let o=e.body.organizationId;if(!o)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let i=z(e.context,e.context.orgOptions),r=await i.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!r)return e.json(null,{status:400,body:{message:"User is not a member of this organization!"}});let n=e.context.roles[r.role];if(!n)return e.json(null,{status:400,body:{message:"Role not found!"}});if(n.authorize({organization:["delete"]}).error)throw new me.APIError("FORBIDDEN",{message:"You are not allowed to delete this organization"});return o===t.session.activeOrganizationId&&await i.setActiveOrganization(t.session.token,null),await i.deleteOrganization(o),e.json(o)}),Rt=c("/organization/get-full-organization",{method:"GET",query:O.z.optional(O.z.object({organizationId:O.z.string({description:"The organization id to get"}).optional(),organizationSlug:O.z.string({description:"The organization slug to get"}).optional()})),requireHeaders:!0,use:[B,M],metadata:{openapi:{description:"Get the full organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=e.context.session,o=e.query?.organizationSlug||e.query?.organizationId||t.session.activeOrganizationId;if(!o)return e.json(null,{status:200});let r=await z(e.context,e.context.orgOptions).findFullOrganization({organizationId:o,isSlug:!!e.query?.organizationSlug});if(!r)throw new me.APIError("BAD_REQUEST",{message:"Organization not found"});return e.json(r)}),Pt=c("/organization/set-active",{method:"POST",body:O.z.object({organizationId:O.z.string({description:"The organization id to set as active. It can be null to unset the active organization"}).nullable().optional(),organizationSlug:O.z.string({description:"The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided"}).optional()}),use:[M,B],metadata:{openapi:{description:"Set the active organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=z(e.context,e.context.orgOptions),o=e.context.session,i=e.body.organizationSlug||e.body.organizationId;if(i===null){if(!o.session.activeOrganizationId)return e.json(null);let d=await t.setActiveOrganization(o.session.token,null);return await m(e,{session:d,user:o.user}),e.json(null)}if(!i){let s=o.session.activeOrganizationId;if(!s)return e.json(null);i=s}let r=await t.findFullOrganization({organizationId:i,isSlug:!!e.body.organizationSlug});if(!r?.members.find(s=>s.userId===o.user.id))throw await t.setActiveOrganization(o.session.token,null),new me.APIError("FORBIDDEN",{message:"You are not a member of this organization"});let a=await t.setActiveOrganization(o.session.token,i);return await m(e,{session:a,user:o.user}),e.json(r)}),Et=c("/organization/list",{method:"GET",use:[B,M],metadata:{openapi:{description:"List all organizations",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Organization"}}}}}}}}},async e=>{let o=await z(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(o)});var Fr=lo({name:["action"]}),Ac=Fr.newRole({name:["action"]}),Vr=e=>{let t={createOrganization:Ot,updateOrganization:It,deleteOrganization:Ut,setActiveOrganization:Pt,getFullOrganization:Rt,listOrganizations:Et,createInvitation:ft(e),cancelInvitation:wt,acceptInvitation:ht,getInvitation:Ct,rejectInvitation:yt,addMember:bt(),removeMember:vt,updateMemberRole:kt(e),getActiveMember:Tt},o={...pt,...e?.roles};return{id:"organization",endpoints:{...Kt(t,{orgOptions:e||{},roles:o,getSession:async r=>await U(r)}),hasPermission:c("/organization/has-permission",{method:"POST",requireHeaders:!0,body:De.z.object({permission:De.z.record(De.z.string(),De.z.array(De.z.string()))}),use:[M],metadata:{openapi:{description:"Check if the user has permission",requestBody:{content:{"application/json":{schema:{type:"object",properties:{permission:{type:"object",description:"The permission to check"}},required:["permission"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},success:{type:"boolean"}},required:["success"]}}}}}}}},async r=>{if(!r.context.session.session.activeOrganizationId)throw new xo.APIError("BAD_REQUEST",{message:"No active organization"});let a=await z(r.context).findMemberByOrgId({userId:r.context.session.user.id,organizationId:r.context.session.session.activeOrganizationId||""});if(!a)throw new xo.APIError("UNAUTHORIZED",{message:"You are not a member of this organization"});let d=o[a.role].authorize(r.body.permission);return d.error?r.json({error:d.error,success:!1},{status:403}):r.json({error:null,success:!0})})},schema:{session:{fields:{activeOrganizationId:{type:"string",required:!1,fieldName:e?.schema?.session?.fields?.activeOrganizationId}}},organization:{modelName:e?.schema?.organization?.modelName,fields:{name:{type:"string",required:!0,fieldName:e?.schema?.organization?.fields?.name},slug:{type:"string",unique:!0,fieldName:e?.schema?.organization?.fields?.slug},logo:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.logo},createdAt:{type:"date",required:!0,fieldName:e?.schema?.organization?.fields?.createdAt},metadata:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.metadata}}},member:{modelName:e?.schema?.member?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.member?.fields?.organizationId},userId:{type:"string",required:!0,fieldName:e?.schema?.member?.fields?.userId,references:{model:"user",field:"id"}},role:{type:"string",required:!0,defaultValue:"member",fieldName:e?.schema?.member?.fields?.role},createdAt:{type:"date",required:!0,fieldName:e?.schema?.member?.fields?.createdAt}}},invitation:{modelName:e?.schema?.invitation?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.invitation?.fields?.organizationId},email:{type:"string",required:!0,fieldName:e?.schema?.invitation?.fields?.email},role:{type:"string",required:!1,fieldName:e?.schema?.invitation?.fields?.role},status:{type:"string",required:!0,defaultValue:"pending",fieldName:e?.schema?.invitation?.fields?.status},expiresAt:{type:"date",required:!0,fieldName:e?.schema?.invitation?.fields?.expiresAt},inviterId:{type:"string",references:{model:"user",field:"id"},fieldName:e?.schema?.invitation?.fields?.inviterId,required:!0}}}},$Infer:{Organization:{},Invitation:{},Member:{},ActiveOrganization:{}}}};var jo=Yo(require("uncrypto"),1);function qr(e){return e.toString(2).padStart(8,"0")}function Mr(e){return[...e].map(t=>qr(t)).join("")}function St(e){return parseInt(Mr(e),2)}function Hr(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,o=t%8,i=new Uint8Array(Math.ceil(t/8));jo.default.getRandomValues(i),o!==0&&(i[0]&=(1<<o)-1);let r=St(i);for(;r>=e;)jo.default.getRandomValues(i),o!==0&&(i[0]&=(1<<o)-1),r=St(i);return r}function L(e,t){let o="";for(let i=0;i<e;i++)o+=t[Hr(t.length)];return o}function F(...e){let t=new Set(e),o="";for(let i of t)i==="a-z"?o+="abcdefghijklmnopqrstuvwxyz":i==="A-Z"?o+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":i==="0-9"?o+="0123456789":o+=i;return o}var We=require("zod");var Bo=require("@noble/ciphers/chacha"),xe=require("@noble/ciphers/utils"),No=require("@noble/ciphers/webcrypto"),_o=require("oslo/crypto"),zo=Yo(require("uncrypto"),1);var Dt=require("oslo/encoding");var Qr=require("@noble/hashes/scrypt"),$r=require("uncrypto");async function $e(e,t){let o=new TextEncoder,i={name:"HMAC",hash:"SHA-256"},r=await zo.default.subtle.importKey("raw",o.encode(e),i,!1,["sign","verify"]),n=await zo.default.subtle.sign(i.name,r,o.encode(t));return btoa(String.fromCharCode(...new Uint8Array(n)))}var ue=async({key:e,data:t})=>{let o=await(0,_o.sha256)(new TextEncoder().encode(e)),i=(0,xe.utf8ToBytes)(t),r=(0,No.managedNonce)(Bo.xchacha20poly1305)(new Uint8Array(o));return(0,xe.bytesToHex)(r.encrypt(i))},fe=async({key:e,data:t})=>{let o=await(0,_o.sha256)(new TextEncoder().encode(e)),i=(0,xe.hexToBytes)(t),r=(0,No.managedNonce)(Bo.xchacha20poly1305)(new Uint8Array(o));return new TextDecoder().decode(r.decrypt(i))};var Ae=require("zod");var je=require("better-call");var go="two_factor";var mo="trust_device";var Lo=require("zod");var be=P({body:Lo.z.object({trustDevice:Lo.z.boolean().optional()})},async e=>{let t=await U(e);if(!t){let o=e.context.createAuthCookie(go),i=await e.getSignedCookie(o.name,e.context.secret);if(!i)throw new je.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let r=await e.context.internalAdapter.findUserById(i);if(!r)throw new je.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let n=await e.context.internalAdapter.createSession(i,e.request);if(!n)throw new je.APIError("INTERNAL_SERVER_ERROR",{message:"failed to create session"});return{valid:async()=>{if(await m(e,{session:n,user:r}),e.body.trustDevice){let a=e.context.createAuthCookie(mo,{maxAge:2592e3}),s=await $e(e.context.secret,`${r.id}!${n.token}`);await e.setSignedCookie(a.name,`${s}!${n.token}`,e.context.secret,a.attributes)}return e.json({session:n,user:r})},invalid:async()=>{throw new je.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:{id:n.token,userId:n.userId,expiresAt:n.expiresAt,user:r}}}return{valid:async()=>e.json({session:t,user:t.user}),invalid:async()=>{throw new je.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:t}});var ze=require("better-call");function Zr(e){return Array.from({length:e?.amount??10}).fill(null).map(()=>L(e?.length??10,F("a-z","0-9"))).map(t=>`${t.slice(0,5)}-${t.slice(5)}`)}async function Fo(e,t){let o=e,i=t?.customBackupCodesGenerate?t.customBackupCodesGenerate():Zr(),r=await ue({data:JSON.stringify(i),key:o});return{backupCodes:i,encryptedBackupCodes:r}}async function Gr(e,t){let o=await xt(e.backupCodes,t);return o?{status:o.includes(e.code),updated:o.filter(i=>i!==e.code)}:{status:!1,updated:null}}async function xt(e,t){let o=Buffer.from(await fe({key:t,data:e})).toString("utf-8"),i=JSON.parse(o),r=Ae.z.array(Ae.z.string()).safeParse(i);return r.success?r.data:null}var jt=(e,t)=>({id:"backup_code",endpoints:{verifyBackupCode:c("/two-factor/verify-backup-code",{method:"POST",body:Ae.z.object({code:Ae.z.string(),disableSession:Ae.z.boolean().optional()}),use:[be]},async o=>{let i=o.context.session.user,r=await o.context.adapter.findOne({model:t,where:[{field:"userId",value:i.id}]});if(!r)throw new ze.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let n=await Gr({backupCodes:r.backupCodes,code:o.body.code},o.context.secret);if(!n.status)throw new ze.APIError("UNAUTHORIZED",{message:"Invalid backup code"});let a=await ue({key:o.context.secret,data:JSON.stringify(n.updated)});return await o.context.adapter.update({model:t,update:{backupCodes:a},where:[{field:"userId",value:i.id}]}),o.body.disableSession||await m(o,{session:o.context.session.session,user:i}),o.json({user:i,session:o.context.session})}),generateBackupCodes:c("/two-factor/generate-backup-codes",{method:"POST",body:Ae.z.object({password:Ae.z.string()}),use:[v]},async o=>{let i=o.context.session.user;if(!i.twoFactorEnabled)throw new ze.APIError("BAD_REQUEST",{message:"Two factor isn't enabled"});await o.context.password.checkPassword(i.id,o);let r=await Fo(o.context.secret,e);return await o.context.adapter.update({model:t,update:{backupCodes:r.encryptedBackupCodes},where:[{field:"userId",value:o.context.session.user.id}]}),o.json({status:!0,backupCodes:r.backupCodes})}),viewBackupCodes:c("/two-factor/view-backup-codes",{method:"GET",body:Ae.z.object({userId:Ae.z.string()}),metadata:{SERVER_ONLY:!0}},async o=>{let i=await o.context.adapter.findOne({model:t,where:[{field:"userId",value:o.body.userId}]});if(!i)throw new ze.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let r=await xt(i.backupCodes,o.context.secret);if(!r)throw new ze.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});return o.json({status:!0,backupCodes:r})})}});var Be=require("better-call"),Vo=require("zod");var zt=require("oslo");var Bt=(e,t)=>{let o={...e,digits:e?.digits||6,period:new zt.TimeSpan(e?.period||3,"m")},i=c("/two-factor/send-otp",{method:"POST",use:[be],metadata:{openapi:{summary:"Send two factor OTP",description:"Send two factor OTP to the user",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async n=>{if(!e||!e.sendOTP)throw n.context.logger.error("send otp isn't configured. Please configure the send otp function on otp options."),new Be.APIError("BAD_REQUEST",{message:"otp isn't configured"});let a=n.context.session.user;if(!await n.context.adapter.findOne({model:t,where:[{field:"userId",value:a.id}]}))throw new Be.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});let d=L(o.digits,F("0-9"));return await n.context.internalAdapter.createVerificationValue({value:d,identifier:`2fa-otp-${a.id}`,expiresAt:new Date(Date.now()+o.period.milliseconds())}),await e.sendOTP({user:a,otp:d},n.request),n.json({status:!0})}),r=c("/two-factor/verify-otp",{method:"POST",body:Vo.z.object({code:Vo.z.string({description:"The otp code to verify"})}),use:[be],metadata:{openapi:{summary:"Verify two factor OTP",description:"Verify two factor OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async n=>{let a=n.context.session.user;if(!a.twoFactorEnabled)throw new Be.APIError("BAD_REQUEST",{message:"two factor isn't enabled"});if(!await n.context.adapter.findOne({model:t,where:[{field:"userId",value:a.id}]}))throw new Be.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});let d=await n.context.internalAdapter.findVerificationValue(`2fa-otp-${a.id}`);if(!d||d.expiresAt<new Date)throw new Be.APIError("BAD_REQUEST",{message:"OTP has expired"});return d.value===n.body.code?n.context.valid():n.context.invalid()});return{id:"otp",endpoints:{sendTwoFactorOTP:i,verifyTwoFactorOTP:r}}};var ve=require("better-call"),Nt=require("oslo"),Ge=require("oslo/otp"),Ze=require("zod");var _t=(e,t)=>{let o={...e,digits:e?.digits||6,period:new Nt.TimeSpan(e?.period||30,"s")},i=c("/totp/generate",{method:"POST",use:[v],metadata:{openapi:{summary:"Generate TOTP code",description:"Use this endpoint to generate a TOTP code",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{code:{type:"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 ve.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 ve.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return{code:await new Ge.TOTPController(o).generate(Buffer.from(d.secret))}}),r=c("/two-factor/get-totp-uri",{method:"POST",use:[v],body:Ze.z.object({password:Ze.z.string({description:"User password"})}),metadata:{openapi:{summary:"Get TOTP URI",description:"Use this endpoint to get the TOTP URI",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{totpURI:{type:"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 ve.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 ve.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return await a.context.password.checkPassword(s.id,a),{totpURI:(0,Ge.createTOTPKeyURI)(e.issuer||a.context.appName,s.email,Buffer.from(d.secret),o)}}),n=c("/two-factor/verify-totp",{method:"POST",body:Ze.z.object({code:Ze.z.string({description:"The otp code to verify"})}),use:[be],metadata:{openapi:{summary:"Verify two factor TOTP",description:"Verify two factor TOTP",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},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 ve.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 ve.APIError("BAD_REQUEST",{message:"totp isn't enabled"});let A=new Ge.TOTPController(o),K=await fe({key:a.context.secret,data:d.secret}),u=Buffer.from(K);if(!await A.verify(a.body.code,u))return a.context.invalid();if(!s.twoFactorEnabled){let l=await a.context.internalAdapter.updateUser(s.id,{twoFactorEnabled:!0}),h=await a.context.internalAdapter.createSession(s.id,a.request,!1,a.context.session.session).catch(k=>{throw console.log(k),k});await a.context.internalAdapter.deleteSession(a.context.session.session.token),await m(a,{session:h,user:l})}return a.context.valid()});return{id:"totp",endpoints:{generateTOTP:i,getTOTPURI:r,verifyTOTP:n}}};var Wr=require("better-call");async function qo(e,t){let i=(await e.context.internalAdapter.findAccounts(t.userId))?.find(a=>a.providerId==="credential"),r=i?.password;return!i||!r?!1:await e.context.password.verify({hash:r,password:t.password})}var Mo=require("better-call"),Vt=require("oslo/otp"),qt=require("oslo");var Lt=require("better-call"),Ne=async e=>{let t=e.context.returned;return t?t instanceof Response?t.status!==200?null:await t.clone().json():t instanceof Lt.APIError?null:t:null};var Ft={user:{fields:{twoFactorEnabled:{type:"boolean",required:!1,defaultValue:!1,input:!1}}},twoFactor:{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"}}}}};var Jr=e=>({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?.onTwoFactorRedirect&&await e.onTwoFactorRedirect()}}}]});var Xr=e=>{let t={twoFactorTable:"twoFactor"},o=_t({issuer:e?.issuer,...e?.totpOptions},t.twoFactorTable),i=jt({...e?.backupCodeOptions},t.twoFactorTable),r=Bt({...e?.otpOptions},t.twoFactorTable);return{id:"two-factor",endpoints:{...o.endpoints,...r.endpoints,...i.endpoints,enableTwoFactor:c("/two-factor/enable",{method:"POST",body:We.z.object({password:We.z.string({description:"User password"}).min(8)}),use:[v],metadata:{openapi:{summary:"Enable two factor authentication",description:"Use this endpoint to enable two factor authentication. This will generate a TOTP URI and backup codes. Once the user verifies the TOTP URI, the two factor authentication will be enabled.",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{totpURI:{type:"string",description:"TOTP URI"},backupCodes:{type:"array",items:{type:"string"},description:"Backup codes"}}}}}}}}}},async n=>{let a=n.context.session.user,{password:s}=n.body;if(!await qo(n,{password:s,userId:a.id}))throw new Mo.APIError("BAD_REQUEST",{message:"Invalid password"});let A=L(16,F("a-z","0-9","-")),K=await ue({key:n.context.secret,data:A}),u=await Fo(n.context.secret,e?.backupCodeOptions);if(e?.skipVerificationOnEnable){let l=await n.context.internalAdapter.updateUser(a.id,{twoFactorEnabled:!0}),h=await n.context.internalAdapter.createSession(l.id,n.request,!1,n.context.session.session);await m(n,{session:h,user:a}),await n.context.internalAdapter.deleteSession(n.context.session.session.token)}await n.context.adapter.deleteMany({model:t.twoFactorTable,where:[{field:"userId",value:a.id}]}),await n.context.adapter.create({model:t.twoFactorTable,data:{secret:K,backupCodes:u.encryptedBackupCodes,userId:a.id}});let p=(0,Vt.createTOTPKeyURI)(e?.issuer||"BetterAuth",a.email,Buffer.from(A),{digits:e?.totpOptions?.digits||6,period:new qt.TimeSpan(e?.totpOptions?.period||30,"s")});return n.json({totpURI:p,backupCodes:u.backupCodes})}),disableTwoFactor:c("/two-factor/disable",{method:"POST",body:We.z.object({password:We.z.string({description:"User password"}).min(8)}),use:[v],metadata:{openapi:{summary:"Disable two factor authentication",description:"Use this endpoint to disable two factor authentication.",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async n=>{let a=n.context.session.user,{password:s}=n.body;if(!await qo(n,{password:s,userId:a.id}))throw new Mo.APIError("BAD_REQUEST",{message:"Invalid password"});await n.context.internalAdapter.updateUser(a.id,{twoFactorEnabled:!1}),await n.context.adapter.delete({model:t.twoFactorTable,where:[{field:"userId",value:a.id}]});let A=await n.context.internalAdapter.createSession(a.id,n.request,!1,n.context.session.session);return await m(n,{session:A,user:a}),await n.context.internalAdapter.deleteSession(n.context.session.session.token),n.json({status:!0})})},options:e,hooks:{after:[{matcher(n){return n.path==="/sign-in/email"||n.path==="/sign-in/username"},handler:P(async n=>{let a=await Ne(n);if(!a||!a.user.twoFactorEnabled)return;let s=n.context.createAuthCookie(mo),d=await n.getSignedCookie(s.name,n.context.secret);if(d){let[K,u]=d.split("!"),p=await $e(n.context.secret,`${a.user.id}!${u}`);if(K===p){let l=await $e(n.context.secret,`${a.user.id}!${a.session.token}`);await n.setSignedCookie(s.name,`${l}!${a.session.token}`,n.context.secret,s.attributes);return}}Q(n),await n.context.internalAdapter.deleteSession(a.session.token);let A=n.context.createAuthCookie(go,{maxAge:60*10});return await n.setSignedCookie(A.name,a.user.id,n.context.secret,A.attributes),n.json({twoFactorRedirect:!0})})}]},schema:ie(Ft,e?.schema),rateLimit:[{pathMatcher(n){return n.startsWith("/two-factor/")},window:10,max:3}]}};var he=require("@simplewebauthn/server"),Z=require("better-call");var Y=require("zod");var _e=require("@simplewebauthn/browser");var en=require("@better-fetch/fetch");var bK=require("nanostores");var cK=require("@better-fetch/fetch");var Yr=require("nanostores");var pK=require("@better-fetch/fetch"),fo=require("nanostores"),Ho=(e,t,o,i)=>{let r=(0,fo.atom)({data:null,error:null,isPending:!0,isRefetching:!1}),n=()=>{let s=typeof i=="function"?i({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):i;return o(t,{...s,async onSuccess(d){r.set({data:d.data,error:null,isPending:!1,isRefetching:!1}),await s?.onSuccess?.(d)},async onError(d){r.set({error:d.error,data:null,isPending:!1,isRefetching:!1}),await s?.onError?.(d)},async onRequest(d){let A=r.get();r.set({isPending:A.data===null,data:A.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?n():(0,fo.onMount)(r,()=>(n(),a=!0,()=>{r.off(),s.off()}))});return r};var Mt=require("nanostores"),Ht=(e,{$listPasskeys:t})=>({signIn:{passkey:async(r,n)=>{let a=await e("/passkey/generate-authenticate-options",{method:"POST",body:{email:r?.email}});if(!a.data)return a;try{let s=await(0,_e.startAuthentication)(a.data,r?.autoFill||!1),d=await e("/passkey/verify-authentication",{body:{response:s},...r?.fetchOptions,...n,method:"POST"});if(!d.data)return d}catch{return{data:null,error:{message:"auth cancelled",status:400,statusText:"BAD_REQUEST"}}}}},passkey:{addPasskey:async(r,n)=>{let a=await e("/passkey/generate-register-options",{method:"GET"});if(!a.data)return a;try{let s=await(0,_e.startRegistration)(a.data),d=await e("/passkey/verify-registration",{...r?.fetchOptions,...n,body:{response:s,name:r?.name},method:"POST"});if(!d.data)return d;t.set(Math.random())}catch(s){return s instanceof _e.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:{}}),on=()=>{let e=(0,Mt.atom)();return{id:"passkey",$InferServerPlugin:{},getActions:t=>Ht(t,{$listPasskeys:e}),getAtoms(t){return{listPasskeys:Ho(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"||t==="/passkey/update-passkey"},signal:"_listPasskeys"}]}};var tn=e=>{let t=ne.BETTER_AUTH_URL,o=e?.rpID||t?.replace("http://","").replace("https://","").split(":")[0]||"localhost";if(!o)throw new ee("passkey rpID not found. Please provide a rpID in the options or set the BETTER_AUTH_URL environment variable.");let i={origin:null,...e,rpID:o,advanced:{webAuthnChallengeCookie:"better-auth-passkey",...e?.advanced}},r=new Date(Date.now()+1e3*60*5),n=new Date,a=Math.floor((r.getTime()-n.getTime())/1e3);return{id:"passkey",endpoints:{generatePasskeyRegistrationOptions:c("/passkey/generate-register-options",{method:"GET",use:[He],metadata:{client:!1,openapi:{description:"Generate registration options for a new passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{challenge:{type:"string"},rp:{type:"object",properties:{name:{type:"string"},id:{type:"string"}}},user:{type:"object",properties:{id:{type:"string"},name:{type:"string"},displayName:{type:"string"}}},pubKeyCredParams:{type:"array",items:{type:"object",properties:{type:{type:"string"},alg:{type:"number"}}}},timeout:{type:"number"},excludeCredentials:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string"},transports:{type:"array",items:{type:"string"}}}}},authenticatorSelection:{type:"object",properties:{authenticatorAttachment:{type:"string"},requireResidentKey:{type:"boolean"},userVerification:{type:"string"}}},attestation:{type:"string"},extensions:{type:"object"}}}}}}}}}},async s=>{let d=s.context.session,A=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}),K=new Uint8Array(Buffer.from(L(32,F("a-z","0-9")))),u;u=await(0,he.generateRegistrationOptions)({rpName:i.rpName||s.context.appName,rpID:i.rpID,userID:K,userName:d.user.email||d.user.id,attestationType:"none",excludeCredentials:A.map(l=>({id:l.id,transports:l.transports?.split(",")})),authenticatorSelection:{residentKey:"preferred",userVerification:"preferred",authenticatorAttachment:"platform"}});let p=V(32);return await s.setSignedCookie(i.advanced.webAuthnChallengeCookie,p,s.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:a}),await s.context.internalAdapter.createVerificationValue({identifier:p,value:JSON.stringify({expectedChallenge:u.challenge,userData:{id:d.user.id}}),expiresAt:r}),s.json(u,{status:200})}),generatePasskeyAuthenticationOptions:c("/passkey/generate-authenticate-options",{method:"POST",body:Y.z.object({email:Y.z.string({description:"The email address of the user"}).optional()}).optional(),metadata:{openapi:{description:"Generate authentication options for a passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{challenge:{type:"string"},rp:{type:"object",properties:{name:{type:"string"},id:{type:"string"}}},user:{type:"object",properties:{id:{type:"string"},name:{type:"string"},displayName:{type:"string"}}},timeout:{type:"number"},allowCredentials:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string"},transports:{type:"array",items:{type:"string"}}}}},userVerification:{type:"string"},authenticatorSelection:{type:"object",properties:{authenticatorAttachment:{type:"string"},requireResidentKey:{type:"boolean"},userVerification:{type:"string"}}},extensions:{type:"object"}}}}}}}}}},async s=>{let d=await U(s),A=[];d&&(A=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}));let K=await(0,he.generateAuthenticationOptions)({rpID:i.rpID,userVerification:"preferred",...A.length?{allowCredentials:A.map(l=>({id:l.id,transports:l.transports?.split(",")}))}:{}}),u={expectedChallenge:K.challenge,userData:{id:d?.user.id||""}},p=V(32);return await s.setSignedCookie(i.advanced.webAuthnChallengeCookie,p,s.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:a}),await s.context.internalAdapter.createVerificationValue({identifier:p,value:JSON.stringify(u),expiresAt:r}),s.json(K,{status:200})}),verifyPasskeyRegistration:c("/passkey/verify-registration",{method:"POST",body:Y.z.object({response:Y.z.any({description:"The response from the authenticator"}),name:Y.z.string({description:"Name of the passkey"}).optional()}),use:[He],metadata:{openapi:{description:"Verify registration of a new passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{$ref:"#/components/schemas/Passkey"}}}},400:{description:"Bad request"}}}}},async s=>{let d=e?.origin||s.headers?.get("origin")||"";if(!d)return s.json(null,{status:400});let A=s.body.response,K=await s.getSignedCookie(i.advanced.webAuthnChallengeCookie,s.context.secret);if(!K)throw new Z.APIError("BAD_REQUEST",{message:"Challenge not found"});let u=await s.context.internalAdapter.findVerificationValue(K);if(!u)return s.json(null,{status:400});let{expectedChallenge:p,userData:l}=JSON.parse(u.value);if(l.id!==s.context.session.user.id)throw new Z.APIError("UNAUTHORIZED",{message:"You are not authorized to register this passkey"});try{let h=await(0,he.verifyRegistrationResponse)({response:A,expectedChallenge:p,expectedOrigin:d,expectedRPID:e?.rpID}),{verified:k,registrationInfo:f}=h;if(!k||!f)return s.json(null,{status:400});let{credentialID:g,credentialPublicKey:b,counter:T,credentialDeviceType:N,credentialBackedUp:eo}=f,ir=Buffer.from(b).toString("base64"),tr={name:s.body.name,userId:l.id,webauthnUserID:s.context.generateId({model:"passkey"}),id:g,publicKey:ir,counter:T,deviceType:N,transports:A.response.transports.join(","),backedUp:eo,createdAt:new Date},rr=await s.context.adapter.create({model:"passkey",data:tr});return s.json(rr,{status:200})}catch(h){throw console.log(h),new Z.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to verify registration"})}}),verifyPasskeyAuthentication:c("/passkey/verify-authentication",{method:"POST",body:Y.z.object({response:Y.z.any()}),metadata:{openapi:{description:"Verify authentication of a passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async s=>{let d=e?.origin||s.headers?.get("origin")||"";if(!d)throw new Z.APIError("BAD_REQUEST",{message:"origin missing"});let A=s.body.response,K=await s.getSignedCookie(i.advanced.webAuthnChallengeCookie,s.context.secret);if(!K)throw new Z.APIError("BAD_REQUEST",{message:"Challenge not found"});let u=await s.context.internalAdapter.findVerificationValue(K);if(!u)throw new Z.APIError("BAD_REQUEST",{message:"Challenge not found"});let{expectedChallenge:p}=JSON.parse(u.value),l=await s.context.adapter.findOne({model:"passkey",where:[{field:"id",value:A.id}]});if(!l)throw new Z.APIError("UNAUTHORIZED",{message:"Passkey not found"});try{let h=await(0,he.verifyAuthenticationResponse)({response:A,expectedChallenge:p,expectedOrigin:d,expectedRPID:i.rpID,authenticator:{credentialID:l.id,credentialPublicKey:new Uint8Array(Buffer.from(l.publicKey,"base64")),counter:l.counter,transports:l.transports?.split(",")},requireUserVerification:!1}),{verified:k}=h;if(!k)throw new Z.APIError("UNAUTHORIZED",{message:"Authentication failed"});await s.context.adapter.update({model:"passkey",where:[{field:"id",value:l.id}],update:{counter:h.authenticationInfo.newCounter}});let f=await s.context.internalAdapter.createSession(l.userId,s.request);if(!f)throw new Z.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});let g=await s.context.internalAdapter.findUserById(l.userId);if(!g)throw new Z.APIError("INTERNAL_SERVER_ERROR",{message:"User not found"});return await m(s,{session:f,user:g}),s.json({session:f},{status:200})}catch(h){throw s.context.logger.error("Failed to verify authentication",h),new Z.APIError("BAD_REQUEST",{message:"Failed to verify authentication"})}}),listPasskeys:c("/passkey/list-user-passkeys",{method:"GET",use:[v]},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:[v]},async s=>(await s.context.adapter.delete({model:"passkey",where:[{field:"id",value:s.body.id}]}),s.json(null,{status:200}))),updatePasskey:c("/passkey/update-passkey",{method:"POST",body:Y.z.object({id:Y.z.string(),name:Y.z.string()}),use:[v]},async s=>{let d=await s.context.adapter.findOne({model:"passkey",where:[{field:"id",value:s.body.id}]});if(!d)throw new Z.APIError("NOT_FOUND",{message:"Passkey not found"});if(d.userId!==s.context.session.user.id)throw new Z.APIError("UNAUTHORIZED",{message:"You are not authorized to update this passkey"});let A=await s.context.adapter.update({model:"passkey",where:[{field:"id",value:s.body.id}],update:{name:s.body.name}});if(!A)throw new Z.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to update passkey"});return s.json({passkey:A},{status:200})})},schema:ie(rn,e?.schema)}},rn={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",required:!1}}}};var Je=require("zod");var Le=require("better-call");var Qo=()=>({id:"username",endpoints:{signInUsername:c("/sign-in/username",{method:"POST",body:Je.z.object({username:Je.z.string({description:"The username of the user"}),password:Je.z.string({description:"The password of the user"}),rememberMe:Je.z.boolean({description:"Remember the user session"}).optional()}),metadata:{openapi:{summary:"Sign in with username",description:"Sign in with username",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async e=>{let t=await e.context.adapter.findOne({model:"user",where:[{field:"username",value:e.body.username.toLowerCase()}]});if(!t)throw await e.context.password.hash(e.body.password),e.context.logger.error("User not found",{username:Qo}),new Le.APIError("UNAUTHORIZED",{message:"Invalid username or password"});if(!t.emailVerified&&e.context.options.emailAndPassword?.requireEmailVerification)throw await Oo(e,t),new Le.APIError("UNAUTHORIZED",{message:"Email not verified"});let o=await e.context.adapter.findOne({model:"account",where:[{field:"userId",value:t.id},{field:"providerId",value:"credential"}]});if(!o)throw new Le.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let i=o?.password;if(!i)throw e.context.logger.error("Password not found",{username:Qo}),new Le.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify({hash:i,password:e.body.password}))throw e.context.logger.error("Invalid password"),new Le.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let n=await e.context.internalAdapter.createSession(t.id,e.request,e.body.rememberMe===!1);return n?(await m(e,{session:n,user:t},e.body.rememberMe===!1),e.json({user:t,session:n})):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 Qt=require("better-call"),nn=()=>({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 o="";return t.includes(".")?o=t:o=await(0,Qt.serializeSigned)("",t,e.context.secret),e.request&&e.request.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${o.replace("=","")}`),e.headers&&e.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${o.replace("=","")}`),{context:e}}}]}});var ke=require("zod");var $t=require("better-call");var sn=e=>({id:"magic-link",endpoints:{signInMagicLink:c("/sign-in/magic-link",{method:"POST",requireHeaders:!0,body:ke.z.object({email:ke.z.string({description:"Email address to send the magic link"}).email(),callbackURL:ke.z.string({description:"URL to redirect after magic link verification"}).optional()}),metadata:{openapi:{description:"Sign in with magic link",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async t=>{let{email:o}=t.body;if(e.disableSignUp&&!await t.context.internalAdapter.findUserByEmail(o))throw new $t.APIError("BAD_REQUEST",{message:"User not found"});let i=L(32,F("a-z","A-Z"));await t.context.internalAdapter.createVerificationValue({identifier:i,value:o,expiresAt:new Date(Date.now()+(e.expiresIn||60*5)*1e3)});let r=`${t.context.baseURL}/magic-link/verify?token=${i}&callbackURL=${t.body.callbackURL||"/"}`;return await e.sendMagicLink({email:o,url:r,token:i},t.request),t.json({status:!0})}),magicLinkVerify:c("/magic-link/verify",{method:"GET",query:ke.z.object({token:ke.z.string({description:"Verification token"}),callbackURL:ke.z.string({description:"URL to redirect after magic link verification, if not provided will return session"}).optional()}),requireHeaders:!0,metadata:{openapi:{description:"Verify magic link",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async t=>{let{token:o,callbackURL:i}=t.query,r=i?.startsWith("http")?i:i?`${t.context.options.baseURL}${i}`:t.context.options.baseURL,n=await t.context.internalAdapter.findVerificationValue(o);if(!n)throw t.redirect(`${r}?error=INVALID_TOKEN`);if(n.expiresAt<new Date)throw await t.context.internalAdapter.deleteVerificationValue(n.id),t.redirect(`${r}?error=EXPIRED_TOKEN`);await t.context.internalAdapter.deleteVerificationValue(n.id);let a=n.value,s=await t.context.internalAdapter.findUserByEmail(a),d=s?.user.id||"";if(!s){if(e.disableSignUp)throw t.redirect(`${r}?error=USER_NOT_FOUND`);if(d=(await t.context.internalAdapter.createUser({email:a,emailVerified:!0,name:a})).id,!d)throw t.redirect(`${r}?error=USER_NOT_CREATED`)}let A=await t.context.internalAdapter.createSession(d,t.headers);if(!A)throw t.redirect(`${r}?error=SESSION_NOT_CREATED`);if(await m(t,{session:A,user:s?.user}),!i)return t.json({session:A,user:s?.user});throw t.redirect(i)})},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 re=require("zod");var H=require("better-call");function an(e){return L(e,F("0-9"))}var dn=e=>{let t={expiresIn:e?.expiresIn||300,otpLength:e?.otpLength||6,...e,phoneNumber:"phoneNumber",phoneNumberVerified:"phoneNumberVerified",code:"code",createdAt:"createdAt"};return{id:"phone-number",endpoints:{signInPhoneNumber:c("/sign-in/phone-number",{method:"POST",body:re.z.object({phoneNumber:re.z.string({description:"Phone number to sign in"}),password:re.z.string({description:"Password to use for sign in"}),rememberMe:re.z.boolean({description:"Remember the session"}).optional()}),metadata:{openapi:{summary:"Sign in with phone number",description:"Use this endpoint to sign in with phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}},400:{description:"Invalid phone number or password"}}}}},async o=>{let{password:i,phoneNumber:r}=o.body;if(t.phoneNumberValidator&&!await t.phoneNumberValidator(o.body.phoneNumber))throw new H.APIError("BAD_REQUEST",{message:"Invalid phone number!"});let n=await o.context.adapter.findOne({model:"user",where:[{field:"phoneNumber",value:r}]});if(!n)throw new H.APIError("UNAUTHORIZED",{message:"Invalid phone number or password"});let s=(await o.context.internalAdapter.findAccountByUserId(n.id)).find(u=>u.providerId==="credential");if(!s)throw o.context.logger.error("Credential account not found",{phoneNumber:r}),new H.APIError("UNAUTHORIZED",{message:"Invalid password or password"});let d=s?.password;if(!d)throw o.context.logger.error("Password not found",{phoneNumber:r}),new H.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await o.context.password.verify({hash:d,password:i}))throw o.context.logger.error("Invalid password"),new H.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let K=await o.context.internalAdapter.createSession(n.id,o.headers,o.body.rememberMe===!1);if(!K)throw o.context.logger.error("Failed to create session"),new H.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await m(o,{session:K,user:n},o.body.rememberMe===!1),o.json({user:n,session:K})}),sendPhoneNumberOTP:c("/phone-number/send-otp",{method:"POST",body:re.z.object({phoneNumber:re.z.string({description:"Phone number to send OTP"})}),metadata:{openapi:{summary:"Send OTP to phone number",description:"Use this endpoint to send OTP to phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async o=>{if(!e?.sendOTP)throw o.context.logger.warn("sendOTP not implemented"),new H.APIError("NOT_IMPLEMENTED",{message:"sendOTP not implemented"});if(t.phoneNumberValidator&&!await t.phoneNumberValidator(o.body.phoneNumber))throw new H.APIError("BAD_REQUEST",{message:"Invalid phone number!"});let i=an(t.otpLength);return await o.context.internalAdapter.createVerificationValue({value:i,identifier:o.body.phoneNumber,expiresAt:R(t.expiresIn,"sec")}),await e.sendOTP({phoneNumber:o.body.phoneNumber,code:i},o.request),o.json({code:i},{body:{message:"Code sent"}})}),verifyPhoneNumber:c("/phone-number/verify",{method:"POST",body:re.z.object({phoneNumber:re.z.string({description:"Phone number to verify"}),code:re.z.string({description:"OTP code"}),disableSession:re.z.boolean({description:"Disable session creation after verification"}).optional(),updatePhoneNumber:re.z.boolean({description:"Check if there is a session and update the phone number"}).optional()}),metadata:{openapi:{summary:"Verify phone number",description:"Use this endpoint to verify phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}},400:{description:"Invalid OTP"}}}}},async o=>{let i=await o.context.internalAdapter.findVerificationValue(o.body.phoneNumber);if(!i||i.expiresAt<new Date)throw i&&i.expiresAt<new Date?(await o.context.internalAdapter.deleteVerificationValue(i.id),new H.APIError("BAD_REQUEST",{message:"OTP expired"})):new H.APIError("BAD_REQUEST",{message:"OTP not found"});if(i.value!==o.body.code)throw new H.APIError("BAD_REQUEST",{message:"Invalid OTP"});if(await o.context.internalAdapter.deleteVerificationValue(i.id),o.body.updatePhoneNumber){let n=await U(o);if(!n)throw new H.APIError("UNAUTHORIZED",{message:"Session not found"});let a=await o.context.internalAdapter.updateUser(n.user.id,{[t.phoneNumber]:o.body.phoneNumber,[t.phoneNumberVerified]:!0});return o.json({user:a,session:n.session})}let r=await o.context.adapter.findOne({model:"user",where:[{value:o.body.phoneNumber,field:t.phoneNumber}]});if(await e?.callbackOnVerification?.({phoneNumber:o.body.phoneNumber,user:r},o.request),r)r=await o.context.internalAdapter.updateUser(r.id,{[t.phoneNumberVerified]:!0});else if(e?.signUpOnVerification){if(r=await o.context.internalAdapter.createUser({email:e.signUpOnVerification.getTempEmail(o.body.phoneNumber),name:e.signUpOnVerification.getTempName?e.signUpOnVerification.getTempName(o.body.phoneNumber):o.body.phoneNumber,[t.phoneNumber]:o.body.phoneNumber,[t.phoneNumberVerified]:!0}),!r)throw new H.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"})}else return o.json(null);if(!r)throw new H.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to update user"});if(!o.body.disableSession){let n=await o.context.internalAdapter.createSession(r.id,o.request);if(!n)throw new H.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await m(o,{session:n,user:r}),o.json({user:r,session:n})}return o.json({user:r,session:null})})},schema:ie(An,e?.schema)}},An={user:{fields:{phoneNumber:{type:"string",required:!1,unique:!0,returned:!0},phoneNumberVerified:{type:"boolean",required:!1,returned:!0,input:!1}}}};var mp=require("zod");var cn={user:{fields:{isAnonymous:{type:"boolean",required:!1}}}},Kn=e=>({id:"anonymous",endpoints:{signInAnonymous:c("/sign-in/anonymous",{method:"POST",metadata:{openapi:{description:"Sign in anonymously",responses:{200:{description:"Sign in anonymously",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async t=>{let{emailDomainName:o=Ie(t.context.baseURL)}=e||{},i=t.context.generateId({model:"user"}),r=`temp-${i}@${o}`,n=await t.context.internalAdapter.createUser({id:i,email:r,emailVerified:!1,isAnonymous:!0,name:"Anonymous",createdAt:new Date,updatedAt:new Date});if(!n)return t.json(null,{status:500,body:{message:"Failed to create user",status:500}});let a=await t.context.internalAdapter.createSession(n.id,t.request);return a?(await m(t,{session:a,user:n}),t.json({user:n,session:a})):t.json(null,{status:400,body:{message:"Could not create session"}})})},hooks:{after:[{matcher(t){return t.path?.startsWith("/sign-in")||t.path?.startsWith("/sign-up")},handler:P(async t=>{let i=t.responseHeader.get("set-cookie"),r=t.context.authCookies.sessionToken.name,n=ao(i||"").get(r)?.value.split(".")[0];if(!n)return;let a=await U(t);if(!(!a||!a.user.isAnonymous)){if(t.path==="/sign-in/anonymous")throw new C.APIError("BAD_REQUEST",{message:"Anonymous users cannot sign in again anonymously"});if(e?.onLinkAccount){let s=await t.context.internalAdapter.findSession(n);if(!s)return;await e?.onLinkAccount?.({anonymousUser:a,newUser:s})}e?.disableDeleteAnonymousUser||await t.context.internalAdapter.deleteUser(a.user.id)}})}]},schema:ie(cn,e?.schema)});var y=require("zod");var pn=e=>{let t={defaultRole:"user",adminRole:"admin",...e},o=P(async i=>{let r=await U(i);if(!r?.session)throw new C.APIError("UNAUTHORIZED");let n=r.user;if(!n.role||(Array.isArray(t.adminRole)?!t.adminRole.includes(n.role):n.role!==t.adminRole))throw new C.APIError("FORBIDDEN",{message:"Only admins can access this endpoint"});return{session:{user:n,session:r.session}}});return{id:"admin",init(i){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 n=await i.internalAdapter.findUserById(r.userId);if(n.banned){if(n.banExpires&&n.banExpires.getTime()<Date.now()){await i.internalAdapter.updateUser(r.userId,{banned:!1,banReason:null,banExpires:null});return}return!1}}}}}}}},hooks:{after:[{matcher(i){return i.path==="/list-sessions"},handler:P(async i=>{let r=await Ne(i);if(!r)return;let n=r.filter(a=>!a.impersonatedBy);return i.json(n)})}]},endpoints:{setRole:c("/admin/set-role",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"}),role:y.z.string({description:"The role to set. `admin` or `user` by default"})}),use:[o],metadata:{openapi:{operationId:"setRole",summary:"Set the role of a user",description:"Set the role of a user",responses:{200:{description:"User role updated",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{let r=await i.context.internalAdapter.updateUser(i.body.userId,{role:i.body.role});return i.json({user:r})}),createUser:c("/admin/create-user",{method:"POST",body:y.z.object({email:y.z.string({description:"The email of the user"}),password:y.z.string({description:"The password of the user"}),name:y.z.string({description:"The name of the user"}),role:y.z.string({description:"The role of the user"}),data:y.z.optional(y.z.record(y.z.any(),{description:"Extra fields for the user. Including custom additional fields."}))}),use:[o],metadata:{openapi:{operationId:"createUser",summary:"Create a new user",description:"Create a new user",responses:{200:{description:"User created",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{if(await i.context.internalAdapter.findUserByEmail(i.body.email))throw new C.APIError("BAD_REQUEST",{message:"User already exists"});let n=await i.context.internalAdapter.createUser({email:i.body.email,name:i.body.name,role:i.body.role,...i.body.data});if(!n)throw new C.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"});let a=await i.context.password.hash(i.body.password);return await i.context.internalAdapter.linkAccount({accountId:n.id,providerId:"credential",password:a,userId:n.id}),i.json({user:n})}),listUsers:c("/admin/list-users",{method:"GET",use:[o],query:y.z.object({searchValue:y.z.string({description:"The value to search for"}).optional(),searchField:y.z.enum(["email","name"],{description:"The field to search in, defaults to email. Can be `email` or `name`"}).optional(),searchOperator:y.z.enum(["contains","starts_with","ends_with"],{description:"The operator to use for the search. Can be `contains`, `starts_with` or `ends_with`"}).optional(),limit:y.z.string({description:"The number of users to return"}).or(y.z.number()).optional(),offset:y.z.string({description:"The offset to start from"}).or(y.z.number()).optional(),sortBy:y.z.string({description:"The field to sort by"}).optional(),sortDirection:y.z.enum(["asc","desc"],{description:"The direction to sort by"}).optional(),filterField:y.z.string({description:"The field to filter by"}).optional(),filterValue:y.z.string({description:"The value to filter by"}).or(y.z.number()).or(y.z.boolean()).optional(),filterOperator:y.z.enum(["eq","ne","lt","lte","gt","gte"],{description:"The operator to use for the filter"}).optional()}),metadata:{openapi:{operationId:"listUsers",summary:"List users",description:"List users",responses:{200:{description:"List of users",content:{"application/json":{schema:{type:"object",properties:{users:{type:"array",items:{$ref:"#/components/schemas/User"}}}}}}}}}}},async i=>{let r=[];i.query?.searchValue&&r.push({field:i.query.searchField||"email",operator:i.query.searchOperator||"contains",value:i.query.searchValue}),i.query?.filterValue&&r.push({field:i.query.filterField||"email",operator:i.query.filterOperator||"eq",value:i.query.filterValue});try{let n=await i.context.internalAdapter.listUsers(Number(i.query?.limit)||void 0,Number(i.query?.offset)||void 0,i.query?.sortBy?{field:i.query.sortBy,direction:i.query.sortDirection||"asc"}:void 0,r.length?r:void 0);return i.json({users:n})}catch(n){return console.log(n),i.json({users:[]})}}),listUserSessions:c("/admin/list-user-sessions",{method:"POST",use:[o],body:y.z.object({userId:y.z.string({description:"The user id"})}),metadata:{openapi:{operationId:"listUserSessions",summary:"List user sessions",description:"List user sessions",responses:{200:{description:"List of user sessions",content:{"application/json":{schema:{type:"object",properties:{sessions:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}}}}}}}},async i=>({sessions:await i.context.internalAdapter.listSessions(i.body.userId)})),unbanUser:c("/admin/unban-user",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"unbanUser",summary:"Unban a user",description:"Unban a user",responses:{200:{description:"User unbanned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{let r=await i.context.internalAdapter.updateUser(i.body.userId,{banned:!1});return i.json({user:r})}),banUser:c("/admin/ban-user",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"}),banReason:y.z.string({description:"The reason for the ban"}).optional(),banExpiresIn:y.z.number({description:"The number of seconds until the ban expires"}).optional()}),use:[o],metadata:{openapi:{operationId:"banUser",summary:"Ban a user",description:"Ban a user",responses:{200:{description:"User banned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{if(i.body.userId===i.context.session.user.id)throw new C.APIError("BAD_REQUEST",{message:"You cannot ban yourself"});let r=await i.context.internalAdapter.updateUser(i.body.userId,{banned:!0,banReason:i.body.banReason||e?.defaultBanReason||"No reason",banExpires:i.body.banExpiresIn?R(i.body.banExpiresIn,"sec"):e?.defaultBanExpiresIn?R(e.defaultBanExpiresIn,"sec"):void 0});return await i.context.internalAdapter.deleteSessions(i.body.userId),i.json({user:r})}),impersonateUser:c("/admin/impersonate-user",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"impersonateUser",summary:"Impersonate a user",description:"Impersonate a user",responses:{200:{description:"Impersonation session created",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{let r=await i.context.internalAdapter.findUserById(i.body.userId);if(!r)throw new C.APIError("NOT_FOUND",{message:"User not found"});let n=await i.context.internalAdapter.createSession(r.id,void 0,!0,{impersonatedBy:i.context.session.user.id,expiresAt:e?.impersonationSessionDuration?R(e.impersonationSessionDuration,"sec"):R(60*60,"sec")});if(!n)throw new C.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await m(i,{session:n,user:r},!0),i.json({session:n,user:r})}),revokeUserSession:c("/admin/revoke-user-session",{method:"POST",body:y.z.object({sessionToken:y.z.string({description:"The session token"})}),use:[o],metadata:{openapi:{operationId:"revokeUserSession",summary:"Revoke a user session",description:"Revoke a user session",responses:{200:{description:"Session revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async i=>(await i.context.internalAdapter.deleteSession(i.body.sessionToken),i.json({success:!0}))),revokeUserSessions:c("/admin/revoke-user-sessions",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"revokeUserSessions",summary:"Revoke all user sessions",description:"Revoke all user sessions",responses:{200:{description:"Sessions revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async i=>(await i.context.internalAdapter.deleteSessions(i.body.userId),i.json({success:!0}))),removeUser:c("/admin/remove-user",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"removeUser",summary:"Remove a user",description:"Delete a user and all their sessions and accounts. Cannot be undone.",responses:{200:{description:"User removed",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async i=>(await i.context.internalAdapter.deleteUser(i.body.userId),i.json({success:!0})))},schema:ie(un,t.schema)}},un={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 se=require("zod"),Fe=require("better-call");var ho=require("@better-fetch/fetch");var Zt=require("oslo/jwt");async function ln(e,t,o){if(t==="oidc"&&e.idToken){let r=(0,Zt.parseJWT)(e.idToken);if(r?.payload)return{id:r.payload.sub,emailVerified:r.payload.email_verified,...r.payload}}if(!o)return null;let i=await(0,ho.betterFetch)(o,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});return{id:i.data?.sub,emailVerified:i.data?.email_verified,email:i.data?.email,...i.data}}var gn=e=>({id:"generic-oauth",endpoints:{signInWithOAuth2:c("/sign-in/oauth2",{method:"POST",query:se.z.object({currentURL:se.z.string({description:"Redirect to the current URL after sign in"}).optional()}).optional(),body:se.z.object({providerId:se.z.string({description:"The provider ID for the OAuth provider"}),callbackURL:se.z.string({description:"The URL to redirect to after sign in"}).optional(),errorCallbackURL:se.z.string({description:"The URL to redirect to if an error occurs"}).optional()}),metadata:{openapi:{description:"Sign in with OAuth2",responses:{200:{description:"Sign in with OAuth2",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}}}}}}}}}},async t=>{let{providerId:o}=t.body,i=e.config.find(N=>N.providerId===o);if(!i)throw new Fe.APIError("BAD_REQUEST",{message:`No config found for provider ${o}`});let{discoveryUrl:r,authorizationUrl:n,tokenUrl:a,clientId:s,clientSecret:d,scopes:A,redirectURI:K,responseType:u,pkce:p,prompt:l,accessType:h}=i,k=n,f=a;if(r){let N=await(0,ho.betterFetch)(r,{onError(eo){t.context.logger.error(eo.error.message,eo.error,{discoveryUrl:r})}});N.data&&(k=N.data.authorization_endpoint,f=N.data.token_endpoint)}if(!k||!f)throw new Fe.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let{state:g,codeVerifier:b}=await Ue(t),T=await S({id:o,options:{clientId:s,clientSecret:d,redirectURI:K},authorizationEndpoint:k,state:g,codeVerifier:p?b:void 0,scopes:A||[],redirectURI:`${t.context.baseURL}/oauth2/callback/${o}`});return u&&u!=="code"&&T.searchParams.set("response_type",u),l&&T.searchParams.set("prompt",l),h&&T.searchParams.set("access_type",h),t.json({url:T.toString(),redirect:!0})}),oAuth2Callback:c("/oauth2/callback/:providerId",{method:"GET",query:se.z.object({code:se.z.string({description:"The OAuth2 code"}).optional(),error:se.z.string({description:"The error message, if any"}).optional(),state:se.z.string({description:"The state parameter from the OAuth2 request"})}),metadata:{openapi:{description:"OAuth2 callback",responses:{200:{description:"OAuth2 callback",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"}}}}}}}}}},async t=>{if(t.query.error||!t.query.code)throw t.redirect(`${t.context.baseURL}?error=${t.query.error||"oAuth_code_missing"}`);let o=e.config.find(g=>g.providerId===t.params.providerId);if(!o)throw new Fe.APIError("BAD_REQUEST",{message:`No config found for provider ${t.params.providerId}`});let i,r=await co(t),{callbackURL:n,codeVerifier:a,errorURL:s}=r,d=t.query.code,A=o.tokenUrl,K=o.userInfoUrl;if(o.discoveryUrl){let g=await(0,ho.betterFetch)(o.discoveryUrl,{method:"GET"});g.data&&(A=g.data.token_endpoint,K=g.data.userinfo_endpoint)}try{if(!A)throw new Fe.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});i=await I({code:d,codeVerifier:a,redirectURI:`${t.context.baseURL}/oauth2/callback/${o.providerId}`,options:{clientId:o.clientId,clientSecret:o.clientSecret},tokenEndpoint:A})}catch(g){throw t.context.logger.error(g&&typeof g=="object"&&"name"in g?g.name:"",g),t.redirect(`${s}?error=oauth_code_verification_failed`)}if(!i)throw new Fe.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let u=o.getUserInfo?await o.getUserInfo(i):await ln(i,o.type||"oauth2",K);if(!u?.email)throw t.context.logger.error("Unable to get user info",u),t.redirect(`${t.context.baseURL}/error?error=email_is_missing`);let p=await Pe(t,{userInfo:u,account:{providerId:o.providerId,accountId:u.id,accessToken:i.accessToken}});function l(g){throw t.redirect(`${s||n||`${t.context.baseURL}/error`}?error=${g}`)}if(p.error)return l(p.error.split(" ").join("_"));let{session:h,user:k}=p.data;await m(t,{session:h,user:k});let f;try{f=new URL(n).toString()}catch{f=n}throw t.redirect(f)})}});var Ve=require("zod"),Gt={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0}}}},Bp=Ve.z.object({id:Ve.z.string(),publicKey:Ve.z.string(),privateKey:Ve.z.string(),createdAt:Ve.z.date()});var $o=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 le=require("jose");var mn=e=>({id:"jwt",endpoints:{getJwks:c("/jwks",{method:"GET",metadata:{openapi:{description:"Get the JSON Web Key Set",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{keys:{type:"array",items:{type:"object",properties:{kid:{type:"string"},kty:{type:"string"},use:{type:"string"},alg:{type:"string"},n:{type:"string"},e:{type:"string"}}}}}}}}}}}}},async t=>{let i=await $o(t.context.adapter).getAllKeys();return t.json({keys:i.map(r=>({...JSON.parse(r.publicKey),kid:r.id}))})}),getToken:c("/token",{method:"GET",requireHeaders:!0,use:[v],metadata:{openapi:{description:"Get a JWT token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async t=>{let o=$o(t.context.adapter),i=await o.getLatestKey(),r=!e?.jwks?.disablePrivateKeyEncryption;if(i===void 0){let{publicKey:A,privateKey:K}=await(0,le.generateKeyPair)(e?.jwks?.keyPairConfig?.alg??"EdDSA",e?.jwks?.keyPairConfig??{crv:"Ed25519"}),u=await(0,le.exportJWK)(A),p=await(0,le.exportJWK)(K),l=JSON.stringify(p),h={id:crypto.randomUUID(),publicKey:JSON.stringify(u),privateKey:r?JSON.stringify(await ue({key:t.context.options.secret,data:l})):l,createdAt:new Date};i=await o.createJwk(h)}let n=r?await fe({key:t.context.options.secret,data:JSON.parse(i.privateKey)}):i.privateKey,a=await(0,le.importJWK)(JSON.parse(n)),s=e?.jwt?.definePayload?await e?.jwt.definePayload(t.context.session.user):t.context.session.user,d=await new le.SignJWT({...s,...t.context.session.session.impersonatedBy?{impersonatedBy:t.context.session.session.impersonatedBy}:{}}).setProtectedHeader({alg:e?.jwks?.keyPairConfig?.alg??"EdDSA",kid:i.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:ie(Gt,e?.schema)});var Xe=require("zod");var fn=e=>{let t={maximumSessions:5,...e},o=i=>i.includes("_multi-");return{id:"multi-session",endpoints:{listDeviceSessions:c("/multi-session/list-device-sessions",{method:"GET",requireHeaders:!0},async i=>{let r=i.headers?.get("cookie");if(!r)return i.json([]);let n=Object.fromEntries(Qe(r)),a=(await Promise.all(Object.entries(n).filter(([A])=>o(A)).map(async([A])=>await i.getSignedCookie(A,i.context.secret)))).filter(A=>A!==void 0);if(!a.length)return i.json([]);let d=(await i.context.internalAdapter.findSessions(a)).filter(A=>A&&A.session.expiresAt>new Date);return i.json(d)}),setActiveSession:c("/multi-session/set-active",{method:"POST",body:Xe.z.object({sessionToken:Xe.z.string({description:"The session token to set as active"})}),requireHeaders:!0,use:[v],metadata:{openapi:{description:"Set the active session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async i=>{let r=i.body.sessionToken,n=`${i.context.authCookies.sessionToken.name}_multi-${r}`;if(!await i.getSignedCookie(n,i.context.secret))throw new C.APIError("UNAUTHORIZED",{message:"Invalid session token"});let s=await i.context.internalAdapter.findSession(r);if(!s||s.session.expiresAt<new Date)throw i.setCookie(n,"",{...i.context.authCookies.sessionToken.options,maxAge:0}),new C.APIError("UNAUTHORIZED",{message:"Invalid session token"});return await m(i,s),i.json(s)}),revokeDeviceSession:c("/multi-session/revoke",{method:"POST",body:Xe.z.object({sessionToken:Xe.z.string({description:"The session token to revoke"})}),requireHeaders:!0,use:[v],metadata:{openapi:{description:"Revoke a device session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async i=>{let r=i.body.sessionToken,n=`${i.context.authCookies.sessionToken.name}_multi-${r}`;if(!await i.getSignedCookie(n,i.context.secret))throw new C.APIError("UNAUTHORIZED",{message:"Invalid session token"});if(await i.context.internalAdapter.deleteSession(r),i.setCookie(n,"",{...i.context.authCookies.sessionToken.options,maxAge:0}),!(i.context.session?.session.token===r))return i.json({success:!0});let d=i.headers?.get("cookie");if(d){let A=Object.fromEntries(Qe(d)),K=(await Promise.all(Object.entries(A).filter(([p])=>o(p)).map(async([p])=>await i.getSignedCookie(p,i.context.secret)))).filter(p=>p!==void 0),u=i.context.internalAdapter;if(K.length>0){let l=(await u.findSessions(K)).filter(h=>h&&h.session.expiresAt>new Date);if(l.length>0){let h=l[0];await m(i,h)}else Q(i)}else Q(i)}else Q(i);return i.json({success:!0})})},hooks:{after:[{matcher:()=>!0,handler:P(async i=>{let r=i.responseHeader.get("set-cookie");if(!r)return;let n=ao(r),a=i.context.authCookies.sessionToken,s=n.get(a.name)?.value;if(!s)return;let d=Qe(i.headers?.get("cookie")||""),A=s.split(".")[0];if(!A)return;let K=`${a.name}_multi-${A}`;n.get(K)||d.get(K)||Object.keys(Object.fromEntries(d)).filter(o).length+(r.includes("session_token")?1:0)>t.maximumSessions||await i.setSignedCookie(K,A,i.context.secret,a.options)})},{matcher:i=>i.path==="/sign-out",handler:P(async i=>{let r=i.headers?.get("cookie");if(!r)return;let n=Object.fromEntries(Qe(r)),a=Object.keys(n).map(s=>o(s)?(i.setCookie(s,"",{maxAge:0}),s.split("_multi-")[1]):null).filter(s=>s!==null);await i.context.internalAdapter.deleteSessions(a)})}]}}};var D=require("zod");var Zo=["email-verification","sign-in","forget-password"],hn=e=>{let t={expireIn:300,otpLength:6,...e};return{id:"email-otp",endpoints:{sendVerificationOTP:c("/email-otp/send-verification-otp",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to send the OTP"}),type:D.z.enum(Zo,{description:"Type of the OTP"})}),metadata:{openapi:{description:"Send verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{if(!e?.sendVerificationOTP)throw o.context.logger.error("send email verification is not implemented"),new C.APIError("BAD_REQUEST",{message:"send email verification is not implemented"});let i=o.body.email,r=L(t.otpLength,F("0-9"));return await o.context.internalAdapter.createVerificationValue({value:r,identifier:`${o.body.type}-otp-${i}`,expiresAt:R(t.expireIn,"sec")}).catch(async n=>{await o.context.internalAdapter.deleteVerificationByIdentifier(`${o.body.type}-otp-${i}`),await o.context.internalAdapter.createVerificationValue({value:r,identifier:`${o.body.type}-otp-${i}`,expiresAt:R(t.expireIn,"sec")})}),await e.sendVerificationOTP({email:i,otp:r,type:o.body.type},o.request),o.json({success:!0})}),createVerificationOTP:c("/email-otp/create-verification-otp",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to send the OTP"}),type:D.z.enum(Zo,{description:"Type of the OTP"})}),metadata:{SERVER_ONLY:!0,openapi:{description:"Create verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string"}}}}}}}},async o=>{let i=o.body.email,r=L(t.otpLength,F("0-9"));return await o.context.internalAdapter.createVerificationValue({value:r,identifier:`${o.body.type}-otp-${i}`,expiresAt:R(t.expireIn,"sec")}),r}),getVerificationOTP:c("/email-otp/get-verification-otp",{method:"GET",query:D.z.object({email:D.z.string({description:"Email address to get the OTP"}),type:D.z.enum(Zo)}),metadata:{SERVER_ONLY:!0,openapi:{description:"Get verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{otp:{type:"string"}}}}}}}}}},async o=>{let i=o.query.email,r=await o.context.internalAdapter.findVerificationValue(`${o.query.type}-otp-${i}`);return!r||r.expiresAt<new Date?o.json({otp:null}):o.json({otp:r.value})}),verifyEmailOTP:c("/email-otp/verify-email",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to verify"}),otp:D.z.string({description:"OTP to verify"})}),metadata:{openapi:{description:"Verify email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async o=>{let i=o.body.email,r=await o.context.internalAdapter.findVerificationValue(`email-verification-otp-${i}`);if(!r||r.expiresAt<new Date)throw r&&await o.context.internalAdapter.deleteVerificationValue(r.id),new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});let n=o.body.otp;if(r.value!==n)throw new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});await o.context.internalAdapter.deleteVerificationValue(r.id);let a=await o.context.internalAdapter.findUserByEmail(i);if(!a)throw new C.APIError("BAD_REQUEST",{message:"User not found"});let s=await o.context.internalAdapter.updateUser(a.user.id,{email:i,emailVerified:!0});return o.json({user:s})}),signInEmailOTP:c("/sign-in/email-otp",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to sign in"}),otp:D.z.string({description:"OTP sent to the email"})}),metadata:{openapi:{description:"Sign in with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async o=>{let i=o.body.email,r=await o.context.internalAdapter.findVerificationValue(`sign-in-otp-${i}`);if(!r||r.expiresAt<new Date)throw r&&await o.context.internalAdapter.deleteVerificationValue(r.id),new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});let n=o.body.otp;if(r.value!==n)throw new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});await o.context.internalAdapter.deleteVerificationValue(r.id);let a=await o.context.internalAdapter.findUserByEmail(i);if(!a){if(t.disableSignUp)throw new C.APIError("BAD_REQUEST",{message:"User not found"});let d=await o.context.internalAdapter.createUser({email:i,emailVerified:!0,name:i}),A=await o.context.internalAdapter.createSession(d.id,o.request);return await m(o,{session:A,user:d}),o.json({user:d,session:A})}a.user.emailVerified||await o.context.internalAdapter.updateUser(a.user.id,{emailVerified:!0});let s=await o.context.internalAdapter.createSession(a.user.id,o.request);return await m(o,{session:s,user:a.user}),o.json({session:s,user:a})}),forgetPasswordEmailOTP:c("/forget-password/email-otp",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to send the OTP"})}),metadata:{openapi:{description:"Forget password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{let i=o.body.email;if(!await o.context.internalAdapter.findUserByEmail(i))throw new C.APIError("BAD_REQUEST",{message:"User not found"});let n=L(t.otpLength,F("0-9"));return await o.context.internalAdapter.createVerificationValue({value:n,identifier:`forget-password-otp-${i}`,expiresAt:R(t.expireIn,"sec")}),await e.sendVerificationOTP({email:i,otp:n,type:"forget-password"},o.request),o.json({success:!0})}),resetPasswordEmailOTP:c("/email-otp/reset-password",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to reset the password"}),otp:D.z.string({description:"OTP sent to the email"}),password:D.z.string({description:"New password"})}),metadata:{openapi:{description:"Reset password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{let i=o.body.email,r=await o.context.internalAdapter.findUserByEmail(i);if(!r)throw new C.APIError("BAD_REQUEST",{message:"User not found"});let n=await o.context.internalAdapter.findVerificationValue(`forget-password-otp-${i}`);if(!n||n.expiresAt<new Date)throw n&&await o.context.internalAdapter.deleteVerificationValue(n.id),new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});let a=o.body.otp;if(n.value!==a)throw new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});await o.context.internalAdapter.deleteVerificationValue(n.id);let s=await o.context.password.hash(o.body.password);return await o.context.internalAdapter.updatePassword(r.user.id,s),o.json({success:!0})})},hooks:{after:[{matcher(o){return!!(o.path?.startsWith("/sign-up")&&t.sendVerificationOnSignUp)},async handler(o){let i=await Ne(o);if(i&&i.user.email&&i.user.emailVerified===!1){let r=L(t.otpLength,F("0-9"));await o.context.internalAdapter.createVerificationValue({value:r,identifier:`email-verification-otp-${i.user.email}`,expiresAt:R(t.expireIn,"sec")}),await e.sendVerificationOTP({email:i.user.email,otp:r,type:"email-verification"},o.request)}}}]}}};var Go=require("zod");var Jt=require("@better-fetch/fetch");function Wt(e){return e==="true"||e===!0}var yn=e=>({id:"one-tap",endpoints:{oneTapCallback:c("/one-tap/callback",{method:"POST",body:Go.z.object({idToken:Go.z.string({description:"Google ID token, which the client obtains from the One Tap API"})}),metadata:{openapi:{summary:"One tap callback",description:"Use this endpoint to authenticate with Google One Tap",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}},400:{description:"Invalid token"}}}}},async t=>{let{idToken:o}=t.body,{data:i,error:r}=await(0,Jt.betterFetch)("https://oauth2.googleapis.com/tokeninfo?id_token="+o);if(r)return t.json({error:"Invalid token"});let n=await t.context.internalAdapter.findUserByEmail(i.email);if(!n){if(e?.disableSignup)throw new C.APIError("BAD_GATEWAY",{message:"User not found"});let s=await t.context.internalAdapter.createOAuthUser({email:i.email,emailVerified:Wt(i.email_verified),name:i.name,image:i.picture},{providerId:"google",accountId:i.sub});if(!s)throw new C.APIError("INTERNAL_SERVER_ERROR",{message:"Could not create user"});let d=await t.context.internalAdapter.createSession(s?.user.id,t.request);return await m(t,{user:s.user,session:d}),t.json({session:d,user:s})}let a=await t.context.internalAdapter.createSession(n.user.id,t.request);return await m(t,{user:n.user,session:a}),t.json({session:a,user:n})})}});var yo=require("zod");function wn(){let e=ne.VERCEL_URL,t=ne.NETLIFY_URL,o=ne.RENDER_URL,i=ne.AWS_LAMBDA_FUNCTION_NAME,r=ne.GOOGLE_CLOUD_FUNCTION_NAME,n=ne.AZURE_FUNCTION_NAME;return e||t||o||i||r||n}var Cn=e=>({id:"oauth-proxy",endpoints:{oAuthProxy:c("/oauth-proxy-callback",{method:"GET",query:yo.z.object({callbackURL:yo.z.string({description:"The URL to redirect to after the proxy"}),cookies:yo.z.string({description:"The cookies to set after the proxy"})}),metadata:{openapi:{description:"OAuth Proxy Callback",parameters:[{in:"query",name:"callbackURL",required:!0,description:"The URL to redirect to after the proxy"},{in:"query",name:"cookies",required:!0,description:"The cookies to set after the proxy"}],responses:{302:{description:"Redirect",headers:{Location:{description:"The URL to redirect to",schema:{type:"string"}}}}}}}},async t=>{let o=t.query.cookies,i=await fe({key:t.context.secret,data:o});throw t.setHeader("set-cookie",i),t.redirect(t.query.callbackURL)})},hooks:{after:[{matcher(t){return t.path?.startsWith("/callback")},handler:P(async t=>{let o=t.context.returned,i=o instanceof C.APIError?o.headers:null,r=i?.get("location");if(r?.includes("/oauth-proxy-callback?callbackURL")){if(!r.startsWith("http"))return;let n=new URL(r);if(n.origin===Ie(t.context.baseURL)){let K=n.searchParams.get("callbackURL");if(!K)return;t.setHeader("location",K);return}let s=i?.get("set-cookie");if(!s)return;let d=await ue({key:t.context.secret,data:s}),A=`${r}&cookies=${encodeURIComponent(d)}`;t.setHeader("location",A)}})}],before:[{matcher(t){return t.path?.startsWith("/sign-in/social")},async handler(t){let o=new URL(e?.currentURL||t.request?.url||wn()||t.context.baseURL);return t.body.callbackURL=`${o.origin}${t.context.options.basePath||"/api/auth"}/oauth-proxy-callback?callbackURL=${encodeURIComponent(t.body.callbackURL||t.context.baseURL)}`,{context:t}}}]}});var bn=(e,t)=>({id:"custom-session",endpoints:{getSession:c("/get-session",{method:"GET",metadata:{CUSTOM_SESSION:!0}},async o=>{let i=await U(o);if(!i)return o.json(null);let r=await e(i);return o.json(r)})}});var ce=require("zod");var qe=e=>{let t=e.plugins?.reduce((d,A)=>{let K=A.schema;if(!K)return d;for(let[u,p]of Object.entries(K))d[u]={fields:{...d[u]?.fields,...p.fields},modelName:p.modelName||u};return d},{}),o=e.rateLimit?.storage==="database",i={rateLimit:{modelName:e.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",fieldName:e.rateLimit?.fields?.key||"key"},count:{type:"number",fieldName:e.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",fieldName:e.rateLimit?.fields?.lastRequest||"lastRequest"}}}},{user:r,session:n,account:a,...s}=t||{};return{user:{modelName:e.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:e.user?.fields?.name||"name"},email:{type:"string",unique:!0,required:!0,fieldName:e.user?.fields?.email||"email"},emailVerified:{type:"boolean",defaultValue:()=>!1,required:!0,fieldName:e.user?.fields?.emailVerified||"emailVerified"},image:{type:"string",required:!1,fieldName:e.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.updatedAt||"updatedAt"},...r?.fields,...e.user?.additionalFields},order:1},session:{modelName:e.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:e.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:e.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:e.session?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,fieldName:e.session?.fields?.updatedAt||"updatedAt"},ipAddress:{type:"string",required:!1,fieldName:e.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:e.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:e.session?.fields?.userId||"userId",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0},...n?.fields,...e.session?.additionalFields},order:2},account:{modelName:e.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:e.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:e.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:e.account?.fields?.userId||"userId"},accessToken:{type:"string",required:!1,fieldName:e.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,fieldName:e.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,fieldName:e.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.accessTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:e.account?.fields?.scope||"scope"},password:{type:"string",required:!1,fieldName:e.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:e.account?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,fieldName:e.account?.fields?.updatedAt||"updatedAt"},...a?.fields},order:3},verification:{modelName:e.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:e.verification?.fields?.identifier||"identifier"},value:{type:"string",required:!0,fieldName:e.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:e.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!1,defaultValue:()=>new Date,fieldName:e.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!1,defaultValue:()=>new Date,fieldName:e.verification?.fields?.updatedAt||"updatedAt"}},order:4},...s,...o?i:{}}};var vn=require("zod");var Xt=require("kysely"),Wo=require("kysely");var Ye={};function er(e){switch(e.constructor.name){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array";default:return"string"}}function wo(e){let t=[];return e.metadata?.openapi?.parameters?(t.push(...e.metadata.openapi.parameters),t):(e.query instanceof ce.ZodObject&&Object.entries(e.query.shape).forEach(([o,i])=>{i instanceof ce.ZodSchema&&t.push({name:o,in:"query",schema:{type:er(i),..."minLength"in i&&i.minLength?{minLength:i.minLength}:{},description:i.description}})}),t)}function Yt(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof ce.ZodObject||e.body instanceof ce.ZodOptional)){let t=e.body.shape;if(!t)return;let o={},i=[];return Object.entries(t).forEach(([r,n])=>{n instanceof ce.ZodSchema&&(o[r]={type:er(n),description:n.description},n instanceof ce.ZodOptional||i.push(r))}),{required:e.body instanceof ce.ZodOptional?!1:!!e.body,content:{"application/json":{schema:{type:"object",properties:o,required:i}}}}}}function Co(e){return{400:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Bad Request. Usually due to missing parameters, or invalid parameters."},401:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Unauthorized. Due to missing or invalid authentication."},403:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Forbidden. You do not have permission to access this resource or to perform this action."},404:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Not Found. The requested resource was not found."},429:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Too Many Requests. You have exceeded the rate limit. Try again later."},500:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Internal Server Error. This is a problem with the server that you cannot fix."},...e}}async function Jo(e,t){let o=Uo(e,{...t,plugins:[]}),i=qe(t),n={schemas:{...Object.entries(i).reduce((s,[d,A])=>{let K=d.charAt(0).toUpperCase()+d.slice(1);return s[K]={type:"object",properties:Object.entries(A.fields).reduce((u,[p,l])=>(u[p]={type:l.type},u),{})},s},{})}};Object.entries(o.api).forEach(([s,d])=>{let A=d.options;if(!A.metadata?.SERVER_ONLY&&(A.method==="GET"&&(Ye[d.path]={get:{tags:["Default",...A.metadata?.openapi?.tags||[]],description:A.metadata?.openapi?.description,operationId:A.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(A),responses:Co(A.metadata?.openapi?.responses)}}),A.method==="POST")){let K=Yt(A);Ye[d.path]={post:{tags:["Default",...A.metadata?.openapi?.tags||[]],description:A.metadata?.openapi?.description,operationId:A.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(A),...K?{requestBody:K}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:Co(A.metadata?.openapi?.responses)}}}});for(let s of t.plugins||[]){if(s.id==="open-api")continue;let d=Uo(e,{...t,plugins:[s]}),A=Object.keys(d.api).map(K=>o.api[K]===void 0?d.api[K]:null).filter(K=>K!==null);Object.entries(A).forEach(([K,u])=>{let p=u.options;p.metadata?.SERVER_ONLY||(p.method==="GET"&&(Ye[u.path]={get:{tags:p.metadata?.openapi?.tags||[s.id.charAt(0).toUpperCase()+s.id.slice(1)],description:p.metadata?.openapi?.description,operationId:p.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(p),responses:Co(p.metadata?.openapi?.responses)}}),p.method==="POST"&&(Ye[u.path]={post:{tags:p.metadata?.openapi?.tags||[s.id.charAt(0).toUpperCase()+s.id.slice(1)],description:p.metadata?.openapi?.description,operationId:p.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(p),requestBody:Yt(p),responses:Co(p.metadata?.openapi?.responses)}}))})}return{openapi:"3.1.1",info:{title:"Better Auth",description:"API Reference for your Better Auth Instance"},components:n,security:[{apiKeyCookie:[]}],servers:[{url:e.baseURL}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:Ye}}var or=`<svg width="75" height="75" viewBox="0 0 75 75" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
|
84
84
|
<rect width="75" height="75" fill="url(#pattern0_21_12)"/>
|
|
85
85
|
<defs>
|
|
86
86
|
<pattern id="pattern0_21_12" patternContentUnits="objectBoundingBox" width="1" height="1">
|