better-auth 1.0.8-beta.3 → 1.0.8-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/plugins.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var tr=Object.create;var oo=Object.defineProperty;var rr=Object.getOwnPropertyDescriptor;var nr=Object.getOwnPropertyNames;var sr=Object.getPrototypeOf,ar=Object.prototype.hasOwnProperty;var dr=(e,t)=>{for(var o in t)oo(e,o,{get:t[o],enumerable:!0})},Xo=(e,t,o,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of nr(t))!ar.call(e,r)&&r!==o&&oo(e,r,{get:()=>t[r],enumerable:!(i=rr(t,r))||i.enumerable});return e};var Yo=(e,t,o)=>(o=e!=null?tr(sr(e)):{},Xo(t||!e||!e.__esModule?oo(o,"default",{value:e,enumerable:!0}):o,e)),Ar=e=>Xo(oo({},"__esModule",{value:!0}),e);var wn={};dr(wn,{HIDE_METADATA:()=>we,admin:()=>rn,anonymous:()=>tn,bearer:()=>Wr,createAuthEndpoint:()=>c,createAuthMiddleware:()=>P,customSession:()=>ln,emailOTP:()=>cn,genericOAuth:()=>an,getPasskeyActions:()=>qt,jwt:()=>dn,magicLink:()=>Jr,multiSession:()=>An,oAuthProxy:()=>un,oneTap:()=>Kn,openAPI:()=>yn,optionsMiddleware:()=>bo,organization:()=>xr,passkey:()=>Zr,passkeyClient:()=>$r,phoneNumber:()=>Yr,twoFactor:()=>Mr,twoFactorClient:()=>qr,username:()=>Qo});module.exports=Ar(wn);var xo=require("better-call"),De=require("zod");var ye=require("better-call"),bo=(0,ye.createMiddleware)(async()=>({})),P=(0,ye.createMiddlewareCreator)({use:[bo,(0,ye.createMiddleware)(async()=>({}))]}),c=(0,ye.createEndpointCreator)({use:[bo]});var F=require("better-call"),x=require("zod");var br=require("oslo"),Ri=require("oslo/encoding");var io=require("oslo/crypto");async function Kr({value:e,secret:t}){return new io.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(i=>Buffer.from(i).toString("base64"))}function pr({value:e,signature:t,secret:o}){return new io.HMAC("SHA-256").verify(new TextEncoder().encode(o),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var to={sign:Kr,verify:pr};var ee=class extends Error{constructor(t,o){super(t),this.name="BetterAuthError",this.message=t,this.cause=o,this.stack=""}};var R=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var ro=Object.create(null),qe=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?ro:globalThis),ne=new Proxy(ro,{get(e,t){return qe()[t]??ro[t]},has(e,t){let o=qe();return t in o||t in ro},set(e,t,o){let i=qe(!0);return i[t]=o,!0},deleteProperty(e,t){if(!t)return!1;let o=qe(!0);return delete o[t],!0},ownKeys(){let e=qe(!0);return Object.keys(e)}});function ur(e){return e?e!=="false":!1}var vo=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var ei=vo==="dev"||vo==="development",lr=vo==="test"||ur(ne.TEST);var H=require("better-call");var oi=require("better-call");var gr=P(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:o,context:i}=e,r=e.headers?.get("origin")||e.headers?.get("referer")||"",n=t?.callbackURL||o?.callbackURL,a=t?.redirectTo,s=o?.currentURL,d=i.trustedOrigins,A=e.headers?.has("cookie"),K=(p,l)=>l.includes("*")?new RegExp("^"+l.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(p):p.startsWith(l),u=(p,l)=>{if(!p)return;if(!d.some(k=>K(p,k)||p?.startsWith("/")&&l!=="origin"&&!p.includes(":")))throw e.context.logger.error(`Invalid ${l}: ${p}`),e.context.logger.info(`If it's a valid URL, please add ${p} to trustedOrigins in your auth config
2
- `,`Current list of trustedOrigins: ${d}`),new oi.APIError("FORBIDDEN",{message:`Invalid ${l}`})};A&&!e.context.options.advanced?.disableCSRFCheck&&u(r,"origin"),n&&u(n,"callbackURL"),a&&u(a,"redirectURL"),s&&u(s,"currentURL")});var we={isAction:!1};var ii=c("/ok",{method:"GET",metadata:{...we,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 Ce=require("zod");var ai=require("oslo"),no=require("oslo/jwt"),oe=require("zod");var Oe=require("better-call");var ae=require("better-call");var Te=require("zod");function ko(e){try{return JSON.parse(e)}catch{return null}}var To=()=>c("/get-session",{method:"GET",query:Te.z.optional(Te.z.object({disableCookieCache:Te.z.boolean({description:"Disable cookie cache and fetch session from database"}).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 t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let o=e.getCookie(e.context.authCookies.sessionData.name),i=o?ko(Buffer.from(o,"base64").toString()):null;if(i&&!await to.verify({value:JSON.stringify(i.session),signature:i?.signature,secret:e.context.secret}))return M(e),e.json(null);let r=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(i?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let K=i.session;if(i.expiresAt<Date.now()||K.session.expiresAt<new Date){let p=e.context.authCookies.sessionData.name;e.setCookie(p,"",{maxAge:0})}else return e.json(K)}let n=await e.context.internalAdapter.findSession(t);if(e.context.session=n,!n||n.session.expiresAt<new Date)return M(e),n&&await e.context.internalAdapter.deleteSession(n.session.token),e.json(null);if(r)return e.json(n);let a=e.context.sessionConfig.expiresIn,s=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-a*1e3+s*1e3<=Date.now()){let K=await e.context.internalAdapter.updateSession(n.session.token,{expiresAt:R(e.context.sessionConfig.expiresIn,"sec")});if(!K)return M(e),e.json(null,{status:401});let u=(K.expiresAt.valueOf()-Date.now())/1e3;return await m(e,{session:K,user:n.user},!1,{maxAge:u}),e.json({session:K,user:n.user})}return e.json(n)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new ae.APIError("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),U=async e=>{if(e.context.session)return e.context.session;let t=await To()({...e,_flag:"json",headers:e.headers});return e.context.session=t,t},v=P(async e=>{let t=await U(e);if(!t?.session)throw new ae.APIError("UNAUTHORIZED");return{session:t}}),Me=P(async e=>{let t=await U(e);if(!t?.session)throw new ae.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let o=e.context.sessionConfig.freshAge,i=t.session.createdAt.valueOf(),r=Date.now();if(!(i+o*1e3>r))throw new ae.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),ti=()=>c("/list-sessions",{method:"GET",use:[v],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 o=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(i=>i.expiresAt>new Date);return e.json(o)}),ri=c("/revoke-session",{method:"POST",body:Te.z.object({token:Te.z.string({description:"The token to revoke"})}),use:[v],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 t=e.body.token,o=await e.context.internalAdapter.findSession(t);if(!o)throw new ae.APIError("BAD_REQUEST",{message:"Session not found"});if(o.session.userId!==e.context.session.user.id)throw new ae.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(i){throw e.context.logger.error(i&&typeof i=="object"&&"name"in i?i.name:"",i),new ae.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ni=c("/revoke-sessions",{method:"POST",use:[v],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(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new ae.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),si=c("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[v],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 t=e.context.session;if(!t.user)throw new ae.APIError("UNAUTHORIZED");let r=(await e.context.internalAdapter.listSessions(t.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 Ke(e,t,o){return await(0,no.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:o},{expiresIn:new ai.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Oo(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Oe.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let o=await Ke(e.context.secret,t.email),i=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:i,token:o},e.request)}var di=c("/send-verification-email",{method:"POST",query:oe.z.object({currentURL:oe.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:oe.z.object({email:oe.z.string({description:"The email to send the verification email to"}).email(),callbackURL:oe.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 Oe.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,o=await e.context.internalAdapter.findUserByEmail(t);if(!o)throw new Oe.APIError("BAD_REQUEST",{message:"User not found"});return await Oo(e,o.user),e.json({status:!0})}),Ai=c("/verify-email",{method:"GET",query:oe.z.object({token:oe.z.string({description:"The token to verify the email"}),callbackURL:oe.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 t(s){throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=${s}`):new Oe.APIError("UNAUTHORIZED",{message:s})}let{token:o}=e.query,i;try{i=await(0,no.validateJWT)("HS256",Buffer.from(e.context.secret),o)}catch(s){return e.context.logger.error("Failed to verify email",s),t("invalid_token")}let n=oe.z.object({email:oe.z.string().email(),updateTo:oe.z.string().optional()}).parse(i.payload),a=await e.context.internalAdapter.findUserByEmail(n.email);if(!a)return t("user_not_found");if(n.updateTo){let s=await U(e);if(!s){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(s.user.email!==n.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let d=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:d,url:`${e.context.baseURL}/verify-email?token=${o}`,token:o},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:d,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await U(e)){let d=await e.context.internalAdapter.createSession(a.user.id,e.request);if(!d)throw new Oe.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await m(e,{session:d,user:a.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var de=require("better-call");var w=require("zod"),ci=require("better-call"),Qn=w.z.object({id:w.z.string(),providerId:w.z.string(),accountId:w.z.string(),userId:w.z.string(),accessToken:w.z.string().nullish(),refreshToken:w.z.string().nullish(),idToken:w.z.string().nullish(),accessTokenExpiresAt:w.z.date().nullish(),refreshTokenExpiresAt:w.z.date().nullish(),scope:w.z.string().nullish(),password:w.z.string().nullish(),createdAt:w.z.date().default(()=>new Date),updatedAt:w.z.date().default(()=>new Date)}),$n=w.z.object({id:w.z.string(),email:w.z.string().transform(e=>e.toLowerCase()),emailVerified:w.z.boolean().default(!1),name:w.z.string(),image:w.z.string().nullish(),createdAt:w.z.date().default(()=>new Date),updatedAt:w.z.date().default(()=>new Date)}),Zn=w.z.object({id:w.z.string(),userId:w.z.string(),expiresAt:w.z.date(),createdAt:w.z.date().default(()=>new Date),updatedAt:w.z.date().default(()=>new Date),token:w.z.string(),ipAddress:w.z.string().nullish(),userAgent:w.z.string().nullish()}),Gn=w.z.object({id:w.z.string(),value:w.z.string(),createdAt:w.z.date().default(()=>new Date),updatedAt:w.z.date().default(()=>new Date),expiresAt:w.z.date(),identifier:w.z.string()});function mr(e,t){let o={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let i of e.plugins||[])i.schema&&i.schema[t]&&(o={...o,...i.schema[t].fields});return o}function fr(e,t){let o=t.action||"create",i=t.fields,r={};for(let n in i){if(n in e){if(i[n].input===!1){if(i[n].defaultValue){r[n]=i[n].defaultValue;continue}continue}if(i[n].validator?.input&&e[n]!==void 0){r[n]=i[n].validator.input.parse(e[n]);continue}r[n]=e[n];continue}if(i[n].defaultValue&&o==="create"){r[n]=i[n].defaultValue;continue}if(i[n].required&&o==="create")throw new ci.APIError("BAD_REQUEST",{message:`${n} is required`})}return r}function so(e,t,o){let i=mr(e,"user");return fr(t||{},{fields:i,action:o})}function ie(e,t){if(!t)return e;for(let o in t){let i=t[o]?.modelName;i&&(e[o].modelName=i);for(let r in e[o].fields){let n=t[o]?.fields?.[r];n&&(e[o].fields[r].fieldName=n)}}return e}var Ki=()=>c("/sign-up/email",{method:"POST",query:Ce.z.object({currentURL:Ce.z.string().optional()}).optional(),body:Ce.z.record(Ce.z.string(),Ce.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:{user:{type:"object"},session:{type:"object"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new de.APIError("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:o,email:i,password:r,image:n,callbackURL:a,...s}=t;if(!Ce.z.string().email().safeParse(i).success)throw new de.APIError("BAD_REQUEST",{message:"Invalid email"});let A=e.context.password.config.minPasswordLength;if(r.length<A)throw e.context.logger.error("Password is too short"),new de.APIError("BAD_REQUEST",{message:"Password is too short"});let K=e.context.password.config.maxPasswordLength;if(r.length>K)throw e.context.logger.error("Password is too long"),new de.APIError("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(i))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${i}`),new de.APIError("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let p=so(e.context.options,s),l;try{if(l=await e.context.internalAdapter.createUser({email:i.toLowerCase(),name:o,image:n,...p,emailVerified:!1}),!l)throw new de.APIError("BAD_REQUEST",{message:"Failed to create user"})}catch(f){throw e.context.logger.error("Failed to create user",f),new de.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:f})}if(!l)throw new de.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let h=await e.context.password.hash(r);if(await e.context.internalAdapter.linkAccount({userId:l.id,providerId:"credential",accountId:l.id,password:h}),e.context.options.emailVerification?.sendOnSignUp){let f=await Ke(e.context.secret,l.email),g=`${e.context.baseURL}/verify-email?token=${f}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:l,url:g,token:f},e.request)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:l,session:null});let k=await e.context.internalAdapter.createSession(l.id,e.request);if(!k)throw new de.APIError("BAD_REQUEST",{message:"Failed to create session"});return await m(e,{session:k,user:l}),e.json({user:l,session:k})});var hr=(e="Unknown")=>`<!DOCTYPE html>
1
+ "use strict";var ir=Object.create;var oo=Object.defineProperty;var tr=Object.getOwnPropertyDescriptor;var rr=Object.getOwnPropertyNames;var nr=Object.getPrototypeOf,sr=Object.prototype.hasOwnProperty;var ar=(e,t)=>{for(var o in t)oo(e,o,{get:t[o],enumerable:!0})},Xo=(e,t,o,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of rr(t))!sr.call(e,r)&&r!==o&&oo(e,r,{get:()=>t[r],enumerable:!(i=tr(t,r))||i.enumerable});return e};var Yo=(e,t,o)=>(o=e!=null?ir(nr(e)):{},Xo(t||!e||!e.__esModule?oo(o,"default",{value:e,enumerable:!0}):o,e)),dr=e=>Xo(oo({},"__esModule",{value:!0}),e);var yn={};ar(yn,{HIDE_METADATA:()=>we,admin:()=>tn,anonymous:()=>on,bearer:()=>Gr,createAuthEndpoint:()=>c,createAuthMiddleware:()=>P,customSession:()=>un,emailOTP:()=>An,genericOAuth:()=>sn,getPasskeyActions:()=>Vt,jwt:()=>an,magicLink:()=>Wr,multiSession:()=>dn,oAuthProxy:()=>pn,oneTap:()=>cn,openAPI:()=>hn,optionsMiddleware:()=>bo,organization:()=>Dr,passkey:()=>$r,passkeyClient:()=>Qr,phoneNumber:()=>Xr,twoFactor:()=>qr,twoFactorClient:()=>Vr,username:()=>Qo});module.exports=dr(yn);var xo=require("better-call"),De=require("zod");var ye=require("better-call"),bo=(0,ye.createMiddleware)(async()=>({})),P=(0,ye.createMiddlewareCreator)({use:[bo,(0,ye.createMiddleware)(async()=>({}))]}),c=(0,ye.createEndpointCreator)({use:[bo]});var q=require("better-call"),x=require("zod");var Cr=require("oslo"),Ri=require("oslo/encoding");var io=require("oslo/crypto");async function cr({value:e,secret:t}){return new io.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(i=>Buffer.from(i).toString("base64"))}function Kr({value:e,signature:t,secret:o}){return new io.HMAC("SHA-256").verify(new TextEncoder().encode(o),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var to={sign:cr,verify:Kr};var ee=class extends Error{constructor(t,o){super(t),this.name="BetterAuthError",this.message=t,this.cause=o,this.stack=""}};var R=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var ro=Object.create(null),Me=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?ro:globalThis),ne=new Proxy(ro,{get(e,t){return Me()[t]??ro[t]},has(e,t){let o=Me();return t in o||t in ro},set(e,t,o){let i=Me(!0);return i[t]=o,!0},deleteProperty(e,t){if(!t)return!1;let o=Me(!0);return delete o[t],!0},ownKeys(){let e=Me(!0);return Object.keys(e)}});function pr(e){return e?e!=="false":!1}var vo=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var ei=vo==="dev"||vo==="development",ur=vo==="test"||pr(ne.TEST);var $=require("better-call");var oi=require("better-call");var lr=P(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:o,context:i}=e,r=e.headers?.get("origin")||e.headers?.get("referer")||"",n=t?.callbackURL||o?.callbackURL,a=t?.redirectTo,s=o?.currentURL,d=i.trustedOrigins,A=e.headers?.has("cookie"),K=(p,l)=>l.includes("*")?new RegExp("^"+l.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(p):p.startsWith(l),u=(p,l)=>{if(!p)return;if(!d.some(k=>K(p,k)||p?.startsWith("/")&&l!=="origin"&&!p.includes(":")))throw e.context.logger.error(`Invalid ${l}: ${p}`),e.context.logger.info(`If it's a valid URL, please add ${p} to trustedOrigins in your auth config
2
+ `,`Current list of trustedOrigins: ${d}`),new oi.APIError("FORBIDDEN",{message:`Invalid ${l}`})};A&&!e.context.options.advanced?.disableCSRFCheck&&u(r,"origin"),n&&u(n,"callbackURL"),a&&u(a,"redirectURL"),s&&u(s,"currentURL")});var we={isAction:!1};var ii=c("/ok",{method:"GET",metadata:{...we,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 Ce=require("zod");var ai=require("oslo"),no=require("oslo/jwt"),oe=require("zod");var Oe=require("better-call");var ae=require("better-call");var Te=require("zod");function ko(e){try{return JSON.parse(e)}catch{return null}}var To=()=>c("/get-session",{method:"GET",query:Te.z.optional(Te.z.object({disableCookieCache:Te.z.boolean({description:"Disable cookie cache and fetch session from database"}).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 t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let o=e.getCookie(e.context.authCookies.sessionData.name),i=o?ko(Buffer.from(o,"base64").toString()):null;if(i&&!await to.verify({value:JSON.stringify(i.session),signature:i?.signature,secret:e.context.secret}))return Q(e),e.json(null);let r=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(i?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let K=i.session;if(i.expiresAt<Date.now()||K.session.expiresAt<new Date){let p=e.context.authCookies.sessionData.name;e.setCookie(p,"",{maxAge:0})}else return e.json(K)}let n=await e.context.internalAdapter.findSession(t);if(e.context.session=n,!n||n.session.expiresAt<new Date)return Q(e),n&&await e.context.internalAdapter.deleteSession(n.session.token),e.json(null);if(r)return e.json(n);let a=e.context.sessionConfig.expiresIn,s=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-a*1e3+s*1e3<=Date.now()){let K=await e.context.internalAdapter.updateSession(n.session.token,{expiresAt:R(e.context.sessionConfig.expiresIn,"sec")});if(!K)return Q(e),e.json(null,{status:401});let u=(K.expiresAt.valueOf()-Date.now())/1e3;return await m(e,{session:K,user:n.user},!1,{maxAge:u}),e.json({session:K,user:n.user})}return e.json(n)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new ae.APIError("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),U=async e=>{if(e.context.session)return e.context.session;let t=await To()({...e,_flag:"json",headers:e.headers});return e.context.session=t,t},v=P(async e=>{let t=await U(e);if(!t?.session)throw new ae.APIError("UNAUTHORIZED");return{session:t}}),He=P(async e=>{let t=await U(e);if(!t?.session)throw new ae.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let o=e.context.sessionConfig.freshAge,i=t.session.createdAt.valueOf(),r=Date.now();if(!(i+o*1e3>r))throw new ae.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),ti=()=>c("/list-sessions",{method:"GET",use:[v],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 o=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(i=>i.expiresAt>new Date);return e.json(o)}),ri=c("/revoke-session",{method:"POST",body:Te.z.object({token:Te.z.string({description:"The token to revoke"})}),use:[v],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 t=e.body.token,o=await e.context.internalAdapter.findSession(t);if(!o)throw new ae.APIError("BAD_REQUEST",{message:"Session not found"});if(o.session.userId!==e.context.session.user.id)throw new ae.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(i){throw e.context.logger.error(i&&typeof i=="object"&&"name"in i?i.name:"",i),new ae.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ni=c("/revoke-sessions",{method:"POST",use:[v],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(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new ae.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),si=c("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[v],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 t=e.context.session;if(!t.user)throw new ae.APIError("UNAUTHORIZED");let r=(await e.context.internalAdapter.listSessions(t.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 Ke(e,t,o){return await(0,no.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:o},{expiresIn:new ai.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Oo(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Oe.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let o=await Ke(e.context.secret,t.email),i=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:i,token:o},e.request)}var di=c("/send-verification-email",{method:"POST",query:oe.z.object({currentURL:oe.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:oe.z.object({email:oe.z.string({description:"The email to send the verification email to"}).email(),callbackURL:oe.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 Oe.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,o=await e.context.internalAdapter.findUserByEmail(t);if(!o)throw new Oe.APIError("BAD_REQUEST",{message:"User not found"});return await Oo(e,o.user),e.json({status:!0})}),Ai=c("/verify-email",{method:"GET",query:oe.z.object({token:oe.z.string({description:"The token to verify the email"}),callbackURL:oe.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 t(s){throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=${s}`):new Oe.APIError("UNAUTHORIZED",{message:s})}let{token:o}=e.query,i;try{i=await(0,no.validateJWT)("HS256",Buffer.from(e.context.secret),o)}catch(s){return e.context.logger.error("Failed to verify email",s),t("invalid_token")}let n=oe.z.object({email:oe.z.string().email(),updateTo:oe.z.string().optional()}).parse(i.payload),a=await e.context.internalAdapter.findUserByEmail(n.email);if(!a)return t("user_not_found");if(n.updateTo){let s=await U(e);if(!s){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(s.user.email!==n.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let d=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:d,url:`${e.context.baseURL}/verify-email?token=${o}`,token:o},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:d,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await U(e)){let d=await e.context.internalAdapter.createSession(a.user.id,e.request);if(!d)throw new Oe.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await m(e,{session:d,user:a.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var de=require("better-call");var w=require("zod"),ci=require("better-call"),Hn=w.z.object({id:w.z.string(),providerId:w.z.string(),accountId:w.z.string(),userId:w.z.string(),accessToken:w.z.string().nullish(),refreshToken:w.z.string().nullish(),idToken:w.z.string().nullish(),accessTokenExpiresAt:w.z.date().nullish(),refreshTokenExpiresAt:w.z.date().nullish(),scope:w.z.string().nullish(),password:w.z.string().nullish(),createdAt:w.z.date().default(()=>new Date),updatedAt:w.z.date().default(()=>new Date)}),Qn=w.z.object({id:w.z.string(),email:w.z.string().transform(e=>e.toLowerCase()),emailVerified:w.z.boolean().default(!1),name:w.z.string(),image:w.z.string().nullish(),createdAt:w.z.date().default(()=>new Date),updatedAt:w.z.date().default(()=>new Date)}),$n=w.z.object({id:w.z.string(),userId:w.z.string(),expiresAt:w.z.date(),createdAt:w.z.date().default(()=>new Date),updatedAt:w.z.date().default(()=>new Date),token:w.z.string(),ipAddress:w.z.string().nullish(),userAgent:w.z.string().nullish()}),Zn=w.z.object({id:w.z.string(),value:w.z.string(),createdAt:w.z.date().default(()=>new Date),updatedAt:w.z.date().default(()=>new Date),expiresAt:w.z.date(),identifier:w.z.string()});function gr(e,t){let o={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let i of e.plugins||[])i.schema&&i.schema[t]&&(o={...o,...i.schema[t].fields});return o}function mr(e,t){let o=t.action||"create",i=t.fields,r={};for(let n in i){if(n in e){if(i[n].input===!1){if(i[n].defaultValue){r[n]=i[n].defaultValue;continue}continue}if(i[n].validator?.input&&e[n]!==void 0){r[n]=i[n].validator.input.parse(e[n]);continue}r[n]=e[n];continue}if(i[n].defaultValue&&o==="create"){r[n]=i[n].defaultValue;continue}if(i[n].required&&o==="create")throw new ci.APIError("BAD_REQUEST",{message:`${n} is required`})}return r}function so(e,t,o){let i=gr(e,"user");return mr(t||{},{fields:i,action:o})}function ie(e,t){if(!t)return e;for(let o in t){let i=t[o]?.modelName;i&&(e[o].modelName=i);for(let r in e[o].fields){let n=t[o]?.fields?.[r];n&&(e[o].fields[r].fieldName=n)}}return e}var Ki=()=>c("/sign-up/email",{method:"POST",query:Ce.z.object({currentURL:Ce.z.string().optional()}).optional(),body:Ce.z.record(Ce.z.string(),Ce.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:{user:{type:"object"},session:{type:"object"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new de.APIError("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:o,email:i,password:r,image:n,callbackURL:a,...s}=t;if(!Ce.z.string().email().safeParse(i).success)throw new de.APIError("BAD_REQUEST",{message:"Invalid email"});let A=e.context.password.config.minPasswordLength;if(r.length<A)throw e.context.logger.error("Password is too short"),new de.APIError("BAD_REQUEST",{message:"Password is too short"});let K=e.context.password.config.maxPasswordLength;if(r.length>K)throw e.context.logger.error("Password is too long"),new de.APIError("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(i))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${i}`),new de.APIError("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let p=so(e.context.options,s),l;try{if(l=await e.context.internalAdapter.createUser({email:i.toLowerCase(),name:o,image:n,...p,emailVerified:!1}),!l)throw new de.APIError("BAD_REQUEST",{message:"Failed to create user"})}catch(f){throw e.context.logger.error("Failed to create user",f),new de.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:f})}if(!l)throw new de.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let h=await e.context.password.hash(r);if(await e.context.internalAdapter.linkAccount({userId:l.id,providerId:"credential",accountId:l.id,password:h}),e.context.options.emailVerification?.sendOnSignUp){let f=await Ke(e.context.secret,l.email),g=`${e.context.baseURL}/verify-email?token=${f}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:l,url:g,token:f},e.request)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:l,session:null});let k=await e.context.internalAdapter.createSession(l.id,e.request);if(!k)throw new de.APIError("BAD_REQUEST",{message:"Failed to create session"});return await m(e,{session:k,user:l}),e.json({user:l,session:k})});var fr=(e="Unknown")=>`<!DOCTYPE html>
3
3
  <html lang="en">
4
4
  <head>
5
5
  <meta charset="UTF-8">
@@ -79,8 +79,8 @@
79
79
  <div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
80
80
  </div>
81
81
  </body>
82
- </html>`,pi=c("/error",{method:"GET",metadata:{...we,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string"}}}}}}}},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(hr(t),{headers:{"Content-Type":"text/html"}})});var ui=require("consola"),Io=["info","success","warn","error","debug"];function yr(e,t){return Io.indexOf(t)<=Io.indexOf(e)}var wr=(0,ui.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),li=e=>{let t=e?.disabled!==!0,o=e?.level??"error",i=(r,n,a=[])=>{if(!(!t||!yr(o,r))){if(!e||typeof e.log!="function"){wr[r]("",n,...a);return}e.log(r==="success"?"info":r,n,a)}};return Object.fromEntries(Io.map(r=>[r,(...[n,...a])=>i(r,n,a)]))},J=li();var C=require("better-call");function Uo(e,t){let o=t.plugins?.reduce((s,d)=>({...s,...d.endpoints}),{}),i=t.plugins?.map(s=>s.middlewares?.map(d=>{let A=async K=>d.middleware({...K,context:{...e,...K.context}});return A.path=d.path,A.options=d.middleware.options,A.headers=d.middleware.headers,{path:d.path,middleware:A}})).filter(s=>s!==void 0).flat()||[],n={...{signInSocial:gi,callbackOAuth:fi,getSession:To(),signOut:hi,signUpEmail:Ki(),signInEmail:mi,forgetPassword:yi,resetPassword:Ci,verifyEmail:Ai,sendVerificationEmail:di,changeEmail:Oi,changePassword:vi,setPassword:ki,updateUser:bi(),deleteUser:Ti,forgetPasswordCallback:wi,listSessions:ti(),revokeSession:ri,revokeSessions:ni,revokeOtherSessions:si,linkSocialAccount:Ui,listUserAccounts:Ii},...o,ok:ii,error:pi},a={};for(let[s,d]of Object.entries(n))a[s]=async(A={})=>{d.headers=new Headers;let K={setHeader(f,g){d.headers.set(f,g)},setCookie(f,g,b){(0,H.setCookie)(d.headers,f,g,b)},getCookie(f,g){let T=A.headers?.get("cookie");return(0,H.getCookie)(T||"",f,g)},getSignedCookie(f,g,b){let T=A.headers;return T?(0,H.getSignedCookie)(T,g,f,b):null},async setSignedCookie(f,g,b,T){await(0,H.setSignedCookie)(d.headers,f,g,b,T)},redirect(f){return d.headers.set("Location",f),new H.APIError("FOUND")},responseHeader:d.headers},u=await e,p={...K,...A,path:d.path,context:{...u,...A.context,endpoint:d}};u.session=null;let l=t.plugins||[];for(let f of l){let g=f.hooks?.before??[];for(let b of g){if(!b.matcher(p))continue;let T=await b.handler(p);if(T&&"context"in T){p={...p,...T.context};continue}if(T)return T}}let h;try{h=await d(p)}catch(f){if(f instanceof H.APIError){let g=t.plugins?.map(b=>{if(b.hooks?.after)return b.hooks.after}).filter(b=>b!==void 0).flat();if(!g?.length)throw f.headers=d.headers,f;p.context.returned=f,p.context.returned.headers=d.headers;for(let b of g||[])if(b.matcher(p))try{let N=await b.handler(p);N&&"response"in N&&(p.context.returned=N.response)}catch(N){if(N instanceof H.APIError){p.context.returned=N;continue}throw N}if(p.context.returned instanceof H.APIError)throw p.context.returned.headers=d.headers,p.context.returned;return p.context.returned}throw f}p.context.returned=h,p.responseHeader=d.headers;for(let f of t.plugins||[])if(f.hooks?.after){for(let g of f.hooks.after)if(g.matcher(p))try{let T=await g.handler(p);T&&(p.context.returned=T)}catch(T){if(T instanceof H.APIError){p.context.returned=T;continue}throw T}}let k=p.context.returned;return k instanceof Response&&d.headers.forEach((f,g)=>{g==="set-cookie"?k.headers.append(g,f):k.headers.set(g,f)}),k},a[s].path=d.path,a[s].method=d.method,a[s].options=d.options,a[s].headers=d.headers;return{api:a,middlewares:i}}function ao(e){let t=new Map;return e.split(", ").forEach(i=>{let r=i.split(";").map(u=>u.trim()),[n,...a]=r,[s,...d]=n.split("="),A=d.join("=");if(!s||A===void 0){console.warn(`Malformed cookie: ${i}`);return}let K={value:A};a.forEach(u=>{let[p,...l]=u.split("="),h=l.join("="),k=p.trim().toLowerCase();switch(k){case"max-age":K["max-age"]=h?parseInt(h.trim(),10):void 0;break;case"expires":K.expires=h?new Date(h.trim()):void 0;break;case"domain":K.domain=h?h.trim():void 0;break;case"path":K.path=h?h.trim():void 0;break;case"secure":K.secure=!0;break;case"httponly":K.httponly=!0;break;case"samesite":K.samesite=h?h.trim().toLowerCase():void 0;break;default:K[k]=h?h.trim():!0;break}}),t.set(s,K)}),t}async function m(e,t,o,i){let r=e.context.authCookies.sessionToken.options,n=o?void 0:e.context.sessionConfig.expiresIn,a=await U(e).catch(()=>null);a&&a.session.userId===t.session.userId&&a.session.token!==t.session.token&&await e.context.internalAdapter.deleteSession(a.session.token),await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...r,maxAge:n,...i}),o&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Ri.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:R(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await to.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),new Date(t.session.expiresAt).getTime()-Date.now())}function M(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}function He(e){let t=e.split("; "),o=new Map;return t.forEach(i=>{let[r,n]=i.split("=");o.set(r,n)}),o}var ji=require("@better-fetch/fetch"),zi=require("better-call"),Re=require("jose"),Bi=require("oslo/jwt");var Pi=require("oslo/crypto"),Ei=require("oslo/encoding");async function Si(e){let t=await(0,Pi.sha256)(new TextEncoder().encode(e));return Ei.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Di(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?R(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function S({id:e,options:t,authorizationEndpoint:o,state:i,codeVerifier:r,scopes:n,claims:a,redirectURI:s}){let d=new URL(o);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",i),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||s),r){let A=await Si(r);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",A)}if(a){let A=a.reduce((K,u)=>(K[u]=null,K),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...A}}))}return d}var xi=require("@better-fetch/fetch");async function I({code:e,codeVerifier:t,redirectURI:o,options:i,tokenEndpoint:r,authentication:n}){let a=new URLSearchParams,s={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(a.set("grant_type","authorization_code"),a.set("code",e),t&&a.set("code_verifier",t),a.set("redirect_uri",o),n==="basic"){let u=btoa(`${i.clientId}:${i.clientSecret}`);s.authorization=`Basic ${u}`}else a.set("client_id",i.clientId),a.set("client_secret",i.clientSecret);let{data:d,error:A}=await(0,xi.betterFetch)(r,{method:"POST",body:a,headers:s});if(A)throw A;return Di(d)}var Ao=require("oslo/oauth2"),pe=require("zod"),Ro=require("better-call");function Ie(e){try{return new URL(e).origin}catch{return null}}async function Ue(e,t){let o=e.body?.callbackURL||(e.query?.currentURL?Ie(e.query?.currentURL):"")||e.context.options.baseURL;if(!o)throw new Ro.APIError("BAD_REQUEST",{message:"callbackURL is required"});let i=(0,Ao.generateCodeVerifier)(),r=(0,Ao.generateState)(),n=JSON.stringify({callbackURL:o,codeVerifier:i,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),a=new Date;a.setMinutes(a.getMinutes()+10);let s=await e.context.internalAdapter.createVerificationValue({value:n,identifier:r,expiresAt:a});if(!s)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new Ro.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:s.identifier,codeVerifier:i}}async function co(e){let t=e.query.state||e.body.state,o=await e.context.internalAdapter.findVerificationValue(t);if(!o)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let i=pe.z.object({callbackURL:pe.z.string(),codeVerifier:pe.z.string(),errorURL:pe.z.string().optional(),expiresAt:pe.z.number(),link:pe.z.object({email:pe.z.string(),userId:pe.z.string()}).optional()}).parse(JSON.parse(o.value));if(i.errorURL||(i.errorURL=`${e.context.baseURL}/error`),i.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(o.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(o.id),i}var Ni=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:o,scopes:i,redirectURI:r}){let n=i||["email","name"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${r||e.redirectURI}&scope=${n.join(" ")}&state=${o}&response_mode=form_post`)},validateAuthorizationCode:async({code:o,codeVerifier:i,redirectURI:r})=>I({code:o,codeVerifier:i,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t}),async verifyIdToken(o,i){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(o,i);let r=(0,Re.decodeProtectedHeader)(o),{kid:n,alg:a}=r;if(!n||!a)return!1;let s=await vr(n),{payload:d}=await(0,Re.jwtVerify)(o,s,{algorithms:[a],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(A=>{d[A]!==void 0&&(d[A]=!!d[A])}),i&&d.nonce!==i?!1:!!d},async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);if(!o.idToken)return null;let i=(0,Bi.parseJWT)(o.idToken)?.payload;if(!i)return null;let r=i.user?`${i.user.name.firstName} ${i.user.name.lastName}`:i.email;return{user:{id:i.sub,name:r,emailVerified:!1,email:i.email},data:i}}}},vr=async e=>{let t="https://appleid.apple.com",o="/auth/keys",{data:i}=await(0,ji.betterFetch)(`${t}${o}`);if(!i?.keys)throw new zi.APIError("BAD_REQUEST",{message:"Keys not found"});let r=i.keys.find(n=>n.kid===e);if(!r)throw new Error(`JWK with kid ${e} not found`);return await(0,Re.importJWK)(r,r.alg)};var Li=require("@better-fetch/fetch");var _i=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:o,redirectURI:i}){let r=o||["identify","email"];return e.scope&&r.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${r.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||i)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:o})=>I({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:i}=await(0,Li.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;if(o.avatar===null){let r=o.discriminator==="0"?Number(BigInt(o.id)>>BigInt(22))%6:parseInt(o.discriminator)%5;o.image_url=`https://cdn.discordapp.com/embed/avatars/${r}.png`}else{let r=o.avatar.startsWith("a_")?"gif":"png";o.image_url=`https://cdn.discordapp.com/avatars/${o.id}/${o.avatar}.${r}`}return{user:{id:o.id,name:o.display_name||o.username||"",email:o.email,emailVerified:o.verified,image:o.image_url},data:o}}});var Fi=require("@better-fetch/fetch");var Vi=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:o,redirectURI:i}){let r=o||["email","public_profile"];return e.scope&&r.push(...e.scope),await S({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:r,state:t,redirectURI:i})},validateAuthorizationCode:async({code:t,redirectURI:o})=>I({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:i}=await(0,Fi.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return i?null:{user:{id:o.id,name:o.name,email:o.email,image:o.picture.data.url,emailVerified:o.email_verified},data:o}}});var Po=require("@better-fetch/fetch");var qi=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:o,scopes:i,codeVerifier:r,redirectURI:n}){let a=i||["user:email"];return e.scope&&a.push(...e.scope),S({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>I({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);let{data:i,error:r}=await(0,Po.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${o.accessToken}`}});if(r)return null;let n=!1;if(!i.email){let{data:a,error:s}=await(0,Po.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${o.accessToken}`,"User-Agent":"better-auth"}});s||(i.email=(a.find(d=>d.primary)??a[0])?.email,n=a.find(d=>d.email===i.email)?.verified??!1)}return{user:{id:i.id.toString(),name:i.name||i.login,email:i.email,image:i.avatar_url,emailVerified:n},data:i}}}};var Mi=require("oslo/jwt");var Hi=require("@better-fetch/fetch"),Qi=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:o,codeVerifier:i,redirectURI:r}){if(!e.clientId||!e.clientSecret)throw J.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new ee("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new ee("codeVerifier is required for Google");let n=o||["email","profile","openid"];e.scope&&n.push(...e.scope);let a=await S({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:i,redirectURI:r});return e.accessType&&a.searchParams.set("access_type",e.accessType),e.prompt&&a.searchParams.set("prompt",e.prompt),a},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:i})=>I({code:t,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,o);let i=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:r}=await(0,Hi.betterFetch)(i);return r?r.aud===e.clientId&&r.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let o=(0,Mi.parseJWT)(t.idToken)?.payload;return{user:{id:o.sub,name:o.name,email:o.email,image:o.picture,emailVerified:o.email_verified},data:o}}});var $i=require("@better-fetch/fetch"),Zi=require("oslo/jwt");var Gi=e=>{let t=e.tenantId||"common",o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,i=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(r){let n=r.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),S({id:"microsoft",options:e,authorizationEndpoint:o,state:r.state,codeVerifier:r.codeVerifier,scopes:n,redirectURI:r.redirectURI})},validateAuthorizationCode({code:r,codeVerifier:n,redirectURI:a}){return I({code:r,codeVerifier:n,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:i})},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let n=(0,Zi.parseJWT)(r.idToken)?.payload,a=e.profilePhotoSize||48;return await(0,$i.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${r.accessToken}`},async onResponse(s){if(!(e.disableProfilePhoto||!s.response.ok))try{let A=await s.response.clone().arrayBuffer(),K=Buffer.from(A).toString("base64");n.picture=`data:image/jpeg;base64, ${K}`}catch(d){J.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};var Wi=require("@better-fetch/fetch");var Ji=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:o,codeVerifier:i,redirectURI:r}){let n=o||["user-read-email"];return e.scope&&n.push(...e.scope),S({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:r})},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:i})=>I({code:t,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:i}=await(0,Wi.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{id:o.id,name:o.display_name,email:o.email,image:o.images[0]?.url,emailVerified:!1},data:o}}});var Xi=require("nanoid"),_=e=>(0,Xi.nanoid)(e);var Yi=require("oslo/jwt");var et=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:o,redirectURI:i}){let r=o||["user:read:email","openid"];return e.scope&&r.push(...e.scope),S({id:"twitch",redirectURI:i,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:r,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:o})=>I({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let o=t.idToken;if(!o)return J.error("No idToken found in token"),null;let i=(0,Yi.parseJWT)(o)?.payload;return{user:{id:i.sub,name:i.preferred_username,email:i.email,image:i.picture,emailVerified:!1},data:i}}});var ot=require("@better-fetch/fetch");var it=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let o=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&o.push(...e.scope),S({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:o,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:i})=>I({code:t,codeVerifier:o,authentication:"basic",redirectURI:e.redirectURI||i,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:i}=await(0,ot.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{id:o.data.id,name:o.data.name,email:o.data.email||null,image:o.data.profile_image_url,emailVerified:o.data.verified||!1},data:o}}});var tt=require("@better-fetch/fetch");var rt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:o,scopes:i,codeVerifier:r,redirectURI:n})=>{let a=i||["account_info.read"];return e.scope&&a.push(...e.scope),await S({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:o,redirectURI:n,codeVerifier:r})},validateAuthorizationCode:async({code:o,codeVerifier:i,redirectURI:r})=>await I({code:o,codeVerifier:i,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t}),async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);let{data:i,error:r}=await(0,tt.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${o.accessToken}`}});return r?null:{user:{id:i.account_id,name:i.name?.display_name,email:i.email,emailVerified:i.email_verified||!1,image:i.profile_photo_url},data:i}}}};var nt=require("@better-fetch/fetch");var st=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",o="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:i,scopes:r,redirectURI:n})=>{let a=r||["profile","email","openid"];return e.scope&&a.push(...e.scope),await S({id:"linkedin",options:e,authorizationEndpoint:t,scopes:a,state:i,redirectURI:n})},validateAuthorizationCode:async({code:i,redirectURI:r})=>await I({code:i,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:o}),async getUserInfo(i){let{data:r,error:n}=await(0,nt.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});return n?null:{user:{id:r.sub,name:r.name,email:r.email,emailVerified:r.email_verified||!1,image:r.picture},data:r}}}};var at=require("@better-fetch/fetch");var Eo=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),kr=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:Eo(`${t}/oauth/authorize`),tokenEndpoint:Eo(`${t}/oauth/token`),userinfoEndpoint:Eo(`${t}/api/v4/user`)}},dt=e=>{let{authorizationEndpoint:t,tokenEndpoint:o,userinfoEndpoint:i}=kr(e.issuer),r="gitlab";return{id:r,name:"Gitlab",createAuthorizationURL:async({state:a,scopes:s,codeVerifier:d,redirectURI:A})=>{let K=s||["read_user"];return e.scope&&K.push(...e.scope),await S({id:r,options:e,authorizationEndpoint:t,scopes:K,state:a,redirectURI:A,codeVerifier:d})},validateAuthorizationCode:async({code:a,redirectURI:s,codeVerifier:d})=>I({code:a,redirectURI:e.redirectURI||s,options:e,codeVerifier:d,tokenEndpoint:o}),async getUserInfo(a){if(e.getUserInfo)return e.getUserInfo(a);let{data:s,error:d}=await(0,at.betterFetch)(i,{headers:{authorization:`Bearer ${a.accessToken}`}});return d||s.state!=="active"||s.locked?null:{user:{id:s.id.toString(),name:s.name??s.username,email:s.email,image:s.avatar_url,emailVerified:!0},data:s}}}};var Tr={apple:Ni,discord:_i,facebook:Vi,github:qi,microsoft:Gi,google:Qi,spotify:Ji,twitch:et,twitter:it,dropbox:rt,linkedin:st,gitlab:dt},Ko=Object.keys(Tr);async function Pe(e,{userInfo:t,account:o,callbackURL:i}){let r=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(s=>{throw J.error(`Better auth was unable to query your database.
83
- Error: `,s),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=r?.user;if(r){let s=r.accounts.find(d=>d.providerId===o.providerId);if(s){let d=Object.fromEntries(Object.entries({accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt}).filter(([A,K])=>K!==void 0));Object.keys(d).length>0&&await e.context.internalAdapter.updateAccount(s.id,d)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(o.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return ei&&J.warn(`User already exist but account isn't linked to ${o.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:o.providerId,accountId:t.id.toString(),userId:r.user.id,accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt,scope:o.scope})}catch(K){return J.error("Unable to link account",K),{error:"unable to link account",data:null}}}}else try{let s=t.emailVerified||!1;if(n=await e.context.internalAdapter.createOAuthUser({...t,id:void 0,emailVerified:s,email:t.email.toLowerCase()},{accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt,scope:o.scope,providerId:o.providerId,accountId:t.id.toString()}).then(d=>d?.user),!s&&n&&e.context.options.emailVerification?.sendOnSignUp){let d=await Ke(e.context.secret,n.email),A=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${i}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:n,url:A,token:d},e.request)}}catch(s){return J.error("Unable to create user",s),{error:"unable to create user",data:null}}if(!n)return{error:"unable to create user",data:null};let a=await e.context.internalAdapter.createSession(n.id,e.request);return a?{data:{session:a,user:n},error:null}:{error:"unable to create session",data:null}}var gi=c("/sign-in/social",{method:"POST",query:x.z.object({currentURL:x.z.string().optional()}).optional(),body:x.z.object({callbackURL:x.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),errorCallbackURL:x.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:x.z.enum(Ko,{description:"OAuth2 provider to use"}),disableRedirect:x.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:x.z.optional(x.z.object({token:x.z.string({description:"ID token from the provider"}),nonce:x.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:x.z.string({description:"Access token from the provider"}).optional(),refreshToken:x.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:x.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new F.APIError("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new F.APIError("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:n,nonce:a}=e.body.idToken;if(!await t.verifyIdToken(n,a))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new F.APIError("UNAUTHORIZED",{message:"Invalid id token"});let d=await t.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!d||!d?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new F.APIError("UNAUTHORIZED",{message:"Failed to get user info"});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new F.APIError("UNAUTHORIZED",{message:"User email not found"});let A=await Pe(e,{userInfo:{email:d.user.email,id:d.user.id,name:d.user.name||"",image:d.user.image,emailVerified:d.user.emailVerified||!1},account:{providerId:t.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(A.error)throw new F.APIError("UNAUTHORIZED",{message:A.error});return await m(e,A.data),e.json({session:A.data.session,user:A.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:o,state:i}=await Ue(e),r=await t.createAuthorizationURL({state:i,codeVerifier:o,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:r.toString(),redirect:!e.body.disableRedirect})}),mi=c("/sign-in/email",{method:"POST",body:x.z.object({email:x.z.string({description:"Email of the user"}),password:x.z.string({description:"Password of the user"}),callbackURL:x.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:x.z.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new F.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:o}=e.body;if(!x.z.string().email().safeParse(t).success)throw new F.APIError("BAD_REQUEST",{message:"Invalid email"});let r=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!r)throw await e.context.password.hash(o),e.context.logger.error("User not found",{email:t}),new F.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let n=r.accounts.find(A=>A.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new F.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let a=n?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new F.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify({hash:a,password:o}))throw e.context.logger.error("Invalid password"),new F.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!r.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new F.APIError("UNAUTHORIZED",{message:"Email is not verified."});let A=await Ke(e.context.secret,r.user.email),K=`${e.context.baseURL}/verify-email?token=${A}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:r.user,url:K,token:A},e.request),e.context.logger.error("Email not verified",{email:t}),new F.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(r.user.id,e.headers,e.body.rememberMe===!1);if(!d)throw e.context.logger.error("Failed to create session"),new F.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await m(e,{session:d,user:r.user},e.body.rememberMe===!1),e.json({user:r.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Ee=require("zod");var po=Ee.z.object({code:Ee.z.string().optional(),error:Ee.z.string().optional(),errorMessage:Ee.z.string().optional(),state:Ee.z.string().optional()}),fi=c("/callback/:id",{method:["GET","POST"],body:po.optional(),query:po.optional(),metadata:we},async e=>{let t;try{if(e.method==="GET")t=po.parse(e.query);else if(e.method==="POST")t=po.parse(e.body);else throw new Error("Unsupported method")}catch(g){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",g),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:o,error:i,state:r}=t;if(!r)throw e.context.logger.error("State not found"),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!o)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${i||"no_code"}`);let n=e.context.socialProviders.find(g=>g.id===e.params.id);if(!n)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:a,callbackURL:s,link:d,errorURL:A}=await co(e),K;try{K=await n.validateAuthorizationCode({code:o,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${n.id}`})}catch(g){throw e.context.logger.error("",g),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let u=await n.getUserInfo(K).then(g=>g?.user);function p(g){let b=A||s||`${e.context.baseURL}/error`;throw b.includes("?")?b=`${b}&error=${g}`:b=`${b}?error=${g}`,e.redirect(b)}if(!u)return e.context.logger.error("Unable to get user info"),p("unable_to_get_user_info");if(!u.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),p("email_not_found");if(!s)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(d){if(d.email!==u.email.toLowerCase())return p("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:n.id,accountId:u.id}))return p("unable_to_link_account");let b;try{b=new URL(s).toString()}catch{b=s}throw e.redirect(b)}let l=await Pe(e,{userInfo:{id:u.id,email:u.email,name:u.name||"",image:u.image,emailVerified:u.emailVerified||!1},account:{providerId:n.id,accountId:u.id,...K,scope:K.scopes?.join(",")},callbackURL:s});if(l.error)return e.context.logger.error(l.error.split(" ").join("_")),p(l.error.split(" ").join("_"));let{session:h,user:k}=l.data;await m(e,{session:h,user:k});let f;try{f=new URL(s).toString()}catch{f=s}throw e.redirect(f)});var vd=require("zod");var At=require("better-call"),hi=c("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw M(e),new At.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),M(e),e.json({success:!0})});var X=require("zod");var uo=require("better-call");function ct(e,t,o){let i=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return o&&Object.entries(o).forEach(([r,n])=>i.searchParams.set(r,n)),i.href}function Or(e,t,o){let i=new URL(t,e.baseURL);return o&&Object.entries(o).forEach(([r,n])=>i.searchParams.set(r,n)),i.href}var yi=c("/forget-password",{method:"POST",body:X.z.object({email:X.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:X.z.string({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new uo.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:o}=e.body,i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let r=60*60*1,n=R(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||r,"sec"),a=_(24);await e.context.internalAdapter.createVerificationValue({value:i.user.id.toString(),identifier:`reset-password:${a}`,expiresAt:n});let s=`${e.context.baseURL}/reset-password/${a}?callbackURL=${o}`;return await e.context.options.emailAndPassword.sendResetPassword({user:i.user,url:s,token:a},e.request),e.json({status:!0})}),wi=c("/reset-password/:token",{method:"GET",query:X.z.object({callbackURL:X.z.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:o}=e.query;if(!t||!o)throw e.redirect(ct(e.context,o,{error:"INVALID_TOKEN"}));let i=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!i||i.expiresAt<new Date?e.redirect(ct(e.context,o,{error:"INVALID_TOKEN"})):e.redirect(Or(e.context,o,{token:t}))}),Ci=c("/reset-password",{query:X.z.optional(X.z.object({token:X.z.string().optional(),currentURL:X.z.string().optional()})),method:"POST",body:X.z.object({newPassword:X.z.string({description:"The new password to set"}),token:X.z.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new uo.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:o}=e.body,i=`reset-password:${t}`,r=await e.context.internalAdapter.findVerificationValue(i);if(!r||r.expiresAt<new Date)throw new uo.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(r.id);let n=r.value,a=await e.context.password.hash(o);return(await e.context.internalAdapter.findAccounts(n)).find(A=>A.providerId==="credential")?(await e.context.internalAdapter.updatePassword(n,a),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:a,accountId:n}),e.json({status:!0}))});var L=require("zod");var G=require("better-call");var bi=()=>c("/update-user",{method:"POST",body:L.z.record(L.z.string(),L.z.any()),use:[v],metadata:{openapi:{description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"}}}}}}}}}},async e=>{let t=e.body;if(t.email)throw new G.APIError("BAD_REQUEST",{message:"You can't update email"});let{name:o,image:i,...r}=t,n=e.context.session;if(!i&&!o&&Object.keys(r).length===0)return e.json({user:n.user});let a=so(e.context.options,r,"update"),s=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:o,image:i,...a});return await m(e,{session:n.session,user:s}),e.json({user:s})}),vi=c("/change-password",{method:"POST",body:L.z.object({newPassword:L.z.string({description:"The new password to set"}),currentPassword:L.z.string({description:"The current password"}),revokeOtherSessions:L.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[v],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:o,revokeOtherSessions:i}=e.body,r=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new G.APIError("BAD_REQUEST",{message:"Password is too short"});let a=e.context.password.config.maxPasswordLength;if(t.length>a)throw e.context.logger.error("Password is too long"),new G.APIError("BAD_REQUEST",{message:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(r.user.id)).find(u=>u.providerId==="credential"&&u.password);if(!d||!d.password)throw new G.APIError("BAD_REQUEST",{message:"User does not have a password"});let A=await e.context.password.hash(t);if(!await e.context.password.verify({hash:d.password,password:o}))throw new G.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:A}),i){await e.context.internalAdapter.deleteSessions(r.user.id);let u=await e.context.internalAdapter.createSession(r.user.id,e.headers);if(!u)throw new G.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await m(e,{session:u,user:r.user})}return e.json(r.user)}),ki=c("/set-password",{method:"POST",body:L.z.object({newPassword:L.z.string()}),metadata:{SERVER_ONLY:!0},use:[v]},async e=>{let{newPassword:t}=e.body,o=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new G.APIError("BAD_REQUEST",{message:"Password is too short"});let r=e.context.password.config.maxPasswordLength;if(t.length>r)throw e.context.logger.error("Password is too long"),new G.APIError("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(o.user.id)).find(d=>d.providerId==="credential"&&d.password),s=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:o.user.id,providerId:"credential",accountId:o.user.id,password:s}),e.json(o.user);throw new G.APIError("BAD_REQUEST",{message:"user already has a password"})}),Ti=c("/delete-user",{method:"POST",body:L.z.object({password:L.z.string({description:"The password of the user"})}),use:[Me],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{let t=e.context.session;return await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),M(e),e.json(null)}),Oi=c("/change-email",{method:"POST",query:L.z.object({currentURL:L.z.string().optional()}).optional(),body:L.z.object({newEmail:L.z.string({description:"The new email to set"}).email(),callbackURL:L.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[v],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new G.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new G.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new G.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let r=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:r,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new G.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let o=await Ke(e.context.secret,e.context.session.user.email,e.body.newEmail),i=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:i,token:o},e.request),e.json({user:null,status:!0})});var Se=require("zod");var So=require("better-call");var Ii=c("/list-accounts",{method:"GET",use:[v],metadata:{openapi:{description:"List all accounts linked to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},provider:{type:"string"}}}}}}}}}}},async e=>{let t=e.context.session,o=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(o.map(i=>({id:i.id,provider:i.providerId})))}),Ui=c("/link-social",{method:"POST",requireHeaders:!0,query:Se.z.object({currentURL:Se.z.string().optional()}).optional(),body:Se.z.object({callbackURL:Se.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:Se.z.enum(Ko,{description:"The OAuth2 provider to use"})}),use:[v],metadata:{openapi:{description:"Link a social account to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}},required:["url","redirect"]}}}}}}}},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(s=>s.providerId===e.body.provider))throw new So.APIError("BAD_REQUEST",{message:"Social Account is already linked."});let r=e.context.socialProviders.find(s=>s.id===e.body.provider);if(!r)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new So.APIError("NOT_FOUND",{message:"Provider not found"});let n=await Ue(e,{userId:t.user.id,email:t.user.email}),a=await r.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${r.id}`});return e.json({url:a.toString(),redirect:!0})});var Kt=(e,t)=>{let o={};for(let[i,r]of Object.entries(e))o[i]=n=>r({...n,context:{...t,...n.context}}),o[i].path=r.path,o[i].method=r.method,o[i].options=r.options,o[i].headers=r.headers;return o};function lo(e){let t=e;return{newRole(o){return Ir(o)}}}function Ir(e){return{statements:e,authorize(t,o){for(let[i,r]of Object.entries(t)){let n=e[i];return n?(o==="OR"?r.some(s=>n.includes(s)):r.every(s=>n.includes(s)))?{success:!0}:{success:!1,error:`Unauthorized to access resource "${i}"`}:{success:!1,error:`You are not allowed to access resource: ${i}`}}return{success:!1,error:"Not authorized"}}}}var Ur={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},Do=lo(Ur),Rr=Do.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),Pr=Do.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),Er=Do.newRole({organization:[],member:[],invitation:[]}),pt={admin:Rr,owner:Pr,member:Er};var z=(e,t)=>{let o=e.adapter;return{findOrganizationBySlug:async i=>await o.findOne({model:"organization",where:[{field:"slug",value:i}]}),createOrganization:async i=>{let r=await o.create({model:"organization",data:{...i.organization,metadata:i.organization.metadata?JSON.stringify(i.organization.metadata):void 0}}),n=await o.create({model:"member",data:{organizationId:r.id,userId:i.user.id,createdAt:new Date,role:t?.creatorRole||"owner"}});return{...r,metadata:r.metadata?JSON.parse(r.metadata):void 0,members:[{...n,user:{id:i.user.id,name:i.user.name,email:i.user.email,image:i.user.image}}]}},findMemberByEmail:async i=>{let r=await o.findOne({model:"user",where:[{field:"email",value:i.email}]});if(!r)return null;let n=await o.findOne({model:"member",where:[{field:"organizationId",value:i.organizationId},{field:"userId",value:r.id}]});return n?{...n,user:{id:r.id,name:r.name,email:r.email,image:r.image}}:null},findMemberByOrgId:async i=>{let[r,n]=await Promise.all([await o.findOne({model:"member",where:[{field:"userId",value:i.userId},{field:"organizationId",value:i.organizationId}]}),await o.findOne({model:"user",where:[{field:"id",value:i.userId}]})]);return!n||!r?null:{...r,user:{id:n.id,name:n.name,email:n.email,image:n.image}}},findMemberById:async i=>{let r=await o.findOne({model:"member",where:[{field:"id",value:i}]});if(!r)return null;let n=await o.findOne({model:"user",where:[{field:"id",value:r.userId}]});return n?{...r,user:{id:n.id,name:n.name,email:n.email,image:n.image}}:null},createMember:async i=>await o.create({model:"member",data:i}),updateMember:async(i,r)=>await o.update({model:"member",where:[{field:"id",value:i}],update:{role:r}}),deleteMember:async i=>await o.delete({model:"member",where:[{field:"id",value:i}]}),updateOrganization:async(i,r)=>await o.update({model:"organization",where:[{field:"id",value:i}],update:{...r,metadata:r.metadata?JSON.stringify(r.metadata):void 0}}),deleteOrganization:async i=>(await o.delete({model:"member",where:[{field:"organizationId",value:i}]}),await o.delete({model:"invitation",where:[{field:"organizationId",value:i}]}),await o.delete({model:"organization",where:[{field:"id",value:i}]}),i),setActiveOrganization:async(i,r)=>await e.internalAdapter.updateSession(i,{activeOrganizationId:r}),findOrganizationById:async i=>await o.findOne({model:"organization",where:[{field:"id",value:i}]}),findFullOrganization:async({organizationId:i,isSlug:r})=>{let n=await o.findOne({model:"organization",where:[{field:r?"slug":"id",value:i}]});if(!n)return null;let[a,s]=await Promise.all([o.findMany({model:"invitation",where:[{field:"organizationId",value:n.id}]}),o.findMany({model:"member",where:[{field:"organizationId",value:n.id}]})]);if(!n)return null;let d=s.map(p=>p.userId),A=await o.findMany({model:"user",where:[{field:"id",value:d,operator:"in"}]}),K=new Map(A.map(p=>[p.id,p])),u=s.map(p=>{let l=K.get(p.userId);if(!l)throw new ee("Unexpected error: User not found for member");return{...p,user:{id:l.id,name:l.name,email:l.email,image:l.image}}});return{...n,invitations:a,members:u}},listOrganizations:async i=>{let r=await o.findMany({model:"member",where:[{field:"userId",value:i}]});if(!r||r.length===0)return[];let n=r.map(s=>s.organizationId);return await o.findMany({model:"organization",where:[{field:"id",value:n,operator:"in"}]})},createInvitation:async({invitation:i,user:r})=>{let a=R(t?.invitationExpiresIn||1728e5);return await o.create({model:"invitation",data:{email:i.email,role:i.role,organizationId:i.organizationId,status:"pending",expiresAt:a,inviterId:r.id}})},findInvitationById:async i=>await o.findOne({model:"invitation",where:[{field:"id",value:i}]}),findPendingInvitation:async i=>(await o.findMany({model:"invitation",where:[{field:"email",value:i.email},{field:"organizationId",value:i.organizationId},{field:"status",value:"pending"}]})).filter(n=>new Date(n.expiresAt)>new Date),updateInvitation:async i=>await o.update({model:"invitation",where:[{field:"id",value:i.invitationId}],update:{status:i.status}})}};var gA=require("better-call");var B=P(async e=>({})),V=P({use:[v]},async e=>({session:e.context.session}));var W=require("zod");var E=require("zod");var ut=E.z.string(),Sr=E.z.enum(["pending","accepted","rejected","canceled"]).default("pending"),CA=E.z.object({id:E.z.string().default(_),name:E.z.string(),slug:E.z.string(),logo:E.z.string().nullish(),metadata:E.z.record(E.z.string()).or(E.z.string().transform(e=>JSON.parse(e))).nullish(),createdAt:E.z.date()}),bA=E.z.object({id:E.z.string().default(_),organizationId:E.z.string(),userId:E.z.string(),role:ut,createdAt:E.z.date()}),vA=E.z.object({id:E.z.string().default(_),organizationId:E.z.string(),email:E.z.string(),role:ut,status:Sr,inviterId:E.z.string(),expiresAt:E.z.date()});var j=require("better-call"),lt=e=>c("/organization/invite-member",{method:"POST",use:[B,V],body:W.z.object({email:W.z.string({description:"The email address of the user to invite"}),role:W.z.string({description:"The role to assign to the user"}),organizationId:W.z.string({description:"The organization ID to invite the user to"}).optional(),resend:W.z.boolean({description:"Resend the invitation email, if the user is already invited"}).optional()}),metadata:{openapi:{description:"Invite a user to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt"]}}}}}}}},async t=>{if(!t.context.orgOptions.sendInvitationEmail)throw t.context.logger.warn("Invitation email is not enabled. Pass `sendInvitationEmail` to the plugin options to enable it."),new j.APIError("BAD_REQUEST",{message:"Invitation email is not enabled"});let o=t.context.session,i=t.body.organizationId||o.session.activeOrganizationId;if(!i)throw new j.APIError("BAD_REQUEST",{message:"Organization not found"});let r=z(t.context,t.context.orgOptions),n=await r.findMemberByOrgId({userId:o.user.id,organizationId:i});if(!n)throw new j.APIError("BAD_REQUEST",{message:"Member not found!"});let a=t.context.roles[n.role];if(!a)throw new j.APIError("BAD_REQUEST",{message:"Role not found!"});if(a.authorize({invitation:["create"]}).error)throw new j.APIError("FORBIDDEN",{message:"You are not allowed to invite members"});if(await r.findMemberByEmail({email:t.body.email,organizationId:i}))throw new j.APIError("BAD_REQUEST",{message:"User is already a member of this organization"});if((await r.findPendingInvitation({email:t.body.email,organizationId:i})).length&&!t.body.resend)throw new j.APIError("BAD_REQUEST",{message:"User is already invited to this organization"});let K=await r.createInvitation({invitation:{role:t.body.role,email:t.body.email,organizationId:i},user:o.user}),u=await r.findOrganizationById(i);if(!u)throw new j.APIError("BAD_REQUEST",{message:"Organization not found"});return await t.context.orgOptions.sendInvitationEmail?.({id:K.id,role:K.role,email:K.email,organization:u,inviter:{...n,user:o.user}},t.request),t.json(K)}),gt=c("/organization/accept-invitation",{method:"POST",body:W.z.object({invitationId:W.z.string({description:"The ID of the invitation to accept"})}),use:[B,V],metadata:{openapi:{description:"Accept an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"},member:{type:"object"}}}}}}}}}},async e=>{let t=e.context.session,o=z(e.context,e.context.orgOptions),i=await o.findInvitationById(e.body.invitationId);if(!i||i.expiresAt<new Date||i.status!=="pending")throw new j.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(i.email!==t.user.email)throw new j.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let r=await o.updateInvitation({invitationId:e.body.invitationId,status:"accepted"}),n=await o.createMember({organizationId:i.organizationId,userId:t.user.id,role:i.role,createdAt:new Date});return await o.setActiveOrganization(t.session.token,i.organizationId),r?e.json({invitation:r,member:n}):e.json(null,{status:400,body:{message:"Invitation not found!"}})}),mt=c("/organization/reject-invitation",{method:"POST",body:W.z.object({invitationId:W.z.string({description:"The ID of the invitation to reject"})}),use:[B,V],metadata:{openapi:{description:"Reject an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"},member:{type:"null"}}}}}}}}}},async e=>{let t=e.context.session,o=z(e.context,e.context.orgOptions),i=await o.findInvitationById(e.body.invitationId);if(!i||i.expiresAt<new Date||i.status!=="pending")throw new j.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(i.email!==t.user.email)throw new j.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let r=await o.updateInvitation({invitationId:e.body.invitationId,status:"rejected"});return e.json({invitation:r,member:null})}),ft=c("/organization/cancel-invitation",{method:"POST",body:W.z.object({invitationId:W.z.string({description:"The ID of the invitation to cancel"})}),use:[B,V],openapi:{description:"Cancel an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"}}}}}}}}},async e=>{let t=e.context.session,o=z(e.context,e.context.orgOptions),i=await o.findInvitationById(e.body.invitationId);if(!i)throw new j.APIError("BAD_REQUEST",{message:"Invitation not found!"});let r=await o.findMemberByOrgId({userId:t.user.id,organizationId:i.organizationId});if(!r)throw new j.APIError("BAD_REQUEST",{message:"Member not found!"});if(e.context.roles[r.role].authorize({invitation:["cancel"]}).error)throw new j.APIError("FORBIDDEN",{message:"You are not allowed to cancel this invitation"});let a=await o.updateInvitation({invitationId:e.body.invitationId,status:"canceled"});return e.json(a)}),ht=c("/organization/get-invitation",{method:"GET",use:[B],requireHeaders:!0,query:W.z.object({id:W.z.string({description:"The ID of the invitation to get"})}),metadata:{openapi:{description:"Get an invitation by ID",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"},organizationName:{type:"string"},organizationSlug:{type:"string"},inviterEmail:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt","organizationName","organizationSlug","inviterEmail"]}}}}}}}},async e=>{let t=await U(e);if(!t)throw new j.APIError("UNAUTHORIZED",{message:"Not authenticated"});let o=z(e.context,e.context.orgOptions),i=await o.findInvitationById(e.query.id);if(!i||i.status!=="pending"||i.expiresAt<new Date)throw new j.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(i.email!==t.user.email)throw new j.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let r=await o.findOrganizationById(i.organizationId);if(!r)throw new j.APIError("BAD_REQUEST",{message:"Organization not found"});let n=await o.findMemberByOrgId({userId:i.inviterId,organizationId:i.organizationId});if(!n)throw new j.APIError("BAD_REQUEST",{message:"Inviter is no longer a member of the organization"});return e.json({...i,organizationName:r.name,organizationSlug:r.slug,inviterEmail:n.user.email})});var te=require("zod");var ge=require("better-call");var yt=()=>c("/organization/add-member",{method:"POST",body:te.z.object({userId:te.z.string(),role:te.z.string(),organizationId:te.z.string().optional()}),use:[B],metadata:{SERVER_ONLY:!0}},async e=>{let t=e.body.userId?await U(e).catch(s=>null):null,o=e.body.organizationId||t?.session.activeOrganizationId;if(!o)return e.json(null,{status:400,body:{message:"No active organization found!"}});let i=z(e.context,e.context.orgOptions),r=await e.context.internalAdapter.findUserById(e.body.userId);if(!r)throw new ge.APIError("BAD_REQUEST",{message:"User not found!"});if(await i.findMemberByEmail({email:r.email,organizationId:o}))throw new ge.APIError("BAD_REQUEST",{message:"User is already a member of this organization"});let a=await i.createMember({id:_(),organizationId:o,userId:r.id,role:e.body.role,createdAt:new Date});return e.json(a)}),wt=c("/organization/remove-member",{method:"POST",body:te.z.object({memberIdOrEmail:te.z.string({description:"The ID or email of the member to remove"}),organizationId:te.z.string({description:"The ID of the organization to remove the member from. If not provided, the active organization will be used"}).optional()}),use:[B,V],metadata:{openapi:{description:"Remove a member from an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{member:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}},required:["member"]}}}}}}}},async e=>{let t=e.context.session,o=e.body.organizationId||t.session.activeOrganizationId;if(!o)return e.json(null,{status:400,body:{message:"No active organization found!"}});let i=z(e.context,e.context.orgOptions),r=await i.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!r)throw new ge.APIError("BAD_REQUEST",{message:"Member not found!"});let n=e.context.roles[r.role];if(!n)throw new ge.APIError("BAD_REQUEST",{message:"Role not found!"});let a=t.user.email===e.body.memberIdOrEmail||r.id===e.body.memberIdOrEmail;if(a&&r.role===(e.context.orgOptions?.creatorRole||"owner"))throw new ge.APIError("BAD_REQUEST",{message:"You cannot leave the organization as the owner"});if(!(a||n.authorize({member:["delete"]}).success))throw new ge.APIError("UNAUTHORIZED",{message:"You are not allowed to delete this member"});let A=null;if(e.body.memberIdOrEmail.includes("@")?A=await i.findMemberByEmail({email:e.body.memberIdOrEmail,organizationId:o}):A=await i.findMemberById(e.body.memberIdOrEmail),A?.organizationId!==o)throw new ge.APIError("BAD_REQUEST",{message:"Member not found!"});return await i.deleteMember(A.id),t.user.id===A.userId&&t.session.activeOrganizationId===A.organizationId&&await i.setActiveOrganization(t.session.token,null),e.json({member:A})}),Ct=e=>c("/organization/update-member-role",{method:"POST",body:te.z.object({role:te.z.string(),memberId:te.z.string(),organizationId:te.z.string().optional()}),use:[B,V],metadata:{openapi:{description:"Update the role of a member in an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{member:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}},required:["member"]}}}}}}}},async t=>{let o=t.context.session,i=t.body.organizationId||o.session.activeOrganizationId;if(!i)return t.json(null,{status:400,body:{message:"No active organization found!"}});let r=z(t.context,t.context.orgOptions),n=await r.findMemberByOrgId({userId:o.user.id,organizationId:i});if(!n)return t.json(null,{status:400,body:{message:"Member not found!"}});let a=t.context.roles[n.role];if(!a)return t.json(null,{status:400,body:{message:"Role not found!"}});if(a.authorize({member:["update"]}).error||t.body.role==="owner"&&n.role!=="owner")return t.json(null,{body:{message:"You are not allowed to update this member"},status:403});let d=await r.updateMember(t.body.memberId,t.body.role);return d?t.json(d):t.json(null,{status:400,body:{message:"Member not found!"}})}),bt=c("/organization/get-active-member",{method:"GET",use:[B,V],metadata:{openapi:{description:"Get the active member in the organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}}}}}}}},async e=>{let t=e.context.session,o=t.session.activeOrganizationId;if(!o)return e.json(null,{status:400,body:{message:"No active organization found!"}});let r=await z(e.context,e.context.orgOptions).findMemberByOrgId({userId:t.user.id,organizationId:o});return r?e.json(r):e.json(null,{status:400,body:{message:"Member not found!"}})});var O=require("zod");var me=require("better-call");var vt=c("/organization/create",{method:"POST",body:O.z.object({name:O.z.string({description:"The name of the organization"}),slug:O.z.string({description:"The slug of the organization"}),userId:O.z.string({description:"The user id of the organization creator. If not provided, the current user will be used. Should only be used by admins or when called by the server."}).optional(),logo:O.z.string({description:"The logo of the organization"}).optional(),metadata:O.z.record(O.z.string(),O.z.any(),{description:"The metadata of the organization"}).optional()}),use:[B,V],metadata:{openapi:{description:"Create an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization that was created",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=e.context.session.user;if(!t)return e.json(null,{status:401});let o=e.context.orgOptions;if(!(typeof o?.allowUserToCreateOrganization=="function"?await o.allowUserToCreateOrganization(t):o?.allowUserToCreateOrganization===void 0?!0:o.allowUserToCreateOrganization))throw new me.APIError("FORBIDDEN",{message:"You are not allowed to create an organization"});let r=z(e.context,o),n=await r.listOrganizations(t.id);if(typeof o.organizationLimit=="number"?n.length>=o.organizationLimit:typeof o.organizationLimit=="function"?await o.organizationLimit(t):!1)throw new me.APIError("FORBIDDEN",{message:"You have reached the organization limit"});if(await r.findOrganizationBySlug(e.body.slug))throw new me.APIError("BAD_REQUEST",{message:"Organization with this slug already exists"});let d=await r.createOrganization({organization:{id:_(),slug:e.body.slug,name:e.body.name,logo:e.body.logo,createdAt:new Date,metadata:e.body.metadata},user:t});return await r.setActiveOrganization(e.context.session.session.token,d.id),e.json(d)}),kt=c("/organization/update",{method:"POST",body:O.z.object({data:O.z.object({name:O.z.string({description:"The name of the organization"}).optional(),slug:O.z.string({description:"The slug of the organization"}).optional(),logo:O.z.string({description:"The logo of the organization"}).optional(),metadata:O.z.record(O.z.string(),O.z.any(),{description:"The metadata of the organization"}).optional()}).partial(),organizationId:O.z.string().optional()}),requireHeaders:!0,use:[B],metadata:{openapi:{description:"Update an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The updated organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=await e.context.getSession(e);if(!t)throw new me.APIError("UNAUTHORIZED",{message:"User not found"});let o=e.body.organizationId||t.session.activeOrganizationId;if(!o)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let i=z(e.context,e.context.orgOptions),r=await i.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!r)return e.json(null,{status:400,body:{message:"User is not a member of this organization!"}});let n=e.context.roles[r.role];if(!n)return e.json(null,{status:400,body:{message:"Role not found!"}});if(n.authorize({organization:["update"]}).error)return e.json(null,{body:{message:"You are not allowed to update this organization"},status:403});let s=await i.updateOrganization(o,e.body.data);return e.json(s)}),Tt=c("/organization/delete",{method:"POST",body:O.z.object({organizationId:O.z.string({description:"The organization id to delete"})}),requireHeaders:!0,use:[B],metadata:{openapi:{description:"Delete an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string",description:"The organization id that was deleted"}}}}}}}},async e=>{let t=await e.context.getSession(e);if(!t)return e.json(null,{status:401});let o=e.body.organizationId;if(!o)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let i=z(e.context,e.context.orgOptions),r=await i.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!r)return e.json(null,{status:400,body:{message:"User is not a member of this organization!"}});let n=e.context.roles[r.role];if(!n)return e.json(null,{status:400,body:{message:"Role not found!"}});if(n.authorize({organization:["delete"]}).error)throw new me.APIError("FORBIDDEN",{message:"You are not allowed to delete this organization"});return o===t.session.activeOrganizationId&&await i.setActiveOrganization(t.session.token,null),await i.deleteOrganization(o),e.json(o)}),Ot=c("/organization/get-full-organization",{method:"GET",query:O.z.optional(O.z.object({organizationId:O.z.string({description:"The organization id to get"}).optional(),organizationSlug:O.z.string({description:"The organization slug to get"}).optional()})),requireHeaders:!0,use:[B,V],metadata:{openapi:{description:"Get the full organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=e.context.session,o=e.query?.organizationSlug||e.query?.organizationId||t.session.activeOrganizationId;if(!o)return e.json(null,{status:200});let r=await z(e.context,e.context.orgOptions).findFullOrganization({organizationId:o,isSlug:!!e.query?.organizationSlug});if(!r)throw new me.APIError("BAD_REQUEST",{message:"Organization not found"});return e.json(r)}),It=c("/organization/set-active",{method:"POST",body:O.z.object({organizationId:O.z.string({description:"The organization id to set as active. It can be null to unset the active organization"}).nullable().optional(),organizationSlug:O.z.string({description:"The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided"}).optional()}),use:[V,B],metadata:{openapi:{description:"Set the active organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=z(e.context,e.context.orgOptions),o=e.context.session,i=e.body.organizationSlug||e.body.organizationId;if(i===null){if(!o.session.activeOrganizationId)return e.json(null);let d=await t.setActiveOrganization(o.session.token,null);return await m(e,{session:d,user:o.user}),e.json(null)}if(!i){let s=o.session.activeOrganizationId;if(!s)return e.json(null);i=s}let r=await t.findFullOrganization({organizationId:i,isSlug:!!e.body.organizationSlug});if(!r?.members.find(s=>s.userId===o.user.id))throw await t.setActiveOrganization(o.session.token,null),new me.APIError("FORBIDDEN",{message:"You are not a member of this organization"});let a=await t.setActiveOrganization(o.session.token,i);return await m(e,{session:a,user:o.user}),e.json(r)}),Ut=c("/organization/list",{method:"GET",use:[B,V],metadata:{openapi:{description:"List all organizations",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Organization"}}}}}}}}},async e=>{let o=await z(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(o)});var Dr=lo({name:["action"]}),XA=Dr.newRole({name:["action"]}),xr=e=>{let t={createOrganization:vt,updateOrganization:kt,deleteOrganization:Tt,setActiveOrganization:It,getFullOrganization:Ot,listOrganizations:Ut,createInvitation:lt(e),cancelInvitation:ft,acceptInvitation:gt,getInvitation:ht,rejectInvitation:mt,addMember:yt(),removeMember:wt,updateMemberRole:Ct(e),getActiveMember:bt},o={...pt,...e?.roles};return{id:"organization",endpoints:{...Kt(t,{orgOptions:e||{},roles:o,getSession:async r=>await U(r)}),hasPermission:c("/organization/has-permission",{method:"POST",requireHeaders:!0,body:De.z.object({permission:De.z.record(De.z.string(),De.z.array(De.z.string()))}),use:[V],metadata:{openapi:{description:"Check if the user has permission",requestBody:{content:{"application/json":{schema:{type:"object",properties:{permission:{type:"object",description:"The permission to check"}},required:["permission"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},success:{type:"boolean"}},required:["success"]}}}}}}}},async r=>{if(!r.context.session.session.activeOrganizationId)throw new xo.APIError("BAD_REQUEST",{message:"No active organization"});let a=await z(r.context).findMemberByOrgId({userId:r.context.session.user.id,organizationId:r.context.session.session.activeOrganizationId||""});if(!a)throw new xo.APIError("UNAUTHORIZED",{message:"You are not a member of this organization"});let d=o[a.role].authorize(r.body.permission);return d.error?r.json({error:d.error,success:!1},{status:403}):r.json({error:null,success:!0})})},schema:{session:{fields:{activeOrganizationId:{type:"string",required:!1,fieldName:e?.schema?.session?.fields?.activeOrganizationId}}},organization:{modelName:e?.schema?.organization?.modelName,fields:{name:{type:"string",required:!0,fieldName:e?.schema?.organization?.fields?.name},slug:{type:"string",unique:!0,fieldName:e?.schema?.organization?.fields?.slug},logo:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.logo},createdAt:{type:"date",required:!0,fieldName:e?.schema?.organization?.fields?.createdAt},metadata:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.metadata}}},member:{modelName:e?.schema?.member?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.member?.fields?.organizationId},userId:{type:"string",required:!0,fieldName:e?.schema?.member?.fields?.userId,references:{model:"user",field:"id"}},role:{type:"string",required:!0,defaultValue:"member",fieldName:e?.schema?.member?.fields?.role},createdAt:{type:"date",required:!0,fieldName:e?.schema?.member?.fields?.createdAt}}},invitation:{modelName:e?.schema?.invitation?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.invitation?.fields?.organizationId},email:{type:"string",required:!0,fieldName:e?.schema?.invitation?.fields?.email},role:{type:"string",required:!1,fieldName:e?.schema?.invitation?.fields?.role},status:{type:"string",required:!0,defaultValue:"pending",fieldName:e?.schema?.invitation?.fields?.status},expiresAt:{type:"date",required:!0,fieldName:e?.schema?.invitation?.fields?.expiresAt},inviterId:{type:"string",references:{model:"user",field:"id"},fieldName:e?.schema?.invitation?.fields?.inviterId,required:!0}}}},$Infer:{Organization:{},Invitation:{},Member:{},ActiveOrganization:{}}}};var jo=Yo(require("uncrypto"),1);function jr(e){return e.toString(2).padStart(8,"0")}function zr(e){return[...e].map(t=>jr(t)).join("")}function Rt(e){return parseInt(zr(e),2)}function Br(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,o=t%8,i=new Uint8Array(Math.ceil(t/8));jo.default.getRandomValues(i),o!==0&&(i[0]&=(1<<o)-1);let r=Rt(i);for(;r>=e;)jo.default.getRandomValues(i),o!==0&&(i[0]&=(1<<o)-1),r=Rt(i);return r}function Q(e,t){let o="";for(let i=0;i<e;i++)o+=t[Br(t.length)];return o}function $(...e){let t=new Set(e),o="";for(let i of t)i==="a-z"?o+="abcdefghijklmnopqrstuvwxyz":i==="A-Z"?o+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":i==="0-9"?o+="0123456789":o+=i;return o}var We=require("zod");var Bo=require("@noble/ciphers/chacha"),xe=require("@noble/ciphers/utils"),No=require("@noble/ciphers/webcrypto"),Lo=require("oslo/crypto"),zo=Yo(require("uncrypto"),1);var Pt=require("oslo/encoding");var Nr=require("@noble/hashes/scrypt"),Lr=require("uncrypto");async function Qe(e,t){let o=new TextEncoder,i={name:"HMAC",hash:"SHA-256"},r=await zo.default.subtle.importKey("raw",o.encode(e),i,!1,["sign","verify"]),n=await zo.default.subtle.sign(i.name,r,o.encode(t));return btoa(String.fromCharCode(...new Uint8Array(n)))}var ue=async({key:e,data:t})=>{let o=await(0,Lo.sha256)(new TextEncoder().encode(e)),i=(0,xe.utf8ToBytes)(t),r=(0,No.managedNonce)(Bo.xchacha20poly1305)(new Uint8Array(o));return(0,xe.bytesToHex)(r.encrypt(i))},fe=async({key:e,data:t})=>{let o=await(0,Lo.sha256)(new TextEncoder().encode(e)),i=(0,xe.hexToBytes)(t),r=(0,No.managedNonce)(Bo.xchacha20poly1305)(new Uint8Array(o));return new TextDecoder().decode(r.decrypt(i))};var Ae=require("zod");var je=require("better-call");var go="two_factor";var mo="trust_device";var _o=require("zod");var be=P({body:_o.z.object({trustDevice:_o.z.boolean().optional()})},async e=>{let t=await U(e);if(!t){let o=e.context.createAuthCookie(go),i=await e.getSignedCookie(o.name,e.context.secret);if(!i)throw new je.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let r=await e.context.internalAdapter.findUserById(i);if(!r)throw new je.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let n=await e.context.internalAdapter.createSession(i,e.request);if(!n)throw new je.APIError("INTERNAL_SERVER_ERROR",{message:"failed to create session"});return{valid:async()=>{if(await m(e,{session:n,user:r}),e.body.trustDevice){let a=e.context.createAuthCookie(mo,{maxAge:2592e3}),s=await Qe(e.context.secret,`${r.id}!${n.token}`);await e.setSignedCookie(a.name,`${s}!${n.token}`,e.context.secret,a.attributes)}return e.json({session:n,user:r})},invalid:async()=>{throw new je.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:{id:n.token,userId:n.userId,expiresAt:n.expiresAt,user:r}}}return{valid:async()=>e.json({session:t,user:t.user}),invalid:async()=>{throw new je.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:t}});var ze=require("better-call");function _r(e){return Array.from({length:e?.amount??10}).fill(null).map(()=>Q(e?.length??10,$("a-z","0-9"))).map(t=>`${t.slice(0,5)}-${t.slice(5)}`)}async function Fo(e,t){let o=e,i=t?.customBackupCodesGenerate?t.customBackupCodesGenerate():_r(),r=await ue({data:JSON.stringify(i),key:o});return{backupCodes:i,encryptedBackupCodes:r}}async function Fr(e,t){let o=await Et(e.backupCodes,t);return o?{status:o.includes(e.code),updated:o.filter(i=>i!==e.code)}:{status:!1,updated:null}}async function Et(e,t){let o=Buffer.from(await fe({key:t,data:e})).toString("utf-8"),i=JSON.parse(o),r=Ae.z.array(Ae.z.string()).safeParse(i);return r.success?r.data:null}var St=(e,t)=>({id:"backup_code",endpoints:{verifyBackupCode:c("/two-factor/verify-backup-code",{method:"POST",body:Ae.z.object({code:Ae.z.string(),disableSession:Ae.z.boolean().optional()}),use:[be]},async o=>{let i=o.context.session.user,r=await o.context.adapter.findOne({model:t,where:[{field:"userId",value:i.id}]});if(!r)throw new ze.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let n=await Fr({backupCodes:r.backupCodes,code:o.body.code},o.context.secret);if(!n.status)throw new ze.APIError("UNAUTHORIZED",{message:"Invalid backup code"});let a=await ue({key:o.context.secret,data:JSON.stringify(n.updated)});return await o.context.adapter.update({model:t,update:{backupCodes:a},where:[{field:"userId",value:i.id}]}),o.body.disableSession||await m(o,{session:o.context.session.session,user:i}),o.json({user:i,session:o.context.session})}),generateBackupCodes:c("/two-factor/generate-backup-codes",{method:"POST",body:Ae.z.object({password:Ae.z.string()}),use:[v]},async o=>{let i=o.context.session.user;if(!i.twoFactorEnabled)throw new ze.APIError("BAD_REQUEST",{message:"Two factor isn't enabled"});await o.context.password.checkPassword(i.id,o);let r=await Fo(o.context.secret,e);return await o.context.adapter.update({model:t,update:{backupCodes:r.encryptedBackupCodes},where:[{field:"userId",value:o.context.session.user.id}]}),o.json({status:!0,backupCodes:r.backupCodes})}),viewBackupCodes:c("/two-factor/view-backup-codes",{method:"GET",body:Ae.z.object({userId:Ae.z.string()}),metadata:{SERVER_ONLY:!0}},async o=>{let i=await o.context.adapter.findOne({model:t,where:[{field:"userId",value:o.body.userId}]});if(!i)throw new ze.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let r=await Et(i.backupCodes,o.context.secret);if(!r)throw new ze.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});return o.json({status:!0,backupCodes:r})})}});var $e=require("better-call"),Dt=require("oslo/otp"),Vo=require("zod");var xt=require("oslo"),jt=(e,t)=>{let o={...e,period:new xt.TimeSpan(e?.period||3,"m")},i=new Dt.TOTPController({digits:6,period:o.period}),r=c("/two-factor/send-otp",{method:"POST",use:[be],metadata:{openapi:{summary:"Send two factor OTP",description:"Send two factor OTP to the user",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async a=>{if(!e||!e.sendOTP)throw a.context.logger.error("send otp isn't configured. Please configure the send otp function on otp options."),new $e.APIError("BAD_REQUEST",{message:"otp isn't configured"});let s=a.context.session.user,d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d)throw new $e.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});let A=await i.generate(Buffer.from(d.secret));return await e.sendOTP({user:s,otp:A},a.request),a.json({status:!0})}),n=c("/two-factor/verify-otp",{method:"POST",body:Vo.z.object({code:Vo.z.string({description:"The otp code to verify"})}),use:[be],metadata:{openapi:{summary:"Verify two factor OTP",description:"Verify two factor OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async a=>{let s=a.context.session.user;if(!s.twoFactorEnabled)throw new $e.APIError("BAD_REQUEST",{message:"two factor isn't enabled"});let d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d)throw new $e.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});return await i.generate(Buffer.from(d.secret))===a.body.code?a.context.valid():a.context.invalid()});return{id:"otp",endpoints:{sendTwoFactorOTP:r,verifyTwoFactorOTP:n}}};var ve=require("better-call"),zt=require("oslo"),Ge=require("oslo/otp"),Ze=require("zod");var Bt=(e,t)=>{let o={...e,digits:6,period:new zt.TimeSpan(e?.period||30,"s")},i=c("/totp/generate",{method:"POST",use:[v],metadata:{openapi:{summary:"Generate TOTP code",description:"Use this endpoint to generate a TOTP code",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{code:{type:"string"}}}}}}}}}},async a=>{if(!e)throw a.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new ve.APIError("BAD_REQUEST",{message:"totp isn't configured"});let s=a.context.session.user,d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d)throw new ve.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return{code:await new Ge.TOTPController(o).generate(Buffer.from(d.secret))}}),r=c("/two-factor/get-totp-uri",{method:"POST",use:[v],body:Ze.z.object({password:Ze.z.string({description:"User password"})}),metadata:{openapi:{summary:"Get TOTP URI",description:"Use this endpoint to get the TOTP URI",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{totpURI:{type:"string"}}}}}}}}}},async a=>{if(!e)throw a.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new ve.APIError("BAD_REQUEST",{message:"totp isn't configured"});let s=a.context.session.user,d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d||!s.twoFactorEnabled)throw new ve.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return await a.context.password.checkPassword(s.id,a),{totpURI:(0,Ge.createTOTPKeyURI)(e.issuer||a.context.appName,s.email,Buffer.from(d.secret),o)}}),n=c("/two-factor/verify-totp",{method:"POST",body:Ze.z.object({code:Ze.z.string({description:"The otp code to verify"})}),use:[be],metadata:{openapi:{summary:"Verify two factor TOTP",description:"Verify two factor TOTP",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async a=>{if(!e)throw a.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new ve.APIError("BAD_REQUEST",{message:"totp isn't configured"});let s=a.context.session.user,d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d)throw new ve.APIError("BAD_REQUEST",{message:"totp isn't enabled"});let A=new Ge.TOTPController(o),K=await fe({key:a.context.secret,data:d.secret}),u=Buffer.from(K);if(!await A.verify(a.body.code,u))return a.context.invalid();if(!s.twoFactorEnabled){let l=await a.context.internalAdapter.updateUser(s.id,{twoFactorEnabled:!0}),h=await a.context.internalAdapter.createSession(s.id,a.request,!1,a.context.session.session).catch(k=>{throw console.log(k),k});await a.context.internalAdapter.deleteSession(a.context.session.session.token),await m(a,{session:h,user:l})}return a.context.valid()});return{id:"totp",endpoints:{generateTOTP:i,getTOTPURI:r,verifyTOTP:n}}};var Vr=require("better-call");async function qo(e,t){let i=(await e.context.internalAdapter.findAccounts(t.userId))?.find(a=>a.providerId==="credential"),r=i?.password;return!i||!r?!1:await e.context.password.verify({hash:r,password:t.password})}var Mo=require("better-call"),_t=require("oslo/otp"),Ft=require("oslo");var Nt=require("better-call"),Be=async e=>{let t=e.context.returned;return t?t instanceof Response?t.status!==200?null:await t.clone().json():t instanceof Nt.APIError?null:t:null};var Lt={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 qr=e=>({id:"two-factor",$InferServerPlugin:{},atomListeners:[{matcher:t=>t.startsWith("/two-factor/"),signal:"$sessionSignal"}],pathMethods:{"/two-factor/disable":"POST","/two-factor/enable":"POST","/two-factor/send-otp":"POST","/two-factor/generate-backup-codes":"POST"},fetchPlugins:[{id:"two-factor",name:"two-factor",hooks:{async onSuccess(t){t.data?.twoFactorRedirect&&e?.onTwoFactorRedirect&&await e.onTwoFactorRedirect()}}}]});var Mr=e=>{let t={twoFactorTable:"twoFactor"},o=Bt({issuer:e?.issuer,...e?.totpOptions},t.twoFactorTable),i=St({...e?.backupCodeOptions},t.twoFactorTable),r=jt({...e?.otpOptions},t.twoFactorTable);return{id:"two-factor",endpoints:{...o.endpoints,...r.endpoints,...i.endpoints,enableTwoFactor:c("/two-factor/enable",{method:"POST",body:We.z.object({password:We.z.string({description:"User password"}).min(8)}),use:[v],metadata:{openapi:{summary:"Enable two factor authentication",description:"Use this endpoint to enable two factor authentication. This will generate a TOTP URI and backup codes. Once the user verifies the TOTP URI, the two factor authentication will be enabled.",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{totpURI:{type:"string",description:"TOTP URI"},backupCodes:{type:"array",items:{type:"string"},description:"Backup codes"}}}}}}}}}},async n=>{let a=n.context.session.user,{password:s}=n.body;if(!await qo(n,{password:s,userId:a.id}))throw new Mo.APIError("BAD_REQUEST",{message:"Invalid password"});let A=Q(16,$("a-z","0-9","-")),K=await ue({key:n.context.secret,data:A}),u=await Fo(n.context.secret,e?.backupCodeOptions);if(e?.skipVerificationOnEnable){let l=await n.context.internalAdapter.updateUser(a.id,{twoFactorEnabled:!0}),h=await n.context.internalAdapter.createSession(l.id,n.request,!1,n.context.session.session);await m(n,{session:h,user:a}),await n.context.internalAdapter.deleteSession(n.context.session.session.token)}await n.context.adapter.deleteMany({model:t.twoFactorTable,where:[{field:"userId",value:a.id}]}),await n.context.adapter.create({model:t.twoFactorTable,data:{secret:K,backupCodes:u.encryptedBackupCodes,userId:a.id}});let p=(0,_t.createTOTPKeyURI)(e?.issuer||"BetterAuth",a.email,Buffer.from(A),{digits:e?.totpOptions?.digits||6,period:new Ft.TimeSpan(e?.totpOptions?.period||30,"s")});return n.json({totpURI:p,backupCodes:u.backupCodes})}),disableTwoFactor:c("/two-factor/disable",{method:"POST",body:We.z.object({password:We.z.string({description:"User password"}).min(8)}),use:[v],metadata:{openapi:{summary:"Disable two factor authentication",description:"Use this endpoint to disable two factor authentication.",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async n=>{let a=n.context.session.user,{password:s}=n.body;if(!await qo(n,{password:s,userId:a.id}))throw new Mo.APIError("BAD_REQUEST",{message:"Invalid password"});await n.context.internalAdapter.updateUser(a.id,{twoFactorEnabled:!1}),await n.context.adapter.delete({model:t.twoFactorTable,where:[{field:"userId",value:a.id}]});let A=await n.context.internalAdapter.createSession(a.id,n.request,!1,n.context.session.session);return await m(n,{session:A,user:a}),await n.context.internalAdapter.deleteSession(n.context.session.session.token),n.json({status:!0})})},options:e,hooks:{after:[{matcher(n){return n.path==="/sign-in/email"||n.path==="/sign-in/username"},handler:P(async n=>{let a=await Be(n);if(!a||!a.user.twoFactorEnabled)return;let s=n.context.createAuthCookie(mo),d=await n.getSignedCookie(s.name,n.context.secret);if(d){let[K,u]=d.split("!"),p=await Qe(n.context.secret,`${a.user.id}!${u}`);if(K===p){let l=await Qe(n.context.secret,`${a.user.id}!${a.session.token}`);await n.setSignedCookie(s.name,`${l}!${a.session.token}`,n.context.secret,s.attributes);return}}M(n),await n.context.internalAdapter.deleteSession(a.session.token);let A=n.context.createAuthCookie(go,{maxAge:60*10});return await n.setSignedCookie(A.name,a.user.id,n.context.secret,A.attributes),n.json({twoFactorRedirect:!0})})}]},schema:ie(Lt,e?.schema),rateLimit:[{pathMatcher(n){return n.startsWith("/two-factor/")},window:10,max:3}]}};var he=require("@simplewebauthn/server"),Z=require("better-call");var Y=require("zod");var Ne=require("@simplewebauthn/browser");var Qr=require("@better-fetch/fetch");var cK=require("nanostores");var Xc=require("@better-fetch/fetch");var Hr=require("nanostores");var eK=require("@better-fetch/fetch"),fo=require("nanostores"),Ho=(e,t,o,i)=>{let r=(0,fo.atom)({data:null,error:null,isPending:!0,isRefetching:!1}),n=()=>{let s=typeof i=="function"?i({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):i;return o(t,{...s,async onSuccess(d){r.set({data:d.data,error:null,isPending:!1,isRefetching:!1}),await s?.onSuccess?.(d)},async onError(d){r.set({error:d.error,data:null,isPending:!1,isRefetching:!1}),await s?.onError?.(d)},async onRequest(d){let A=r.get();r.set({isPending:A.data===null,data:A.data,error:null,isRefetching:!0}),await s?.onRequest?.(d)}})};e=Array.isArray(e)?e:[e];let a=!1;for(let s of e)s.subscribe(()=>{a?n():(0,fo.onMount)(r,()=>(n(),a=!0,()=>{r.off(),s.off()}))});return r};var Vt=require("nanostores"),qt=(e,{$listPasskeys:t})=>({signIn:{passkey:async(r,n)=>{let a=await e("/passkey/generate-authenticate-options",{method:"POST",body:{email:r?.email}});if(!a.data)return a;try{let s=await(0,Ne.startAuthentication)(a.data,r?.autoFill||!1),d=await e("/passkey/verify-authentication",{body:{response:s},...r?.fetchOptions,...n,method:"POST"});if(!d.data)return d}catch{return{data:null,error:{message:"auth cancelled",status:400,statusText:"BAD_REQUEST"}}}}},passkey:{addPasskey:async(r,n)=>{let a=await e("/passkey/generate-register-options",{method:"GET"});if(!a.data)return a;try{let s=await(0,Ne.startRegistration)(a.data),d=await e("/passkey/verify-registration",{...r?.fetchOptions,...n,body:{response:s,name:r?.name},method:"POST"});if(!d.data)return d;t.set(Math.random())}catch(s){return s instanceof Ne.WebAuthnError?s.code==="ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED"?{data:null,error:{message:"previously registered",status:400,statusText:"BAD_REQUEST"}}:s.code==="ERROR_CEREMONY_ABORTED"?{data:null,error:{message:"registration cancelled",status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:s.message,status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:s instanceof Error?s.message:"unknown error",status:500,statusText:"INTERNAL_SERVER_ERROR"}}}}},$Infer:{}}),$r=()=>{let e=(0,Vt.atom)();return{id:"passkey",$InferServerPlugin:{},getActions:t=>qt(t,{$listPasskeys:e}),getAtoms(t){return{listPasskeys:Ho(e,"/passkey/list-user-passkeys",t,{method:"GET"}),$listPasskeys:e}},pathMethods:{"/passkey/register":"POST","/passkey/authenticate":"POST"},atomListeners:[{matcher(t){return t==="/passkey/verify-registration"||t==="/passkey/delete-passkey"||t==="/passkey/update-passkey"},signal:"_listPasskeys"}]}};var Zr=e=>{let t=ne.BETTER_AUTH_URL,o=e?.rpID||t?.replace("http://","").replace("https://","").split(":")[0]||"localhost";if(!o)throw new ee("passkey rpID not found. Please provide a rpID in the options or set the BETTER_AUTH_URL environment variable.");let i={origin:null,...e,rpID:o,advanced:{webAuthnChallengeCookie:"better-auth-passkey",...e?.advanced}},r=new Date(Date.now()+1e3*60*5),n=new Date,a=Math.floor((r.getTime()-n.getTime())/1e3);return{id:"passkey",endpoints:{generatePasskeyRegistrationOptions:c("/passkey/generate-register-options",{method:"GET",use:[Me],metadata:{client:!1,openapi:{description:"Generate registration options for a new passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{challenge:{type:"string"},rp:{type:"object",properties:{name:{type:"string"},id:{type:"string"}}},user:{type:"object",properties:{id:{type:"string"},name:{type:"string"},displayName:{type:"string"}}},pubKeyCredParams:{type:"array",items:{type:"object",properties:{type:{type:"string"},alg:{type:"number"}}}},timeout:{type:"number"},excludeCredentials:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string"},transports:{type:"array",items:{type:"string"}}}}},authenticatorSelection:{type:"object",properties:{authenticatorAttachment:{type:"string"},requireResidentKey:{type:"boolean"},userVerification:{type:"string"}}},attestation:{type:"string"},extensions:{type:"object"}}}}}}}}}},async s=>{let d=s.context.session,A=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}),K=new Uint8Array(Buffer.from(Q(32,$("a-z","0-9")))),u;u=await(0,he.generateRegistrationOptions)({rpName:i.rpName||s.context.appName,rpID:i.rpID,userID:K,userName:d.user.email||d.user.id,attestationType:"none",excludeCredentials:A.map(l=>({id:l.id,transports:l.transports?.split(",")})),authenticatorSelection:{residentKey:"preferred",userVerification:"preferred",authenticatorAttachment:"platform"}});let p=_(32);return await s.setSignedCookie(i.advanced.webAuthnChallengeCookie,p,s.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:a}),await s.context.internalAdapter.createVerificationValue({identifier:p,value:JSON.stringify({expectedChallenge:u.challenge,userData:{id:d.user.id}}),expiresAt:r}),s.json(u,{status:200})}),generatePasskeyAuthenticationOptions:c("/passkey/generate-authenticate-options",{method:"POST",body:Y.z.object({email:Y.z.string({description:"The email address of the user"}).optional()}).optional(),metadata:{openapi:{description:"Generate authentication options for a passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{challenge:{type:"string"},rp:{type:"object",properties:{name:{type:"string"},id:{type:"string"}}},user:{type:"object",properties:{id:{type:"string"},name:{type:"string"},displayName:{type:"string"}}},timeout:{type:"number"},allowCredentials:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string"},transports:{type:"array",items:{type:"string"}}}}},userVerification:{type:"string"},authenticatorSelection:{type:"object",properties:{authenticatorAttachment:{type:"string"},requireResidentKey:{type:"boolean"},userVerification:{type:"string"}}},extensions:{type:"object"}}}}}}}}}},async s=>{let d=await U(s),A=[];d&&(A=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}));let K=await(0,he.generateAuthenticationOptions)({rpID:i.rpID,userVerification:"preferred",...A.length?{allowCredentials:A.map(l=>({id:l.id,transports:l.transports?.split(",")}))}:{}}),u={expectedChallenge:K.challenge,userData:{id:d?.user.id||""}},p=_(32);return await s.setSignedCookie(i.advanced.webAuthnChallengeCookie,p,s.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:a}),await s.context.internalAdapter.createVerificationValue({identifier:p,value:JSON.stringify(u),expiresAt:r}),s.json(K,{status:200})}),verifyPasskeyRegistration:c("/passkey/verify-registration",{method:"POST",body:Y.z.object({response:Y.z.any({description:"The response from the authenticator"}),name:Y.z.string({description:"Name of the passkey"}).optional()}),use:[Me],metadata:{openapi:{description:"Verify registration of a new passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{$ref:"#/components/schemas/Passkey"}}}},400:{description:"Bad request"}}}}},async s=>{let d=e?.origin||s.headers?.get("origin")||"";if(!d)return s.json(null,{status:400});let A=s.body.response,K=await s.getSignedCookie(i.advanced.webAuthnChallengeCookie,s.context.secret);if(!K)throw new Z.APIError("BAD_REQUEST",{message:"Challenge not found"});let u=await s.context.internalAdapter.findVerificationValue(K);if(!u)return s.json(null,{status:400});let{expectedChallenge:p,userData:l}=JSON.parse(u.value);if(l.id!==s.context.session.user.id)throw new Z.APIError("UNAUTHORIZED",{message:"You are not authorized to register this passkey"});try{let h=await(0,he.verifyRegistrationResponse)({response:A,expectedChallenge:p,expectedOrigin:d,expectedRPID:e?.rpID}),{verified:k,registrationInfo:f}=h;if(!k||!f)return s.json(null,{status:400});let{credentialID:g,credentialPublicKey:b,counter:T,credentialDeviceType:N,credentialBackedUp:eo}=f,er=Buffer.from(b).toString("base64"),or={name:s.body.name,userId:l.id,webauthnUserID:s.context.generateId({model:"passkey"}),id:g,publicKey:er,counter:T,deviceType:N,transports:A.response.transports.join(","),backedUp:eo,createdAt:new Date},ir=await s.context.adapter.create({model:"passkey",data:or});return s.json(ir,{status:200})}catch(h){throw console.log(h),new Z.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to verify registration"})}}),verifyPasskeyAuthentication:c("/passkey/verify-authentication",{method:"POST",body:Y.z.object({response:Y.z.any()}),metadata:{openapi:{description:"Verify authentication of a passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async s=>{let d=e?.origin||s.headers?.get("origin")||"";if(!d)throw new Z.APIError("BAD_REQUEST",{message:"origin missing"});let A=s.body.response,K=await s.getSignedCookie(i.advanced.webAuthnChallengeCookie,s.context.secret);if(!K)throw new Z.APIError("BAD_REQUEST",{message:"Challenge not found"});let u=await s.context.internalAdapter.findVerificationValue(K);if(!u)throw new Z.APIError("BAD_REQUEST",{message:"Challenge not found"});let{expectedChallenge:p}=JSON.parse(u.value),l=await s.context.adapter.findOne({model:"passkey",where:[{field:"id",value:A.id}]});if(!l)throw new Z.APIError("UNAUTHORIZED",{message:"Passkey not found"});try{let h=await(0,he.verifyAuthenticationResponse)({response:A,expectedChallenge:p,expectedOrigin:d,expectedRPID:i.rpID,authenticator:{credentialID:l.id,credentialPublicKey:new Uint8Array(Buffer.from(l.publicKey,"base64")),counter:l.counter,transports:l.transports?.split(",")},requireUserVerification:!1}),{verified:k}=h;if(!k)throw new Z.APIError("UNAUTHORIZED",{message:"Authentication failed"});await s.context.adapter.update({model:"passkey",where:[{field:"id",value:l.id}],update:{counter:h.authenticationInfo.newCounter}});let f=await s.context.internalAdapter.createSession(l.userId,s.request);if(!f)throw new Z.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});let g=await s.context.internalAdapter.findUserById(l.userId);if(!g)throw new Z.APIError("INTERNAL_SERVER_ERROR",{message:"User not found"});return await m(s,{session:f,user:g}),s.json({session:f},{status:200})}catch(h){throw s.context.logger.error("Failed to verify authentication",h),new Z.APIError("BAD_REQUEST",{message:"Failed to verify authentication"})}}),listPasskeys:c("/passkey/list-user-passkeys",{method:"GET",use:[v]},async s=>{let d=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:s.context.session.user.id}]});return s.json(d,{status:200})}),deletePasskey:c("/passkey/delete-passkey",{method:"POST",body:Y.z.object({id:Y.z.string()}),use:[v]},async s=>(await s.context.adapter.delete({model:"passkey",where:[{field:"id",value:s.body.id}]}),s.json(null,{status:200}))),updatePasskey:c("/passkey/update-passkey",{method:"POST",body:Y.z.object({id:Y.z.string(),name:Y.z.string()}),use:[v]},async s=>{let d=await s.context.adapter.findOne({model:"passkey",where:[{field:"id",value:s.body.id}]});if(!d)throw new Z.APIError("NOT_FOUND",{message:"Passkey not found"});if(d.userId!==s.context.session.user.id)throw new Z.APIError("UNAUTHORIZED",{message:"You are not authorized to update this passkey"});let A=await s.context.adapter.update({model:"passkey",where:[{field:"id",value:s.body.id}],update:{name:s.body.name}});if(!A)throw new Z.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to update passkey"});return s.json({passkey:A},{status:200})})},schema:ie(Gr,e?.schema)}},Gr={passkey:{fields:{name:{type:"string",required:!1},publicKey:{type:"string",required:!0},userId:{type:"string",references:{model:"user",field:"id"},required:!0},webauthnUserID:{type:"string",required:!0},counter:{type:"number",required:!0},deviceType:{type:"string",required:!0},backedUp:{type:"boolean",required:!0},transports:{type:"string",required:!1},createdAt:{type:"date",required:!1}}}};var Je=require("zod");var Le=require("better-call");var Qo=()=>({id:"username",endpoints:{signInUsername:c("/sign-in/username",{method:"POST",body:Je.z.object({username:Je.z.string({description:"The username of the user"}),password:Je.z.string({description:"The password of the user"}),rememberMe:Je.z.boolean({description:"Remember the user session"}).optional()}),metadata:{openapi:{summary:"Sign in with username",description:"Sign in with username",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async e=>{let t=await e.context.adapter.findOne({model:"user",where:[{field:"username",value:e.body.username.toLowerCase()}]});if(!t)throw await e.context.password.hash(e.body.password),e.context.logger.error("User not found",{username:Qo}),new Le.APIError("UNAUTHORIZED",{message:"Invalid username or password"});if(!t.emailVerified&&e.context.options.emailAndPassword?.requireEmailVerification)throw await Oo(e,t),new Le.APIError("UNAUTHORIZED",{message:"Email not verified"});let o=await e.context.adapter.findOne({model:"account",where:[{field:"userId",value:t.id},{field:"providerId",value:"credential"}]});if(!o)throw new Le.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let i=o?.password;if(!i)throw e.context.logger.error("Password not found",{username:Qo}),new Le.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify({hash:i,password:e.body.password}))throw e.context.logger.error("Invalid password"),new Le.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let n=await e.context.internalAdapter.createSession(t.id,e.request,e.body.rememberMe===!1);return n?(await m(e,{session:n,user:t},e.body.rememberMe===!1),e.json({user:t,session:n})):e.json(null,{status:500,body:{message:"Failed to create session",status:500}})})},schema:{user:{fields:{username:{type:"string",required:!1,unique:!0,returned:!0}}}}});var Mt=require("better-call"),Wr=()=>({id:"bearer",hooks:{before:[{matcher(e){return!!(e.request?.headers.get("authorization")||e.headers?.get("authorization"))},handler:async e=>{let t=e.request?.headers.get("authorization")?.replace("Bearer ","")||e.headers?.get("authorization")?.replace("Bearer ","");if(!t)return;let o="";return t.includes(".")?o=t:o=await(0,Mt.serializeSigned)("",t,e.context.secret),e.request&&e.request.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${o.replace("=","")}`),e.headers&&e.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${o.replace("=","")}`),{context:e}}}]}});var ke=require("zod");var Ht=require("better-call");var Jr=e=>({id:"magic-link",endpoints:{signInMagicLink:c("/sign-in/magic-link",{method:"POST",requireHeaders:!0,body:ke.z.object({email:ke.z.string({description:"Email address to send the magic link"}).email(),callbackURL:ke.z.string({description:"URL to redirect after magic link verification"}).optional()}),metadata:{openapi:{description:"Sign in with magic link",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async t=>{let{email:o}=t.body;if(e.disableSignUp&&!await t.context.internalAdapter.findUserByEmail(o))throw new Ht.APIError("BAD_REQUEST",{message:"User not found"});let i=Q(32,$("a-z","A-Z"));await t.context.internalAdapter.createVerificationValue({identifier:i,value:o,expiresAt:new Date(Date.now()+(e.expiresIn||60*5)*1e3)});let r=`${t.context.baseURL}/magic-link/verify?token=${i}&callbackURL=${t.body.callbackURL||"/"}`;return await e.sendMagicLink({email:o,url:r,token:i},t.request),t.json({status:!0})}),magicLinkVerify:c("/magic-link/verify",{method:"GET",query:ke.z.object({token:ke.z.string({description:"Verification token"}),callbackURL:ke.z.string({description:"URL to redirect after magic link verification, if not provided will return session"}).optional()}),requireHeaders:!0,metadata:{openapi:{description:"Verify magic link",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async t=>{let{token:o,callbackURL:i}=t.query,r=i?.startsWith("http")?i:i?`${t.context.options.baseURL}${i}`:t.context.options.baseURL,n=await t.context.internalAdapter.findVerificationValue(o);if(!n)throw t.redirect(`${r}?error=INVALID_TOKEN`);if(n.expiresAt<new Date)throw await t.context.internalAdapter.deleteVerificationValue(n.id),t.redirect(`${r}?error=EXPIRED_TOKEN`);await t.context.internalAdapter.deleteVerificationValue(n.id);let a=n.value,s=await t.context.internalAdapter.findUserByEmail(a),d=s?.user.id||"";if(!s){if(e.disableSignUp)throw t.redirect(`${r}?error=USER_NOT_FOUND`);if(d=(await t.context.internalAdapter.createUser({email:a,emailVerified:!0,name:a})).id,!d)throw t.redirect(`${r}?error=USER_NOT_CREATED`)}let A=await t.context.internalAdapter.createSession(d,t.headers);if(!A)throw t.redirect(`${r}?error=SESSION_NOT_CREATED`);if(await m(t,{session:A,user:s?.user}),!i)return t.json({session:A,user:s?.user});throw t.redirect(i)})},rateLimit:[{pathMatcher(t){return t.startsWith("/sign-in/magic-link")||t.startsWith("/magic-link/verify")},window:e.rateLimit?.window||60,max:e.rateLimit?.max||5}]});var re=require("zod");var q=require("better-call");function Xr(e){return Q(e,$("0-9"))}var Yr=e=>{let t={expiresIn:e?.expiresIn||300,otpLength:e?.otpLength||6,...e,phoneNumber:"phoneNumber",phoneNumberVerified:"phoneNumberVerified",code:"code",createdAt:"createdAt"};return{id:"phone-number",endpoints:{signInPhoneNumber:c("/sign-in/phone-number",{method:"POST",body:re.z.object({phoneNumber:re.z.string({description:"Phone number to sign in"}),password:re.z.string({description:"Password to use for sign in"}),rememberMe:re.z.boolean({description:"Remember the session"}).optional()}),metadata:{openapi:{summary:"Sign in with phone number",description:"Use this endpoint to sign in with phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}},400:{description:"Invalid phone number or password"}}}}},async o=>{let{password:i,phoneNumber:r}=o.body;if(t.phoneNumberValidator&&!await t.phoneNumberValidator(o.body.phoneNumber))throw new q.APIError("BAD_REQUEST",{message:"Invalid phone number!"});let n=await o.context.adapter.findOne({model:"user",where:[{field:"phoneNumber",value:r}]});if(!n)throw new q.APIError("UNAUTHORIZED",{message:"Invalid phone number or password"});let s=(await o.context.internalAdapter.findAccountByUserId(n.id)).find(u=>u.providerId==="credential");if(!s)throw o.context.logger.error("Credential account not found",{phoneNumber:r}),new q.APIError("UNAUTHORIZED",{message:"Invalid password or password"});let d=s?.password;if(!d)throw o.context.logger.error("Password not found",{phoneNumber:r}),new q.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await o.context.password.verify({hash:d,password:i}))throw o.context.logger.error("Invalid password"),new q.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let K=await o.context.internalAdapter.createSession(n.id,o.headers,o.body.rememberMe===!1);if(!K)throw o.context.logger.error("Failed to create session"),new q.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await m(o,{session:K,user:n},o.body.rememberMe===!1),o.json({user:n,session:K})}),sendPhoneNumberOTP:c("/phone-number/send-otp",{method:"POST",body:re.z.object({phoneNumber:re.z.string({description:"Phone number to send OTP"})}),metadata:{openapi:{summary:"Send OTP to phone number",description:"Use this endpoint to send OTP to phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async o=>{if(!e?.sendOTP)throw o.context.logger.warn("sendOTP not implemented"),new q.APIError("NOT_IMPLEMENTED",{message:"sendOTP not implemented"});if(t.phoneNumberValidator&&!await t.phoneNumberValidator(o.body.phoneNumber))throw new q.APIError("BAD_REQUEST",{message:"Invalid phone number!"});let i=Xr(t.otpLength);return await o.context.internalAdapter.createVerificationValue({value:i,identifier:o.body.phoneNumber,expiresAt:R(t.expiresIn,"sec")}),await e.sendOTP({phoneNumber:o.body.phoneNumber,code:i},o.request),o.json({code:i},{body:{message:"Code sent"}})}),verifyPhoneNumber:c("/phone-number/verify",{method:"POST",body:re.z.object({phoneNumber:re.z.string({description:"Phone number to verify"}),code:re.z.string({description:"OTP code"}),disableSession:re.z.boolean({description:"Disable session creation after verification"}).optional(),updatePhoneNumber:re.z.boolean({description:"Check if there is a session and update the phone number"}).optional()}),metadata:{openapi:{summary:"Verify phone number",description:"Use this endpoint to verify phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}},400:{description:"Invalid OTP"}}}}},async o=>{let i=await o.context.internalAdapter.findVerificationValue(o.body.phoneNumber);if(!i||i.expiresAt<new Date)throw i&&i.expiresAt<new Date?(await o.context.internalAdapter.deleteVerificationValue(i.id),new q.APIError("BAD_REQUEST",{message:"OTP expired"})):new q.APIError("BAD_REQUEST",{message:"OTP not found"});if(i.value!==o.body.code)throw new q.APIError("BAD_REQUEST",{message:"Invalid OTP"});if(await o.context.internalAdapter.deleteVerificationValue(i.id),o.body.updatePhoneNumber){let n=await U(o);if(!n)throw new q.APIError("UNAUTHORIZED",{message:"Session not found"});let a=await o.context.internalAdapter.updateUser(n.user.id,{[t.phoneNumber]:o.body.phoneNumber,[t.phoneNumberVerified]:!0});return o.json({user:a,session:n.session})}let r=await o.context.adapter.findOne({model:"user",where:[{value:o.body.phoneNumber,field:t.phoneNumber}]});if(await e?.callbackOnVerification?.({phoneNumber:o.body.phoneNumber,user:r},o.request),r)r=await o.context.internalAdapter.updateUser(r.id,{[t.phoneNumberVerified]:!0});else if(e?.signUpOnVerification){if(r=await o.context.internalAdapter.createUser({email:e.signUpOnVerification.getTempEmail(o.body.phoneNumber),name:e.signUpOnVerification.getTempName?e.signUpOnVerification.getTempName(o.body.phoneNumber):o.body.phoneNumber,[t.phoneNumber]:o.body.phoneNumber,[t.phoneNumberVerified]:!0}),!r)throw new q.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"})}else return o.json(null);if(!r)throw new q.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to update user"});if(!o.body.disableSession){let n=await o.context.internalAdapter.createSession(r.id,o.request);if(!n)throw new q.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await m(o,{session:n,user:r}),o.json({user:r,session:n})}return o.json({user:r,session:null})})},schema:ie(en,e?.schema)}},en={user:{fields:{phoneNumber:{type:"string",required:!1,unique:!0,returned:!0},phoneNumberVerified:{type:"boolean",required:!1,returned:!0,input:!1}}}};var tp=require("zod");var on={user:{fields:{isAnonymous:{type:"boolean",required:!1}}}},tn=e=>({id:"anonymous",endpoints:{signInAnonymous:c("/sign-in/anonymous",{method:"POST",metadata:{openapi:{description:"Sign in anonymously",responses:{200:{description:"Sign in anonymously",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async t=>{let{emailDomainName:o=Ie(t.context.baseURL)}=e||{},i=t.context.generateId({model:"user"}),r=`temp-${i}@${o}`,n=await t.context.internalAdapter.createUser({id:i,email:r,emailVerified:!1,isAnonymous:!0,name:"Anonymous",createdAt:new Date,updatedAt:new Date});if(!n)return t.json(null,{status:500,body:{message:"Failed to create user",status:500}});let a=await t.context.internalAdapter.createSession(n.id,t.request);return a?(await m(t,{session:a,user:n}),t.json({user:n,session:a})):t.json(null,{status:400,body:{message:"Could not create session"}})})},hooks:{after:[{matcher(t){return t.path?.startsWith("/sign-in")||t.path?.startsWith("/sign-up")},handler:P(async t=>{let i=t.responseHeader.get("set-cookie"),r=t.context.authCookies.sessionToken.name,n=ao(i||"").get(r)?.value.split(".")[0];if(!n)return;let a=await U(t);if(!(!a||!a.user.isAnonymous)){if(t.path==="/sign-in/anonymous")throw new C.APIError("BAD_REQUEST",{message:"Anonymous users cannot sign in again anonymously"});if(e?.onLinkAccount){let s=await t.context.internalAdapter.findSession(n);if(!s)return;await e?.onLinkAccount?.({anonymousUser:a,newUser:s})}e?.disableDeleteAnonymousUser||await t.context.internalAdapter.deleteUser(a.user.id)}})}]},schema:ie(on,e?.schema)});var y=require("zod");var rn=e=>{let t={defaultRole:"user",adminRole:"admin",...e},o=P(async i=>{let r=await U(i);if(!r?.session)throw new C.APIError("UNAUTHORIZED");let n=r.user;if(!n.role||(Array.isArray(t.adminRole)?!t.adminRole.includes(n.role):n.role!==t.adminRole))throw new C.APIError("FORBIDDEN",{message:"Only admins can access this endpoint"});return{session:{user:n,session:r.session}}});return{id:"admin",init(i){return{options:{databaseHooks:{user:{create:{async before(r){if(e?.defaultRole!==!1)return{data:{role:e?.defaultRole??"user",...r}}}}},session:{create:{async before(r){let n=await i.internalAdapter.findUserById(r.userId);if(n.banned){if(n.banExpires&&n.banExpires.getTime()<Date.now()){await i.internalAdapter.updateUser(r.userId,{banned:!1,banReason:null,banExpires:null});return}return!1}}}}}}}},hooks:{after:[{matcher(i){return i.path==="/list-sessions"},handler:P(async i=>{let r=await Be(i);if(!r)return;let n=r.filter(a=>!a.impersonatedBy);return i.json(n)})}]},endpoints:{setRole:c("/admin/set-role",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"}),role:y.z.string({description:"The role to set. `admin` or `user` by default"})}),use:[o],metadata:{openapi:{operationId:"setRole",summary:"Set the role of a user",description:"Set the role of a user",responses:{200:{description:"User role updated",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{let r=await i.context.internalAdapter.updateUser(i.body.userId,{role:i.body.role});return i.json({user:r})}),createUser:c("/admin/create-user",{method:"POST",body:y.z.object({email:y.z.string({description:"The email of the user"}),password:y.z.string({description:"The password of the user"}),name:y.z.string({description:"The name of the user"}),role:y.z.string({description:"The role of the user"}),data:y.z.optional(y.z.record(y.z.any(),{description:"Extra fields for the user. Including custom additional fields."}))}),use:[o],metadata:{openapi:{operationId:"createUser",summary:"Create a new user",description:"Create a new user",responses:{200:{description:"User created",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{if(await i.context.internalAdapter.findUserByEmail(i.body.email))throw new C.APIError("BAD_REQUEST",{message:"User already exists"});let n=await i.context.internalAdapter.createUser({email:i.body.email,name:i.body.name,role:i.body.role,...i.body.data});if(!n)throw new C.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"});let a=await i.context.password.hash(i.body.password);return await i.context.internalAdapter.linkAccount({accountId:n.id,providerId:"credential",password:a,userId:n.id}),i.json({user:n})}),listUsers:c("/admin/list-users",{method:"GET",use:[o],query:y.z.object({searchValue:y.z.string({description:"The value to search for"}).optional(),searchField:y.z.enum(["email","name"],{description:"The field to search in, defaults to email. Can be `email` or `name`"}).optional(),searchOperator:y.z.enum(["contains","starts_with","ends_with"],{description:"The operator to use for the search. Can be `contains`, `starts_with` or `ends_with`"}).optional(),limit:y.z.string({description:"The number of users to return"}).or(y.z.number()).optional(),offset:y.z.string({description:"The offset to start from"}).or(y.z.number()).optional(),sortBy:y.z.string({description:"The field to sort by"}).optional(),sortDirection:y.z.enum(["asc","desc"],{description:"The direction to sort by"}).optional(),filterField:y.z.string({description:"The field to filter by"}).optional(),filterValue:y.z.string({description:"The value to filter by"}).or(y.z.number()).or(y.z.boolean()).optional(),filterOperator:y.z.enum(["eq","ne","lt","lte","gt","gte"],{description:"The operator to use for the filter"}).optional()}),metadata:{openapi:{operationId:"listUsers",summary:"List users",description:"List users",responses:{200:{description:"List of users",content:{"application/json":{schema:{type:"object",properties:{users:{type:"array",items:{$ref:"#/components/schemas/User"}}}}}}}}}}},async i=>{let r=[];i.query?.searchValue&&r.push({field:i.query.searchField||"email",operator:i.query.searchOperator||"contains",value:i.query.searchValue}),i.query?.filterValue&&r.push({field:i.query.filterField||"email",operator:i.query.filterOperator||"eq",value:i.query.filterValue});try{let n=await i.context.internalAdapter.listUsers(Number(i.query?.limit)||void 0,Number(i.query?.offset)||void 0,i.query?.sortBy?{field:i.query.sortBy,direction:i.query.sortDirection||"asc"}:void 0,r.length?r:void 0);return i.json({users:n})}catch(n){return console.log(n),i.json({users:[]})}}),listUserSessions:c("/admin/list-user-sessions",{method:"POST",use:[o],body:y.z.object({userId:y.z.string({description:"The user id"})}),metadata:{openapi:{operationId:"listUserSessions",summary:"List user sessions",description:"List user sessions",responses:{200:{description:"List of user sessions",content:{"application/json":{schema:{type:"object",properties:{sessions:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}}}}}}}},async i=>({sessions:await i.context.internalAdapter.listSessions(i.body.userId)})),unbanUser:c("/admin/unban-user",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"unbanUser",summary:"Unban a user",description:"Unban a user",responses:{200:{description:"User unbanned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{let r=await i.context.internalAdapter.updateUser(i.body.userId,{banned:!1});return i.json({user:r})}),banUser:c("/admin/ban-user",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"}),banReason:y.z.string({description:"The reason for the ban"}).optional(),banExpiresIn:y.z.number({description:"The number of seconds until the ban expires"}).optional()}),use:[o],metadata:{openapi:{operationId:"banUser",summary:"Ban a user",description:"Ban a user",responses:{200:{description:"User banned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{if(i.body.userId===i.context.session.user.id)throw new C.APIError("BAD_REQUEST",{message:"You cannot ban yourself"});let r=await i.context.internalAdapter.updateUser(i.body.userId,{banned:!0,banReason:i.body.banReason||e?.defaultBanReason||"No reason",banExpires:i.body.banExpiresIn?R(i.body.banExpiresIn,"sec"):e?.defaultBanExpiresIn?R(e.defaultBanExpiresIn,"sec"):void 0});return await i.context.internalAdapter.deleteSessions(i.body.userId),i.json({user:r})}),impersonateUser:c("/admin/impersonate-user",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"impersonateUser",summary:"Impersonate a user",description:"Impersonate a user",responses:{200:{description:"Impersonation session created",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{let r=await i.context.internalAdapter.findUserById(i.body.userId);if(!r)throw new C.APIError("NOT_FOUND",{message:"User not found"});let n=await i.context.internalAdapter.createSession(r.id,void 0,!0,{impersonatedBy:i.context.session.user.id,expiresAt:e?.impersonationSessionDuration?R(e.impersonationSessionDuration,"sec"):R(60*60,"sec")});if(!n)throw new C.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await m(i,{session:n,user:r},!0),i.json({session:n,user:r})}),revokeUserSession:c("/admin/revoke-user-session",{method:"POST",body:y.z.object({sessionToken:y.z.string({description:"The session token"})}),use:[o],metadata:{openapi:{operationId:"revokeUserSession",summary:"Revoke a user session",description:"Revoke a user session",responses:{200:{description:"Session revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async i=>(await i.context.internalAdapter.deleteSession(i.body.sessionToken),i.json({success:!0}))),revokeUserSessions:c("/admin/revoke-user-sessions",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"revokeUserSessions",summary:"Revoke all user sessions",description:"Revoke all user sessions",responses:{200:{description:"Sessions revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async i=>(await i.context.internalAdapter.deleteSessions(i.body.userId),i.json({success:!0}))),removeUser:c("/admin/remove-user",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"removeUser",summary:"Remove a user",description:"Delete a user and all their sessions and accounts. Cannot be undone.",responses:{200:{description:"User removed",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async i=>(await i.context.internalAdapter.deleteUser(i.body.userId),i.json({success:!0})))},schema:ie(nn,t.schema)}},nn={user:{fields:{role:{type:"string",required:!1,input:!1},banned:{type:"boolean",defaultValue:!1,required:!1,input:!1},banReason:{type:"string",required:!1,input:!1},banExpires:{type:"date",required:!1,input:!1}}},session:{fields:{impersonatedBy:{type:"string",required:!1}}}};var se=require("zod"),_e=require("better-call");var ho=require("@better-fetch/fetch");var Qt=require("oslo/jwt");async function sn(e,t,o){if(t==="oidc"&&e.idToken){let r=(0,Qt.parseJWT)(e.idToken);if(r?.payload)return{id:r.payload.sub,emailVerified:r.payload.email_verified,...r.payload}}if(!o)return null;let i=await(0,ho.betterFetch)(o,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});return{id:i.data?.sub,emailVerified:i.data?.email_verified,email:i.data?.email,...i.data}}var an=e=>({id:"generic-oauth",endpoints:{signInWithOAuth2:c("/sign-in/oauth2",{method:"POST",query:se.z.object({currentURL:se.z.string({description:"Redirect to the current URL after sign in"}).optional()}).optional(),body:se.z.object({providerId:se.z.string({description:"The provider ID for the OAuth provider"}),callbackURL:se.z.string({description:"The URL to redirect to after sign in"}).optional(),errorCallbackURL:se.z.string({description:"The URL to redirect to if an error occurs"}).optional()}),metadata:{openapi:{description:"Sign in with OAuth2",responses:{200:{description:"Sign in with OAuth2",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}}}}}}}}}},async t=>{let{providerId:o}=t.body,i=e.config.find(N=>N.providerId===o);if(!i)throw new _e.APIError("BAD_REQUEST",{message:`No config found for provider ${o}`});let{discoveryUrl:r,authorizationUrl:n,tokenUrl:a,clientId:s,clientSecret:d,scopes:A,redirectURI:K,responseType:u,pkce:p,prompt:l,accessType:h}=i,k=n,f=a;if(r){let N=await(0,ho.betterFetch)(r,{onError(eo){t.context.logger.error(eo.error.message,eo.error,{discoveryUrl:r})}});N.data&&(k=N.data.authorization_endpoint,f=N.data.token_endpoint)}if(!k||!f)throw new _e.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let{state:g,codeVerifier:b}=await Ue(t),T=await S({id:o,options:{clientId:s,clientSecret:d,redirectURI:K},authorizationEndpoint:k,state:g,codeVerifier:p?b:void 0,scopes:A||[],redirectURI:`${t.context.baseURL}/oauth2/callback/${o}`});return u&&u!=="code"&&T.searchParams.set("response_type",u),l&&T.searchParams.set("prompt",l),h&&T.searchParams.set("access_type",h),t.json({url:T.toString(),redirect:!0})}),oAuth2Callback:c("/oauth2/callback/:providerId",{method:"GET",query:se.z.object({code:se.z.string({description:"The OAuth2 code"}).optional(),error:se.z.string({description:"The error message, if any"}).optional(),state:se.z.string({description:"The state parameter from the OAuth2 request"})}),metadata:{openapi:{description:"OAuth2 callback",responses:{200:{description:"OAuth2 callback",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"}}}}}}}}}},async t=>{if(t.query.error||!t.query.code)throw t.redirect(`${t.context.baseURL}?error=${t.query.error||"oAuth_code_missing"}`);let o=e.config.find(g=>g.providerId===t.params.providerId);if(!o)throw new _e.APIError("BAD_REQUEST",{message:`No config found for provider ${t.params.providerId}`});let i,r=await co(t),{callbackURL:n,codeVerifier:a,errorURL:s}=r,d=t.query.code,A=o.tokenUrl,K=o.userInfoUrl;if(o.discoveryUrl){let g=await(0,ho.betterFetch)(o.discoveryUrl,{method:"GET"});g.data&&(A=g.data.token_endpoint,K=g.data.userinfo_endpoint)}try{if(!A)throw new _e.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});i=await I({code:d,codeVerifier:a,redirectURI:`${t.context.baseURL}/oauth2/callback/${o.providerId}`,options:{clientId:o.clientId,clientSecret:o.clientSecret},tokenEndpoint:A})}catch(g){throw t.context.logger.error(g&&typeof g=="object"&&"name"in g?g.name:"",g),t.redirect(`${s}?error=oauth_code_verification_failed`)}if(!i)throw new _e.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let u=o.getUserInfo?await o.getUserInfo(i):await sn(i,o.type||"oauth2",K);if(!u?.email)throw t.context.logger.error("Unable to get user info",u),t.redirect(`${t.context.baseURL}/error?error=email_is_missing`);let p=await Pe(t,{userInfo:u,account:{providerId:o.providerId,accountId:u.id,accessToken:i.accessToken}});function l(g){throw t.redirect(`${s||n||`${t.context.baseURL}/error`}?error=${g}`)}if(p.error)return l(p.error.split(" ").join("_"));let{session:h,user:k}=p.data;await m(t,{session:h,user:k});let f;try{f=new URL(n).toString()}catch{f=n}throw t.redirect(f)})}});var Fe=require("zod"),$t={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0}}}},kp=Fe.z.object({id:Fe.z.string(),publicKey:Fe.z.string(),privateKey:Fe.z.string(),createdAt:Fe.z.date()});var $o=e=>({getAllKeys:async()=>await e.findMany({model:"jwks"}),getLatestKey:async()=>(await e.findMany({model:"jwks",sortBy:{field:"createdAt",direction:"desc"},limit:1}))[0],createJwk:async t=>await e.create({model:"jwks",data:{...t,createdAt:new Date}})});var le=require("jose");var dn=e=>({id:"jwt",endpoints:{getJwks:c("/jwks",{method:"GET",metadata:{openapi:{description:"Get the JSON Web Key Set",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{keys:{type:"array",items:{type:"object",properties:{kid:{type:"string"},kty:{type:"string"},use:{type:"string"},alg:{type:"string"},n:{type:"string"},e:{type:"string"}}}}}}}}}}}}},async t=>{let i=await $o(t.context.adapter).getAllKeys();return t.json({keys:i.map(r=>({...JSON.parse(r.publicKey),kid:r.id}))})}),getToken:c("/token",{method:"GET",requireHeaders:!0,use:[v],metadata:{openapi:{description:"Get a JWT token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async t=>{let o=$o(t.context.adapter),i=await o.getLatestKey(),r=!e?.jwks?.disablePrivateKeyEncryption;if(i===void 0){let{publicKey:A,privateKey:K}=await(0,le.generateKeyPair)(e?.jwks?.keyPairConfig?.alg??"EdDSA",e?.jwks?.keyPairConfig??{crv:"Ed25519"}),u=await(0,le.exportJWK)(A),p=await(0,le.exportJWK)(K),l=JSON.stringify(p),h={id:crypto.randomUUID(),publicKey:JSON.stringify(u),privateKey:r?JSON.stringify(await ue({key:t.context.options.secret,data:l})):l,createdAt:new Date};i=await o.createJwk(h)}let n=r?await fe({key:t.context.options.secret,data:JSON.parse(i.privateKey)}):i.privateKey,a=await(0,le.importJWK)(JSON.parse(n)),s=e?.jwt?.definePayload?await e?.jwt.definePayload(t.context.session.user):t.context.session.user,d=await new le.SignJWT({...s,...t.context.session.session.impersonatedBy?{impersonatedBy:t.context.session.session.impersonatedBy}:{}}).setProtectedHeader({alg:e?.jwks?.keyPairConfig?.alg??"EdDSA",kid:i.id}).setIssuedAt().setIssuer(e?.jwt?.issuer??t.context.options.baseURL).setAudience(e?.jwt?.audience??t.context.options.baseURL).setExpirationTime(e?.jwt?.expirationTime??"15m").setSubject(t.context.session.user.id).sign(a);return t.json({token:d})})},schema:ie($t,e?.schema)});var Xe=require("zod");var An=e=>{let t={maximumSessions:5,...e},o=i=>i.includes("_multi-");return{id:"multi-session",endpoints:{listDeviceSessions:c("/multi-session/list-device-sessions",{method:"GET",requireHeaders:!0},async i=>{let r=i.headers?.get("cookie");if(!r)return i.json([]);let n=Object.fromEntries(He(r)),a=(await Promise.all(Object.entries(n).filter(([A])=>o(A)).map(async([A])=>await i.getSignedCookie(A,i.context.secret)))).filter(A=>A!==void 0);if(!a.length)return i.json([]);let d=(await i.context.internalAdapter.findSessions(a)).filter(A=>A&&A.session.expiresAt>new Date);return i.json(d)}),setActiveSession:c("/multi-session/set-active",{method:"POST",body:Xe.z.object({sessionToken:Xe.z.string({description:"The session token to set as active"})}),requireHeaders:!0,use:[v],metadata:{openapi:{description:"Set the active session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async i=>{let r=i.body.sessionToken,n=`${i.context.authCookies.sessionToken.name}_multi-${r}`;if(!await i.getSignedCookie(n,i.context.secret))throw new C.APIError("UNAUTHORIZED",{message:"Invalid session token"});let s=await i.context.internalAdapter.findSession(r);if(!s||s.session.expiresAt<new Date)throw i.setCookie(n,"",{...i.context.authCookies.sessionToken.options,maxAge:0}),new C.APIError("UNAUTHORIZED",{message:"Invalid session token"});return await m(i,s),i.json(s)}),revokeDeviceSession:c("/multi-session/revoke",{method:"POST",body:Xe.z.object({sessionToken:Xe.z.string({description:"The session token to revoke"})}),requireHeaders:!0,use:[v],metadata:{openapi:{description:"Revoke a device session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async i=>{let r=i.body.sessionToken,n=`${i.context.authCookies.sessionToken.name}_multi-${r}`;if(!await i.getSignedCookie(n,i.context.secret))throw new C.APIError("UNAUTHORIZED",{message:"Invalid session token"});if(await i.context.internalAdapter.deleteSession(r),i.setCookie(n,"",{...i.context.authCookies.sessionToken.options,maxAge:0}),!(i.context.session?.session.token===r))return i.json({success:!0});let d=i.headers?.get("cookie");if(d){let A=Object.fromEntries(He(d)),K=(await Promise.all(Object.entries(A).filter(([p])=>o(p)).map(async([p])=>await i.getSignedCookie(p,i.context.secret)))).filter(p=>p!==void 0),u=i.context.internalAdapter;if(K.length>0){let l=(await u.findSessions(K)).filter(h=>h&&h.session.expiresAt>new Date);if(l.length>0){let h=l[0];await m(i,h)}else M(i)}else M(i)}else M(i);return i.json({success:!0})})},hooks:{after:[{matcher:()=>!0,handler:P(async i=>{let r=i.responseHeader.get("set-cookie");if(!r)return;let n=ao(r),a=i.context.authCookies.sessionToken,s=n.get(a.name)?.value;if(!s)return;let d=He(i.headers?.get("cookie")||""),A=s.split(".")[0];if(!A)return;let K=`${a.name}_multi-${A}`;n.get(K)||d.get(K)||Object.keys(Object.fromEntries(d)).filter(o).length+(r.includes("session_token")?1:0)>t.maximumSessions||await i.setSignedCookie(K,A,i.context.secret,a.options)})},{matcher:i=>i.path==="/sign-out",handler:P(async i=>{let r=i.headers?.get("cookie");if(!r)return;let n=Object.fromEntries(He(r)),a=Object.keys(n).map(s=>o(s)?(i.setCookie(s,"",{maxAge:0}),s.split("_multi-")[1]):null).filter(s=>s!==null);await i.context.internalAdapter.deleteSessions(a)})}]}}};var D=require("zod");var Zo=["email-verification","sign-in","forget-password"],cn=e=>{let t={expireIn:300,otpLength:6,...e};return{id:"email-otp",endpoints:{sendVerificationOTP:c("/email-otp/send-verification-otp",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to send the OTP"}),type:D.z.enum(Zo,{description:"Type of the OTP"})}),metadata:{openapi:{description:"Send verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{if(!e?.sendVerificationOTP)throw o.context.logger.error("send email verification is not implemented"),new C.APIError("BAD_REQUEST",{message:"send email verification is not implemented"});let i=o.body.email,r=Q(t.otpLength,$("0-9"));return await o.context.internalAdapter.createVerificationValue({value:r,identifier:`${o.body.type}-otp-${i}`,expiresAt:R(t.expireIn,"sec")}).catch(async n=>{await o.context.internalAdapter.deleteVerificationByIdentifier(`${o.body.type}-otp-${i}`),await o.context.internalAdapter.createVerificationValue({value:r,identifier:`${o.body.type}-otp-${i}`,expiresAt:R(t.expireIn,"sec")})}),await e.sendVerificationOTP({email:i,otp:r,type:o.body.type},o.request),o.json({success:!0})}),createVerificationOTP:c("/email-otp/create-verification-otp",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to send the OTP"}),type:D.z.enum(Zo,{description:"Type of the OTP"})}),metadata:{SERVER_ONLY:!0,openapi:{description:"Create verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string"}}}}}}}},async o=>{let i=o.body.email,r=Q(t.otpLength,$("0-9"));return await o.context.internalAdapter.createVerificationValue({value:r,identifier:`${o.body.type}-otp-${i}`,expiresAt:R(t.expireIn,"sec")}),r}),getVerificationOTP:c("/email-otp/get-verification-otp",{method:"GET",query:D.z.object({email:D.z.string({description:"Email address to get the OTP"}),type:D.z.enum(Zo)}),metadata:{SERVER_ONLY:!0,openapi:{description:"Get verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{otp:{type:"string"}}}}}}}}}},async o=>{let i=o.query.email,r=await o.context.internalAdapter.findVerificationValue(`${o.query.type}-otp-${i}`);return!r||r.expiresAt<new Date?o.json({otp:null}):o.json({otp:r.value})}),verifyEmailOTP:c("/email-otp/verify-email",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to verify"}),otp:D.z.string({description:"OTP to verify"})}),metadata:{openapi:{description:"Verify email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async o=>{let i=o.body.email,r=await o.context.internalAdapter.findVerificationValue(`email-verification-otp-${i}`);if(!r||r.expiresAt<new Date)throw r&&await o.context.internalAdapter.deleteVerificationValue(r.id),new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});let n=o.body.otp;if(r.value!==n)throw new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});await o.context.internalAdapter.deleteVerificationValue(r.id);let a=await o.context.internalAdapter.findUserByEmail(i);if(!a)throw new C.APIError("BAD_REQUEST",{message:"User not found"});let s=await o.context.internalAdapter.updateUser(a.user.id,{email:i,emailVerified:!0});return o.json({user:s})}),signInEmailOTP:c("/sign-in/email-otp",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to sign in"}),otp:D.z.string({description:"OTP sent to the email"})}),metadata:{openapi:{description:"Sign in with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async o=>{let i=o.body.email,r=await o.context.internalAdapter.findVerificationValue(`sign-in-otp-${i}`);if(!r||r.expiresAt<new Date)throw r&&await o.context.internalAdapter.deleteVerificationValue(r.id),new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});let n=o.body.otp;if(r.value!==n)throw new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});await o.context.internalAdapter.deleteVerificationValue(r.id);let a=await o.context.internalAdapter.findUserByEmail(i);if(!a){if(t.disableSignUp)throw new C.APIError("BAD_REQUEST",{message:"User not found"});let d=await o.context.internalAdapter.createUser({email:i,emailVerified:!0,name:i}),A=await o.context.internalAdapter.createSession(d.id,o.request);return await m(o,{session:A,user:d}),o.json({user:d,session:A})}a.user.emailVerified||await o.context.internalAdapter.updateUser(a.user.id,{emailVerified:!0});let s=await o.context.internalAdapter.createSession(a.user.id,o.request);return await m(o,{session:s,user:a.user}),o.json({session:s,user:a})}),forgetPasswordEmailOTP:c("/forget-password/email-otp",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to send the OTP"})}),metadata:{openapi:{description:"Forget password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{let i=o.body.email;if(!await o.context.internalAdapter.findUserByEmail(i))throw new C.APIError("BAD_REQUEST",{message:"User not found"});let n=Q(t.otpLength,$("0-9"));return await o.context.internalAdapter.createVerificationValue({value:n,identifier:`forget-password-otp-${i}`,expiresAt:R(t.expireIn,"sec")}),await e.sendVerificationOTP({email:i,otp:n,type:"forget-password"},o.request),o.json({success:!0})}),resetPasswordEmailOTP:c("/email-otp/reset-password",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to reset the password"}),otp:D.z.string({description:"OTP sent to the email"}),password:D.z.string({description:"New password"})}),metadata:{openapi:{description:"Reset password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{let i=o.body.email,r=await o.context.internalAdapter.findUserByEmail(i);if(!r)throw new C.APIError("BAD_REQUEST",{message:"User not found"});let n=await o.context.internalAdapter.findVerificationValue(`forget-password-otp-${i}`);if(!n||n.expiresAt<new Date)throw n&&await o.context.internalAdapter.deleteVerificationValue(n.id),new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});let a=o.body.otp;if(n.value!==a)throw new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});await o.context.internalAdapter.deleteVerificationValue(n.id);let s=await o.context.password.hash(o.body.password);return await o.context.internalAdapter.updatePassword(r.user.id,s),o.json({success:!0})})},hooks:{after:[{matcher(o){return!!(o.path?.startsWith("/sign-up")&&t.sendVerificationOnSignUp)},async handler(o){let i=await Be(o);if(i&&i.user.email&&i.user.emailVerified===!1){let r=Q(t.otpLength,$("0-9"));await o.context.internalAdapter.createVerificationValue({value:r,identifier:`email-verification-otp-${i.user.email}`,expiresAt:R(t.expireIn,"sec")}),await e.sendVerificationOTP({email:i.user.email,otp:r,type:"email-verification"},o.request)}}}]}}};var Go=require("zod");var Gt=require("@better-fetch/fetch");function Zt(e){return e==="true"||e===!0}var Kn=e=>({id:"one-tap",endpoints:{oneTapCallback:c("/one-tap/callback",{method:"POST",body:Go.z.object({idToken:Go.z.string({description:"Google ID token, which the client obtains from the One Tap API"})}),metadata:{openapi:{summary:"One tap callback",description:"Use this endpoint to authenticate with Google One Tap",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}},400:{description:"Invalid token"}}}}},async t=>{let{idToken:o}=t.body,{data:i,error:r}=await(0,Gt.betterFetch)("https://oauth2.googleapis.com/tokeninfo?id_token="+o);if(r)return t.json({error:"Invalid token"});let n=await t.context.internalAdapter.findUserByEmail(i.email);if(!n){if(e?.disableSignup)throw new C.APIError("BAD_GATEWAY",{message:"User not found"});let s=await t.context.internalAdapter.createOAuthUser({email:i.email,emailVerified:Zt(i.email_verified),name:i.name,image:i.picture},{providerId:"google",accountId:i.sub});if(!s)throw new C.APIError("INTERNAL_SERVER_ERROR",{message:"Could not create user"});let d=await t.context.internalAdapter.createSession(s?.user.id,t.request);return await m(t,{user:s.user,session:d}),t.json({session:d,user:s})}let a=await t.context.internalAdapter.createSession(n.user.id,t.request);return await m(t,{user:n.user,session:a}),t.json({session:a,user:n})})}});var yo=require("zod");function pn(){let e=ne.VERCEL_URL,t=ne.NETLIFY_URL,o=ne.RENDER_URL,i=ne.AWS_LAMBDA_FUNCTION_NAME,r=ne.GOOGLE_CLOUD_FUNCTION_NAME,n=ne.AZURE_FUNCTION_NAME;return e||t||o||i||r||n}var un=e=>({id:"oauth-proxy",endpoints:{oAuthProxy:c("/oauth-proxy-callback",{method:"GET",query:yo.z.object({callbackURL:yo.z.string({description:"The URL to redirect to after the proxy"}),cookies:yo.z.string({description:"The cookies to set after the proxy"})}),metadata:{openapi:{description:"OAuth Proxy Callback",parameters:[{in:"query",name:"callbackURL",required:!0,description:"The URL to redirect to after the proxy"},{in:"query",name:"cookies",required:!0,description:"The cookies to set after the proxy"}],responses:{302:{description:"Redirect",headers:{Location:{description:"The URL to redirect to",schema:{type:"string"}}}}}}}},async t=>{let o=t.query.cookies,i=await fe({key:t.context.secret,data:o});throw t.setHeader("set-cookie",i),t.redirect(t.query.callbackURL)})},hooks:{after:[{matcher(t){return t.path?.startsWith("/callback")},handler:P(async t=>{let o=t.context.returned,i=o instanceof C.APIError?o.headers:null,r=i?.get("location");if(r?.includes("/oauth-proxy-callback?callbackURL")){if(!r.startsWith("http"))return;let n=new URL(r);if(n.origin===Ie(t.context.baseURL)){let K=n.searchParams.get("callbackURL");if(!K)return;t.setHeader("location",K);return}let s=i?.get("set-cookie");if(!s)return;let d=await ue({key:t.context.secret,data:s}),A=`${r}&cookies=${encodeURIComponent(d)}`;t.setHeader("location",A)}})}],before:[{matcher(t){return t.path?.startsWith("/sign-in/social")},async handler(t){let o=new URL(e?.currentURL||t.request?.url||pn()||t.context.baseURL);return t.body.callbackURL=`${o.origin}${t.context.options.basePath||"/api/auth"}/oauth-proxy-callback?callbackURL=${encodeURIComponent(t.body.callbackURL||t.context.baseURL)}`,{context:t}}}]}});var ln=(e,t)=>({id:"custom-session",endpoints:{getSession:c("/get-session",{method:"GET",metadata:{CUSTOM_SESSION:!0}},async o=>{let i=await U(o);if(!i)return o.json(null);let r=await e(i);return o.json(r)})}});var ce=require("zod");var Ve=e=>{let t=e.plugins?.reduce((d,A)=>{let K=A.schema;if(!K)return d;for(let[u,p]of Object.entries(K))d[u]={fields:{...d[u]?.fields,...p.fields},modelName:p.modelName||u};return d},{}),o=e.rateLimit?.storage==="database",i={rateLimit:{modelName:e.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",fieldName:e.rateLimit?.fields?.key||"key"},count:{type:"number",fieldName:e.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",fieldName:e.rateLimit?.fields?.lastRequest||"lastRequest"}}}},{user:r,session:n,account:a,...s}=t||{};return{user:{modelName:e.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:e.user?.fields?.name||"name"},email:{type:"string",unique:!0,required:!0,fieldName:e.user?.fields?.email||"email"},emailVerified:{type:"boolean",defaultValue:()=>!1,required:!0,fieldName:e.user?.fields?.emailVerified||"emailVerified"},image:{type:"string",required:!1,fieldName:e.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.updatedAt||"updatedAt"},...r?.fields,...e.user?.additionalFields},order:1},session:{modelName:e.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:e.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:e.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:e.session?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,fieldName:e.session?.fields?.updatedAt||"updatedAt"},ipAddress:{type:"string",required:!1,fieldName:e.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:e.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:e.session?.fields?.userId||"userId",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0},...n?.fields,...e.session?.additionalFields},order:2},account:{modelName:e.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:e.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:e.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:e.account?.fields?.userId||"userId"},accessToken:{type:"string",required:!1,fieldName:e.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,fieldName:e.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,fieldName:e.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.accessTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:e.account?.fields?.scope||"scope"},password:{type:"string",required:!1,fieldName:e.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:e.account?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,fieldName:e.account?.fields?.updatedAt||"updatedAt"},...a?.fields},order:3},verification:{modelName:e.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:e.verification?.fields?.identifier||"identifier"},value:{type:"string",required:!0,fieldName:e.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:e.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!1,defaultValue:()=>new Date,fieldName:e.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!1,defaultValue:()=>new Date,fieldName:e.verification?.fields?.updatedAt||"updatedAt"}},order:4},...s,...o?i:{}}};var gn=require("zod");var Wt=require("kysely"),Wo=require("kysely");var Ye={};function Xt(e){switch(e.constructor.name){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array";default:return"string"}}function wo(e){let t=[];return e.metadata?.openapi?.parameters?(t.push(...e.metadata.openapi.parameters),t):(e.query instanceof ce.ZodObject&&Object.entries(e.query.shape).forEach(([o,i])=>{i instanceof ce.ZodSchema&&t.push({name:o,in:"query",schema:{type:Xt(i),..."minLength"in i&&i.minLength?{minLength:i.minLength}:{},description:i.description}})}),t)}function Jt(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof ce.ZodObject||e.body instanceof ce.ZodOptional)){let t=e.body.shape;if(!t)return;let o={},i=[];return Object.entries(t).forEach(([r,n])=>{n instanceof ce.ZodSchema&&(o[r]={type:Xt(n),description:n.description},n instanceof ce.ZodOptional||i.push(r))}),{required:e.body instanceof ce.ZodOptional?!1:!!e.body,content:{"application/json":{schema:{type:"object",properties:o,required:i}}}}}}function Co(e){return{400:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Bad Request. Usually due to missing parameters, or invalid parameters."},401:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Unauthorized. Due to missing or invalid authentication."},403:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Forbidden. You do not have permission to access this resource or to perform this action."},404:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Not Found. The requested resource was not found."},429:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Too Many Requests. You have exceeded the rate limit. Try again later."},500:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Internal Server Error. This is a problem with the server that you cannot fix."},...e}}async function Jo(e,t){let o=Uo(e,{...t,plugins:[]}),i=Ve(t),n={schemas:{...Object.entries(i).reduce((s,[d,A])=>{let K=d.charAt(0).toUpperCase()+d.slice(1);return s[K]={type:"object",properties:Object.entries(A.fields).reduce((u,[p,l])=>(u[p]={type:l.type},u),{})},s},{})}};Object.entries(o.api).forEach(([s,d])=>{let A=d.options;if(!A.metadata?.SERVER_ONLY&&(A.method==="GET"&&(Ye[d.path]={get:{tags:["Default",...A.metadata?.openapi?.tags||[]],description:A.metadata?.openapi?.description,operationId:A.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(A),responses:Co(A.metadata?.openapi?.responses)}}),A.method==="POST")){let K=Jt(A);Ye[d.path]={post:{tags:["Default",...A.metadata?.openapi?.tags||[]],description:A.metadata?.openapi?.description,operationId:A.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(A),...K?{requestBody:K}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:Co(A.metadata?.openapi?.responses)}}}});for(let s of t.plugins||[]){if(s.id==="open-api")continue;let d=Uo(e,{...t,plugins:[s]}),A=Object.keys(d.api).map(K=>o.api[K]===void 0?d.api[K]:null).filter(K=>K!==null);Object.entries(A).forEach(([K,u])=>{let p=u.options;p.metadata?.SERVER_ONLY||(p.method==="GET"&&(Ye[u.path]={get:{tags:p.metadata?.openapi?.tags||[s.id.charAt(0).toUpperCase()+s.id.slice(1)],description:p.metadata?.openapi?.description,operationId:p.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(p),responses:Co(p.metadata?.openapi?.responses)}}),p.method==="POST"&&(Ye[u.path]={post:{tags:p.metadata?.openapi?.tags||[s.id.charAt(0).toUpperCase()+s.id.slice(1)],description:p.metadata?.openapi?.description,operationId:p.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(p),requestBody:Jt(p),responses:Co(p.metadata?.openapi?.responses)}}))})}return{openapi:"3.1.1",info:{title:"Better Auth",description:"API Reference for your Better Auth Instance"},components:n,security:[{apiKeyCookie:[]}],servers:[{url:e.baseURL}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:Ye}}var Yt=`<svg width="75" height="75" viewBox="0 0 75 75" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
82
+ </html>`,pi=c("/error",{method:"GET",metadata:{...we,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string"}}}}}}}},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(fr(t),{headers:{"Content-Type":"text/html"}})});var ui=require("consola"),Io=["info","success","warn","error","debug"];function hr(e,t){return Io.indexOf(t)<=Io.indexOf(e)}var yr=(0,ui.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),li=e=>{let t=e?.disabled!==!0,o=e?.level??"error",i=(r,n,a=[])=>{if(!(!t||!hr(o,r))){if(!e||typeof e.log!="function"){yr[r]("",n,...a);return}e.log(r==="success"?"info":r,n,a)}};return Object.fromEntries(Io.map(r=>[r,(...[n,...a])=>i(r,n,a)]))},J=li();var C=require("better-call");function Uo(e,t){let o=t.plugins?.reduce((s,d)=>({...s,...d.endpoints}),{}),i=t.plugins?.map(s=>s.middlewares?.map(d=>{let A=async K=>d.middleware({...K,context:{...e,...K.context}});return A.path=d.path,A.options=d.middleware.options,A.headers=d.middleware.headers,{path:d.path,middleware:A}})).filter(s=>s!==void 0).flat()||[],n={...{signInSocial:gi,callbackOAuth:fi,getSession:To(),signOut:hi,signUpEmail:Ki(),signInEmail:mi,forgetPassword:yi,resetPassword:Ci,verifyEmail:Ai,sendVerificationEmail:di,changeEmail:Oi,changePassword:vi,setPassword:ki,updateUser:bi(),deleteUser:Ti,forgetPasswordCallback:wi,listSessions:ti(),revokeSession:ri,revokeSessions:ni,revokeOtherSessions:si,linkSocialAccount:Ui,listUserAccounts:Ii},...o,ok:ii,error:pi},a={};for(let[s,d]of Object.entries(n))a[s]=async(A={})=>{d.headers=new Headers;let K={setHeader(f,g){d.headers.set(f,g)},setCookie(f,g,b){(0,$.setCookie)(d.headers,f,g,b)},getCookie(f,g){let T=A.headers?.get("cookie");return(0,$.getCookie)(T||"",f,g)},getSignedCookie(f,g,b){let T=A.headers;return T?(0,$.getSignedCookie)(T,g,f,b):null},async setSignedCookie(f,g,b,T){await(0,$.setSignedCookie)(d.headers,f,g,b,T)},redirect(f){return d.headers.set("Location",f),new $.APIError("FOUND")},responseHeader:d.headers},u=await e,p={...K,...A,path:d.path,context:{...u,...A.context,endpoint:d}};u.session=null;let l=t.plugins||[];for(let f of l){let g=f.hooks?.before??[];for(let b of g){if(!b.matcher(p))continue;let T=await b.handler(p);if(T&&"context"in T){p={...p,...T.context};continue}if(T)return T}}let h;try{h=await d(p)}catch(f){if(f instanceof $.APIError){let g=t.plugins?.map(b=>{if(b.hooks?.after)return b.hooks.after}).filter(b=>b!==void 0).flat();if(!g?.length)throw f.headers=d.headers,f;p.context.returned=f,p.context.returned.headers=d.headers;for(let b of g||[])if(b.matcher(p))try{let N=await b.handler(p);N&&"response"in N&&(p.context.returned=N.response)}catch(N){if(N instanceof $.APIError){p.context.returned=N;continue}throw N}if(p.context.returned instanceof $.APIError)throw p.context.returned.headers=d.headers,p.context.returned;return p.context.returned}throw f}p.context.returned=h,p.responseHeader=d.headers;for(let f of t.plugins||[])if(f.hooks?.after){for(let g of f.hooks.after)if(g.matcher(p))try{let T=await g.handler(p);T&&(p.context.returned=T)}catch(T){if(T instanceof $.APIError){p.context.returned=T;continue}throw T}}let k=p.context.returned;return k instanceof Response&&d.headers.forEach((f,g)=>{g==="set-cookie"?k.headers.append(g,f):k.headers.set(g,f)}),k},a[s].path=d.path,a[s].method=d.method,a[s].options=d.options,a[s].headers=d.headers;return{api:a,middlewares:i}}function ao(e){let t=new Map;return e.split(", ").forEach(i=>{let r=i.split(";").map(u=>u.trim()),[n,...a]=r,[s,...d]=n.split("="),A=d.join("=");if(!s||A===void 0){console.warn(`Malformed cookie: ${i}`);return}let K={value:A};a.forEach(u=>{let[p,...l]=u.split("="),h=l.join("="),k=p.trim().toLowerCase();switch(k){case"max-age":K["max-age"]=h?parseInt(h.trim(),10):void 0;break;case"expires":K.expires=h?new Date(h.trim()):void 0;break;case"domain":K.domain=h?h.trim():void 0;break;case"path":K.path=h?h.trim():void 0;break;case"secure":K.secure=!0;break;case"httponly":K.httponly=!0;break;case"samesite":K.samesite=h?h.trim().toLowerCase():void 0;break;default:K[k]=h?h.trim():!0;break}}),t.set(s,K)}),t}async function m(e,t,o,i){let r=e.context.authCookies.sessionToken.options,n=o?void 0:e.context.sessionConfig.expiresIn,a=await U(e).catch(()=>null);a&&a.session.userId===t.session.userId&&a.session.token!==t.session.token&&await e.context.internalAdapter.deleteSession(a.session.token),await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...r,maxAge:n,...i}),o&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Ri.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:R(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await to.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),new Date(t.session.expiresAt).getTime()-Date.now())}function Q(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}function Qe(e){let t=e.split("; "),o=new Map;return t.forEach(i=>{let[r,n]=i.split("=");o.set(r,n)}),o}var ji=require("@better-fetch/fetch"),zi=require("better-call"),Re=require("jose"),Bi=require("oslo/jwt");var Pi=require("oslo/crypto"),Ei=require("oslo/encoding");async function Si(e){let t=await(0,Pi.sha256)(new TextEncoder().encode(e));return Ei.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Di(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?R(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function S({id:e,options:t,authorizationEndpoint:o,state:i,codeVerifier:r,scopes:n,claims:a,redirectURI:s}){let d=new URL(o);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",i),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||s),r){let A=await Si(r);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",A)}if(a){let A=a.reduce((K,u)=>(K[u]=null,K),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...A}}))}return d}var xi=require("@better-fetch/fetch");async function I({code:e,codeVerifier:t,redirectURI:o,options:i,tokenEndpoint:r,authentication:n}){let a=new URLSearchParams,s={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(a.set("grant_type","authorization_code"),a.set("code",e),t&&a.set("code_verifier",t),a.set("redirect_uri",o),n==="basic"){let u=btoa(`${i.clientId}:${i.clientSecret}`);s.authorization=`Basic ${u}`}else a.set("client_id",i.clientId),a.set("client_secret",i.clientSecret);let{data:d,error:A}=await(0,xi.betterFetch)(r,{method:"POST",body:a,headers:s});if(A)throw A;return Di(d)}var Ao=require("oslo/oauth2"),pe=require("zod"),Ro=require("better-call");function Ie(e){try{return new URL(e).origin}catch{return null}}async function Ue(e,t){let o=e.body?.callbackURL||(e.query?.currentURL?Ie(e.query?.currentURL):"")||e.context.options.baseURL;if(!o)throw new Ro.APIError("BAD_REQUEST",{message:"callbackURL is required"});let i=(0,Ao.generateCodeVerifier)(),r=(0,Ao.generateState)(),n=JSON.stringify({callbackURL:o,codeVerifier:i,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),a=new Date;a.setMinutes(a.getMinutes()+10);let s=await e.context.internalAdapter.createVerificationValue({value:n,identifier:r,expiresAt:a});if(!s)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new Ro.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:s.identifier,codeVerifier:i}}async function co(e){let t=e.query.state||e.body.state,o=await e.context.internalAdapter.findVerificationValue(t);if(!o)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let i=pe.z.object({callbackURL:pe.z.string(),codeVerifier:pe.z.string(),errorURL:pe.z.string().optional(),expiresAt:pe.z.number(),link:pe.z.object({email:pe.z.string(),userId:pe.z.string()}).optional()}).parse(JSON.parse(o.value));if(i.errorURL||(i.errorURL=`${e.context.baseURL}/error`),i.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(o.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(o.id),i}var Ni=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:o,scopes:i,redirectURI:r}){let n=i||["email","name"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${r||e.redirectURI}&scope=${n.join(" ")}&state=${o}&response_mode=form_post`)},validateAuthorizationCode:async({code:o,codeVerifier:i,redirectURI:r})=>I({code:o,codeVerifier:i,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t}),async verifyIdToken(o,i){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(o,i);let r=(0,Re.decodeProtectedHeader)(o),{kid:n,alg:a}=r;if(!n||!a)return!1;let s=await br(n),{payload:d}=await(0,Re.jwtVerify)(o,s,{algorithms:[a],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(A=>{d[A]!==void 0&&(d[A]=!!d[A])}),i&&d.nonce!==i?!1:!!d},async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);if(!o.idToken)return null;let i=(0,Bi.parseJWT)(o.idToken)?.payload;if(!i)return null;let r=i.user?`${i.user.name.firstName} ${i.user.name.lastName}`:i.email;return{user:{id:i.sub,name:r,emailVerified:!1,email:i.email},data:i}}}},br=async e=>{let t="https://appleid.apple.com",o="/auth/keys",{data:i}=await(0,ji.betterFetch)(`${t}${o}`);if(!i?.keys)throw new zi.APIError("BAD_REQUEST",{message:"Keys not found"});let r=i.keys.find(n=>n.kid===e);if(!r)throw new Error(`JWK with kid ${e} not found`);return await(0,Re.importJWK)(r,r.alg)};var Li=require("@better-fetch/fetch");var _i=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:o,redirectURI:i}){let r=o||["identify","email"];return e.scope&&r.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${r.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||i)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:o})=>I({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:i}=await(0,Li.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(i)return null;if(o.avatar===null){let r=o.discriminator==="0"?Number(BigInt(o.id)>>BigInt(22))%6:parseInt(o.discriminator)%5;o.image_url=`https://cdn.discordapp.com/embed/avatars/${r}.png`}else{let r=o.avatar.startsWith("a_")?"gif":"png";o.image_url=`https://cdn.discordapp.com/avatars/${o.id}/${o.avatar}.${r}`}return{user:{id:o.id,name:o.display_name||o.username||"",email:o.email,emailVerified:o.verified,image:o.image_url},data:o}}});var Fi=require("@better-fetch/fetch");var Vi=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:o,redirectURI:i}){let r=o||["email","public_profile"];return e.scope&&r.push(...e.scope),await S({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:r,state:t,redirectURI:i})},validateAuthorizationCode:async({code:t,redirectURI:o})=>I({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:i}=await(0,Fi.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return i?null:{user:{id:o.id,name:o.name,email:o.email,image:o.picture.data.url,emailVerified:o.email_verified},data:o}}});var Po=require("@better-fetch/fetch");var qi=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:o,scopes:i,codeVerifier:r,redirectURI:n}){let a=i||["user:email"];return e.scope&&a.push(...e.scope),S({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>I({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);let{data:i,error:r}=await(0,Po.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${o.accessToken}`}});if(r)return null;let n=!1;if(!i.email){let{data:a,error:s}=await(0,Po.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${o.accessToken}`,"User-Agent":"better-auth"}});s||(i.email=(a.find(d=>d.primary)??a[0])?.email,n=a.find(d=>d.email===i.email)?.verified??!1)}return{user:{id:i.id.toString(),name:i.name||i.login,email:i.email,image:i.avatar_url,emailVerified:n},data:i}}}};var Mi=require("oslo/jwt");var Hi=require("@better-fetch/fetch"),Qi=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:o,codeVerifier:i,redirectURI:r}){if(!e.clientId||!e.clientSecret)throw J.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new ee("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new ee("codeVerifier is required for Google");let n=o||["email","profile","openid"];e.scope&&n.push(...e.scope);let a=await S({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:i,redirectURI:r});return e.accessType&&a.searchParams.set("access_type",e.accessType),e.prompt&&a.searchParams.set("prompt",e.prompt),a},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:i})=>I({code:t,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,o);let i=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:r}=await(0,Hi.betterFetch)(i);return r?r.aud===e.clientId&&r.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let o=(0,Mi.parseJWT)(t.idToken)?.payload;return{user:{id:o.sub,name:o.name,email:o.email,image:o.picture,emailVerified:o.email_verified},data:o}}});var $i=require("@better-fetch/fetch"),Zi=require("oslo/jwt");var Gi=e=>{let t=e.tenantId||"common",o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,i=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(r){let n=r.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),S({id:"microsoft",options:e,authorizationEndpoint:o,state:r.state,codeVerifier:r.codeVerifier,scopes:n,redirectURI:r.redirectURI})},validateAuthorizationCode({code:r,codeVerifier:n,redirectURI:a}){return I({code:r,codeVerifier:n,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:i})},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let n=(0,Zi.parseJWT)(r.idToken)?.payload,a=e.profilePhotoSize||48;return await(0,$i.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${r.accessToken}`},async onResponse(s){if(!(e.disableProfilePhoto||!s.response.ok))try{let A=await s.response.clone().arrayBuffer(),K=Buffer.from(A).toString("base64");n.picture=`data:image/jpeg;base64, ${K}`}catch(d){J.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};var Wi=require("@better-fetch/fetch");var Ji=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:o,codeVerifier:i,redirectURI:r}){let n=o||["user-read-email"];return e.scope&&n.push(...e.scope),S({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:i,redirectURI:r})},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:i})=>I({code:t,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:i}=await(0,Wi.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{id:o.id,name:o.display_name,email:o.email,image:o.images[0]?.url,emailVerified:!1},data:o}}});var Xi=require("nanoid"),V=e=>(0,Xi.nanoid)(e);var Yi=require("oslo/jwt");var et=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:o,redirectURI:i}){let r=o||["user:read:email","openid"];return e.scope&&r.push(...e.scope),S({id:"twitch",redirectURI:i,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:r,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:o})=>I({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let o=t.idToken;if(!o)return J.error("No idToken found in token"),null;let i=(0,Yi.parseJWT)(o)?.payload;return{user:{id:i.sub,name:i.preferred_username,email:i.email,image:i.picture,emailVerified:!1},data:i}}});var ot=require("@better-fetch/fetch");var it=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let o=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&o.push(...e.scope),S({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:o,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:i})=>I({code:t,codeVerifier:o,authentication:"basic",redirectURI:e.redirectURI||i,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:i}=await(0,ot.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{id:o.data.id,name:o.data.name,email:o.data.email||null,image:o.data.profile_image_url,emailVerified:o.data.verified||!1},data:o}}});var tt=require("@better-fetch/fetch");var rt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:o,scopes:i,codeVerifier:r,redirectURI:n})=>{let a=i||["account_info.read"];return e.scope&&a.push(...e.scope),await S({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:o,redirectURI:n,codeVerifier:r})},validateAuthorizationCode:async({code:o,codeVerifier:i,redirectURI:r})=>await I({code:o,codeVerifier:i,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t}),async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);let{data:i,error:r}=await(0,tt.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${o.accessToken}`}});return r?null:{user:{id:i.account_id,name:i.name?.display_name,email:i.email,emailVerified:i.email_verified||!1,image:i.profile_photo_url},data:i}}}};var nt=require("@better-fetch/fetch");var st=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",o="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:i,scopes:r,redirectURI:n})=>{let a=r||["profile","email","openid"];return e.scope&&a.push(...e.scope),await S({id:"linkedin",options:e,authorizationEndpoint:t,scopes:a,state:i,redirectURI:n})},validateAuthorizationCode:async({code:i,redirectURI:r})=>await I({code:i,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:o}),async getUserInfo(i){let{data:r,error:n}=await(0,nt.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});return n?null:{user:{id:r.sub,name:r.name,email:r.email,emailVerified:r.email_verified||!1,image:r.picture},data:r}}}};var at=require("@better-fetch/fetch");var Eo=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),vr=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:Eo(`${t}/oauth/authorize`),tokenEndpoint:Eo(`${t}/oauth/token`),userinfoEndpoint:Eo(`${t}/api/v4/user`)}},dt=e=>{let{authorizationEndpoint:t,tokenEndpoint:o,userinfoEndpoint:i}=vr(e.issuer),r="gitlab";return{id:r,name:"Gitlab",createAuthorizationURL:async({state:a,scopes:s,codeVerifier:d,redirectURI:A})=>{let K=s||["read_user"];return e.scope&&K.push(...e.scope),await S({id:r,options:e,authorizationEndpoint:t,scopes:K,state:a,redirectURI:A,codeVerifier:d})},validateAuthorizationCode:async({code:a,redirectURI:s,codeVerifier:d})=>I({code:a,redirectURI:e.redirectURI||s,options:e,codeVerifier:d,tokenEndpoint:o}),async getUserInfo(a){if(e.getUserInfo)return e.getUserInfo(a);let{data:s,error:d}=await(0,at.betterFetch)(i,{headers:{authorization:`Bearer ${a.accessToken}`}});return d||s.state!=="active"||s.locked?null:{user:{id:s.id.toString(),name:s.name??s.username,email:s.email,image:s.avatar_url,emailVerified:!0},data:s}}}};var kr={apple:Ni,discord:_i,facebook:Vi,github:qi,microsoft:Gi,google:Qi,spotify:Ji,twitch:et,twitter:it,dropbox:rt,linkedin:st,gitlab:dt},Ko=Object.keys(kr);async function Pe(e,{userInfo:t,account:o,callbackURL:i}){let r=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(s=>{throw J.error(`Better auth was unable to query your database.
83
+ Error: `,s),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=r?.user;if(r){let s=r.accounts.find(d=>d.providerId===o.providerId);if(s){let d=Object.fromEntries(Object.entries({accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt}).filter(([A,K])=>K!==void 0));Object.keys(d).length>0&&await e.context.internalAdapter.updateAccount(s.id,d)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(o.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return ei&&J.warn(`User already exist but account isn't linked to ${o.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:o.providerId,accountId:t.id.toString(),userId:r.user.id,accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt,scope:o.scope})}catch(K){return J.error("Unable to link account",K),{error:"unable to link account",data:null}}}}else try{let s=t.emailVerified||!1;if(n=await e.context.internalAdapter.createOAuthUser({...t,id:void 0,emailVerified:s,email:t.email.toLowerCase()},{accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt,scope:o.scope,providerId:o.providerId,accountId:t.id.toString()}).then(d=>d?.user),!s&&n&&e.context.options.emailVerification?.sendOnSignUp){let d=await Ke(e.context.secret,n.email),A=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${i}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:n,url:A,token:d},e.request)}}catch(s){return J.error("Unable to create user",s),{error:"unable to create user",data:null}}if(!n)return{error:"unable to create user",data:null};let a=await e.context.internalAdapter.createSession(n.id,e.request);return a?{data:{session:a,user:n},error:null}:{error:"unable to create session",data:null}}var gi=c("/sign-in/social",{method:"POST",query:x.z.object({currentURL:x.z.string().optional()}).optional(),body:x.z.object({callbackURL:x.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),errorCallbackURL:x.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:x.z.enum(Ko,{description:"OAuth2 provider to use"}),disableRedirect:x.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:x.z.optional(x.z.object({token:x.z.string({description:"ID token from the provider"}),nonce:x.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:x.z.string({description:"Access token from the provider"}).optional(),refreshToken:x.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:x.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new q.APIError("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new q.APIError("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:n,nonce:a}=e.body.idToken;if(!await t.verifyIdToken(n,a))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new q.APIError("UNAUTHORIZED",{message:"Invalid id token"});let d=await t.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!d||!d?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new q.APIError("UNAUTHORIZED",{message:"Failed to get user info"});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new q.APIError("UNAUTHORIZED",{message:"User email not found"});let A=await Pe(e,{userInfo:{email:d.user.email,id:d.user.id,name:d.user.name||"",image:d.user.image,emailVerified:d.user.emailVerified||!1},account:{providerId:t.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(A.error)throw new q.APIError("UNAUTHORIZED",{message:A.error});return await m(e,A.data),e.json({session:A.data.session,user:A.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:o,state:i}=await Ue(e),r=await t.createAuthorizationURL({state:i,codeVerifier:o,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:r.toString(),redirect:!e.body.disableRedirect})}),mi=c("/sign-in/email",{method:"POST",body:x.z.object({email:x.z.string({description:"Email of the user"}),password:x.z.string({description:"Password of the user"}),callbackURL:x.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:x.z.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new q.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:o}=e.body;if(!x.z.string().email().safeParse(t).success)throw new q.APIError("BAD_REQUEST",{message:"Invalid email"});let r=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!r)throw await e.context.password.hash(o),e.context.logger.error("User not found",{email:t}),new q.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let n=r.accounts.find(A=>A.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new q.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let a=n?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new q.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify({hash:a,password:o}))throw e.context.logger.error("Invalid password"),new q.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!r.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new q.APIError("UNAUTHORIZED",{message:"Email is not verified."});let A=await Ke(e.context.secret,r.user.email),K=`${e.context.baseURL}/verify-email?token=${A}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:r.user,url:K,token:A},e.request),e.context.logger.error("Email not verified",{email:t}),new q.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(r.user.id,e.headers,e.body.rememberMe===!1);if(!d)throw e.context.logger.error("Failed to create session"),new q.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await m(e,{session:d,user:r.user},e.body.rememberMe===!1),e.json({user:r.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Ee=require("zod");var po=Ee.z.object({code:Ee.z.string().optional(),error:Ee.z.string().optional(),errorMessage:Ee.z.string().optional(),state:Ee.z.string().optional()}),fi=c("/callback/:id",{method:["GET","POST"],body:po.optional(),query:po.optional(),metadata:we},async e=>{let t;try{if(e.method==="GET")t=po.parse(e.query);else if(e.method==="POST")t=po.parse(e.body);else throw new Error("Unsupported method")}catch(g){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",g),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:o,error:i,state:r}=t;if(!r)throw e.context.logger.error("State not found"),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!o)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${i||"no_code"}`);let n=e.context.socialProviders.find(g=>g.id===e.params.id);if(!n)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:a,callbackURL:s,link:d,errorURL:A}=await co(e),K;try{K=await n.validateAuthorizationCode({code:o,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${n.id}`})}catch(g){throw e.context.logger.error("",g),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let u=await n.getUserInfo(K).then(g=>g?.user);function p(g){let b=A||s||`${e.context.baseURL}/error`;throw b.includes("?")?b=`${b}&error=${g}`:b=`${b}?error=${g}`,e.redirect(b)}if(!u)return e.context.logger.error("Unable to get user info"),p("unable_to_get_user_info");if(!u.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),p("email_not_found");if(!s)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(d){if(d.email!==u.email.toLowerCase())return p("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:n.id,accountId:u.id}))return p("unable_to_link_account");let b;try{b=new URL(s).toString()}catch{b=s}throw e.redirect(b)}let l=await Pe(e,{userInfo:{id:u.id,email:u.email,name:u.name||"",image:u.image,emailVerified:u.emailVerified||!1},account:{providerId:n.id,accountId:u.id,...K,scope:K.scopes?.join(",")},callbackURL:s});if(l.error)return e.context.logger.error(l.error.split(" ").join("_")),p(l.error.split(" ").join("_"));let{session:h,user:k}=l.data;await m(e,{session:h,user:k});let f;try{f=new URL(s).toString()}catch{f=s}throw e.redirect(f)});var bd=require("zod");var At=require("better-call"),hi=c("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw Q(e),new At.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),Q(e),e.json({success:!0})});var X=require("zod");var uo=require("better-call");function ct(e,t,o){let i=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return o&&Object.entries(o).forEach(([r,n])=>i.searchParams.set(r,n)),i.href}function Tr(e,t,o){let i=new URL(t,e.baseURL);return o&&Object.entries(o).forEach(([r,n])=>i.searchParams.set(r,n)),i.href}var yi=c("/forget-password",{method:"POST",body:X.z.object({email:X.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:X.z.string({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new uo.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:o}=e.body,i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let r=60*60*1,n=R(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||r,"sec"),a=V(24);await e.context.internalAdapter.createVerificationValue({value:i.user.id.toString(),identifier:`reset-password:${a}`,expiresAt:n});let s=`${e.context.baseURL}/reset-password/${a}?callbackURL=${o}`;return await e.context.options.emailAndPassword.sendResetPassword({user:i.user,url:s,token:a},e.request),e.json({status:!0})}),wi=c("/reset-password/:token",{method:"GET",query:X.z.object({callbackURL:X.z.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:o}=e.query;if(!t||!o)throw e.redirect(ct(e.context,o,{error:"INVALID_TOKEN"}));let i=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!i||i.expiresAt<new Date?e.redirect(ct(e.context,o,{error:"INVALID_TOKEN"})):e.redirect(Tr(e.context,o,{token:t}))}),Ci=c("/reset-password",{query:X.z.optional(X.z.object({token:X.z.string().optional(),currentURL:X.z.string().optional()})),method:"POST",body:X.z.object({newPassword:X.z.string({description:"The new password to set"}),token:X.z.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new uo.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:o}=e.body,i=`reset-password:${t}`,r=await e.context.internalAdapter.findVerificationValue(i);if(!r||r.expiresAt<new Date)throw new uo.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(r.id);let n=r.value,a=await e.context.password.hash(o);return(await e.context.internalAdapter.findAccounts(n)).find(A=>A.providerId==="credential")?(await e.context.internalAdapter.updatePassword(n,a),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:a,accountId:n}),e.json({status:!0}))});var L=require("zod");var G=require("better-call");var bi=()=>c("/update-user",{method:"POST",body:L.z.record(L.z.string(),L.z.any()),use:[v],metadata:{openapi:{description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"}}}}}}}}}},async e=>{let t=e.body;if(t.email)throw new G.APIError("BAD_REQUEST",{message:"You can't update email"});let{name:o,image:i,...r}=t,n=e.context.session;if(!i&&!o&&Object.keys(r).length===0)return e.json({user:n.user});let a=so(e.context.options,r,"update"),s=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:o,image:i,...a});return await m(e,{session:n.session,user:s}),e.json({user:s})}),vi=c("/change-password",{method:"POST",body:L.z.object({newPassword:L.z.string({description:"The new password to set"}),currentPassword:L.z.string({description:"The current password"}),revokeOtherSessions:L.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[v],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:o,revokeOtherSessions:i}=e.body,r=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new G.APIError("BAD_REQUEST",{message:"Password is too short"});let a=e.context.password.config.maxPasswordLength;if(t.length>a)throw e.context.logger.error("Password is too long"),new G.APIError("BAD_REQUEST",{message:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(r.user.id)).find(u=>u.providerId==="credential"&&u.password);if(!d||!d.password)throw new G.APIError("BAD_REQUEST",{message:"User does not have a password"});let A=await e.context.password.hash(t);if(!await e.context.password.verify({hash:d.password,password:o}))throw new G.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:A}),i){await e.context.internalAdapter.deleteSessions(r.user.id);let u=await e.context.internalAdapter.createSession(r.user.id,e.headers);if(!u)throw new G.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await m(e,{session:u,user:r.user})}return e.json(r.user)}),ki=c("/set-password",{method:"POST",body:L.z.object({newPassword:L.z.string()}),metadata:{SERVER_ONLY:!0},use:[v]},async e=>{let{newPassword:t}=e.body,o=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new G.APIError("BAD_REQUEST",{message:"Password is too short"});let r=e.context.password.config.maxPasswordLength;if(t.length>r)throw e.context.logger.error("Password is too long"),new G.APIError("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(o.user.id)).find(d=>d.providerId==="credential"&&d.password),s=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:o.user.id,providerId:"credential",accountId:o.user.id,password:s}),e.json(o.user);throw new G.APIError("BAD_REQUEST",{message:"user already has a password"})}),Ti=c("/delete-user",{method:"POST",body:L.z.object({password:L.z.string({description:"The password of the user"})}),use:[He],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{let t=e.context.session;return await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),Q(e),e.json(null)}),Oi=c("/change-email",{method:"POST",query:L.z.object({currentURL:L.z.string().optional()}).optional(),body:L.z.object({newEmail:L.z.string({description:"The new email to set"}).email(),callbackURL:L.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[v],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new G.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new G.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new G.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let r=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:r,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new G.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let o=await Ke(e.context.secret,e.context.session.user.email,e.body.newEmail),i=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:i,token:o},e.request),e.json({user:null,status:!0})});var Se=require("zod");var So=require("better-call");var Ii=c("/list-accounts",{method:"GET",use:[v],metadata:{openapi:{description:"List all accounts linked to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},provider:{type:"string"}}}}}}}}}}},async e=>{let t=e.context.session,o=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(o.map(i=>({id:i.id,provider:i.providerId})))}),Ui=c("/link-social",{method:"POST",requireHeaders:!0,query:Se.z.object({currentURL:Se.z.string().optional()}).optional(),body:Se.z.object({callbackURL:Se.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:Se.z.enum(Ko,{description:"The OAuth2 provider to use"})}),use:[v],metadata:{openapi:{description:"Link a social account to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}},required:["url","redirect"]}}}}}}}},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(s=>s.providerId===e.body.provider))throw new So.APIError("BAD_REQUEST",{message:"Social Account is already linked."});let r=e.context.socialProviders.find(s=>s.id===e.body.provider);if(!r)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new So.APIError("NOT_FOUND",{message:"Provider not found"});let n=await Ue(e,{userId:t.user.id,email:t.user.email}),a=await r.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${r.id}`});return e.json({url:a.toString(),redirect:!0})});var Kt=(e,t)=>{let o={};for(let[i,r]of Object.entries(e))o[i]=n=>r({...n,context:{...t,...n.context}}),o[i].path=r.path,o[i].method=r.method,o[i].options=r.options,o[i].headers=r.headers;return o};function lo(e){let t=e;return{newRole(o){return Or(o)}}}function Or(e){return{statements:e,authorize(t,o){for(let[i,r]of Object.entries(t)){let n=e[i];return n?(o==="OR"?r.some(s=>n.includes(s)):r.every(s=>n.includes(s)))?{success:!0}:{success:!1,error:`Unauthorized to access resource "${i}"`}:{success:!1,error:`You are not allowed to access resource: ${i}`}}return{success:!1,error:"Not authorized"}}}}var Ir={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},Do=lo(Ir),Ur=Do.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),Rr=Do.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),Pr=Do.newRole({organization:[],member:[],invitation:[]}),pt={admin:Ur,owner:Rr,member:Pr};var z=(e,t)=>{let o=e.adapter;return{findOrganizationBySlug:async i=>await o.findOne({model:"organization",where:[{field:"slug",value:i}]}),createOrganization:async i=>{let r=await o.create({model:"organization",data:{...i.organization,metadata:i.organization.metadata?JSON.stringify(i.organization.metadata):void 0}}),n=await o.create({model:"member",data:{organizationId:r.id,userId:i.user.id,createdAt:new Date,role:t?.creatorRole||"owner"}});return{...r,metadata:r.metadata?JSON.parse(r.metadata):void 0,members:[{...n,user:{id:i.user.id,name:i.user.name,email:i.user.email,image:i.user.image}}]}},findMemberByEmail:async i=>{let r=await o.findOne({model:"user",where:[{field:"email",value:i.email}]});if(!r)return null;let n=await o.findOne({model:"member",where:[{field:"organizationId",value:i.organizationId},{field:"userId",value:r.id}]});return n?{...n,user:{id:r.id,name:r.name,email:r.email,image:r.image}}:null},findMemberByOrgId:async i=>{let[r,n]=await Promise.all([await o.findOne({model:"member",where:[{field:"userId",value:i.userId},{field:"organizationId",value:i.organizationId}]}),await o.findOne({model:"user",where:[{field:"id",value:i.userId}]})]);return!n||!r?null:{...r,user:{id:n.id,name:n.name,email:n.email,image:n.image}}},findMemberById:async i=>{let r=await o.findOne({model:"member",where:[{field:"id",value:i}]});if(!r)return null;let n=await o.findOne({model:"user",where:[{field:"id",value:r.userId}]});return n?{...r,user:{id:n.id,name:n.name,email:n.email,image:n.image}}:null},createMember:async i=>await o.create({model:"member",data:i}),updateMember:async(i,r)=>await o.update({model:"member",where:[{field:"id",value:i}],update:{role:r}}),deleteMember:async i=>await o.delete({model:"member",where:[{field:"id",value:i}]}),updateOrganization:async(i,r)=>await o.update({model:"organization",where:[{field:"id",value:i}],update:{...r,metadata:r.metadata?JSON.stringify(r.metadata):void 0}}),deleteOrganization:async i=>(await o.delete({model:"member",where:[{field:"organizationId",value:i}]}),await o.delete({model:"invitation",where:[{field:"organizationId",value:i}]}),await o.delete({model:"organization",where:[{field:"id",value:i}]}),i),setActiveOrganization:async(i,r)=>await e.internalAdapter.updateSession(i,{activeOrganizationId:r}),findOrganizationById:async i=>await o.findOne({model:"organization",where:[{field:"id",value:i}]}),findFullOrganization:async({organizationId:i,isSlug:r})=>{let n=await o.findOne({model:"organization",where:[{field:r?"slug":"id",value:i}]});if(!n)return null;let[a,s]=await Promise.all([o.findMany({model:"invitation",where:[{field:"organizationId",value:n.id}]}),o.findMany({model:"member",where:[{field:"organizationId",value:n.id}]})]);if(!n)return null;let d=s.map(p=>p.userId),A=await o.findMany({model:"user",where:[{field:"id",value:d,operator:"in"}]}),K=new Map(A.map(p=>[p.id,p])),u=s.map(p=>{let l=K.get(p.userId);if(!l)throw new ee("Unexpected error: User not found for member");return{...p,user:{id:l.id,name:l.name,email:l.email,image:l.image}}});return{...n,invitations:a,members:u}},listOrganizations:async i=>{let r=await o.findMany({model:"member",where:[{field:"userId",value:i}]});if(!r||r.length===0)return[];let n=r.map(s=>s.organizationId);return await o.findMany({model:"organization",where:[{field:"id",value:n,operator:"in"}]})},createInvitation:async({invitation:i,user:r})=>{let a=R(t?.invitationExpiresIn||1728e5);return await o.create({model:"invitation",data:{email:i.email,role:i.role,organizationId:i.organizationId,status:"pending",expiresAt:a,inviterId:r.id}})},findInvitationById:async i=>await o.findOne({model:"invitation",where:[{field:"id",value:i}]}),findPendingInvitation:async i=>(await o.findMany({model:"invitation",where:[{field:"email",value:i.email},{field:"organizationId",value:i.organizationId},{field:"status",value:"pending"}]})).filter(n=>new Date(n.expiresAt)>new Date),updateInvitation:async i=>await o.update({model:"invitation",where:[{field:"id",value:i.invitationId}],update:{status:i.status}})}};var lA=require("better-call");var B=P(async e=>({})),M=P({use:[v]},async e=>({session:e.context.session}));var W=require("zod");var E=require("zod");var ut=E.z.string(),Er=E.z.enum(["pending","accepted","rejected","canceled"]).default("pending"),wA=E.z.object({id:E.z.string().default(V),name:E.z.string(),slug:E.z.string(),logo:E.z.string().nullish(),metadata:E.z.record(E.z.string()).or(E.z.string().transform(e=>JSON.parse(e))).nullish(),createdAt:E.z.date()}),CA=E.z.object({id:E.z.string().default(V),organizationId:E.z.string(),userId:E.z.string(),role:ut,createdAt:E.z.date()}),bA=E.z.object({id:E.z.string().default(V),organizationId:E.z.string(),email:E.z.string(),role:ut,status:Er,inviterId:E.z.string(),expiresAt:E.z.date()});var j=require("better-call"),lt=e=>c("/organization/invite-member",{method:"POST",use:[B,M],body:W.z.object({email:W.z.string({description:"The email address of the user to invite"}),role:W.z.string({description:"The role to assign to the user"}),organizationId:W.z.string({description:"The organization ID to invite the user to"}).optional(),resend:W.z.boolean({description:"Resend the invitation email, if the user is already invited"}).optional()}),metadata:{openapi:{description:"Invite a user to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt"]}}}}}}}},async t=>{if(!t.context.orgOptions.sendInvitationEmail)throw t.context.logger.warn("Invitation email is not enabled. Pass `sendInvitationEmail` to the plugin options to enable it."),new j.APIError("BAD_REQUEST",{message:"Invitation email is not enabled"});let o=t.context.session,i=t.body.organizationId||o.session.activeOrganizationId;if(!i)throw new j.APIError("BAD_REQUEST",{message:"Organization not found"});let r=z(t.context,t.context.orgOptions),n=await r.findMemberByOrgId({userId:o.user.id,organizationId:i});if(!n)throw new j.APIError("BAD_REQUEST",{message:"Member not found!"});let a=t.context.roles[n.role];if(!a)throw new j.APIError("BAD_REQUEST",{message:"Role not found!"});if(a.authorize({invitation:["create"]}).error)throw new j.APIError("FORBIDDEN",{message:"You are not allowed to invite members"});if(await r.findMemberByEmail({email:t.body.email,organizationId:i}))throw new j.APIError("BAD_REQUEST",{message:"User is already a member of this organization"});if((await r.findPendingInvitation({email:t.body.email,organizationId:i})).length&&!t.body.resend)throw new j.APIError("BAD_REQUEST",{message:"User is already invited to this organization"});let K=await r.createInvitation({invitation:{role:t.body.role,email:t.body.email,organizationId:i},user:o.user}),u=await r.findOrganizationById(i);if(!u)throw new j.APIError("BAD_REQUEST",{message:"Organization not found"});return await t.context.orgOptions.sendInvitationEmail?.({id:K.id,role:K.role,email:K.email,organization:u,inviter:{...n,user:o.user}},t.request),t.json(K)}),gt=c("/organization/accept-invitation",{method:"POST",body:W.z.object({invitationId:W.z.string({description:"The ID of the invitation to accept"})}),use:[B,M],metadata:{openapi:{description:"Accept an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"},member:{type:"object"}}}}}}}}}},async e=>{let t=e.context.session,o=z(e.context,e.context.orgOptions),i=await o.findInvitationById(e.body.invitationId);if(!i||i.expiresAt<new Date||i.status!=="pending")throw new j.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(i.email!==t.user.email)throw new j.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let r=await o.updateInvitation({invitationId:e.body.invitationId,status:"accepted"}),n=await o.createMember({organizationId:i.organizationId,userId:t.user.id,role:i.role,createdAt:new Date});return await o.setActiveOrganization(t.session.token,i.organizationId),r?e.json({invitation:r,member:n}):e.json(null,{status:400,body:{message:"Invitation not found!"}})}),mt=c("/organization/reject-invitation",{method:"POST",body:W.z.object({invitationId:W.z.string({description:"The ID of the invitation to reject"})}),use:[B,M],metadata:{openapi:{description:"Reject an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"},member:{type:"null"}}}}}}}}}},async e=>{let t=e.context.session,o=z(e.context,e.context.orgOptions),i=await o.findInvitationById(e.body.invitationId);if(!i||i.expiresAt<new Date||i.status!=="pending")throw new j.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(i.email!==t.user.email)throw new j.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let r=await o.updateInvitation({invitationId:e.body.invitationId,status:"rejected"});return e.json({invitation:r,member:null})}),ft=c("/organization/cancel-invitation",{method:"POST",body:W.z.object({invitationId:W.z.string({description:"The ID of the invitation to cancel"})}),use:[B,M],openapi:{description:"Cancel an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"}}}}}}}}},async e=>{let t=e.context.session,o=z(e.context,e.context.orgOptions),i=await o.findInvitationById(e.body.invitationId);if(!i)throw new j.APIError("BAD_REQUEST",{message:"Invitation not found!"});let r=await o.findMemberByOrgId({userId:t.user.id,organizationId:i.organizationId});if(!r)throw new j.APIError("BAD_REQUEST",{message:"Member not found!"});if(e.context.roles[r.role].authorize({invitation:["cancel"]}).error)throw new j.APIError("FORBIDDEN",{message:"You are not allowed to cancel this invitation"});let a=await o.updateInvitation({invitationId:e.body.invitationId,status:"canceled"});return e.json(a)}),ht=c("/organization/get-invitation",{method:"GET",use:[B],requireHeaders:!0,query:W.z.object({id:W.z.string({description:"The ID of the invitation to get"})}),metadata:{openapi:{description:"Get an invitation by ID",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"},organizationName:{type:"string"},organizationSlug:{type:"string"},inviterEmail:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt","organizationName","organizationSlug","inviterEmail"]}}}}}}}},async e=>{let t=await U(e);if(!t)throw new j.APIError("UNAUTHORIZED",{message:"Not authenticated"});let o=z(e.context,e.context.orgOptions),i=await o.findInvitationById(e.query.id);if(!i||i.status!=="pending"||i.expiresAt<new Date)throw new j.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(i.email!==t.user.email)throw new j.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let r=await o.findOrganizationById(i.organizationId);if(!r)throw new j.APIError("BAD_REQUEST",{message:"Organization not found"});let n=await o.findMemberByOrgId({userId:i.inviterId,organizationId:i.organizationId});if(!n)throw new j.APIError("BAD_REQUEST",{message:"Inviter is no longer a member of the organization"});return e.json({...i,organizationName:r.name,organizationSlug:r.slug,inviterEmail:n.user.email})});var te=require("zod");var ge=require("better-call");var yt=()=>c("/organization/add-member",{method:"POST",body:te.z.object({userId:te.z.string(),role:te.z.string(),organizationId:te.z.string().optional()}),use:[B],metadata:{SERVER_ONLY:!0}},async e=>{let t=e.body.userId?await U(e).catch(s=>null):null,o=e.body.organizationId||t?.session.activeOrganizationId;if(!o)return e.json(null,{status:400,body:{message:"No active organization found!"}});let i=z(e.context,e.context.orgOptions),r=await e.context.internalAdapter.findUserById(e.body.userId);if(!r)throw new ge.APIError("BAD_REQUEST",{message:"User not found!"});if(await i.findMemberByEmail({email:r.email,organizationId:o}))throw new ge.APIError("BAD_REQUEST",{message:"User is already a member of this organization"});let a=await i.createMember({id:V(),organizationId:o,userId:r.id,role:e.body.role,createdAt:new Date});return e.json(a)}),wt=c("/organization/remove-member",{method:"POST",body:te.z.object({memberIdOrEmail:te.z.string({description:"The ID or email of the member to remove"}),organizationId:te.z.string({description:"The ID of the organization to remove the member from. If not provided, the active organization will be used"}).optional()}),use:[B,M],metadata:{openapi:{description:"Remove a member from an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{member:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}},required:["member"]}}}}}}}},async e=>{let t=e.context.session,o=e.body.organizationId||t.session.activeOrganizationId;if(!o)return e.json(null,{status:400,body:{message:"No active organization found!"}});let i=z(e.context,e.context.orgOptions),r=await i.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!r)throw new ge.APIError("BAD_REQUEST",{message:"Member not found!"});let n=e.context.roles[r.role];if(!n)throw new ge.APIError("BAD_REQUEST",{message:"Role not found!"});let a=t.user.email===e.body.memberIdOrEmail||r.id===e.body.memberIdOrEmail;if(a&&r.role===(e.context.orgOptions?.creatorRole||"owner"))throw new ge.APIError("BAD_REQUEST",{message:"You cannot leave the organization as the owner"});if(!(a||n.authorize({member:["delete"]}).success))throw new ge.APIError("UNAUTHORIZED",{message:"You are not allowed to delete this member"});let A=null;if(e.body.memberIdOrEmail.includes("@")?A=await i.findMemberByEmail({email:e.body.memberIdOrEmail,organizationId:o}):A=await i.findMemberById(e.body.memberIdOrEmail),A?.organizationId!==o)throw new ge.APIError("BAD_REQUEST",{message:"Member not found!"});return await i.deleteMember(A.id),t.user.id===A.userId&&t.session.activeOrganizationId===A.organizationId&&await i.setActiveOrganization(t.session.token,null),e.json({member:A})}),Ct=e=>c("/organization/update-member-role",{method:"POST",body:te.z.object({role:te.z.string(),memberId:te.z.string(),organizationId:te.z.string().optional()}),use:[B,M],metadata:{openapi:{description:"Update the role of a member in an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{member:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}},required:["member"]}}}}}}}},async t=>{let o=t.context.session,i=t.body.organizationId||o.session.activeOrganizationId;if(!i)return t.json(null,{status:400,body:{message:"No active organization found!"}});let r=z(t.context,t.context.orgOptions),n=await r.findMemberByOrgId({userId:o.user.id,organizationId:i});if(!n)return t.json(null,{status:400,body:{message:"Member not found!"}});let a=t.context.roles[n.role];if(!a)return t.json(null,{status:400,body:{message:"Role not found!"}});if(a.authorize({member:["update"]}).error||t.body.role==="owner"&&n.role!=="owner")return t.json(null,{body:{message:"You are not allowed to update this member"},status:403});let d=await r.updateMember(t.body.memberId,t.body.role);return d?t.json(d):t.json(null,{status:400,body:{message:"Member not found!"}})}),bt=c("/organization/get-active-member",{method:"GET",use:[B,M],metadata:{openapi:{description:"Get the active member in the organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}}}}}}}},async e=>{let t=e.context.session,o=t.session.activeOrganizationId;if(!o)return e.json(null,{status:400,body:{message:"No active organization found!"}});let r=await z(e.context,e.context.orgOptions).findMemberByOrgId({userId:t.user.id,organizationId:o});return r?e.json(r):e.json(null,{status:400,body:{message:"Member not found!"}})});var O=require("zod");var me=require("better-call");var vt=c("/organization/create",{method:"POST",body:O.z.object({name:O.z.string({description:"The name of the organization"}),slug:O.z.string({description:"The slug of the organization"}),userId:O.z.string({description:"The user id of the organization creator. If not provided, the current user will be used. Should only be used by admins or when called by the server."}).optional(),logo:O.z.string({description:"The logo of the organization"}).optional(),metadata:O.z.record(O.z.string(),O.z.any(),{description:"The metadata of the organization"}).optional()}),use:[B,M],metadata:{openapi:{description:"Create an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization that was created",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=e.context.session.user;if(!t)return e.json(null,{status:401});let o=e.context.orgOptions;if(!(typeof o?.allowUserToCreateOrganization=="function"?await o.allowUserToCreateOrganization(t):o?.allowUserToCreateOrganization===void 0?!0:o.allowUserToCreateOrganization))throw new me.APIError("FORBIDDEN",{message:"You are not allowed to create an organization"});let r=z(e.context,o),n=await r.listOrganizations(t.id);if(typeof o.organizationLimit=="number"?n.length>=o.organizationLimit:typeof o.organizationLimit=="function"?await o.organizationLimit(t):!1)throw new me.APIError("FORBIDDEN",{message:"You have reached the organization limit"});if(await r.findOrganizationBySlug(e.body.slug))throw new me.APIError("BAD_REQUEST",{message:"Organization with this slug already exists"});let d=await r.createOrganization({organization:{id:V(),slug:e.body.slug,name:e.body.name,logo:e.body.logo,createdAt:new Date,metadata:e.body.metadata},user:t});return await r.setActiveOrganization(e.context.session.session.token,d.id),e.json(d)}),kt=c("/organization/update",{method:"POST",body:O.z.object({data:O.z.object({name:O.z.string({description:"The name of the organization"}).optional(),slug:O.z.string({description:"The slug of the organization"}).optional(),logo:O.z.string({description:"The logo of the organization"}).optional(),metadata:O.z.record(O.z.string(),O.z.any(),{description:"The metadata of the organization"}).optional()}).partial(),organizationId:O.z.string().optional()}),requireHeaders:!0,use:[B],metadata:{openapi:{description:"Update an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The updated organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=await e.context.getSession(e);if(!t)throw new me.APIError("UNAUTHORIZED",{message:"User not found"});let o=e.body.organizationId||t.session.activeOrganizationId;if(!o)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let i=z(e.context,e.context.orgOptions),r=await i.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!r)return e.json(null,{status:400,body:{message:"User is not a member of this organization!"}});let n=e.context.roles[r.role];if(!n)return e.json(null,{status:400,body:{message:"Role not found!"}});if(n.authorize({organization:["update"]}).error)return e.json(null,{body:{message:"You are not allowed to update this organization"},status:403});let s=await i.updateOrganization(o,e.body.data);return e.json(s)}),Tt=c("/organization/delete",{method:"POST",body:O.z.object({organizationId:O.z.string({description:"The organization id to delete"})}),requireHeaders:!0,use:[B],metadata:{openapi:{description:"Delete an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string",description:"The organization id that was deleted"}}}}}}}},async e=>{let t=await e.context.getSession(e);if(!t)return e.json(null,{status:401});let o=e.body.organizationId;if(!o)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let i=z(e.context,e.context.orgOptions),r=await i.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!r)return e.json(null,{status:400,body:{message:"User is not a member of this organization!"}});let n=e.context.roles[r.role];if(!n)return e.json(null,{status:400,body:{message:"Role not found!"}});if(n.authorize({organization:["delete"]}).error)throw new me.APIError("FORBIDDEN",{message:"You are not allowed to delete this organization"});return o===t.session.activeOrganizationId&&await i.setActiveOrganization(t.session.token,null),await i.deleteOrganization(o),e.json(o)}),Ot=c("/organization/get-full-organization",{method:"GET",query:O.z.optional(O.z.object({organizationId:O.z.string({description:"The organization id to get"}).optional(),organizationSlug:O.z.string({description:"The organization slug to get"}).optional()})),requireHeaders:!0,use:[B,M],metadata:{openapi:{description:"Get the full organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=e.context.session,o=e.query?.organizationSlug||e.query?.organizationId||t.session.activeOrganizationId;if(!o)return e.json(null,{status:200});let r=await z(e.context,e.context.orgOptions).findFullOrganization({organizationId:o,isSlug:!!e.query?.organizationSlug});if(!r)throw new me.APIError("BAD_REQUEST",{message:"Organization not found"});return e.json(r)}),It=c("/organization/set-active",{method:"POST",body:O.z.object({organizationId:O.z.string({description:"The organization id to set as active. It can be null to unset the active organization"}).nullable().optional(),organizationSlug:O.z.string({description:"The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided"}).optional()}),use:[M,B],metadata:{openapi:{description:"Set the active organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let t=z(e.context,e.context.orgOptions),o=e.context.session,i=e.body.organizationSlug||e.body.organizationId;if(i===null){if(!o.session.activeOrganizationId)return e.json(null);let d=await t.setActiveOrganization(o.session.token,null);return await m(e,{session:d,user:o.user}),e.json(null)}if(!i){let s=o.session.activeOrganizationId;if(!s)return e.json(null);i=s}let r=await t.findFullOrganization({organizationId:i,isSlug:!!e.body.organizationSlug});if(!r?.members.find(s=>s.userId===o.user.id))throw await t.setActiveOrganization(o.session.token,null),new me.APIError("FORBIDDEN",{message:"You are not a member of this organization"});let a=await t.setActiveOrganization(o.session.token,i);return await m(e,{session:a,user:o.user}),e.json(r)}),Ut=c("/organization/list",{method:"GET",use:[B,M],metadata:{openapi:{description:"List all organizations",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Organization"}}}}}}}}},async e=>{let o=await z(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(o)});var Sr=lo({name:["action"]}),JA=Sr.newRole({name:["action"]}),Dr=e=>{let t={createOrganization:vt,updateOrganization:kt,deleteOrganization:Tt,setActiveOrganization:It,getFullOrganization:Ot,listOrganizations:Ut,createInvitation:lt(e),cancelInvitation:ft,acceptInvitation:gt,getInvitation:ht,rejectInvitation:mt,addMember:yt(),removeMember:wt,updateMemberRole:Ct(e),getActiveMember:bt},o={...pt,...e?.roles};return{id:"organization",endpoints:{...Kt(t,{orgOptions:e||{},roles:o,getSession:async r=>await U(r)}),hasPermission:c("/organization/has-permission",{method:"POST",requireHeaders:!0,body:De.z.object({permission:De.z.record(De.z.string(),De.z.array(De.z.string()))}),use:[M],metadata:{openapi:{description:"Check if the user has permission",requestBody:{content:{"application/json":{schema:{type:"object",properties:{permission:{type:"object",description:"The permission to check"}},required:["permission"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},success:{type:"boolean"}},required:["success"]}}}}}}}},async r=>{if(!r.context.session.session.activeOrganizationId)throw new xo.APIError("BAD_REQUEST",{message:"No active organization"});let a=await z(r.context).findMemberByOrgId({userId:r.context.session.user.id,organizationId:r.context.session.session.activeOrganizationId||""});if(!a)throw new xo.APIError("UNAUTHORIZED",{message:"You are not a member of this organization"});let d=o[a.role].authorize(r.body.permission);return d.error?r.json({error:d.error,success:!1},{status:403}):r.json({error:null,success:!0})})},schema:{session:{fields:{activeOrganizationId:{type:"string",required:!1,fieldName:e?.schema?.session?.fields?.activeOrganizationId}}},organization:{modelName:e?.schema?.organization?.modelName,fields:{name:{type:"string",required:!0,fieldName:e?.schema?.organization?.fields?.name},slug:{type:"string",unique:!0,fieldName:e?.schema?.organization?.fields?.slug},logo:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.logo},createdAt:{type:"date",required:!0,fieldName:e?.schema?.organization?.fields?.createdAt},metadata:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.metadata}}},member:{modelName:e?.schema?.member?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.member?.fields?.organizationId},userId:{type:"string",required:!0,fieldName:e?.schema?.member?.fields?.userId,references:{model:"user",field:"id"}},role:{type:"string",required:!0,defaultValue:"member",fieldName:e?.schema?.member?.fields?.role},createdAt:{type:"date",required:!0,fieldName:e?.schema?.member?.fields?.createdAt}}},invitation:{modelName:e?.schema?.invitation?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.invitation?.fields?.organizationId},email:{type:"string",required:!0,fieldName:e?.schema?.invitation?.fields?.email},role:{type:"string",required:!1,fieldName:e?.schema?.invitation?.fields?.role},status:{type:"string",required:!0,defaultValue:"pending",fieldName:e?.schema?.invitation?.fields?.status},expiresAt:{type:"date",required:!0,fieldName:e?.schema?.invitation?.fields?.expiresAt},inviterId:{type:"string",references:{model:"user",field:"id"},fieldName:e?.schema?.invitation?.fields?.inviterId,required:!0}}}},$Infer:{Organization:{},Invitation:{},Member:{},ActiveOrganization:{}}}};var jo=Yo(require("uncrypto"),1);function xr(e){return e.toString(2).padStart(8,"0")}function jr(e){return[...e].map(t=>xr(t)).join("")}function Rt(e){return parseInt(jr(e),2)}function zr(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,o=t%8,i=new Uint8Array(Math.ceil(t/8));jo.default.getRandomValues(i),o!==0&&(i[0]&=(1<<o)-1);let r=Rt(i);for(;r>=e;)jo.default.getRandomValues(i),o!==0&&(i[0]&=(1<<o)-1),r=Rt(i);return r}function _(e,t){let o="";for(let i=0;i<e;i++)o+=t[zr(t.length)];return o}function F(...e){let t=new Set(e),o="";for(let i of t)i==="a-z"?o+="abcdefghijklmnopqrstuvwxyz":i==="A-Z"?o+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":i==="0-9"?o+="0123456789":o+=i;return o}var We=require("zod");var Bo=require("@noble/ciphers/chacha"),xe=require("@noble/ciphers/utils"),No=require("@noble/ciphers/webcrypto"),Lo=require("oslo/crypto"),zo=Yo(require("uncrypto"),1);var Pt=require("oslo/encoding");var Br=require("@noble/hashes/scrypt"),Nr=require("uncrypto");async function $e(e,t){let o=new TextEncoder,i={name:"HMAC",hash:"SHA-256"},r=await zo.default.subtle.importKey("raw",o.encode(e),i,!1,["sign","verify"]),n=await zo.default.subtle.sign(i.name,r,o.encode(t));return btoa(String.fromCharCode(...new Uint8Array(n)))}var ue=async({key:e,data:t})=>{let o=await(0,Lo.sha256)(new TextEncoder().encode(e)),i=(0,xe.utf8ToBytes)(t),r=(0,No.managedNonce)(Bo.xchacha20poly1305)(new Uint8Array(o));return(0,xe.bytesToHex)(r.encrypt(i))},fe=async({key:e,data:t})=>{let o=await(0,Lo.sha256)(new TextEncoder().encode(e)),i=(0,xe.hexToBytes)(t),r=(0,No.managedNonce)(Bo.xchacha20poly1305)(new Uint8Array(o));return new TextDecoder().decode(r.decrypt(i))};var Ae=require("zod");var je=require("better-call");var go="two_factor";var mo="trust_device";var _o=require("zod");var be=P({body:_o.z.object({trustDevice:_o.z.boolean().optional()})},async e=>{let t=await U(e);if(!t){let o=e.context.createAuthCookie(go),i=await e.getSignedCookie(o.name,e.context.secret);if(!i)throw new je.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let r=await e.context.internalAdapter.findUserById(i);if(!r)throw new je.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let n=await e.context.internalAdapter.createSession(i,e.request);if(!n)throw new je.APIError("INTERNAL_SERVER_ERROR",{message:"failed to create session"});return{valid:async()=>{if(await m(e,{session:n,user:r}),e.body.trustDevice){let a=e.context.createAuthCookie(mo,{maxAge:2592e3}),s=await $e(e.context.secret,`${r.id}!${n.token}`);await e.setSignedCookie(a.name,`${s}!${n.token}`,e.context.secret,a.attributes)}return e.json({session:n,user:r})},invalid:async()=>{throw new je.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:{id:n.token,userId:n.userId,expiresAt:n.expiresAt,user:r}}}return{valid:async()=>e.json({session:t,user:t.user}),invalid:async()=>{throw new je.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:t}});var ze=require("better-call");function Lr(e){return Array.from({length:e?.amount??10}).fill(null).map(()=>_(e?.length??10,F("a-z","0-9"))).map(t=>`${t.slice(0,5)}-${t.slice(5)}`)}async function Fo(e,t){let o=e,i=t?.customBackupCodesGenerate?t.customBackupCodesGenerate():Lr(),r=await ue({data:JSON.stringify(i),key:o});return{backupCodes:i,encryptedBackupCodes:r}}async function _r(e,t){let o=await Et(e.backupCodes,t);return o?{status:o.includes(e.code),updated:o.filter(i=>i!==e.code)}:{status:!1,updated:null}}async function Et(e,t){let o=Buffer.from(await fe({key:t,data:e})).toString("utf-8"),i=JSON.parse(o),r=Ae.z.array(Ae.z.string()).safeParse(i);return r.success?r.data:null}var St=(e,t)=>({id:"backup_code",endpoints:{verifyBackupCode:c("/two-factor/verify-backup-code",{method:"POST",body:Ae.z.object({code:Ae.z.string(),disableSession:Ae.z.boolean().optional()}),use:[be]},async o=>{let i=o.context.session.user,r=await o.context.adapter.findOne({model:t,where:[{field:"userId",value:i.id}]});if(!r)throw new ze.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let n=await _r({backupCodes:r.backupCodes,code:o.body.code},o.context.secret);if(!n.status)throw new ze.APIError("UNAUTHORIZED",{message:"Invalid backup code"});let a=await ue({key:o.context.secret,data:JSON.stringify(n.updated)});return await o.context.adapter.update({model:t,update:{backupCodes:a},where:[{field:"userId",value:i.id}]}),o.body.disableSession||await m(o,{session:o.context.session.session,user:i}),o.json({user:i,session:o.context.session})}),generateBackupCodes:c("/two-factor/generate-backup-codes",{method:"POST",body:Ae.z.object({password:Ae.z.string()}),use:[v]},async o=>{let i=o.context.session.user;if(!i.twoFactorEnabled)throw new ze.APIError("BAD_REQUEST",{message:"Two factor isn't enabled"});await o.context.password.checkPassword(i.id,o);let r=await Fo(o.context.secret,e);return await o.context.adapter.update({model:t,update:{backupCodes:r.encryptedBackupCodes},where:[{field:"userId",value:o.context.session.user.id}]}),o.json({status:!0,backupCodes:r.backupCodes})}),viewBackupCodes:c("/two-factor/view-backup-codes",{method:"GET",body:Ae.z.object({userId:Ae.z.string()}),metadata:{SERVER_ONLY:!0}},async o=>{let i=await o.context.adapter.findOne({model:t,where:[{field:"userId",value:o.body.userId}]});if(!i)throw new ze.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let r=await Et(i.backupCodes,o.context.secret);if(!r)throw new ze.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});return o.json({status:!0,backupCodes:r})})}});var Be=require("better-call"),Vo=require("zod");var Dt=require("oslo");var xt=(e,t)=>{let o={...e,digits:e?.digits||6,period:new Dt.TimeSpan(e?.period||3,"m")},i=c("/two-factor/send-otp",{method:"POST",use:[be],metadata:{openapi:{summary:"Send two factor OTP",description:"Send two factor OTP to the user",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async n=>{if(!e||!e.sendOTP)throw n.context.logger.error("send otp isn't configured. Please configure the send otp function on otp options."),new Be.APIError("BAD_REQUEST",{message:"otp isn't configured"});let a=n.context.session.user;if(!await n.context.adapter.findOne({model:t,where:[{field:"userId",value:a.id}]}))throw new Be.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});let d=_(o.digits,F("0-9"));return await n.context.internalAdapter.createVerificationValue({value:d,identifier:`2fa-otp-${a.id}`,expiresAt:new Date(Date.now()+o.period.milliseconds())}),await e.sendOTP({user:a,otp:d},n.request),n.json({status:!0})}),r=c("/two-factor/verify-otp",{method:"POST",body:Vo.z.object({code:Vo.z.string({description:"The otp code to verify"})}),use:[be],metadata:{openapi:{summary:"Verify two factor OTP",description:"Verify two factor OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async n=>{let a=n.context.session.user;if(!a.twoFactorEnabled)throw new Be.APIError("BAD_REQUEST",{message:"two factor isn't enabled"});if(!await n.context.adapter.findOne({model:t,where:[{field:"userId",value:a.id}]}))throw new Be.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});let d=await n.context.internalAdapter.findVerificationValue(`2fa-otp-${a.id}`);if(!d||d.expiresAt<new Date)throw new Be.APIError("BAD_REQUEST",{message:"OTP has expired"});return d.value===n.body.code?n.context.valid():n.context.invalid()});return{id:"otp",endpoints:{sendTwoFactorOTP:i,verifyTwoFactorOTP:r}}};var ve=require("better-call"),jt=require("oslo"),Ge=require("oslo/otp"),Ze=require("zod");var zt=(e,t)=>{let o={...e,digits:e?.digits||6,period:new jt.TimeSpan(e?.period||30,"s")},i=c("/totp/generate",{method:"POST",use:[v],metadata:{openapi:{summary:"Generate TOTP code",description:"Use this endpoint to generate a TOTP code",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{code:{type:"string"}}}}}}}}}},async a=>{if(!e)throw a.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new ve.APIError("BAD_REQUEST",{message:"totp isn't configured"});let s=a.context.session.user,d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d)throw new ve.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return{code:await new Ge.TOTPController(o).generate(Buffer.from(d.secret))}}),r=c("/two-factor/get-totp-uri",{method:"POST",use:[v],body:Ze.z.object({password:Ze.z.string({description:"User password"})}),metadata:{openapi:{summary:"Get TOTP URI",description:"Use this endpoint to get the TOTP URI",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{totpURI:{type:"string"}}}}}}}}}},async a=>{if(!e)throw a.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new ve.APIError("BAD_REQUEST",{message:"totp isn't configured"});let s=a.context.session.user,d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d||!s.twoFactorEnabled)throw new ve.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return await a.context.password.checkPassword(s.id,a),{totpURI:(0,Ge.createTOTPKeyURI)(e.issuer||a.context.appName,s.email,Buffer.from(d.secret),o)}}),n=c("/two-factor/verify-totp",{method:"POST",body:Ze.z.object({code:Ze.z.string({description:"The otp code to verify"})}),use:[be],metadata:{openapi:{summary:"Verify two factor TOTP",description:"Verify two factor TOTP",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async a=>{if(!e)throw a.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new ve.APIError("BAD_REQUEST",{message:"totp isn't configured"});let s=a.context.session.user,d=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!d)throw new ve.APIError("BAD_REQUEST",{message:"totp isn't enabled"});let A=new Ge.TOTPController(o),K=await fe({key:a.context.secret,data:d.secret}),u=Buffer.from(K);if(!await A.verify(a.body.code,u))return a.context.invalid();if(!s.twoFactorEnabled){let l=await a.context.internalAdapter.updateUser(s.id,{twoFactorEnabled:!0}),h=await a.context.internalAdapter.createSession(s.id,a.request,!1,a.context.session.session).catch(k=>{throw console.log(k),k});await a.context.internalAdapter.deleteSession(a.context.session.session.token),await m(a,{session:h,user:l})}return a.context.valid()});return{id:"totp",endpoints:{generateTOTP:i,getTOTPURI:r,verifyTOTP:n}}};var Fr=require("better-call");async function qo(e,t){let i=(await e.context.internalAdapter.findAccounts(t.userId))?.find(a=>a.providerId==="credential"),r=i?.password;return!i||!r?!1:await e.context.password.verify({hash:r,password:t.password})}var Mo=require("better-call"),Lt=require("oslo/otp"),_t=require("oslo");var Bt=require("better-call"),Ne=async e=>{let t=e.context.returned;return t?t instanceof Response?t.status!==200?null:await t.clone().json():t instanceof Bt.APIError?null:t:null};var Nt={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 Vr=e=>({id:"two-factor",$InferServerPlugin:{},atomListeners:[{matcher:t=>t.startsWith("/two-factor/"),signal:"$sessionSignal"}],pathMethods:{"/two-factor/disable":"POST","/two-factor/enable":"POST","/two-factor/send-otp":"POST","/two-factor/generate-backup-codes":"POST"},fetchPlugins:[{id:"two-factor",name:"two-factor",hooks:{async onSuccess(t){t.data?.twoFactorRedirect&&e?.onTwoFactorRedirect&&await e.onTwoFactorRedirect()}}}]});var qr=e=>{let t={twoFactorTable:"twoFactor"},o=zt({issuer:e?.issuer,...e?.totpOptions},t.twoFactorTable),i=St({...e?.backupCodeOptions},t.twoFactorTable),r=xt({...e?.otpOptions},t.twoFactorTable);return{id:"two-factor",endpoints:{...o.endpoints,...r.endpoints,...i.endpoints,enableTwoFactor:c("/two-factor/enable",{method:"POST",body:We.z.object({password:We.z.string({description:"User password"}).min(8)}),use:[v],metadata:{openapi:{summary:"Enable two factor authentication",description:"Use this endpoint to enable two factor authentication. This will generate a TOTP URI and backup codes. Once the user verifies the TOTP URI, the two factor authentication will be enabled.",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{totpURI:{type:"string",description:"TOTP URI"},backupCodes:{type:"array",items:{type:"string"},description:"Backup codes"}}}}}}}}}},async n=>{let a=n.context.session.user,{password:s}=n.body;if(!await qo(n,{password:s,userId:a.id}))throw new Mo.APIError("BAD_REQUEST",{message:"Invalid password"});let A=_(16,F("a-z","0-9","-")),K=await ue({key:n.context.secret,data:A}),u=await Fo(n.context.secret,e?.backupCodeOptions);if(e?.skipVerificationOnEnable){let l=await n.context.internalAdapter.updateUser(a.id,{twoFactorEnabled:!0}),h=await n.context.internalAdapter.createSession(l.id,n.request,!1,n.context.session.session);await m(n,{session:h,user:a}),await n.context.internalAdapter.deleteSession(n.context.session.session.token)}await n.context.adapter.deleteMany({model:t.twoFactorTable,where:[{field:"userId",value:a.id}]}),await n.context.adapter.create({model:t.twoFactorTable,data:{secret:K,backupCodes:u.encryptedBackupCodes,userId:a.id}});let p=(0,Lt.createTOTPKeyURI)(e?.issuer||"BetterAuth",a.email,Buffer.from(A),{digits:e?.totpOptions?.digits||6,period:new _t.TimeSpan(e?.totpOptions?.period||30,"s")});return n.json({totpURI:p,backupCodes:u.backupCodes})}),disableTwoFactor:c("/two-factor/disable",{method:"POST",body:We.z.object({password:We.z.string({description:"User password"}).min(8)}),use:[v],metadata:{openapi:{summary:"Disable two factor authentication",description:"Use this endpoint to disable two factor authentication.",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async n=>{let a=n.context.session.user,{password:s}=n.body;if(!await qo(n,{password:s,userId:a.id}))throw new Mo.APIError("BAD_REQUEST",{message:"Invalid password"});await n.context.internalAdapter.updateUser(a.id,{twoFactorEnabled:!1}),await n.context.adapter.delete({model:t.twoFactorTable,where:[{field:"userId",value:a.id}]});let A=await n.context.internalAdapter.createSession(a.id,n.request,!1,n.context.session.session);return await m(n,{session:A,user:a}),await n.context.internalAdapter.deleteSession(n.context.session.session.token),n.json({status:!0})})},options:e,hooks:{after:[{matcher(n){return n.path==="/sign-in/email"||n.path==="/sign-in/username"},handler:P(async n=>{let a=await Ne(n);if(!a||!a.user.twoFactorEnabled)return;let s=n.context.createAuthCookie(mo),d=await n.getSignedCookie(s.name,n.context.secret);if(d){let[K,u]=d.split("!"),p=await $e(n.context.secret,`${a.user.id}!${u}`);if(K===p){let l=await $e(n.context.secret,`${a.user.id}!${a.session.token}`);await n.setSignedCookie(s.name,`${l}!${a.session.token}`,n.context.secret,s.attributes);return}}Q(n),await n.context.internalAdapter.deleteSession(a.session.token);let A=n.context.createAuthCookie(go,{maxAge:60*10});return await n.setSignedCookie(A.name,a.user.id,n.context.secret,A.attributes),n.json({twoFactorRedirect:!0})})}]},schema:ie(Nt,e?.schema),rateLimit:[{pathMatcher(n){return n.startsWith("/two-factor/")},window:10,max:3}]}};var he=require("@simplewebauthn/server"),Z=require("better-call");var Y=require("zod");var Le=require("@simplewebauthn/browser");var Hr=require("@better-fetch/fetch");var cK=require("nanostores");var Xc=require("@better-fetch/fetch");var Mr=require("nanostores");var eK=require("@better-fetch/fetch"),fo=require("nanostores"),Ho=(e,t,o,i)=>{let r=(0,fo.atom)({data:null,error:null,isPending:!0,isRefetching:!1}),n=()=>{let s=typeof i=="function"?i({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):i;return o(t,{...s,async onSuccess(d){r.set({data:d.data,error:null,isPending:!1,isRefetching:!1}),await s?.onSuccess?.(d)},async onError(d){r.set({error:d.error,data:null,isPending:!1,isRefetching:!1}),await s?.onError?.(d)},async onRequest(d){let A=r.get();r.set({isPending:A.data===null,data:A.data,error:null,isRefetching:!0}),await s?.onRequest?.(d)}})};e=Array.isArray(e)?e:[e];let a=!1;for(let s of e)s.subscribe(()=>{a?n():(0,fo.onMount)(r,()=>(n(),a=!0,()=>{r.off(),s.off()}))});return r};var Ft=require("nanostores"),Vt=(e,{$listPasskeys:t})=>({signIn:{passkey:async(r,n)=>{let a=await e("/passkey/generate-authenticate-options",{method:"POST",body:{email:r?.email}});if(!a.data)return a;try{let s=await(0,Le.startAuthentication)(a.data,r?.autoFill||!1),d=await e("/passkey/verify-authentication",{body:{response:s},...r?.fetchOptions,...n,method:"POST"});if(!d.data)return d}catch{return{data:null,error:{message:"auth cancelled",status:400,statusText:"BAD_REQUEST"}}}}},passkey:{addPasskey:async(r,n)=>{let a=await e("/passkey/generate-register-options",{method:"GET"});if(!a.data)return a;try{let s=await(0,Le.startRegistration)(a.data),d=await e("/passkey/verify-registration",{...r?.fetchOptions,...n,body:{response:s,name:r?.name},method:"POST"});if(!d.data)return d;t.set(Math.random())}catch(s){return s instanceof Le.WebAuthnError?s.code==="ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED"?{data:null,error:{message:"previously registered",status:400,statusText:"BAD_REQUEST"}}:s.code==="ERROR_CEREMONY_ABORTED"?{data:null,error:{message:"registration cancelled",status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:s.message,status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:s instanceof Error?s.message:"unknown error",status:500,statusText:"INTERNAL_SERVER_ERROR"}}}}},$Infer:{}}),Qr=()=>{let e=(0,Ft.atom)();return{id:"passkey",$InferServerPlugin:{},getActions:t=>Vt(t,{$listPasskeys:e}),getAtoms(t){return{listPasskeys:Ho(e,"/passkey/list-user-passkeys",t,{method:"GET"}),$listPasskeys:e}},pathMethods:{"/passkey/register":"POST","/passkey/authenticate":"POST"},atomListeners:[{matcher(t){return t==="/passkey/verify-registration"||t==="/passkey/delete-passkey"||t==="/passkey/update-passkey"},signal:"_listPasskeys"}]}};var $r=e=>{let t=ne.BETTER_AUTH_URL,o=e?.rpID||t?.replace("http://","").replace("https://","").split(":")[0]||"localhost";if(!o)throw new ee("passkey rpID not found. Please provide a rpID in the options or set the BETTER_AUTH_URL environment variable.");let i={origin:null,...e,rpID:o,advanced:{webAuthnChallengeCookie:"better-auth-passkey",...e?.advanced}},r=new Date(Date.now()+1e3*60*5),n=new Date,a=Math.floor((r.getTime()-n.getTime())/1e3);return{id:"passkey",endpoints:{generatePasskeyRegistrationOptions:c("/passkey/generate-register-options",{method:"GET",use:[He],metadata:{client:!1,openapi:{description:"Generate registration options for a new passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{challenge:{type:"string"},rp:{type:"object",properties:{name:{type:"string"},id:{type:"string"}}},user:{type:"object",properties:{id:{type:"string"},name:{type:"string"},displayName:{type:"string"}}},pubKeyCredParams:{type:"array",items:{type:"object",properties:{type:{type:"string"},alg:{type:"number"}}}},timeout:{type:"number"},excludeCredentials:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string"},transports:{type:"array",items:{type:"string"}}}}},authenticatorSelection:{type:"object",properties:{authenticatorAttachment:{type:"string"},requireResidentKey:{type:"boolean"},userVerification:{type:"string"}}},attestation:{type:"string"},extensions:{type:"object"}}}}}}}}}},async s=>{let d=s.context.session,A=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}),K=new Uint8Array(Buffer.from(_(32,F("a-z","0-9")))),u;u=await(0,he.generateRegistrationOptions)({rpName:i.rpName||s.context.appName,rpID:i.rpID,userID:K,userName:d.user.email||d.user.id,attestationType:"none",excludeCredentials:A.map(l=>({id:l.id,transports:l.transports?.split(",")})),authenticatorSelection:{residentKey:"preferred",userVerification:"preferred",authenticatorAttachment:"platform"}});let p=V(32);return await s.setSignedCookie(i.advanced.webAuthnChallengeCookie,p,s.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:a}),await s.context.internalAdapter.createVerificationValue({identifier:p,value:JSON.stringify({expectedChallenge:u.challenge,userData:{id:d.user.id}}),expiresAt:r}),s.json(u,{status:200})}),generatePasskeyAuthenticationOptions:c("/passkey/generate-authenticate-options",{method:"POST",body:Y.z.object({email:Y.z.string({description:"The email address of the user"}).optional()}).optional(),metadata:{openapi:{description:"Generate authentication options for a passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{challenge:{type:"string"},rp:{type:"object",properties:{name:{type:"string"},id:{type:"string"}}},user:{type:"object",properties:{id:{type:"string"},name:{type:"string"},displayName:{type:"string"}}},timeout:{type:"number"},allowCredentials:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string"},transports:{type:"array",items:{type:"string"}}}}},userVerification:{type:"string"},authenticatorSelection:{type:"object",properties:{authenticatorAttachment:{type:"string"},requireResidentKey:{type:"boolean"},userVerification:{type:"string"}}},extensions:{type:"object"}}}}}}}}}},async s=>{let d=await U(s),A=[];d&&(A=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}));let K=await(0,he.generateAuthenticationOptions)({rpID:i.rpID,userVerification:"preferred",...A.length?{allowCredentials:A.map(l=>({id:l.id,transports:l.transports?.split(",")}))}:{}}),u={expectedChallenge:K.challenge,userData:{id:d?.user.id||""}},p=V(32);return await s.setSignedCookie(i.advanced.webAuthnChallengeCookie,p,s.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:a}),await s.context.internalAdapter.createVerificationValue({identifier:p,value:JSON.stringify(u),expiresAt:r}),s.json(K,{status:200})}),verifyPasskeyRegistration:c("/passkey/verify-registration",{method:"POST",body:Y.z.object({response:Y.z.any({description:"The response from the authenticator"}),name:Y.z.string({description:"Name of the passkey"}).optional()}),use:[He],metadata:{openapi:{description:"Verify registration of a new passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{$ref:"#/components/schemas/Passkey"}}}},400:{description:"Bad request"}}}}},async s=>{let d=e?.origin||s.headers?.get("origin")||"";if(!d)return s.json(null,{status:400});let A=s.body.response,K=await s.getSignedCookie(i.advanced.webAuthnChallengeCookie,s.context.secret);if(!K)throw new Z.APIError("BAD_REQUEST",{message:"Challenge not found"});let u=await s.context.internalAdapter.findVerificationValue(K);if(!u)return s.json(null,{status:400});let{expectedChallenge:p,userData:l}=JSON.parse(u.value);if(l.id!==s.context.session.user.id)throw new Z.APIError("UNAUTHORIZED",{message:"You are not authorized to register this passkey"});try{let h=await(0,he.verifyRegistrationResponse)({response:A,expectedChallenge:p,expectedOrigin:d,expectedRPID:e?.rpID}),{verified:k,registrationInfo:f}=h;if(!k||!f)return s.json(null,{status:400});let{credentialID:g,credentialPublicKey:b,counter:T,credentialDeviceType:N,credentialBackedUp:eo}=f,Yt=Buffer.from(b).toString("base64"),er={name:s.body.name,userId:l.id,webauthnUserID:s.context.generateId({model:"passkey"}),id:g,publicKey:Yt,counter:T,deviceType:N,transports:A.response.transports.join(","),backedUp:eo,createdAt:new Date},or=await s.context.adapter.create({model:"passkey",data:er});return s.json(or,{status:200})}catch(h){throw console.log(h),new Z.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to verify registration"})}}),verifyPasskeyAuthentication:c("/passkey/verify-authentication",{method:"POST",body:Y.z.object({response:Y.z.any()}),metadata:{openapi:{description:"Verify authentication of a passkey",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async s=>{let d=e?.origin||s.headers?.get("origin")||"";if(!d)throw new Z.APIError("BAD_REQUEST",{message:"origin missing"});let A=s.body.response,K=await s.getSignedCookie(i.advanced.webAuthnChallengeCookie,s.context.secret);if(!K)throw new Z.APIError("BAD_REQUEST",{message:"Challenge not found"});let u=await s.context.internalAdapter.findVerificationValue(K);if(!u)throw new Z.APIError("BAD_REQUEST",{message:"Challenge not found"});let{expectedChallenge:p}=JSON.parse(u.value),l=await s.context.adapter.findOne({model:"passkey",where:[{field:"id",value:A.id}]});if(!l)throw new Z.APIError("UNAUTHORIZED",{message:"Passkey not found"});try{let h=await(0,he.verifyAuthenticationResponse)({response:A,expectedChallenge:p,expectedOrigin:d,expectedRPID:i.rpID,authenticator:{credentialID:l.id,credentialPublicKey:new Uint8Array(Buffer.from(l.publicKey,"base64")),counter:l.counter,transports:l.transports?.split(",")},requireUserVerification:!1}),{verified:k}=h;if(!k)throw new Z.APIError("UNAUTHORIZED",{message:"Authentication failed"});await s.context.adapter.update({model:"passkey",where:[{field:"id",value:l.id}],update:{counter:h.authenticationInfo.newCounter}});let f=await s.context.internalAdapter.createSession(l.userId,s.request);if(!f)throw new Z.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});let g=await s.context.internalAdapter.findUserById(l.userId);if(!g)throw new Z.APIError("INTERNAL_SERVER_ERROR",{message:"User not found"});return await m(s,{session:f,user:g}),s.json({session:f},{status:200})}catch(h){throw s.context.logger.error("Failed to verify authentication",h),new Z.APIError("BAD_REQUEST",{message:"Failed to verify authentication"})}}),listPasskeys:c("/passkey/list-user-passkeys",{method:"GET",use:[v]},async s=>{let d=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:s.context.session.user.id}]});return s.json(d,{status:200})}),deletePasskey:c("/passkey/delete-passkey",{method:"POST",body:Y.z.object({id:Y.z.string()}),use:[v]},async s=>(await s.context.adapter.delete({model:"passkey",where:[{field:"id",value:s.body.id}]}),s.json(null,{status:200}))),updatePasskey:c("/passkey/update-passkey",{method:"POST",body:Y.z.object({id:Y.z.string(),name:Y.z.string()}),use:[v]},async s=>{let d=await s.context.adapter.findOne({model:"passkey",where:[{field:"id",value:s.body.id}]});if(!d)throw new Z.APIError("NOT_FOUND",{message:"Passkey not found"});if(d.userId!==s.context.session.user.id)throw new Z.APIError("UNAUTHORIZED",{message:"You are not authorized to update this passkey"});let A=await s.context.adapter.update({model:"passkey",where:[{field:"id",value:s.body.id}],update:{name:s.body.name}});if(!A)throw new Z.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to update passkey"});return s.json({passkey:A},{status:200})})},schema:ie(Zr,e?.schema)}},Zr={passkey:{fields:{name:{type:"string",required:!1},publicKey:{type:"string",required:!0},userId:{type:"string",references:{model:"user",field:"id"},required:!0},webauthnUserID:{type:"string",required:!0},counter:{type:"number",required:!0},deviceType:{type:"string",required:!0},backedUp:{type:"boolean",required:!0},transports:{type:"string",required:!1},createdAt:{type:"date",required:!1}}}};var Je=require("zod");var _e=require("better-call");var Qo=()=>({id:"username",endpoints:{signInUsername:c("/sign-in/username",{method:"POST",body:Je.z.object({username:Je.z.string({description:"The username of the user"}),password:Je.z.string({description:"The password of the user"}),rememberMe:Je.z.boolean({description:"Remember the user session"}).optional()}),metadata:{openapi:{summary:"Sign in with username",description:"Sign in with username",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async e=>{let t=await e.context.adapter.findOne({model:"user",where:[{field:"username",value:e.body.username.toLowerCase()}]});if(!t)throw await e.context.password.hash(e.body.password),e.context.logger.error("User not found",{username:Qo}),new _e.APIError("UNAUTHORIZED",{message:"Invalid username or password"});if(!t.emailVerified&&e.context.options.emailAndPassword?.requireEmailVerification)throw await Oo(e,t),new _e.APIError("UNAUTHORIZED",{message:"Email not verified"});let o=await e.context.adapter.findOne({model:"account",where:[{field:"userId",value:t.id},{field:"providerId",value:"credential"}]});if(!o)throw new _e.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let i=o?.password;if(!i)throw e.context.logger.error("Password not found",{username:Qo}),new _e.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify({hash:i,password:e.body.password}))throw e.context.logger.error("Invalid password"),new _e.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let n=await e.context.internalAdapter.createSession(t.id,e.request,e.body.rememberMe===!1);return n?(await m(e,{session:n,user:t},e.body.rememberMe===!1),e.json({user:t,session:n})):e.json(null,{status:500,body:{message:"Failed to create session",status:500}})})},schema:{user:{fields:{username:{type:"string",required:!1,unique:!0,returned:!0}}}}});var qt=require("better-call"),Gr=()=>({id:"bearer",hooks:{before:[{matcher(e){return!!(e.request?.headers.get("authorization")||e.headers?.get("authorization"))},handler:async e=>{let t=e.request?.headers.get("authorization")?.replace("Bearer ","")||e.headers?.get("authorization")?.replace("Bearer ","");if(!t)return;let o="";return t.includes(".")?o=t:o=await(0,qt.serializeSigned)("",t,e.context.secret),e.request&&e.request.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${o.replace("=","")}`),e.headers&&e.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${o.replace("=","")}`),{context:e}}}]}});var ke=require("zod");var Mt=require("better-call");var Wr=e=>({id:"magic-link",endpoints:{signInMagicLink:c("/sign-in/magic-link",{method:"POST",requireHeaders:!0,body:ke.z.object({email:ke.z.string({description:"Email address to send the magic link"}).email(),callbackURL:ke.z.string({description:"URL to redirect after magic link verification"}).optional()}),metadata:{openapi:{description:"Sign in with magic link",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async t=>{let{email:o}=t.body;if(e.disableSignUp&&!await t.context.internalAdapter.findUserByEmail(o))throw new Mt.APIError("BAD_REQUEST",{message:"User not found"});let i=_(32,F("a-z","A-Z"));await t.context.internalAdapter.createVerificationValue({identifier:i,value:o,expiresAt:new Date(Date.now()+(e.expiresIn||60*5)*1e3)});let r=`${t.context.baseURL}/magic-link/verify?token=${i}&callbackURL=${t.body.callbackURL||"/"}`;return await e.sendMagicLink({email:o,url:r,token:i},t.request),t.json({status:!0})}),magicLinkVerify:c("/magic-link/verify",{method:"GET",query:ke.z.object({token:ke.z.string({description:"Verification token"}),callbackURL:ke.z.string({description:"URL to redirect after magic link verification, if not provided will return session"}).optional()}),requireHeaders:!0,metadata:{openapi:{description:"Verify magic link",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async t=>{let{token:o,callbackURL:i}=t.query,r=i?.startsWith("http")?i:i?`${t.context.options.baseURL}${i}`:t.context.options.baseURL,n=await t.context.internalAdapter.findVerificationValue(o);if(!n)throw t.redirect(`${r}?error=INVALID_TOKEN`);if(n.expiresAt<new Date)throw await t.context.internalAdapter.deleteVerificationValue(n.id),t.redirect(`${r}?error=EXPIRED_TOKEN`);await t.context.internalAdapter.deleteVerificationValue(n.id);let a=n.value,s=await t.context.internalAdapter.findUserByEmail(a),d=s?.user.id||"";if(!s){if(e.disableSignUp)throw t.redirect(`${r}?error=USER_NOT_FOUND`);if(d=(await t.context.internalAdapter.createUser({email:a,emailVerified:!0,name:a})).id,!d)throw t.redirect(`${r}?error=USER_NOT_CREATED`)}let A=await t.context.internalAdapter.createSession(d,t.headers);if(!A)throw t.redirect(`${r}?error=SESSION_NOT_CREATED`);if(await m(t,{session:A,user:s?.user}),!i)return t.json({session:A,user:s?.user});throw t.redirect(i)})},rateLimit:[{pathMatcher(t){return t.startsWith("/sign-in/magic-link")||t.startsWith("/magic-link/verify")},window:e.rateLimit?.window||60,max:e.rateLimit?.max||5}]});var re=require("zod");var H=require("better-call");function Jr(e){return _(e,F("0-9"))}var Xr=e=>{let t={expiresIn:e?.expiresIn||300,otpLength:e?.otpLength||6,...e,phoneNumber:"phoneNumber",phoneNumberVerified:"phoneNumberVerified",code:"code",createdAt:"createdAt"};return{id:"phone-number",endpoints:{signInPhoneNumber:c("/sign-in/phone-number",{method:"POST",body:re.z.object({phoneNumber:re.z.string({description:"Phone number to sign in"}),password:re.z.string({description:"Password to use for sign in"}),rememberMe:re.z.boolean({description:"Remember the session"}).optional()}),metadata:{openapi:{summary:"Sign in with phone number",description:"Use this endpoint to sign in with phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}},400:{description:"Invalid phone number or password"}}}}},async o=>{let{password:i,phoneNumber:r}=o.body;if(t.phoneNumberValidator&&!await t.phoneNumberValidator(o.body.phoneNumber))throw new H.APIError("BAD_REQUEST",{message:"Invalid phone number!"});let n=await o.context.adapter.findOne({model:"user",where:[{field:"phoneNumber",value:r}]});if(!n)throw new H.APIError("UNAUTHORIZED",{message:"Invalid phone number or password"});let s=(await o.context.internalAdapter.findAccountByUserId(n.id)).find(u=>u.providerId==="credential");if(!s)throw o.context.logger.error("Credential account not found",{phoneNumber:r}),new H.APIError("UNAUTHORIZED",{message:"Invalid password or password"});let d=s?.password;if(!d)throw o.context.logger.error("Password not found",{phoneNumber:r}),new H.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await o.context.password.verify({hash:d,password:i}))throw o.context.logger.error("Invalid password"),new H.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let K=await o.context.internalAdapter.createSession(n.id,o.headers,o.body.rememberMe===!1);if(!K)throw o.context.logger.error("Failed to create session"),new H.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await m(o,{session:K,user:n},o.body.rememberMe===!1),o.json({user:n,session:K})}),sendPhoneNumberOTP:c("/phone-number/send-otp",{method:"POST",body:re.z.object({phoneNumber:re.z.string({description:"Phone number to send OTP"})}),metadata:{openapi:{summary:"Send OTP to phone number",description:"Use this endpoint to send OTP to phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async o=>{if(!e?.sendOTP)throw o.context.logger.warn("sendOTP not implemented"),new H.APIError("NOT_IMPLEMENTED",{message:"sendOTP not implemented"});if(t.phoneNumberValidator&&!await t.phoneNumberValidator(o.body.phoneNumber))throw new H.APIError("BAD_REQUEST",{message:"Invalid phone number!"});let i=Jr(t.otpLength);return await o.context.internalAdapter.createVerificationValue({value:i,identifier:o.body.phoneNumber,expiresAt:R(t.expiresIn,"sec")}),await e.sendOTP({phoneNumber:o.body.phoneNumber,code:i},o.request),o.json({code:i},{body:{message:"Code sent"}})}),verifyPhoneNumber:c("/phone-number/verify",{method:"POST",body:re.z.object({phoneNumber:re.z.string({description:"Phone number to verify"}),code:re.z.string({description:"OTP code"}),disableSession:re.z.boolean({description:"Disable session creation after verification"}).optional(),updatePhoneNumber:re.z.boolean({description:"Check if there is a session and update the phone number"}).optional()}),metadata:{openapi:{summary:"Verify phone number",description:"Use this endpoint to verify phone number",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}},400:{description:"Invalid OTP"}}}}},async o=>{let i=await o.context.internalAdapter.findVerificationValue(o.body.phoneNumber);if(!i||i.expiresAt<new Date)throw i&&i.expiresAt<new Date?(await o.context.internalAdapter.deleteVerificationValue(i.id),new H.APIError("BAD_REQUEST",{message:"OTP expired"})):new H.APIError("BAD_REQUEST",{message:"OTP not found"});if(i.value!==o.body.code)throw new H.APIError("BAD_REQUEST",{message:"Invalid OTP"});if(await o.context.internalAdapter.deleteVerificationValue(i.id),o.body.updatePhoneNumber){let n=await U(o);if(!n)throw new H.APIError("UNAUTHORIZED",{message:"Session not found"});let a=await o.context.internalAdapter.updateUser(n.user.id,{[t.phoneNumber]:o.body.phoneNumber,[t.phoneNumberVerified]:!0});return o.json({user:a,session:n.session})}let r=await o.context.adapter.findOne({model:"user",where:[{value:o.body.phoneNumber,field:t.phoneNumber}]});if(await e?.callbackOnVerification?.({phoneNumber:o.body.phoneNumber,user:r},o.request),r)r=await o.context.internalAdapter.updateUser(r.id,{[t.phoneNumberVerified]:!0});else if(e?.signUpOnVerification){if(r=await o.context.internalAdapter.createUser({email:e.signUpOnVerification.getTempEmail(o.body.phoneNumber),name:e.signUpOnVerification.getTempName?e.signUpOnVerification.getTempName(o.body.phoneNumber):o.body.phoneNumber,[t.phoneNumber]:o.body.phoneNumber,[t.phoneNumberVerified]:!0}),!r)throw new H.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"})}else return o.json(null);if(!r)throw new H.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to update user"});if(!o.body.disableSession){let n=await o.context.internalAdapter.createSession(r.id,o.request);if(!n)throw new H.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await m(o,{session:n,user:r}),o.json({user:r,session:n})}return o.json({user:r,session:null})})},schema:ie(Yr,e?.schema)}},Yr={user:{fields:{phoneNumber:{type:"string",required:!1,unique:!0,returned:!0},phoneNumberVerified:{type:"boolean",required:!1,returned:!0,input:!1}}}};var tp=require("zod");var en={user:{fields:{isAnonymous:{type:"boolean",required:!1}}}},on=e=>({id:"anonymous",endpoints:{signInAnonymous:c("/sign-in/anonymous",{method:"POST",metadata:{openapi:{description:"Sign in anonymously",responses:{200:{description:"Sign in anonymously",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async t=>{let{emailDomainName:o=Ie(t.context.baseURL)}=e||{},i=t.context.generateId({model:"user"}),r=`temp-${i}@${o}`,n=await t.context.internalAdapter.createUser({id:i,email:r,emailVerified:!1,isAnonymous:!0,name:"Anonymous",createdAt:new Date,updatedAt:new Date});if(!n)return t.json(null,{status:500,body:{message:"Failed to create user",status:500}});let a=await t.context.internalAdapter.createSession(n.id,t.request);return a?(await m(t,{session:a,user:n}),t.json({user:n,session:a})):t.json(null,{status:400,body:{message:"Could not create session"}})})},hooks:{after:[{matcher(t){return t.path?.startsWith("/sign-in")||t.path?.startsWith("/sign-up")},handler:P(async t=>{let i=t.responseHeader.get("set-cookie"),r=t.context.authCookies.sessionToken.name,n=ao(i||"").get(r)?.value.split(".")[0];if(!n)return;let a=await U(t);if(!(!a||!a.user.isAnonymous)){if(t.path==="/sign-in/anonymous")throw new C.APIError("BAD_REQUEST",{message:"Anonymous users cannot sign in again anonymously"});if(e?.onLinkAccount){let s=await t.context.internalAdapter.findSession(n);if(!s)return;await e?.onLinkAccount?.({anonymousUser:a,newUser:s})}e?.disableDeleteAnonymousUser||await t.context.internalAdapter.deleteUser(a.user.id)}})}]},schema:ie(en,e?.schema)});var y=require("zod");var tn=e=>{let t={defaultRole:"user",adminRole:"admin",...e},o=P(async i=>{let r=await U(i);if(!r?.session)throw new C.APIError("UNAUTHORIZED");let n=r.user;if(!n.role||(Array.isArray(t.adminRole)?!t.adminRole.includes(n.role):n.role!==t.adminRole))throw new C.APIError("FORBIDDEN",{message:"Only admins can access this endpoint"});return{session:{user:n,session:r.session}}});return{id:"admin",init(i){return{options:{databaseHooks:{user:{create:{async before(r){if(e?.defaultRole!==!1)return{data:{role:e?.defaultRole??"user",...r}}}}},session:{create:{async before(r){let n=await i.internalAdapter.findUserById(r.userId);if(n.banned){if(n.banExpires&&n.banExpires.getTime()<Date.now()){await i.internalAdapter.updateUser(r.userId,{banned:!1,banReason:null,banExpires:null});return}return!1}}}}}}}},hooks:{after:[{matcher(i){return i.path==="/list-sessions"},handler:P(async i=>{let r=await Ne(i);if(!r)return;let n=r.filter(a=>!a.impersonatedBy);return i.json(n)})}]},endpoints:{setRole:c("/admin/set-role",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"}),role:y.z.string({description:"The role to set. `admin` or `user` by default"})}),use:[o],metadata:{openapi:{operationId:"setRole",summary:"Set the role of a user",description:"Set the role of a user",responses:{200:{description:"User role updated",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{let r=await i.context.internalAdapter.updateUser(i.body.userId,{role:i.body.role});return i.json({user:r})}),createUser:c("/admin/create-user",{method:"POST",body:y.z.object({email:y.z.string({description:"The email of the user"}),password:y.z.string({description:"The password of the user"}),name:y.z.string({description:"The name of the user"}),role:y.z.string({description:"The role of the user"}),data:y.z.optional(y.z.record(y.z.any(),{description:"Extra fields for the user. Including custom additional fields."}))}),use:[o],metadata:{openapi:{operationId:"createUser",summary:"Create a new user",description:"Create a new user",responses:{200:{description:"User created",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{if(await i.context.internalAdapter.findUserByEmail(i.body.email))throw new C.APIError("BAD_REQUEST",{message:"User already exists"});let n=await i.context.internalAdapter.createUser({email:i.body.email,name:i.body.name,role:i.body.role,...i.body.data});if(!n)throw new C.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"});let a=await i.context.password.hash(i.body.password);return await i.context.internalAdapter.linkAccount({accountId:n.id,providerId:"credential",password:a,userId:n.id}),i.json({user:n})}),listUsers:c("/admin/list-users",{method:"GET",use:[o],query:y.z.object({searchValue:y.z.string({description:"The value to search for"}).optional(),searchField:y.z.enum(["email","name"],{description:"The field to search in, defaults to email. Can be `email` or `name`"}).optional(),searchOperator:y.z.enum(["contains","starts_with","ends_with"],{description:"The operator to use for the search. Can be `contains`, `starts_with` or `ends_with`"}).optional(),limit:y.z.string({description:"The number of users to return"}).or(y.z.number()).optional(),offset:y.z.string({description:"The offset to start from"}).or(y.z.number()).optional(),sortBy:y.z.string({description:"The field to sort by"}).optional(),sortDirection:y.z.enum(["asc","desc"],{description:"The direction to sort by"}).optional(),filterField:y.z.string({description:"The field to filter by"}).optional(),filterValue:y.z.string({description:"The value to filter by"}).or(y.z.number()).or(y.z.boolean()).optional(),filterOperator:y.z.enum(["eq","ne","lt","lte","gt","gte"],{description:"The operator to use for the filter"}).optional()}),metadata:{openapi:{operationId:"listUsers",summary:"List users",description:"List users",responses:{200:{description:"List of users",content:{"application/json":{schema:{type:"object",properties:{users:{type:"array",items:{$ref:"#/components/schemas/User"}}}}}}}}}}},async i=>{let r=[];i.query?.searchValue&&r.push({field:i.query.searchField||"email",operator:i.query.searchOperator||"contains",value:i.query.searchValue}),i.query?.filterValue&&r.push({field:i.query.filterField||"email",operator:i.query.filterOperator||"eq",value:i.query.filterValue});try{let n=await i.context.internalAdapter.listUsers(Number(i.query?.limit)||void 0,Number(i.query?.offset)||void 0,i.query?.sortBy?{field:i.query.sortBy,direction:i.query.sortDirection||"asc"}:void 0,r.length?r:void 0);return i.json({users:n})}catch(n){return console.log(n),i.json({users:[]})}}),listUserSessions:c("/admin/list-user-sessions",{method:"POST",use:[o],body:y.z.object({userId:y.z.string({description:"The user id"})}),metadata:{openapi:{operationId:"listUserSessions",summary:"List user sessions",description:"List user sessions",responses:{200:{description:"List of user sessions",content:{"application/json":{schema:{type:"object",properties:{sessions:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}}}}}}}},async i=>({sessions:await i.context.internalAdapter.listSessions(i.body.userId)})),unbanUser:c("/admin/unban-user",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"unbanUser",summary:"Unban a user",description:"Unban a user",responses:{200:{description:"User unbanned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{let r=await i.context.internalAdapter.updateUser(i.body.userId,{banned:!1});return i.json({user:r})}),banUser:c("/admin/ban-user",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"}),banReason:y.z.string({description:"The reason for the ban"}).optional(),banExpiresIn:y.z.number({description:"The number of seconds until the ban expires"}).optional()}),use:[o],metadata:{openapi:{operationId:"banUser",summary:"Ban a user",description:"Ban a user",responses:{200:{description:"User banned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{if(i.body.userId===i.context.session.user.id)throw new C.APIError("BAD_REQUEST",{message:"You cannot ban yourself"});let r=await i.context.internalAdapter.updateUser(i.body.userId,{banned:!0,banReason:i.body.banReason||e?.defaultBanReason||"No reason",banExpires:i.body.banExpiresIn?R(i.body.banExpiresIn,"sec"):e?.defaultBanExpiresIn?R(e.defaultBanExpiresIn,"sec"):void 0});return await i.context.internalAdapter.deleteSessions(i.body.userId),i.json({user:r})}),impersonateUser:c("/admin/impersonate-user",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"impersonateUser",summary:"Impersonate a user",description:"Impersonate a user",responses:{200:{description:"Impersonation session created",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async i=>{let r=await i.context.internalAdapter.findUserById(i.body.userId);if(!r)throw new C.APIError("NOT_FOUND",{message:"User not found"});let n=await i.context.internalAdapter.createSession(r.id,void 0,!0,{impersonatedBy:i.context.session.user.id,expiresAt:e?.impersonationSessionDuration?R(e.impersonationSessionDuration,"sec"):R(60*60,"sec")});if(!n)throw new C.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await m(i,{session:n,user:r},!0),i.json({session:n,user:r})}),revokeUserSession:c("/admin/revoke-user-session",{method:"POST",body:y.z.object({sessionToken:y.z.string({description:"The session token"})}),use:[o],metadata:{openapi:{operationId:"revokeUserSession",summary:"Revoke a user session",description:"Revoke a user session",responses:{200:{description:"Session revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async i=>(await i.context.internalAdapter.deleteSession(i.body.sessionToken),i.json({success:!0}))),revokeUserSessions:c("/admin/revoke-user-sessions",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"revokeUserSessions",summary:"Revoke all user sessions",description:"Revoke all user sessions",responses:{200:{description:"Sessions revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async i=>(await i.context.internalAdapter.deleteSessions(i.body.userId),i.json({success:!0}))),removeUser:c("/admin/remove-user",{method:"POST",body:y.z.object({userId:y.z.string({description:"The user id"})}),use:[o],metadata:{openapi:{operationId:"removeUser",summary:"Remove a user",description:"Delete a user and all their sessions and accounts. Cannot be undone.",responses:{200:{description:"User removed",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async i=>(await i.context.internalAdapter.deleteUser(i.body.userId),i.json({success:!0})))},schema:ie(rn,t.schema)}},rn={user:{fields:{role:{type:"string",required:!1,input:!1},banned:{type:"boolean",defaultValue:!1,required:!1,input:!1},banReason:{type:"string",required:!1,input:!1},banExpires:{type:"date",required:!1,input:!1}}},session:{fields:{impersonatedBy:{type:"string",required:!1}}}};var se=require("zod"),Fe=require("better-call");var ho=require("@better-fetch/fetch");var Ht=require("oslo/jwt");async function nn(e,t,o){if(t==="oidc"&&e.idToken){let r=(0,Ht.parseJWT)(e.idToken);if(r?.payload)return{id:r.payload.sub,emailVerified:r.payload.email_verified,...r.payload}}if(!o)return null;let i=await(0,ho.betterFetch)(o,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});return{id:i.data?.sub,emailVerified:i.data?.email_verified,email:i.data?.email,...i.data}}var sn=e=>({id:"generic-oauth",endpoints:{signInWithOAuth2:c("/sign-in/oauth2",{method:"POST",query:se.z.object({currentURL:se.z.string({description:"Redirect to the current URL after sign in"}).optional()}).optional(),body:se.z.object({providerId:se.z.string({description:"The provider ID for the OAuth provider"}),callbackURL:se.z.string({description:"The URL to redirect to after sign in"}).optional(),errorCallbackURL:se.z.string({description:"The URL to redirect to if an error occurs"}).optional()}),metadata:{openapi:{description:"Sign in with OAuth2",responses:{200:{description:"Sign in with OAuth2",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}}}}}}}}}},async t=>{let{providerId:o}=t.body,i=e.config.find(N=>N.providerId===o);if(!i)throw new Fe.APIError("BAD_REQUEST",{message:`No config found for provider ${o}`});let{discoveryUrl:r,authorizationUrl:n,tokenUrl:a,clientId:s,clientSecret:d,scopes:A,redirectURI:K,responseType:u,pkce:p,prompt:l,accessType:h}=i,k=n,f=a;if(r){let N=await(0,ho.betterFetch)(r,{onError(eo){t.context.logger.error(eo.error.message,eo.error,{discoveryUrl:r})}});N.data&&(k=N.data.authorization_endpoint,f=N.data.token_endpoint)}if(!k||!f)throw new Fe.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let{state:g,codeVerifier:b}=await Ue(t),T=await S({id:o,options:{clientId:s,clientSecret:d,redirectURI:K},authorizationEndpoint:k,state:g,codeVerifier:p?b:void 0,scopes:A||[],redirectURI:`${t.context.baseURL}/oauth2/callback/${o}`});return u&&u!=="code"&&T.searchParams.set("response_type",u),l&&T.searchParams.set("prompt",l),h&&T.searchParams.set("access_type",h),t.json({url:T.toString(),redirect:!0})}),oAuth2Callback:c("/oauth2/callback/:providerId",{method:"GET",query:se.z.object({code:se.z.string({description:"The OAuth2 code"}).optional(),error:se.z.string({description:"The error message, if any"}).optional(),state:se.z.string({description:"The state parameter from the OAuth2 request"})}),metadata:{openapi:{description:"OAuth2 callback",responses:{200:{description:"OAuth2 callback",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"}}}}}}}}}},async t=>{if(t.query.error||!t.query.code)throw t.redirect(`${t.context.baseURL}?error=${t.query.error||"oAuth_code_missing"}`);let o=e.config.find(g=>g.providerId===t.params.providerId);if(!o)throw new Fe.APIError("BAD_REQUEST",{message:`No config found for provider ${t.params.providerId}`});let i,r=await co(t),{callbackURL:n,codeVerifier:a,errorURL:s}=r,d=t.query.code,A=o.tokenUrl,K=o.userInfoUrl;if(o.discoveryUrl){let g=await(0,ho.betterFetch)(o.discoveryUrl,{method:"GET"});g.data&&(A=g.data.token_endpoint,K=g.data.userinfo_endpoint)}try{if(!A)throw new Fe.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});i=await I({code:d,codeVerifier:a,redirectURI:`${t.context.baseURL}/oauth2/callback/${o.providerId}`,options:{clientId:o.clientId,clientSecret:o.clientSecret},tokenEndpoint:A})}catch(g){throw t.context.logger.error(g&&typeof g=="object"&&"name"in g?g.name:"",g),t.redirect(`${s}?error=oauth_code_verification_failed`)}if(!i)throw new Fe.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let u=o.getUserInfo?await o.getUserInfo(i):await nn(i,o.type||"oauth2",K);if(!u?.email)throw t.context.logger.error("Unable to get user info",u),t.redirect(`${t.context.baseURL}/error?error=email_is_missing`);let p=await Pe(t,{userInfo:u,account:{providerId:o.providerId,accountId:u.id,accessToken:i.accessToken}});function l(g){throw t.redirect(`${s||n||`${t.context.baseURL}/error`}?error=${g}`)}if(p.error)return l(p.error.split(" ").join("_"));let{session:h,user:k}=p.data;await m(t,{session:h,user:k});let f;try{f=new URL(n).toString()}catch{f=n}throw t.redirect(f)})}});var Ve=require("zod"),Qt={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0}}}},kp=Ve.z.object({id:Ve.z.string(),publicKey:Ve.z.string(),privateKey:Ve.z.string(),createdAt:Ve.z.date()});var $o=e=>({getAllKeys:async()=>await e.findMany({model:"jwks"}),getLatestKey:async()=>(await e.findMany({model:"jwks",sortBy:{field:"createdAt",direction:"desc"},limit:1}))[0],createJwk:async t=>await e.create({model:"jwks",data:{...t,createdAt:new Date}})});var le=require("jose");var an=e=>({id:"jwt",endpoints:{getJwks:c("/jwks",{method:"GET",metadata:{openapi:{description:"Get the JSON Web Key Set",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{keys:{type:"array",items:{type:"object",properties:{kid:{type:"string"},kty:{type:"string"},use:{type:"string"},alg:{type:"string"},n:{type:"string"},e:{type:"string"}}}}}}}}}}}}},async t=>{let i=await $o(t.context.adapter).getAllKeys();return t.json({keys:i.map(r=>({...JSON.parse(r.publicKey),kid:r.id}))})}),getToken:c("/token",{method:"GET",requireHeaders:!0,use:[v],metadata:{openapi:{description:"Get a JWT token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async t=>{let o=$o(t.context.adapter),i=await o.getLatestKey(),r=!e?.jwks?.disablePrivateKeyEncryption;if(i===void 0){let{publicKey:A,privateKey:K}=await(0,le.generateKeyPair)(e?.jwks?.keyPairConfig?.alg??"EdDSA",e?.jwks?.keyPairConfig??{crv:"Ed25519"}),u=await(0,le.exportJWK)(A),p=await(0,le.exportJWK)(K),l=JSON.stringify(p),h={id:crypto.randomUUID(),publicKey:JSON.stringify(u),privateKey:r?JSON.stringify(await ue({key:t.context.options.secret,data:l})):l,createdAt:new Date};i=await o.createJwk(h)}let n=r?await fe({key:t.context.options.secret,data:JSON.parse(i.privateKey)}):i.privateKey,a=await(0,le.importJWK)(JSON.parse(n)),s=e?.jwt?.definePayload?await e?.jwt.definePayload(t.context.session.user):t.context.session.user,d=await new le.SignJWT({...s,...t.context.session.session.impersonatedBy?{impersonatedBy:t.context.session.session.impersonatedBy}:{}}).setProtectedHeader({alg:e?.jwks?.keyPairConfig?.alg??"EdDSA",kid:i.id}).setIssuedAt().setIssuer(e?.jwt?.issuer??t.context.options.baseURL).setAudience(e?.jwt?.audience??t.context.options.baseURL).setExpirationTime(e?.jwt?.expirationTime??"15m").setSubject(t.context.session.user.id).sign(a);return t.json({token:d})})},schema:ie(Qt,e?.schema)});var Xe=require("zod");var dn=e=>{let t={maximumSessions:5,...e},o=i=>i.includes("_multi-");return{id:"multi-session",endpoints:{listDeviceSessions:c("/multi-session/list-device-sessions",{method:"GET",requireHeaders:!0},async i=>{let r=i.headers?.get("cookie");if(!r)return i.json([]);let n=Object.fromEntries(Qe(r)),a=(await Promise.all(Object.entries(n).filter(([A])=>o(A)).map(async([A])=>await i.getSignedCookie(A,i.context.secret)))).filter(A=>A!==void 0);if(!a.length)return i.json([]);let d=(await i.context.internalAdapter.findSessions(a)).filter(A=>A&&A.session.expiresAt>new Date);return i.json(d)}),setActiveSession:c("/multi-session/set-active",{method:"POST",body:Xe.z.object({sessionToken:Xe.z.string({description:"The session token to set as active"})}),requireHeaders:!0,use:[v],metadata:{openapi:{description:"Set the active session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async i=>{let r=i.body.sessionToken,n=`${i.context.authCookies.sessionToken.name}_multi-${r}`;if(!await i.getSignedCookie(n,i.context.secret))throw new C.APIError("UNAUTHORIZED",{message:"Invalid session token"});let s=await i.context.internalAdapter.findSession(r);if(!s||s.session.expiresAt<new Date)throw i.setCookie(n,"",{...i.context.authCookies.sessionToken.options,maxAge:0}),new C.APIError("UNAUTHORIZED",{message:"Invalid session token"});return await m(i,s),i.json(s)}),revokeDeviceSession:c("/multi-session/revoke",{method:"POST",body:Xe.z.object({sessionToken:Xe.z.string({description:"The session token to revoke"})}),requireHeaders:!0,use:[v],metadata:{openapi:{description:"Revoke a device session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async i=>{let r=i.body.sessionToken,n=`${i.context.authCookies.sessionToken.name}_multi-${r}`;if(!await i.getSignedCookie(n,i.context.secret))throw new C.APIError("UNAUTHORIZED",{message:"Invalid session token"});if(await i.context.internalAdapter.deleteSession(r),i.setCookie(n,"",{...i.context.authCookies.sessionToken.options,maxAge:0}),!(i.context.session?.session.token===r))return i.json({success:!0});let d=i.headers?.get("cookie");if(d){let A=Object.fromEntries(Qe(d)),K=(await Promise.all(Object.entries(A).filter(([p])=>o(p)).map(async([p])=>await i.getSignedCookie(p,i.context.secret)))).filter(p=>p!==void 0),u=i.context.internalAdapter;if(K.length>0){let l=(await u.findSessions(K)).filter(h=>h&&h.session.expiresAt>new Date);if(l.length>0){let h=l[0];await m(i,h)}else Q(i)}else Q(i)}else Q(i);return i.json({success:!0})})},hooks:{after:[{matcher:()=>!0,handler:P(async i=>{let r=i.responseHeader.get("set-cookie");if(!r)return;let n=ao(r),a=i.context.authCookies.sessionToken,s=n.get(a.name)?.value;if(!s)return;let d=Qe(i.headers?.get("cookie")||""),A=s.split(".")[0];if(!A)return;let K=`${a.name}_multi-${A}`;n.get(K)||d.get(K)||Object.keys(Object.fromEntries(d)).filter(o).length+(r.includes("session_token")?1:0)>t.maximumSessions||await i.setSignedCookie(K,A,i.context.secret,a.options)})},{matcher:i=>i.path==="/sign-out",handler:P(async i=>{let r=i.headers?.get("cookie");if(!r)return;let n=Object.fromEntries(Qe(r)),a=Object.keys(n).map(s=>o(s)?(i.setCookie(s,"",{maxAge:0}),s.split("_multi-")[1]):null).filter(s=>s!==null);await i.context.internalAdapter.deleteSessions(a)})}]}}};var D=require("zod");var Zo=["email-verification","sign-in","forget-password"],An=e=>{let t={expireIn:300,otpLength:6,...e};return{id:"email-otp",endpoints:{sendVerificationOTP:c("/email-otp/send-verification-otp",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to send the OTP"}),type:D.z.enum(Zo,{description:"Type of the OTP"})}),metadata:{openapi:{description:"Send verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{if(!e?.sendVerificationOTP)throw o.context.logger.error("send email verification is not implemented"),new C.APIError("BAD_REQUEST",{message:"send email verification is not implemented"});let i=o.body.email,r=_(t.otpLength,F("0-9"));return await o.context.internalAdapter.createVerificationValue({value:r,identifier:`${o.body.type}-otp-${i}`,expiresAt:R(t.expireIn,"sec")}).catch(async n=>{await o.context.internalAdapter.deleteVerificationByIdentifier(`${o.body.type}-otp-${i}`),await o.context.internalAdapter.createVerificationValue({value:r,identifier:`${o.body.type}-otp-${i}`,expiresAt:R(t.expireIn,"sec")})}),await e.sendVerificationOTP({email:i,otp:r,type:o.body.type},o.request),o.json({success:!0})}),createVerificationOTP:c("/email-otp/create-verification-otp",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to send the OTP"}),type:D.z.enum(Zo,{description:"Type of the OTP"})}),metadata:{SERVER_ONLY:!0,openapi:{description:"Create verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string"}}}}}}}},async o=>{let i=o.body.email,r=_(t.otpLength,F("0-9"));return await o.context.internalAdapter.createVerificationValue({value:r,identifier:`${o.body.type}-otp-${i}`,expiresAt:R(t.expireIn,"sec")}),r}),getVerificationOTP:c("/email-otp/get-verification-otp",{method:"GET",query:D.z.object({email:D.z.string({description:"Email address to get the OTP"}),type:D.z.enum(Zo)}),metadata:{SERVER_ONLY:!0,openapi:{description:"Get verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{otp:{type:"string"}}}}}}}}}},async o=>{let i=o.query.email,r=await o.context.internalAdapter.findVerificationValue(`${o.query.type}-otp-${i}`);return!r||r.expiresAt<new Date?o.json({otp:null}):o.json({otp:r.value})}),verifyEmailOTP:c("/email-otp/verify-email",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to verify"}),otp:D.z.string({description:"OTP to verify"})}),metadata:{openapi:{description:"Verify email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async o=>{let i=o.body.email,r=await o.context.internalAdapter.findVerificationValue(`email-verification-otp-${i}`);if(!r||r.expiresAt<new Date)throw r&&await o.context.internalAdapter.deleteVerificationValue(r.id),new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});let n=o.body.otp;if(r.value!==n)throw new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});await o.context.internalAdapter.deleteVerificationValue(r.id);let a=await o.context.internalAdapter.findUserByEmail(i);if(!a)throw new C.APIError("BAD_REQUEST",{message:"User not found"});let s=await o.context.internalAdapter.updateUser(a.user.id,{email:i,emailVerified:!0});return o.json({user:s})}),signInEmailOTP:c("/sign-in/email-otp",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to sign in"}),otp:D.z.string({description:"OTP sent to the email"})}),metadata:{openapi:{description:"Sign in with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async o=>{let i=o.body.email,r=await o.context.internalAdapter.findVerificationValue(`sign-in-otp-${i}`);if(!r||r.expiresAt<new Date)throw r&&await o.context.internalAdapter.deleteVerificationValue(r.id),new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});let n=o.body.otp;if(r.value!==n)throw new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});await o.context.internalAdapter.deleteVerificationValue(r.id);let a=await o.context.internalAdapter.findUserByEmail(i);if(!a){if(t.disableSignUp)throw new C.APIError("BAD_REQUEST",{message:"User not found"});let d=await o.context.internalAdapter.createUser({email:i,emailVerified:!0,name:i}),A=await o.context.internalAdapter.createSession(d.id,o.request);return await m(o,{session:A,user:d}),o.json({user:d,session:A})}a.user.emailVerified||await o.context.internalAdapter.updateUser(a.user.id,{emailVerified:!0});let s=await o.context.internalAdapter.createSession(a.user.id,o.request);return await m(o,{session:s,user:a.user}),o.json({session:s,user:a})}),forgetPasswordEmailOTP:c("/forget-password/email-otp",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to send the OTP"})}),metadata:{openapi:{description:"Forget password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{let i=o.body.email;if(!await o.context.internalAdapter.findUserByEmail(i))throw new C.APIError("BAD_REQUEST",{message:"User not found"});let n=_(t.otpLength,F("0-9"));return await o.context.internalAdapter.createVerificationValue({value:n,identifier:`forget-password-otp-${i}`,expiresAt:R(t.expireIn,"sec")}),await e.sendVerificationOTP({email:i,otp:n,type:"forget-password"},o.request),o.json({success:!0})}),resetPasswordEmailOTP:c("/email-otp/reset-password",{method:"POST",body:D.z.object({email:D.z.string({description:"Email address to reset the password"}),otp:D.z.string({description:"OTP sent to the email"}),password:D.z.string({description:"New password"})}),metadata:{openapi:{description:"Reset password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{let i=o.body.email,r=await o.context.internalAdapter.findUserByEmail(i);if(!r)throw new C.APIError("BAD_REQUEST",{message:"User not found"});let n=await o.context.internalAdapter.findVerificationValue(`forget-password-otp-${i}`);if(!n||n.expiresAt<new Date)throw n&&await o.context.internalAdapter.deleteVerificationValue(n.id),new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});let a=o.body.otp;if(n.value!==a)throw new C.APIError("BAD_REQUEST",{message:"Invalid OTP"});await o.context.internalAdapter.deleteVerificationValue(n.id);let s=await o.context.password.hash(o.body.password);return await o.context.internalAdapter.updatePassword(r.user.id,s),o.json({success:!0})})},hooks:{after:[{matcher(o){return!!(o.path?.startsWith("/sign-up")&&t.sendVerificationOnSignUp)},async handler(o){let i=await Ne(o);if(i&&i.user.email&&i.user.emailVerified===!1){let r=_(t.otpLength,F("0-9"));await o.context.internalAdapter.createVerificationValue({value:r,identifier:`email-verification-otp-${i.user.email}`,expiresAt:R(t.expireIn,"sec")}),await e.sendVerificationOTP({email:i.user.email,otp:r,type:"email-verification"},o.request)}}}]}}};var Go=require("zod");var Zt=require("@better-fetch/fetch");function $t(e){return e==="true"||e===!0}var cn=e=>({id:"one-tap",endpoints:{oneTapCallback:c("/one-tap/callback",{method:"POST",body:Go.z.object({idToken:Go.z.string({description:"Google ID token, which the client obtains from the One Tap API"})}),metadata:{openapi:{summary:"One tap callback",description:"Use this endpoint to authenticate with Google One Tap",responses:{200:{description:"Successful response",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}},400:{description:"Invalid token"}}}}},async t=>{let{idToken:o}=t.body,{data:i,error:r}=await(0,Zt.betterFetch)("https://oauth2.googleapis.com/tokeninfo?id_token="+o);if(r)return t.json({error:"Invalid token"});let n=await t.context.internalAdapter.findUserByEmail(i.email);if(!n){if(e?.disableSignup)throw new C.APIError("BAD_GATEWAY",{message:"User not found"});let s=await t.context.internalAdapter.createOAuthUser({email:i.email,emailVerified:$t(i.email_verified),name:i.name,image:i.picture},{providerId:"google",accountId:i.sub});if(!s)throw new C.APIError("INTERNAL_SERVER_ERROR",{message:"Could not create user"});let d=await t.context.internalAdapter.createSession(s?.user.id,t.request);return await m(t,{user:s.user,session:d}),t.json({session:d,user:s})}let a=await t.context.internalAdapter.createSession(n.user.id,t.request);return await m(t,{user:n.user,session:a}),t.json({session:a,user:n})})}});var yo=require("zod");function Kn(){let e=ne.VERCEL_URL,t=ne.NETLIFY_URL,o=ne.RENDER_URL,i=ne.AWS_LAMBDA_FUNCTION_NAME,r=ne.GOOGLE_CLOUD_FUNCTION_NAME,n=ne.AZURE_FUNCTION_NAME;return e||t||o||i||r||n}var pn=e=>({id:"oauth-proxy",endpoints:{oAuthProxy:c("/oauth-proxy-callback",{method:"GET",query:yo.z.object({callbackURL:yo.z.string({description:"The URL to redirect to after the proxy"}),cookies:yo.z.string({description:"The cookies to set after the proxy"})}),metadata:{openapi:{description:"OAuth Proxy Callback",parameters:[{in:"query",name:"callbackURL",required:!0,description:"The URL to redirect to after the proxy"},{in:"query",name:"cookies",required:!0,description:"The cookies to set after the proxy"}],responses:{302:{description:"Redirect",headers:{Location:{description:"The URL to redirect to",schema:{type:"string"}}}}}}}},async t=>{let o=t.query.cookies,i=await fe({key:t.context.secret,data:o});throw t.setHeader("set-cookie",i),t.redirect(t.query.callbackURL)})},hooks:{after:[{matcher(t){return t.path?.startsWith("/callback")},handler:P(async t=>{let o=t.context.returned,i=o instanceof C.APIError?o.headers:null,r=i?.get("location");if(r?.includes("/oauth-proxy-callback?callbackURL")){if(!r.startsWith("http"))return;let n=new URL(r);if(n.origin===Ie(t.context.baseURL)){let K=n.searchParams.get("callbackURL");if(!K)return;t.setHeader("location",K);return}let s=i?.get("set-cookie");if(!s)return;let d=await ue({key:t.context.secret,data:s}),A=`${r}&cookies=${encodeURIComponent(d)}`;t.setHeader("location",A)}})}],before:[{matcher(t){return t.path?.startsWith("/sign-in/social")},async handler(t){let o=new URL(e?.currentURL||t.request?.url||Kn()||t.context.baseURL);return t.body.callbackURL=`${o.origin}${t.context.options.basePath||"/api/auth"}/oauth-proxy-callback?callbackURL=${encodeURIComponent(t.body.callbackURL||t.context.baseURL)}`,{context:t}}}]}});var un=(e,t)=>({id:"custom-session",endpoints:{getSession:c("/get-session",{method:"GET",metadata:{CUSTOM_SESSION:!0}},async o=>{let i=await U(o);if(!i)return o.json(null);let r=await e(i);return o.json(r)})}});var ce=require("zod");var qe=e=>{let t=e.plugins?.reduce((d,A)=>{let K=A.schema;if(!K)return d;for(let[u,p]of Object.entries(K))d[u]={fields:{...d[u]?.fields,...p.fields},modelName:p.modelName||u};return d},{}),o=e.rateLimit?.storage==="database",i={rateLimit:{modelName:e.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",fieldName:e.rateLimit?.fields?.key||"key"},count:{type:"number",fieldName:e.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",fieldName:e.rateLimit?.fields?.lastRequest||"lastRequest"}}}},{user:r,session:n,account:a,...s}=t||{};return{user:{modelName:e.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:e.user?.fields?.name||"name"},email:{type:"string",unique:!0,required:!0,fieldName:e.user?.fields?.email||"email"},emailVerified:{type:"boolean",defaultValue:()=>!1,required:!0,fieldName:e.user?.fields?.emailVerified||"emailVerified"},image:{type:"string",required:!1,fieldName:e.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.updatedAt||"updatedAt"},...r?.fields,...e.user?.additionalFields},order:1},session:{modelName:e.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:e.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:e.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:e.session?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,fieldName:e.session?.fields?.updatedAt||"updatedAt"},ipAddress:{type:"string",required:!1,fieldName:e.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:e.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:e.session?.fields?.userId||"userId",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0},...n?.fields,...e.session?.additionalFields},order:2},account:{modelName:e.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:e.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:e.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:e.account?.fields?.userId||"userId"},accessToken:{type:"string",required:!1,fieldName:e.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,fieldName:e.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,fieldName:e.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.accessTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:e.account?.fields?.scope||"scope"},password:{type:"string",required:!1,fieldName:e.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:e.account?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,fieldName:e.account?.fields?.updatedAt||"updatedAt"},...a?.fields},order:3},verification:{modelName:e.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:e.verification?.fields?.identifier||"identifier"},value:{type:"string",required:!0,fieldName:e.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:e.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!1,defaultValue:()=>new Date,fieldName:e.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!1,defaultValue:()=>new Date,fieldName:e.verification?.fields?.updatedAt||"updatedAt"}},order:4},...s,...o?i:{}}};var ln=require("zod");var Gt=require("kysely"),Wo=require("kysely");var Ye={};function Jt(e){switch(e.constructor.name){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array";default:return"string"}}function wo(e){let t=[];return e.metadata?.openapi?.parameters?(t.push(...e.metadata.openapi.parameters),t):(e.query instanceof ce.ZodObject&&Object.entries(e.query.shape).forEach(([o,i])=>{i instanceof ce.ZodSchema&&t.push({name:o,in:"query",schema:{type:Jt(i),..."minLength"in i&&i.minLength?{minLength:i.minLength}:{},description:i.description}})}),t)}function Wt(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof ce.ZodObject||e.body instanceof ce.ZodOptional)){let t=e.body.shape;if(!t)return;let o={},i=[];return Object.entries(t).forEach(([r,n])=>{n instanceof ce.ZodSchema&&(o[r]={type:Jt(n),description:n.description},n instanceof ce.ZodOptional||i.push(r))}),{required:e.body instanceof ce.ZodOptional?!1:!!e.body,content:{"application/json":{schema:{type:"object",properties:o,required:i}}}}}}function Co(e){return{400:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Bad Request. Usually due to missing parameters, or invalid parameters."},401:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Unauthorized. Due to missing or invalid authentication."},403:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Forbidden. You do not have permission to access this resource or to perform this action."},404:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Not Found. The requested resource was not found."},429:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Too Many Requests. You have exceeded the rate limit. Try again later."},500:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Internal Server Error. This is a problem with the server that you cannot fix."},...e}}async function Jo(e,t){let o=Uo(e,{...t,plugins:[]}),i=qe(t),n={schemas:{...Object.entries(i).reduce((s,[d,A])=>{let K=d.charAt(0).toUpperCase()+d.slice(1);return s[K]={type:"object",properties:Object.entries(A.fields).reduce((u,[p,l])=>(u[p]={type:l.type},u),{})},s},{})}};Object.entries(o.api).forEach(([s,d])=>{let A=d.options;if(!A.metadata?.SERVER_ONLY&&(A.method==="GET"&&(Ye[d.path]={get:{tags:["Default",...A.metadata?.openapi?.tags||[]],description:A.metadata?.openapi?.description,operationId:A.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(A),responses:Co(A.metadata?.openapi?.responses)}}),A.method==="POST")){let K=Wt(A);Ye[d.path]={post:{tags:["Default",...A.metadata?.openapi?.tags||[]],description:A.metadata?.openapi?.description,operationId:A.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(A),...K?{requestBody:K}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:Co(A.metadata?.openapi?.responses)}}}});for(let s of t.plugins||[]){if(s.id==="open-api")continue;let d=Uo(e,{...t,plugins:[s]}),A=Object.keys(d.api).map(K=>o.api[K]===void 0?d.api[K]:null).filter(K=>K!==null);Object.entries(A).forEach(([K,u])=>{let p=u.options;p.metadata?.SERVER_ONLY||(p.method==="GET"&&(Ye[u.path]={get:{tags:p.metadata?.openapi?.tags||[s.id.charAt(0).toUpperCase()+s.id.slice(1)],description:p.metadata?.openapi?.description,operationId:p.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(p),responses:Co(p.metadata?.openapi?.responses)}}),p.method==="POST"&&(Ye[u.path]={post:{tags:p.metadata?.openapi?.tags||[s.id.charAt(0).toUpperCase()+s.id.slice(1)],description:p.metadata?.openapi?.description,operationId:p.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(p),requestBody:Wt(p),responses:Co(p.metadata?.openapi?.responses)}}))})}return{openapi:"3.1.1",info:{title:"Better Auth",description:"API Reference for your Better Auth Instance"},components:n,security:[{apiKeyCookie:[]}],servers:[{url:e.baseURL}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:Ye}}var Xt=`<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">
@@ -89,7 +89,7 @@ Error: `,s),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
89
89
  <image id="image0_21_12" width="1056" height="1056" xlink:href="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBARXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAEIKADAAQAAAABAAAEIAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/+ICKElDQ19QUk9GSUxFAAEBAAACGGFwcGwEAAAAbW50clJHQiBYWVogB+YAAQABAAAAAAAAYWNzcEFQUEwAAAAAQVBQTAAAAAAAAAAAAAAAAAAAAAAAAPbWAAEAAAAA0y1hcHBs7P2jjjiFR8NttL1PetoYLwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKZGVzYwAAAPwAAAAwY3BydAAAASwAAABQd3RwdAAAAXwAAAAUclhZWgAAAZAAAAAUZ1hZWgAAAaQAAAAUYlhZWgAAAbgAAAAUclRSQwAAAcwAAAAgY2hhZAAAAewAAAAsYlRSQwAAAcwAAAAgZ1RSQwAAAcwAAAAgbWx1YwAAAAAAAAABAAAADGVuVVMAAAAUAAAAHABEAGkAcwBwAGwAYQB5ACAAUAAzbWx1YwAAAAAAAAABAAAADGVuVVMAAAA0AAAAHABDAG8AcAB5AHIAaQBnAGgAdAAgAEEAcABwAGwAZQAgAEkAbgBjAC4ALAAgADIAMAAyADJYWVogAAAAAAAA9tUAAQAAAADTLFhZWiAAAAAAAACD3wAAPb////+7WFlaIAAAAAAAAEq/AACxNwAACrlYWVogAAAAAAAAKDgAABELAADIuXBhcmEAAAAAAAMAAAACZmYAAPKnAAANWQAAE9AAAApbc2YzMgAAAAAAAQxCAAAF3v//8yYAAAeTAAD9kP//+6L///2jAAAD3AAAwG7/wAARCAQgBCADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9sAQwACAgICAgIDAgIDBAMDAwQFBAQEBAUHBQUFBQUHCAcHBwcHBwgICAgICAgICgoKCgoKCwsLCwsNDQ0NDQ0NDQ0N/9sAQwECAgIDAwMGAwMGDQkHCQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0N/90ABABC/9oADAMBAAIRAxEAPwD9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//Q/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0f38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9L9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//T/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/1P38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9X9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//W/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/1/38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9D9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//R/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0v38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9P9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//U/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/1f38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9b9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//X/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0P38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9H9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//S/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0/38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9T9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//V/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/1v38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAK/Ln/gq38a/in8Dvgp4T8R/CfxFdeG9SvvFMdlcXFoELyW5srqQxnzEcY3op4Gciv1Gr8Z/+C2X/JvXgj/sc4v/AE33lAH4z/8ADwv9tD/oq2tf9823/wAZo/4eF/tof9FW1r/vm2/+M18Z0UAfZn/Dwv8AbQ/6KtrX/fNt/wDGaP8Ah4X+2h/0VbWv++bb/wCM18Z0UAfZn/Dwv9tD/oq2tf8AfNt/8Zo/4eF/tof9FW1r/vm2/wDjNfGdFAH2Z/w8L/bQ/wCira1/3zbf/GaP+Hhf7aH/AEVbWv8Avm2/+M18Z0UAfZn/AA8L/bQ/6KtrX/fNt/8AGaP+Hhf7aH/RVta/75tv/jNfGdFAH2Z/w8L/AG0P+ira1/3zbf8Axmj/AIeF/tof9FW1r/vm2/8AjNfGdFAH63/sVftq/tTfEb9qb4deCfG3xF1TVtD1bVGgvbKdYBHPGIJW2ttiVsblB4I6V/UbX8Z//BPT/k9D4U/9hpv/AEmmr+zCgAooooAKKKKACiiigAooooAKKKKACiiigD+M/wD4eF/tof8ARVta/wC+bb/4zR/w8L/bQ/6KtrX/AHzbf/Ga+M6KAPsz/h4X+2h/0VbWv++bb/4zR/w8L/bQ/wCira1/3zbf/Ga+M6KAPsz/AIeF/tof9FW1r/vm2/8AjNH/AA8L/bQ/6KtrX/fNt/8AGa+M6KAPsz/h4X+2h/0VbWv++bb/AOM0f8PC/wBtD/oq2tf9823/AMZr4zooA+zP+Hhf7aH/AEVbWv8Avm2/+M0f8PC/20P+ira1/wB823/xmvjOigD7M/4eF/tof9FW1r/vm2/+M0f8PC/20P8Aoq2tf9823/xmvjOigD7M/wCHhf7aH/RVta/75tv/AIzR/wAPC/20P+ira1/3zbf/ABmvjOigD7M/4eF/tof9FW1r/vm2/wDjNH/Dwv8AbQ/6KtrX/fNt/wDGa+M6KAPsz/h4X+2h/wBFW1r/AL5tv/jNH/Dwv9tD/oq2tf8AfNt/8Zr4zooA+zP+Hhf7aH/RVta/75tv/jNH/Dwv9tD/AKKtrX/fNt/8Zr4zooA+zP8Ah4X+2h/0VbWv++bb/wCM0f8ADwv9tD/oq2tf9823/wAZr4zooA+zP+Hhf7aH/RVta/75tv8A4zR/w8L/AG0P+ira1/3zbf8AxmvjOigD7M/4eF/tof8ARVta/wC+bb/4zR/w8L/bQ/6KtrX/AHzbf/Ga+M6KAP6tv+CUnxr+Kfxx+CnizxH8WPEV14k1Kx8UyWVvcXYQPHbiytZBGPLRBje7HkZya/Uavxn/AOCJv/JvXjf/ALHOX/032dfsxQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf//X/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAr8Z/+C2X/JvXgj/sc4v/AE33lfsxX4z/APBbL/k3rwR/2OcX/pvvKAP5m6KKKACiiigAooooAKKKKACiiigAooooA+zP+Cen/J6Hwp/7DTf+k01f2YV/Gf8A8E9P+T0PhT/2Gm/9Jpq/swoAKKKKACiiigAooooAKKKKACiiigAooooA/gDooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/pk/4Im/8m9eN/8Asc5f/TfZ1+zFfjP/AMETf+TevG//AGOcv/pvs6/ZigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvxn/4LZf8m9eCP+xzi/8ATfeV+zFfjP8A8Fsv+TevBH/Y5xf+m+8oA/mbooooAKKKKACiiigAooooAKKKKACiiigD7M/4J6f8nofCn/sNN/6TTV/ZhX8Z/wDwT0/5PQ+FP/Yab/0mmr+zCgAooooAKKKKACiiigAooooAKKKKACiiigD+AOiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD+mT/gib/yb143/wCxzl/9N9nX7MV+M/8AwRN/5N68b/8AY5y/+m+zr9mKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/0f38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAK/Gf/gtl/yb14I/7HOL/wBN95X7MV+M/wDwWy/5N68Ef9jnF/6b7ygD+ZuiiigAooooAKKKKACiiigAooooAKKKKAPsz/gnp/yeh8Kf+w03/pNNX9mFfxn/APBPT/k9D4U/9hpv/Saav7MKACiiigAooooAKKKKACiiigAooooAKKKKAP4A6KKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP6ZP+CJv/JvXjf/ALHOX/032dfsxX4z/wDBE3/k3rxv/wBjnL/6b7Ov2YoAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/S/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAr8Z/+C2X/JvXgj/sc4v/AE33lfsxX4z/APBbL/k3rwR/2OcX/pvvKAP5m6KKKACiiigAooooAKKKKACiiigAooooA+zP+Cen/J6Hwp/7DTf+k01f2YV/Gf8A8E9P+T0PhT/2Gm/9Jpq/swoAKKKKACiiigAooooAKKKKACiiigAooooA/gDooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/pk/4Im/8m9eN/8Asc5f/TfZ1+zFfjP/AMETf+TevG//AGOcv/pvs6/ZigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvxn/4LZf8m9eCP+xzi/8ATfeV+zFfjP8A8Fsv+TevBH/Y5xf+m+8oA/mbooooAKKKKACiiigAooooAKKKKACiiigD7M/4J6f8nofCn/sNN/6TTV/ZhX8Z/wDwT0/5PQ+FP/Yab/0mmr+zCgAooooAKKKKACiiigAooooAKKKKACiiigD+AOiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD+mT/gib/yb143/wCxzl/9N9nX7MV+M/8AwRN/5N68b/8AY5y/+m+zr9mKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/1P38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAK/Gf/gtl/yb14I/7HOL/wBN95X7MV+M/wDwWy/5N68Ef9jnF/6b7ygD+ZuiiigAooooAKKKKACiiigAooooAKKKKAPsz/gnp/yeh8Kf+w03/pNNX9mFfwq/BT4r638Dvin4d+LHhy0tb7UvDd0bu3t70ObeRzG0eJBGyPjDnowOa/Ub/h9l+0L/ANCR4M/79ah/8m0Af0yUV/M3/wAPsv2hf+hI8Gf9+tQ/+TaP+H2X7Qv/AEJHgz/v1qH/AMm0Af0yUV/M3/w+y/aF/wChI8Gf9+tQ/wDk2j/h9l+0L/0JHgz/AL9ah/8AJtAH9MlFfzN/8Psv2hf+hI8Gf9+tQ/8Ak2j/AIfZftC/9CR4M/79ah/8m0Af0yUV/M3/AMPsv2hf+hI8Gf8AfrUP/k2j/h9l+0L/ANCR4M/79ah/8m0Af0yUV/M3/wAPsv2hf+hI8Gf9+tQ/+TaP+H2X7Qv/AEJHgz/v1qH/AMm0Af0yUV/M3/w+y/aF/wChI8Gf9+tQ/wDk2j/h9l+0L/0JHgz/AL9ah/8AJtAH4z0V/TJ/w5N/Z6/6Hfxn/wB/dP8A/kKj/hyb+z1/0O/jP/v7p/8A8hUAfzN0V/TJ/wAOTf2ev+h38Z/9/dP/APkKj/hyb+z1/wBDv4z/AO/un/8AyFQB/M3RX9Mn/Dk39nr/AKHfxn/390//AOQqP+HJv7PX/Q7+M/8Av7p//wAhUAfzN0V/TJ/w5N/Z6/6Hfxn/AN/dP/8AkKj/AIcm/s9f9Dv4z/7+6f8A/IVAH8zdFf0yf8OTf2ev+h38Z/8Af3T/AP5Co/4cm/s9f9Dv4z/7+6f/APIVAH8zdFf0yf8ADk39nr/od/Gf/f3T/wD5Co/4cm/s9f8AQ7+M/wDv7p//AMhUAfzN0V/TJ/w5N/Z6/wCh38Z/9/dP/wDkKvwV/ag+FGifA74++M/hP4cu7q+03w3fi0t7i9KG4kQxRyZkMaomcueigYoA8FooooAKKKKACiiigAooooAKKKKACiiigD+mT/gib/yb143/AOxzl/8ATfZ1+zFfjP8A8ETf+TevG/8A2Ocv/pvs6/ZigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//9X9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvxn/4LZf8m9eCP+xzi/8ATfeV+zFfjP8A8Fsv+TevBH/Y5xf+m+8oA/mbooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/v8ooooAKKKKACiiigAooooAKKKKACiiigAr+M//goX/wAnofFb/sNL/wCk0Nf2YV/Gf/wUL/5PQ+K3/YaX/wBJoaAPjOiiigAooooAKKKKACiiigAooooAKKKKAP6ZP+CJv/JvXjf/ALHOX/032dfsxX4z/wDBE3/k3rxv/wBjnL/6b7Ov2YoAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/W/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAr8Z/+C2X/JvXgj/sc4v/AE33lfsxX4z/APBbL/k3rwR/2OcX/pvvKAP5m6KKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP7/KKKKACiiigAooooAKKKKACiiigAooooAK/jP/4KF/8AJ6HxW/7DS/8ApNDX9mFfxn/8FC/+T0Pit/2Gl/8ASaGgD4zooooAKKKKACiiigAooooAKKKKACiiigD+mT/gib/yb143/wCxzl/9N9nX7MV+M/8AwRN/5N68b/8AY5y/+m+zr9mKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/1/38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAK/Gf/gtl/yb14I/7HOL/wBN95X7MV+M/wDwWy/5N68Ef9jnF/6b7ygD+ZuiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD+/yiiigAooooAKKKKACiiigAooooAKKKKACv4z/+Chf/ACeh8Vv+w0v/AKTQ1/ZhX8Z//BQv/k9D4rf9hpf/AEmhoA+M6KKKACiiigAooooAKKKKACiiigAooooA/pk/4Im/8m9eN/8Asc5f/TfZ1+zFfjP/AMETf+TevG//AGOcv/pvs6/ZigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvxn/4LZf8m9eCP+xzi/8ATfeV+zFfjP8A8Fsv+TevBH/Y5xf+m+8oA/mbooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/v8ooooAKKKKACiiigAooooAKKKKACiiigAr+M//goX/wAnofFb/sNL/wCk0Nf2YV/Gf/wUL/5PQ+K3/YaX/wBJoaAPjOiiigAooooAKKKKACiiigAooooAKKKKAP6ZP+CJv/JvXjf/ALHOX/032dfsxX4z/wDBE3/k3rxv/wBjnL/6b7Ov2YoAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/R/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAr8Z/+C2X/JvXgj/sc4v/AE33lfsxX4z/APBbL/k3rwR/2OcX/pvvKAP5m6KKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP7/KKKKACiiigAooooAKKKKACiiigAooooAK/jP/4KF/8AJ6HxW/7DS/8ApNDX9mFfxn/8FC/+T0Pit/2Gl/8ASaGgD4zooooAKKKKACiiigAooooAKKKKACiiigD+mT/gib/yb143/wCxzl/9N9nX7MV+M/8AwRN/5N68b/8AY5y/+m+zr9mKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/0v38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAK/Gf/gtl/yb14I/7HOL/wBN95X7MV+M/wDwWy/5N68Ef9jnF/6b7ygD+ZuiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD+/yiiigAooooAKKKKACiiigAooooAKKKKACv4z/+Chf/ACeh8Vv+w0v/AKTQ1/ZhX8Z//BQv/k9D4rf9hpf/AEmhoA+M6KKKACiiigAooooAKKKKACiiigAooooA/pk/4Im/8m9eN/8Asc5f/TfZ1+zFfjP/AMETf+TevG//AGOcv/pvs6/ZigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvxn/4LZf8m9eCP+xzi/8ATfeV+zFfjP8A8Fsv+TevBH/Y5xf+m+8oA/mbooooAKKKKACiiigAooooAKKKKACiiigD1L4KfCjW/jj8U/Dvwn8OXdrY6l4kujaW9xelxbxuI2kzIY1d8YQ9FJzX6jf8OTf2hf8Aod/Bn/f3UP8A5Cr4z/4J6f8AJ6Hwp/7DTf8ApNNX9mFAH8zf/Dk39oX/AKHfwZ/391D/AOQqP+HJv7Qv/Q7+DP8Av7qH/wAhV/TJRQB/M3/w5N/aF/6HfwZ/391D/wCQqP8Ahyb+0L/0O/gz/v7qH/yFX9MlFAH8zf8Aw5N/aF/6HfwZ/wB/dQ/+QqP+HJv7Qv8A0O/gz/v7qH/yFX9MlFAH8zf/AA5N/aF/6HfwZ/391D/5Co/4cm/tC/8AQ7+DP+/uof8AyFX9MlFAH8zf/Dk39oX/AKHfwZ/391D/AOQqP+HJv7Qv/Q7+DP8Av7qH/wAhV/TJRQB/M3/w5N/aF/6HfwZ/391D/wCQqP8Ahyb+0L/0O/gz/v7qH/yFX9MlFAH4z/8AD7L9nr/oSPGf/frT/wD5No/4fZfs9f8AQkeM/wDv1p//AMm1/M3RQB/TJ/w+y/Z6/wChI8Z/9+tP/wDk2j/h9l+z1/0JHjP/AL9af/8AJtfzN0UAf0yf8Psv2ev+hI8Z/wDfrT//AJNo/wCH2X7PX/QkeM/+/Wn/APybX8zdFAH9Mn/D7L9nr/oSPGf/AH60/wD+TaP+H2X7PX/QkeM/+/Wn/wDybX8zdFAH9Mn/AA+y/Z6/6Ejxn/360/8A+TaP+H2X7PX/AEJHjP8A79af/wDJtfzN0UAf0yf8Psv2ev8AoSPGf/frT/8A5No/4fZfs9f9CR4z/wC/Wn//ACbX8zdFAH9Mn/D7L9nr/oSPGf8A360//wCTa/BX9qD4r6J8cfj74z+LHhy0urHTfEl+Lu3t70ILiNBFHHiQRs6Zyh6MRivBaKACiiigAooooAKKKKACiiigAooooAKKKKAP6ZP+CJv/ACb143/7HOX/ANN9nX7MV+M//BE3/k3rxv8A9jnL/wCm+zr9mKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//U/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAr8Z/+C2X/JvXgj/sc4v/AE33lfsxX4z/APBbL/k3rwR/2OcX/pvvKAP5m6KKKACiiigAooooAKKKKACiiigAooooA+zP+Cen/J6Hwp/7DTf+k01f2YV/Gf8A8E9P+T0PhT/2Gm/9Jpq/swoAKKKKACiiigAooooAKKKKACiiigAooooA/gDooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/pk/4Im/8m9eN/8Asc5f/TfZ1+zFfjP/AMETf+TevG//AGOcv/pvs6/ZigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9X9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvxn/4LZf8m9eCP+xzi/8ATfeV+zFfjP8A8Fsv+TevBH/Y5xf+m+8oA/mbooooAKKKKACiiigAooooAKKKKACiiigD7M/4J6f8nofCn/sNN/6TTV/ZhX8Z/wDwT0/5PQ+FP/Yab/0mmr+zCgAooooAKKKKACiiigAooooAKKKKACiiigD+AOiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD+mT/gib/yb143/wCxzl/9N9nX7MV+M/8AwRN/5N68b/8AY5y/+m+zr9mKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/1v38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAK/Gf/gtl/yb14I/7HOL/wBN95X7MV+M/wDwWy/5N68Ef9jnF/6b7ygD+ZuiiigAooooAKKKKACiiigAooooAKKKKAPsz/gnp/yeh8Kf+w03/pNNX9mFfxn/APBPT/k9D4U/9hpv/Saav7MKACiiigAooooAKKKKACiiigAooooAKKKKAP4A6KKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP6ZP+CJv/JvXjf/ALHOX/032dfsxX4z/wDBE3/k3rxv/wBjnL/6b7Ov2YoAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/X/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAr8Z/+C2X/JvXgj/sc4v/AE33lfsxX4z/APBbL/k3rwR/2OcX/pvvKAP5m6KKKACiiigAooooAKKKKACiiigAooooA+zP+Cen/J6Hwp/7DTf+k01f2YV/Gf8A8E9P+T0PhT/2Gm/9Jpq/swoAKKKKACiiigAooooAKKKKACiiigAooooA/gDooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/pk/4Im/8m9eN/8Asc5f/TfZ1+zFfjP/AMETf+TevG//AGOcv/pvs6/ZigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvxn/4LZf8m9eCP+xzi/8ATfeV+zFfjP8A8Fsv+TevBH/Y5xf+m+8oA/mbooooAKKKKACiiigAooooAKKKKACiiigD7M/4J6f8nofCn/sNN/6TTV/ZhX8Z/wDwT0/5PQ+FP/Yab/0mmr+zCgAooooAKKKKACiiigAooooAKKKKACiiigD+AOiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD+mT/gib/yb143/wCxzl/9N9nX7MV+M/8AwRN/5N68b/8AY5y/+m+zr9mKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/0f38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAK/Gf/gtl/yb14I/7HOL/wBN95X7MV+XP/BVv4KfFP44/BTwn4c+E/h268SalY+KY724t7QoHjtxZXUZkPmOgxvdRwc5NAH8pNFfZn/DvT9tD/olOtf99W3/AMeo/wCHen7aH/RKda/76tv/AI9QB8Z0V9mf8O9P20P+iU61/wB9W3/x6j/h3p+2h/0SnWv++rb/AOPUAfGdFfZn/DvT9tD/AKJTrX/fVt/8eo/4d6ftof8ARKda/wC+rb/49QB8Z0V9mf8ADvT9tD/olOtf99W3/wAeo/4d6ftof9Ep1r/vq2/+PUAfGdFfZn/DvT9tD/olOtf99W3/AMeo/wCHen7aH/RKda/76tv/AI9QB8Z0V9mf8O9P20P+iU61/wB9W3/x6j/h3p+2h/0SnWv++rb/AOPUAH/BPT/k9D4U/wDYab/0mmr+zCv5cv2Kv2Kv2pvhz+1N8OvG3jb4dappOh6TqjT3t7O0BjgjMEq7m2ys2NzAcA9a/qNoAKKKKACiiigAooooAKKKKACiiigAooooA/gDor7M/wCHen7aH/RKda/76tv/AI9R/wAO9P20P+iU61/31bf/AB6gD4zor7M/4d6ftof9Ep1r/vq2/wDj1H/DvT9tD/olOtf99W3/AMeoA+M6K+zP+Hen7aH/AESnWv8Avq2/+PUf8O9P20P+iU61/wB9W3/x6gD4zor7M/4d6ftof9Ep1r/vq2/+PUf8O9P20P8AolOtf99W3/x6gD4zor7M/wCHen7aH/RKda/76tv/AI9R/wAO9P20P+iU61/31bf/AB6gD4zor7M/4d6ftof9Ep1r/vq2/wDj1H/DvT9tD/olOtf99W3/AMeoA+M6K+zP+Hen7aH/AESnWv8Avq2/+PUf8O9P20P+iU61/wB9W3/x6gD4zor7M/4d6ftof9Ep1r/vq2/+PUf8O9P20P8AolOtf99W3/x6gD4zor7M/wCHen7aH/RKda/76tv/AI9R/wAO9P20P+iU61/31bf/AB6gD4zor7M/4d6ftof9Ep1r/vq2/wDj1H/DvT9tD/olOtf99W3/AMeoA+M6K+zP+Hen7aH/AESnWv8Avq2/+PUf8O9P20P+iU61/wB9W3/x6gD4zor7M/4d6ftof9Ep1r/vq2/+PUf8O9P20P8AolOtf99W3/x6gD4zor7M/wCHen7aH/RKda/76tv/AI9R/wAO9P20P+iU61/31bf/AB6gD9mP+CJv/JvXjf8A7HOX/wBN9nX7MV+XP/BKT4KfFP4HfBTxZ4c+LHh268N6lfeKZL23t7soXktzZWsYkHlu4xvRhyc5FfqNQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf/9L9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//T/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/1P38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9X9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//W/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/1/38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9D9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//R/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0v38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9P9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//U/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/1f38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9b9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//X/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0P38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9H9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//S/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0/38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9T9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//V/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/1v38ooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9f9/KKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//Q/fyiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/2Q=="/>
90
90
  </defs>
91
91
  </svg>
92
- `;var hn=e=>`<!doctype html>
92
+ `;var fn=e=>`<!doctype html>
93
93
  <html>
94
94
  <head>
95
95
  <title>Scalar API Reference</title>
@@ -106,7 +106,7 @@ Error: `,s),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
106
106
  </script>
