better-auth 1.0.13 → 1.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/plugins.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";var fr=Object.create;var so=Object.defineProperty;var hr=Object.getOwnPropertyDescriptor;var yr=Object.getOwnPropertyNames;var wr=Object.getPrototypeOf,Cr=Object.prototype.hasOwnProperty;var br=(e,i)=>{for(var t in i)so(e,t,{get:i[t],enumerable:!0})},ni=(e,i,t,o)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of yr(i))!Cr.call(e,r)&&r!==t&&so(e,r,{get:()=>i[r],enumerable:!(o=hr(i,r))||o.enumerable});return e};var Ro=(e,i,t)=>(t=e!=null?fr(wr(e)):{},ni(i||!e||!e.__esModule?so(t,"default",{value:e,enumerable:!0}):t,e)),Or=e=>ni(so({},"__esModule",{value:!0}),e);var Fn={};br(Fn,{HIDE_METADATA:()=>Ee,admin:()=>Rn,anonymous:()=>En,bearer:()=>yn,createAuthEndpoint:()=>p,createAuthMiddleware:()=>P,customSession:()=>Dn,emailOTP:()=>vn,genericOAuth:()=>Sn,getPasskeyActions:()=>ir,jwt:()=>Un,magicLink:()=>wn,multiSession:()=>_n,oAuthProxy:()=>Nn,oneTap:()=>kn,openAPI:()=>zn,optionsMiddleware:()=>Io,organization:()=>An,passkey:()=>fn,passkeyClient:()=>mn,phoneNumber:()=>bn,twoFactor:()=>un,twoFactorClient:()=>Kn,username:()=>Xo});module.exports=Or(Fn);var $o=require("better-call"),je=require("zod");var Te=require("better-call"),Io=(0,Te.createMiddleware)(async()=>({})),P=(0,Te.createMiddlewareCreator)({use:[Io,(0,Te.createMiddleware)(async()=>({}))]}),p=(0,Te.createEndpointCreator)({use:[Io]});var Z=require("better-call"),B=require("zod");var xr=require("oslo"),ji=require("oslo/encoding");var ao=require("oslo/crypto");async function Er({value:e,secret:i}){return new ao.HMAC("SHA-256").sign(new TextEncoder().encode(i),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function Rr({value:e,signature:i,secret:t}){return new ao.HMAC("SHA-256").verify(new TextEncoder().encode(t),Buffer.from(i,"base64"),new TextEncoder().encode(e))}var Ao={sign:Er,verify:Rr};var te=class extends Error{constructor(i,t){super(i),this.name="BetterAuthError",this.message=i,this.cause=t,this.stack=""}};var k=(e,i="ms")=>new Date(Date.now()+(i==="sec"?e*1e3:e));var co=Object.create(null),Ze=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?co:globalThis),de=new Proxy(co,{get(e,i){return Ze()[i]??co[i]},has(e,i){let t=Ze();return i in t||i in co},set(e,i,t){let o=Ze(!0);return o[i]=t,!0},deleteProperty(e,i){if(!i)return!1;let t=Ze(!0);return delete t[i],!0},ownKeys(){let e=Ze(!0);return Object.keys(e)}});function Ir(e){return e?e!=="false":!1}var So=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var si=So==="dev"||So==="development",Sr=So==="test"||Ir(de.TEST);var W=require("better-call");var di=require("better-call");function Uo(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function Ur(e){let i="";for(let t=0;t<e.length;t++)i+=Uo(e[t]);return i}function ai(e,i=!0){if(Array.isArray(e))return`(?:${e.map(c=>`^${ai(c,i)}$`).join("|")})`;let t="",o="",r=".";i===!0?(t="/",o="[/\\\\]",r="[^/\\\\]"):i&&(t=i,o=Ur(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],l=A[d+1],u="";if(!(!c&&d>0)){if(i&&(d===A.length-1?u=s:l!=="**"?u=n:u=""),i&&c==="**"){u&&(a+=d===0?"":u,a+=`(?:${r}*?${u})*?`);continue}for(let K=0;K<c.length;K++){let m=c[K];m==="\\"?K<c.length-1&&(a+=Uo(c[K+1]),K++):m==="?"?a+=r:m==="*"?a+=`${r}*?`:a+=Uo(m)}a+=u}}return a}function _r(e,i){if(typeof i!="string")throw new TypeError(`Sample must be a string, but ${typeof i} given`);return e.test(i)}function _o(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=ai(e,i.separator),o=new RegExp(`^${t}$`,i.flags),r=_r.bind(null,o);return r.options=i,r.pattern=e,r.regexp=o,r}function ve(e){try{return new URL(e).origin}catch{return null}}function Ai(e){return e.includes("://")?new URL(e).host:e}var vr=P(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=o.trustedOrigins,d=e.headers?.has("cookie"),c=(u,K)=>u.startsWith("/")?!1:K.includes("*")?_o(K)(Ai(u)):u.startsWith(K),l=(u,K)=>{if(!u)return;if(!a.some(E=>c(u,E)||u?.startsWith("/")&&K!=="origin"&&!u.includes(":")))throw e.context.logger.error(`Invalid ${K}: ${u}`),e.context.logger.info(`If it's a valid URL, please add ${u} to trustedOrigins in your auth config
2
- `,`Current list of trustedOrigins: ${a}`),new di.APIError("FORBIDDEN",{message:`Invalid ${K}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&l(r,"origin"),n&&l(n,"callbackURL"),s&&l(s,"redirectURL"),A&&l(A,"currentURL")});var Ee={isAction:!1};var ci=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 gi=require("oslo"),po=require("oslo/jwt"),re=require("zod");var ke=require("better-call");var pe=require("better-call");var we=require("zod");function vo(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 ko=()=>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?vo(Buffer.from(t,"base64").toString()):null;if(o&&!await Ao.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return $(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 u=e.context.authCookies.sessionData.name;e.setCookie(u,"",{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 $(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:k(e.context.sessionConfig.expiresIn,"sec")});if(!c)return $(e),e.json(null,{status:401});let l=(c.expiresAt.valueOf()-Date.now())/1e3;return await h(e,{session:c,user:n.user},!1,{maxAge:l}),e.json({session:c,user:n.user})}return e.json(n)}catch(i){throw e.context.logger.error("INTERNAL_SERVER_ERROR",i),new pe.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 ko()({...e,_flag:"json",headers:e.headers,query:i}).catch(o=>null);return e.context.session=t,t},R=P(async e=>{let i=await S(e);if(!i?.session)throw new pe.APIError("UNAUTHORIZED");return{session:i}}),Qe=P(async e=>{let i=await S(e);if(!i?.session)throw new pe.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 pe.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:i}}),pi=()=>p("/list-sessions",{method:"GET",use:[R],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)}),Ki=p("/revoke-session",{method:"POST",body:we.z.object({token:we.z.string({description:"The token to revoke"})}),use:[R],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 pe.APIError("BAD_REQUEST",{message:"Session not found"});if(t.session.userId!==e.context.session.user.id)throw new pe.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 pe.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ui=p("/revoke-sessions",{method:"POST",use:[R],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 pe.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),li=p("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[R],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 pe.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 me(e,i,t){return await(0,po.createJWT)("HS256",Buffer.from(e),{email:i.toLowerCase(),updateTo:t},{expiresIn:new gi.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[i],includeIssuedTimestamp:!0})}async function Po(e,i){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new ke.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await me(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 mi=p("/send-verification-email",{method:"POST",query:re.z.object({currentURL:re.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:re.z.object({email:re.z.string({description:"The email to send the verification email to"}).email(),callbackURL:re.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 ke.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 ke.APIError("BAD_REQUEST",{message:g.USER_NOT_FOUND});return await Po(e,t.user),e.json({status:!0})}),fi=p("/verify-email",{method:"GET",query:re.z.object({token:re.z.string({description:"The token to verify the email"}),callbackURL:re.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.redirect(`${e.query.callbackURL}?error=${A}`):new ke.APIError("UNAUTHORIZED",{message:A})}let{token:t}=e.query,o;try{o=await(0,po.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=re.z.object({email:re.z.string().email(),updateTo:re.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});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${t}`,token:t},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 ke.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await h(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var Ke=require("better-call");var b=require("zod"),hi=require("better-call"),bs=b.z.object({id:b.z.string(),providerId:b.z.string(),accountId:b.z.string(),userId:b.z.string(),accessToken:b.z.string().nullish(),refreshToken:b.z.string().nullish(),idToken:b.z.string().nullish(),accessTokenExpiresAt:b.z.date().nullish(),refreshTokenExpiresAt:b.z.date().nullish(),scope:b.z.string().nullish(),password:b.z.string().nullish(),createdAt:b.z.date().default(()=>new Date),updatedAt:b.z.date().default(()=>new Date)}),Os=b.z.object({id:b.z.string(),email:b.z.string().transform(e=>e.toLowerCase()),emailVerified:b.z.boolean().default(!1),name:b.z.string(),image:b.z.string().nullish(),createdAt:b.z.date().default(()=>new Date),updatedAt:b.z.date().default(()=>new Date)}),Ts=b.z.object({id:b.z.string(),userId:b.z.string(),expiresAt:b.z.date(),createdAt:b.z.date().default(()=>new Date),updatedAt:b.z.date().default(()=>new Date),token:b.z.string(),ipAddress:b.z.string().nullish(),userAgent:b.z.string().nullish()}),Es=b.z.object({id:b.z.string(),value:b.z.string(),createdAt:b.z.date().default(()=>new Date),updatedAt:b.z.date().default(()=>new Date),expiresAt:b.z.date(),identifier:b.z.string()});function kr(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 Pr(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}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 hi.APIError("BAD_REQUEST",{message:`${n} is required`})}return r}function Ko(e,i,t){let o=kr(e,"user");return Pr(i||{},{fields:o,action:t})}function ne(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 yi=()=>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 Ke.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 Ke.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 Ke.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 Ke.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 Ke.APIError("UNPROCESSABLE_ENTITY",{message:g.USER_ALREADY_EXISTS});let u=Ko(e.context.options,A),K;try{if(K=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:t,image:n,...u,emailVerified:!1}),!K)throw new Ke.APIError("BAD_REQUEST",{message:g.FAILED_TO_CREATE_USER})}catch(v){throw e.context.logger.error("Failed to create user",v),new Ke.APIError("UNPROCESSABLE_ENTITY",{message:g.FAILED_TO_CREATE_USER,details:v})}if(!K)throw new Ke.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 v=await me(e.context.secret,K.email),f=`${e.context.baseURL}/verify-email?token=${v}&callbackURL=${i.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:K,url:f,token:v},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 E=await e.context.internalAdapter.createSession(K.id,e.request);if(!E)throw new Ke.APIError("BAD_REQUEST",{message:g.FAILED_TO_CREATE_SESSION});return await h(e,{session:E,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 Nr=(e="Unknown")=>`<!DOCTYPE html>
2
+ `,`Current list of trustedOrigins: ${a}`),new di.APIError("FORBIDDEN",{message:`Invalid ${K}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&l(r,"origin"),n&&l(n,"callbackURL"),s&&l(s,"redirectURL"),A&&l(A,"currentURL")});var Ee={isAction:!1};var ci=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 gi=require("oslo"),po=require("oslo/jwt"),re=require("zod");var ke=require("better-call");var pe=require("better-call");var we=require("zod");function vo(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 ko=()=>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?vo(Buffer.from(t,"base64").toString()):null;if(o&&!await Ao.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return $(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 u=e.context.authCookies.sessionData.name;e.setCookie(u,"",{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 $(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:k(e.context.sessionConfig.expiresIn,"sec")});if(!c)return $(e),e.json(null,{status:401});let l=(c.expiresAt.valueOf()-Date.now())/1e3;return await h(e,{session:c,user:n.user},!1,{maxAge:l}),e.json({session:c,user:n.user})}return e.json(n)}catch(i){throw e.context.logger.error("INTERNAL_SERVER_ERROR",i),new pe.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 ko()({...e,_flag:"json",headers:e.headers,query:i}).catch(o=>null);return e.context.session=t,t},R=P(async e=>{let i=await S(e);if(!i?.session)throw new pe.APIError("UNAUTHORIZED");return{session:i}}),Qe=P(async e=>{let i=await S(e);if(!i?.session)throw new pe.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 pe.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:i}}),pi=()=>p("/list-sessions",{method:"GET",use:[R],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)}),Ki=p("/revoke-session",{method:"POST",body:we.z.object({token:we.z.string({description:"The token to revoke"})}),use:[R],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 pe.APIError("BAD_REQUEST",{message:"Session not found"});if(t.session.userId!==e.context.session.user.id)throw new pe.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 pe.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ui=p("/revoke-sessions",{method:"POST",use:[R],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 pe.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),li=p("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[R],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 pe.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 me(e,i,t){return await(0,po.createJWT)("HS256",Buffer.from(e),{email:i.toLowerCase(),updateTo:t},{expiresIn:new gi.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[i],includeIssuedTimestamp:!0})}async function Po(e,i){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new ke.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await me(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 mi=p("/send-verification-email",{method:"POST",query:re.z.object({currentURL:re.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:re.z.object({email:re.z.string({description:"The email to send the verification email to"}).email(),callbackURL:re.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 ke.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 ke.APIError("BAD_REQUEST",{message:g.USER_NOT_FOUND});return await Po(e,t.user),e.json({status:!0})}),fi=p("/verify-email",{method:"GET",query:re.z.object({token:re.z.string({description:"The token to verify the email"}),callbackURL:re.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.redirect(`${e.query.callbackURL}?error=${A}`):new ke.APIError("UNAUTHORIZED",{message:A})}let{token:t}=e.query,o;try{o=await(0,po.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=re.z.object({email:re.z.string().email(),updateTo:re.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});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${t}`,token:t},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 ke.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await h(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var Ke=require("better-call");var b=require("zod"),hi=require("better-call"),bs=b.z.object({id:b.z.string(),providerId:b.z.string(),accountId:b.z.string(),userId:b.z.string(),accessToken:b.z.string().nullish(),refreshToken:b.z.string().nullish(),idToken:b.z.string().nullish(),accessTokenExpiresAt:b.z.date().nullish(),refreshTokenExpiresAt:b.z.date().nullish(),scope:b.z.string().nullish(),password:b.z.string().nullish(),createdAt:b.z.date().default(()=>new Date),updatedAt:b.z.date().default(()=>new Date)}),Os=b.z.object({id:b.z.string(),email:b.z.string().transform(e=>e.toLowerCase()),emailVerified:b.z.boolean().default(!1),name:b.z.string(),image:b.z.string().nullish(),createdAt:b.z.date().default(()=>new Date),updatedAt:b.z.date().default(()=>new Date)}),Ts=b.z.object({id:b.z.string(),userId:b.z.string(),expiresAt:b.z.date(),createdAt:b.z.date().default(()=>new Date),updatedAt:b.z.date().default(()=>new Date),token:b.z.string(),ipAddress:b.z.string().nullish(),userAgent:b.z.string().nullish()}),Es=b.z.object({id:b.z.string(),value:b.z.string(),createdAt:b.z.date().default(()=>new Date),updatedAt:b.z.date().default(()=>new Date),expiresAt:b.z.date(),identifier:b.z.string()});function kr(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 Pr(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}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 hi.APIError("BAD_REQUEST",{message:`${n} is required`})}return r}function Ko(e,i,t){let o=kr(e,"user");return Pr(i||{},{fields:o,action:t})}function ne(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 yi=()=>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 Ke.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 Ke.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 Ke.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 Ke.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 Ke.APIError("UNPROCESSABLE_ENTITY",{message:g.USER_ALREADY_EXISTS});let u=Ko(e.context.options,A),K;try{if(K=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:t,image:n,...u,emailVerified:!1}),!K)throw new Ke.APIError("BAD_REQUEST",{message:g.FAILED_TO_CREATE_USER})}catch(v){throw e.context.logger.error("Failed to create user",v),new Ke.APIError("UNPROCESSABLE_ENTITY",{message:g.FAILED_TO_CREATE_USER,details:v})}if(!K)throw new Ke.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 v=await me(e.context.secret,K.email),f=`${e.context.baseURL}/verify-email?token=${v}&callbackURL=${i.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:K,url:f,token:v},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 E=await e.context.internalAdapter.createSession(K.id,e.request);if(!E)throw new Ke.APIError("BAD_REQUEST",{message:g.FAILED_TO_CREATE_SESSION});return await h(e,{session:E,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 Nr=(e="Unknown")=>`<!DOCTYPE html>
3
3
  <html lang="en">
4
4
  <head>
5
5
  <meta charset="UTF-8">
@@ -80,7 +80,7 @@
80
80
  </div>
81
81
  </body>
82
82
  </html>`,wi=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(Nr(i),{headers:{"Content-Type":"text/html"}})});var Ci=require("consola"),No=["info","success","warn","error","debug"];function Dr(e,i){return No.indexOf(i)<=No.indexOf(e)}var Lr=(0,Ci.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),bi=e=>{let i=e?.disabled!==!0,t=e?.level??"error",o=(r,n,s=[])=>{if(!(!i||!Dr(t,r))){if(!e||typeof e.log!="function"){Lr[r]("",n,...s);return}e.log(r==="success"?"info":r,n,s)}};return Object.fromEntries(No.map(r=>[r,(...[n,...s])=>o(r,n,s)]))},se=bi();var Oi=Ro(require("defu"),1);var T=require("better-call");function Do(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:Ti,callbackOAuth:Ri,getSession:ko(),signOut:Ii,signUpEmail:yi(),signInEmail:Ei,forgetPassword:Si,resetPassword:_i,verifyEmail:fi,sendVerificationEmail:mi,changeEmail:Li,changePassword:ki,setPassword:Pi,updateUser:vi(),deleteUser:Ni,forgetPasswordCallback:Ui,listSessions:pi(),revokeSession:Ki,revokeSessions:ui,revokeOtherSessions:li,linkSocialAccount:xi,listUserAccounts:Bi,deleteUserCallback:Di},...t,ok:ci,error:wi},s={};for(let[A,a]of Object.entries(n))s[A]=async(d={})=>{a.headers=new Headers;let c={setHeader(f,w){a.headers.set(f,w)},setCookie(f,w,O){(0,W.setCookie)(a.headers,f,w,O)},getCookie(f,w){let I=d.headers?.get("cookie");return(0,W.getCookie)(I||"",f,w)},getSignedCookie(f,w,O){let I=d.headers;return I?(0,W.getSignedCookie)(I,w,f,O):null},async setSignedCookie(f,w,O,I){await(0,W.setSignedCookie)(a.headers,f,w,O,I)},redirect(f){return a.headers.set("Location",f),new W.APIError("FOUND")},responseHeader:a.headers},l=await e,u=null,K={...c,...d,path:a.path,context:{...l,...d.context,session:null,setNewSession:function(f){this.newSession=f,u=f}}},m=i.plugins||[];for(let f of m){let w=f.hooks?.before??[];for(let O of w){if(!O.matcher(K))continue;let I=await O.handler(K);if(I&&"context"in I){K=(0,Oi.default)(K,I.context);continue}if(I)return I}}let E;try{E=await a(K),u&&(K.context.newSession=u)}catch(f){if(u&&(K.context.newSession=u),f instanceof W.APIError){let w=i.plugins?.map(O=>{if(O.hooks?.after)return O.hooks.after}).filter(O=>O!==void 0).flat();if(!w?.length)throw f.headers=a.headers,f;K.context.returned=f,K.context.returned.headers=a.headers;for(let O of w||[])if(O.matcher(K))try{let q=await O.handler(K);q&&"response"in q&&(K.context.returned=q.response)}catch(q){if(q instanceof W.APIError){K.context.returned=q;continue}throw q}if(K.context.returned instanceof W.APIError)throw K.context.returned.headers=a.headers,K.context.returned;return K.context.returned}throw f}K.context.returned=E,K.responseHeader=a.headers;for(let f of i.plugins||[])if(f.hooks?.after){for(let w of f.hooks.after)if(w.matcher(K))try{let I=await w.handler(K);I&&(K.context.returned=I)}catch(I){if(I instanceof W.APIError){K.context.returned=I;continue}throw I}}let v=K.context.returned;return v instanceof Response&&a.headers.forEach((f,w)=>{w==="set-cookie"?v.headers.append(w,f):v.headers.set(w,f)}),v},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}}function uo(e){let i=new Map;return e.split(", ").forEach(o=>{let r=o.split(";").map(l=>l.trim()),[n,...s]=r,[A,...a]=n.split("="),d=a.join("=");if(!A||d===void 0)return;let c={value:d};s.forEach(l=>{let[u,...K]=l.split("="),m=K.join("="),E=u.trim().toLowerCase();switch(E){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[E]=m?m.trim():!0;break}}),i.set(A,c)}),i}async function h(e,i,t,o){let r=e.context.authCookies.sessionToken.options,n=t?void 0:e.context.sessionConfig.expiresIn;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&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(ji.base64url.encode(new TextEncoder().encode(JSON.stringify({session:i,expiresAt:k(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await Ao.sign({value:JSON.stringify(i),secret:e.context.secret})})))),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 $(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 We(e){let i=e.split("; "),t=new Map;return i.forEach(o=>{let[r,n]=o.split("=");t.set(r,n)}),t}var Hi=require("@better-fetch/fetch"),$i=require("better-call"),Ne=require("jose"),Gi=require("oslo/jwt");var zi=require("oslo/crypto"),Fi=require("oslo/encoding");async function Vi(e){let i=await(0,zi.sha256)(new TextEncoder().encode(e));return Fi.base64url.encode(new Uint8Array(i),{includePadding:!1})}function Mi(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?k(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function N({id:e,options:i,authorizationEndpoint:t,state:o,codeVerifier:r,scopes:n,claims:s,redirectURI:A}){let a=new URL(t);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",i.clientId),a.searchParams.set("state",o),a.searchParams.set("scope",n.join(" ")),a.searchParams.set("redirect_uri",i.redirectURI||A),r){let d=await Vi(r);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",d)}if(s){let d=s.reduce((c,l)=>(c[l]=null,c),{});a.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...d}}))}return a}var qi=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 l=btoa(`${o.clientId}:${o.clientSecret}`);A.authorization=`Basic ${l}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await(0,qi.betterFetch)(r,{method:"POST",body:s,headers:A});if(d)throw d;return Mi(a)}var lo=require("oslo/oauth2"),fe=require("zod"),Lo=require("better-call");async function Pe(e,i){let t=e.body?.callbackURL||(e.query?.currentURL?ve(e.query?.currentURL):"")||e.context.options.baseURL;if(!t)throw new Lo.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,lo.generateCodeVerifier)(),r=(0,lo.generateState)(),n=JSON.stringify({callbackURL:t,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,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 Lo.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=fe.z.object({callbackURL:fe.z.string(),codeVerifier:fe.z.string(),errorURL:fe.z.string().optional(),expiresAt:fe.z.number(),link:fe.z.object({email:fe.z.string(),userId:fe.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 Zi=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,Ne.decodeProtectedHeader)(t),{kid:n,alg:s}=r;if(!n||!s)return!1;let A=await jr(n),{payload:a}=await(0,Ne.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,Gi.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}}}},jr=async e=>{let i="https://appleid.apple.com",t="/auth/keys",{data:o}=await(0,Hi.betterFetch)(`${i}${t}`);if(!o?.keys)throw new $i.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,Ne.importJWK)(r,r.alg)};var Qi=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,Qi.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 Ji=require("@better-fetch/fetch");var Yi=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 N({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,Ji.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 Bo=require("@better-fetch/fetch");var Xi=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),N({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,Bo.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,Bo.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 et=require("oslo/jwt");var ot=require("@better-fetch/fetch"),it=e=>({id:"google",name:"Google",async createAuthorizationURL({state:i,scopes:t,codeVerifier:o,redirectURI:r}){if(!e.clientId||!e.clientSecret)throw se.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new te("codeVerifier is required for Google");let n=t||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await N({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,ot.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,et.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 tt=require("@better-fetch/fetch"),rt=require("oslo/jwt");var nt=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),N({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,rt.parseJWT)(r.idToken)?.payload,s=e.profilePhotoSize||48;await(0,tt.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(),l=Buffer.from(c).toString("base64");n.picture=`data:image/jpeg;base64, ${l}`}catch(d){se.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 st=require("@better-fetch/fetch");var at=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),N({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,st.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 At=require("nanoid"),G=e=>(0,At.nanoid)(e);var dt=require("oslo/jwt");var ct=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),N({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 se.error("No idToken found in token"),null;let o=(0,dt.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 pt=require("@better-fetch/fetch");var Kt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(i){let t=i.scopes||["users.read","tweet.read","offline.access"];return e.scope&&t.push(...e.scope),N({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,pt.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 ut=require("@better-fetch/fetch");var lt=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 N({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,ut.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 gt=require("@better-fetch/fetch");var mt=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 N({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,gt.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 ft=require("@better-fetch/fetch");var xo=(e="")=>e.split("://").map(i=>i.replace(/\/{2,}/g,"/")).join("://"),zr=e=>{let i=e||"https://gitlab.com";return{authorizationEndpoint:xo(`${i}/oauth/authorize`),tokenEndpoint:xo(`${i}/oauth/token`),userinfoEndpoint:xo(`${i}/api/v4/user`)}},ht=e=>{let{authorizationEndpoint:i,tokenEndpoint:t,userinfoEndpoint:o}=zr(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 N({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,ft.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 Fr={apple:Zi,discord:Wi,facebook:Yi,github:Xi,microsoft:nt,google:it,spotify:at,twitch:ct,twitter:Kt,dropbox:lt,linkedin:mt,gitlab:ht},mo=Object.keys(Fr);async function De(e,{userInfo:i,account:t,callbackURL:o}){let r=await e.context.internalAdapter.findUserByEmail(i.email.toLowerCase(),{includeAccounts:!0}).catch(A=>{throw se.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;if(r){let A=r.accounts.find(a=>a.providerId===t.providerId);if(A){let a=Object.fromEntries(Object.entries({accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt}).filter(([d,c])=>c!==void 0));Object.keys(a).length>0&&await e.context.internalAdapter.updateAccount(A.id,a)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.providerId)&&!i.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return si&&se.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(c){return se.error("Unable to link account",c),{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 me(e.context.secret,n.email),a=`${e.context.baseURL}/verify-email?token=${A}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:n,url:a,token:A},e.request)}if(!n)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(n.id,e.request);return s?{data:{session:s,user:n},error:null}:{error:"unable to create session",data:null}}var Ti=p("/sign-in/social",{method:"POST",query:B.z.object({currentURL:B.z.string().optional()}).optional(),body:B.z.object({callbackURL:B.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),errorCallbackURL:B.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:B.z.enum(mo,{description:"OAuth2 provider to use"}),disableRedirect:B.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:B.z.optional(B.z.object({token:B.z.string({description:"ID token from the provider"}),nonce:B.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:B.z.string({description:"Access token from the provider"}).optional(),refreshToken:B.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:B.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 Z.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 Z.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 Z.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 Z.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 Z.APIError("UNAUTHORIZED",{message:g.USER_EMAIL_NOT_FOUND});let d=await De(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 Z.APIError("UNAUTHORIZED",{message:d.error});return await h(e,d.data),e.json({session:d.data.session,user:d.data.user,url:void 0,redirect:!1})}let{codeVerifier:t,state:o}=await Pe(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})}),Ei=p("/sign-in/email",{method:"POST",body:B.z.object({email:B.z.string({description:"Email of the user"}),password:B.z.string({description:"Password of the user"}),callbackURL:B.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:B.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 Z.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:i,password:t}=e.body;if(!B.z.string().email().safeParse(i).success)throw new Z.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 Z.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 Z.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 Z.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 Z.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 Z.APIError("UNAUTHORIZED",{message:g.EMAIL_NOT_VERIFIED});let d=await me(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 Z.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 Z.APIError("UNAUTHORIZED",{message:g.FAILED_TO_CREATE_SESSION});return await h(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 Le=require("zod");var fo=Le.z.object({code:Le.z.string().optional(),error:Le.z.string().optional(),errorMessage:Le.z.string().optional(),state:Le.z.string().optional()}),Ri=p("/callback/:id",{method:["GET","POST"],body:fo.optional(),query:fo.optional(),metadata:Ee},async e=>{let i;try{if(e.method==="GET")i=fo.parse(e.query);else if(e.method==="POST")i=fo.parse(e.body);else throw new Error("Unsupported method")}catch(f){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",f),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:t,error:o,state:r}=i;if(!r)throw e.context.logger.error("State not found"),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"}`);let n=e.context.socialProviders.find(f=>f.id===e.params.id);if(!n)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:s,callbackURL:A,link:a,errorURL:d}=await go(e),c;try{c=await n.validateAuthorizationCode({code:t,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${n.id}`})}catch(f){throw e.context.logger.error("",f),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let l=await n.getUserInfo(c).then(f=>f?.user);function u(f){let w=d||A||`${e.context.baseURL}/error`;throw w.includes("?")?w=`${w}&error=${f}`:w=`${w}?error=${f}`,e.redirect(w)}if(!l)return e.context.logger.error("Unable to get user info"),u("unable_to_get_user_info");if(!l.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),u("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(a){if(a.email!==l.email.toLowerCase())return u("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:a.userId,providerId:n.id,accountId:l.id}))return u("unable_to_link_account");let w;try{w=new URL(A).toString()}catch{w=A}throw e.redirect(w)}let K=await De(e,{userInfo:{...l,email:l.email,name:l.name||l.email},account:{providerId:n.id,accountId:l.id,...c,scope:c.scopes?.join(",")},callbackURL:A});if(K.error)return e.context.logger.error(K.error.split(" ").join("_")),u(K.error.split(" ").join("_"));let{session:m,user:E}=K.data;await h(e,{session:m,user:E});let v;try{v=new URL(A).toString()}catch{v=A}throw e.redirect(v)});var ed=require("zod");var yt=require("better-call");var Ii=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 $(e),new yt.APIError("BAD_REQUEST",{message:g.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(i),$(e),e.json({success:!0})});var oe=require("zod");var ho=require("better-call");function wt(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 Vr(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 Si=p("/forget-password",{method:"POST",body:oe.z.object({email:oe.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:oe.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 ho.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=k(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})}),Ui=p("/reset-password/:token",{method:"GET",query:oe.z.object({callbackURL:oe.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(wt(e.context,t,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${i}`);throw!o||o.expiresAt<new Date?e.redirect(wt(e.context,t,{error:"INVALID_TOKEN"})):e.redirect(Vr(e.context,t,{token:i}))}),_i=p("/reset-password",{query:oe.z.optional(oe.z.object({token:oe.z.string().optional(),currentURL:oe.z.string().optional()})),method:"POST",body:oe.z.object({newPassword:oe.z.string({description:"The new password to set"}),token:oe.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 ho.APIError("BAD_REQUEST",{message:g.INVALID_TOKEN});let{newPassword:t}=e.body,o=`reset-password:${i}`,r=await e.context.internalAdapter.findVerificationValue(o);if(!r||r.expiresAt<new Date)throw new ho.APIError("BAD_REQUEST",{message:g.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(r.id);let n=r.value,s=await e.context.password.hash(t);return(await e.context.internalAdapter.findAccounts(n)).find(d=>d.providerId==="credential")?(await e.context.internalAdapter.updatePassword(n,s),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:s,accountId:n}),e.json({status:!0}))});var H=require("zod");var V=require("better-call");var Fo=require("@noble/ciphers/chacha"),Be=require("@noble/ciphers/utils"),Vo=require("@noble/ciphers/webcrypto"),Mo=require("oslo/crypto"),zo=Ro(require("uncrypto"),1);var Ct=require("oslo/encoding");var Mr=require("@noble/hashes/scrypt"),qr=require("uncrypto");var jo=Ro(require("uncrypto"),1);function Hr(e){return e.toString(2).padStart(8,"0")}function $r(e){return[...e].map(i=>Hr(i)).join("")}function bt(e){return parseInt($r(e),2)}function Gr(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));jo.default.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1);let r=bt(o);for(;r>=e;)jo.default.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1),r=bt(o);return r}function z(e,i){let t="";for(let o=0;o<e;o++)t+=i[Gr(i.length)];return t}function F(...e){let i=new Set(e),t="";for(let o of i)o==="a-z"?t+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?t+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?t+="0123456789":t+=o;return t}async function Je(e,i){let t=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},r=await zo.default.subtle.importKey("raw",t.encode(e),o,!1,["sign","verify"]),n=await zo.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,Mo.sha256)(new TextEncoder().encode(e)),o=(0,Be.utf8ToBytes)(i),r=(0,Vo.managedNonce)(Fo.xchacha20poly1305)(new Uint8Array(t));return(0,Be.bytesToHex)(r.encrypt(o))},Ce=async({key:e,data:i})=>{let t=await(0,Mo.sha256)(new TextEncoder().encode(e)),o=(0,Be.hexToBytes)(i),r=(0,Vo.managedNonce)(Fo.xchacha20poly1305)(new Uint8Array(t));return new TextDecoder().decode(r.decrypt(o))};var vi=()=>p("/update-user",{method:"POST",body:H.z.record(H.z.string(),H.z.any()),use:[R],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 V.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&&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=Ko(e.context.options,r,"update"),A=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:t,image:o,...s});return await h(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})}),ki=p("/change-password",{method:"POST",body:H.z.object({newPassword:H.z.string({description:"The new password to set"}),currentPassword:H.z.string({description:"The current password"}),revokeOtherSessions:H.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[R],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 V.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 V.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_LONG});let a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(l=>l.providerId==="credential"&&l.password);if(!a||!a.password)throw new V.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 V.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 l=await e.context.internalAdapter.createSession(r.user.id,e.headers);if(!l)throw new V.APIError("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_GET_SESSION});await h(e,{session:l,user:r.user})}return e.json(r.user)}),Pi=p("/set-password",{method:"POST",body:H.z.object({newPassword:H.z.string()}),metadata:{SERVER_ONLY:!0},use:[R]},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 V.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 V.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 V.APIError("BAD_REQUEST",{message:"user already has a password"})}),Ni=p("/delete-user",{method:"POST",use:[Qe],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 V.APIError("NOT_FOUND");let i=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let r=z(32,F("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),$(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(i.user,e.request),e.json({success:!0,message:"User deleted"})}),Di=p("/delete-user/callback",{method:"GET",query:H.z.object({token:H.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 V.APIError("NOT_FOUND");let i=await S(e);if(!i)throw new V.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 V.APIError("NOT_FOUND",{message:g.INVALID_TOKEN});if(t.value!==i.user.id)throw new V.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),$(e);let r=e.context.options.user.deleteUser?.afterDelete;return r&&await r(i.user,e.request),e.json({success:!0,message:"User deleted"})}),Li=p("/change-email",{method:"POST",query:H.z.object({currentURL:H.z.string().optional()}).optional(),body:H.z.object({newEmail:H.z.string({description:"The new email to set"}).email(),callbackURL:H.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[R],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 V.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 V.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 V.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 V.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await me(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 xe=require("zod");var qo=require("better-call");var Bi=p("/list-accounts",{method:"GET",use:[R],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})))}),xi=p("/link-social",{method:"POST",requireHeaders:!0,query:xe.z.object({currentURL:xe.z.string().optional()}).optional(),body:xe.z.object({callbackURL:xe.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:xe.z.enum(mo,{description:"The OAuth2 provider to use"})}),use:[R],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 qo.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 qo.APIError("NOT_FOUND",{message:g.PROVIDER_NOT_FOUND});let n=await Pe(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 Ot=(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 yo(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 Qr={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},Ho=yo(Qr),Wr=Ho.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),Jr=Ho.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),Yr=Ho.newRole({organization:[],member:[],invitation:[]}),Tt={admin:Wr,owner:Jr,member:Yr};var Xr={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},en=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,Et={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},on=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function tn(e){return e instanceof Date&&!isNaN(e.getTime())}function rn(e){let i=on.exec(e);if(!i)return null;let[,t,o,r,n,s,A,a,d,c,l]=i,u=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(l,10))*(d==="+"?-1:1);u.setUTCMinutes(u.getUTCMinutes()+K)}return tn(u)?u:null}function nn(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 Et)return Et[A];if(!en.test(s)){if(t)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(Xr).some(([d,c])=>{let l=c.test(s);return l&&o&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${d} pattern`),l})&&t)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(s,(c,l)=>{if(c==="__proto__"||c==="constructor"&&l&&typeof l=="object"&&"prototype"in l){o&&console.warn(`[better-json] Dropping "${c}" key to prevent prototype pollution`);return}if(n&&typeof l=="string"){let u=rn(l);if(u)return u}return r?r(c,l):l})}catch(d){if(t)throw d;return e}}function Rt(e,i={strict:!0}){return nn(e,i)}var It=Rt;var j=(e,i)=>{let t=e.adapter;return{findOrganizationBySlug:async o=>await t.findOne({model:"organization",where:[{field:"slug",value:o}]}),createOrganization:async o=>{let r=await t.create({model:"organization",data:{...o.organization,metadata:o.organization.metadata?JSON.stringify(o.organization.metadata):void 0}}),n=await t.create({model:"member",data:{organizationId:r.id,userId:o.user.id,createdAt:new Date,role:i?.creatorRole||"owner"}});return{...r,metadata:r.metadata?JSON.parse(r.metadata):void 0,members:[{...n,user:{id:o.user.id,name:o.user.name,email:o.user.email,image:o.user.image}}]}},findMemberByEmail:async o=>{let r=await t.findOne({model:"user",where:[{field:"email",value:o.email}]});if(!r)return null;let n=await t.findOne({model:"member",where:[{field:"organizationId",value:o.organizationId},{field:"userId",value:r.id}]});return n?{...n,user:{id:r.id,name:r.name,email:r.email,image:r.image}}:null},findMemberByOrgId:async o=>{let[r,n]=await Promise.all([await t.findOne({model:"member",where:[{field:"userId",value:o.userId},{field:"organizationId",value:o.organizationId}]}),await t.findOne({model:"user",where:[{field:"id",value:o.userId}]})]);return!n||!r?null:{...r,user:{id:n.id,name:n.name,email:n.email,image:n.image}}},findMemberById:async o=>{let r=await t.findOne({model:"member",where:[{field:"id",value:o}]});if(!r)return null;let n=await t.findOne({model:"user",where:[{field:"id",value:r.userId}]});return n?{...r,user:{id:n.id,name:n.name,email:n.email,image:n.image}}:null},createMember:async o=>await t.create({model:"member",data:o}),updateMember:async(o,r)=>await t.update({model:"member",where:[{field:"id",value:o}],update:{role:r}}),deleteMember:async o=>await t.delete({model:"member",where:[{field:"id",value:o}]}),updateOrganization:async(o,r)=>{let n=await t.update({model:"organization",where:[{field:"id",value:o}],update:{...r,metadata:typeof r.metadata=="object"?JSON.stringify(r.metadata):r.metadata}});return n?{...n,metadata:n.metadata?It(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(u=>u.userId),d=await t.findMany({model:"user",where:[{field:"id",value:a,operator:"in"}]}),c=new Map(d.map(u=>[u.id,u])),l=A.map(u=>{let K=c.get(u.userId);if(!K)throw new te("Unexpected error: User not found for member");return{...u,user:{id:K.id,name:K.name,email:K.email,image:K.image}}});return{...n,invitations:s,members:l}},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=k(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 Ac=require("better-call");var M=P(async e=>({})),J=P({use:[R]},async e=>({session:e.context.session}));var ee=require("zod");var D=require("zod");var St=D.z.string(),sn=D.z.enum(["pending","accepted","rejected","canceled"]).default("pending"),lc=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()}),gc=D.z.object({id:D.z.string().default(G),organizationId:D.z.string(),userId:D.z.string(),role:St,createdAt:D.z.date()}),mc=D.z.object({id:D.z.string().default(G),organizationId:D.z.string(),email:D.z.string(),role:St,status:sn,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 Ut=e=>p("/organization/invite-member",{method:"POST",use:[M,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=j(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}),l=await r.findOrganizationById(o);if(!l)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:l,inviter:{...n,user:t.user}},i.request),i.json(c)}),_t=p("/organization/accept-invitation",{method:"POST",body:ee.z.object({invitationId:ee.z.string({description:"The ID of the invitation to accept"})}),use:[M,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=j(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}})}),vt=p("/organization/reject-invitation",{method:"POST",body:ee.z.object({invitationId:ee.z.string({description:"The ID of the invitation to reject"})}),use:[M,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=j(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})}),kt=p("/organization/cancel-invitation",{method:"POST",body:ee.z.object({invitationId:ee.z.string({description:"The ID of the invitation to cancel"})}),use:[M,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=j(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)}),Pt=p("/organization/get-invitation",{method:"GET",use:[M],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=j(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 Nt=()=>p("/organization/add-member",{method:"POST",body:ae.z.object({userId:ae.z.string(),role:ae.z.string(),organizationId:ae.z.string().optional()}),use:[M],metadata:{SERVER_ONLY:!0}},async e=>{let i=e.body.userId?await S(e).catch(A=>null):null,t=e.body.organizationId||i?.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:y.NO_ACTIVE_ORGANIZATION}});let o=j(e.context,e.context.orgOptions),r=await e.context.internalAdapter.findUserById(e.body.userId);if(!r)throw new 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)}),Dt=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:[M,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=j(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})}),Lt=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:[M,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=j(i.context,i.context.orgOptions),n=await r.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!n)return i.json(null,{status:400,body:{message:y.MEMBER_NOT_FOUND}});let s=i.context.roles[n.role];if(!s)return i.json(null,{status:400,body:{message:y.ROLE_NOT_FOUND}});if(s.authorize({member:["update"]}).error||i.body.role==="owner"&&n.role!=="owner")return i.json(null,{body:{message:"You are not allowed to update this member"},status:403});let a=await r.updateMember(i.body.memberId,i.body.role);return a?i.json(a):i.json(null,{status:400,body:{message:y.MEMBER_NOT_FOUND}})}),Bt=p("/organization/get-active-member",{method:"GET",use:[M,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 j(e.context,e.context.orgOptions).findMemberByOrgId({userId:i.user.id,organizationId:t});return r?e.json(r):e.json(null,{status:400,body:{message:y.MEMBER_NOT_FOUND}})});var _=require("zod");var ue=require("better-call");var xt=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:[M],metadata:{openapi:{description:"Create an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization that was created",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let i=await S(e);if(!i&&(e.request||e.headers))throw new ue.APIError("UNAUTHORIZED");let t=i?.user||null;if(!t){if(!e.body.userId)throw new ue.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 ue.APIError("FORBIDDEN",{message:y.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION});let n=j(e.context,o),s=await n.listOrganizations(t.id);if(typeof o.organizationLimit=="number"?s.length>=o.organizationLimit:typeof o.organizationLimit=="function"?await o.organizationLimit(t):!1)throw new ue.APIError("FORBIDDEN",{message:y.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS});if(await n.findOrganizationBySlug(e.body.slug))throw new ue.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)}),jt=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:[M],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 ue.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=j(e.context,e.context.orgOptions),r=await o.findMemberByOrgId({userId:i.user.id,organizationId:t});if(!r)return e.json(null,{status:400,body:{message:y.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION}});let n=e.context.roles[r.role];if(!n)return e.json(null,{status:400,body:{message:"Role not found!"}});if(n.authorize({organization:["update"]}).error)return e.json(null,{body:{message:y.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION},status:403});let A=await o.updateOrganization(t,e.body.data);return e.json(A)}),zt=p("/organization/delete",{method:"POST",body:_.z.object({organizationId:_.z.string({description:"The organization id to delete"})}),requireHeaders:!0,use:[M],metadata:{openapi:{description:"Delete an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string",description:"The organization id that was deleted"}}}}}}}},async e=>{let i=await e.context.getSession(e);if(!i)return e.json(null,{status:401});let t=e.body.organizationId;if(!t)return e.json(null,{status:400,body:{message:y.ORGANIZATION_NOT_FOUND}});let o=j(e.context,e.context.orgOptions),r=await o.findMemberByOrgId({userId:i.user.id,organizationId:t});if(!r)return e.json(null,{status:400,body:{message:y.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION}});let n=e.context.roles[r.role];if(!n)return e.json(null,{status:400,body:{message:"Role not found!"}});if(n.authorize({organization:["delete"]}).error)throw new ue.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)}),Ft=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:[M,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 j(e.context,e.context.orgOptions).findFullOrganization({organizationId:t,isSlug:!!e.query?.organizationSlug});if(!r)throw new ue.APIError("BAD_REQUEST",{message:y.ORGANIZATION_NOT_FOUND});return e.json(r)}),Vt=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,M],metadata:{openapi:{description:"Set the active organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let i=j(e.context,e.context.orgOptions),t=e.context.session,o=e.body.organizationSlug||e.body.organizationId;if(o===null){if(!t.session.activeOrganizationId)return e.json(null);let a=await i.setActiveOrganization(t.session.token,null);return await h(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 ue.APIError("FORBIDDEN",{message:y.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION});let s=await i.setActiveOrganization(t.session.token,o);return await h(e,{session:s,user:t.user}),e.json(r)}),Mt=p("/organization/list",{method:"GET",use:[M,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 j(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(t)});var an=yo({name:["action"]}),Yc=an.newRole({name:["action"]}),An=e=>{let i={createOrganization:xt,updateOrganization:jt,deleteOrganization:zt,setActiveOrganization:Vt,getFullOrganization:Ft,listOrganizations:Mt,createInvitation:Ut(e),cancelInvitation:kt,acceptInvitation:_t,getInvitation:Pt,rejectInvitation:vt,addMember:Nt(),removeMember:Dt,updateMemberRole:Lt(e),getActiveMember:Bt},t={...Tt,...e?.roles};return{id:"organization",endpoints:{...Ot(i,{orgOptions:e||{},roles:t,getSession:async r=>await S(r)}),hasPermission:p("/organization/has-permission",{method:"POST",requireHeaders:!0,body:je.z.object({permission:je.z.record(je.z.string(),je.z.array(je.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 $o.APIError("BAD_REQUEST",{message:y.NO_ACTIVE_ORGANIZATION});let s=await j(r.context).findMemberByOrgId({userId:r.context.session.user.id,organizationId:r.context.session.session.activeOrganizationId||""});if(!s)throw new $o.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 eo=require("zod");var le=require("zod");var ze=require("better-call");var wo="two_factor";var Co="trust_device";var Go=require("zod");var Ie=P({body:Go.z.object({trustDevice:Go.z.boolean().optional()})},async e=>{let i=await S(e);if(!i){let t=e.context.createAuthCookie(wo),o=await e.getSignedCookie(t.name,e.context.secret);if(!o)throw new ze.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let r=await e.context.internalAdapter.findUserById(o);if(!r)throw new ze.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let n=await e.context.internalAdapter.createSession(o,e.request);if(!n)throw new ze.APIError("INTERNAL_SERVER_ERROR",{message:"failed to create session"});return{valid:async()=>{if(await h(e,{session:n,user:r}),e.body.trustDevice){let s=e.context.createAuthCookie(Co,{maxAge:2592e3}),A=await Je(e.context.secret,`${r.id}!${n.token}`);await e.setSignedCookie(s.name,`${A}!${n.token}`,e.context.secret,s.attributes)}return e.json({session:n,user:r})},invalid:async()=>{throw new ze.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 ze.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:i}});var Fe=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 dn(e){return Array.from({length:e?.amount??10}).fill(null).map(()=>z(e?.length??10,F("a-z","0-9"))).map(i=>`${i.slice(0,5)}-${i.slice(5)}`)}async function Zo(e,i){let t=e,o=i?.customBackupCodesGenerate?i.customBackupCodesGenerate():dn(),r=await he({data:JSON.stringify(o),key:t});return{backupCodes:o,encryptedBackupCodes:r}}async function cn(e,i){let t=await qt(e.backupCodes,i);return t?{status:t.includes(e.code),updated:t.filter(o=>o!==e.code)}:{status:!1,updated:null}}async function qt(e,i){let t=Buffer.from(await Ce({key:i,data:e})).toString("utf-8"),o=JSON.parse(t),r=le.z.array(le.z.string()).safeParse(o);return r.success?r.data:null}var Ht=(e,i)=>({id:"backup_code",endpoints:{verifyBackupCode:p("/two-factor/verify-backup-code",{method:"POST",body:le.z.object({code:le.z.string(),disableSession:le.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 Fe.APIError("BAD_REQUEST",{message:Y.BACKUP_CODES_NOT_ENABLED});let n=await cn({backupCodes:r.backupCodes,code:t.body.code},t.context.secret);if(!n.status)throw new Fe.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 h(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:le.z.object({password:le.z.string()}),use:[R]},async t=>{let o=t.context.session.user;if(!o.twoFactorEnabled)throw new Fe.APIError("BAD_REQUEST",{message:Y.TWO_FACTOR_NOT_ENABLED});await t.context.password.checkPassword(o.id,t);let r=await Zo(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:le.z.object({userId:le.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 Fe.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let r=await qt(o.backupCodes,t.context.secret);if(!r)throw new Fe.APIError("BAD_REQUEST",{message:Y.BACKUP_CODES_NOT_ENABLED});return t.json({status:!0,backupCodes:r})})}});var Ve=require("better-call"),Qo=require("zod");var $t=require("oslo");var Gt=(e,i)=>{let t={...e,digits:e?.digits||6,period:new $t.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 Ve.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 Ve.APIError("BAD_REQUEST",{message:Y.OTP_NOT_ENABLED});let a=z(t.digits,F("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:Qo.z.object({code:Qo.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 Ve.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 Ve.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 Ve.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"),Zt=require("oslo"),Xe=require("oslo/otp"),Ye=require("zod");var Qt=(e,i)=>{let t={...e,digits:e?.digits||6,period:new Zt.TimeSpan(e?.period||30,"s")},o=p("/totp/generate",{method:"POST",use:[R],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 Xe.TOTPController(t).generate(Buffer.from(a.secret))}}),r=p("/two-factor/get-totp-uri",{method:"POST",use:[R],body:Ye.z.object({password:Ye.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,Xe.createTOTPKeyURI)(e.issuer||s.context.appName,A.email,Buffer.from(a.secret),t)}}),n=p("/two-factor/verify-totp",{method:"POST",body:Ye.z.object({code:Ye.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 Xe.TOTPController(t),c=await Ce({key:s.context.secret,data:a.secret}),l=Buffer.from(c);if(!await d.verify(s.body.code,l))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(E=>{throw console.log(E),E});await s.context.internalAdapter.deleteSession(s.context.session.session.token),await h(s,{session:m,user:K})}return s.context.valid()});return{id:"totp",endpoints:{generateTOTP:o,getTOTPURI:r,verifyTOTP:n}}};var pn=require("better-call");async function Wo(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 Jo=require("better-call"),Xt=require("oslo/otp"),er=require("oslo");var Wt=require("better-call"),Jt=async e=>{let i=e.context.returned;return i?i instanceof Response?i.status!==200?null:await i.clone().json():i instanceof Wt.APIError?null:i:null};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 Kn=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 un=e=>{let i={twoFactorTable:"twoFactor"},t=Qt({issuer:e?.issuer,...e?.totpOptions},i.twoFactorTable),o=Ht({...e?.backupCodeOptions},i.twoFactorTable),r=Gt({...e?.otpOptions},i.twoFactorTable);return{id:"two-factor",endpoints:{...t.endpoints,...r.endpoints,...o.endpoints,enableTwoFactor:p("/two-factor/enable",{method:"POST",body:eo.z.object({password:eo.z.string({description:"User password"}).min(8)}),use:[R],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 Wo(n,{password:A,userId:s.id}))throw new Jo.APIError("BAD_REQUEST",{message:g.INVALID_PASSWORD});let d=z(16,F("a-z","0-9","-")),c=await he({key:n.context.secret,data:d}),l=await Zo(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 h(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:l.encryptedBackupCodes,userId:s.id}});let u=(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:u,backupCodes:l.backupCodes})}),disableTwoFactor:p("/two-factor/disable",{method:"POST",body:eo.z.object({password:eo.z.string({description:"User password"}).min(8)}),use:[R],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 Wo(n,{password:A,userId:s.id}))throw new Jo.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 h(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:P(async n=>{let s=n.context.newSession;if(!s||!s?.user.twoFactorEnabled)return;let A=n.context.createAuthCookie(Co),a=await n.getSignedCookie(A.name,n.context.secret);if(a){let[c,l]=a.split("!"),u=await Je(n.context.secret,`${s.user.id}!${l}`);if(c===u){let K=await Je(n.context.secret,`${s.user.id}!${s.session.token}`);await n.setSignedCookie(A.name,`${K}!${s.session.token}`,n.context.secret,A.attributes);return}}$(n),await n.context.internalAdapter.deleteSession(s.session.token);let d=n.context.createAuthCookie(wo,{maxAge:60*10});return await n.setSignedCookie(d.name,s.user.id,n.context.secret,d.attributes),n.json({twoFactorRedirect:!0})})}]},schema:ne(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 ie=require("zod");var Me=require("@simplewebauthn/browser");var gn=require("@better-fetch/fetch");var cK=require("nanostores");var Yp=require("@better-fetch/fetch");var ln=require("nanostores");var eK=require("@better-fetch/fetch"),bo=require("nanostores"),Yo=(e,i,t,o)=>{let r=(0,bo.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,bo.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,Me.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,Me.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 Me.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:{}}),mn=()=>{let e=(0,or.atom)();return{id:"passkey",$InferServerPlugin:{},getActions:i=>ir(i,{$listPasskeys:e}),getAtoms(i){return{listPasskeys:Yo(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 fn=e=>{let i=de.BETTER_AUTH_URL,t=e?.rpID||i?.replace("http://","").replace("https://","").split(":")[0]||"localhost";if(!t)throw new te("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:[Qe],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}]}),l=new Uint8Array(Buffer.from(z(32,F("a-z","0-9")))),u;u=await(0,Oe.generateRegistrationOptions)({rpName:o.rpName||a.context.appName,rpID:o.rpID,userID:l,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:u.challenge,userData:{id:d.user.id}}),expiresAt:r}),a.json(u,{status:200})}),generatePasskeyAuthenticationOptions:p("/passkey/generate-authenticate-options",{method:"POST",body:ie.z.object({email:ie.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 l=await(0,Oe.generateAuthenticationOptions)({rpID:o.rpID,userVerification:"preferred",...c.length?{allowCredentials:c.map(m=>({id:m.id,transports:m.transports?.split(",")}))}:{}}),u={expectedChallenge:l.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(u),expiresAt:r}),a.json(l,{status:200})}),verifyPasskeyRegistration:p("/passkey/verify-registration",{method:"POST",body:ie.z.object({response:ie.z.any({description:"The response from the authenticator"}),name:ie.z.string({description:"Name of the passkey"}).optional()}),use:[Qe],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,l=await a.getSignedCookie(o.advanced.webAuthnChallengeCookie,a.context.secret);if(!l)throw new X.APIError("BAD_REQUEST",{message:A.CHALLENGE_NOT_FOUND});let u=await a.context.internalAdapter.findVerificationValue(l);if(!u)return a.json(null,{status:400});let{expectedChallenge:K,userData:m}=JSON.parse(u.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 E=await(0,Oe.verifyRegistrationResponse)({response:c,expectedChallenge:K,expectedOrigin:d,expectedRPID:e?.rpID}),{verified:v,registrationInfo:f}=E;if(!v||!f)return a.json(null,{status:400});let{credentialID:w,credentialPublicKey:O,counter:I,credentialDeviceType:q,credentialBackedUp:no}=f,lr=Buffer.from(O).toString("base64"),gr={name:a.body.name,userId:m.id,webauthnUserID:a.context.generateId({model:"passkey"}),id:w,publicKey:lr,counter:I,deviceType:q,transports:c.response.transports.join(","),backedUp:no,createdAt:new Date},mr=await a.context.adapter.create({model:"passkey",data:gr});return a.json(mr,{status:200})}catch(E){throw console.log(E),new X.APIError("INTERNAL_SERVER_ERROR",{message:A.FAILED_TO_VERIFY_REGISTRATION})}}),verifyPasskeyAuthentication:p("/passkey/verify-authentication",{method:"POST",body:ie.z.object({response:ie.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,l=await a.getSignedCookie(o.advanced.webAuthnChallengeCookie,a.context.secret);if(!l)throw new X.APIError("BAD_REQUEST",{message:A.CHALLENGE_NOT_FOUND});let u=await a.context.internalAdapter.findVerificationValue(l);if(!u)throw new X.APIError("BAD_REQUEST",{message:A.CHALLENGE_NOT_FOUND});let{expectedChallenge:K}=JSON.parse(u.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 E=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:v}=E;if(!v)throw new X.APIError("UNAUTHORIZED",{message:A.AUTHENTICATION_FAILED});await a.context.adapter.update({model:"passkey",where:[{field:"id",value:m.id}],update:{counter:E.authenticationInfo.newCounter}});let f=await a.context.internalAdapter.createSession(m.userId,a.request);if(!f)throw new X.APIError("INTERNAL_SERVER_ERROR",{message:A.UNABLE_TO_CREATE_SESSION});let w=await a.context.internalAdapter.findUserById(m.userId);if(!w)throw new X.APIError("INTERNAL_SERVER_ERROR",{message:"User not found"});return await h(a,{session:f,user:w}),a.json({session:f},{status:200})}catch(E){throw a.context.logger.error("Failed to verify authentication",E),new X.APIError("BAD_REQUEST",{message:A.AUTHENTICATION_FAILED})}}),listPasskeys:p("/passkey/list-user-passkeys",{method:"GET",use:[R]},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:ie.z.object({id:ie.z.string()}),use:[R]},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:ie.z.object({id:ie.z.string(),name:ie.z.string()}),use:[R]},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:ne(hn,e?.schema),$ERROR_CODES:A}},hn={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 oo=require("zod");var qe=require("better-call");var Xo=()=>{let e={INVALID_USERNAME_OR_PASSWORD:"invalid username or password",EMAIL_NOT_VERIFIED:"email not verified",UNEXPECTED_ERROR:"unexpected error"};return{id:"username",endpoints:{signInUsername:p("/sign-in/username",{method:"POST",body:oo.z.object({username:oo.z.string({description:"The username of the user"}),password:oo.z.string({description:"The password of the user"}),rememberMe:oo.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:Xo}),new qe.APIError("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});if(!t.emailVerified&&i.context.options.emailAndPassword?.requireEmailVerification)throw await Po(i,t),new qe.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 qe.APIError("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});let r=o?.password;if(!r)throw i.context.logger.error("Password not found",{username:Xo}),new qe.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 qe.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 h(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}}}},$ERROR_CODES:Y}};var tr=require("better-call"),yn=()=>({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)return;let t="";return i.includes(".")?t=i:t=await(0,tr.serializeSigned)("",i,e.context.secret),e.request&&e.request.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${t.replace("=","")}`),e.headers&&e.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${t.replace("=","")}`),{context:e}}}]}});var Ue=require("zod");var rr=require("better-call");var wn=e=>({id:"magic-link",endpoints:{signInMagicLink:p("/sign-in/magic-link",{method:"POST",requireHeaders:!0,body:Ue.z.object({email:Ue.z.string({description:"Email address to send the magic link"}).email(),callbackURL:Ue.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 rr.APIError("BAD_REQUEST",{message:g.USER_NOT_FOUND});let o=z(32,F("a-z","A-Z"));await i.context.internalAdapter.createVerificationValue({identifier:o,value:t,expiresAt:new Date(Date.now()+(e.expiresIn||60*5)*1e3)});let r=`${i.context.baseURL}/magic-link/verify?token=${o}&callbackURL=${i.body.callbackURL||"/"}`;return await e.sendMagicLink({email:t,url:r,token:o},i.request),i.json({status:!0})}),magicLinkVerify:p("/magic-link/verify",{method:"GET",query:Ue.z.object({token:Ue.z.string({description:"Verification token"}),callbackURL:Ue.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 h(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 Q=require("better-call");function Cn(e){return z(e,F("0-9"))}var bn=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 Q.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 Q.APIError("UNAUTHORIZED",{message:t.INVALID_PHONE_NUMBER_OR_PASSWORD});let a=(await o.context.internalAdapter.findAccountByUserId(s.id)).find(u=>u.providerId==="credential");if(!a)throw o.context.logger.error("Credential account not found",{phoneNumber:n}),new Q.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 Q.APIError("UNAUTHORIZED",{message:t.UNEXPECTED_ERROR});if(!await o.context.password.verify({hash:d,password:r}))throw o.context.logger.error("Invalid password"),new Q.APIError("UNAUTHORIZED",{message:t.INVALID_PHONE_NUMBER_OR_PASSWORD});let l=await o.context.internalAdapter.createSession(s.id,o.headers,o.body.rememberMe===!1);if(!l)throw o.context.logger.error("Failed to create session"),new Q.APIError("UNAUTHORIZED",{message:g.FAILED_TO_CREATE_SESSION});return await h(o,{session:l,user:s},o.body.rememberMe===!1),o.json({user:s,session:l})}),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 Q.APIError("NOT_IMPLEMENTED",{message:"sendOTP not implemented"});if(i.phoneNumberValidator&&!await i.phoneNumberValidator(o.body.phoneNumber))throw new Q.APIError("BAD_REQUEST",{message:t.INVALID_PHONE_NUMBER});let r=Cn(i.otpLength);return await o.context.internalAdapter.createVerificationValue({value:r,identifier:o.body.phoneNumber,expiresAt:k(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 Q.APIError("BAD_REQUEST",{message:"OTP expired"})):new Q.APIError("BAD_REQUEST",{message:t.OTP_NOT_FOUND});if(r.value!==o.body.code)throw new Q.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 Q.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 Q.APIError("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_CREATE_USER})}else return o.json(null);if(!n)throw new Q.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 Q.APIError("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_CREATE_SESSION});return await h(o,{session:s,user:n}),o.json({user:n,session:s})}return o.json({user:n,session:null})})},schema:ne(On,e?.schema),$ERROR_CODES:t}},On={user:{fields:{phoneNumber:{type:"string",required:!1,unique:!0,returned:!0},phoneNumberVerified:{type:"boolean",required:!1,returned:!0,input:!1}}}};var Tn={user:{fields:{isAnonymous:{type:"boolean",required:!1}}}},En=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=ve(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 h(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:P(async t=>{let r=t.responseHeader.get("set-cookie"),n=t.context.authCookies.sessionToken.name;if(!uo(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 T.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:ne(Tn,e?.schema),$ERROR_CODES:i}};var C=require("zod");var Rn=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=P(async r=>{let n=await S(r);if(!n?.session)throw new T.APIError("UNAUTHORIZED");let s=n.user;if(!s.role||(Array.isArray(i.adminRole)?!i.adminRole.includes(s.role):s.role!==i.adminRole))throw new T.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:P(async r=>{let n=await Jt(r);if(!n)return;let s=n.filter(A=>!A.impersonatedBy);return r.json(s)})}]},endpoints:{setRole:p("/admin/set-role",{method:"POST",body:C.z.object({userId:C.z.string({description:"The user id"}),role:C.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:C.z.object({email:C.z.string({description:"The email of the user"}),password:C.z.string({description:"The password of the user"}),name:C.z.string({description:"The name of the user"}),role:C.z.string({description:"The role of the user"}),data:C.z.optional(C.z.record(C.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 T.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 T.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:C.z.object({searchValue:C.z.string({description:"The value to search for"}).optional(),searchField:C.z.enum(["email","name"],{description:"The field to search in, defaults to email. Can be `email` or `name`"}).optional(),searchOperator:C.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:C.z.string({description:"The number of users to return"}).or(C.z.number()).optional(),offset:C.z.string({description:"The offset to start from"}).or(C.z.number()).optional(),sortBy:C.z.string({description:"The field to sort by"}).optional(),sortDirection:C.z.enum(["asc","desc"],{description:"The direction to sort by"}).optional(),filterField:C.z.string({description:"The field to filter by"}).optional(),filterValue:C.z.string({description:"The value to filter by"}).or(C.z.number()).or(C.z.boolean()).optional(),filterOperator:C.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:C.z.object({userId:C.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:C.z.object({userId:C.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:C.z.object({userId:C.z.string({description:"The user id"}),banReason:C.z.string({description:"The reason for the ban"}).optional(),banExpiresIn:C.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 T.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?k(r.body.banExpiresIn,"sec"):e?.defaultBanExpiresIn?k(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:C.z.object({userId:C.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 T.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?k(e.impersonationSessionDuration,"sec"):k(60*60,"sec")});if(!s)throw new T.APIError("INTERNAL_SERVER_ERROR",{message:t.FAILED_TO_CREATE_USER});return await h(r,{session:s,user:n},!0),r.json({session:s,user:n})}),revokeUserSession:p("/admin/revoke-user-session",{method:"POST",body:C.z.object({sessionToken:C.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:C.z.object({userId:C.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:C.z.object({userId:C.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:ne(In,i.schema)}},In={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 io=require("@better-fetch/fetch"),_e=require("better-call"),sr=require("oslo/jwt"),ce=require("zod");async function nr(e,i){if(e.idToken){let o=(0,sr.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,io.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 Sn=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 N({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,io.betterFetch)(o.discoveryUrl,{method:"GET"});a.data&&(A=a.data.token_endpoint,n=a.data.userinfo_endpoint)}if(!A)throw new _e.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 nr(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(q=>q.providerId===o);if(!r)throw new _e.APIError("BAD_REQUEST",{message:`No config found for provider ${o}`});let{discoveryUrl:n,authorizationUrl:s,tokenUrl:A,clientId:a,clientSecret:d,scopes:c,redirectURI:l,responseType:u,pkce:K,prompt:m,accessType:E}=r,v=s,f=A;if(n){let q=await(0,io.betterFetch)(n,{onError(no){t.context.logger.error(no.error.message,no.error,{discoveryUrl:n})}});q.data&&(v=q.data.authorization_endpoint,f=q.data.token_endpoint)}if(!v||!f)throw new _e.APIError("BAD_REQUEST",{message:i.INVALID_OAUTH_CONFIGURATION});let{state:w,codeVerifier:O}=await Pe(t),I=await N({id:o,options:{clientId:a,clientSecret:d,redirectURI:l},authorizationEndpoint:v,state:w,codeVerifier:K?O:void 0,scopes:c||[],redirectURI:`${t.context.baseURL}/oauth2/callback/${o}`});return u&&u!=="code"&&I.searchParams.set("response_type",u),m&&I.searchParams.set("prompt",m),E&&I.searchParams.set("access_type",E),t.json({url:I.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(O=>O.providerId===t.params.providerId);if(!o)throw new _e.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,l=o.userInfoUrl;if(o.discoveryUrl){let O=await(0,io.betterFetch)(o.discoveryUrl,{method:"GET"});O.data&&(c=O.data.token_endpoint,l=O.data.userinfo_endpoint)}try{if(!c)throw new _e.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(O){throw t.context.logger.error(O&&typeof O=="object"&&"name"in O?O.name:"",O),t.redirect(`${a}?error=oauth_code_verification_failed`)}if(!r)throw new _e.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let u=o.getUserInfo?await o.getUserInfo(r):await nr(r,l);if(!u?.email)throw t.context.logger.error("Unable to get user info",u),t.redirect(`${t.context.baseURL}/error?error=email_is_missing`);let K=o.mapProfileToUser?await o.mapProfileToUser(u):null,m=await De(t,{userInfo:{...u,...K},account:{providerId:o.providerId,accountId:u.id,...r,scope:r.scopes?.join(",")}});function E(O){throw t.redirect(`${a||s||`${t.context.baseURL}/error`}?error=${O}`)}if(m.error)return E(m.error.split(" ").join("_"));let{session:v,user:f}=m.data;await h(t,{session:v,user:f});let w;try{w=new URL(s).toString()}catch{w=s}throw t.redirect(w)})},$ERROR_CODES:i}};var He=require("zod"),ar={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0}}}},Eu=He.z.object({id:He.z.string(),publicKey:He.z.string(),privateKey:He.z.string(),createdAt:He.z.date()});var ei=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 Un=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 ei(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:[R],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=ei(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"}),l=await(0,ye.exportJWK)(d),u=await(0,ye.exportJWK)(c),K=JSON.stringify(u),m={id:crypto.randomUUID(),publicKey:JSON.stringify(l),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:ne(ar,e?.schema)});var to=require("zod");var _n=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(We(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:to.z.object({sessionToken:to.z.string({description:"The session token to set as active"})}),requireHeaders:!0,use:[R],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 T.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 T.APIError("UNAUTHORIZED",{message:o.INVALID_SESSION_TOKEN});return await h(r,a),r.json(a)}),revokeDeviceSession:p("/multi-session/revoke",{method:"POST",body:to.z.object({sessionToken:to.z.string({description:"The session token to revoke"})}),requireHeaders:!0,use:[R],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 T.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(We(d)),l=(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),u=r.context.internalAdapter;if(l.length>0){let m=(await u.findSessions(l)).filter(E=>E&&E.session.expiresAt>new Date);if(m.length>0){let E=m[0];await h(r,E)}else $(r)}else $(r)}else $(r);return r.json({success:!0})})},hooks:{after:[{matcher:()=>!0,handler:P(async r=>{let n=r.responseHeader.get("set-cookie");if(!n)return;let s=uo(n),A=r.context.authCookies.sessionToken,a=s.get(A.name)?.value;if(!a)return;let d=We(r.headers?.get("cookie")||""),c=a.split(".")[0];if(!c)return;let l=`${A.name}_multi-${c}`;s.get(l)||d.get(l)||Object.keys(Object.fromEntries(d)).filter(t).length+(n.includes("session_token")?1:0)>i.maximumSessions||await r.setSignedCookie(l,c,r.context.secret,A.options)})},{matcher:r=>r.path==="/sign-out",handler:P(async r=>{let n=r.headers?.get("cookie");if(!n)return;let s=Object.fromEntries(We(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 L=require("zod");var oi=["email-verification","sign-in","forget-password"],vn=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:L.z.object({email:L.z.string({description:"Email address to send the OTP"}),type:L.z.enum(oi,{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 T.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 T.APIError("BAD_REQUEST",{message:t.INVALID_EMAIL});let s=z(i.otpLength,F("0-9"));return await o.context.internalAdapter.createVerificationValue({value:s,identifier:`${o.body.type}-otp-${r}`,expiresAt:k(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:k(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:L.z.object({email:L.z.string({description:"Email address to send the OTP"}),type:L.z.enum(oi,{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=z(i.otpLength,F("0-9"));return await o.context.internalAdapter.createVerificationValue({value:n,identifier:`${o.body.type}-otp-${r}`,expiresAt:k(i.expireIn,"sec")}),n}),getVerificationOTP:p("/email-otp/get-verification-otp",{method:"GET",query:L.z.object({email:L.z.string({description:"Email address to get the OTP"}),type:L.z.enum(oi)}),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:L.z.object({email:L.z.string({description:"Email address to verify"}),otp:L.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 T.APIError("BAD_REQUEST",{message:"Invalid email"});let s=await o.context.internalAdapter.findVerificationValue(`email-verification-otp-${r}`);if(!s||s.expiresAt<new Date)throw s&&await o.context.internalAdapter.deleteVerificationValue(s.id),new T.APIError("BAD_REQUEST",{message:"Invalid OTP"});let A=o.body.otp;if(s.value!==A)throw new T.APIError("BAD_REQUEST",{message:"Invalid OTP"});await o.context.internalAdapter.deleteVerificationValue(s.id);let a=await o.context.internalAdapter.findUserByEmail(r);if(!a)throw new T.APIError("BAD_REQUEST",{message:"User not found"});let d=await o.context.internalAdapter.updateUser(a.user.id,{email:r,emailVerified:!0});return o.json({user:d})}),signInEmailOTP:p("/sign-in/email-otp",{method:"POST",body:L.z.object({email:L.z.string({description:"Email address to sign in"}),otp:L.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||n.expiresAt<new Date)throw n&&await o.context.internalAdapter.deleteVerificationValue(n.id),new T.APIError("BAD_REQUEST",{message:"Invalid OTP"});let s=o.body.otp;if(n.value!==s)throw new T.APIError("BAD_REQUEST",{message:"Invalid OTP"});await o.context.internalAdapter.deleteVerificationValue(n.id);let A=await o.context.internalAdapter.findUserByEmail(r);if(!A){if(i.disableSignUp)throw new T.APIError("BAD_REQUEST",{message:"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 h(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 h(o,{session:a,user:A.user}),o.json({session:a,user:A})}),forgetPasswordEmailOTP:p("/forget-password/email-otp",{method:"POST",body:L.z.object({email:L.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 T.APIError("BAD_REQUEST",{message:"User not found"});let s=z(i.otpLength,F("0-9"));return await o.context.internalAdapter.createVerificationValue({value:s,identifier:`forget-password-otp-${r}`,expiresAt:k(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:L.z.object({email:L.z.string({description:"Email address to reset the password"}),otp:L.z.string({description:"OTP sent to the email"}),password:L.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 T.APIError("BAD_REQUEST",{message:t.USER_NOT_FOUND});let s=await o.context.internalAdapter.findVerificationValue(`forget-password-otp-${r}`);if(!s||s.expiresAt<new Date)throw s&&await o.context.internalAdapter.deleteVerificationValue(s.id),new T.APIError("BAD_REQUEST",{message:t.OTP_EXPIRED});let A=o.body.otp;if(s.value!==A)throw new T.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=z(i.otpLength,F("0-9"));await o.context.internalAdapter.createVerificationValue({value:n,identifier:`email-verification-otp-${r.user.email}`,expiresAt:k(i.expireIn,"sec")}),await e.sendVerificationOTP({email:r.user.email,otp:n,type:"email-verification"},o.request)}}}]},$ERROR_CODES:t}};var ii=require("zod");var dr=require("@better-fetch/fetch");function Ar(e){return e==="true"||e===!0}var kn=e=>({id:"one-tap",endpoints:{oneTapCallback:p("/one-tap/callback",{method:"POST",body:ii.z.object({idToken:ii.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,dr.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 T.APIError("BAD_GATEWAY",{message:"User not found"});let A=await i.context.internalAdapter.createOAuthUser({email:o.email,emailVerified:Ar(o.email_verified),name:o.name,image:o.picture},{providerId:"google",accountId:o.sub});if(!A)throw new T.APIError("INTERNAL_SERVER_ERROR",{message:"Could not create user"});let a=await i.context.internalAdapter.createSession(A?.user.id,i.request);return await h(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 h(i,{user:n.user,session:s}),i.json({session:s,user:n})})}});var Oo=require("zod");function Pn(){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 Nn=e=>({id:"oauth-proxy",endpoints:{oAuthProxy:p("/oauth-proxy-callback",{method:"GET",query:Oo.z.object({callbackURL:Oo.z.string({description:"The URL to redirect to after the proxy"}),cookies:Oo.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:P(async i=>{let t=i.context.returned,o=t instanceof T.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===ve(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||Pn()||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 $e=require("zod");var Dn=(e,i)=>({id:"custom-session",endpoints:{getSession:p("/get-session",{method:"GET",metadata:{CUSTOM_SESSION:!0},query:$e.z.optional($e.z.object({disableCookieCache:$e.z.boolean({description:"Disable cookie cache and fetch session from database"}).or($e.z.string().transform(t=>t==="true")).optional(),disableRefresh:$e.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 ge=require("zod");var Ge=e=>{let i=e.plugins?.reduce((a,d)=>{let c=d.schema;if(!c)return a;for(let[l,u]of Object.entries(c))a[l]={fields:{...a[l]?.fields,...u.fields},modelName:u.modelName||l};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 Ln=require("zod");var cr=require("kysely"),ti=require("kysely");var ro={};function Kr(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 To(e){let i=[];return e.metadata?.openapi?.parameters?(i.push(...e.metadata.openapi.parameters),i):(e.query instanceof ge.ZodObject&&Object.entries(e.query.shape).forEach(([t,o])=>{o instanceof ge.ZodSchema&&i.push({name:t,in:"query",schema:{type:Kr(o),..."minLength"in o&&o.minLength?{minLength:o.minLength}:{},description:o.description}})}),i)}function pr(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof ge.ZodObject||e.body instanceof ge.ZodOptional)){let i=e.body.shape;if(!i)return;let t={},o=[];return Object.entries(i).forEach(([r,n])=>{n instanceof ge.ZodSchema&&(t[r]={type:Kr(n),description:n.description},n instanceof ge.ZodOptional||o.push(r))}),{required:e.body instanceof ge.ZodOptional?!1:!!e.body,content:{"application/json":{schema:{type:"object",properties:t,required:o}}}}}}function Eo(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 ri(e,i){let t=Do(e,{...i,plugins:[]}),o=Ge(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((l,[u,K])=>(l[u]={type:K.type},l),{})},A},{})}};Object.entries(t.api).forEach(([A,a])=>{let d=a.options;if(!d.metadata?.SERVER_ONLY&&(d.method==="GET"&&(ro[a.path]={get:{tags:["Default",...d.metadata?.openapi?.tags||[]],description:d.metadata?.openapi?.description,operationId:d.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:To(d),responses:Eo(d.metadata?.openapi?.responses)}}),d.method==="POST")){let c=pr(d);ro[a.path]={post:{tags:["Default",...d.metadata?.openapi?.tags||[]],description:d.metadata?.openapi?.description,operationId:d.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:To(d),...c?{requestBody:c}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:Eo(d.metadata?.openapi?.responses)}}}});for(let A of i.plugins||[]){if(A.id==="open-api")continue;let a=Do(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,l])=>{let u=l.options;u.metadata?.SERVER_ONLY||(u.method==="GET"&&(ro[l.path]={get:{tags:u.metadata?.openapi?.tags||[A.id.charAt(0).toUpperCase()+A.id.slice(1)],description:u.metadata?.openapi?.description,operationId:u.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:To(u),responses:Eo(u.metadata?.openapi?.responses)}}),u.method==="POST"&&(ro[l.path]={post:{tags:u.metadata?.openapi?.tags||[A.id.charAt(0).toUpperCase()+A.id.slice(1)],description:u.metadata?.openapi?.description,operationId:u.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:To(u),requestBody:pr(u),responses:Eo(u.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:ro}}var ur=`<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">
83
+ Error: `,A),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=r?.user;if(r){let A=r.accounts.find(a=>a.providerId===t.providerId);if(A){let a=Object.fromEntries(Object.entries({accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt}).filter(([d,c])=>c!==void 0));Object.keys(a).length>0&&await e.context.internalAdapter.updateAccount(A.id,a)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.providerId)&&!i.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return si&&se.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(c){return se.error("Unable to link account",c),{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 me(e.context.secret,n.email),a=`${e.context.baseURL}/verify-email?token=${A}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:n,url:a,token:A},e.request)}if(!n)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(n.id,e.request);return s?{data:{session:s,user:n},error:null}:{error:"unable to create session",data:null}}var Ti=p("/sign-in/social",{method:"POST",query:B.z.object({currentURL:B.z.string().optional()}).optional(),body:B.z.object({callbackURL:B.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),errorCallbackURL:B.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:B.z.enum(mo,{description:"OAuth2 provider to use"}),disableRedirect:B.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:B.z.optional(B.z.object({token:B.z.string({description:"ID token from the provider"}),nonce:B.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:B.z.string({description:"Access token from the provider"}).optional(),refreshToken:B.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:B.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 Z.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 Z.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 Z.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 Z.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 Z.APIError("UNAUTHORIZED",{message:g.USER_EMAIL_NOT_FOUND});let d=await De(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 Z.APIError("UNAUTHORIZED",{message:d.error});return await h(e,d.data),e.json({session:d.data.session,user:d.data.user,url:void 0,redirect:!1})}let{codeVerifier:t,state:o}=await Pe(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})}),Ei=p("/sign-in/email",{method:"POST",body:B.z.object({email:B.z.string({description:"Email of the user"}),password:B.z.string({description:"Password of the user"}),callbackURL:B.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:B.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 Z.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:i,password:t}=e.body;if(!B.z.string().email().safeParse(i).success)throw new Z.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 Z.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 Z.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 Z.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 Z.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 Z.APIError("UNAUTHORIZED",{message:g.EMAIL_NOT_VERIFIED});let d=await me(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 Z.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 Z.APIError("UNAUTHORIZED",{message:g.FAILED_TO_CREATE_SESSION});return await h(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 Le=require("zod");var fo=Le.z.object({code:Le.z.string().optional(),error:Le.z.string().optional(),errorMessage:Le.z.string().optional(),state:Le.z.string().optional()}),Ri=p("/callback/:id",{method:["GET","POST"],body:fo.optional(),query:fo.optional(),metadata:Ee},async e=>{let i;try{if(e.method==="GET")i=fo.parse(e.query);else if(e.method==="POST")i=fo.parse(e.body);else throw new Error("Unsupported method")}catch(f){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",f),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:t,error:o,state:r}=i;if(!r)throw e.context.logger.error("State not found"),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"}`);let n=e.context.socialProviders.find(f=>f.id===e.params.id);if(!n)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:s,callbackURL:A,link:a,errorURL:d}=await go(e),c;try{c=await n.validateAuthorizationCode({code:t,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${n.id}`})}catch(f){throw e.context.logger.error("",f),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let l=await n.getUserInfo(c).then(f=>f?.user);function u(f){let w=d||A||`${e.context.baseURL}/error`;throw w.includes("?")?w=`${w}&error=${f}`:w=`${w}?error=${f}`,e.redirect(w)}if(!l)return e.context.logger.error("Unable to get user info"),u("unable_to_get_user_info");if(!l.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),u("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(a){if(a.email!==l.email.toLowerCase())return u("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:a.userId,providerId:n.id,accountId:l.id}))return u("unable_to_link_account");let w;try{w=new URL(A).toString()}catch{w=A}throw e.redirect(w)}let K=await De(e,{userInfo:{...l,email:l.email,name:l.name||l.email},account:{providerId:n.id,accountId:l.id,...c,scope:c.scopes?.join(",")},callbackURL:A});if(K.error)return e.context.logger.error(K.error.split(" ").join("_")),u(K.error.split(" ").join("_"));let{session:m,user:E}=K.data;await h(e,{session:m,user:E});let v;try{v=new URL(A).toString()}catch{v=A}throw e.redirect(v)});var ed=require("zod");var yt=require("better-call");var Ii=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 $(e),new yt.APIError("BAD_REQUEST",{message:g.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(i),$(e),e.json({success:!0})});var oe=require("zod");var ho=require("better-call");function wt(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 Vr(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 Si=p("/forget-password",{method:"POST",body:oe.z.object({email:oe.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:oe.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 ho.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=k(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})}),Ui=p("/reset-password/:token",{method:"GET",query:oe.z.object({callbackURL:oe.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(wt(e.context,t,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${i}`);throw!o||o.expiresAt<new Date?e.redirect(wt(e.context,t,{error:"INVALID_TOKEN"})):e.redirect(Vr(e.context,t,{token:i}))}),_i=p("/reset-password",{query:oe.z.optional(oe.z.object({token:oe.z.string().optional(),currentURL:oe.z.string().optional()})),method:"POST",body:oe.z.object({newPassword:oe.z.string({description:"The new password to set"}),token:oe.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 ho.APIError("BAD_REQUEST",{message:g.INVALID_TOKEN});let{newPassword:t}=e.body,o=`reset-password:${i}`,r=await e.context.internalAdapter.findVerificationValue(o);if(!r||r.expiresAt<new Date)throw new ho.APIError("BAD_REQUEST",{message:g.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(r.id);let n=r.value,s=await e.context.password.hash(t);return(await e.context.internalAdapter.findAccounts(n)).find(d=>d.providerId==="credential")?(await e.context.internalAdapter.updatePassword(n,s),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:s,accountId:n}),e.json({status:!0}))});var H=require("zod");var V=require("better-call");var Fo=require("@noble/ciphers/chacha"),Be=require("@noble/ciphers/utils"),Vo=require("@noble/ciphers/webcrypto"),Mo=require("oslo/crypto"),zo=Ro(require("uncrypto"),1);var Ct=require("oslo/encoding");var Mr=require("@noble/hashes/scrypt"),qr=require("uncrypto");var jo=Ro(require("uncrypto"),1);function Hr(e){return e.toString(2).padStart(8,"0")}function $r(e){return[...e].map(i=>Hr(i)).join("")}function bt(e){return parseInt($r(e),2)}function Gr(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));jo.default.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1);let r=bt(o);for(;r>=e;)jo.default.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1),r=bt(o);return r}function z(e,i){let t="";for(let o=0;o<e;o++)t+=i[Gr(i.length)];return t}function F(...e){let i=new Set(e),t="";for(let o of i)o==="a-z"?t+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?t+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?t+="0123456789":t+=o;return t}async function Je(e,i){let t=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},r=await zo.default.subtle.importKey("raw",t.encode(e),o,!1,["sign","verify"]),n=await zo.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,Mo.sha256)(new TextEncoder().encode(e)),o=(0,Be.utf8ToBytes)(i),r=(0,Vo.managedNonce)(Fo.xchacha20poly1305)(new Uint8Array(t));return(0,Be.bytesToHex)(r.encrypt(o))},Ce=async({key:e,data:i})=>{let t=await(0,Mo.sha256)(new TextEncoder().encode(e)),o=(0,Be.hexToBytes)(i),r=(0,Vo.managedNonce)(Fo.xchacha20poly1305)(new Uint8Array(t));return new TextDecoder().decode(r.decrypt(o))};var vi=()=>p("/update-user",{method:"POST",body:H.z.record(H.z.string(),H.z.any()),use:[R],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 V.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=Ko(e.context.options,r,"update"),A=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:t,image:o,...s});return await h(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})}),ki=p("/change-password",{method:"POST",body:H.z.object({newPassword:H.z.string({description:"The new password to set"}),currentPassword:H.z.string({description:"The current password"}),revokeOtherSessions:H.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[R],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 V.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 V.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_LONG});let a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(l=>l.providerId==="credential"&&l.password);if(!a||!a.password)throw new V.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 V.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 l=await e.context.internalAdapter.createSession(r.user.id,e.headers);if(!l)throw new V.APIError("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_GET_SESSION});await h(e,{session:l,user:r.user})}return e.json(r.user)}),Pi=p("/set-password",{method:"POST",body:H.z.object({newPassword:H.z.string()}),metadata:{SERVER_ONLY:!0},use:[R]},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 V.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 V.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 V.APIError("BAD_REQUEST",{message:"user already has a password"})}),Ni=p("/delete-user",{method:"POST",use:[Qe],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 V.APIError("NOT_FOUND");let i=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let r=z(32,F("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),$(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(i.user,e.request),e.json({success:!0,message:"User deleted"})}),Di=p("/delete-user/callback",{method:"GET",query:H.z.object({token:H.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 V.APIError("NOT_FOUND");let i=await S(e);if(!i)throw new V.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 V.APIError("NOT_FOUND",{message:g.INVALID_TOKEN});if(t.value!==i.user.id)throw new V.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),$(e);let r=e.context.options.user.deleteUser?.afterDelete;return r&&await r(i.user,e.request),e.json({success:!0,message:"User deleted"})}),Li=p("/change-email",{method:"POST",query:H.z.object({currentURL:H.z.string().optional()}).optional(),body:H.z.object({newEmail:H.z.string({description:"The new email to set"}).email(),callbackURL:H.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[R],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 V.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 V.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 V.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 V.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await me(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 xe=require("zod");var qo=require("better-call");var Bi=p("/list-accounts",{method:"GET",use:[R],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})))}),xi=p("/link-social",{method:"POST",requireHeaders:!0,query:xe.z.object({currentURL:xe.z.string().optional()}).optional(),body:xe.z.object({callbackURL:xe.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:xe.z.enum(mo,{description:"The OAuth2 provider to use"})}),use:[R],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 qo.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 qo.APIError("NOT_FOUND",{message:g.PROVIDER_NOT_FOUND});let n=await Pe(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 Ot=(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 yo(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 Qr={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},Ho=yo(Qr),Wr=Ho.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),Jr=Ho.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),Yr=Ho.newRole({organization:[],member:[],invitation:[]}),Tt={admin:Wr,owner:Jr,member:Yr};var Xr={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},en=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,Et={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},on=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function tn(e){return e instanceof Date&&!isNaN(e.getTime())}function rn(e){let i=on.exec(e);if(!i)return null;let[,t,o,r,n,s,A,a,d,c,l]=i,u=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(l,10))*(d==="+"?-1:1);u.setUTCMinutes(u.getUTCMinutes()+K)}return tn(u)?u:null}function nn(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 Et)return Et[A];if(!en.test(s)){if(t)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(Xr).some(([d,c])=>{let l=c.test(s);return l&&o&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${d} pattern`),l})&&t)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(s,(c,l)=>{if(c==="__proto__"||c==="constructor"&&l&&typeof l=="object"&&"prototype"in l){o&&console.warn(`[better-json] Dropping "${c}" key to prevent prototype pollution`);return}if(n&&typeof l=="string"){let u=rn(l);if(u)return u}return r?r(c,l):l})}catch(d){if(t)throw d;return e}}function Rt(e,i={strict:!0}){return nn(e,i)}var It=Rt;var j=(e,i)=>{let t=e.adapter;return{findOrganizationBySlug:async o=>await t.findOne({model:"organization",where:[{field:"slug",value:o}]}),createOrganization:async o=>{let r=await t.create({model:"organization",data:{...o.organization,metadata:o.organization.metadata?JSON.stringify(o.organization.metadata):void 0}}),n=await t.create({model:"member",data:{organizationId:r.id,userId:o.user.id,createdAt:new Date,role:i?.creatorRole||"owner"}});return{...r,metadata:r.metadata?JSON.parse(r.metadata):void 0,members:[{...n,user:{id:o.user.id,name:o.user.name,email:o.user.email,image:o.user.image}}]}},findMemberByEmail:async o=>{let r=await t.findOne({model:"user",where:[{field:"email",value:o.email}]});if(!r)return null;let n=await t.findOne({model:"member",where:[{field:"organizationId",value:o.organizationId},{field:"userId",value:r.id}]});return n?{...n,user:{id:r.id,name:r.name,email:r.email,image:r.image}}:null},findMemberByOrgId:async o=>{let[r,n]=await Promise.all([await t.findOne({model:"member",where:[{field:"userId",value:o.userId},{field:"organizationId",value:o.organizationId}]}),await t.findOne({model:"user",where:[{field:"id",value:o.userId}]})]);return!n||!r?null:{...r,user:{id:n.id,name:n.name,email:n.email,image:n.image}}},findMemberById:async o=>{let r=await t.findOne({model:"member",where:[{field:"id",value:o}]});if(!r)return null;let n=await t.findOne({model:"user",where:[{field:"id",value:r.userId}]});return n?{...r,user:{id:n.id,name:n.name,email:n.email,image:n.image}}:null},createMember:async o=>await t.create({model:"member",data:o}),updateMember:async(o,r)=>await t.update({model:"member",where:[{field:"id",value:o}],update:{role:r}}),deleteMember:async o=>await t.delete({model:"member",where:[{field:"id",value:o}]}),updateOrganization:async(o,r)=>{let n=await t.update({model:"organization",where:[{field:"id",value:o}],update:{...r,metadata:typeof r.metadata=="object"?JSON.stringify(r.metadata):r.metadata}});return n?{...n,metadata:n.metadata?It(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(u=>u.userId),d=await t.findMany({model:"user",where:[{field:"id",value:a,operator:"in"}]}),c=new Map(d.map(u=>[u.id,u])),l=A.map(u=>{let K=c.get(u.userId);if(!K)throw new te("Unexpected error: User not found for member");return{...u,user:{id:K.id,name:K.name,email:K.email,image:K.image}}});return{...n,invitations:s,members:l}},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=k(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 Ac=require("better-call");var M=P(async e=>({})),J=P({use:[R]},async e=>({session:e.context.session}));var ee=require("zod");var D=require("zod");var St=D.z.string(),sn=D.z.enum(["pending","accepted","rejected","canceled"]).default("pending"),lc=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()}),gc=D.z.object({id:D.z.string().default(G),organizationId:D.z.string(),userId:D.z.string(),role:St,createdAt:D.z.date()}),mc=D.z.object({id:D.z.string().default(G),organizationId:D.z.string(),email:D.z.string(),role:St,status:sn,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 Ut=e=>p("/organization/invite-member",{method:"POST",use:[M,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=j(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}),l=await r.findOrganizationById(o);if(!l)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:l,inviter:{...n,user:t.user}},i.request),i.json(c)}),_t=p("/organization/accept-invitation",{method:"POST",body:ee.z.object({invitationId:ee.z.string({description:"The ID of the invitation to accept"})}),use:[M,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=j(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}})}),vt=p("/organization/reject-invitation",{method:"POST",body:ee.z.object({invitationId:ee.z.string({description:"The ID of the invitation to reject"})}),use:[M,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=j(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})}),kt=p("/organization/cancel-invitation",{method:"POST",body:ee.z.object({invitationId:ee.z.string({description:"The ID of the invitation to cancel"})}),use:[M,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=j(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)}),Pt=p("/organization/get-invitation",{method:"GET",use:[M],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=j(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 Nt=()=>p("/organization/add-member",{method:"POST",body:ae.z.object({userId:ae.z.string(),role:ae.z.string(),organizationId:ae.z.string().optional()}),use:[M],metadata:{SERVER_ONLY:!0}},async e=>{let i=e.body.userId?await S(e).catch(A=>null):null,t=e.body.organizationId||i?.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:y.NO_ACTIVE_ORGANIZATION}});let o=j(e.context,e.context.orgOptions),r=await e.context.internalAdapter.findUserById(e.body.userId);if(!r)throw new 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)}),Dt=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:[M,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=j(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})}),Lt=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:[M,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=j(i.context,i.context.orgOptions),n=await r.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!n)return i.json(null,{status:400,body:{message:y.MEMBER_NOT_FOUND}});let s=i.context.roles[n.role];if(!s)return i.json(null,{status:400,body:{message:y.ROLE_NOT_FOUND}});if(s.authorize({member:["update"]}).error||i.body.role==="owner"&&n.role!=="owner")return i.json(null,{body:{message:"You are not allowed to update this member"},status:403});let a=await r.updateMember(i.body.memberId,i.body.role);return a?i.json(a):i.json(null,{status:400,body:{message:y.MEMBER_NOT_FOUND}})}),Bt=p("/organization/get-active-member",{method:"GET",use:[M,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 j(e.context,e.context.orgOptions).findMemberByOrgId({userId:i.user.id,organizationId:t});return r?e.json(r):e.json(null,{status:400,body:{message:y.MEMBER_NOT_FOUND}})});var _=require("zod");var ue=require("better-call");var xt=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:[M],metadata:{openapi:{description:"Create an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization that was created",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let i=await S(e);if(!i&&(e.request||e.headers))throw new ue.APIError("UNAUTHORIZED");let t=i?.user||null;if(!t){if(!e.body.userId)throw new ue.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 ue.APIError("FORBIDDEN",{message:y.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION});let n=j(e.context,o),s=await n.listOrganizations(t.id);if(typeof o.organizationLimit=="number"?s.length>=o.organizationLimit:typeof o.organizationLimit=="function"?await o.organizationLimit(t):!1)throw new ue.APIError("FORBIDDEN",{message:y.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS});if(await n.findOrganizationBySlug(e.body.slug))throw new ue.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)}),jt=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:[M],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 ue.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=j(e.context,e.context.orgOptions),r=await o.findMemberByOrgId({userId:i.user.id,organizationId:t});if(!r)return e.json(null,{status:400,body:{message:y.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION}});let n=e.context.roles[r.role];if(!n)return e.json(null,{status:400,body:{message:"Role not found!"}});if(n.authorize({organization:["update"]}).error)return e.json(null,{body:{message:y.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION},status:403});let A=await o.updateOrganization(t,e.body.data);return e.json(A)}),zt=p("/organization/delete",{method:"POST",body:_.z.object({organizationId:_.z.string({description:"The organization id to delete"})}),requireHeaders:!0,use:[M],metadata:{openapi:{description:"Delete an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string",description:"The organization id that was deleted"}}}}}}}},async e=>{let i=await e.context.getSession(e);if(!i)return e.json(null,{status:401});let t=e.body.organizationId;if(!t)return e.json(null,{status:400,body:{message:y.ORGANIZATION_NOT_FOUND}});let o=j(e.context,e.context.orgOptions),r=await o.findMemberByOrgId({userId:i.user.id,organizationId:t});if(!r)return e.json(null,{status:400,body:{message:y.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION}});let n=e.context.roles[r.role];if(!n)return e.json(null,{status:400,body:{message:"Role not found!"}});if(n.authorize({organization:["delete"]}).error)throw new ue.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)}),Ft=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:[M,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 j(e.context,e.context.orgOptions).findFullOrganization({organizationId:t,isSlug:!!e.query?.organizationSlug});if(!r)throw new ue.APIError("BAD_REQUEST",{message:y.ORGANIZATION_NOT_FOUND});return e.json(r)}),Vt=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,M],metadata:{openapi:{description:"Set the active organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let i=j(e.context,e.context.orgOptions),t=e.context.session,o=e.body.organizationSlug||e.body.organizationId;if(o===null){if(!t.session.activeOrganizationId)return e.json(null);let a=await i.setActiveOrganization(t.session.token,null);return await h(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 ue.APIError("FORBIDDEN",{message:y.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION});let s=await i.setActiveOrganization(t.session.token,o);return await h(e,{session:s,user:t.user}),e.json(r)}),Mt=p("/organization/list",{method:"GET",use:[M,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 j(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(t)});var an=yo({name:["action"]}),Yc=an.newRole({name:["action"]}),An=e=>{let i={createOrganization:xt,updateOrganization:jt,deleteOrganization:zt,setActiveOrganization:Vt,getFullOrganization:Ft,listOrganizations:Mt,createInvitation:Ut(e),cancelInvitation:kt,acceptInvitation:_t,getInvitation:Pt,rejectInvitation:vt,addMember:Nt(),removeMember:Dt,updateMemberRole:Lt(e),getActiveMember:Bt},t={...Tt,...e?.roles};return{id:"organization",endpoints:{...Ot(i,{orgOptions:e||{},roles:t,getSession:async r=>await S(r)}),hasPermission:p("/organization/has-permission",{method:"POST",requireHeaders:!0,body:je.z.object({permission:je.z.record(je.z.string(),je.z.array(je.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 $o.APIError("BAD_REQUEST",{message:y.NO_ACTIVE_ORGANIZATION});let s=await j(r.context).findMemberByOrgId({userId:r.context.session.user.id,organizationId:r.context.session.session.activeOrganizationId||""});if(!s)throw new $o.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 eo=require("zod");var le=require("zod");var ze=require("better-call");var wo="two_factor";var Co="trust_device";var Go=require("zod");var Ie=P({body:Go.z.object({trustDevice:Go.z.boolean().optional()})},async e=>{let i=await S(e);if(!i){let t=e.context.createAuthCookie(wo),o=await e.getSignedCookie(t.name,e.context.secret);if(!o)throw new ze.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let r=await e.context.internalAdapter.findUserById(o);if(!r)throw new ze.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let n=await e.context.internalAdapter.createSession(o,e.request);if(!n)throw new ze.APIError("INTERNAL_SERVER_ERROR",{message:"failed to create session"});return{valid:async()=>{if(await h(e,{session:n,user:r}),e.body.trustDevice){let s=e.context.createAuthCookie(Co,{maxAge:2592e3}),A=await Je(e.context.secret,`${r.id}!${n.token}`);await e.setSignedCookie(s.name,`${A}!${n.token}`,e.context.secret,s.attributes)}return e.json({session:n,user:r})},invalid:async()=>{throw new ze.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 ze.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:i}});var Fe=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 dn(e){return Array.from({length:e?.amount??10}).fill(null).map(()=>z(e?.length??10,F("a-z","0-9"))).map(i=>`${i.slice(0,5)}-${i.slice(5)}`)}async function Zo(e,i){let t=e,o=i?.customBackupCodesGenerate?i.customBackupCodesGenerate():dn(),r=await he({data:JSON.stringify(o),key:t});return{backupCodes:o,encryptedBackupCodes:r}}async function cn(e,i){let t=await qt(e.backupCodes,i);return t?{status:t.includes(e.code),updated:t.filter(o=>o!==e.code)}:{status:!1,updated:null}}async function qt(e,i){let t=Buffer.from(await Ce({key:i,data:e})).toString("utf-8"),o=JSON.parse(t),r=le.z.array(le.z.string()).safeParse(o);return r.success?r.data:null}var Ht=(e,i)=>({id:"backup_code",endpoints:{verifyBackupCode:p("/two-factor/verify-backup-code",{method:"POST",body:le.z.object({code:le.z.string(),disableSession:le.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 Fe.APIError("BAD_REQUEST",{message:Y.BACKUP_CODES_NOT_ENABLED});let n=await cn({backupCodes:r.backupCodes,code:t.body.code},t.context.secret);if(!n.status)throw new Fe.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 h(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:le.z.object({password:le.z.string()}),use:[R]},async t=>{let o=t.context.session.user;if(!o.twoFactorEnabled)throw new Fe.APIError("BAD_REQUEST",{message:Y.TWO_FACTOR_NOT_ENABLED});await t.context.password.checkPassword(o.id,t);let r=await Zo(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:le.z.object({userId:le.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 Fe.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let r=await qt(o.backupCodes,t.context.secret);if(!r)throw new Fe.APIError("BAD_REQUEST",{message:Y.BACKUP_CODES_NOT_ENABLED});return t.json({status:!0,backupCodes:r})})}});var Ve=require("better-call"),Qo=require("zod");var $t=require("oslo");var Gt=(e,i)=>{let t={...e,digits:e?.digits||6,period:new $t.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 Ve.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 Ve.APIError("BAD_REQUEST",{message:Y.OTP_NOT_ENABLED});let a=z(t.digits,F("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:Qo.z.object({code:Qo.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 Ve.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 Ve.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 Ve.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"),Zt=require("oslo"),Xe=require("oslo/otp"),Ye=require("zod");var Qt=(e,i)=>{let t={...e,digits:e?.digits||6,period:new Zt.TimeSpan(e?.period||30,"s")},o=p("/totp/generate",{method:"POST",use:[R],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 Xe.TOTPController(t).generate(Buffer.from(a.secret))}}),r=p("/two-factor/get-totp-uri",{method:"POST",use:[R],body:Ye.z.object({password:Ye.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,Xe.createTOTPKeyURI)(e.issuer||s.context.appName,A.email,Buffer.from(a.secret),t)}}),n=p("/two-factor/verify-totp",{method:"POST",body:Ye.z.object({code:Ye.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 Xe.TOTPController(t),c=await Ce({key:s.context.secret,data:a.secret}),l=Buffer.from(c);if(!await d.verify(s.body.code,l))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(E=>{throw console.log(E),E});await s.context.internalAdapter.deleteSession(s.context.session.session.token),await h(s,{session:m,user:K})}return s.context.valid()});return{id:"totp",endpoints:{generateTOTP:o,getTOTPURI:r,verifyTOTP:n}}};var pn=require("better-call");async function Wo(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 Jo=require("better-call"),Xt=require("oslo/otp"),er=require("oslo");var Wt=require("better-call"),Jt=async e=>{let i=e.context.returned;return i?i instanceof Response?i.status!==200?null:await i.clone().json():i instanceof Wt.APIError?null:i:null};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 Kn=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 un=e=>{let i={twoFactorTable:"twoFactor"},t=Qt({issuer:e?.issuer,...e?.totpOptions},i.twoFactorTable),o=Ht({...e?.backupCodeOptions},i.twoFactorTable),r=Gt({...e?.otpOptions},i.twoFactorTable);return{id:"two-factor",endpoints:{...t.endpoints,...r.endpoints,...o.endpoints,enableTwoFactor:p("/two-factor/enable",{method:"POST",body:eo.z.object({password:eo.z.string({description:"User password"}).min(8)}),use:[R],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 Wo(n,{password:A,userId:s.id}))throw new Jo.APIError("BAD_REQUEST",{message:g.INVALID_PASSWORD});let d=z(16,F("a-z","0-9","-")),c=await he({key:n.context.secret,data:d}),l=await Zo(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 h(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:l.encryptedBackupCodes,userId:s.id}});let u=(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:u,backupCodes:l.backupCodes})}),disableTwoFactor:p("/two-factor/disable",{method:"POST",body:eo.z.object({password:eo.z.string({description:"User password"}).min(8)}),use:[R],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 Wo(n,{password:A,userId:s.id}))throw new Jo.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 h(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:P(async n=>{let s=n.context.newSession;if(!s||!s?.user.twoFactorEnabled)return;let A=n.context.createAuthCookie(Co),a=await n.getSignedCookie(A.name,n.context.secret);if(a){let[c,l]=a.split("!"),u=await Je(n.context.secret,`${s.user.id}!${l}`);if(c===u){let K=await Je(n.context.secret,`${s.user.id}!${s.session.token}`);await n.setSignedCookie(A.name,`${K}!${s.session.token}`,n.context.secret,A.attributes);return}}$(n),await n.context.internalAdapter.deleteSession(s.session.token);let d=n.context.createAuthCookie(wo,{maxAge:60*10});return await n.setSignedCookie(d.name,s.user.id,n.context.secret,d.attributes),n.json({twoFactorRedirect:!0})})}]},schema:ne(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 ie=require("zod");var Me=require("@simplewebauthn/browser");var gn=require("@better-fetch/fetch");var cK=require("nanostores");var Yp=require("@better-fetch/fetch");var ln=require("nanostores");var eK=require("@better-fetch/fetch"),bo=require("nanostores"),Yo=(e,i,t,o)=>{let r=(0,bo.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,bo.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,Me.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,Me.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 Me.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:{}}),mn=()=>{let e=(0,or.atom)();return{id:"passkey",$InferServerPlugin:{},getActions:i=>ir(i,{$listPasskeys:e}),getAtoms(i){return{listPasskeys:Yo(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 fn=e=>{let i=de.BETTER_AUTH_URL,t=e?.rpID||i?.replace("http://","").replace("https://","").split(":")[0]||"localhost";if(!t)throw new te("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:[Qe],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}]}),l=new Uint8Array(Buffer.from(z(32,F("a-z","0-9")))),u;u=await(0,Oe.generateRegistrationOptions)({rpName:o.rpName||a.context.appName,rpID:o.rpID,userID:l,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:u.challenge,userData:{id:d.user.id}}),expiresAt:r}),a.json(u,{status:200})}),generatePasskeyAuthenticationOptions:p("/passkey/generate-authenticate-options",{method:"POST",body:ie.z.object({email:ie.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 l=await(0,Oe.generateAuthenticationOptions)({rpID:o.rpID,userVerification:"preferred",...c.length?{allowCredentials:c.map(m=>({id:m.id,transports:m.transports?.split(",")}))}:{}}),u={expectedChallenge:l.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(u),expiresAt:r}),a.json(l,{status:200})}),verifyPasskeyRegistration:p("/passkey/verify-registration",{method:"POST",body:ie.z.object({response:ie.z.any({description:"The response from the authenticator"}),name:ie.z.string({description:"Name of the passkey"}).optional()}),use:[Qe],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,l=await a.getSignedCookie(o.advanced.webAuthnChallengeCookie,a.context.secret);if(!l)throw new X.APIError("BAD_REQUEST",{message:A.CHALLENGE_NOT_FOUND});let u=await a.context.internalAdapter.findVerificationValue(l);if(!u)return a.json(null,{status:400});let{expectedChallenge:K,userData:m}=JSON.parse(u.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 E=await(0,Oe.verifyRegistrationResponse)({response:c,expectedChallenge:K,expectedOrigin:d,expectedRPID:e?.rpID}),{verified:v,registrationInfo:f}=E;if(!v||!f)return a.json(null,{status:400});let{credentialID:w,credentialPublicKey:O,counter:I,credentialDeviceType:q,credentialBackedUp:no}=f,lr=Buffer.from(O).toString("base64"),gr={name:a.body.name,userId:m.id,webauthnUserID:a.context.generateId({model:"passkey"}),id:w,publicKey:lr,counter:I,deviceType:q,transports:c.response.transports.join(","),backedUp:no,createdAt:new Date},mr=await a.context.adapter.create({model:"passkey",data:gr});return a.json(mr,{status:200})}catch(E){throw console.log(E),new X.APIError("INTERNAL_SERVER_ERROR",{message:A.FAILED_TO_VERIFY_REGISTRATION})}}),verifyPasskeyAuthentication:p("/passkey/verify-authentication",{method:"POST",body:ie.z.object({response:ie.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,l=await a.getSignedCookie(o.advanced.webAuthnChallengeCookie,a.context.secret);if(!l)throw new X.APIError("BAD_REQUEST",{message:A.CHALLENGE_NOT_FOUND});let u=await a.context.internalAdapter.findVerificationValue(l);if(!u)throw new X.APIError("BAD_REQUEST",{message:A.CHALLENGE_NOT_FOUND});let{expectedChallenge:K}=JSON.parse(u.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 E=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:v}=E;if(!v)throw new X.APIError("UNAUTHORIZED",{message:A.AUTHENTICATION_FAILED});await a.context.adapter.update({model:"passkey",where:[{field:"id",value:m.id}],update:{counter:E.authenticationInfo.newCounter}});let f=await a.context.internalAdapter.createSession(m.userId,a.request);if(!f)throw new X.APIError("INTERNAL_SERVER_ERROR",{message:A.UNABLE_TO_CREATE_SESSION});let w=await a.context.internalAdapter.findUserById(m.userId);if(!w)throw new X.APIError("INTERNAL_SERVER_ERROR",{message:"User not found"});return await h(a,{session:f,user:w}),a.json({session:f},{status:200})}catch(E){throw a.context.logger.error("Failed to verify authentication",E),new X.APIError("BAD_REQUEST",{message:A.AUTHENTICATION_FAILED})}}),listPasskeys:p("/passkey/list-user-passkeys",{method:"GET",use:[R]},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:ie.z.object({id:ie.z.string()}),use:[R]},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:ie.z.object({id:ie.z.string(),name:ie.z.string()}),use:[R]},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:ne(hn,e?.schema),$ERROR_CODES:A}},hn={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 oo=require("zod");var qe=require("better-call");var Xo=()=>{let e={INVALID_USERNAME_OR_PASSWORD:"invalid username or password",EMAIL_NOT_VERIFIED:"email not verified",UNEXPECTED_ERROR:"unexpected error"};return{id:"username",endpoints:{signInUsername:p("/sign-in/username",{method:"POST",body:oo.z.object({username:oo.z.string({description:"The username of the user"}),password:oo.z.string({description:"The password of the user"}),rememberMe:oo.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:Xo}),new qe.APIError("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});if(!t.emailVerified&&i.context.options.emailAndPassword?.requireEmailVerification)throw await Po(i,t),new qe.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 qe.APIError("UNAUTHORIZED",{message:e.INVALID_USERNAME_OR_PASSWORD});let r=o?.password;if(!r)throw i.context.logger.error("Password not found",{username:Xo}),new qe.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 qe.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 h(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}}}},$ERROR_CODES:Y}};var tr=require("better-call"),yn=()=>({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)return;let t="";return i.includes(".")?t=i:t=await(0,tr.serializeSigned)("",i,e.context.secret),e.request&&e.request.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${t.replace("=","")}`),e.headers&&e.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${t.replace("=","")}`),{context:e}}}]}});var Ue=require("zod");var rr=require("better-call");var wn=e=>({id:"magic-link",endpoints:{signInMagicLink:p("/sign-in/magic-link",{method:"POST",requireHeaders:!0,body:Ue.z.object({email:Ue.z.string({description:"Email address to send the magic link"}).email(),callbackURL:Ue.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 rr.APIError("BAD_REQUEST",{message:g.USER_NOT_FOUND});let o=z(32,F("a-z","A-Z"));await i.context.internalAdapter.createVerificationValue({identifier:o,value:t,expiresAt:new Date(Date.now()+(e.expiresIn||60*5)*1e3)});let r=`${i.context.baseURL}/magic-link/verify?token=${o}&callbackURL=${i.body.callbackURL||"/"}`;return await e.sendMagicLink({email:t,url:r,token:o},i.request),i.json({status:!0})}),magicLinkVerify:p("/magic-link/verify",{method:"GET",query:Ue.z.object({token:Ue.z.string({description:"Verification token"}),callbackURL:Ue.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 h(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 Q=require("better-call");function Cn(e){return z(e,F("0-9"))}var bn=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 Q.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 Q.APIError("UNAUTHORIZED",{message:t.INVALID_PHONE_NUMBER_OR_PASSWORD});let a=(await o.context.internalAdapter.findAccountByUserId(s.id)).find(u=>u.providerId==="credential");if(!a)throw o.context.logger.error("Credential account not found",{phoneNumber:n}),new Q.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 Q.APIError("UNAUTHORIZED",{message:t.UNEXPECTED_ERROR});if(!await o.context.password.verify({hash:d,password:r}))throw o.context.logger.error("Invalid password"),new Q.APIError("UNAUTHORIZED",{message:t.INVALID_PHONE_NUMBER_OR_PASSWORD});let l=await o.context.internalAdapter.createSession(s.id,o.headers,o.body.rememberMe===!1);if(!l)throw o.context.logger.error("Failed to create session"),new Q.APIError("UNAUTHORIZED",{message:g.FAILED_TO_CREATE_SESSION});return await h(o,{session:l,user:s},o.body.rememberMe===!1),o.json({user:s,session:l})}),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 Q.APIError("NOT_IMPLEMENTED",{message:"sendOTP not implemented"});if(i.phoneNumberValidator&&!await i.phoneNumberValidator(o.body.phoneNumber))throw new Q.APIError("BAD_REQUEST",{message:t.INVALID_PHONE_NUMBER});let r=Cn(i.otpLength);return await o.context.internalAdapter.createVerificationValue({value:r,identifier:o.body.phoneNumber,expiresAt:k(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 Q.APIError("BAD_REQUEST",{message:"OTP expired"})):new Q.APIError("BAD_REQUEST",{message:t.OTP_NOT_FOUND});if(r.value!==o.body.code)throw new Q.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 Q.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 Q.APIError("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_CREATE_USER})}else return o.json(null);if(!n)throw new Q.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 Q.APIError("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_CREATE_SESSION});return await h(o,{session:s,user:n}),o.json({user:n,session:s})}return o.json({user:n,session:null})})},schema:ne(On,e?.schema),$ERROR_CODES:t}},On={user:{fields:{phoneNumber:{type:"string",required:!1,unique:!0,returned:!0},phoneNumberVerified:{type:"boolean",required:!1,returned:!0,input:!1}}}};var Tn={user:{fields:{isAnonymous:{type:"boolean",required:!1}}}},En=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=ve(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 h(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:P(async t=>{let r=t.responseHeader.get("set-cookie"),n=t.context.authCookies.sessionToken.name;if(!uo(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 T.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:ne(Tn,e?.schema),$ERROR_CODES:i}};var C=require("zod");var Rn=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=P(async r=>{let n=await S(r);if(!n?.session)throw new T.APIError("UNAUTHORIZED");let s=n.user;if(!s.role||(Array.isArray(i.adminRole)?!i.adminRole.includes(s.role):s.role!==i.adminRole))throw new T.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:P(async r=>{let n=await Jt(r);if(!n)return;let s=n.filter(A=>!A.impersonatedBy);return r.json(s)})}]},endpoints:{setRole:p("/admin/set-role",{method:"POST",body:C.z.object({userId:C.z.string({description:"The user id"}),role:C.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:C.z.object({email:C.z.string({description:"The email of the user"}),password:C.z.string({description:"The password of the user"}),name:C.z.string({description:"The name of the user"}),role:C.z.string({description:"The role of the user"}),data:C.z.optional(C.z.record(C.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 T.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 T.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:C.z.object({searchValue:C.z.string({description:"The value to search for"}).optional(),searchField:C.z.enum(["email","name"],{description:"The field to search in, defaults to email. Can be `email` or `name`"}).optional(),searchOperator:C.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:C.z.string({description:"The number of users to return"}).or(C.z.number()).optional(),offset:C.z.string({description:"The offset to start from"}).or(C.z.number()).optional(),sortBy:C.z.string({description:"The field to sort by"}).optional(),sortDirection:C.z.enum(["asc","desc"],{description:"The direction to sort by"}).optional(),filterField:C.z.string({description:"The field to filter by"}).optional(),filterValue:C.z.string({description:"The value to filter by"}).or(C.z.number()).or(C.z.boolean()).optional(),filterOperator:C.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:C.z.object({userId:C.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:C.z.object({userId:C.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:C.z.object({userId:C.z.string({description:"The user id"}),banReason:C.z.string({description:"The reason for the ban"}).optional(),banExpiresIn:C.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 T.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?k(r.body.banExpiresIn,"sec"):e?.defaultBanExpiresIn?k(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:C.z.object({userId:C.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 T.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?k(e.impersonationSessionDuration,"sec"):k(60*60,"sec")});if(!s)throw new T.APIError("INTERNAL_SERVER_ERROR",{message:t.FAILED_TO_CREATE_USER});return await h(r,{session:s,user:n},!0),r.json({session:s,user:n})}),revokeUserSession:p("/admin/revoke-user-session",{method:"POST",body:C.z.object({sessionToken:C.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:C.z.object({userId:C.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:C.z.object({userId:C.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:ne(In,i.schema)}},In={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 io=require("@better-fetch/fetch"),_e=require("better-call"),sr=require("oslo/jwt"),ce=require("zod");async function nr(e,i){if(e.idToken){let o=(0,sr.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,io.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 Sn=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 N({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,io.betterFetch)(o.discoveryUrl,{method:"GET"});a.data&&(A=a.data.token_endpoint,n=a.data.userinfo_endpoint)}if(!A)throw new _e.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 nr(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(q=>q.providerId===o);if(!r)throw new _e.APIError("BAD_REQUEST",{message:`No config found for provider ${o}`});let{discoveryUrl:n,authorizationUrl:s,tokenUrl:A,clientId:a,clientSecret:d,scopes:c,redirectURI:l,responseType:u,pkce:K,prompt:m,accessType:E}=r,v=s,f=A;if(n){let q=await(0,io.betterFetch)(n,{onError(no){t.context.logger.error(no.error.message,no.error,{discoveryUrl:n})}});q.data&&(v=q.data.authorization_endpoint,f=q.data.token_endpoint)}if(!v||!f)throw new _e.APIError("BAD_REQUEST",{message:i.INVALID_OAUTH_CONFIGURATION});let{state:w,codeVerifier:O}=await Pe(t),I=await N({id:o,options:{clientId:a,clientSecret:d,redirectURI:l},authorizationEndpoint:v,state:w,codeVerifier:K?O:void 0,scopes:c||[],redirectURI:`${t.context.baseURL}/oauth2/callback/${o}`});return u&&u!=="code"&&I.searchParams.set("response_type",u),m&&I.searchParams.set("prompt",m),E&&I.searchParams.set("access_type",E),t.json({url:I.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(O=>O.providerId===t.params.providerId);if(!o)throw new _e.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,l=o.userInfoUrl;if(o.discoveryUrl){let O=await(0,io.betterFetch)(o.discoveryUrl,{method:"GET"});O.data&&(c=O.data.token_endpoint,l=O.data.userinfo_endpoint)}try{if(!c)throw new _e.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(O){throw t.context.logger.error(O&&typeof O=="object"&&"name"in O?O.name:"",O),t.redirect(`${a}?error=oauth_code_verification_failed`)}if(!r)throw new _e.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let u=o.getUserInfo?await o.getUserInfo(r):await nr(r,l);if(!u?.email)throw t.context.logger.error("Unable to get user info",u),t.redirect(`${t.context.baseURL}/error?error=email_is_missing`);let K=o.mapProfileToUser?await o.mapProfileToUser(u):null,m=await De(t,{userInfo:{...u,...K},account:{providerId:o.providerId,accountId:u.id,...r,scope:r.scopes?.join(",")}});function E(O){throw t.redirect(`${a||s||`${t.context.baseURL}/error`}?error=${O}`)}if(m.error)return E(m.error.split(" ").join("_"));let{session:v,user:f}=m.data;await h(t,{session:v,user:f});let w;try{w=new URL(s).toString()}catch{w=s}throw t.redirect(w)})},$ERROR_CODES:i}};var He=require("zod"),ar={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0}}}},Eu=He.z.object({id:He.z.string(),publicKey:He.z.string(),privateKey:He.z.string(),createdAt:He.z.date()});var ei=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 Un=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 ei(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:[R],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=ei(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"}),l=await(0,ye.exportJWK)(d),u=await(0,ye.exportJWK)(c),K=JSON.stringify(u),m={id:crypto.randomUUID(),publicKey:JSON.stringify(l),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:ne(ar,e?.schema)});var to=require("zod");var _n=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(We(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:to.z.object({sessionToken:to.z.string({description:"The session token to set as active"})}),requireHeaders:!0,use:[R],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 T.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 T.APIError("UNAUTHORIZED",{message:o.INVALID_SESSION_TOKEN});return await h(r,a),r.json(a)}),revokeDeviceSession:p("/multi-session/revoke",{method:"POST",body:to.z.object({sessionToken:to.z.string({description:"The session token to revoke"})}),requireHeaders:!0,use:[R],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 T.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(We(d)),l=(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),u=r.context.internalAdapter;if(l.length>0){let m=(await u.findSessions(l)).filter(E=>E&&E.session.expiresAt>new Date);if(m.length>0){let E=m[0];await h(r,E)}else $(r)}else $(r)}else $(r);return r.json({success:!0})})},hooks:{after:[{matcher:()=>!0,handler:P(async r=>{let n=r.responseHeader.get("set-cookie");if(!n)return;let s=uo(n),A=r.context.authCookies.sessionToken,a=s.get(A.name)?.value;if(!a)return;let d=We(r.headers?.get("cookie")||""),c=a.split(".")[0];if(!c)return;let l=`${A.name}_multi-${c}`;s.get(l)||d.get(l)||Object.keys(Object.fromEntries(d)).filter(t).length+(n.includes("session_token")?1:0)>i.maximumSessions||await r.setSignedCookie(l,c,r.context.secret,A.options)})},{matcher:r=>r.path==="/sign-out",handler:P(async r=>{let n=r.headers?.get("cookie");if(!n)return;let s=Object.fromEntries(We(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 L=require("zod");var oi=["email-verification","sign-in","forget-password"],vn=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:L.z.object({email:L.z.string({description:"Email address to send the OTP"}),type:L.z.enum(oi,{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 T.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 T.APIError("BAD_REQUEST",{message:t.INVALID_EMAIL});let s=z(i.otpLength,F("0-9"));return await o.context.internalAdapter.createVerificationValue({value:s,identifier:`${o.body.type}-otp-${r}`,expiresAt:k(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:k(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:L.z.object({email:L.z.string({description:"Email address to send the OTP"}),type:L.z.enum(oi,{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=z(i.otpLength,F("0-9"));return await o.context.internalAdapter.createVerificationValue({value:n,identifier:`${o.body.type}-otp-${r}`,expiresAt:k(i.expireIn,"sec")}),n}),getVerificationOTP:p("/email-otp/get-verification-otp",{method:"GET",query:L.z.object({email:L.z.string({description:"Email address to get the OTP"}),type:L.z.enum(oi)}),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:L.z.object({email:L.z.string({description:"Email address to verify"}),otp:L.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 T.APIError("BAD_REQUEST",{message:"Invalid email"});let s=await o.context.internalAdapter.findVerificationValue(`email-verification-otp-${r}`);if(!s||s.expiresAt<new Date)throw s&&await o.context.internalAdapter.deleteVerificationValue(s.id),new T.APIError("BAD_REQUEST",{message:"Invalid OTP"});let A=o.body.otp;if(s.value!==A)throw new T.APIError("BAD_REQUEST",{message:"Invalid OTP"});await o.context.internalAdapter.deleteVerificationValue(s.id);let a=await o.context.internalAdapter.findUserByEmail(r);if(!a)throw new T.APIError("BAD_REQUEST",{message:"User not found"});let d=await o.context.internalAdapter.updateUser(a.user.id,{email:r,emailVerified:!0});return o.json({user:d})}),signInEmailOTP:p("/sign-in/email-otp",{method:"POST",body:L.z.object({email:L.z.string({description:"Email address to sign in"}),otp:L.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||n.expiresAt<new Date)throw n&&await o.context.internalAdapter.deleteVerificationValue(n.id),new T.APIError("BAD_REQUEST",{message:"Invalid OTP"});let s=o.body.otp;if(n.value!==s)throw new T.APIError("BAD_REQUEST",{message:"Invalid OTP"});await o.context.internalAdapter.deleteVerificationValue(n.id);let A=await o.context.internalAdapter.findUserByEmail(r);if(!A){if(i.disableSignUp)throw new T.APIError("BAD_REQUEST",{message:"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 h(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 h(o,{session:a,user:A.user}),o.json({session:a,user:A})}),forgetPasswordEmailOTP:p("/forget-password/email-otp",{method:"POST",body:L.z.object({email:L.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 T.APIError("BAD_REQUEST",{message:"User not found"});let s=z(i.otpLength,F("0-9"));return await o.context.internalAdapter.createVerificationValue({value:s,identifier:`forget-password-otp-${r}`,expiresAt:k(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:L.z.object({email:L.z.string({description:"Email address to reset the password"}),otp:L.z.string({description:"OTP sent to the email"}),password:L.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 T.APIError("BAD_REQUEST",{message:t.USER_NOT_FOUND});let s=await o.context.internalAdapter.findVerificationValue(`forget-password-otp-${r}`);if(!s||s.expiresAt<new Date)throw s&&await o.context.internalAdapter.deleteVerificationValue(s.id),new T.APIError("BAD_REQUEST",{message:t.OTP_EXPIRED});let A=o.body.otp;if(s.value!==A)throw new T.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=z(i.otpLength,F("0-9"));await o.context.internalAdapter.createVerificationValue({value:n,identifier:`email-verification-otp-${r.user.email}`,expiresAt:k(i.expireIn,"sec")}),await e.sendVerificationOTP({email:r.user.email,otp:n,type:"email-verification"},o.request)}}}]},$ERROR_CODES:t}};var ii=require("zod");var dr=require("@better-fetch/fetch");function Ar(e){return e==="true"||e===!0}var kn=e=>({id:"one-tap",endpoints:{oneTapCallback:p("/one-tap/callback",{method:"POST",body:ii.z.object({idToken:ii.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,dr.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 T.APIError("BAD_GATEWAY",{message:"User not found"});let A=await i.context.internalAdapter.createOAuthUser({email:o.email,emailVerified:Ar(o.email_verified),name:o.name,image:o.picture},{providerId:"google",accountId:o.sub});if(!A)throw new T.APIError("INTERNAL_SERVER_ERROR",{message:"Could not create user"});let a=await i.context.internalAdapter.createSession(A?.user.id,i.request);return await h(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 h(i,{user:n.user,session:s}),i.json({session:s,user:n})})}});var Oo=require("zod");function Pn(){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 Nn=e=>({id:"oauth-proxy",endpoints:{oAuthProxy:p("/oauth-proxy-callback",{method:"GET",query:Oo.z.object({callbackURL:Oo.z.string({description:"The URL to redirect to after the proxy"}),cookies:Oo.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:P(async i=>{let t=i.context.returned,o=t instanceof T.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===ve(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||Pn()||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 $e=require("zod");var Dn=(e,i)=>({id:"custom-session",endpoints:{getSession:p("/get-session",{method:"GET",metadata:{CUSTOM_SESSION:!0},query:$e.z.optional($e.z.object({disableCookieCache:$e.z.boolean({description:"Disable cookie cache and fetch session from database"}).or($e.z.string().transform(t=>t==="true")).optional(),disableRefresh:$e.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 ge=require("zod");var Ge=e=>{let i=e.plugins?.reduce((a,d)=>{let c=d.schema;if(!c)return a;for(let[l,u]of Object.entries(c))a[l]={fields:{...a[l]?.fields,...u.fields},modelName:u.modelName||l};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 Ln=require("zod");var cr=require("kysely"),ti=require("kysely");var ro={};function Kr(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 To(e){let i=[];return e.metadata?.openapi?.parameters?(i.push(...e.metadata.openapi.parameters),i):(e.query instanceof ge.ZodObject&&Object.entries(e.query.shape).forEach(([t,o])=>{o instanceof ge.ZodSchema&&i.push({name:t,in:"query",schema:{type:Kr(o),..."minLength"in o&&o.minLength?{minLength:o.minLength}:{},description:o.description}})}),i)}function pr(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof ge.ZodObject||e.body instanceof ge.ZodOptional)){let i=e.body.shape;if(!i)return;let t={},o=[];return Object.entries(i).forEach(([r,n])=>{n instanceof ge.ZodSchema&&(t[r]={type:Kr(n),description:n.description},n instanceof ge.ZodOptional||o.push(r))}),{required:e.body instanceof ge.ZodOptional?!1:!!e.body,content:{"application/json":{schema:{type:"object",properties:t,required:o}}}}}}function Eo(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 ri(e,i){let t=Do(e,{...i,plugins:[]}),o=Ge(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((l,[u,K])=>(l[u]={type:K.type},l),{})},A},{})}};Object.entries(t.api).forEach(([A,a])=>{let d=a.options;if(!d.metadata?.SERVER_ONLY&&(d.method==="GET"&&(ro[a.path]={get:{tags:["Default",...d.metadata?.openapi?.tags||[]],description:d.metadata?.openapi?.description,operationId:d.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:To(d),responses:Eo(d.metadata?.openapi?.responses)}}),d.method==="POST")){let c=pr(d);ro[a.path]={post:{tags:["Default",...d.metadata?.openapi?.tags||[]],description:d.metadata?.openapi?.description,operationId:d.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:To(d),...c?{requestBody:c}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:Eo(d.metadata?.openapi?.responses)}}}});for(let A of i.plugins||[]){if(A.id==="open-api")continue;let a=Do(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,l])=>{let u=l.options;u.metadata?.SERVER_ONLY||(u.method==="GET"&&(ro[l.path]={get:{tags:u.metadata?.openapi?.tags||[A.id.charAt(0).toUpperCase()+A.id.slice(1)],description:u.metadata?.openapi?.description,operationId:u.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:To(u),responses:Eo(u.metadata?.openapi?.responses)}}),u.method==="POST"&&(ro[l.path]={post:{tags:u.metadata?.openapi?.tags||[A.id.charAt(0).toUpperCase()+A.id.slice(1)],description:u.metadata?.openapi?.description,operationId:u.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:To(u),requestBody:pr(u),responses:Eo(u.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:ro}}var ur=`<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">