better-auth 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/adapters/drizzle.d.cts +1 -1
  2. package/dist/adapters/drizzle.d.ts +1 -1
  3. package/dist/adapters/kysely.d.cts +1 -1
  4. package/dist/adapters/kysely.d.ts +1 -1
  5. package/dist/adapters/memory.d.cts +1 -1
  6. package/dist/adapters/memory.d.ts +1 -1
  7. package/dist/adapters/mongodb.d.cts +1 -1
  8. package/dist/adapters/mongodb.d.ts +1 -1
  9. package/dist/adapters/prisma.d.cts +1 -1
  10. package/dist/adapters/prisma.d.ts +1 -1
  11. package/dist/api.cjs +4 -4
  12. package/dist/api.d.cts +1 -1
  13. package/dist/api.d.ts +1 -1
  14. package/dist/api.js +4 -4
  15. package/dist/{auth-BVa3db5J.d.cts → auth-BubrmklB.d.cts} +5 -1
  16. package/dist/{auth-5eyWphKM.d.ts → auth-DF-f5DGM.d.ts} +5 -1
  17. package/dist/client/plugins.d.cts +3 -3
  18. package/dist/client/plugins.d.ts +3 -3
  19. package/dist/client.d.cts +1 -1
  20. package/dist/client.d.ts +1 -1
  21. package/dist/cookies.d.cts +1 -1
  22. package/dist/cookies.d.ts +1 -1
  23. package/dist/db.d.cts +2 -2
  24. package/dist/db.d.ts +2 -2
  25. package/dist/{index-x5P1hIyV.d.cts → index-CwnHFdnT.d.cts} +2345 -65
  26. package/dist/{index-CX-Hopog.d.ts → index-aMRluDla.d.ts} +2345 -65
  27. package/dist/index.cjs +4 -4
  28. package/dist/index.d.cts +2 -2
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.js +4 -4
  31. package/dist/next-js.d.cts +1 -1
  32. package/dist/next-js.d.ts +1 -1
  33. package/dist/node.d.cts +1 -1
  34. package/dist/node.d.ts +1 -1
  35. package/dist/oauth2.d.cts +2 -2
  36. package/dist/oauth2.d.ts +2 -2
  37. package/dist/plugins.cjs +7 -7
  38. package/dist/plugins.d.cts +233 -8
  39. package/dist/plugins.d.ts +233 -8
  40. package/dist/plugins.js +7 -7
  41. package/dist/react.d.cts +1 -1
  42. package/dist/react.d.ts +1 -1
  43. package/dist/solid-start.d.cts +1 -1
  44. package/dist/solid-start.d.ts +1 -1
  45. package/dist/solid.d.cts +1 -1
  46. package/dist/solid.d.ts +1 -1
  47. package/dist/{state-CYO8U5dl.d.cts → state-CQJXHclh.d.cts} +1 -1
  48. package/dist/{state-BpBNrIEi.d.ts → state-C_runTlH.d.ts} +1 -1
  49. package/dist/svelte-kit.d.cts +1 -1
  50. package/dist/svelte-kit.d.ts +1 -1
  51. package/dist/svelte.d.cts +1 -1
  52. package/dist/svelte.d.ts +1 -1
  53. package/dist/types.d.cts +2 -2
  54. package/dist/types.d.ts +2 -2
  55. package/dist/vue.d.cts +1 -1
  56. package/dist/vue.d.ts +1 -1
  57. package/package.json +1 -1
