better-auth 1.0.21 → 1.0.22-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/adapters/prisma.d.cts +1 -1
  2. package/dist/adapters/prisma.d.ts +1 -1
  3. package/dist/api.cjs +1 -1
  4. package/dist/api.js +1 -1
  5. package/dist/client/plugins.d.cts +1 -1
  6. package/dist/client/plugins.d.ts +1 -1
  7. package/dist/{index-Dt4lZbQi.d.ts → index-Dd3_WG87.d.ts} +105 -103
  8. package/dist/{index-CgaJXZ9u.d.cts → index-Dp04oxSM.d.cts} +105 -103
  9. package/dist/index.cjs +2 -2
  10. package/dist/index.js +2 -2
  11. package/dist/plugin/custom-session.cjs +4 -4
  12. package/dist/plugin/custom-session.js +2 -2
  13. package/dist/plugins/admin.cjs +1 -1
  14. package/dist/plugins/admin.js +1 -1
  15. package/dist/plugins/anonymous.cjs +1 -1
  16. package/dist/plugins/anonymous.js +1 -1
  17. package/dist/plugins/bearer.cjs +1 -1
  18. package/dist/plugins/bearer.js +1 -1
  19. package/dist/plugins/email-otp.cjs +1 -1
  20. package/dist/plugins/email-otp.js +1 -1
  21. package/dist/plugins/generic-oauth.cjs +1 -1
  22. package/dist/plugins/generic-oauth.js +1 -1
  23. package/dist/plugins/jwt.cjs +2 -2
  24. package/dist/plugins/jwt.js +2 -2
  25. package/dist/plugins/multi-session.cjs +1 -1
  26. package/dist/plugins/multi-session.js +1 -1
  27. package/dist/plugins/one-tap.cjs +1 -1
  28. package/dist/plugins/one-tap.js +1 -1
  29. package/dist/plugins/open-api.cjs +1 -1
  30. package/dist/plugins/open-api.js +1 -1
  31. package/dist/plugins/organization.cjs +4 -4
  32. package/dist/plugins/organization.d.cts +1 -1
  33. package/dist/plugins/organization.d.ts +1 -1
  34. package/dist/plugins/organization.js +2 -2
  35. package/dist/plugins/passkey.cjs +1 -1
  36. package/dist/plugins/passkey.js +1 -1
  37. package/dist/plugins/phone-number.cjs +1 -1
  38. package/dist/plugins/phone-number.js +1 -1
  39. package/dist/plugins/two-factor.cjs +1 -1
  40. package/dist/plugins/two-factor.js +1 -1
  41. package/dist/plugins/username.cjs +1 -1
  42. package/dist/plugins/username.js +1 -1
  43. package/dist/plugins.cjs +3 -3
  44. package/dist/plugins.d.cts +1 -1
  45. package/dist/plugins.d.ts +1 -1
  46. package/dist/plugins.js +4 -4
  47. package/package.json +1 -1
