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.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var hr=Object.create;var Ao=Object.defineProperty;var yr=Object.getOwnPropertyDescriptor;var wr=Object.getOwnPropertyNames;var Cr=Object.getPrototypeOf,br=Object.prototype.hasOwnProperty;var Or=(e,i)=>{for(var t in i)Ao(e,t,{get:i[t],enumerable:!0})},Ai=(e,i,t,o)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of wr(i))!br.call(e,r)&&r!==t&&Ao(e,r,{get:()=>i[r],enumerable:!(o=yr(i,r))||o.enumerable});return e};var So=(e,i,t)=>(t=e!=null?hr(Cr(e)):{},Ai(i||!e||!e.__esModule?Ao(t,"default",{value:e,enumerable:!0}):t,e)),Tr=e=>Ai(Ao({},"__esModule",{value:!0}),e);var Vn={};Or(Vn,{HIDE_METADATA:()=>Ee,admin:()=>In,anonymous:()=>Rn,bearer:()=>wn,createAuthEndpoint:()=>p,createAuthMiddleware:()=>v,customSession:()=>Ln,emailOTP:()=>kn,genericOAuth:()=>Un,getPasskeyActions:()=>ir,jwt:()=>_n,magicLink:()=>Cn,multiSession:()=>vn,oAuthProxy:()=>Dn,oneTap:()=>Pn,openAPI:()=>Fn,optionsMiddleware:()=>Uo,organization:()=>dn,passkey:()=>hn,passkeyClient:()=>fn,phoneNumber:()=>On,twoFactor:()=>ln,twoFactorClient:()=>un,username:()=>ii});module.exports=Tr(Vn);var Zo=require("better-call"),Ve=require("zod");var Te=require("better-call"),Uo=(0,Te.createMiddleware)(async()=>({})),v=(0,Te.createMiddlewareCreator)({use:[Uo,(0,Te.createMiddleware)(async()=>({}))]}),p=(0,Te.createEndpointCreator)({use:[Uo]});var Q=require("better-call"),L=require("zod");var _r=require("oslo"),di=require("oslo/encoding");var co=require("oslo/crypto");async function Rr({value:e,secret:i}){return new co.HMAC("SHA-256").sign(new TextEncoder().encode(i),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function Ir({value:e,signature:i,secret:t}){return new co.HMAC("SHA-256").verify(new TextEncoder().encode(t),Buffer.from(i,"base64"),new TextEncoder().encode(e))}var po={sign:Rr,verify:Ir};var oe=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 Ko=Object.create(null),We=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Ko:globalThis),de=new Proxy(Ko,{get(e,i){return We()[i]??Ko[i]},has(e,i){let t=We();return i in t||i in Ko},set(e,i,t){let o=We(!0);return o[i]=t,!0},deleteProperty(e,i){if(!i)return!1;let t=We(!0);return delete t[i],!0},ownKeys(){let e=We(!0);return Object.keys(e)}});function Sr(e){return e?e!=="false":!1}var _o=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var uo=_o==="dev"||_o==="development",Ur=_o==="test"||Sr(de.TEST);function ke(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=di.base64url.encode(new TextEncoder().encode(JSON.stringify({session:i,expiresAt:P(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await po.sign({value:JSON.stringify(i),secret:e.context.secret})})),{includePadding:!1});if(A.length>4093)throw new oe("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 q(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}function Je(e){let i=e.split("; "),t=new Map;return i.forEach(o=>{let[r,n]=o.split("=");t.set(r,n)}),t}var mi=require("@better-fetch/fetch"),gi=require("better-call"),De=require("jose"),fi=require("oslo/jwt");var ci=require("oslo/crypto"),pi=require("oslo/encoding");async function Ki(e){let i=await(0,ci.sha256)(new TextEncoder().encode(e));return pi.base64url.encode(new Uint8Array(i),{includePadding:!1})}function lo(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 k({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 Ki(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}var ui=require("@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(0,ui.betterFetch)(r,{method:"POST",body:s,headers:A});if(d)throw d;return lo(a)}var mo=require("oslo/oauth2"),pe=require("zod"),vo=require("better-call");function Pe(e){try{return new URL(e).origin}catch{return null}}function li(e){return e.includes("://")?new URL(e).host:e}async function Ne(e,i){let t=e.body?.callbackURL||(e.query?.currentURL?Pe(e.query?.currentURL):"")||e.context.options.baseURL;if(!t)throw new vo.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,mo.generateCodeVerifier)(),r=(0,mo.generateState)(),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 vo.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:A.identifier,codeVerifier:o}}async function go(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.z.object({callbackURL:pe.z.string(),codeVerifier:pe.z.string(),errorURL:pe.z.string().optional(),newUserURL:pe.z.string().optional(),expiresAt:pe.z.number(),link:pe.z.object({email:pe.z.string(),userId:pe.z.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 hi=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=(0,De.decodeProtectedHeader)(t),{kid:n,alg:s}=r;if(!n||!s)return!1;let A=await vr(n),{payload:a}=await(0,De.jwtVerify)(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=(0,fi.parseJWT)(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}}}},vr=async e=>{let i="https://appleid.apple.com",t="/auth/keys",{data:o}=await(0,mi.betterFetch)(`${i}${t}`);if(!o?.keys)throw new gi.APIError("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(0,De.importJWK)(r,r.alg)};var yi=require("@better-fetch/fetch");var wi=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(0,yi.betterFetch)("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}}});var Ci=require("@better-fetch/fetch");var bi=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 k({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(0,Ci.betterFetch)("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}}});var ko=require("@better-fetch/fetch");var Oi=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),k({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(0,ko.betterFetch)("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(0,ko.betterFetch)("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}}}};var Ri=require("oslo/jwt");var Ti=require("consola"),Po=["info","success","warn","error","debug"];function kr(e,i){return Po.indexOf(i)<=Po.indexOf(e)}var Pr=(0,Ti.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Ei=e=>{let i=e?.disabled!==!0,t=e?.level??"error",o=(r,n,s=[])=>{if(!(!i||!kr(t,r))){if(!e||typeof e.log!="function"){Pr[r]("",n,...s);return}e.log(r==="success"?"info":r,n,s)}};return Object.fromEntries(Po.map(r=>[r,(...[n,...s])=>o(r,n,s)]))},re=Ei();var Ii=require("@better-fetch/fetch"),Si=e=>({id:"google",name:"Google",async createAuthorizationURL({state:i,scopes:t,codeVerifier:o,redirectURI:r}){if(!e.clientId||!e.clientSecret)throw re.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new oe("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new oe("codeVerifier is required for Google");let n=t||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await k({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(0,Ii.betterFetch)(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=(0,Ri.parseJWT)(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}}});var Ui=require("@better-fetch/fetch"),_i=require("oslo/jwt");var vi=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),k({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=(0,_i.parseJWT)(r.idToken)?.payload,s=e.profilePhotoSize||48;await(0,Ui.betterFetch)(`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){re.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}}}};var ki=require("@better-fetch/fetch");var Pi=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),k({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(0,ki.betterFetch)("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 Ee={isAction:!1};var Ni=require("nanoid"),G=e=>(0,Ni.nanoid)(e);var Di=require("oslo/jwt");var Li=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),k({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 re.error("No idToken found in token"),null;let o=(0,Di.parseJWT)(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}}});var Bi=require("@better-fetch/fetch");var xi=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(i){let t=i.scopes||["users.read","tweet.read","offline.access"];return e.scope&&t.push(...e.scope),k({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(0,Bi.betterFetch)("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}}});var ji=require("@better-fetch/fetch");var zi=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 k({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(0,ji.betterFetch)("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}}}};var Fi=require("@better-fetch/fetch");var Vi=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 k({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(0,Fi.betterFetch)("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}}}};var Mi=require("@better-fetch/fetch");var No=(e="")=>e.split("://").map(i=>i.replace(/\/{2,}/g,"/")).join("://"),Nr=e=>{let i=e||"https://gitlab.com";return{authorizationEndpoint:No(`${i}/oauth/authorize`),tokenEndpoint:No(`${i}/oauth/token`),userinfoEndpoint:No(`${i}/api/v4/user`)}},qi=e=>{let{authorizationEndpoint:i,tokenEndpoint:t,userinfoEndpoint:o}=Nr(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 k({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(0,Mi.betterFetch)(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}}}};var Do=require("@better-fetch/fetch");var Hi=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:i,scopes:t,redirectURI:o}){let r=t||["identity"];return e.scope&&r.push(...e.scope),k({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(0,Do.betterFetch)("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:r,body:o.toString()});if(s)throw s;return lo(n)},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let{data:t,error:o}=await(0,Do.betterFetch)("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 Dr={apple:hi,discord:wi,facebook:bi,github:Oi,microsoft:vi,google:Si,spotify:Pi,twitch:Li,twitter:xi,dropbox:zi,linkedin:Vi,gitlab:qi,reddit:Hi},fo=Object.keys(Dr);var Wi=require("oslo"),ho=require("oslo/jwt"),ne=require("zod");var Le=require("better-call");var Ke=require("better-call");var we=require("zod");function Lo(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 Bo=()=>p("/get-session",{method:"GET",query:we.z.optional(we.z.object({disableCookieCache:we.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(we.z.string().transform(e=>e==="true")).optional(),disableRefresh:we.z.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?Lo(Buffer.from(t,"base64").toString()):null;if(o&&!await po.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return q(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 q(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 q(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.APIError("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_GET_SESSION})}}),S=async(e,i)=>{if(e.context.session)return e.context.session;let t=await Bo()({...e,_flag:"json",headers:e.headers,query:i}).catch(o=>null);return e.context.session=t,t},I=v(async e=>{let i=await S(e);if(!i?.session)throw new Ke.APIError("UNAUTHORIZED");return{session:i}}),Ye=v(async e=>{let i=await S(e);if(!i?.session)throw new Ke.APIError("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.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:i}}),$i=()=>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)}),Gi=p("/revoke-session",{method:"POST",body:we.z.object({token:we.z.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.APIError("BAD_REQUEST",{message:"Session not found"});if(t.session.userId!==e.context.session.user.id)throw new Ke.APIError("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.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Qi=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.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Zi=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.APIError("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 ue(e,i,t){return await(0,ho.createJWT)("HS256",Buffer.from(e),{email:i.toLowerCase(),updateTo:t},{expiresIn:new Wi.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[i],includeIssuedTimestamp:!0})}async function xo(e,i){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Le.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await ue(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 Ji=p("/send-verification-email",{method:"POST",query:ne.z.object({currentURL:ne.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:ne.z.object({email:ne.z.string({description:"The email to send the verification email to"}).email(),callbackURL:ne.z.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.APIError("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.APIError("BAD_REQUEST",{message:g.USER_NOT_FOUND});return await xo(e,t.user),e.json({status:!0})}),Yi=p("/verify-email",{method:"GET",query:ne.z.object({token:ne.z.string({description:"The token to verify the email"}),callbackURL:ne.z.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.APIError("UNAUTHORIZED",{message:A})}let{token:t}=e.query,o;try{o=await(0,ho.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(A){return e.context.logger.error("Failed to verify email",A),i("invalid_token")}let n=ne.z.object({email:ne.z.string().email(),updateTo:ne.z.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 ue(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.APIError("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})});var W=require("better-call");var et=require("better-call");function jo(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function Lr(e){let i="";for(let t=0;t<e.length;t++)i+=jo(e[t]);return i}function Xi(e,i=!0){if(Array.isArray(e))return`(?:${e.map(c=>`^${Xi(c,i)}$`).join("|")})`;let t="",o="",r=".";i===!0?(t="/",o="[/\\\\]",r="[^/\\\\]"):i&&(t=i,o=Lr(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+=jo(c[K+1]),K++):m==="?"?a+=r:m==="*"?a+=`${r}*?`:a+=jo(m)}a+=l}}return a}function Br(e,i){if(typeof i!="string")throw new TypeError(`Sample must be a string, but ${typeof i} given`);return e.test(i)}function zo(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=Xi(e,i.separator),o=new RegExp(`^${t}$`,i.flags),r=Br.bind(null,o);return r.options=i,r.pattern=e,r.regexp=o,r}var xr=v(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("*")?zo(C)(li(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
+ "use strict";var hr=Object.create;var Ao=Object.defineProperty;var yr=Object.getOwnPropertyDescriptor;var wr=Object.getOwnPropertyNames;var Cr=Object.getPrototypeOf,br=Object.prototype.hasOwnProperty;var Or=(e,i)=>{for(var t in i)Ao(e,t,{get:i[t],enumerable:!0})},Ai=(e,i,t,o)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of wr(i))!br.call(e,r)&&r!==t&&Ao(e,r,{get:()=>i[r],enumerable:!(o=yr(i,r))||o.enumerable});return e};var So=(e,i,t)=>(t=e!=null?hr(Cr(e)):{},Ai(i||!e||!e.__esModule?Ao(t,"default",{value:e,enumerable:!0}):t,e)),Tr=e=>Ai(Ao({},"__esModule",{value:!0}),e);var Vn={};Or(Vn,{HIDE_METADATA:()=>Ee,admin:()=>In,anonymous:()=>Rn,bearer:()=>wn,createAuthEndpoint:()=>p,createAuthMiddleware:()=>v,customSession:()=>Ln,emailOTP:()=>kn,genericOAuth:()=>Un,getPasskeyActions:()=>ir,jwt:()=>_n,magicLink:()=>Cn,multiSession:()=>vn,oAuthProxy:()=>Dn,oneTap:()=>Pn,openAPI:()=>Fn,optionsMiddleware:()=>Uo,organization:()=>dn,passkey:()=>hn,passkeyClient:()=>fn,phoneNumber:()=>On,twoFactor:()=>ln,twoFactorClient:()=>un,username:()=>ii});module.exports=Tr(Vn);var Zo=require("better-call"),Ie=require("zod");var Te=require("better-call"),Uo=(0,Te.createMiddleware)(async()=>({})),v=(0,Te.createMiddlewareCreator)({use:[Uo,(0,Te.createMiddleware)(async()=>({}))]}),p=(0,Te.createEndpointCreator)({use:[Uo]});var Q=require("better-call"),L=require("zod");var _r=require("oslo"),di=require("oslo/encoding");var co=require("oslo/crypto");async function Rr({value:e,secret:i}){return new co.HMAC("SHA-256").sign(new TextEncoder().encode(i),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function Ir({value:e,signature:i,secret:t}){return new co.HMAC("SHA-256").verify(new TextEncoder().encode(t),Buffer.from(i,"base64"),new TextEncoder().encode(e))}var po={sign:Rr,verify:Ir};var oe=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 Ko=Object.create(null),We=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Ko:globalThis),de=new Proxy(Ko,{get(e,i){return We()[i]??Ko[i]},has(e,i){let t=We();return i in t||i in Ko},set(e,i,t){let o=We(!0);return o[i]=t,!0},deleteProperty(e,i){if(!i)return!1;let t=We(!0);return delete t[i],!0},ownKeys(){let e=We(!0);return Object.keys(e)}});function Sr(e){return e?e!=="false":!1}var _o=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var uo=_o==="dev"||_o==="development",Ur=_o==="test"||Sr(de.TEST);function Pe(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=di.base64url.encode(new TextEncoder().encode(JSON.stringify({session:i,expiresAt:P(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await po.sign({value:JSON.stringify(i),secret:e.context.secret})})),{includePadding:!1});if(A.length>4093)throw new oe("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 q(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}function Je(e){let i=e.split("; "),t=new Map;return i.forEach(o=>{let[r,n]=o.split("=");t.set(r,n)}),t}var mi=require("@better-fetch/fetch"),gi=require("better-call"),Le=require("jose"),fi=require("oslo/jwt");var ci=require("oslo/crypto"),pi=require("oslo/encoding");async function Ki(e){let i=await(0,ci.sha256)(new TextEncoder().encode(e));return pi.base64url.encode(new Uint8Array(i),{includePadding:!1})}function lo(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 k({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 Ki(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}var ui=require("@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(0,ui.betterFetch)(r,{method:"POST",body:s,headers:A});if(d)throw d;return lo(a)}var mo=require("oslo/oauth2"),pe=require("zod"),vo=require("better-call");function Ne(e){try{return new URL(e).origin}catch{return null}}function li(e){return e.includes("://")?new URL(e).host:e}async function De(e,i){let t=e.body?.callbackURL||(e.query?.currentURL?Ne(e.query?.currentURL):"")||e.context.options.baseURL;if(!t)throw new vo.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,mo.generateCodeVerifier)(),r=(0,mo.generateState)(),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 vo.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:A.identifier,codeVerifier:o}}async function go(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.z.object({callbackURL:pe.z.string(),codeVerifier:pe.z.string(),errorURL:pe.z.string().optional(),newUserURL:pe.z.string().optional(),expiresAt:pe.z.number(),link:pe.z.object({email:pe.z.string(),userId:pe.z.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 hi=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=(0,Le.decodeProtectedHeader)(t),{kid:n,alg:s}=r;if(!n||!s)return!1;let A=await vr(n),{payload:a}=await(0,Le.jwtVerify)(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=(0,fi.parseJWT)(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}}}},vr=async e=>{let i="https://appleid.apple.com",t="/auth/keys",{data:o}=await(0,mi.betterFetch)(`${i}${t}`);if(!o?.keys)throw new gi.APIError("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(0,Le.importJWK)(r,r.alg)};var yi=require("@better-fetch/fetch");var wi=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(0,yi.betterFetch)("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}}});var Ci=require("@better-fetch/fetch");var bi=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 k({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(0,Ci.betterFetch)("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}}});var ko=require("@better-fetch/fetch");var Oi=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),k({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(0,ko.betterFetch)("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(0,ko.betterFetch)("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}}}};var Ri=require("oslo/jwt");var Ti=require("consola"),Po=["info","success","warn","error","debug"];function kr(e,i){return Po.indexOf(i)<=Po.indexOf(e)}var Pr=(0,Ti.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Ei=e=>{let i=e?.disabled!==!0,t=e?.level??"error",o=(r,n,s=[])=>{if(!(!i||!kr(t,r))){if(!e||typeof e.log!="function"){Pr[r]("",n,...s);return}e.log(r==="success"?"info":r,n,s)}};return Object.fromEntries(Po.map(r=>[r,(...[n,...s])=>o(r,n,s)]))},re=Ei();var Ii=require("@better-fetch/fetch"),Si=e=>({id:"google",name:"Google",async createAuthorizationURL({state:i,scopes:t,codeVerifier:o,redirectURI:r}){if(!e.clientId||!e.clientSecret)throw re.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new oe("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new oe("codeVerifier is required for Google");let n=t||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await k({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(0,Ii.betterFetch)(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=(0,Ri.parseJWT)(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}}});var Ui=require("@better-fetch/fetch"),_i=require("oslo/jwt");var vi=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),k({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=(0,_i.parseJWT)(r.idToken)?.payload,s=e.profilePhotoSize||48;await(0,Ui.betterFetch)(`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){re.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}}}};var ki=require("@better-fetch/fetch");var Pi=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),k({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(0,ki.betterFetch)("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 Ee={isAction:!1};var Ni=require("nanoid"),G=e=>(0,Ni.nanoid)(e);var Di=require("oslo/jwt");var Li=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),k({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 re.error("No idToken found in token"),null;let o=(0,Di.parseJWT)(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}}});var Bi=require("@better-fetch/fetch");var xi=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(i){let t=i.scopes||["users.read","tweet.read","offline.access"];return e.scope&&t.push(...e.scope),k({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(0,Bi.betterFetch)("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}}});var ji=require("@better-fetch/fetch");var zi=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 k({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(0,ji.betterFetch)("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}}}};var Fi=require("@better-fetch/fetch");var Vi=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 k({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(0,Fi.betterFetch)("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}}}};var Mi=require("@better-fetch/fetch");var No=(e="")=>e.split("://").map(i=>i.replace(/\/{2,}/g,"/")).join("://"),Nr=e=>{let i=e||"https://gitlab.com";return{authorizationEndpoint:No(`${i}/oauth/authorize`),tokenEndpoint:No(`${i}/oauth/token`),userinfoEndpoint:No(`${i}/api/v4/user`)}},qi=e=>{let{authorizationEndpoint:i,tokenEndpoint:t,userinfoEndpoint:o}=Nr(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 k({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(0,Mi.betterFetch)(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}}}};var Do=require("@better-fetch/fetch");var Hi=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:i,scopes:t,redirectURI:o}){let r=t||["identity"];return e.scope&&r.push(...e.scope),k({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(0,Do.betterFetch)("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:r,body:o.toString()});if(s)throw s;return lo(n)},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let{data:t,error:o}=await(0,Do.betterFetch)("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 Dr={apple:hi,discord:wi,facebook:bi,github:Oi,microsoft:vi,google:Si,spotify:Pi,twitch:Li,twitter:xi,dropbox:zi,linkedin:Vi,gitlab:qi,reddit:Hi},fo=Object.keys(Dr);var Wi=require("oslo"),ho=require("oslo/jwt"),ne=require("zod");var Be=require("better-call");var Ke=require("better-call");var we=require("zod");function Lo(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 Bo=()=>p("/get-session",{method:"GET",query:we.z.optional(we.z.object({disableCookieCache:we.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(we.z.string().transform(e=>e==="true")).optional(),disableRefresh:we.z.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?Lo(Buffer.from(t,"base64").toString()):null;if(o&&!await po.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return q(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 q(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 q(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.APIError("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_GET_SESSION})}}),S=async(e,i)=>{if(e.context.session)return e.context.session;let t=await Bo()({...e,_flag:"json",headers:e.headers,query:i}).catch(o=>null);return e.context.session=t,t},I=v(async e=>{let i=await S(e);if(!i?.session)throw new Ke.APIError("UNAUTHORIZED");return{session:i}}),Ye=v(async e=>{let i=await S(e);if(!i?.session)throw new Ke.APIError("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.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:i}}),$i=()=>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)}),Gi=p("/revoke-session",{method:"POST",body:we.z.object({token:we.z.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.APIError("BAD_REQUEST",{message:"Session not found"});if(t.session.userId!==e.context.session.user.id)throw new Ke.APIError("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.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Qi=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.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Zi=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.APIError("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 ue(e,i,t){return await(0,ho.createJWT)("HS256",Buffer.from(e),{email:i.toLowerCase(),updateTo:t},{expiresIn:new Wi.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[i],includeIssuedTimestamp:!0})}async function xo(e,i){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Be.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await ue(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 Ji=p("/send-verification-email",{method:"POST",query:ne.z.object({currentURL:ne.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:ne.z.object({email:ne.z.string({description:"The email to send the verification email to"}).email(),callbackURL:ne.z.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 Be.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:i}=e.body,t=await e.context.internalAdapter.findUserByEmail(i);if(!t)throw new Be.APIError("BAD_REQUEST",{message:g.USER_NOT_FOUND});return await xo(e,t.user),e.json({status:!0})}),Yi=p("/verify-email",{method:"GET",query:ne.z.object({token:ne.z.string({description:"The token to verify the email"}),callbackURL:ne.z.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 Be.APIError("UNAUTHORIZED",{message:A})}let{token:t}=e.query,o;try{o=await(0,ho.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(A){return e.context.logger.error("Failed to verify email",A),i("invalid_token")}let n=ne.z.object({email:ne.z.string().email(),updateTo:ne.z.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 ue(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 Be.APIError("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})});var W=require("better-call");var et=require("better-call");function jo(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function Lr(e){let i="";for(let t=0;t<e.length;t++)i+=jo(e[t]);return i}function Xi(e,i=!0){if(Array.isArray(e))return`(?:${e.map(c=>`^${Xi(c,i)}$`).join("|")})`;let t="",o="",r=".";i===!0?(t="/",o="[/\\\\]",r="[^/\\\\]"):i&&(t=i,o=Lr(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+=jo(c[K+1]),K++):m==="?"?a+=r:m==="*"?a+=`${r}*?`:a+=jo(m)}a+=l}}return a}function Br(e,i){if(typeof i!="string")throw new TypeError(`Sample must be a string, but ${typeof i} given`);return e.test(i)}function zo(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=Xi(e,i.separator),o=new RegExp(`^${t}$`,i.flags),r=Br.bind(null,o);return r.options=i,r.pattern=e,r.regexp=o,r}var xr=v(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("*")?zo(C)(li(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 et.APIError("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 ot=p("/ok",{method:"GET",metadata:{...Ee,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}));var Re=require("zod");var le=require("better-call");var E=require("zod"),it=require("better-call"),nA=E.z.object({id:E.z.string(),providerId:E.z.string(),accountId:E.z.string(),userId:E.z.string(),accessToken:E.z.string().nullish(),refreshToken:E.z.string().nullish(),idToken:E.z.string().nullish(),accessTokenExpiresAt:E.z.date().nullish(),refreshTokenExpiresAt:E.z.date().nullish(),scope:E.z.string().nullish(),password:E.z.string().nullish(),createdAt:E.z.date().default(()=>new Date),updatedAt:E.z.date().default(()=>new Date)}),sA=E.z.object({id:E.z.string(),email:E.z.string().transform(e=>e.toLowerCase()),emailVerified:E.z.boolean().default(!1),name:E.z.string(),image:E.z.string().nullish(),createdAt:E.z.date().default(()=>new Date),updatedAt:E.z.date().default(()=>new Date)}),aA=E.z.object({id:E.z.string(),userId:E.z.string(),expiresAt:E.z.date(),createdAt:E.z.date().default(()=>new Date),updatedAt:E.z.date().default(()=>new Date),token:E.z.string(),ipAddress:E.z.string().nullish(),userAgent:E.z.string().nullish()}),AA=E.z.object({id:E.z.string(),value:E.z.string(),createdAt:E.z.date().default(()=>new Date),updatedAt:E.z.date().default(()=>new Date),expiresAt:E.z.date(),identifier:E.z.string()});function jr(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 zr(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 it.APIError("BAD_REQUEST",{message:`${n} is required`})}return r}function yo(e,i,t){let o=jr(e,"user");return zr(i||{},{fields:o,action:t})}function se(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 tt=()=>p("/sign-up/email",{method:"POST",query:Re.z.object({currentURL:Re.z.string().optional()}).optional(),body:Re.z.record(Re.z.string(),Re.z.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 le.APIError("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(!Re.z.string().email().safeParse(o).success)throw new le.APIError("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 le.APIError("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 le.APIError("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 le.APIError("UNPROCESSABLE_ENTITY",{message:g.USER_ALREADY_EXISTS});let l=yo(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 le.APIError("BAD_REQUEST",{message:g.FAILED_TO_CREATE_USER})}catch(N){throw uo&&e.context.logger.error("Failed to create user",N),new le.APIError("UNPROCESSABLE_ENTITY",{message:g.FAILED_TO_CREATE_USER,details:N})}if(!K)throw new le.APIError("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 ue(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 le.APIError("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 Fr=(e="Unknown")=>`<!DOCTYPE html>
3
3
  <html lang="en">
4
4
  <head>
@@ -79,8 +79,8 @@
79
79
  <div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
80
80
  </div>
81
81
  </body>
82
- </html>`,rt=p("/error",{method:"GET",metadata:{...Ee,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(Fr(i),{headers:{"Content-Type":"text/html"}})});var nt=So(require("defu"),1);var b=require("better-call");function Fo(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:st,callbackOAuth:At,getSession:Bo(),signOut:dt,signUpEmail:tt(),signInEmail:at,forgetPassword:ct,resetPassword:Kt,verifyEmail:Yi,sendVerificationEmail:Ji,changeEmail:ht,changePassword:lt,setPassword:mt,updateUser:ut(),deleteUser:gt,forgetPasswordCallback:pt,listSessions:$i(),revokeSession:Gi,revokeSessions:Qi,revokeOtherSessions:Zi,linkSocialAccount:wt,listUserAccounts:yt,deleteUserCallback:ft},...t,ok:ot,error:rt},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){(0,W.setCookie)(a.headers,w,R,h)},getCookie(w,R){let T=d.headers?.get("cookie");return(0,W.getCookie)(T||"",w,R)},getSignedCookie(w,R,h){let T=d.headers;return T?(0,W.getSignedCookie)(T,R,w,h):null},async setSignedCookie(w,R,h,T){await(0,W.setSignedCookie)(a.headers,w,R,h,T)},redirect(w){return a.headers.set("Location",w),new W.APIError("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=(0,nt.default)(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 W.APIError){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 j=await h.handler(K);j&&"response"in j&&(K.context.returned=j.response)}catch(j){if(j instanceof W.APIError){K.context.returned=j;continue}throw j}if(K.context.returned instanceof W.APIError)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 j=T.responseHeader;K.responseHeader=j}else K.context.returned=T}catch(T){if(T instanceof W.APIError){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 Be(e,{userInfo:i,account:t,callbackURL:o}){let r=await e.context.internalAdapter.findUserByEmail(i.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw re.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 uo&&re.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 re.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 ue(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 st=p("/sign-in/social",{method:"POST",query:L.z.object({currentURL:L.z.string().optional()}).optional(),body:L.z.object({callbackURL:L.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:L.z.string().optional(),errorCallbackURL:L.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:L.z.enum(fo,{description:"OAuth2 provider to use"}),disableRedirect:L.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:L.z.optional(L.z.object({token:L.z.string({description:"ID token from the provider"}),nonce:L.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:L.z.string({description:"Access token from the provider"}).optional(),refreshToken:L.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:L.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let 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.APIError("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.APIError("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.APIError("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.APIError("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.APIError("UNAUTHORIZED",{message:g.USER_EMAIL_NOT_FOUND});let d=await Be(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.APIError("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 Ne(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})}),at=p("/sign-in/email",{method:"POST",body:L.z.object({email:L.z.string({description:"Email of the user"}),password:L.z.string({description:"Password of the user"}),callbackURL:L.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:L.z.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new Q.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:i,password:t}=e.body;if(!L.z.string().email().safeParse(i).success)throw new Q.APIError("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.APIError("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.APIError("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.APIError("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.APIError("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.APIError("UNAUTHORIZED",{message:g.EMAIL_NOT_VERIFIED});let d=await ue(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.APIError("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.APIError("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})});var xe=require("zod");var wo=xe.z.object({code:xe.z.string().optional(),error:xe.z.string().optional(),error_description:xe.z.string().optional(),state:xe.z.string().optional()}),At=p("/callback/:id",{method:["GET","POST"],body:wo.optional(),query:wo.optional(),metadata:Ee},async e=>{let i;try{if(e.method==="GET")i=wo.parse(e.query);else if(e.method==="POST")i=wo.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 go(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 Be(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)});var nd=require("zod");var Ct=require("better-call");var dt=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 q(e),new Ct.APIError("BAD_REQUEST",{message:g.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(i),q(e),e.json({success:!0})});var ie=require("zod");var je=require("better-call");function bt(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 Mr(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 ct=p("/forget-password",{method:"POST",body:ie.z.object({email:ie.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:ie.z.string({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new je.APIError("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=G(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})}),pt=p("/reset-password/:token",{method:"GET",query:ie.z.object({callbackURL:ie.z.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:i}=e.params,{callbackURL:t}=e.query;if(!i||!t)throw e.redirect(bt(e.context,t,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${i}`);throw!o||o.expiresAt<new Date?e.redirect(bt(e.context,t,{error:"INVALID_TOKEN"})):e.redirect(Mr(e.context,t,{token:i}))}),Kt=p("/reset-password",{query:ie.z.optional(ie.z.object({token:ie.z.string().optional(),currentURL:ie.z.string().optional()})),method:"POST",body:ie.z.object({newPassword:ie.z.string({description:"The new password to set"}),token:ie.z.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let i=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!i)throw new je.APIError("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.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_SHORT});if(t.length>r)throw new je.APIError("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.APIError("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}))});var $=require("zod");var M=require("better-call");var qo=require("@noble/ciphers/chacha"),ze=require("@noble/ciphers/utils"),Ho=require("@noble/ciphers/webcrypto"),$o=require("oslo/crypto"),Mo=So(require("uncrypto"),1);var Ot=require("oslo/encoding");var qr=require("@noble/hashes/scrypt"),Hr=require("uncrypto");var Vo=So(require("uncrypto"),1);function $r(e){return e.toString(2).padStart(8,"0")}function Gr(e){return[...e].map(i=>$r(i)).join("")}function Tt(e){return parseInt(Gr(e),2)}function Qr(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));Vo.default.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1);let r=Tt(o);for(;r>=e;)Vo.default.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1),r=Tt(o);return r}function F(e,i){let t="";for(let o=0;o<e;o++)t+=i[Qr(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 Xe(e,i){let t=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},r=await Mo.default.subtle.importKey("raw",t.encode(e),o,!1,["sign","verify"]),n=await Mo.default.subtle.sign(o.name,r,t.encode(i));return btoa(String.fromCharCode(...new Uint8Array(n)))}var he=async({key:e,data:i})=>{let t=await(0,$o.sha256)(new TextEncoder().encode(e)),o=(0,ze.utf8ToBytes)(i),r=(0,Ho.managedNonce)(qo.xchacha20poly1305)(new Uint8Array(t));return(0,ze.bytesToHex)(r.encrypt(o))},Ce=async({key:e,data:i})=>{let t=await(0,$o.sha256)(new TextEncoder().encode(e)),o=(0,ze.hexToBytes)(i),r=(0,Ho.managedNonce)(qo.xchacha20poly1305)(new Uint8Array(t));return new TextDecoder().decode(r.decrypt(o))};var ut=()=>p("/update-user",{method:"POST",body:$.z.record($.z.string(),$.z.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 M.APIError("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=yo(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})}),lt=p("/change-password",{method:"POST",body:$.z.object({newPassword:$.z.string({description:"The new password to set"}),currentPassword:$.z.string({description:"The current password"}),revokeOtherSessions:$.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[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 M.APIError("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 M.APIError("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 M.APIError("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 M.APIError("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 M.APIError("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_GET_SESSION});await f(e,{session:u,user:r.user})}return e.json(r.user)}),mt=p("/set-password",{method:"POST",body:$.z.object({newPassword:$.z.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 M.APIError("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 M.APIError("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 M.APIError("BAD_REQUEST",{message:"user already has a password"})}),gt=p("/delete-user",{method:"POST",use:[Ye],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 M.APIError("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),q(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(i.user,e.request),e.json({success:!0,message:"User deleted"})}),ft=p("/delete-user/callback",{method:"GET",query:$.z.object({token:$.z.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 M.APIError("NOT_FOUND");let i=await S(e);if(!i)throw new M.APIError("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 M.APIError("NOT_FOUND",{message:g.INVALID_TOKEN});if(t.value!==i.user.id)throw new M.APIError("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),q(e);let r=e.context.options.user.deleteUser?.afterDelete;return r&&await r(i.user,e.request),e.json({success:!0,message:"User deleted"})}),ht=p("/change-email",{method:"POST",query:$.z.object({currentURL:$.z.string().optional()}).optional(),body:$.z.object({newEmail:$.z.string({description:"The new email to set"}).email(),callbackURL:$.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[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 M.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new M.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new M.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let r=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:r,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new M.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await ue(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})});var Fe=require("zod");var Go=require("better-call");var yt=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})))}),wt=p("/link-social",{method:"POST",requireHeaders:!0,query:Fe.z.object({currentURL:Fe.z.string().optional()}).optional(),body:Fe.z.object({callbackURL:Fe.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:Fe.z.enum(fo,{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 Go.APIError("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 Go.APIError("NOT_FOUND",{message:g.PROVIDER_NOT_FOUND});let n=await Ne(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 Et=(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 Co(e){let i=e;return{newRole(t){return Zr(t)}}}function Zr(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 Wr={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},Qo=Co(Wr),Jr=Qo.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),Yr=Qo.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),Xr=Qo.newRole({organization:[],member:[],invitation:[]}),Rt={admin:Jr,owner:Yr,member:Xr};var en={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*:/},on=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,It={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},tn=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function rn(e){return e instanceof Date&&!isNaN(e.getTime())}function nn(e){let i=tn.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 rn(l)?l:null}function sn(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 It)return It[A];if(!on.test(s)){if(t)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(en).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=nn(u);if(l)return l}return r?r(c,u):u})}catch(d){if(t)throw d;return e}}function St(e,i={strict:!0}){return sn(e,i)}var Ut=St;var z=(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?Ut(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 oe("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}})}};var uc=require("better-call");var H=v(async e=>({})),J=v({use:[I]},async e=>({session:e.context.session}));var ee=require("zod");var D=require("zod");var _t=D.z.string(),an=D.z.enum(["pending","accepted","rejected","canceled"]).default("pending"),yc=D.z.object({id:D.z.string().default(G),name:D.z.string(),slug:D.z.string(),logo:D.z.string().nullish(),metadata:D.z.record(D.z.string()).or(D.z.string().transform(e=>JSON.parse(e))).nullish(),createdAt:D.z.date()}),wc=D.z.object({id:D.z.string().default(G),organizationId:D.z.string(),userId:D.z.string(),role:_t,createdAt:D.z.date()}),Cc=D.z.object({id:D.z.string().default(G),organizationId:D.z.string(),email:D.z.string(),role:_t,status:an,inviterId:D.z.string(),expiresAt:D.z.date()});var x=require("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 vt=e=>p("/organization/invite-member",{method:"POST",use:[H,J],body:ee.z.object({email:ee.z.string({description:"The email address of the user to invite"}),role:ee.z.string({description:"The role to assign to the user"}),organizationId:ee.z.string({description:"The organization ID to invite the user to"}).optional(),resend:ee.z.boolean({description:"Resend the invitation email, if the user is already invited"}).optional()}),metadata:{openapi:{description:"Invite a user to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt"]}}}}}}}},async 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 x.APIError("BAD_REQUEST",{message:"Invitation email is not enabled"});let t=i.context.session,o=i.body.organizationId||t.session.activeOrganizationId;if(!o)throw new x.APIError("BAD_REQUEST",{message:y.ORGANIZATION_NOT_FOUND});let r=z(i.context,i.context.orgOptions),n=await r.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!n)throw new x.APIError("BAD_REQUEST",{message:y.MEMBER_NOT_FOUND});let s=i.context.roles[n.role];if(!s)throw new x.APIError("BAD_REQUEST",{message:y.ROLE_NOT_FOUND});if(s.authorize({invitation:["create"]}).error)throw new x.APIError("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 x.APIError("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 x.APIError("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 x.APIError("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)}),kt=p("/organization/accept-invitation",{method:"POST",body:ee.z.object({invitationId:ee.z.string({description:"The ID of the invitation to accept"})}),use:[H,J],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=z(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new x.APIError("BAD_REQUEST",{message:y.INVITATION_NOT_FOUND});if(o.email!==i.user.email)throw new x.APIError("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}})}),Pt=p("/organization/reject-invitation",{method:"POST",body:ee.z.object({invitationId:ee.z.string({description:"The ID of the invitation to reject"})}),use:[H,J],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=z(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new x.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==i.user.email)throw new x.APIError("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})}),Nt=p("/organization/cancel-invitation",{method:"POST",body:ee.z.object({invitationId:ee.z.string({description:"The ID of the invitation to cancel"})}),use:[H,J],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=z(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o)throw new x.APIError("BAD_REQUEST",{message:y.INVITATION_NOT_FOUND});let r=await t.findMemberByOrgId({userId:i.user.id,organizationId:o.organizationId});if(!r)throw new x.APIError("BAD_REQUEST",{message:y.MEMBER_NOT_FOUND});if(e.context.roles[r.role].authorize({invitation:["cancel"]}).error)throw new x.APIError("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)}),Dt=p("/organization/get-invitation",{method:"GET",use:[H],requireHeaders:!0,query:ee.z.object({id:ee.z.string({description:"The ID of the invitation to get"})}),metadata:{openapi:{description:"Get an invitation by ID",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"},organizationName:{type:"string"},organizationSlug:{type:"string"},inviterEmail:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt","organizationName","organizationSlug","inviterEmail"]}}}}}}}},async e=>{let i=await S(e);if(!i)throw new x.APIError("UNAUTHORIZED",{message:"Not authenticated"});let t=z(e.context,e.context.orgOptions),o=await t.findInvitationById(e.query.id);if(!o||o.status!=="pending"||o.expiresAt<new Date)throw new x.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==i.user.email)throw new x.APIError("FORBIDDEN",{message:y.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let r=await t.findOrganizationById(o.organizationId);if(!r)throw new x.APIError("BAD_REQUEST",{message:y.ORGANIZATION_NOT_FOUND});let n=await t.findMemberByOrgId({userId:o.inviterId,organizationId:o.organizationId});if(!n)throw new x.APIError("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})});var ae=require("zod");var be=require("better-call");var Lt=()=>p("/organization/add-member",{method:"POST",body:ae.z.object({userId:ae.z.string(),role:ae.z.string(),organizationId:ae.z.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=z(e.context,e.context.orgOptions),r=await e.context.internalAdapter.findUserById(e.body.userId);if(!r)throw new be.APIError("BAD_REQUEST",{message:g.USER_NOT_FOUND});if(await o.findMemberByEmail({email:r.email,organizationId:t}))throw new be.APIError("BAD_REQUEST",{message:y.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION});let s=await o.createMember({id:G(),organizationId:t,userId:r.id,role:e.body.role,createdAt:new Date});return e.json(s)}),Bt=p("/organization/remove-member",{method:"POST",body:ae.z.object({memberIdOrEmail:ae.z.string({description:"The ID or email of the member to remove"}),organizationId:ae.z.string({description:"The ID of the organization to remove the member from. If not provided, the active organization will be used"}).optional()}),use:[H,J],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=z(e.context,e.context.orgOptions),r=await o.findMemberByOrgId({userId:i.user.id,organizationId:t});if(!r)throw new be.APIError("BAD_REQUEST",{message:y.MEMBER_NOT_FOUND});let n=e.context.roles[r.role];if(!n)throw new be.APIError("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 be.APIError("BAD_REQUEST",{message:y.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER});if(!(s||n.authorize({member:["delete"]}).success))throw new be.APIError("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 be.APIError("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})}),xt=e=>p("/organization/update-member-role",{method:"POST",body:ae.z.object({role:ae.z.string(),memberId:ae.z.string(),organizationId:ae.z.string().optional()}),use:[H,J],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=z(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}})}),jt=p("/organization/get-active-member",{method:"GET",use:[H,J],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 z(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}})});var _=require("zod");var me=require("better-call");var zt=p("/organization/create",{method:"POST",body:_.z.object({name:_.z.string({description:"The name of the organization"}),slug:_.z.string({description:"The slug of the organization"}),userId:_.z.string({description:"The user id of the organization creator. If not provided, the current user will be used. Should only be used by admins or when called by the server."}).optional(),logo:_.z.string({description:"The logo of the organization"}).optional(),metadata:_.z.record(_.z.string(),_.z.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.APIError("UNAUTHORIZED");let t=i?.user||null;if(!t){if(!e.body.userId)throw new me.APIError("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.APIError("FORBIDDEN",{message:y.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION});let n=z(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.APIError("FORBIDDEN",{message:y.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS});if(await n.findOrganizationBySlug(e.body.slug))throw new me.APIError("BAD_REQUEST",{message:y.ORGANIZATION_ALREADY_EXISTS});let d=await n.createOrganization({organization:{id:G(),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)}),Ft=p("/organization/update",{method:"POST",body:_.z.object({data:_.z.object({name:_.z.string({description:"The name of the organization"}).optional(),slug:_.z.string({description:"The slug of the organization"}).optional(),logo:_.z.string({description:"The logo of the organization"}).optional(),metadata:_.z.record(_.z.string(),_.z.any(),{description:"The metadata of the organization"}).optional()}).partial(),organizationId:_.z.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.APIError("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=z(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)}),Vt=p("/organization/delete",{method:"POST",body:_.z.object({organizationId:_.z.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=z(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.APIError("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)}),Mt=p("/organization/get-full-organization",{method:"GET",query:_.z.optional(_.z.object({organizationId:_.z.string({description:"The organization id to get"}).optional(),organizationSlug:_.z.string({description:"The organization slug to get"}).optional()})),requireHeaders:!0,use:[H,J],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 z(e.context,e.context.orgOptions).findFullOrganization({organizationId:t,isSlug:!!e.query?.organizationSlug});if(!r)throw new me.APIError("BAD_REQUEST",{message:y.ORGANIZATION_NOT_FOUND});return e.json(r)}),qt=p("/organization/set-active",{method:"POST",body:_.z.object({organizationId:_.z.string({description:"The organization id to set as active. It can be null to unset the active organization"}).nullable().optional(),organizationSlug:_.z.string({description:"The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided"}).optional()}),use:[J,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=z(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.APIError("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)}),Ht=p("/organization/list",{method:"GET",use:[H,J],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 z(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(t)});var An=Co({name:["action"]}),tp=An.newRole({name:["action"]}),dn=e=>{let i={createOrganization:zt,updateOrganization:Ft,deleteOrganization:Vt,setActiveOrganization:qt,getFullOrganization:Mt,listOrganizations:Ht,createInvitation:vt(e),cancelInvitation:Nt,acceptInvitation:kt,getInvitation:Dt,rejectInvitation:Pt,addMember:Lt(),removeMember:Bt,updateMemberRole:xt(e),getActiveMember:jt},t={...Rt,...e?.roles};return{id:"organization",endpoints:{...Et(i,{orgOptions:e||{},roles:t,getSession:async r=>await S(r)}),hasPermission:p("/organization/has-permission",{method:"POST",requireHeaders:!0,body:Ve.z.object({permission:Ve.z.record(Ve.z.string(),Ve.z.array(Ve.z.string()))}),use:[J],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 Zo.APIError("BAD_REQUEST",{message:y.NO_ACTIVE_ORGANIZATION});let s=await z(r.context).findMemberByOrgId({userId:r.context.session.user.id,organizationId:r.context.session.session.activeOrganizationId||""});if(!s)throw new Zo.APIError("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}};var io=require("zod");var ge=require("zod");var Me=require("better-call");var bo="two_factor";var Oo="trust_device";var Wo=require("zod");var Ie=v({body:Wo.z.object({trustDevice:Wo.z.boolean().optional()})},async e=>{let i=await S(e);if(!i){let t=e.context.createAuthCookie(bo),o=await e.getSignedCookie(t.name,e.context.secret);if(!o)throw new Me.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let r=await e.context.internalAdapter.findUserById(o);if(!r)throw new Me.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let n=await e.context.internalAdapter.createSession(o,e.request);if(!n)throw new Me.APIError("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(Oo,{maxAge:2592e3}),A=await Xe(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 Me.APIError("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 Me.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:i}});var qe=require("better-call");var Y={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 cn(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 Jo(e,i){let t=e,o=i?.customBackupCodesGenerate?i.customBackupCodesGenerate():cn(),r=await he({data:JSON.stringify(o),key:t});return{backupCodes:o,encryptedBackupCodes:r}}async function pn(e,i){let t=await $t(e.backupCodes,i);return t?{status:t.includes(e.code),updated:t.filter(o=>o!==e.code)}:{status:!1,updated:null}}async function $t(e,i){let t=Buffer.from(await Ce({key:i,data:e})).toString("utf-8"),o=JSON.parse(t),r=ge.z.array(ge.z.string()).safeParse(o);return r.success?r.data:null}var Gt=(e,i)=>({id:"backup_code",endpoints:{verifyBackupCode:p("/two-factor/verify-backup-code",{method:"POST",body:ge.z.object({code:ge.z.string(),disableSession:ge.z.boolean().optional()}),use:[Ie]},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 qe.APIError("BAD_REQUEST",{message:Y.BACKUP_CODES_NOT_ENABLED});let n=await pn({backupCodes:r.backupCodes,code:t.body.code},t.context.secret);if(!n.status)throw new qe.APIError("UNAUTHORIZED",{message:Y.INVALID_BACKUP_CODE});let s=await he({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.z.object({password:ge.z.string()}),use:[I]},async t=>{let o=t.context.session.user;if(!o.twoFactorEnabled)throw new qe.APIError("BAD_REQUEST",{message:Y.TWO_FACTOR_NOT_ENABLED});await t.context.password.checkPassword(o.id,t);let r=await Jo(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.z.object({userId:ge.z.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 qe.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let r=await $t(o.backupCodes,t.context.secret);if(!r)throw new qe.APIError("BAD_REQUEST",{message:Y.BACKUP_CODES_NOT_ENABLED});return t.json({status:!0,backupCodes:r})})}});var He=require("better-call"),Yo=require("zod");var Qt=require("oslo");var Zt=(e,i)=>{let t={...e,digits:e?.digits||6,period:new Qt.TimeSpan(e?.period||3,"m")},o=p("/two-factor/send-otp",{method:"POST",use:[Ie],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 He.APIError("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 He.APIError("BAD_REQUEST",{message:Y.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:Yo.z.object({code:Yo.z.string({description:"The otp code to verify"})}),use:[Ie],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 He.APIError("BAD_REQUEST",{message:"two factor isn't enabled"});if(!await n.context.adapter.findOne({model:i,where:[{field:"userId",value:s.id}]}))throw new He.APIError("BAD_REQUEST",{message:Y.OTP_NOT_ENABLED});let a=await n.context.internalAdapter.findVerificationValue(`2fa-otp-${s.id}`);if(!a||a.expiresAt<new Date)throw new He.APIError("BAD_REQUEST",{message:Y.OTP_HAS_EXPIRED});return a.value===n.body.code?n.context.valid():n.context.invalid()});return{id:"otp",endpoints:{sendTwoFactorOTP:o,verifyTwoFactorOTP:r}}};var Se=require("better-call"),Wt=require("oslo"),oo=require("oslo/otp"),eo=require("zod");var Jt=(e,i)=>{let t={...e,digits:e?.digits||6,period:new Wt.TimeSpan(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.APIError("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.APIError("BAD_REQUEST",{message:Y.TOTP_NOT_ENABLED});return{code:await new oo.TOTPController(t).generate(Buffer.from(a.secret))}}),r=p("/two-factor/get-totp-uri",{method:"POST",use:[I],body:eo.z.object({password:eo.z.string({description:"User password"})}),metadata:{openapi:{summary:"Get TOTP URI",description:"Use this endpoint to get the TOTP URI",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{totpURI:{type:"string"}}}}}}}}}},async 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.APIError("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.APIError("BAD_REQUEST",{message:Y.TOTP_NOT_ENABLED});return await s.context.password.checkPassword(A.id,s),{totpURI:(0,oo.createTOTPKeyURI)(e.issuer||s.context.appName,A.email,Buffer.from(a.secret),t)}}),n=p("/two-factor/verify-totp",{method:"POST",body:eo.z.object({code:eo.z.string({description:"The otp code to verify"})}),use:[Ie],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.APIError("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.APIError("BAD_REQUEST",{message:Y.TOTP_NOT_ENABLED});let d=new oo.TOTPController(t),c=await Ce({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}}};var Kn=require("better-call");async function Xo(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})}var ei=require("better-call"),Xt=require("oslo/otp"),er=require("oslo");var Yt={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 un=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 ln=e=>{let i={twoFactorTable:"twoFactor"},t=Jt({issuer:e?.issuer,...e?.totpOptions},i.twoFactorTable),o=Gt({...e?.backupCodeOptions},i.twoFactorTable),r=Zt({...e?.otpOptions},i.twoFactorTable);return{id:"two-factor",endpoints:{...t.endpoints,...r.endpoints,...o.endpoints,enableTwoFactor:p("/two-factor/enable",{method:"POST",body:io.z.object({password:io.z.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 Xo(n,{password:A,userId:s.id}))throw new ei.APIError("BAD_REQUEST",{message:g.INVALID_PASSWORD});let d=F(16,V("a-z","0-9","-")),c=await he({key:n.context.secret,data:d}),u=await Jo(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=(0,Xt.createTOTPKeyURI)(e?.issuer||"BetterAuth",s.email,Buffer.from(d),{digits:e?.totpOptions?.digits||6,period:new er.TimeSpan(e?.totpOptions?.period||30,"s")});return n.json({totpURI:l,backupCodes:u.backupCodes})}),disableTwoFactor:p("/two-factor/disable",{method:"POST",body:io.z.object({password:io.z.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 Xo(n,{password:A,userId:s.id}))throw new ei.APIError("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:v(async n=>{let s=n.context.newSession;if(!s||!s?.user.twoFactorEnabled)return;let A=n.context.createAuthCookie(Oo),a=await n.getSignedCookie(A.name,n.context.secret);if(a){let[c,u]=a.split("!"),l=await Xe(n.context.secret,`${s.user.id}!${u}`);if(c===l){let K=await Xe(n.context.secret,`${s.user.id}!${s.session.token}`);await n.setSignedCookie(A.name,`${K}!${s.session.token}`,n.context.secret,A.attributes);return}}q(n),await n.context.internalAdapter.deleteSession(s.session.token);let d=n.context.createAuthCookie(bo,{maxAge:60*10});return await n.setSignedCookie(d.name,s.user.id,n.context.secret,d.attributes),n.json({twoFactorRedirect:!0})})}]},schema:se(Yt,e?.schema),rateLimit:[{pathMatcher(n){return n.startsWith("/two-factor/")},window:10,max:3}]}};var Oe=require("@simplewebauthn/server"),X=require("better-call");var te=require("zod");var $e=require("@simplewebauthn/browser");var gn=require("@better-fetch/fetch");var KK=require("nanostores");var eK=require("@better-fetch/fetch");var mn=require("nanostores");var iK=require("@better-fetch/fetch"),To=require("nanostores"),oi=(e,i,t,o)=>{let r=(0,To.atom)({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():(0,To.onMount)(r,()=>(n(),s=!0,()=>{r.off(),A.off()}))});return r};var or=require("nanostores"),ir=(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(0,$e.startAuthentication)(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(0,$e.startRegistration)(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 $e.WebAuthnError?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:{}}),fn=()=>{let e=(0,or.atom)();return{id:"passkey",$InferServerPlugin:{},getActions:i=>ir(i,{$listPasskeys:e}),getAtoms(i){return{listPasskeys:oi(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 hn=e=>{let i=de.BETTER_AUTH_URL,t=e?.rpID||i?.replace("http://","").replace("https://","").split(":")[0]||"localhost";if(!t)throw new oe("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:[Ye],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(0,Oe.generateRegistrationOptions)({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=G(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:te.z.object({email:te.z.string({description:"The email address of the user"}).optional()}).optional(),metadata:{openapi:{description:"Generate authentication options for a passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{challenge:{type:"string"},rp:{type:"object",properties:{name:{type:"string"},id:{type:"string"}}},user:{type:"object",properties:{id:{type:"string"},name:{type:"string"},displayName:{type:"string"}}},timeout:{type:"number"},allowCredentials:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string"},transports:{type:"array",items:{type:"string"}}}}},userVerification:{type:"string"},authenticatorSelection:{type:"object",properties:{authenticatorAttachment:{type:"string"},requireResidentKey:{type:"boolean"},userVerification:{type:"string"}}},extensions:{type:"object"}}}}}}}}}},async 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(0,Oe.generateAuthenticationOptions)({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=G(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:te.z.object({response:te.z.any({description:"The response from the authenticator"}),name:te.z.string({description:"Name of the passkey"}).optional()}),use:[Ye],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 X.APIError("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 X.APIError("UNAUTHORIZED",{message:A.YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY});try{let C=await(0,Oe.verifyRegistrationResponse)({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:j,credentialBackedUp:ao}=w,mr=Buffer.from(h).toString("base64"),gr={name:a.body.name,userId:m.id,webauthnUserID:a.context.generateId({model:"passkey"}),id:R,publicKey:mr,counter:T,deviceType:j,transports:c.response.transports.join(","),backedUp:ao,createdAt:new Date},fr=await a.context.adapter.create({model:"passkey",data:gr});return a.json(fr,{status:200})}catch(C){throw console.log(C),new X.APIError("INTERNAL_SERVER_ERROR",{message:A.FAILED_TO_VERIFY_REGISTRATION})}}),verifyPasskeyAuthentication:p("/passkey/verify-authentication",{method:"POST",body:te.z.object({response:te.z.any()}),metadata:{openapi:{description:"Verify authentication of a passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async a=>{let d=e?.origin||a.headers?.get("origin")||"";if(!d)throw new X.APIError("BAD_REQUEST",{message:"origin missing"});let c=a.body.response,u=await a.getSignedCookie(o.advanced.webAuthnChallengeCookie,a.context.secret);if(!u)throw new X.APIError("BAD_REQUEST",{message:A.CHALLENGE_NOT_FOUND});let l=await a.context.internalAdapter.findVerificationValue(u);if(!l)throw new X.APIError("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 X.APIError("UNAUTHORIZED",{message:A.PASSKEY_NOT_FOUND});try{let C=await(0,Oe.verifyAuthenticationResponse)({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 X.APIError("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 X.APIError("INTERNAL_SERVER_ERROR",{message:A.UNABLE_TO_CREATE_SESSION});let R=await a.context.internalAdapter.findUserById(m.userId);if(!R)throw new X.APIError("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 X.APIError("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:te.z.object({id:te.z.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:te.z.object({id:te.z.string(),name:te.z.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 X.APIError("NOT_FOUND",{message:A.PASSKEY_NOT_FOUND});if(d.userId!==a.context.session.user.id)throw new X.APIError("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 X.APIError("INTERNAL_SERVER_ERROR",{message:A.FAILED_TO_UPDATE_PASSKEY});return a.json({passkey:c},{status:200})})},schema:se(yn,e?.schema),$ERROR_CODES:A}},yn={passkey:{fields:{name:{type:"string",required:!1},publicKey:{type:"string",required:!0},userId:{type:"string",references:{model:"user",field:"id"},required:!0},webauthnUserID:{type:"string",required:!0},counter:{type:"number",required:!0},deviceType:{type:"string",required:!0},backedUp:{type:"boolean",required:!0},transports:{type:"string",required:!1},createdAt:{type:"date",required:!1}}}};var to=require("zod");var Ue=require("better-call");var ii=()=>{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:to.z.object({username:to.z.string({description:"The username of the user"}),password:to.z.string({description:"The password of the user"}),rememberMe:to.z.boolean({description:"Remember the user session"}).optional()}),metadata:{openapi:{summary:"Sign in with username",description:"Sign in with username",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async 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:ii}),new Ue.APIError("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});if(!t.emailVerified&&i.context.options.emailAndPassword?.requireEmailVerification)throw await xo(i,t),new Ue.APIError("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.APIError("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});let r=o?.password;if(!r)throw i.context.logger.error("Password not found",{username:ii}),new Ue.APIError("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.APIError("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.APIError("UNPROCESSABLE_ENTITY",{message:e.USERNAME_IS_ALREADY_TAKEN})}}]},$ERROR_CODES:Y}};var QK=require("better-call");var wn=()=>({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:v(async e=>{let i=e.responseHeader.get("set-cookie");if(!i)return;let t=ke(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}})}]}});var _e=require("zod");var tr=require("better-call");var Cn=e=>({id:"magic-link",endpoints:{signInMagicLink:p("/sign-in/magic-link",{method:"POST",requireHeaders:!0,body:_e.z.object({email:_e.z.string({description:"Email address to send the magic link"}).email(),callbackURL:_e.z.string({description:"URL to redirect after magic link verification"}).optional()}),metadata:{openapi:{description:"Sign in with magic link",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async i=>{let{email:t}=i.body;if(e.disableSignUp&&!await i.context.internalAdapter.findUserByEmail(t))throw new tr.APIError("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.z.object({token:_e.z.string({description:"Verification token"}),callbackURL:_e.z.string({description:"URL to redirect after magic link verification, if not provided will return session"}).optional()}),requireHeaders:!0,metadata:{openapi:{description:"Verify magic link",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async 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}]});var Ae=require("zod");var Z=require("better-call");function bn(e){return F(e,V("0-9"))}var On=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.z.object({phoneNumber:Ae.z.string({description:"Phone number to sign in"}),password:Ae.z.string({description:"Password to use for sign in"}),rememberMe:Ae.z.boolean({description:"Remember the session"}).optional()}),metadata:{openapi:{summary:"Sign in with phone number",description:"Use this endpoint to sign in with phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}},400:{description:"Invalid phone number or password"}}}}},async o=>{let{password:r,phoneNumber:n}=o.body;if(i.phoneNumberValidator&&!await i.phoneNumberValidator(o.body.phoneNumber))throw new Z.APIError("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 Z.APIError("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 Z.APIError("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 Z.APIError("UNAUTHORIZED",{message:t.UNEXPECTED_ERROR});if(!await o.context.password.verify({hash:d,password:r}))throw o.context.logger.error("Invalid password"),new Z.APIError("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 Z.APIError("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.z.object({phoneNumber:Ae.z.string({description:"Phone number to send OTP"})}),metadata:{openapi:{summary:"Send OTP to phone number",description:"Use this endpoint to send OTP to phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async o=>{if(!e?.sendOTP)throw o.context.logger.warn("sendOTP not implemented"),new Z.APIError("NOT_IMPLEMENTED",{message:"sendOTP not implemented"});if(i.phoneNumberValidator&&!await i.phoneNumberValidator(o.body.phoneNumber))throw new Z.APIError("BAD_REQUEST",{message:t.INVALID_PHONE_NUMBER});let r=bn(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.z.object({phoneNumber:Ae.z.string({description:"Phone number to verify"}),code:Ae.z.string({description:"OTP code"}),disableSession:Ae.z.boolean({description:"Disable session creation after verification"}).optional(),updatePhoneNumber:Ae.z.boolean({description:"Check if there is a session and update the phone number"}).optional()}),metadata:{openapi:{summary:"Verify phone number",description:"Use this endpoint to verify phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}},400:{description:"Invalid OTP"}}}}},async o=>{let 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 Z.APIError("BAD_REQUEST",{message:"OTP expired"})):new Z.APIError("BAD_REQUEST",{message:t.OTP_NOT_FOUND});if(r.value!==o.body.code)throw new Z.APIError("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 Z.APIError("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 Z.APIError("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_CREATE_USER})}else return o.json(null);if(!n)throw new Z.APIError("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 Z.APIError("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:se(Tn,e?.schema),$ERROR_CODES:t}},Tn={user:{fields:{phoneNumber:{type:"string",required:!1,unique:!0,returned:!0},phoneNumberVerified:{type:"boolean",required:!1,returned:!0,input:!1}}}};var En={user:{fields:{isAnonymous:{type:"boolean",required:!1}}}},Rn=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=Pe(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:v(async t=>{let r=t.responseHeader.get("set-cookie"),n=t.context.authCookies.sessionToken.name;if(!ke(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.APIError("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:se(En,e?.schema),$ERROR_CODES:i}};var O=require("zod");var rr=require("better-call"),nr=async e=>{let i=e.context.returned;return i?i instanceof Response?i.status!==200?null:await i.clone().json():i instanceof rr.APIError?null:i:null};var In=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=v(async r=>{let n=await S(r);if(!n?.session)throw new b.APIError("UNAUTHORIZED");let s=n.user;if(!s.role||(Array.isArray(i.adminRole)?!i.adminRole.includes(s.role):s.role!==i.adminRole))throw new b.APIError("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:v(async r=>{let n=await nr(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.z.object({userId:O.z.string({description:"The user id"}),role:O.z.string({description:"The role to set. `admin` or `user` by default"})}),use:[o],metadata:{openapi:{operationId:"setRole",summary:"Set the role of a user",description:"Set the role of a user",responses:{200:{description:"User role updated",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async 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.z.object({email:O.z.string({description:"The email of the user"}),password:O.z.string({description:"The password of the user"}),name:O.z.string({description:"The name of the user"}),role:O.z.string({description:"The role of the user"}),data:O.z.optional(O.z.record(O.z.any(),{description:"Extra fields for the user. Including custom additional fields."}))}),use:[o],metadata:{openapi:{operationId:"createUser",summary:"Create a new user",description:"Create a new user",responses:{200:{description:"User created",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async r=>{if(await r.context.internalAdapter.findUserByEmail(r.body.email))throw new b.APIError("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.APIError("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.z.object({searchValue:O.z.string({description:"The value to search for"}).optional(),searchField:O.z.enum(["email","name"],{description:"The field to search in, defaults to email. Can be `email` or `name`"}).optional(),searchOperator:O.z.enum(["contains","starts_with","ends_with"],{description:"The operator to use for the search. Can be `contains`, `starts_with` or `ends_with`"}).optional(),limit:O.z.string({description:"The number of users to return"}).or(O.z.number()).optional(),offset:O.z.string({description:"The offset to start from"}).or(O.z.number()).optional(),sortBy:O.z.string({description:"The field to sort by"}).optional(),sortDirection:O.z.enum(["asc","desc"],{description:"The direction to sort by"}).optional(),filterField:O.z.string({description:"The field to filter by"}).optional(),filterValue:O.z.string({description:"The value to filter by"}).or(O.z.number()).or(O.z.boolean()).optional(),filterOperator:O.z.enum(["eq","ne","lt","lte","gt","gte"],{description:"The operator to use for the filter"}).optional()}),metadata:{openapi:{operationId:"listUsers",summary:"List users",description:"List users",responses:{200:{description:"List of users",content:{"application/json":{schema:{type:"object",properties:{users:{type:"array",items:{$ref:"#/components/schemas/User"}}}}}}}}}}},async 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.z.object({userId:O.z.string({description:"The user id"})}),metadata:{openapi:{operationId:"listUserSessions",summary:"List user sessions",description:"List user sessions",responses:{200:{description:"List of user sessions",content:{"application/json":{schema:{type:"object",properties:{sessions:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}}}}}}}},async r=>({sessions:await r.context.internalAdapter.listSessions(r.body.userId)})),unbanUser:p("/admin/unban-user",{method:"POST",body:O.z.object({userId:O.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"unbanUser",summary:"Unban a user",description:"Unban a user",responses:{200:{description:"User unbanned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async 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.z.object({userId:O.z.string({description:"The user id"}),banReason:O.z.string({description:"The reason for the ban"}).optional(),banExpiresIn:O.z.number({description:"The number of seconds until the ban expires"}).optional()}),use:[o],metadata:{openapi:{operationId:"banUser",summary:"Ban a user",description:"Ban a user",responses:{200:{description:"User banned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async r=>{if(r.body.userId===r.context.session.user.id)throw new b.APIError("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.z.object({userId:O.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"impersonateUser",summary:"Impersonate a user",description:"Impersonate a user",responses:{200:{description:"Impersonation session created",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async r=>{let n=await r.context.internalAdapter.findUserById(r.body.userId);if(!n)throw new b.APIError("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.APIError("INTERNAL_SERVER_ERROR",{message:t.FAILED_TO_CREATE_USER});let A=r.context.authCookies;return q(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.APIError("UNAUTHORIZED");if(!n.session.impersonatedBy)throw new b.APIError("BAD_REQUEST",{message:"You are not impersonating anyone"});let s=await r.context.internalAdapter.findUserById(n.session.impersonatedBy);if(!s)throw new b.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to find user"});let A=await r.getSignedCookie("admin_session",r.context.secret);if(!A)throw new b.APIError("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.APIError("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.z.object({sessionToken:O.z.string({description:"The session token"})}),use:[o],metadata:{openapi:{operationId:"revokeUserSession",summary:"Revoke a user session",description:"Revoke a user session",responses:{200:{description:"Session revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async r=>(await r.context.internalAdapter.deleteSession(r.body.sessionToken),r.json({success:!0}))),revokeUserSessions:p("/admin/revoke-user-sessions",{method:"POST",body:O.z.object({userId:O.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"revokeUserSessions",summary:"Revoke all user sessions",description:"Revoke all user sessions",responses:{200:{description:"Sessions revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async r=>(await r.context.internalAdapter.deleteSessions(r.body.userId),r.json({success:!0}))),removeUser:p("/admin/remove-user",{method:"POST",body:O.z.object({userId:O.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"removeUser",summary:"Remove a user",description:"Delete a user and all their sessions and accounts. Cannot be undone.",responses:{200:{description:"User removed",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async r=>(await r.context.internalAdapter.deleteUser(r.body.userId),r.json({success:!0})))},$ERROR_CODES:t,schema:se(Sn,i.schema)}},Sn={user:{fields:{role:{type:"string",required:!1,input:!1},banned:{type:"boolean",defaultValue:!1,required:!1,input:!1},banReason:{type:"string",required:!1,input:!1},banExpires:{type:"date",required:!1,input:!1}}},session:{fields:{impersonatedBy:{type:"string",required:!1}}}};var ro=require("@better-fetch/fetch"),ve=require("better-call"),ar=require("oslo/jwt"),ce=require("zod");async function sr(e,i){if(e.idToken){let o=(0,ar.parseJWT)(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(0,ro.betterFetch)(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 Un=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 k({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(0,ro.betterFetch)(o.discoveryUrl,{method:"GET"});a.data&&(A=a.data.token_endpoint,n=a.data.userinfo_endpoint)}if(!A)throw new ve.APIError("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 sr(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.z.object({currentURL:ce.z.string({description:"Redirect to the current URL after sign in"}).optional()}).optional(),body:ce.z.object({providerId:ce.z.string({description:"The provider ID for the OAuth provider"}),callbackURL:ce.z.string({description:"The URL to redirect to after sign in"}).optional(),errorCallbackURL:ce.z.string({description:"The URL to redirect to if an error occurs"}).optional()}),metadata:{openapi:{description:"Sign in with OAuth2",responses:{200:{description:"Sign in with OAuth2",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}}}}}}}}}},async t=>{let{providerId:o}=t.body,r=e.config.find(j=>j.providerId===o);if(!r)throw new ve.APIError("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 j=await(0,ro.betterFetch)(n,{onError(ao){t.context.logger.error(ao.error.message,ao.error,{discoveryUrl:n})}});j.data&&(N=j.data.authorization_endpoint,w=j.data.token_endpoint)}if(!N||!w)throw new ve.APIError("BAD_REQUEST",{message:i.INVALID_OAUTH_CONFIGURATION});let{state:R,codeVerifier:h}=await Ne(t),T=await k({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.z.object({code:ce.z.string({description:"The OAuth2 code"}).optional(),error:ce.z.string({description:"The error message, if any"}).optional(),state:ce.z.string({description:"The state parameter from the OAuth2 request"})}),metadata:{openapi:{description:"OAuth2 callback",responses:{200:{description:"OAuth2 callback",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"}}}}}}}}}},async t=>{if(t.query.error||!t.query.code)throw t.redirect(`${t.context.baseURL}?error=${t.query.error||"oAuth_code_missing"}`);let o=e.config.find(h=>h.providerId===t.params.providerId);if(!o)throw new ve.APIError("BAD_REQUEST",{message:`No config found for provider ${t.params.providerId}`});let r,n=await go(t),{callbackURL:s,codeVerifier:A,errorURL:a}=n,d=t.query.code,c=o.tokenUrl,u=o.userInfoUrl;if(o.discoveryUrl){let h=await(0,ro.betterFetch)(o.discoveryUrl,{method:"GET"});h.data&&(c=h.data.token_endpoint,u=h.data.userinfo_endpoint)}try{if(!c)throw new ve.APIError("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.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let l=o.getUserInfo?await o.getUserInfo(r):await sr(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 Be(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}};var Ge=require("zod"),Ar={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0}}}},ku=Ge.z.object({id:Ge.z.string(),publicKey:Ge.z.string(),privateKey:Ge.z.string(),createdAt:Ge.z.date()});var ti=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}})});var ye=require("jose");var _n=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 ti(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=ti(i.context.adapter),o=await t.getLatestKey(),r=!e?.jwks?.disablePrivateKeyEncryption;if(o===void 0){let{publicKey:d,privateKey:c}=await(0,ye.generateKeyPair)(e?.jwks?.keyPairConfig?.alg??"EdDSA",e?.jwks?.keyPairConfig??{crv:"Ed25519"}),u=await(0,ye.exportJWK)(d),l=await(0,ye.exportJWK)(c),K=JSON.stringify(l),m={id:crypto.randomUUID(),publicKey:JSON.stringify(u),privateKey:r?JSON.stringify(await he({key:i.context.options.secret,data:K})):K,createdAt:new Date};o=await t.createJwk(m)}let n=r?await Ce({key:i.context.options.secret,data:JSON.parse(o.privateKey)}):o.privateKey,s=await(0,ye.importJWK)(JSON.parse(n)),A=e?.jwt?.definePayload?await e?.jwt.definePayload(i.context.session.user):i.context.session.user,a=await new ye.SignJWT({...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:se(Ar,e?.schema)});var no=require("zod");var vn=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(Je(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:no.z.object({sessionToken:no.z.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.APIError("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.APIError("UNAUTHORIZED",{message:o.INVALID_SESSION_TOKEN});return await f(r,a),r.json(a)}),revokeDeviceSession:p("/multi-session/revoke",{method:"POST",body:no.z.object({sessionToken:no.z.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.APIError("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(Je(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 q(r)}else q(r)}else q(r);return r.json({success:!0})})},hooks:{after:[{matcher:()=>!0,handler:v(async r=>{let n=r.responseHeader.get("set-cookie");if(!n)return;let s=ke(n),A=r.context.authCookies.sessionToken,a=s.get(A.name)?.value;if(!a)return;let d=Je(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:v(async r=>{let n=r.headers?.get("cookie");if(!n)return;let s=Object.fromEntries(Je(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}};var B=require("zod");var ri=["email-verification","sign-in","forget-password"],kn=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.z.object({email:B.z.string({description:"Email address to send the OTP"}),type:B.z.enum(ri,{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.APIError("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.APIError("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.z.object({email:B.z.string({description:"Email address to send the OTP"}),type:B.z.enum(ri,{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.z.object({email:B.z.string({description:"Email address to get the OTP"}),type:B.z.enum(ri)}),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.z.object({email:B.z.string({description:"Email address to verify"}),otp:B.z.string({description:"OTP to verify"})}),metadata:{openapi:{description:"Verify email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async o=>{let r=o.body.email;if(!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r))throw new b.APIError("BAD_REQUEST",{message:t.INVALID_EMAIL});let s=await o.context.internalAdapter.findVerificationValue(`email-verification-otp-${r}`);if(!s)throw new b.APIError("BAD_REQUEST",{message:t.INVALID_OTP});if(s.expiresAt<new Date)throw await o.context.internalAdapter.deleteVerificationValue(s.id),new b.APIError("BAD_REQUEST",{message:t.OTP_EXPIRED});let A=o.body.otp;if(s.value!==A)throw new b.APIError("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.APIError("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.z.object({email:B.z.string({description:"Email address to sign in"}),otp:B.z.string({description:"OTP sent to the email"})}),metadata:{openapi:{description:"Sign in with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async o=>{let r=o.body.email,n=await o.context.internalAdapter.findVerificationValue(`sign-in-otp-${r}`);if(!n)throw new b.APIError("BAD_REQUEST",{message:t.INVALID_OTP});if(n.expiresAt<new Date)throw await o.context.internalAdapter.deleteVerificationValue(n.id),new b.APIError("BAD_REQUEST",{message:t.OTP_EXPIRED});let s=o.body.otp;if(n.value!==s)throw new b.APIError("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.APIError("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.z.object({email:B.z.string({description:"Email address to send the OTP"})}),metadata:{openapi:{description:"Forget password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{let r=o.body.email;if(!await o.context.internalAdapter.findUserByEmail(r))throw new b.APIError("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.z.object({email:B.z.string({description:"Email address to reset the password"}),otp:B.z.string({description:"OTP sent to the email"}),password:B.z.string({description:"New password"})}),metadata:{openapi:{description:"Reset password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{let r=o.body.email,n=await o.context.internalAdapter.findUserByEmail(r);if(!n)throw new b.APIError("BAD_REQUEST",{message:t.USER_NOT_FOUND});let s=await o.context.internalAdapter.findVerificationValue(`forget-password-otp-${r}`);if(!s)throw new b.APIError("BAD_REQUEST",{message:t.INVALID_OTP});if(s.expiresAt<new Date)throw await o.context.internalAdapter.deleteVerificationValue(s.id),new b.APIError("BAD_REQUEST",{message:t.OTP_EXPIRED});let A=o.body.otp;if(s.value!==A)throw new b.APIError("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}};var ni=require("zod");var cr=require("@better-fetch/fetch");function dr(e){return e==="true"||e===!0}var Pn=e=>({id:"one-tap",endpoints:{oneTapCallback:p("/one-tap/callback",{method:"POST",body:ni.z.object({idToken:ni.z.string({description:"Google ID token, which the client obtains from the One Tap API"})}),metadata:{openapi:{summary:"One tap callback",description:"Use this endpoint to authenticate with Google One Tap",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}},400:{description:"Invalid token"}}}}},async i=>{let{idToken:t}=i.body,{data:o,error:r}=await(0,cr.betterFetch)("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.APIError("BAD_GATEWAY",{message:"User not found"});let A=await i.context.internalAdapter.createOAuthUser({email:o.email,emailVerified:dr(o.email_verified),name:o.name,image:o.picture},{providerId:"google",accountId:o.sub});if(!A)throw new b.APIError("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})})}});var Eo=require("zod");function Nn(){let e=de.VERCEL_URL,i=de.NETLIFY_URL,t=de.RENDER_URL,o=de.AWS_LAMBDA_FUNCTION_NAME,r=de.GOOGLE_CLOUD_FUNCTION_NAME,n=de.AZURE_FUNCTION_NAME;return e||i||t||o||r||n}var Dn=e=>({id:"oauth-proxy",endpoints:{oAuthProxy:p("/oauth-proxy-callback",{method:"GET",query:Eo.z.object({callbackURL:Eo.z.string({description:"The URL to redirect to after the proxy"}),cookies:Eo.z.string({description:"The cookies to set after the proxy"})}),metadata:{openapi:{description:"OAuth Proxy Callback",parameters:[{in:"query",name:"callbackURL",required:!0,description:"The URL to redirect to after the proxy"},{in:"query",name:"cookies",required:!0,description:"The cookies to set after the proxy"}],responses:{302:{description:"Redirect",headers:{Location:{description:"The URL to redirect to",schema:{type:"string"}}}}}}}},async i=>{let t=i.query.cookies,o=await Ce({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:v(async i=>{let t=i.context.returned,o=t instanceof b.APIError?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===Pe(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 he({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||Nn()||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}}}]}});var Qe=require("zod");var Ln=(e,i)=>({id:"custom-session",endpoints:{getSession:p("/get-session",{method:"GET",metadata:{CUSTOM_SESSION:!0},query:Qe.z.optional(Qe.z.object({disableCookieCache:Qe.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(Qe.z.string().transform(t=>t==="true")).optional(),disableRefresh:Qe.z.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)})}});var fe=require("zod");var Ze=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:{}}};var Bn=require("zod");var pr=require("kysely"),si=require("kysely");var so={};function ur(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 Ro(e){let i=[];return e.metadata?.openapi?.parameters?(i.push(...e.metadata.openapi.parameters),i):(e.query instanceof fe.ZodObject&&Object.entries(e.query.shape).forEach(([t,o])=>{o instanceof fe.ZodSchema&&i.push({name:t,in:"query",schema:{type:ur(o),..."minLength"in o&&o.minLength?{minLength:o.minLength}:{},description:o.description}})}),i)}function Kr(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof fe.ZodObject||e.body instanceof fe.ZodOptional)){let i=e.body.shape;if(!i)return;let t={},o=[];return Object.entries(i).forEach(([r,n])=>{n instanceof fe.ZodSchema&&(t[r]={type:ur(n),description:n.description},n instanceof fe.ZodOptional||o.push(r))}),{required:e.body instanceof fe.ZodOptional?!1:!!e.body,content:{"application/json":{schema:{type:"object",properties:t,required:o}}}}}}function Io(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 ai(e,i){let t=Fo(e,{...i,plugins:[]}),o=Ze(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"&&(so[a.path]={get:{tags:["Default",...d.metadata?.openapi?.tags||[]],description:d.metadata?.openapi?.description,operationId:d.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Ro(d),responses:Io(d.metadata?.openapi?.responses)}}),d.method==="POST")){let c=Kr(d);so[a.path]={post:{tags:["Default",...d.metadata?.openapi?.tags||[]],description:d.metadata?.openapi?.description,operationId:d.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Ro(d),...c?{requestBody:c}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:Io(d.metadata?.openapi?.responses)}}}});for(let A of i.plugins||[]){if(A.id==="open-api")continue;let a=Fo(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"&&(so[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:Ro(l),responses:Io(l.metadata?.openapi?.responses)}}),l.method==="POST"&&(so[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:Ro(l),requestBody:Kr(l),responses:Io(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:so}}var lr=`<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>`,rt=p("/error",{method:"GET",metadata:{...Ee,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(Fr(i),{headers:{"Content-Type":"text/html"}})});var nt=So(require("defu"),1);var b=require("better-call");function Fo(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:st,callbackOAuth:At,getSession:Bo(),signOut:dt,signUpEmail:tt(),signInEmail:at,forgetPassword:ct,resetPassword:Kt,verifyEmail:Yi,sendVerificationEmail:Ji,changeEmail:ht,changePassword:lt,setPassword:mt,updateUser:ut(),deleteUser:gt,forgetPasswordCallback:pt,listSessions:$i(),revokeSession:Gi,revokeSessions:Qi,revokeOtherSessions:Zi,linkSocialAccount:wt,listUserAccounts:yt,deleteUserCallback:ft},...t,ok:ot,error:rt},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){(0,W.setCookie)(a.headers,w,R,h)},getCookie(w,R){let T=d.headers?.get("cookie");return(0,W.getCookie)(T||"",w,R)},getSignedCookie(w,R,h){let T=d.headers;return T?(0,W.getSignedCookie)(T,R,w,h):null},async setSignedCookie(w,R,h,T){await(0,W.setSignedCookie)(a.headers,w,R,h,T)},redirect(w){return a.headers.set("Location",w),new W.APIError("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=(0,nt.default)(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 W.APIError){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 j=await h.handler(K);j&&"response"in j&&(K.context.returned=j.response)}catch(j){if(j instanceof W.APIError){K.context.returned=j;continue}throw j}if(K.context.returned instanceof W.APIError)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 j=T.responseHeader;K.responseHeader=j}else K.context.returned=T}catch(T){if(T instanceof W.APIError){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 xe(e,{userInfo:i,account:t,callbackURL:o}){let r=await e.context.internalAdapter.findUserByEmail(i.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw re.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 uo&&re.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 re.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 ue(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 st=p("/sign-in/social",{method:"POST",query:L.z.object({currentURL:L.z.string().optional()}).optional(),body:L.z.object({callbackURL:L.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:L.z.string().optional(),errorCallbackURL:L.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:L.z.enum(fo,{description:"OAuth2 provider to use"}),disableRedirect:L.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:L.z.optional(L.z.object({token:L.z.string({description:"ID token from the provider"}),nonce:L.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:L.z.string({description:"Access token from the provider"}).optional(),refreshToken:L.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:L.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let 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.APIError("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.APIError("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.APIError("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.APIError("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.APIError("UNAUTHORIZED",{message:g.USER_EMAIL_NOT_FOUND});let d=await xe(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.APIError("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 De(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})}),at=p("/sign-in/email",{method:"POST",body:L.z.object({email:L.z.string({description:"Email of the user"}),password:L.z.string({description:"Password of the user"}),callbackURL:L.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:L.z.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new Q.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:i,password:t}=e.body;if(!L.z.string().email().safeParse(i).success)throw new Q.APIError("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.APIError("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.APIError("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.APIError("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.APIError("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.APIError("UNAUTHORIZED",{message:g.EMAIL_NOT_VERIFIED});let d=await ue(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.APIError("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.APIError("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})});var je=require("zod");var wo=je.z.object({code:je.z.string().optional(),error:je.z.string().optional(),error_description:je.z.string().optional(),state:je.z.string().optional()}),At=p("/callback/:id",{method:["GET","POST"],body:wo.optional(),query:wo.optional(),metadata:Ee},async e=>{let i;try{if(e.method==="GET")i=wo.parse(e.query);else if(e.method==="POST")i=wo.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 go(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 xe(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)});var nd=require("zod");var Ct=require("better-call");var dt=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 q(e),new Ct.APIError("BAD_REQUEST",{message:g.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(i),q(e),e.json({success:!0})});var ie=require("zod");var ze=require("better-call");function bt(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 Mr(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 ct=p("/forget-password",{method:"POST",body:ie.z.object({email:ie.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:ie.z.string({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new ze.APIError("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=G(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})}),pt=p("/reset-password/:token",{method:"GET",query:ie.z.object({callbackURL:ie.z.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:i}=e.params,{callbackURL:t}=e.query;if(!i||!t)throw e.redirect(bt(e.context,t,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${i}`);throw!o||o.expiresAt<new Date?e.redirect(bt(e.context,t,{error:"INVALID_TOKEN"})):e.redirect(Mr(e.context,t,{token:i}))}),Kt=p("/reset-password",{query:ie.z.optional(ie.z.object({token:ie.z.string().optional(),currentURL:ie.z.string().optional()})),method:"POST",body:ie.z.object({newPassword:ie.z.string({description:"The new password to set"}),token:ie.z.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let i=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!i)throw new ze.APIError("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 ze.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_SHORT});if(t.length>r)throw new ze.APIError("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 ze.APIError("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}))});var $=require("zod");var M=require("better-call");var qo=require("@noble/ciphers/chacha"),Fe=require("@noble/ciphers/utils"),Ho=require("@noble/ciphers/webcrypto"),$o=require("oslo/crypto"),Mo=So(require("uncrypto"),1);var Ot=require("oslo/encoding");var qr=require("@noble/hashes/scrypt"),Hr=require("uncrypto");var Vo=So(require("uncrypto"),1);function $r(e){return e.toString(2).padStart(8,"0")}function Gr(e){return[...e].map(i=>$r(i)).join("")}function Tt(e){return parseInt(Gr(e),2)}function Qr(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));Vo.default.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1);let r=Tt(o);for(;r>=e;)Vo.default.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1),r=Tt(o);return r}function F(e,i){let t="";for(let o=0;o<e;o++)t+=i[Qr(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 Xe(e,i){let t=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},r=await Mo.default.subtle.importKey("raw",t.encode(e),o,!1,["sign","verify"]),n=await Mo.default.subtle.sign(o.name,r,t.encode(i));return btoa(String.fromCharCode(...new Uint8Array(n)))}var he=async({key:e,data:i})=>{let t=await(0,$o.sha256)(new TextEncoder().encode(e)),o=(0,Fe.utf8ToBytes)(i),r=(0,Ho.managedNonce)(qo.xchacha20poly1305)(new Uint8Array(t));return(0,Fe.bytesToHex)(r.encrypt(o))},Ce=async({key:e,data:i})=>{let t=await(0,$o.sha256)(new TextEncoder().encode(e)),o=(0,Fe.hexToBytes)(i),r=(0,Ho.managedNonce)(qo.xchacha20poly1305)(new Uint8Array(t));return new TextDecoder().decode(r.decrypt(o))};var ut=()=>p("/update-user",{method:"POST",body:$.z.record($.z.string(),$.z.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 M.APIError("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=yo(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})}),lt=p("/change-password",{method:"POST",body:$.z.object({newPassword:$.z.string({description:"The new password to set"}),currentPassword:$.z.string({description:"The current password"}),revokeOtherSessions:$.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[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 M.APIError("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 M.APIError("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 M.APIError("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 M.APIError("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 M.APIError("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_GET_SESSION});await f(e,{session:u,user:r.user})}return e.json(r.user)}),mt=p("/set-password",{method:"POST",body:$.z.object({newPassword:$.z.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 M.APIError("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 M.APIError("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 M.APIError("BAD_REQUEST",{message:"user already has a password"})}),gt=p("/delete-user",{method:"POST",use:[Ye],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 M.APIError("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),q(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(i.user,e.request),e.json({success:!0,message:"User deleted"})}),ft=p("/delete-user/callback",{method:"GET",query:$.z.object({token:$.z.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 M.APIError("NOT_FOUND");let i=await S(e);if(!i)throw new M.APIError("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 M.APIError("NOT_FOUND",{message:g.INVALID_TOKEN});if(t.value!==i.user.id)throw new M.APIError("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),q(e);let r=e.context.options.user.deleteUser?.afterDelete;return r&&await r(i.user,e.request),e.json({success:!0,message:"User deleted"})}),ht=p("/change-email",{method:"POST",query:$.z.object({currentURL:$.z.string().optional()}).optional(),body:$.z.object({newEmail:$.z.string({description:"The new email to set"}).email(),callbackURL:$.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[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 M.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new M.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new M.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let r=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:r,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new M.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await ue(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})});var Ve=require("zod");var Go=require("better-call");var yt=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})))}),wt=p("/link-social",{method:"POST",requireHeaders:!0,query:Ve.z.object({currentURL:Ve.z.string().optional()}).optional(),body:Ve.z.object({callbackURL:Ve.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:Ve.z.enum(fo,{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 Go.APIError("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 Go.APIError("NOT_FOUND",{message:g.PROVIDER_NOT_FOUND});let n=await De(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 Et=(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 Co(e){let i=e;return{newRole(t){return Zr(t)}}}function Zr(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 Wr={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},Qo=Co(Wr),Jr=Qo.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),Yr=Qo.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),Xr=Qo.newRole({organization:[],member:[],invitation:[]}),Rt={admin:Jr,owner:Yr,member:Xr};var en={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*:/},on=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,It={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},tn=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function rn(e){return e instanceof Date&&!isNaN(e.getTime())}function nn(e){let i=tn.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 rn(l)?l:null}function sn(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 It)return It[A];if(!on.test(s)){if(t)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(en).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=nn(u);if(l)return l}return r?r(c,u):u})}catch(d){if(t)throw d;return e}}function St(e,i={strict:!0}){return sn(e,i)}var Ut=St;var z=(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?Ut(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 oe("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}})}};var uc=require("better-call");var H=v(async e=>({})),J=v({use:[I]},async e=>({session:e.context.session}));var ee=require("zod");var D=require("zod");var _t=D.z.string(),an=D.z.enum(["pending","accepted","rejected","canceled"]).default("pending"),yc=D.z.object({id:D.z.string().default(G),name:D.z.string(),slug:D.z.string(),logo:D.z.string().nullish(),metadata:D.z.record(D.z.string()).or(D.z.string().transform(e=>JSON.parse(e))).nullish(),createdAt:D.z.date()}),wc=D.z.object({id:D.z.string().default(G),organizationId:D.z.string(),userId:D.z.string(),role:_t,createdAt:D.z.date()}),Cc=D.z.object({id:D.z.string().default(G),organizationId:D.z.string(),email:D.z.string(),role:_t,status:an,inviterId:D.z.string(),expiresAt:D.z.date()});var x=require("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 vt=e=>p("/organization/invite-member",{method:"POST",use:[H,J],body:ee.z.object({email:ee.z.string({description:"The email address of the user to invite"}),role:ee.z.string({description:"The role to assign to the user"}),organizationId:ee.z.string({description:"The organization ID to invite the user to"}).optional(),resend:ee.z.boolean({description:"Resend the invitation email, if the user is already invited"}).optional()}),metadata:{openapi:{description:"Invite a user to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt"]}}}}}}}},async 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 x.APIError("BAD_REQUEST",{message:"Invitation email is not enabled"});let t=i.context.session,o=i.body.organizationId||t.session.activeOrganizationId;if(!o)throw new x.APIError("BAD_REQUEST",{message:y.ORGANIZATION_NOT_FOUND});let r=z(i.context,i.context.orgOptions),n=await r.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!n)throw new x.APIError("BAD_REQUEST",{message:y.MEMBER_NOT_FOUND});let s=i.context.roles[n.role];if(!s)throw new x.APIError("BAD_REQUEST",{message:y.ROLE_NOT_FOUND});if(s.authorize({invitation:["create"]}).error)throw new x.APIError("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 x.APIError("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 x.APIError("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 x.APIError("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)}),kt=p("/organization/accept-invitation",{method:"POST",body:ee.z.object({invitationId:ee.z.string({description:"The ID of the invitation to accept"})}),use:[H,J],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=z(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new x.APIError("BAD_REQUEST",{message:y.INVITATION_NOT_FOUND});if(o.email!==i.user.email)throw new x.APIError("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}})}),Pt=p("/organization/reject-invitation",{method:"POST",body:ee.z.object({invitationId:ee.z.string({description:"The ID of the invitation to reject"})}),use:[H,J],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=z(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new x.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==i.user.email)throw new x.APIError("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})}),Nt=p("/organization/cancel-invitation",{method:"POST",body:ee.z.object({invitationId:ee.z.string({description:"The ID of the invitation to cancel"})}),use:[H,J],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=z(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o)throw new x.APIError("BAD_REQUEST",{message:y.INVITATION_NOT_FOUND});let r=await t.findMemberByOrgId({userId:i.user.id,organizationId:o.organizationId});if(!r)throw new x.APIError("BAD_REQUEST",{message:y.MEMBER_NOT_FOUND});if(e.context.roles[r.role].authorize({invitation:["cancel"]}).error)throw new x.APIError("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)}),Dt=p("/organization/get-invitation",{method:"GET",use:[H],requireHeaders:!0,query:ee.z.object({id:ee.z.string({description:"The ID of the invitation to get"})}),metadata:{openapi:{description:"Get an invitation by ID",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"},organizationName:{type:"string"},organizationSlug:{type:"string"},inviterEmail:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt","organizationName","organizationSlug","inviterEmail"]}}}}}}}},async e=>{let i=await S(e);if(!i)throw new x.APIError("UNAUTHORIZED",{message:"Not authenticated"});let t=z(e.context,e.context.orgOptions),o=await t.findInvitationById(e.query.id);if(!o||o.status!=="pending"||o.expiresAt<new Date)throw new x.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==i.user.email)throw new x.APIError("FORBIDDEN",{message:y.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let r=await t.findOrganizationById(o.organizationId);if(!r)throw new x.APIError("BAD_REQUEST",{message:y.ORGANIZATION_NOT_FOUND});let n=await t.findMemberByOrgId({userId:o.inviterId,organizationId:o.organizationId});if(!n)throw new x.APIError("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})});var ae=require("zod");var be=require("better-call");var Lt=()=>p("/organization/add-member",{method:"POST",body:ae.z.object({userId:ae.z.string(),role:ae.z.string(),organizationId:ae.z.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=z(e.context,e.context.orgOptions),r=await e.context.internalAdapter.findUserById(e.body.userId);if(!r)throw new be.APIError("BAD_REQUEST",{message:g.USER_NOT_FOUND});if(await o.findMemberByEmail({email:r.email,organizationId:t}))throw new be.APIError("BAD_REQUEST",{message:y.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION});let s=await o.createMember({id:G(),organizationId:t,userId:r.id,role:e.body.role,createdAt:new Date});return e.json(s)}),Bt=p("/organization/remove-member",{method:"POST",body:ae.z.object({memberIdOrEmail:ae.z.string({description:"The ID or email of the member to remove"}),organizationId:ae.z.string({description:"The ID of the organization to remove the member from. If not provided, the active organization will be used"}).optional()}),use:[H,J],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=z(e.context,e.context.orgOptions),r=await o.findMemberByOrgId({userId:i.user.id,organizationId:t});if(!r)throw new be.APIError("BAD_REQUEST",{message:y.MEMBER_NOT_FOUND});let n=e.context.roles[r.role];if(!n)throw new be.APIError("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 be.APIError("BAD_REQUEST",{message:y.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER});if(!(s||n.authorize({member:["delete"]}).success))throw new be.APIError("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 be.APIError("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})}),xt=e=>p("/organization/update-member-role",{method:"POST",body:ae.z.object({role:ae.z.string(),memberId:ae.z.string(),organizationId:ae.z.string().optional()}),use:[H,J],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=z(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}})}),jt=p("/organization/get-active-member",{method:"GET",use:[H,J],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 z(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}})});var _=require("zod");var me=require("better-call");var zt=p("/organization/create",{method:"POST",body:_.z.object({name:_.z.string({description:"The name of the organization"}),slug:_.z.string({description:"The slug of the organization"}),userId:_.z.string({description:"The user id of the organization creator. If not provided, the current user will be used. Should only be used by admins or when called by the server."}).optional(),logo:_.z.string({description:"The logo of the organization"}).optional(),metadata:_.z.record(_.z.string(),_.z.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.APIError("UNAUTHORIZED");let t=i?.user||null;if(!t){if(!e.body.userId)throw new me.APIError("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.APIError("FORBIDDEN",{message:y.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION});let n=z(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.APIError("FORBIDDEN",{message:y.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS});if(await n.findOrganizationBySlug(e.body.slug))throw new me.APIError("BAD_REQUEST",{message:y.ORGANIZATION_ALREADY_EXISTS});let d=await n.createOrganization({organization:{id:G(),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)}),Ft=p("/organization/update",{method:"POST",body:_.z.object({data:_.z.object({name:_.z.string({description:"The name of the organization"}).optional(),slug:_.z.string({description:"The slug of the organization"}).optional(),logo:_.z.string({description:"The logo of the organization"}).optional(),metadata:_.z.record(_.z.string(),_.z.any(),{description:"The metadata of the organization"}).optional()}).partial(),organizationId:_.z.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.APIError("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=z(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)}),Vt=p("/organization/delete",{method:"POST",body:_.z.object({organizationId:_.z.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=z(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.APIError("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)}),Mt=p("/organization/get-full-organization",{method:"GET",query:_.z.optional(_.z.object({organizationId:_.z.string({description:"The organization id to get"}).optional(),organizationSlug:_.z.string({description:"The organization slug to get"}).optional()})),requireHeaders:!0,use:[H,J],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 z(e.context,e.context.orgOptions).findFullOrganization({organizationId:t,isSlug:!!e.query?.organizationSlug});if(!r)throw new me.APIError("BAD_REQUEST",{message:y.ORGANIZATION_NOT_FOUND});return e.json(r)}),qt=p("/organization/set-active",{method:"POST",body:_.z.object({organizationId:_.z.string({description:"The organization id to set as active. It can be null to unset the active organization"}).nullable().optional(),organizationSlug:_.z.string({description:"The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided"}).optional()}),use:[J,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=z(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.APIError("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)}),Ht=p("/organization/list",{method:"GET",use:[H,J],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 z(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(t)});var An=Co({name:["action"]}),rp=An.newRole({name:["action"]}),dn=e=>{let i={createOrganization:zt,updateOrganization:Ft,deleteOrganization:Vt,setActiveOrganization:qt,getFullOrganization:Mt,listOrganizations:Ht,createInvitation:vt(e),cancelInvitation:Nt,acceptInvitation:kt,getInvitation:Dt,rejectInvitation:Pt,addMember:Lt(),removeMember:Bt,updateMemberRole:xt(e),getActiveMember:jt},t={...Rt,...e?.roles};return{id:"organization",endpoints:{...Et(i,{orgOptions:e||{},roles:t,getSession:async r=>await S(r)}),hasPermission:p("/organization/has-permission",{method:"POST",requireHeaders:!0,body:Ie.z.object({organizationId:Ie.z.string().optional(),permission:Ie.z.record(Ie.z.string(),Ie.z.array(Ie.z.string()))}),use:[J],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 Zo.APIError("BAD_REQUEST",{message:y.NO_ACTIVE_ORGANIZATION});let A=await z(r.context).findMemberByOrgId({userId:r.context.session.user.id,organizationId:n});if(!A)throw new Zo.APIError("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}};var io=require("zod");var ge=require("zod");var Me=require("better-call");var bo="two_factor";var Oo="trust_device";var Wo=require("zod");var Se=v({body:Wo.z.object({trustDevice:Wo.z.boolean().optional()})},async e=>{let i=await S(e);if(!i){let t=e.context.createAuthCookie(bo),o=await e.getSignedCookie(t.name,e.context.secret);if(!o)throw new Me.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let r=await e.context.internalAdapter.findUserById(o);if(!r)throw new Me.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let n=await e.context.internalAdapter.createSession(o,e.request);if(!n)throw new Me.APIError("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(Oo,{maxAge:2592e3}),A=await Xe(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 Me.APIError("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 Me.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:i}});var qe=require("better-call");var Y={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 cn(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 Jo(e,i){let t=e,o=i?.customBackupCodesGenerate?i.customBackupCodesGenerate():cn(),r=await he({data:JSON.stringify(o),key:t});return{backupCodes:o,encryptedBackupCodes:r}}async function pn(e,i){let t=await $t(e.backupCodes,i);return t?{status:t.includes(e.code),updated:t.filter(o=>o!==e.code)}:{status:!1,updated:null}}async function $t(e,i){let t=Buffer.from(await Ce({key:i,data:e})).toString("utf-8"),o=JSON.parse(t),r=ge.z.array(ge.z.string()).safeParse(o);return r.success?r.data:null}var Gt=(e,i)=>({id:"backup_code",endpoints:{verifyBackupCode:p("/two-factor/verify-backup-code",{method:"POST",body:ge.z.object({code:ge.z.string(),disableSession:ge.z.boolean().optional()}),use:[Se]},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 qe.APIError("BAD_REQUEST",{message:Y.BACKUP_CODES_NOT_ENABLED});let n=await pn({backupCodes:r.backupCodes,code:t.body.code},t.context.secret);if(!n.status)throw new qe.APIError("UNAUTHORIZED",{message:Y.INVALID_BACKUP_CODE});let s=await he({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.z.object({password:ge.z.string()}),use:[I]},async t=>{let o=t.context.session.user;if(!o.twoFactorEnabled)throw new qe.APIError("BAD_REQUEST",{message:Y.TWO_FACTOR_NOT_ENABLED});await t.context.password.checkPassword(o.id,t);let r=await Jo(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.z.object({userId:ge.z.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 qe.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let r=await $t(o.backupCodes,t.context.secret);if(!r)throw new qe.APIError("BAD_REQUEST",{message:Y.BACKUP_CODES_NOT_ENABLED});return t.json({status:!0,backupCodes:r})})}});var He=require("better-call"),Yo=require("zod");var Qt=require("oslo");var Zt=(e,i)=>{let t={...e,digits:e?.digits||6,period:new Qt.TimeSpan(e?.period||3,"m")},o=p("/two-factor/send-otp",{method:"POST",use:[Se],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 He.APIError("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 He.APIError("BAD_REQUEST",{message:Y.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:Yo.z.object({code:Yo.z.string({description:"The otp code to verify"})}),use:[Se],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 He.APIError("BAD_REQUEST",{message:"two factor isn't enabled"});if(!await n.context.adapter.findOne({model:i,where:[{field:"userId",value:s.id}]}))throw new He.APIError("BAD_REQUEST",{message:Y.OTP_NOT_ENABLED});let a=await n.context.internalAdapter.findVerificationValue(`2fa-otp-${s.id}`);if(!a||a.expiresAt<new Date)throw new He.APIError("BAD_REQUEST",{message:Y.OTP_HAS_EXPIRED});return a.value===n.body.code?n.context.valid():n.context.invalid()});return{id:"otp",endpoints:{sendTwoFactorOTP:o,verifyTwoFactorOTP:r}}};var Ue=require("better-call"),Wt=require("oslo"),oo=require("oslo/otp"),eo=require("zod");var Jt=(e,i)=>{let t={...e,digits:e?.digits||6,period:new Wt.TimeSpan(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 Ue.APIError("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 Ue.APIError("BAD_REQUEST",{message:Y.TOTP_NOT_ENABLED});return{code:await new oo.TOTPController(t).generate(Buffer.from(a.secret))}}),r=p("/two-factor/get-totp-uri",{method:"POST",use:[I],body:eo.z.object({password:eo.z.string({description:"User password"})}),metadata:{openapi:{summary:"Get TOTP URI",description:"Use this endpoint to get the TOTP URI",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{totpURI:{type:"string"}}}}}}}}}},async s=>{if(!e)throw s.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new Ue.APIError("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 Ue.APIError("BAD_REQUEST",{message:Y.TOTP_NOT_ENABLED});return await s.context.password.checkPassword(A.id,s),{totpURI:(0,oo.createTOTPKeyURI)(e.issuer||s.context.appName,A.email,Buffer.from(a.secret),t)}}),n=p("/two-factor/verify-totp",{method:"POST",body:eo.z.object({code:eo.z.string({description:"The otp code to verify"})}),use:[Se],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 Ue.APIError("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 Ue.APIError("BAD_REQUEST",{message:Y.TOTP_NOT_ENABLED});let d=new oo.TOTPController(t),c=await Ce({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}}};var Kn=require("better-call");async function Xo(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})}var ei=require("better-call"),Xt=require("oslo/otp"),er=require("oslo");var Yt={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 un=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 ln=e=>{let i={twoFactorTable:"twoFactor"},t=Jt({issuer:e?.issuer,...e?.totpOptions},i.twoFactorTable),o=Gt({...e?.backupCodeOptions},i.twoFactorTable),r=Zt({...e?.otpOptions},i.twoFactorTable);return{id:"two-factor",endpoints:{...t.endpoints,...r.endpoints,...o.endpoints,enableTwoFactor:p("/two-factor/enable",{method:"POST",body:io.z.object({password:io.z.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 Xo(n,{password:A,userId:s.id}))throw new ei.APIError("BAD_REQUEST",{message:g.INVALID_PASSWORD});let d=F(16,V("a-z","0-9","-")),c=await he({key:n.context.secret,data:d}),u=await Jo(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=(0,Xt.createTOTPKeyURI)(e?.issuer||"BetterAuth",s.email,Buffer.from(d),{digits:e?.totpOptions?.digits||6,period:new er.TimeSpan(e?.totpOptions?.period||30,"s")});return n.json({totpURI:l,backupCodes:u.backupCodes})}),disableTwoFactor:p("/two-factor/disable",{method:"POST",body:io.z.object({password:io.z.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 Xo(n,{password:A,userId:s.id}))throw new ei.APIError("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:v(async n=>{let s=n.context.newSession;if(!s||!s?.user.twoFactorEnabled)return;let A=n.context.createAuthCookie(Oo),a=await n.getSignedCookie(A.name,n.context.secret);if(a){let[c,u]=a.split("!"),l=await Xe(n.context.secret,`${s.user.id}!${u}`);if(c===l){let K=await Xe(n.context.secret,`${s.user.id}!${s.session.token}`);await n.setSignedCookie(A.name,`${K}!${s.session.token}`,n.context.secret,A.attributes);return}}q(n),await n.context.internalAdapter.deleteSession(s.session.token);let d=n.context.createAuthCookie(bo,{maxAge:60*10});return await n.setSignedCookie(d.name,s.user.id,n.context.secret,d.attributes),n.json({twoFactorRedirect:!0})})}]},schema:se(Yt,e?.schema),rateLimit:[{pathMatcher(n){return n.startsWith("/two-factor/")},window:10,max:3}]}};var Oe=require("@simplewebauthn/server"),X=require("better-call");var te=require("zod");var $e=require("@simplewebauthn/browser");var gn=require("@better-fetch/fetch");var uK=require("nanostores");var oK=require("@better-fetch/fetch");var mn=require("nanostores");var tK=require("@better-fetch/fetch"),To=require("nanostores"),oi=(e,i,t,o)=>{let r=(0,To.atom)({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():(0,To.onMount)(r,()=>(n(),s=!0,()=>{r.off(),A.off()}))});return r};var or=require("nanostores"),ir=(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(0,$e.startAuthentication)(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(0,$e.startRegistration)(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 $e.WebAuthnError?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:{}}),fn=()=>{let e=(0,or.atom)();return{id:"passkey",$InferServerPlugin:{},getActions:i=>ir(i,{$listPasskeys:e}),getAtoms(i){return{listPasskeys:oi(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 hn=e=>{let i=de.BETTER_AUTH_URL,t=e?.rpID||i?.replace("http://","").replace("https://","").split(":")[0]||"localhost";if(!t)throw new oe("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:[Ye],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(0,Oe.generateRegistrationOptions)({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=G(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:te.z.object({email:te.z.string({description:"The email address of the user"}).optional()}).optional(),metadata:{openapi:{description:"Generate authentication options for a passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{challenge:{type:"string"},rp:{type:"object",properties:{name:{type:"string"},id:{type:"string"}}},user:{type:"object",properties:{id:{type:"string"},name:{type:"string"},displayName:{type:"string"}}},timeout:{type:"number"},allowCredentials:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string"},transports:{type:"array",items:{type:"string"}}}}},userVerification:{type:"string"},authenticatorSelection:{type:"object",properties:{authenticatorAttachment:{type:"string"},requireResidentKey:{type:"boolean"},userVerification:{type:"string"}}},extensions:{type:"object"}}}}}}}}}},async 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(0,Oe.generateAuthenticationOptions)({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=G(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:te.z.object({response:te.z.any({description:"The response from the authenticator"}),name:te.z.string({description:"Name of the passkey"}).optional()}),use:[Ye],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 X.APIError("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 X.APIError("UNAUTHORIZED",{message:A.YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY});try{let C=await(0,Oe.verifyRegistrationResponse)({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:j,credentialBackedUp:ao}=w,mr=Buffer.from(h).toString("base64"),gr={name:a.body.name,userId:m.id,webauthnUserID:a.context.generateId({model:"passkey"}),id:R,publicKey:mr,counter:T,deviceType:j,transports:c.response.transports.join(","),backedUp:ao,createdAt:new Date},fr=await a.context.adapter.create({model:"passkey",data:gr});return a.json(fr,{status:200})}catch(C){throw console.log(C),new X.APIError("INTERNAL_SERVER_ERROR",{message:A.FAILED_TO_VERIFY_REGISTRATION})}}),verifyPasskeyAuthentication:p("/passkey/verify-authentication",{method:"POST",body:te.z.object({response:te.z.any()}),metadata:{openapi:{description:"Verify authentication of a passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async a=>{let d=e?.origin||a.headers?.get("origin")||"";if(!d)throw new X.APIError("BAD_REQUEST",{message:"origin missing"});let c=a.body.response,u=await a.getSignedCookie(o.advanced.webAuthnChallengeCookie,a.context.secret);if(!u)throw new X.APIError("BAD_REQUEST",{message:A.CHALLENGE_NOT_FOUND});let l=await a.context.internalAdapter.findVerificationValue(u);if(!l)throw new X.APIError("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 X.APIError("UNAUTHORIZED",{message:A.PASSKEY_NOT_FOUND});try{let C=await(0,Oe.verifyAuthenticationResponse)({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 X.APIError("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 X.APIError("INTERNAL_SERVER_ERROR",{message:A.UNABLE_TO_CREATE_SESSION});let R=await a.context.internalAdapter.findUserById(m.userId);if(!R)throw new X.APIError("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 X.APIError("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:te.z.object({id:te.z.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:te.z.object({id:te.z.string(),name:te.z.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 X.APIError("NOT_FOUND",{message:A.PASSKEY_NOT_FOUND});if(d.userId!==a.context.session.user.id)throw new X.APIError("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 X.APIError("INTERNAL_SERVER_ERROR",{message:A.FAILED_TO_UPDATE_PASSKEY});return a.json({passkey:c},{status:200})})},schema:se(yn,e?.schema),$ERROR_CODES:A}},yn={passkey:{fields:{name:{type:"string",required:!1},publicKey:{type:"string",required:!0},userId:{type:"string",references:{model:"user",field:"id"},required:!0},webauthnUserID:{type:"string",required:!0},counter:{type:"number",required:!0},deviceType:{type:"string",required:!0},backedUp:{type:"boolean",required:!0},transports:{type:"string",required:!1},createdAt:{type:"date",required:!1}}}};var to=require("zod");var _e=require("better-call");var ii=()=>{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:to.z.object({username:to.z.string({description:"The username of the user"}),password:to.z.string({description:"The password of the user"}),rememberMe:to.z.boolean({description:"Remember the user session"}).optional()}),metadata:{openapi:{summary:"Sign in with username",description:"Sign in with username",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async 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:ii}),new _e.APIError("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});if(!t.emailVerified&&i.context.options.emailAndPassword?.requireEmailVerification)throw await xo(i,t),new _e.APIError("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 _e.APIError("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});let r=o?.password;if(!r)throw i.context.logger.error("Password not found",{username:ii}),new _e.APIError("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 _e.APIError("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 _e.APIError("UNPROCESSABLE_ENTITY",{message:e.USERNAME_IS_ALREADY_TAKEN})}}]},$ERROR_CODES:Y}};var ZK=require("better-call");var wn=()=>({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:v(async e=>{let i=e.responseHeader.get("set-cookie");if(!i)return;let t=Pe(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}})}]}});var ve=require("zod");var tr=require("better-call");var Cn=e=>({id:"magic-link",endpoints:{signInMagicLink:p("/sign-in/magic-link",{method:"POST",requireHeaders:!0,body:ve.z.object({email:ve.z.string({description:"Email address to send the magic link"}).email(),callbackURL:ve.z.string({description:"URL to redirect after magic link verification"}).optional()}),metadata:{openapi:{description:"Sign in with magic link",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async i=>{let{email:t}=i.body;if(e.disableSignUp&&!await i.context.internalAdapter.findUserByEmail(t))throw new tr.APIError("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:ve.z.object({token:ve.z.string({description:"Verification token"}),callbackURL:ve.z.string({description:"URL to redirect after magic link verification, if not provided will return session"}).optional()}),requireHeaders:!0,metadata:{openapi:{description:"Verify magic link",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async 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}]});var Ae=require("zod");var Z=require("better-call");function bn(e){return F(e,V("0-9"))}var On=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.z.object({phoneNumber:Ae.z.string({description:"Phone number to sign in"}),password:Ae.z.string({description:"Password to use for sign in"}),rememberMe:Ae.z.boolean({description:"Remember the session"}).optional()}),metadata:{openapi:{summary:"Sign in with phone number",description:"Use this endpoint to sign in with phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}},400:{description:"Invalid phone number or password"}}}}},async o=>{let{password:r,phoneNumber:n}=o.body;if(i.phoneNumberValidator&&!await i.phoneNumberValidator(o.body.phoneNumber))throw new Z.APIError("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 Z.APIError("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 Z.APIError("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 Z.APIError("UNAUTHORIZED",{message:t.UNEXPECTED_ERROR});if(!await o.context.password.verify({hash:d,password:r}))throw o.context.logger.error("Invalid password"),new Z.APIError("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 Z.APIError("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.z.object({phoneNumber:Ae.z.string({description:"Phone number to send OTP"})}),metadata:{openapi:{summary:"Send OTP to phone number",description:"Use this endpoint to send OTP to phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async o=>{if(!e?.sendOTP)throw o.context.logger.warn("sendOTP not implemented"),new Z.APIError("NOT_IMPLEMENTED",{message:"sendOTP not implemented"});if(i.phoneNumberValidator&&!await i.phoneNumberValidator(o.body.phoneNumber))throw new Z.APIError("BAD_REQUEST",{message:t.INVALID_PHONE_NUMBER});let r=bn(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.z.object({phoneNumber:Ae.z.string({description:"Phone number to verify"}),code:Ae.z.string({description:"OTP code"}),disableSession:Ae.z.boolean({description:"Disable session creation after verification"}).optional(),updatePhoneNumber:Ae.z.boolean({description:"Check if there is a session and update the phone number"}).optional()}),metadata:{openapi:{summary:"Verify phone number",description:"Use this endpoint to verify phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}},400:{description:"Invalid OTP"}}}}},async o=>{let 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 Z.APIError("BAD_REQUEST",{message:"OTP expired"})):new Z.APIError("BAD_REQUEST",{message:t.OTP_NOT_FOUND});if(r.value!==o.body.code)throw new Z.APIError("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 Z.APIError("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 Z.APIError("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_CREATE_USER})}else return o.json(null);if(!n)throw new Z.APIError("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 Z.APIError("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:se(Tn,e?.schema),$ERROR_CODES:t}},Tn={user:{fields:{phoneNumber:{type:"string",required:!1,unique:!0,returned:!0},phoneNumberVerified:{type:"boolean",required:!1,returned:!0,input:!1}}}};var En={user:{fields:{isAnonymous:{type:"boolean",required:!1}}}},Rn=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=Ne(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:v(async t=>{let r=t.responseHeader.get("set-cookie"),n=t.context.authCookies.sessionToken.name;if(!Pe(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.APIError("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:se(En,e?.schema),$ERROR_CODES:i}};var O=require("zod");var rr=require("better-call"),nr=async e=>{let i=e.context.returned;return i?i instanceof Response?i.status!==200?null:await i.clone().json():i instanceof rr.APIError?null:i:null};var In=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=v(async r=>{let n=await S(r);if(!n?.session)throw new b.APIError("UNAUTHORIZED");let s=n.user;if(!s.role||(Array.isArray(i.adminRole)?!i.adminRole.includes(s.role):s.role!==i.adminRole))throw new b.APIError("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:v(async r=>{let n=await nr(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.z.object({userId:O.z.string({description:"The user id"}),role:O.z.string({description:"The role to set. `admin` or `user` by default"})}),use:[o],metadata:{openapi:{operationId:"setRole",summary:"Set the role of a user",description:"Set the role of a user",responses:{200:{description:"User role updated",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async 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.z.object({email:O.z.string({description:"The email of the user"}),password:O.z.string({description:"The password of the user"}),name:O.z.string({description:"The name of the user"}),role:O.z.string({description:"The role of the user"}),data:O.z.optional(O.z.record(O.z.any(),{description:"Extra fields for the user. Including custom additional fields."}))}),use:[o],metadata:{openapi:{operationId:"createUser",summary:"Create a new user",description:"Create a new user",responses:{200:{description:"User created",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async r=>{if(await r.context.internalAdapter.findUserByEmail(r.body.email))throw new b.APIError("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.APIError("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.z.object({searchValue:O.z.string({description:"The value to search for"}).optional(),searchField:O.z.enum(["email","name"],{description:"The field to search in, defaults to email. Can be `email` or `name`"}).optional(),searchOperator:O.z.enum(["contains","starts_with","ends_with"],{description:"The operator to use for the search. Can be `contains`, `starts_with` or `ends_with`"}).optional(),limit:O.z.string({description:"The number of users to return"}).or(O.z.number()).optional(),offset:O.z.string({description:"The offset to start from"}).or(O.z.number()).optional(),sortBy:O.z.string({description:"The field to sort by"}).optional(),sortDirection:O.z.enum(["asc","desc"],{description:"The direction to sort by"}).optional(),filterField:O.z.string({description:"The field to filter by"}).optional(),filterValue:O.z.string({description:"The value to filter by"}).or(O.z.number()).or(O.z.boolean()).optional(),filterOperator:O.z.enum(["eq","ne","lt","lte","gt","gte"],{description:"The operator to use for the filter"}).optional()}),metadata:{openapi:{operationId:"listUsers",summary:"List users",description:"List users",responses:{200:{description:"List of users",content:{"application/json":{schema:{type:"object",properties:{users:{type:"array",items:{$ref:"#/components/schemas/User"}}}}}}}}}}},async 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.z.object({userId:O.z.string({description:"The user id"})}),metadata:{openapi:{operationId:"listUserSessions",summary:"List user sessions",description:"List user sessions",responses:{200:{description:"List of user sessions",content:{"application/json":{schema:{type:"object",properties:{sessions:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}}}}}}}},async r=>({sessions:await r.context.internalAdapter.listSessions(r.body.userId)})),unbanUser:p("/admin/unban-user",{method:"POST",body:O.z.object({userId:O.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"unbanUser",summary:"Unban a user",description:"Unban a user",responses:{200:{description:"User unbanned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async 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.z.object({userId:O.z.string({description:"The user id"}),banReason:O.z.string({description:"The reason for the ban"}).optional(),banExpiresIn:O.z.number({description:"The number of seconds until the ban expires"}).optional()}),use:[o],metadata:{openapi:{operationId:"banUser",summary:"Ban a user",description:"Ban a user",responses:{200:{description:"User banned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async r=>{if(r.body.userId===r.context.session.user.id)throw new b.APIError("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.z.object({userId:O.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"impersonateUser",summary:"Impersonate a user",description:"Impersonate a user",responses:{200:{description:"Impersonation session created",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async r=>{let n=await r.context.internalAdapter.findUserById(r.body.userId);if(!n)throw new b.APIError("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.APIError("INTERNAL_SERVER_ERROR",{message:t.FAILED_TO_CREATE_USER});let A=r.context.authCookies;return q(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.APIError("UNAUTHORIZED");if(!n.session.impersonatedBy)throw new b.APIError("BAD_REQUEST",{message:"You are not impersonating anyone"});let s=await r.context.internalAdapter.findUserById(n.session.impersonatedBy);if(!s)throw new b.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to find user"});let A=await r.getSignedCookie("admin_session",r.context.secret);if(!A)throw new b.APIError("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.APIError("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.z.object({sessionToken:O.z.string({description:"The session token"})}),use:[o],metadata:{openapi:{operationId:"revokeUserSession",summary:"Revoke a user session",description:"Revoke a user session",responses:{200:{description:"Session revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async r=>(await r.context.internalAdapter.deleteSession(r.body.sessionToken),r.json({success:!0}))),revokeUserSessions:p("/admin/revoke-user-sessions",{method:"POST",body:O.z.object({userId:O.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"revokeUserSessions",summary:"Revoke all user sessions",description:"Revoke all user sessions",responses:{200:{description:"Sessions revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async r=>(await r.context.internalAdapter.deleteSessions(r.body.userId),r.json({success:!0}))),removeUser:p("/admin/remove-user",{method:"POST",body:O.z.object({userId:O.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"removeUser",summary:"Remove a user",description:"Delete a user and all their sessions and accounts. Cannot be undone.",responses:{200:{description:"User removed",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async r=>(await r.context.internalAdapter.deleteUser(r.body.userId),r.json({success:!0})))},$ERROR_CODES:t,schema:se(Sn,i.schema)}},Sn={user:{fields:{role:{type:"string",required:!1,input:!1},banned:{type:"boolean",defaultValue:!1,required:!1,input:!1},banReason:{type:"string",required:!1,input:!1},banExpires:{type:"date",required:!1,input:!1}}},session:{fields:{impersonatedBy:{type:"string",required:!1}}}};var ro=require("@better-fetch/fetch"),ke=require("better-call"),ar=require("oslo/jwt"),ce=require("zod");async function sr(e,i){if(e.idToken){let o=(0,ar.parseJWT)(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(0,ro.betterFetch)(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 Un=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 k({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(0,ro.betterFetch)(o.discoveryUrl,{method:"GET"});a.data&&(A=a.data.token_endpoint,n=a.data.userinfo_endpoint)}if(!A)throw new ke.APIError("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 sr(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.z.object({currentURL:ce.z.string({description:"Redirect to the current URL after sign in"}).optional()}).optional(),body:ce.z.object({providerId:ce.z.string({description:"The provider ID for the OAuth provider"}),callbackURL:ce.z.string({description:"The URL to redirect to after sign in"}).optional(),errorCallbackURL:ce.z.string({description:"The URL to redirect to if an error occurs"}).optional()}),metadata:{openapi:{description:"Sign in with OAuth2",responses:{200:{description:"Sign in with OAuth2",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}}}}}}}}}},async t=>{let{providerId:o}=t.body,r=e.config.find(j=>j.providerId===o);if(!r)throw new ke.APIError("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 j=await(0,ro.betterFetch)(n,{onError(ao){t.context.logger.error(ao.error.message,ao.error,{discoveryUrl:n})}});j.data&&(N=j.data.authorization_endpoint,w=j.data.token_endpoint)}if(!N||!w)throw new ke.APIError("BAD_REQUEST",{message:i.INVALID_OAUTH_CONFIGURATION});let{state:R,codeVerifier:h}=await De(t),T=await k({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.z.object({code:ce.z.string({description:"The OAuth2 code"}).optional(),error:ce.z.string({description:"The error message, if any"}).optional(),state:ce.z.string({description:"The state parameter from the OAuth2 request"})}),metadata:{openapi:{description:"OAuth2 callback",responses:{200:{description:"OAuth2 callback",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"}}}}}}}}}},async t=>{if(t.query.error||!t.query.code)throw t.redirect(`${t.context.baseURL}?error=${t.query.error||"oAuth_code_missing"}`);let o=e.config.find(h=>h.providerId===t.params.providerId);if(!o)throw new ke.APIError("BAD_REQUEST",{message:`No config found for provider ${t.params.providerId}`});let r,n=await go(t),{callbackURL:s,codeVerifier:A,errorURL:a}=n,d=t.query.code,c=o.tokenUrl,u=o.userInfoUrl;if(o.discoveryUrl){let h=await(0,ro.betterFetch)(o.discoveryUrl,{method:"GET"});h.data&&(c=h.data.token_endpoint,u=h.data.userinfo_endpoint)}try{if(!c)throw new ke.APIError("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 ke.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let l=o.getUserInfo?await o.getUserInfo(r):await sr(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 xe(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}};var Ge=require("zod"),Ar={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0}}}},Pu=Ge.z.object({id:Ge.z.string(),publicKey:Ge.z.string(),privateKey:Ge.z.string(),createdAt:Ge.z.date()});var ti=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}})});var ye=require("jose");var _n=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 ti(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=ti(i.context.adapter),o=await t.getLatestKey(),r=!e?.jwks?.disablePrivateKeyEncryption;if(o===void 0){let{publicKey:d,privateKey:c}=await(0,ye.generateKeyPair)(e?.jwks?.keyPairConfig?.alg??"EdDSA",e?.jwks?.keyPairConfig??{crv:"Ed25519",extractable:!0}),u=await(0,ye.exportJWK)(d),l=await(0,ye.exportJWK)(c),K=JSON.stringify(l),m={id:crypto.randomUUID(),publicKey:JSON.stringify(u),privateKey:r?JSON.stringify(await he({key:i.context.options.secret,data:K})):K,createdAt:new Date};o=await t.createJwk(m)}let n=r?await Ce({key:i.context.options.secret,data:JSON.parse(o.privateKey)}):o.privateKey,s=await(0,ye.importJWK)(JSON.parse(n)),A=e?.jwt?.definePayload?await e?.jwt.definePayload(i.context.session.user):i.context.session.user,a=await new ye.SignJWT({...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:se(Ar,e?.schema)});var no=require("zod");var vn=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(Je(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:no.z.object({sessionToken:no.z.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.APIError("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.APIError("UNAUTHORIZED",{message:o.INVALID_SESSION_TOKEN});return await f(r,a),r.json(a)}),revokeDeviceSession:p("/multi-session/revoke",{method:"POST",body:no.z.object({sessionToken:no.z.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.APIError("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(Je(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 q(r)}else q(r)}else q(r);return r.json({success:!0})})},hooks:{after:[{matcher:()=>!0,handler:v(async r=>{let n=r.responseHeader.get("set-cookie");if(!n)return;let s=Pe(n),A=r.context.authCookies.sessionToken,a=s.get(A.name)?.value;if(!a)return;let d=Je(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:v(async r=>{let n=r.headers?.get("cookie");if(!n)return;let s=Object.fromEntries(Je(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}};var B=require("zod");var ri=["email-verification","sign-in","forget-password"],kn=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.z.object({email:B.z.string({description:"Email address to send the OTP"}),type:B.z.enum(ri,{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.APIError("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.APIError("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.z.object({email:B.z.string({description:"Email address to send the OTP"}),type:B.z.enum(ri,{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.z.object({email:B.z.string({description:"Email address to get the OTP"}),type:B.z.enum(ri)}),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.z.object({email:B.z.string({description:"Email address to verify"}),otp:B.z.string({description:"OTP to verify"})}),metadata:{openapi:{description:"Verify email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async o=>{let r=o.body.email;if(!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r))throw new b.APIError("BAD_REQUEST",{message:t.INVALID_EMAIL});let s=await o.context.internalAdapter.findVerificationValue(`email-verification-otp-${r}`);if(!s)throw new b.APIError("BAD_REQUEST",{message:t.INVALID_OTP});if(s.expiresAt<new Date)throw await o.context.internalAdapter.deleteVerificationValue(s.id),new b.APIError("BAD_REQUEST",{message:t.OTP_EXPIRED});let A=o.body.otp;if(s.value!==A)throw new b.APIError("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.APIError("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.z.object({email:B.z.string({description:"Email address to sign in"}),otp:B.z.string({description:"OTP sent to the email"})}),metadata:{openapi:{description:"Sign in with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async o=>{let r=o.body.email,n=await o.context.internalAdapter.findVerificationValue(`sign-in-otp-${r}`);if(!n)throw new b.APIError("BAD_REQUEST",{message:t.INVALID_OTP});if(n.expiresAt<new Date)throw await o.context.internalAdapter.deleteVerificationValue(n.id),new b.APIError("BAD_REQUEST",{message:t.OTP_EXPIRED});let s=o.body.otp;if(n.value!==s)throw new b.APIError("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.APIError("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.z.object({email:B.z.string({description:"Email address to send the OTP"})}),metadata:{openapi:{description:"Forget password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{let r=o.body.email;if(!await o.context.internalAdapter.findUserByEmail(r))throw new b.APIError("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.z.object({email:B.z.string({description:"Email address to reset the password"}),otp:B.z.string({description:"OTP sent to the email"}),password:B.z.string({description:"New password"})}),metadata:{openapi:{description:"Reset password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{let r=o.body.email,n=await o.context.internalAdapter.findUserByEmail(r);if(!n)throw new b.APIError("BAD_REQUEST",{message:t.USER_NOT_FOUND});let s=await o.context.internalAdapter.findVerificationValue(`forget-password-otp-${r}`);if(!s)throw new b.APIError("BAD_REQUEST",{message:t.INVALID_OTP});if(s.expiresAt<new Date)throw await o.context.internalAdapter.deleteVerificationValue(s.id),new b.APIError("BAD_REQUEST",{message:t.OTP_EXPIRED});let A=o.body.otp;if(s.value!==A)throw new b.APIError("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}};var ni=require("zod");var cr=require("@better-fetch/fetch");function dr(e){return e==="true"||e===!0}var Pn=e=>({id:"one-tap",endpoints:{oneTapCallback:p("/one-tap/callback",{method:"POST",body:ni.z.object({idToken:ni.z.string({description:"Google ID token, which the client obtains from the One Tap API"})}),metadata:{openapi:{summary:"One tap callback",description:"Use this endpoint to authenticate with Google One Tap",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}},400:{description:"Invalid token"}}}}},async i=>{let{idToken:t}=i.body,{data:o,error:r}=await(0,cr.betterFetch)("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.APIError("BAD_GATEWAY",{message:"User not found"});let A=await i.context.internalAdapter.createOAuthUser({email:o.email,emailVerified:dr(o.email_verified),name:o.name,image:o.picture},{providerId:"google",accountId:o.sub});if(!A)throw new b.APIError("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})})}});var Eo=require("zod");function Nn(){let e=de.VERCEL_URL,i=de.NETLIFY_URL,t=de.RENDER_URL,o=de.AWS_LAMBDA_FUNCTION_NAME,r=de.GOOGLE_CLOUD_FUNCTION_NAME,n=de.AZURE_FUNCTION_NAME;return e||i||t||o||r||n}var Dn=e=>({id:"oauth-proxy",endpoints:{oAuthProxy:p("/oauth-proxy-callback",{method:"GET",query:Eo.z.object({callbackURL:Eo.z.string({description:"The URL to redirect to after the proxy"}),cookies:Eo.z.string({description:"The cookies to set after the proxy"})}),metadata:{openapi:{description:"OAuth Proxy Callback",parameters:[{in:"query",name:"callbackURL",required:!0,description:"The URL to redirect to after the proxy"},{in:"query",name:"cookies",required:!0,description:"The cookies to set after the proxy"}],responses:{302:{description:"Redirect",headers:{Location:{description:"The URL to redirect to",schema:{type:"string"}}}}}}}},async i=>{let t=i.query.cookies,o=await Ce({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:v(async i=>{let t=i.context.returned,o=t instanceof b.APIError?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===Ne(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 he({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||Nn()||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}}}]}});var Qe=require("zod");var Ln=(e,i)=>({id:"custom-session",endpoints:{getSession:p("/get-session",{method:"GET",metadata:{CUSTOM_SESSION:!0},query:Qe.z.optional(Qe.z.object({disableCookieCache:Qe.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(Qe.z.string().transform(t=>t==="true")).optional(),disableRefresh:Qe.z.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)})}});var fe=require("zod");var Ze=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:{}}};var Bn=require("zod");var pr=require("kysely"),si=require("kysely");var so={};function ur(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 Ro(e){let i=[];return e.metadata?.openapi?.parameters?(i.push(...e.metadata.openapi.parameters),i):(e.query instanceof fe.ZodObject&&Object.entries(e.query.shape).forEach(([t,o])=>{o instanceof fe.ZodSchema&&i.push({name:t,in:"query",schema:{type:ur(o),..."minLength"in o&&o.minLength?{minLength:o.minLength}:{},description:o.description}})}),i)}function Kr(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof fe.ZodObject||e.body instanceof fe.ZodOptional)){let i=e.body.shape;if(!i)return;let t={},o=[];return Object.entries(i).forEach(([r,n])=>{n instanceof fe.ZodSchema&&(t[r]={type:ur(n),description:n.description},n instanceof fe.ZodOptional||o.push(r))}),{required:e.body instanceof fe.ZodOptional?!1:!!e.body,content:{"application/json":{schema:{type:"object",properties:t,required:o}}}}}}function Io(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 ai(e,i){let t=Fo(e,{...i,plugins:[]}),o=Ze(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"&&(so[a.path]={get:{tags:["Default",...d.metadata?.openapi?.tags||[]],description:d.metadata?.openapi?.description,operationId:d.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Ro(d),responses:Io(d.metadata?.openapi?.responses)}}),d.method==="POST")){let c=Kr(d);so[a.path]={post:{tags:["Default",...d.metadata?.openapi?.tags||[]],description:d.metadata?.openapi?.description,operationId:d.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Ro(d),...c?{requestBody:c}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:Io(d.metadata?.openapi?.responses)}}}});for(let A of i.plugins||[]){if(A.id==="open-api")continue;let a=Fo(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"&&(so[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:Ro(l),responses:Io(l.metadata?.openapi?.responses)}}),l.method==="POST"&&(so[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:Ro(l),requestBody:Kr(l),responses:Io(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:so}}var lr=`<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">