package/dist/plugins.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var or=Object.create;var oo=Object.defineProperty;var ir=Object.getOwnPropertyDescriptor;var tr=Object.getOwnPropertyNames;var rr=Object.getPrototypeOf,nr=Object.prototype.hasOwnProperty;var sr=(e,t)=>{for(var i in t)oo(e,i,{get:t[i],enumerable:!0})},Jo=(e,t,i,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of tr(t))!nr.call(e,r)&&r!==i&&oo(e,r,{get:()=>t[r],enumerable:!(o=ir(t,r))||o.enumerable});return e};var Xo=(e,t,i)=>(i=e!=null?or(rr(e)):{},Jo(t||!e||!e.__esModule?oo(i,"default",{value:e,enumerable:!0}):i,e)),ar=e=>Jo(oo({},"__esModule",{value:!0}),e);var fn={};sr(fn,{HIDE_METADATA:()=>we,admin:()=>on,anonymous:()=>en,bearer:()=>Zr,createAuthEndpoint:()=>K,createAuthMiddleware:()=>R,customSession:()=>un,emailOTP:()=>An,genericOAuth:()=>nn,getPasskeyActions:()=>Ft,jwt:()=>sn,magicLink:()=>Wr,multiSession:()=>an,oAuthProxy:()=>cn,oneTap:()=>dn,openAPI:()=>mn,optionsMiddleware:()=>bo,organization:()=>Sr,passkey:()=>Qr,passkeyClient:()=>Hr,phoneNumber:()=>Jr,twoFactor:()=>Vr,twoFactorClient:()=>Fr,username:()=>Ho});module.exports=ar(fn);var Do=require("better-call"),Se=require("zod");var ye=require("better-call"),bo=(0,ye.createMiddleware)(async()=>({})),R=(0,ye.createMiddlewareCreator)({use:[bo,(0,ye.createMiddleware)(async()=>({}))]}),K=(0,ye.createEndpointCreator)({use:[bo]});var F=require("better-call"),x=require("zod");var lr=require("oslo"),ei=require("oslo/encoding");var io=require("oslo/crypto");async function dr({value:e,secret:t}){return new io.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function Kr({value:e,signature:t,secret:i}){return new io.HMAC("SHA-256").verify(new TextEncoder().encode(i),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var to={sign:dr,verify:Kr};var X=class extends Error{constructor(t,i){super(t),this.name="BetterAuthError",this.message=t,this.cause=i,this.stack=""}};var I=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var ro=Object.create(null),Fe=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?ro:globalThis),re=new Proxy(ro,{get(e,t){return Fe()[t]??ro[t]},has(e,t){let i=Fe();return t in i||t in ro},set(e,t,i){let o=Fe(!0);return o[t]=i,!0},deleteProperty(e,t){if(!t)return!1;let i=Fe(!0);return delete i[t],!0},ownKeys(){let e=Fe(!0);return Object.keys(e)}});function cr(e){return e?e!=="false":!1}var vo=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Yo=vo==="dev"||vo==="development",ur=vo==="test"||cr(re.TEST);function no(e){let t=new Map;return e.split(", ").forEach(o=>{let r=o.split(";").map(l=>l.trim()),[n,...a]=r,[s,...A]=n.split("="),d=A.join("=");if(!s||d===void 0){console.warn(`Malformed cookie: ${o}`);return}let c={value:d};a.forEach(l=>{let[u,...p]=l.split("="),h=p.join("="),k=u.trim().toLowerCase();switch(k){case"max-age":c["max-age"]=h?parseInt(h.trim(),10):void 0;break;case"expires":c.expires=h?new Date(h.trim()):void 0;break;case"domain":c.domain=h?h.trim():void 0;break;case"path":c.path=h?h.trim():void 0;break;case"secure":c.secure=!0;break;case"httponly":c.httponly=!0;break;case"samesite":c.samesite=h?h.trim().toLowerCase():void 0;break;default:c[k]=h?h.trim():!0;break}}),t.set(s,c)}),t}async function m(e,t,i,o){let r=e.context.authCookies.sessionToken.options,n=i?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...r,maxAge:n,...o}),i&&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(ei.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:I(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}),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 Ve(e){let t=e.split("; "),i=new Map;return t.forEach(o=>{let[r,n]=o.split("=");i.set(r,n)}),i}var si=require("@better-fetch/fetch"),ai=require("better-call"),Ie=require("jose"),Ai=require("oslo/jwt");var oi=require("oslo/crypto"),ii=require("oslo/encoding");async function ti(e){let t=await(0,oi.sha256)(new TextEncoder().encode(e));return ii.base64url.encode(new Uint8Array(t),{includePadding:!1})}function ri(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?I(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function P({id:e,options:t,authorizationEndpoint:i,state:o,codeVerifier:r,scopes:n,claims:a,redirectURI:s}){let A=new URL(i);if(A.searchParams.set("response_type","code"),A.searchParams.set("client_id",t.clientId),A.searchParams.set("state",o),A.searchParams.set("scope",n.join(" ")),A.searchParams.set("redirect_uri",t.redirectURI||s),r){let d=await ti(r);A.searchParams.set("code_challenge_method","S256"),A.searchParams.set("code_challenge",d)}if(a){let d=a.reduce((c,l)=>(c[l]=null,c),{});A.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...d}}))}return A}var ni=require("@better-fetch/fetch");async function O({code:e,codeVerifier:t,redirectURI:i,options:o,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",i),n==="basic"){let l=btoa(`${o.clientId}:${o.clientSecret}`);s.authorization=`Basic ${l}`}else a.set("client_id",o.clientId),a.set("client_secret",o.clientSecret);let{data:A,error:d}=await(0,ni.betterFetch)(r,{method:"POST",body:a,headers:s});if(d)throw d;return ri(A)}var so=require("oslo/oauth2"),ce=require("zod"),ko=require("better-call");function Te(e){try{return new URL(e).origin}catch{return null}}async function Oe(e,t){let i=e.body?.callbackURL||(e.query?.currentURL?Te(e.query?.currentURL):"")||e.context.options.baseURL;if(!i)throw new ko.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,so.generateCodeVerifier)(),r=(0,so.generateState)(),n=JSON.stringify({callbackURL:i,codeVerifier:o,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 ko.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:s.identifier,codeVerifier:o}}async function ao(e){let t=e.query.state||e.body.state,i=await e.context.internalAdapter.findVerificationValue(t);if(!i)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=ce.z.object({callbackURL:ce.z.string(),codeVerifier:ce.z.string(),errorURL:ce.z.string().optional(),expiresAt:ce.z.number(),link:ce.z.object({email:ce.z.string(),userId:ce.z.string()}).optional()}).parse(JSON.parse(i.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(i.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(i.id),o}var di=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:i,scopes:o,redirectURI:r}){let n=o||["email","name"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${r||e.redirectURI}&scope=${n.join(" ")}&state=${i}&response_mode=form_post`)},validateAuthorizationCode:async({code:i,codeVerifier:o,redirectURI:r})=>O({code:i,codeVerifier:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t}),async verifyIdToken(i,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(i,o);let r=(0,Ie.decodeProtectedHeader)(i),{kid:n,alg:a}=r;if(!n||!a)return!1;let s=await pr(n),{payload:A}=await(0,Ie.jwtVerify)(i,s,{algorithms:[a],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{A[d]!==void 0&&(A[d]=!!A[d])}),o&&A.nonce!==o?!1:!!A},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);if(!i.idToken)return null;let o=(0,Ai.parseJWT)(i.idToken)?.payload;if(!o)return null;let r=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email;return{user:{id:o.sub,name:r,emailVerified:!1,email:o.email},data:o}}}},pr=async e=>{let t="https://appleid.apple.com",i="/auth/keys",{data:o}=await(0,si.betterFetch)(`${t}${i}`);if(!o?.keys)throw new ai.APIError("BAD_REQUEST",{message:"Keys not found"});let r=o.keys.find(n=>n.kid===e);if(!r)throw new Error(`JWK with kid ${e} not found`);return await(0,Ie.importJWK)(r,r.alg)};var Ki=require("@better-fetch/fetch");var ci=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:i,redirectURI:o}){let r=i||["identify","email"];return e.scope&&r.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${r.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:i})=>O({code:t,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:i,error:o}=await(0,Ki.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(i.avatar===null){let r=i.discriminator==="0"?Number(BigInt(i.id)>>BigInt(22))%6:parseInt(i.discriminator)%5;i.image_url=`https://cdn.discordapp.com/embed/avatars/${r}.png`}else{let r=i.avatar.startsWith("a_")?"gif":"png";i.image_url=`https://cdn.discordapp.com/avatars/${i.id}/${i.avatar}.${r}`}return{user:{id:i.id,name:i.display_name||i.username||"",email:i.email,emailVerified:i.verified,image:i.image_url},data:i}}});var ui=require("@better-fetch/fetch");var li=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:i,redirectURI:o}){let r=i||["email","public_profile"];return e.scope&&r.push(...e.scope),await P({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:r,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:i})=>O({code:t,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:i,error:o}=await(0,ui.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:i.id,name:i.name,email:i.email,image:i.picture.data.url,emailVerified:i.email_verified},data:i}}});var To=require("@better-fetch/fetch");var pi=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:i,scopes:o,codeVerifier:r,redirectURI:n}){let a=o||["user:email"];return e.scope&&a.push(...e.scope),P({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:i,redirectURI:n})},validateAuthorizationCode:async({code:i,redirectURI:o})=>O({code:i,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let{data:o,error:r}=await(0,To.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${i.accessToken}`}});if(r)return null;let n=!1;if(!o.email){let{data:a,error:s}=await(0,To.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${i.accessToken}`,"User-Agent":"better-auth"}});s||(o.email=(a.find(A=>A.primary)??a[0])?.email,n=a.find(A=>A.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n},data:o}}}};var fi=require("oslo/jwt");var gi=require("consola"),Oo=["info","success","warn","error","debug"];function gr(e,t){return Oo.indexOf(t)<=Oo.indexOf(e)}var mr=(0,gi.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),mi=e=>{let t=e?.disabled!==!0,i=e?.level??"error",o=(r,n,a=[])=>{if(!(!t||!gr(i,r))){if(!e||typeof e.log!="function"){mr[r]("",n,...a);return}e.log(r==="success"?"info":r,n,a)}};return Object.fromEntries(Oo.map(r=>[r,(...[n,...a])=>o(r,n,a)]))},G=mi();var hi=require("@better-fetch/fetch"),yi=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:i,codeVerifier:o,redirectURI:r}){if(!e.clientId||!e.clientSecret)throw G.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new X("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new X("codeVerifier is required for Google");let n=i||["email","profile","openid"];e.scope&&n.push(...e.scope);let a=await P({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,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:i,redirectURI:o})=>O({code:t,codeVerifier:i,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,i){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,i);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:r}=await(0,hi.betterFetch)(o);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 i=(0,fi.parseJWT)(t.idToken)?.payload;return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:i.email_verified},data:i}}});var wi=require("@better-fetch/fetch"),Ci=require("oslo/jwt");var bi=e=>{let t=e.tenantId||"common",i=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`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),P({id:"microsoft",options:e,authorizationEndpoint:i,state:r.state,codeVerifier:r.codeVerifier,scopes:n,redirectURI:r.redirectURI})},validateAuthorizationCode({code:r,codeVerifier:n,redirectURI:a}){return O({code:r,codeVerifier:n,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:o})},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let n=(0,Ci.parseJWT)(r.idToken)?.payload,a=e.profilePhotoSize||48;return await(0,wi.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 d=await s.response.clone().arrayBuffer(),c=Buffer.from(d).toString("base64");n.picture=`data:image/jpeg;base64, ${c}`}catch(A){G.error(A&&typeof A=="object"&&"name"in A?A.name:"",A)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};var vi=require("@better-fetch/fetch");var ki=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:i,codeVerifier:o,redirectURI:r}){let n=i||["user-read-email"];return e.scope&&n.push(...e.scope),P({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:r})},validateAuthorizationCode:async({code:t,codeVerifier:i,redirectURI:o})=>O({code:t,codeVerifier:i,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:i,error:o}=await(0,vi.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:i.id,name:i.display_name,email:i.email,image:i.images[0]?.url,emailVerified:!1},data:i}}});var we={isAction:!1};var Ti=require("nanoid"),L=e=>(0,Ti.nanoid)(e);var Oi=require("oslo/jwt");var Ii=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:i,redirectURI:o}){let r=i||["user:read:email","openid"];return e.scope&&r.push(...e.scope),P({id:"twitch",redirectURI:o,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:i})=>O({code:t,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let i=t.idToken;if(!i)return G.error("No idToken found in token"),null;let o=(0,Oi.parseJWT)(i)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var Ri=require("@better-fetch/fetch");var Ui=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let i=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&i.push(...e.scope),P({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:i,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:i,redirectURI:o})=>O({code:t,codeVerifier:i,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:i,error:o}=await(0,Ri.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:i.data.id,name:i.data.name,email:i.data.email||null,image:i.data.profile_image_url,emailVerified:i.data.verified||!1},data:i}}});var Ei=require("@better-fetch/fetch");var Pi=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:i,scopes:o,codeVerifier:r,redirectURI:n})=>{let a=o||["account_info.read"];return e.scope&&a.push(...e.scope),await P({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:a,state:i,redirectURI:n,codeVerifier:r})},validateAuthorizationCode:async({code:i,codeVerifier:o,redirectURI:r})=>await O({code:i,codeVerifier:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t}),async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);let{data:o,error:r}=await(0,Ei.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${i.accessToken}`}});return r?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};var Si=require("@better-fetch/fetch");var Di=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",i="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:r,redirectURI:n})=>{let a=r||["profile","email","openid"];return e.scope&&a.push(...e.scope),await P({id:"linkedin",options:e,authorizationEndpoint:t,scopes:a,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:r})=>await O({code:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:i}),async getUserInfo(o){let{data:r,error:n}=await(0,Si.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.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 xi=require("@better-fetch/fetch");var Io=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),fr=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:Io(`${t}/oauth/authorize`),tokenEndpoint:Io(`${t}/oauth/token`),userinfoEndpoint:Io(`${t}/api/v4/user`)}},zi=e=>{let{authorizationEndpoint:t,tokenEndpoint:i,userinfoEndpoint:o}=fr(e.issuer),r="gitlab";return{id:r,name:"Gitlab",createAuthorizationURL:async({state:a,scopes:s,codeVerifier:A,redirectURI:d})=>{let c=s||["read_user"];return e.scope&&c.push(...e.scope),await P({id:r,options:e,authorizationEndpoint:t,scopes:c,state:a,redirectURI:d,codeVerifier:A})},validateAuthorizationCode:async({code:a,redirectURI:s,codeVerifier:A})=>O({code:a,redirectURI:e.redirectURI||s,options:e,codeVerifier:A,tokenEndpoint:i}),async getUserInfo(a){if(e.getUserInfo)return e.getUserInfo(a);let{data:s,error:A}=await(0,xi.betterFetch)(o,{headers:{authorization:`Bearer ${a.accessToken}`}});return A||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 hr={apple:di,discord:ci,facebook:li,github:pi,microsoft:bi,google:yi,spotify:ki,twitch:Ii,twitter:Ui,dropbox:Pi,linkedin:Di,gitlab:zi},Ao=Object.keys(hr);var Li=require("oslo"),Ko=require("oslo/jwt"),Y=require("zod");var Me=require("better-call");var se=require("better-call");var Re=require("zod");function Ro(e){try{return JSON.parse(e)}catch{return null}}var Uo=()=>K("/get-session",{method:"GET",query:Re.z.optional(Re.z.object({disableCookieCache:Re.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 i=e.getCookie(e.context.authCookies.sessionData.name),o=i?Ro(Buffer.from(i,"base64").toString()):null;if(o&&!await to.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return M(e),e.json(null);let r=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let c=o.session;if(o.expiresAt<Date.now()||c.session.expiresAt<new Date){let u=e.context.authCookies.sessionData.name;e.setCookie(u,"",{maxAge:0})}else return e.json(c)}let n=await e.context.internalAdapter.findSession(t);if(!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 c=await e.context.internalAdapter.updateSession(n.session.token,{expiresAt:I(e.context.sessionConfig.expiresIn,"sec")});if(!c)return M(e),e.json(null,{status:401});let l=(c.expiresAt.valueOf()-Date.now())/1e3;return await m(e,{session:c,user:n.user},!1,{maxAge:l}),e.json({session:c,user:n.user})}return e.json(n)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new se.APIError("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),U=async e=>{if(e.context.session)return e.context.session;let t=await Uo()({...e,_flag:"json",headers:e.headers});return e.context.session=t,t},v=R(async e=>{let t=await U(e);if(!t?.session)throw new se.APIError("UNAUTHORIZED");return{session:t}}),qe=R(async e=>{let t=await U(e);if(!t?.session)throw new se.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let i=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),r=Date.now();if(!(o+i*1e3>r))throw new se.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),Bi=()=>K("/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 i=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(i)}),ji=K("/revoke-session",{method:"POST",body:Re.z.object({token:Re.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,i=await e.context.internalAdapter.findSession(t);if(!i)throw new se.APIError("BAD_REQUEST",{message:"Session not found"});if(i.session.userId!==e.context.session.user.id)throw new se.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new se.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Ni=K("/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 se.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),_i=K("/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 se.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 ue(e,t,i){return await(0,Ko.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:i},{expiresIn:new Li.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Fi=K("/send-verification-email",{method:"POST",query:Y.z.object({currentURL:Y.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:Y.z.object({email:Y.z.string({description:"The email to send the verification email to"}).email(),callbackURL:Y.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 Me.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,i=await e.context.internalAdapter.findUserByEmail(t);if(!i)throw new Me.APIError("BAD_REQUEST",{message:"User not found"});let o=await ue(e.context.secret,t),r=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail({user:i.user,url:r,token:o},e.request),e.json({status:!0})}),Vi=K("/verify-email",{method:"GET",query:Y.z.object({token:Y.z.string({description:"The token to verify the email"}),callbackURL:Y.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 Me.APIError("UNAUTHORIZED",{message:s})}let{token:i}=e.query,o;try{o=await(0,Ko.validateJWT)("HS256",Buffer.from(e.context.secret),i)}catch(s){return e.context.logger.error("Failed to verify email",s),t("invalid_token")}let n=Y.z.object({email:Y.z.string().email(),updateTo:Y.z.string().optional()}).parse(o.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 A=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:A,url:`${e.context.baseURL}/verify-email?token=${i}`,token:i},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:A,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await U(e)){let A=await e.context.internalAdapter.createSession(a.user.id,e.request);if(!A)throw new Me.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await m(e,{session:A,user:a.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var H=require("better-call");var qi=require("better-call");var yr=R(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:i,context:o}=e,r=e.headers?.get("origin")||e.headers?.get("referer")||"",n=t?.callbackURL||i?.callbackURL,a=t?.redirectTo,s=i?.currentURL,A=o.trustedOrigins,d=e.headers?.has("cookie"),c=(u,p)=>p.includes("*")?new RegExp("^"+p.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(u):u.startsWith(p),l=(u,p)=>{if(!u)return;if(!A.some(k=>c(u,k)||u?.startsWith("/")&&p!=="origin"&&!u.includes(":")))throw e.context.logger.error(`Invalid ${p}: ${u}`),e.context.logger.info(`If it's a valid URL, please add ${u} to trustedOrigins in your auth config
2
- `,`Current list of trustedOrigins: ${A}`),new qi.APIError("FORBIDDEN",{message:`Invalid ${p}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&l(r,"origin"),n&&l(n,"callbackURL"),a&&l(a,"redirectURL"),s&&l(s,"currentURL")});var Mi=K("/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 ae=require("better-call");var w=require("zod"),va=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)}),ka=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)}),Ta=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()}),Oa=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 wr(e,t){let i={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(i={...i,...o.schema[t].fields});return i}function Cr(e,t){let i=t.action||"create",o=t.fields,r={};for(let n in o){if(n in e){if(o[n].input===!1){if(o[n].defaultValue){r[n]=o[n].defaultValue;continue}continue}r[n]=e[n];continue}if(o[n].defaultValue&&i==="create"){r[n]=o[n].defaultValue;continue}}return r}function co(e,t,i){let o=wr(e,"user");return Cr(t||{},{fields:o,action:i})}function ee(e,t){if(!t)return e;for(let i in t){let o=t[i]?.modelName;o&&(e[i].modelName=o);for(let r in e[i].fields){let n=t[i]?.fields?.[r];n&&(e[i].fields[r].fieldName=n)}}return e}var Hi=()=>K("/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 ae.APIError("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:i,email:o,password:r,image:n,callbackURL:a,...s}=t;if(!Ce.z.string().email().safeParse(o).success)throw new ae.APIError("BAD_REQUEST",{message:"Invalid email"});let d=e.context.password.config.minPasswordLength;if(r.length<d)throw e.context.logger.error("Password is too short"),new ae.APIError("BAD_REQUEST",{message:"Password is too short"});let c=e.context.password.config.maxPasswordLength;if(r.length>c)throw e.context.logger.error("Password is too long"),new ae.APIError("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new ae.APIError("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let u=co(e.context.options,s),p;try{if(p=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:i,image:n,...u,emailVerified:!1}),!p)throw new ae.APIError("BAD_REQUEST",{message:"Failed to create user"})}catch(f){throw e.context.logger.error("Failed to create user",f),new ae.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:f})}if(!p)throw new ae.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let h=await e.context.password.hash(r);if(await e.context.internalAdapter.linkAccount({userId:p.id,providerId:"credential",accountId:p.id,password:h}),e.context.options.emailVerification?.sendOnSignUp){let f=await ue(e.context.secret,p.email),g=`${e.context.baseURL}/verify-email?token=${f}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:p,url:g,token:f},e.request)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:p,session:null});let k=await e.context.internalAdapter.createSession(p.id,e.request);if(!k)throw new ae.APIError("BAD_REQUEST",{message:"Failed to create session"});return await m(e,{session:k,user:p}),e.json({user:p,session:k})});var br=(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})},Yo=(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 ei=(e,t,o)=>(o=e!=null?ir(nr(e)):{},Yo(t||!e||!e.__esModule?oo(o,"default",{value:e,enumerable:!0}):o,e)),dr=e=>Yo(oo({},"__esModule",{value:!0}),e);var hn={};ar(hn,{HIDE_METADATA:()=>we,admin:()=>tn,anonymous:()=>on,bearer:()=>Gr,createAuthEndpoint:()=>c,createAuthMiddleware:()=>R,customSession:()=>un,emailOTP:()=>An,genericOAuth:()=>sn,getPasskeyActions:()=>qt,jwt:()=>an,magicLink:()=>Wr,multiSession:()=>dn,oAuthProxy:()=>pn,oneTap:()=>cn,openAPI:()=>fn,optionsMiddleware:()=>bo,organization:()=>Dr,passkey:()=>$r,passkeyClient:()=>Qr,phoneNumber:()=>Xr,twoFactor:()=>qr,twoFactorClient:()=>Vr,username:()=>Qo});module.exports=dr(hn);var xo=require("better-call"),De=require("zod");var ye=require("better-call"),bo=(0,ye.createMiddleware)(async()=>({})),R=(0,ye.createMiddlewareCreator)({use:[bo,(0,ye.createMiddleware)(async()=>({}))]}),c=(0,ye.createEndpointCreator)({use:[bo]});var F=require("better-call"),x=require("zod");var lr=require("oslo"),ii=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 X=class extends Error{constructor(t,o){super(t),this.name="BetterAuthError",this.message=t,this.cause=o,this.stack=""}};var I=(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),re=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 pr(e){return e?e!=="false":!1}var vo=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var oi=vo==="dev"||vo==="development",ur=vo==="test"||pr(re.TEST);function no(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;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(ii.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:I(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}),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 Me(e){let t=e.split("; "),o=new Map;return t.forEach(i=>{let[r,n]=i.split("=");o.set(r,n)}),o}var di=require("@better-fetch/fetch"),Ai=require("better-call"),Ie=require("jose"),ci=require("oslo/jwt");var ti=require("oslo/crypto"),ri=require("oslo/encoding");async function ni(e){let t=await(0,ti.sha256)(new TextEncoder().encode(e));return ri.base64url.encode(new Uint8Array(t),{includePadding:!1})}function si(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?I(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function E({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 ni(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 ai=require("@better-fetch/fetch");async function O({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,ai.betterFetch)(r,{method:"POST",body:a,headers:s});if(A)throw A;return si(d)}var so=require("oslo/oauth2"),Ke=require("zod"),ko=require("better-call");function Te(e){try{return new URL(e).origin}catch{return null}}async function Oe(e,t){let o=e.body?.callbackURL||(e.query?.currentURL?Te(e.query?.currentURL):"")||e.context.options.baseURL;if(!o)throw new ko.APIError("BAD_REQUEST",{message:"callbackURL is required"});let i=(0,so.generateCodeVerifier)(),r=(0,so.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 ko.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:s.identifier,codeVerifier:i}}async function ao(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=Ke.z.object({callbackURL:Ke.z.string(),codeVerifier:Ke.z.string(),errorURL:Ke.z.string().optional(),expiresAt:Ke.z.number(),link:Ke.z.object({email:Ke.z.string(),userId:Ke.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 Ki=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})=>O({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,Ie.decodeProtectedHeader)(o),{kid:n,alg:a}=r;if(!n||!a)return!1;let s=await gr(n),{payload:d}=await(0,Ie.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,ci.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}}}},gr=async e=>{let t="https://appleid.apple.com",o="/auth/keys",{data:i}=await(0,di.betterFetch)(`${t}${o}`);if(!i?.keys)throw new Ai.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,Ie.importJWK)(r,r.alg)};var pi=require("@better-fetch/fetch");var ui=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})=>O({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,pi.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 li=require("@better-fetch/fetch");var gi=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 E({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})=>O({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,li.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 To=require("@better-fetch/fetch");var mi=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),E({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>O({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,To.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,To.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 yi=require("oslo/jwt");var fi=require("consola"),Oo=["info","success","warn","error","debug"];function mr(e,t){return Oo.indexOf(t)<=Oo.indexOf(e)}var fr=(0,fi.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),hi=e=>{let t=e?.disabled!==!0,o=e?.level??"error",i=(r,n,a=[])=>{if(!(!t||!mr(o,r))){if(!e||typeof e.log!="function"){fr[r]("",n,...a);return}e.log(r==="success"?"info":r,n,a)}};return Object.fromEntries(Oo.map(r=>[r,(...[n,...a])=>i(r,n,a)]))},W=hi();var wi=require("@better-fetch/fetch"),Ci=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:o,codeVerifier:i,redirectURI:r}){if(!e.clientId||!e.clientSecret)throw W.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new X("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new X("codeVerifier is required for Google");let n=o||["email","profile","openid"];e.scope&&n.push(...e.scope);let a=await E({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})=>O({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,wi.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,yi.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 bi=require("@better-fetch/fetch"),vi=require("oslo/jwt");var ki=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),E({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 O({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,vi.parseJWT)(r.idToken)?.payload,a=e.profilePhotoSize||48;return await(0,bi.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){W.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 Ti=require("@better-fetch/fetch");var Oi=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),E({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})=>O({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,Ti.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 we={isAction:!1};var Ii=require("nanoid"),_=e=>(0,Ii.nanoid)(e);var Ri=require("oslo/jwt");var Ui=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),E({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})=>O({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 W.error("No idToken found in token"),null;let i=(0,Ri.parseJWT)(o)?.payload;return{user:{id:i.sub,name:i.preferred_username,email:i.email,image:i.picture,emailVerified:!1},data:i}}});var Pi=require("@better-fetch/fetch");var Ei=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let o=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&o.push(...e.scope),E({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})=>O({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,Pi.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 Si=require("@better-fetch/fetch");var Di=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 E({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 O({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,Si.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 xi=require("@better-fetch/fetch");var ji=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 E({id:"linkedin",options:e,authorizationEndpoint:t,scopes:a,state:i,redirectURI:n})},validateAuthorizationCode:async({code:i,redirectURI:r})=>await O({code:i,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:o}),async getUserInfo(i){let{data:r,error:n}=await(0,xi.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 Bi=require("@better-fetch/fetch");var Io=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),hr=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:Io(`${t}/oauth/authorize`),tokenEndpoint:Io(`${t}/oauth/token`),userinfoEndpoint:Io(`${t}/api/v4/user`)}},zi=e=>{let{authorizationEndpoint:t,tokenEndpoint:o,userinfoEndpoint:i}=hr(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 E({id:r,options:e,authorizationEndpoint:t,scopes:K,state:a,redirectURI:A,codeVerifier:d})},validateAuthorizationCode:async({code:a,redirectURI:s,codeVerifier:d})=>O({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,Bi.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 yr={apple:Ki,discord:ui,facebook:gi,github:mi,microsoft:ki,google:Ci,spotify:Oi,twitch:Ui,twitter:Ei,dropbox:Di,linkedin:ji,gitlab:zi},Ao=Object.keys(yr);var Vi=require("oslo"),co=require("oslo/jwt"),Y=require("zod");var Ue=require("better-call");var se=require("better-call");var Re=require("zod");function Ro(e){try{return JSON.parse(e)}catch{return null}}var Uo=()=>c("/get-session",{method:"GET",query:Re.z.optional(Re.z.object({disableCookieCache:Re.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?Ro(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(!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:I(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 se.APIError("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),U=async e=>{if(e.context.session)return e.context.session;let t=await Uo()({...e,_flag:"json",headers:e.headers});return e.context.session=t,t},v=R(async e=>{let t=await U(e);if(!t?.session)throw new se.APIError("UNAUTHORIZED");return{session:t}}),He=R(async e=>{let t=await U(e);if(!t?.session)throw new se.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 se.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),Ni=()=>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)}),Li=c("/revoke-session",{method:"POST",body:Re.z.object({token:Re.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 se.APIError("BAD_REQUEST",{message:"Session not found"});if(o.session.userId!==e.context.session.user.id)throw new se.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 se.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),_i=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 se.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Fi=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 se.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 pe(e,t,o){return await(0,co.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:o},{expiresIn:new Vi.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Po(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Ue.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let o=await pe(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 qi=c("/send-verification-email",{method:"POST",query:Y.z.object({currentURL:Y.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:Y.z.object({email:Y.z.string({description:"The email to send the verification email to"}).email(),callbackURL:Y.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 Ue.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 Ue.APIError("BAD_REQUEST",{message:"User not found"});return await Po(e,o.user),e.json({status:!0})}),Mi=c("/verify-email",{method:"GET",query:Y.z.object({token:Y.z.string({description:"The token to verify the email"}),callbackURL:Y.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 Ue.APIError("UNAUTHORIZED",{message:s})}let{token:o}=e.query,i;try{i=await(0,co.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=Y.z.object({email:Y.z.string().email(),updateTo:Y.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 Ue.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 H=require("better-call");var Hi=require("better-call");var wr=R(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 Hi.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 Qi=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 ae=require("better-call");var w=require("zod"),ka=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)}),Ta=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)}),Oa=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()}),Ia=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 Cr(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 br(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}r[n]=e[n];continue}if(i[n].defaultValue&&o==="create"){r[n]=i[n].defaultValue;continue}}return r}function Ko(e,t,o){let i=Cr(e,"user");return br(t||{},{fields:i,action:o})}function ee(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 $i=()=>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 ae.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 ae.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 ae.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 ae.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 ae.APIError("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let p=Ko(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 ae.APIError("BAD_REQUEST",{message:"Failed to create user"})}catch(f){throw e.context.logger.error("Failed to create user",f),new ae.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:f})}if(!l)throw new ae.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 pe(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 ae.APIError("BAD_REQUEST",{message:"Failed to create session"});return await m(e,{session:k,user:l}),e.json({user:l,session:k})});var vr=(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>`,Qi=K("/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(br(t),{headers:{"Content-Type":"text/html"}})});var b=require("better-call");function Eo(e,t){let i=t.plugins?.reduce((s,A)=>({...s,...A.endpoints}),{}),o=t.plugins?.map(s=>s.middlewares?.map(A=>{let d=async c=>A.middleware({...c,context:{...e,...c.context}});return d.path=A.path,d.options=A.middleware.options,d.headers=A.middleware.headers,{path:A.path,middleware:d}})).filter(s=>s!==void 0).flat()||[],n={...{signInSocial:$i,callbackOAuth:Wi,getSession:Uo(),signOut:Gi,signUpEmail:Hi(),signInEmail:Zi,forgetPassword:Ji,resetPassword:Yi,verifyEmail:Vi,sendVerificationEmail:Fi,changeEmail:rt,changePassword:ot,setPassword:it,updateUser:et(),deleteUser:tt,forgetPasswordCallback:Xi,listSessions:Bi(),revokeSession:ji,revokeSessions:Ni,revokeOtherSessions:_i,linkSocialAccount:st,listUserAccounts:nt},...i,ok:Mi,error:Qi},a={};for(let[s,A]of Object.entries(n))a[s]=async(d={})=>{A.headers=new Headers;let c={setHeader(f,g){A.headers.set(f,g)},setCookie(f,g,C){(0,H.setCookie)(A.headers,f,g,C)},getCookie(f,g){let T=d.headers?.get("cookie");return(0,H.getCookie)(T||"",f,g)},getSignedCookie(f,g,C){let T=d.headers;return T?(0,H.getSignedCookie)(T,g,f,C):null},async setSignedCookie(f,g,C,T){await(0,H.setSignedCookie)(A.headers,f,g,C,T)},redirect(f){return A.headers.set("Location",f),new H.APIError("FOUND")},responseHeader:A.headers},l=await e,u={...c,...d,path:A.path,context:{...l,...d.context,endpoint:A}};l.session=null;let p=t.plugins||[];for(let f of p){let g=f.hooks?.before??[];for(let C of g){if(!C.matcher(u))continue;let T=await C.handler(u);if(T&&"context"in T){u={...u,...T.context};continue}if(T)return T}}let h;try{h=await A(u)}catch(f){if(f instanceof H.APIError){let g=t.plugins?.map(C=>{if(C.hooks?.after)return C.hooks.after}).filter(C=>C!==void 0).flat();if(!g?.length)throw f.headers=A.headers,f;u.context.returned=f,u.context.returned.headers=A.headers;for(let C of g||[])if(C.matcher(u))try{let N=await C.handler(u);N&&"response"in N&&(u.context.returned=N.response)}catch(N){if(N instanceof H.APIError){u.context.returned=N;continue}throw N}if(u.context.returned instanceof H.APIError)throw u.context.returned.headers=A.headers,u.context.returned;return u.context.returned}throw f}u.context.returned=h,u.responseHeader=A.headers;for(let f of t.plugins||[])if(f.hooks?.after){for(let g of f.hooks.after)if(g.matcher(u))try{let T=await g.handler(u);T&&(u.context.returned=T)}catch(T){if(T instanceof H.APIError){u.context.returned=T;continue}throw T}}let k=u.context.returned;return k instanceof Response&&A.headers.forEach((f,g)=>{g==="set-cookie"?k.headers.append(g,f):k.headers.set(g,f)}),k},a[s].path=A.path,a[s].method=A.method,a[s].options=A.options,a[s].headers=A.headers;return{api:a,middlewares:o}}async function Ue(e,{userInfo:t,account:i,callbackURL:o}){let r=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(s=>{throw G.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(A=>A.providerId===i.providerId);if(s)await e.context.internalAdapter.updateAccount(s.id,{accessToken:i.accessToken,idToken:i.idToken,refreshToken:i.refreshToken,accessTokenExpiresAt:i.accessTokenExpiresAt,refreshTokenExpiresAt:i.refreshTokenExpiresAt});else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(i.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Yo&&G.warn(`User already exist but account isn't linked to ${i.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:i.providerId,accountId:t.id.toString(),userId:r.user.id,accessToken:i.accessToken,idToken:i.idToken,refreshToken:i.refreshToken,accessTokenExpiresAt:i.accessTokenExpiresAt,refreshTokenExpiresAt:i.refreshTokenExpiresAt,scope:i.scope})}catch(c){return G.error("Unable to link account",c),{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:i.accessToken,idToken:i.idToken,refreshToken:i.refreshToken,accessTokenExpiresAt:i.accessTokenExpiresAt,refreshTokenExpiresAt:i.refreshTokenExpiresAt,scope:i.scope,providerId:i.providerId,accountId:t.id.toString()}).then(A=>A?.user),!s&&n&&e.context.options.emailVerification?.sendOnSignUp){let A=await ue(e.context.secret,n.email),d=`${e.context.baseURL}/verify-email?token=${A}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:n,url:d,token:A},e.request)}}catch(s){return G.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 $i=K("/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(Ao,{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 A=await t.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!A||!A?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new F.APIError("UNAUTHORIZED",{message:"Failed to get user info"});if(!A.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 d=await Ue(e,{userInfo:{email:A.user.email,id:A.user.id,name:A.user.name||"",image:A.user.image,emailVerified:A.user.emailVerified||!1},account:{providerId:t.id,accountId:A.user.id,accessToken:e.body.idToken.accessToken}});if(d.error)throw new F.APIError("UNAUTHORIZED",{message:d.error});return await m(e,d.data),e.json({session:d.data.session,user:d.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:i,state:o}=await Oe(e),r=await t.createAuthorizationURL({state:o,codeVerifier:i,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:r.toString(),redirect:!e.body.disableRedirect})}),Zi=K("/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:i}=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(i),e.context.logger.error("User not found",{email:t}),new F.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let n=r.accounts.find(d=>d.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email: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(a,i))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 d=await ue(e.context.secret,r.user.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:r.user,url:c,token:d},e.request),e.context.logger.error("Email not verified",{email:t}),new F.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let A=await e.context.internalAdapter.createSession(r.user.id,e.headers,e.body.rememberMe===!1);if(!A)throw e.context.logger.error("Failed to create session"),new F.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await m(e,{session:A,user:r.user},e.body.rememberMe===!1),e.json({user:r.user,session:A,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Ee=require("zod");var uo=Ee.z.object({code:Ee.z.string().optional(),error:Ee.z.string().optional(),errorMessage:Ee.z.string().optional(),state:Ee.z.string().optional()}),Wi=K("/callback/:id",{method:["GET","POST"],body:uo.optional(),query:uo.optional(),metadata:we},async e=>{let t;try{if(e.method==="GET")t=uo.parse(e.query);else if(e.method==="POST")t=uo.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:i,error:o,state:r}=t;if(!r)throw e.context.logger.error("State not found"),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!i)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"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:A,errorURL:d}=await ao(e),c;try{c=await n.validateAuthorizationCode({code:i,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 l=await n.getUserInfo(c).then(g=>g?.user);function u(g){let C=d||s||`${e.context.baseURL}/error`;throw C.includes("?")?C=`${C}&error=${g}`:C=`${C}?error=${g}`,e.redirect(C)}if(!l)return e.context.logger.error("Unable to get user info"),u("unable_to_get_user_info");if(!l.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),u("email_not_found");if(!s)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(A){if(A.email!==l.email.toLowerCase())return u("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:A.userId,providerId:n.id,accountId:l.id}))return u("unable_to_link_account");let C;try{C=new URL(s).toString()}catch{C=s}throw e.redirect(C)}let p=await Ue(e,{userInfo:{id:l.id,email:l.email,name:l.name||"",image:l.image,emailVerified:l.emailVerified||!1},account:{providerId:n.id,accountId:l.id,...c,scope:c.scopes?.join(",")},callbackURL:s});if(p.error)return e.context.logger.error(p.error.split(" ").join("_")),u(p.error.split(" ").join("_"));let{session:h,user:k}=p.data;await m(e,{session:h,user:k});let f;try{f=new URL(s).toString()}catch{f=s}throw e.redirect(f)});var yA=require("zod");var at=require("better-call"),Gi=K("/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 J=require("zod");var lo=require("better-call");function At(e,t,i){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return i&&Object.entries(i).forEach(([r,n])=>o.searchParams.set(r,n)),o.href}function kr(e,t,i){let o=new URL(t,e.baseURL);return i&&Object.entries(i).forEach(([r,n])=>o.searchParams.set(r,n)),o.href}var Ji=K("/forget-password",{method:"POST",body:J.z.object({email:J.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:J.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 lo.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:i}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)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=I(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||r,"sec"),a=L(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${a}`,expiresAt:n});let s=`${e.context.baseURL}/reset-password/${a}?callbackURL=${i}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:s,token:a},e.request),e.json({status:!0})}),Xi=K("/reset-password/:token",{method:"GET",query:J.z.object({callbackURL:J.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:i}=e.query;if(!t||!i)throw e.redirect(At(e.context,i,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(At(e.context,i,{error:"INVALID_TOKEN"})):e.redirect(kr(e.context,i,{token:t}))}),Yi=K("/reset-password",{query:J.z.optional(J.z.object({token:J.z.string().optional(),currentURL:J.z.string().optional()})),method:"POST",body:J.z.object({newPassword:J.z.string({description:"The new password to set"}),token:J.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 lo.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:i}=e.body,o=`reset-password:${t}`,r=await e.context.internalAdapter.findVerificationValue(o);if(!r||r.expiresAt<new Date)throw new lo.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(r.id);let n=r.value,a=await e.context.password.hash(i);return(await e.context.internalAdapter.findAccounts(n)).find(d=>d.providerId==="credential")?(await e.context.internalAdapter.updatePassword(n,a),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:a,accountId:n}),e.json({status:!0}))});var _=require("zod");var Z=require("better-call");var et=()=>K("/update-user",{method:"POST",body:_.z.record(_.z.string(),_.z.any()),use:[v],metadata:{openapi:{description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"}}}}}}}}}},async e=>{let t=e.body;if(t.email)throw new Z.APIError("BAD_REQUEST",{message:"You can't update email"});let{name:i,image:o,...r}=t,n=e.context.session;if(!o&&!i&&Object.keys(r).length===0)return e.json({user:n.user});let a=co(e.context.options,r,"update"),s=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:i,image:o,...a});return await m(e,{session:n.session,user:s}),e.json({user:s})}),ot=K("/change-password",{method:"POST",body:_.z.object({newPassword:_.z.string({description:"The new password to set"}),currentPassword:_.z.string({description:"The current password"}),revokeOtherSessions:_.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[v],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:i,revokeOtherSessions:o}=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 Z.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 Z.APIError("BAD_REQUEST",{message:"Password too long"});let A=(await e.context.internalAdapter.findAccounts(r.user.id)).find(l=>l.providerId==="credential"&&l.password);if(!A||!A.password)throw new Z.APIError("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify(A.password,i))throw new Z.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(A.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(r.user.id);let l=await e.context.internalAdapter.createSession(r.user.id,e.headers);if(!l)throw new Z.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await m(e,{session:l,user:r.user})}return e.json(r.user)}),it=K("/set-password",{method:"POST",body:_.z.object({newPassword:_.z.string()}),metadata:{SERVER_ONLY:!0},use:[v]},async e=>{let{newPassword:t}=e.body,i=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new Z.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 Z.APIError("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(i.user.id)).find(A=>A.providerId==="credential"&&A.password),s=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:i.user.id,providerId:"credential",accountId:i.user.id,password:s}),e.json(i.user);throw new Z.APIError("BAD_REQUEST",{message:"user already has a password"})}),tt=K("/delete-user",{method:"POST",body:_.z.object({password:_.z.string({description:"The password of the user"})}),use:[qe],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)}),rt=K("/change-email",{method:"POST",query:_.z.object({currentURL:_.z.string().optional()}).optional(),body:_.z.object({newEmail:_.z.string({description:"The new email to set"}).email(),callbackURL:_.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[v],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new Z.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 Z.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 Z.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 Z.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let i=await ue(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${i}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:i},e.request),e.json({user:null,status:!0})});var Pe=require("zod");var Po=require("better-call");var nt=K("/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,i=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(i.map(o=>({id:o.id,provider:o.providerId})))}),st=K("/link-social",{method:"POST",requireHeaders:!0,query:Pe.z.object({currentURL:Pe.z.string().optional()}).optional(),body:Pe.z.object({callbackURL:Pe.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:Pe.z.enum(Ao,{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 Po.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 Po.APIError("NOT_FOUND",{message:"Provider not found"});let n=await Oe(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 dt=(e,t)=>{let i={};for(let[o,r]of Object.entries(e))i[o]=n=>r({...n,context:{...t,...n.context}}),i[o].path=r.path,i[o].method=r.method,i[o].options=r.options,i[o].headers=r.headers;return i};function po(e){let t=e;return{newRole(i){return Tr(i)}}}function Tr(e){return{statements:e,authorize(t,i){for(let[o,r]of Object.entries(t)){let n=e[o];return n?(i==="OR"?r.some(s=>n.includes(s)):r.every(s=>n.includes(s)))?{success:!0}:{success:!1,error:`Unauthorized to access resource "${o}"`}:{success:!1,error:`You are not allowed to access resource: ${o}`}}return{success:!1,error:"Not authorized"}}}}var Or={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},So=po(Or),Ir=So.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),Rr=So.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),Ur=So.newRole({organization:[],member:[],invitation:[]}),Kt={admin:Ir,owner:Rr,member:Ur};var B=(e,t)=>{let i=e.adapter;return{findOrganizationBySlug:async o=>await i.findOne({model:"organization",where:[{field:"slug",value:o}]}),createOrganization:async o=>{let r=await i.create({model:"organization",data:{...o.organization,metadata:o.organization.metadata?JSON.stringify(o.organization.metadata):void 0}}),n=await i.create({model:"member",data:{organizationId:r.id,userId:o.user.id,createdAt:new Date,role:t?.creatorRole||"owner"}});return{...r,metadata:r.metadata?JSON.parse(r.metadata):void 0,members:[{...n,user:{id:o.user.id,name:o.user.name,email:o.user.email,image:o.user.image}}]}},findMemberByEmail:async o=>{let r=await i.findOne({model:"user",where:[{field:"email",value:o.email}]});if(!r)return null;let n=await i.findOne({model:"member",where:[{field:"organizationId",value:o.organizationId},{field:"userId",value:r.id}]});return n?{...n,user:{id:r.id,name:r.name,email:r.email,image:r.image}}:null},findMemberByOrgId:async o=>{let[r,n]=await Promise.all([await i.findOne({model:"member",where:[{field:"userId",value:o.userId},{field:"organizationId",value:o.organizationId}]}),await i.findOne({model:"user",where:[{field:"id",value:o.userId}]})]);return!n||!r?null:{...r,user:{id:n.id,name:n.name,email:n.email,image:n.image}}},findMemberById:async o=>{let r=await i.findOne({model:"member",where:[{field:"id",value:o}]});if(!r)return null;let n=await i.findOne({model:"user",where:[{field:"id",value:r.userId}]});return n?{...r,user:{id:n.id,name:n.name,email:n.email,image:n.image}}:null},createMember:async o=>await i.create({model:"member",data:o}),updateMember:async(o,r)=>await i.update({model:"member",where:[{field:"id",value:o}],update:{role:r}}),deleteMember:async o=>await i.delete({model:"member",where:[{field:"id",value:o}]}),updateOrganization:async(o,r)=>await i.update({model:"organization",where:[{field:"id",value:o}],update:r}),deleteOrganization:async o=>(await i.delete({model:"member",where:[{field:"organizationId",value:o}]}),await i.delete({model:"invitation",where:[{field:"organizationId",value:o}]}),await i.delete({model:"organization",where:[{field:"id",value:o}]}),o),setActiveOrganization:async(o,r)=>await e.internalAdapter.updateSession(o,{activeOrganizationId:r}),findOrganizationById:async o=>await i.findOne({model:"organization",where:[{field:"id",value:o}]}),findFullOrganization:async o=>{let[r,n,a]=await Promise.all([i.findOne({model:"organization",where:[{field:"id",value:o}]}),i.findMany({model:"invitation",where:[{field:"organizationId",value:o}]}),i.findMany({model:"member",where:[{field:"organizationId",value:o}]})]);if(!r)return null;let s=a.map(l=>l.userId),A=await i.findMany({model:"user",where:[{field:"id",value:s,operator:"in"}]}),d=new Map(A.map(l=>[l.id,l])),c=a.map(l=>{let u=d.get(l.userId);if(!u)throw new X("Unexpected error: User not found for member");return{...l,user:{id:u.id,name:u.name,email:u.email,image:u.image}}});return{...r,invitations:n,members:c}},listOrganizations:async o=>{let r=await i.findMany({model:"member",where:[{field:"userId",value:o}]});if(!r||r.length===0)return[];let n=r.map(s=>s.organizationId);return await i.findMany({model:"organization",where:[{field:"id",value:n,operator:"in"}]})},createInvitation:async({invitation:o,user:r})=>{let a=I(t?.invitationExpiresIn||1728e5);return await i.create({model:"invitation",data:{email:o.email,role:o.role,organizationId:o.organizationId,status:"pending",expiresAt:a,inviterId:r.id}})},findInvitationById:async o=>await i.findOne({model:"invitation",where:[{field:"id",value:o}]}),findPendingInvitation:async o=>(await i.findMany({model:"invitation",where:[{field:"email",value:o.email},{field:"organizationId",value:o.organizationId},{field:"status",value:"pending"}]})).filter(n=>new Date(n.expiresAt)>new Date),updateInvitation:async o=>await i.update({model:"invitation",where:[{field:"id",value:o.invitationId}],update:{status:o.status}})}};var cd=require("better-call");var j=R(async e=>({})),V=R({use:[v]},async e=>({session:e.context.session}));var W=require("zod");var E=require("zod");var ct=E.z.string(),Er=E.z.enum(["pending","accepted","rejected","canceled"]).default("pending"),fd=E.z.object({id:E.z.string().default(L),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()}),hd=E.z.object({id:E.z.string().default(L),organizationId:E.z.string(),userId:E.z.string(),role:ct,createdAt:E.z.date()}),yd=E.z.object({id:E.z.string().default(L),organizationId:E.z.string(),email:E.z.string(),role:ct,status:Er,inviterId:E.z.string(),expiresAt:E.z.date()});var z=require("better-call"),ut=e=>K("/organization/invite-member",{method:"POST",use:[j,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 z.APIError("BAD_REQUEST",{message:"Invitation email is not enabled"});let i=t.context.session,o=t.body.organizationId||i.session.activeOrganizationId;if(!o)throw new z.APIError("BAD_REQUEST",{message:"Organization not found"});let r=B(t.context,t.context.orgOptions),n=await r.findMemberByOrgId({userId:i.user.id,organizationId:o});if(!n)throw new z.APIError("BAD_REQUEST",{message:"Member not found!"});let a=t.context.roles[n.role];if(!a)throw new z.APIError("BAD_REQUEST",{message:"Role not found!"});if(a.authorize({invitation:["create"]}).error)throw new z.APIError("FORBIDDEN",{message:"You are not allowed to invite members"});if(await r.findMemberByEmail({email:t.body.email,organizationId:o}))throw new z.APIError("BAD_REQUEST",{message:"User is already a member of this organization"});if((await r.findPendingInvitation({email:t.body.email,organizationId:o})).length&&!t.body.resend)throw new z.APIError("BAD_REQUEST",{message:"User is already invited to this organization"});let c=await r.createInvitation({invitation:{role:t.body.role,email:t.body.email,organizationId:o},user:i.user}),l=await r.findOrganizationById(o);if(!l)throw new z.APIError("BAD_REQUEST",{message:"Organization not found"});return await t.context.orgOptions.sendInvitationEmail?.({id:c.id,role:c.role,email:c.email,organization:l,inviter:{...n,user:i.user}},t.request),t.json(c)}),lt=K("/organization/accept-invitation",{method:"POST",body:W.z.object({invitationId:W.z.string({description:"The ID of the invitation to accept"})}),use:[j,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,i=B(e.context,e.context.orgOptions),o=await i.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new z.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==t.user.email)throw new z.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let r=await i.updateInvitation({invitationId:e.body.invitationId,status:"accepted"}),n=await i.createMember({organizationId:o.organizationId,userId:t.user.id,role:o.role,createdAt:new Date});return await i.setActiveOrganization(t.session.token,o.organizationId),r?e.json({invitation:r,member:n}):e.json(null,{status:400,body:{message:"Invitation not found!"}})}),pt=K("/organization/reject-invitation",{method:"POST",body:W.z.object({invitationId:W.z.string({description:"The ID of the invitation to reject"})}),use:[j,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,i=B(e.context,e.context.orgOptions),o=await i.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new z.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==t.user.email)throw new z.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let r=await i.updateInvitation({invitationId:e.body.invitationId,status:"rejected"});return e.json({invitation:r,member:null})}),gt=K("/organization/cancel-invitation",{method:"POST",body:W.z.object({invitationId:W.z.string({description:"The ID of the invitation to cancel"})}),use:[j,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,i=B(e.context,e.context.orgOptions),o=await i.findInvitationById(e.body.invitationId);if(!o)throw new z.APIError("BAD_REQUEST",{message:"Invitation not found!"});let r=await i.findMemberByOrgId({userId:t.user.id,organizationId:o.organizationId});if(!r)throw new z.APIError("BAD_REQUEST",{message:"Member not found!"});if(e.context.roles[r.role].authorize({invitation:["cancel"]}).error)throw new z.APIError("FORBIDDEN",{message:"You are not allowed to cancel this invitation"});let a=await i.updateInvitation({invitationId:e.body.invitationId,status:"canceled"});return e.json(a)}),mt=K("/organization/get-invitation",{method:"GET",use:[j],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 z.APIError("UNAUTHORIZED",{message:"Not authenticated"});let i=B(e.context,e.context.orgOptions),o=await i.findInvitationById(e.query.id);if(!o||o.status!=="pending"||o.expiresAt<new Date)throw new z.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==t.user.email)throw new z.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let r=await i.findOrganizationById(o.organizationId);if(!r)throw new z.APIError("BAD_REQUEST",{message:"Organization not found"});let n=await i.findMemberByOrgId({userId:o.inviterId,organizationId:o.organizationId});if(!n)throw new z.APIError("BAD_REQUEST",{message:"Inviter is no longer a member of the organization"});return e.json({...o,organizationName:r.name,organizationSlug:r.slug,inviterEmail:n.user.email})});var oe=require("zod");var ge=require("better-call");var ft=()=>K("/organization/add-member",{method:"POST",body:oe.z.object({userId:oe.z.string(),role:oe.z.string(),organizationId:oe.z.string().optional()}),use:[j],metadata:{SERVER_ONLY:!0}},async e=>{let t=e.body.userId?await U(e).catch(s=>null):null,i=e.body.organizationId||t?.session.activeOrganizationId;if(!i)return e.json(null,{status:400,body:{message:"No active organization found!"}});let o=B(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 o.findMemberByEmail({email:r.email,organizationId:i}))throw new ge.APIError("BAD_REQUEST",{message:"User is already a member of this organization"});let a=await o.createMember({id:L(),organizationId:i,userId:r.id,role:e.body.role,createdAt:new Date});return e.json(a)}),ht=K("/organization/remove-member",{method:"POST",body:oe.z.object({memberIdOrEmail:oe.z.string({description:"The ID or email of the member to remove"}),organizationId:oe.z.string({description:"The ID of the organization to remove the member from. If not provided, the active organization will be used"}).optional()}),use:[j,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,i=e.body.organizationId||t.session.activeOrganizationId;if(!i)return e.json(null,{status:400,body:{message:"No active organization found!"}});let o=B(e.context,e.context.orgOptions),r=await o.findMemberByOrgId({userId:t.user.id,organizationId:i});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 d=null;if(e.body.memberIdOrEmail.includes("@")?d=await o.findMemberByEmail({email:e.body.memberIdOrEmail,organizationId:i}):d=await o.findMemberById(e.body.memberIdOrEmail),d?.organizationId!==i)throw new ge.APIError("BAD_REQUEST",{message:"Member not found!"});return await o.deleteMember(d.id),t.user.id===d.userId&&t.session.activeOrganizationId===d.organizationId&&await o.setActiveOrganization(t.session.token,null),e.json({member:d})}),yt=e=>K("/organization/update-member-role",{method:"POST",body:oe.z.object({role:oe.z.string(),memberId:oe.z.string(),organizationId:oe.z.string().optional()}),use:[j,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 i=t.context.session,o=t.body.organizationId||i.session.activeOrganizationId;if(!o)return t.json(null,{status:400,body:{message:"No active organization found!"}});let r=B(t.context,t.context.orgOptions),n=await r.findMemberByOrgId({userId:i.user.id,organizationId:o});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 A=await r.updateMember(t.body.memberId,t.body.role);return A?t.json(A):t.json(null,{status:400,body:{message:"Member not found!"}})}),wt=K("/organization/get-active-member",{method:"GET",use:[j,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,i=t.session.activeOrganizationId;if(!i)return e.json(null,{status:400,body:{message:"No active organization found!"}});let r=await B(e.context,e.context.orgOptions).findMemberByOrgId({userId:t.user.id,organizationId:i});return r?e.json(r):e.json(null,{status:400,body:{message:"Member not found!"}})});var S=require("zod");var me=require("better-call");var Ct=K("/organization/create",{method:"POST",body:S.z.object({name:S.z.string({description:"The name of the organization"}),slug:S.z.string({description:"The slug of the organization"}),userId:S.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:S.z.string({description:"The logo of the organization"}).optional(),metadata:S.z.record(S.z.string(),S.z.any(),{description:"The metadata of the organization"}).optional()}),use:[j,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 i=e.context.orgOptions;if(!(typeof i?.allowUserToCreateOrganization=="function"?await i.allowUserToCreateOrganization(t):i?.allowUserToCreateOrganization===void 0?!0:i.allowUserToCreateOrganization))throw new me.APIError("FORBIDDEN",{message:"You are not allowed to create an organization"});let r=B(e.context,i),n=await r.listOrganizations(t.id);if(typeof i.organizationLimit=="number"?n.length>=i.organizationLimit:typeof i.organizationLimit=="function"?await i.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 A=await r.createOrganization({organization:{id:L(),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,A.id),e.json(A)}),bt=K("/organization/update",{method:"POST",body:S.z.object({data:S.z.object({name:S.z.string({description:"The name of the organization"}).optional(),slug:S.z.string({description:"The slug of the organization"}).optional(),logo:S.z.string({description:"The logo of the organization"}).optional()}).partial(),organizationId:S.z.string().optional()}),requireHeaders:!0,use:[j],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 i=e.body.organizationId||t.session.activeOrganizationId;if(!i)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let o=B(e.context,e.context.orgOptions),r=await o.findMemberByOrgId({userId:t.user.id,organizationId:i});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 o.updateOrganization(i,e.body.data);return e.json(s)}),vt=K("/organization/delete",{method:"POST",body:S.z.object({organizationId:S.z.string({description:"The organization id to delete"})}),requireHeaders:!0,use:[j],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 i=e.body.organizationId;if(!i)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let o=B(e.context,e.context.orgOptions),r=await o.findMemberByOrgId({userId:t.user.id,organizationId:i});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 i===t.session.activeOrganizationId&&await o.setActiveOrganization(t.session.token,null),await o.deleteOrganization(i),e.json(i)}),kt=K("/organization/get-full-organization",{method:"GET",query:S.z.optional(S.z.object({organizationId:S.z.string({description:"The organization id to get"}).optional()})),requireHeaders:!0,use:[j,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,i=e.query?.organizationId||t.session.activeOrganizationId;if(!i)return e.json(null,{status:200});let r=await B(e.context,e.context.orgOptions).findFullOrganization(i);if(!r)throw new me.APIError("BAD_REQUEST",{message:"Organization not found"});return e.json(r)}),Tt=K("/organization/set-active",{method:"POST",body:S.z.object({organizationId:S.z.string({description:"The organization id to set as active. Can be null to unset the active organization"}).nullable().optional()}),use:[V,j],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=B(e.context,e.context.orgOptions),i=e.context.session,o=e.body.organizationId;if(o===null){if(!i.session.activeOrganizationId)return e.json(null);let A=await t.setActiveOrganization(i.session.token,null);return await m(e,{session:A,user:i.user}),e.json(null)}if(!o){let s=i.session.activeOrganizationId;if(!s)return e.json(null);o=s}if(!await t.findMemberByOrgId({userId:i.user.id,organizationId:o}))throw await t.setActiveOrganization(i.session.token,null),new me.APIError("FORBIDDEN",{message:"You are not a member of this organization"});let n=await t.setActiveOrganization(i.session.token,o);await m(e,{session:n,user:i.user});let a=await t.findFullOrganization(o);return e.json(a)}),Ot=K("/organization/list",{method:"GET",use:[j,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 i=await B(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(i)});var Pr=po({name:["action"]}),Zd=Pr.newRole({name:["action"]}),Sr=e=>{let t={createOrganization:Ct,updateOrganization:bt,deleteOrganization:vt,setActiveOrganization:Tt,getFullOrganization:kt,listOrganizations:Ot,createInvitation:ut(e),cancelInvitation:gt,acceptInvitation:lt,getInvitation:mt,rejectInvitation:pt,addMember:ft(),removeMember:ht,updateMemberRole:yt(e),getActiveMember:wt},i={...Kt,...e?.roles};return{id:"organization",endpoints:{...dt(t,{orgOptions:e||{},roles:i,getSession:async r=>await U(r)}),hasPermission:K("/organization/has-permission",{method:"POST",requireHeaders:!0,body:Se.z.object({permission:Se.z.record(Se.z.string(),Se.z.array(Se.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 Do.APIError("BAD_REQUEST",{message:"No active organization"});let a=await B(r.context).findMemberByOrgId({userId:r.context.session.user.id,organizationId:r.context.session.session.activeOrganizationId||""});if(!a)throw new Do.APIError("UNAUTHORIZED",{message:"You are not a member of this organization"});let A=i[a.role].authorize(r.body.permission);return A.error?r.json({error:A.error,success:!1},{status:403}):r.json({error:null,success:!0})})},schema:{session:{fields:{activeOrganizationId:{type:"string",required:!1,fieldName:e?.schema?.session?.fields?.activeOrganizationId}}},organization:{modelName:e?.schema?.organization?.modelName,fields:{name:{type:"string",required:!0,fieldName:e?.schema?.organization?.fields?.name},slug:{type:"string",unique:!0,fieldName:e?.schema?.organization?.fields?.slug},logo:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.logo},createdAt:{type:"date",required:!0,fieldName:e?.schema?.organization?.fields?.createdAt},metadata:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.metadata}}},member:{modelName:e?.schema?.member?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.member?.fields?.organizationId},userId:{type:"string",required:!0,fieldName:e?.schema?.member?.fields?.userId,references:{model:"user",field:"id"}},role:{type:"string",required:!0,defaultValue:"member",fieldName:e?.schema?.member?.fields?.role},createdAt:{type:"date",required:!0,fieldName:e?.schema?.member?.fields?.createdAt}}},invitation:{modelName:e?.schema?.invitation?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.invitation?.fields?.organizationId},email:{type:"string",required:!0,fieldName:e?.schema?.invitation?.fields?.email},role:{type:"string",required:!1,fieldName:e?.schema?.invitation?.fields?.role},status:{type:"string",required:!0,defaultValue:"pending",fieldName:e?.schema?.invitation?.fields?.status},expiresAt:{type:"date",required:!0,fieldName:e?.schema?.invitation?.fields?.expiresAt},inviterId:{type:"string",references:{model:"user",field:"id"},fieldName:e?.schema?.invitation?.fields?.inviterId,required:!0}}}},$Infer:{Organization:{},Invitation:{},Member:{},ActiveOrganization:{}}}};var xo=Xo(require("uncrypto"),1);function Dr(e){return e.toString(2).padStart(8,"0")}function xr(e){return[...e].map(t=>Dr(t)).join("")}function It(e){return parseInt(xr(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,i=t%8,o=new Uint8Array(Math.ceil(t/8));xo.default.getRandomValues(o),i!==0&&(o[0]&=(1<<i)-1);let r=It(o);for(;r>=e;)xo.default.getRandomValues(o),i!==0&&(o[0]&=(1<<i)-1),r=It(o);return r}function Q(e,t){let i="";for(let o=0;o<e;o++)i+=t[zr(t.length)];return i}function $(...e){let t=new Set(e),i="";for(let o of t)o==="a-z"?i+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?i+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?i+="0123456789":i+=o;return i}var We=require("zod");var Bo=require("@noble/ciphers/chacha"),De=require("@noble/ciphers/utils"),jo=require("@noble/ciphers/webcrypto"),No=require("oslo/crypto"),zo=Xo(require("uncrypto"),1);var Rt=require("oslo/encoding");var Br=require("@noble/hashes/scrypt"),jr=require("uncrypto");async function He(e,t){let i=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},r=await zo.default.subtle.importKey("raw",i.encode(e),o,!1,["sign","verify"]),n=await zo.default.subtle.sign(o.name,r,i.encode(t));return btoa(String.fromCharCode(...new Uint8Array(n)))}var le=async({key:e,data:t})=>{let i=await(0,No.sha256)(new TextEncoder().encode(e)),o=(0,De.utf8ToBytes)(t),r=(0,jo.managedNonce)(Bo.xchacha20poly1305)(new Uint8Array(i));return(0,De.bytesToHex)(r.encrypt(o))},fe=async({key:e,data:t})=>{let i=await(0,No.sha256)(new TextEncoder().encode(e)),o=(0,De.hexToBytes)(t),r=(0,jo.managedNonce)(Bo.xchacha20poly1305)(new Uint8Array(i));return new TextDecoder().decode(r.decrypt(o))};var Ae=require("zod");var xe=require("better-call");var go="two_factor";var mo="trust_device";var _o=require("zod");var be=R({body:_o.z.object({trustDevice:_o.z.boolean().optional()})},async e=>{let t=await U(e);if(!t){let i=e.context.createAuthCookie(go),o=await e.getSignedCookie(i.name,e.context.secret);if(!o)throw new xe.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let r=await e.context.internalAdapter.findUserById(o);if(!r)throw new xe.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let n=await e.context.internalAdapter.createSession(o,e.request);if(!n)throw new xe.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 He(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 xe.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 xe.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:t}});var ze=require("better-call");function Nr(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 Lo(e,t){let i=e,o=t?.customBackupCodesGenerate?t.customBackupCodesGenerate():Nr(),r=await le({data:JSON.stringify(o),key:i});return{backupCodes:o,encryptedBackupCodes:r}}async function _r(e,t){let i=await Ut(e.backupCodes,t);return i?{status:i.includes(e.code),updated:i.filter(o=>o!==e.code)}:{status:!1,updated:null}}async function Ut(e,t){let i=Buffer.from(await fe({key:t,data:e})).toString("utf-8"),o=JSON.parse(i),r=Ae.z.array(Ae.z.string()).safeParse(o);return r.success?r.data:null}var Et=(e,t)=>({id:"backup_code",endpoints:{verifyBackupCode:K("/two-factor/verify-backup-code",{method:"POST",body:Ae.z.object({code:Ae.z.string(),disableSession:Ae.z.boolean().optional()}),use:[be]},async i=>{let o=i.context.session.user,r=await i.context.adapter.findOne({model:t,where:[{field:"userId",value:o.id}]});if(!r)throw new ze.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let n=await _r({backupCodes:r.backupCodes,code:i.body.code},i.context.secret);if(!n.status)throw new ze.APIError("UNAUTHORIZED",{message:"Invalid backup code"});let a=await le({key:i.context.secret,data:JSON.stringify(n.updated)});return await i.context.adapter.update({model:t,update:{backupCodes:a},where:[{field:"userId",value:o.id}]}),i.body.disableSession||await m(i,{session:i.context.session.session,user:o}),i.json({user:o,session:i.context.session})}),generateBackupCodes:K("/two-factor/generate-backup-codes",{method:"POST",body:Ae.z.object({password:Ae.z.string()}),use:[v]},async i=>{let o=i.context.session.user;if(!o.twoFactorEnabled)throw new ze.APIError("BAD_REQUEST",{message:"Two factor isn't enabled"});await i.context.password.checkPassword(o.id,i);let r=await Lo(i.context.secret,e);return await i.context.adapter.update({model:t,update:{backupCodes:r.encryptedBackupCodes},where:[{field:"userId",value:i.context.session.user.id}]}),i.json({status:!0,backupCodes:r.backupCodes})}),viewBackupCodes:K("/two-factor/view-backup-codes",{method:"GET",body:Ae.z.object({userId:Ae.z.string()}),metadata:{SERVER_ONLY:!0}},async i=>{let o=await i.context.adapter.findOne({model:t,where:[{field:"userId",value:i.body.userId}]});if(!o)throw new ze.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let r=await Ut(o.backupCodes,i.context.secret);if(!r)throw new ze.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});return i.json({status:!0,backupCodes:r})})}});var Qe=require("better-call"),Pt=require("oslo/otp"),Fo=require("zod");var St=require("oslo"),Dt=(e,t)=>{let i={...e,period:new St.TimeSpan(e?.period||3,"m")},o=new Pt.TOTPController({digits:6,period:i.period}),r=K("/two-factor/send-otp",{method:"POST",use:[be]},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 Qe.APIError("BAD_REQUEST",{message:"otp isn't configured"});let s=a.context.session.user,A=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!A)throw new Qe.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});let d=await o.generate(Buffer.from(A.secret));return await e.sendOTP({user:s,otp:d},a.request),a.json({status:!0})}),n=K("/two-factor/verify-otp",{method:"POST",body:Fo.z.object({code:Fo.z.string()}),use:[be]},async a=>{let s=a.context.session.user;if(!s.twoFactorEnabled)throw new Qe.APIError("BAD_REQUEST",{message:"two factor isn't enabled"});let A=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!A)throw new Qe.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});return await o.generate(Buffer.from(A.secret))===a.body.code?a.context.valid():a.context.invalid()});return{id:"otp",endpoints:{sendTwoFactorOTP:r,verifyTwoFactorOTP:n}}};var ve=require("better-call"),xt=require("oslo"),Ze=require("oslo/otp"),$e=require("zod");var zt=(e,t)=>{let i={...e,digits:6,period:new xt.TimeSpan(e?.period||30,"s")},o=K("/totp/generate",{method:"POST",use:[v]},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,A=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!A)throw new ve.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return{code:await new Ze.TOTPController(i).generate(Buffer.from(A.secret))}}),r=K("/two-factor/get-totp-uri",{method:"POST",use:[v],body:$e.z.object({password:$e.z.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,A=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!A||!s.twoFactorEnabled)throw new ve.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return await a.context.password.checkPassword(s.id,a),{totpURI:(0,Ze.createTOTPKeyURI)(e.issuer||a.context.appName,s.email,Buffer.from(A.secret),i)}}),n=K("/two-factor/verify-totp",{method:"POST",body:$e.z.object({code:$e.z.string()}),use:[be]},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,A=await a.context.adapter.findOne({model:t,where:[{field:"userId",value:s.id}]});if(!A)throw new ve.APIError("BAD_REQUEST",{message:"totp isn't enabled"});let d=new Ze.TOTPController(i),c=await fe({key:a.context.secret,data:A.secret}),l=Buffer.from(c);if(!await d.verify(a.body.code,l))return a.context.invalid();if(!s.twoFactorEnabled){let p=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:p})}return a.context.valid()});return{id:"totp",endpoints:{generateTOTP:o,getTOTPURI:r,verifyTOTP:n}}};var Lr=require("better-call");async function Vo(e,t){let o=(await e.context.internalAdapter.findAccounts(t.userId))?.find(a=>a.providerId==="credential"),r=o?.password;return!o||!r?!1:await e.context.password.verify(r,t.password)}var qo=require("better-call"),Nt=require("oslo/otp"),_t=require("oslo");var Bt=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 Bt.APIError?null:t:null};var jt={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 Fr=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 Vr=e=>{let t={twoFactorTable:"twoFactor"},i=zt({issuer:e?.issuer,...e?.totpOptions},t.twoFactorTable),o=Et({...e?.backupCodeOptions},t.twoFactorTable),r=Dt({...e?.otpOptions},t.twoFactorTable);return{id:"two-factor",endpoints:{...i.endpoints,...r.endpoints,...o.endpoints,enableTwoFactor:K("/two-factor/enable",{method:"POST",body:We.z.object({password:We.z.string().min(8)}),use:[v]},async n=>{let a=n.context.session.user,{password:s}=n.body;if(!await Vo(n,{password:s,userId:a.id}))throw new qo.APIError("BAD_REQUEST",{message:"Invalid password"});let d=Q(16,$("a-z","0-9","-")),c=await le({key:n.context.secret,data:d}),l=await Lo(n.context.secret,e?.backupCodeOptions);if(e?.skipVerificationOnEnable){let p=await n.context.internalAdapter.updateUser(a.id,{twoFactorEnabled:!0}),h=await n.context.internalAdapter.createSession(p.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:c,backupCodes:l.encryptedBackupCodes,userId:a.id}});let u=(0,Nt.createTOTPKeyURI)(e?.issuer||"BetterAuth",a.email,Buffer.from(d),{digits:e?.totpOptions?.digits||6,period:new _t.TimeSpan(e?.totpOptions?.period||30,"s")});return n.json({totpURI:u,backupCodes:l.backupCodes})}),disableTwoFactor:K("/two-factor/disable",{method:"POST",body:We.z.object({password:We.z.string().min(8)}),use:[v]},async n=>{let a=n.context.session.user,{password:s}=n.body;if(!await Vo(n,{password:s,userId:a.id}))throw new qo.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 d=await n.context.internalAdapter.createSession(a.id,n.request,!1,n.context.session.session);return await m(n,{session:d,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:R(async n=>{let a=await Be(n);if(!a||!a.user.twoFactorEnabled)return;let s=n.context.createAuthCookie(mo),A=await n.getSignedCookie(s.name,n.context.secret);if(A){let[c,l]=A.split("!"),u=await He(n.context.secret,`${a.user.id}!${l}`);if(c===u){let p=await He(n.context.secret,`${a.user.id}!${a.session.token}`);await n.setSignedCookie(s.name,`${p}!${a.session.token}`,n.context.secret,s.attributes);return}}M(n),await n.context.internalAdapter.deleteSession(a.session.token);let d=n.context.createAuthCookie(go,{maxAge:60*10});return await n.setSignedCookie(d.name,a.user.id,n.context.secret,d.attributes),n.json({twoFactorRedirect:!0})})}]},schema:ee(jt,e?.schema),rateLimit:[{pathMatcher(n){return n.startsWith("/two-factor/")},window:10,max:3}]}};var he=require("@simplewebauthn/server"),ie=require("better-call");var de=require("zod");var je=require("@simplewebauthn/browser");var Mr=require("@better-fetch/fetch");var sc=require("nanostores");var ZK=require("@better-fetch/fetch");var qr=require("nanostores");var GK=require("@better-fetch/fetch"),fo=require("nanostores"),Mo=(e,t,i,o)=>{let r=(0,fo.atom)({data:null,error:null,isPending:!0,isRefetching:!1}),n=()=>{let s=typeof o=="function"?o({data:r.get().data,error:r.get().error,isPending:r.get().isPending}):o;return i(t,{...s,async onSuccess(A){r.set({data:A.data,error:null,isPending:!1,isRefetching:!1}),await s?.onSuccess?.(A)},async onError(A){r.set({error:A.error,data:null,isPending:!1,isRefetching:!1}),await s?.onError?.(A)},async onRequest(A){let d=r.get();r.set({isPending:d.data===null,data:d.data,error:null,isRefetching:!0}),await s?.onRequest?.(A)}})};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 Lt=require("nanostores"),Ft=(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,je.startAuthentication)(a.data,r?.autoFill||!1),A=await e("/passkey/verify-authentication",{body:{response:s},...r?.fetchOptions,...n,method:"POST"});if(!A.data)return A}catch{return{data:null,error:{message:"auth cancelled",status:400,statusText:"BAD_REQUEST"}}}}},passkey:{addPasskey:async(r,n)=>{let a=await e("/passkey/generate-register-options",{method:"GET"});if(!a.data)return a;try{let s=await(0,je.startRegistration)(a.data),A=await e("/passkey/verify-registration",{...r?.fetchOptions,...n,body:{response:s,name:r?.name},method:"POST"});if(!A.data)return A;t.set(Math.random())}catch(s){return s instanceof je.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:{}}),Hr=()=>{let e=(0,Lt.atom)();return{id:"passkey",$InferServerPlugin:{},getActions:t=>Ft(t,{$listPasskeys:e}),getAtoms(t){return{listPasskeys:Mo(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"},signal:"_listPasskeys"}]}};var Qr=e=>{let t=re.BETTER_AUTH_URL,i=e?.rpID||t?.replace("http://","").replace("https://","").split(":")[0]||"localhost";if(!i)throw new X("passkey rpID not found. Please provide a rpID in the options or set the BETTER_AUTH_URL environment variable.");let o={origin:null,...e,rpID:i,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:K("/passkey/generate-register-options",{method:"GET",use:[qe],metadata:{client:!1}},async s=>{let A=s.context.session,d=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:A.user.id}]}),c=new Uint8Array(Buffer.from(Q(32,$("a-z","0-9")))),l;l=await(0,he.generateRegistrationOptions)({rpName:o.rpName||s.context.appName,rpID:o.rpID,userID:c,userName:A.user.email||A.user.id,attestationType:"none",excludeCredentials:d.map(p=>({id:p.id,transports:p.transports?.split(",")})),authenticatorSelection:{residentKey:"preferred",userVerification:"preferred",authenticatorAttachment:"platform"}});let u=L(32);return await s.setSignedCookie(o.advanced.webAuthnChallengeCookie,u,s.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:a}),await s.context.internalAdapter.createVerificationValue({identifier:u,value:JSON.stringify({expectedChallenge:l.challenge,userData:{id:A.user.id}}),expiresAt:r}),s.json(l,{status:200})}),generatePasskeyAuthenticationOptions:K("/passkey/generate-authenticate-options",{method:"POST",body:de.z.object({email:de.z.string().optional()}).optional()},async s=>{let A=await U(s),d=[];A&&(d=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:A.user.id}]}));let c=await(0,he.generateAuthenticationOptions)({rpID:o.rpID,userVerification:"preferred",...d.length?{allowCredentials:d.map(p=>({id:p.id,transports:p.transports?.split(",")}))}:{}}),l={expectedChallenge:c.challenge,userData:{id:A?.user.id||""}},u=L(32);return await s.setSignedCookie(o.advanced.webAuthnChallengeCookie,u,s.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:a}),await s.context.internalAdapter.createVerificationValue({identifier:u,value:JSON.stringify(l),expiresAt:r}),s.json(c,{status:200})}),verifyPasskeyRegistration:K("/passkey/verify-registration",{method:"POST",body:de.z.object({response:de.z.any(),name:de.z.string().optional()}),use:[qe]},async s=>{let A=e?.origin||s.headers?.get("origin")||"";if(!A)return s.json(null,{status:400});let d=s.body.response,c=await s.getSignedCookie(o.advanced.webAuthnChallengeCookie,s.context.secret);if(!c)throw new ie.APIError("BAD_REQUEST",{message:"Challenge not found"});let l=await s.context.internalAdapter.findVerificationValue(c);if(!l)return s.json(null,{status:400});let{expectedChallenge:u,userData:p}=JSON.parse(l.value);if(p.id!==s.context.session.user.id)throw new ie.APIError("UNAUTHORIZED",{message:"You are not authorized to register this passkey"});try{let h=await(0,he.verifyRegistrationResponse)({response:d,expectedChallenge:u,expectedOrigin:A,expectedRPID:e?.rpID}),{verified:k,registrationInfo:f}=h;if(!k||!f)return s.json(null,{status:400});let{credentialID:g,credentialPublicKey:C,counter:T,credentialDeviceType:N,credentialBackedUp:eo}=f,Xt=Buffer.from(C).toString("base64"),Yt={name:s.body.name,userId:p.id,webauthnUserID:s.context.generateId({model:"passkey"}),id:g,publicKey:Xt,counter:T,deviceType:N,transports:d.response.transports.join(","),backedUp:eo,createdAt:new Date},er=await s.context.adapter.create({model:"passkey",data:Yt});return s.json(er,{status:200})}catch(h){throw console.log(h),new ie.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to verify registration"})}}),verifyPasskeyAuthentication:K("/passkey/verify-authentication",{method:"POST",body:de.z.object({response:de.z.any()})},async s=>{let A=e?.origin||s.headers?.get("origin")||"";if(!A)throw new ie.APIError("BAD_REQUEST",{message:"origin missing"});let d=s.body.response,c=await s.getSignedCookie(o.advanced.webAuthnChallengeCookie,s.context.secret);if(!c)throw new ie.APIError("BAD_REQUEST",{message:"Challenge not found"});let l=await s.context.internalAdapter.findVerificationValue(c);if(!l)throw new ie.APIError("BAD_REQUEST",{message:"Challenge not found"});let{expectedChallenge:u}=JSON.parse(l.value),p=await s.context.adapter.findOne({model:"passkey",where:[{field:"id",value:d.id}]});if(!p)throw new ie.APIError("UNAUTHORIZED",{message:"Passkey not found"});try{let h=await(0,he.verifyAuthenticationResponse)({response:d,expectedChallenge:u,expectedOrigin:A,expectedRPID:o.rpID,authenticator:{credentialID:p.id,credentialPublicKey:new Uint8Array(Buffer.from(p.publicKey,"base64")),counter:p.counter,transports:p.transports?.split(",")}}),{verified:k}=h;if(!k)throw new ie.APIError("UNAUTHORIZED",{message:"Authentication failed"});await s.context.adapter.update({model:"passkey",where:[{field:"id",value:p.id}],update:{counter:h.authenticationInfo.newCounter}});let f=await s.context.internalAdapter.createSession(p.userId,s.request);if(!f)throw new ie.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});let g=await s.context.internalAdapter.findUserById(p.userId);if(!g)throw new ie.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 ie.APIError("BAD_REQUEST",{message:"Failed to verify authentication"})}}),listPasskeys:K("/passkey/list-user-passkeys",{method:"GET",use:[v]},async s=>{let A=await s.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:s.context.session.user.id}]});return s.json(A,{status:200})}),deletePasskey:K("/passkey/delete-passkey",{method:"POST",body:de.z.object({id:de.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})))},schema:ee($r,e?.schema)}},$r={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",defaultValue:new Date,required:!1}}}};var Ge=require("zod");var Je=require("better-call");var Ho=()=>({id:"username",endpoints:{signInUsername:K("/sign-in/username",{method:"POST",body:Ge.z.object({username:Ge.z.string(),password:Ge.z.string(),rememberMe:Ge.z.boolean().optional()})},async e=>{let t=await e.context.adapter.findOne({model:"user",where:[{field:"username",value:e.body.username}]});if(!t)throw await e.context.password.hash(e.body.password),e.context.logger.error("User not found",{username:Ho}),new Je.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let i=await e.context.adapter.findOne({model:"account",where:[{field:"userId",value:t.id},{field:"providerId",value:"credential"}]});if(!i)throw new Je.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let o=i?.password;if(!o)throw e.context.logger.error("Password not found",{username:Ho}),new Je.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(o,e.body.password))throw e.context.logger.error("Invalid password"),new Je.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 Vt=require("better-call"),Zr=()=>({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 i="";return t.includes(".")?i=t:i=await(0,Vt.serializeSigned)("",t,e.context.secret),e.request&&e.request.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${i.replace("=","")}`),e.headers&&e.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${i.replace("=","")}`),{context:e}}}]}});var ke=require("zod");var Qo=require("better-call");var Wr=e=>({id:"magic-link",endpoints:{signInMagicLink:K("/sign-in/magic-link",{method:"POST",requireHeaders:!0,body:ke.z.object({email:ke.z.string().email(),callbackURL:ke.z.string().optional()})},async t=>{let{email:i}=t.body;if(e.disableSignUp&&!await t.context.internalAdapter.findUserByEmail(i))throw new Qo.APIError("BAD_REQUEST",{message:"User not found"});let o=Q(32,$("a-z","A-Z"));await t.context.internalAdapter.createVerificationValue({identifier:o,value:i,expiresAt:new Date(Date.now()+(e.expiresIn||60*5)*1e3)});let r=`${t.context.baseURL}/magic-link/verify?token=${o}&callbackURL=${t.body.callbackURL||"/"}`;try{await e.sendMagicLink({email:i,url:r,token:o},t.request)}catch(n){throw t.context.logger.error("Failed to send magic link",n),new Qo.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to send magic link"})}return t.json({status:!0})}),magicLinkVerify:K("/magic-link/verify",{method:"GET",query:ke.z.object({token:ke.z.string(),callbackURL:ke.z.string().optional()}),requireHeaders:!0},async t=>{let{token:i,callbackURL:o}=t.query,r=o?.startsWith("http")?o:o?`${t.context.options.baseURL}${o}`:t.context.options.baseURL,n=await t.context.internalAdapter.findVerificationValue(i);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),A=s?.user.id||"";if(!s){if(e.disableSignUp)throw t.redirect(`${r}?error=USER_NOT_FOUND`);if(A=(await t.context.internalAdapter.createUser({email:a,emailVerified:!0,name:a})).id,!A)throw t.redirect(`${r}?error=USER_NOT_CREATED`)}let d=await t.context.internalAdapter.createSession(A,t.headers);if(!d)throw t.redirect(`${r}?error=SESSION_NOT_CREATED`);if(await m(t,{session:d,user:s?.user}),!o)return t.json({session:d,user:s?.user});throw t.redirect(o)})},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 te=require("zod");var q=require("better-call");function Gr(e){return Q(e,$("0-9"))}var Jr=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:K("/sign-in/phone-number",{method:"POST",body:te.z.object({phoneNumber:te.z.string(),password:te.z.string(),rememberMe:te.z.boolean().optional()})},async i=>{let{password:o,phoneNumber:r}=i.body;if(t.phoneNumberValidator&&!await t.phoneNumberValidator(i.body.phoneNumber))throw new q.APIError("BAD_REQUEST",{message:"Invalid phone number!"});let n=await i.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 i.context.internalAdapter.findAccountByUserId(n.id)).find(l=>l.providerId==="credential");if(!s)throw i.context.logger.error("Credential account not found",{phoneNumber:r}),new q.APIError("UNAUTHORIZED",{message:"Invalid password or password"});let A=s?.password;if(!A)throw i.context.logger.error("Password not found",{phoneNumber:r}),new q.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await i.context.password.verify(A,o))throw i.context.logger.error("Invalid password"),new q.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let c=await i.context.internalAdapter.createSession(n.id,i.headers,i.body.rememberMe===!1);if(!c)throw i.context.logger.error("Failed to create session"),new q.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await m(i,{session:c,user:n},i.body.rememberMe===!1),i.json({user:n,session:c})}),sendPhoneNumberOTP:K("/phone-number/send-otp",{method:"POST",body:te.z.object({phoneNumber:te.z.string()})},async i=>{if(!e?.sendOTP)throw i.context.logger.warn("sendOTP not implemented"),new q.APIError("NOT_IMPLEMENTED",{message:"sendOTP not implemented"});if(t.phoneNumberValidator&&!await t.phoneNumberValidator(i.body.phoneNumber))throw new q.APIError("BAD_REQUEST",{message:"Invalid phone number!"});let o=Gr(t.otpLength);return await i.context.internalAdapter.createVerificationValue({value:o,identifier:i.body.phoneNumber,expiresAt:I(t.expiresIn,"sec")}),await e.sendOTP({phoneNumber:i.body.phoneNumber,code:o},i.request),i.json({code:o},{body:{message:"Code sent"}})}),verifyPhoneNumber:K("/phone-number/verify",{method:"POST",body:te.z.object({phoneNumber:te.z.string(),code:te.z.string(),disableSession:te.z.boolean().optional(),updatePhoneNumber:te.z.boolean().optional()})},async i=>{let o=await i.context.internalAdapter.findVerificationValue(i.body.phoneNumber);if(!o||o.expiresAt<new Date)throw o&&o.expiresAt<new Date?(await i.context.internalAdapter.deleteVerificationValue(o.id),new q.APIError("BAD_REQUEST",{message:"OTP expired"})):new q.APIError("BAD_REQUEST",{message:"OTP not found"});if(o.value!==i.body.code)throw new q.APIError("BAD_REQUEST",{message:"Invalid OTP"});if(await i.context.internalAdapter.deleteVerificationValue(o.id),i.body.updatePhoneNumber){let n=await U(i);if(!n)throw new q.APIError("UNAUTHORIZED",{message:"Session not found"});let a=await i.context.internalAdapter.updateUser(n.user.id,{[t.phoneNumber]:i.body.phoneNumber,[t.phoneNumberVerified]:!0});return i.json({user:a,session:n.session})}let r=await i.context.adapter.findOne({model:"user",where:[{value:i.body.phoneNumber,field:t.phoneNumber}]});if(await e?.callbackOnVerification?.({phoneNumber:i.body.phoneNumber,user:r},i.request),r)r=await i.context.internalAdapter.updateUser(r.id,{[t.phoneNumberVerified]:!0});else if(e?.signUpOnVerification){if(r=await i.context.internalAdapter.createUser({email:e.signUpOnVerification.getTempEmail(i.body.phoneNumber),name:e.signUpOnVerification.getTempName?e.signUpOnVerification.getTempName(i.body.phoneNumber):i.body.phoneNumber,[t.phoneNumber]:i.body.phoneNumber,[t.phoneNumberVerified]:!0}),!r)throw new q.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"})}else return i.json(null);if(!r)throw new q.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to update user"});if(!i.body.disableSession){let n=await i.context.internalAdapter.createSession(r.id,i.request);if(!n)throw new q.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await m(i,{session:n,user:r}),i.json({user:r,session:n})}return i.json({user:r,session:null})})},schema:ee(Xr,e?.schema)}},Xr={user:{fields:{phoneNumber:{type:"string",required:!1,unique:!0,returned:!0},phoneNumberVerified:{type:"boolean",required:!1,returned:!0,input:!1}}}};var Xc=require("zod");var Yr={user:{fields:{isAnonymous:{type:"boolean",required:!1}}}},en=e=>({id:"anonymous",endpoints:{signInAnonymous:K("/sign-in/anonymous",{method:"POST"},async t=>{let{emailDomainName:i=Te(t.context.baseURL)}=e||{},o=t.context.generateId({model:"user"}),r=`temp-${o}@${i}`,n=await t.context.internalAdapter.createUser({id:o,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:R(async t=>{let o=t.responseHeader.get("set-cookie"),r=t.context.authCookies.sessionToken.name,n=no(o||"").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 b.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:ee(Yr,e?.schema)});var y=require("zod");var on=e=>{let t={defaultRole:"user",adminRole:"admin",...e},i=R(async o=>{let r=await U(o);if(!r?.session)throw new b.APIError("UNAUTHORIZED");let n=r.user;if(!n.role||(Array.isArray(t.adminRole)?!t.adminRole.includes(n.role):n.role!==t.adminRole))throw new b.APIError("FORBIDDEN",{message:"Only admins can access this endpoint"});return{session:{user:n,session:r.session}}});return{id:"admin",init(o){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 o.internalAdapter.findUserById(r.userId);if(n.banned){if(n.banExpires&&n.banExpires<Date.now()){await o.internalAdapter.updateUser(r.userId,{banned:!1,banReason:null,banExpires:null});return}return!1}}}}}}}},hooks:{after:[{matcher(o){return o.path==="/list-sessions"},handler:R(async o=>{let r=await Be(o);if(!r)return;let n=r.filter(a=>!a.impersonatedBy);return o.json(n)})}]},endpoints:{setRole:K("/admin/set-role",{method:"POST",body:y.z.object({userId:y.z.string(),role:y.z.string()}),use:[i]},async o=>{let r=await o.context.internalAdapter.updateUser(o.body.userId,{role:o.body.role});return o.json({user:r})}),createUser:K("/admin/create-user",{method:"POST",body:y.z.object({email:y.z.string(),password:y.z.string(),name:y.z.string(),role:y.z.string(),data:y.z.optional(y.z.record(y.z.any()))}),use:[i]},async o=>{if(await o.context.internalAdapter.findUserByEmail(o.body.email))throw new b.APIError("BAD_REQUEST",{message:"User already exists"});let n=await o.context.internalAdapter.createUser({email:o.body.email,name:o.body.name,role:o.body.role,...o.body.data});if(!n)throw new b.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"});let a=await o.context.password.hash(o.body.password);return await o.context.internalAdapter.linkAccount({accountId:n.id,providerId:"credential",password:a,userId:n.id}),o.json({user:n})}),listUsers:K("/admin/list-users",{method:"GET",use:[i],query:y.z.object({searchValue:y.z.string().optional(),searchField:y.z.enum(["email","name"]).optional(),searchOperator:y.z.enum(["contains","starts_with","ends_with"]).optional(),limit:y.z.string().or(y.z.number()).optional(),offset:y.z.string().or(y.z.number()).optional(),sortBy:y.z.string().optional(),sortDirection:y.z.enum(["asc","desc"]).optional(),filterField:y.z.string().optional(),filterValue:y.z.string().or(y.z.number()).or(y.z.boolean()).optional(),filterOperator:y.z.enum(["eq","ne","lt","lte","gt","gte"]).optional()})},async o=>{let r=[];o.query?.searchValue&&r.push({field:o.query.searchField||"email",operator:o.query.searchOperator||"contains",value:o.query.searchValue}),o.query?.filterValue&&r.push({field:o.query.filterField||"email",operator:o.query.filterOperator||"eq",value:o.query.filterValue});try{let n=await o.context.internalAdapter.listUsers(Number(o.query?.limit)||void 0,Number(o.query?.offset)||void 0,o.query?.sortBy?{field:o.query.sortBy,direction:o.query.sortDirection||"asc"}:void 0,r.length?r:void 0);return o.json({users:n})}catch(n){return console.log(n),o.json({users:[]})}}),listUserSessions:K("/admin/list-user-sessions",{method:"POST",use:[i],body:y.z.object({userId:y.z.string()})},async o=>({sessions:await o.context.internalAdapter.listSessions(o.body.userId)})),unbanUser:K("/admin/unban-user",{method:"POST",body:y.z.object({userId:y.z.string()}),use:[i]},async o=>{let r=await o.context.internalAdapter.updateUser(o.body.userId,{banned:!1});return o.json({user:r})}),banUser:K("/admin/ban-user",{method:"POST",body:y.z.object({userId:y.z.string(),banReason:y.z.string().optional(),banExpiresIn:y.z.number().optional()}),use:[i]},async o=>{if(o.body.userId===o.context.session.user.id)throw new b.APIError("BAD_REQUEST",{message:"You cannot ban yourself"});let r=await o.context.internalAdapter.updateUser(o.body.userId,{banned:!0,banReason:o.body.banReason||e?.defaultBanReason||"No reason",banExpires:o.body.banExpiresIn?I(o.body.banExpiresIn,"sec"):e?.defaultBanExpiresIn?I(e.defaultBanExpiresIn,"sec"):void 0});return await o.context.internalAdapter.deleteSessions(o.body.userId),o.json({user:r})}),impersonateUser:K("/admin/impersonate-user",{method:"POST",body:y.z.object({userId:y.z.string()}),use:[i]},async o=>{let r=await o.context.internalAdapter.findUserById(o.body.userId);if(!r)throw new b.APIError("NOT_FOUND",{message:"User not found"});let n=await o.context.internalAdapter.createSession(r.id,void 0,!0,{impersonatedBy:o.context.session.user.id,expiresAt:e?.impersonationSessionDuration?I(e.impersonationSessionDuration,"sec"):I(60*60,"sec")});if(!n)throw new b.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await m(o,{session:n,user:r},!0),o.json({session:n,user:r})}),revokeUserSession:K("/admin/revoke-user-session",{method:"POST",body:y.z.object({sessionToken:y.z.string()}),use:[i]},async o=>(await o.context.internalAdapter.deleteSession(o.body.sessionToken),o.json({success:!0}))),revokeUserSessions:K("/admin/revoke-user-sessions",{method:"POST",body:y.z.object({userId:y.z.string()}),use:[i]},async o=>(await o.context.internalAdapter.deleteSessions(o.body.userId),o.json({success:!0}))),removeUser:K("/admin/remove-user",{method:"POST",body:y.z.object({userId:y.z.string()}),use:[i]},async o=>(await o.context.internalAdapter.deleteUser(o.body.userId),o.json({success:!0})))},schema:ee(tn,t.schema)}},tn={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 ne=require("zod"),Ne=require("better-call");var ho=require("@better-fetch/fetch");var qt=require("oslo/jwt");async function rn(e,t,i){if(t==="oidc"&&e.idToken){let r=(0,qt.parseJWT)(e.idToken);if(r?.payload)return r.payload}if(!i)return null;let o=await(0,ho.betterFetch)(i,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});return{id:o.data?.sub,emailVerified:o.data?.email_verified,email:o.data?.email,...o.data}}var nn=e=>({id:"generic-oauth",endpoints:{signInWithOAuth2:K("/sign-in/oauth2",{method:"POST",query:ne.z.object({currentURL:ne.z.string().optional()}).optional(),body:ne.z.object({providerId:ne.z.string(),callbackURL:ne.z.string().optional(),errorCallbackURL:ne.z.string().optional()})},async t=>{let{providerId:i}=t.body,o=e.config.find(N=>N.providerId===i);if(!o)throw new Ne.APIError("BAD_REQUEST",{message:`No config found for provider ${i}`});let{discoveryUrl:r,authorizationUrl:n,tokenUrl:a,clientId:s,clientSecret:A,scopes:d,redirectURI:c,responseType:l,pkce:u,prompt:p,accessType:h}=o,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 Ne.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let{state:g,codeVerifier:C}=await Oe(t),T=await P({id:i,options:{clientId:s,clientSecret:A,redirectURI:c},authorizationEndpoint:k,state:g,codeVerifier:u?C:void 0,scopes:d||[],redirectURI:`${t.context.baseURL}/oauth2/callback/${i}`});return l&&l!=="code"&&T.searchParams.set("response_type",l),p&&T.searchParams.set("prompt",p),h&&T.searchParams.set("access_type",h),t.json({url:T.toString(),redirect:!0})}),oAuth2Callback:K("/oauth2/callback/:providerId",{method:"GET",query:ne.z.object({code:ne.z.string().optional(),error:ne.z.string().optional(),state:ne.z.string()})},async t=>{if(t.query.error||!t.query.code)throw t.redirect(`${t.context.baseURL}?error=${t.query.error||"oAuth_code_missing"}`);let i=e.config.find(g=>g.providerId===t.params.providerId);if(!i)throw new Ne.APIError("BAD_REQUEST",{message:`No config found for provider ${t.params.providerId}`});let o,r=await ao(t),{callbackURL:n,codeVerifier:a,errorURL:s}=r,A=t.query.code,d=i.tokenUrl,c=i.userInfoUrl;if(i.discoveryUrl){let g=await(0,ho.betterFetch)(i.discoveryUrl,{method:"GET"});g.data&&(d=g.data.token_endpoint,c=g.data.userinfo_endpoint)}try{if(!d)throw new Ne.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});o=await O({code:A,codeVerifier:a,redirectURI:`${t.context.baseURL}/oauth2/callback/${i.providerId}`,options:{clientId:i.clientId,clientSecret:i.clientSecret},tokenEndpoint:d})}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(!o)throw new Ne.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let l=i.getUserInfo?await i.getUserInfo(o):await rn(o,i.type||"oauth2",c);if(!l?.email)throw t.context.logger.error("Unable to get user info",l),t.redirect(`${t.context.baseURL}/error?error=email_is_missing`);let u=await Ue(t,{userInfo:l,account:{providerId:i.providerId,accountId:l.id,accessToken:o.accessToken}});function p(g){throw t.redirect(`${s||n||`${t.context.baseURL}/error`}?error=${g}`)}if(u.error)return p(u.error.split(" ").join("_"));let{session:h,user:k}=u.data;await m(t,{session:h,user:k});let f;try{f=new URL(n).toString()}catch{f=n}throw t.redirect(f)})}});var _e=require("zod"),Mt={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0}}}},yu=_e.z.object({id:_e.z.string(),publicKey:_e.z.string(),privateKey:_e.z.string(),createdAt:_e.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 pe=require("jose");var sn=e=>({id:"jwt",endpoints:{getJwks:K("/jwks",{method:"GET"},async t=>{let o=await $o(t.context.adapter).getAllKeys();return t.json({keys:o.map(r=>({...JSON.parse(r.publicKey),kid:r.id}))})}),getToken:K("/token",{method:"GET",requireHeaders:!0,use:[v]},async t=>{let i=$o(t.context.adapter),o=await i.getLatestKey(),r=!e?.jwks?.disablePrivateKeyEncryption;if(o===void 0){let{publicKey:d,privateKey:c}=await(0,pe.generateKeyPair)(e?.jwks?.keyPairConfig?.alg??"EdDSA",e?.jwks?.keyPairConfig??{crv:"Ed25519"}),l=await(0,pe.exportJWK)(d),u=await(0,pe.exportJWK)(c),p=JSON.stringify(u),h={id:crypto.randomUUID(),publicKey:JSON.stringify(l),privateKey:r?JSON.stringify(await le({key:t.context.options.secret,data:p})):p,createdAt:new Date};o=await i.createJwk(h)}let n=r?await fe({key:t.context.options.secret,data:JSON.parse(o.privateKey)}):o.privateKey,a=await(0,pe.importJWK)(JSON.parse(n)),s=e?.jwt?.definePayload?await e?.jwt.definePayload(t.context.session.user):t.context.session.user,A=await new pe.SignJWT({...s,...t.context.session.session.impersonatedBy?{impersonatedBy:t.context.session.session.impersonatedBy}:{}}).setProtectedHeader({alg:e?.jwks?.keyPairConfig?.alg??"EdDSA",kid:o.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:A})})},schema:ee(Mt,e?.schema)});var Xe=require("zod");var an=e=>{let t={maximumSessions:5,...e},i=o=>o.includes("_multi-");return{id:"multi-session",endpoints:{listDeviceSessions:K("/multi-session/list-device-sessions",{method:"GET",requireHeaders:!0},async o=>{let r=o.headers?.get("cookie");if(!r)return o.json([]);let n=Object.fromEntries(Ve(r)),a=(await Promise.all(Object.entries(n).filter(([d])=>i(d)).map(async([d])=>await o.getSignedCookie(d,o.context.secret)))).filter(d=>d!==void 0);if(!a.length)return o.json([]);let A=(await o.context.internalAdapter.findSessions(a)).filter(d=>d&&d.session.expiresAt>new Date);return o.json(A)}),setActiveSession:K("/multi-session/set-active",{method:"POST",body:Xe.z.object({sessionToken:Xe.z.string()}),requireHeaders:!0,use:[v]},async o=>{let r=o.body.sessionToken,n=`${o.context.authCookies.sessionToken.name}_multi-${r}`;if(!await o.getSignedCookie(n,o.context.secret))throw new b.APIError("UNAUTHORIZED",{message:"Invalid session token"});let s=await o.context.internalAdapter.findSession(r);if(!s||s.session.expiresAt<new Date)throw o.setCookie(n,"",{...o.context.authCookies.sessionToken.options,maxAge:0}),new b.APIError("UNAUTHORIZED",{message:"Invalid session token"});return await m(o,s),o.json(s)}),revokeDeviceSession:K("/multi-session/revoke",{method:"POST",body:Xe.z.object({sessionToken:Xe.z.string()}),requireHeaders:!0,use:[v]},async o=>{let r=o.body.sessionToken,n=`${o.context.authCookies.sessionToken.name}_multi-${r}`;if(!await o.getSignedCookie(n,o.context.secret))throw new b.APIError("UNAUTHORIZED",{message:"Invalid session token"});if(await o.context.internalAdapter.deleteSession(r),o.setCookie(n,"",{...o.context.authCookies.sessionToken.options,maxAge:0}),!(o.context.session?.session.token===r))return o.json({success:!0});let A=o.headers?.get("cookie");if(A){let d=Object.fromEntries(Ve(A)),c=(await Promise.all(Object.entries(d).filter(([u])=>i(u)).map(async([u])=>await o.getSignedCookie(u,o.context.secret)))).filter(u=>u!==void 0),l=o.context.internalAdapter;if(c.length>0){let p=(await l.findSessions(c)).filter(h=>h&&h.session.expiresAt>new Date);if(p.length>0){let h=p[0];await m(o,h)}else M(o)}else M(o)}else M(o);return o.json({success:!0})})},hooks:{after:[{matcher:()=>!0,handler:R(async o=>{let r=o.responseHeader.get("set-cookie");if(!r)return;let n=no(r),a=o.context.authCookies.sessionToken,s=n.get(a.name)?.value;if(!s)return;let A=Ve(o.headers?.get("cookie")||""),d=s.split(".")[0];if(!d)return;let c=`${a.name}_multi-${d}`;n.get(c)||A.get(c)||Object.keys(Object.fromEntries(A)).filter(i).length+(r.includes("session_token")?1:0)>t.maximumSessions||await o.setSignedCookie(c,d,o.context.secret,a.options)})},{matcher:o=>o.path==="/sign-out",handler:R(async o=>{let r=o.headers?.get("cookie");if(!r)return;let n=Object.fromEntries(Ve(r)),a=Object.keys(n).map(s=>i(s)?(o.setCookie(s,"",{maxAge:0}),s.split("_multi-")[1]):null).filter(s=>s!==null);await o.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:K("/email-otp/send-verification-otp",{method:"POST",body:D.z.object({email:D.z.string(),type:D.z.enum(Zo)})},async i=>{if(!e?.sendVerificationOTP)throw i.context.logger.error("send email verification is not implemented"),new b.APIError("BAD_REQUEST",{message:"send email verification is not implemented"});let o=i.body.email,r=Q(t.otpLength,$("0-9"));return await i.context.internalAdapter.createVerificationValue({value:r,identifier:`${i.body.type}-otp-${o}`,expiresAt:I(t.expireIn,"sec")}).catch(async n=>{await i.context.internalAdapter.deleteVerificationByIdentifier(`${i.body.type}-otp-${o}`),await i.context.internalAdapter.createVerificationValue({value:r,identifier:`${i.body.type}-otp-${o}`,expiresAt:I(t.expireIn,"sec")})}),await e.sendVerificationOTP({email:o,otp:r,type:i.body.type},i.request),i.json({success:!0})}),createVerificationOTP:K("/email-otp/create-verification-otp",{method:"POST",body:D.z.object({email:D.z.string(),type:D.z.enum(Zo)}),metadata:{SERVER_ONLY:!0}},async i=>{let o=i.body.email,r=Q(t.otpLength,$("0-9"));return await i.context.internalAdapter.createVerificationValue({value:r,identifier:`${i.body.type}-otp-${o}`,expiresAt:I(t.expireIn,"sec")}),r}),getVerificationOTP:K("/email-otp/get-verification-otp",{method:"GET",query:D.z.object({email:D.z.string(),type:D.z.enum(Zo)}),metadata:{SERVER_ONLY:!0}},async i=>{let o=i.query.email,r=await i.context.internalAdapter.findVerificationValue(`${i.query.type}-otp-${o}`);return!r||r.expiresAt<new Date?i.json({otp:null}):i.json({otp:r.value})}),verifyEmailOTP:K("/email-otp/verify-email",{method:"POST",body:D.z.object({email:D.z.string(),otp:D.z.string()})},async i=>{let o=i.body.email,r=await i.context.internalAdapter.findVerificationValue(`email-verification-otp-${o}`);if(!r||r.expiresAt<new Date)throw r&&await i.context.internalAdapter.deleteVerificationValue(r.id),new b.APIError("BAD_REQUEST",{message:"Invalid OTP"});let n=i.body.otp;if(r.value!==n)throw new b.APIError("BAD_REQUEST",{message:"Invalid OTP"});await i.context.internalAdapter.deleteVerificationValue(r.id);let a=await i.context.internalAdapter.findUserByEmail(o);if(!a)throw new b.APIError("BAD_REQUEST",{message:"User not found"});let s=await i.context.internalAdapter.updateUser(a.user.id,{email:o,emailVerified:!0});return i.json({user:s})}),signInEmailOTP:K("/sign-in/email-otp",{method:"POST",body:D.z.object({email:D.z.string(),otp:D.z.string()})},async i=>{let o=i.body.email,r=await i.context.internalAdapter.findVerificationValue(`sign-in-otp-${o}`);if(!r||r.expiresAt<new Date)throw r&&await i.context.internalAdapter.deleteVerificationValue(r.id),new b.APIError("BAD_REQUEST",{message:"Invalid OTP"});let n=i.body.otp;if(r.value!==n)throw new b.APIError("BAD_REQUEST",{message:"Invalid OTP"});await i.context.internalAdapter.deleteVerificationValue(r.id);let a=await i.context.internalAdapter.findUserByEmail(o);if(!a){if(t.disableSignUp)throw new b.APIError("BAD_REQUEST",{message:"User not found"});let A=await i.context.internalAdapter.createUser({email:o,emailVerified:!0,name:o}),d=await i.context.internalAdapter.createSession(A.id,i.request);return await m(i,{session:d,user:A}),i.json({user:A,session:d})}a.user.emailVerified||await i.context.internalAdapter.updateUser(a.user.id,{emailVerified:!0});let s=await i.context.internalAdapter.createSession(a.user.id,i.request);return await m(i,{session:s,user:a.user}),i.json({session:s,user:a})}),forgetEmailOTP:K("/forget-password/email-otp",{method:"POST",body:D.z.object({email:D.z.string()})},async i=>{let o=i.body.email;if(!await i.context.internalAdapter.findUserByEmail(o))throw new b.APIError("BAD_REQUEST",{message:"User not found"});let n=Q(t.otpLength,$("0-9"));return await i.context.internalAdapter.createVerificationValue({value:n,identifier:`forget-password-otp-${o}`,expiresAt:I(t.expireIn,"sec")}),await e.sendVerificationOTP({email:o,otp:n,type:"forget-password"},i.request),i.json({success:!0})}),resetPasswordEmailOTP:K("/email-otp/reset-password",{method:"POST",body:D.z.object({email:D.z.string(),otp:D.z.string(),password:D.z.string()})},async i=>{let o=i.body.email,r=await i.context.internalAdapter.findUserByEmail(o);if(!r)throw new b.APIError("BAD_REQUEST",{message:"User not found"});let n=await i.context.internalAdapter.findVerificationValue(`forget-password-otp-${o}`);if(!n||n.expiresAt<new Date)throw n&&await i.context.internalAdapter.deleteVerificationValue(n.id),new b.APIError("BAD_REQUEST",{message:"Invalid OTP"});let a=i.body.otp;if(n.value!==a)throw new b.APIError("BAD_REQUEST",{message:"Invalid OTP"});await i.context.internalAdapter.deleteVerificationValue(n.id);let s=await i.context.password.hash(i.body.password);return await i.context.internalAdapter.updatePassword(r.user.id,s),i.json({success:!0})})},hooks:{after:[{matcher(i){return!!(i.path?.startsWith("/sign-up")&&t.sendVerificationOnSignUp)},async handler(i){let o=await Be(i);if(o&&o.user.email&&o.user.emailVerified===!1){let r=Q(t.otpLength,$("0-9"));await i.context.internalAdapter.createVerificationValue({value:r,identifier:`email-verification-otp-${o.user.email}`,expiresAt:I(t.expireIn,"sec")}),await e.sendVerificationOTP({email:o.user.email,otp:r,type:"email-verification"},i.request)}}}]}}};var Wo=require("zod");var Qt=require("@better-fetch/fetch");function Ht(e){return e==="true"||e===!0}var dn=e=>({id:"one-tap",endpoints:{oneTapCallback:K("/one-tap/callback",{method:"POST",body:Wo.z.object({idToken:Wo.z.string()})},async t=>{let{idToken:i}=t.body,{data:o,error:r}=await(0,Qt.betterFetch)("https://oauth2.googleapis.com/tokeninfo?id_token="+i);if(r)return t.json({error:"Invalid token"});let n=await t.context.internalAdapter.findUserByEmail(o.email);if(!n){if(e?.disableSignup)throw new b.APIError("BAD_GATEWAY",{message:"User not found"});let s=await t.context.internalAdapter.createOAuthUser({email:o.email,emailVerified:Ht(o.email_verified),name:o.name,image:o.picture},{providerId:"google",accountId:o.sub});if(!s)throw new b.APIError("INTERNAL_SERVER_ERROR",{message:"Could not create user"});let A=await t.context.internalAdapter.createSession(s?.user.id,t.request);return await m(t,{user:s.user,session:A}),t.json({session:A,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=re.VERCEL_URL,t=re.NETLIFY_URL,i=re.RENDER_URL,o=re.AWS_LAMBDA_FUNCTION_NAME,r=re.GOOGLE_CLOUD_FUNCTION_NAME,n=re.AZURE_FUNCTION_NAME;return e||t||i||o||r||n}var cn=e=>({id:"oauth-proxy",endpoints:{oAuthProxy:K("/oauth-proxy-callback",{method:"GET",query:yo.z.object({callbackURL:yo.z.string(),cookies:yo.z.string()})},async t=>{let i=t.query.cookies,o=await fe({key:t.context.secret,data:i});throw t.setHeader("set-cookie",o),t.redirect(t.query.callbackURL)})},hooks:{after:[{matcher(t){return t.path?.startsWith("/callback")},handler:R(async t=>{let i=t.context.returned,o=i instanceof b.APIError?i.headers:null,r=o?.get("location");if(r?.includes("/oauth-proxy-callback?callbackURL")){if(!r.startsWith("http"))return;let n=new URL(r);if(n.origin===Te(t.context.baseURL)){let c=n.searchParams.get("callbackURL");if(!c)return;t.setHeader("location",c);return}let s=o?.get("set-cookie");if(!s)return;let A=await le({key:t.context.secret,data:s}),d=`${r}&cookies=${encodeURIComponent(A)}`;t.setHeader("location",d)}})}],before:[{matcher(t){return t.path?.startsWith("/sign-in/social")},async handler(t){let i=new URL(e?.currentURL||t.request?.url||Kn()||t.context.baseURL);return t.body.callbackURL=`${i.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:K("/get-session",{method:"GET",metadata:{CUSTOM_SESSION:!0}},async i=>{let o=await U(i);if(!o)return i.json(null);let r=await e(o);return i.json(r)})}});var Ke=require("zod");var Le=e=>{let t=e.plugins?.reduce((A,d)=>{let c=d.schema;if(!c)return A;for(let[l,u]of Object.entries(c))A[l]={fields:{...A[l]?.fields,...u.fields},modelName:u.modelName||l};return A},{}),i=e.rateLimit?.storage==="database",o={rateLimit:{modelName:e.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",fieldName:e.rateLimit?.fields?.key||"key"},count:{type:"number",fieldName:e.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",fieldName:e.rateLimit?.fields?.lastRequest||"lastRequest"}}}},{user:r,session:n,account: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,...i?o:{}}};var ln=require("zod");var $t=require("kysely"),Go=require("kysely");var Ye={};function Wt(e){switch(e.constructor.name){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array";default:return"string"}}function wo(e){let t=[];return e.metadata?.openapi?.parameters?(t.push(...e.metadata.openapi.parameters),t):(e.query instanceof Ke.ZodObject&&Object.entries(e.query.shape).forEach(([i,o])=>{o instanceof Ke.ZodSchema&&t.push({name:i,in:"query",schema:{type:Wt(o),..."minLength"in o&&o.minLength?{minLength:o.minLength}:{},description:o.description}})}),t)}function Zt(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof Ke.ZodObject||e.body instanceof Ke.ZodOptional)){let t=e.body.shape;if(!t)return;let i={},o=[];return Object.entries(t).forEach(([r,n])=>{n instanceof Ke.ZodSchema&&(i[r]={type:Wt(n),description:n.description},n instanceof Ke.ZodOptional||o.push(r))}),{required:e.body instanceof Ke.ZodOptional?!1:!!e.body,content:{"application/json":{schema:{type:"object",properties:i,required:o}}}}}}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 Gt(e,t){let i=Eo(e,{...t,plugins:[]}),o=Le(t),n={schemas:{...Object.entries(o).reduce((s,[A,d])=>{let c=A.charAt(0).toUpperCase()+A.slice(1);return s[c]={type:"object",properties:Object.entries(d.fields).reduce((l,[u,p])=>(l[u]={type:p.type},l),{})},s},{})}};Object.entries(i.api).forEach(([s,A])=>{let d=A.options;if(!d.metadata?.SERVER_ONLY&&(d.method==="GET"&&(Ye[A.path]={get:{tags:["Default",...d.metadata?.openapi?.tags||[]],description:d.metadata?.openapi?.description,operationId:d.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(d),responses:Co(d.metadata?.openapi?.responses)}}),d.method==="POST")){let c=Zt(d);Ye[A.path]={post:{tags:["Default",...d.metadata?.openapi?.tags||[]],description:d.metadata?.openapi?.description,operationId:d.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(d),...c?{requestBody:c}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:Co(d.metadata?.openapi?.responses)}}}});for(let s of t.plugins||[]){if(s.id==="open-api")continue;let A=Eo(e,{...t,plugins:[s]}),d=Object.keys(A.api).map(c=>i.api[c]===void 0?A.api[c]:null).filter(c=>c!==null);Object.entries(d).forEach(([c,l])=>{let u=l.options;u.metadata?.SERVER_ONLY||(u.method==="GET"&&(Ye[l.path]={get:{tags:u.metadata?.openapi?.tags||[s.id.charAt(0).toUpperCase()+s.id.slice(1)],description:u.metadata?.openapi?.description,operationId:u.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(u),responses:Co(u.metadata?.openapi?.responses)}}),u.method==="POST"&&(Ye[l.path]={post:{tags:u.metadata?.openapi?.tags||[s.id.charAt(0).toUpperCase()+s.id.slice(1)],description:u.metadata?.openapi?.description,operationId:u.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:wo(u),requestBody:Zt(u),responses:Co(u.metadata?.openapi?.responses)}}))})}return{openapi:"3.1.1",info:{title:"Better Auth",description:"API Reference for your Better Auth Instance"},components:n,security:[{apiKeyCookie:[]}],servers:[{url:e.baseURL}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:Ye}}var Jt=`<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>`,Zi=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(vr(t),{headers:{"Content-Type":"text/html"}})});var C=require("better-call");function Eo(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:Ji,getSession:Uo(),signOut:Xi,signUpEmail:$i(),signInEmail:Wi,forgetPassword:Yi,resetPassword:ot,verifyEmail:Mi,sendVerificationEmail:qi,changeEmail:st,changePassword:tt,setPassword:rt,updateUser:it(),deleteUser:nt,forgetPasswordCallback:et,listSessions:Ni(),revokeSession:Li,revokeSessions:_i,revokeOtherSessions:Fi,linkSocialAccount:dt,listUserAccounts:at},...o,ok:Qi,error:Zi},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}}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 W.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)await e.context.internalAdapter.updateAccount(s.id,{accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt});else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(o.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return oi&&W.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 W.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 pe(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 W.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(Ao,{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 Oe(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})}),Wi=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(a,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 pe(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()}),Ji=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 ao(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 wd=require("zod");var At=require("better-call"),Xi=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 J=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:J.z.object({email:J.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:J.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=I(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||r,"sec"),a=_(24);await e.context.internalAdapter.createVerificationValue({value:i.user.id,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})}),et=c("/reset-password/:token",{method:"GET",query:J.z.object({callbackURL:J.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}))}),ot=c("/reset-password",{query:J.z.optional(J.z.object({token:J.z.string().optional(),currentURL:J.z.string().optional()})),method:"POST",body:J.z.object({newPassword:J.z.string({description:"The new password to set"}),token:J.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 Z=require("better-call");var it=()=>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 Z.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=Ko(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})}),tt=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 Z.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 Z.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 Z.APIError("BAD_REQUEST",{message:"User does not have a password"});let A=await e.context.password.hash(t);if(!await e.context.password.verify(d.password,o))throw new Z.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 Z.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await m(e,{session:u,user:r.user})}return e.json(r.user)}),rt=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 Z.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 Z.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 Z.APIError("BAD_REQUEST",{message:"user already has a password"})}),nt=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),M(e),e.json(null)}),st=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 Z.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 Z.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 Z.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 Z.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let o=await pe(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 at=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})))}),dt=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(Ao,{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 Oe(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),Rr=Do.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),Ur=Do.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),Pr=Do.newRole({organization:[],member:[],invitation:[]}),pt={admin:Rr,owner:Ur,member:Pr};var B=(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}),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 i=>{let[r,n,a]=await Promise.all([o.findOne({model:"organization",where:[{field:"id",value:i}]}),o.findMany({model:"invitation",where:[{field:"organizationId",value:i}]}),o.findMany({model:"member",where:[{field:"organizationId",value:i}]})]);if(!r)return null;let s=a.map(u=>u.userId),d=await o.findMany({model:"user",where:[{field:"id",value:s,operator:"in"}]}),A=new Map(d.map(u=>[u.id,u])),K=a.map(u=>{let p=A.get(u.userId);if(!p)throw new X("Unexpected error: User not found for member");return{...u,user:{id:p.id,name:p.name,email:p.email,image:p.image}}});return{...r,invitations:n,members:K}},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=I(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 pA=require("better-call");var z=R(async e=>({})),V=R({use:[v]},async e=>({session:e.context.session}));var G=require("zod");var P=require("zod");var ut=P.z.string(),Er=P.z.enum(["pending","accepted","rejected","canceled"]).default("pending"),hA=P.z.object({id:P.z.string().default(_),name:P.z.string(),slug:P.z.string(),logo:P.z.string().nullish(),metadata:P.z.record(P.z.string()).or(P.z.string().transform(e=>JSON.parse(e))).nullish(),createdAt:P.z.date()}),yA=P.z.object({id:P.z.string().default(_),organizationId:P.z.string(),userId:P.z.string(),role:ut,createdAt:P.z.date()}),wA=P.z.object({id:P.z.string().default(_),organizationId:P.z.string(),email:P.z.string(),role:ut,status:Er,inviterId:P.z.string(),expiresAt:P.z.date()});var j=require("better-call"),lt=e=>c("/organization/invite-member",{method:"POST",use:[z,V],body:G.z.object({email:G.z.string({description:"The email address of the user to invite"}),role:G.z.string({description:"The role to assign to the user"}),organizationId:G.z.string({description:"The organization ID to invite the user to"}).optional(),resend:G.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=B(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:G.z.object({invitationId:G.z.string({description:"The ID of the invitation to accept"})}),use:[z,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=B(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:G.z.object({invitationId:G.z.string({description:"The ID of the invitation to reject"})}),use:[z,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=B(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:G.z.object({invitationId:G.z.string({description:"The ID of the invitation to cancel"})}),use:[z,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=B(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:[z],requireHeaders:!0,query:G.z.object({id:G.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=B(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 oe=require("zod");var ge=require("better-call");var yt=()=>c("/organization/add-member",{method:"POST",body:oe.z.object({userId:oe.z.string(),role:oe.z.string(),organizationId:oe.z.string().optional()}),use:[z],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=B(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:oe.z.object({memberIdOrEmail:oe.z.string({description:"The ID or email of the member to remove"}),organizationId:oe.z.string({description:"The ID of the organization to remove the member from. If not provided, the active organization will be used"}).optional()}),use:[z,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=B(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:oe.z.object({role:oe.z.string(),memberId:oe.z.string(),organizationId:oe.z.string().optional()}),use:[z,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=B(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:[z,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 B(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 S=require("zod");var me=require("better-call");var vt=c("/organization/create",{method:"POST",body:S.z.object({name:S.z.string({description:"The name of the organization"}),slug:S.z.string({description:"The slug of the organization"}),userId:S.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:S.z.string({description:"The logo of the organization"}).optional(),metadata:S.z.record(S.z.string(),S.z.any(),{description:"The metadata of the organization"}).optional()}),use:[z,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=B(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:S.z.object({data:S.z.object({name:S.z.string({description:"The name of the organization"}).optional(),slug:S.z.string({description:"The slug of the organization"}).optional(),logo:S.z.string({description:"The logo of the organization"}).optional()}).partial(),organizationId:S.z.string().optional()}),requireHeaders:!0,use:[z],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=B(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:S.z.object({organizationId:S.z.string({description:"The organization id to delete"})}),requireHeaders:!0,use:[z],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=B(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:S.z.optional(S.z.object({organizationId:S.z.string({description:"The organization id to get"}).optional()})),requireHeaders:!0,use:[z,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?.organizationId||t.session.activeOrganizationId;if(!o)return e.json(null,{status:200});let r=await B(e.context,e.context.orgOptions).findFullOrganization(o);if(!r)throw new me.APIError("BAD_REQUEST",{message:"Organization not found"});return e.json(r)}),It=c("/organization/set-active",{method:"POST",body:S.z.object({organizationId:S.z.string({description:"The organization id to set as active. Can be null to unset the active organization"}).nullable().optional()}),use:[V,z],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=B(e.context,e.context.orgOptions),o=e.context.session,i=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}if(!await t.findMemberByOrgId({userId:o.user.id,organizationId:i}))throw await t.setActiveOrganization(o.session.token,null),new me.APIError("FORBIDDEN",{message:"You are not a member of this organization"});let n=await t.setActiveOrganization(o.session.token,i);await m(e,{session:n,user:o.user});let a=await t.findFullOrganization(i);return e.json(a)}),Rt=c("/organization/list",{method:"GET",use:[z,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 B(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(o)});var Sr=lo({name:["action"]}),GA=Sr.newRole({name:["action"]}),Dr=e=>{let t={createOrganization:vt,updateOrganization:kt,deleteOrganization:Tt,setActiveOrganization:It,getFullOrganization:Ot,listOrganizations:Rt,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 B(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=ei(require("uncrypto"),1);function xr(e){return e.toString(2).padStart(8,"0")}function jr(e){return[...e].map(t=>xr(t)).join("")}function Ut(e){return parseInt(jr(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=Ut(i);for(;r>=e;)jo.default.getRandomValues(i),o!==0&&(i[0]&=(1<<o)-1),r=Ut(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 zo=require("@noble/ciphers/chacha"),xe=require("@noble/ciphers/utils"),No=require("@noble/ciphers/webcrypto"),Lo=require("oslo/crypto"),Bo=ei(require("uncrypto"),1);var Pt=require("oslo/encoding");var zr=require("@noble/hashes/scrypt"),Nr=require("uncrypto");async function Qe(e,t){let o=new TextEncoder,i={name:"HMAC",hash:"SHA-256"},r=await Bo.default.subtle.importKey("raw",o.encode(e),i,!1,["sign","verify"]),n=await Bo.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)(zo.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)(zo.xchacha20poly1305)(new Uint8Array(o));return new TextDecoder().decode(r.decrypt(i))};var de=require("zod");var je=require("better-call");var go="two_factor";var mo="trust_device";var _o=require("zod");var be=R({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 Be=require("better-call");function Lr(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():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=de.z.array(de.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:de.z.object({code:de.z.string(),disableSession:de.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 Be.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 Be.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:de.z.object({password:de.z.string()}),use:[v]},async o=>{let i=o.context.session.user;if(!i.twoFactorEnabled)throw new Be.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:de.z.object({userId:de.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 Be.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let r=await Et(i.backupCodes,o.context.secret);if(!r)throw new Be.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"),Bt=require("oslo"),Ge=require("oslo/otp"),Ze=require("zod");var zt=(e,t)=>{let o={...e,digits:6,period:new Bt.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(r,t.password)}var Mo=require("better-call"),_t=require("oslo/otp"),Ft=require("oslo");var Nt=require("better-call"),ze=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 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=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:R(async n=>{let a=await ze(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:ee(Lt,e?.schema),rateLimit:[{pathMatcher(n){return n.startsWith("/two-factor/")},window:10,max:3}]}};var he=require("@simplewebauthn/server"),ie=require("better-call");var Ae=require("zod");var Ne=require("@simplewebauthn/browser");var Hr=require("@better-fetch/fetch");var aK=require("nanostores");var Gc=require("@better-fetch/fetch");var Mr=require("nanostores");var Jc=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:{}}),Qr=()=>{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"},signal:"_listPasskeys"}]}};var $r=e=>{let t=re.BETTER_AUTH_URL,o=e?.rpID||t?.replace("http://","").replace("https://","").split(":")[0]||"localhost";if(!o)throw new X("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(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:Ae.z.object({email:Ae.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:Ae.z.object({response:Ae.z.any({description:"The response from the authenticator"}),name:Ae.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 ie.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 ie.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 ie.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to verify registration"})}}),verifyPasskeyAuthentication:c("/passkey/verify-authentication",{method:"POST",body:Ae.z.object({response:Ae.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 ie.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 ie.APIError("BAD_REQUEST",{message:"Challenge not found"});let u=await s.context.internalAdapter.findVerificationValue(K);if(!u)throw new ie.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 ie.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(",")}}),{verified:k}=h;if(!k)throw new ie.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 ie.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});let g=await s.context.internalAdapter.findUserById(l.userId);if(!g)throw new ie.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 ie.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:Ae.z.object({id:Ae.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})))},schema:ee(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",defaultValue:new 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}]});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 Po(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(i,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"),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,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 $o=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 $o.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||"/"}`;try{await e.sendMagicLink({email:o,url:r,token:i},t.request)}catch(n){throw t.context.logger.error("Failed to send magic link",n),new $o.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to send magic link"})}return 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 te=require("zod");var q=require("better-call");function Jr(e){return Q(e,$("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:te.z.object({phoneNumber:te.z.string({description:"Phone number to sign in"}),password:te.z.string({description:"Password to use for sign in"}),rememberMe:te.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(d,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:te.z.object({phoneNumber:te.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=Jr(t.otpLength);return await o.context.internalAdapter.createVerificationValue({value:i,identifier:o.body.phoneNumber,expiresAt:I(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:te.z.object({phoneNumber:te.z.string({description:"Phone number to verify"}),code:te.z.string({description:"OTP code"}),disableSession:te.z.boolean({description:"Disable session creation after verification"}).optional(),updatePhoneNumber:te.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:ee(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 ep=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=Te(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:R(async t=>{let i=t.responseHeader.get("set-cookie"),r=t.context.authCookies.sessionToken.name,n=no(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:ee(en,e?.schema)});var y=require("zod");var tn=e=>{let t={defaultRole:"user",adminRole:"admin",...e},o=R(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<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:R(async i=>{let r=await ze(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?I(i.body.banExpiresIn,"sec"):e?.defaultBanExpiresIn?I(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?I(e.impersonationSessionDuration,"sec"):I(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:ee(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 ne=require("zod"),_e=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 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:ne.z.object({currentURL:ne.z.string({description:"Redirect to the current URL after sign in"}).optional()}).optional(),body:ne.z.object({providerId:ne.z.string({description:"The provider ID for the OAuth provider"}),callbackURL:ne.z.string({description:"The URL to redirect to after sign in"}).optional(),errorCallbackURL:ne.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 Oe(t),T=await E({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:ne.z.object({code:ne.z.string({description:"The OAuth2 code"}).optional(),error:ne.z.string({description:"The error message, if any"}).optional(),state:ne.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 ao(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 O({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 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 Fe=require("zod"),Qt={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0}}}},Cp=Fe.z.object({id:Fe.z.string(),publicKey:Fe.z.string(),privateKey:Fe.z.string(),createdAt:Fe.z.date()});var Zo=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 Zo(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=Zo(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:ee(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(Me(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(Me(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:R(async i=>{let r=i.responseHeader.get("set-cookie");if(!r)return;let n=no(r),a=i.context.authCookies.sessionToken,s=n.get(a.name)?.value;if(!s)return;let d=Me(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:R(async i=>{let r=i.headers?.get("cookie");if(!r)return;let n=Object.fromEntries(Me(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 Go=["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(Go,{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:I(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:I(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(Go,{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:I(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(Go)}),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:I(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 ze(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:I(t.expireIn,"sec")}),await e.sendVerificationOTP({email:i.user.email,otp:r,type:"email-verification"},o.request)}}}]}}};var Wo=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:Wo.z.object({idToken:Wo.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=re.VERCEL_URL,t=re.NETLIFY_URL,o=re.RENDER_URL,i=re.AWS_LAMBDA_FUNCTION_NAME,r=re.GOOGLE_CLOUD_FUNCTION_NAME,n=re.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:R(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===Te(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 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 ln=require("zod");var Gt=require("kysely"),Jo=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 Xo(e,t){let o=Eo(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=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=Eo(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 gn=e=>`<!doctype html>
92
+ `;var mn=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(Jt)}",
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>`,mn=()=>({id:"open-api",endpoints:{openAPI:K("/reference",{method:"GET"},async e=>{let t=await Gt(e.context,e.context.options);return new Response(gn(t),{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>`,fn=e=>{let t=e?.path??"/reference";return{id:"open-api",endpoints:{openAPIGenerator:c("/open-api/schema",{method:"GET"},async o=>{let i=await Xo(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 Xo(o.context,o.context.options);return new Response(mn(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});