package/dist/plugins.js CHANGED
@@ -1,4 +1,4 @@
1
- import{APIError as et}from"better-call";import{z as Fe}from"zod";import{createEndpointCreator as Et,createMiddleware as ko,createMiddlewareCreator as Rt}from"better-call";var Po=ko(async()=>({})),k=Rt({use:[Po,ko(async()=>({}))]}),p=Et({use:[Po]});import{APIError as Q}from"better-call";import{z as L}from"zod";import{TimeSpan as Fn}from"oslo";import{base64url as kt}from"oslo/encoding";import{HMAC as No,sha256 as kn}from"oslo/crypto";async function St({value:e,secret:i}){return new No("SHA-256").sign(new TextEncoder().encode(i),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function Ut({value:e,signature:i,secret:t}){return new No("SHA-256").verify(new TextEncoder().encode(t),Buffer.from(i,"base64"),new TextEncoder().encode(e))}var Ze={sign:St,verify:Ut};var X=class extends Error{constructor(i,t){super(i),this.name="BetterAuthError",this.message=i,this.cause=t,this.stack=""}};var P=(e,i="ms")=>new Date(Date.now()+(i==="sec"?e*1e3:e));var We=Object.create(null),ke=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?We:globalThis),ne=new Proxy(We,{get(e,i){return ke()[i]??We[i]},has(e,i){let t=ke();return i in t||i in We},set(e,i,t){let o=ke(!0);return o[i]=t,!0},deleteProperty(e,i){if(!i)return!1;let t=ke(!0);return delete t[i],!0},ownKeys(){let e=ke(!0);return Object.keys(e)}});function _t(e){return e?e!=="false":!1}var lo=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Je=lo==="dev"||lo==="development",vt=lo==="test"||_t(ne.TEST);function Ce(e){let i=new Map;return e.split(", ").forEach(o=>{let r=o.split(";").map(u=>u.trim()),[n,...s]=r,[A,...a]=n.split("="),d=a.join("=");if(!A||d===void 0)return;let c={value:d};s.forEach(u=>{let[l,...K]=u.split("="),m=K.join("="),C=l.trim().toLowerCase();switch(C){case"max-age":c["max-age"]=m?parseInt(m.trim(),10):void 0;break;case"expires":c.expires=m?new Date(m.trim()):void 0;break;case"domain":c.domain=m?m.trim():void 0;break;case"path":c.path=m?m.trim():void 0;break;case"secure":c.secure=!0;break;case"httponly":c.httponly=!0;break;case"samesite":c.samesite=m?m.trim().toLowerCase():void 0;break;default:c[C]=m?m.trim():!0;break}}),i.set(A,c)}),i}async function f(e,i,t,o){let r=e.context.authCookies.sessionToken.options,n=t?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,i.session.token,e.context.secret,{...r,maxAge:n,...o}),t&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled){let A=kt.encode(new TextEncoder().encode(JSON.stringify({session:i,expiresAt:P(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await Ze.sign({value:JSON.stringify(i),secret:e.context.secret})})),{includePadding:!1});if(A.length>4093)throw new X("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");e.setCookie(e.context.authCookies.sessionData.name,A,e.context.authCookies.sessionData.options)}e.context.setNewSession(i),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(i.session.token,JSON.stringify({user:i.user,session:i.session}),Math.floor((new Date(i.session.expiresAt).getTime()-Date.now())/1e3))}function M(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 Pe(e){let i=e.split("; "),t=new Map;return i.forEach(o=>{let[r,n]=o.split("=");t.set(r,n)}),t}import{betterFetch as xt}from"@better-fetch/fetch";import{APIError as jt}from"better-call";import{decodeProtectedHeader as zt,importJWK as Ft,jwtVerify as Vt}from"jose";import{parseJWT as Mt}from"oslo/jwt";import{sha256 as Pt}from"oslo/crypto";import{base64url as Nt}from"oslo/encoding";async function Do(e){let i=await Pt(new TextEncoder().encode(e));return Nt.encode(new Uint8Array(i),{includePadding:!1})}function Ye(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?P(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function v({id:e,options:i,authorizationEndpoint:t,state:o,codeVerifier:r,scopes:n,claims:s,redirectURI:A,duration:a}){let d=new URL(t);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",i.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",i.redirectURI||A),r){let c=await Do(r);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",c)}if(s){let c=s.reduce((u,l)=>(u[l]=null,u),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...c}}))}return a&&d.searchParams.set("duration",a),d}import{betterFetch as Dt}from"@better-fetch/fetch";async function U({code:e,codeVerifier:i,redirectURI:t,options:o,tokenEndpoint:r,authentication:n}){let s=new URLSearchParams,A={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),i&&s.set("code_verifier",i),s.set("redirect_uri",t),n==="basic"){let u=btoa(`${o.clientId}:${o.clientSecret}`);A.authorization=`Basic ${u}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await Dt(r,{method:"POST",body:s,headers:A});if(d)throw d;return Ye(a)}import{generateCodeVerifier as Lt,generateState as Bt}from"oslo/oauth2";import{z as pe}from"zod";import{APIError as Bo}from"better-call";function be(e){try{return new URL(e).origin}catch{return null}}function Lo(e){return e.includes("://")?new URL(e).host:e}async function Oe(e,i){let t=e.body?.callbackURL||(e.query?.currentURL?be(e.query?.currentURL):"")||e.context.options.baseURL;if(!t)throw new Bo("BAD_REQUEST",{message:"callbackURL is required"});let o=Lt(),r=Bt(),n=JSON.stringify({callbackURL:t,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,newUserURL:e.body?.newUserCallbackURL,link:i,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let A=await e.context.internalAdapter.createVerificationValue({value:n,identifier:r,expiresAt:s});if(!A)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 Bo("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:A.identifier,codeVerifier:o}}async function Xe(e){let i=e.query.state||e.body.state,t=await e.context.internalAdapter.findVerificationValue(i);if(!t)throw e.context.logger.error("State Mismatch. Verification not found",{state:i}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=pe.object({callbackURL:pe.string(),codeVerifier:pe.string(),errorURL:pe.string().optional(),newUserURL:pe.string().optional(),expiresAt:pe.number(),link:pe.object({email:pe.string(),userId:pe.string()}).optional()}).parse(JSON.parse(t.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(t.id),e.context.logger.error("State expired.",{state:i}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(t.id),o}var xo=e=>{let i="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:t,scopes:o,redirectURI:r}){let n=o||["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=${t}&response_mode=form_post`)},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:r})=>U({code:t,codeVerifier:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:i}),async verifyIdToken(t,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,o);let r=zt(t),{kid:n,alg:s}=r;if(!n||!s)return!1;let A=await qt(n),{payload:a}=await Vt(t,A,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let o=Mt(t.idToken)?.payload;if(!o)return null;let r=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:r,emailVerified:!1,email:o.email,...n},data:o}}}},qt=async e=>{let i="https://appleid.apple.com",t="/auth/keys",{data:o}=await xt(`${i}${t}`);if(!o?.keys)throw new jt("BAD_REQUEST",{message:"Keys not found"});let r=o.keys.find(n=>n.kid===e);if(!r)throw new Error(`JWK with kid ${e} not found`);return await Ft(r,r.alg)};import{betterFetch as Ht}from"@better-fetch/fetch";var jo=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:i,scopes:t,redirectURI:o}){let r=t||["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||o)}&state=${i}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:i,redirectURI:t})=>U({code:i,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let{data:t,error:o}=await Ht("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${i.accessToken}`}});if(o)return null;if(t.avatar===null){let n=t.discriminator==="0"?Number(BigInt(t.id)>>BigInt(22))%6:parseInt(t.discriminator)%5;t.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=t.avatar.startsWith("a_")?"gif":"png";t.image_url=`https://cdn.discordapp.com/avatars/${t.id}/${t.avatar}.${n}`}let r=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.display_name||t.username||"",email:t.email,emailVerified:t.verified,image:t.image_url,...r},data:t}}});import{betterFetch as $t}from"@better-fetch/fetch";var zo=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:i,scopes:t,redirectURI:o}){let r=t||["email","public_profile"];return e.scope&&r.push(...e.scope),await v({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:r,state:i,redirectURI:o})},validateAuthorizationCode:async({code:i,redirectURI:t})=>U({code:i,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let{data:t,error:o}=await $t("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:i.accessToken}});if(o)return null;let r=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.name,email:t.email,image:t.picture.data.url,emailVerified:t.email_verified,...r},data:t}}});import{betterFetch as Fo}from"@better-fetch/fetch";var Vo=e=>{let i="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:t,scopes:o,codeVerifier:r,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),v({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:t,redirectURI:n})},validateAuthorizationCode:async({code:t,redirectURI:o})=>U({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:r}=await Fo("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${t.accessToken}`}});if(r)return null;let n=!1;if(!o.email){let{data:A,error:a}=await Fo("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(A.find(d=>d.primary)??A[0])?.email,n=A.find(d=>d.email===o.email)?.verified??!1)}let s=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n,...s},data:o}}}};import{parseJWT as Wt}from"oslo/jwt";import{createConsola as Gt}from"consola";var mo=["info","success","warn","error","debug"];function Qt(e,i){return mo.indexOf(i)<=mo.indexOf(e)}var Zt=Gt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Mo=e=>{let i=e?.disabled!==!0,t=e?.level??"error",o=(r,n,s=[])=>{if(!(!i||!Qt(t,r))){if(!e||typeof e.log!="function"){Zt[r]("",n,...s);return}e.log(r==="success"?"info":r,n,s)}};return Object.fromEntries(mo.map(r=>[r,(...[n,...s])=>o(r,n,s)]))},oe=Mo();import{betterFetch as Jt}from"@better-fetch/fetch";var qo=e=>({id:"google",name:"Google",async createAuthorizationURL({state:i,scopes:t,codeVerifier:o,redirectURI:r}){if(!e.clientId||!e.clientSecret)throw oe.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new X("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new X("codeVerifier is required for Google");let n=t||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await v({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:i,codeVerifier:o,redirectURI:r});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:i,codeVerifier:t,redirectURI:o})=>U({code:i,codeVerifier:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(i,t){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(i,t);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${i}`,{data:r}=await Jt(o);return r?r.aud===e.clientId&&r.iss==="https://accounts.google.com":!1},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);if(!i.idToken)return null;let t=Wt(i.idToken)?.payload,o=await e.mapProfileToUser?.(t);return{user:{id:t.sub,name:t.name,email:t.email,image:t.picture,emailVerified:t.email_verified,...o},data:t}}});import{betterFetch as Yt}from"@better-fetch/fetch";import{parseJWT as Xt}from"oslo/jwt";var Ho=e=>{let i=e.tenantId||"common",t=`https://login.microsoftonline.com/${i}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${i}/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),v({id:"microsoft",options:e,authorizationEndpoint:t,state:r.state,codeVerifier:r.codeVerifier,scopes:n,redirectURI:r.redirectURI})},validateAuthorizationCode({code:r,codeVerifier:n,redirectURI:s}){return U({code:r,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let n=Xt(r.idToken)?.payload,s=e.profilePhotoSize||48;await Yt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${r.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let c=await a.response.clone().arrayBuffer(),u=Buffer.from(c).toString("base64");n.picture=`data:image/jpeg;base64, ${u}`}catch(d){oe.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let A=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0,...A},data:n}}}};import{betterFetch as er}from"@better-fetch/fetch";var $o=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:i,scopes:t,codeVerifier:o,redirectURI:r}){let n=t||["user-read-email"];return e.scope&&n.push(...e.scope),v({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:i,codeVerifier:o,redirectURI:r})},validateAuthorizationCode:async({code:i,codeVerifier:t,redirectURI:o})=>U({code:i,codeVerifier:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let{data:t,error:o}=await er("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});if(o)return null;let r=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.display_name,email:t.email,image:t.images[0]?.url,emailVerified:!1,...r},data:t}}});var Te={isAction:!1};import{nanoid as or}from"nanoid";var $=e=>or(e);import{parseJWT as ir}from"oslo/jwt";var Go=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:i,scopes:t,redirectURI:o}){let r=t||["user:read:email","openid"];return e.scope&&r.push(...e.scope),v({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:r,state:i,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:i,redirectURI:t})=>U({code:i,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let t=i.idToken;if(!t)return oe.error("No idToken found in token"),null;let o=ir(t)?.payload,r=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...r},data:o}}});import{betterFetch as tr}from"@better-fetch/fetch";var Qo=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(i){let t=i.scopes||["users.read","tweet.read","offline.access"];return e.scope&&t.push(...e.scope),v({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:t,state:i.state,codeVerifier:i.codeVerifier,redirectURI:i.redirectURI})},validateAuthorizationCode:async({code:i,codeVerifier:t,redirectURI:o})=>U({code:i,codeVerifier:t,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let{data:t,error:o}=await tr("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});if(o)return null;let r=await e.mapProfileToUser?.(t);return{user:{id:t.data.id,name:t.data.name,email:t.data.username||null,image:t.data.profile_image_url,emailVerified:t.data.verified||!1,...r},data:t}}});import{betterFetch as rr}from"@better-fetch/fetch";var Zo=e=>{let i="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:t,scopes:o,codeVerifier:r,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await v({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:t,redirectURI:n,codeVerifier:r})},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:r})=>await U({code:t,codeVerifier:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:r}=await rr("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let n=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...n},data:o}}}};import{betterFetch as nr}from"@better-fetch/fetch";var Wo=e=>{let i="https://www.linkedin.com/oauth/v2/authorization",t="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:r,redirectURI:n})=>{let s=r||["profile","email","openid"];return e.scope&&s.push(...e.scope),await v({id:"linkedin",options:e,authorizationEndpoint:i,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:r})=>await U({code:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t}),async getUserInfo(o){let{data:r,error:n}=await nr("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(n)return null;let s=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,emailVerified:r.email_verified||!1,image:r.picture,...s},data:r}}}};import{betterFetch as sr}from"@better-fetch/fetch";var go=(e="")=>e.split("://").map(i=>i.replace(/\/{2,}/g,"/")).join("://"),ar=e=>{let i=e||"https://gitlab.com";return{authorizationEndpoint:go(`${i}/oauth/authorize`),tokenEndpoint:go(`${i}/oauth/token`),userinfoEndpoint:go(`${i}/api/v4/user`)}},Jo=e=>{let{authorizationEndpoint:i,tokenEndpoint:t,userinfoEndpoint:o}=ar(e.issuer),r="gitlab";return{id:r,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:A,codeVerifier:a,redirectURI:d})=>{let c=A||["read_user"];return e.scope&&c.push(...e.scope),await v({id:r,options:e,authorizationEndpoint:i,scopes:c,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:A,codeVerifier:a})=>U({code:s,redirectURI:e.redirectURI||A,options:e,codeVerifier:a,tokenEndpoint:t}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:A,error:a}=await sr(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(a||A.state!=="active"||A.locked)return null;let d=await e.mapProfileToUser?.(A);return{user:{id:A.id.toString(),name:A.name??A.username,email:A.email,image:A.avatar_url,emailVerified:!0,...d},data:A}}}};import{betterFetch as Yo}from"@better-fetch/fetch";var Xo=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:i,scopes:t,redirectURI:o}){let r=t||["identity"];return e.scope&&r.push(...e.scope),v({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:r,state:i,redirectURI:o,duration:e.duration})},validateAuthorizationCode:async({code:i,redirectURI:t})=>{let o=new URLSearchParams({grant_type:"authorization_code",code:i,redirect_uri:e.redirectURI||t}),r={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`},{data:n,error:s}=await Yo("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:r,body:o.toString()});if(s)throw s;return Ye(n)},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let{data:t,error:o}=await Yo("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${i.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let r=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.name,email:t.oauth_client_id,emailVerified:t.has_verified_email,image:t.icon_img?.split("?")[0],...r},data:t}}});var Ar={apple:xo,discord:jo,facebook:zo,github:Vo,microsoft:Ho,google:qo,spotify:$o,twitch:Go,twitter:Qo,dropbox:Zo,linkedin:Wo,gitlab:Jo,reddit:Xo},eo=Object.keys(Ar);import{TimeSpan as dr}from"oslo";import{createJWT as cr,validateJWT as pr}from"oslo/jwt";import{z as se}from"zod";import{APIError as De}from"better-call";import{APIError as Ke}from"better-call";import{z as he}from"zod";function fo(e){try{return JSON.parse(e)}catch{return null}}var g={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found"};var ho=()=>p("/get-session",{method:"GET",query:he.optional(he.object({disableCookieCache:he.boolean({description:"Disable cookie cache and fetch session from database"}).or(he.string().transform(e=>e==="true")).optional(),disableRefresh:he.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let i=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!i)return e.json(null);let t=e.getCookie(e.context.authCookies.sessionData.name),o=t?fo(Buffer.from(t,"base64").toString()):null;if(o&&!await Ze.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return M(e),e.json(null);let r=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let c=o.session;if(o.expiresAt<Date.now()||c.session.expiresAt<new Date){let l=e.context.authCookies.sessionData.name;e.setCookie(l,"",{maxAge:0})}else return e.json(c)}let n=await e.context.internalAdapter.findSession(i);if(e.context.session=n,!n||n.session.expiresAt<new Date)return M(e),n&&await e.context.internalAdapter.deleteSession(n.session.token),e.json(null);if(r||e.query?.disableRefresh)return e.json(n);let s=e.context.sessionConfig.expiresIn,A=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-s*1e3+A*1e3<=Date.now()){let c=await e.context.internalAdapter.updateSession(n.session.token,{expiresAt:P(e.context.sessionConfig.expiresIn,"sec")});if(!c)return M(e),e.json(null,{status:401});let u=(c.expiresAt.valueOf()-Date.now())/1e3;return await f(e,{session:c,user:n.user},!1,{maxAge:u}),e.json({session:c,user:n.user})}return e.json(n)}catch(i){throw e.context.logger.error("INTERNAL_SERVER_ERROR",i),new Ke("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_GET_SESSION})}}),S=async(e,i)=>{if(e.context.session)return e.context.session;let t=await ho()({...e,_flag:"json",headers:e.headers,query:i}).catch(o=>null);return e.context.session=t,t},I=k(async e=>{let i=await S(e);if(!i?.session)throw new Ke("UNAUTHORIZED");return{session:i}}),Ne=k(async e=>{let i=await S(e);if(!i?.session)throw new Ke("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:i};let t=e.context.sessionConfig.freshAge,o=i.session.createdAt.valueOf(),r=Date.now();if(!(o+t*1e3>r))throw new Ke("FORBIDDEN",{message:"Session is not fresh"});return{session:i}}),ei=()=>p("/list-sessions",{method:"GET",use:[I],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async e=>{let t=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(t)}),oi=p("/revoke-session",{method:"POST",body:he.object({token:he.string({description:"The token to revoke"})}),use:[I],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let i=e.body.token,t=await e.context.internalAdapter.findSession(i);if(!t)throw new Ke("BAD_REQUEST",{message:"Session not found"});if(t.session.userId!==e.context.session.user.id)throw new Ke("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(i)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new Ke("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ii=p("/revoke-sessions",{method:"POST",use:[I],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(i){throw e.context.logger.error(i&&typeof i=="object"&&"name"in i?i.name:"",i),new Ke("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ti=p("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[I],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let i=e.context.session;if(!i.user)throw new Ke("UNAUTHORIZED");let r=(await e.context.internalAdapter.listSessions(i.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.token!==e.context.session.session.token);return await Promise.all(r.map(n=>e.context.internalAdapter.deleteSession(n.token))),e.json({status:!0})});async function de(e,i,t){return await cr("HS256",Buffer.from(e),{email:i.toLowerCase(),updateTo:t},{expiresIn:new dr(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[i],includeIssuedTimestamp:!0})}async function yo(e,i){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new De("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await de(e.context.secret,i.email),o=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:i,url:o,token:t},e.request)}var ri=p("/send-verification-email",{method:"POST",query:se.object({currentURL:se.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:se.object({email:se.string({description:"The email to send the verification email to"}).email(),callbackURL:se.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new De("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:i}=e.body,t=await e.context.internalAdapter.findUserByEmail(i);if(!t)throw new De("BAD_REQUEST",{message:g.USER_NOT_FOUND});return await yo(e,t.user),e.json({status:!0})}),ni=p("/verify-email",{method:"GET",query:se.object({token:se.string({description:"The token to verify the email"}),callbackURL:se.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function i(A){throw e.query.callbackURL?e.query.callbackURL.includes("?")?e.redirect(`${e.query.callbackURL}&error=${A}`):e.redirect(`${e.query.callbackURL}?error=${A}`):new De("UNAUTHORIZED",{message:A})}let{token:t}=e.query,o;try{o=await pr("HS256",Buffer.from(e.context.secret),t)}catch(A){return e.context.logger.error("Failed to verify email",A),i("invalid_token")}let n=se.object({email:se.string().email(),updateTo:se.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(n.email);if(!s)return i("user_not_found");if(n.updateTo){let A=await S(e);if(!A){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return i("unauthorized")}if(A.user.email!==n.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return i("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo,emailVerified:!1}),d=await de(e.context.secret,n.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${d}`,token:d},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await S(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new De("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await f(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});import{APIError as Le,createRouter as rd,getCookie as Cr,getSignedCookie as br,setCookie as Or,setSignedCookie as Tr}from"better-call";import{APIError as lr}from"better-call";function wo(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function Kr(e){let i="";for(let t=0;t<e.length;t++)i+=wo(e[t]);return i}function si(e,i=!0){if(Array.isArray(e))return`(?:${e.map(c=>`^${si(c,i)}$`).join("|")})`;let t="",o="",r=".";i===!0?(t="/",o="[/\\\\]",r="[^/\\\\]"):i&&(t=i,o=Kr(t),o.length>1?(o=`(?:${o})`,r=`((?!${o}).)`):r=`[^${o}]`);let n=i?`${o}+?`:"",s=i?`${o}*?`:"",A=i?e.split(t):[e],a="";for(let d=0;d<A.length;d++){let c=A[d],u=A[d+1],l="";if(!(!c&&d>0)){if(i&&(d===A.length-1?l=s:u!=="**"?l=n:l=""),i&&c==="**"){l&&(a+=d===0?"":l,a+=`(?:${r}*?${l})*?`);continue}for(let K=0;K<c.length;K++){let m=c[K];m==="\\"?K<c.length-1&&(a+=wo(c[K+1]),K++):m==="?"?a+=r:m==="*"?a+=`${r}*?`:a+=wo(m)}a+=l}}return a}function ur(e,i){if(typeof i!="string")throw new TypeError(`Sample must be a string, but ${typeof i} given`);return e.test(i)}function Co(e,i){if(typeof e!="string"&&!Array.isArray(e))throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if((typeof i=="string"||typeof i=="boolean")&&(i={separator:i}),arguments.length===2&&!(typeof i>"u"||typeof i=="object"&&i!==null&&!Array.isArray(i)))throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof i} given`);if(i=i||{},i.separator==="\\")throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let t=si(e,i.separator),o=new RegExp(`^${t}$`,i.flags),r=ur.bind(null,o);return r.options=i,r.pattern=e,r.regexp=o,r}var mr=k(async e=>{if(e.request?.method!=="POST")return;let{body:i,query:t,context:o}=e,r=e.headers?.get("origin")||e.headers?.get("referer")||"",n=i?.callbackURL||t?.callbackURL,s=i?.redirectTo,A=t?.currentURL,a=i?.errorCallbackURL,d=i?.newUserCallbackURL,c=o.trustedOrigins,u=e.headers?.has("cookie"),l=(m,C)=>m.startsWith("/")?!1:C.includes("*")?Co(C)(Lo(m)):m.startsWith(C),K=(m,C)=>{if(!m)return;if(!c.some(w=>l(m,w)||m?.startsWith("/")&&C!=="origin"&&!m.includes(":")))throw e.context.logger.error(`Invalid ${C}: ${m}`),e.context.logger.info(`If it's a valid URL, please add ${m} to trustedOrigins in your auth config
1
+ import{APIError as et}from"better-call";import{z as Ie}from"zod";import{createEndpointCreator as Et,createMiddleware as ko,createMiddlewareCreator as Rt}from"better-call";var Po=ko(async()=>({})),k=Rt({use:[Po,ko(async()=>({}))]}),p=Et({use:[Po]});import{APIError as Q}from"better-call";import{z as L}from"zod";import{TimeSpan as Fn}from"oslo";import{base64url as kt}from"oslo/encoding";import{HMAC as No,sha256 as kn}from"oslo/crypto";async function St({value:e,secret:i}){return new No("SHA-256").sign(new TextEncoder().encode(i),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function Ut({value:e,signature:i,secret:t}){return new No("SHA-256").verify(new TextEncoder().encode(t),Buffer.from(i,"base64"),new TextEncoder().encode(e))}var Ze={sign:St,verify:Ut};var X=class extends Error{constructor(i,t){super(i),this.name="BetterAuthError",this.message=i,this.cause=t,this.stack=""}};var P=(e,i="ms")=>new Date(Date.now()+(i==="sec"?e*1e3:e));var We=Object.create(null),Pe=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?We:globalThis),ne=new Proxy(We,{get(e,i){return Pe()[i]??We[i]},has(e,i){let t=Pe();return i in t||i in We},set(e,i,t){let o=Pe(!0);return o[i]=t,!0},deleteProperty(e,i){if(!i)return!1;let t=Pe(!0);return delete t[i],!0},ownKeys(){let e=Pe(!0);return Object.keys(e)}});function _t(e){return e?e!=="false":!1}var lo=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Je=lo==="dev"||lo==="development",vt=lo==="test"||_t(ne.TEST);function Ce(e){let i=new Map;return e.split(", ").forEach(o=>{let r=o.split(";").map(u=>u.trim()),[n,...s]=r,[A,...a]=n.split("="),d=a.join("=");if(!A||d===void 0)return;let c={value:d};s.forEach(u=>{let[l,...K]=u.split("="),m=K.join("="),C=l.trim().toLowerCase();switch(C){case"max-age":c["max-age"]=m?parseInt(m.trim(),10):void 0;break;case"expires":c.expires=m?new Date(m.trim()):void 0;break;case"domain":c.domain=m?m.trim():void 0;break;case"path":c.path=m?m.trim():void 0;break;case"secure":c.secure=!0;break;case"httponly":c.httponly=!0;break;case"samesite":c.samesite=m?m.trim().toLowerCase():void 0;break;default:c[C]=m?m.trim():!0;break}}),i.set(A,c)}),i}async function f(e,i,t,o){let r=e.context.authCookies.sessionToken.options,n=t?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,i.session.token,e.context.secret,{...r,maxAge:n,...o}),t&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled){let A=kt.encode(new TextEncoder().encode(JSON.stringify({session:i,expiresAt:P(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await Ze.sign({value:JSON.stringify(i),secret:e.context.secret})})),{includePadding:!1});if(A.length>4093)throw new X("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");e.setCookie(e.context.authCookies.sessionData.name,A,e.context.authCookies.sessionData.options)}e.context.setNewSession(i),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(i.session.token,JSON.stringify({user:i.user,session:i.session}),Math.floor((new Date(i.session.expiresAt).getTime()-Date.now())/1e3))}function M(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 Ne(e){let i=e.split("; "),t=new Map;return i.forEach(o=>{let[r,n]=o.split("=");t.set(r,n)}),t}import{betterFetch as xt}from"@better-fetch/fetch";import{APIError as jt}from"better-call";import{decodeProtectedHeader as zt,importJWK as Ft,jwtVerify as Vt}from"jose";import{parseJWT as Mt}from"oslo/jwt";import{sha256 as Pt}from"oslo/crypto";import{base64url as Nt}from"oslo/encoding";async function Do(e){let i=await Pt(new TextEncoder().encode(e));return Nt.encode(new Uint8Array(i),{includePadding:!1})}function Ye(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?P(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function v({id:e,options:i,authorizationEndpoint:t,state:o,codeVerifier:r,scopes:n,claims:s,redirectURI:A,duration:a}){let d=new URL(t);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",i.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",i.redirectURI||A),r){let c=await Do(r);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",c)}if(s){let c=s.reduce((u,l)=>(u[l]=null,u),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...c}}))}return a&&d.searchParams.set("duration",a),d}import{betterFetch as Dt}from"@better-fetch/fetch";async function U({code:e,codeVerifier:i,redirectURI:t,options:o,tokenEndpoint:r,authentication:n}){let s=new URLSearchParams,A={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),i&&s.set("code_verifier",i),s.set("redirect_uri",t),n==="basic"){let u=btoa(`${o.clientId}:${o.clientSecret}`);A.authorization=`Basic ${u}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await Dt(r,{method:"POST",body:s,headers:A});if(d)throw d;return Ye(a)}import{generateCodeVerifier as Lt,generateState as Bt}from"oslo/oauth2";import{z as pe}from"zod";import{APIError as Bo}from"better-call";function be(e){try{return new URL(e).origin}catch{return null}}function Lo(e){return e.includes("://")?new URL(e).host:e}async function Oe(e,i){let t=e.body?.callbackURL||(e.query?.currentURL?be(e.query?.currentURL):"")||e.context.options.baseURL;if(!t)throw new Bo("BAD_REQUEST",{message:"callbackURL is required"});let o=Lt(),r=Bt(),n=JSON.stringify({callbackURL:t,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,newUserURL:e.body?.newUserCallbackURL,link:i,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let A=await e.context.internalAdapter.createVerificationValue({value:n,identifier:r,expiresAt:s});if(!A)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 Bo("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:A.identifier,codeVerifier:o}}async function Xe(e){let i=e.query.state||e.body.state,t=await e.context.internalAdapter.findVerificationValue(i);if(!t)throw e.context.logger.error("State Mismatch. Verification not found",{state:i}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=pe.object({callbackURL:pe.string(),codeVerifier:pe.string(),errorURL:pe.string().optional(),newUserURL:pe.string().optional(),expiresAt:pe.number(),link:pe.object({email:pe.string(),userId:pe.string()}).optional()}).parse(JSON.parse(t.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(t.id),e.context.logger.error("State expired.",{state:i}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(t.id),o}var xo=e=>{let i="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:t,scopes:o,redirectURI:r}){let n=o||["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=${t}&response_mode=form_post`)},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:r})=>U({code:t,codeVerifier:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:i}),async verifyIdToken(t,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,o);let r=zt(t),{kid:n,alg:s}=r;if(!n||!s)return!1;let A=await qt(n),{payload:a}=await Vt(t,A,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let o=Mt(t.idToken)?.payload;if(!o)return null;let r=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:r,emailVerified:!1,email:o.email,...n},data:o}}}},qt=async e=>{let i="https://appleid.apple.com",t="/auth/keys",{data:o}=await xt(`${i}${t}`);if(!o?.keys)throw new jt("BAD_REQUEST",{message:"Keys not found"});let r=o.keys.find(n=>n.kid===e);if(!r)throw new Error(`JWK with kid ${e} not found`);return await Ft(r,r.alg)};import{betterFetch as Ht}from"@better-fetch/fetch";var jo=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:i,scopes:t,redirectURI:o}){let r=t||["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||o)}&state=${i}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:i,redirectURI:t})=>U({code:i,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let{data:t,error:o}=await Ht("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${i.accessToken}`}});if(o)return null;if(t.avatar===null){let n=t.discriminator==="0"?Number(BigInt(t.id)>>BigInt(22))%6:parseInt(t.discriminator)%5;t.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=t.avatar.startsWith("a_")?"gif":"png";t.image_url=`https://cdn.discordapp.com/avatars/${t.id}/${t.avatar}.${n}`}let r=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.display_name||t.username||"",email:t.email,emailVerified:t.verified,image:t.image_url,...r},data:t}}});import{betterFetch as $t}from"@better-fetch/fetch";var zo=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:i,scopes:t,redirectURI:o}){let r=t||["email","public_profile"];return e.scope&&r.push(...e.scope),await v({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:r,state:i,redirectURI:o})},validateAuthorizationCode:async({code:i,redirectURI:t})=>U({code:i,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let{data:t,error:o}=await $t("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:i.accessToken}});if(o)return null;let r=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.name,email:t.email,image:t.picture.data.url,emailVerified:t.email_verified,...r},data:t}}});import{betterFetch as Fo}from"@better-fetch/fetch";var Vo=e=>{let i="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:t,scopes:o,codeVerifier:r,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),v({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:t,redirectURI:n})},validateAuthorizationCode:async({code:t,redirectURI:o})=>U({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:r}=await Fo("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${t.accessToken}`}});if(r)return null;let n=!1;if(!o.email){let{data:A,error:a}=await Fo("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(A.find(d=>d.primary)??A[0])?.email,n=A.find(d=>d.email===o.email)?.verified??!1)}let s=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n,...s},data:o}}}};import{parseJWT as Wt}from"oslo/jwt";import{createConsola as Gt}from"consola";var mo=["info","success","warn","error","debug"];function Qt(e,i){return mo.indexOf(i)<=mo.indexOf(e)}var Zt=Gt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Mo=e=>{let i=e?.disabled!==!0,t=e?.level??"error",o=(r,n,s=[])=>{if(!(!i||!Qt(t,r))){if(!e||typeof e.log!="function"){Zt[r]("",n,...s);return}e.log(r==="success"?"info":r,n,s)}};return Object.fromEntries(mo.map(r=>[r,(...[n,...s])=>o(r,n,s)]))},oe=Mo();import{betterFetch as Jt}from"@better-fetch/fetch";var qo=e=>({id:"google",name:"Google",async createAuthorizationURL({state:i,scopes:t,codeVerifier:o,redirectURI:r}){if(!e.clientId||!e.clientSecret)throw oe.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new X("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new X("codeVerifier is required for Google");let n=t||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await v({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:i,codeVerifier:o,redirectURI:r});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:i,codeVerifier:t,redirectURI:o})=>U({code:i,codeVerifier:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(i,t){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(i,t);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${i}`,{data:r}=await Jt(o);return r?r.aud===e.clientId&&r.iss==="https://accounts.google.com":!1},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);if(!i.idToken)return null;let t=Wt(i.idToken)?.payload,o=await e.mapProfileToUser?.(t);return{user:{id:t.sub,name:t.name,email:t.email,image:t.picture,emailVerified:t.email_verified,...o},data:t}}});import{betterFetch as Yt}from"@better-fetch/fetch";import{parseJWT as Xt}from"oslo/jwt";var Ho=e=>{let i=e.tenantId||"common",t=`https://login.microsoftonline.com/${i}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${i}/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),v({id:"microsoft",options:e,authorizationEndpoint:t,state:r.state,codeVerifier:r.codeVerifier,scopes:n,redirectURI:r.redirectURI})},validateAuthorizationCode({code:r,codeVerifier:n,redirectURI:s}){return U({code:r,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let n=Xt(r.idToken)?.payload,s=e.profilePhotoSize||48;await Yt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${r.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let c=await a.response.clone().arrayBuffer(),u=Buffer.from(c).toString("base64");n.picture=`data:image/jpeg;base64, ${u}`}catch(d){oe.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let A=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0,...A},data:n}}}};import{betterFetch as er}from"@better-fetch/fetch";var $o=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:i,scopes:t,codeVerifier:o,redirectURI:r}){let n=t||["user-read-email"];return e.scope&&n.push(...e.scope),v({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:i,codeVerifier:o,redirectURI:r})},validateAuthorizationCode:async({code:i,codeVerifier:t,redirectURI:o})=>U({code:i,codeVerifier:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let{data:t,error:o}=await er("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});if(o)return null;let r=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.display_name,email:t.email,image:t.images[0]?.url,emailVerified:!1,...r},data:t}}});var Te={isAction:!1};import{nanoid as or}from"nanoid";var $=e=>or(e);import{parseJWT as ir}from"oslo/jwt";var Go=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:i,scopes:t,redirectURI:o}){let r=t||["user:read:email","openid"];return e.scope&&r.push(...e.scope),v({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:r,state:i,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:i,redirectURI:t})=>U({code:i,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let t=i.idToken;if(!t)return oe.error("No idToken found in token"),null;let o=ir(t)?.payload,r=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...r},data:o}}});import{betterFetch as tr}from"@better-fetch/fetch";var Qo=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(i){let t=i.scopes||["users.read","tweet.read","offline.access"];return e.scope&&t.push(...e.scope),v({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:t,state:i.state,codeVerifier:i.codeVerifier,redirectURI:i.redirectURI})},validateAuthorizationCode:async({code:i,codeVerifier:t,redirectURI:o})=>U({code:i,codeVerifier:t,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let{data:t,error:o}=await tr("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});if(o)return null;let r=await e.mapProfileToUser?.(t);return{user:{id:t.data.id,name:t.data.name,email:t.data.username||null,image:t.data.profile_image_url,emailVerified:t.data.verified||!1,...r},data:t}}});import{betterFetch as rr}from"@better-fetch/fetch";var Zo=e=>{let i="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:t,scopes:o,codeVerifier:r,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await v({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:t,redirectURI:n,codeVerifier:r})},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:r})=>await U({code:t,codeVerifier:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:i}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:r}=await rr("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let n=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...n},data:o}}}};import{betterFetch as nr}from"@better-fetch/fetch";var Wo=e=>{let i="https://www.linkedin.com/oauth/v2/authorization",t="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:r,redirectURI:n})=>{let s=r||["profile","email","openid"];return e.scope&&s.push(...e.scope),await v({id:"linkedin",options:e,authorizationEndpoint:i,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:r})=>await U({code:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t}),async getUserInfo(o){let{data:r,error:n}=await nr("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(n)return null;let s=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,emailVerified:r.email_verified||!1,image:r.picture,...s},data:r}}}};import{betterFetch as sr}from"@better-fetch/fetch";var go=(e="")=>e.split("://").map(i=>i.replace(/\/{2,}/g,"/")).join("://"),ar=e=>{let i=e||"https://gitlab.com";return{authorizationEndpoint:go(`${i}/oauth/authorize`),tokenEndpoint:go(`${i}/oauth/token`),userinfoEndpoint:go(`${i}/api/v4/user`)}},Jo=e=>{let{authorizationEndpoint:i,tokenEndpoint:t,userinfoEndpoint:o}=ar(e.issuer),r="gitlab";return{id:r,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:A,codeVerifier:a,redirectURI:d})=>{let c=A||["read_user"];return e.scope&&c.push(...e.scope),await v({id:r,options:e,authorizationEndpoint:i,scopes:c,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:A,codeVerifier:a})=>U({code:s,redirectURI:e.redirectURI||A,options:e,codeVerifier:a,tokenEndpoint:t}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:A,error:a}=await sr(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(a||A.state!=="active"||A.locked)return null;let d=await e.mapProfileToUser?.(A);return{user:{id:A.id.toString(),name:A.name??A.username,email:A.email,image:A.avatar_url,emailVerified:!0,...d},data:A}}}};import{betterFetch as Yo}from"@better-fetch/fetch";var Xo=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:i,scopes:t,redirectURI:o}){let r=t||["identity"];return e.scope&&r.push(...e.scope),v({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:r,state:i,redirectURI:o,duration:e.duration})},validateAuthorizationCode:async({code:i,redirectURI:t})=>{let o=new URLSearchParams({grant_type:"authorization_code",code:i,redirect_uri:e.redirectURI||t}),r={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`},{data:n,error:s}=await Yo("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:r,body:o.toString()});if(s)throw s;return Ye(n)},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let{data:t,error:o}=await Yo("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${i.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let r=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.name,email:t.oauth_client_id,emailVerified:t.has_verified_email,image:t.icon_img?.split("?")[0],...r},data:t}}});var Ar={apple:xo,discord:jo,facebook:zo,github:Vo,microsoft:Ho,google:qo,spotify:$o,twitch:Go,twitter:Qo,dropbox:Zo,linkedin:Wo,gitlab:Jo,reddit:Xo},eo=Object.keys(Ar);import{TimeSpan as dr}from"oslo";import{createJWT as cr,validateJWT as pr}from"oslo/jwt";import{z as se}from"zod";import{APIError as Le}from"better-call";import{APIError as Ke}from"better-call";import{z as he}from"zod";function fo(e){try{return JSON.parse(e)}catch{return null}}var g={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found"};var ho=()=>p("/get-session",{method:"GET",query:he.optional(he.object({disableCookieCache:he.boolean({description:"Disable cookie cache and fetch session from database"}).or(he.string().transform(e=>e==="true")).optional(),disableRefresh:he.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let i=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!i)return e.json(null);let t=e.getCookie(e.context.authCookies.sessionData.name),o=t?fo(Buffer.from(t,"base64").toString()):null;if(o&&!await Ze.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return M(e),e.json(null);let r=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let c=o.session;if(o.expiresAt<Date.now()||c.session.expiresAt<new Date){let l=e.context.authCookies.sessionData.name;e.setCookie(l,"",{maxAge:0})}else return e.json(c)}let n=await e.context.internalAdapter.findSession(i);if(e.context.session=n,!n||n.session.expiresAt<new Date)return M(e),n&&await e.context.internalAdapter.deleteSession(n.session.token),e.json(null);if(r||e.query?.disableRefresh)return e.json(n);let s=e.context.sessionConfig.expiresIn,A=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-s*1e3+A*1e3<=Date.now()){let c=await e.context.internalAdapter.updateSession(n.session.token,{expiresAt:P(e.context.sessionConfig.expiresIn,"sec")});if(!c)return M(e),e.json(null,{status:401});let u=(c.expiresAt.valueOf()-Date.now())/1e3;return await f(e,{session:c,user:n.user},!1,{maxAge:u}),e.json({session:c,user:n.user})}return e.json(n)}catch(i){throw e.context.logger.error("INTERNAL_SERVER_ERROR",i),new Ke("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_GET_SESSION})}}),S=async(e,i)=>{if(e.context.session)return e.context.session;let t=await ho()({...e,_flag:"json",headers:e.headers,query:i}).catch(o=>null);return e.context.session=t,t},I=k(async e=>{let i=await S(e);if(!i?.session)throw new Ke("UNAUTHORIZED");return{session:i}}),De=k(async e=>{let i=await S(e);if(!i?.session)throw new Ke("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:i};let t=e.context.sessionConfig.freshAge,o=i.session.updatedAt?.valueOf()||i.session.createdAt.valueOf();if(!(Date.now()-o<t*1e3))throw new Ke("FORBIDDEN",{message:"Session is not fresh"});return{session:i}}),ei=()=>p("/list-sessions",{method:"GET",use:[I],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async e=>{let t=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(t)}),oi=p("/revoke-session",{method:"POST",body:he.object({token:he.string({description:"The token to revoke"})}),use:[I],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let i=e.body.token,t=await e.context.internalAdapter.findSession(i);if(!t)throw new Ke("BAD_REQUEST",{message:"Session not found"});if(t.session.userId!==e.context.session.user.id)throw new Ke("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(i)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new Ke("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ii=p("/revoke-sessions",{method:"POST",use:[I],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(i){throw e.context.logger.error(i&&typeof i=="object"&&"name"in i?i.name:"",i),new Ke("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ti=p("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[I],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let i=e.context.session;if(!i.user)throw new Ke("UNAUTHORIZED");let r=(await e.context.internalAdapter.listSessions(i.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.token!==e.context.session.session.token);return await Promise.all(r.map(n=>e.context.internalAdapter.deleteSession(n.token))),e.json({status:!0})});async function de(e,i,t){return await cr("HS256",Buffer.from(e),{email:i.toLowerCase(),updateTo:t},{expiresIn:new dr(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[i],includeIssuedTimestamp:!0})}async function yo(e,i){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Le("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await de(e.context.secret,i.email),o=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:i,url:o,token:t},e.request)}var ri=p("/send-verification-email",{method:"POST",query:se.object({currentURL:se.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:se.object({email:se.string({description:"The email to send the verification email to"}).email(),callbackURL:se.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Le("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:i}=e.body,t=await e.context.internalAdapter.findUserByEmail(i);if(!t)throw new Le("BAD_REQUEST",{message:g.USER_NOT_FOUND});return await yo(e,t.user),e.json({status:!0})}),ni=p("/verify-email",{method:"GET",query:se.object({token:se.string({description:"The token to verify the email"}),callbackURL:se.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function i(A){throw e.query.callbackURL?e.query.callbackURL.includes("?")?e.redirect(`${e.query.callbackURL}&error=${A}`):e.redirect(`${e.query.callbackURL}?error=${A}`):new Le("UNAUTHORIZED",{message:A})}let{token:t}=e.query,o;try{o=await pr("HS256",Buffer.from(e.context.secret),t)}catch(A){return e.context.logger.error("Failed to verify email",A),i("invalid_token")}let n=se.object({email:se.string().email(),updateTo:se.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(n.email);if(!s)return i("user_not_found");if(n.updateTo){let A=await S(e);if(!A){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return i("unauthorized")}if(A.user.email!==n.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return i("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo,emailVerified:!1}),d=await de(e.context.secret,n.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${d}`,token:d},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await S(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new Le("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await f(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});import{APIError as Be,createRouter as rd,getCookie as Cr,getSignedCookie as br,setCookie as Or,setSignedCookie as Tr}from"better-call";import{APIError as lr}from"better-call";function wo(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function Kr(e){let i="";for(let t=0;t<e.length;t++)i+=wo(e[t]);return i}function si(e,i=!0){if(Array.isArray(e))return`(?:${e.map(c=>`^${si(c,i)}$`).join("|")})`;let t="",o="",r=".";i===!0?(t="/",o="[/\\\\]",r="[^/\\\\]"):i&&(t=i,o=Kr(t),o.length>1?(o=`(?:${o})`,r=`((?!${o}).)`):r=`[^${o}]`);let n=i?`${o}+?`:"",s=i?`${o}*?`:"",A=i?e.split(t):[e],a="";for(let d=0;d<A.length;d++){let c=A[d],u=A[d+1],l="";if(!(!c&&d>0)){if(i&&(d===A.length-1?l=s:u!=="**"?l=n:l=""),i&&c==="**"){l&&(a+=d===0?"":l,a+=`(?:${r}*?${l})*?`);continue}for(let K=0;K<c.length;K++){let m=c[K];m==="\\"?K<c.length-1&&(a+=wo(c[K+1]),K++):m==="?"?a+=r:m==="*"?a+=`${r}*?`:a+=wo(m)}a+=l}}return a}function ur(e,i){if(typeof i!="string")throw new TypeError(`Sample must be a string, but ${typeof i} given`);return e.test(i)}function Co(e,i){if(typeof e!="string"&&!Array.isArray(e))throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if((typeof i=="string"||typeof i=="boolean")&&(i={separator:i}),arguments.length===2&&!(typeof i>"u"||typeof i=="object"&&i!==null&&!Array.isArray(i)))throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof i} given`);if(i=i||{},i.separator==="\\")throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let t=si(e,i.separator),o=new RegExp(`^${t}$`,i.flags),r=ur.bind(null,o);return r.options=i,r.pattern=e,r.regexp=o,r}var mr=k(async e=>{if(e.request?.method!=="POST")return;let{body:i,query:t,context:o}=e,r=e.headers?.get("origin")||e.headers?.get("referer")||"",n=i?.callbackURL||t?.callbackURL,s=i?.redirectTo,A=t?.currentURL,a=i?.errorCallbackURL,d=i?.newUserCallbackURL,c=o.trustedOrigins,u=e.headers?.has("cookie"),l=(m,C)=>m.startsWith("/")?!1:C.includes("*")?Co(C)(Lo(m)):m.startsWith(C),K=(m,C)=>{if(!m)return;if(!c.some(w=>l(m,w)||m?.startsWith("/")&&C!=="origin"&&!m.includes(":")))throw e.context.logger.error(`Invalid ${C}: ${m}`),e.context.logger.info(`If it's a valid URL, please add ${m} to trustedOrigins in your auth config
2
2
  `,`Current list of trustedOrigins: ${c}`),new lr("FORBIDDEN",{message:`Invalid ${C}`})};u&&!e.context.options.advanced?.disableCSRFCheck&&K(r,"origin"),n&&K(n,"callbackURL"),s&&K(s,"redirectURL"),A&&K(A,"currentURL"),a&&K(a,"errorCallbackURL"),d&&K(s,"newUserCallbackURL")});var ai=p("/ok",{method:"GET",metadata:{...Te,openapi:{description:"Check if the API is working",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean"}}}}}}}}}},async e=>e.json({ok:!0}));import{z as Ee}from"zod";import{APIError as ue}from"better-call";import{z as E}from"zod";import{APIError as gr}from"better-call";var _A=E.object({id:E.string(),providerId:E.string(),accountId:E.string(),userId:E.string(),accessToken:E.string().nullish(),refreshToken:E.string().nullish(),idToken:E.string().nullish(),accessTokenExpiresAt:E.date().nullish(),refreshTokenExpiresAt:E.date().nullish(),scope:E.string().nullish(),password:E.string().nullish(),createdAt:E.date().default(()=>new Date),updatedAt:E.date().default(()=>new Date)}),vA=E.object({id:E.string(),email:E.string().transform(e=>e.toLowerCase()),emailVerified:E.boolean().default(!1),name:E.string(),image:E.string().nullish(),createdAt:E.date().default(()=>new Date),updatedAt:E.date().default(()=>new Date)}),kA=E.object({id:E.string(),userId:E.string(),expiresAt:E.date(),createdAt:E.date().default(()=>new Date),updatedAt:E.date().default(()=>new Date),token:E.string(),ipAddress:E.string().nullish(),userAgent:E.string().nullish()}),PA=E.object({id:E.string(),value:E.string(),createdAt:E.date().default(()=>new Date),updatedAt:E.date().default(()=>new Date),expiresAt:E.date(),identifier:E.string()});function fr(e,i){let t={...i==="user"?e.user?.additionalFields:{},...i==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[i]&&(t={...t,...o.schema[i].fields});return t}function hr(e,i){let t=i.action||"create",o=i.fields,r={};for(let n in o){if(n in e){if(o[n].input===!1){if(o[n].defaultValue){r[n]=o[n].defaultValue;continue}continue}if(o[n].validator?.input&&e[n]!==void 0){r[n]=o[n].validator.input.parse(e[n]);continue}if(o[n].transform?.input&&e[n]!==void 0){r[n]=o[n].transform?.input(e[n]);continue}r[n]=e[n];continue}if(o[n].defaultValue&&t==="create"){r[n]=o[n].defaultValue;continue}if(o[n].required&&t==="create")throw new gr("BAD_REQUEST",{message:`${n} is required`})}return r}function oo(e,i,t){let o=fr(e,"user");return hr(i||{},{fields:o,action:t})}function ie(e,i){if(!i)return e;for(let t in i){let o=i[t]?.modelName;o&&(e[t].modelName=o);for(let r in e[t].fields){let n=i[t]?.fields?.[r];n&&(e[t].fields[r].fieldName=n)}}return e}var Ai=()=>p("/sign-up/email",{method:"POST",query:Ee.object({currentURL:Ee.string().optional()}).optional(),body:Ee.record(Ee.string(),Ee.any()),metadata:{openapi:{description:"Sign up a user using email and password",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},email:{type:"string",description:"The email of the user"},password:{type:"string",description:"The password of the user"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["name","email","password"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"The id of the user"},email:{type:"string",description:"The email of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"},emailVerified:{type:"boolean",description:"If the email is verified"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new ue("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let i=e.body,{name:t,email:o,password:r,image:n,callbackURL:s,...A}=i;if(!Ee.string().email().safeParse(o).success)throw new ue("BAD_REQUEST",{message:g.INVALID_EMAIL});let d=e.context.password.config.minPasswordLength;if(r.length<d)throw e.context.logger.error("Password is too short"),new ue("BAD_REQUEST",{message:g.PASSWORD_TOO_SHORT});let c=e.context.password.config.maxPasswordLength;if(r.length>c)throw e.context.logger.error("Password is too long"),new ue("BAD_REQUEST",{message:g.PASSWORD_TOO_LONG});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new ue("UNPROCESSABLE_ENTITY",{message:g.USER_ALREADY_EXISTS});let l=oo(e.context.options,A),K;try{if(K=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:t,image:n,...l,emailVerified:!1}),!K)throw new ue("BAD_REQUEST",{message:g.FAILED_TO_CREATE_USER})}catch(N){throw Je&&e.context.logger.error("Failed to create user",N),new ue("UNPROCESSABLE_ENTITY",{message:g.FAILED_TO_CREATE_USER,details:N})}if(!K)throw new ue("UNPROCESSABLE_ENTITY",{message:g.FAILED_TO_CREATE_USER});let m=await e.context.password.hash(r);if(await e.context.internalAdapter.linkAccount({userId:K.id,providerId:"credential",accountId:K.id,password:m}),e.context.options.emailVerification?.sendOnSignUp){let N=await de(e.context.secret,K.email),w=`${e.context.baseURL}/verify-email?token=${N}&callbackURL=${i.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:K,url:w,token:N},e.request)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({id:K.id,email:K.email,name:K.name,image:K.image,emailVerified:K.emailVerified});let C=await e.context.internalAdapter.createSession(K.id,e.request);if(!C)throw new ue("BAD_REQUEST",{message:g.FAILED_TO_CREATE_SESSION});return await f(e,{session:C,user:K}),e.json({id:K.id,email:K.email,name:K.name,image:K.image,emailVerified:K.emailVerified,createdAt:K.createdAt,updatedAt:K.updatedAt})});var yr=(e="Unknown")=>`<!DOCTYPE html>
3
3
  <html lang="en">
4
4
  <head>
@@ -79,8 +79,8 @@ import{APIError as et}from"better-call";import{z as Fe}from"zod";import{createEn
79
79
  <div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
80
80
  </div>
81
81
  </body>
82
- </html>`,di=p("/error",{method:"GET",metadata:{...Te,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string"}}}}}}}},async e=>{let i=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(yr(i),{headers:{"Content-Type":"text/html"}})});import Er from"defu";import{APIError as b}from"better-call";function bo(e,i){let t=i.plugins?.reduce((A,a)=>({...A,...a.endpoints}),{}),o=i.plugins?.map(A=>A.middlewares?.map(a=>{let d=async c=>a.middleware({...c,context:{...e,...c.context}});return d.path=a.path,d.options=a.middleware.options,d.headers=a.middleware.headers,{path:a.path,middleware:d}})).filter(A=>A!==void 0).flat()||[],n={...{signInSocial:ci,callbackOAuth:Ki,getSession:ho(),signOut:ui,signUpEmail:Ai(),signInEmail:pi,forgetPassword:li,resetPassword:gi,verifyEmail:ni,sendVerificationEmail:ri,changeEmail:bi,changePassword:hi,setPassword:yi,updateUser:fi(),deleteUser:wi,forgetPasswordCallback:mi,listSessions:ei(),revokeSession:oi,revokeSessions:ii,revokeOtherSessions:ti,linkSocialAccount:Ti,listUserAccounts:Oi,deleteUserCallback:Ci},...t,ok:ai,error:di},s={};for(let[A,a]of Object.entries(n))s[A]=async(d={})=>{a.headers=new Headers;let c={setHeader(w,R){a.headers.set(w,R)},setCookie(w,R,h){Or(a.headers,w,R,h)},getCookie(w,R){let T=d.headers?.get("cookie");return Cr(T||"",w,R)},getSignedCookie(w,R,h){let T=d.headers;return T?br(T,R,w,h):null},async setSignedCookie(w,R,h,T){await Tr(a.headers,w,R,h,T)},redirect(w){return a.headers.set("Location",w),new Le("FOUND")},responseHeader:a.headers},u=await e,l=null,K={...c,...d,path:a.path,context:{...u,...d.context,session:null,setNewSession:function(w){this.newSession=w,l=w}}},m=i.plugins||[];for(let w of m){let R=w.hooks?.before??[];for(let h of R){if(!h.matcher(K))continue;let T=await h.handler(K);if(T&&"context"in T){K=Er(K,T.context);continue}if(T)return T}}let C;try{C=await a(K),l&&(K.context.newSession=l)}catch(w){if(l&&(K.context.newSession=l),w instanceof Le){let R=i.plugins?.map(h=>{if(h.hooks?.after)return h.hooks.after}).filter(h=>h!==void 0).flat();if(!R?.length)throw w.headers=a.headers,w;K.context.returned=w,K.context.returned.headers=a.headers;for(let h of R||[])if(h.matcher(K))try{let x=await h.handler(K);x&&"response"in x&&(K.context.returned=x.response)}catch(x){if(x instanceof Le){K.context.returned=x;continue}throw x}if(K.context.returned instanceof Le)throw K.context.returned.headers=a.headers,K.context.returned;return K.context.returned}throw w}K.context.returned=C,K.responseHeader=a.headers;for(let w of i.plugins||[])if(w.hooks?.after){for(let R of w.hooks.after)if(R.matcher(K))try{let T=await R.handler(K);if(T)if("responseHeader"in T){let x=T.responseHeader;K.responseHeader=x}else K.context.returned=T}catch(T){if(T instanceof Le){K.context.returned=T;continue}throw T}}let N=K.context.returned;return N instanceof Response&&a.headers.forEach((w,R)=>{R==="set-cookie"?N.headers.append(R,w):N.headers.set(R,w)}),N},s[A].path=a.path,s[A].method=a.method,s[A].options=a.options,s[A].headers=a.headers;return{api:s,middlewares:o}}async function Re(e,{userInfo:i,account:t,callbackURL:o}){let r=await e.context.internalAdapter.findUserByEmail(i.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw oe.error(`Better auth was unable to query your database.
83
- Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=r?.user,s=!n;if(r){let a=r.accounts.find(d=>d.providerId===t.providerId);if(a){let d=Object.fromEntries(Object.entries({accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt}).filter(([c,u])=>u!==void 0));Object.keys(d).length>0&&await e.context.internalAdapter.updateAccount(a.id,d)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.providerId)&&!i.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Je&&oe.warn(`User already exist but account isn't linked to ${t.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:t.providerId,accountId:i.id.toString(),userId:r.user.id,accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt,scope:t.scope})}catch(u){return oe.error("Unable to link account",u),{error:"unable to link account",data:null}}n=await e.context.internalAdapter.updateUser(r.user.id,{...i,updatedAt:new Date})}}else if(n=await e.context.internalAdapter.createOAuthUser({...i,email:i.email.toLowerCase(),id:void 0},{accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt,scope:t.scope,providerId:t.providerId,accountId:i.id.toString()}).then(a=>a?.user),!i.emailVerified&&n&&e.context.options.emailVerification?.sendOnSignUp){let a=await de(e.context.secret,n.email),d=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:n,url:d,token:a},e.request)}if(!n)return{error:"unable to create user",data:null,isRegister:!1};let A=await e.context.internalAdapter.createSession(n.id,e.request);return A?{data:{session:A,user:n},error:null,isRegister:s}:{error:"unable to create session",data:null,isRegister:!1}}var ci=p("/sign-in/social",{method:"POST",query:L.object({currentURL:L.string().optional()}).optional(),body:L.object({callbackURL:L.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:L.string().optional(),errorCallbackURL:L.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:L.enum(eo,{description:"OAuth2 provider to use"}),disableRedirect:L.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:L.optional(L.object({token:L.string({description:"ID token from the provider"}),nonce:L.string({description:"Nonce used to generate the token"}).optional(),accessToken:L.string({description:"Access token from the provider"}).optional(),refreshToken:L.string({description:"Refresh token from the provider"}).optional(),expiresAt:L.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 i=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Q("NOT_FOUND",{message:g.PROVIDER_NOT_FOUND});if(e.body.idToken){if(!i.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new Q("NOT_FOUND",{message:g.ID_TOKEN_NOT_SUPPORTED});let{token:n,nonce:s}=e.body.idToken;if(!await i.verifyIdToken(n,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new Q("UNAUTHORIZED",{message:g.INVALID_TOKEN});let a=await i.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new Q("UNAUTHORIZED",{message:g.FAILED_TO_GET_USER_INFO});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new Q("UNAUTHORIZED",{message:g.USER_EMAIL_NOT_FOUND});let d=await Re(e,{userInfo:{email:a.user.email,id:a.user.id,name:a.user.name||"",image:a.user.image,emailVerified:a.user.emailVerified||!1},account:{providerId:i.id,accountId:a.user.id,accessToken:e.body.idToken.accessToken}});if(d.error)throw new Q("UNAUTHORIZED",{message:d.error});return await f(e,d.data),e.json({session:d.data.session,user:d.data.user,url:void 0,redirect:!1})}let{codeVerifier:t,state:o}=await Oe(e),r=await i.createAuthorizationURL({state:o,codeVerifier:t,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:r.toString(),redirect:!e.body.disableRedirect})}),pi=p("/sign-in/email",{method:"POST",body:L.object({email:L.string({description:"Email of the user"}),password:L.string({description:"Password of the user"}),callbackURL:L.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:L.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:{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("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:i,password:t}=e.body;if(!L.string().email().safeParse(i).success)throw new Q("BAD_REQUEST",{message:g.INVALID_EMAIL});let r=await e.context.internalAdapter.findUserByEmail(i,{includeAccounts:!0});if(!r)throw await e.context.password.hash(t),e.context.logger.error("User not found",{email:i}),new Q("UNAUTHORIZED",{message:g.INVALID_EMAIL_OR_PASSWORD});let n=r.accounts.find(d=>d.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:i}),new Q("UNAUTHORIZED",{message:g.INVALID_EMAIL_OR_PASSWORD});let s=n?.password;if(!s)throw e.context.logger.error("Password not found",{email:i}),new Q("UNAUTHORIZED",{message:g.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:s,password:t}))throw e.context.logger.error("Invalid password"),new Q("UNAUTHORIZED",{message:g.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!r.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new Q("UNAUTHORIZED",{message:g.EMAIL_NOT_VERIFIED});let d=await de(e.context.secret,r.user.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:r.user,url:c,token:d},e.request),e.context.logger.error("Email not verified",{email:i}),new Q("FORBIDDEN",{message:g.EMAIL_NOT_VERIFIED})}let a=await e.context.internalAdapter.createSession(r.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new Q("UNAUTHORIZED",{message:g.FAILED_TO_CREATE_SESSION});return await f(e,{session:a,user:r.user},e.body.rememberMe===!1),e.json({user:{id:r.user.id,email:r.user.email,name:r.user.name,image:r.user.image,emailVerified:r.user.emailVerified,createdAt:r.user.createdAt,updatedAt:r.user.updatedAt},redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as Be}from"zod";var io=Be.object({code:Be.string().optional(),error:Be.string().optional(),error_description:Be.string().optional(),state:Be.string().optional()}),Ki=p("/callback/:id",{method:["GET","POST"],body:io.optional(),query:io.optional(),metadata:Te},async e=>{let i;try{if(e.method==="GET")i=io.parse(e.query);else if(e.method==="POST")i=io.parse(e.body);else throw new Error("Unsupported method")}catch(h){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",h),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:t,error:o,state:r,error_description:n}=i;if(!r)throw e.context.logger.error("State not found",o),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!t)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}&error_description=${n}`);let s=e.context.socialProviders.find(h=>h.id===e.params.id);if(!s)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:a,link:d,errorURL:c,newUserURL:u}=await Xe(e),l;try{l=await s.validateAuthorizationCode({code:t,codeVerifier:A,redirectURI:`${e.context.baseURL}/callback/${s.id}`})}catch(h){throw e.context.logger.error("",h),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let K=await s.getUserInfo(l).then(h=>h?.user);function m(h){let T=c||a||`${e.context.baseURL}/error`;throw T.includes("?")?T=`${T}&error=${h}`:T=`${T}?error=${h}`,e.redirect(T)}if(!K)return e.context.logger.error("Unable to get user info"),m("unable_to_get_user_info");if(!K.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),m("email_not_found");if(!a)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!==K.email.toLowerCase())return m("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:s.id,accountId:K.id}))return m("unable_to_link_account");let T;try{T=a.toString()}catch{T=a}throw e.redirect(T)}let C=await Re(e,{userInfo:{...K,email:K.email,name:K.name||K.email},account:{providerId:s.id,accountId:K.id,...l,scope:l.scopes?.join(",")},callbackURL:a});if(C.error)return e.context.logger.error(C.error.split(" ").join("_")),m(C.error.split(" ").join("_"));let{session:N,user:w}=C.data;await f(e,{session:N,user:w});let R;try{R=(C.isRegister&&u||a).toString()}catch{R=C.isRegister&&u||a}throw e.redirect(R)});import"zod";import{APIError as Rr}from"better-call";var ui=p("/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 i=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!i)throw M(e),new Rr("BAD_REQUEST",{message:g.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(i),M(e),e.json({success:!0})});import{z as te}from"zod";import{APIError as xe}from"better-call";function Ei(e,i,t){let o=i?new URL(i,e.baseURL):new URL(`${e.baseURL}/error`);return t&&Object.entries(t).forEach(([r,n])=>o.searchParams.set(r,n)),o.href}function Ir(e,i,t){let o=new URL(i,e.baseURL);return t&&Object.entries(t).forEach(([r,n])=>o.searchParams.set(r,n)),o.href}var li=p("/forget-password",{method:"POST",body:te.object({email:te.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:te.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 xe("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:i,redirectTo:t}=e.body,o=await e.context.internalAdapter.findUserByEmail(i,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:i}),e.json({status:!1},{body:{status:!0}});let r=60*60*1,n=P(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||r,"sec"),s=$(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:n});let A=`${e.context.baseURL}/reset-password/${s}?callbackURL=${t}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:A,token:s},e.request),e.json({status:!0})}),mi=p("/reset-password/:token",{method:"GET",query:te.object({callbackURL:te.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:i}=e.params,{callbackURL:t}=e.query;if(!i||!t)throw e.redirect(Ei(e.context,t,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${i}`);throw!o||o.expiresAt<new Date?e.redirect(Ei(e.context,t,{error:"INVALID_TOKEN"})):e.redirect(Ir(e.context,t,{token:i}))}),gi=p("/reset-password",{query:te.optional(te.object({token:te.string().optional(),currentURL:te.string().optional()})),method:"POST",body:te.object({newPassword:te.string({description:"The new password to set"}),token:te.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 i=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!i)throw new xe("BAD_REQUEST",{message:g.INVALID_TOKEN});let{newPassword:t}=e.body,o=e.context.password?.config.minPasswordLength,r=e.context.password?.config.maxPasswordLength;if(t.length<o)throw new xe("BAD_REQUEST",{message:g.PASSWORD_TOO_SHORT});if(t.length>r)throw new xe("BAD_REQUEST",{message:g.PASSWORD_TOO_LONG});let n=`reset-password:${i}`,s=await e.context.internalAdapter.findVerificationValue(n);if(!s||s.expiresAt<new Date)throw new xe("BAD_REQUEST",{message:g.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(s.id);let A=s.value,a=await e.context.password.hash(t);return(await e.context.internalAdapter.findAccounts(A)).find(u=>u.providerId==="credential")?(await e.context.internalAdapter.updatePassword(A,a),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:A,providerId:"credential",password:a,accountId:A}),e.json({status:!0}))});import{z as G}from"zod";import{APIError as q}from"better-call";import{xchacha20poly1305 as Ui}from"@noble/ciphers/chacha";import{bytesToHex as vr,hexToBytes as kr,utf8ToBytes as Pr}from"@noble/ciphers/utils";import{managedNonce as _i}from"@noble/ciphers/webcrypto";import{sha256 as vi}from"oslo/crypto";import Si from"uncrypto";import{decodeHex as ec,encodeHex as oc}from"oslo/encoding";import{scryptAsync as rc}from"@noble/hashes/scrypt";import{getRandomValues as sc}from"uncrypto";import Ri from"uncrypto";function Sr(e){return e.toString(2).padStart(8,"0")}function Ur(e){return[...e].map(i=>Sr(i)).join("")}function Ii(e){return parseInt(Ur(e),2)}function _r(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let i=(e-1).toString(2).length,t=i%8,o=new Uint8Array(Math.ceil(i/8));Ri.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1);let r=Ii(o);for(;r>=e;)Ri.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1),r=Ii(o);return r}function F(e,i){let t="";for(let o=0;o<e;o++)t+=i[_r(i.length)];return t}function V(...e){let i=new Set(e),t="";for(let o of i)o==="a-z"?t+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?t+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?t+="0123456789":t+=o;return t}async function je(e,i){let t=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},r=await Si.subtle.importKey("raw",t.encode(e),o,!1,["sign","verify"]),n=await Si.subtle.sign(o.name,r,t.encode(i));return btoa(String.fromCharCode(...new Uint8Array(n)))}var le=async({key:e,data:i})=>{let t=await vi(new TextEncoder().encode(e)),o=Pr(i),r=_i(Ui)(new Uint8Array(t));return vr(r.encrypt(o))},fe=async({key:e,data:i})=>{let t=await vi(new TextEncoder().encode(e)),o=kr(i),r=_i(Ui)(new Uint8Array(t));return new TextDecoder().decode(r.decrypt(o))};var fi=()=>p("/update-user",{method:"POST",body:G.record(G.string(),G.any()),use:[I],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 i=e.body;if(i.email)throw new q("BAD_REQUEST",{message:g.EMAIL_CAN_NOT_BE_UPDATED});let{name:t,image:o,...r}=i,n=e.context.session;if(o===void 0&&t===void 0&&Object.keys(r).length===0)return e.json({id:n.user.id,email:n.user.email,name:n.user.name,image:n.user.image,emailVerified:n.user.emailVerified,createdAt:n.user.createdAt,updatedAt:n.user.updatedAt});let s=oo(e.context.options,r,"update"),A=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:t,image:o,...s});return await f(e,{session:n.session,user:A}),e.json({id:A.id,email:A.email,name:A.name,image:A.image,emailVerified:A.emailVerified,createdAt:A.createdAt,updatedAt:A.updatedAt})}),hi=p("/change-password",{method:"POST",body:G.object({newPassword:G.string({description:"The new password to set"}),currentPassword:G.string({description:"The current password"}),revokeOtherSessions:G.boolean({description:"Revoke all other sessions"}).optional()}),use:[I],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:i,currentPassword:t,revokeOtherSessions:o}=e.body,r=e.context.session,n=e.context.password.config.minPasswordLength;if(i.length<n)throw e.context.logger.error("Password is too short"),new q("BAD_REQUEST",{message:g.PASSWORD_TOO_SHORT});let s=e.context.password.config.maxPasswordLength;if(i.length>s)throw e.context.logger.error("Password is too long"),new q("BAD_REQUEST",{message:g.PASSWORD_TOO_LONG});let a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(u=>u.providerId==="credential"&&u.password);if(!a||!a.password)throw new q("BAD_REQUEST",{message:g.CREDENTIAL_ACCOUNT_NOT_FOUND});let d=await e.context.password.hash(i);if(!await e.context.password.verify({hash:a.password,password:t}))throw new q("BAD_REQUEST",{message:g.INVALID_PASSWORD});if(await e.context.internalAdapter.updateAccount(a.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(r.user.id);let u=await e.context.internalAdapter.createSession(r.user.id,e.headers);if(!u)throw new q("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_GET_SESSION});await f(e,{session:u,user:r.user})}return e.json(r.user)}),yi=p("/set-password",{method:"POST",body:G.object({newPassword:G.string()}),metadata:{SERVER_ONLY:!0},use:[I]},async e=>{let{newPassword:i}=e.body,t=e.context.session,o=e.context.password.config.minPasswordLength;if(i.length<o)throw e.context.logger.error("Password is too short"),new q("BAD_REQUEST",{message:g.PASSWORD_TOO_SHORT});let r=e.context.password.config.maxPasswordLength;if(i.length>r)throw e.context.logger.error("Password is too long"),new q("BAD_REQUEST",{message:g.PASSWORD_TOO_LONG});let s=(await e.context.internalAdapter.findAccounts(t.user.id)).find(a=>a.providerId==="credential"&&a.password),A=await e.context.password.hash(i);if(!s)return await e.context.internalAdapter.linkAccount({userId:t.user.id,providerId:"credential",accountId:t.user.id,password:A}),e.json(t.user);throw new q("BAD_REQUEST",{message:"user already has a password"})}),wi=p("/delete-user",{method:"POST",use:[Ne],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options",{session:e.context.session}),new q("NOT_FOUND");let i=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let r=F(32,V("a-z","A-Z","0-9"));await e.context.internalAdapter.createVerificationValue({value:i.user.id,identifier:`delete-account-${r}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let n=`${e.context.baseURL}/delete-user/callback?token=${r}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:i.user,url:n,token:r},e.request),e.json({success:!0,message:"Verification email sent"})}let t=e.context.options.user.deleteUser?.beforeDelete;t&&await t(i.user,e.request),await e.context.internalAdapter.deleteUser(i.user.id),await e.context.internalAdapter.deleteSessions(i.user.id),await e.context.internalAdapter.deleteAccounts(i.user.id),M(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(i.user,e.request),e.json({success:!0,message:"User deleted"})}),Ci=p("/delete-user/callback",{method:"GET",query:G.object({token:G.string()})},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new q("NOT_FOUND");let i=await S(e);if(!i)throw new q("NOT_FOUND",{message:g.FAILED_TO_GET_USER_INFO});let t=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!t||t.expiresAt<new Date)throw t&&await e.context.internalAdapter.deleteVerificationValue(t.id),new q("NOT_FOUND",{message:g.INVALID_TOKEN});if(t.value!==i.user.id)throw new q("NOT_FOUND",{message:g.INVALID_TOKEN});let o=e.context.options.user.deleteUser?.beforeDelete;o&&await o(i.user,e.request),await e.context.internalAdapter.deleteUser(i.user.id),await e.context.internalAdapter.deleteSessions(i.user.id),await e.context.internalAdapter.deleteAccounts(i.user.id),await e.context.internalAdapter.deleteVerificationValue(t.id),M(e);let r=e.context.options.user.deleteUser?.afterDelete;return r&&await r(i.user,e.request),e.json({success:!0,message:"User deleted"})}),bi=p("/change-email",{method:"POST",query:G.object({currentURL:G.string().optional()}).optional(),body:G.object({newEmail:G.string({description:"The new email to set"}).email(),callbackURL:G.string({description:"The URL to redirect to after email verification"}).optional()}),use:[I],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 q("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 q("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 q("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 q("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await de(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:t},e.request),e.json({user:null,status:!0})});import{z as ze}from"zod";import{APIError as ki}from"better-call";var Oi=p("/list-accounts",{method:"GET",use:[I],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 i=e.context.session,t=await e.context.internalAdapter.findAccounts(i.user.id);return e.json(t.map(o=>({id:o.id,provider:o.providerId})))}),Ti=p("/link-social",{method:"POST",requireHeaders:!0,query:ze.object({currentURL:ze.string().optional()}).optional(),body:ze.object({callbackURL:ze.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:ze.enum(eo,{description:"The OAuth2 provider to use"})}),use:[I],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 i=e.context.session;if((await e.context.internalAdapter.findAccounts(i.user.id)).find(A=>A.providerId===e.body.provider))throw new ki("BAD_REQUEST",{message:g.SOCIAL_ACCOUNT_ALREADY_LINKED});let r=e.context.socialProviders.find(A=>A.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 ki("NOT_FOUND",{message:g.PROVIDER_NOT_FOUND});let n=await Oe(e,{userId:i.user.id,email:i.user.email}),s=await r.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${r.id}`});return e.json({url:s.toString(),redirect:!0})});var Pi=(e,i)=>{let t={};for(let[o,r]of Object.entries(e))t[o]=n=>r({...n,context:{...i,...n.context}}),t[o].path=r.path,t[o].method=r.method,t[o].options=r.options,t[o].headers=r.headers;return t};function to(e){let i=e;return{newRole(t){return Nr(t)}}}function Nr(e){return{statements:e,authorize(i,t){for(let[o,r]of Object.entries(i)){let n=e[o];return n?(t==="OR"?r.some(A=>n.includes(A)):r.every(A=>n.includes(A)))?{success:!0}:{success:!1,error:`Unauthorized to access resource "${o}"`}:{success:!1,error:`You are not allowed to access resource: ${o}`}}return{success:!1,error:"Not authorized"}}}}var Dr={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},Oo=to(Dr),Lr=Oo.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),Br=Oo.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),xr=Oo.newRole({organization:[],member:[],invitation:[]}),Ni={admin:Lr,owner:Br,member:xr};var jr={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*:/},zr=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,Di={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},Fr=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Vr(e){return e instanceof Date&&!isNaN(e.getTime())}function Mr(e){let i=Fr.exec(e);if(!i)return null;let[,t,o,r,n,s,A,a,d,c,u]=i,l=new Date(Date.UTC(parseInt(t,10),parseInt(o,10)-1,parseInt(r,10),parseInt(n,10),parseInt(s,10),parseInt(A,10),a?parseInt(a.padEnd(3,"0"),10):0));if(d){let K=(parseInt(c,10)*60+parseInt(u,10))*(d==="+"?-1:1);l.setUTCMinutes(l.getUTCMinutes()+K)}return Vr(l)?l:null}function qr(e,i={}){let{strict:t=!1,warnings:o=!1,reviver:r,parseDates:n=!0}=i;if(typeof e!="string")return e;let s=e.trim();if(s[0]==='"'&&s.endsWith('"')&&!s.slice(1,-1).includes('"'))return s.slice(1,-1);let A=s.toLowerCase();if(A.length<=9&&A in Di)return Di[A];if(!zr.test(s)){if(t)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(jr).some(([d,c])=>{let u=c.test(s);return u&&o&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${d} pattern`),u})&&t)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(s,(c,u)=>{if(c==="__proto__"||c==="constructor"&&u&&typeof u=="object"&&"prototype"in u){o&&console.warn(`[better-json] Dropping "${c}" key to prevent prototype pollution`);return}if(n&&typeof u=="string"){let l=Mr(u);if(l)return l}return r?r(c,u):u})}catch(d){if(t)throw d;return e}}function Li(e,i={strict:!0}){return qr(e,i)}var Bi=Li;var j=(e,i)=>{let t=e.adapter;return{findOrganizationBySlug:async o=>await t.findOne({model:"organization",where:[{field:"slug",value:o}]}),createOrganization:async o=>{let r=await t.create({model:"organization",data:{...o.organization,metadata:o.organization.metadata?JSON.stringify(o.organization.metadata):void 0}}),n=await t.create({model:"member",data:{organizationId:r.id,userId:o.user.id,createdAt:new Date,role:i?.creatorRole||"owner"}});return{...r,metadata:r.metadata?JSON.parse(r.metadata):void 0,members:[{...n,user:{id:o.user.id,name:o.user.name,email:o.user.email,image:o.user.image}}]}},findMemberByEmail:async o=>{let r=await t.findOne({model:"user",where:[{field:"email",value:o.email}]});if(!r)return null;let n=await t.findOne({model:"member",where:[{field:"organizationId",value:o.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 o=>{let[r,n]=await Promise.all([await t.findOne({model:"member",where:[{field:"userId",value:o.userId},{field:"organizationId",value:o.organizationId}]}),await t.findOne({model:"user",where:[{field:"id",value:o.userId}]})]);return!n||!r?null:{...r,user:{id:n.id,name:n.name,email:n.email,image:n.image}}},findMemberById:async o=>{let r=await t.findOne({model:"member",where:[{field:"id",value:o}]});if(!r)return null;let n=await t.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 o=>await t.create({model:"member",data:o}),updateMember:async(o,r)=>await t.update({model:"member",where:[{field:"id",value:o}],update:{role:r}}),deleteMember:async o=>await t.delete({model:"member",where:[{field:"id",value:o}]}),updateOrganization:async(o,r)=>{let n=await t.update({model:"organization",where:[{field:"id",value:o}],update:{...r,metadata:typeof r.metadata=="object"?JSON.stringify(r.metadata):r.metadata}});return n?{...n,metadata:n.metadata?Bi(n.metadata):void 0}:null},deleteOrganization:async o=>(await t.delete({model:"member",where:[{field:"organizationId",value:o}]}),await t.delete({model:"invitation",where:[{field:"organizationId",value:o}]}),await t.delete({model:"organization",where:[{field:"id",value:o}]}),o),setActiveOrganization:async(o,r)=>await e.internalAdapter.updateSession(o,{activeOrganizationId:r}),findOrganizationById:async o=>await t.findOne({model:"organization",where:[{field:"id",value:o}]}),findFullOrganization:async({organizationId:o,isSlug:r})=>{let n=await t.findOne({model:"organization",where:[{field:r?"slug":"id",value:o}]});if(!n)return null;let[s,A]=await Promise.all([t.findMany({model:"invitation",where:[{field:"organizationId",value:n.id}]}),t.findMany({model:"member",where:[{field:"organizationId",value:n.id}]})]);if(!n)return null;let a=A.map(l=>l.userId),d=await t.findMany({model:"user",where:[{field:"id",value:a,operator:"in"}]}),c=new Map(d.map(l=>[l.id,l])),u=A.map(l=>{let K=c.get(l.userId);if(!K)throw new X("Unexpected error: User not found for member");return{...l,user:{id:K.id,name:K.name,email:K.email,image:K.image}}});return{...n,invitations:s,members:u}},listOrganizations:async o=>{let r=await t.findMany({model:"member",where:[{field:"userId",value:o}]});if(!r||r.length===0)return[];let n=r.map(A=>A.organizationId);return await t.findMany({model:"organization",where:[{field:"id",value:n,operator:"in"}]})},createInvitation:async({invitation:o,user:r})=>{let s=P(i?.invitationExpiresIn||1728e5);return await t.create({model:"invitation",data:{email:o.email,role:o.role,organizationId:o.organizationId,status:"pending",expiresAt:s,inviterId:r.id}})},findInvitationById:async o=>await t.findOne({model:"invitation",where:[{field:"id",value:o}]}),findPendingInvitation:async o=>(await t.findMany({model:"invitation",where:[{field:"email",value:o.email},{field:"organizationId",value:o.organizationId},{field:"status",value:"pending"}]})).filter(n=>new Date(n.expiresAt)>new Date),updateInvitation:async o=>await t.update({model:"invitation",where:[{field:"id",value:o.invitationId}],update:{status:o.status}})}};import"better-call";var H=k(async e=>({})),Z=k({use:[I]},async e=>({session:e.context.session}));import{z as ee}from"zod";import{z as D}from"zod";var xi=D.string(),Hr=D.enum(["pending","accepted","rejected","canceled"]).default("pending"),wp=D.object({id:D.string().default($),name:D.string(),slug:D.string(),logo:D.string().nullish(),metadata:D.record(D.string()).or(D.string().transform(e=>JSON.parse(e))).nullish(),createdAt:D.date()}),Cp=D.object({id:D.string().default($),organizationId:D.string(),userId:D.string(),role:xi,createdAt:D.date()}),bp=D.object({id:D.string().default($),organizationId:D.string(),email:D.string(),role:xi,status:Hr,inviterId:D.string(),expiresAt:D.date()});import{APIError as z}from"better-call";var y={YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization"};var ji=e=>p("/organization/invite-member",{method:"POST",use:[H,Z],body:ee.object({email:ee.string({description:"The email address of the user to invite"}),role:ee.string({description:"The role to assign to the user"}),organizationId:ee.string({description:"The organization ID to invite the user to"}).optional(),resend:ee.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 i=>{if(!i.context.orgOptions.sendInvitationEmail)throw i.context.logger.warn("Invitation email is not enabled. Pass `sendInvitationEmail` to the plugin options to enable it."),new z("BAD_REQUEST",{message:"Invitation email is not enabled"});let t=i.context.session,o=i.body.organizationId||t.session.activeOrganizationId;if(!o)throw new z("BAD_REQUEST",{message:y.ORGANIZATION_NOT_FOUND});let r=j(i.context,i.context.orgOptions),n=await r.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!n)throw new z("BAD_REQUEST",{message:y.MEMBER_NOT_FOUND});let s=i.context.roles[n.role];if(!s)throw new z("BAD_REQUEST",{message:y.ROLE_NOT_FOUND});if(s.authorize({invitation:["create"]}).error)throw new z("FORBIDDEN",{message:y.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION});if(await r.findMemberByEmail({email:i.body.email,organizationId:o}))throw new z("BAD_REQUEST",{message:y.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION});if((await r.findPendingInvitation({email:i.body.email,organizationId:o})).length&&!i.body.resend)throw new z("BAD_REQUEST",{message:y.USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION});let c=await r.createInvitation({invitation:{role:i.body.role,email:i.body.email,organizationId:o},user:t.user}),u=await r.findOrganizationById(o);if(!u)throw new z("BAD_REQUEST",{message:y.ORGANIZATION_NOT_FOUND});return await i.context.orgOptions.sendInvitationEmail?.({id:c.id,role:c.role,email:c.email,organization:u,inviter:{...n,user:t.user}},i.request),i.json(c)}),zi=p("/organization/accept-invitation",{method:"POST",body:ee.object({invitationId:ee.string({description:"The ID of the invitation to accept"})}),use:[H,Z],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 i=e.context.session,t=j(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new z("BAD_REQUEST",{message:y.INVITATION_NOT_FOUND});if(o.email!==i.user.email)throw new z("FORBIDDEN",{message:y.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let r=await t.updateInvitation({invitationId:e.body.invitationId,status:"accepted"}),n=await t.createMember({organizationId:o.organizationId,userId:i.user.id,role:o.role,createdAt:new Date});return await t.setActiveOrganization(i.session.token,o.organizationId),r?e.json({invitation:r,member:n}):e.json(null,{status:400,body:{message:y.INVITATION_NOT_FOUND}})}),Fi=p("/organization/reject-invitation",{method:"POST",body:ee.object({invitationId:ee.string({description:"The ID of the invitation to reject"})}),use:[H,Z],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 i=e.context.session,t=j(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new z("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==i.user.email)throw new z("FORBIDDEN",{message:y.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let r=await t.updateInvitation({invitationId:e.body.invitationId,status:"rejected"});return e.json({invitation:r,member:null})}),Vi=p("/organization/cancel-invitation",{method:"POST",body:ee.object({invitationId:ee.string({description:"The ID of the invitation to cancel"})}),use:[H,Z],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 i=e.context.session,t=j(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o)throw new z("BAD_REQUEST",{message:y.INVITATION_NOT_FOUND});let r=await t.findMemberByOrgId({userId:i.user.id,organizationId:o.organizationId});if(!r)throw new z("BAD_REQUEST",{message:y.MEMBER_NOT_FOUND});if(e.context.roles[r.role].authorize({invitation:["cancel"]}).error)throw new z("FORBIDDEN",{message:y.YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION});let s=await t.updateInvitation({invitationId:e.body.invitationId,status:"canceled"});return e.json(s)}),Mi=p("/organization/get-invitation",{method:"GET",use:[H],requireHeaders:!0,query:ee.object({id:ee.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 i=await S(e);if(!i)throw new z("UNAUTHORIZED",{message:"Not authenticated"});let t=j(e.context,e.context.orgOptions),o=await t.findInvitationById(e.query.id);if(!o||o.status!=="pending"||o.expiresAt<new Date)throw new z("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==i.user.email)throw new z("FORBIDDEN",{message:y.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let r=await t.findOrganizationById(o.organizationId);if(!r)throw new z("BAD_REQUEST",{message:y.ORGANIZATION_NOT_FOUND});let n=await t.findMemberByOrgId({userId:o.inviterId,organizationId:o.organizationId});if(!n)throw new z("BAD_REQUEST",{message:y.INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION});return e.json({...o,organizationName:r.name,organizationSlug:r.slug,inviterEmail:n.user.email})});import{z as ae}from"zod";import{APIError as ye}from"better-call";var qi=()=>p("/organization/add-member",{method:"POST",body:ae.object({userId:ae.string(),role:ae.string(),organizationId:ae.string().optional()}),use:[H],metadata:{SERVER_ONLY:!0}},async e=>{let i=e.body.userId?await S(e).catch(A=>null):null,t=e.body.organizationId||i?.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:y.NO_ACTIVE_ORGANIZATION}});let o=j(e.context,e.context.orgOptions),r=await e.context.internalAdapter.findUserById(e.body.userId);if(!r)throw new ye("BAD_REQUEST",{message:g.USER_NOT_FOUND});if(await o.findMemberByEmail({email:r.email,organizationId:t}))throw new ye("BAD_REQUEST",{message:y.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION});let s=await o.createMember({id:$(),organizationId:t,userId:r.id,role:e.body.role,createdAt:new Date});return e.json(s)}),Hi=p("/organization/remove-member",{method:"POST",body:ae.object({memberIdOrEmail:ae.string({description:"The ID or email of the member to remove"}),organizationId:ae.string({description:"The ID of the organization to remove the member from. If not provided, the active organization will be used"}).optional()}),use:[H,Z],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 i=e.context.session,t=e.body.organizationId||i.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:y.NO_ACTIVE_ORGANIZATION}});let o=j(e.context,e.context.orgOptions),r=await o.findMemberByOrgId({userId:i.user.id,organizationId:t});if(!r)throw new ye("BAD_REQUEST",{message:y.MEMBER_NOT_FOUND});let n=e.context.roles[r.role];if(!n)throw new ye("BAD_REQUEST",{message:y.ROLE_NOT_FOUND});let s=i.user.email===e.body.memberIdOrEmail||r.id===e.body.memberIdOrEmail;if(s&&r.role===(e.context.orgOptions?.creatorRole||"owner"))throw new ye("BAD_REQUEST",{message:y.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER});if(!(s||n.authorize({member:["delete"]}).success))throw new ye("UNAUTHORIZED",{message:y.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER});let d=null;if(e.body.memberIdOrEmail.includes("@")?d=await o.findMemberByEmail({email:e.body.memberIdOrEmail,organizationId:t}):d=await o.findMemberById(e.body.memberIdOrEmail),d?.organizationId!==t)throw new ye("BAD_REQUEST",{message:y.MEMBER_NOT_FOUND});return await o.deleteMember(d.id),i.user.id===d.userId&&i.session.activeOrganizationId===d.organizationId&&await o.setActiveOrganization(i.session.token,null),e.json({member:d})}),$i=e=>p("/organization/update-member-role",{method:"POST",body:ae.object({role:ae.string(),memberId:ae.string(),organizationId:ae.string().optional()}),use:[H,Z],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 i=>{let t=i.context.session,o=i.body.organizationId||t.session.activeOrganizationId;if(!o)return i.json(null,{status:400,body:{message:y.NO_ACTIVE_ORGANIZATION}});let r=j(i.context,i.context.orgOptions),n=await r.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!n)return i.json(null,{status:400,body:{message:y.MEMBER_NOT_FOUND}});let s=i.context.roles[n.role];if(!s)return i.json(null,{status:400,body:{message:y.ROLE_NOT_FOUND}});if(s.authorize({member:["update"]}).error||i.body.role==="owner"&&n.role!=="owner")return i.json(null,{body:{message:"You are not allowed to update this member"},status:403});let a=await r.updateMember(i.body.memberId,i.body.role);return a?i.json(a):i.json(null,{status:400,body:{message:y.MEMBER_NOT_FOUND}})}),Gi=p("/organization/get-active-member",{method:"GET",use:[H,Z],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 i=e.context.session,t=i.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:y.NO_ACTIVE_ORGANIZATION}});let r=await j(e.context,e.context.orgOptions).findMemberByOrgId({userId:i.user.id,organizationId:t});return r?e.json(r):e.json(null,{status:400,body:{message:y.MEMBER_NOT_FOUND}})});import{z as _}from"zod";import{APIError as me}from"better-call";var Qi=p("/organization/create",{method:"POST",body:_.object({name:_.string({description:"The name of the organization"}),slug:_.string({description:"The slug of the organization"}),userId:_.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:_.string({description:"The logo of the organization"}).optional(),metadata:_.record(_.string(),_.any(),{description:"The metadata of the organization"}).optional()}),use:[H],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 i=await S(e);if(!i&&(e.request||e.headers))throw new me("UNAUTHORIZED");let t=i?.user||null;if(!t){if(!e.body.userId)throw new me("UNAUTHORIZED");t=await e.context.internalAdapter.findUserById(e.body.userId)}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("FORBIDDEN",{message:y.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION});let n=j(e.context,o),s=await n.listOrganizations(t.id);if(typeof o.organizationLimit=="number"?s.length>=o.organizationLimit:typeof o.organizationLimit=="function"?await o.organizationLimit(t):!1)throw new me("FORBIDDEN",{message:y.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS});if(await n.findOrganizationBySlug(e.body.slug))throw new me("BAD_REQUEST",{message:y.ORGANIZATION_ALREADY_EXISTS});let d=await n.createOrganization({organization:{id:$(),slug:e.body.slug,name:e.body.name,logo:e.body.logo,createdAt:new Date,metadata:e.body.metadata},user:t});return e.context.session&&await n.setActiveOrganization(e.context.session.session.token,d.id),e.json(d)}),Zi=p("/organization/update",{method:"POST",body:_.object({data:_.object({name:_.string({description:"The name of the organization"}).optional(),slug:_.string({description:"The slug of the organization"}).optional(),logo:_.string({description:"The logo of the organization"}).optional(),metadata:_.record(_.string(),_.any(),{description:"The metadata of the organization"}).optional()}).partial(),organizationId:_.string().optional()}),requireHeaders:!0,use:[H],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 i=await e.context.getSession(e);if(!i)throw new me("UNAUTHORIZED",{message:"User not found"});let t=e.body.organizationId||i.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:y.ORGANIZATION_NOT_FOUND}});let o=j(e.context,e.context.orgOptions),r=await o.findMemberByOrgId({userId:i.user.id,organizationId:t});if(!r)return e.json(null,{status:400,body:{message:y.USER_IS_NOT_A_MEMBER_OF_THE_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:y.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION},status:403});let A=await o.updateOrganization(t,e.body.data);return e.json(A)}),Wi=p("/organization/delete",{method:"POST",body:_.object({organizationId:_.string({description:"The organization id to delete"})}),requireHeaders:!0,use:[H],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 i=await e.context.getSession(e);if(!i)return e.json(null,{status:401});let t=e.body.organizationId;if(!t)return e.json(null,{status:400,body:{message:y.ORGANIZATION_NOT_FOUND}});let o=j(e.context,e.context.orgOptions),r=await o.findMemberByOrgId({userId:i.user.id,organizationId:t});if(!r)return e.json(null,{status:400,body:{message:y.USER_IS_NOT_A_MEMBER_OF_THE_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("FORBIDDEN",{message:y.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION});return t===i.session.activeOrganizationId&&await o.setActiveOrganization(i.session.token,null),await o.deleteOrganization(t),e.json(t)}),Ji=p("/organization/get-full-organization",{method:"GET",query:_.optional(_.object({organizationId:_.string({description:"The organization id to get"}).optional(),organizationSlug:_.string({description:"The organization slug to get"}).optional()})),requireHeaders:!0,use:[H,Z],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 i=e.context.session,t=e.query?.organizationSlug||e.query?.organizationId||i.session.activeOrganizationId;if(!t)return e.json(null,{status:200});let r=await j(e.context,e.context.orgOptions).findFullOrganization({organizationId:t,isSlug:!!e.query?.organizationSlug});if(!r)throw new me("BAD_REQUEST",{message:y.ORGANIZATION_NOT_FOUND});return e.json(r)}),Yi=p("/organization/set-active",{method:"POST",body:_.object({organizationId:_.string({description:"The organization id to set as active. It can be null to unset the active organization"}).nullable().optional(),organizationSlug:_.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:[Z,H],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 i=j(e.context,e.context.orgOptions),t=e.context.session,o=e.body.organizationSlug||e.body.organizationId;if(o===null){if(!t.session.activeOrganizationId)return e.json(null);let a=await i.setActiveOrganization(t.session.token,null);return await f(e,{session:a,user:t.user}),e.json(null)}if(!o){let A=t.session.activeOrganizationId;if(!A)return e.json(null);o=A}let r=await i.findFullOrganization({organizationId:o,isSlug:!!e.body.organizationSlug});if(!r?.members.find(A=>A.userId===t.user.id))throw await i.setActiveOrganization(t.session.token,null),new me("FORBIDDEN",{message:y.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION});let s=await i.setActiveOrganization(t.session.token,o);return await f(e,{session:s,user:t.user}),e.json(r)}),Xi=p("/organization/list",{method:"GET",use:[H,Z],metadata:{openapi:{description:"List all organizations",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Organization"}}}}}}}}},async e=>{let t=await j(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(t)});var $r=to({name:["action"]}),KK=$r.newRole({name:["action"]}),uK=e=>{let i={createOrganization:Qi,updateOrganization:Zi,deleteOrganization:Wi,setActiveOrganization:Yi,getFullOrganization:Ji,listOrganizations:Xi,createInvitation:ji(e),cancelInvitation:Vi,acceptInvitation:zi,getInvitation:Mi,rejectInvitation:Fi,addMember:qi(),removeMember:Hi,updateMemberRole:$i(e),getActiveMember:Gi},t={...Ni,...e?.roles};return{id:"organization",endpoints:{...Pi(i,{orgOptions:e||{},roles:t,getSession:async r=>await S(r)}),hasPermission:p("/organization/has-permission",{method:"POST",requireHeaders:!0,body:Fe.object({permission:Fe.record(Fe.string(),Fe.array(Fe.string()))}),use:[Z],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 et("BAD_REQUEST",{message:y.NO_ACTIVE_ORGANIZATION});let s=await j(r.context).findMemberByOrgId({userId:r.context.session.user.id,organizationId:r.context.session.session.activeOrganizationId||""});if(!s)throw new et("UNAUTHORIZED",{message:y.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION});let a=t[s.role].authorize(r.body.permission);return a.error?r.json({error:a.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:{}},$ERROR_CODES:y}};import{z as ao}from"zod";import{z as ge}from"zod";import{APIError as Ve}from"better-call";var ro="two_factor";var no="trust_device";import{z as ot}from"zod";var we=k({body:ot.object({trustDevice:ot.boolean().optional()})},async e=>{let i=await S(e);if(!i){let t=e.context.createAuthCookie(ro),o=await e.getSignedCookie(t.name,e.context.secret);if(!o)throw new Ve("UNAUTHORIZED",{message:"invalid two factor cookie"});let r=await e.context.internalAdapter.findUserById(o);if(!r)throw new Ve("UNAUTHORIZED",{message:"invalid two factor cookie"});let n=await e.context.internalAdapter.createSession(o,e.request);if(!n)throw new Ve("INTERNAL_SERVER_ERROR",{message:"failed to create session"});return{valid:async()=>{if(await f(e,{session:n,user:r}),e.body.trustDevice){let s=e.context.createAuthCookie(no,{maxAge:2592e3}),A=await je(e.context.secret,`${r.id}!${n.token}`);await e.setSignedCookie(s.name,`${A}!${n.token}`,e.context.secret,s.attributes)}return e.json({session:n,user:r})},invalid:async()=>{throw new Ve("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:{session:n,user:r}}}return{valid:async()=>e.json({session:i,user:i.user}),invalid:async()=>{throw new Ve("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:i}});import{APIError as Me}from"better-call";var W={OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code"};function Gr(e){return Array.from({length:e?.amount??10}).fill(null).map(()=>F(e?.length??10,V("a-z","0-9"))).map(i=>`${i.slice(0,5)}-${i.slice(5)}`)}async function To(e,i){let t=e,o=i?.customBackupCodesGenerate?i.customBackupCodesGenerate():Gr(),r=await le({data:JSON.stringify(o),key:t});return{backupCodes:o,encryptedBackupCodes:r}}async function Qr(e,i){let t=await it(e.backupCodes,i);return t?{status:t.includes(e.code),updated:t.filter(o=>o!==e.code)}:{status:!1,updated:null}}async function it(e,i){let t=Buffer.from(await fe({key:i,data:e})).toString("utf-8"),o=JSON.parse(t),r=ge.array(ge.string()).safeParse(o);return r.success?r.data:null}var tt=(e,i)=>({id:"backup_code",endpoints:{verifyBackupCode:p("/two-factor/verify-backup-code",{method:"POST",body:ge.object({code:ge.string(),disableSession:ge.boolean().optional()}),use:[we]},async t=>{let o=t.context.session.user,r=await t.context.adapter.findOne({model:i,where:[{field:"userId",value:o.id}]});if(!r)throw new Me("BAD_REQUEST",{message:W.BACKUP_CODES_NOT_ENABLED});let n=await Qr({backupCodes:r.backupCodes,code:t.body.code},t.context.secret);if(!n.status)throw new Me("UNAUTHORIZED",{message:W.INVALID_BACKUP_CODE});let s=await le({key:t.context.secret,data:JSON.stringify(n.updated)});return await t.context.adapter.updateMany({model:i,update:{backupCodes:s},where:[{field:"userId",value:o.id}]}),t.body.disableSession||await f(t,{session:t.context.session.session,user:o}),t.json({user:o,session:t.context.session})}),generateBackupCodes:p("/two-factor/generate-backup-codes",{method:"POST",body:ge.object({password:ge.string()}),use:[I]},async t=>{let o=t.context.session.user;if(!o.twoFactorEnabled)throw new Me("BAD_REQUEST",{message:W.TWO_FACTOR_NOT_ENABLED});await t.context.password.checkPassword(o.id,t);let r=await To(t.context.secret,e);return await t.context.adapter.update({model:i,update:{backupCodes:r.encryptedBackupCodes},where:[{field:"userId",value:t.context.session.user.id}]}),t.json({status:!0,backupCodes:r.backupCodes})}),viewBackupCodes:p("/two-factor/view-backup-codes",{method:"GET",body:ge.object({userId:ge.string()}),metadata:{SERVER_ONLY:!0}},async t=>{let o=await t.context.adapter.findOne({model:i,where:[{field:"userId",value:t.body.userId}]});if(!o)throw new Me("BAD_REQUEST",{message:"Backup codes aren't enabled"});let r=await it(o.backupCodes,t.context.secret);if(!r)throw new Me("BAD_REQUEST",{message:W.BACKUP_CODES_NOT_ENABLED});return t.json({status:!0,backupCodes:r})})}});import{APIError as qe}from"better-call";import{z as rt}from"zod";import{TimeSpan as Zr}from"oslo";var nt=(e,i)=>{let t={...e,digits:e?.digits||6,period:new Zr(e?.period||3,"m")},o=p("/two-factor/send-otp",{method:"POST",use:[we],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 qe("BAD_REQUEST",{message:"otp isn't configured"});let s=n.context.session.user;if(!await n.context.adapter.findOne({model:i,where:[{field:"userId",value:s.id}]}))throw new qe("BAD_REQUEST",{message:W.OTP_NOT_ENABLED});let a=F(t.digits,V("0-9"));return await n.context.internalAdapter.createVerificationValue({value:a,identifier:`2fa-otp-${s.id}`,expiresAt:new Date(Date.now()+t.period.milliseconds())}),await e.sendOTP({user:s,otp:a},n.request),n.json({status:!0})}),r=p("/two-factor/verify-otp",{method:"POST",body:rt.object({code:rt.string({description:"The otp code to verify"})}),use:[we],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 s=n.context.session.user;if(!s.twoFactorEnabled)throw new qe("BAD_REQUEST",{message:"two factor isn't enabled"});if(!await n.context.adapter.findOne({model:i,where:[{field:"userId",value:s.id}]}))throw new qe("BAD_REQUEST",{message:W.OTP_NOT_ENABLED});let a=await n.context.internalAdapter.findVerificationValue(`2fa-otp-${s.id}`);if(!a||a.expiresAt<new Date)throw new qe("BAD_REQUEST",{message:W.OTP_HAS_EXPIRED});return a.value===n.body.code?n.context.valid():n.context.invalid()});return{id:"otp",endpoints:{sendTwoFactorOTP:o,verifyTwoFactorOTP:r}}};import{APIError as Ie}from"better-call";import{TimeSpan as Wr}from"oslo";import{TOTPController as st,createTOTPKeyURI as Jr}from"oslo/otp";import{z as so}from"zod";var at=(e,i)=>{let t={...e,digits:e?.digits||6,period:new Wr(e?.period||30,"s")},o=p("/totp/generate",{method:"POST",use:[I],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 s=>{if(!e)throw s.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new Ie("BAD_REQUEST",{message:"totp isn't configured"});let A=s.context.session.user,a=await s.context.adapter.findOne({model:i,where:[{field:"userId",value:A.id}]});if(!a)throw new Ie("BAD_REQUEST",{message:W.TOTP_NOT_ENABLED});return{code:await new st(t).generate(Buffer.from(a.secret))}}),r=p("/two-factor/get-totp-uri",{method:"POST",use:[I],body:so.object({password:so.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 s=>{if(!e)throw s.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new Ie("BAD_REQUEST",{message:"totp isn't configured"});let A=s.context.session.user,a=await s.context.adapter.findOne({model:i,where:[{field:"userId",value:A.id}]});if(!a||!A.twoFactorEnabled)throw new Ie("BAD_REQUEST",{message:W.TOTP_NOT_ENABLED});return await s.context.password.checkPassword(A.id,s),{totpURI:Jr(e.issuer||s.context.appName,A.email,Buffer.from(a.secret),t)}}),n=p("/two-factor/verify-totp",{method:"POST",body:so.object({code:so.string({description:"The otp code to verify"})}),use:[we],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 s=>{if(!e)throw s.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new Ie("BAD_REQUEST",{message:"totp isn't configured"});let A=s.context.session.user,a=await s.context.adapter.findOne({model:i,where:[{field:"userId",value:A.id}]});if(!a)throw new Ie("BAD_REQUEST",{message:W.TOTP_NOT_ENABLED});let d=new st(t),c=await fe({key:s.context.secret,data:a.secret}),u=Buffer.from(c);if(!await d.verify(s.body.code,u))return s.context.invalid();if(!A.twoFactorEnabled){let K=await s.context.internalAdapter.updateUser(A.id,{twoFactorEnabled:!0}),m=await s.context.internalAdapter.createSession(A.id,s.request,!1,s.context.session.session).catch(C=>{throw console.log(C),C});await s.context.internalAdapter.deleteSession(s.context.session.session.token),await f(s,{session:m,user:K})}return s.context.valid()});return{id:"totp",endpoints:{generateTOTP:o,getTOTPURI:r,verifyTOTP:n}}};import{APIError as tu}from"better-call";async function Eo(e,i){let o=(await e.context.internalAdapter.findAccounts(i.userId))?.find(s=>s.providerId==="credential"),r=o?.password;return!o||!r?!1:await e.context.password.verify({hash:r,password:i.password})}import{APIError as dt}from"better-call";import{createTOTPKeyURI as Yr}from"oslo/otp";import{TimeSpan as Xr}from"oslo";var At={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 su=e=>({id:"two-factor",$InferServerPlugin:{},atomListeners:[{matcher:i=>i.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(i){i.data?.twoFactorRedirect&&e?.onTwoFactorRedirect&&await e.onTwoFactorRedirect()}}}]});var Eu=e=>{let i={twoFactorTable:"twoFactor"},t=at({issuer:e?.issuer,...e?.totpOptions},i.twoFactorTable),o=tt({...e?.backupCodeOptions},i.twoFactorTable),r=nt({...e?.otpOptions},i.twoFactorTable);return{id:"two-factor",endpoints:{...t.endpoints,...r.endpoints,...o.endpoints,enableTwoFactor:p("/two-factor/enable",{method:"POST",body:ao.object({password:ao.string({description:"User password"}).min(8)}),use:[I],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 s=n.context.session.user,{password:A}=n.body;if(!await Eo(n,{password:A,userId:s.id}))throw new dt("BAD_REQUEST",{message:g.INVALID_PASSWORD});let d=F(16,V("a-z","0-9","-")),c=await le({key:n.context.secret,data:d}),u=await To(n.context.secret,e?.backupCodeOptions);if(e?.skipVerificationOnEnable){let K=await n.context.internalAdapter.updateUser(s.id,{twoFactorEnabled:!0}),m=await n.context.internalAdapter.createSession(K.id,n.request,!1,n.context.session.session);await f(n,{session:m,user:s}),await n.context.internalAdapter.deleteSession(n.context.session.session.token)}await n.context.adapter.deleteMany({model:i.twoFactorTable,where:[{field:"userId",value:s.id}]}),await n.context.adapter.create({model:i.twoFactorTable,data:{secret:c,backupCodes:u.encryptedBackupCodes,userId:s.id}});let l=Yr(e?.issuer||"BetterAuth",s.email,Buffer.from(d),{digits:e?.totpOptions?.digits||6,period:new Xr(e?.totpOptions?.period||30,"s")});return n.json({totpURI:l,backupCodes:u.backupCodes})}),disableTwoFactor:p("/two-factor/disable",{method:"POST",body:ao.object({password:ao.string({description:"User password"}).min(8)}),use:[I],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 s=n.context.session.user,{password:A}=n.body;if(!await Eo(n,{password:A,userId:s.id}))throw new dt("BAD_REQUEST",{message:"Invalid password"});await n.context.internalAdapter.updateUser(s.id,{twoFactorEnabled:!1}),await n.context.adapter.delete({model:i.twoFactorTable,where:[{field:"userId",value:s.id}]});let d=await n.context.internalAdapter.createSession(s.id,n.request,!1,n.context.session.session);return await f(n,{session:d,user:s}),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:k(async n=>{let s=n.context.newSession;if(!s||!s?.user.twoFactorEnabled)return;let A=n.context.createAuthCookie(no),a=await n.getSignedCookie(A.name,n.context.secret);if(a){let[c,u]=a.split("!"),l=await je(n.context.secret,`${s.user.id}!${u}`);if(c===l){let K=await je(n.context.secret,`${s.user.id}!${s.session.token}`);await n.setSignedCookie(A.name,`${K}!${s.session.token}`,n.context.secret,A.attributes);return}}M(n),await n.context.internalAdapter.deleteSession(s.session.token);let d=n.context.createAuthCookie(ro,{maxAge:60*10});return await n.setSignedCookie(d.name,s.user.id,n.context.secret,d.attributes),n.json({twoFactorRedirect:!0})})}]},schema:ie(At,e?.schema),rateLimit:[{pathMatcher(n){return n.startsWith("/two-factor/")},window:10,max:3}]}};import{generateAuthenticationOptions as An,generateRegistrationOptions as dn,verifyAuthenticationResponse as cn,verifyRegistrationResponse as pn}from"@simplewebauthn/server";import{APIError as Y}from"better-call";import{z as re}from"zod";import{WebAuthnError as tn,startAuthentication as rn,startRegistration as nn}from"@simplewebauthn/browser";import{createFetch as qu}from"@better-fetch/fetch";import"nanostores";import"@better-fetch/fetch";import{atom as Lu}from"nanostores";import"@better-fetch/fetch";import{atom as en,onMount as on}from"nanostores";var Ro=(e,i,t,o)=>{let r=en({data:null,error:null,isPending:!0,isRefetching:!1}),n=()=>{let A=typeof o=="function"?o({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):o;return t(i,{...A,async onSuccess(a){r.set({data:a.data,error:null,isPending:!1,isRefetching:!1}),await A?.onSuccess?.(a)},async onError(a){r.set({error:a.error,data:null,isPending:!1,isRefetching:!1}),await A?.onError?.(a)},async onRequest(a){let d=r.get();r.set({isPending:d.data===null,data:d.data,error:null,isRefetching:!0}),await A?.onRequest?.(a)}})};e=Array.isArray(e)?e:[e];let s=!1;for(let A of e)A.subscribe(()=>{s?n():on(r,()=>(n(),s=!0,()=>{r.off(),A.off()}))});return r};import{atom as sn}from"nanostores";var an=(e,{$listPasskeys:i})=>({signIn:{passkey:async(r,n)=>{let s=await e("/passkey/generate-authenticate-options",{method:"POST",body:{email:r?.email}});if(!s.data)return s;try{let A=await rn(s.data,r?.autoFill||!1),a=await e("/passkey/verify-authentication",{body:{response:A},...r?.fetchOptions,...n,method:"POST"});if(!a.data)return a}catch{return{data:null,error:{message:"auth cancelled",status:400,statusText:"BAD_REQUEST"}}}}},passkey:{addPasskey:async(r,n)=>{let s=await e("/passkey/generate-register-options",{method:"GET"});if(!s.data)return s;try{let A=await nn(s.data),a=await e("/passkey/verify-registration",{...r?.fetchOptions,...n,body:{response:A,name:r?.name},method:"POST"});if(!a.data)return a;i.set(Math.random())}catch(A){return A instanceof tn?A.code==="ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED"?{data:null,error:{message:"previously registered",status:400,statusText:"BAD_REQUEST"}}:A.code==="ERROR_CEREMONY_ABORTED"?{data:null,error:{message:"registration cancelled",status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:A.message,status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:A instanceof Error?A.message:"unknown error",status:500,statusText:"INTERNAL_SERVER_ERROR"}}}}},$Infer:{}}),Kl=()=>{let e=sn();return{id:"passkey",$InferServerPlugin:{},getActions:i=>an(i,{$listPasskeys:e}),getAtoms(i){return{listPasskeys:Ro(e,"/passkey/list-user-passkeys",i,{method:"GET"}),$listPasskeys:e}},pathMethods:{"/passkey/register":"POST","/passkey/authenticate":"POST"},atomListeners:[{matcher(i){return i==="/passkey/verify-registration"||i==="/passkey/delete-passkey"||i==="/passkey/update-passkey"},signal:"_listPasskeys"}]}};var Rl=e=>{let i=ne.BETTER_AUTH_URL,t=e?.rpID||i?.replace("http://","").replace("https://","").split(":")[0]||"localhost";if(!t)throw new X("passkey rpID not found. Please provide a rpID in the options or set the BETTER_AUTH_URL environment variable.");let o={origin:null,...e,rpID:t,advanced:{webAuthnChallengeCookie:"better-auth-passkey",...e?.advanced}},r=new Date(Date.now()+1e3*60*5),n=new Date,s=Math.floor((r.getTime()-n.getTime())/1e3),A={CHALLENGE_NOT_FOUND:"Challenge not found",YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY:"You are not allowed to register this passkey",FAILED_TO_VERIFY_REGISTRATION:"Failed to verify registration",PASSKEY_NOT_FOUND:"Passkey not found",AUTHENTICATION_FAILED:"Authentication failed",UNABLE_TO_CREATE_SESSION:"Unable to create session",FAILED_TO_UPDATE_PASSKEY:"Failed to update passkey"};return{id:"passkey",endpoints:{generatePasskeyRegistrationOptions:p("/passkey/generate-register-options",{method:"GET",use:[Ne],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 a=>{let d=a.context.session,c=await a.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}),u=new Uint8Array(Buffer.from(F(32,V("a-z","0-9")))),l;l=await dn({rpName:o.rpName||a.context.appName,rpID:o.rpID,userID:u,userName:d.user.email||d.user.id,attestationType:"none",excludeCredentials:c.map(m=>({id:m.id,transports:m.transports?.split(",")})),authenticatorSelection:{residentKey:"preferred",userVerification:"preferred",authenticatorAttachment:"platform"}});let K=$(32);return await a.setSignedCookie(o.advanced.webAuthnChallengeCookie,K,a.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:s}),await a.context.internalAdapter.createVerificationValue({identifier:K,value:JSON.stringify({expectedChallenge:l.challenge,userData:{id:d.user.id}}),expiresAt:r}),a.json(l,{status:200})}),generatePasskeyAuthenticationOptions:p("/passkey/generate-authenticate-options",{method:"POST",body:re.object({email:re.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 a=>{let d=await S(a),c=[];d&&(c=await a.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}));let u=await An({rpID:o.rpID,userVerification:"preferred",...c.length?{allowCredentials:c.map(m=>({id:m.id,transports:m.transports?.split(",")}))}:{}}),l={expectedChallenge:u.challenge,userData:{id:d?.user.id||""}},K=$(32);return await a.setSignedCookie(o.advanced.webAuthnChallengeCookie,K,a.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:s}),await a.context.internalAdapter.createVerificationValue({identifier:K,value:JSON.stringify(l),expiresAt:r}),a.json(u,{status:200})}),verifyPasskeyRegistration:p("/passkey/verify-registration",{method:"POST",body:re.object({response:re.any({description:"The response from the authenticator"}),name:re.string({description:"Name of the passkey"}).optional()}),use:[Ne],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 a=>{let d=e?.origin||a.headers?.get("origin")||"";if(!d)return a.json(null,{status:400});let c=a.body.response,u=await a.getSignedCookie(o.advanced.webAuthnChallengeCookie,a.context.secret);if(!u)throw new Y("BAD_REQUEST",{message:A.CHALLENGE_NOT_FOUND});let l=await a.context.internalAdapter.findVerificationValue(u);if(!l)return a.json(null,{status:400});let{expectedChallenge:K,userData:m}=JSON.parse(l.value);if(m.id!==a.context.session.user.id)throw new Y("UNAUTHORIZED",{message:A.YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY});try{let C=await pn({response:c,expectedChallenge:K,expectedOrigin:d,expectedRPID:e?.rpID}),{verified:N,registrationInfo:w}=C;if(!N||!w)return a.json(null,{status:400});let{credentialID:R,credentialPublicKey:h,counter:T,credentialDeviceType:x,credentialBackedUp:Qe}=w,bt=Buffer.from(h).toString("base64"),Ot={name:a.body.name,userId:m.id,webauthnUserID:a.context.generateId({model:"passkey"}),id:R,publicKey:bt,counter:T,deviceType:x,transports:c.response.transports.join(","),backedUp:Qe,createdAt:new Date},Tt=await a.context.adapter.create({model:"passkey",data:Ot});return a.json(Tt,{status:200})}catch(C){throw console.log(C),new Y("INTERNAL_SERVER_ERROR",{message:A.FAILED_TO_VERIFY_REGISTRATION})}}),verifyPasskeyAuthentication:p("/passkey/verify-authentication",{method:"POST",body:re.object({response:re.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 a=>{let d=e?.origin||a.headers?.get("origin")||"";if(!d)throw new Y("BAD_REQUEST",{message:"origin missing"});let c=a.body.response,u=await a.getSignedCookie(o.advanced.webAuthnChallengeCookie,a.context.secret);if(!u)throw new Y("BAD_REQUEST",{message:A.CHALLENGE_NOT_FOUND});let l=await a.context.internalAdapter.findVerificationValue(u);if(!l)throw new Y("BAD_REQUEST",{message:A.CHALLENGE_NOT_FOUND});let{expectedChallenge:K}=JSON.parse(l.value),m=await a.context.adapter.findOne({model:"passkey",where:[{field:"id",value:c.id}]});if(!m)throw new Y("UNAUTHORIZED",{message:A.PASSKEY_NOT_FOUND});try{let C=await cn({response:c,expectedChallenge:K,expectedOrigin:d,expectedRPID:o.rpID,authenticator:{credentialID:m.id,credentialPublicKey:new Uint8Array(Buffer.from(m.publicKey,"base64")),counter:m.counter,transports:m.transports?.split(",")},requireUserVerification:!1}),{verified:N}=C;if(!N)throw new Y("UNAUTHORIZED",{message:A.AUTHENTICATION_FAILED});await a.context.adapter.update({model:"passkey",where:[{field:"id",value:m.id}],update:{counter:C.authenticationInfo.newCounter}});let w=await a.context.internalAdapter.createSession(m.userId,a.request);if(!w)throw new Y("INTERNAL_SERVER_ERROR",{message:A.UNABLE_TO_CREATE_SESSION});let R=await a.context.internalAdapter.findUserById(m.userId);if(!R)throw new Y("INTERNAL_SERVER_ERROR",{message:"User not found"});return await f(a,{session:w,user:R}),a.json({session:w},{status:200})}catch(C){throw a.context.logger.error("Failed to verify authentication",C),new Y("BAD_REQUEST",{message:A.AUTHENTICATION_FAILED})}}),listPasskeys:p("/passkey/list-user-passkeys",{method:"GET",use:[I]},async a=>{let d=await a.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:a.context.session.user.id}]});return a.json(d,{status:200})}),deletePasskey:p("/passkey/delete-passkey",{method:"POST",body:re.object({id:re.string()}),use:[I]},async a=>(await a.context.adapter.delete({model:"passkey",where:[{field:"id",value:a.body.id}]}),a.json(null,{status:200}))),updatePasskey:p("/passkey/update-passkey",{method:"POST",body:re.object({id:re.string(),name:re.string()}),use:[I]},async a=>{let d=await a.context.adapter.findOne({model:"passkey",where:[{field:"id",value:a.body.id}]});if(!d)throw new Y("NOT_FOUND",{message:A.PASSKEY_NOT_FOUND});if(d.userId!==a.context.session.user.id)throw new Y("UNAUTHORIZED",{message:A.YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY});let c=await a.context.adapter.update({model:"passkey",where:[{field:"id",value:a.body.id}],update:{name:a.body.name}});if(!c)throw new Y("INTERNAL_SERVER_ERROR",{message:A.FAILED_TO_UPDATE_PASSKEY});return a.json({passkey:c},{status:200})})},schema:ie(Kn,e?.schema),$ERROR_CODES:A}},Kn={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}}}};import{z as Ao}from"zod";import{APIError as Se}from"better-call";var ct=()=>{let e={INVALID_USERNAME_OR_PASSWORD:"invalid username or password",EMAIL_NOT_VERIFIED:"email not verified",UNEXPECTED_ERROR:"unexpected error",USERNAME_IS_ALREADY_TAKEN:"username is already taken. please try another."};return{id:"username",endpoints:{signInUsername:p("/sign-in/username",{method:"POST",body:Ao.object({username:Ao.string({description:"The username of the user"}),password:Ao.string({description:"The password of the user"}),rememberMe:Ao.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 i=>{let t=await i.context.adapter.findOne({model:"user",where:[{field:"username",value:i.body.username.toLowerCase()}]});if(!t)throw await i.context.password.hash(i.body.password),i.context.logger.error("User not found",{username:ct}),new Se("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});if(!t.emailVerified&&i.context.options.emailAndPassword?.requireEmailVerification)throw await yo(i,t),new Se("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});let o=await i.context.adapter.findOne({model:"account",where:[{field:"userId",value:t.id},{field:"providerId",value:"credential"}]});if(!o)throw new Se("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});let r=o?.password;if(!r)throw i.context.logger.error("Password not found",{username:ct}),new Se("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});if(!await i.context.password.verify({hash:r,password:i.body.password}))throw i.context.logger.error("Invalid password"),new Se("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});let s=await i.context.internalAdapter.createSession(t.id,i.request,i.body.rememberMe===!1);return s?(await f(i,{session:s,user:t},i.body.rememberMe===!1),i.json({id:t.id,email:t.email,name:t.name,image:t.image,emailVerified:t.emailVerified,createdAt:t.createdAt,updatedAt:t.updatedAt})):i.json(null,{status:500,body:{message:g.FAILED_TO_CREATE_SESSION,status:500}})})},schema:{user:{fields:{username:{type:"string",required:!1,unique:!0,returned:!0,transform:{input(i){return i?.toString().toLowerCase()}}}}}},hooks:{before:[{matcher(i){return i.path==="/sign-up/email"},async handler(i){let t=i.body.username;if(t&&await i.context.adapter.findOne({model:"user",where:[{field:"username",value:t.toLowerCase()}]}))throw new Se("UNPROCESSABLE_ENTITY",{message:e.USERNAME_IS_ALREADY_TAKEN})}}]},$ERROR_CODES:W}};import"better-call";var Fl=()=>({id:"bearer",hooks:{before:[{matcher(e){return!!(e.request?.headers.get("authorization")||e.headers?.get("authorization"))},handler:async e=>{let i=e.request?.headers.get("authorization")?.replace("Bearer ","")||e.headers?.get("authorization")?.replace("Bearer ","");if(!(!i||!i.includes(".")))return e.request&&e.request.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${i.replace("=","")}`),e.headers&&e.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${i.replace("=","")}`),{context:e}}}],after:[{matcher(e){return!!e.responseHeader.get("set-cookie")},handler:k(async e=>{let i=e.responseHeader.get("set-cookie");if(!i)return;let t=Ce(i),o=e.context.authCookies.sessionToken.name,r=t.get(o);if(!r||!r.value||r["max-age"]===0)return;let n=r.value;return e.responseHeader.set("set-auth-token",n),{responseHeader:e.responseHeader}})}]}});import{z as Ue}from"zod";import{APIError as un}from"better-call";var Zl=e=>({id:"magic-link",endpoints:{signInMagicLink:p("/sign-in/magic-link",{method:"POST",requireHeaders:!0,body:Ue.object({email:Ue.string({description:"Email address to send the magic link"}).email(),callbackURL:Ue.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 i=>{let{email:t}=i.body;if(e.disableSignUp&&!await i.context.internalAdapter.findUserByEmail(t))throw new un("BAD_REQUEST",{message:g.USER_NOT_FOUND});let o=F(32,V("a-z","A-Z"));await i.context.internalAdapter.createVerificationValue({identifier:o,value:t,expiresAt:new Date(Date.now()+(e.expiresIn||60*5)*1e3)});let r=`${i.context.baseURL}/magic-link/verify?token=${o}&callbackURL=${i.body.callbackURL||"/"}`;return await e.sendMagicLink({email:t,url:r,token:o},i.request),i.json({status:!0})}),magicLinkVerify:p("/magic-link/verify",{method:"GET",query:Ue.object({token:Ue.string({description:"Verification token"}),callbackURL:Ue.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 i=>{let{token:t,callbackURL:o}=i.query,r=o?.startsWith("http")?o:o?`${i.context.options.baseURL}${o}`:i.context.options.baseURL,n=await i.context.internalAdapter.findVerificationValue(t);if(!n)throw i.redirect(`${r}?error=INVALID_TOKEN`);if(n.expiresAt<new Date)throw await i.context.internalAdapter.deleteVerificationValue(n.id),i.redirect(`${r}?error=EXPIRED_TOKEN`);await i.context.internalAdapter.deleteVerificationValue(n.id);let s=n.value,A=await i.context.internalAdapter.findUserByEmail(s),a=A?.user.id||"";if(!A){if(e.disableSignUp)throw i.redirect(`${r}?error=failed_to_create_user`);if(a=(await i.context.internalAdapter.createUser({email:s,emailVerified:!0,name:s})).id,!a)throw i.redirect(`${r}?error=failed_to_create_user`)}let d=await i.context.internalAdapter.createSession(a,i.headers);if(!d)throw i.redirect(`${r}?error=failed_to_create_session`);if(await f(i,{session:d,user:A?.user}),!o)return i.json({session:d,user:A?.user});throw i.redirect(o)})},rateLimit:[{pathMatcher(i){return i.startsWith("/sign-in/magic-link")||i.startsWith("/magic-link/verify")},window:e.rateLimit?.window||60,max:e.rateLimit?.max||5}]});import{z as Ae}from"zod";import{APIError as J}from"better-call";function ln(e){return F(e,V("0-9"))}var sm=e=>{let i={expiresIn:e?.expiresIn||300,otpLength:e?.otpLength||6,...e,phoneNumber:"phoneNumber",phoneNumberVerified:"phoneNumberVerified",code:"code",createdAt:"createdAt"},t={INVALID_PHONE_NUMBER:"Invalid phone number",INVALID_PHONE_NUMBER_OR_PASSWORD:"Invalid phone number or password",UNEXPECTED_ERROR:"Unexpected error",OTP_NOT_FOUND:"OTP not found"};return{id:"phone-number",endpoints:{signInPhoneNumber:p("/sign-in/phone-number",{method:"POST",body:Ae.object({phoneNumber:Ae.string({description:"Phone number to sign in"}),password:Ae.string({description:"Password to use for sign in"}),rememberMe:Ae.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:r,phoneNumber:n}=o.body;if(i.phoneNumberValidator&&!await i.phoneNumberValidator(o.body.phoneNumber))throw new J("BAD_REQUEST",{message:t.INVALID_PHONE_NUMBER});let s=await o.context.adapter.findOne({model:"user",where:[{field:"phoneNumber",value:n}]});if(!s)throw new J("UNAUTHORIZED",{message:t.INVALID_PHONE_NUMBER_OR_PASSWORD});let a=(await o.context.internalAdapter.findAccountByUserId(s.id)).find(l=>l.providerId==="credential");if(!a)throw o.context.logger.error("Credential account not found",{phoneNumber:n}),new J("UNAUTHORIZED",{message:t.INVALID_PHONE_NUMBER_OR_PASSWORD});let d=a?.password;if(!d)throw o.context.logger.error("Password not found",{phoneNumber:n}),new J("UNAUTHORIZED",{message:t.UNEXPECTED_ERROR});if(!await o.context.password.verify({hash:d,password:r}))throw o.context.logger.error("Invalid password"),new J("UNAUTHORIZED",{message:t.INVALID_PHONE_NUMBER_OR_PASSWORD});let u=await o.context.internalAdapter.createSession(s.id,o.headers,o.body.rememberMe===!1);if(!u)throw o.context.logger.error("Failed to create session"),new J("UNAUTHORIZED",{message:g.FAILED_TO_CREATE_SESSION});return await f(o,{session:u,user:s},o.body.rememberMe===!1),o.json({user:s,session:u})}),sendPhoneNumberOTP:p("/phone-number/send-otp",{method:"POST",body:Ae.object({phoneNumber:Ae.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 J("NOT_IMPLEMENTED",{message:"sendOTP not implemented"});if(i.phoneNumberValidator&&!await i.phoneNumberValidator(o.body.phoneNumber))throw new J("BAD_REQUEST",{message:t.INVALID_PHONE_NUMBER});let r=ln(i.otpLength);return await o.context.internalAdapter.createVerificationValue({value:r,identifier:o.body.phoneNumber,expiresAt:P(i.expiresIn,"sec")}),await e.sendOTP({phoneNumber:o.body.phoneNumber,code:r},o.request),o.json({code:r},{body:{message:"Code sent"}})}),verifyPhoneNumber:p("/phone-number/verify",{method:"POST",body:Ae.object({phoneNumber:Ae.string({description:"Phone number to verify"}),code:Ae.string({description:"OTP code"}),disableSession:Ae.boolean({description:"Disable session creation after verification"}).optional(),updatePhoneNumber:Ae.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 r=await o.context.internalAdapter.findVerificationValue(o.body.phoneNumber);if(!r||r.expiresAt<new Date)throw r&&r.expiresAt<new Date?(await o.context.internalAdapter.deleteVerificationValue(r.id),new J("BAD_REQUEST",{message:"OTP expired"})):new J("BAD_REQUEST",{message:t.OTP_NOT_FOUND});if(r.value!==o.body.code)throw new J("BAD_REQUEST",{message:"Invalid OTP"});if(await o.context.internalAdapter.deleteVerificationValue(r.id),o.body.updatePhoneNumber){let s=await S(o);if(!s)throw new J("UNAUTHORIZED",{message:g.USER_NOT_FOUND});let A=await o.context.internalAdapter.updateUser(s.user.id,{[i.phoneNumber]:o.body.phoneNumber,[i.phoneNumberVerified]:!0});return o.json({user:A,session:s.session})}let n=await o.context.adapter.findOne({model:"user",where:[{value:o.body.phoneNumber,field:i.phoneNumber}]});if(await e?.callbackOnVerification?.({phoneNumber:o.body.phoneNumber,user:n},o.request),n)n=await o.context.internalAdapter.updateUser(n.id,{[i.phoneNumberVerified]:!0});else if(e?.signUpOnVerification){if(n=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,[i.phoneNumber]:o.body.phoneNumber,[i.phoneNumberVerified]:!0}),!n)throw new J("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_CREATE_USER})}else return o.json(null);if(!n)throw new J("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_UPDATE_USER});if(!o.body.disableSession){let s=await o.context.internalAdapter.createSession(n.id,o.request);if(!s)throw new J("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_CREATE_SESSION});return await f(o,{session:s,user:n}),o.json({user:n,session:s})}return o.json({user:n,session:null})})},schema:ie(mn,e?.schema),$ERROR_CODES:t}},mn={user:{fields:{phoneNumber:{type:"string",required:!1,unique:!0,returned:!0},phoneNumberVerified:{type:"boolean",required:!1,returned:!0,input:!1}}}};var gn={user:{fields:{isAnonymous:{type:"boolean",required:!1}}}},Km=e=>{let i={FAILED_TO_CREATE_USER:"Failed to create user",COULD_NOT_CREATE_SESSION:"Could not create session",ANONYMOUS_USERS_CANNOT_SIGN_IN_AGAIN_ANONYMOUSLY:"Anonymous users cannot sign in again anonymously"};return{id:"anonymous",endpoints:{signInAnonymous:p("/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=be(t.context.baseURL)}=e||{},r=t.context.generateId({model:"user"}),n=`temp-${r}@${o}`,s=await t.context.internalAdapter.createUser({id:r,email:n,emailVerified:!1,isAnonymous:!0,name:"Anonymous",createdAt:new Date,updatedAt:new Date});if(!s)return t.json(null,{status:500,body:{message:i.FAILED_TO_CREATE_USER,status:500}});let A=await t.context.internalAdapter.createSession(s.id,t.request);return A?(await f(t,{session:A,user:s}),t.json({id:s.id,email:s.email,emailVerified:s.emailVerified,name:s.name,createdAt:s.createdAt,updatedAt:s.updatedAt})):t.json(null,{status:400,body:{message:i.COULD_NOT_CREATE_SESSION}})})},hooks:{after:[{matcher(t){return!!t.responseHeader.get("set-cookie")?.includes(t.context.authCookies.sessionToken.name)},handler:k(async t=>{let r=t.responseHeader.get("set-cookie"),n=t.context.authCookies.sessionToken.name;if(!Ce(r||"").get(n)?.value.split(".")[0])return;let A=await S(t,{disableRefresh:!0});if(!A||!A.user.isAnonymous)return;if(t.path==="/sign-in/anonymous")throw new b("BAD_REQUEST",{message:i.ANONYMOUS_USERS_CANNOT_SIGN_IN_AGAIN_ANONYMOUSLY});let a=t.context.newSession;a&&(e?.onLinkAccount&&await e?.onLinkAccount?.({anonymousUser:A,newUser:a}),e?.disableDeleteAnonymousUser||await t.context.internalAdapter.deleteUser(A.user.id))})}]},schema:ie(gn,e?.schema),$ERROR_CODES:i}};import{z as O}from"zod";import{APIError as fn}from"better-call";var pt=async e=>{let i=e.context.returned;return i?i instanceof Response?i.status!==200?null:await i.clone().json():i instanceof fn?null:i:null};var Tm=e=>{let i={defaultRole:"user",adminRole:"admin",...e},t={FAILED_TO_CREATE_USER:"Failed to create user",USER_ALREADY_EXISTS:"User already exists",USER_NOT_FOUND:"User not found",YOU_CANNOT_BAN_YOURSELF:"You cannot ban yourself",ONLY_ADMINS_CAN_ACCESS_THIS_ENDPOINT:"Only admins can access this endpoint"},o=k(async r=>{let n=await S(r);if(!n?.session)throw new b("UNAUTHORIZED");let s=n.user;if(!s.role||(Array.isArray(i.adminRole)?!i.adminRole.includes(s.role):s.role!==i.adminRole))throw new b("FORBIDDEN",{message:"Only admins can access this endpoint"});return{session:{user:s,session:n.session}}});return{id:"admin",init(r){return{options:{databaseHooks:{user:{create:{async before(n){if(e?.defaultRole!==!1)return{data:{role:e?.defaultRole??"user",...n}}}}},session:{create:{async before(n){let s=await r.internalAdapter.findUserById(n.userId);if(s.banned){if(s.banExpires&&s.banExpires.getTime()<Date.now()){await r.internalAdapter.updateUser(n.userId,{banned:!1,banReason:null,banExpires:null});return}return!1}}}}}}}},hooks:{after:[{matcher(r){return r.path==="/list-sessions"},handler:k(async r=>{let n=await pt(r);if(!n)return;let s=n.filter(A=>!A.impersonatedBy);return r.json(s)})}]},endpoints:{setRole:p("/admin/set-role",{method:"POST",body:O.object({userId:O.string({description:"The user id"}),role:O.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 r=>{let n=await r.context.internalAdapter.updateUser(r.body.userId,{role:r.body.role});return r.json({user:n})}),createUser:p("/admin/create-user",{method:"POST",body:O.object({email:O.string({description:"The email of the user"}),password:O.string({description:"The password of the user"}),name:O.string({description:"The name of the user"}),role:O.string({description:"The role of the user"}),data:O.optional(O.record(O.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 r=>{if(await r.context.internalAdapter.findUserByEmail(r.body.email))throw new b("BAD_REQUEST",{message:t.USER_ALREADY_EXISTS});let s=await r.context.internalAdapter.createUser({email:r.body.email,name:r.body.name,role:r.body.role,...r.body.data});if(!s)throw new b("INTERNAL_SERVER_ERROR",{message:t.FAILED_TO_CREATE_USER});let A=await r.context.password.hash(r.body.password);return await r.context.internalAdapter.linkAccount({accountId:s.id,providerId:"credential",password:A,userId:s.id}),r.json({user:s})}),listUsers:p("/admin/list-users",{method:"GET",use:[o],query:O.object({searchValue:O.string({description:"The value to search for"}).optional(),searchField:O.enum(["email","name"],{description:"The field to search in, defaults to email. Can be `email` or `name`"}).optional(),searchOperator:O.enum(["contains","starts_with","ends_with"],{description:"The operator to use for the search. Can be `contains`, `starts_with` or `ends_with`"}).optional(),limit:O.string({description:"The number of users to return"}).or(O.number()).optional(),offset:O.string({description:"The offset to start from"}).or(O.number()).optional(),sortBy:O.string({description:"The field to sort by"}).optional(),sortDirection:O.enum(["asc","desc"],{description:"The direction to sort by"}).optional(),filterField:O.string({description:"The field to filter by"}).optional(),filterValue:O.string({description:"The value to filter by"}).or(O.number()).or(O.boolean()).optional(),filterOperator:O.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 r=>{let n=[];r.query?.searchValue&&n.push({field:r.query.searchField||"email",operator:r.query.searchOperator||"contains",value:r.query.searchValue}),r.query?.filterValue&&n.push({field:r.query.filterField||"email",operator:r.query.filterOperator||"eq",value:r.query.filterValue});try{let s=await r.context.internalAdapter.listUsers(Number(r.query?.limit)||void 0,Number(r.query?.offset)||void 0,r.query?.sortBy?{field:r.query.sortBy,direction:r.query.sortDirection||"asc"}:void 0,n.length?n:void 0);return r.json({users:s})}catch(s){return console.log(s),r.json({users:[]})}}),listUserSessions:p("/admin/list-user-sessions",{method:"POST",use:[o],body:O.object({userId:O.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 r=>({sessions:await r.context.internalAdapter.listSessions(r.body.userId)})),unbanUser:p("/admin/unban-user",{method:"POST",body:O.object({userId:O.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 r=>{let n=await r.context.internalAdapter.updateUser(r.body.userId,{banned:!1});return r.json({user:n})}),banUser:p("/admin/ban-user",{method:"POST",body:O.object({userId:O.string({description:"The user id"}),banReason:O.string({description:"The reason for the ban"}).optional(),banExpiresIn:O.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 r=>{if(r.body.userId===r.context.session.user.id)throw new b("BAD_REQUEST",{message:t.YOU_CANNOT_BAN_YOURSELF});let n=await r.context.internalAdapter.updateUser(r.body.userId,{banned:!0,banReason:r.body.banReason||e?.defaultBanReason||"No reason",banExpires:r.body.banExpiresIn?P(r.body.banExpiresIn,"sec"):e?.defaultBanExpiresIn?P(e.defaultBanExpiresIn,"sec"):void 0});return await r.context.internalAdapter.deleteSessions(r.body.userId),r.json({user:n})}),impersonateUser:p("/admin/impersonate-user",{method:"POST",body:O.object({userId:O.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 r=>{let n=await r.context.internalAdapter.findUserById(r.body.userId);if(!n)throw new b("NOT_FOUND",{message:"User not found"});let s=await r.context.internalAdapter.createSession(n.id,void 0,!0,{impersonatedBy:r.context.session.user.id,expiresAt:e?.impersonationSessionDuration?P(e.impersonationSessionDuration,"sec"):P(60*60,"sec")});if(!s)throw new b("INTERNAL_SERVER_ERROR",{message:t.FAILED_TO_CREATE_USER});let A=r.context.authCookies;return M(r),await r.setSignedCookie("admin_session",r.context.session.session.token,r.context.secret,A.sessionToken.options),await f(r,{session:s,user:n},!0),r.json({session:s,user:n})}),stopImpersonating:p("/admin/stop-impersonating",{method:"POST"},async r=>{let n=await S(r);if(!n)throw new b("UNAUTHORIZED");if(!n.session.impersonatedBy)throw new b("BAD_REQUEST",{message:"You are not impersonating anyone"});let s=await r.context.internalAdapter.findUserById(n.session.impersonatedBy);if(!s)throw new b("INTERNAL_SERVER_ERROR",{message:"Failed to find user"});let A=await r.getSignedCookie("admin_session",r.context.secret);if(!A)throw new b("INTERNAL_SERVER_ERROR",{message:"Failed to find admin session"});let a=await r.context.internalAdapter.findSession(A);if(!a||a.session.userId!==s.id)throw new b("INTERNAL_SERVER_ERROR",{message:"Failed to find admin session"});return await f(r,a),r.json(a)}),revokeUserSession:p("/admin/revoke-user-session",{method:"POST",body:O.object({sessionToken:O.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 r=>(await r.context.internalAdapter.deleteSession(r.body.sessionToken),r.json({success:!0}))),revokeUserSessions:p("/admin/revoke-user-sessions",{method:"POST",body:O.object({userId:O.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 r=>(await r.context.internalAdapter.deleteSessions(r.body.userId),r.json({success:!0}))),removeUser:p("/admin/remove-user",{method:"POST",body:O.object({userId:O.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 r=>(await r.context.internalAdapter.deleteUser(r.body.userId),r.json({success:!0})))},$ERROR_CODES:t,schema:ie(hn,i.schema)}},hn={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}}}};import{betterFetch as co}from"@better-fetch/fetch";import{APIError as _e}from"better-call";import{parseJWT as yn}from"oslo/jwt";import{z as ce}from"zod";async function Kt(e,i){if(e.idToken){let o=yn(e.idToken);if(o?.payload&&o.payload.sub&&o.payload.email)return{id:o.payload.sub,emailVerified:o.payload.email_verified,image:o.payload.picture,...o.payload}}if(!i)return null;let t=await co(i,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});return{id:t.data?.sub,emailVerified:t.data?.email_verified,email:t.data?.email,image:t.data?.picture,name:t.data?.name,...t.data}}var Dm=e=>{let i={INVALID_OAUTH_CONFIGURATION:"Invalid OAuth configuration"};return{id:"generic-oauth",init:t=>({context:{socialProviders:e.config.map(o=>{let r=o.tokenUrl,n=o.userInfoUrl;return{id:o.providerId,name:o.providerId,createAuthorizationURL(s){return v({id:o.providerId,options:{clientId:o.clientId,clientSecret:o.clientSecret,redirectURI:o.redirectURI},authorizationEndpoint:o.authorizationUrl,state:s.state,codeVerifier:o.pkce?s.codeVerifier:void 0,scopes:o.scopes||[],redirectURI:`${t.baseURL}/oauth2/callback/${o.providerId}`})},async validateAuthorizationCode(s){let A=o.tokenUrl;if(o.discoveryUrl){let a=await co(o.discoveryUrl,{method:"GET"});a.data&&(A=a.data.token_endpoint,n=a.data.userinfo_endpoint)}if(!A)throw new _e("BAD_REQUEST",{message:"Invalid OAuth configuration. Token URL not found."});return U({code:s.code,codeVerifier:s.codeVerifier,redirectURI:s.redirectURI,options:{clientId:o.clientId,clientSecret:o.clientSecret},tokenEndpoint:A})},async getUserInfo(s){if(!n)return null;let A=o.getUserInfo?await o.getUserInfo(s):await Kt(s,n);return A?{user:{id:A?.id,email:A?.email,emailVerified:A?.emailVerified,image:A?.image,name:A?.name,...o.mapProfileToUser?.(A)},data:A}:null}}})}}),endpoints:{signInWithOAuth2:p("/sign-in/oauth2",{method:"POST",query:ce.object({currentURL:ce.string({description:"Redirect to the current URL after sign in"}).optional()}).optional(),body:ce.object({providerId:ce.string({description:"The provider ID for the OAuth provider"}),callbackURL:ce.string({description:"The URL to redirect to after sign in"}).optional(),errorCallbackURL:ce.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,r=e.config.find(x=>x.providerId===o);if(!r)throw new _e("BAD_REQUEST",{message:`No config found for provider ${o}`});let{discoveryUrl:n,authorizationUrl:s,tokenUrl:A,clientId:a,clientSecret:d,scopes:c,redirectURI:u,responseType:l,pkce:K,prompt:m,accessType:C}=r,N=s,w=A;if(n){let x=await co(n,{onError(Qe){t.context.logger.error(Qe.error.message,Qe.error,{discoveryUrl:n})}});x.data&&(N=x.data.authorization_endpoint,w=x.data.token_endpoint)}if(!N||!w)throw new _e("BAD_REQUEST",{message:i.INVALID_OAUTH_CONFIGURATION});let{state:R,codeVerifier:h}=await Oe(t),T=await v({id:o,options:{clientId:a,clientSecret:d,redirectURI:u},authorizationEndpoint:N,state:R,codeVerifier:K?h:void 0,scopes:c||[],redirectURI:`${t.context.baseURL}/oauth2/callback/${o}`});return l&&l!=="code"&&T.searchParams.set("response_type",l),m&&T.searchParams.set("prompt",m),C&&T.searchParams.set("access_type",C),t.json({url:T.toString(),redirect:!0})}),oAuth2Callback:p("/oauth2/callback/:providerId",{method:"GET",query:ce.object({code:ce.string({description:"The OAuth2 code"}).optional(),error:ce.string({description:"The error message, if any"}).optional(),state:ce.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(h=>h.providerId===t.params.providerId);if(!o)throw new _e("BAD_REQUEST",{message:`No config found for provider ${t.params.providerId}`});let r,n=await Xe(t),{callbackURL:s,codeVerifier:A,errorURL:a}=n,d=t.query.code,c=o.tokenUrl,u=o.userInfoUrl;if(o.discoveryUrl){let h=await co(o.discoveryUrl,{method:"GET"});h.data&&(c=h.data.token_endpoint,u=h.data.userinfo_endpoint)}try{if(!c)throw new _e("BAD_REQUEST",{message:"Invalid OAuth configuration."});r=await U({code:d,codeVerifier:A,redirectURI:`${t.context.baseURL}/oauth2/callback/${o.providerId}`,options:{clientId:o.clientId,clientSecret:o.clientSecret},tokenEndpoint:c})}catch(h){throw t.context.logger.error(h&&typeof h=="object"&&"name"in h?h.name:"",h),t.redirect(`${a}?error=oauth_code_verification_failed`)}if(!r)throw new _e("BAD_REQUEST",{message:"Invalid OAuth configuration."});let l=o.getUserInfo?await o.getUserInfo(r):await Kt(r,u);if(!l?.email)throw t.context.logger.error("Unable to get user info",l),t.redirect(`${t.context.baseURL}/error?error=email_is_missing`);let K=o.mapProfileToUser?await o.mapProfileToUser(l):null,m=await Re(t,{userInfo:{...l,...K},account:{providerId:o.providerId,accountId:l.id,...r,scope:r.scopes?.join(",")}});function C(h){throw t.redirect(`${a||s||`${t.context.baseURL}/error`}?error=${h}`)}if(m.error)return C(m.error.split(" ").join("_"));let{session:N,user:w}=m.data;await f(t,{session:N,user:w});let R;try{R=new URL(s).toString()}catch{R=s}throw t.redirect(R)})},$ERROR_CODES:i}};import{z as He}from"zod";var ut={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0}}}},xm=He.object({id:He.string(),publicKey:He.string(),privateKey:He.string(),createdAt:He.date()});var Io=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 i=>await e.create({model:"jwks",data:{...i,createdAt:new Date}})});import{exportJWK as lt,generateKeyPair as wn,importJWK as Cn,SignJWT as bn}from"jose";var Gm=e=>({id:"jwt",endpoints:{getJwks:p("/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 i=>{let o=await Io(i.context.adapter).getAllKeys();return i.json({keys:o.map(r=>({...JSON.parse(r.publicKey),kid:r.id}))})}),getToken:p("/token",{method:"GET",requireHeaders:!0,use:[I],metadata:{openapi:{description:"Get a JWT token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async i=>{let t=Io(i.context.adapter),o=await t.getLatestKey(),r=!e?.jwks?.disablePrivateKeyEncryption;if(o===void 0){let{publicKey:d,privateKey:c}=await wn(e?.jwks?.keyPairConfig?.alg??"EdDSA",e?.jwks?.keyPairConfig??{crv:"Ed25519"}),u=await lt(d),l=await lt(c),K=JSON.stringify(l),m={id:crypto.randomUUID(),publicKey:JSON.stringify(u),privateKey:r?JSON.stringify(await le({key:i.context.options.secret,data:K})):K,createdAt:new Date};o=await t.createJwk(m)}let n=r?await fe({key:i.context.options.secret,data:JSON.parse(o.privateKey)}):o.privateKey,s=await Cn(JSON.parse(n)),A=e?.jwt?.definePayload?await e?.jwt.definePayload(i.context.session.user):i.context.session.user,a=await new bn({...A,...i.context.session.session.impersonatedBy?{impersonatedBy:i.context.session.session.impersonatedBy}:{}}).setProtectedHeader({alg:e?.jwks?.keyPairConfig?.alg??"EdDSA",kid:o.id}).setIssuedAt().setIssuer(e?.jwt?.issuer??i.context.options.baseURL).setAudience(e?.jwt?.audience??i.context.options.baseURL).setExpirationTime(e?.jwt?.expirationTime??"15m").setSubject(i.context.session.user.id).sign(s);return i.json({token:a})})},schema:ie(ut,e?.schema)});import{z as po}from"zod";var Ym=e=>{let i={maximumSessions:5,...e},t=r=>r.includes("_multi-"),o={INVALID_SESSION_TOKEN:"Invalid session token"};return{id:"multi-session",endpoints:{listDeviceSessions:p("/multi-session/list-device-sessions",{method:"GET",requireHeaders:!0},async r=>{let n=r.headers?.get("cookie");if(!n)return r.json([]);let s=Object.fromEntries(Pe(n)),A=(await Promise.all(Object.entries(s).filter(([c])=>t(c)).map(async([c])=>await r.getSignedCookie(c,r.context.secret)))).filter(c=>c!==void 0);if(!A.length)return r.json([]);let d=(await r.context.internalAdapter.findSessions(A)).filter(c=>c&&c.session.expiresAt>new Date);return r.json(d)}),setActiveSession:p("/multi-session/set-active",{method:"POST",body:po.object({sessionToken:po.string({description:"The session token to set as active"})}),requireHeaders:!0,use:[I],metadata:{openapi:{description:"Set the active session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async r=>{let n=r.body.sessionToken,s=`${r.context.authCookies.sessionToken.name}_multi-${n}`;if(!await r.getSignedCookie(s,r.context.secret))throw new b("UNAUTHORIZED",{message:o.INVALID_SESSION_TOKEN});let a=await r.context.internalAdapter.findSession(n);if(!a||a.session.expiresAt<new Date)throw r.setCookie(s,"",{...r.context.authCookies.sessionToken.options,maxAge:0}),new b("UNAUTHORIZED",{message:o.INVALID_SESSION_TOKEN});return await f(r,a),r.json(a)}),revokeDeviceSession:p("/multi-session/revoke",{method:"POST",body:po.object({sessionToken:po.string({description:"The session token to revoke"})}),requireHeaders:!0,use:[I],metadata:{openapi:{description:"Revoke a device session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async r=>{let n=r.body.sessionToken,s=`${r.context.authCookies.sessionToken.name}_multi-${n}`;if(!await r.getSignedCookie(s,r.context.secret))throw new b("UNAUTHORIZED",{message:o.INVALID_SESSION_TOKEN});if(await r.context.internalAdapter.deleteSession(n),r.setCookie(s,"",{...r.context.authCookies.sessionToken.options,maxAge:0}),!(r.context.session?.session.token===n))return r.json({success:!0});let d=r.headers?.get("cookie");if(d){let c=Object.fromEntries(Pe(d)),u=(await Promise.all(Object.entries(c).filter(([K])=>t(K)).map(async([K])=>await r.getSignedCookie(K,r.context.secret)))).filter(K=>K!==void 0),l=r.context.internalAdapter;if(u.length>0){let m=(await l.findSessions(u)).filter(C=>C&&C.session.expiresAt>new Date);if(m.length>0){let C=m[0];await f(r,C)}else M(r)}else M(r)}else M(r);return r.json({success:!0})})},hooks:{after:[{matcher:()=>!0,handler:k(async r=>{let n=r.responseHeader.get("set-cookie");if(!n)return;let s=Ce(n),A=r.context.authCookies.sessionToken,a=s.get(A.name)?.value;if(!a)return;let d=Pe(r.headers?.get("cookie")||""),c=a.split(".")[0];if(!c)return;let u=`${A.name}_multi-${c}`;s.get(u)||d.get(u)||Object.keys(Object.fromEntries(d)).filter(t).length+(n.includes("session_token")?1:0)>i.maximumSessions||await r.setSignedCookie(u,c,r.context.secret,A.options)})},{matcher:r=>r.path==="/sign-out",handler:k(async r=>{let n=r.headers?.get("cookie");if(!n)return;let s=Object.fromEntries(Pe(n)),A=Object.keys(s).map(a=>t(a)?(r.setCookie(a,"",{maxAge:0}),a.split("_multi-")[1]):null).filter(a=>a!==null);await r.context.internalAdapter.deleteSessions(A)})}]},$ERROR_CODES:o}};import{z as B}from"zod";var So=["email-verification","sign-in","forget-password"],ng=e=>{let i={expireIn:300,otpLength:6,...e},t={OTP_EXPIRED:"otp expired",INVALID_OTP:"invalid otp",INVALID_EMAIL:"invalid email",USER_NOT_FOUND:"user not found"};return{id:"email-otp",endpoints:{sendVerificationOTP:p("/email-otp/send-verification-otp",{method:"POST",body:B.object({email:B.string({description:"Email address to send the OTP"}),type:B.enum(So,{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 b("BAD_REQUEST",{message:"send email verification is not implemented"});let r=o.body.email;if(!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r))throw new b("BAD_REQUEST",{message:t.INVALID_EMAIL});let s=F(i.otpLength,V("0-9"));return await o.context.internalAdapter.createVerificationValue({value:s,identifier:`${o.body.type}-otp-${r}`,expiresAt:P(i.expireIn,"sec")}).catch(async A=>{await o.context.internalAdapter.deleteVerificationByIdentifier(`${o.body.type}-otp-${r}`),await o.context.internalAdapter.createVerificationValue({value:s,identifier:`${o.body.type}-otp-${r}`,expiresAt:P(i.expireIn,"sec")})}),await e.sendVerificationOTP({email:r,otp:s,type:o.body.type},o.request),o.json({success:!0})}),createVerificationOTP:p("/email-otp/create-verification-otp",{method:"POST",body:B.object({email:B.string({description:"Email address to send the OTP"}),type:B.enum(So,{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 r=o.body.email,n=F(i.otpLength,V("0-9"));return await o.context.internalAdapter.createVerificationValue({value:n,identifier:`${o.body.type}-otp-${r}`,expiresAt:P(i.expireIn,"sec")}),n}),getVerificationOTP:p("/email-otp/get-verification-otp",{method:"GET",query:B.object({email:B.string({description:"Email address to get the OTP"}),type:B.enum(So)}),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 r=o.query.email,n=await o.context.internalAdapter.findVerificationValue(`${o.query.type}-otp-${r}`);return!n||n.expiresAt<new Date?o.json({otp:null}):o.json({otp:n.value})}),verifyEmailOTP:p("/email-otp/verify-email",{method:"POST",body:B.object({email:B.string({description:"Email address to verify"}),otp:B.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 r=o.body.email;if(!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r))throw new b("BAD_REQUEST",{message:t.INVALID_EMAIL});let s=await o.context.internalAdapter.findVerificationValue(`email-verification-otp-${r}`);if(!s)throw new b("BAD_REQUEST",{message:t.INVALID_OTP});if(s.expiresAt<new Date)throw await o.context.internalAdapter.deleteVerificationValue(s.id),new b("BAD_REQUEST",{message:t.OTP_EXPIRED});let A=o.body.otp;if(s.value!==A)throw new b("BAD_REQUEST",{message:t.INVALID_OTP});await o.context.internalAdapter.deleteVerificationValue(s.id);let a=await o.context.internalAdapter.findUserByEmail(r);if(!a)throw new b("BAD_REQUEST",{message:t.USER_NOT_FOUND});let d=await o.context.internalAdapter.updateUser(a.user.id,{email:r,emailVerified:!0});return o.json({id:d.id,email:d.email,emailVerified:d.emailVerified,name:d.name,image:d.image,createdAt:d.createdAt,updatedAt:d.updatedAt})}),signInEmailOTP:p("/sign-in/email-otp",{method:"POST",body:B.object({email:B.string({description:"Email address to sign in"}),otp:B.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 r=o.body.email,n=await o.context.internalAdapter.findVerificationValue(`sign-in-otp-${r}`);if(!n)throw new b("BAD_REQUEST",{message:t.INVALID_OTP});if(n.expiresAt<new Date)throw await o.context.internalAdapter.deleteVerificationValue(n.id),new b("BAD_REQUEST",{message:t.OTP_EXPIRED});let s=o.body.otp;if(n.value!==s)throw new b("BAD_REQUEST",{message:t.INVALID_OTP});await o.context.internalAdapter.deleteVerificationValue(n.id);let A=await o.context.internalAdapter.findUserByEmail(r);if(!A){if(i.disableSignUp)throw new b("BAD_REQUEST",{message:t.USER_NOT_FOUND});let d=await o.context.internalAdapter.createUser({email:r,emailVerified:!0,name:r}),c=await o.context.internalAdapter.createSession(d.id,o.request);return await f(o,{session:c,user:d}),o.json({user:d,session:c})}A.user.emailVerified||await o.context.internalAdapter.updateUser(A.user.id,{emailVerified:!0});let a=await o.context.internalAdapter.createSession(A.user.id,o.request);return await f(o,{session:a,user:A.user}),o.json({session:a,user:A})}),forgetPasswordEmailOTP:p("/forget-password/email-otp",{method:"POST",body:B.object({email:B.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 r=o.body.email;if(!await o.context.internalAdapter.findUserByEmail(r))throw new b("BAD_REQUEST",{message:t.USER_NOT_FOUND});let s=F(i.otpLength,V("0-9"));return await o.context.internalAdapter.createVerificationValue({value:s,identifier:`forget-password-otp-${r}`,expiresAt:P(i.expireIn,"sec")}),await e.sendVerificationOTP({email:r,otp:s,type:"forget-password"},o.request),o.json({success:!0})}),resetPasswordEmailOTP:p("/email-otp/reset-password",{method:"POST",body:B.object({email:B.string({description:"Email address to reset the password"}),otp:B.string({description:"OTP sent to the email"}),password:B.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 r=o.body.email,n=await o.context.internalAdapter.findUserByEmail(r);if(!n)throw new b("BAD_REQUEST",{message:t.USER_NOT_FOUND});let s=await o.context.internalAdapter.findVerificationValue(`forget-password-otp-${r}`);if(!s)throw new b("BAD_REQUEST",{message:t.INVALID_OTP});if(s.expiresAt<new Date)throw await o.context.internalAdapter.deleteVerificationValue(s.id),new b("BAD_REQUEST",{message:t.OTP_EXPIRED});let A=o.body.otp;if(s.value!==A)throw new b("BAD_REQUEST",{message:t.INVALID_OTP});await o.context.internalAdapter.deleteVerificationValue(s.id);let a=await o.context.password.hash(o.body.password);return await o.context.internalAdapter.updatePassword(n.user.id,a),o.json({success:!0})})},hooks:{after:[{matcher(o){return!!(o.path?.startsWith("/sign-up")&&i.sendVerificationOnSignUp)},async handler(o){let r=o.context.newSession;if(r?.user&&r.user.email&&r.user.emailVerified===!1){let n=F(i.otpLength,V("0-9"));await o.context.internalAdapter.createVerificationValue({value:n,identifier:`email-verification-otp-${r.user.email}`,expiresAt:P(i.expireIn,"sec")}),await e.sendVerificationOTP({email:r.user.email,otp:n,type:"email-verification"},o.request)}}}]},$ERROR_CODES:t}};import{z as gt}from"zod";import{betterFetch as On}from"@better-fetch/fetch";function mt(e){return e==="true"||e===!0}var ug=e=>({id:"one-tap",endpoints:{oneTapCallback:p("/one-tap/callback",{method:"POST",body:gt.object({idToken:gt.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 i=>{let{idToken:t}=i.body,{data:o,error:r}=await On("https://oauth2.googleapis.com/tokeninfo?id_token="+t);if(r)return i.json({error:"Invalid token"});let n=await i.context.internalAdapter.findUserByEmail(o.email);if(!n){if(e?.disableSignup)throw new b("BAD_GATEWAY",{message:"User not found"});let A=await i.context.internalAdapter.createOAuthUser({email:o.email,emailVerified:mt(o.email_verified),name:o.name,image:o.picture},{providerId:"google",accountId:o.sub});if(!A)throw new b("INTERNAL_SERVER_ERROR",{message:"Could not create user"});let a=await i.context.internalAdapter.createSession(A?.user.id,i.request);return await f(i,{user:A.user,session:a}),i.json({session:a,user:A})}let s=await i.context.internalAdapter.createSession(n.user.id,i.request);return await f(i,{user:n.user,session:s}),i.json({session:s,user:n})})}});import{z as Uo}from"zod";function Tn(){let e=ne.VERCEL_URL,i=ne.NETLIFY_URL,t=ne.RENDER_URL,o=ne.AWS_LAMBDA_FUNCTION_NAME,r=ne.GOOGLE_CLOUD_FUNCTION_NAME,n=ne.AZURE_FUNCTION_NAME;return e||i||t||o||r||n}var wg=e=>({id:"oauth-proxy",endpoints:{oAuthProxy:p("/oauth-proxy-callback",{method:"GET",query:Uo.object({callbackURL:Uo.string({description:"The URL to redirect to after the proxy"}),cookies:Uo.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 i=>{let t=i.query.cookies,o=await fe({key:i.context.secret,data:t});throw i.setHeader("set-cookie",o),i.redirect(i.query.callbackURL)})},hooks:{after:[{matcher(i){return i.path?.startsWith("/callback")},handler:k(async i=>{let t=i.context.returned,o=t instanceof b?t.headers:null,r=o?.get("location");if(r?.includes("/oauth-proxy-callback?callbackURL")){if(!r.startsWith("http"))return;let n=new URL(r);if(n.origin===be(i.context.baseURL)){let c=n.searchParams.get("callbackURL");if(!c)return;i.setHeader("location",c);return}let A=o?.get("set-cookie");if(!A)return;let a=await le({key:i.context.secret,data:A}),d=`${r}&cookies=${encodeURIComponent(a)}`;i.setHeader("location",d)}})}],before:[{matcher(i){return i.path?.startsWith("/sign-in/social")},async handler(i){let t=new URL(e?.currentURL||i.request?.url||Tn()||i.context.baseURL);return i.body.callbackURL=`${t.origin}${i.context.options.basePath||"/api/auth"}/oauth-proxy-callback?callbackURL=${encodeURIComponent(i.body.callbackURL||i.context.baseURL)}`,{context:i}}}]}});import{z as $e}from"zod";var Tg=(e,i)=>({id:"custom-session",endpoints:{getSession:p("/get-session",{method:"GET",metadata:{CUSTOM_SESSION:!0},query:$e.optional($e.object({disableCookieCache:$e.boolean({description:"Disable cookie cache and fetch session from database"}).or($e.string().transform(t=>t==="true")).optional(),disableRefresh:$e.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}))},async t=>{let o=await S(t);if(!o)return t.json(null);let r=await e(o);return t.json(r)})}});import{ZodObject as ht,ZodOptional as _o,ZodSchema as yt}from"zod";var ve=e=>{let i=e.plugins?.reduce((a,d)=>{let c=d.schema;if(!c)return a;for(let[u,l]of Object.entries(c))a[u]={fields:{...a[u]?.fields,...l.fields},modelName:l.modelName||u};return a},{}),t=e.rateLimit?.storage==="database",o={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:s,...A}=i||{};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"},...s?.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},...A,...t?o:{}}};import{z as zg}from"zod";import{Kysely as Mg,MssqlDialect as qg}from"kysely";import{MysqlDialect as $g,PostgresDialect as Gg,SqliteDialect as Qg}from"kysely";var Ge={};function wt(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 Ko(e){let i=[];return e.metadata?.openapi?.parameters?(i.push(...e.metadata.openapi.parameters),i):(e.query instanceof ht&&Object.entries(e.query.shape).forEach(([t,o])=>{o instanceof yt&&i.push({name:t,in:"query",schema:{type:wt(o),..."minLength"in o&&o.minLength?{minLength:o.minLength}:{},description:o.description}})}),i)}function ft(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof ht||e.body instanceof _o)){let i=e.body.shape;if(!i)return;let t={},o=[];return Object.entries(i).forEach(([r,n])=>{n instanceof yt&&(t[r]={type:wt(n),description:n.description},n instanceof _o||o.push(r))}),{required:e.body instanceof _o?!1:!!e.body,content:{"application/json":{schema:{type:"object",properties:t,required:o}}}}}}function uo(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 vo(e,i){let t=bo(e,{...i,plugins:[]}),o=ve(i),n={schemas:{...Object.entries(o).reduce((A,[a,d])=>{let c=a.charAt(0).toUpperCase()+a.slice(1);return A[c]={type:"object",properties:Object.entries(d.fields).reduce((u,[l,K])=>(u[l]={type:K.type},u),{})},A},{})}};Object.entries(t.api).forEach(([A,a])=>{let d=a.options;if(!d.metadata?.SERVER_ONLY&&(d.method==="GET"&&(Ge[a.path]={get:{tags:["Default",...d.metadata?.openapi?.tags||[]],description:d.metadata?.openapi?.description,operationId:d.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Ko(d),responses:uo(d.metadata?.openapi?.responses)}}),d.method==="POST")){let c=ft(d);Ge[a.path]={post:{tags:["Default",...d.metadata?.openapi?.tags||[]],description:d.metadata?.openapi?.description,operationId:d.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Ko(d),...c?{requestBody:c}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:uo(d.metadata?.openapi?.responses)}}}});for(let A of i.plugins||[]){if(A.id==="open-api")continue;let a=bo(e,{...i,plugins:[A]}),d=Object.keys(a.api).map(c=>t.api[c]===void 0?a.api[c]:null).filter(c=>c!==null);Object.entries(d).forEach(([c,u])=>{let l=u.options;l.metadata?.SERVER_ONLY||(l.method==="GET"&&(Ge[u.path]={get:{tags:l.metadata?.openapi?.tags||[A.id.charAt(0).toUpperCase()+A.id.slice(1)],description:l.metadata?.openapi?.description,operationId:l.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Ko(l),responses:uo(l.metadata?.openapi?.responses)}}),l.method==="POST"&&(Ge[u.path]={post:{tags:l.metadata?.openapi?.tags||[A.id.charAt(0).toUpperCase()+A.id.slice(1)],description:l.metadata?.openapi?.description,operationId:l.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Ko(l),requestBody:ft(l),responses:uo(l.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:Ge}}var Ct=`<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>`,di=p("/error",{method:"GET",metadata:{...Te,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string"}}}}}}}},async e=>{let i=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(yr(i),{headers:{"Content-Type":"text/html"}})});import Er from"defu";import{APIError as b}from"better-call";function bo(e,i){let t=i.plugins?.reduce((A,a)=>({...A,...a.endpoints}),{}),o=i.plugins?.map(A=>A.middlewares?.map(a=>{let d=async c=>a.middleware({...c,context:{...e,...c.context}});return d.path=a.path,d.options=a.middleware.options,d.headers=a.middleware.headers,{path:a.path,middleware:d}})).filter(A=>A!==void 0).flat()||[],n={...{signInSocial:ci,callbackOAuth:Ki,getSession:ho(),signOut:ui,signUpEmail:Ai(),signInEmail:pi,forgetPassword:li,resetPassword:gi,verifyEmail:ni,sendVerificationEmail:ri,changeEmail:bi,changePassword:hi,setPassword:yi,updateUser:fi(),deleteUser:wi,forgetPasswordCallback:mi,listSessions:ei(),revokeSession:oi,revokeSessions:ii,revokeOtherSessions:ti,linkSocialAccount:Ti,listUserAccounts:Oi,deleteUserCallback:Ci},...t,ok:ai,error:di},s={};for(let[A,a]of Object.entries(n))s[A]=async(d={})=>{a.headers=new Headers;let c={setHeader(w,R){a.headers.set(w,R)},setCookie(w,R,h){Or(a.headers,w,R,h)},getCookie(w,R){let T=d.headers?.get("cookie");return Cr(T||"",w,R)},getSignedCookie(w,R,h){let T=d.headers;return T?br(T,R,w,h):null},async setSignedCookie(w,R,h,T){await Tr(a.headers,w,R,h,T)},redirect(w){return a.headers.set("Location",w),new Be("FOUND")},responseHeader:a.headers},u=await e,l=null,K={...c,...d,path:a.path,context:{...u,...d.context,session:null,setNewSession:function(w){this.newSession=w,l=w}}},m=i.plugins||[];for(let w of m){let R=w.hooks?.before??[];for(let h of R){if(!h.matcher(K))continue;let T=await h.handler(K);if(T&&"context"in T){K=Er(K,T.context);continue}if(T)return T}}let C;try{C=await a(K),l&&(K.context.newSession=l)}catch(w){if(l&&(K.context.newSession=l),w instanceof Be){let R=i.plugins?.map(h=>{if(h.hooks?.after)return h.hooks.after}).filter(h=>h!==void 0).flat();if(!R?.length)throw w.headers=a.headers,w;K.context.returned=w,K.context.returned.headers=a.headers;for(let h of R||[])if(h.matcher(K))try{let x=await h.handler(K);x&&"response"in x&&(K.context.returned=x.response)}catch(x){if(x instanceof Be){K.context.returned=x;continue}throw x}if(K.context.returned instanceof Be)throw K.context.returned.headers=a.headers,K.context.returned;return K.context.returned}throw w}K.context.returned=C,K.responseHeader=a.headers;for(let w of i.plugins||[])if(w.hooks?.after){for(let R of w.hooks.after)if(R.matcher(K))try{let T=await R.handler(K);if(T)if("responseHeader"in T){let x=T.responseHeader;K.responseHeader=x}else K.context.returned=T}catch(T){if(T instanceof Be){K.context.returned=T;continue}throw T}}let N=K.context.returned;return N instanceof Response&&a.headers.forEach((w,R)=>{R==="set-cookie"?N.headers.append(R,w):N.headers.set(R,w)}),N},s[A].path=a.path,s[A].method=a.method,s[A].options=a.options,s[A].headers=a.headers;return{api:s,middlewares:o}}async function Re(e,{userInfo:i,account:t,callbackURL:o}){let r=await e.context.internalAdapter.findUserByEmail(i.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw oe.error(`Better auth was unable to query your database.
83
+ Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=r?.user,s=!n;if(r){let a=r.accounts.find(d=>d.providerId===t.providerId);if(a){let d=Object.fromEntries(Object.entries({accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt}).filter(([c,u])=>u!==void 0));Object.keys(d).length>0&&await e.context.internalAdapter.updateAccount(a.id,d)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.providerId)&&!i.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Je&&oe.warn(`User already exist but account isn't linked to ${t.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:t.providerId,accountId:i.id.toString(),userId:r.user.id,accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt,scope:t.scope})}catch(u){return oe.error("Unable to link account",u),{error:"unable to link account",data:null}}n=await e.context.internalAdapter.updateUser(r.user.id,{...i,updatedAt:new Date})}}else if(n=await e.context.internalAdapter.createOAuthUser({...i,email:i.email.toLowerCase(),id:void 0},{accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt,scope:t.scope,providerId:t.providerId,accountId:i.id.toString()}).then(a=>a?.user),!i.emailVerified&&n&&e.context.options.emailVerification?.sendOnSignUp){let a=await de(e.context.secret,n.email),d=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:n,url:d,token:a},e.request)}if(!n)return{error:"unable to create user",data:null,isRegister:!1};let A=await e.context.internalAdapter.createSession(n.id,e.request);return A?{data:{session:A,user:n},error:null,isRegister:s}:{error:"unable to create session",data:null,isRegister:!1}}var ci=p("/sign-in/social",{method:"POST",query:L.object({currentURL:L.string().optional()}).optional(),body:L.object({callbackURL:L.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:L.string().optional(),errorCallbackURL:L.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:L.enum(eo,{description:"OAuth2 provider to use"}),disableRedirect:L.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:L.optional(L.object({token:L.string({description:"ID token from the provider"}),nonce:L.string({description:"Nonce used to generate the token"}).optional(),accessToken:L.string({description:"Access token from the provider"}).optional(),refreshToken:L.string({description:"Refresh token from the provider"}).optional(),expiresAt:L.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 i=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Q("NOT_FOUND",{message:g.PROVIDER_NOT_FOUND});if(e.body.idToken){if(!i.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new Q("NOT_FOUND",{message:g.ID_TOKEN_NOT_SUPPORTED});let{token:n,nonce:s}=e.body.idToken;if(!await i.verifyIdToken(n,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new Q("UNAUTHORIZED",{message:g.INVALID_TOKEN});let a=await i.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new Q("UNAUTHORIZED",{message:g.FAILED_TO_GET_USER_INFO});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new Q("UNAUTHORIZED",{message:g.USER_EMAIL_NOT_FOUND});let d=await Re(e,{userInfo:{email:a.user.email,id:a.user.id,name:a.user.name||"",image:a.user.image,emailVerified:a.user.emailVerified||!1},account:{providerId:i.id,accountId:a.user.id,accessToken:e.body.idToken.accessToken}});if(d.error)throw new Q("UNAUTHORIZED",{message:d.error});return await f(e,d.data),e.json({session:d.data.session,user:d.data.user,url:void 0,redirect:!1})}let{codeVerifier:t,state:o}=await Oe(e),r=await i.createAuthorizationURL({state:o,codeVerifier:t,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:r.toString(),redirect:!e.body.disableRedirect})}),pi=p("/sign-in/email",{method:"POST",body:L.object({email:L.string({description:"Email of the user"}),password:L.string({description:"Password of the user"}),callbackURL:L.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:L.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:{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("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:i,password:t}=e.body;if(!L.string().email().safeParse(i).success)throw new Q("BAD_REQUEST",{message:g.INVALID_EMAIL});let r=await e.context.internalAdapter.findUserByEmail(i,{includeAccounts:!0});if(!r)throw await e.context.password.hash(t),e.context.logger.error("User not found",{email:i}),new Q("UNAUTHORIZED",{message:g.INVALID_EMAIL_OR_PASSWORD});let n=r.accounts.find(d=>d.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:i}),new Q("UNAUTHORIZED",{message:g.INVALID_EMAIL_OR_PASSWORD});let s=n?.password;if(!s)throw e.context.logger.error("Password not found",{email:i}),new Q("UNAUTHORIZED",{message:g.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:s,password:t}))throw e.context.logger.error("Invalid password"),new Q("UNAUTHORIZED",{message:g.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!r.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new Q("UNAUTHORIZED",{message:g.EMAIL_NOT_VERIFIED});let d=await de(e.context.secret,r.user.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:r.user,url:c,token:d},e.request),e.context.logger.error("Email not verified",{email:i}),new Q("FORBIDDEN",{message:g.EMAIL_NOT_VERIFIED})}let a=await e.context.internalAdapter.createSession(r.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new Q("UNAUTHORIZED",{message:g.FAILED_TO_CREATE_SESSION});return await f(e,{session:a,user:r.user},e.body.rememberMe===!1),e.json({user:{id:r.user.id,email:r.user.email,name:r.user.name,image:r.user.image,emailVerified:r.user.emailVerified,createdAt:r.user.createdAt,updatedAt:r.user.updatedAt},redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as xe}from"zod";var io=xe.object({code:xe.string().optional(),error:xe.string().optional(),error_description:xe.string().optional(),state:xe.string().optional()}),Ki=p("/callback/:id",{method:["GET","POST"],body:io.optional(),query:io.optional(),metadata:Te},async e=>{let i;try{if(e.method==="GET")i=io.parse(e.query);else if(e.method==="POST")i=io.parse(e.body);else throw new Error("Unsupported method")}catch(h){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",h),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:t,error:o,state:r,error_description:n}=i;if(!r)throw e.context.logger.error("State not found",o),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!t)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}&error_description=${n}`);let s=e.context.socialProviders.find(h=>h.id===e.params.id);if(!s)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:a,link:d,errorURL:c,newUserURL:u}=await Xe(e),l;try{l=await s.validateAuthorizationCode({code:t,codeVerifier:A,redirectURI:`${e.context.baseURL}/callback/${s.id}`})}catch(h){throw e.context.logger.error("",h),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let K=await s.getUserInfo(l).then(h=>h?.user);function m(h){let T=c||a||`${e.context.baseURL}/error`;throw T.includes("?")?T=`${T}&error=${h}`:T=`${T}?error=${h}`,e.redirect(T)}if(!K)return e.context.logger.error("Unable to get user info"),m("unable_to_get_user_info");if(!K.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),m("email_not_found");if(!a)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!==K.email.toLowerCase())return m("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:s.id,accountId:K.id}))return m("unable_to_link_account");let T;try{T=a.toString()}catch{T=a}throw e.redirect(T)}let C=await Re(e,{userInfo:{...K,email:K.email,name:K.name||K.email},account:{providerId:s.id,accountId:K.id,...l,scope:l.scopes?.join(",")},callbackURL:a});if(C.error)return e.context.logger.error(C.error.split(" ").join("_")),m(C.error.split(" ").join("_"));let{session:N,user:w}=C.data;await f(e,{session:N,user:w});let R;try{R=(C.isRegister&&u||a).toString()}catch{R=C.isRegister&&u||a}throw e.redirect(R)});import"zod";import{APIError as Rr}from"better-call";var ui=p("/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 i=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!i)throw M(e),new Rr("BAD_REQUEST",{message:g.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(i),M(e),e.json({success:!0})});import{z as te}from"zod";import{APIError as je}from"better-call";function Ei(e,i,t){let o=i?new URL(i,e.baseURL):new URL(`${e.baseURL}/error`);return t&&Object.entries(t).forEach(([r,n])=>o.searchParams.set(r,n)),o.href}function Ir(e,i,t){let o=new URL(i,e.baseURL);return t&&Object.entries(t).forEach(([r,n])=>o.searchParams.set(r,n)),o.href}var li=p("/forget-password",{method:"POST",body:te.object({email:te.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:te.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 je("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:i,redirectTo:t}=e.body,o=await e.context.internalAdapter.findUserByEmail(i,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:i}),e.json({status:!1},{body:{status:!0}});let r=60*60*1,n=P(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||r,"sec"),s=$(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:n});let A=`${e.context.baseURL}/reset-password/${s}?callbackURL=${t}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:A,token:s},e.request),e.json({status:!0})}),mi=p("/reset-password/:token",{method:"GET",query:te.object({callbackURL:te.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:i}=e.params,{callbackURL:t}=e.query;if(!i||!t)throw e.redirect(Ei(e.context,t,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${i}`);throw!o||o.expiresAt<new Date?e.redirect(Ei(e.context,t,{error:"INVALID_TOKEN"})):e.redirect(Ir(e.context,t,{token:i}))}),gi=p("/reset-password",{query:te.optional(te.object({token:te.string().optional(),currentURL:te.string().optional()})),method:"POST",body:te.object({newPassword:te.string({description:"The new password to set"}),token:te.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 i=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!i)throw new je("BAD_REQUEST",{message:g.INVALID_TOKEN});let{newPassword:t}=e.body,o=e.context.password?.config.minPasswordLength,r=e.context.password?.config.maxPasswordLength;if(t.length<o)throw new je("BAD_REQUEST",{message:g.PASSWORD_TOO_SHORT});if(t.length>r)throw new je("BAD_REQUEST",{message:g.PASSWORD_TOO_LONG});let n=`reset-password:${i}`,s=await e.context.internalAdapter.findVerificationValue(n);if(!s||s.expiresAt<new Date)throw new je("BAD_REQUEST",{message:g.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(s.id);let A=s.value,a=await e.context.password.hash(t);return(await e.context.internalAdapter.findAccounts(A)).find(u=>u.providerId==="credential")?(await e.context.internalAdapter.updatePassword(A,a),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:A,providerId:"credential",password:a,accountId:A}),e.json({status:!0}))});import{z as G}from"zod";import{APIError as q}from"better-call";import{xchacha20poly1305 as Ui}from"@noble/ciphers/chacha";import{bytesToHex as vr,hexToBytes as kr,utf8ToBytes as Pr}from"@noble/ciphers/utils";import{managedNonce as _i}from"@noble/ciphers/webcrypto";import{sha256 as vi}from"oslo/crypto";import Si from"uncrypto";import{decodeHex as ec,encodeHex as oc}from"oslo/encoding";import{scryptAsync as rc}from"@noble/hashes/scrypt";import{getRandomValues as sc}from"uncrypto";import Ri from"uncrypto";function Sr(e){return e.toString(2).padStart(8,"0")}function Ur(e){return[...e].map(i=>Sr(i)).join("")}function Ii(e){return parseInt(Ur(e),2)}function _r(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let i=(e-1).toString(2).length,t=i%8,o=new Uint8Array(Math.ceil(i/8));Ri.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1);let r=Ii(o);for(;r>=e;)Ri.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1),r=Ii(o);return r}function F(e,i){let t="";for(let o=0;o<e;o++)t+=i[_r(i.length)];return t}function V(...e){let i=new Set(e),t="";for(let o of i)o==="a-z"?t+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?t+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?t+="0123456789":t+=o;return t}async function ze(e,i){let t=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},r=await Si.subtle.importKey("raw",t.encode(e),o,!1,["sign","verify"]),n=await Si.subtle.sign(o.name,r,t.encode(i));return btoa(String.fromCharCode(...new Uint8Array(n)))}var le=async({key:e,data:i})=>{let t=await vi(new TextEncoder().encode(e)),o=Pr(i),r=_i(Ui)(new Uint8Array(t));return vr(r.encrypt(o))},fe=async({key:e,data:i})=>{let t=await vi(new TextEncoder().encode(e)),o=kr(i),r=_i(Ui)(new Uint8Array(t));return new TextDecoder().decode(r.decrypt(o))};var fi=()=>p("/update-user",{method:"POST",body:G.record(G.string(),G.any()),use:[I],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 i=e.body;if(i.email)throw new q("BAD_REQUEST",{message:g.EMAIL_CAN_NOT_BE_UPDATED});let{name:t,image:o,...r}=i,n=e.context.session;if(o===void 0&&t===void 0&&Object.keys(r).length===0)return e.json({id:n.user.id,email:n.user.email,name:n.user.name,image:n.user.image,emailVerified:n.user.emailVerified,createdAt:n.user.createdAt,updatedAt:n.user.updatedAt});let s=oo(e.context.options,r,"update"),A=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:t,image:o,...s});return await f(e,{session:n.session,user:A}),e.json({id:A.id,email:A.email,name:A.name,image:A.image,emailVerified:A.emailVerified,createdAt:A.createdAt,updatedAt:A.updatedAt})}),hi=p("/change-password",{method:"POST",body:G.object({newPassword:G.string({description:"The new password to set"}),currentPassword:G.string({description:"The current password"}),revokeOtherSessions:G.boolean({description:"Revoke all other sessions"}).optional()}),use:[I],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:i,currentPassword:t,revokeOtherSessions:o}=e.body,r=e.context.session,n=e.context.password.config.minPasswordLength;if(i.length<n)throw e.context.logger.error("Password is too short"),new q("BAD_REQUEST",{message:g.PASSWORD_TOO_SHORT});let s=e.context.password.config.maxPasswordLength;if(i.length>s)throw e.context.logger.error("Password is too long"),new q("BAD_REQUEST",{message:g.PASSWORD_TOO_LONG});let a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(u=>u.providerId==="credential"&&u.password);if(!a||!a.password)throw new q("BAD_REQUEST",{message:g.CREDENTIAL_ACCOUNT_NOT_FOUND});let d=await e.context.password.hash(i);if(!await e.context.password.verify({hash:a.password,password:t}))throw new q("BAD_REQUEST",{message:g.INVALID_PASSWORD});if(await e.context.internalAdapter.updateAccount(a.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(r.user.id);let u=await e.context.internalAdapter.createSession(r.user.id,e.headers);if(!u)throw new q("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_GET_SESSION});await f(e,{session:u,user:r.user})}return e.json(r.user)}),yi=p("/set-password",{method:"POST",body:G.object({newPassword:G.string()}),metadata:{SERVER_ONLY:!0},use:[I]},async e=>{let{newPassword:i}=e.body,t=e.context.session,o=e.context.password.config.minPasswordLength;if(i.length<o)throw e.context.logger.error("Password is too short"),new q("BAD_REQUEST",{message:g.PASSWORD_TOO_SHORT});let r=e.context.password.config.maxPasswordLength;if(i.length>r)throw e.context.logger.error("Password is too long"),new q("BAD_REQUEST",{message:g.PASSWORD_TOO_LONG});let s=(await e.context.internalAdapter.findAccounts(t.user.id)).find(a=>a.providerId==="credential"&&a.password),A=await e.context.password.hash(i);if(!s)return await e.context.internalAdapter.linkAccount({userId:t.user.id,providerId:"credential",accountId:t.user.id,password:A}),e.json(t.user);throw new q("BAD_REQUEST",{message:"user already has a password"})}),wi=p("/delete-user",{method:"POST",use:[De],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options",{session:e.context.session}),new q("NOT_FOUND");let i=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let r=F(32,V("a-z","A-Z","0-9"));await e.context.internalAdapter.createVerificationValue({value:i.user.id,identifier:`delete-account-${r}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let n=`${e.context.baseURL}/delete-user/callback?token=${r}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:i.user,url:n,token:r},e.request),e.json({success:!0,message:"Verification email sent"})}let t=e.context.options.user.deleteUser?.beforeDelete;t&&await t(i.user,e.request),await e.context.internalAdapter.deleteUser(i.user.id),await e.context.internalAdapter.deleteSessions(i.user.id),await e.context.internalAdapter.deleteAccounts(i.user.id),M(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(i.user,e.request),e.json({success:!0,message:"User deleted"})}),Ci=p("/delete-user/callback",{method:"GET",query:G.object({token:G.string()})},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new q("NOT_FOUND");let i=await S(e);if(!i)throw new q("NOT_FOUND",{message:g.FAILED_TO_GET_USER_INFO});let t=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!t||t.expiresAt<new Date)throw t&&await e.context.internalAdapter.deleteVerificationValue(t.id),new q("NOT_FOUND",{message:g.INVALID_TOKEN});if(t.value!==i.user.id)throw new q("NOT_FOUND",{message:g.INVALID_TOKEN});let o=e.context.options.user.deleteUser?.beforeDelete;o&&await o(i.user,e.request),await e.context.internalAdapter.deleteUser(i.user.id),await e.context.internalAdapter.deleteSessions(i.user.id),await e.context.internalAdapter.deleteAccounts(i.user.id),await e.context.internalAdapter.deleteVerificationValue(t.id),M(e);let r=e.context.options.user.deleteUser?.afterDelete;return r&&await r(i.user,e.request),e.json({success:!0,message:"User deleted"})}),bi=p("/change-email",{method:"POST",query:G.object({currentURL:G.string().optional()}).optional(),body:G.object({newEmail:G.string({description:"The new email to set"}).email(),callbackURL:G.string({description:"The URL to redirect to after email verification"}).optional()}),use:[I],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 q("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 q("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 q("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 q("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await de(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:t},e.request),e.json({user:null,status:!0})});import{z as Fe}from"zod";import{APIError as ki}from"better-call";var Oi=p("/list-accounts",{method:"GET",use:[I],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 i=e.context.session,t=await e.context.internalAdapter.findAccounts(i.user.id);return e.json(t.map(o=>({id:o.id,provider:o.providerId})))}),Ti=p("/link-social",{method:"POST",requireHeaders:!0,query:Fe.object({currentURL:Fe.string().optional()}).optional(),body:Fe.object({callbackURL:Fe.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:Fe.enum(eo,{description:"The OAuth2 provider to use"})}),use:[I],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 i=e.context.session;if((await e.context.internalAdapter.findAccounts(i.user.id)).find(A=>A.providerId===e.body.provider))throw new ki("BAD_REQUEST",{message:g.SOCIAL_ACCOUNT_ALREADY_LINKED});let r=e.context.socialProviders.find(A=>A.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 ki("NOT_FOUND",{message:g.PROVIDER_NOT_FOUND});let n=await Oe(e,{userId:i.user.id,email:i.user.email}),s=await r.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${r.id}`});return e.json({url:s.toString(),redirect:!0})});var Pi=(e,i)=>{let t={};for(let[o,r]of Object.entries(e))t[o]=n=>r({...n,context:{...i,...n.context}}),t[o].path=r.path,t[o].method=r.method,t[o].options=r.options,t[o].headers=r.headers;return t};function to(e){let i=e;return{newRole(t){return Nr(t)}}}function Nr(e){return{statements:e,authorize(i,t){for(let[o,r]of Object.entries(i)){let n=e[o];return n?(t==="OR"?r.some(A=>n.includes(A)):r.every(A=>n.includes(A)))?{success:!0}:{success:!1,error:`Unauthorized to access resource "${o}"`}:{success:!1,error:`You are not allowed to access resource: ${o}`}}return{success:!1,error:"Not authorized"}}}}var Dr={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},Oo=to(Dr),Lr=Oo.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),Br=Oo.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),xr=Oo.newRole({organization:[],member:[],invitation:[]}),Ni={admin:Lr,owner:Br,member:xr};var jr={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*:/},zr=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,Di={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},Fr=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Vr(e){return e instanceof Date&&!isNaN(e.getTime())}function Mr(e){let i=Fr.exec(e);if(!i)return null;let[,t,o,r,n,s,A,a,d,c,u]=i,l=new Date(Date.UTC(parseInt(t,10),parseInt(o,10)-1,parseInt(r,10),parseInt(n,10),parseInt(s,10),parseInt(A,10),a?parseInt(a.padEnd(3,"0"),10):0));if(d){let K=(parseInt(c,10)*60+parseInt(u,10))*(d==="+"?-1:1);l.setUTCMinutes(l.getUTCMinutes()+K)}return Vr(l)?l:null}function qr(e,i={}){let{strict:t=!1,warnings:o=!1,reviver:r,parseDates:n=!0}=i;if(typeof e!="string")return e;let s=e.trim();if(s[0]==='"'&&s.endsWith('"')&&!s.slice(1,-1).includes('"'))return s.slice(1,-1);let A=s.toLowerCase();if(A.length<=9&&A in Di)return Di[A];if(!zr.test(s)){if(t)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(jr).some(([d,c])=>{let u=c.test(s);return u&&o&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${d} pattern`),u})&&t)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(s,(c,u)=>{if(c==="__proto__"||c==="constructor"&&u&&typeof u=="object"&&"prototype"in u){o&&console.warn(`[better-json] Dropping "${c}" key to prevent prototype pollution`);return}if(n&&typeof u=="string"){let l=Mr(u);if(l)return l}return r?r(c,u):u})}catch(d){if(t)throw d;return e}}function Li(e,i={strict:!0}){return qr(e,i)}var Bi=Li;var j=(e,i)=>{let t=e.adapter;return{findOrganizationBySlug:async o=>await t.findOne({model:"organization",where:[{field:"slug",value:o}]}),createOrganization:async o=>{let r=await t.create({model:"organization",data:{...o.organization,metadata:o.organization.metadata?JSON.stringify(o.organization.metadata):void 0}}),n=await t.create({model:"member",data:{organizationId:r.id,userId:o.user.id,createdAt:new Date,role:i?.creatorRole||"owner"}});return{...r,metadata:r.metadata?JSON.parse(r.metadata):void 0,members:[{...n,user:{id:o.user.id,name:o.user.name,email:o.user.email,image:o.user.image}}]}},findMemberByEmail:async o=>{let r=await t.findOne({model:"user",where:[{field:"email",value:o.email}]});if(!r)return null;let n=await t.findOne({model:"member",where:[{field:"organizationId",value:o.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 o=>{let[r,n]=await Promise.all([await t.findOne({model:"member",where:[{field:"userId",value:o.userId},{field:"organizationId",value:o.organizationId}]}),await t.findOne({model:"user",where:[{field:"id",value:o.userId}]})]);return!n||!r?null:{...r,user:{id:n.id,name:n.name,email:n.email,image:n.image}}},findMemberById:async o=>{let r=await t.findOne({model:"member",where:[{field:"id",value:o}]});if(!r)return null;let n=await t.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 o=>await t.create({model:"member",data:o}),updateMember:async(o,r)=>await t.update({model:"member",where:[{field:"id",value:o}],update:{role:r}}),deleteMember:async o=>await t.delete({model:"member",where:[{field:"id",value:o}]}),updateOrganization:async(o,r)=>{let n=await t.update({model:"organization",where:[{field:"id",value:o}],update:{...r,metadata:typeof r.metadata=="object"?JSON.stringify(r.metadata):r.metadata}});return n?{...n,metadata:n.metadata?Bi(n.metadata):void 0}:null},deleteOrganization:async o=>(await t.delete({model:"member",where:[{field:"organizationId",value:o}]}),await t.delete({model:"invitation",where:[{field:"organizationId",value:o}]}),await t.delete({model:"organization",where:[{field:"id",value:o}]}),o),setActiveOrganization:async(o,r)=>await e.internalAdapter.updateSession(o,{activeOrganizationId:r}),findOrganizationById:async o=>await t.findOne({model:"organization",where:[{field:"id",value:o}]}),findFullOrganization:async({organizationId:o,isSlug:r})=>{let n=await t.findOne({model:"organization",where:[{field:r?"slug":"id",value:o}]});if(!n)return null;let[s,A]=await Promise.all([t.findMany({model:"invitation",where:[{field:"organizationId",value:n.id}]}),t.findMany({model:"member",where:[{field:"organizationId",value:n.id}]})]);if(!n)return null;let a=A.map(l=>l.userId),d=await t.findMany({model:"user",where:[{field:"id",value:a,operator:"in"}]}),c=new Map(d.map(l=>[l.id,l])),u=A.map(l=>{let K=c.get(l.userId);if(!K)throw new X("Unexpected error: User not found for member");return{...l,user:{id:K.id,name:K.name,email:K.email,image:K.image}}});return{...n,invitations:s,members:u}},listOrganizations:async o=>{let r=await t.findMany({model:"member",where:[{field:"userId",value:o}]});if(!r||r.length===0)return[];let n=r.map(A=>A.organizationId);return await t.findMany({model:"organization",where:[{field:"id",value:n,operator:"in"}]})},createInvitation:async({invitation:o,user:r})=>{let s=P(i?.invitationExpiresIn||1728e5);return await t.create({model:"invitation",data:{email:o.email,role:o.role,organizationId:o.organizationId,status:"pending",expiresAt:s,inviterId:r.id}})},findInvitationById:async o=>await t.findOne({model:"invitation",where:[{field:"id",value:o}]}),findPendingInvitation:async o=>(await t.findMany({model:"invitation",where:[{field:"email",value:o.email},{field:"organizationId",value:o.organizationId},{field:"status",value:"pending"}]})).filter(n=>new Date(n.expiresAt)>new Date),updateInvitation:async o=>await t.update({model:"invitation",where:[{field:"id",value:o.invitationId}],update:{status:o.status}})}};import"better-call";var H=k(async e=>({})),Z=k({use:[I]},async e=>({session:e.context.session}));import{z as ee}from"zod";import{z as D}from"zod";var xi=D.string(),Hr=D.enum(["pending","accepted","rejected","canceled"]).default("pending"),wp=D.object({id:D.string().default($),name:D.string(),slug:D.string(),logo:D.string().nullish(),metadata:D.record(D.string()).or(D.string().transform(e=>JSON.parse(e))).nullish(),createdAt:D.date()}),Cp=D.object({id:D.string().default($),organizationId:D.string(),userId:D.string(),role:xi,createdAt:D.date()}),bp=D.object({id:D.string().default($),organizationId:D.string(),email:D.string(),role:xi,status:Hr,inviterId:D.string(),expiresAt:D.date()});import{APIError as z}from"better-call";var y={YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization"};var ji=e=>p("/organization/invite-member",{method:"POST",use:[H,Z],body:ee.object({email:ee.string({description:"The email address of the user to invite"}),role:ee.string({description:"The role to assign to the user"}),organizationId:ee.string({description:"The organization ID to invite the user to"}).optional(),resend:ee.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 i=>{if(!i.context.orgOptions.sendInvitationEmail)throw i.context.logger.warn("Invitation email is not enabled. Pass `sendInvitationEmail` to the plugin options to enable it."),new z("BAD_REQUEST",{message:"Invitation email is not enabled"});let t=i.context.session,o=i.body.organizationId||t.session.activeOrganizationId;if(!o)throw new z("BAD_REQUEST",{message:y.ORGANIZATION_NOT_FOUND});let r=j(i.context,i.context.orgOptions),n=await r.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!n)throw new z("BAD_REQUEST",{message:y.MEMBER_NOT_FOUND});let s=i.context.roles[n.role];if(!s)throw new z("BAD_REQUEST",{message:y.ROLE_NOT_FOUND});if(s.authorize({invitation:["create"]}).error)throw new z("FORBIDDEN",{message:y.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION});if(await r.findMemberByEmail({email:i.body.email,organizationId:o}))throw new z("BAD_REQUEST",{message:y.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION});if((await r.findPendingInvitation({email:i.body.email,organizationId:o})).length&&!i.body.resend)throw new z("BAD_REQUEST",{message:y.USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION});let c=await r.createInvitation({invitation:{role:i.body.role,email:i.body.email,organizationId:o},user:t.user}),u=await r.findOrganizationById(o);if(!u)throw new z("BAD_REQUEST",{message:y.ORGANIZATION_NOT_FOUND});return await i.context.orgOptions.sendInvitationEmail?.({id:c.id,role:c.role,email:c.email,organization:u,inviter:{...n,user:t.user}},i.request),i.json(c)}),zi=p("/organization/accept-invitation",{method:"POST",body:ee.object({invitationId:ee.string({description:"The ID of the invitation to accept"})}),use:[H,Z],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 i=e.context.session,t=j(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new z("BAD_REQUEST",{message:y.INVITATION_NOT_FOUND});if(o.email!==i.user.email)throw new z("FORBIDDEN",{message:y.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let r=await t.updateInvitation({invitationId:e.body.invitationId,status:"accepted"}),n=await t.createMember({organizationId:o.organizationId,userId:i.user.id,role:o.role,createdAt:new Date});return await t.setActiveOrganization(i.session.token,o.organizationId),r?e.json({invitation:r,member:n}):e.json(null,{status:400,body:{message:y.INVITATION_NOT_FOUND}})}),Fi=p("/organization/reject-invitation",{method:"POST",body:ee.object({invitationId:ee.string({description:"The ID of the invitation to reject"})}),use:[H,Z],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 i=e.context.session,t=j(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new z("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==i.user.email)throw new z("FORBIDDEN",{message:y.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let r=await t.updateInvitation({invitationId:e.body.invitationId,status:"rejected"});return e.json({invitation:r,member:null})}),Vi=p("/organization/cancel-invitation",{method:"POST",body:ee.object({invitationId:ee.string({description:"The ID of the invitation to cancel"})}),use:[H,Z],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 i=e.context.session,t=j(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o)throw new z("BAD_REQUEST",{message:y.INVITATION_NOT_FOUND});let r=await t.findMemberByOrgId({userId:i.user.id,organizationId:o.organizationId});if(!r)throw new z("BAD_REQUEST",{message:y.MEMBER_NOT_FOUND});if(e.context.roles[r.role].authorize({invitation:["cancel"]}).error)throw new z("FORBIDDEN",{message:y.YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION});let s=await t.updateInvitation({invitationId:e.body.invitationId,status:"canceled"});return e.json(s)}),Mi=p("/organization/get-invitation",{method:"GET",use:[H],requireHeaders:!0,query:ee.object({id:ee.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 i=await S(e);if(!i)throw new z("UNAUTHORIZED",{message:"Not authenticated"});let t=j(e.context,e.context.orgOptions),o=await t.findInvitationById(e.query.id);if(!o||o.status!=="pending"||o.expiresAt<new Date)throw new z("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==i.user.email)throw new z("FORBIDDEN",{message:y.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let r=await t.findOrganizationById(o.organizationId);if(!r)throw new z("BAD_REQUEST",{message:y.ORGANIZATION_NOT_FOUND});let n=await t.findMemberByOrgId({userId:o.inviterId,organizationId:o.organizationId});if(!n)throw new z("BAD_REQUEST",{message:y.INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION});return e.json({...o,organizationName:r.name,organizationSlug:r.slug,inviterEmail:n.user.email})});import{z as ae}from"zod";import{APIError as ye}from"better-call";var qi=()=>p("/organization/add-member",{method:"POST",body:ae.object({userId:ae.string(),role:ae.string(),organizationId:ae.string().optional()}),use:[H],metadata:{SERVER_ONLY:!0}},async e=>{let i=e.body.userId?await S(e).catch(A=>null):null,t=e.body.organizationId||i?.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:y.NO_ACTIVE_ORGANIZATION}});let o=j(e.context,e.context.orgOptions),r=await e.context.internalAdapter.findUserById(e.body.userId);if(!r)throw new ye("BAD_REQUEST",{message:g.USER_NOT_FOUND});if(await o.findMemberByEmail({email:r.email,organizationId:t}))throw new ye("BAD_REQUEST",{message:y.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION});let s=await o.createMember({id:$(),organizationId:t,userId:r.id,role:e.body.role,createdAt:new Date});return e.json(s)}),Hi=p("/organization/remove-member",{method:"POST",body:ae.object({memberIdOrEmail:ae.string({description:"The ID or email of the member to remove"}),organizationId:ae.string({description:"The ID of the organization to remove the member from. If not provided, the active organization will be used"}).optional()}),use:[H,Z],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 i=e.context.session,t=e.body.organizationId||i.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:y.NO_ACTIVE_ORGANIZATION}});let o=j(e.context,e.context.orgOptions),r=await o.findMemberByOrgId({userId:i.user.id,organizationId:t});if(!r)throw new ye("BAD_REQUEST",{message:y.MEMBER_NOT_FOUND});let n=e.context.roles[r.role];if(!n)throw new ye("BAD_REQUEST",{message:y.ROLE_NOT_FOUND});let s=i.user.email===e.body.memberIdOrEmail||r.id===e.body.memberIdOrEmail;if(s&&r.role===(e.context.orgOptions?.creatorRole||"owner"))throw new ye("BAD_REQUEST",{message:y.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER});if(!(s||n.authorize({member:["delete"]}).success))throw new ye("UNAUTHORIZED",{message:y.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER});let d=null;if(e.body.memberIdOrEmail.includes("@")?d=await o.findMemberByEmail({email:e.body.memberIdOrEmail,organizationId:t}):d=await o.findMemberById(e.body.memberIdOrEmail),d?.organizationId!==t)throw new ye("BAD_REQUEST",{message:y.MEMBER_NOT_FOUND});return await o.deleteMember(d.id),i.user.id===d.userId&&i.session.activeOrganizationId===d.organizationId&&await o.setActiveOrganization(i.session.token,null),e.json({member:d})}),$i=e=>p("/organization/update-member-role",{method:"POST",body:ae.object({role:ae.string(),memberId:ae.string(),organizationId:ae.string().optional()}),use:[H,Z],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 i=>{let t=i.context.session,o=i.body.organizationId||t.session.activeOrganizationId;if(!o)return i.json(null,{status:400,body:{message:y.NO_ACTIVE_ORGANIZATION}});let r=j(i.context,i.context.orgOptions),n=await r.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!n)return i.json(null,{status:400,body:{message:y.MEMBER_NOT_FOUND}});let s=i.context.roles[n.role];if(!s)return i.json(null,{status:400,body:{message:y.ROLE_NOT_FOUND}});if(s.authorize({member:["update"]}).error||i.body.role==="owner"&&n.role!=="owner")return i.json(null,{body:{message:"You are not allowed to update this member"},status:403});let a=await r.updateMember(i.body.memberId,i.body.role);return a?i.json(a):i.json(null,{status:400,body:{message:y.MEMBER_NOT_FOUND}})}),Gi=p("/organization/get-active-member",{method:"GET",use:[H,Z],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 i=e.context.session,t=i.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:y.NO_ACTIVE_ORGANIZATION}});let r=await j(e.context,e.context.orgOptions).findMemberByOrgId({userId:i.user.id,organizationId:t});return r?e.json(r):e.json(null,{status:400,body:{message:y.MEMBER_NOT_FOUND}})});import{z as _}from"zod";import{APIError as me}from"better-call";var Qi=p("/organization/create",{method:"POST",body:_.object({name:_.string({description:"The name of the organization"}),slug:_.string({description:"The slug of the organization"}),userId:_.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:_.string({description:"The logo of the organization"}).optional(),metadata:_.record(_.string(),_.any(),{description:"The metadata of the organization"}).optional()}),use:[H],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 i=await S(e);if(!i&&(e.request||e.headers))throw new me("UNAUTHORIZED");let t=i?.user||null;if(!t){if(!e.body.userId)throw new me("UNAUTHORIZED");t=await e.context.internalAdapter.findUserById(e.body.userId)}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("FORBIDDEN",{message:y.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION});let n=j(e.context,o),s=await n.listOrganizations(t.id);if(typeof o.organizationLimit=="number"?s.length>=o.organizationLimit:typeof o.organizationLimit=="function"?await o.organizationLimit(t):!1)throw new me("FORBIDDEN",{message:y.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS});if(await n.findOrganizationBySlug(e.body.slug))throw new me("BAD_REQUEST",{message:y.ORGANIZATION_ALREADY_EXISTS});let d=await n.createOrganization({organization:{id:$(),slug:e.body.slug,name:e.body.name,logo:e.body.logo,createdAt:new Date,metadata:e.body.metadata},user:t});return e.context.session&&await n.setActiveOrganization(e.context.session.session.token,d.id),e.json(d)}),Zi=p("/organization/update",{method:"POST",body:_.object({data:_.object({name:_.string({description:"The name of the organization"}).optional(),slug:_.string({description:"The slug of the organization"}).optional(),logo:_.string({description:"The logo of the organization"}).optional(),metadata:_.record(_.string(),_.any(),{description:"The metadata of the organization"}).optional()}).partial(),organizationId:_.string().optional()}),requireHeaders:!0,use:[H],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 i=await e.context.getSession(e);if(!i)throw new me("UNAUTHORIZED",{message:"User not found"});let t=e.body.organizationId||i.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:y.ORGANIZATION_NOT_FOUND}});let o=j(e.context,e.context.orgOptions),r=await o.findMemberByOrgId({userId:i.user.id,organizationId:t});if(!r)return e.json(null,{status:400,body:{message:y.USER_IS_NOT_A_MEMBER_OF_THE_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:y.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION},status:403});let A=await o.updateOrganization(t,e.body.data);return e.json(A)}),Wi=p("/organization/delete",{method:"POST",body:_.object({organizationId:_.string({description:"The organization id to delete"})}),requireHeaders:!0,use:[H],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 i=await e.context.getSession(e);if(!i)return e.json(null,{status:401});let t=e.body.organizationId;if(!t)return e.json(null,{status:400,body:{message:y.ORGANIZATION_NOT_FOUND}});let o=j(e.context,e.context.orgOptions),r=await o.findMemberByOrgId({userId:i.user.id,organizationId:t});if(!r)return e.json(null,{status:400,body:{message:y.USER_IS_NOT_A_MEMBER_OF_THE_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("FORBIDDEN",{message:y.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION});return t===i.session.activeOrganizationId&&await o.setActiveOrganization(i.session.token,null),await o.deleteOrganization(t),e.json(t)}),Ji=p("/organization/get-full-organization",{method:"GET",query:_.optional(_.object({organizationId:_.string({description:"The organization id to get"}).optional(),organizationSlug:_.string({description:"The organization slug to get"}).optional()})),requireHeaders:!0,use:[H,Z],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 i=e.context.session,t=e.query?.organizationSlug||e.query?.organizationId||i.session.activeOrganizationId;if(!t)return e.json(null,{status:200});let r=await j(e.context,e.context.orgOptions).findFullOrganization({organizationId:t,isSlug:!!e.query?.organizationSlug});if(!r)throw new me("BAD_REQUEST",{message:y.ORGANIZATION_NOT_FOUND});return e.json(r)}),Yi=p("/organization/set-active",{method:"POST",body:_.object({organizationId:_.string({description:"The organization id to set as active. It can be null to unset the active organization"}).nullable().optional(),organizationSlug:_.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:[Z,H],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 i=j(e.context,e.context.orgOptions),t=e.context.session,o=e.body.organizationSlug||e.body.organizationId;if(o===null){if(!t.session.activeOrganizationId)return e.json(null);let a=await i.setActiveOrganization(t.session.token,null);return await f(e,{session:a,user:t.user}),e.json(null)}if(!o){let A=t.session.activeOrganizationId;if(!A)return e.json(null);o=A}let r=await i.findFullOrganization({organizationId:o,isSlug:!!e.body.organizationSlug});if(!r?.members.find(A=>A.userId===t.user.id))throw await i.setActiveOrganization(t.session.token,null),new me("FORBIDDEN",{message:y.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION});let s=await i.setActiveOrganization(t.session.token,o);return await f(e,{session:s,user:t.user}),e.json(r)}),Xi=p("/organization/list",{method:"GET",use:[H,Z],metadata:{openapi:{description:"List all organizations",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Organization"}}}}}}}}},async e=>{let t=await j(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(t)});var $r=to({name:["action"]}),uK=$r.newRole({name:["action"]}),lK=e=>{let i={createOrganization:Qi,updateOrganization:Zi,deleteOrganization:Wi,setActiveOrganization:Yi,getFullOrganization:Ji,listOrganizations:Xi,createInvitation:ji(e),cancelInvitation:Vi,acceptInvitation:zi,getInvitation:Mi,rejectInvitation:Fi,addMember:qi(),removeMember:Hi,updateMemberRole:$i(e),getActiveMember:Gi},t={...Ni,...e?.roles};return{id:"organization",endpoints:{...Pi(i,{orgOptions:e||{},roles:t,getSession:async r=>await S(r)}),hasPermission:p("/organization/has-permission",{method:"POST",requireHeaders:!0,body:Ie.object({organizationId:Ie.string().optional(),permission:Ie.record(Ie.string(),Ie.array(Ie.string()))}),use:[Z],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=>{let n=r.body.organizationId||r.context.session.session.activeOrganizationId;if(!n)throw new et("BAD_REQUEST",{message:y.NO_ACTIVE_ORGANIZATION});let A=await j(r.context).findMemberByOrgId({userId:r.context.session.user.id,organizationId:n});if(!A)throw new et("UNAUTHORIZED",{message:y.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION});let d=t[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:{}},$ERROR_CODES:y}};import{z as ao}from"zod";import{z as ge}from"zod";import{APIError as Ve}from"better-call";var ro="two_factor";var no="trust_device";import{z as ot}from"zod";var we=k({body:ot.object({trustDevice:ot.boolean().optional()})},async e=>{let i=await S(e);if(!i){let t=e.context.createAuthCookie(ro),o=await e.getSignedCookie(t.name,e.context.secret);if(!o)throw new Ve("UNAUTHORIZED",{message:"invalid two factor cookie"});let r=await e.context.internalAdapter.findUserById(o);if(!r)throw new Ve("UNAUTHORIZED",{message:"invalid two factor cookie"});let n=await e.context.internalAdapter.createSession(o,e.request);if(!n)throw new Ve("INTERNAL_SERVER_ERROR",{message:"failed to create session"});return{valid:async()=>{if(await f(e,{session:n,user:r}),e.body.trustDevice){let s=e.context.createAuthCookie(no,{maxAge:2592e3}),A=await ze(e.context.secret,`${r.id}!${n.token}`);await e.setSignedCookie(s.name,`${A}!${n.token}`,e.context.secret,s.attributes)}return e.json({session:n,user:r})},invalid:async()=>{throw new Ve("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:{session:n,user:r}}}return{valid:async()=>e.json({session:i,user:i.user}),invalid:async()=>{throw new Ve("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:i}});import{APIError as Me}from"better-call";var W={OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code"};function Gr(e){return Array.from({length:e?.amount??10}).fill(null).map(()=>F(e?.length??10,V("a-z","0-9"))).map(i=>`${i.slice(0,5)}-${i.slice(5)}`)}async function To(e,i){let t=e,o=i?.customBackupCodesGenerate?i.customBackupCodesGenerate():Gr(),r=await le({data:JSON.stringify(o),key:t});return{backupCodes:o,encryptedBackupCodes:r}}async function Qr(e,i){let t=await it(e.backupCodes,i);return t?{status:t.includes(e.code),updated:t.filter(o=>o!==e.code)}:{status:!1,updated:null}}async function it(e,i){let t=Buffer.from(await fe({key:i,data:e})).toString("utf-8"),o=JSON.parse(t),r=ge.array(ge.string()).safeParse(o);return r.success?r.data:null}var tt=(e,i)=>({id:"backup_code",endpoints:{verifyBackupCode:p("/two-factor/verify-backup-code",{method:"POST",body:ge.object({code:ge.string(),disableSession:ge.boolean().optional()}),use:[we]},async t=>{let o=t.context.session.user,r=await t.context.adapter.findOne({model:i,where:[{field:"userId",value:o.id}]});if(!r)throw new Me("BAD_REQUEST",{message:W.BACKUP_CODES_NOT_ENABLED});let n=await Qr({backupCodes:r.backupCodes,code:t.body.code},t.context.secret);if(!n.status)throw new Me("UNAUTHORIZED",{message:W.INVALID_BACKUP_CODE});let s=await le({key:t.context.secret,data:JSON.stringify(n.updated)});return await t.context.adapter.updateMany({model:i,update:{backupCodes:s},where:[{field:"userId",value:o.id}]}),t.body.disableSession||await f(t,{session:t.context.session.session,user:o}),t.json({user:o,session:t.context.session})}),generateBackupCodes:p("/two-factor/generate-backup-codes",{method:"POST",body:ge.object({password:ge.string()}),use:[I]},async t=>{let o=t.context.session.user;if(!o.twoFactorEnabled)throw new Me("BAD_REQUEST",{message:W.TWO_FACTOR_NOT_ENABLED});await t.context.password.checkPassword(o.id,t);let r=await To(t.context.secret,e);return await t.context.adapter.update({model:i,update:{backupCodes:r.encryptedBackupCodes},where:[{field:"userId",value:t.context.session.user.id}]}),t.json({status:!0,backupCodes:r.backupCodes})}),viewBackupCodes:p("/two-factor/view-backup-codes",{method:"GET",body:ge.object({userId:ge.string()}),metadata:{SERVER_ONLY:!0}},async t=>{let o=await t.context.adapter.findOne({model:i,where:[{field:"userId",value:t.body.userId}]});if(!o)throw new Me("BAD_REQUEST",{message:"Backup codes aren't enabled"});let r=await it(o.backupCodes,t.context.secret);if(!r)throw new Me("BAD_REQUEST",{message:W.BACKUP_CODES_NOT_ENABLED});return t.json({status:!0,backupCodes:r})})}});import{APIError as qe}from"better-call";import{z as rt}from"zod";import{TimeSpan as Zr}from"oslo";var nt=(e,i)=>{let t={...e,digits:e?.digits||6,period:new Zr(e?.period||3,"m")},o=p("/two-factor/send-otp",{method:"POST",use:[we],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 qe("BAD_REQUEST",{message:"otp isn't configured"});let s=n.context.session.user;if(!await n.context.adapter.findOne({model:i,where:[{field:"userId",value:s.id}]}))throw new qe("BAD_REQUEST",{message:W.OTP_NOT_ENABLED});let a=F(t.digits,V("0-9"));return await n.context.internalAdapter.createVerificationValue({value:a,identifier:`2fa-otp-${s.id}`,expiresAt:new Date(Date.now()+t.period.milliseconds())}),await e.sendOTP({user:s,otp:a},n.request),n.json({status:!0})}),r=p("/two-factor/verify-otp",{method:"POST",body:rt.object({code:rt.string({description:"The otp code to verify"})}),use:[we],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 s=n.context.session.user;if(!s.twoFactorEnabled)throw new qe("BAD_REQUEST",{message:"two factor isn't enabled"});if(!await n.context.adapter.findOne({model:i,where:[{field:"userId",value:s.id}]}))throw new qe("BAD_REQUEST",{message:W.OTP_NOT_ENABLED});let a=await n.context.internalAdapter.findVerificationValue(`2fa-otp-${s.id}`);if(!a||a.expiresAt<new Date)throw new qe("BAD_REQUEST",{message:W.OTP_HAS_EXPIRED});return a.value===n.body.code?n.context.valid():n.context.invalid()});return{id:"otp",endpoints:{sendTwoFactorOTP:o,verifyTwoFactorOTP:r}}};import{APIError as Se}from"better-call";import{TimeSpan as Wr}from"oslo";import{TOTPController as st,createTOTPKeyURI as Jr}from"oslo/otp";import{z as so}from"zod";var at=(e,i)=>{let t={...e,digits:e?.digits||6,period:new Wr(e?.period||30,"s")},o=p("/totp/generate",{method:"POST",use:[I],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 s=>{if(!e)throw s.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new Se("BAD_REQUEST",{message:"totp isn't configured"});let A=s.context.session.user,a=await s.context.adapter.findOne({model:i,where:[{field:"userId",value:A.id}]});if(!a)throw new Se("BAD_REQUEST",{message:W.TOTP_NOT_ENABLED});return{code:await new st(t).generate(Buffer.from(a.secret))}}),r=p("/two-factor/get-totp-uri",{method:"POST",use:[I],body:so.object({password:so.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 s=>{if(!e)throw s.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new Se("BAD_REQUEST",{message:"totp isn't configured"});let A=s.context.session.user,a=await s.context.adapter.findOne({model:i,where:[{field:"userId",value:A.id}]});if(!a||!A.twoFactorEnabled)throw new Se("BAD_REQUEST",{message:W.TOTP_NOT_ENABLED});return await s.context.password.checkPassword(A.id,s),{totpURI:Jr(e.issuer||s.context.appName,A.email,Buffer.from(a.secret),t)}}),n=p("/two-factor/verify-totp",{method:"POST",body:so.object({code:so.string({description:"The otp code to verify"})}),use:[we],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 s=>{if(!e)throw s.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new Se("BAD_REQUEST",{message:"totp isn't configured"});let A=s.context.session.user,a=await s.context.adapter.findOne({model:i,where:[{field:"userId",value:A.id}]});if(!a)throw new Se("BAD_REQUEST",{message:W.TOTP_NOT_ENABLED});let d=new st(t),c=await fe({key:s.context.secret,data:a.secret}),u=Buffer.from(c);if(!await d.verify(s.body.code,u))return s.context.invalid();if(!A.twoFactorEnabled){let K=await s.context.internalAdapter.updateUser(A.id,{twoFactorEnabled:!0}),m=await s.context.internalAdapter.createSession(A.id,s.request,!1,s.context.session.session).catch(C=>{throw console.log(C),C});await s.context.internalAdapter.deleteSession(s.context.session.session.token),await f(s,{session:m,user:K})}return s.context.valid()});return{id:"totp",endpoints:{generateTOTP:o,getTOTPURI:r,verifyTOTP:n}}};import{APIError as ru}from"better-call";async function Eo(e,i){let o=(await e.context.internalAdapter.findAccounts(i.userId))?.find(s=>s.providerId==="credential"),r=o?.password;return!o||!r?!1:await e.context.password.verify({hash:r,password:i.password})}import{APIError as dt}from"better-call";import{createTOTPKeyURI as Yr}from"oslo/otp";import{TimeSpan as Xr}from"oslo";var At={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 au=e=>({id:"two-factor",$InferServerPlugin:{},atomListeners:[{matcher:i=>i.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(i){i.data?.twoFactorRedirect&&e?.onTwoFactorRedirect&&await e.onTwoFactorRedirect()}}}]});var Ru=e=>{let i={twoFactorTable:"twoFactor"},t=at({issuer:e?.issuer,...e?.totpOptions},i.twoFactorTable),o=tt({...e?.backupCodeOptions},i.twoFactorTable),r=nt({...e?.otpOptions},i.twoFactorTable);return{id:"two-factor",endpoints:{...t.endpoints,...r.endpoints,...o.endpoints,enableTwoFactor:p("/two-factor/enable",{method:"POST",body:ao.object({password:ao.string({description:"User password"}).min(8)}),use:[I],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 s=n.context.session.user,{password:A}=n.body;if(!await Eo(n,{password:A,userId:s.id}))throw new dt("BAD_REQUEST",{message:g.INVALID_PASSWORD});let d=F(16,V("a-z","0-9","-")),c=await le({key:n.context.secret,data:d}),u=await To(n.context.secret,e?.backupCodeOptions);if(e?.skipVerificationOnEnable){let K=await n.context.internalAdapter.updateUser(s.id,{twoFactorEnabled:!0}),m=await n.context.internalAdapter.createSession(K.id,n.request,!1,n.context.session.session);await f(n,{session:m,user:s}),await n.context.internalAdapter.deleteSession(n.context.session.session.token)}await n.context.adapter.deleteMany({model:i.twoFactorTable,where:[{field:"userId",value:s.id}]}),await n.context.adapter.create({model:i.twoFactorTable,data:{secret:c,backupCodes:u.encryptedBackupCodes,userId:s.id}});let l=Yr(e?.issuer||"BetterAuth",s.email,Buffer.from(d),{digits:e?.totpOptions?.digits||6,period:new Xr(e?.totpOptions?.period||30,"s")});return n.json({totpURI:l,backupCodes:u.backupCodes})}),disableTwoFactor:p("/two-factor/disable",{method:"POST",body:ao.object({password:ao.string({description:"User password"}).min(8)}),use:[I],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 s=n.context.session.user,{password:A}=n.body;if(!await Eo(n,{password:A,userId:s.id}))throw new dt("BAD_REQUEST",{message:"Invalid password"});await n.context.internalAdapter.updateUser(s.id,{twoFactorEnabled:!1}),await n.context.adapter.delete({model:i.twoFactorTable,where:[{field:"userId",value:s.id}]});let d=await n.context.internalAdapter.createSession(s.id,n.request,!1,n.context.session.session);return await f(n,{session:d,user:s}),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:k(async n=>{let s=n.context.newSession;if(!s||!s?.user.twoFactorEnabled)return;let A=n.context.createAuthCookie(no),a=await n.getSignedCookie(A.name,n.context.secret);if(a){let[c,u]=a.split("!"),l=await ze(n.context.secret,`${s.user.id}!${u}`);if(c===l){let K=await ze(n.context.secret,`${s.user.id}!${s.session.token}`);await n.setSignedCookie(A.name,`${K}!${s.session.token}`,n.context.secret,A.attributes);return}}M(n),await n.context.internalAdapter.deleteSession(s.session.token);let d=n.context.createAuthCookie(ro,{maxAge:60*10});return await n.setSignedCookie(d.name,s.user.id,n.context.secret,d.attributes),n.json({twoFactorRedirect:!0})})}]},schema:ie(At,e?.schema),rateLimit:[{pathMatcher(n){return n.startsWith("/two-factor/")},window:10,max:3}]}};import{generateAuthenticationOptions as An,generateRegistrationOptions as dn,verifyAuthenticationResponse as cn,verifyRegistrationResponse as pn}from"@simplewebauthn/server";import{APIError as Y}from"better-call";import{z as re}from"zod";import{WebAuthnError as tn,startAuthentication as rn,startRegistration as nn}from"@simplewebauthn/browser";import{createFetch as Hu}from"@better-fetch/fetch";import"nanostores";import"@better-fetch/fetch";import{atom as Bu}from"nanostores";import"@better-fetch/fetch";import{atom as en,onMount as on}from"nanostores";var Ro=(e,i,t,o)=>{let r=en({data:null,error:null,isPending:!0,isRefetching:!1}),n=()=>{let A=typeof o=="function"?o({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):o;return t(i,{...A,async onSuccess(a){r.set({data:a.data,error:null,isPending:!1,isRefetching:!1}),await A?.onSuccess?.(a)},async onError(a){r.set({error:a.error,data:null,isPending:!1,isRefetching:!1}),await A?.onError?.(a)},async onRequest(a){let d=r.get();r.set({isPending:d.data===null,data:d.data,error:null,isRefetching:!0}),await A?.onRequest?.(a)}})};e=Array.isArray(e)?e:[e];let s=!1;for(let A of e)A.subscribe(()=>{s?n():on(r,()=>(n(),s=!0,()=>{r.off(),A.off()}))});return r};import{atom as sn}from"nanostores";var an=(e,{$listPasskeys:i})=>({signIn:{passkey:async(r,n)=>{let s=await e("/passkey/generate-authenticate-options",{method:"POST",body:{email:r?.email}});if(!s.data)return s;try{let A=await rn(s.data,r?.autoFill||!1),a=await e("/passkey/verify-authentication",{body:{response:A},...r?.fetchOptions,...n,method:"POST"});if(!a.data)return a}catch{return{data:null,error:{message:"auth cancelled",status:400,statusText:"BAD_REQUEST"}}}}},passkey:{addPasskey:async(r,n)=>{let s=await e("/passkey/generate-register-options",{method:"GET"});if(!s.data)return s;try{let A=await nn(s.data),a=await e("/passkey/verify-registration",{...r?.fetchOptions,...n,body:{response:A,name:r?.name},method:"POST"});if(!a.data)return a;i.set(Math.random())}catch(A){return A instanceof tn?A.code==="ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED"?{data:null,error:{message:"previously registered",status:400,statusText:"BAD_REQUEST"}}:A.code==="ERROR_CEREMONY_ABORTED"?{data:null,error:{message:"registration cancelled",status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:A.message,status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:A instanceof Error?A.message:"unknown error",status:500,statusText:"INTERNAL_SERVER_ERROR"}}}}},$Infer:{}}),ul=()=>{let e=sn();return{id:"passkey",$InferServerPlugin:{},getActions:i=>an(i,{$listPasskeys:e}),getAtoms(i){return{listPasskeys:Ro(e,"/passkey/list-user-passkeys",i,{method:"GET"}),$listPasskeys:e}},pathMethods:{"/passkey/register":"POST","/passkey/authenticate":"POST"},atomListeners:[{matcher(i){return i==="/passkey/verify-registration"||i==="/passkey/delete-passkey"||i==="/passkey/update-passkey"},signal:"_listPasskeys"}]}};var Il=e=>{let i=ne.BETTER_AUTH_URL,t=e?.rpID||i?.replace("http://","").replace("https://","").split(":")[0]||"localhost";if(!t)throw new X("passkey rpID not found. Please provide a rpID in the options or set the BETTER_AUTH_URL environment variable.");let o={origin:null,...e,rpID:t,advanced:{webAuthnChallengeCookie:"better-auth-passkey",...e?.advanced}},r=new Date(Date.now()+1e3*60*5),n=new Date,s=Math.floor((r.getTime()-n.getTime())/1e3),A={CHALLENGE_NOT_FOUND:"Challenge not found",YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY:"You are not allowed to register this passkey",FAILED_TO_VERIFY_REGISTRATION:"Failed to verify registration",PASSKEY_NOT_FOUND:"Passkey not found",AUTHENTICATION_FAILED:"Authentication failed",UNABLE_TO_CREATE_SESSION:"Unable to create session",FAILED_TO_UPDATE_PASSKEY:"Failed to update passkey"};return{id:"passkey",endpoints:{generatePasskeyRegistrationOptions:p("/passkey/generate-register-options",{method:"GET",use:[De],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 a=>{let d=a.context.session,c=await a.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}),u=new Uint8Array(Buffer.from(F(32,V("a-z","0-9")))),l;l=await dn({rpName:o.rpName||a.context.appName,rpID:o.rpID,userID:u,userName:d.user.email||d.user.id,attestationType:"none",excludeCredentials:c.map(m=>({id:m.id,transports:m.transports?.split(",")})),authenticatorSelection:{residentKey:"preferred",userVerification:"preferred",authenticatorAttachment:"platform"}});let K=$(32);return await a.setSignedCookie(o.advanced.webAuthnChallengeCookie,K,a.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:s}),await a.context.internalAdapter.createVerificationValue({identifier:K,value:JSON.stringify({expectedChallenge:l.challenge,userData:{id:d.user.id}}),expiresAt:r}),a.json(l,{status:200})}),generatePasskeyAuthenticationOptions:p("/passkey/generate-authenticate-options",{method:"POST",body:re.object({email:re.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 a=>{let d=await S(a),c=[];d&&(c=await a.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}));let u=await An({rpID:o.rpID,userVerification:"preferred",...c.length?{allowCredentials:c.map(m=>({id:m.id,transports:m.transports?.split(",")}))}:{}}),l={expectedChallenge:u.challenge,userData:{id:d?.user.id||""}},K=$(32);return await a.setSignedCookie(o.advanced.webAuthnChallengeCookie,K,a.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:s}),await a.context.internalAdapter.createVerificationValue({identifier:K,value:JSON.stringify(l),expiresAt:r}),a.json(u,{status:200})}),verifyPasskeyRegistration:p("/passkey/verify-registration",{method:"POST",body:re.object({response:re.any({description:"The response from the authenticator"}),name:re.string({description:"Name of the passkey"}).optional()}),use:[De],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 a=>{let d=e?.origin||a.headers?.get("origin")||"";if(!d)return a.json(null,{status:400});let c=a.body.response,u=await a.getSignedCookie(o.advanced.webAuthnChallengeCookie,a.context.secret);if(!u)throw new Y("BAD_REQUEST",{message:A.CHALLENGE_NOT_FOUND});let l=await a.context.internalAdapter.findVerificationValue(u);if(!l)return a.json(null,{status:400});let{expectedChallenge:K,userData:m}=JSON.parse(l.value);if(m.id!==a.context.session.user.id)throw new Y("UNAUTHORIZED",{message:A.YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY});try{let C=await pn({response:c,expectedChallenge:K,expectedOrigin:d,expectedRPID:e?.rpID}),{verified:N,registrationInfo:w}=C;if(!N||!w)return a.json(null,{status:400});let{credentialID:R,credentialPublicKey:h,counter:T,credentialDeviceType:x,credentialBackedUp:Qe}=w,bt=Buffer.from(h).toString("base64"),Ot={name:a.body.name,userId:m.id,webauthnUserID:a.context.generateId({model:"passkey"}),id:R,publicKey:bt,counter:T,deviceType:x,transports:c.response.transports.join(","),backedUp:Qe,createdAt:new Date},Tt=await a.context.adapter.create({model:"passkey",data:Ot});return a.json(Tt,{status:200})}catch(C){throw console.log(C),new Y("INTERNAL_SERVER_ERROR",{message:A.FAILED_TO_VERIFY_REGISTRATION})}}),verifyPasskeyAuthentication:p("/passkey/verify-authentication",{method:"POST",body:re.object({response:re.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 a=>{let d=e?.origin||a.headers?.get("origin")||"";if(!d)throw new Y("BAD_REQUEST",{message:"origin missing"});let c=a.body.response,u=await a.getSignedCookie(o.advanced.webAuthnChallengeCookie,a.context.secret);if(!u)throw new Y("BAD_REQUEST",{message:A.CHALLENGE_NOT_FOUND});let l=await a.context.internalAdapter.findVerificationValue(u);if(!l)throw new Y("BAD_REQUEST",{message:A.CHALLENGE_NOT_FOUND});let{expectedChallenge:K}=JSON.parse(l.value),m=await a.context.adapter.findOne({model:"passkey",where:[{field:"id",value:c.id}]});if(!m)throw new Y("UNAUTHORIZED",{message:A.PASSKEY_NOT_FOUND});try{let C=await cn({response:c,expectedChallenge:K,expectedOrigin:d,expectedRPID:o.rpID,authenticator:{credentialID:m.id,credentialPublicKey:new Uint8Array(Buffer.from(m.publicKey,"base64")),counter:m.counter,transports:m.transports?.split(",")},requireUserVerification:!1}),{verified:N}=C;if(!N)throw new Y("UNAUTHORIZED",{message:A.AUTHENTICATION_FAILED});await a.context.adapter.update({model:"passkey",where:[{field:"id",value:m.id}],update:{counter:C.authenticationInfo.newCounter}});let w=await a.context.internalAdapter.createSession(m.userId,a.request);if(!w)throw new Y("INTERNAL_SERVER_ERROR",{message:A.UNABLE_TO_CREATE_SESSION});let R=await a.context.internalAdapter.findUserById(m.userId);if(!R)throw new Y("INTERNAL_SERVER_ERROR",{message:"User not found"});return await f(a,{session:w,user:R}),a.json({session:w},{status:200})}catch(C){throw a.context.logger.error("Failed to verify authentication",C),new Y("BAD_REQUEST",{message:A.AUTHENTICATION_FAILED})}}),listPasskeys:p("/passkey/list-user-passkeys",{method:"GET",use:[I]},async a=>{let d=await a.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:a.context.session.user.id}]});return a.json(d,{status:200})}),deletePasskey:p("/passkey/delete-passkey",{method:"POST",body:re.object({id:re.string()}),use:[I]},async a=>(await a.context.adapter.delete({model:"passkey",where:[{field:"id",value:a.body.id}]}),a.json(null,{status:200}))),updatePasskey:p("/passkey/update-passkey",{method:"POST",body:re.object({id:re.string(),name:re.string()}),use:[I]},async a=>{let d=await a.context.adapter.findOne({model:"passkey",where:[{field:"id",value:a.body.id}]});if(!d)throw new Y("NOT_FOUND",{message:A.PASSKEY_NOT_FOUND});if(d.userId!==a.context.session.user.id)throw new Y("UNAUTHORIZED",{message:A.YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY});let c=await a.context.adapter.update({model:"passkey",where:[{field:"id",value:a.body.id}],update:{name:a.body.name}});if(!c)throw new Y("INTERNAL_SERVER_ERROR",{message:A.FAILED_TO_UPDATE_PASSKEY});return a.json({passkey:c},{status:200})})},schema:ie(Kn,e?.schema),$ERROR_CODES:A}},Kn={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}}}};import{z as Ao}from"zod";import{APIError as Ue}from"better-call";var ct=()=>{let e={INVALID_USERNAME_OR_PASSWORD:"invalid username or password",EMAIL_NOT_VERIFIED:"email not verified",UNEXPECTED_ERROR:"unexpected error",USERNAME_IS_ALREADY_TAKEN:"username is already taken. please try another."};return{id:"username",endpoints:{signInUsername:p("/sign-in/username",{method:"POST",body:Ao.object({username:Ao.string({description:"The username of the user"}),password:Ao.string({description:"The password of the user"}),rememberMe:Ao.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 i=>{let t=await i.context.adapter.findOne({model:"user",where:[{field:"username",value:i.body.username.toLowerCase()}]});if(!t)throw await i.context.password.hash(i.body.password),i.context.logger.error("User not found",{username:ct}),new Ue("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});if(!t.emailVerified&&i.context.options.emailAndPassword?.requireEmailVerification)throw await yo(i,t),new Ue("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});let o=await i.context.adapter.findOne({model:"account",where:[{field:"userId",value:t.id},{field:"providerId",value:"credential"}]});if(!o)throw new Ue("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});let r=o?.password;if(!r)throw i.context.logger.error("Password not found",{username:ct}),new Ue("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});if(!await i.context.password.verify({hash:r,password:i.body.password}))throw i.context.logger.error("Invalid password"),new Ue("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});let s=await i.context.internalAdapter.createSession(t.id,i.request,i.body.rememberMe===!1);return s?(await f(i,{session:s,user:t},i.body.rememberMe===!1),i.json({id:t.id,email:t.email,name:t.name,image:t.image,emailVerified:t.emailVerified,createdAt:t.createdAt,updatedAt:t.updatedAt})):i.json(null,{status:500,body:{message:g.FAILED_TO_CREATE_SESSION,status:500}})})},schema:{user:{fields:{username:{type:"string",required:!1,unique:!0,returned:!0,transform:{input(i){return i?.toString().toLowerCase()}}}}}},hooks:{before:[{matcher(i){return i.path==="/sign-up/email"},async handler(i){let t=i.body.username;if(t&&await i.context.adapter.findOne({model:"user",where:[{field:"username",value:t.toLowerCase()}]}))throw new Ue("UNPROCESSABLE_ENTITY",{message:e.USERNAME_IS_ALREADY_TAKEN})}}]},$ERROR_CODES:W}};import"better-call";var Vl=()=>({id:"bearer",hooks:{before:[{matcher(e){return!!(e.request?.headers.get("authorization")||e.headers?.get("authorization"))},handler:async e=>{let i=e.request?.headers.get("authorization")?.replace("Bearer ","")||e.headers?.get("authorization")?.replace("Bearer ","");if(!(!i||!i.includes(".")))return e.request&&e.request.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${i.replace("=","")}`),e.headers&&e.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${i.replace("=","")}`),{context:e}}}],after:[{matcher(e){return!!e.responseHeader.get("set-cookie")},handler:k(async e=>{let i=e.responseHeader.get("set-cookie");if(!i)return;let t=Ce(i),o=e.context.authCookies.sessionToken.name,r=t.get(o);if(!r||!r.value||r["max-age"]===0)return;let n=r.value;return e.responseHeader.set("set-auth-token",n),{responseHeader:e.responseHeader}})}]}});import{z as _e}from"zod";import{APIError as un}from"better-call";var Wl=e=>({id:"magic-link",endpoints:{signInMagicLink:p("/sign-in/magic-link",{method:"POST",requireHeaders:!0,body:_e.object({email:_e.string({description:"Email address to send the magic link"}).email(),callbackURL:_e.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 i=>{let{email:t}=i.body;if(e.disableSignUp&&!await i.context.internalAdapter.findUserByEmail(t))throw new un("BAD_REQUEST",{message:g.USER_NOT_FOUND});let o=F(32,V("a-z","A-Z"));await i.context.internalAdapter.createVerificationValue({identifier:o,value:t,expiresAt:new Date(Date.now()+(e.expiresIn||60*5)*1e3)});let r=`${i.context.baseURL}/magic-link/verify?token=${o}&callbackURL=${i.body.callbackURL||"/"}`;return await e.sendMagicLink({email:t,url:r,token:o},i.request),i.json({status:!0})}),magicLinkVerify:p("/magic-link/verify",{method:"GET",query:_e.object({token:_e.string({description:"Verification token"}),callbackURL:_e.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 i=>{let{token:t,callbackURL:o}=i.query,r=o?.startsWith("http")?o:o?`${i.context.options.baseURL}${o}`:i.context.options.baseURL,n=await i.context.internalAdapter.findVerificationValue(t);if(!n)throw i.redirect(`${r}?error=INVALID_TOKEN`);if(n.expiresAt<new Date)throw await i.context.internalAdapter.deleteVerificationValue(n.id),i.redirect(`${r}?error=EXPIRED_TOKEN`);await i.context.internalAdapter.deleteVerificationValue(n.id);let s=n.value,A=await i.context.internalAdapter.findUserByEmail(s),a=A?.user.id||"";if(!A){if(e.disableSignUp)throw i.redirect(`${r}?error=failed_to_create_user`);if(a=(await i.context.internalAdapter.createUser({email:s,emailVerified:!0,name:s})).id,!a)throw i.redirect(`${r}?error=failed_to_create_user`)}let d=await i.context.internalAdapter.createSession(a,i.headers);if(!d)throw i.redirect(`${r}?error=failed_to_create_session`);if(await f(i,{session:d,user:A?.user}),!o)return i.json({session:d,user:A?.user});throw i.redirect(o)})},rateLimit:[{pathMatcher(i){return i.startsWith("/sign-in/magic-link")||i.startsWith("/magic-link/verify")},window:e.rateLimit?.window||60,max:e.rateLimit?.max||5}]});import{z as Ae}from"zod";import{APIError as J}from"better-call";function ln(e){return F(e,V("0-9"))}var am=e=>{let i={expiresIn:e?.expiresIn||300,otpLength:e?.otpLength||6,...e,phoneNumber:"phoneNumber",phoneNumberVerified:"phoneNumberVerified",code:"code",createdAt:"createdAt"},t={INVALID_PHONE_NUMBER:"Invalid phone number",INVALID_PHONE_NUMBER_OR_PASSWORD:"Invalid phone number or password",UNEXPECTED_ERROR:"Unexpected error",OTP_NOT_FOUND:"OTP not found"};return{id:"phone-number",endpoints:{signInPhoneNumber:p("/sign-in/phone-number",{method:"POST",body:Ae.object({phoneNumber:Ae.string({description:"Phone number to sign in"}),password:Ae.string({description:"Password to use for sign in"}),rememberMe:Ae.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:r,phoneNumber:n}=o.body;if(i.phoneNumberValidator&&!await i.phoneNumberValidator(o.body.phoneNumber))throw new J("BAD_REQUEST",{message:t.INVALID_PHONE_NUMBER});let s=await o.context.adapter.findOne({model:"user",where:[{field:"phoneNumber",value:n}]});if(!s)throw new J("UNAUTHORIZED",{message:t.INVALID_PHONE_NUMBER_OR_PASSWORD});let a=(await o.context.internalAdapter.findAccountByUserId(s.id)).find(l=>l.providerId==="credential");if(!a)throw o.context.logger.error("Credential account not found",{phoneNumber:n}),new J("UNAUTHORIZED",{message:t.INVALID_PHONE_NUMBER_OR_PASSWORD});let d=a?.password;if(!d)throw o.context.logger.error("Password not found",{phoneNumber:n}),new J("UNAUTHORIZED",{message:t.UNEXPECTED_ERROR});if(!await o.context.password.verify({hash:d,password:r}))throw o.context.logger.error("Invalid password"),new J("UNAUTHORIZED",{message:t.INVALID_PHONE_NUMBER_OR_PASSWORD});let u=await o.context.internalAdapter.createSession(s.id,o.headers,o.body.rememberMe===!1);if(!u)throw o.context.logger.error("Failed to create session"),new J("UNAUTHORIZED",{message:g.FAILED_TO_CREATE_SESSION});return await f(o,{session:u,user:s},o.body.rememberMe===!1),o.json({user:s,session:u})}),sendPhoneNumberOTP:p("/phone-number/send-otp",{method:"POST",body:Ae.object({phoneNumber:Ae.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 J("NOT_IMPLEMENTED",{message:"sendOTP not implemented"});if(i.phoneNumberValidator&&!await i.phoneNumberValidator(o.body.phoneNumber))throw new J("BAD_REQUEST",{message:t.INVALID_PHONE_NUMBER});let r=ln(i.otpLength);return await o.context.internalAdapter.createVerificationValue({value:r,identifier:o.body.phoneNumber,expiresAt:P(i.expiresIn,"sec")}),await e.sendOTP({phoneNumber:o.body.phoneNumber,code:r},o.request),o.json({code:r},{body:{message:"Code sent"}})}),verifyPhoneNumber:p("/phone-number/verify",{method:"POST",body:Ae.object({phoneNumber:Ae.string({description:"Phone number to verify"}),code:Ae.string({description:"OTP code"}),disableSession:Ae.boolean({description:"Disable session creation after verification"}).optional(),updatePhoneNumber:Ae.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 r=await o.context.internalAdapter.findVerificationValue(o.body.phoneNumber);if(!r||r.expiresAt<new Date)throw r&&r.expiresAt<new Date?(await o.context.internalAdapter.deleteVerificationValue(r.id),new J("BAD_REQUEST",{message:"OTP expired"})):new J("BAD_REQUEST",{message:t.OTP_NOT_FOUND});if(r.value!==o.body.code)throw new J("BAD_REQUEST",{message:"Invalid OTP"});if(await o.context.internalAdapter.deleteVerificationValue(r.id),o.body.updatePhoneNumber){let s=await S(o);if(!s)throw new J("UNAUTHORIZED",{message:g.USER_NOT_FOUND});let A=await o.context.internalAdapter.updateUser(s.user.id,{[i.phoneNumber]:o.body.phoneNumber,[i.phoneNumberVerified]:!0});return o.json({user:A,session:s.session})}let n=await o.context.adapter.findOne({model:"user",where:[{value:o.body.phoneNumber,field:i.phoneNumber}]});if(await e?.callbackOnVerification?.({phoneNumber:o.body.phoneNumber,user:n},o.request),n)n=await o.context.internalAdapter.updateUser(n.id,{[i.phoneNumberVerified]:!0});else if(e?.signUpOnVerification){if(n=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,[i.phoneNumber]:o.body.phoneNumber,[i.phoneNumberVerified]:!0}),!n)throw new J("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_CREATE_USER})}else return o.json(null);if(!n)throw new J("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_UPDATE_USER});if(!o.body.disableSession){let s=await o.context.internalAdapter.createSession(n.id,o.request);if(!s)throw new J("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_CREATE_SESSION});return await f(o,{session:s,user:n}),o.json({user:n,session:s})}return o.json({user:n,session:null})})},schema:ie(mn,e?.schema),$ERROR_CODES:t}},mn={user:{fields:{phoneNumber:{type:"string",required:!1,unique:!0,returned:!0},phoneNumberVerified:{type:"boolean",required:!1,returned:!0,input:!1}}}};var gn={user:{fields:{isAnonymous:{type:"boolean",required:!1}}}},um=e=>{let i={FAILED_TO_CREATE_USER:"Failed to create user",COULD_NOT_CREATE_SESSION:"Could not create session",ANONYMOUS_USERS_CANNOT_SIGN_IN_AGAIN_ANONYMOUSLY:"Anonymous users cannot sign in again anonymously"};return{id:"anonymous",endpoints:{signInAnonymous:p("/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=be(t.context.baseURL)}=e||{},r=t.context.generateId({model:"user"}),n=`temp-${r}@${o}`,s=await t.context.internalAdapter.createUser({id:r,email:n,emailVerified:!1,isAnonymous:!0,name:"Anonymous",createdAt:new Date,updatedAt:new Date});if(!s)return t.json(null,{status:500,body:{message:i.FAILED_TO_CREATE_USER,status:500}});let A=await t.context.internalAdapter.createSession(s.id,t.request);return A?(await f(t,{session:A,user:s}),t.json({id:s.id,email:s.email,emailVerified:s.emailVerified,name:s.name,createdAt:s.createdAt,updatedAt:s.updatedAt})):t.json(null,{status:400,body:{message:i.COULD_NOT_CREATE_SESSION}})})},hooks:{after:[{matcher(t){return!!t.responseHeader.get("set-cookie")?.includes(t.context.authCookies.sessionToken.name)},handler:k(async t=>{let r=t.responseHeader.get("set-cookie"),n=t.context.authCookies.sessionToken.name;if(!Ce(r||"").get(n)?.value.split(".")[0])return;let A=await S(t,{disableRefresh:!0});if(!A||!A.user.isAnonymous)return;if(t.path==="/sign-in/anonymous")throw new b("BAD_REQUEST",{message:i.ANONYMOUS_USERS_CANNOT_SIGN_IN_AGAIN_ANONYMOUSLY});let a=t.context.newSession;a&&(e?.onLinkAccount&&await e?.onLinkAccount?.({anonymousUser:A,newUser:a}),e?.disableDeleteAnonymousUser||await t.context.internalAdapter.deleteUser(A.user.id))})}]},schema:ie(gn,e?.schema),$ERROR_CODES:i}};import{z as O}from"zod";import{APIError as fn}from"better-call";var pt=async e=>{let i=e.context.returned;return i?i instanceof Response?i.status!==200?null:await i.clone().json():i instanceof fn?null:i:null};var Em=e=>{let i={defaultRole:"user",adminRole:"admin",...e},t={FAILED_TO_CREATE_USER:"Failed to create user",USER_ALREADY_EXISTS:"User already exists",USER_NOT_FOUND:"User not found",YOU_CANNOT_BAN_YOURSELF:"You cannot ban yourself",ONLY_ADMINS_CAN_ACCESS_THIS_ENDPOINT:"Only admins can access this endpoint"},o=k(async r=>{let n=await S(r);if(!n?.session)throw new b("UNAUTHORIZED");let s=n.user;if(!s.role||(Array.isArray(i.adminRole)?!i.adminRole.includes(s.role):s.role!==i.adminRole))throw new b("FORBIDDEN",{message:"Only admins can access this endpoint"});return{session:{user:s,session:n.session}}});return{id:"admin",init(r){return{options:{databaseHooks:{user:{create:{async before(n){if(e?.defaultRole!==!1)return{data:{role:e?.defaultRole??"user",...n}}}}},session:{create:{async before(n){let s=await r.internalAdapter.findUserById(n.userId);if(s.banned){if(s.banExpires&&s.banExpires.getTime()<Date.now()){await r.internalAdapter.updateUser(n.userId,{banned:!1,banReason:null,banExpires:null});return}return!1}}}}}}}},hooks:{after:[{matcher(r){return r.path==="/list-sessions"},handler:k(async r=>{let n=await pt(r);if(!n)return;let s=n.filter(A=>!A.impersonatedBy);return r.json(s)})}]},endpoints:{setRole:p("/admin/set-role",{method:"POST",body:O.object({userId:O.string({description:"The user id"}),role:O.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 r=>{let n=await r.context.internalAdapter.updateUser(r.body.userId,{role:r.body.role});return r.json({user:n})}),createUser:p("/admin/create-user",{method:"POST",body:O.object({email:O.string({description:"The email of the user"}),password:O.string({description:"The password of the user"}),name:O.string({description:"The name of the user"}),role:O.string({description:"The role of the user"}),data:O.optional(O.record(O.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 r=>{if(await r.context.internalAdapter.findUserByEmail(r.body.email))throw new b("BAD_REQUEST",{message:t.USER_ALREADY_EXISTS});let s=await r.context.internalAdapter.createUser({email:r.body.email,name:r.body.name,role:r.body.role,...r.body.data});if(!s)throw new b("INTERNAL_SERVER_ERROR",{message:t.FAILED_TO_CREATE_USER});let A=await r.context.password.hash(r.body.password);return await r.context.internalAdapter.linkAccount({accountId:s.id,providerId:"credential",password:A,userId:s.id}),r.json({user:s})}),listUsers:p("/admin/list-users",{method:"GET",use:[o],query:O.object({searchValue:O.string({description:"The value to search for"}).optional(),searchField:O.enum(["email","name"],{description:"The field to search in, defaults to email. Can be `email` or `name`"}).optional(),searchOperator:O.enum(["contains","starts_with","ends_with"],{description:"The operator to use for the search. Can be `contains`, `starts_with` or `ends_with`"}).optional(),limit:O.string({description:"The number of users to return"}).or(O.number()).optional(),offset:O.string({description:"The offset to start from"}).or(O.number()).optional(),sortBy:O.string({description:"The field to sort by"}).optional(),sortDirection:O.enum(["asc","desc"],{description:"The direction to sort by"}).optional(),filterField:O.string({description:"The field to filter by"}).optional(),filterValue:O.string({description:"The value to filter by"}).or(O.number()).or(O.boolean()).optional(),filterOperator:O.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 r=>{let n=[];r.query?.searchValue&&n.push({field:r.query.searchField||"email",operator:r.query.searchOperator||"contains",value:r.query.searchValue}),r.query?.filterValue&&n.push({field:r.query.filterField||"email",operator:r.query.filterOperator||"eq",value:r.query.filterValue});try{let s=await r.context.internalAdapter.listUsers(Number(r.query?.limit)||void 0,Number(r.query?.offset)||void 0,r.query?.sortBy?{field:r.query.sortBy,direction:r.query.sortDirection||"asc"}:void 0,n.length?n:void 0);return r.json({users:s})}catch(s){return console.log(s),r.json({users:[]})}}),listUserSessions:p("/admin/list-user-sessions",{method:"POST",use:[o],body:O.object({userId:O.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 r=>({sessions:await r.context.internalAdapter.listSessions(r.body.userId)})),unbanUser:p("/admin/unban-user",{method:"POST",body:O.object({userId:O.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 r=>{let n=await r.context.internalAdapter.updateUser(r.body.userId,{banned:!1});return r.json({user:n})}),banUser:p("/admin/ban-user",{method:"POST",body:O.object({userId:O.string({description:"The user id"}),banReason:O.string({description:"The reason for the ban"}).optional(),banExpiresIn:O.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 r=>{if(r.body.userId===r.context.session.user.id)throw new b("BAD_REQUEST",{message:t.YOU_CANNOT_BAN_YOURSELF});let n=await r.context.internalAdapter.updateUser(r.body.userId,{banned:!0,banReason:r.body.banReason||e?.defaultBanReason||"No reason",banExpires:r.body.banExpiresIn?P(r.body.banExpiresIn,"sec"):e?.defaultBanExpiresIn?P(e.defaultBanExpiresIn,"sec"):void 0});return await r.context.internalAdapter.deleteSessions(r.body.userId),r.json({user:n})}),impersonateUser:p("/admin/impersonate-user",{method:"POST",body:O.object({userId:O.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 r=>{let n=await r.context.internalAdapter.findUserById(r.body.userId);if(!n)throw new b("NOT_FOUND",{message:"User not found"});let s=await r.context.internalAdapter.createSession(n.id,void 0,!0,{impersonatedBy:r.context.session.user.id,expiresAt:e?.impersonationSessionDuration?P(e.impersonationSessionDuration,"sec"):P(60*60,"sec")});if(!s)throw new b("INTERNAL_SERVER_ERROR",{message:t.FAILED_TO_CREATE_USER});let A=r.context.authCookies;return M(r),await r.setSignedCookie("admin_session",r.context.session.session.token,r.context.secret,A.sessionToken.options),await f(r,{session:s,user:n},!0),r.json({session:s,user:n})}),stopImpersonating:p("/admin/stop-impersonating",{method:"POST"},async r=>{let n=await S(r);if(!n)throw new b("UNAUTHORIZED");if(!n.session.impersonatedBy)throw new b("BAD_REQUEST",{message:"You are not impersonating anyone"});let s=await r.context.internalAdapter.findUserById(n.session.impersonatedBy);if(!s)throw new b("INTERNAL_SERVER_ERROR",{message:"Failed to find user"});let A=await r.getSignedCookie("admin_session",r.context.secret);if(!A)throw new b("INTERNAL_SERVER_ERROR",{message:"Failed to find admin session"});let a=await r.context.internalAdapter.findSession(A);if(!a||a.session.userId!==s.id)throw new b("INTERNAL_SERVER_ERROR",{message:"Failed to find admin session"});return await f(r,a),r.json(a)}),revokeUserSession:p("/admin/revoke-user-session",{method:"POST",body:O.object({sessionToken:O.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 r=>(await r.context.internalAdapter.deleteSession(r.body.sessionToken),r.json({success:!0}))),revokeUserSessions:p("/admin/revoke-user-sessions",{method:"POST",body:O.object({userId:O.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 r=>(await r.context.internalAdapter.deleteSessions(r.body.userId),r.json({success:!0}))),removeUser:p("/admin/remove-user",{method:"POST",body:O.object({userId:O.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 r=>(await r.context.internalAdapter.deleteUser(r.body.userId),r.json({success:!0})))},$ERROR_CODES:t,schema:ie(hn,i.schema)}},hn={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}}}};import{betterFetch as co}from"@better-fetch/fetch";import{APIError as ve}from"better-call";import{parseJWT as yn}from"oslo/jwt";import{z as ce}from"zod";async function Kt(e,i){if(e.idToken){let o=yn(e.idToken);if(o?.payload&&o.payload.sub&&o.payload.email)return{id:o.payload.sub,emailVerified:o.payload.email_verified,image:o.payload.picture,...o.payload}}if(!i)return null;let t=await co(i,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});return{id:t.data?.sub,emailVerified:t.data?.email_verified,email:t.data?.email,image:t.data?.picture,name:t.data?.name,...t.data}}var Lm=e=>{let i={INVALID_OAUTH_CONFIGURATION:"Invalid OAuth configuration"};return{id:"generic-oauth",init:t=>({context:{socialProviders:e.config.map(o=>{let r=o.tokenUrl,n=o.userInfoUrl;return{id:o.providerId,name:o.providerId,createAuthorizationURL(s){return v({id:o.providerId,options:{clientId:o.clientId,clientSecret:o.clientSecret,redirectURI:o.redirectURI},authorizationEndpoint:o.authorizationUrl,state:s.state,codeVerifier:o.pkce?s.codeVerifier:void 0,scopes:o.scopes||[],redirectURI:`${t.baseURL}/oauth2/callback/${o.providerId}`})},async validateAuthorizationCode(s){let A=o.tokenUrl;if(o.discoveryUrl){let a=await co(o.discoveryUrl,{method:"GET"});a.data&&(A=a.data.token_endpoint,n=a.data.userinfo_endpoint)}if(!A)throw new ve("BAD_REQUEST",{message:"Invalid OAuth configuration. Token URL not found."});return U({code:s.code,codeVerifier:s.codeVerifier,redirectURI:s.redirectURI,options:{clientId:o.clientId,clientSecret:o.clientSecret},tokenEndpoint:A})},async getUserInfo(s){if(!n)return null;let A=o.getUserInfo?await o.getUserInfo(s):await Kt(s,n);return A?{user:{id:A?.id,email:A?.email,emailVerified:A?.emailVerified,image:A?.image,name:A?.name,...o.mapProfileToUser?.(A)},data:A}:null}}})}}),endpoints:{signInWithOAuth2:p("/sign-in/oauth2",{method:"POST",query:ce.object({currentURL:ce.string({description:"Redirect to the current URL after sign in"}).optional()}).optional(),body:ce.object({providerId:ce.string({description:"The provider ID for the OAuth provider"}),callbackURL:ce.string({description:"The URL to redirect to after sign in"}).optional(),errorCallbackURL:ce.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,r=e.config.find(x=>x.providerId===o);if(!r)throw new ve("BAD_REQUEST",{message:`No config found for provider ${o}`});let{discoveryUrl:n,authorizationUrl:s,tokenUrl:A,clientId:a,clientSecret:d,scopes:c,redirectURI:u,responseType:l,pkce:K,prompt:m,accessType:C}=r,N=s,w=A;if(n){let x=await co(n,{onError(Qe){t.context.logger.error(Qe.error.message,Qe.error,{discoveryUrl:n})}});x.data&&(N=x.data.authorization_endpoint,w=x.data.token_endpoint)}if(!N||!w)throw new ve("BAD_REQUEST",{message:i.INVALID_OAUTH_CONFIGURATION});let{state:R,codeVerifier:h}=await Oe(t),T=await v({id:o,options:{clientId:a,clientSecret:d,redirectURI:u},authorizationEndpoint:N,state:R,codeVerifier:K?h:void 0,scopes:c||[],redirectURI:`${t.context.baseURL}/oauth2/callback/${o}`});return l&&l!=="code"&&T.searchParams.set("response_type",l),m&&T.searchParams.set("prompt",m),C&&T.searchParams.set("access_type",C),t.json({url:T.toString(),redirect:!0})}),oAuth2Callback:p("/oauth2/callback/:providerId",{method:"GET",query:ce.object({code:ce.string({description:"The OAuth2 code"}).optional(),error:ce.string({description:"The error message, if any"}).optional(),state:ce.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(h=>h.providerId===t.params.providerId);if(!o)throw new ve("BAD_REQUEST",{message:`No config found for provider ${t.params.providerId}`});let r,n=await Xe(t),{callbackURL:s,codeVerifier:A,errorURL:a}=n,d=t.query.code,c=o.tokenUrl,u=o.userInfoUrl;if(o.discoveryUrl){let h=await co(o.discoveryUrl,{method:"GET"});h.data&&(c=h.data.token_endpoint,u=h.data.userinfo_endpoint)}try{if(!c)throw new ve("BAD_REQUEST",{message:"Invalid OAuth configuration."});r=await U({code:d,codeVerifier:A,redirectURI:`${t.context.baseURL}/oauth2/callback/${o.providerId}`,options:{clientId:o.clientId,clientSecret:o.clientSecret},tokenEndpoint:c})}catch(h){throw t.context.logger.error(h&&typeof h=="object"&&"name"in h?h.name:"",h),t.redirect(`${a}?error=oauth_code_verification_failed`)}if(!r)throw new ve("BAD_REQUEST",{message:"Invalid OAuth configuration."});let l=o.getUserInfo?await o.getUserInfo(r):await Kt(r,u);if(!l?.email)throw t.context.logger.error("Unable to get user info",l),t.redirect(`${t.context.baseURL}/error?error=email_is_missing`);let K=o.mapProfileToUser?await o.mapProfileToUser(l):null,m=await Re(t,{userInfo:{...l,...K},account:{providerId:o.providerId,accountId:l.id,...r,scope:r.scopes?.join(",")}});function C(h){throw t.redirect(`${a||s||`${t.context.baseURL}/error`}?error=${h}`)}if(m.error)return C(m.error.split(" ").join("_"));let{session:N,user:w}=m.data;await f(t,{session:N,user:w});let R;try{R=new URL(s).toString()}catch{R=s}throw t.redirect(R)})},$ERROR_CODES:i}};import{z as He}from"zod";var ut={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0}}}},jm=He.object({id:He.string(),publicKey:He.string(),privateKey:He.string(),createdAt:He.date()});var Io=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 i=>await e.create({model:"jwks",data:{...i,createdAt:new Date}})});import{exportJWK as lt,generateKeyPair as wn,importJWK as Cn,SignJWT as bn}from"jose";var Qm=e=>({id:"jwt",endpoints:{getJwks:p("/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 i=>{let o=await Io(i.context.adapter).getAllKeys();return i.json({keys:o.map(r=>({...JSON.parse(r.publicKey),kid:r.id}))})}),getToken:p("/token",{method:"GET",requireHeaders:!0,use:[I],metadata:{openapi:{description:"Get a JWT token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async i=>{let t=Io(i.context.adapter),o=await t.getLatestKey(),r=!e?.jwks?.disablePrivateKeyEncryption;if(o===void 0){let{publicKey:d,privateKey:c}=await wn(e?.jwks?.keyPairConfig?.alg??"EdDSA",e?.jwks?.keyPairConfig??{crv:"Ed25519",extractable:!0}),u=await lt(d),l=await lt(c),K=JSON.stringify(l),m={id:crypto.randomUUID(),publicKey:JSON.stringify(u),privateKey:r?JSON.stringify(await le({key:i.context.options.secret,data:K})):K,createdAt:new Date};o=await t.createJwk(m)}let n=r?await fe({key:i.context.options.secret,data:JSON.parse(o.privateKey)}):o.privateKey,s=await Cn(JSON.parse(n)),A=e?.jwt?.definePayload?await e?.jwt.definePayload(i.context.session.user):i.context.session.user,a=await new bn({...A,...i.context.session.session.impersonatedBy?{impersonatedBy:i.context.session.session.impersonatedBy}:{}}).setProtectedHeader({alg:e?.jwks?.keyPairConfig?.alg??"EdDSA",kid:o.id}).setIssuedAt().setIssuer(e?.jwt?.issuer??i.context.options.baseURL).setAudience(e?.jwt?.audience??i.context.options.baseURL).setExpirationTime(e?.jwt?.expirationTime??"15m").setSubject(i.context.session.user.id).sign(s);return i.json({token:a})})},schema:ie(ut,e?.schema)});import{z as po}from"zod";var Xm=e=>{let i={maximumSessions:5,...e},t=r=>r.includes("_multi-"),o={INVALID_SESSION_TOKEN:"Invalid session token"};return{id:"multi-session",endpoints:{listDeviceSessions:p("/multi-session/list-device-sessions",{method:"GET",requireHeaders:!0},async r=>{let n=r.headers?.get("cookie");if(!n)return r.json([]);let s=Object.fromEntries(Ne(n)),A=(await Promise.all(Object.entries(s).filter(([c])=>t(c)).map(async([c])=>await r.getSignedCookie(c,r.context.secret)))).filter(c=>c!==void 0);if(!A.length)return r.json([]);let d=(await r.context.internalAdapter.findSessions(A)).filter(c=>c&&c.session.expiresAt>new Date);return r.json(d)}),setActiveSession:p("/multi-session/set-active",{method:"POST",body:po.object({sessionToken:po.string({description:"The session token to set as active"})}),requireHeaders:!0,use:[I],metadata:{openapi:{description:"Set the active session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async r=>{let n=r.body.sessionToken,s=`${r.context.authCookies.sessionToken.name}_multi-${n}`;if(!await r.getSignedCookie(s,r.context.secret))throw new b("UNAUTHORIZED",{message:o.INVALID_SESSION_TOKEN});let a=await r.context.internalAdapter.findSession(n);if(!a||a.session.expiresAt<new Date)throw r.setCookie(s,"",{...r.context.authCookies.sessionToken.options,maxAge:0}),new b("UNAUTHORIZED",{message:o.INVALID_SESSION_TOKEN});return await f(r,a),r.json(a)}),revokeDeviceSession:p("/multi-session/revoke",{method:"POST",body:po.object({sessionToken:po.string({description:"The session token to revoke"})}),requireHeaders:!0,use:[I],metadata:{openapi:{description:"Revoke a device session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async r=>{let n=r.body.sessionToken,s=`${r.context.authCookies.sessionToken.name}_multi-${n}`;if(!await r.getSignedCookie(s,r.context.secret))throw new b("UNAUTHORIZED",{message:o.INVALID_SESSION_TOKEN});if(await r.context.internalAdapter.deleteSession(n),r.setCookie(s,"",{...r.context.authCookies.sessionToken.options,maxAge:0}),!(r.context.session?.session.token===n))return r.json({success:!0});let d=r.headers?.get("cookie");if(d){let c=Object.fromEntries(Ne(d)),u=(await Promise.all(Object.entries(c).filter(([K])=>t(K)).map(async([K])=>await r.getSignedCookie(K,r.context.secret)))).filter(K=>K!==void 0),l=r.context.internalAdapter;if(u.length>0){let m=(await l.findSessions(u)).filter(C=>C&&C.session.expiresAt>new Date);if(m.length>0){let C=m[0];await f(r,C)}else M(r)}else M(r)}else M(r);return r.json({success:!0})})},hooks:{after:[{matcher:()=>!0,handler:k(async r=>{let n=r.responseHeader.get("set-cookie");if(!n)return;let s=Ce(n),A=r.context.authCookies.sessionToken,a=s.get(A.name)?.value;if(!a)return;let d=Ne(r.headers?.get("cookie")||""),c=a.split(".")[0];if(!c)return;let u=`${A.name}_multi-${c}`;s.get(u)||d.get(u)||Object.keys(Object.fromEntries(d)).filter(t).length+(n.includes("session_token")?1:0)>i.maximumSessions||await r.setSignedCookie(u,c,r.context.secret,A.options)})},{matcher:r=>r.path==="/sign-out",handler:k(async r=>{let n=r.headers?.get("cookie");if(!n)return;let s=Object.fromEntries(Ne(n)),A=Object.keys(s).map(a=>t(a)?(r.setCookie(a,"",{maxAge:0}),a.split("_multi-")[1]):null).filter(a=>a!==null);await r.context.internalAdapter.deleteSessions(A)})}]},$ERROR_CODES:o}};import{z as B}from"zod";var So=["email-verification","sign-in","forget-password"],sg=e=>{let i={expireIn:300,otpLength:6,...e},t={OTP_EXPIRED:"otp expired",INVALID_OTP:"invalid otp",INVALID_EMAIL:"invalid email",USER_NOT_FOUND:"user not found"};return{id:"email-otp",endpoints:{sendVerificationOTP:p("/email-otp/send-verification-otp",{method:"POST",body:B.object({email:B.string({description:"Email address to send the OTP"}),type:B.enum(So,{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 b("BAD_REQUEST",{message:"send email verification is not implemented"});let r=o.body.email;if(!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r))throw new b("BAD_REQUEST",{message:t.INVALID_EMAIL});let s=F(i.otpLength,V("0-9"));return await o.context.internalAdapter.createVerificationValue({value:s,identifier:`${o.body.type}-otp-${r}`,expiresAt:P(i.expireIn,"sec")}).catch(async A=>{await o.context.internalAdapter.deleteVerificationByIdentifier(`${o.body.type}-otp-${r}`),await o.context.internalAdapter.createVerificationValue({value:s,identifier:`${o.body.type}-otp-${r}`,expiresAt:P(i.expireIn,"sec")})}),await e.sendVerificationOTP({email:r,otp:s,type:o.body.type},o.request),o.json({success:!0})}),createVerificationOTP:p("/email-otp/create-verification-otp",{method:"POST",body:B.object({email:B.string({description:"Email address to send the OTP"}),type:B.enum(So,{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 r=o.body.email,n=F(i.otpLength,V("0-9"));return await o.context.internalAdapter.createVerificationValue({value:n,identifier:`${o.body.type}-otp-${r}`,expiresAt:P(i.expireIn,"sec")}),n}),getVerificationOTP:p("/email-otp/get-verification-otp",{method:"GET",query:B.object({email:B.string({description:"Email address to get the OTP"}),type:B.enum(So)}),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 r=o.query.email,n=await o.context.internalAdapter.findVerificationValue(`${o.query.type}-otp-${r}`);return!n||n.expiresAt<new Date?o.json({otp:null}):o.json({otp:n.value})}),verifyEmailOTP:p("/email-otp/verify-email",{method:"POST",body:B.object({email:B.string({description:"Email address to verify"}),otp:B.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 r=o.body.email;if(!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r))throw new b("BAD_REQUEST",{message:t.INVALID_EMAIL});let s=await o.context.internalAdapter.findVerificationValue(`email-verification-otp-${r}`);if(!s)throw new b("BAD_REQUEST",{message:t.INVALID_OTP});if(s.expiresAt<new Date)throw await o.context.internalAdapter.deleteVerificationValue(s.id),new b("BAD_REQUEST",{message:t.OTP_EXPIRED});let A=o.body.otp;if(s.value!==A)throw new b("BAD_REQUEST",{message:t.INVALID_OTP});await o.context.internalAdapter.deleteVerificationValue(s.id);let a=await o.context.internalAdapter.findUserByEmail(r);if(!a)throw new b("BAD_REQUEST",{message:t.USER_NOT_FOUND});let d=await o.context.internalAdapter.updateUser(a.user.id,{email:r,emailVerified:!0});return o.json({id:d.id,email:d.email,emailVerified:d.emailVerified,name:d.name,image:d.image,createdAt:d.createdAt,updatedAt:d.updatedAt})}),signInEmailOTP:p("/sign-in/email-otp",{method:"POST",body:B.object({email:B.string({description:"Email address to sign in"}),otp:B.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 r=o.body.email,n=await o.context.internalAdapter.findVerificationValue(`sign-in-otp-${r}`);if(!n)throw new b("BAD_REQUEST",{message:t.INVALID_OTP});if(n.expiresAt<new Date)throw await o.context.internalAdapter.deleteVerificationValue(n.id),new b("BAD_REQUEST",{message:t.OTP_EXPIRED});let s=o.body.otp;if(n.value!==s)throw new b("BAD_REQUEST",{message:t.INVALID_OTP});await o.context.internalAdapter.deleteVerificationValue(n.id);let A=await o.context.internalAdapter.findUserByEmail(r);if(!A){if(i.disableSignUp)throw new b("BAD_REQUEST",{message:t.USER_NOT_FOUND});let d=await o.context.internalAdapter.createUser({email:r,emailVerified:!0,name:r}),c=await o.context.internalAdapter.createSession(d.id,o.request);return await f(o,{session:c,user:d}),o.json({user:d,session:c})}A.user.emailVerified||await o.context.internalAdapter.updateUser(A.user.id,{emailVerified:!0});let a=await o.context.internalAdapter.createSession(A.user.id,o.request);return await f(o,{session:a,user:A.user}),o.json({session:a,user:A})}),forgetPasswordEmailOTP:p("/forget-password/email-otp",{method:"POST",body:B.object({email:B.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 r=o.body.email;if(!await o.context.internalAdapter.findUserByEmail(r))throw new b("BAD_REQUEST",{message:t.USER_NOT_FOUND});let s=F(i.otpLength,V("0-9"));return await o.context.internalAdapter.createVerificationValue({value:s,identifier:`forget-password-otp-${r}`,expiresAt:P(i.expireIn,"sec")}),await e.sendVerificationOTP({email:r,otp:s,type:"forget-password"},o.request),o.json({success:!0})}),resetPasswordEmailOTP:p("/email-otp/reset-password",{method:"POST",body:B.object({email:B.string({description:"Email address to reset the password"}),otp:B.string({description:"OTP sent to the email"}),password:B.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 r=o.body.email,n=await o.context.internalAdapter.findUserByEmail(r);if(!n)throw new b("BAD_REQUEST",{message:t.USER_NOT_FOUND});let s=await o.context.internalAdapter.findVerificationValue(`forget-password-otp-${r}`);if(!s)throw new b("BAD_REQUEST",{message:t.INVALID_OTP});if(s.expiresAt<new Date)throw await o.context.internalAdapter.deleteVerificationValue(s.id),new b("BAD_REQUEST",{message:t.OTP_EXPIRED});let A=o.body.otp;if(s.value!==A)throw new b("BAD_REQUEST",{message:t.INVALID_OTP});await o.context.internalAdapter.deleteVerificationValue(s.id);let a=await o.context.password.hash(o.body.password);return await o.context.internalAdapter.updatePassword(n.user.id,a),o.json({success:!0})})},hooks:{after:[{matcher(o){return!!(o.path?.startsWith("/sign-up")&&i.sendVerificationOnSignUp)},async handler(o){let r=o.context.newSession;if(r?.user&&r.user.email&&r.user.emailVerified===!1){let n=F(i.otpLength,V("0-9"));await o.context.internalAdapter.createVerificationValue({value:n,identifier:`email-verification-otp-${r.user.email}`,expiresAt:P(i.expireIn,"sec")}),await e.sendVerificationOTP({email:r.user.email,otp:n,type:"email-verification"},o.request)}}}]},$ERROR_CODES:t}};import{z as gt}from"zod";import{betterFetch as On}from"@better-fetch/fetch";function mt(e){return e==="true"||e===!0}var lg=e=>({id:"one-tap",endpoints:{oneTapCallback:p("/one-tap/callback",{method:"POST",body:gt.object({idToken:gt.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 i=>{let{idToken:t}=i.body,{data:o,error:r}=await On("https://oauth2.googleapis.com/tokeninfo?id_token="+t);if(r)return i.json({error:"Invalid token"});let n=await i.context.internalAdapter.findUserByEmail(o.email);if(!n){if(e?.disableSignup)throw new b("BAD_GATEWAY",{message:"User not found"});let A=await i.context.internalAdapter.createOAuthUser({email:o.email,emailVerified:mt(o.email_verified),name:o.name,image:o.picture},{providerId:"google",accountId:o.sub});if(!A)throw new b("INTERNAL_SERVER_ERROR",{message:"Could not create user"});let a=await i.context.internalAdapter.createSession(A?.user.id,i.request);return await f(i,{user:A.user,session:a}),i.json({session:a,user:A})}let s=await i.context.internalAdapter.createSession(n.user.id,i.request);return await f(i,{user:n.user,session:s}),i.json({session:s,user:n})})}});import{z as Uo}from"zod";function Tn(){let e=ne.VERCEL_URL,i=ne.NETLIFY_URL,t=ne.RENDER_URL,o=ne.AWS_LAMBDA_FUNCTION_NAME,r=ne.GOOGLE_CLOUD_FUNCTION_NAME,n=ne.AZURE_FUNCTION_NAME;return e||i||t||o||r||n}var Cg=e=>({id:"oauth-proxy",endpoints:{oAuthProxy:p("/oauth-proxy-callback",{method:"GET",query:Uo.object({callbackURL:Uo.string({description:"The URL to redirect to after the proxy"}),cookies:Uo.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 i=>{let t=i.query.cookies,o=await fe({key:i.context.secret,data:t});throw i.setHeader("set-cookie",o),i.redirect(i.query.callbackURL)})},hooks:{after:[{matcher(i){return i.path?.startsWith("/callback")},handler:k(async i=>{let t=i.context.returned,o=t instanceof b?t.headers:null,r=o?.get("location");if(r?.includes("/oauth-proxy-callback?callbackURL")){if(!r.startsWith("http"))return;let n=new URL(r);if(n.origin===be(i.context.baseURL)){let c=n.searchParams.get("callbackURL");if(!c)return;i.setHeader("location",c);return}let A=o?.get("set-cookie");if(!A)return;let a=await le({key:i.context.secret,data:A}),d=`${r}&cookies=${encodeURIComponent(a)}`;i.setHeader("location",d)}})}],before:[{matcher(i){return i.path?.startsWith("/sign-in/social")},async handler(i){let t=new URL(e?.currentURL||i.request?.url||Tn()||i.context.baseURL);return i.body.callbackURL=`${t.origin}${i.context.options.basePath||"/api/auth"}/oauth-proxy-callback?callbackURL=${encodeURIComponent(i.body.callbackURL||i.context.baseURL)}`,{context:i}}}]}});import{z as $e}from"zod";var Eg=(e,i)=>({id:"custom-session",endpoints:{getSession:p("/get-session",{method:"GET",metadata:{CUSTOM_SESSION:!0},query:$e.optional($e.object({disableCookieCache:$e.boolean({description:"Disable cookie cache and fetch session from database"}).or($e.string().transform(t=>t==="true")).optional(),disableRefresh:$e.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}))},async t=>{let o=await S(t);if(!o)return t.json(null);let r=await e(o);return t.json(r)})}});import{ZodObject as ht,ZodOptional as _o,ZodSchema as yt}from"zod";var ke=e=>{let i=e.plugins?.reduce((a,d)=>{let c=d.schema;if(!c)return a;for(let[u,l]of Object.entries(c))a[u]={fields:{...a[u]?.fields,...l.fields},modelName:l.modelName||u};return a},{}),t=e.rateLimit?.storage==="database",o={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:s,...A}=i||{};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"},...s?.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},...A,...t?o:{}}};import{z as Fg}from"zod";import{Kysely as qg,MssqlDialect as Hg}from"kysely";import{MysqlDialect as Gg,PostgresDialect as Qg,SqliteDialect as Zg}from"kysely";var Ge={};function wt(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 Ko(e){let i=[];return e.metadata?.openapi?.parameters?(i.push(...e.metadata.openapi.parameters),i):(e.query instanceof ht&&Object.entries(e.query.shape).forEach(([t,o])=>{o instanceof yt&&i.push({name:t,in:"query",schema:{type:wt(o),..."minLength"in o&&o.minLength?{minLength:o.minLength}:{},description:o.description}})}),i)}function ft(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof ht||e.body instanceof _o)){let i=e.body.shape;if(!i)return;let t={},o=[];return Object.entries(i).forEach(([r,n])=>{n instanceof yt&&(t[r]={type:wt(n),description:n.description},n instanceof _o||o.push(r))}),{required:e.body instanceof _o?!1:!!e.body,content:{"application/json":{schema:{type:"object",properties:t,required:o}}}}}}function uo(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 vo(e,i){let t=bo(e,{...i,plugins:[]}),o=ke(i),n={schemas:{...Object.entries(o).reduce((A,[a,d])=>{let c=a.charAt(0).toUpperCase()+a.slice(1);return A[c]={type:"object",properties:Object.entries(d.fields).reduce((u,[l,K])=>(u[l]={type:K.type},u),{})},A},{})}};Object.entries(t.api).forEach(([A,a])=>{let d=a.options;if(!d.metadata?.SERVER_ONLY&&(d.method==="GET"&&(Ge[a.path]={get:{tags:["Default",...d.metadata?.openapi?.tags||[]],description:d.metadata?.openapi?.description,operationId:d.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Ko(d),responses:uo(d.metadata?.openapi?.responses)}}),d.method==="POST")){let c=ft(d);Ge[a.path]={post:{tags:["Default",...d.metadata?.openapi?.tags||[]],description:d.metadata?.openapi?.description,operationId:d.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Ko(d),...c?{requestBody:c}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:uo(d.metadata?.openapi?.responses)}}}});for(let A of i.plugins||[]){if(A.id==="open-api")continue;let a=bo(e,{...i,plugins:[A]}),d=Object.keys(a.api).map(c=>t.api[c]===void 0?a.api[c]:null).filter(c=>c!==null);Object.entries(d).forEach(([c,u])=>{let l=u.options;l.metadata?.SERVER_ONLY||(l.method==="GET"&&(Ge[u.path]={get:{tags:l.metadata?.openapi?.tags||[A.id.charAt(0).toUpperCase()+A.id.slice(1)],description:l.metadata?.openapi?.description,operationId:l.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Ko(l),responses:uo(l.metadata?.openapi?.responses)}}),l.method==="POST"&&(Ge[u.path]={post:{tags:l.metadata?.openapi?.tags||[A.id.charAt(0).toUpperCase()+A.id.slice(1)],description:l.metadata?.openapi?.description,operationId:l.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Ko(l),requestBody:ft(l),responses:uo(l.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:Ge}}var Ct=`<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">
@@ -119,4 +119,4 @@ Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
119
119
  </script>
120
120
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
121
121
  </body>
122
- </html>`,Hf=e=>{let i=e?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:p("/open-api/generate-schema",{method:"GET"},async t=>{let o=await vo(t.context,t.context.options);return t.json(o)}),openAPIReference:p(i,{method:"GET",metadata:{isAction:!1}},async t=>{if(e?.disableDefaultReference)throw new b("NOT_FOUND");let o=await vo(t.context,t.context.options);return new Response(In(o),{headers:{"Content-Type":"text/html"}})})}}};export{Te as HIDE_METADATA,Tm as admin,Km as anonymous,Fl as bearer,p as createAuthEndpoint,k as createAuthMiddleware,Tg as customSession,ng as emailOTP,Dm as genericOAuth,an as getPasskeyActions,Gm as jwt,Zl as magicLink,Ym as multiSession,wg as oAuthProxy,ug as oneTap,Hf as openAPI,Po as optionsMiddleware,uK as organization,Rl as passkey,Kl as passkeyClient,sm as phoneNumber,Eu as twoFactor,su as twoFactorClient,ct as username};
122
+ </html>`,$f=e=>{let i=e?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:p("/open-api/generate-schema",{method:"GET"},async t=>{let o=await vo(t.context,t.context.options);return t.json(o)}),openAPIReference:p(i,{method:"GET",metadata:{isAction:!1}},async t=>{if(e?.disableDefaultReference)throw new b("NOT_FOUND");let o=await vo(t.context,t.context.options);return new Response(In(o),{headers:{"Content-Type":"text/html"}})})}}};export{Te as HIDE_METADATA,Em as admin,um as anonymous,Vl as bearer,p as createAuthEndpoint,k as createAuthMiddleware,Eg as customSession,sg as emailOTP,Lm as genericOAuth,an as getPasskeyActions,Qm as jwt,Wl as magicLink,Xm as multiSession,Cg as oAuthProxy,lg as oneTap,$f as openAPI,Po as optionsMiddleware,lK as organization,Il as passkey,ul as passkeyClient,am as phoneNumber,Ru as twoFactor,au as twoFactorClient,ct as username};