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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/plugins.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var go=Object.create;var Ge=Object.defineProperty;var ho=Object.getOwnPropertyDescriptor;var wo=Object.getOwnPropertyNames;var yo=Object.getPrototypeOf,bo=Object.prototype.hasOwnProperty;var Ao=(e,o)=>{for(var r in o)Ge(e,r,{get:o[r],enumerable:!0})},Bt=(e,o,r,t)=>{if(o&&typeof o=="object"||typeof o=="function")for(let n of wo(o))!bo.call(e,n)&&n!==r&&Ge(e,n,{get:()=>o[n],enumerable:!(t=ho(o,n))||t.enumerable});return e};var Dt=(e,o,r)=>(r=e!=null?go(yo(e)):{},Bt(o||!e||!e.__esModule?Ge(r,"default",{value:e,enumerable:!0}):r,e)),ko=e=>Bt(Ge({},"__esModule",{value:!0}),e);var Wn={};Ao(Wn,{HIDE_METADATA:()=>we,admin:()=>Dn,anonymous:()=>Bn,bearer:()=>Pn,createAuthEndpoint:()=>u,createAuthMiddleware:()=>P,emailOTP:()=>Mn,genericOAuth:()=>Vn,getPasskeyActions:()=>no,jwt:()=>Fn,magicLink:()=>_n,multiSession:()=>qn,oAuthProxy:()=>Qn,oneTap:()=>$n,optionsMiddleware:()=>lt,organization:()=>fn,passkey:()=>Tn,passkeyClient:()=>Un,phoneNumber:()=>zn,twoFactor:()=>Rn,twoFactorClient:()=>vn,username:()=>Ct});module.exports=ko(Wn);var At=require("better-call"),Se=require("zod");var he=require("better-call"),lt=(0,he.createMiddleware)(async()=>({})),P=(0,he.createMiddlewareCreator)({use:[lt,(0,he.createMiddleware)(async()=>({}))]}),u=(0,he.createEndpointCreator)({use:[lt]});var B=require("better-call"),T=require("zod");var Uo=require("oslo"),jt=require("oslo/encoding");var Ke=require("oslo/crypto");async function vo({value:e,secret:o}){return new Ke.HMAC("SHA-256").sign(new TextEncoder().encode(o),new TextEncoder().encode(e)).then(t=>Buffer.from(t).toString("base64"))}function Ro({value:e,signature:o,secret:r}){return new Ke.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(o,"base64"),new TextEncoder().encode(e))}var Je={sign:vo,verify:Ro};var X=class extends Error{constructor(o,r){super(o),this.name="BetterAuthError",this.message=o,this.cause=r,this.stack=""}};var R=(e,o="ms")=>new Date(Date.now()+(o==="sec"?e*1e3:e));var Ze=Object.create(null),Ne=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Ze:globalThis),ee=new Proxy(Ze,{get(e,o){return Ne()[o]??Ze[o]},has(e,o){let r=Ne();return o in r||o in Ze},set(e,o,r){let t=Ne(!0);return t[o]=r,!0},deleteProperty(e,o){if(!o)return!1;let r=Ne(!0);return delete r[o],!0},ownKeys(){let e=Ne(!0);return Object.keys(e)}});function Eo(e){return e?e!=="false":!1}var mt=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Nt=mt==="dev"||mt==="development",Io=mt==="test"||Eo(ee.TEST);function Ye(e){let o=new Map;return e.split(", ").forEach(t=>{let n=t.split(";").map(m=>m.trim()),[i,...s]=n,[a,...d]=i.split("="),c=d.join("=");if(!a||c===void 0){console.warn(`Malformed cookie: ${t}`);return}let l={value:c};s.forEach(m=>{let[f,...p]=m.split("="),g=p.join("="),v=f.trim().toLowerCase();switch(v){case"max-age":l["max-age"]=g;break;case"expires":l.expires=g?new Date(g.trim()):void 0;break;case"domain":l.domain=g?g.trim():void 0;break;case"path":l.path=g?g.trim():void 0;break;case"secure":l.secure=!0;break;case"httponly":l.httponly=!0;break;case"samesite":l.samesite=g?g.trim().toLowerCase():void 0;break;default:l[v]=g?g.trim():!0;break}}),o.set(a,l)}),o}async function w(e,o,r,t){let n=e.context.authCookies.sessionToken.options,i=r?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,o.session.id,e.context.secret,{...n,maxAge:i,...t}),r&&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(jt.base64url.encode(new TextEncoder().encode(JSON.stringify({session:o,expiresAt:R(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await Je.sign({value:JSON.stringify(o),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(o.session.id,JSON.stringify({user:o.user,session:o.session}),o.session.expiresAt.getTime()-Date.now())}function te(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}function je(e){let o=e.split("; "),r=new Map;return o.forEach(t=>{let[n,i]=t.split("=");r.set(n,i)}),r}var Ht=require("@better-fetch/fetch"),Qt=require("better-call"),ve=require("jose"),Wt=require("oslo/jwt");var Vt=require("oslo/crypto"),Ft=require("oslo/encoding");async function qt(e){let o=await(0,Vt.sha256)(new TextEncoder().encode(e));return Ft.base64url.encode(new Uint8Array(o),{includePadding:!1})}function Mt(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?R(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function I({id:e,options:o,authorizationEndpoint:r,state:t,codeVerifier:n,scopes:i,claims:s,redirectURI:a}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",o.clientId),d.searchParams.set("state",t),d.searchParams.set("scope",i.join(" ")),d.searchParams.set("redirect_uri",o.redirectURI||a),n){let c=await qt(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",c)}if(s){let c=s.reduce((l,m)=>(l[m]=null,l),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...c}}))}return d}var $t=require("@better-fetch/fetch");async function k({code:e,codeVerifier:o,redirectURI:r,options:t,tokenEndpoint:n,authentication:i}){let s=new URLSearchParams,a={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),o&&s.set("code_verifier",o),s.set("redirect_uri",r),i==="basic"){let m=btoa(`${t.clientId}:${t.clientSecret}`);a.authorization=`Basic ${m}`}else s.set("client_id",t.clientId),s.set("client_secret",t.clientSecret);let{data:d,error:c}=await(0,$t.betterFetch)(n,{method:"POST",body:s,headers:a});if(c)throw c;return Mt(d)}var Xe=require("oslo/oauth2"),se=require("zod"),pt=require("better-call");function ke(e){try{return new URL(e).origin}catch{return null}}async function Oe(e,o){let r=e.body?.callbackURL||(e.query?.currentURL?ke(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new pt.APIError("BAD_REQUEST",{message:"callbackURL is required"});let t=(0,Xe.generateCodeVerifier)(),n=(0,Xe.generateState)(),i=JSON.stringify({callbackURL:r,codeVerifier:t,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,link:o,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:s});if(!a)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new pt.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:t}}async function et(e){let o=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(o);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:o}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let t=se.z.object({callbackURL:se.z.string(),codeVerifier:se.z.string(),errorURL:se.z.string().optional(),expiresAt:se.z.number(),link:se.z.object({email:se.z.string(),userId:se.z.string()}).optional()}).parse(JSON.parse(r.value));if(t.errorURL||(t.errorURL=`${e.context.baseURL}/error`),t.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:o}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),t}var Gt=e=>{let o="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:t,redirectURI:n}){let i=t||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:n})=>k({code:r,codeVerifier:t,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:o}),async verifyIdToken(r,t){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,t);let n=(0,ve.decodeProtectedHeader)(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let a=await To(i),{payload:d}=await(0,ve.jwtVerify)(r,a,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(c=>{d[c]!==void 0&&(d[c]=!!d[c])}),t&&d.nonce!==t?!1:!!d},async getUserInfo(r){if(!r.idToken)return null;let t=(0,Wt.parseJWT)(r.idToken)?.payload;if(!t)return null;let n=t.user?`${t.user.name.firstName} ${t.user.name.lastName}`:t.email;return{user:{id:t.sub,name:n,emailVerified:!1,email:t.email},data:t}}}},To=async e=>{let o="https://appleid.apple.com",r="/auth/keys",{data:t}=await(0,Ht.betterFetch)(`${o}${r}`);if(!t?.keys)throw new Qt.APIError("BAD_REQUEST",{message:"Keys not found"});let n=t.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await(0,ve.importJWK)(n,n.alg)};var Kt=require("@better-fetch/fetch");var Jt=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:o,scopes:r,redirectURI:t}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||t)}&state=${o}`)},validateAuthorizationCode:async({code:o,redirectURI:r})=>k({code:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(o){let{data:r,error:t}=await(0,Kt.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${o.accessToken}`}});if(t)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var Zt=require("@better-fetch/fetch");var Yt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:o,scopes:r,redirectURI:t}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await I({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:o,redirectURI:t})},validateAuthorizationCode:async({code:o,redirectURI:r})=>k({code:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(o){let{data:r,error:t}=await(0,Zt.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:o.accessToken}});return t?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});var ft=require("@better-fetch/fetch");var Xt=e=>{let o="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:t,codeVerifier:n,redirectURI:i}){let s=t||["user:email"];return e.scope&&s.push(...e.scope),I({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:t})=>k({code:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:o}),async getUserInfo(r){let{data:t,error:n}=await(0,ft.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!t.email){let{data:s,error:a}=await(0,ft.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(t.email=(s.find(d=>d.primary)??s[0])?.email,i=s.find(d=>d.email===t.email)?.verified??!1)}return{user:{id:t.id.toString(),name:t.name||t.login,email:t.email,image:t.avatar_url,emailVerified:i},data:t}}}};var tr=require("oslo/jwt");var er=require("consola"),gt=["info","success","warn","error","debug"];function So(e,o){return gt.indexOf(o)<=gt.indexOf(e)}var Po=(0,er.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),_o=e=>{let o=e?.disabled!==!0,r=e?.level??"error",t=(n,i,s=[])=>{if(!(!o||!So(r,n))){if(!e||typeof e.log!="function"){Po[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(gt.map(n=>[n,(...[i,...s])=>t(n,i,s)]))},W=_o();var rr=require("@better-fetch/fetch"),or=e=>({id:"google",name:"Google",async createAuthorizationURL({state:o,scopes:r,codeVerifier:t,redirectURI:n}){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(!t)throw new X("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await I({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:o,codeVerifier:t,redirectURI:n});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:o,codeVerifier:r,redirectURI:t})=>k({code:o,codeVerifier:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(o,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(o,r);let t=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${o}`,{data:n}=await(0,rr.betterFetch)(t);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(o){if(!o.idToken)return null;let r=(0,tr.parseJWT)(o.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});var nr=require("@better-fetch/fetch"),ir=require("oslo/jwt");var sr=e=>{let o=e.tenantId||"common",r=`https://login.microsoftonline.com/${o}/oauth2/v2.0/authorize`,t=`https://login.microsoftonline.com/${o}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),I({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return k({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:t})},async getUserInfo(n){if(!n.idToken)return null;let i=(0,ir.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,nr.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let c=await a.response.clone().arrayBuffer(),l=Buffer.from(c).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(d){W.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};var ar=require("@better-fetch/fetch");var dr=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:o,scopes:r,codeVerifier:t,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),I({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:o,codeVerifier:t,redirectURI:n})},validateAuthorizationCode:async({code:o,codeVerifier:r,redirectURI:t})=>k({code:o,codeVerifier:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(o){let{data:r,error:t}=await(0,ar.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return t?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});var we={isAction:!1};var cr=require("nanoid"),x=e=>(0,cr.nanoid)(e);var ur=require("oslo/jwt");var lr=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:o,scopes:r,redirectURI:t}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),I({id:"twitch",redirectURI:t,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:o,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:o,redirectURI:r})=>k({code:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(o){let r=o.idToken;if(!r)return W.error("No idToken found in token"),null;let t=(0,ur.parseJWT)(r)?.payload;return{user:{id:t.sub,name:t.preferred_username,email:t.email,image:t.picture,emailVerified:!1},data:t}}});var mr=require("@better-fetch/fetch");var pr=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(o){let r=o.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),I({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:o.state,codeVerifier:o.codeVerifier,redirectURI:o.redirectURI})},validateAuthorizationCode:async({code:o,codeVerifier:r,redirectURI:t})=>k({code:o,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(o){let{data:r,error:t}=await(0,mr.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return t?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var fr=require("@better-fetch/fetch");var gr=e=>{let o="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:t,codeVerifier:n,redirectURI:i})=>{let s=t||["account_info.read"];return e.scope&&s.push(...e.scope),await I({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:n})=>await k({code:r,codeVerifier:t,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:o}),async getUserInfo(r){let{data:t,error:n}=await(0,fr.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:t.account_id,name:t.name?.display_name,email:t.email,emailVerified:t.email_verified||!1,image:t.profile_photo_url},data:t}}}};var hr=require("@better-fetch/fetch");var wr=e=>{let o="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:t,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await I({id:"linkedin",options:e,authorizationEndpoint:o,scopes:s,state:t,redirectURI:i})},validateAuthorizationCode:async({code:t,redirectURI:n})=>await k({code:t,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(t){let{data:n,error:i}=await(0,hr.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};var yr=require("@better-fetch/fetch");var ht=(e="")=>e.split("://").map(o=>o.replace(/\/{2,}/g,"/")).join("://"),Co=e=>{let o=e||"https://gitlab.com";return{authorizationEndpoint:ht(`${o}/oauth/authorize`),tokenEndpoint:ht(`${o}/oauth/token`),userinfoEndpoint:ht(`${o}/api/v4/user`)}},br=e=>{let{authorizationEndpoint:o,tokenEndpoint:r,userinfoEndpoint:t}=Co(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:d,redirectURI:c})=>{let l=a||["read_user"];return e.scope&&l.push(...e.scope),await I({id:n,options:e,authorizationEndpoint:o,scopes:l,state:s,redirectURI:c,codeVerifier:d})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:d})=>k({code:s,redirectURI:e.redirectURI||a,options:e,codeVerifier:d,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:d}=await(0,yr.betterFetch)(t,{headers:{authorization:`Bearer ${s.accessToken}`}});return d||a.state!=="active"||a.locked?null:{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0},data:a}}}};var zo={apple:Gt,discord:Jt,facebook:Yt,github:Xt,microsoft:sr,google:or,spotify:dr,twitch:lr,twitter:pr,dropbox:gr,linkedin:wr,gitlab:br},tt=Object.keys(zo);var Or=require("oslo"),rt=require("oslo/jwt"),G=require("zod");var ue=require("better-call");var ce=require("better-call");var Re=require("zod");function Ar(e){try{return JSON.parse(e)}catch{return null}}var kr=()=>u("/get-session",{method:"GET",query:Re.z.optional(Re.z.object({disableCookieCache:Re.z.boolean().optional()})),requireHeaders:!0},async e=>{try{let o=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!o)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),t=r?Ar(Buffer.from(r,"base64").toString()):null;if(t&&!await Je.verify({value:JSON.stringify(t.session),signature:t?.signature,secret:e.context.secret}))return te(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(t?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let l=t.session;if(t.expiresAt<Date.now()||l.session.expiresAt<new Date){let f=e.context.authCookies.sessionData.name;e.setCookie(f,"",{maxAge:0})}else return e.json(l)}let i=await e.context.internalAdapter.findSession(o);if(!i||i.session.expiresAt<new Date)return te(e),i&&await e.context.internalAdapter.deleteSession(i.session.id),e.json(null);if(n)return e.json(i);let s=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+a*1e3<=Date.now()){let l=await e.context.internalAdapter.updateSession(i.session.id,{expiresAt:R(e.context.sessionConfig.expiresIn,"sec")});if(!l)return te(e),e.json(null,{status:401});let m=(l.expiresAt.valueOf()-Date.now())/1e3;return await w(e,{session:l,user:i.user},!1,{maxAge:m}),e.json({session:l,user:i.user})}return e.json(i)}catch(o){throw e.context.logger.error("INTERNAL_SERVER_ERROR",o),new ce.APIError("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),z=async e=>{if(e.context.session)return e.context.session;let o=await kr()({...e,_flag:"json",headers:e.headers});return e.context.session=o,o},b=P(async e=>{let o=await z(e);if(!o?.session)throw new ce.APIError("UNAUTHORIZED");return{session:o}});var xo=u("/revoke-session",{method:"POST",body:Re.z.object({id:Re.z.string()}),use:[b],requireHeaders:!0},async e=>{let o=e.body.id,r=await e.context.internalAdapter.findSession(o);if(!r)throw new ce.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new ce.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(o)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new ce.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Lo=u("/revoke-sessions",{method:"POST",use:[b],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new ce.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Bo=u("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[b]},async e=>{let o=e.context.session;if(!o.user)throw new ce.APIError("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(o.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.id!==e.context.session.session.id);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.id))),e.json({status:!0})});async function le(e,o,r){return await(0,rt.createJWT)("HS256",Buffer.from(e),{email:o.toLowerCase(),updateTo:r},{expiresIn:new Or.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[o],includeIssuedTimestamp:!0})}var Do=u("/send-verification-email",{method:"POST",query:G.z.object({currentURL:G.z.string().optional()}).optional(),body:G.z.object({email:G.z.string().email(),callbackURL:G.z.string().optional()})},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:o}=e.body,r=await e.context.internalAdapter.findUserByEmail(o);if(!r)throw new ue.APIError("BAD_REQUEST",{message:"User not found"});let t=await le(e.context.secret,o),n=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail({user:r.user,url:n,token:t},e.request),e.json({status:!0})}),No=u("/verify-email",{method:"GET",query:G.z.object({token:G.z.string(),callbackURL:G.z.string().optional()})},async e=>{let{token:o}=e.query,r;try{r=await(0,rt.validateJWT)("HS256",Buffer.from(e.context.secret),o)}catch(s){throw e.context.logger.error("Failed to verify email",s),new ue.APIError("BAD_REQUEST",{message:"Invalid token"})}let n=G.z.object({email:G.z.string().email(),updateTo:G.z.string().optional()}).parse(r.payload),i=await e.context.internalAdapter.findUserByEmail(n.email);if(!i)throw new ue.APIError("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await z(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new ue.APIError("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new ue.APIError("UNAUTHORIZED",{message:"Invalid session"});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=${o}`,token:o},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 z(e)){let a=await e.context.internalAdapter.createSession(i.user.id,e.request);if(!a)throw new ue.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await w(e,{session:a,user:i.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var wt=require("better-call");var vr=require("better-call");var jo=P(async e=>{if(e.request?.method!=="POST")return;let{body:o,query:r,context:t}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=o?.callbackURL||r?.callbackURL,s=o?.redirectTo,a=r?.currentURL,d=t.trustedOrigins,c=e.headers?.has("cookie"),l=(f,p)=>p.includes("*")?new RegExp("^"+p.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(f):f.startsWith(p),m=(f,p)=>{if(!f)return;if(!d.some(v=>l(f,v)||f?.startsWith("/")&&p!=="origin"&&!f.includes(":")))throw e.context.logger.error(`Invalid ${p}: ${f}`),e.context.logger.info(`If it's a valid URL, please add ${f} to trustedOrigins in your auth config
2
- `,`Current list of trustedOrigins: ${d}`),new vr.APIError("FORBIDDEN",{message:`Invalid ${p}`})};c&&!e.context.options.advanced?.disableCSRFCheck&&m(n,"origin"),i&&m(i,"callbackURL"),s&&m(s,"redirectURL"),a&&m(a,"currentURL")});var Vo=u("/ok",{method:"GET",metadata:we},async e=>e.json({ok:!0}));var qo=require("zod");var Mo=require("better-call");var A=require("zod"),Xs=A.z.object({id:A.z.string(),providerId:A.z.string(),accountId:A.z.string(),userId:A.z.string(),accessToken:A.z.string().nullish(),refreshToken:A.z.string().nullish(),idToken:A.z.string().nullish(),expiresAt:A.z.date().nullish(),password:A.z.string().nullish()}),Rr=A.z.object({id:A.z.string(),email:A.z.string().transform(e=>e.toLowerCase()),emailVerified:A.z.boolean().default(!1),name:A.z.string(),image:A.z.string().nullish(),createdAt:A.z.date().default(new Date),updatedAt:A.z.date().default(new Date)}),ea=A.z.object({id:A.z.string(),userId:A.z.string(),expiresAt:A.z.date(),ipAddress:A.z.string().nullish(),userAgent:A.z.string().nullish()}),ta=A.z.object({id:A.z.string(),value:A.z.string(),createdAt:A.z.date(),expiresAt:A.z.date(),identifier:A.z.string()});function K(e,o){if(!o)return e;for(let r in o){let t=o[r]?.modelName;t&&(e[r].modelName=t);for(let n in e[r].fields){let i=o[r]?.fields?.[n];i&&(e[r].fields[n].fieldName=i)}}return e}var $o=(e="Unknown")=>`<!DOCTYPE html>
1
+ "use strict";var go=Object.create;var Ge=Object.defineProperty;var ho=Object.getOwnPropertyDescriptor;var wo=Object.getOwnPropertyNames;var yo=Object.getPrototypeOf,bo=Object.prototype.hasOwnProperty;var Ao=(e,o)=>{for(var r in o)Ge(e,r,{get:o[r],enumerable:!0})},Bt=(e,o,r,t)=>{if(o&&typeof o=="object"||typeof o=="function")for(let n of wo(o))!bo.call(e,n)&&n!==r&&Ge(e,n,{get:()=>o[n],enumerable:!(t=ho(o,n))||t.enumerable});return e};var Dt=(e,o,r)=>(r=e!=null?go(yo(e)):{},Bt(o||!e||!e.__esModule?Ge(r,"default",{value:e,enumerable:!0}):r,e)),ko=e=>Bt(Ge({},"__esModule",{value:!0}),e);var Wn={};Ao(Wn,{HIDE_METADATA:()=>we,admin:()=>Dn,anonymous:()=>Bn,bearer:()=>Pn,createAuthEndpoint:()=>u,createAuthMiddleware:()=>P,emailOTP:()=>Mn,genericOAuth:()=>Vn,getPasskeyActions:()=>no,jwt:()=>Fn,magicLink:()=>_n,multiSession:()=>qn,oAuthProxy:()=>Qn,oneTap:()=>$n,optionsMiddleware:()=>lt,organization:()=>fn,passkey:()=>Tn,passkeyClient:()=>Un,phoneNumber:()=>zn,twoFactor:()=>Rn,twoFactorClient:()=>vn,username:()=>Ct});module.exports=ko(Wn);var At=require("better-call"),Se=require("zod");var he=require("better-call"),lt=(0,he.createMiddleware)(async()=>({})),P=(0,he.createMiddlewareCreator)({use:[lt,(0,he.createMiddleware)(async()=>({}))]}),u=(0,he.createEndpointCreator)({use:[lt]});var B=require("better-call"),T=require("zod");var Uo=require("oslo"),jt=require("oslo/encoding");var Ke=require("oslo/crypto");async function vo({value:e,secret:o}){return new Ke.HMAC("SHA-256").sign(new TextEncoder().encode(o),new TextEncoder().encode(e)).then(t=>Buffer.from(t).toString("base64"))}function Ro({value:e,signature:o,secret:r}){return new Ke.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(o,"base64"),new TextEncoder().encode(e))}var Je={sign:vo,verify:Ro};var X=class extends Error{constructor(o,r){super(o),this.name="BetterAuthError",this.message=o,this.cause=r,this.stack=""}};var R=(e,o="ms")=>new Date(Date.now()+(o==="sec"?e*1e3:e));var Ze=Object.create(null),Ne=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Ze:globalThis),ee=new Proxy(Ze,{get(e,o){return Ne()[o]??Ze[o]},has(e,o){let r=Ne();return o in r||o in Ze},set(e,o,r){let t=Ne(!0);return t[o]=r,!0},deleteProperty(e,o){if(!o)return!1;let r=Ne(!0);return delete r[o],!0},ownKeys(){let e=Ne(!0);return Object.keys(e)}});function Eo(e){return e?e!=="false":!1}var pt=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Nt=pt==="dev"||pt==="development",Io=pt==="test"||Eo(ee.TEST);function Ye(e){let o=new Map;return e.split(", ").forEach(t=>{let n=t.split(";").map(p=>p.trim()),[i,...s]=n,[a,...d]=i.split("="),c=d.join("=");if(!a||c===void 0){console.warn(`Malformed cookie: ${t}`);return}let l={value:c};s.forEach(p=>{let[f,...m]=p.split("="),g=m.join("="),v=f.trim().toLowerCase();switch(v){case"max-age":l["max-age"]=g;break;case"expires":l.expires=g?new Date(g.trim()):void 0;break;case"domain":l.domain=g?g.trim():void 0;break;case"path":l.path=g?g.trim():void 0;break;case"secure":l.secure=!0;break;case"httponly":l.httponly=!0;break;case"samesite":l.samesite=g?g.trim().toLowerCase():void 0;break;default:l[v]=g?g.trim():!0;break}}),o.set(a,l)}),o}async function w(e,o,r,t){let n=e.context.authCookies.sessionToken.options,i=r?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,o.session.id,e.context.secret,{...n,maxAge:i,...t}),r&&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(jt.base64url.encode(new TextEncoder().encode(JSON.stringify({session:o,expiresAt:R(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await Je.sign({value:JSON.stringify(o),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(o.session.id,JSON.stringify({user:o.user,session:o.session}),o.session.expiresAt.getTime()-Date.now())}function te(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}function je(e){let o=e.split("; "),r=new Map;return o.forEach(t=>{let[n,i]=t.split("=");r.set(n,i)}),r}var Ht=require("@better-fetch/fetch"),Qt=require("better-call"),ve=require("jose"),Wt=require("oslo/jwt");var Vt=require("oslo/crypto"),Ft=require("oslo/encoding");async function qt(e){let o=await(0,Vt.sha256)(new TextEncoder().encode(e));return Ft.base64url.encode(new Uint8Array(o),{includePadding:!1})}function Mt(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?R(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function I({id:e,options:o,authorizationEndpoint:r,state:t,codeVerifier:n,scopes:i,claims:s,redirectURI:a}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",o.clientId),d.searchParams.set("state",t),d.searchParams.set("scope",i.join(" ")),d.searchParams.set("redirect_uri",o.redirectURI||a),n){let c=await qt(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",c)}if(s){let c=s.reduce((l,p)=>(l[p]=null,l),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...c}}))}return d}var $t=require("@better-fetch/fetch");async function k({code:e,codeVerifier:o,redirectURI:r,options:t,tokenEndpoint:n,authentication:i}){let s=new URLSearchParams,a={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),o&&s.set("code_verifier",o),s.set("redirect_uri",r),i==="basic"){let p=btoa(`${t.clientId}:${t.clientSecret}`);a.authorization=`Basic ${p}`}else s.set("client_id",t.clientId),s.set("client_secret",t.clientSecret);let{data:d,error:c}=await(0,$t.betterFetch)(n,{method:"POST",body:s,headers:a});if(c)throw c;return Mt(d)}var Xe=require("oslo/oauth2"),se=require("zod"),mt=require("better-call");function ke(e){try{return new URL(e).origin}catch{return null}}async function Oe(e,o){let r=e.body?.callbackURL||(e.query?.currentURL?ke(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new mt.APIError("BAD_REQUEST",{message:"callbackURL is required"});let t=(0,Xe.generateCodeVerifier)(),n=(0,Xe.generateState)(),i=JSON.stringify({callbackURL:r,codeVerifier:t,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,link:o,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:s});if(!a)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new mt.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:t}}async function et(e){let o=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(o);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:o}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let t=se.z.object({callbackURL:se.z.string(),codeVerifier:se.z.string(),errorURL:se.z.string().optional(),expiresAt:se.z.number(),link:se.z.object({email:se.z.string(),userId:se.z.string()}).optional()}).parse(JSON.parse(r.value));if(t.errorURL||(t.errorURL=`${e.context.baseURL}/error`),t.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:o}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),t}var Gt=e=>{let o="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:t,redirectURI:n}){let i=t||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:n})=>k({code:r,codeVerifier:t,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:o}),async verifyIdToken(r,t){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,t);let n=(0,ve.decodeProtectedHeader)(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let a=await To(i),{payload:d}=await(0,ve.jwtVerify)(r,a,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(c=>{d[c]!==void 0&&(d[c]=!!d[c])}),t&&d.nonce!==t?!1:!!d},async getUserInfo(r){if(!r.idToken)return null;let t=(0,Wt.parseJWT)(r.idToken)?.payload;if(!t)return null;let n=t.user?`${t.user.name.firstName} ${t.user.name.lastName}`:t.email;return{user:{id:t.sub,name:n,emailVerified:!1,email:t.email},data:t}}}},To=async e=>{let o="https://appleid.apple.com",r="/auth/keys",{data:t}=await(0,Ht.betterFetch)(`${o}${r}`);if(!t?.keys)throw new Qt.APIError("BAD_REQUEST",{message:"Keys not found"});let n=t.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await(0,ve.importJWK)(n,n.alg)};var Kt=require("@better-fetch/fetch");var Jt=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:o,scopes:r,redirectURI:t}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||t)}&state=${o}`)},validateAuthorizationCode:async({code:o,redirectURI:r})=>k({code:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(o){let{data:r,error:t}=await(0,Kt.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${o.accessToken}`}});if(t)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var Zt=require("@better-fetch/fetch");var Yt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:o,scopes:r,redirectURI:t}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await I({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:o,redirectURI:t})},validateAuthorizationCode:async({code:o,redirectURI:r})=>k({code:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(o){let{data:r,error:t}=await(0,Zt.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:o.accessToken}});return t?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});var ft=require("@better-fetch/fetch");var Xt=e=>{let o="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:t,codeVerifier:n,redirectURI:i}){let s=t||["user:email"];return e.scope&&s.push(...e.scope),I({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:t})=>k({code:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:o}),async getUserInfo(r){let{data:t,error:n}=await(0,ft.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!t.email){let{data:s,error:a}=await(0,ft.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(t.email=(s.find(d=>d.primary)??s[0])?.email,i=s.find(d=>d.email===t.email)?.verified??!1)}return{user:{id:t.id.toString(),name:t.name||t.login,email:t.email,image:t.avatar_url,emailVerified:i},data:t}}}};var tr=require("oslo/jwt");var er=require("consola"),gt=["info","success","warn","error","debug"];function So(e,o){return gt.indexOf(o)<=gt.indexOf(e)}var Po=(0,er.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),_o=e=>{let o=e?.disabled!==!0,r=e?.level??"error",t=(n,i,s=[])=>{if(!(!o||!So(r,n))){if(!e||typeof e.log!="function"){Po[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(gt.map(n=>[n,(...[i,...s])=>t(n,i,s)]))},W=_o();var rr=require("@better-fetch/fetch"),or=e=>({id:"google",name:"Google",async createAuthorizationURL({state:o,scopes:r,codeVerifier:t,redirectURI:n}){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(!t)throw new X("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await I({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:o,codeVerifier:t,redirectURI:n});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:o,codeVerifier:r,redirectURI:t})=>k({code:o,codeVerifier:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(o,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(o,r);let t=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${o}`,{data:n}=await(0,rr.betterFetch)(t);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(o){if(!o.idToken)return null;let r=(0,tr.parseJWT)(o.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});var nr=require("@better-fetch/fetch"),ir=require("oslo/jwt");var sr=e=>{let o=e.tenantId||"common",r=`https://login.microsoftonline.com/${o}/oauth2/v2.0/authorize`,t=`https://login.microsoftonline.com/${o}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),I({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return k({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:t})},async getUserInfo(n){if(!n.idToken)return null;let i=(0,ir.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,nr.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let c=await a.response.clone().arrayBuffer(),l=Buffer.from(c).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(d){W.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};var ar=require("@better-fetch/fetch");var dr=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:o,scopes:r,codeVerifier:t,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),I({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:o,codeVerifier:t,redirectURI:n})},validateAuthorizationCode:async({code:o,codeVerifier:r,redirectURI:t})=>k({code:o,codeVerifier:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(o){let{data:r,error:t}=await(0,ar.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return t?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});var we={isAction:!1};var cr=require("nanoid"),x=e=>(0,cr.nanoid)(e);var ur=require("oslo/jwt");var lr=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:o,scopes:r,redirectURI:t}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),I({id:"twitch",redirectURI:t,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:o,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:o,redirectURI:r})=>k({code:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(o){let r=o.idToken;if(!r)return W.error("No idToken found in token"),null;let t=(0,ur.parseJWT)(r)?.payload;return{user:{id:t.sub,name:t.preferred_username,email:t.email,image:t.picture,emailVerified:!1},data:t}}});var pr=require("@better-fetch/fetch");var mr=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(o){let r=o.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),I({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:o.state,codeVerifier:o.codeVerifier,redirectURI:o.redirectURI})},validateAuthorizationCode:async({code:o,codeVerifier:r,redirectURI:t})=>k({code:o,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(o){let{data:r,error:t}=await(0,pr.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return t?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var fr=require("@better-fetch/fetch");var gr=e=>{let o="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:t,codeVerifier:n,redirectURI:i})=>{let s=t||["account_info.read"];return e.scope&&s.push(...e.scope),await I({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:n})=>await k({code:r,codeVerifier:t,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:o}),async getUserInfo(r){let{data:t,error:n}=await(0,fr.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:t.account_id,name:t.name?.display_name,email:t.email,emailVerified:t.email_verified||!1,image:t.profile_photo_url},data:t}}}};var hr=require("@better-fetch/fetch");var wr=e=>{let o="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:t,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await I({id:"linkedin",options:e,authorizationEndpoint:o,scopes:s,state:t,redirectURI:i})},validateAuthorizationCode:async({code:t,redirectURI:n})=>await k({code:t,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(t){let{data:n,error:i}=await(0,hr.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};var yr=require("@better-fetch/fetch");var ht=(e="")=>e.split("://").map(o=>o.replace(/\/{2,}/g,"/")).join("://"),Co=e=>{let o=e||"https://gitlab.com";return{authorizationEndpoint:ht(`${o}/oauth/authorize`),tokenEndpoint:ht(`${o}/oauth/token`),userinfoEndpoint:ht(`${o}/api/v4/user`)}},br=e=>{let{authorizationEndpoint:o,tokenEndpoint:r,userinfoEndpoint:t}=Co(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:d,redirectURI:c})=>{let l=a||["read_user"];return e.scope&&l.push(...e.scope),await I({id:n,options:e,authorizationEndpoint:o,scopes:l,state:s,redirectURI:c,codeVerifier:d})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:d})=>k({code:s,redirectURI:e.redirectURI||a,options:e,codeVerifier:d,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:d}=await(0,yr.betterFetch)(t,{headers:{authorization:`Bearer ${s.accessToken}`}});return d||a.state!=="active"||a.locked?null:{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0},data:a}}}};var zo={apple:Gt,discord:Jt,facebook:Yt,github:Xt,microsoft:sr,google:or,spotify:dr,twitch:lr,twitter:mr,dropbox:gr,linkedin:wr,gitlab:br},tt=Object.keys(zo);var Or=require("oslo"),rt=require("oslo/jwt"),G=require("zod");var ue=require("better-call");var ce=require("better-call");var Re=require("zod");function Ar(e){try{return JSON.parse(e)}catch{return null}}var kr=()=>u("/get-session",{method:"GET",query:Re.z.optional(Re.z.object({disableCookieCache:Re.z.boolean().optional()})),requireHeaders:!0},async e=>{try{let o=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!o)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),t=r?Ar(Buffer.from(r,"base64").toString()):null;if(t&&!await Je.verify({value:JSON.stringify(t.session),signature:t?.signature,secret:e.context.secret}))return te(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(t?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let l=t.session;if(t.expiresAt<Date.now()||l.session.expiresAt<new Date){let f=e.context.authCookies.sessionData.name;e.setCookie(f,"",{maxAge:0})}else return e.json(l)}let i=await e.context.internalAdapter.findSession(o);if(!i||i.session.expiresAt<new Date)return te(e),i&&await e.context.internalAdapter.deleteSession(i.session.id),e.json(null);if(n)return e.json(i);let s=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+a*1e3<=Date.now()){let l=await e.context.internalAdapter.updateSession(i.session.id,{expiresAt:R(e.context.sessionConfig.expiresIn,"sec")});if(!l)return te(e),e.json(null,{status:401});let p=(l.expiresAt.valueOf()-Date.now())/1e3;return await w(e,{session:l,user:i.user},!1,{maxAge:p}),e.json({session:l,user:i.user})}return e.json(i)}catch(o){throw e.context.logger.error("INTERNAL_SERVER_ERROR",o),new ce.APIError("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),z=async e=>{if(e.context.session)return e.context.session;let o=await kr()({...e,_flag:"json",headers:e.headers});return e.context.session=o,o},b=P(async e=>{let o=await z(e);if(!o?.session)throw new ce.APIError("UNAUTHORIZED");return{session:o}});var xo=u("/revoke-session",{method:"POST",body:Re.z.object({id:Re.z.string()}),use:[b],requireHeaders:!0},async e=>{let o=e.body.id,r=await e.context.internalAdapter.findSession(o);if(!r)throw new ce.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new ce.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(o)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new ce.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Lo=u("/revoke-sessions",{method:"POST",use:[b],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new ce.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Bo=u("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[b]},async e=>{let o=e.context.session;if(!o.user)throw new ce.APIError("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(o.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.id!==e.context.session.session.id);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.id))),e.json({status:!0})});async function le(e,o,r){return await(0,rt.createJWT)("HS256",Buffer.from(e),{email:o.toLowerCase(),updateTo:r},{expiresIn:new Or.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[o],includeIssuedTimestamp:!0})}var Do=u("/send-verification-email",{method:"POST",query:G.z.object({currentURL:G.z.string().optional()}).optional(),body:G.z.object({email:G.z.string().email(),callbackURL:G.z.string().optional()})},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:o}=e.body,r=await e.context.internalAdapter.findUserByEmail(o);if(!r)throw new ue.APIError("BAD_REQUEST",{message:"User not found"});let t=await le(e.context.secret,o),n=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail({user:r.user,url:n,token:t},e.request),e.json({status:!0})}),No=u("/verify-email",{method:"GET",query:G.z.object({token:G.z.string(),callbackURL:G.z.string().optional()})},async e=>{let{token:o}=e.query,r;try{r=await(0,rt.validateJWT)("HS256",Buffer.from(e.context.secret),o)}catch(s){throw e.context.logger.error("Failed to verify email",s),new ue.APIError("BAD_REQUEST",{message:"Invalid token"})}let n=G.z.object({email:G.z.string().email(),updateTo:G.z.string().optional()}).parse(r.payload),i=await e.context.internalAdapter.findUserByEmail(n.email);if(!i)throw new ue.APIError("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await z(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new ue.APIError("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new ue.APIError("UNAUTHORIZED",{message:"Invalid session"});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=${o}`,token:o},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 z(e)){let a=await e.context.internalAdapter.createSession(i.user.id,e.request);if(!a)throw new ue.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await w(e,{session:a,user:i.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var wt=require("better-call");var vr=require("better-call");var jo=P(async e=>{if(e.request?.method!=="POST")return;let{body:o,query:r,context:t}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=o?.callbackURL||r?.callbackURL,s=o?.redirectTo,a=r?.currentURL,d=t.trustedOrigins,c=e.headers?.has("cookie"),l=(f,m)=>m.includes("*")?new RegExp("^"+m.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(f):f.startsWith(m),p=(f,m)=>{if(!f)return;if(!d.some(v=>l(f,v)||f?.startsWith("/")&&m!=="origin"&&!f.includes(":")))throw e.context.logger.error(`Invalid ${m}: ${f}`),e.context.logger.info(`If it's a valid URL, please add ${f} to trustedOrigins in your auth config
2
+ `,`Current list of trustedOrigins: ${d}`),new vr.APIError("FORBIDDEN",{message:`Invalid ${m}`})};c&&!e.context.options.advanced?.disableCSRFCheck&&p(n,"origin"),i&&p(i,"callbackURL"),s&&p(s,"redirectURL"),a&&p(a,"currentURL")});var Vo=u("/ok",{method:"GET",metadata:we},async e=>e.json({ok:!0}));var qo=require("zod");var Mo=require("better-call");var A=require("zod"),Xs=A.z.object({id:A.z.string(),providerId:A.z.string(),accountId:A.z.string(),userId:A.z.string(),accessToken:A.z.string().nullish(),refreshToken:A.z.string().nullish(),idToken:A.z.string().nullish(),expiresAt:A.z.date().nullish(),password:A.z.string().nullish()}),Rr=A.z.object({id:A.z.string(),email:A.z.string().transform(e=>e.toLowerCase()),emailVerified:A.z.boolean().default(!1),name:A.z.string(),image:A.z.string().nullish(),createdAt:A.z.date().default(new Date),updatedAt:A.z.date().default(new Date)}),ea=A.z.object({id:A.z.string(),userId:A.z.string(),expiresAt:A.z.date(),ipAddress:A.z.string().nullish(),userAgent:A.z.string().nullish()}),ta=A.z.object({id:A.z.string(),value:A.z.string(),createdAt:A.z.date(),expiresAt:A.z.date(),identifier:A.z.string()});function K(e,o){if(!o)return e;for(let r in o){let t=o[r]?.modelName;t&&(e[r].modelName=t);for(let n in e[r].fields){let i=o[r]?.fields?.[n];i&&(e[r].fields[n].fieldName=i)}}return e}var $o=(e="Unknown")=>`<!DOCTYPE html>
3
3
  <html lang="en">
4
4
  <head>
5
5
  <meta charset="UTF-8">
@@ -80,4 +80,4 @@
80
80
  </div>
81
81
  </body>
82
82
  </html>`,Ho=u("/error",{method:"GET",metadata:we},async e=>{let o=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response($o(o),{headers:{"Content-Type":"text/html"}})});var O=require("better-call");async function Ee(e,{userInfo:o,account:r,callbackURL:t}){let n=await e.context.internalAdapter.findUserByEmail(o.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw W.error(`Better auth was unable to query your database.
83
- Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user;if(n){let a=n.accounts.find(d=>d.providerId===r.providerId);if(a)await e.context.internalAdapter.updateAccount(a.id,{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt});else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!o.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Nt&&W.warn(`User already exist but account isn't linked to ${r.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:r.providerId,accountId:o.id.toString(),id:e.context.uuid(),userId:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt})}catch(l){return W.error("Unable to link account",l),{error:"unable to link account",data:null}}}}else try{let a=o.emailVerified||!1;if(i=await e.context.internalAdapter.createOAuthUser({...o,id:e.context.uuid(),emailVerified:a,email:o.email.toLowerCase()},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,providerId:r.providerId,accountId:o.id.toString()}).then(d=>d?.user),!a&&i&&e.context.options.emailVerification?.sendOnSignUp){let d=await le(e.context.secret,i.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${t}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:c,token:d},e.request)}}catch(a){return W.error("Unable to create user",a),{error:"unable to create user",data:null}}if(!i)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(i.id,e.request);return s?{data:{session:s,user:i},error:null}:{error:"unable to create session",data:null}}var Qo=u("/sign-in/social",{method:"POST",query:T.z.object({currentURL:T.z.string().optional()}).optional(),body:T.z.object({callbackURL:T.z.string().optional(),errorCallbackURL:T.z.string().optional(),provider:T.z.enum(tt),disableRedirect:T.z.boolean().optional(),idToken:T.z.optional(T.z.object({token:T.z.string(),nonce:T.z.string().optional(),accessToken:T.z.string().optional(),refreshToken:T.z.string().optional(),expiresAt:T.z.number().optional()}))})},async e=>{let o=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!o)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new B.APIError("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!o.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new B.APIError("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:i,nonce:s}=e.body.idToken;if(!await o.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new B.APIError("UNAUTHORIZED",{message:"Invalid id token"});let d=await o.getUserInfo({idToken:i,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 B.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 B.APIError("UNAUTHORIZED",{message:"User email not found"});let c=await Ee(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:o.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new B.APIError("UNAUTHORIZED",{message:c.error});return await w(e,c.data),e.json({session:c.data.session,user:c.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:r,state:t}=await Oe(e),n=await o.createAuthorizationURL({state:t,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${o.id}`});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),Wo=u("/sign-in/email",{method:"POST",body:T.z.object({email:T.z.string(),password:T.z.string(),callbackURL:T.z.string().optional(),rememberMe:T.z.boolean().default(!0).optional()})},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 B.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:o,password:r}=e.body;if(!T.z.string().email().safeParse(o).success)throw new B.APIError("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(o,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:o}),new B.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(c=>c.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:o}),new B.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:o}),new B.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new B.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Email verification is required but no email verification handler is provided"),new B.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await le(e.context.secret,n.user.email),l=`${e.context.baseURL}/verify-email?token=${c}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:l,token:c},e.request),e.context.logger.error("Email not verified",{email:o}),new B.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!d)throw e.context.logger.error("Failed to create session"),new B.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await w(e,{session:d,user:n.user},e.body.rememberMe===!1),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Ie=require("zod");var ot=Ie.z.object({code:Ie.z.string().optional(),error:Ie.z.string().optional(),errorMessage:Ie.z.string().optional(),state:Ie.z.string().optional()}),Go=u("/callback/:id",{method:["GET","POST"],body:ot.optional(),query:ot.optional(),metadata:we},async e=>{let o;try{if(e.method==="GET")o=ot.parse(e.query);else if(e.method==="POST")o=ot.parse(e.body);else throw new Error("Unsupported method")}catch(y){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",y),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:t,state:n}=o;if(!n)throw e.context.logger.error("State not found"),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${t||"no_code"}`);let i=e.context.socialProviders.find(y=>y.id===e.params.id);if(!i)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:s,callbackURL:a,link:d,errorURL:c}=await et(e),l;try{l=await i.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${i.id}`})}catch(y){throw e.context.logger.error("",y),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let m=await i.getUserInfo(l).then(y=>y?.user),p={id:x(),...m};function g(y){let C=c||a||`${e.context.baseURL}/error`;throw C.includes("?")?C=`${C}&error=${y}`:C=`${C}?error=${y}`,e.redirect(C)}if(!m)return e.context.logger.error("Unable to get user info"),g("unable_to_get_user_info");if(!p.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),g("email_not_found");if(!a)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(d){if(d.email!==p.email.toLowerCase())return g("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:i.id,accountId:m.id}))return g("unable_to_link_account");let C;try{C=new URL(a).toString()}catch{C=a}throw e.redirect(C)}let v=await Ee(e,{userInfo:{email:p.email,id:p.id,name:p.name||"",image:p.image,emailVerified:p.emailVerified||!1},account:{providerId:i.id,accountId:m.id,accessToken:l.accessToken,refreshToken:l.refreshToken,expiresAt:l.accessTokenExpiresAt},callbackURL:a});if(v.error)return e.context.logger.error(v.error.split(" ").join("_")),g(v.error.split(" ").join("_"));let{session:H,user:oe}=v.data;await w(e,{session:H,user:oe});let Y;try{Y=new URL(a).toString()}catch{Y=a}throw e.redirect(Y)});var ed=require("zod");var Er=require("better-call"),Ko=u("/sign-out",{method:"POST",requireHeaders:!0},async e=>{let o=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!o)throw te(e),new Er.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(o),te(e),e.json({success:!0})});var Q=require("zod");var nt=require("better-call");function Ir(e,o,r){let t=o?new URL(o,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>t.searchParams.set(n,i)),t.href}function sn(e,o,r){let t=new URL(o,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>t.searchParams.set(n,i)),t.href}var Jo=u("/forget-password",{method:"POST",body:Q.z.object({email:Q.z.string().email(),redirectTo:Q.z.string()})},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 nt.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:o,redirectTo:r}=e.body,t=await e.context.internalAdapter.findUserByEmail(o,{includeAccounts:!0});if(!t)return e.context.logger.error("Reset Password: User not found",{email:o}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=R(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`reset-password:${s}`,expiresAt:i});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:t.user,url:a,token:s},e.request),e.json({status:!0})}),Zo=u("/reset-password/:token",{method:"GET",query:Q.z.object({callbackURL:Q.z.string()})},async e=>{let{token:o}=e.params,{callbackURL:r}=e.query;if(!o||!r)throw e.redirect(Ir(e.context,r,{error:"INVALID_TOKEN"}));let t=await e.context.internalAdapter.findVerificationValue(`reset-password:${o}`);throw!t||t.expiresAt<new Date?e.redirect(Ir(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(sn(e.context,r,{token:o}))}),Yo=u("/reset-password",{query:Q.z.optional(Q.z.object({token:Q.z.string().optional(),currentURL:Q.z.string().optional()})),method:"POST",body:Q.z.object({newPassword:Q.z.string(),token:Q.z.string().optional()})},async e=>{let o=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!o)throw new nt.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,t=`reset-password:${o}`,n=await e.context.internalAdapter.findVerificationValue(t);if(!n||n.expiresAt<new Date)throw new nt.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(i)).find(c=>c.providerId==="credential")?(await e.context.internalAdapter.updatePassword(i,s),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0}))});var F=require("zod");var V=require("better-call");var Xo=u("/change-password",{method:"POST",body:F.z.object({newPassword:F.z.string(),currentPassword:F.z.string(),revokeOtherSessions:F.z.boolean().optional()}),use:[b]},async e=>{let{newPassword:o,currentPassword:r,revokeOtherSessions:t}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(o.length<i)throw e.context.logger.error("Password is too short"),new V.APIError("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(o.length>s)throw e.context.logger.error("Password is too long"),new V.APIError("BAD_REQUEST",{message:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(n.user.id)).find(m=>m.providerId==="credential"&&m.password);if(!d||!d.password)throw new V.APIError("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(o);if(!await e.context.password.verify(d.password,r))throw new V.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),t){await e.context.internalAdapter.deleteSessions(n.user.id);let m=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!m)throw new V.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await w(e,{session:m,user:n.user})}return e.json(n.user)}),en=u("/set-password",{method:"POST",body:F.z.object({newPassword:F.z.string()}),metadata:{SERVER_ONLY:!0},use:[b]},async e=>{let{newPassword:o}=e.body,r=e.context.session,t=e.context.password.config.minPasswordLength;if(o.length<t)throw e.context.logger.error("Password is too short"),new V.APIError("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(o.length>n)throw e.context.logger.error("Password is too long"),new V.APIError("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(d=>d.providerId==="credential"&&d.password),a=await e.context.password.hash(o);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:a}),e.json(r.user);throw new V.APIError("BAD_REQUEST",{message:"user already has a password"})}),tn=u("/delete-user",{method:"POST",body:F.z.object({password:F.z.string()}),use:[b]},async e=>{let{password:o}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password);if(!n||!n.password)throw new V.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,o))throw new V.APIError("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),te(e),e.json(null)}),rn=u("/change-email",{method:"POST",query:F.z.object({currentURL:F.z.string().optional()}).optional(),body:F.z.object({newEmail:F.z.string().email(),callbackURL:F.z.string().optional()}),use:[b]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new V.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new V.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new V.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new V.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await le(e.context.secret,e.context.session.user.email,e.body.newEmail),t=`${e.context.baseURL}/verify-email?token=${r}&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:t,token:r},e.request),e.json({user:null,status:!0})});var Ue=require("zod");var yt=require("better-call");var on=u("/list-accounts",{method:"GET",use:[b]},async e=>{let o=e.context.session,r=await e.context.internalAdapter.findAccounts(o.user.id);return e.json(r.map(t=>({id:t.id,provider:t.providerId})))}),nn=u("/link-social",{method:"POST",requireHeaders:!0,query:Ue.z.object({currentURL:Ue.z.string().optional()}).optional(),body:Ue.z.object({callbackURL:Ue.z.string().optional(),provider:Ue.z.enum(tt)}),use:[b]},async e=>{let o=e.context.session;if((await e.context.internalAdapter.findAccounts(o.user.id)).find(a=>a.providerId===e.body.provider))throw new yt.APIError("BAD_REQUEST",{message:"Social Account is already linked."});let n=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!n)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new yt.APIError("NOT_FOUND",{message:"Provider not found"});let i=await Oe(e,{userId:o.user.id,email:o.user.email}),s=await n.createAuthorizationURL({state:i.state,codeVerifier:i.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${n.id}`});return e.json({url:s.toString(),redirect:!0})});var Ur=(e,o)=>{let r={};for(let[t,n]of Object.entries(e))r[t]=i=>n({...i,context:{...o,...i.context}}),r[t].path=n.path,r[t].method=n.method,r[t].options=n.options,r[t].headers=n.headers;return r};function it(e){let o=e;return{newRole(r){return an(r)}}}function an(e){return{statements:e,authorize(o,r){for(let[t,n]of Object.entries(o)){let i=e[t];return i?(r==="OR"?n.some(a=>i.includes(a)):n.every(a=>i.includes(a)))?{success:!0}:{success:!1,error:`Unauthorized to access resource "${t}"`}:{success:!1,error:`You are not allowed to access resource: ${t}`}}return{success:!1,error:"Not authorized"}}}}var dn={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},bt=it(dn),cn=bt.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),un=bt.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),ln=bt.newRole({organization:[],member:[],invitation:[]}),Tr={admin:cn,owner:un,member:ln};var _=(e,o)=>{let r=e.adapter;return{findOrganizationBySlug:async t=>await r.findOne({model:"organization",where:[{field:"slug",value:t}]}),createOrganization:async t=>{let n=await r.create({model:"organization",data:{...t.organization,metadata:t.organization.metadata?JSON.stringify(t.organization.metadata):void 0}}),i=await r.create({model:"member",data:{id:x(),organizationId:n.id,userId:t.user.id,createdAt:new Date,role:o?.creatorRole||"owner"}});return{...n,metadata:n.metadata?JSON.parse(n.metadata):void 0,members:[{...i,user:{id:t.user.id,name:t.user.name,email:t.user.email,image:t.user.image}}]}},findMemberByEmail:async t=>{let n=await r.findOne({model:e.tables.user.modelName,where:[{field:"email",value:t.email}]});if(!n)return null;let i=await r.findOne({model:"member",where:[{field:"organizationId",value:t.organizationId},{field:"userId",value:n.id}]});return i?{...i,user:{id:n.id,name:n.name,email:n.email,image:n.image}}:null},findMemberByOrgId:async t=>{let[n,i]=await Promise.all([await r.findOne({model:"member",where:[{field:"userId",value:t.userId},{field:"organizationId",value:t.organizationId}]}),await r.findOne({model:e.tables.user.modelName,where:[{field:"id",value:t.userId}]})]);return!i||!n?null:{...n,user:{id:i.id,name:i.name,email:i.email,image:i.image}}},findMemberById:async t=>{let n=await r.findOne({model:"member",where:[{field:"id",value:t}]});if(!n)return null;let i=await r.findOne({model:e.tables.user.modelName,where:[{field:"id",value:n.userId}]});return i?{...n,user:{id:i.id,name:i.name,email:i.email,image:i.image}}:null},createMember:async t=>await r.create({model:"member",data:t}),updateMember:async(t,n)=>await r.update({model:"member",where:[{field:"id",value:t}],update:{role:n}}),deleteMember:async t=>await r.delete({model:"member",where:[{field:"id",value:t}]}),updateOrganization:async(t,n)=>await r.update({model:"organization",where:[{field:"id",value:t}],update:n}),deleteOrganization:async t=>(await r.delete({model:"member",where:[{field:"organizationId",value:t}]}),await r.delete({model:"invitation",where:[{field:"organizationId",value:t}]}),await r.delete({model:"organization",where:[{field:"id",value:t}]}),t),setActiveOrganization:async(t,n)=>await r.update({model:e.tables.session.modelName,where:[{field:"id",value:t}],update:{activeOrganizationId:n}}),findOrganizationById:async t=>await r.findOne({model:"organization",where:[{field:"id",value:t}]}),findFullOrganization:async t=>{let[n,i,s]=await Promise.all([r.findOne({model:"organization",where:[{field:"id",value:t}]}),r.findMany({model:"invitation",where:[{field:"organizationId",value:t}]}),r.findMany({model:"member",where:[{field:"organizationId",value:t}]})]);if(!n)return null;let a=s.map(m=>m.userId),d=await r.findMany({model:e.tables.user.modelName,where:[{field:"id",value:a,operator:"in"}]}),c=new Map(d.map(m=>[m.id,m])),l=s.map(m=>{let f=c.get(m.userId);if(!f)throw new X("Unexpected error: User not found for member");return{...m,user:{id:f.id,name:f.name,email:f.email,image:f.image}}});return{...n,invitations:i,members:l}},listOrganizations:async t=>{let n=await r.findMany({model:"member",where:[{field:"userId",value:t}]});if(!n||n.length===0)return[];let i=n.map(a=>a.organizationId);return await r.findMany({model:"organization",where:[{field:"id",value:i,operator:"in"}]})},createInvitation:async({invitation:t,user:n})=>{let s=R(o?.invitationExpiresIn||1728e5);return await r.create({model:"invitation",data:{id:x(),email:t.email,role:t.role,organizationId:t.organizationId,status:"pending",expiresAt:s,inviterId:n.id}})},findInvitationById:async t=>await r.findOne({model:"invitation",where:[{field:"id",value:t}]}),findPendingInvitation:async t=>(await r.findMany({model:"invitation",where:[{field:"email",value:t.email},{field:"organizationId",value:t.organizationId},{field:"status",value:"pending"}]})).filter(i=>new Date(i.expiresAt)>new Date),updateInvitation:async t=>await r.update({model:"invitation",where:[{field:"id",value:t.invitationId}],update:{status:t.status}})}};var Qd=require("better-call");var L=P(async e=>({})),D=P({use:[b]},async e=>({session:e.context.session}));var q=require("zod");var E=require("zod"),Sr=E.z.string(),mn=E.z.enum(["pending","accepted","rejected","canceled"]).default("pending"),Zd=E.z.object({id:E.z.string(),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()}),Yd=E.z.object({id:E.z.string(),organizationId:E.z.string(),userId:E.z.string(),role:Sr,createdAt:E.z.date()}),Xd=E.z.object({id:E.z.string(),organizationId:E.z.string(),email:E.z.string(),role:Sr,status:mn,inviterId:E.z.string(),expiresAt:E.z.date()});var S=require("better-call"),Pr=e=>u("/organization/invite-member",{method:"POST",use:[L,D],body:q.z.object({email:q.z.string(),role:q.z.string(),organizationId:q.z.string().optional(),resend:q.z.boolean().optional()})},async o=>{if(!o.context.orgOptions.sendInvitationEmail)throw o.context.logger.warn("Invitation email is not enabled. Pass `sendInvitationEmail` to the plugin options to enable it."),new S.APIError("BAD_REQUEST",{message:"Invitation email is not enabled"});let r=o.context.session,t=o.body.organizationId||r.session.activeOrganizationId;if(!t)throw new S.APIError("BAD_REQUEST",{message:"Organization not found"});let n=_(o.context,o.context.orgOptions),i=await n.findMemberByOrgId({userId:r.user.id,organizationId:t});if(!i)throw new S.APIError("BAD_REQUEST",{message:"Member not found!"});let s=o.context.roles[i.role];if(!s)throw new S.APIError("BAD_REQUEST",{message:"Role not found!"});if(s.authorize({invitation:["create"]}).error)throw new S.APIError("FORBIDDEN",{message:"You are not allowed to invite members"});if(await n.findMemberByEmail({email:o.body.email,organizationId:t}))throw new S.APIError("BAD_REQUEST",{message:"User is already a member of this organization"});if((await n.findPendingInvitation({email:o.body.email,organizationId:t})).length&&!o.body.resend)throw new S.APIError("BAD_REQUEST",{message:"User is already invited to this organization"});let l=await n.createInvitation({invitation:{role:o.body.role,email:o.body.email,organizationId:t},user:r.user}),m=await n.findOrganizationById(t);if(!m)throw new S.APIError("BAD_REQUEST",{message:"Organization not found"});return await o.context.orgOptions.sendInvitationEmail?.({id:l.id,role:l.role,email:l.email,organization:m,inviter:{...i,user:r.user}},o.request),o.json(l)}),_r=u("/organization/accept-invitation",{method:"POST",body:q.z.object({invitationId:q.z.string()}),use:[L,D]},async e=>{let o=e.context.session,r=_(e.context,e.context.orgOptions),t=await r.findInvitationById(e.body.invitationId);if(!t||t.expiresAt<new Date||t.status!=="pending")throw new S.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(t.email!==o.user.email)throw new S.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let n=await r.updateInvitation({invitationId:e.body.invitationId,status:"accepted"}),i=await r.createMember({id:x(),organizationId:t.organizationId,userId:o.user.id,role:t.role,createdAt:new Date});return await r.setActiveOrganization(o.session.id,t.organizationId),n?e.json({invitation:n,member:i}):e.json(null,{status:400,body:{message:"Invitation not found!"}})}),Cr=u("/organization/reject-invitation",{method:"POST",body:q.z.object({invitationId:q.z.string()}),use:[L,D]},async e=>{let o=e.context.session,r=_(e.context,e.context.orgOptions),t=await r.findInvitationById(e.body.invitationId);if(!t||t.expiresAt<new Date||t.status!=="pending")throw new S.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(t.email!==o.user.email)throw new S.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let n=await r.updateInvitation({invitationId:e.body.invitationId,status:"rejected"});return e.json({invitation:n,member:null})}),zr=u("/organization/cancel-invitation",{method:"POST",body:q.z.object({invitationId:q.z.string()}),use:[L,D]},async e=>{let o=e.context.session,r=_(e.context,e.context.orgOptions),t=await r.findInvitationById(e.body.invitationId);if(!t)throw new S.APIError("BAD_REQUEST",{message:"Invitation not found!"});let n=await r.findMemberByOrgId({userId:o.user.id,organizationId:t.organizationId});if(!n)throw new S.APIError("BAD_REQUEST",{message:"Member not found!"});if(e.context.roles[n.role].authorize({invitation:["cancel"]}).error)throw new S.APIError("FORBIDDEN",{message:"You are not allowed to cancel this invitation"});let s=await r.updateInvitation({invitationId:e.body.invitationId,status:"canceled"});return e.json(s)}),xr=u("/organization/get-invitation",{method:"GET",use:[L],requireHeaders:!0,query:q.z.object({id:q.z.string()})},async e=>{let o=await z(e);if(!o)throw new S.APIError("UNAUTHORIZED",{message:"Not authenticated"});let r=_(e.context,e.context.orgOptions),t=await r.findInvitationById(e.query.id);if(!t||t.status!=="pending"||t.expiresAt<new Date)throw new S.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(t.email!==o.user.email)throw new S.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let n=await r.findOrganizationById(t.organizationId);if(!n)throw new S.APIError("BAD_REQUEST",{message:"Organization not found"});let i=await r.findMemberByOrgId({userId:t.inviterId,organizationId:t.organizationId});if(!i)throw new S.APIError("BAD_REQUEST",{message:"Inviter is no longer a member of the organization"});return e.json({...t,organizationName:n.name,organizationSlug:n.slug,inviterEmail:i.user.email})});var me=require("zod");var Te=require("better-call"),Lr=u("/organization/remove-member",{method:"POST",body:me.z.object({memberIdOrEmail:me.z.string(),organizationId:me.z.string().optional()}),use:[L,D]},async e=>{let o=e.context.session,r=e.body.organizationId||o.session.activeOrganizationId;if(!r)return e.json(null,{status:400,body:{message:"No active organization found!"}});let t=_(e.context,e.context.orgOptions),n=await t.findMemberByOrgId({userId:o.user.id,organizationId:r});if(!n)throw new Te.APIError("BAD_REQUEST",{message:"Member not found!"});let i=e.context.roles[n.role];if(!i)throw new Te.APIError("BAD_REQUEST",{message:"Role not found!"});let s=o.user.email===e.body.memberIdOrEmail||n.id===e.body.memberIdOrEmail;if(s&&n.role===(e.context.orgOptions?.creatorRole||"owner"))throw new Te.APIError("BAD_REQUEST",{message:"You cannot leave the organization as the owner"});if(!(s||i.authorize({member:["delete"]}).success))throw new Te.APIError("UNAUTHORIZED",{message:"You are not allowed to delete this member"});let c=null;if(e.body.memberIdOrEmail.includes("@")?c=await t.findMemberByEmail({email:e.body.memberIdOrEmail,organizationId:r}):c=await t.findMemberById(e.body.memberIdOrEmail),c?.organizationId!==r)throw new Te.APIError("BAD_REQUEST",{message:"Member not found!"});return await t.deleteMember(c.id),o.user.id===c.userId&&o.session.activeOrganizationId===c.organizationId&&await t.setActiveOrganization(o.session.id,null),e.json({member:c})}),Br=e=>u("/organization/update-member-role",{method:"POST",body:me.z.object({role:me.z.string(),memberId:me.z.string(),organizationId:me.z.string().optional()}),use:[L,D]},async o=>{let r=o.context.session,t=o.body.organizationId||r.session.activeOrganizationId;if(!t)return o.json(null,{status:400,body:{message:"No active organization found!"}});let n=_(o.context,o.context.orgOptions),i=await n.findMemberByOrgId({userId:r.user.id,organizationId:t});if(!i)return o.json(null,{status:400,body:{message:"Member not found!"}});let s=o.context.roles[i.role];if(!s)return o.json(null,{status:400,body:{message:"Role not found!"}});if(s.authorize({member:["update"]}).error||o.body.role==="owner"&&i.role!=="owner")return o.json(null,{body:{message:"You are not allowed to update this member"},status:403});let d=await n.updateMember(o.body.memberId,o.body.role);return d?o.json(d):o.json(null,{status:400,body:{message:"Member not found!"}})}),Dr=u("/organization/get-active-member",{method:"GET",use:[L,D]},async e=>{let o=e.context.session,r=o.session.activeOrganizationId;if(!r)return e.json(null,{status:400,body:{message:"No active organization found!"}});let n=await _(e.context,e.context.orgOptions).findMemberByOrgId({userId:o.user.id,organizationId:r});return n?e.json(n):e.json(null,{status:400,body:{message:"Member not found!"}})});var U=require("zod");var pe=require("better-call"),Nr=u("/organization/create",{method:"POST",body:U.z.object({name:U.z.string(),slug:U.z.string(),userId:U.z.string().optional(),logo:U.z.string().optional(),metadata:U.z.record(U.z.string(),U.z.any()).optional()}),use:[L,D]},async e=>{let o=e.context.session.user;if(!o)return e.json(null,{status:401});let r=e.context.orgOptions;if(!(typeof r?.allowUserToCreateOrganization=="function"?await r.allowUserToCreateOrganization(o):r?.allowUserToCreateOrganization===void 0?!0:r.allowUserToCreateOrganization))throw new pe.APIError("FORBIDDEN",{message:"You are not allowed to create an organization"});let n=_(e.context,r),i=await n.listOrganizations(o.id);if(typeof r.organizationLimit=="number"?i.length>=r.organizationLimit:typeof r.organizationLimit=="function"?await r.organizationLimit(o):!1)throw new pe.APIError("FORBIDDEN",{message:"You have reached the organization limit"});if(await n.findOrganizationBySlug(e.body.slug))throw new pe.APIError("BAD_REQUEST",{message:"Organization with this slug already exists"});let d=await n.createOrganization({organization:{id:x(),slug:e.body.slug,name:e.body.name,logo:e.body.logo,createdAt:new Date,metadata:e.body.metadata},user:o});return await n.setActiveOrganization(e.context.session.session.id,d.id),e.json(d)}),jr=u("/organization/update",{method:"POST",body:U.z.object({data:U.z.object({name:U.z.string().optional(),slug:U.z.string().optional(),logo:U.z.string().optional()}).partial(),organizationId:U.z.string().optional()}),requireHeaders:!0,use:[L]},async e=>{let o=await e.context.getSession(e);if(!o)throw new pe.APIError("UNAUTHORIZED",{message:"User not found"});let r=e.body.organizationId||o.session.activeOrganizationId;if(!r)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let t=_(e.context,e.context.orgOptions),n=await t.findMemberByOrgId({userId:o.user.id,organizationId:r});if(!n)return e.json(null,{status:400,body:{message:"User is not a member of this organization!"}});let i=e.context.roles[n.role];if(!i)return e.json(null,{status:400,body:{message:"Role not found!"}});if(i.authorize({organization:["update"]}).error)return e.json(null,{body:{message:"You are not allowed to update this organization"},status:403});let a=await t.updateOrganization(r,e.body.data);return e.json(a)}),Vr=u("/organization/delete",{method:"POST",body:U.z.object({organizationId:U.z.string()}),requireHeaders:!0,use:[L]},async e=>{let o=await e.context.getSession(e);if(!o)return e.json(null,{status:401});let r=e.body.organizationId;if(!r)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let t=_(e.context,e.context.orgOptions),n=await t.findMemberByOrgId({userId:o.user.id,organizationId:r});if(!n)return e.json(null,{status:400,body:{message:"User is not a member of this organization!"}});let i=e.context.roles[n.role];if(!i)return e.json(null,{status:400,body:{message:"Role not found!"}});if(i.authorize({organization:["delete"]}).error)throw new pe.APIError("FORBIDDEN",{message:"You are not allowed to delete this organization"});return r===o.session.activeOrganizationId&&await t.setActiveOrganization(o.session.id,null),await t.deleteOrganization(r),e.json(r)}),Fr=u("/organization/get-full-organization",{method:"GET",query:U.z.optional(U.z.object({organizationId:U.z.string().optional()})),requireHeaders:!0,use:[L,D]},async e=>{let o=e.context.session,r=e.query?.organizationId||o.session.activeOrganizationId;if(!r)return e.json(null,{status:200});let n=await _(e.context,e.context.orgOptions).findFullOrganization(r);if(!n)throw new pe.APIError("BAD_REQUEST",{message:"Organization not found"});return e.json(n)}),qr=u("/organization/set-active",{method:"POST",body:U.z.object({organizationId:U.z.string().nullable().optional()}),use:[D,L]},async e=>{let o=_(e.context,e.context.orgOptions),r=e.context.session,t=e.body.organizationId;if(t===null)return r.session.activeOrganizationId&&await o.setActiveOrganization(r.session.id,null),e.json(null);if(!t){let s=r.session.activeOrganizationId;if(!s)return e.json(null);t=s}if(!await o.findMemberByOrgId({userId:r.user.id,organizationId:t}))throw await o.setActiveOrganization(r.session.id,null),new pe.APIError("FORBIDDEN",{message:"You are not a member of this organization"});await o.setActiveOrganization(r.session.id,t);let i=await o.findFullOrganization(t);return e.json(i)}),Mr=u("/organization/list",{method:"GET",use:[L,D]},async e=>{let r=await _(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(r)});var pn=it({name:["action"]}),Ic=pn.newRole({name:["action"]}),fn=e=>{let o={createOrganization:Nr,updateOrganization:jr,deleteOrganization:Vr,setActiveOrganization:qr,getFullOrganization:Fr,listOrganization:Mr,createInvitation:Pr(e),cancelInvitation:zr,acceptInvitation:_r,getInvitation:xr,rejectInvitation:Cr,removeMember:Lr,updateMemberRole:Br(e),getActiveMember:Dr},r={...Tr,...e?.roles};return{id:"organization",endpoints:{...Ur(o,{orgOptions:e||{},roles:r,getSession:async n=>await z(n)}),hasPermission:u("/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:[D]},async n=>{if(!n.context.session.session.activeOrganizationId)throw new At.APIError("BAD_REQUEST",{message:"No active organization"});let s=await _(n.context).findMemberByOrgId({userId:n.context.session.user.id,organizationId:n.context.session.session.activeOrganizationId||""});if(!s)throw new At.APIError("UNAUTHORIZED",{message:"You are not a member of this organization"});let d=r[s.role].authorize(n.body.permission);return d.error?n.json({error:d.error,success:!1},{status:403}):n.json({error:null,success:!0})})},schema:{session:{fields:{activeOrganizationId:{type:"string",required:!1,fieldName:e?.schema?.session?.fields?.activeOrganizationId}}},organization:{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:{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},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:{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 kt=Dt(require("uncrypto"),1);function gn(e){return e.toString(2).padStart(8,"0")}function hn(e){return[...e].map(o=>gn(o)).join("")}function $r(e){return parseInt(hn(e),2)}function wn(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let o=(e-1).toString(2).length,r=o%8,t=new Uint8Array(Math.ceil(o/8));kt.default.getRandomValues(t),r!==0&&(t[0]&=(1<<r)-1);let n=$r(t);for(;n>=e;)kt.default.getRandomValues(t),r!==0&&(t[0]&=(1<<r)-1),n=$r(t);return n}function M(e,o){let r="";for(let t=0;t<e;t++)r+=o[wn(o.length)];return r}function $(...e){let o=new Set(e),r="";for(let t of o)t==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":t==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":t==="0-9"?r+="0123456789":r+=t;return r}var $e=require("zod");var vt=require("@noble/ciphers/chacha"),Pe=require("@noble/ciphers/utils"),Rt=require("@noble/ciphers/webcrypto"),Et=require("oslo/crypto"),Ot=Dt(require("uncrypto"),1);var Hr=require("oslo/encoding");var yn=require("@noble/hashes/scrypt"),bn=require("uncrypto");async function Ve(e,o){let r=new TextEncoder,t={name:"HMAC",hash:"SHA-256"},n=await Ot.default.subtle.importKey("raw",r.encode(e),t,!1,["sign","verify"]),i=await Ot.default.subtle.sign(t.name,n,r.encode(o));return btoa(String.fromCharCode(...new Uint8Array(i)))}var ae=async({key:e,data:o})=>{let r=await(0,Et.sha256)(new TextEncoder().encode(e)),t=(0,Pe.utf8ToBytes)(o),n=(0,Rt.managedNonce)(vt.xchacha20poly1305)(new Uint8Array(r));return(0,Pe.bytesToHex)(n.encrypt(t))},fe=async({key:e,data:o})=>{let r=await(0,Et.sha256)(new TextEncoder().encode(e)),t=(0,Pe.hexToBytes)(o),n=(0,Rt.managedNonce)(vt.xchacha20poly1305)(new Uint8Array(r));return new TextDecoder().decode(n.decrypt(t))};var ne=require("zod");var _e=require("better-call");var st="two_factor";var at="trust_device";var It=require("zod");var ye=P({body:It.z.object({trustDevice:It.z.boolean().optional()})},async e=>{let o=await z(e);if(!o){let r=e.context.createAuthCookie(st),t=await e.getSignedCookie(r.name,e.context.secret);if(!t)throw new _e.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let n=await e.context.internalAdapter.findUserById(t);if(!n)throw new _e.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let i=await e.context.internalAdapter.createSession(t,e.request);if(!i)throw new _e.APIError("INTERNAL_SERVER_ERROR",{message:"failed to create session"});return{valid:async()=>{if(await w(e,{session:i,user:n}),e.body.trustDevice){let s=e.context.createAuthCookie(at,{maxAge:2592e3}),a=await Ve(e.context.secret,`${n.id}!${i.id}`);await e.setSignedCookie(s.name,`${a}!${i.id}`,e.context.secret,s.attributes)}return e.json({session:i,user:n})},invalid:async()=>{throw new _e.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:{id:i.id,userId:i.userId,expiresAt:i.expiresAt,user:n}}}return{valid:async()=>e.json({session:o,user:o.user}),invalid:async()=>{throw new _e.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:o}});var Ce=require("better-call");function An(e){return Array.from({length:e?.amount??10}).fill(null).map(()=>M(e?.length??10,$("a-z","0-9"))).map(o=>`${o.slice(0,5)}-${o.slice(5)}`)}async function Ut(e,o){let r=e,t=o?.customBackupCodesGenerate?o.customBackupCodesGenerate():An(),n=await ae({data:JSON.stringify(t),key:r});return{backupCodes:t,encryptedBackupCodes:n}}async function kn(e,o){let r=await Qr(e.backupCodes,o);return r?{status:r.includes(e.code),updated:r.filter(t=>t!==e.code)}:{status:!1,updated:null}}async function Qr(e,o){let r=Buffer.from(await fe({key:o,data:e})).toString("utf-8"),t=JSON.parse(r),n=ne.z.array(ne.z.string()).safeParse(t);return n.success?n.data:null}var Wr=(e,o)=>({id:"backup_code",endpoints:{verifyBackupCode:u("/two-factor/verify-backup-code",{method:"POST",body:ne.z.object({code:ne.z.string(),disableSession:ne.z.boolean().optional()}),use:[ye]},async r=>{let t=r.context.session.user,n=await r.context.adapter.findOne({model:o,where:[{field:"userId",value:t.id}]});if(!n)throw new Ce.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let i=await kn({backupCodes:n.backupCodes,code:r.body.code},r.context.secret);if(!i.status)throw new Ce.APIError("UNAUTHORIZED",{message:"Invalid backup code"});let s=await ae({key:r.context.secret,data:JSON.stringify(i.updated)});return await r.context.adapter.update({model:o,update:{backupCodes:s},where:[{field:"userId",value:t.id}]}),r.body.disableSession||await w(r,{session:r.context.session,user:t}),r.json({user:t,session:r.context.session})}),generateBackupCodes:u("/two-factor/generate-backup-codes",{method:"POST",body:ne.z.object({password:ne.z.string()}),use:[b]},async r=>{let t=r.context.session.user;if(!t.twoFactorEnabled)throw new Ce.APIError("BAD_REQUEST",{message:"Two factor isn't enabled"});await r.context.password.checkPassword(t.id,r);let n=await Ut(r.context.secret,e);return await r.context.adapter.update({model:o,update:{backupCodes:n.encryptedBackupCodes},where:[{field:"userId",value:r.context.session.user.id}]}),r.json({status:!0,backupCodes:n.backupCodes})}),viewBackupCodes:u("/two-factor/view-backup-codes",{method:"GET",body:ne.z.object({userId:ne.z.string()}),metadata:{SERVER_ONLY:!0}},async r=>{let t=await r.context.adapter.findOne({model:o,where:[{field:"userId",value:r.body.userId}]});if(!t)throw new Ce.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let n=await Qr(t.backupCodes,r.context.secret);if(!n)throw new Ce.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});return r.json({status:!0,backupCodes:n})})}});var Fe=require("better-call"),Gr=require("oslo/otp"),Tt=require("zod");var Kr=require("oslo"),Jr=(e,o)=>{let r={...e,period:new Kr.TimeSpan(e?.period||3,"m")},t=new Gr.TOTPController({digits:6,period:r.period}),n=u("/two-factor/send-otp",{method:"POST",use:[ye]},async s=>{if(!e||!e.sendOTP)throw s.context.logger.error("send otp isn't configured. Please configure the send otp function on otp options."),new Fe.APIError("BAD_REQUEST",{message:"otp isn't configured"});let a=s.context.session.user,d=await s.context.adapter.findOne({model:o,where:[{field:"userId",value:a.id}]});if(!d)throw new Fe.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});let c=await t.generate(Buffer.from(d.secret));return await e.sendOTP({user:a,otp:c},s.request),s.json({status:!0})}),i=u("/two-factor/verify-otp",{method:"POST",body:Tt.z.object({code:Tt.z.string()}),use:[ye]},async s=>{let a=s.context.session.user;if(!a.twoFactorEnabled)throw new Fe.APIError("BAD_REQUEST",{message:"two factor isn't enabled"});let d=await s.context.adapter.findOne({model:o,where:[{field:"userId",value:a.id}]});if(!d)throw new Fe.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});return await t.generate(Buffer.from(d.secret))===s.body.code?s.context.valid():s.context.invalid()});return{id:"otp",endpoints:{send2FaOTP:n,verifyOTP:i}}};var be=require("better-call"),Zr=require("oslo"),Me=require("oslo/otp"),qe=require("zod");var Yr=(e,o)=>{let r={...e,digits:6,period:new Zr.TimeSpan(e?.period||30,"s")},t=u("/totp/generate",{method:"POST",use:[b]},async s=>{if(!e)throw s.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new be.APIError("BAD_REQUEST",{message:"totp isn't configured"});let a=s.context.session.user,d=await s.context.adapter.findOne({model:o,where:[{field:"userId",value:a.id}]});if(!d)throw new be.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return{code:await new Me.TOTPController(r).generate(Buffer.from(d.secret))}}),n=u("/two-factor/get-totp-uri",{method:"POST",use:[b],body:qe.z.object({password:qe.z.string()})},async s=>{if(!e)throw s.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new be.APIError("BAD_REQUEST",{message:"totp isn't configured"});let a=s.context.session.user,d=await s.context.adapter.findOne({model:o,where:[{field:"userId",value:a.id}]});if(!d||!a.twoFactorEnabled)throw new be.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return await s.context.password.checkPassword(a.id,s),{totpURI:(0,Me.createTOTPKeyURI)(e.issuer||s.context.appName,a.email,Buffer.from(d.secret),r)}}),i=u("/two-factor/verify-totp",{method:"POST",body:qe.z.object({code:qe.z.string()}),use:[ye]},async s=>{if(!e)throw s.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new be.APIError("BAD_REQUEST",{message:"totp isn't configured"});let a=s.context.session.user,d=await s.context.adapter.findOne({model:o,where:[{field:"userId",value:a.id}]});if(!d)throw new be.APIError("BAD_REQUEST",{message:"totp isn't enabled"});let c=new Me.TOTPController(r),l=await fe({key:s.context.secret,data:d.secret}),m=Buffer.from(l);if(!await c.verify(s.body.code,m))return s.context.invalid();if(!a.twoFactorEnabled){let p=await s.context.internalAdapter.updateUser(a.id,{twoFactorEnabled:!0}),g=await s.context.internalAdapter.createSession(a.id,s.request);await w(s,{session:g,user:p})}return s.context.valid()});return{id:"totp",endpoints:{generateTOTP:t,viewTOTPURI:n,verifyTOTP:i}}};var On=require("better-call");async function St(e,o){let t=(await e.context.internalAdapter.findAccounts(o.userId))?.find(s=>s.providerId==="credential"),n=t?.password;return!t||!n?!1:await e.context.password.verify(n,o.password)}var Pt=require("better-call"),to=require("oslo/otp"),ro=require("oslo");var Xr=require("better-call"),ze=async e=>{let o=e.context.returned;return o?o instanceof Response?o.status!==200?null:await o.clone().json():o instanceof Xr.APIError?null:o:null};var eo={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 vn=(e={redirect:!0,twoFactorPage:"/"})=>({id:"two-factor",$InferServerPlugin:{},atomListeners:[{matcher:o=>o.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(o){o.data?.twoFactorRedirect&&(e.redirect||e.twoFactorPage)&&typeof window<"u"&&(window.location.href=e.twoFactorPage)}}}]});var Rn=e=>{let o={twoFactorTable:"twoFactor"},r=Yr({issuer:e?.issuer,...e?.totpOptions},o.twoFactorTable),t=Wr({...e?.backupCodeOptions},o.twoFactorTable),n=Jr({...e?.otpOptions},o.twoFactorTable);return{id:"two-factor",endpoints:{...r.endpoints,...n.endpoints,...t.endpoints,enableTwoFactor:u("/two-factor/enable",{method:"POST",body:$e.z.object({password:$e.z.string().min(8)}),use:[b]},async i=>{let s=i.context.session.user,{password:a}=i.body;if(!await St(i,{password:a,userId:s.id}))throw new Pt.APIError("BAD_REQUEST",{message:"Invalid password"});let c=M(16,$("a-z","0-9","-")),l=await ae({key:i.context.secret,data:c}),m=await Ut(i.context.secret,e?.backupCodeOptions);if(e?.skipVerificationOnEnable){let p=await i.context.internalAdapter.updateUser(s.id,{twoFactorEnabled:!0}),g=await i.context.internalAdapter.createSession(p.id,i.request);await w(i,{session:g,user:s})}await i.context.adapter.deleteMany({model:o.twoFactorTable,where:[{field:"userId",value:s.id}]}),await i.context.adapter.create({model:o.twoFactorTable,data:{id:i.context.uuid(),secret:l,backupCodes:m.encryptedBackupCodes,userId:s.id}});let f=(0,to.createTOTPKeyURI)(e?.issuer||"BetterAuth",s.email,Buffer.from(c),{digits:e?.totpOptions?.digits||6,period:new ro.TimeSpan(e?.totpOptions?.period||30,"s")});return i.json({totpURI:f,backupCodes:m.backupCodes})}),disableTwoFactor:u("/two-factor/disable",{method:"POST",body:$e.z.object({password:$e.z.string().min(8)}),use:[b]},async i=>{let s=i.context.session.user,{password:a}=i.body;if(!await St(i,{password:a,userId:s.id}))throw new Pt.APIError("BAD_REQUEST",{message:"Invalid password"});return await i.context.internalAdapter.updateUser(s.id,{twoFactorEnabled:!1}),await i.context.adapter.delete({model:o.twoFactorTable,where:[{field:"userId",value:s.id}]}),i.json({status:!0})})},options:e,hooks:{after:[{matcher(i){return i.path==="/sign-in/email"||i.path==="/sign-in/username"},handler:P(async i=>{let s=await ze(i);if(!s||!s.user.twoFactorEnabled)return;let a=i.context.createAuthCookie(at),d=await i.getSignedCookie(a.name,i.context.secret);if(d){let[m,f]=d.split("!"),p=await Ve(i.context.secret,`${s.user.id}!${f}`);if(m===p){let g=await Ve(i.context.secret,`${s.user.id}!${s.session.id}`);await i.setSignedCookie(a.name,`${g}!${s.session.id}`,i.context.secret,a.attributes);return}}te(i),await i.context.internalAdapter.deleteSession(s.session.id);let c=i.context.createAuthCookie(st,{maxAge:60*10});return await i.setSignedCookie(c.name,s.user.id,i.context.secret,c.attributes),{response:{twoFactorRedirect:!0},responseHeader:i.responseHeader}})}]},schema:K(eo,e?.schema),rateLimit:[{pathMatcher(i){return i.startsWith("/two-factor/")},window:10,max:3}]}};var ge=require("@simplewebauthn/server"),J=require("better-call");var ie=require("zod");var xe=require("@simplewebauthn/browser");var In=require("@better-fetch/fetch");var Nu=require("nanostores");var Iu=require("@better-fetch/fetch");var En=require("nanostores");var Tu=require("@better-fetch/fetch"),dt=require("nanostores"),_t=(e,o,r,t)=>{let n=(0,dt.atom)({data:null,error:null,isPending:!0,isRefetching:!1}),i=()=>{let a=typeof t=="function"?t({data:n.get().data,error:n.get().error,isPending:n.get().isPending}):t;return r(o,{...a,async onSuccess(d){n.set({data:d.data,error:null,isPending:!1,isRefetching:!1}),await a?.onSuccess?.(d)},async onError(d){n.set({error:d.error,data:null,isPending:!1,isRefetching:!1}),await a?.onError?.(d)},async onRequest(d){let c=n.get();n.set({isPending:c.data===null,data:c.data,error:null,isRefetching:!0}),await a?.onRequest?.(d)}})};e=Array.isArray(e)?e:[e];let s=!1;for(let a of e)a.subscribe(()=>{s?i():(0,dt.onMount)(n,()=>(i(),s=!0,()=>{n.off(),a.off()}))});return n};var oo=require("nanostores"),no=(e,{$listPasskeys:o})=>({signIn:{passkey:async(n,i)=>{let s=await e("/passkey/generate-authenticate-options",{method:"POST",body:{email:n?.email}});if(!s.data)return s;try{let a=await(0,xe.startAuthentication)(s.data,n?.autoFill||!1),d=await e("/passkey/verify-authentication",{body:{response:a},...n?.fetchOptions,...i,method:"POST"});if(!d.data)return d}catch{return{data:null,error:{message:"auth cancelled",status:400,statusText:"BAD_REQUEST"}}}}},passkey:{addPasskey:async(n,i)=>{let s=await e("/passkey/generate-register-options",{method:"GET"});if(!s.data)return s;try{let a=await(0,xe.startRegistration)(s.data),d=await e("/passkey/verify-registration",{...n?.fetchOptions,...i,body:{response:a,name:n?.name},method:"POST"});if(!d.data)return d;o.set(Math.random())}catch(a){return a instanceof xe.WebAuthnError?a.code==="ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED"?{data:null,error:{message:"previously registered",status:400,statusText:"BAD_REQUEST"}}:a.code==="ERROR_CEREMONY_ABORTED"?{data:null,error:{message:"registration cancelled",status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:a.message,status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:a instanceof Error?a.message:"unknown error",status:500,statusText:"INTERNAL_SERVER_ERROR"}}}}},$Infer:{}}),Un=()=>{let e=(0,oo.atom)();return{id:"passkey",$InferServerPlugin:{},getActions:o=>no(o,{$listPasskeys:e}),getAtoms(o){return{listPasskeys:_t(e,"/passkey/list-user-passkeys",o,{method:"GET"}),$listPasskeys:e}},pathMethods:{"/passkey/register":"POST","/passkey/authenticate":"POST"},atomListeners:[{matcher(o){return o==="/passkey/verify-registration"||o==="/passkey/delete-passkey"},signal:"_listPasskeys"}]}};var Tn=e=>{let o=ee.BETTER_AUTH_URL,r=e?.rpID||o?.replace("http://","").replace("https://","").split(":")[0]||"localhost";if(!r)throw new X("passkey rpID not found. Please provide a rpID in the options or set the BETTER_AUTH_URL environment variable.");let t={origin:null,...e,rpID:r,advanced:{webAuthnChallengeCookie:"better-auth-passkey",...e?.advanced}},n=new Date(Date.now()+1e3*60*5),i=new Date,s=Math.floor((n.getTime()-i.getTime())/1e3);return{id:"passkey",endpoints:{generatePasskeyRegistrationOptions:u("/passkey/generate-register-options",{method:"GET",use:[b],metadata:{client:!1}},async a=>{let d=a.context.session,c=await a.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}),l=new Uint8Array(Buffer.from(M(32,$("a-z","0-9")))),m;m=await(0,ge.generateRegistrationOptions)({rpName:t.rpName||a.context.appName,rpID:t.rpID,userID:l,userName:d.user.email||d.user.id,attestationType:"none",excludeCredentials:c.map(p=>({id:p.id,transports:p.transports?.split(",")})),authenticatorSelection:{residentKey:"preferred",userVerification:"preferred",authenticatorAttachment:"platform"}});let f=x();return await a.setSignedCookie(t.advanced.webAuthnChallengeCookie,f,a.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:s}),await a.context.internalAdapter.createVerificationValue({identifier:f,value:JSON.stringify({expectedChallenge:m.challenge,userData:{id:d.user.id}}),expiresAt:n}),a.json(m,{status:200})}),generatePasskeyAuthenticationOptions:u("/passkey/generate-authenticate-options",{method:"POST",body:ie.z.object({email:ie.z.string().optional()}).optional()},async a=>{let d=await z(a),c=[];d&&(c=await a.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}));let l=await(0,ge.generateAuthenticationOptions)({rpID:t.rpID,userVerification:"preferred",...c.length?{allowCredentials:c.map(p=>({id:p.id,transports:p.transports?.split(",")}))}:{}}),m={expectedChallenge:l.challenge,userData:{id:d?.user.id||""}},f=x();return await a.setSignedCookie(t.advanced.webAuthnChallengeCookie,f,a.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:s}),await a.context.internalAdapter.createVerificationValue({identifier:f,value:JSON.stringify(m),expiresAt:n}),a.json(l,{status:200})}),verifyPasskeyRegistration:u("/passkey/verify-registration",{method:"POST",body:ie.z.object({response:ie.z.any(),name:ie.z.string().optional()}),use:[b]},async a=>{let d=e?.origin||a.headers?.get("origin")||"";if(!d)return a.json(null,{status:400});let c=a.body.response,l=await a.getSignedCookie(t.advanced.webAuthnChallengeCookie,a.context.secret);if(!l)throw new J.APIError("BAD_REQUEST",{message:"Challenge not found"});let m=await a.context.internalAdapter.findVerificationValue(l);if(!m)return a.json(null,{status:400});let{expectedChallenge:f,userData:p}=JSON.parse(m.value);if(p.id!==a.context.session.user.id)throw new J.APIError("UNAUTHORIZED",{message:"You are not authorized to register this passkey"});try{let g=await(0,ge.verifyRegistrationResponse)({response:c,expectedChallenge:f,expectedOrigin:d,expectedRPID:e?.rpID}),{verified:v,registrationInfo:H}=g;if(!v||!H)return a.json(null,{status:400});let{credentialID:oe,credentialPublicKey:Y,counter:y,credentialDeviceType:C,credentialBackedUp:De}=H,lo=Buffer.from(Y).toString("base64"),mo=x(),po={name:a.body.name,userId:p.id,webauthnUserID:mo,id:oe,publicKey:lo,counter:y,deviceType:C,transports:c.response.transports.join(","),backedUp:De,createdAt:new Date},fo=await a.context.adapter.create({model:"passkey",data:po});return a.json(fo,{status:200})}catch(g){throw console.log(g),new J.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to verify registration"})}}),verifyPasskeyAuthentication:u("/passkey/verify-authentication",{method:"POST",body:ie.z.object({response:ie.z.any()})},async a=>{let d=e?.origin||a.headers?.get("origin")||"";if(!d)throw new J.APIError("BAD_REQUEST",{message:"origin missing"});let c=a.body.response,l=await a.getSignedCookie(t.advanced.webAuthnChallengeCookie,a.context.secret);if(!l)throw new J.APIError("BAD_REQUEST",{message:"Challenge not found"});let m=await a.context.internalAdapter.findVerificationValue(l);if(!m)throw new J.APIError("BAD_REQUEST",{message:"Challenge not found"});let{expectedChallenge:f}=JSON.parse(m.value),p=await a.context.adapter.findOne({model:"passkey",where:[{field:"id",value:c.id}]});if(!p)throw new J.APIError("UNAUTHORIZED",{message:"Passkey not found"});try{let g=await(0,ge.verifyAuthenticationResponse)({response:c,expectedChallenge:f,expectedOrigin:d,expectedRPID:t.rpID,authenticator:{credentialID:p.id,credentialPublicKey:new Uint8Array(Buffer.from(p.publicKey,"base64")),counter:p.counter,transports:p.transports?.split(",")}}),{verified:v}=g;if(!v)throw new J.APIError("UNAUTHORIZED",{message:"Authentication failed"});await a.context.adapter.update({model:"passkey",where:[{field:"id",value:p.id}],update:{counter:g.authenticationInfo.newCounter}});let H=await a.context.internalAdapter.createSession(p.userId,a.request);if(!H)throw new J.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});let oe=await a.context.internalAdapter.findUserById(p.userId);if(!oe)throw new J.APIError("INTERNAL_SERVER_ERROR",{message:"User not found"});return await w(a,{session:H,user:oe}),a.json({session:H},{status:200})}catch(g){throw a.context.logger.error("Failed to verify authentication",g),new J.APIError("BAD_REQUEST",{message:"Failed to verify authentication"})}}),listPasskeys:u("/passkey/list-user-passkeys",{method:"GET",use:[b]},async a=>{let d=await a.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:a.context.session.user.id}]});return a.json(d,{status:200})}),deletePasskey:u("/passkey/delete-passkey",{method:"POST",body:ie.z.object({id:ie.z.string()}),use:[b]},async a=>(await a.context.adapter.delete({model:"passkey",where:[{field:"id",value:a.body.id}]}),a.json(null,{status:200})))},schema:K(Sn,e?.schema)}},Sn={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 He=require("zod");var Qe=require("better-call"),Ct=()=>({id:"username",endpoints:{signInUsername:u("/sign-in/username",{method:"POST",body:He.z.object({username:He.z.string(),password:He.z.string(),rememberMe:He.z.boolean().optional()})},async e=>{let o=await e.context.adapter.findOne({model:e.context.tables.user.modelName,where:[{field:"username",value:e.body.username}]});if(!o)throw await e.context.password.hash(e.body.password),e.context.logger.error("User not found",{username:Ct}),new Qe.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let r=await e.context.adapter.findOne({model:"account",where:[{field:e.context.tables.account.fields.userId.fieldName||"userId",value:o.id},{field:e.context.tables.account.fields.providerId.fieldName||"providerId",value:"credential"}]});if(!r)throw new Qe.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let t=r?.password;if(!t)throw e.context.logger.error("Password not found",{username:Ct}),new Qe.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(t,e.body.password))throw e.context.logger.error("Invalid password"),new Qe.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let i=await e.context.internalAdapter.createSession(o.id,e.request,e.body.rememberMe===!1);return i?(await e.setSignedCookie(e.context.authCookies.sessionToken.name,i.id,e.context.secret,e.body.rememberMe===!1?{...e.context.authCookies.sessionToken.options,maxAge:void 0}:e.context.authCookies.sessionToken.options),e.json({user:o,session:i})):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 io=require("better-call"),Pn=()=>({id:"bearer",hooks:{before:[{matcher(e){return!!(e.request?.headers.get("authorization")||e.headers?.get("authorization"))},handler:async e=>{let o=e.request?.headers.get("authorization")?.replace("Bearer ","")||e.headers?.get("authorization")?.replace("Bearer ","");if(!o)return;let r="";return o.includes(".")?r=o:r=await(0,io.serializeSigned)("",o,e.context.secret),e.request&&e.request.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${r.replace("=","")}`),e.headers&&e.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${r.replace("=","")}`),{context:e}}}]}});var Ae=require("zod");var zt=require("better-call");var _n=e=>({id:"magic-link",endpoints:{signInMagicLink:u("/sign-in/magic-link",{method:"POST",requireHeaders:!0,body:Ae.z.object({email:Ae.z.string().email(),callbackURL:Ae.z.string().optional()})},async o=>{let{email:r}=o.body;if(e.disableSignUp&&!await o.context.internalAdapter.findUserByEmail(r))throw new zt.APIError("BAD_REQUEST",{message:"User not found"});let t=M(32,$("a-z","A-Z"));await o.context.internalAdapter.createVerificationValue({identifier:t,value:r,expiresAt:new Date(Date.now()+(e.expiresIn||60*5)*1e3)});let n=`${o.context.baseURL}/magic-link/verify?token=${t}&callbackURL=${o.body.callbackURL||"/"}`;try{await e.sendMagicLink({email:r,url:n,token:t},o.request)}catch(i){throw o.context.logger.error("Failed to send magic link",i),new zt.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to send magic link"})}return o.json({status:!0})}),magicLinkVerify:u("/magic-link/verify",{method:"GET",query:Ae.z.object({token:Ae.z.string(),callbackURL:Ae.z.string().optional()}),requireHeaders:!0},async o=>{let{token:r,callbackURL:t}=o.query,n=t?.startsWith("http")?t:t?`${o.context.options.baseURL}${t}`:o.context.options.baseURL,i=await o.context.internalAdapter.findVerificationValue(r);if(!i)throw o.redirect(`${n}?error=INVALID_TOKEN`);if(i.expiresAt<new Date)throw await o.context.internalAdapter.deleteVerificationValue(i.id),o.redirect(`${n}?error=EXPIRED_TOKEN`);await o.context.internalAdapter.deleteVerificationValue(i.id);let s=i.value,a=await o.context.internalAdapter.findUserByEmail(s),d=a?.user.id||"";if(!a){if(e.disableSignUp)throw o.redirect(`${n}?error=USER_NOT_FOUND`);if(d=(await o.context.internalAdapter.createUser({email:s,emailVerified:!0,name:s})).id,!d)throw o.redirect(`${n}?error=USER_NOT_CREATED`)}let c=await o.context.internalAdapter.createSession(d,o.headers);if(!c)throw o.redirect(`${n}?error=SESSION_NOT_CREATED`);if(await w(o,{session:c,user:a?.user}),!t)return o.json({session:c,user:a?.user});throw o.redirect(t)})},rateLimit:[{pathMatcher(o){return o.startsWith("/sign-in/magic-link")||o.startsWith("/magic-link/verify")},window:e.rateLimit?.window||60,max:e.rateLimit?.max||5}]});var Z=require("zod");var N=require("better-call");function Cn(e){return M(e,$("0-9"))}var zn=e=>{let o={expiresIn:e?.expiresIn||300,otpLength:e?.otpLength||6,...e,phoneNumber:"phoneNumber",phoneNumberVerified:"phoneNumberVerified",code:"code",createdAt:"createdAt"};return{id:"phone-number",endpoints:{signInPhoneNumber:u("/sign-in/phone-number",{method:"POST",body:Z.z.object({phoneNumber:Z.z.string(),password:Z.z.string(),rememberMe:Z.z.boolean().optional()})},async r=>{let{password:t,phoneNumber:n}=r.body;if(o.phoneNumberValidator&&!await o.phoneNumberValidator(r.body.phoneNumber))throw new N.APIError("BAD_REQUEST",{message:"Invalid phone number!"});let i=await r.context.adapter.findOne({model:"user",where:[{field:"phoneNumber",value:n}]});if(!i)throw new N.APIError("UNAUTHORIZED",{message:"Invalid phone number or password"});let a=(await r.context.internalAdapter.findAccountByUserId(i.id)).find(m=>m.providerId==="credential");if(!a)throw r.context.logger.error("Credential account not found",{phoneNumber:n}),new N.APIError("UNAUTHORIZED",{message:"Invalid password or password"});let d=a?.password;if(!d)throw r.context.logger.error("Password not found",{phoneNumber:n}),new N.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await r.context.password.verify(d,t))throw r.context.logger.error("Invalid password"),new N.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let l=await r.context.internalAdapter.createSession(i.id,r.headers,r.body.rememberMe===!1);if(!l)throw r.context.logger.error("Failed to create session"),new N.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await w(r,{session:l,user:i},r.body.rememberMe===!1),r.json({user:i,session:l})}),sendPhoneNumberOTP:u("/phone-number/send-otp",{method:"POST",body:Z.z.object({phoneNumber:Z.z.string()})},async r=>{if(!e?.sendOTP)throw r.context.logger.warn("sendOTP not implemented"),new N.APIError("NOT_IMPLEMENTED",{message:"sendOTP not implemented"});if(o.phoneNumberValidator&&!await o.phoneNumberValidator(r.body.phoneNumber))throw new N.APIError("BAD_REQUEST",{message:"Invalid phone number!"});let t=Cn(o.otpLength);return await r.context.internalAdapter.createVerificationValue({value:t,identifier:r.body.phoneNumber,expiresAt:R(o.expiresIn,"sec")}),await e.sendOTP({phoneNumber:r.body.phoneNumber,code:t},r.request),r.json({code:t},{body:{message:"Code sent"}})}),verifyPhoneNumber:u("/phone-number/verify",{method:"POST",body:Z.z.object({phoneNumber:Z.z.string(),code:Z.z.string(),disableSession:Z.z.boolean().optional(),updatePhoneNumber:Z.z.boolean().optional()})},async r=>{let t=await r.context.internalAdapter.findVerificationValue(r.body.phoneNumber);if(!t||t.expiresAt<new Date)throw t&&t.expiresAt<new Date?(await r.context.internalAdapter.deleteVerificationValue(t.id),new N.APIError("BAD_REQUEST",{message:"OTP expired"})):new N.APIError("BAD_REQUEST",{message:"OTP not found"});if(t.value!==r.body.code)throw new N.APIError("BAD_REQUEST",{message:"Invalid OTP"});if(await r.context.internalAdapter.deleteVerificationValue(t.id),r.body.updatePhoneNumber){let i=await z(r);if(!i)throw new N.APIError("UNAUTHORIZED",{message:"Session not found"});let s=await r.context.internalAdapter.updateUser(i.user.id,{[o.phoneNumber]:r.body.phoneNumber,[o.phoneNumberVerified]:!0});return r.json({user:s,session:i.session})}let n=await r.context.adapter.findOne({model:r.context.tables.user.modelName,where:[{value:r.body.phoneNumber,field:o.phoneNumber}]});if(await e?.callbackOnVerification?.({phoneNumber:r.body.phoneNumber,user:n},r.request),n)n=await r.context.internalAdapter.updateUser(n.id,{[o.phoneNumberVerified]:!0});else if(e?.signUpOnVerification){if(n=await r.context.internalAdapter.createUser({email:e.signUpOnVerification.getTempEmail(r.body.phoneNumber),name:e.signUpOnVerification.getTempName?e.signUpOnVerification.getTempName(r.body.phoneNumber):r.body.phoneNumber,[o.phoneNumber]:r.body.phoneNumber,[o.phoneNumberVerified]:!0}),!n)throw new N.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"})}else return r.json(null);if(!n)throw new N.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to update user"});if(!r.body.disableSession){let i=await r.context.internalAdapter.createSession(n.id,r.request);if(!i)throw new N.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await w(r,{session:i,user:n}),r.json({user:n,session:i})}return r.json({user:n,session:null})})},schema:K(xn,e?.schema)}},xn={user:{fields:{phoneNumber:{type:"string",required:!1,unique:!0,returned:!0},phoneNumberVerified:{type:"boolean",required:!1,returned:!0,input:!1}}}};var Sl=require("zod");var Ln={user:{fields:{isAnonymous:{type:"boolean",required:!1}}}},Bn=e=>({id:"anonymous",endpoints:{signInAnonymous:u("/sign-in/anonymous",{method:"POST"},async o=>{let{emailDomainName:r=ke(o.context.baseURL)}=e||{},t=x(),n=`temp-${t}@${r}`,i=await o.context.internalAdapter.createUser({id:t,email:n,emailVerified:!1,isAnonymous:!0,name:"Anonymous",createdAt:new Date,updatedAt:new Date});if(!i)return o.json(null,{status:500,body:{message:"Failed to create user",status:500}});let s=await o.context.internalAdapter.createSession(i.id,o.request);return s?(await w(o,{session:s,user:i}),o.json({user:i,session:s})):o.json(null,{status:400,body:{message:"Could not create session"}})})},hooks:{after:[{matcher(o){return o.path?.startsWith("/sign-in")||o.path?.startsWith("/sign-up")},async handler(o){let r=o.context.returned;if(!(r instanceof Response))return;let t=r.headers.get("set-cookie"),n=o.context.authCookies.sessionToken.name,i=Ye(t||"").get(n)?.value.split(".")[0];if(!i)return;let s=await z(o);if(!(!s||!s.user.isAnonymous)){if(o.path==="/sign-in/anonymous")throw new O.APIError("BAD_REQUEST",{message:"Anonymous users cannot sign in again anonymously"});if(e?.onLinkAccount){let a=await o.context.internalAdapter.findSession(i);if(!a)return;await e?.onLinkAccount?.({anonymousUser:s,newUser:a})}e?.disableDeleteAnonymousUser||await o.context.internalAdapter.deleteUser(s.user.id)}}}]},schema:K(Ln,e?.schema)});var h=require("zod");var Dn=e=>{let o={defaultRole:"user",adminRole:"admin",...e},r=P(async t=>{let n=await z(t);if(!n?.session)throw new O.APIError("UNAUTHORIZED");let i=n.user;if(!i.role||(Array.isArray(o.adminRole)?!o.adminRole.includes(i.role):i.role!==o.adminRole))throw new O.APIError("FORBIDDEN",{message:"Only admins can access this endpoint"});return{session:{user:i,session:n.session}}});return{id:"admin",init(t){return{options:{databaseHooks:{user:{create:{async before(n){if(e?.defaultRole!==!1)return{data:{role:e?.defaultRole??"user",...n}}}}},session:{create:{async before(n){let i=await t.internalAdapter.findUserById(n.userId);if(i.banned){if(i.banExpires&&i.banExpires<Date.now()){await t.internalAdapter.updateUser(n.userId,{banned:!1,banReason:null,banExpires:null});return}return!1}}}}}}}},hooks:{after:[{matcher(t){return t.path==="/list-sessions"},handler:P(async t=>{let n=await ze(t);return n?{response:n.filter(s=>!s.impersonatedBy)}:void 0})}]},endpoints:{setRole:u("/admin/set-role",{method:"POST",body:h.z.object({userId:h.z.string(),role:h.z.string()}),use:[r]},async t=>{let n=await t.context.internalAdapter.updateUser(t.body.userId,{role:t.body.role});return t.json({user:n})}),createUser:u("/admin/create-user",{method:"POST",body:h.z.object({email:h.z.string(),password:h.z.string(),name:h.z.string(),role:h.z.string(),data:h.z.optional(h.z.record(h.z.any()))}),use:[r]},async t=>{if(await t.context.internalAdapter.findUserByEmail(t.body.email))throw new O.APIError("BAD_REQUEST",{message:"User already exists"});let i=await t.context.internalAdapter.createUser({email:t.body.email,name:t.body.name,role:t.body.role,...t.body.data});if(!i)throw new O.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"});let s=await t.context.password.hash(t.body.password);return await t.context.internalAdapter.linkAccount({accountId:i.id,providerId:"credential",password:s,userId:i.id}),t.json({user:i})}),listUsers:u("/admin/list-users",{method:"GET",use:[r],query:h.z.object({searchValue:h.z.string().optional(),searchField:h.z.enum(["email","name"]).optional(),searchOperator:h.z.enum(["contains","starts_with","ends_with"]).optional(),limit:h.z.string().or(h.z.number()).optional(),offset:h.z.string().or(h.z.number()).optional(),sortBy:h.z.string().optional(),sortDirection:h.z.enum(["asc","desc"]).optional(),filterField:h.z.string().optional(),filterValue:h.z.string().or(h.z.number()).or(h.z.boolean()).optional(),filterOperator:h.z.enum(["eq","ne","lt","lte","gt","gte"]).optional()})},async t=>{let n=[];t.query?.searchValue&&n.push({field:t.query.searchField||"email",operator:t.query.searchOperator||"contains",value:t.query.searchValue}),t.query?.filterValue&&n.push({field:t.query.filterField||"email",operator:t.query.filterOperator||"eq",value:t.query.filterValue});try{let i=await t.context.internalAdapter.listUsers(Number(t.query?.limit)||void 0,Number(t.query?.offset)||void 0,t.query?.sortBy?{field:t.query.sortBy,direction:t.query.sortDirection||"asc"}:void 0,n.length?n:void 0);return t.json({users:i})}catch(i){return console.log(i),t.json({users:[]})}}),listUserSessions:u("/admin/list-user-sessions",{method:"POST",use:[r],body:h.z.object({userId:h.z.string()})},async t=>({sessions:await t.context.internalAdapter.listSessions(t.body.userId)})),unbanUser:u("/admin/unban-user",{method:"POST",body:h.z.object({userId:h.z.string()}),use:[r]},async t=>{let n=await t.context.internalAdapter.updateUser(t.body.userId,{banned:!1});return t.json({user:n})}),banUser:u("/admin/ban-user",{method:"POST",body:h.z.object({userId:h.z.string(),banReason:h.z.string().optional(),banExpiresIn:h.z.number().optional()}),use:[r]},async t=>{if(t.body.userId===t.context.session.user.id)throw new O.APIError("BAD_REQUEST",{message:"You cannot ban yourself"});let n=await t.context.internalAdapter.updateUser(t.body.userId,{banned:!0,banReason:t.body.banReason||e?.defaultBanReason||"No reason",banExpires:t.body.banExpiresIn?R(t.body.banExpiresIn,"sec"):e?.defaultBanExpiresIn?R(e.defaultBanExpiresIn,"sec"):void 0});return await t.context.internalAdapter.deleteSessions(t.body.userId),t.json({user:n})}),impersonateUser:u("/admin/impersonate-user",{method:"POST",body:h.z.object({userId:h.z.string()}),use:[r]},async t=>{let n=await t.context.internalAdapter.findUserById(t.body.userId);if(!n)throw new O.APIError("NOT_FOUND",{message:"User not found"});let i=await t.context.internalAdapter.createSession(n.id,void 0,!0,{impersonatedBy:t.context.session.user.id,expiresAt:e?.impersonationSessionDuration?R(e.impersonationSessionDuration,"sec"):R(60*60,"sec")});if(!i)throw new O.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await w(t,{session:i,user:n},!0),t.json({session:i,user:n})}),revokeUserSession:u("/admin/revoke-user-session",{method:"POST",body:h.z.object({sessionId:h.z.string()}),use:[r]},async t=>(await t.context.internalAdapter.deleteSession(t.body.sessionId),t.json({success:!0}))),revokeUserSessions:u("/admin/revoke-user-sessions",{method:"POST",body:h.z.object({userId:h.z.string()}),use:[r]},async t=>(await t.context.internalAdapter.deleteSessions(t.body.userId),t.json({success:!0}))),removeUser:u("/admin/remove-user",{method:"POST",body:h.z.object({userId:h.z.string()}),use:[r]},async t=>(await t.context.internalAdapter.deleteUser(t.body.userId),t.json({success:!0})))},schema:K(Nn,o.schema)}},Nn={user:{fields:{role:{type:"string",required:!1,input:!1},banned:{type:"boolean",defaultValue:!1,required:!1,input:!1},banReason:{type:"string",required:!1,input:!1},banExpires:{type:"date",required:!1,input:!1}}},session:{fields:{impersonatedBy:{type:"string",required:!1}}}};var re=require("zod"),Le=require("better-call");var ct=require("@better-fetch/fetch");var so=require("oslo/jwt");async function jn(e,o,r){if(o==="oidc"&&e.idToken){let n=(0,so.parseJWT)(e.idToken);if(n?.payload)return n.payload}return r?(await(0,ct.betterFetch)(r,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}})).data:null}var Vn=e=>({id:"generic-oauth",endpoints:{signInWithOAuth2:u("/sign-in/oauth2",{method:"POST",query:re.z.object({currentURL:re.z.string().optional()}).optional(),body:re.z.object({providerId:re.z.string(),callbackURL:re.z.string().optional(),errorCallbackURL:re.z.string().optional()})},async o=>{let{providerId:r}=o.body,t=e.config.find(C=>C.providerId===r);if(!t)throw new Le.APIError("BAD_REQUEST",{message:`No config found for provider ${r}`});let{discoveryUrl:n,authorizationUrl:i,tokenUrl:s,clientId:a,clientSecret:d,scopes:c,redirectURI:l,responseType:m,pkce:f,prompt:p,accessType:g}=t,v=i,H=s;if(n){let C=await(0,ct.betterFetch)(n,{onError(De){o.context.logger.error(De.error.message,De.error,{discoveryUrl:n})}});C.data&&(v=C.data.authorization_endpoint,H=C.data.token_endpoint)}if(!v||!H)throw new Le.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let{state:oe,codeVerifier:Y}=await Oe(o),y=await I({id:r,options:{clientId:a,clientSecret:d,redirectURI:l},authorizationEndpoint:v,state:oe,codeVerifier:f?Y:void 0,scopes:c||[],redirectURI:`${o.context.baseURL}/oauth2/callback/${r}`});return m&&m!=="code"&&y.searchParams.set("response_type",m),p&&y.searchParams.set("prompt",p),g&&y.searchParams.set("access_type",g),o.json({url:y.toString(),redirect:!0})}),oAuth2Callback:u("/oauth2/callback/:providerId",{method:"GET",query:re.z.object({code:re.z.string().optional(),error:re.z.string().optional(),state:re.z.string()})},async o=>{if(o.query.error||!o.query.code)throw o.redirect(`${o.context.baseURL}?error=${o.query.error||"oAuth_code_missing"}`);let r=e.config.find(y=>y.providerId===o.params.providerId);if(!r)throw new Le.APIError("BAD_REQUEST",{message:`No config found for provider ${o.params.providerId}`});let t,n=await et(o),{callbackURL:i,codeVerifier:s,errorURL:a}=n,d=o.query.code,c=r.tokenUrl,l=r.userInfoUrl;if(r.discoveryUrl){let y=await(0,ct.betterFetch)(r.discoveryUrl,{method:"GET"});y.data&&(c=y.data.token_endpoint,l=y.data.userinfo_endpoint)}try{if(!c)throw new Le.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});t=await k({code:d,codeVerifier:s,redirectURI:`${o.context.baseURL}/oauth2/callback/${r.providerId}`,options:{clientId:r.clientId,clientSecret:r.clientSecret},tokenEndpoint:c})}catch(y){throw o.context.logger.error(y&&typeof y=="object"&&"name"in y?y.name:"",y),o.redirect(`${a}?error=oauth_code_verification_failed`)}if(!t)throw new Le.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let m=r.getUserInfo?await r.getUserInfo(t):await jn(t,r.type||"oauth2",l),f=x(),p=Rr.safeParse({...m,id:f});if(!m||p.success===!1)throw o.context.logger.error("Unable to get user info",p.error),o.redirect(`${o.context.baseURL}/error?error=please_restart_the_process`);let g=await Ee(o,{userInfo:p.data,account:{providerId:r.providerId,accountId:m.id,accessToken:t.accessToken}});function v(y){throw o.redirect(`${a||i||`${o.context.baseURL}/error`}?error=${y}`)}if(g.error)return v(g.error.split(" ").join("_"));let{session:H,user:oe}=g.data;await w(o,{session:H,user:oe});let Y;try{Y=new URL(i).toString()}catch{Y=i}throw o.redirect(Y)})}});var Be=require("zod"),ao={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0}}}},Zl=Be.z.object({id:Be.z.string(),publicKey:Be.z.string(),privateKey:Be.z.string(),createdAt:Be.z.date()});var xt=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 o=>await e.create({model:"jwks",data:{...o,createdAt:new Date}})});var de=require("jose");var Fn=e=>({id:"jwt",endpoints:{getJwks:u("/jwks",{method:"GET"},async o=>{let t=await xt(o.context.adapter).getAllKeys();return o.json({keys:t.map(n=>({...JSON.parse(n.publicKey),kid:n.id}))})}),getToken:u("/token",{method:"GET",requireHeaders:!0,use:[b]},async o=>{let r=xt(o.context.adapter),t=await r.getLatestKey(),n=!e?.jwks?.disablePrivateKeyEncryption;if(t===void 0){let{publicKey:c,privateKey:l}=await(0,de.generateKeyPair)(e?.jwks?.keyPairConfig?.alg??"EdDSA",e?.jwks?.keyPairConfig??{crv:"Ed25519"}),m=await(0,de.exportJWK)(c),f=await(0,de.exportJWK)(l),p=JSON.stringify(f),g={id:crypto.randomUUID(),publicKey:JSON.stringify(m),privateKey:n?JSON.stringify(await ae({key:o.context.options.secret,data:p})):p,createdAt:new Date};t=await r.createJwk(g)}let i=n?await fe({key:o.context.options.secret,data:JSON.parse(t.privateKey)}):t.privateKey,s=await(0,de.importJWK)(JSON.parse(i)),a=e?.jwt?.definePayload?await e?.jwt.definePayload(o.context.session.user):o.context.session.user,d=await new de.SignJWT({...a,...o.context.session.session.impersonatedBy?{impersonatedBy:o.context.session.session.impersonatedBy}:{}}).setProtectedHeader({alg:e?.jwks?.keyPairConfig?.alg??"EdDSA",kid:t.id}).setIssuedAt().setIssuer(e?.jwt?.issuer??o.context.options.baseURL).setAudience(e?.jwt?.audience??o.context.options.baseURL).setExpirationTime(e?.jwt?.expirationTime??"15m").setSubject(o.context.session.user.id).sign(s);return o.json({token:d})})},schema:K(ao,e?.schema)});var We=require("zod");var qn=e=>{let o={maximumSessions:5,...e},r=t=>t.includes("_multi-");return{id:"multi-session",endpoints:{listDeviceSessions:u("/multi-session/list-device-sessions",{method:"GET",requireHeaders:!0},async t=>{let n=t.headers?.get("cookie");if(!n)return t.json([]);let i=Object.fromEntries(je(n)),s=(await Promise.all(Object.entries(i).filter(([c])=>r(c)).map(async([c])=>await t.getSignedCookie(c,t.context.secret)))).filter(c=>c!==void 0);if(!s.length)return t.json([]);let d=(await t.context.internalAdapter.findSessions(s)).filter(c=>c&&c.session.expiresAt>new Date);return t.json(d)}),setActiveSession:u("/multi-session/set-active",{method:"POST",body:We.z.object({sessionId:We.z.string()}),requireHeaders:!0,use:[b]},async t=>{let n=t.body.sessionId,i=`${t.context.authCookies.sessionToken.name}_multi-${n}`;if(!await t.getSignedCookie(i,t.context.secret))throw new O.APIError("UNAUTHORIZED",{message:"Invalid session id"});let a=await t.context.internalAdapter.findSession(n);if(!a||a.session.expiresAt<new Date)throw t.setCookie(i,"",{...t.context.authCookies.sessionToken.options,maxAge:0}),new O.APIError("UNAUTHORIZED",{message:"Invalid session id"});return await t.setSignedCookie(t.context.authCookies.sessionToken.name,n,t.context.secret,t.context.authCookies.sessionToken.options),t.json(a)}),revokeDeviceSession:u("/multi-session/revoke",{method:"POST",body:We.z.object({sessionId:We.z.string()}),requireHeaders:!0,use:[b]},async t=>{let n=t.body.sessionId,i=`${t.context.authCookies.sessionToken.name}_multi-${n}`;if(!await t.getSignedCookie(i,t.context.secret))throw new O.APIError("UNAUTHORIZED",{message:"Invalid session id"});if(await t.context.internalAdapter.deleteSession(n),t.setCookie(i,"",{...t.context.authCookies.sessionToken.options,maxAge:0}),!(t.context.session?.session.id===n))return t.json({success:!0});let d=t.headers?.get("cookie"),c=t.context.authCookies;if(d){let l=Object.fromEntries(je(d)),m=(await Promise.all(Object.entries(l).filter(([p])=>r(p)).map(async([p])=>await t.getSignedCookie(p,t.context.secret)))).filter(p=>p!==void 0),f=t.context.internalAdapter;if(m.length>0){let g=(await f.findSessions(m)).filter(v=>v&&v.session.expiresAt>new Date);if(g.length>0){let v=g[0];await w(t,v)}else t.setCookie(c.sessionToken.name,"",{...c.sessionToken.options,maxAge:0})}else t.setCookie(c.sessionToken.name,"",{...c.sessionToken.options,maxAge:0})}else t.setCookie(c.sessionToken.name,"",{...c.sessionToken.options,maxAge:0});return t.json({success:!0})})},hooks:{after:[{matcher:()=>!0,handler:P(async t=>{if(!t.context.returned||!(t.context.returned instanceof Response))return;let n=t.context.returned.headers.get("set-cookie");if(!n)return;let i=Ye(n),s=t.context.authCookies.sessionToken,a=i.get(s.name)?.value;if(!a)return;let d=je(t.headers?.get("cookie")||""),c=a.split(".")[0],l=`${s.name}_multi-${c}`;if(i.get(l)||d.get(l)||Object.keys(Object.fromEntries(d)).filter(r).length+(n.includes("session_token")?1:0)>o.maximumSessions)return;await t.setSignedCookie(l,c,t.context.secret,s.options);let f=t.context.returned;return f.headers.append("Set-Cookie",t.responseHeader.get("set-cookie")),{response:f}})},{matcher:t=>t.path==="/sign-out",handler:P(async t=>{let n=t.headers?.get("cookie");if(!n)return;let i=Object.fromEntries(je(n));return await Promise.all(Object.entries(i).map(async([s,a])=>{if(r(s)){t.setCookie(s,"",{maxAge:0});let d=s.split("_multi-")[1];await t.context.internalAdapter.deleteSession(d)}})),{responseHeader:t.responseHeader}})}]}}};var j=require("zod");var Mn=e=>{let o={expireIn:300,otpLength:6,...e};return{id:"email-otp",endpoints:{sendVerificationOTP:u("/email-otp/send-verification-otp",{method:"POST",body:j.z.object({email:j.z.string(),type:j.z.enum(["email-verification","sign-in"])})},async r=>{if(!e?.sendVerificationOTP)throw r.context.logger.error("send email verification is not implemented"),new O.APIError("BAD_REQUEST",{message:"send email verification is not implemented"});let t=r.body.email,n=M(o.otpLength,$("0-9"));return await r.context.internalAdapter.createVerificationValue({value:n,identifier:`${r.body.type}-otp-${t}`,expiresAt:R(o.expireIn,"sec")}).catch(async i=>{await r.context.internalAdapter.deleteVerificationByIdentifier(`${r.body.type}-otp-${t}`),await r.context.internalAdapter.createVerificationValue({value:n,identifier:`${r.body.type}-otp-${t}`,expiresAt:R(o.expireIn,"sec")})}),await e.sendVerificationOTP({email:t,otp:n,type:r.body.type},r.request),r.json({success:!0})}),createVerificationOTP:u("/email-otp/create-verification-otp",{method:"POST",body:j.z.object({email:j.z.string(),type:j.z.enum(["email-verification","sign-in"])}),metadata:{SERVER_ONLY:!0}},async r=>{let t=r.body.email,n=M(o.otpLength,$("0-9"));return await r.context.internalAdapter.createVerificationValue({value:n,identifier:`${r.body.type}-otp-${t}`,expiresAt:R(o.expireIn,"sec")}),n}),getVerificationOTP:u("/email-otp/get-verification-otp",{method:"GET",query:j.z.object({email:j.z.string(),type:j.z.enum(["email-verification","sign-in"])}),metadata:{SERVER_ONLY:!0}},async r=>{let t=r.query.email,n=await r.context.internalAdapter.findVerificationValue(`${r.query.type}-otp-${t}`);return!n||n.expiresAt<new Date?r.json({otp:null}):r.json({otp:n.value})}),verifyEmailOTP:u("/email-otp/verify-email",{method:"POST",body:j.z.object({email:j.z.string(),otp:j.z.string()})},async r=>{let t=r.body.email,n=await r.context.internalAdapter.findVerificationValue(`email-verification-otp-${t}`);if(!n||n.expiresAt<new Date)throw n&&await r.context.internalAdapter.deleteVerificationValue(n.id),new O.APIError("BAD_REQUEST",{message:"Invalid OTP"});let i=r.body.otp;if(n.value!==i)throw new O.APIError("BAD_REQUEST",{message:"Invalid OTP"});await r.context.internalAdapter.deleteVerificationValue(n.id);let s=await r.context.internalAdapter.findUserByEmail(t);if(!s)throw new O.APIError("BAD_REQUEST",{message:"User not found"});let a=await r.context.internalAdapter.updateUser(s.user.id,{email:t,emailVerified:!0});return r.json({user:a})}),signInEmailOTP:u("/sign-in/email-otp",{method:"POST",body:j.z.object({email:j.z.string(),otp:j.z.string()})},async r=>{let t=r.body.email,n=await r.context.internalAdapter.findVerificationValue(`sign-in-otp-${t}`);if(!n||n.expiresAt<new Date)throw n&&await r.context.internalAdapter.deleteVerificationValue(n.id),new O.APIError("BAD_REQUEST",{message:"Invalid OTP"});let i=r.body.otp;if(n.value!==i)throw new O.APIError("BAD_REQUEST",{message:"Invalid OTP"});await r.context.internalAdapter.deleteVerificationValue(n.id);let s=await r.context.internalAdapter.findUserByEmail(t);if(!s){if(o.disableSignUp)throw new O.APIError("BAD_REQUEST",{message:"User not found"});let d=await r.context.internalAdapter.createUser({email:t,emailVerified:!0,name:t}),c=await r.context.internalAdapter.createSession(d.id,r.request);return await w(r,{session:c,user:d}),r.json({user:d,session:c})}let a=await r.context.internalAdapter.createSession(s.user.id,r.request);return await w(r,{session:a,user:s.user}),r.json({session:a,user:s})})},hooks:{after:[{matcher(r){return!!(r.path?.startsWith("/sign-up")&&o.sendVerificationOnSignUp)},async handler(r){let t=await ze(r);if(t&&t.user.email&&t.user.emailVerified===!1){let n=M(o.otpLength,$("0-9"));await r.context.internalAdapter.createVerificationValue({value:n,identifier:`email-verification-otp-${t.user.email}`,expiresAt:R(o.expireIn,"sec")}),await e.sendVerificationOTP({email:t.user.email,otp:n,type:"email-verification"},r.request)}}}]}}};var Lt=require("zod");var uo=require("@better-fetch/fetch");function co(e){return e==="true"||e===!0}var $n=e=>({id:"one-tap",endpoints:{oneTapCallback:u("/one-tap/callback",{method:"POST",body:Lt.z.object({idToken:Lt.z.string()})},async o=>{let{idToken:r}=o.body,{data:t,error:n}=await(0,uo.betterFetch)("https://oauth2.googleapis.com/tokeninfo?id_token="+r);if(n)return o.json({error:"Invalid token"});let i=await o.context.internalAdapter.findUserByEmail(t.email);if(!i){if(e?.disableSignup)throw new O.APIError("BAD_GATEWAY",{message:"User not found"});let a=await o.context.internalAdapter.createOAuthUser({email:t.email,emailVerified:co(t.email_verified),name:t.name,image:t.picture},{providerId:"google",accountId:t.sub});if(!a)throw new O.APIError("INTERNAL_SERVER_ERROR",{message:"Could not create user"});let d=await o.context.internalAdapter.createSession(a?.user.id,o.request);return await w(o,{user:a.user,session:d}),o.json({session:d,user:a})}let s=await o.context.internalAdapter.createSession(i.user.id,o.request);return await w(o,{user:i.user,session:s}),o.json({session:s,user:i})})}});var ut=require("zod");function Hn(){let e=ee.VERCEL_URL,o=ee.NETLIFY_URL,r=ee.RENDER_URL,t=ee.AWS_LAMBDA_FUNCTION_NAME,n=ee.GOOGLE_CLOUD_FUNCTION_NAME,i=ee.AZURE_FUNCTION_NAME;return e||o||r||t||n||i}var Qn=e=>({id:"oauth-proxy",endpoints:{oAuthProxy:u("/oauth-proxy-callback",{method:"GET",query:ut.z.object({callbackURL:ut.z.string(),cookies:ut.z.string()})},async o=>{let r=o.query.cookies,t=await fe({key:o.context.secret,data:r});throw o.setHeader("set-cookie",t),o.redirect(o.query.callbackURL)})},hooks:{after:[{matcher(o){return o.path?.startsWith("/callback")},handler:P(async o=>{let r=o.context.returned;if(!r||!(r instanceof Response))return;let t=r.headers.get("location");if(t?.includes("/oauth-proxy-callback?callbackURL")){if(!t.startsWith("http"))return;let n=new URL(t);if(n.origin===ke(o.context.baseURL)){let c=n.searchParams.get("callbackURL");return c?(r.headers.set("location",c),{response:r}):void 0}let s=r.headers.get("set-cookie");if(!s)return;let a=await ae({key:o.context.secret,data:s}),d=`${t}&cookies=${encodeURIComponent(a)}`;return r.headers.set("location",d),{response:r}}})}],before:[{matcher(o){return o.path?.startsWith("/sign-in/social")},async handler(o){let r=new URL(e?.currentURL||o.request?.url||Hn()||o.context.baseURL);return o.body.callbackURL=`${r.origin}${o.context.options.basePath||"/api/auth"}/oauth-proxy-callback?callbackURL=${encodeURIComponent(o.body.callbackURL||o.context.baseURL)}`,{context:o}}}]}});0&&(module.exports={HIDE_METADATA,admin,anonymous,bearer,createAuthEndpoint,createAuthMiddleware,emailOTP,genericOAuth,getPasskeyActions,jwt,magicLink,multiSession,oAuthProxy,oneTap,optionsMiddleware,organization,passkey,passkeyClient,phoneNumber,twoFactor,twoFactorClient,username});
83
+ Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user;if(n){let a=n.accounts.find(d=>d.providerId===r.providerId);if(a)await e.context.internalAdapter.updateAccount(a.id,{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt});else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!o.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Nt&&W.warn(`User already exist but account isn't linked to ${r.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:r.providerId,accountId:o.id.toString(),id:e.context.uuid(),userId:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt})}catch(l){return W.error("Unable to link account",l),{error:"unable to link account",data:null}}}}else try{let a=o.emailVerified||!1;if(i=await e.context.internalAdapter.createOAuthUser({...o,id:e.context.uuid(),emailVerified:a,email:o.email.toLowerCase()},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,providerId:r.providerId,accountId:o.id.toString()}).then(d=>d?.user),!a&&i&&e.context.options.emailVerification?.sendOnSignUp){let d=await le(e.context.secret,i.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${t}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:c,token:d},e.request)}}catch(a){return W.error("Unable to create user",a),{error:"unable to create user",data:null}}if(!i)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(i.id,e.request);return s?{data:{session:s,user:i},error:null}:{error:"unable to create session",data:null}}var Qo=u("/sign-in/social",{method:"POST",query:T.z.object({currentURL:T.z.string().optional()}).optional(),body:T.z.object({callbackURL:T.z.string().optional(),errorCallbackURL:T.z.string().optional(),provider:T.z.enum(tt),disableRedirect:T.z.boolean().optional(),idToken:T.z.optional(T.z.object({token:T.z.string(),nonce:T.z.string().optional(),accessToken:T.z.string().optional(),refreshToken:T.z.string().optional(),expiresAt:T.z.number().optional()}))})},async e=>{let o=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!o)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new B.APIError("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!o.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new B.APIError("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:i,nonce:s}=e.body.idToken;if(!await o.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new B.APIError("UNAUTHORIZED",{message:"Invalid id token"});let d=await o.getUserInfo({idToken:i,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 B.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 B.APIError("UNAUTHORIZED",{message:"User email not found"});let c=await Ee(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:o.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new B.APIError("UNAUTHORIZED",{message:c.error});return await w(e,c.data),e.json({session:c.data.session,user:c.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:r,state:t}=await Oe(e),n=await o.createAuthorizationURL({state:t,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${o.id}`});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),Wo=u("/sign-in/email",{method:"POST",body:T.z.object({email:T.z.string(),password:T.z.string(),callbackURL:T.z.string().optional(),rememberMe:T.z.boolean().default(!0).optional()})},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 B.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:o,password:r}=e.body;if(!T.z.string().email().safeParse(o).success)throw new B.APIError("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(o,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:o}),new B.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(c=>c.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:o}),new B.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:o}),new B.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new B.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Email verification is required but no email verification handler is provided"),new B.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await le(e.context.secret,n.user.email),l=`${e.context.baseURL}/verify-email?token=${c}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:l,token:c},e.request),e.context.logger.error("Email not verified",{email:o}),new B.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!d)throw e.context.logger.error("Failed to create session"),new B.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await w(e,{session:d,user:n.user},e.body.rememberMe===!1),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Ie=require("zod");var ot=Ie.z.object({code:Ie.z.string().optional(),error:Ie.z.string().optional(),errorMessage:Ie.z.string().optional(),state:Ie.z.string().optional()}),Go=u("/callback/:id",{method:["GET","POST"],body:ot.optional(),query:ot.optional(),metadata:we},async e=>{let o;try{if(e.method==="GET")o=ot.parse(e.query);else if(e.method==="POST")o=ot.parse(e.body);else throw new Error("Unsupported method")}catch(y){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",y),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:t,state:n}=o;if(!n)throw e.context.logger.error("State not found"),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${t||"no_code"}`);let i=e.context.socialProviders.find(y=>y.id===e.params.id);if(!i)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:s,callbackURL:a,link:d,errorURL:c}=await et(e),l;try{l=await i.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${i.id}`})}catch(y){throw e.context.logger.error("",y),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let p=await i.getUserInfo(l).then(y=>y?.user),m={id:x(),...p};function g(y){let C=c||a||`${e.context.baseURL}/error`;throw C.includes("?")?C=`${C}&error=${y}`:C=`${C}?error=${y}`,e.redirect(C)}if(!p)return e.context.logger.error("Unable to get user info"),g("unable_to_get_user_info");if(!m.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),g("email_not_found");if(!a)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(d){if(d.email!==m.email.toLowerCase())return g("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:i.id,accountId:p.id}))return g("unable_to_link_account");let C;try{C=new URL(a).toString()}catch{C=a}throw e.redirect(C)}let v=await Ee(e,{userInfo:{email:m.email,id:m.id,name:m.name||"",image:m.image,emailVerified:m.emailVerified||!1},account:{providerId:i.id,accountId:p.id,accessToken:l.accessToken,refreshToken:l.refreshToken,expiresAt:l.accessTokenExpiresAt},callbackURL:a});if(v.error)return e.context.logger.error(v.error.split(" ").join("_")),g(v.error.split(" ").join("_"));let{session:H,user:oe}=v.data;await w(e,{session:H,user:oe});let Y;try{Y=new URL(a).toString()}catch{Y=a}throw e.redirect(Y)});var ed=require("zod");var Er=require("better-call"),Ko=u("/sign-out",{method:"POST",requireHeaders:!0},async e=>{let o=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!o)throw te(e),new Er.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(o),te(e),e.json({success:!0})});var Q=require("zod");var nt=require("better-call");function Ir(e,o,r){let t=o?new URL(o,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>t.searchParams.set(n,i)),t.href}function sn(e,o,r){let t=new URL(o,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>t.searchParams.set(n,i)),t.href}var Jo=u("/forget-password",{method:"POST",body:Q.z.object({email:Q.z.string().email(),redirectTo:Q.z.string()})},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 nt.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:o,redirectTo:r}=e.body,t=await e.context.internalAdapter.findUserByEmail(o,{includeAccounts:!0});if(!t)return e.context.logger.error("Reset Password: User not found",{email:o}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=R(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`reset-password:${s}`,expiresAt:i});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:t.user,url:a,token:s},e.request),e.json({status:!0})}),Zo=u("/reset-password/:token",{method:"GET",query:Q.z.object({callbackURL:Q.z.string()})},async e=>{let{token:o}=e.params,{callbackURL:r}=e.query;if(!o||!r)throw e.redirect(Ir(e.context,r,{error:"INVALID_TOKEN"}));let t=await e.context.internalAdapter.findVerificationValue(`reset-password:${o}`);throw!t||t.expiresAt<new Date?e.redirect(Ir(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(sn(e.context,r,{token:o}))}),Yo=u("/reset-password",{query:Q.z.optional(Q.z.object({token:Q.z.string().optional(),currentURL:Q.z.string().optional()})),method:"POST",body:Q.z.object({newPassword:Q.z.string(),token:Q.z.string().optional()})},async e=>{let o=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!o)throw new nt.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,t=`reset-password:${o}`,n=await e.context.internalAdapter.findVerificationValue(t);if(!n||n.expiresAt<new Date)throw new nt.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(i)).find(c=>c.providerId==="credential")?(await e.context.internalAdapter.updatePassword(i,s),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0}))});var F=require("zod");var V=require("better-call");var Xo=u("/change-password",{method:"POST",body:F.z.object({newPassword:F.z.string(),currentPassword:F.z.string(),revokeOtherSessions:F.z.boolean().optional()}),use:[b]},async e=>{let{newPassword:o,currentPassword:r,revokeOtherSessions:t}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(o.length<i)throw e.context.logger.error("Password is too short"),new V.APIError("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(o.length>s)throw e.context.logger.error("Password is too long"),new V.APIError("BAD_REQUEST",{message:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(n.user.id)).find(p=>p.providerId==="credential"&&p.password);if(!d||!d.password)throw new V.APIError("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(o);if(!await e.context.password.verify(d.password,r))throw new V.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),t){await e.context.internalAdapter.deleteSessions(n.user.id);let p=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!p)throw new V.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await w(e,{session:p,user:n.user})}return e.json(n.user)}),en=u("/set-password",{method:"POST",body:F.z.object({newPassword:F.z.string()}),metadata:{SERVER_ONLY:!0},use:[b]},async e=>{let{newPassword:o}=e.body,r=e.context.session,t=e.context.password.config.minPasswordLength;if(o.length<t)throw e.context.logger.error("Password is too short"),new V.APIError("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(o.length>n)throw e.context.logger.error("Password is too long"),new V.APIError("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(d=>d.providerId==="credential"&&d.password),a=await e.context.password.hash(o);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:a}),e.json(r.user);throw new V.APIError("BAD_REQUEST",{message:"user already has a password"})}),tn=u("/delete-user",{method:"POST",body:F.z.object({password:F.z.string()}),use:[b]},async e=>{let{password:o}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password);if(!n||!n.password)throw new V.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,o))throw new V.APIError("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),te(e),e.json(null)}),rn=u("/change-email",{method:"POST",query:F.z.object({currentURL:F.z.string().optional()}).optional(),body:F.z.object({newEmail:F.z.string().email(),callbackURL:F.z.string().optional()}),use:[b]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new V.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new V.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new V.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new V.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await le(e.context.secret,e.context.session.user.email,e.body.newEmail),t=`${e.context.baseURL}/verify-email?token=${r}&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:t,token:r},e.request),e.json({user:null,status:!0})});var Ue=require("zod");var yt=require("better-call");var on=u("/list-accounts",{method:"GET",use:[b]},async e=>{let o=e.context.session,r=await e.context.internalAdapter.findAccounts(o.user.id);return e.json(r.map(t=>({id:t.id,provider:t.providerId})))}),nn=u("/link-social",{method:"POST",requireHeaders:!0,query:Ue.z.object({currentURL:Ue.z.string().optional()}).optional(),body:Ue.z.object({callbackURL:Ue.z.string().optional(),provider:Ue.z.enum(tt)}),use:[b]},async e=>{let o=e.context.session;if((await e.context.internalAdapter.findAccounts(o.user.id)).find(a=>a.providerId===e.body.provider))throw new yt.APIError("BAD_REQUEST",{message:"Social Account is already linked."});let n=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!n)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new yt.APIError("NOT_FOUND",{message:"Provider not found"});let i=await Oe(e,{userId:o.user.id,email:o.user.email}),s=await n.createAuthorizationURL({state:i.state,codeVerifier:i.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${n.id}`});return e.json({url:s.toString(),redirect:!0})});var Ur=(e,o)=>{let r={};for(let[t,n]of Object.entries(e))r[t]=i=>n({...i,context:{...o,...i.context}}),r[t].path=n.path,r[t].method=n.method,r[t].options=n.options,r[t].headers=n.headers;return r};function it(e){let o=e;return{newRole(r){return an(r)}}}function an(e){return{statements:e,authorize(o,r){for(let[t,n]of Object.entries(o)){let i=e[t];return i?(r==="OR"?n.some(a=>i.includes(a)):n.every(a=>i.includes(a)))?{success:!0}:{success:!1,error:`Unauthorized to access resource "${t}"`}:{success:!1,error:`You are not allowed to access resource: ${t}`}}return{success:!1,error:"Not authorized"}}}}var dn={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},bt=it(dn),cn=bt.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),un=bt.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),ln=bt.newRole({organization:[],member:[],invitation:[]}),Tr={admin:cn,owner:un,member:ln};var _=(e,o)=>{let r=e.adapter;return{findOrganizationBySlug:async t=>await r.findOne({model:"organization",where:[{field:"slug",value:t}]}),createOrganization:async t=>{let n=await r.create({model:"organization",data:{...t.organization,metadata:t.organization.metadata?JSON.stringify(t.organization.metadata):void 0}}),i=await r.create({model:"member",data:{id:x(),organizationId:n.id,userId:t.user.id,createdAt:new Date,role:o?.creatorRole||"owner"}});return{...n,metadata:n.metadata?JSON.parse(n.metadata):void 0,members:[{...i,user:{id:t.user.id,name:t.user.name,email:t.user.email,image:t.user.image}}]}},findMemberByEmail:async t=>{let n=await r.findOne({model:"user",where:[{field:"email",value:t.email}]});if(!n)return null;let i=await r.findOne({model:"member",where:[{field:"organizationId",value:t.organizationId},{field:"userId",value:n.id}]});return i?{...i,user:{id:n.id,name:n.name,email:n.email,image:n.image}}:null},findMemberByOrgId:async t=>{let[n,i]=await Promise.all([await r.findOne({model:"member",where:[{field:"userId",value:t.userId},{field:"organizationId",value:t.organizationId}]}),await r.findOne({model:"user",where:[{field:"id",value:t.userId}]})]);return!i||!n?null:{...n,user:{id:i.id,name:i.name,email:i.email,image:i.image}}},findMemberById:async t=>{let n=await r.findOne({model:"member",where:[{field:"id",value:t}]});if(!n)return null;let i=await r.findOne({model:"user",where:[{field:"id",value:n.userId}]});return i?{...n,user:{id:i.id,name:i.name,email:i.email,image:i.image}}:null},createMember:async t=>await r.create({model:"member",data:t}),updateMember:async(t,n)=>await r.update({model:"member",where:[{field:"id",value:t}],update:{role:n}}),deleteMember:async t=>await r.delete({model:"member",where:[{field:"id",value:t}]}),updateOrganization:async(t,n)=>await r.update({model:"organization",where:[{field:"id",value:t}],update:n}),deleteOrganization:async t=>(await r.delete({model:"member",where:[{field:"organizationId",value:t}]}),await r.delete({model:"invitation",where:[{field:"organizationId",value:t}]}),await r.delete({model:"organization",where:[{field:"id",value:t}]}),t),setActiveOrganization:async(t,n)=>await r.update({model:"session",where:[{field:"id",value:t}],update:{activeOrganizationId:n}}),findOrganizationById:async t=>await r.findOne({model:"organization",where:[{field:"id",value:t}]}),findFullOrganization:async t=>{let[n,i,s]=await Promise.all([r.findOne({model:"organization",where:[{field:"id",value:t}]}),r.findMany({model:"invitation",where:[{field:"organizationId",value:t}]}),r.findMany({model:"member",where:[{field:"organizationId",value:t}]})]);if(!n)return null;let a=s.map(p=>p.userId),d=await r.findMany({model:"user",where:[{field:"id",value:a,operator:"in"}]}),c=new Map(d.map(p=>[p.id,p])),l=s.map(p=>{let f=c.get(p.userId);if(!f)throw new X("Unexpected error: User not found for member");return{...p,user:{id:f.id,name:f.name,email:f.email,image:f.image}}});return{...n,invitations:i,members:l}},listOrganizations:async t=>{let n=await r.findMany({model:"member",where:[{field:"userId",value:t}]});if(!n||n.length===0)return[];let i=n.map(a=>a.organizationId);return await r.findMany({model:"organization",where:[{field:"id",value:i,operator:"in"}]})},createInvitation:async({invitation:t,user:n})=>{let s=R(o?.invitationExpiresIn||1728e5);return await r.create({model:"invitation",data:{id:x(),email:t.email,role:t.role,organizationId:t.organizationId,status:"pending",expiresAt:s,inviterId:n.id}})},findInvitationById:async t=>await r.findOne({model:"invitation",where:[{field:"id",value:t}]}),findPendingInvitation:async t=>(await r.findMany({model:"invitation",where:[{field:"email",value:t.email},{field:"organizationId",value:t.organizationId},{field:"status",value:"pending"}]})).filter(i=>new Date(i.expiresAt)>new Date),updateInvitation:async t=>await r.update({model:"invitation",where:[{field:"id",value:t.invitationId}],update:{status:t.status}})}};var Qd=require("better-call");var L=P(async e=>({})),D=P({use:[b]},async e=>({session:e.context.session}));var q=require("zod");var E=require("zod"),Sr=E.z.string(),pn=E.z.enum(["pending","accepted","rejected","canceled"]).default("pending"),Zd=E.z.object({id:E.z.string(),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()}),Yd=E.z.object({id:E.z.string(),organizationId:E.z.string(),userId:E.z.string(),role:Sr,createdAt:E.z.date()}),Xd=E.z.object({id:E.z.string(),organizationId:E.z.string(),email:E.z.string(),role:Sr,status:pn,inviterId:E.z.string(),expiresAt:E.z.date()});var S=require("better-call"),Pr=e=>u("/organization/invite-member",{method:"POST",use:[L,D],body:q.z.object({email:q.z.string(),role:q.z.string(),organizationId:q.z.string().optional(),resend:q.z.boolean().optional()})},async o=>{if(!o.context.orgOptions.sendInvitationEmail)throw o.context.logger.warn("Invitation email is not enabled. Pass `sendInvitationEmail` to the plugin options to enable it."),new S.APIError("BAD_REQUEST",{message:"Invitation email is not enabled"});let r=o.context.session,t=o.body.organizationId||r.session.activeOrganizationId;if(!t)throw new S.APIError("BAD_REQUEST",{message:"Organization not found"});let n=_(o.context,o.context.orgOptions),i=await n.findMemberByOrgId({userId:r.user.id,organizationId:t});if(!i)throw new S.APIError("BAD_REQUEST",{message:"Member not found!"});let s=o.context.roles[i.role];if(!s)throw new S.APIError("BAD_REQUEST",{message:"Role not found!"});if(s.authorize({invitation:["create"]}).error)throw new S.APIError("FORBIDDEN",{message:"You are not allowed to invite members"});if(await n.findMemberByEmail({email:o.body.email,organizationId:t}))throw new S.APIError("BAD_REQUEST",{message:"User is already a member of this organization"});if((await n.findPendingInvitation({email:o.body.email,organizationId:t})).length&&!o.body.resend)throw new S.APIError("BAD_REQUEST",{message:"User is already invited to this organization"});let l=await n.createInvitation({invitation:{role:o.body.role,email:o.body.email,organizationId:t},user:r.user}),p=await n.findOrganizationById(t);if(!p)throw new S.APIError("BAD_REQUEST",{message:"Organization not found"});return await o.context.orgOptions.sendInvitationEmail?.({id:l.id,role:l.role,email:l.email,organization:p,inviter:{...i,user:r.user}},o.request),o.json(l)}),_r=u("/organization/accept-invitation",{method:"POST",body:q.z.object({invitationId:q.z.string()}),use:[L,D]},async e=>{let o=e.context.session,r=_(e.context,e.context.orgOptions),t=await r.findInvitationById(e.body.invitationId);if(!t||t.expiresAt<new Date||t.status!=="pending")throw new S.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(t.email!==o.user.email)throw new S.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let n=await r.updateInvitation({invitationId:e.body.invitationId,status:"accepted"}),i=await r.createMember({id:x(),organizationId:t.organizationId,userId:o.user.id,role:t.role,createdAt:new Date});return await r.setActiveOrganization(o.session.id,t.organizationId),n?e.json({invitation:n,member:i}):e.json(null,{status:400,body:{message:"Invitation not found!"}})}),Cr=u("/organization/reject-invitation",{method:"POST",body:q.z.object({invitationId:q.z.string()}),use:[L,D]},async e=>{let o=e.context.session,r=_(e.context,e.context.orgOptions),t=await r.findInvitationById(e.body.invitationId);if(!t||t.expiresAt<new Date||t.status!=="pending")throw new S.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(t.email!==o.user.email)throw new S.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let n=await r.updateInvitation({invitationId:e.body.invitationId,status:"rejected"});return e.json({invitation:n,member:null})}),zr=u("/organization/cancel-invitation",{method:"POST",body:q.z.object({invitationId:q.z.string()}),use:[L,D]},async e=>{let o=e.context.session,r=_(e.context,e.context.orgOptions),t=await r.findInvitationById(e.body.invitationId);if(!t)throw new S.APIError("BAD_REQUEST",{message:"Invitation not found!"});let n=await r.findMemberByOrgId({userId:o.user.id,organizationId:t.organizationId});if(!n)throw new S.APIError("BAD_REQUEST",{message:"Member not found!"});if(e.context.roles[n.role].authorize({invitation:["cancel"]}).error)throw new S.APIError("FORBIDDEN",{message:"You are not allowed to cancel this invitation"});let s=await r.updateInvitation({invitationId:e.body.invitationId,status:"canceled"});return e.json(s)}),xr=u("/organization/get-invitation",{method:"GET",use:[L],requireHeaders:!0,query:q.z.object({id:q.z.string()})},async e=>{let o=await z(e);if(!o)throw new S.APIError("UNAUTHORIZED",{message:"Not authenticated"});let r=_(e.context,e.context.orgOptions),t=await r.findInvitationById(e.query.id);if(!t||t.status!=="pending"||t.expiresAt<new Date)throw new S.APIError("BAD_REQUEST",{message:"Invitation not found!"});if(t.email!==o.user.email)throw new S.APIError("FORBIDDEN",{message:"You are not the recipient of the invitation"});let n=await r.findOrganizationById(t.organizationId);if(!n)throw new S.APIError("BAD_REQUEST",{message:"Organization not found"});let i=await r.findMemberByOrgId({userId:t.inviterId,organizationId:t.organizationId});if(!i)throw new S.APIError("BAD_REQUEST",{message:"Inviter is no longer a member of the organization"});return e.json({...t,organizationName:n.name,organizationSlug:n.slug,inviterEmail:i.user.email})});var pe=require("zod");var Te=require("better-call"),Lr=u("/organization/remove-member",{method:"POST",body:pe.z.object({memberIdOrEmail:pe.z.string(),organizationId:pe.z.string().optional()}),use:[L,D]},async e=>{let o=e.context.session,r=e.body.organizationId||o.session.activeOrganizationId;if(!r)return e.json(null,{status:400,body:{message:"No active organization found!"}});let t=_(e.context,e.context.orgOptions),n=await t.findMemberByOrgId({userId:o.user.id,organizationId:r});if(!n)throw new Te.APIError("BAD_REQUEST",{message:"Member not found!"});let i=e.context.roles[n.role];if(!i)throw new Te.APIError("BAD_REQUEST",{message:"Role not found!"});let s=o.user.email===e.body.memberIdOrEmail||n.id===e.body.memberIdOrEmail;if(s&&n.role===(e.context.orgOptions?.creatorRole||"owner"))throw new Te.APIError("BAD_REQUEST",{message:"You cannot leave the organization as the owner"});if(!(s||i.authorize({member:["delete"]}).success))throw new Te.APIError("UNAUTHORIZED",{message:"You are not allowed to delete this member"});let c=null;if(e.body.memberIdOrEmail.includes("@")?c=await t.findMemberByEmail({email:e.body.memberIdOrEmail,organizationId:r}):c=await t.findMemberById(e.body.memberIdOrEmail),c?.organizationId!==r)throw new Te.APIError("BAD_REQUEST",{message:"Member not found!"});return await t.deleteMember(c.id),o.user.id===c.userId&&o.session.activeOrganizationId===c.organizationId&&await t.setActiveOrganization(o.session.id,null),e.json({member:c})}),Br=e=>u("/organization/update-member-role",{method:"POST",body:pe.z.object({role:pe.z.string(),memberId:pe.z.string(),organizationId:pe.z.string().optional()}),use:[L,D]},async o=>{let r=o.context.session,t=o.body.organizationId||r.session.activeOrganizationId;if(!t)return o.json(null,{status:400,body:{message:"No active organization found!"}});let n=_(o.context,o.context.orgOptions),i=await n.findMemberByOrgId({userId:r.user.id,organizationId:t});if(!i)return o.json(null,{status:400,body:{message:"Member not found!"}});let s=o.context.roles[i.role];if(!s)return o.json(null,{status:400,body:{message:"Role not found!"}});if(s.authorize({member:["update"]}).error||o.body.role==="owner"&&i.role!=="owner")return o.json(null,{body:{message:"You are not allowed to update this member"},status:403});let d=await n.updateMember(o.body.memberId,o.body.role);return d?o.json(d):o.json(null,{status:400,body:{message:"Member not found!"}})}),Dr=u("/organization/get-active-member",{method:"GET",use:[L,D]},async e=>{let o=e.context.session,r=o.session.activeOrganizationId;if(!r)return e.json(null,{status:400,body:{message:"No active organization found!"}});let n=await _(e.context,e.context.orgOptions).findMemberByOrgId({userId:o.user.id,organizationId:r});return n?e.json(n):e.json(null,{status:400,body:{message:"Member not found!"}})});var U=require("zod");var me=require("better-call"),Nr=u("/organization/create",{method:"POST",body:U.z.object({name:U.z.string(),slug:U.z.string(),userId:U.z.string().optional(),logo:U.z.string().optional(),metadata:U.z.record(U.z.string(),U.z.any()).optional()}),use:[L,D]},async e=>{let o=e.context.session.user;if(!o)return e.json(null,{status:401});let r=e.context.orgOptions;if(!(typeof r?.allowUserToCreateOrganization=="function"?await r.allowUserToCreateOrganization(o):r?.allowUserToCreateOrganization===void 0?!0:r.allowUserToCreateOrganization))throw new me.APIError("FORBIDDEN",{message:"You are not allowed to create an organization"});let n=_(e.context,r),i=await n.listOrganizations(o.id);if(typeof r.organizationLimit=="number"?i.length>=r.organizationLimit:typeof r.organizationLimit=="function"?await r.organizationLimit(o):!1)throw new me.APIError("FORBIDDEN",{message:"You have reached the organization limit"});if(await n.findOrganizationBySlug(e.body.slug))throw new me.APIError("BAD_REQUEST",{message:"Organization with this slug already exists"});let d=await n.createOrganization({organization:{id:x(),slug:e.body.slug,name:e.body.name,logo:e.body.logo,createdAt:new Date,metadata:e.body.metadata},user:o});return await n.setActiveOrganization(e.context.session.session.id,d.id),e.json(d)}),jr=u("/organization/update",{method:"POST",body:U.z.object({data:U.z.object({name:U.z.string().optional(),slug:U.z.string().optional(),logo:U.z.string().optional()}).partial(),organizationId:U.z.string().optional()}),requireHeaders:!0,use:[L]},async e=>{let o=await e.context.getSession(e);if(!o)throw new me.APIError("UNAUTHORIZED",{message:"User not found"});let r=e.body.organizationId||o.session.activeOrganizationId;if(!r)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let t=_(e.context,e.context.orgOptions),n=await t.findMemberByOrgId({userId:o.user.id,organizationId:r});if(!n)return e.json(null,{status:400,body:{message:"User is not a member of this organization!"}});let i=e.context.roles[n.role];if(!i)return e.json(null,{status:400,body:{message:"Role not found!"}});if(i.authorize({organization:["update"]}).error)return e.json(null,{body:{message:"You are not allowed to update this organization"},status:403});let a=await t.updateOrganization(r,e.body.data);return e.json(a)}),Vr=u("/organization/delete",{method:"POST",body:U.z.object({organizationId:U.z.string()}),requireHeaders:!0,use:[L]},async e=>{let o=await e.context.getSession(e);if(!o)return e.json(null,{status:401});let r=e.body.organizationId;if(!r)return e.json(null,{status:400,body:{message:"Organization id not found!"}});let t=_(e.context,e.context.orgOptions),n=await t.findMemberByOrgId({userId:o.user.id,organizationId:r});if(!n)return e.json(null,{status:400,body:{message:"User is not a member of this organization!"}});let i=e.context.roles[n.role];if(!i)return e.json(null,{status:400,body:{message:"Role not found!"}});if(i.authorize({organization:["delete"]}).error)throw new me.APIError("FORBIDDEN",{message:"You are not allowed to delete this organization"});return r===o.session.activeOrganizationId&&await t.setActiveOrganization(o.session.id,null),await t.deleteOrganization(r),e.json(r)}),Fr=u("/organization/get-full-organization",{method:"GET",query:U.z.optional(U.z.object({organizationId:U.z.string().optional()})),requireHeaders:!0,use:[L,D]},async e=>{let o=e.context.session,r=e.query?.organizationId||o.session.activeOrganizationId;if(!r)return e.json(null,{status:200});let n=await _(e.context,e.context.orgOptions).findFullOrganization(r);if(!n)throw new me.APIError("BAD_REQUEST",{message:"Organization not found"});return e.json(n)}),qr=u("/organization/set-active",{method:"POST",body:U.z.object({organizationId:U.z.string().nullable().optional()}),use:[D,L]},async e=>{let o=_(e.context,e.context.orgOptions),r=e.context.session,t=e.body.organizationId;if(t===null)return r.session.activeOrganizationId&&await o.setActiveOrganization(r.session.id,null),e.json(null);if(!t){let s=r.session.activeOrganizationId;if(!s)return e.json(null);t=s}if(!await o.findMemberByOrgId({userId:r.user.id,organizationId:t}))throw await o.setActiveOrganization(r.session.id,null),new me.APIError("FORBIDDEN",{message:"You are not a member of this organization"});await o.setActiveOrganization(r.session.id,t);let i=await o.findFullOrganization(t);return e.json(i)}),Mr=u("/organization/list",{method:"GET",use:[L,D]},async e=>{let r=await _(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(r)});var mn=it({name:["action"]}),Ic=mn.newRole({name:["action"]}),fn=e=>{let o={createOrganization:Nr,updateOrganization:jr,deleteOrganization:Vr,setActiveOrganization:qr,getFullOrganization:Fr,listOrganization:Mr,createInvitation:Pr(e),cancelInvitation:zr,acceptInvitation:_r,getInvitation:xr,rejectInvitation:Cr,removeMember:Lr,updateMemberRole:Br(e),getActiveMember:Dr},r={...Tr,...e?.roles};return{id:"organization",endpoints:{...Ur(o,{orgOptions:e||{},roles:r,getSession:async n=>await z(n)}),hasPermission:u("/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:[D]},async n=>{if(!n.context.session.session.activeOrganizationId)throw new At.APIError("BAD_REQUEST",{message:"No active organization"});let s=await _(n.context).findMemberByOrgId({userId:n.context.session.user.id,organizationId:n.context.session.session.activeOrganizationId||""});if(!s)throw new At.APIError("UNAUTHORIZED",{message:"You are not a member of this organization"});let d=r[s.role].authorize(n.body.permission);return d.error?n.json({error:d.error,success:!1},{status:403}):n.json({error:null,success:!0})})},schema:{session:{fields:{activeOrganizationId:{type:"string",required:!1,fieldName:e?.schema?.session?.fields?.activeOrganizationId}}},organization:{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:{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},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:{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 kt=Dt(require("uncrypto"),1);function gn(e){return e.toString(2).padStart(8,"0")}function hn(e){return[...e].map(o=>gn(o)).join("")}function $r(e){return parseInt(hn(e),2)}function wn(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let o=(e-1).toString(2).length,r=o%8,t=new Uint8Array(Math.ceil(o/8));kt.default.getRandomValues(t),r!==0&&(t[0]&=(1<<r)-1);let n=$r(t);for(;n>=e;)kt.default.getRandomValues(t),r!==0&&(t[0]&=(1<<r)-1),n=$r(t);return n}function M(e,o){let r="";for(let t=0;t<e;t++)r+=o[wn(o.length)];return r}function $(...e){let o=new Set(e),r="";for(let t of o)t==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":t==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":t==="0-9"?r+="0123456789":r+=t;return r}var $e=require("zod");var vt=require("@noble/ciphers/chacha"),Pe=require("@noble/ciphers/utils"),Rt=require("@noble/ciphers/webcrypto"),Et=require("oslo/crypto"),Ot=Dt(require("uncrypto"),1);var Hr=require("oslo/encoding");var yn=require("@noble/hashes/scrypt"),bn=require("uncrypto");async function Ve(e,o){let r=new TextEncoder,t={name:"HMAC",hash:"SHA-256"},n=await Ot.default.subtle.importKey("raw",r.encode(e),t,!1,["sign","verify"]),i=await Ot.default.subtle.sign(t.name,n,r.encode(o));return btoa(String.fromCharCode(...new Uint8Array(i)))}var ae=async({key:e,data:o})=>{let r=await(0,Et.sha256)(new TextEncoder().encode(e)),t=(0,Pe.utf8ToBytes)(o),n=(0,Rt.managedNonce)(vt.xchacha20poly1305)(new Uint8Array(r));return(0,Pe.bytesToHex)(n.encrypt(t))},fe=async({key:e,data:o})=>{let r=await(0,Et.sha256)(new TextEncoder().encode(e)),t=(0,Pe.hexToBytes)(o),n=(0,Rt.managedNonce)(vt.xchacha20poly1305)(new Uint8Array(r));return new TextDecoder().decode(n.decrypt(t))};var ne=require("zod");var _e=require("better-call");var st="two_factor";var at="trust_device";var It=require("zod");var ye=P({body:It.z.object({trustDevice:It.z.boolean().optional()})},async e=>{let o=await z(e);if(!o){let r=e.context.createAuthCookie(st),t=await e.getSignedCookie(r.name,e.context.secret);if(!t)throw new _e.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let n=await e.context.internalAdapter.findUserById(t);if(!n)throw new _e.APIError("UNAUTHORIZED",{message:"invalid two factor cookie"});let i=await e.context.internalAdapter.createSession(t,e.request);if(!i)throw new _e.APIError("INTERNAL_SERVER_ERROR",{message:"failed to create session"});return{valid:async()=>{if(await w(e,{session:i,user:n}),e.body.trustDevice){let s=e.context.createAuthCookie(at,{maxAge:2592e3}),a=await Ve(e.context.secret,`${n.id}!${i.id}`);await e.setSignedCookie(s.name,`${a}!${i.id}`,e.context.secret,s.attributes)}return e.json({session:i,user:n})},invalid:async()=>{throw new _e.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:{id:i.id,userId:i.userId,expiresAt:i.expiresAt,user:n}}}return{valid:async()=>e.json({session:o,user:o.user}),invalid:async()=>{throw new _e.APIError("UNAUTHORIZED",{message:"invalid two factor authentication"})},session:o}});var Ce=require("better-call");function An(e){return Array.from({length:e?.amount??10}).fill(null).map(()=>M(e?.length??10,$("a-z","0-9"))).map(o=>`${o.slice(0,5)}-${o.slice(5)}`)}async function Ut(e,o){let r=e,t=o?.customBackupCodesGenerate?o.customBackupCodesGenerate():An(),n=await ae({data:JSON.stringify(t),key:r});return{backupCodes:t,encryptedBackupCodes:n}}async function kn(e,o){let r=await Qr(e.backupCodes,o);return r?{status:r.includes(e.code),updated:r.filter(t=>t!==e.code)}:{status:!1,updated:null}}async function Qr(e,o){let r=Buffer.from(await fe({key:o,data:e})).toString("utf-8"),t=JSON.parse(r),n=ne.z.array(ne.z.string()).safeParse(t);return n.success?n.data:null}var Wr=(e,o)=>({id:"backup_code",endpoints:{verifyBackupCode:u("/two-factor/verify-backup-code",{method:"POST",body:ne.z.object({code:ne.z.string(),disableSession:ne.z.boolean().optional()}),use:[ye]},async r=>{let t=r.context.session.user,n=await r.context.adapter.findOne({model:o,where:[{field:"userId",value:t.id}]});if(!n)throw new Ce.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let i=await kn({backupCodes:n.backupCodes,code:r.body.code},r.context.secret);if(!i.status)throw new Ce.APIError("UNAUTHORIZED",{message:"Invalid backup code"});let s=await ae({key:r.context.secret,data:JSON.stringify(i.updated)});return await r.context.adapter.update({model:o,update:{backupCodes:s},where:[{field:"userId",value:t.id}]}),r.body.disableSession||await w(r,{session:r.context.session,user:t}),r.json({user:t,session:r.context.session})}),generateBackupCodes:u("/two-factor/generate-backup-codes",{method:"POST",body:ne.z.object({password:ne.z.string()}),use:[b]},async r=>{let t=r.context.session.user;if(!t.twoFactorEnabled)throw new Ce.APIError("BAD_REQUEST",{message:"Two factor isn't enabled"});await r.context.password.checkPassword(t.id,r);let n=await Ut(r.context.secret,e);return await r.context.adapter.update({model:o,update:{backupCodes:n.encryptedBackupCodes},where:[{field:"userId",value:r.context.session.user.id}]}),r.json({status:!0,backupCodes:n.backupCodes})}),viewBackupCodes:u("/two-factor/view-backup-codes",{method:"GET",body:ne.z.object({userId:ne.z.string()}),metadata:{SERVER_ONLY:!0}},async r=>{let t=await r.context.adapter.findOne({model:o,where:[{field:"userId",value:r.body.userId}]});if(!t)throw new Ce.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});let n=await Qr(t.backupCodes,r.context.secret);if(!n)throw new Ce.APIError("BAD_REQUEST",{message:"Backup codes aren't enabled"});return r.json({status:!0,backupCodes:n})})}});var Fe=require("better-call"),Gr=require("oslo/otp"),Tt=require("zod");var Kr=require("oslo"),Jr=(e,o)=>{let r={...e,period:new Kr.TimeSpan(e?.period||3,"m")},t=new Gr.TOTPController({digits:6,period:r.period}),n=u("/two-factor/send-otp",{method:"POST",use:[ye]},async s=>{if(!e||!e.sendOTP)throw s.context.logger.error("send otp isn't configured. Please configure the send otp function on otp options."),new Fe.APIError("BAD_REQUEST",{message:"otp isn't configured"});let a=s.context.session.user,d=await s.context.adapter.findOne({model:o,where:[{field:"userId",value:a.id}]});if(!d)throw new Fe.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});let c=await t.generate(Buffer.from(d.secret));return await e.sendOTP({user:a,otp:c},s.request),s.json({status:!0})}),i=u("/two-factor/verify-otp",{method:"POST",body:Tt.z.object({code:Tt.z.string()}),use:[ye]},async s=>{let a=s.context.session.user;if(!a.twoFactorEnabled)throw new Fe.APIError("BAD_REQUEST",{message:"two factor isn't enabled"});let d=await s.context.adapter.findOne({model:o,where:[{field:"userId",value:a.id}]});if(!d)throw new Fe.APIError("BAD_REQUEST",{message:"OTP isn't enabled"});return await t.generate(Buffer.from(d.secret))===s.body.code?s.context.valid():s.context.invalid()});return{id:"otp",endpoints:{send2FaOTP:n,verifyOTP:i}}};var be=require("better-call"),Zr=require("oslo"),Me=require("oslo/otp"),qe=require("zod");var Yr=(e,o)=>{let r={...e,digits:6,period:new Zr.TimeSpan(e?.period||30,"s")},t=u("/totp/generate",{method:"POST",use:[b]},async s=>{if(!e)throw s.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new be.APIError("BAD_REQUEST",{message:"totp isn't configured"});let a=s.context.session.user,d=await s.context.adapter.findOne({model:o,where:[{field:"userId",value:a.id}]});if(!d)throw new be.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return{code:await new Me.TOTPController(r).generate(Buffer.from(d.secret))}}),n=u("/two-factor/get-totp-uri",{method:"POST",use:[b],body:qe.z.object({password:qe.z.string()})},async s=>{if(!e)throw s.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new be.APIError("BAD_REQUEST",{message:"totp isn't configured"});let a=s.context.session.user,d=await s.context.adapter.findOne({model:o,where:[{field:"userId",value:a.id}]});if(!d||!a.twoFactorEnabled)throw new be.APIError("BAD_REQUEST",{message:"totp isn't enabled"});return await s.context.password.checkPassword(a.id,s),{totpURI:(0,Me.createTOTPKeyURI)(e.issuer||s.context.appName,a.email,Buffer.from(d.secret),r)}}),i=u("/two-factor/verify-totp",{method:"POST",body:qe.z.object({code:qe.z.string()}),use:[ye]},async s=>{if(!e)throw s.context.logger.error("totp isn't configured. please pass totp option on two factor plugin to enable totp"),new be.APIError("BAD_REQUEST",{message:"totp isn't configured"});let a=s.context.session.user,d=await s.context.adapter.findOne({model:o,where:[{field:"userId",value:a.id}]});if(!d)throw new be.APIError("BAD_REQUEST",{message:"totp isn't enabled"});let c=new Me.TOTPController(r),l=await fe({key:s.context.secret,data:d.secret}),p=Buffer.from(l);if(!await c.verify(s.body.code,p))return s.context.invalid();if(!a.twoFactorEnabled){let m=await s.context.internalAdapter.updateUser(a.id,{twoFactorEnabled:!0}),g=await s.context.internalAdapter.createSession(a.id,s.request);await w(s,{session:g,user:m})}return s.context.valid()});return{id:"totp",endpoints:{generateTOTP:t,viewTOTPURI:n,verifyTOTP:i}}};var On=require("better-call");async function St(e,o){let t=(await e.context.internalAdapter.findAccounts(o.userId))?.find(s=>s.providerId==="credential"),n=t?.password;return!t||!n?!1:await e.context.password.verify(n,o.password)}var Pt=require("better-call"),to=require("oslo/otp"),ro=require("oslo");var Xr=require("better-call"),ze=async e=>{let o=e.context.returned;return o?o instanceof Response?o.status!==200?null:await o.clone().json():o instanceof Xr.APIError?null:o:null};var eo={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 vn=(e={redirect:!0,twoFactorPage:"/"})=>({id:"two-factor",$InferServerPlugin:{},atomListeners:[{matcher:o=>o.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(o){o.data?.twoFactorRedirect&&(e.redirect||e.twoFactorPage)&&typeof window<"u"&&(window.location.href=e.twoFactorPage)}}}]});var Rn=e=>{let o={twoFactorTable:"twoFactor"},r=Yr({issuer:e?.issuer,...e?.totpOptions},o.twoFactorTable),t=Wr({...e?.backupCodeOptions},o.twoFactorTable),n=Jr({...e?.otpOptions},o.twoFactorTable);return{id:"two-factor",endpoints:{...r.endpoints,...n.endpoints,...t.endpoints,enableTwoFactor:u("/two-factor/enable",{method:"POST",body:$e.z.object({password:$e.z.string().min(8)}),use:[b]},async i=>{let s=i.context.session.user,{password:a}=i.body;if(!await St(i,{password:a,userId:s.id}))throw new Pt.APIError("BAD_REQUEST",{message:"Invalid password"});let c=M(16,$("a-z","0-9","-")),l=await ae({key:i.context.secret,data:c}),p=await Ut(i.context.secret,e?.backupCodeOptions);if(e?.skipVerificationOnEnable){let m=await i.context.internalAdapter.updateUser(s.id,{twoFactorEnabled:!0}),g=await i.context.internalAdapter.createSession(m.id,i.request);await w(i,{session:g,user:s})}await i.context.adapter.deleteMany({model:o.twoFactorTable,where:[{field:"userId",value:s.id}]}),await i.context.adapter.create({model:o.twoFactorTable,data:{id:i.context.uuid(),secret:l,backupCodes:p.encryptedBackupCodes,userId:s.id}});let f=(0,to.createTOTPKeyURI)(e?.issuer||"BetterAuth",s.email,Buffer.from(c),{digits:e?.totpOptions?.digits||6,period:new ro.TimeSpan(e?.totpOptions?.period||30,"s")});return i.json({totpURI:f,backupCodes:p.backupCodes})}),disableTwoFactor:u("/two-factor/disable",{method:"POST",body:$e.z.object({password:$e.z.string().min(8)}),use:[b]},async i=>{let s=i.context.session.user,{password:a}=i.body;if(!await St(i,{password:a,userId:s.id}))throw new Pt.APIError("BAD_REQUEST",{message:"Invalid password"});return await i.context.internalAdapter.updateUser(s.id,{twoFactorEnabled:!1}),await i.context.adapter.delete({model:o.twoFactorTable,where:[{field:"userId",value:s.id}]}),i.json({status:!0})})},options:e,hooks:{after:[{matcher(i){return i.path==="/sign-in/email"||i.path==="/sign-in/username"},handler:P(async i=>{let s=await ze(i);if(!s||!s.user.twoFactorEnabled)return;let a=i.context.createAuthCookie(at),d=await i.getSignedCookie(a.name,i.context.secret);if(d){let[p,f]=d.split("!"),m=await Ve(i.context.secret,`${s.user.id}!${f}`);if(p===m){let g=await Ve(i.context.secret,`${s.user.id}!${s.session.id}`);await i.setSignedCookie(a.name,`${g}!${s.session.id}`,i.context.secret,a.attributes);return}}te(i),await i.context.internalAdapter.deleteSession(s.session.id);let c=i.context.createAuthCookie(st,{maxAge:60*10});return await i.setSignedCookie(c.name,s.user.id,i.context.secret,c.attributes),{response:{twoFactorRedirect:!0},responseHeader:i.responseHeader}})}]},schema:K(eo,e?.schema),rateLimit:[{pathMatcher(i){return i.startsWith("/two-factor/")},window:10,max:3}]}};var ge=require("@simplewebauthn/server"),J=require("better-call");var ie=require("zod");var xe=require("@simplewebauthn/browser");var In=require("@better-fetch/fetch");var Nu=require("nanostores");var Iu=require("@better-fetch/fetch");var En=require("nanostores");var Tu=require("@better-fetch/fetch"),dt=require("nanostores"),_t=(e,o,r,t)=>{let n=(0,dt.atom)({data:null,error:null,isPending:!0,isRefetching:!1}),i=()=>{let a=typeof t=="function"?t({data:n.get().data,error:n.get().error,isPending:n.get().isPending}):t;return r(o,{...a,async onSuccess(d){n.set({data:d.data,error:null,isPending:!1,isRefetching:!1}),await a?.onSuccess?.(d)},async onError(d){n.set({error:d.error,data:null,isPending:!1,isRefetching:!1}),await a?.onError?.(d)},async onRequest(d){let c=n.get();n.set({isPending:c.data===null,data:c.data,error:null,isRefetching:!0}),await a?.onRequest?.(d)}})};e=Array.isArray(e)?e:[e];let s=!1;for(let a of e)a.subscribe(()=>{s?i():(0,dt.onMount)(n,()=>(i(),s=!0,()=>{n.off(),a.off()}))});return n};var oo=require("nanostores"),no=(e,{$listPasskeys:o})=>({signIn:{passkey:async(n,i)=>{let s=await e("/passkey/generate-authenticate-options",{method:"POST",body:{email:n?.email}});if(!s.data)return s;try{let a=await(0,xe.startAuthentication)(s.data,n?.autoFill||!1),d=await e("/passkey/verify-authentication",{body:{response:a},...n?.fetchOptions,...i,method:"POST"});if(!d.data)return d}catch{return{data:null,error:{message:"auth cancelled",status:400,statusText:"BAD_REQUEST"}}}}},passkey:{addPasskey:async(n,i)=>{let s=await e("/passkey/generate-register-options",{method:"GET"});if(!s.data)return s;try{let a=await(0,xe.startRegistration)(s.data),d=await e("/passkey/verify-registration",{...n?.fetchOptions,...i,body:{response:a,name:n?.name},method:"POST"});if(!d.data)return d;o.set(Math.random())}catch(a){return a instanceof xe.WebAuthnError?a.code==="ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED"?{data:null,error:{message:"previously registered",status:400,statusText:"BAD_REQUEST"}}:a.code==="ERROR_CEREMONY_ABORTED"?{data:null,error:{message:"registration cancelled",status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:a.message,status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:a instanceof Error?a.message:"unknown error",status:500,statusText:"INTERNAL_SERVER_ERROR"}}}}},$Infer:{}}),Un=()=>{let e=(0,oo.atom)();return{id:"passkey",$InferServerPlugin:{},getActions:o=>no(o,{$listPasskeys:e}),getAtoms(o){return{listPasskeys:_t(e,"/passkey/list-user-passkeys",o,{method:"GET"}),$listPasskeys:e}},pathMethods:{"/passkey/register":"POST","/passkey/authenticate":"POST"},atomListeners:[{matcher(o){return o==="/passkey/verify-registration"||o==="/passkey/delete-passkey"},signal:"_listPasskeys"}]}};var Tn=e=>{let o=ee.BETTER_AUTH_URL,r=e?.rpID||o?.replace("http://","").replace("https://","").split(":")[0]||"localhost";if(!r)throw new X("passkey rpID not found. Please provide a rpID in the options or set the BETTER_AUTH_URL environment variable.");let t={origin:null,...e,rpID:r,advanced:{webAuthnChallengeCookie:"better-auth-passkey",...e?.advanced}},n=new Date(Date.now()+1e3*60*5),i=new Date,s=Math.floor((n.getTime()-i.getTime())/1e3);return{id:"passkey",endpoints:{generatePasskeyRegistrationOptions:u("/passkey/generate-register-options",{method:"GET",use:[b],metadata:{client:!1}},async a=>{let d=a.context.session,c=await a.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}),l=new Uint8Array(Buffer.from(M(32,$("a-z","0-9")))),p;p=await(0,ge.generateRegistrationOptions)({rpName:t.rpName||a.context.appName,rpID:t.rpID,userID:l,userName:d.user.email||d.user.id,attestationType:"none",excludeCredentials:c.map(m=>({id:m.id,transports:m.transports?.split(",")})),authenticatorSelection:{residentKey:"preferred",userVerification:"preferred",authenticatorAttachment:"platform"}});let f=x();return await a.setSignedCookie(t.advanced.webAuthnChallengeCookie,f,a.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:s}),await a.context.internalAdapter.createVerificationValue({identifier:f,value:JSON.stringify({expectedChallenge:p.challenge,userData:{id:d.user.id}}),expiresAt:n}),a.json(p,{status:200})}),generatePasskeyAuthenticationOptions:u("/passkey/generate-authenticate-options",{method:"POST",body:ie.z.object({email:ie.z.string().optional()}).optional()},async a=>{let d=await z(a),c=[];d&&(c=await a.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:d.user.id}]}));let l=await(0,ge.generateAuthenticationOptions)({rpID:t.rpID,userVerification:"preferred",...c.length?{allowCredentials:c.map(m=>({id:m.id,transports:m.transports?.split(",")}))}:{}}),p={expectedChallenge:l.challenge,userData:{id:d?.user.id||""}},f=x();return await a.setSignedCookie(t.advanced.webAuthnChallengeCookie,f,a.context.secret,{secure:!0,httpOnly:!0,sameSite:"lax",maxAge:s}),await a.context.internalAdapter.createVerificationValue({identifier:f,value:JSON.stringify(p),expiresAt:n}),a.json(l,{status:200})}),verifyPasskeyRegistration:u("/passkey/verify-registration",{method:"POST",body:ie.z.object({response:ie.z.any(),name:ie.z.string().optional()}),use:[b]},async a=>{let d=e?.origin||a.headers?.get("origin")||"";if(!d)return a.json(null,{status:400});let c=a.body.response,l=await a.getSignedCookie(t.advanced.webAuthnChallengeCookie,a.context.secret);if(!l)throw new J.APIError("BAD_REQUEST",{message:"Challenge not found"});let p=await a.context.internalAdapter.findVerificationValue(l);if(!p)return a.json(null,{status:400});let{expectedChallenge:f,userData:m}=JSON.parse(p.value);if(m.id!==a.context.session.user.id)throw new J.APIError("UNAUTHORIZED",{message:"You are not authorized to register this passkey"});try{let g=await(0,ge.verifyRegistrationResponse)({response:c,expectedChallenge:f,expectedOrigin:d,expectedRPID:e?.rpID}),{verified:v,registrationInfo:H}=g;if(!v||!H)return a.json(null,{status:400});let{credentialID:oe,credentialPublicKey:Y,counter:y,credentialDeviceType:C,credentialBackedUp:De}=H,lo=Buffer.from(Y).toString("base64"),po=x(),mo={name:a.body.name,userId:m.id,webauthnUserID:po,id:oe,publicKey:lo,counter:y,deviceType:C,transports:c.response.transports.join(","),backedUp:De,createdAt:new Date},fo=await a.context.adapter.create({model:"passkey",data:mo});return a.json(fo,{status:200})}catch(g){throw console.log(g),new J.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to verify registration"})}}),verifyPasskeyAuthentication:u("/passkey/verify-authentication",{method:"POST",body:ie.z.object({response:ie.z.any()})},async a=>{let d=e?.origin||a.headers?.get("origin")||"";if(!d)throw new J.APIError("BAD_REQUEST",{message:"origin missing"});let c=a.body.response,l=await a.getSignedCookie(t.advanced.webAuthnChallengeCookie,a.context.secret);if(!l)throw new J.APIError("BAD_REQUEST",{message:"Challenge not found"});let p=await a.context.internalAdapter.findVerificationValue(l);if(!p)throw new J.APIError("BAD_REQUEST",{message:"Challenge not found"});let{expectedChallenge:f}=JSON.parse(p.value),m=await a.context.adapter.findOne({model:"passkey",where:[{field:"id",value:c.id}]});if(!m)throw new J.APIError("UNAUTHORIZED",{message:"Passkey not found"});try{let g=await(0,ge.verifyAuthenticationResponse)({response:c,expectedChallenge:f,expectedOrigin:d,expectedRPID:t.rpID,authenticator:{credentialID:m.id,credentialPublicKey:new Uint8Array(Buffer.from(m.publicKey,"base64")),counter:m.counter,transports:m.transports?.split(",")}}),{verified:v}=g;if(!v)throw new J.APIError("UNAUTHORIZED",{message:"Authentication failed"});await a.context.adapter.update({model:"passkey",where:[{field:"id",value:m.id}],update:{counter:g.authenticationInfo.newCounter}});let H=await a.context.internalAdapter.createSession(m.userId,a.request);if(!H)throw new J.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});let oe=await a.context.internalAdapter.findUserById(m.userId);if(!oe)throw new J.APIError("INTERNAL_SERVER_ERROR",{message:"User not found"});return await w(a,{session:H,user:oe}),a.json({session:H},{status:200})}catch(g){throw a.context.logger.error("Failed to verify authentication",g),new J.APIError("BAD_REQUEST",{message:"Failed to verify authentication"})}}),listPasskeys:u("/passkey/list-user-passkeys",{method:"GET",use:[b]},async a=>{let d=await a.context.adapter.findMany({model:"passkey",where:[{field:"userId",value:a.context.session.user.id}]});return a.json(d,{status:200})}),deletePasskey:u("/passkey/delete-passkey",{method:"POST",body:ie.z.object({id:ie.z.string()}),use:[b]},async a=>(await a.context.adapter.delete({model:"passkey",where:[{field:"id",value:a.body.id}]}),a.json(null,{status:200})))},schema:K(Sn,e?.schema)}},Sn={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 He=require("zod");var Qe=require("better-call"),Ct=()=>({id:"username",endpoints:{signInUsername:u("/sign-in/username",{method:"POST",body:He.z.object({username:He.z.string(),password:He.z.string(),rememberMe:He.z.boolean().optional()})},async e=>{let o=await e.context.adapter.findOne({model:e.context.tables.user.modelName,where:[{field:"username",value:e.body.username}]});if(!o)throw await e.context.password.hash(e.body.password),e.context.logger.error("User not found",{username:Ct}),new Qe.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let r=await e.context.adapter.findOne({model:"account",where:[{field:e.context.tables.account.fields.userId.fieldName||"userId",value:o.id},{field:e.context.tables.account.fields.providerId.fieldName||"providerId",value:"credential"}]});if(!r)throw new Qe.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let t=r?.password;if(!t)throw e.context.logger.error("Password not found",{username:Ct}),new Qe.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(t,e.body.password))throw e.context.logger.error("Invalid password"),new Qe.APIError("UNAUTHORIZED",{message:"Invalid username or password"});let i=await e.context.internalAdapter.createSession(o.id,e.request,e.body.rememberMe===!1);return i?(await e.setSignedCookie(e.context.authCookies.sessionToken.name,i.id,e.context.secret,e.body.rememberMe===!1?{...e.context.authCookies.sessionToken.options,maxAge:void 0}:e.context.authCookies.sessionToken.options),e.json({user:o,session:i})):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 io=require("better-call"),Pn=()=>({id:"bearer",hooks:{before:[{matcher(e){return!!(e.request?.headers.get("authorization")||e.headers?.get("authorization"))},handler:async e=>{let o=e.request?.headers.get("authorization")?.replace("Bearer ","")||e.headers?.get("authorization")?.replace("Bearer ","");if(!o)return;let r="";return o.includes(".")?r=o:r=await(0,io.serializeSigned)("",o,e.context.secret),e.request&&e.request.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${r.replace("=","")}`),e.headers&&e.headers.set("cookie",`${e.context.authCookies.sessionToken.name}=${r.replace("=","")}`),{context:e}}}]}});var Ae=require("zod");var zt=require("better-call");var _n=e=>({id:"magic-link",endpoints:{signInMagicLink:u("/sign-in/magic-link",{method:"POST",requireHeaders:!0,body:Ae.z.object({email:Ae.z.string().email(),callbackURL:Ae.z.string().optional()})},async o=>{let{email:r}=o.body;if(e.disableSignUp&&!await o.context.internalAdapter.findUserByEmail(r))throw new zt.APIError("BAD_REQUEST",{message:"User not found"});let t=M(32,$("a-z","A-Z"));await o.context.internalAdapter.createVerificationValue({identifier:t,value:r,expiresAt:new Date(Date.now()+(e.expiresIn||60*5)*1e3)});let n=`${o.context.baseURL}/magic-link/verify?token=${t}&callbackURL=${o.body.callbackURL||"/"}`;try{await e.sendMagicLink({email:r,url:n,token:t},o.request)}catch(i){throw o.context.logger.error("Failed to send magic link",i),new zt.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to send magic link"})}return o.json({status:!0})}),magicLinkVerify:u("/magic-link/verify",{method:"GET",query:Ae.z.object({token:Ae.z.string(),callbackURL:Ae.z.string().optional()}),requireHeaders:!0},async o=>{let{token:r,callbackURL:t}=o.query,n=t?.startsWith("http")?t:t?`${o.context.options.baseURL}${t}`:o.context.options.baseURL,i=await o.context.internalAdapter.findVerificationValue(r);if(!i)throw o.redirect(`${n}?error=INVALID_TOKEN`);if(i.expiresAt<new Date)throw await o.context.internalAdapter.deleteVerificationValue(i.id),o.redirect(`${n}?error=EXPIRED_TOKEN`);await o.context.internalAdapter.deleteVerificationValue(i.id);let s=i.value,a=await o.context.internalAdapter.findUserByEmail(s),d=a?.user.id||"";if(!a){if(e.disableSignUp)throw o.redirect(`${n}?error=USER_NOT_FOUND`);if(d=(await o.context.internalAdapter.createUser({email:s,emailVerified:!0,name:s})).id,!d)throw o.redirect(`${n}?error=USER_NOT_CREATED`)}let c=await o.context.internalAdapter.createSession(d,o.headers);if(!c)throw o.redirect(`${n}?error=SESSION_NOT_CREATED`);if(await w(o,{session:c,user:a?.user}),!t)return o.json({session:c,user:a?.user});throw o.redirect(t)})},rateLimit:[{pathMatcher(o){return o.startsWith("/sign-in/magic-link")||o.startsWith("/magic-link/verify")},window:e.rateLimit?.window||60,max:e.rateLimit?.max||5}]});var Z=require("zod");var N=require("better-call");function Cn(e){return M(e,$("0-9"))}var zn=e=>{let o={expiresIn:e?.expiresIn||300,otpLength:e?.otpLength||6,...e,phoneNumber:"phoneNumber",phoneNumberVerified:"phoneNumberVerified",code:"code",createdAt:"createdAt"};return{id:"phone-number",endpoints:{signInPhoneNumber:u("/sign-in/phone-number",{method:"POST",body:Z.z.object({phoneNumber:Z.z.string(),password:Z.z.string(),rememberMe:Z.z.boolean().optional()})},async r=>{let{password:t,phoneNumber:n}=r.body;if(o.phoneNumberValidator&&!await o.phoneNumberValidator(r.body.phoneNumber))throw new N.APIError("BAD_REQUEST",{message:"Invalid phone number!"});let i=await r.context.adapter.findOne({model:"user",where:[{field:"phoneNumber",value:n}]});if(!i)throw new N.APIError("UNAUTHORIZED",{message:"Invalid phone number or password"});let a=(await r.context.internalAdapter.findAccountByUserId(i.id)).find(p=>p.providerId==="credential");if(!a)throw r.context.logger.error("Credential account not found",{phoneNumber:n}),new N.APIError("UNAUTHORIZED",{message:"Invalid password or password"});let d=a?.password;if(!d)throw r.context.logger.error("Password not found",{phoneNumber:n}),new N.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await r.context.password.verify(d,t))throw r.context.logger.error("Invalid password"),new N.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let l=await r.context.internalAdapter.createSession(i.id,r.headers,r.body.rememberMe===!1);if(!l)throw r.context.logger.error("Failed to create session"),new N.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await w(r,{session:l,user:i},r.body.rememberMe===!1),r.json({user:i,session:l})}),sendPhoneNumberOTP:u("/phone-number/send-otp",{method:"POST",body:Z.z.object({phoneNumber:Z.z.string()})},async r=>{if(!e?.sendOTP)throw r.context.logger.warn("sendOTP not implemented"),new N.APIError("NOT_IMPLEMENTED",{message:"sendOTP not implemented"});if(o.phoneNumberValidator&&!await o.phoneNumberValidator(r.body.phoneNumber))throw new N.APIError("BAD_REQUEST",{message:"Invalid phone number!"});let t=Cn(o.otpLength);return await r.context.internalAdapter.createVerificationValue({value:t,identifier:r.body.phoneNumber,expiresAt:R(o.expiresIn,"sec")}),await e.sendOTP({phoneNumber:r.body.phoneNumber,code:t},r.request),r.json({code:t},{body:{message:"Code sent"}})}),verifyPhoneNumber:u("/phone-number/verify",{method:"POST",body:Z.z.object({phoneNumber:Z.z.string(),code:Z.z.string(),disableSession:Z.z.boolean().optional(),updatePhoneNumber:Z.z.boolean().optional()})},async r=>{let t=await r.context.internalAdapter.findVerificationValue(r.body.phoneNumber);if(!t||t.expiresAt<new Date)throw t&&t.expiresAt<new Date?(await r.context.internalAdapter.deleteVerificationValue(t.id),new N.APIError("BAD_REQUEST",{message:"OTP expired"})):new N.APIError("BAD_REQUEST",{message:"OTP not found"});if(t.value!==r.body.code)throw new N.APIError("BAD_REQUEST",{message:"Invalid OTP"});if(await r.context.internalAdapter.deleteVerificationValue(t.id),r.body.updatePhoneNumber){let i=await z(r);if(!i)throw new N.APIError("UNAUTHORIZED",{message:"Session not found"});let s=await r.context.internalAdapter.updateUser(i.user.id,{[o.phoneNumber]:r.body.phoneNumber,[o.phoneNumberVerified]:!0});return r.json({user:s,session:i.session})}let n=await r.context.adapter.findOne({model:r.context.tables.user.modelName,where:[{value:r.body.phoneNumber,field:o.phoneNumber}]});if(await e?.callbackOnVerification?.({phoneNumber:r.body.phoneNumber,user:n},r.request),n)n=await r.context.internalAdapter.updateUser(n.id,{[o.phoneNumberVerified]:!0});else if(e?.signUpOnVerification){if(n=await r.context.internalAdapter.createUser({email:e.signUpOnVerification.getTempEmail(r.body.phoneNumber),name:e.signUpOnVerification.getTempName?e.signUpOnVerification.getTempName(r.body.phoneNumber):r.body.phoneNumber,[o.phoneNumber]:r.body.phoneNumber,[o.phoneNumberVerified]:!0}),!n)throw new N.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"})}else return r.json(null);if(!n)throw new N.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to update user"});if(!r.body.disableSession){let i=await r.context.internalAdapter.createSession(n.id,r.request);if(!i)throw new N.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await w(r,{session:i,user:n}),r.json({user:n,session:i})}return r.json({user:n,session:null})})},schema:K(xn,e?.schema)}},xn={user:{fields:{phoneNumber:{type:"string",required:!1,unique:!0,returned:!0},phoneNumberVerified:{type:"boolean",required:!1,returned:!0,input:!1}}}};var Sl=require("zod");var Ln={user:{fields:{isAnonymous:{type:"boolean",required:!1}}}},Bn=e=>({id:"anonymous",endpoints:{signInAnonymous:u("/sign-in/anonymous",{method:"POST"},async o=>{let{emailDomainName:r=ke(o.context.baseURL)}=e||{},t=x(),n=`temp-${t}@${r}`,i=await o.context.internalAdapter.createUser({id:t,email:n,emailVerified:!1,isAnonymous:!0,name:"Anonymous",createdAt:new Date,updatedAt:new Date});if(!i)return o.json(null,{status:500,body:{message:"Failed to create user",status:500}});let s=await o.context.internalAdapter.createSession(i.id,o.request);return s?(await w(o,{session:s,user:i}),o.json({user:i,session:s})):o.json(null,{status:400,body:{message:"Could not create session"}})})},hooks:{after:[{matcher(o){return o.path?.startsWith("/sign-in")||o.path?.startsWith("/sign-up")},async handler(o){let r=o.context.returned;if(!(r instanceof Response))return;let t=r.headers.get("set-cookie"),n=o.context.authCookies.sessionToken.name,i=Ye(t||"").get(n)?.value.split(".")[0];if(!i)return;let s=await z(o);if(!(!s||!s.user.isAnonymous)){if(o.path==="/sign-in/anonymous")throw new O.APIError("BAD_REQUEST",{message:"Anonymous users cannot sign in again anonymously"});if(e?.onLinkAccount){let a=await o.context.internalAdapter.findSession(i);if(!a)return;await e?.onLinkAccount?.({anonymousUser:s,newUser:a})}e?.disableDeleteAnonymousUser||await o.context.internalAdapter.deleteUser(s.user.id)}}}]},schema:K(Ln,e?.schema)});var h=require("zod");var Dn=e=>{let o={defaultRole:"user",adminRole:"admin",...e},r=P(async t=>{let n=await z(t);if(!n?.session)throw new O.APIError("UNAUTHORIZED");let i=n.user;if(!i.role||(Array.isArray(o.adminRole)?!o.adminRole.includes(i.role):i.role!==o.adminRole))throw new O.APIError("FORBIDDEN",{message:"Only admins can access this endpoint"});return{session:{user:i,session:n.session}}});return{id:"admin",init(t){return{options:{databaseHooks:{user:{create:{async before(n){if(e?.defaultRole!==!1)return{data:{role:e?.defaultRole??"user",...n}}}}},session:{create:{async before(n){let i=await t.internalAdapter.findUserById(n.userId);if(i.banned){if(i.banExpires&&i.banExpires<Date.now()){await t.internalAdapter.updateUser(n.userId,{banned:!1,banReason:null,banExpires:null});return}return!1}}}}}}}},hooks:{after:[{matcher(t){return t.path==="/list-sessions"},handler:P(async t=>{let n=await ze(t);return n?{response:n.filter(s=>!s.impersonatedBy)}:void 0})}]},endpoints:{setRole:u("/admin/set-role",{method:"POST",body:h.z.object({userId:h.z.string(),role:h.z.string()}),use:[r]},async t=>{let n=await t.context.internalAdapter.updateUser(t.body.userId,{role:t.body.role});return t.json({user:n})}),createUser:u("/admin/create-user",{method:"POST",body:h.z.object({email:h.z.string(),password:h.z.string(),name:h.z.string(),role:h.z.string(),data:h.z.optional(h.z.record(h.z.any()))}),use:[r]},async t=>{if(await t.context.internalAdapter.findUserByEmail(t.body.email))throw new O.APIError("BAD_REQUEST",{message:"User already exists"});let i=await t.context.internalAdapter.createUser({email:t.body.email,name:t.body.name,role:t.body.role,...t.body.data});if(!i)throw new O.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create user"});let s=await t.context.password.hash(t.body.password);return await t.context.internalAdapter.linkAccount({accountId:i.id,providerId:"credential",password:s,userId:i.id}),t.json({user:i})}),listUsers:u("/admin/list-users",{method:"GET",use:[r],query:h.z.object({searchValue:h.z.string().optional(),searchField:h.z.enum(["email","name"]).optional(),searchOperator:h.z.enum(["contains","starts_with","ends_with"]).optional(),limit:h.z.string().or(h.z.number()).optional(),offset:h.z.string().or(h.z.number()).optional(),sortBy:h.z.string().optional(),sortDirection:h.z.enum(["asc","desc"]).optional(),filterField:h.z.string().optional(),filterValue:h.z.string().or(h.z.number()).or(h.z.boolean()).optional(),filterOperator:h.z.enum(["eq","ne","lt","lte","gt","gte"]).optional()})},async t=>{let n=[];t.query?.searchValue&&n.push({field:t.query.searchField||"email",operator:t.query.searchOperator||"contains",value:t.query.searchValue}),t.query?.filterValue&&n.push({field:t.query.filterField||"email",operator:t.query.filterOperator||"eq",value:t.query.filterValue});try{let i=await t.context.internalAdapter.listUsers(Number(t.query?.limit)||void 0,Number(t.query?.offset)||void 0,t.query?.sortBy?{field:t.query.sortBy,direction:t.query.sortDirection||"asc"}:void 0,n.length?n:void 0);return t.json({users:i})}catch(i){return console.log(i),t.json({users:[]})}}),listUserSessions:u("/admin/list-user-sessions",{method:"POST",use:[r],body:h.z.object({userId:h.z.string()})},async t=>({sessions:await t.context.internalAdapter.listSessions(t.body.userId)})),unbanUser:u("/admin/unban-user",{method:"POST",body:h.z.object({userId:h.z.string()}),use:[r]},async t=>{let n=await t.context.internalAdapter.updateUser(t.body.userId,{banned:!1});return t.json({user:n})}),banUser:u("/admin/ban-user",{method:"POST",body:h.z.object({userId:h.z.string(),banReason:h.z.string().optional(),banExpiresIn:h.z.number().optional()}),use:[r]},async t=>{if(t.body.userId===t.context.session.user.id)throw new O.APIError("BAD_REQUEST",{message:"You cannot ban yourself"});let n=await t.context.internalAdapter.updateUser(t.body.userId,{banned:!0,banReason:t.body.banReason||e?.defaultBanReason||"No reason",banExpires:t.body.banExpiresIn?R(t.body.banExpiresIn,"sec"):e?.defaultBanExpiresIn?R(e.defaultBanExpiresIn,"sec"):void 0});return await t.context.internalAdapter.deleteSessions(t.body.userId),t.json({user:n})}),impersonateUser:u("/admin/impersonate-user",{method:"POST",body:h.z.object({userId:h.z.string()}),use:[r]},async t=>{let n=await t.context.internalAdapter.findUserById(t.body.userId);if(!n)throw new O.APIError("NOT_FOUND",{message:"User not found"});let i=await t.context.internalAdapter.createSession(n.id,void 0,!0,{impersonatedBy:t.context.session.user.id,expiresAt:e?.impersonationSessionDuration?R(e.impersonationSessionDuration,"sec"):R(60*60,"sec")});if(!i)throw new O.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});return await w(t,{session:i,user:n},!0),t.json({session:i,user:n})}),revokeUserSession:u("/admin/revoke-user-session",{method:"POST",body:h.z.object({sessionId:h.z.string()}),use:[r]},async t=>(await t.context.internalAdapter.deleteSession(t.body.sessionId),t.json({success:!0}))),revokeUserSessions:u("/admin/revoke-user-sessions",{method:"POST",body:h.z.object({userId:h.z.string()}),use:[r]},async t=>(await t.context.internalAdapter.deleteSessions(t.body.userId),t.json({success:!0}))),removeUser:u("/admin/remove-user",{method:"POST",body:h.z.object({userId:h.z.string()}),use:[r]},async t=>(await t.context.internalAdapter.deleteUser(t.body.userId),t.json({success:!0})))},schema:K(Nn,o.schema)}},Nn={user:{fields:{role:{type:"string",required:!1,input:!1},banned:{type:"boolean",defaultValue:!1,required:!1,input:!1},banReason:{type:"string",required:!1,input:!1},banExpires:{type:"date",required:!1,input:!1}}},session:{fields:{impersonatedBy:{type:"string",required:!1}}}};var re=require("zod"),Le=require("better-call");var ct=require("@better-fetch/fetch");var so=require("oslo/jwt");async function jn(e,o,r){if(o==="oidc"&&e.idToken){let n=(0,so.parseJWT)(e.idToken);if(n?.payload)return n.payload}return r?(await(0,ct.betterFetch)(r,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}})).data:null}var Vn=e=>({id:"generic-oauth",endpoints:{signInWithOAuth2:u("/sign-in/oauth2",{method:"POST",query:re.z.object({currentURL:re.z.string().optional()}).optional(),body:re.z.object({providerId:re.z.string(),callbackURL:re.z.string().optional(),errorCallbackURL:re.z.string().optional()})},async o=>{let{providerId:r}=o.body,t=e.config.find(C=>C.providerId===r);if(!t)throw new Le.APIError("BAD_REQUEST",{message:`No config found for provider ${r}`});let{discoveryUrl:n,authorizationUrl:i,tokenUrl:s,clientId:a,clientSecret:d,scopes:c,redirectURI:l,responseType:p,pkce:f,prompt:m,accessType:g}=t,v=i,H=s;if(n){let C=await(0,ct.betterFetch)(n,{onError(De){o.context.logger.error(De.error.message,De.error,{discoveryUrl:n})}});C.data&&(v=C.data.authorization_endpoint,H=C.data.token_endpoint)}if(!v||!H)throw new Le.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let{state:oe,codeVerifier:Y}=await Oe(o),y=await I({id:r,options:{clientId:a,clientSecret:d,redirectURI:l},authorizationEndpoint:v,state:oe,codeVerifier:f?Y:void 0,scopes:c||[],redirectURI:`${o.context.baseURL}/oauth2/callback/${r}`});return p&&p!=="code"&&y.searchParams.set("response_type",p),m&&y.searchParams.set("prompt",m),g&&y.searchParams.set("access_type",g),o.json({url:y.toString(),redirect:!0})}),oAuth2Callback:u("/oauth2/callback/:providerId",{method:"GET",query:re.z.object({code:re.z.string().optional(),error:re.z.string().optional(),state:re.z.string()})},async o=>{if(o.query.error||!o.query.code)throw o.redirect(`${o.context.baseURL}?error=${o.query.error||"oAuth_code_missing"}`);let r=e.config.find(y=>y.providerId===o.params.providerId);if(!r)throw new Le.APIError("BAD_REQUEST",{message:`No config found for provider ${o.params.providerId}`});let t,n=await et(o),{callbackURL:i,codeVerifier:s,errorURL:a}=n,d=o.query.code,c=r.tokenUrl,l=r.userInfoUrl;if(r.discoveryUrl){let y=await(0,ct.betterFetch)(r.discoveryUrl,{method:"GET"});y.data&&(c=y.data.token_endpoint,l=y.data.userinfo_endpoint)}try{if(!c)throw new Le.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});t=await k({code:d,codeVerifier:s,redirectURI:`${o.context.baseURL}/oauth2/callback/${r.providerId}`,options:{clientId:r.clientId,clientSecret:r.clientSecret},tokenEndpoint:c})}catch(y){throw o.context.logger.error(y&&typeof y=="object"&&"name"in y?y.name:"",y),o.redirect(`${a}?error=oauth_code_verification_failed`)}if(!t)throw new Le.APIError("BAD_REQUEST",{message:"Invalid OAuth configuration."});let p=r.getUserInfo?await r.getUserInfo(t):await jn(t,r.type||"oauth2",l),f=x(),m=Rr.safeParse({...p,id:f});if(!p||m.success===!1)throw o.context.logger.error("Unable to get user info",m.error),o.redirect(`${o.context.baseURL}/error?error=please_restart_the_process`);let g=await Ee(o,{userInfo:m.data,account:{providerId:r.providerId,accountId:p.id,accessToken:t.accessToken}});function v(y){throw o.redirect(`${a||i||`${o.context.baseURL}/error`}?error=${y}`)}if(g.error)return v(g.error.split(" ").join("_"));let{session:H,user:oe}=g.data;await w(o,{session:H,user:oe});let Y;try{Y=new URL(i).toString()}catch{Y=i}throw o.redirect(Y)})}});var Be=require("zod"),ao={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0}}}},Zl=Be.z.object({id:Be.z.string(),publicKey:Be.z.string(),privateKey:Be.z.string(),createdAt:Be.z.date()});var xt=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 o=>await e.create({model:"jwks",data:{...o,createdAt:new Date}})});var de=require("jose");var Fn=e=>({id:"jwt",endpoints:{getJwks:u("/jwks",{method:"GET"},async o=>{let t=await xt(o.context.adapter).getAllKeys();return o.json({keys:t.map(n=>({...JSON.parse(n.publicKey),kid:n.id}))})}),getToken:u("/token",{method:"GET",requireHeaders:!0,use:[b]},async o=>{let r=xt(o.context.adapter),t=await r.getLatestKey(),n=!e?.jwks?.disablePrivateKeyEncryption;if(t===void 0){let{publicKey:c,privateKey:l}=await(0,de.generateKeyPair)(e?.jwks?.keyPairConfig?.alg??"EdDSA",e?.jwks?.keyPairConfig??{crv:"Ed25519"}),p=await(0,de.exportJWK)(c),f=await(0,de.exportJWK)(l),m=JSON.stringify(f),g={id:crypto.randomUUID(),publicKey:JSON.stringify(p),privateKey:n?JSON.stringify(await ae({key:o.context.options.secret,data:m})):m,createdAt:new Date};t=await r.createJwk(g)}let i=n?await fe({key:o.context.options.secret,data:JSON.parse(t.privateKey)}):t.privateKey,s=await(0,de.importJWK)(JSON.parse(i)),a=e?.jwt?.definePayload?await e?.jwt.definePayload(o.context.session.user):o.context.session.user,d=await new de.SignJWT({...a,...o.context.session.session.impersonatedBy?{impersonatedBy:o.context.session.session.impersonatedBy}:{}}).setProtectedHeader({alg:e?.jwks?.keyPairConfig?.alg??"EdDSA",kid:t.id}).setIssuedAt().setIssuer(e?.jwt?.issuer??o.context.options.baseURL).setAudience(e?.jwt?.audience??o.context.options.baseURL).setExpirationTime(e?.jwt?.expirationTime??"15m").setSubject(o.context.session.user.id).sign(s);return o.json({token:d})})},schema:K(ao,e?.schema)});var We=require("zod");var qn=e=>{let o={maximumSessions:5,...e},r=t=>t.includes("_multi-");return{id:"multi-session",endpoints:{listDeviceSessions:u("/multi-session/list-device-sessions",{method:"GET",requireHeaders:!0},async t=>{let n=t.headers?.get("cookie");if(!n)return t.json([]);let i=Object.fromEntries(je(n)),s=(await Promise.all(Object.entries(i).filter(([c])=>r(c)).map(async([c])=>await t.getSignedCookie(c,t.context.secret)))).filter(c=>c!==void 0);if(!s.length)return t.json([]);let d=(await t.context.internalAdapter.findSessions(s)).filter(c=>c&&c.session.expiresAt>new Date);return t.json(d)}),setActiveSession:u("/multi-session/set-active",{method:"POST",body:We.z.object({sessionId:We.z.string()}),requireHeaders:!0,use:[b]},async t=>{let n=t.body.sessionId,i=`${t.context.authCookies.sessionToken.name}_multi-${n}`;if(!await t.getSignedCookie(i,t.context.secret))throw new O.APIError("UNAUTHORIZED",{message:"Invalid session id"});let a=await t.context.internalAdapter.findSession(n);if(!a||a.session.expiresAt<new Date)throw t.setCookie(i,"",{...t.context.authCookies.sessionToken.options,maxAge:0}),new O.APIError("UNAUTHORIZED",{message:"Invalid session id"});return await t.setSignedCookie(t.context.authCookies.sessionToken.name,n,t.context.secret,t.context.authCookies.sessionToken.options),t.json(a)}),revokeDeviceSession:u("/multi-session/revoke",{method:"POST",body:We.z.object({sessionId:We.z.string()}),requireHeaders:!0,use:[b]},async t=>{let n=t.body.sessionId,i=`${t.context.authCookies.sessionToken.name}_multi-${n}`;if(!await t.getSignedCookie(i,t.context.secret))throw new O.APIError("UNAUTHORIZED",{message:"Invalid session id"});if(await t.context.internalAdapter.deleteSession(n),t.setCookie(i,"",{...t.context.authCookies.sessionToken.options,maxAge:0}),!(t.context.session?.session.id===n))return t.json({success:!0});let d=t.headers?.get("cookie"),c=t.context.authCookies;if(d){let l=Object.fromEntries(je(d)),p=(await Promise.all(Object.entries(l).filter(([m])=>r(m)).map(async([m])=>await t.getSignedCookie(m,t.context.secret)))).filter(m=>m!==void 0),f=t.context.internalAdapter;if(p.length>0){let g=(await f.findSessions(p)).filter(v=>v&&v.session.expiresAt>new Date);if(g.length>0){let v=g[0];await w(t,v)}else t.setCookie(c.sessionToken.name,"",{...c.sessionToken.options,maxAge:0})}else t.setCookie(c.sessionToken.name,"",{...c.sessionToken.options,maxAge:0})}else t.setCookie(c.sessionToken.name,"",{...c.sessionToken.options,maxAge:0});return t.json({success:!0})})},hooks:{after:[{matcher:()=>!0,handler:P(async t=>{if(!t.context.returned||!(t.context.returned instanceof Response))return;let n=t.context.returned.headers.get("set-cookie");if(!n)return;let i=Ye(n),s=t.context.authCookies.sessionToken,a=i.get(s.name)?.value;if(!a)return;let d=je(t.headers?.get("cookie")||""),c=a.split(".")[0],l=`${s.name}_multi-${c}`;if(i.get(l)||d.get(l)||Object.keys(Object.fromEntries(d)).filter(r).length+(n.includes("session_token")?1:0)>o.maximumSessions)return;await t.setSignedCookie(l,c,t.context.secret,s.options);let f=t.context.returned;return f.headers.append("Set-Cookie",t.responseHeader.get("set-cookie")),{response:f}})},{matcher:t=>t.path==="/sign-out",handler:P(async t=>{let n=t.headers?.get("cookie");if(!n)return;let i=Object.fromEntries(je(n));return await Promise.all(Object.entries(i).map(async([s,a])=>{if(r(s)){t.setCookie(s,"",{maxAge:0});let d=s.split("_multi-")[1];await t.context.internalAdapter.deleteSession(d)}})),{responseHeader:t.responseHeader}})}]}}};var j=require("zod");var Mn=e=>{let o={expireIn:300,otpLength:6,...e};return{id:"email-otp",endpoints:{sendVerificationOTP:u("/email-otp/send-verification-otp",{method:"POST",body:j.z.object({email:j.z.string(),type:j.z.enum(["email-verification","sign-in"])})},async r=>{if(!e?.sendVerificationOTP)throw r.context.logger.error("send email verification is not implemented"),new O.APIError("BAD_REQUEST",{message:"send email verification is not implemented"});let t=r.body.email,n=M(o.otpLength,$("0-9"));return await r.context.internalAdapter.createVerificationValue({value:n,identifier:`${r.body.type}-otp-${t}`,expiresAt:R(o.expireIn,"sec")}).catch(async i=>{await r.context.internalAdapter.deleteVerificationByIdentifier(`${r.body.type}-otp-${t}`),await r.context.internalAdapter.createVerificationValue({value:n,identifier:`${r.body.type}-otp-${t}`,expiresAt:R(o.expireIn,"sec")})}),await e.sendVerificationOTP({email:t,otp:n,type:r.body.type},r.request),r.json({success:!0})}),createVerificationOTP:u("/email-otp/create-verification-otp",{method:"POST",body:j.z.object({email:j.z.string(),type:j.z.enum(["email-verification","sign-in"])}),metadata:{SERVER_ONLY:!0}},async r=>{let t=r.body.email,n=M(o.otpLength,$("0-9"));return await r.context.internalAdapter.createVerificationValue({value:n,identifier:`${r.body.type}-otp-${t}`,expiresAt:R(o.expireIn,"sec")}),n}),getVerificationOTP:u("/email-otp/get-verification-otp",{method:"GET",query:j.z.object({email:j.z.string(),type:j.z.enum(["email-verification","sign-in"])}),metadata:{SERVER_ONLY:!0}},async r=>{let t=r.query.email,n=await r.context.internalAdapter.findVerificationValue(`${r.query.type}-otp-${t}`);return!n||n.expiresAt<new Date?r.json({otp:null}):r.json({otp:n.value})}),verifyEmailOTP:u("/email-otp/verify-email",{method:"POST",body:j.z.object({email:j.z.string(),otp:j.z.string()})},async r=>{let t=r.body.email,n=await r.context.internalAdapter.findVerificationValue(`email-verification-otp-${t}`);if(!n||n.expiresAt<new Date)throw n&&await r.context.internalAdapter.deleteVerificationValue(n.id),new O.APIError("BAD_REQUEST",{message:"Invalid OTP"});let i=r.body.otp;if(n.value!==i)throw new O.APIError("BAD_REQUEST",{message:"Invalid OTP"});await r.context.internalAdapter.deleteVerificationValue(n.id);let s=await r.context.internalAdapter.findUserByEmail(t);if(!s)throw new O.APIError("BAD_REQUEST",{message:"User not found"});let a=await r.context.internalAdapter.updateUser(s.user.id,{email:t,emailVerified:!0});return r.json({user:a})}),signInEmailOTP:u("/sign-in/email-otp",{method:"POST",body:j.z.object({email:j.z.string(),otp:j.z.string()})},async r=>{let t=r.body.email,n=await r.context.internalAdapter.findVerificationValue(`sign-in-otp-${t}`);if(!n||n.expiresAt<new Date)throw n&&await r.context.internalAdapter.deleteVerificationValue(n.id),new O.APIError("BAD_REQUEST",{message:"Invalid OTP"});let i=r.body.otp;if(n.value!==i)throw new O.APIError("BAD_REQUEST",{message:"Invalid OTP"});await r.context.internalAdapter.deleteVerificationValue(n.id);let s=await r.context.internalAdapter.findUserByEmail(t);if(!s){if(o.disableSignUp)throw new O.APIError("BAD_REQUEST",{message:"User not found"});let d=await r.context.internalAdapter.createUser({email:t,emailVerified:!0,name:t}),c=await r.context.internalAdapter.createSession(d.id,r.request);return await w(r,{session:c,user:d}),r.json({user:d,session:c})}let a=await r.context.internalAdapter.createSession(s.user.id,r.request);return await w(r,{session:a,user:s.user}),r.json({session:a,user:s})})},hooks:{after:[{matcher(r){return!!(r.path?.startsWith("/sign-up")&&o.sendVerificationOnSignUp)},async handler(r){let t=await ze(r);if(t&&t.user.email&&t.user.emailVerified===!1){let n=M(o.otpLength,$("0-9"));await r.context.internalAdapter.createVerificationValue({value:n,identifier:`email-verification-otp-${t.user.email}`,expiresAt:R(o.expireIn,"sec")}),await e.sendVerificationOTP({email:t.user.email,otp:n,type:"email-verification"},r.request)}}}]}}};var Lt=require("zod");var uo=require("@better-fetch/fetch");function co(e){return e==="true"||e===!0}var $n=e=>({id:"one-tap",endpoints:{oneTapCallback:u("/one-tap/callback",{method:"POST",body:Lt.z.object({idToken:Lt.z.string()})},async o=>{let{idToken:r}=o.body,{data:t,error:n}=await(0,uo.betterFetch)("https://oauth2.googleapis.com/tokeninfo?id_token="+r);if(n)return o.json({error:"Invalid token"});let i=await o.context.internalAdapter.findUserByEmail(t.email);if(!i){if(e?.disableSignup)throw new O.APIError("BAD_GATEWAY",{message:"User not found"});let a=await o.context.internalAdapter.createOAuthUser({email:t.email,emailVerified:co(t.email_verified),name:t.name,image:t.picture},{providerId:"google",accountId:t.sub});if(!a)throw new O.APIError("INTERNAL_SERVER_ERROR",{message:"Could not create user"});let d=await o.context.internalAdapter.createSession(a?.user.id,o.request);return await w(o,{user:a.user,session:d}),o.json({session:d,user:a})}let s=await o.context.internalAdapter.createSession(i.user.id,o.request);return await w(o,{user:i.user,session:s}),o.json({session:s,user:i})})}});var ut=require("zod");function Hn(){let e=ee.VERCEL_URL,o=ee.NETLIFY_URL,r=ee.RENDER_URL,t=ee.AWS_LAMBDA_FUNCTION_NAME,n=ee.GOOGLE_CLOUD_FUNCTION_NAME,i=ee.AZURE_FUNCTION_NAME;return e||o||r||t||n||i}var Qn=e=>({id:"oauth-proxy",endpoints:{oAuthProxy:u("/oauth-proxy-callback",{method:"GET",query:ut.z.object({callbackURL:ut.z.string(),cookies:ut.z.string()})},async o=>{let r=o.query.cookies,t=await fe({key:o.context.secret,data:r});throw o.setHeader("set-cookie",t),o.redirect(o.query.callbackURL)})},hooks:{after:[{matcher(o){return o.path?.startsWith("/callback")},handler:P(async o=>{let r=o.context.returned;if(!r||!(r instanceof Response))return;let t=r.headers.get("location");if(t?.includes("/oauth-proxy-callback?callbackURL")){if(!t.startsWith("http"))return;let n=new URL(t);if(n.origin===ke(o.context.baseURL)){let c=n.searchParams.get("callbackURL");return c?(r.headers.set("location",c),{response:r}):void 0}let s=r.headers.get("set-cookie");if(!s)return;let a=await ae({key:o.context.secret,data:s}),d=`${t}&cookies=${encodeURIComponent(a)}`;return r.headers.set("location",d),{response:r}}})}],before:[{matcher(o){return o.path?.startsWith("/sign-in/social")},async handler(o){let r=new URL(e?.currentURL||o.request?.url||Hn()||o.context.baseURL);return o.body.callbackURL=`${r.origin}${o.context.options.basePath||"/api/auth"}/oauth-proxy-callback?callbackURL=${encodeURIComponent(o.body.callbackURL||o.context.baseURL)}`,{context:o}}}]}});0&&(module.exports={HIDE_METADATA,admin,anonymous,bearer,createAuthEndpoint,createAuthMiddleware,emailOTP,genericOAuth,getPasskeyActions,jwt,magicLink,multiSession,oAuthProxy,oneTap,optionsMiddleware,organization,passkey,passkeyClient,phoneNumber,twoFactor,twoFactorClient,username});