107
107
  <script>
108
108
  var configuration = {
109
- favicon: "data:image/svg+xml;utf8,${encodeURIComponent(Yt)}",
109
+ favicon: "data:image/svg+xml;utf8,${encodeURIComponent(Xt)}",
110
110
  theme: "saturn",
111
111
  metaData: {
112
112
  title: "Better Auth API",
@@ -119,4 +119,4 @@ Error: `,s),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
119
119
  </script>
120
120
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
121
121
  </body>
122
- </html>`,yn=e=>{let t=e?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:c("/open-api/generate-schema",{method:"GET"},async o=>{let i=await Jo(o.context,o.context.options);return o.json(i)}),openAPIReference:c(t,{method:"GET",metadata:{isAction:!1}},async o=>{if(e?.disableDefaultReference)throw new C.APIError("NOT_FOUND");let i=await Jo(o.context,o.context.options);return new Response(hn(i),{headers:{"Content-Type":"text/html"}})})}}};0&&(module.exports={HIDE_METADATA,admin,anonymous,bearer,createAuthEndpoint,createAuthMiddleware,customSession,emailOTP,genericOAuth,getPasskeyActions,jwt,magicLink,multiSession,oAuthProxy,oneTap,openAPI,optionsMiddleware,organization,passkey,passkeyClient,phoneNumber,twoFactor,twoFactorClient,username});
122
+ </html>`,hn=e=>{let t=e?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:c("/open-api/generate-schema",{method:"GET"},async o=>{let i=await Jo(o.context,o.context.options);return o.json(i)}),openAPIReference:c(t,{method:"GET",metadata:{isAction:!1}},async o=>{if(e?.disableDefaultReference)throw new C.APIError("NOT_FOUND");let i=await Jo(o.context,o.context.options);return new Response(fn(i),{headers:{"Content-Type":"text/html"}})})}}};0&&(module.exports={HIDE_METADATA,admin,anonymous,bearer,createAuthEndpoint,createAuthMiddleware,customSession,emailOTP,genericOAuth,getPasskeyActions,jwt,magicLink,multiSession,oAuthProxy,oneTap,openAPI,optionsMiddleware,organization,passkey,passkeyClient,phoneNumber,twoFactor,twoFactorClient,username});