better-auth 1.0.21 → 1.0.22-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/prisma.d.cts +1 -1
- package/dist/adapters/prisma.d.ts +1 -1
- package/dist/api.cjs +1 -1
- package/dist/api.js +1 -1
- package/dist/client/plugins.d.cts +1 -1
- package/dist/client/plugins.d.ts +1 -1
- package/dist/{index-Dt4lZbQi.d.ts → index-Dd3_WG87.d.ts} +105 -103
- package/dist/{index-CgaJXZ9u.d.cts → index-Dp04oxSM.d.cts} +105 -103
- package/dist/index.cjs +2 -2
- package/dist/index.js +2 -2
- package/dist/plugin/custom-session.cjs +4 -4
- package/dist/plugin/custom-session.js +2 -2
- package/dist/plugins/admin.cjs +1 -1
- package/dist/plugins/admin.js +1 -1
- package/dist/plugins/anonymous.cjs +1 -1
- package/dist/plugins/anonymous.js +1 -1
- package/dist/plugins/bearer.cjs +1 -1
- package/dist/plugins/bearer.js +1 -1
- package/dist/plugins/email-otp.cjs +1 -1
- package/dist/plugins/email-otp.js +1 -1
- package/dist/plugins/generic-oauth.cjs +1 -1
- package/dist/plugins/generic-oauth.js +1 -1
- package/dist/plugins/jwt.cjs +2 -2
- package/dist/plugins/jwt.js +2 -2
- package/dist/plugins/multi-session.cjs +1 -1
- package/dist/plugins/multi-session.js +1 -1
- package/dist/plugins/one-tap.cjs +1 -1
- package/dist/plugins/one-tap.js +1 -1
- package/dist/plugins/open-api.cjs +1 -1
- package/dist/plugins/open-api.js +1 -1
- package/dist/plugins/organization.cjs +4 -4
- package/dist/plugins/organization.d.cts +1 -1
- package/dist/plugins/organization.d.ts +1 -1
- package/dist/plugins/organization.js +2 -2
- package/dist/plugins/passkey.cjs +1 -1
- package/dist/plugins/passkey.js +1 -1
- package/dist/plugins/phone-number.cjs +1 -1
- package/dist/plugins/phone-number.js +1 -1
- package/dist/plugins/two-factor.cjs +1 -1
- package/dist/plugins/two-factor.js +1 -1
- package/dist/plugins/username.cjs +1 -1
- package/dist/plugins/username.js +1 -1
- package/dist/plugins.cjs +3 -3
- package/dist/plugins.d.cts +1 -1
- package/dist/plugins.d.ts +1 -1
- package/dist/plugins.js +4 -4
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{APIError as Et}from"better-call";import{z as ie}from"zod";import{createEndpointCreator as Rt,createMiddleware as Ee,createMiddlewareCreator as Tt}from"better-call";var Re=Ee(async()=>({})),Y=Tt({use:[Re,Ee(async()=>({}))]}),u=Rt({use:[Re]});import{APIError as k}from"better-call";import{z as _}from"zod";import{TimeSpan as Ao}from"oslo";import{base64url as Nt}from"oslo/encoding";import{HMAC as Te,sha256 as po}from"oslo/crypto";async function St({value:e,secret:r}){return new Te("SHA-256").sign(new TextEncoder().encode(r),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function vt({value:e,signature:r,secret:t}){return new Te("SHA-256").verify(new TextEncoder().encode(t),Buffer.from(r,"base64"),new TextEncoder().encode(e))}var se={sign:St,verify:vt};var F=class extends Error{constructor(r,t){super(r),this.name="BetterAuthError",this.message=r,this.cause=t,this.stack=""}};var q=(e,r="ms")=>new Date(Date.now()+(r==="sec"?e*1e3:e));var ae=Object.create(null),ee=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?ae:globalThis),Ue=new Proxy(ae,{get(e,r){return ee()[r]??ae[r]},has(e,r){let t=ee();return r in t||r in ae},set(e,r,t){let o=ee(!0);return o[r]=t,!0},deleteProperty(e,r){if(!r)return!1;let t=ee(!0);return delete t[r],!0},ownKeys(){let e=ee(!0);return Object.keys(e)}});function kt(e){return e?e!=="false":!1}var he=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var ye=he==="dev"||he==="development",zt=he==="test"||kt(Ue.TEST);async function S(e,r,t,o){let n=e.context.authCookies.sessionToken.options,i=t?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,r.session.token,e.context.secret,{...n,maxAge:i,...o}),t&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled){let a=Nt.encode(new TextEncoder().encode(JSON.stringify({session:r,expiresAt:q(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await se.sign({value:JSON.stringify(r),secret:e.context.secret})})),{includePadding:!1});if(a.length>4093)throw new F("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");e.setCookie(e.context.authCookies.sessionData.name,a,e.context.authCookies.sessionData.options)}e.context.setNewSession(r),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(r.session.token,JSON.stringify({user:r.user,session:r.session}),Math.floor((new Date(r.session.expiresAt).getTime()-Date.now())/1e3))}function $(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}import{betterFetch as jt}from"@better-fetch/fetch";import{APIError as Bt}from"better-call";import{decodeProtectedHeader as Mt,importJWK as Vt,jwtVerify as Ft}from"jose";import{parseJWT as qt}from"oslo/jwt";import{sha256 as Lt}from"oslo/crypto";import{base64url as Pt}from"oslo/encoding";async function Se(e){let r=await Lt(new TextEncoder().encode(e));return Pt.encode(new Uint8Array(r),{includePadding:!1})}function de(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?q(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function O({id:e,options:r,authorizationEndpoint:t,state:o,codeVerifier:n,scopes:i,claims:s,redirectURI:a,duration:d}){let c=new URL(t);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",r.clientId),c.searchParams.set("state",o),c.searchParams.set("scope",i.join(" ")),c.searchParams.set("redirect_uri",r.redirectURI||a),n){let l=await Se(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((m,h)=>(m[h]=null,m),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return d&&c.searchParams.set("duration",d),c}import{betterFetch as Dt}from"@better-fetch/fetch";async function b({code:e,codeVerifier:r,redirectURI:t,options:o,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),r&&s.set("code_verifier",r),s.set("redirect_uri",t),i==="basic"){let m=btoa(`${o.clientId}:${o.clientSecret}`);a.authorization=`Basic ${m}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:d,error:c}=await Dt(n,{method:"POST",body:s,headers:a});if(c)throw c;return de(d)}import{generateCodeVerifier as xt,generateState as Ct}from"oslo/oauth2";import{z as G}from"zod";import{APIError as ze}from"better-call";function ve(e){try{return new URL(e).origin}catch{return null}}function ke(e){return e.includes("://")?new URL(e).host:e}async function ce(e,r){let t=e.body?.callbackURL||(e.query?.currentURL?ve(e.query?.currentURL):"")||e.context.options.baseURL;if(!t)throw new ze("BAD_REQUEST",{message:"callbackURL is required"});let o=xt(),n=Ct(),i=JSON.stringify({callbackURL:t,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,newUserURL:e.body?.newUserCallbackURL,link:r,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 ze("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function Ne(e){let r=e.query.state||e.body.state,t=await e.context.internalAdapter.findVerificationValue(r);if(!t)throw e.context.logger.error("State Mismatch. Verification not found",{state:r}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=G.object({callbackURL:G.string(),codeVerifier:G.string(),errorURL:G.string().optional(),newUserURL:G.string().optional(),expiresAt:G.number(),link:G.object({email:G.string(),userId:G.string()}).optional()}).parse(JSON.parse(t.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(t.id),e.context.logger.error("State expired.",{state:r}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(t.id),o}var Le=e=>{let r="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:t,scopes:o,redirectURI:n}){let i=o||["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=${t}&response_mode=form_post`)},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:n})=>b({code:t,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async verifyIdToken(t,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,o);let n=Mt(t),{kid:i,alg:s}=n;if(!i||!s)return!1;let a=await $t(i),{payload:d}=await Ft(t,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])}),o&&d.nonce!==o?!1:!!d},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let o=qt(t.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email,...i},data:o}}}},$t=async e=>{let r="https://appleid.apple.com",t="/auth/keys",{data:o}=await jt(`${r}${t}`);if(!o?.keys)throw new Bt("BAD_REQUEST",{message:"Keys not found"});let n=o.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await Vt(n,n.alg)};import{betterFetch as Ht}from"@better-fetch/fetch";var Pe=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["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||o)}&state=${r}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:r,redirectURI:t})=>b({code:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await Ht("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${r.accessToken}`}});if(o)return null;if(t.avatar===null){let i=t.discriminator==="0"?Number(BigInt(t.id)>>BigInt(22))%6:parseInt(t.discriminator)%5;t.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=t.avatar.startsWith("a_")?"gif":"png";t.image_url=`https://cdn.discordapp.com/avatars/${t.id}/${t.avatar}.${i}`}let n=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.display_name||t.username||"",email:t.email,emailVerified:t.verified,image:t.image_url,...n},data:t}}});import{betterFetch as Gt}from"@better-fetch/fetch";var De=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["email","public_profile"];return e.scope&&n.push(...e.scope),await O({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:r,redirectURI:o})},validateAuthorizationCode:async({code:r,redirectURI:t})=>b({code:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await Gt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:r.accessToken}});if(o)return null;let n=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.name,email:t.email,image:t.picture.data.url,emailVerified:t.email_verified,...n},data:t}}});import{betterFetch as xe}from"@better-fetch/fetch";var Ce=e=>{let r="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:t,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),O({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:t,redirectURI:i})},validateAuthorizationCode:async({code:t,redirectURI:o})=>b({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:n}=await xe("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:a,error:d}=await xe("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});d||(o.email=(a.find(c=>c.primary)??a[0])?.email,i=a.find(c=>c.email===o.email)?.verified??!1)}let s=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i,...s},data:o}}}};import{parseJWT as Kt}from"oslo/jwt";import{createConsola as Zt}from"consola";var we=["info","success","warn","error","debug"];function Wt(e,r){return we.indexOf(r)<=we.indexOf(e)}var Qt=Zt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Yt=e=>{let r=e?.disabled!==!0,t=e?.level??"error",o=(n,i,s=[])=>{if(!(!r||!Wt(t,n))){if(!e||typeof e.log!="function"){Qt[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(we.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},j=Yt();import{betterFetch as Jt}from"@better-fetch/fetch";var je=e=>({id:"google",name:"Google",async createAuthorizationURL({state:r,scopes:t,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw j.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new F("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new F("codeVerifier is required for Google");let i=t||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await O({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:r,codeVerifier:o,redirectURI:n});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:o})=>b({code:r,codeVerifier:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(r,t){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,t);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${r}`,{data:n}=await Jt(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let t=Kt(r.idToken)?.payload,o=await e.mapProfileToUser?.(t);return{user:{id:t.sub,name:t.name,email:t.email,image:t.picture,emailVerified:t.email_verified,...o},data:t}}});import{betterFetch as Xt}from"@better-fetch/fetch";import{parseJWT as er}from"oslo/jwt";var Be=e=>{let r=e.tenantId||"common",t=`https://login.microsoftonline.com/${r}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${r}/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),O({id:"microsoft",options:e,authorizationEndpoint:t,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return b({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=er(n.idToken)?.payload,s=e.profilePhotoSize||48;await Xt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(d){if(!(e.disableProfilePhoto||!d.response.ok))try{let l=await d.response.clone().arrayBuffer(),m=Buffer.from(l).toString("base64");i.picture=`data:image/jpeg;base64, ${m}`}catch(c){j.error(c&&typeof c=="object"&&"name"in c?c.name:"",c)}}});let a=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0,...a},data:i}}}};import{betterFetch as tr}from"@better-fetch/fetch";var Me=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:r,scopes:t,codeVerifier:o,redirectURI:n}){let i=t||["user-read-email"];return e.scope&&i.push(...e.scope),O({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:r,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:o})=>b({code:r,codeVerifier:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await tr("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.display_name,email:t.email,image:t.images[0]?.url,emailVerified:!1,...n},data:t}}});var X={isAction:!1};import{nanoid as rr}from"nanoid";var H=e=>rr(e);import{parseJWT as or}from"oslo/jwt";var Ve=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["user:read:email","openid"];return e.scope&&n.push(...e.scope),O({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:r,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:r,redirectURI:t})=>b({code:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let t=r.idToken;if(!t)return j.error("No idToken found in token"),null;let o=or(t)?.payload,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...n},data:o}}});import{betterFetch as nr}from"@better-fetch/fetch";var Fe=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(r){let t=r.scopes||["users.read","tweet.read","offline.access"];return e.scope&&t.push(...e.scope),O({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:t,state:r.state,codeVerifier:r.codeVerifier,redirectURI:r.redirectURI})},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:o})=>b({code:r,codeVerifier:t,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await nr("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(t);return{user:{id:t.data.id,name:t.data.name,email:t.data.username||null,image:t.data.profile_image_url,emailVerified:t.data.verified||!1,...n},data:t}}});import{betterFetch as ir}from"@better-fetch/fetch";var qe=e=>{let r="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:t,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await O({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:t,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:n})=>await b({code:t,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:n}=await ir("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...i},data:o}}}};import{betterFetch as sr}from"@better-fetch/fetch";var $e=e=>{let r="https://www.linkedin.com/oauth/v2/authorization",t="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await O({id:"linkedin",options:e,authorizationEndpoint:r,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await b({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(o){let{data:n,error:i}=await sr("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(i)return null;let s=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture,...s},data:n}}}};import{betterFetch as ar}from"@better-fetch/fetch";var be=(e="")=>e.split("://").map(r=>r.replace(/\/{2,}/g,"/")).join("://"),dr=e=>{let r=e||"https://gitlab.com";return{authorizationEndpoint:be(`${r}/oauth/authorize`),tokenEndpoint:be(`${r}/oauth/token`),userinfoEndpoint:be(`${r}/api/v4/user`)}},He=e=>{let{authorizationEndpoint:r,tokenEndpoint:t,userinfoEndpoint:o}=dr(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 O({id:n,options:e,authorizationEndpoint:r,scopes:l,state:s,redirectURI:c,codeVerifier:d})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:d})=>b({code:s,redirectURI:e.redirectURI||a,options:e,codeVerifier:d,tokenEndpoint:t}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:a,error:d}=await ar(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(d||a.state!=="active"||a.locked)return null;let c=await e.mapProfileToUser?.(a);return{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0,...c},data:a}}}};import{betterFetch as Ge}from"@better-fetch/fetch";var Ze=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["identity"];return e.scope&&n.push(...e.scope),O({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:n,state:r,redirectURI:o,duration:e.duration})},validateAuthorizationCode:async({code:r,redirectURI:t})=>{let o=new URLSearchParams({grant_type:"authorization_code",code:r,redirect_uri:e.redirectURI||t}),n={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`},{data:i,error:s}=await Ge("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:n,body:o.toString()});if(s)throw s;return de(i)},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await Ge("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let n=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.name,email:t.oauth_client_id,emailVerified:t.has_verified_email,image:t.icon_img?.split("?")[0],...n},data:t}}});var cr={apple:Le,discord:Pe,facebook:De,github:Ce,microsoft:Be,google:je,spotify:Me,twitch:Ve,twitter:Fe,dropbox:qe,linkedin:$e,gitlab:He,reddit:Ze},le=Object.keys(cr);import{TimeSpan as mr}from"oslo";import{createJWT as fr,validateJWT as gr}from"oslo/jwt";import{z as B}from"zod";import{APIError as te}from"better-call";import{APIError as Z}from"better-call";import{z as K}from"zod";function We(e){try{return JSON.parse(e)}catch{return null}}var f={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found"};var Qe=()=>u("/get-session",{method:"GET",query:K.optional(K.object({disableCookieCache:K.boolean({description:"Disable cookie cache and fetch session from database"}).or(K.string().transform(e=>e==="true")).optional(),disableRefresh:K.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let r=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!r)return e.json(null);let t=e.getCookie(e.context.authCookies.sessionData.name),o=t?We(Buffer.from(t,"base64").toString()):null;if(o&&!await se.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return $(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let l=o.session;if(o.expiresAt<Date.now()||l.session.expiresAt<new Date){let h=e.context.authCookies.sessionData.name;e.setCookie(h,"",{maxAge:0})}else return e.json(l)}let i=await e.context.internalAdapter.findSession(r);if(e.context.session=i,!i||i.session.expiresAt<new Date)return $(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n||e.query?.disableRefresh)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.token,{expiresAt:q(e.context.sessionConfig.expiresIn,"sec")});if(!l)return $(e),e.json(null,{status:401});let m=(l.expiresAt.valueOf()-Date.now())/1e3;return await S(e,{session:l,user:i.user},!1,{maxAge:m}),e.json({session:l,user:i.user})}return e.json(i)}catch(r){throw e.context.logger.error("INTERNAL_SERVER_ERROR",r),new Z("INTERNAL_SERVER_ERROR",{message:f.FAILED_TO_GET_SESSION})}}),v=async(e,r)=>{if(e.context.session)return e.context.session;let t=await Qe()({...e,_flag:"json",headers:e.headers,query:r}).catch(o=>null);return e.context.session=t,t},x=Y(async e=>{let r=await v(e);if(!r?.session)throw new Z("UNAUTHORIZED");return{session:r}}),Ye=Y(async e=>{let r=await v(e);if(!r?.session)throw new Z("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:r};let t=e.context.sessionConfig.freshAge,o=r.session.createdAt.valueOf(),n=Date.now();if(!(o+t*1e3>n))throw new Z("FORBIDDEN",{message:"Session is not fresh"});return{session:r}});var lr=u("/revoke-session",{method:"POST",body:K.object({token:K.string({description:"The token to revoke"})}),use:[x],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let r=e.body.token,t=await e.context.internalAdapter.findSession(r);if(!t)throw new Z("BAD_REQUEST",{message:"Session not found"});if(t.session.userId!==e.context.session.user.id)throw new Z("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(r)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new Z("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ur=u("/revoke-sessions",{method:"POST",use:[x],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(r){throw e.context.logger.error(r&&typeof r=="object"&&"name"in r?r.name:"",r),new Z("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),pr=u("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[x],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let r=e.context.session;if(!r.user)throw new Z("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(r.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});async function W(e,r,t){return await fr("HS256",Buffer.from(e),{email:r.toLowerCase(),updateTo:t},{expiresIn:new mr(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[r],includeIssuedTimestamp:!0})}async function hr(e,r){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new te("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await W(e.context.secret,r.email),o=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:r,url:o,token:t},e.request)}var yr=u("/send-verification-email",{method:"POST",query:B.object({currentURL:B.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:B.object({email:B.string({description:"The email to send the verification email to"}).email(),callbackURL:B.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new te("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:r}=e.body,t=await e.context.internalAdapter.findUserByEmail(r);if(!t)throw new te("BAD_REQUEST",{message:f.USER_NOT_FOUND});return await hr(e,t.user),e.json({status:!0})}),wr=u("/verify-email",{method:"GET",query:B.object({token:B.string({description:"The token to verify the email"}),callbackURL:B.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function r(a){throw e.query.callbackURL?e.query.callbackURL.includes("?")?e.redirect(`${e.query.callbackURL}&error=${a}`):e.redirect(`${e.query.callbackURL}?error=${a}`):new te("UNAUTHORIZED",{message:a})}let{token:t}=e.query,o;try{o=await gr("HS256",Buffer.from(e.context.secret),t)}catch(a){return e.context.logger.error("Failed to verify email",a),r("invalid_token")}let i=B.object({email:B.string().email(),updateTo:B.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(i.email);if(!s)return r("user_not_found");if(i.updateTo){let a=await v(e);if(!a){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return r("unauthorized")}if(a.user.email!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return r("unauthorized")}let d=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),c=await W(e.context.secret,i.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:d,url:`${e.context.baseURL}/verify-email?token=${c}`,token:c},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:d,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await v(e)){let d=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!d)throw new te("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await S(e,{session:d,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});import{APIError as Hs,createRouter as Gs,getCookie as Zs,getSignedCookie as Ws,setCookie as Qs,setSignedCookie as Ys}from"better-call";import{APIError as Ar}from"better-call";function Oe(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function br(e){let r="";for(let t=0;t<e.length;t++)r+=Oe(e[t]);return r}function Ke(e,r=!0){if(Array.isArray(e))return`(?:${e.map(l=>`^${Ke(l,r)}$`).join("|")})`;let t="",o="",n=".";r===!0?(t="/",o="[/\\\\]",n="[^/\\\\]"):r&&(t=r,o=br(t),o.length>1?(o=`(?:${o})`,n=`((?!${o}).)`):n=`[^${o}]`);let i=r?`${o}+?`:"",s=r?`${o}*?`:"",a=r?e.split(t):[e],d="";for(let c=0;c<a.length;c++){let l=a[c],m=a[c+1],h="";if(!(!l&&c>0)){if(r&&(c===a.length-1?h=s:m!=="**"?h=i:h=""),r&&l==="**"){h&&(d+=c===0?"":h,d+=`(?:${n}*?${h})*?`);continue}for(let y=0;y<l.length;y++){let I=l[y];I==="\\"?y<l.length-1&&(d+=Oe(l[y+1]),y++):I==="?"?d+=n:I==="*"?d+=`${n}*?`:d+=Oe(I)}d+=h}}return d}function Or(e,r){if(typeof r!="string")throw new TypeError(`Sample must be a string, but ${typeof r} given`);return e.test(r)}function Ae(e,r){if(typeof e!="string"&&!Array.isArray(e))throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if((typeof r=="string"||typeof r=="boolean")&&(r={separator:r}),arguments.length===2&&!(typeof r>"u"||typeof r=="object"&&r!==null&&!Array.isArray(r)))throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof r} given`);if(r=r||{},r.separator==="\\")throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let t=Ke(e,r.separator),o=new RegExp(`^${t}$`,r.flags),n=Or.bind(null,o);return n.options=r,n.pattern=e,n.regexp=o,n}var Ir=Y(async e=>{if(e.request?.method!=="POST")return;let{body:r,query:t,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=r?.callbackURL||t?.callbackURL,s=r?.redirectTo,a=t?.currentURL,d=r?.errorCallbackURL,c=r?.newUserCallbackURL,l=o.trustedOrigins,m=e.headers?.has("cookie"),h=(I,N)=>I.startsWith("/")?!1:N.includes("*")?Ae(N)(ke(I)):I.startsWith(N),y=(I,N)=>{if(!I)return;if(!l.some(fe=>h(I,fe)||I?.startsWith("/")&&N!=="origin"&&!I.includes(":")))throw e.context.logger.error(`Invalid ${N}: ${I}`),e.context.logger.info(`If it's a valid URL, please add ${I} to trustedOrigins in your auth config
|
|
1
|
+
import{APIError as Et}from"better-call";import{z as ee}from"zod";import{createEndpointCreator as Rt,createMiddleware as Ee,createMiddlewareCreator as Tt}from"better-call";var Re=Ee(async()=>({})),Y=Tt({use:[Re,Ee(async()=>({}))]}),u=Rt({use:[Re]});import{APIError as k}from"better-call";import{z as _}from"zod";import{TimeSpan as Ao}from"oslo";import{base64url as Nt}from"oslo/encoding";import{HMAC as Te,sha256 as po}from"oslo/crypto";async function St({value:e,secret:r}){return new Te("SHA-256").sign(new TextEncoder().encode(r),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function vt({value:e,signature:r,secret:t}){return new Te("SHA-256").verify(new TextEncoder().encode(t),Buffer.from(r,"base64"),new TextEncoder().encode(e))}var se={sign:St,verify:vt};var F=class extends Error{constructor(r,t){super(r),this.name="BetterAuthError",this.message=r,this.cause=t,this.stack=""}};var q=(e,r="ms")=>new Date(Date.now()+(r==="sec"?e*1e3:e));var ae=Object.create(null),te=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?ae:globalThis),Ue=new Proxy(ae,{get(e,r){return te()[r]??ae[r]},has(e,r){let t=te();return r in t||r in ae},set(e,r,t){let o=te(!0);return o[r]=t,!0},deleteProperty(e,r){if(!r)return!1;let t=te(!0);return delete t[r],!0},ownKeys(){let e=te(!0);return Object.keys(e)}});function kt(e){return e?e!=="false":!1}var he=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var ye=he==="dev"||he==="development",zt=he==="test"||kt(Ue.TEST);async function S(e,r,t,o){let n=e.context.authCookies.sessionToken.options,i=t?void 0:e.context.sessionConfig.expiresIn;if(await e.setSignedCookie(e.context.authCookies.sessionToken.name,r.session.token,e.context.secret,{...n,maxAge:i,...o}),t&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled){let a=Nt.encode(new TextEncoder().encode(JSON.stringify({session:r,expiresAt:q(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await se.sign({value:JSON.stringify(r),secret:e.context.secret})})),{includePadding:!1});if(a.length>4093)throw new F("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");e.setCookie(e.context.authCookies.sessionData.name,a,e.context.authCookies.sessionData.options)}e.context.setNewSession(r),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(r.session.token,JSON.stringify({user:r.user,session:r.session}),Math.floor((new Date(r.session.expiresAt).getTime()-Date.now())/1e3))}function $(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}import{betterFetch as jt}from"@better-fetch/fetch";import{APIError as Bt}from"better-call";import{decodeProtectedHeader as Mt,importJWK as Vt,jwtVerify as Ft}from"jose";import{parseJWT as qt}from"oslo/jwt";import{sha256 as Lt}from"oslo/crypto";import{base64url as Pt}from"oslo/encoding";async function Se(e){let r=await Lt(new TextEncoder().encode(e));return Pt.encode(new Uint8Array(r),{includePadding:!1})}function de(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?q(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function O({id:e,options:r,authorizationEndpoint:t,state:o,codeVerifier:n,scopes:i,claims:s,redirectURI:a,duration:d}){let c=new URL(t);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",r.clientId),c.searchParams.set("state",o),c.searchParams.set("scope",i.join(" ")),c.searchParams.set("redirect_uri",r.redirectURI||a),n){let l=await Se(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((m,h)=>(m[h]=null,m),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return d&&c.searchParams.set("duration",d),c}import{betterFetch as Dt}from"@better-fetch/fetch";async function b({code:e,codeVerifier:r,redirectURI:t,options:o,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),r&&s.set("code_verifier",r),s.set("redirect_uri",t),i==="basic"){let m=btoa(`${o.clientId}:${o.clientSecret}`);a.authorization=`Basic ${m}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:d,error:c}=await Dt(n,{method:"POST",body:s,headers:a});if(c)throw c;return de(d)}import{generateCodeVerifier as xt,generateState as Ct}from"oslo/oauth2";import{z as G}from"zod";import{APIError as ze}from"better-call";function ve(e){try{return new URL(e).origin}catch{return null}}function ke(e){return e.includes("://")?new URL(e).host:e}async function ce(e,r){let t=e.body?.callbackURL||(e.query?.currentURL?ve(e.query?.currentURL):"")||e.context.options.baseURL;if(!t)throw new ze("BAD_REQUEST",{message:"callbackURL is required"});let o=xt(),n=Ct(),i=JSON.stringify({callbackURL:t,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,newUserURL:e.body?.newUserCallbackURL,link:r,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 ze("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function Ne(e){let r=e.query.state||e.body.state,t=await e.context.internalAdapter.findVerificationValue(r);if(!t)throw e.context.logger.error("State Mismatch. Verification not found",{state:r}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=G.object({callbackURL:G.string(),codeVerifier:G.string(),errorURL:G.string().optional(),newUserURL:G.string().optional(),expiresAt:G.number(),link:G.object({email:G.string(),userId:G.string()}).optional()}).parse(JSON.parse(t.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(t.id),e.context.logger.error("State expired.",{state:r}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(t.id),o}var Le=e=>{let r="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:t,scopes:o,redirectURI:n}){let i=o||["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=${t}&response_mode=form_post`)},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:n})=>b({code:t,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async verifyIdToken(t,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,o);let n=Mt(t),{kid:i,alg:s}=n;if(!i||!s)return!1;let a=await $t(i),{payload:d}=await Ft(t,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])}),o&&d.nonce!==o?!1:!!d},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let o=qt(t.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email,...i},data:o}}}},$t=async e=>{let r="https://appleid.apple.com",t="/auth/keys",{data:o}=await jt(`${r}${t}`);if(!o?.keys)throw new Bt("BAD_REQUEST",{message:"Keys not found"});let n=o.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await Vt(n,n.alg)};import{betterFetch as Ht}from"@better-fetch/fetch";var Pe=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["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||o)}&state=${r}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:r,redirectURI:t})=>b({code:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await Ht("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${r.accessToken}`}});if(o)return null;if(t.avatar===null){let i=t.discriminator==="0"?Number(BigInt(t.id)>>BigInt(22))%6:parseInt(t.discriminator)%5;t.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=t.avatar.startsWith("a_")?"gif":"png";t.image_url=`https://cdn.discordapp.com/avatars/${t.id}/${t.avatar}.${i}`}let n=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.display_name||t.username||"",email:t.email,emailVerified:t.verified,image:t.image_url,...n},data:t}}});import{betterFetch as Gt}from"@better-fetch/fetch";var De=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["email","public_profile"];return e.scope&&n.push(...e.scope),await O({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:r,redirectURI:o})},validateAuthorizationCode:async({code:r,redirectURI:t})=>b({code:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await Gt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:r.accessToken}});if(o)return null;let n=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.name,email:t.email,image:t.picture.data.url,emailVerified:t.email_verified,...n},data:t}}});import{betterFetch as xe}from"@better-fetch/fetch";var Ce=e=>{let r="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:t,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),O({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:t,redirectURI:i})},validateAuthorizationCode:async({code:t,redirectURI:o})=>b({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:n}=await xe("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:a,error:d}=await xe("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});d||(o.email=(a.find(c=>c.primary)??a[0])?.email,i=a.find(c=>c.email===o.email)?.verified??!1)}let s=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i,...s},data:o}}}};import{parseJWT as Kt}from"oslo/jwt";import{createConsola as Zt}from"consola";var we=["info","success","warn","error","debug"];function Wt(e,r){return we.indexOf(r)<=we.indexOf(e)}var Qt=Zt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Yt=e=>{let r=e?.disabled!==!0,t=e?.level??"error",o=(n,i,s=[])=>{if(!(!r||!Wt(t,n))){if(!e||typeof e.log!="function"){Qt[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(we.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},j=Yt();import{betterFetch as Jt}from"@better-fetch/fetch";var je=e=>({id:"google",name:"Google",async createAuthorizationURL({state:r,scopes:t,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw j.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new F("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new F("codeVerifier is required for Google");let i=t||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await O({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:r,codeVerifier:o,redirectURI:n});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:o})=>b({code:r,codeVerifier:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(r,t){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,t);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${r}`,{data:n}=await Jt(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let t=Kt(r.idToken)?.payload,o=await e.mapProfileToUser?.(t);return{user:{id:t.sub,name:t.name,email:t.email,image:t.picture,emailVerified:t.email_verified,...o},data:t}}});import{betterFetch as Xt}from"@better-fetch/fetch";import{parseJWT as er}from"oslo/jwt";var Be=e=>{let r=e.tenantId||"common",t=`https://login.microsoftonline.com/${r}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${r}/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),O({id:"microsoft",options:e,authorizationEndpoint:t,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return b({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=er(n.idToken)?.payload,s=e.profilePhotoSize||48;await Xt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(d){if(!(e.disableProfilePhoto||!d.response.ok))try{let l=await d.response.clone().arrayBuffer(),m=Buffer.from(l).toString("base64");i.picture=`data:image/jpeg;base64, ${m}`}catch(c){j.error(c&&typeof c=="object"&&"name"in c?c.name:"",c)}}});let a=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0,...a},data:i}}}};import{betterFetch as tr}from"@better-fetch/fetch";var Me=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:r,scopes:t,codeVerifier:o,redirectURI:n}){let i=t||["user-read-email"];return e.scope&&i.push(...e.scope),O({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:r,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:o})=>b({code:r,codeVerifier:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await tr("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.display_name,email:t.email,image:t.images[0]?.url,emailVerified:!1,...n},data:t}}});var X={isAction:!1};import{nanoid as rr}from"nanoid";var H=e=>rr(e);import{parseJWT as or}from"oslo/jwt";var Ve=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["user:read:email","openid"];return e.scope&&n.push(...e.scope),O({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:r,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:r,redirectURI:t})=>b({code:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let t=r.idToken;if(!t)return j.error("No idToken found in token"),null;let o=or(t)?.payload,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...n},data:o}}});import{betterFetch as nr}from"@better-fetch/fetch";var Fe=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(r){let t=r.scopes||["users.read","tweet.read","offline.access"];return e.scope&&t.push(...e.scope),O({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:t,state:r.state,codeVerifier:r.codeVerifier,redirectURI:r.redirectURI})},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:o})=>b({code:r,codeVerifier:t,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await nr("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(t);return{user:{id:t.data.id,name:t.data.name,email:t.data.username||null,image:t.data.profile_image_url,emailVerified:t.data.verified||!1,...n},data:t}}});import{betterFetch as ir}from"@better-fetch/fetch";var qe=e=>{let r="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:t,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await O({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:t,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:n})=>await b({code:t,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:n}=await ir("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...i},data:o}}}};import{betterFetch as sr}from"@better-fetch/fetch";var $e=e=>{let r="https://www.linkedin.com/oauth/v2/authorization",t="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await O({id:"linkedin",options:e,authorizationEndpoint:r,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await b({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(o){let{data:n,error:i}=await sr("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(i)return null;let s=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture,...s},data:n}}}};import{betterFetch as ar}from"@better-fetch/fetch";var be=(e="")=>e.split("://").map(r=>r.replace(/\/{2,}/g,"/")).join("://"),dr=e=>{let r=e||"https://gitlab.com";return{authorizationEndpoint:be(`${r}/oauth/authorize`),tokenEndpoint:be(`${r}/oauth/token`),userinfoEndpoint:be(`${r}/api/v4/user`)}},He=e=>{let{authorizationEndpoint:r,tokenEndpoint:t,userinfoEndpoint:o}=dr(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 O({id:n,options:e,authorizationEndpoint:r,scopes:l,state:s,redirectURI:c,codeVerifier:d})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:d})=>b({code:s,redirectURI:e.redirectURI||a,options:e,codeVerifier:d,tokenEndpoint:t}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:a,error:d}=await ar(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(d||a.state!=="active"||a.locked)return null;let c=await e.mapProfileToUser?.(a);return{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0,...c},data:a}}}};import{betterFetch as Ge}from"@better-fetch/fetch";var Ze=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["identity"];return e.scope&&n.push(...e.scope),O({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:n,state:r,redirectURI:o,duration:e.duration})},validateAuthorizationCode:async({code:r,redirectURI:t})=>{let o=new URLSearchParams({grant_type:"authorization_code",code:r,redirect_uri:e.redirectURI||t}),n={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`},{data:i,error:s}=await Ge("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:n,body:o.toString()});if(s)throw s;return de(i)},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:t,error:o}=await Ge("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let n=await e.mapProfileToUser?.(t);return{user:{id:t.id,name:t.name,email:t.oauth_client_id,emailVerified:t.has_verified_email,image:t.icon_img?.split("?")[0],...n},data:t}}});var cr={apple:Le,discord:Pe,facebook:De,github:Ce,microsoft:Be,google:je,spotify:Me,twitch:Ve,twitter:Fe,dropbox:qe,linkedin:$e,gitlab:He,reddit:Ze},le=Object.keys(cr);import{TimeSpan as mr}from"oslo";import{createJWT as fr,validateJWT as gr}from"oslo/jwt";import{z as B}from"zod";import{APIError as re}from"better-call";import{APIError as Z}from"better-call";import{z as K}from"zod";function We(e){try{return JSON.parse(e)}catch{return null}}var f={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found"};var Qe=()=>u("/get-session",{method:"GET",query:K.optional(K.object({disableCookieCache:K.boolean({description:"Disable cookie cache and fetch session from database"}).or(K.string().transform(e=>e==="true")).optional(),disableRefresh:K.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let r=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!r)return e.json(null);let t=e.getCookie(e.context.authCookies.sessionData.name),o=t?We(Buffer.from(t,"base64").toString()):null;if(o&&!await se.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return $(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let l=o.session;if(o.expiresAt<Date.now()||l.session.expiresAt<new Date){let h=e.context.authCookies.sessionData.name;e.setCookie(h,"",{maxAge:0})}else return e.json(l)}let i=await e.context.internalAdapter.findSession(r);if(e.context.session=i,!i||i.session.expiresAt<new Date)return $(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n||e.query?.disableRefresh)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.token,{expiresAt:q(e.context.sessionConfig.expiresIn,"sec")});if(!l)return $(e),e.json(null,{status:401});let m=(l.expiresAt.valueOf()-Date.now())/1e3;return await S(e,{session:l,user:i.user},!1,{maxAge:m}),e.json({session:l,user:i.user})}return e.json(i)}catch(r){throw e.context.logger.error("INTERNAL_SERVER_ERROR",r),new Z("INTERNAL_SERVER_ERROR",{message:f.FAILED_TO_GET_SESSION})}}),v=async(e,r)=>{if(e.context.session)return e.context.session;let t=await Qe()({...e,_flag:"json",headers:e.headers,query:r}).catch(o=>null);return e.context.session=t,t},x=Y(async e=>{let r=await v(e);if(!r?.session)throw new Z("UNAUTHORIZED");return{session:r}}),Ye=Y(async e=>{let r=await v(e);if(!r?.session)throw new Z("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:r};let t=e.context.sessionConfig.freshAge,o=r.session.updatedAt?.valueOf()||r.session.createdAt.valueOf();if(!(Date.now()-o<t*1e3))throw new Z("FORBIDDEN",{message:"Session is not fresh"});return{session:r}});var lr=u("/revoke-session",{method:"POST",body:K.object({token:K.string({description:"The token to revoke"})}),use:[x],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let r=e.body.token,t=await e.context.internalAdapter.findSession(r);if(!t)throw new Z("BAD_REQUEST",{message:"Session not found"});if(t.session.userId!==e.context.session.user.id)throw new Z("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(r)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new Z("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ur=u("/revoke-sessions",{method:"POST",use:[x],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(r){throw e.context.logger.error(r&&typeof r=="object"&&"name"in r?r.name:"",r),new Z("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),pr=u("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[x],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let r=e.context.session;if(!r.user)throw new Z("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(r.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});async function W(e,r,t){return await fr("HS256",Buffer.from(e),{email:r.toLowerCase(),updateTo:t},{expiresIn:new mr(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[r],includeIssuedTimestamp:!0})}async function hr(e,r){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new re("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await W(e.context.secret,r.email),o=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:r,url:o,token:t},e.request)}var yr=u("/send-verification-email",{method:"POST",query:B.object({currentURL:B.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:B.object({email:B.string({description:"The email to send the verification email to"}).email(),callbackURL:B.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new re("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:r}=e.body,t=await e.context.internalAdapter.findUserByEmail(r);if(!t)throw new re("BAD_REQUEST",{message:f.USER_NOT_FOUND});return await hr(e,t.user),e.json({status:!0})}),wr=u("/verify-email",{method:"GET",query:B.object({token:B.string({description:"The token to verify the email"}),callbackURL:B.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function r(a){throw e.query.callbackURL?e.query.callbackURL.includes("?")?e.redirect(`${e.query.callbackURL}&error=${a}`):e.redirect(`${e.query.callbackURL}?error=${a}`):new re("UNAUTHORIZED",{message:a})}let{token:t}=e.query,o;try{o=await gr("HS256",Buffer.from(e.context.secret),t)}catch(a){return e.context.logger.error("Failed to verify email",a),r("invalid_token")}let i=B.object({email:B.string().email(),updateTo:B.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(i.email);if(!s)return r("user_not_found");if(i.updateTo){let a=await v(e);if(!a){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return r("unauthorized")}if(a.user.email!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return r("unauthorized")}let d=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),c=await W(e.context.secret,i.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:d,url:`${e.context.baseURL}/verify-email?token=${c}`,token:c},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:d,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await v(e)){let d=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!d)throw new re("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await S(e,{session:d,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});import{APIError as Hs,createRouter as Gs,getCookie as Zs,getSignedCookie as Ws,setCookie as Qs,setSignedCookie as Ys}from"better-call";import{APIError as Ar}from"better-call";function Oe(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function br(e){let r="";for(let t=0;t<e.length;t++)r+=Oe(e[t]);return r}function Ke(e,r=!0){if(Array.isArray(e))return`(?:${e.map(l=>`^${Ke(l,r)}$`).join("|")})`;let t="",o="",n=".";r===!0?(t="/",o="[/\\\\]",n="[^/\\\\]"):r&&(t=r,o=br(t),o.length>1?(o=`(?:${o})`,n=`((?!${o}).)`):n=`[^${o}]`);let i=r?`${o}+?`:"",s=r?`${o}*?`:"",a=r?e.split(t):[e],d="";for(let c=0;c<a.length;c++){let l=a[c],m=a[c+1],h="";if(!(!l&&c>0)){if(r&&(c===a.length-1?h=s:m!=="**"?h=i:h=""),r&&l==="**"){h&&(d+=c===0?"":h,d+=`(?:${n}*?${h})*?`);continue}for(let y=0;y<l.length;y++){let I=l[y];I==="\\"?y<l.length-1&&(d+=Oe(l[y+1]),y++):I==="?"?d+=n:I==="*"?d+=`${n}*?`:d+=Oe(I)}d+=h}}return d}function Or(e,r){if(typeof r!="string")throw new TypeError(`Sample must be a string, but ${typeof r} given`);return e.test(r)}function Ae(e,r){if(typeof e!="string"&&!Array.isArray(e))throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if((typeof r=="string"||typeof r=="boolean")&&(r={separator:r}),arguments.length===2&&!(typeof r>"u"||typeof r=="object"&&r!==null&&!Array.isArray(r)))throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof r} given`);if(r=r||{},r.separator==="\\")throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let t=Ke(e,r.separator),o=new RegExp(`^${t}$`,r.flags),n=Or.bind(null,o);return n.options=r,n.pattern=e,n.regexp=o,n}var Ir=Y(async e=>{if(e.request?.method!=="POST")return;let{body:r,query:t,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=r?.callbackURL||t?.callbackURL,s=r?.redirectTo,a=t?.currentURL,d=r?.errorCallbackURL,c=r?.newUserCallbackURL,l=o.trustedOrigins,m=e.headers?.has("cookie"),h=(I,N)=>I.startsWith("/")?!1:N.includes("*")?Ae(N)(ke(I)):I.startsWith(N),y=(I,N)=>{if(!I)return;if(!l.some(fe=>h(I,fe)||I?.startsWith("/")&&N!=="origin"&&!I.includes(":")))throw e.context.logger.error(`Invalid ${N}: ${I}`),e.context.logger.info(`If it's a valid URL, please add ${I} to trustedOrigins in your auth config
|
|
2
2
|
`,`Current list of trustedOrigins: ${l}`),new Ar("FORBIDDEN",{message:`Invalid ${N}`})};m&&!e.context.options.advanced?.disableCSRFCheck&&y(n,"origin"),i&&y(i,"callbackURL"),s&&y(s,"redirectURL"),a&&y(a,"currentURL"),d&&y(d,"errorCallbackURL"),c&&y(s,"newUserCallbackURL")});var _r=u("/ok",{method:"GET",metadata:{...X,openapi:{description:"Check if the API is working",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean"}}}}}}}}}},async e=>e.json({ok:!0}));import{z as ws}from"zod";import{APIError as Rs}from"better-call";import{z as g}from"zod";import{APIError as us}from"better-call";var ps=g.object({id:g.string(),providerId:g.string(),accountId:g.string(),userId:g.string(),accessToken:g.string().nullish(),refreshToken:g.string().nullish(),idToken:g.string().nullish(),accessTokenExpiresAt:g.date().nullish(),refreshTokenExpiresAt:g.date().nullish(),scope:g.string().nullish(),password:g.string().nullish(),createdAt:g.date().default(()=>new Date),updatedAt:g.date().default(()=>new Date)}),ms=g.object({id:g.string(),email:g.string().transform(e=>e.toLowerCase()),emailVerified:g.boolean().default(!1),name:g.string(),image:g.string().nullish(),createdAt:g.date().default(()=>new Date),updatedAt:g.date().default(()=>new Date)}),fs=g.object({id:g.string(),userId:g.string(),expiresAt:g.date(),createdAt:g.date().default(()=>new Date),updatedAt:g.date().default(()=>new Date),token:g.string(),ipAddress:g.string().nullish(),userAgent:g.string().nullish()}),gs=g.object({id:g.string(),value:g.string(),createdAt:g.date().default(()=>new Date),updatedAt:g.date().default(()=>new Date),expiresAt:g.date(),identifier:g.string()});var Rr=(e="Unknown")=>`<!DOCTYPE html>
|
|
3
3
|
<html lang="en">
|
|
4
4
|
<head>
|
|
@@ -80,4 +80,4 @@ import{APIError as Et}from"better-call";import{z as ie}from"zod";import{createEn
|
|
|
80
80
|
</div>
|
|
81
81
|
</body>
|
|
82
82
|
</html>`,Tr=u("/error",{method:"GET",metadata:{...X,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string"}}}}}}}},async e=>{let r=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Rr(r),{headers:{"Content-Type":"text/html"}})});import ia from"defu";import{APIError as ua}from"better-call";async function ue(e,{userInfo:r,account:t,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(r.email.toLowerCase(),{includeAccounts:!0}).catch(d=>{throw j.error(`Better auth was unable to query your database.
|
|
83
|
-
Error: `,d),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user,s=!i;if(n){let d=n.accounts.find(c=>c.providerId===t.providerId);if(d){let c=Object.fromEntries(Object.entries({accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt}).filter(([l,m])=>m!==void 0));Object.keys(c).length>0&&await e.context.internalAdapter.updateAccount(d.id,c)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.providerId)&&!r.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return ye&&j.warn(`User already exist but account isn't linked to ${t.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:t.providerId,accountId:r.id.toString(),userId:n.user.id,accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt,scope:t.scope})}catch(m){return j.error("Unable to link account",m),{error:"unable to link account",data:null}}i=await e.context.internalAdapter.updateUser(n.user.id,{...r,updatedAt:new Date})}}else if(i=await e.context.internalAdapter.createOAuthUser({...r,email:r.email.toLowerCase(),id:void 0},{accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt,scope:t.scope,providerId:t.providerId,accountId:r.id.toString()}).then(d=>d?.user),!r.emailVerified&&i&&e.context.options.emailVerification?.sendOnSignUp){let d=await W(e.context.secret,i.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:c,token:d},e.request)}if(!i)return{error:"unable to create user",data:null,isRegister:!1};let a=await e.context.internalAdapter.createSession(i.id,e.request);return a?{data:{session:a,user:i},error:null,isRegister:s}:{error:"unable to create session",data:null,isRegister:!1}}var Ur=u("/sign-in/social",{method:"POST",query:_.object({currentURL:_.string().optional()}).optional(),body:_.object({callbackURL:_.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:_.string().optional(),errorCallbackURL:_.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:_.enum(le,{description:"OAuth2 provider to use"}),disableRedirect:_.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:_.optional(_.object({token:_.string({description:"ID token from the provider"}),nonce:_.string({description:"Nonce used to generate the token"}).optional(),accessToken:_.string({description:"Access token from the provider"}).optional(),refreshToken:_.string({description:"Refresh token from the provider"}).optional(),expiresAt:_.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let r=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!r)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new k("NOT_FOUND",{message:f.PROVIDER_NOT_FOUND});if(e.body.idToken){if(!r.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new k("NOT_FOUND",{message:f.ID_TOKEN_NOT_SUPPORTED});let{token:i,nonce:s}=e.body.idToken;if(!await r.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new k("UNAUTHORIZED",{message:f.INVALID_TOKEN});let d=await r.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 k("UNAUTHORIZED",{message:f.FAILED_TO_GET_USER_INFO});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new k("UNAUTHORIZED",{message:f.USER_EMAIL_NOT_FOUND});let c=await ue(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:r.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new k("UNAUTHORIZED",{message:c.error});return await S(e,c.data),e.json({session:c.data.session,user:c.data.user,url:void 0,redirect:!1})}let{codeVerifier:t,state:o}=await ce(e),n=await r.createAuthorizationURL({state:o,codeVerifier:t,redirectURI:`${e.context.baseURL}/callback/${r.id}`});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),Sr=u("/sign-in/email",{method:"POST",body:_.object({email:_.string({description:"Email of the user"}),password:_.string({description:"Password of the user"}),callbackURL:_.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:_.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new k("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:r,password:t}=e.body;if(!_.string().email().safeParse(r).success)throw new k("BAD_REQUEST",{message:f.INVALID_EMAIL});let n=await e.context.internalAdapter.findUserByEmail(r,{includeAccounts:!0});if(!n)throw await e.context.password.hash(t),e.context.logger.error("User not found",{email:r}),new k("UNAUTHORIZED",{message:f.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:r}),new k("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:r}),new k("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:s,password:t}))throw e.context.logger.error("Invalid password"),new k("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new k("UNAUTHORIZED",{message:f.EMAIL_NOT_VERIFIED});let c=await W(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:r}),new k("FORBIDDEN",{message:f.EMAIL_NOT_VERIFIED})}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 k("UNAUTHORIZED",{message:f.FAILED_TO_CREATE_SESSION});return await S(e,{session:d,user:n.user},e.body.rememberMe===!1),e.json({user:{id:n.user.id,email:n.user.email,name:n.user.name,image:n.user.image,emailVerified:n.user.emailVerified,createdAt:n.user.createdAt,updatedAt:n.user.updatedAt},redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as re}from"zod";var pe=re.object({code:re.string().optional(),error:re.string().optional(),error_description:re.string().optional(),state:re.string().optional()}),vr=u("/callback/:id",{method:["GET","POST"],body:pe.optional(),query:pe.optional(),metadata:X},async e=>{let r;try{if(e.method==="GET")r=pe.parse(e.query);else if(e.method==="POST")r=pe.parse(e.body);else throw new Error("Unsupported method")}catch(D){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",D),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:t,error:o,state:n,error_description:i}=r;if(!n)throw e.context.logger.error("State not found",o),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!t)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}&error_description=${i}`);let s=e.context.socialProviders.find(D=>D.id===e.params.id);if(!s)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:a,callbackURL:d,link:c,errorURL:l,newUserURL:m}=await Ne(e),h;try{h=await s.validateAuthorizationCode({code:t,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${s.id}`})}catch(D){throw e.context.logger.error("",D),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let y=await s.getUserInfo(h).then(D=>D?.user);function I(D){let V=l||d||`${e.context.baseURL}/error`;throw V.includes("?")?V=`${V}&error=${D}`:V=`${V}?error=${D}`,e.redirect(V)}if(!y)return e.context.logger.error("Unable to get user info"),I("unable_to_get_user_info");if(!y.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),I("email_not_found");if(!d)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(c){if(c.email!==y.email.toLowerCase())return I("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:c.userId,providerId:s.id,accountId:y.id}))return I("unable_to_link_account");let V;try{V=d.toString()}catch{V=d}throw e.redirect(V)}let N=await ue(e,{userInfo:{...y,email:y.email,name:y.name||y.email},account:{providerId:s.id,accountId:y.id,...h,scope:h.scopes?.join(",")},callbackURL:d});if(N.error)return e.context.logger.error(N.error.split(" ").join("_")),I(N.error.split(" ").join("_"));let{session:_e,user:fe}=N.data;await S(e,{session:_e,user:fe});let ge;try{ge=(N.isRegister&&m||d).toString()}catch{ge=N.isRegister&&m||d}throw e.redirect(ge)});import"zod";import{APIError as Vr}from"better-call";var kr=u("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let r=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!r)throw $(e),new Vr("BAD_REQUEST",{message:f.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(r),$(e),e.json({success:!0})});import{z as C}from"zod";import{APIError as oe}from"better-call";function Je(e,r,t){let o=r?new URL(r,e.baseURL):new URL(`${e.baseURL}/error`);return t&&Object.entries(t).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function Fr(e,r,t){let o=new URL(r,e.baseURL);return t&&Object.entries(t).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var zr=u("/forget-password",{method:"POST",body:C.object({email:C.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:C.string({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new oe("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:r,redirectTo:t}=e.body,o=await e.context.internalAdapter.findUserByEmail(r,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:r}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=q(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=H(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:i});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${t}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:a,token:s},e.request),e.json({status:!0})}),Nr=u("/reset-password/:token",{method:"GET",query:C.object({callbackURL:C.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:r}=e.params,{callbackURL:t}=e.query;if(!r||!t)throw e.redirect(Je(e.context,t,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${r}`);throw!o||o.expiresAt<new Date?e.redirect(Je(e.context,t,{error:"INVALID_TOKEN"})):e.redirect(Fr(e.context,t,{token:r}))}),Lr=u("/reset-password",{query:C.optional(C.object({token:C.string().optional(),currentURL:C.string().optional()})),method:"POST",body:C.object({newPassword:C.string({description:"The new password to set"}),token:C.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let r=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!r)throw new oe("BAD_REQUEST",{message:f.INVALID_TOKEN});let{newPassword:t}=e.body,o=e.context.password?.config.minPasswordLength,n=e.context.password?.config.maxPasswordLength;if(t.length<o)throw new oe("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});if(t.length>n)throw new oe("BAD_REQUEST",{message:f.PASSWORD_TOO_LONG});let i=`reset-password:${r}`,s=await e.context.internalAdapter.findVerificationValue(i);if(!s||s.expiresAt<new Date)throw new oe("BAD_REQUEST",{message:f.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(s.id);let a=s.value,d=await e.context.password.hash(t);return(await e.context.internalAdapter.findAccounts(a)).find(m=>m.providerId==="credential")?(await e.context.internalAdapter.updatePassword(a,d),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:a,providerId:"credential",password:d,accountId:a}),e.json({status:!0}))});import{z as L}from"zod";import{APIError as U}from"better-call";import{xchacha20poly1305 as sd}from"@noble/ciphers/chacha";import{bytesToHex as dd,hexToBytes as cd,utf8ToBytes as ld}from"@noble/ciphers/utils";import{managedNonce as pd}from"@noble/ciphers/webcrypto";import{sha256 as fd}from"oslo/crypto";import hd from"uncrypto";import{decodeHex as Qa,encodeHex as Ya}from"oslo/encoding";import{scryptAsync as Xa}from"@noble/hashes/scrypt";import{getRandomValues as td}from"uncrypto";import Xe from"uncrypto";function qr(e){return e.toString(2).padStart(8,"0")}function $r(e){return[...e].map(r=>qr(r)).join("")}function et(e){return parseInt($r(e),2)}function Hr(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let r=(e-1).toString(2).length,t=r%8,o=new Uint8Array(Math.ceil(r/8));Xe.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1);let n=et(o);for(;n>=e;)Xe.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1),n=et(o);return n}function tt(e,r){let t="";for(let o=0;o<e;o++)t+=r[Hr(r.length)];return t}function rt(...e){let r=new Set(e),t="";for(let o of r)o==="a-z"?t+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?t+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?t+="0123456789":t+=o;return t}var Pr=u("/change-password",{method:"POST",body:L.object({newPassword:L.string({description:"The new password to set"}),currentPassword:L.string({description:"The current password"}),revokeOtherSessions:L.boolean({description:"Revoke all other sessions"}).optional()}),use:[x],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:r,currentPassword:t,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(r.length<i)throw e.context.logger.error("Password is too short"),new U("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});let s=e.context.password.config.maxPasswordLength;if(r.length>s)throw e.context.logger.error("Password is too long"),new U("BAD_REQUEST",{message:f.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 U("BAD_REQUEST",{message:f.CREDENTIAL_ACCOUNT_NOT_FOUND});let c=await e.context.password.hash(r);if(!await e.context.password.verify({hash:d.password,password:t}))throw new U("BAD_REQUEST",{message:f.INVALID_PASSWORD});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let m=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!m)throw new U("INTERNAL_SERVER_ERROR",{message:f.FAILED_TO_GET_SESSION});await S(e,{session:m,user:n.user})}return e.json(n.user)}),Dr=u("/set-password",{method:"POST",body:L.object({newPassword:L.string()}),metadata:{SERVER_ONLY:!0},use:[x]},async e=>{let{newPassword:r}=e.body,t=e.context.session,o=e.context.password.config.minPasswordLength;if(r.length<o)throw e.context.logger.error("Password is too short"),new U("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});let n=e.context.password.config.maxPasswordLength;if(r.length>n)throw e.context.logger.error("Password is too long"),new U("BAD_REQUEST",{message:f.PASSWORD_TOO_LONG});let s=(await e.context.internalAdapter.findAccounts(t.user.id)).find(d=>d.providerId==="credential"&&d.password),a=await e.context.password.hash(r);if(!s)return await e.context.internalAdapter.linkAccount({userId:t.user.id,providerId:"credential",accountId:t.user.id,password:a}),e.json(t.user);throw new U("BAD_REQUEST",{message:"user already has a password"})}),xr=u("/delete-user",{method:"POST",use:[Ye],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options",{session:e.context.session}),new U("NOT_FOUND");let r=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=tt(32,rt("a-z","A-Z","0-9"));await e.context.internalAdapter.createVerificationValue({value:r.user.id,identifier:`delete-account-${n}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let i=`${e.context.baseURL}/delete-user/callback?token=${n}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:r.user,url:i,token:n},e.request),e.json({success:!0,message:"Verification email sent"})}let t=e.context.options.user.deleteUser?.beforeDelete;t&&await t(r.user,e.request),await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),await e.context.internalAdapter.deleteAccounts(r.user.id),$(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(r.user,e.request),e.json({success:!0,message:"User deleted"})}),Cr=u("/delete-user/callback",{method:"GET",query:L.object({token:L.string()})},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new U("NOT_FOUND");let r=await v(e);if(!r)throw new U("NOT_FOUND",{message:f.FAILED_TO_GET_USER_INFO});let t=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!t||t.expiresAt<new Date)throw t&&await e.context.internalAdapter.deleteVerificationValue(t.id),new U("NOT_FOUND",{message:f.INVALID_TOKEN});if(t.value!==r.user.id)throw new U("NOT_FOUND",{message:f.INVALID_TOKEN});let o=e.context.options.user.deleteUser?.beforeDelete;o&&await o(r.user,e.request),await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),await e.context.internalAdapter.deleteAccounts(r.user.id),await e.context.internalAdapter.deleteVerificationValue(t.id),$(e);let n=e.context.options.user.deleteUser?.afterDelete;return n&&await n(r.user,e.request),e.json({success:!0,message:"User deleted"})}),jr=u("/change-email",{method:"POST",query:L.object({currentURL:L.string().optional()}).optional(),body:L.object({newEmail:L.string({description:"The new email to set"}).email(),callbackURL:L.string({description:"The URL to redirect to after email verification"}).optional()}),use:[x],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new U("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 U("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 U("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 U("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await W(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:t},e.request),e.json({user:null,status:!0})});import{z as ne}from"zod";import{APIError as ot}from"better-call";var Br=u("/list-accounts",{method:"GET",use:[x],metadata:{openapi:{description:"List all accounts linked to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},provider:{type:"string"}}}}}}}}}}},async e=>{let r=e.context.session,t=await e.context.internalAdapter.findAccounts(r.user.id);return e.json(t.map(o=>({id:o.id,provider:o.providerId})))}),Mr=u("/link-social",{method:"POST",requireHeaders:!0,query:ne.object({currentURL:ne.string().optional()}).optional(),body:ne.object({callbackURL:ne.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:ne.enum(le,{description:"The OAuth2 provider to use"})}),use:[x],metadata:{openapi:{description:"Link a social account to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}},required:["url","redirect"]}}}}}}}},async e=>{let r=e.context.session;if((await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId===e.body.provider))throw new ot("BAD_REQUEST",{message:f.SOCIAL_ACCOUNT_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 ot("NOT_FOUND",{message:f.PROVIDER_NOT_FOUND});let i=await ce(e,{userId:r.user.id,email:r.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 nt=(e,r)=>{let t={};for(let[o,n]of Object.entries(e))t[o]=i=>n({...i,context:{...r,...i.context}}),t[o].path=n.path,t[o].method=n.method,t[o].options=n.options,t[o].headers=n.headers;return t};function me(e){let r=e;return{newRole(t){return Gr(t)}}}function Gr(e){return{statements:e,authorize(r,t){for(let[o,n]of Object.entries(r)){let i=e[o];return i?(t==="OR"?n.some(a=>i.includes(a)):n.every(a=>i.includes(a)))?{success:!0}:{success:!1,error:`Unauthorized to access resource "${o}"`}:{success:!1,error:`You are not allowed to access resource: ${o}`}}return{success:!1,error:"Not authorized"}}}}var Zr={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},Ie=me(Zr),Wr=Ie.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),Qr=Ie.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),Yr=Ie.newRole({organization:[],member:[],invitation:[]}),it={admin:Wr,owner:Qr,member:Yr};var Kr={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},Jr=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,st={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},Xr=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function eo(e){return e instanceof Date&&!isNaN(e.getTime())}function to(e){let r=Xr.exec(e);if(!r)return null;let[,t,o,n,i,s,a,d,c,l,m]=r,h=new Date(Date.UTC(parseInt(t,10),parseInt(o,10)-1,parseInt(n,10),parseInt(i,10),parseInt(s,10),parseInt(a,10),d?parseInt(d.padEnd(3,"0"),10):0));if(c){let y=(parseInt(l,10)*60+parseInt(m,10))*(c==="+"?-1:1);h.setUTCMinutes(h.getUTCMinutes()+y)}return eo(h)?h:null}function ro(e,r={}){let{strict:t=!1,warnings:o=!1,reviver:n,parseDates:i=!0}=r;if(typeof e!="string")return e;let s=e.trim();if(s[0]==='"'&&s.endsWith('"')&&!s.slice(1,-1).includes('"'))return s.slice(1,-1);let a=s.toLowerCase();if(a.length<=9&&a in st)return st[a];if(!Jr.test(s)){if(t)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(Kr).some(([c,l])=>{let m=l.test(s);return m&&o&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${c} pattern`),m})&&t)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(s,(l,m)=>{if(l==="__proto__"||l==="constructor"&&m&&typeof m=="object"&&"prototype"in m){o&&console.warn(`[better-json] Dropping "${l}" key to prevent prototype pollution`);return}if(i&&typeof m=="string"){let h=to(m);if(h)return h}return n?n(l,m):m})}catch(c){if(t)throw c;return e}}function oo(e,r={strict:!0}){return ro(e,r)}var at=oo;var E=(e,r)=>{let t=e.adapter;return{findOrganizationBySlug:async o=>await t.findOne({model:"organization",where:[{field:"slug",value:o}]}),createOrganization:async o=>{let n=await t.create({model:"organization",data:{...o.organization,metadata:o.organization.metadata?JSON.stringify(o.organization.metadata):void 0}}),i=await t.create({model:"member",data:{organizationId:n.id,userId:o.user.id,createdAt:new Date,role:r?.creatorRole||"owner"}});return{...n,metadata:n.metadata?JSON.parse(n.metadata):void 0,members:[{...i,user:{id:o.user.id,name:o.user.name,email:o.user.email,image:o.user.image}}]}},findMemberByEmail:async o=>{let n=await t.findOne({model:"user",where:[{field:"email",value:o.email}]});if(!n)return null;let i=await t.findOne({model:"member",where:[{field:"organizationId",value:o.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 o=>{let[n,i]=await Promise.all([await t.findOne({model:"member",where:[{field:"userId",value:o.userId},{field:"organizationId",value:o.organizationId}]}),await t.findOne({model:"user",where:[{field:"id",value:o.userId}]})]);return!i||!n?null:{...n,user:{id:i.id,name:i.name,email:i.email,image:i.image}}},findMemberById:async o=>{let n=await t.findOne({model:"member",where:[{field:"id",value:o}]});if(!n)return null;let i=await t.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 o=>await t.create({model:"member",data:o}),updateMember:async(o,n)=>await t.update({model:"member",where:[{field:"id",value:o}],update:{role:n}}),deleteMember:async o=>await t.delete({model:"member",where:[{field:"id",value:o}]}),updateOrganization:async(o,n)=>{let i=await t.update({model:"organization",where:[{field:"id",value:o}],update:{...n,metadata:typeof n.metadata=="object"?JSON.stringify(n.metadata):n.metadata}});return i?{...i,metadata:i.metadata?at(i.metadata):void 0}:null},deleteOrganization:async o=>(await t.delete({model:"member",where:[{field:"organizationId",value:o}]}),await t.delete({model:"invitation",where:[{field:"organizationId",value:o}]}),await t.delete({model:"organization",where:[{field:"id",value:o}]}),o),setActiveOrganization:async(o,n)=>await e.internalAdapter.updateSession(o,{activeOrganizationId:n}),findOrganizationById:async o=>await t.findOne({model:"organization",where:[{field:"id",value:o}]}),findFullOrganization:async({organizationId:o,isSlug:n})=>{let i=await t.findOne({model:"organization",where:[{field:n?"slug":"id",value:o}]});if(!i)return null;let[s,a]=await Promise.all([t.findMany({model:"invitation",where:[{field:"organizationId",value:i.id}]}),t.findMany({model:"member",where:[{field:"organizationId",value:i.id}]})]);if(!i)return null;let d=a.map(h=>h.userId),c=await t.findMany({model:"user",where:[{field:"id",value:d,operator:"in"}]}),l=new Map(c.map(h=>[h.id,h])),m=a.map(h=>{let y=l.get(h.userId);if(!y)throw new F("Unexpected error: User not found for member");return{...h,user:{id:y.id,name:y.name,email:y.email,image:y.image}}});return{...i,invitations:s,members:m}},listOrganizations:async o=>{let n=await t.findMany({model:"member",where:[{field:"userId",value:o}]});if(!n||n.length===0)return[];let i=n.map(a=>a.organizationId);return await t.findMany({model:"organization",where:[{field:"id",value:i,operator:"in"}]})},createInvitation:async({invitation:o,user:n})=>{let s=q(r?.invitationExpiresIn||1728e5);return await t.create({model:"invitation",data:{email:o.email,role:o.role,organizationId:o.organizationId,status:"pending",expiresAt:s,inviterId:n.id}})},findInvitationById:async o=>await t.findOne({model:"invitation",where:[{field:"id",value:o}]}),findPendingInvitation:async o=>(await t.findMany({model:"invitation",where:[{field:"email",value:o.email},{field:"organizationId",value:o.organizationId},{field:"status",value:"pending"}]})).filter(i=>new Date(i.expiresAt)>new Date),updateInvitation:async o=>await t.update({model:"invitation",where:[{field:"id",value:o.invitationId}],update:{status:o.status}})}};import"better-call";var T=Y(async e=>({})),z=Y({use:[x]},async e=>({session:e.context.session}));import{z as P}from"zod";import{z as A}from"zod";var dt=A.string(),no=A.enum(["pending","accepted","rejected","canceled"]).default("pending"),Ic=A.object({id:A.string().default(H),name:A.string(),slug:A.string(),logo:A.string().nullish(),metadata:A.record(A.string()).or(A.string().transform(e=>JSON.parse(e))).nullish(),createdAt:A.date()}),_c=A.object({id:A.string().default(H),organizationId:A.string(),userId:A.string(),role:dt,createdAt:A.date()}),Ec=A.object({id:A.string().default(H),organizationId:A.string(),email:A.string(),role:dt,status:no,inviterId:A.string(),expiresAt:A.date()});import{APIError as R}from"better-call";var p={YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization"};var ct=e=>u("/organization/invite-member",{method:"POST",use:[T,z],body:P.object({email:P.string({description:"The email address of the user to invite"}),role:P.string({description:"The role to assign to the user"}),organizationId:P.string({description:"The organization ID to invite the user to"}).optional(),resend:P.boolean({description:"Resend the invitation email, if the user is already invited"}).optional()}),metadata:{openapi:{description:"Invite a user to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt"]}}}}}}}},async r=>{if(!r.context.orgOptions.sendInvitationEmail)throw r.context.logger.warn("Invitation email is not enabled. Pass `sendInvitationEmail` to the plugin options to enable it."),new R("BAD_REQUEST",{message:"Invitation email is not enabled"});let t=r.context.session,o=r.body.organizationId||t.session.activeOrganizationId;if(!o)throw new R("BAD_REQUEST",{message:p.ORGANIZATION_NOT_FOUND});let n=E(r.context,r.context.orgOptions),i=await n.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!i)throw new R("BAD_REQUEST",{message:p.MEMBER_NOT_FOUND});let s=r.context.roles[i.role];if(!s)throw new R("BAD_REQUEST",{message:p.ROLE_NOT_FOUND});if(s.authorize({invitation:["create"]}).error)throw new R("FORBIDDEN",{message:p.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION});if(await n.findMemberByEmail({email:r.body.email,organizationId:o}))throw new R("BAD_REQUEST",{message:p.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION});if((await n.findPendingInvitation({email:r.body.email,organizationId:o})).length&&!r.body.resend)throw new R("BAD_REQUEST",{message:p.USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION});let l=await n.createInvitation({invitation:{role:r.body.role,email:r.body.email,organizationId:o},user:t.user}),m=await n.findOrganizationById(o);if(!m)throw new R("BAD_REQUEST",{message:p.ORGANIZATION_NOT_FOUND});return await r.context.orgOptions.sendInvitationEmail?.({id:l.id,role:l.role,email:l.email,organization:m,inviter:{...i,user:t.user}},r.request),r.json(l)}),lt=u("/organization/accept-invitation",{method:"POST",body:P.object({invitationId:P.string({description:"The ID of the invitation to accept"})}),use:[T,z],metadata:{openapi:{description:"Accept an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"},member:{type:"object"}}}}}}}}}},async e=>{let r=e.context.session,t=E(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new R("BAD_REQUEST",{message:p.INVITATION_NOT_FOUND});if(o.email!==r.user.email)throw new R("FORBIDDEN",{message:p.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let n=await t.updateInvitation({invitationId:e.body.invitationId,status:"accepted"}),i=await t.createMember({organizationId:o.organizationId,userId:r.user.id,role:o.role,createdAt:new Date});return await t.setActiveOrganization(r.session.token,o.organizationId),n?e.json({invitation:n,member:i}):e.json(null,{status:400,body:{message:p.INVITATION_NOT_FOUND}})}),ut=u("/organization/reject-invitation",{method:"POST",body:P.object({invitationId:P.string({description:"The ID of the invitation to reject"})}),use:[T,z],metadata:{openapi:{description:"Reject an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"},member:{type:"null"}}}}}}}}}},async e=>{let r=e.context.session,t=E(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new R("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==r.user.email)throw new R("FORBIDDEN",{message:p.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let n=await t.updateInvitation({invitationId:e.body.invitationId,status:"rejected"});return e.json({invitation:n,member:null})}),pt=u("/organization/cancel-invitation",{method:"POST",body:P.object({invitationId:P.string({description:"The ID of the invitation to cancel"})}),use:[T,z],openapi:{description:"Cancel an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"}}}}}}}}},async e=>{let r=e.context.session,t=E(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o)throw new R("BAD_REQUEST",{message:p.INVITATION_NOT_FOUND});let n=await t.findMemberByOrgId({userId:r.user.id,organizationId:o.organizationId});if(!n)throw new R("BAD_REQUEST",{message:p.MEMBER_NOT_FOUND});if(e.context.roles[n.role].authorize({invitation:["cancel"]}).error)throw new R("FORBIDDEN",{message:p.YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION});let s=await t.updateInvitation({invitationId:e.body.invitationId,status:"canceled"});return e.json(s)}),mt=u("/organization/get-invitation",{method:"GET",use:[T],requireHeaders:!0,query:P.object({id:P.string({description:"The ID of the invitation to get"})}),metadata:{openapi:{description:"Get an invitation by ID",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"},organizationName:{type:"string"},organizationSlug:{type:"string"},inviterEmail:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt","organizationName","organizationSlug","inviterEmail"]}}}}}}}},async e=>{let r=await v(e);if(!r)throw new R("UNAUTHORIZED",{message:"Not authenticated"});let t=E(e.context,e.context.orgOptions),o=await t.findInvitationById(e.query.id);if(!o||o.status!=="pending"||o.expiresAt<new Date)throw new R("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==r.user.email)throw new R("FORBIDDEN",{message:p.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let n=await t.findOrganizationById(o.organizationId);if(!n)throw new R("BAD_REQUEST",{message:p.ORGANIZATION_NOT_FOUND});let i=await t.findMemberByOrgId({userId:o.inviterId,organizationId:o.organizationId});if(!i)throw new R("BAD_REQUEST",{message:p.INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION});return e.json({...o,organizationName:n.name,organizationSlug:n.slug,inviterEmail:i.user.email})});import{z as M}from"zod";import{APIError as J}from"better-call";var ft=()=>u("/organization/add-member",{method:"POST",body:M.object({userId:M.string(),role:M.string(),organizationId:M.string().optional()}),use:[T],metadata:{SERVER_ONLY:!0}},async e=>{let r=e.body.userId?await v(e).catch(a=>null):null,t=e.body.organizationId||r?.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:p.NO_ACTIVE_ORGANIZATION}});let o=E(e.context,e.context.orgOptions),n=await e.context.internalAdapter.findUserById(e.body.userId);if(!n)throw new J("BAD_REQUEST",{message:f.USER_NOT_FOUND});if(await o.findMemberByEmail({email:n.email,organizationId:t}))throw new J("BAD_REQUEST",{message:p.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION});let s=await o.createMember({id:H(),organizationId:t,userId:n.id,role:e.body.role,createdAt:new Date});return e.json(s)}),gt=u("/organization/remove-member",{method:"POST",body:M.object({memberIdOrEmail:M.string({description:"The ID or email of the member to remove"}),organizationId:M.string({description:"The ID of the organization to remove the member from. If not provided, the active organization will be used"}).optional()}),use:[T,z],metadata:{openapi:{description:"Remove a member from an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{member:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}},required:["member"]}}}}}}}},async e=>{let r=e.context.session,t=e.body.organizationId||r.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:p.NO_ACTIVE_ORGANIZATION}});let o=E(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:r.user.id,organizationId:t});if(!n)throw new J("BAD_REQUEST",{message:p.MEMBER_NOT_FOUND});let i=e.context.roles[n.role];if(!i)throw new J("BAD_REQUEST",{message:p.ROLE_NOT_FOUND});let s=r.user.email===e.body.memberIdOrEmail||n.id===e.body.memberIdOrEmail;if(s&&n.role===(e.context.orgOptions?.creatorRole||"owner"))throw new J("BAD_REQUEST",{message:p.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER});if(!(s||i.authorize({member:["delete"]}).success))throw new J("UNAUTHORIZED",{message:p.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER});let c=null;if(e.body.memberIdOrEmail.includes("@")?c=await o.findMemberByEmail({email:e.body.memberIdOrEmail,organizationId:t}):c=await o.findMemberById(e.body.memberIdOrEmail),c?.organizationId!==t)throw new J("BAD_REQUEST",{message:p.MEMBER_NOT_FOUND});return await o.deleteMember(c.id),r.user.id===c.userId&&r.session.activeOrganizationId===c.organizationId&&await o.setActiveOrganization(r.session.token,null),e.json({member:c})}),ht=e=>u("/organization/update-member-role",{method:"POST",body:M.object({role:M.string(),memberId:M.string(),organizationId:M.string().optional()}),use:[T,z],metadata:{openapi:{description:"Update the role of a member in an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{member:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}},required:["member"]}}}}}}}},async r=>{let t=r.context.session,o=r.body.organizationId||t.session.activeOrganizationId;if(!o)return r.json(null,{status:400,body:{message:p.NO_ACTIVE_ORGANIZATION}});let n=E(r.context,r.context.orgOptions),i=await n.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!i)return r.json(null,{status:400,body:{message:p.MEMBER_NOT_FOUND}});let s=r.context.roles[i.role];if(!s)return r.json(null,{status:400,body:{message:p.ROLE_NOT_FOUND}});if(s.authorize({member:["update"]}).error||r.body.role==="owner"&&i.role!=="owner")return r.json(null,{body:{message:"You are not allowed to update this member"},status:403});let d=await n.updateMember(r.body.memberId,r.body.role);return d?r.json(d):r.json(null,{status:400,body:{message:p.MEMBER_NOT_FOUND}})}),yt=u("/organization/get-active-member",{method:"GET",use:[T,z],metadata:{openapi:{description:"Get the active member in the organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}}}}}}}},async e=>{let r=e.context.session,t=r.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:p.NO_ACTIVE_ORGANIZATION}});let n=await E(e.context,e.context.orgOptions).findMemberByOrgId({userId:r.user.id,organizationId:t});return n?e.json(n):e.json(null,{status:400,body:{message:p.MEMBER_NOT_FOUND}})});import{z as w}from"zod";import{APIError as Q}from"better-call";var wt=u("/organization/create",{method:"POST",body:w.object({name:w.string({description:"The name of the organization"}),slug:w.string({description:"The slug of the organization"}),userId:w.string({description:"The user id of the organization creator. If not provided, the current user will be used. Should only be used by admins or when called by the server."}).optional(),logo:w.string({description:"The logo of the organization"}).optional(),metadata:w.record(w.string(),w.any(),{description:"The metadata of the organization"}).optional()}),use:[T],metadata:{openapi:{description:"Create an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization that was created",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let r=await v(e);if(!r&&(e.request||e.headers))throw new Q("UNAUTHORIZED");let t=r?.user||null;if(!t){if(!e.body.userId)throw new Q("UNAUTHORIZED");t=await e.context.internalAdapter.findUserById(e.body.userId)}if(!t)return e.json(null,{status:401});let o=e.context.orgOptions;if(!(typeof o?.allowUserToCreateOrganization=="function"?await o.allowUserToCreateOrganization(t):o?.allowUserToCreateOrganization===void 0?!0:o.allowUserToCreateOrganization))throw new Q("FORBIDDEN",{message:p.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION});let i=E(e.context,o),s=await i.listOrganizations(t.id);if(typeof o.organizationLimit=="number"?s.length>=o.organizationLimit:typeof o.organizationLimit=="function"?await o.organizationLimit(t):!1)throw new Q("FORBIDDEN",{message:p.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS});if(await i.findOrganizationBySlug(e.body.slug))throw new Q("BAD_REQUEST",{message:p.ORGANIZATION_ALREADY_EXISTS});let c=await i.createOrganization({organization:{id:H(),slug:e.body.slug,name:e.body.name,logo:e.body.logo,createdAt:new Date,metadata:e.body.metadata},user:t});return e.context.session&&await i.setActiveOrganization(e.context.session.session.token,c.id),e.json(c)}),bt=u("/organization/update",{method:"POST",body:w.object({data:w.object({name:w.string({description:"The name of the organization"}).optional(),slug:w.string({description:"The slug of the organization"}).optional(),logo:w.string({description:"The logo of the organization"}).optional(),metadata:w.record(w.string(),w.any(),{description:"The metadata of the organization"}).optional()}).partial(),organizationId:w.string().optional()}),requireHeaders:!0,use:[T],metadata:{openapi:{description:"Update an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The updated organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let r=await e.context.getSession(e);if(!r)throw new Q("UNAUTHORIZED",{message:"User not found"});let t=e.body.organizationId||r.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:p.ORGANIZATION_NOT_FOUND}});let o=E(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:r.user.id,organizationId:t});if(!n)return e.json(null,{status:400,body:{message:p.USER_IS_NOT_A_MEMBER_OF_THE_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:p.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION},status:403});let a=await o.updateOrganization(t,e.body.data);return e.json(a)}),Ot=u("/organization/delete",{method:"POST",body:w.object({organizationId:w.string({description:"The organization id to delete"})}),requireHeaders:!0,use:[T],metadata:{openapi:{description:"Delete an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string",description:"The organization id that was deleted"}}}}}}}},async e=>{let r=await e.context.getSession(e);if(!r)return e.json(null,{status:401});let t=e.body.organizationId;if(!t)return e.json(null,{status:400,body:{message:p.ORGANIZATION_NOT_FOUND}});let o=E(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:r.user.id,organizationId:t});if(!n)return e.json(null,{status:400,body:{message:p.USER_IS_NOT_A_MEMBER_OF_THE_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 Q("FORBIDDEN",{message:p.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION});return t===r.session.activeOrganizationId&&await o.setActiveOrganization(r.session.token,null),await o.deleteOrganization(t),e.json(t)}),At=u("/organization/get-full-organization",{method:"GET",query:w.optional(w.object({organizationId:w.string({description:"The organization id to get"}).optional(),organizationSlug:w.string({description:"The organization slug to get"}).optional()})),requireHeaders:!0,use:[T,z],metadata:{openapi:{description:"Get the full organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let r=e.context.session,t=e.query?.organizationSlug||e.query?.organizationId||r.session.activeOrganizationId;if(!t)return e.json(null,{status:200});let n=await E(e.context,e.context.orgOptions).findFullOrganization({organizationId:t,isSlug:!!e.query?.organizationSlug});if(!n)throw new Q("BAD_REQUEST",{message:p.ORGANIZATION_NOT_FOUND});return e.json(n)}),It=u("/organization/set-active",{method:"POST",body:w.object({organizationId:w.string({description:"The organization id to set as active. It can be null to unset the active organization"}).nullable().optional(),organizationSlug:w.string({description:"The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided"}).optional()}),use:[z,T],metadata:{openapi:{description:"Set the active organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let r=E(e.context,e.context.orgOptions),t=e.context.session,o=e.body.organizationSlug||e.body.organizationId;if(o===null){if(!t.session.activeOrganizationId)return e.json(null);let d=await r.setActiveOrganization(t.session.token,null);return await S(e,{session:d,user:t.user}),e.json(null)}if(!o){let a=t.session.activeOrganizationId;if(!a)return e.json(null);o=a}let n=await r.findFullOrganization({organizationId:o,isSlug:!!e.body.organizationSlug});if(!n?.members.find(a=>a.userId===t.user.id))throw await r.setActiveOrganization(t.session.token,null),new Q("FORBIDDEN",{message:p.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION});let s=await r.setActiveOrganization(t.session.token,o);return await S(e,{session:s,user:t.user}),e.json(n)}),_t=u("/organization/list",{method:"GET",use:[T,z],metadata:{openapi:{description:"List all organizations",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Organization"}}}}}}}}},async e=>{let t=await E(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(t)});var io=me({name:["action"]}),fl=io.newRole({name:["action"]}),gl=e=>{let r={createOrganization:wt,updateOrganization:bt,deleteOrganization:Ot,setActiveOrganization:It,getFullOrganization:At,listOrganizations:_t,createInvitation:ct(e),cancelInvitation:pt,acceptInvitation:lt,getInvitation:mt,rejectInvitation:ut,addMember:ft(),removeMember:gt,updateMemberRole:ht(e),getActiveMember:yt},t={...it,...e?.roles};return{id:"organization",endpoints:{...nt(r,{orgOptions:e||{},roles:t,getSession:async n=>await v(n)}),hasPermission:u("/organization/has-permission",{method:"POST",requireHeaders:!0,body:ie.object({permission:ie.record(ie.string(),ie.array(ie.string()))}),use:[z],metadata:{openapi:{description:"Check if the user has permission",requestBody:{content:{"application/json":{schema:{type:"object",properties:{permission:{type:"object",description:"The permission to check"}},required:["permission"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},success:{type:"boolean"}},required:["success"]}}}}}}}},async n=>{if(!n.context.session.session.activeOrganizationId)throw new Et("BAD_REQUEST",{message:p.NO_ACTIVE_ORGANIZATION});let s=await E(n.context).findMemberByOrgId({userId:n.context.session.user.id,organizationId:n.context.session.session.activeOrganizationId||""});if(!s)throw new Et("UNAUTHORIZED",{message:p.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION});let d=t[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:{modelName:e?.schema?.organization?.modelName,fields:{name:{type:"string",required:!0,fieldName:e?.schema?.organization?.fields?.name},slug:{type:"string",unique:!0,fieldName:e?.schema?.organization?.fields?.slug},logo:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.logo},createdAt:{type:"date",required:!0,fieldName:e?.schema?.organization?.fields?.createdAt},metadata:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.metadata}}},member:{modelName:e?.schema?.member?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.member?.fields?.organizationId},userId:{type:"string",required:!0,fieldName:e?.schema?.member?.fields?.userId,references:{model:"user",field:"id"}},role:{type:"string",required:!0,defaultValue:"member",fieldName:e?.schema?.member?.fields?.role},createdAt:{type:"date",required:!0,fieldName:e?.schema?.member?.fields?.createdAt}}},invitation:{modelName:e?.schema?.invitation?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.invitation?.fields?.organizationId},email:{type:"string",required:!0,fieldName:e?.schema?.invitation?.fields?.email},role:{type:"string",required:!1,fieldName:e?.schema?.invitation?.fields?.role},status:{type:"string",required:!0,defaultValue:"pending",fieldName:e?.schema?.invitation?.fields?.status},expiresAt:{type:"date",required:!0,fieldName:e?.schema?.invitation?.fields?.expiresAt},inviterId:{type:"string",references:{model:"user",field:"id"},fieldName:e?.schema?.invitation?.fields?.inviterId,required:!0}}}},$Infer:{Organization:{},Invitation:{},Member:{},ActiveOrganization:{}},$ERROR_CODES:p}};export{gl as organization};
|
|
83
|
+
Error: `,d),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user,s=!i;if(n){let d=n.accounts.find(c=>c.providerId===t.providerId);if(d){let c=Object.fromEntries(Object.entries({accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt}).filter(([l,m])=>m!==void 0));Object.keys(c).length>0&&await e.context.internalAdapter.updateAccount(d.id,c)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.providerId)&&!r.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return ye&&j.warn(`User already exist but account isn't linked to ${t.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:t.providerId,accountId:r.id.toString(),userId:n.user.id,accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt,scope:t.scope})}catch(m){return j.error("Unable to link account",m),{error:"unable to link account",data:null}}i=await e.context.internalAdapter.updateUser(n.user.id,{...r,updatedAt:new Date})}}else if(i=await e.context.internalAdapter.createOAuthUser({...r,email:r.email.toLowerCase(),id:void 0},{accessToken:t.accessToken,idToken:t.idToken,refreshToken:t.refreshToken,accessTokenExpiresAt:t.accessTokenExpiresAt,refreshTokenExpiresAt:t.refreshTokenExpiresAt,scope:t.scope,providerId:t.providerId,accountId:r.id.toString()}).then(d=>d?.user),!r.emailVerified&&i&&e.context.options.emailVerification?.sendOnSignUp){let d=await W(e.context.secret,i.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:c,token:d},e.request)}if(!i)return{error:"unable to create user",data:null,isRegister:!1};let a=await e.context.internalAdapter.createSession(i.id,e.request);return a?{data:{session:a,user:i},error:null,isRegister:s}:{error:"unable to create session",data:null,isRegister:!1}}var Ur=u("/sign-in/social",{method:"POST",query:_.object({currentURL:_.string().optional()}).optional(),body:_.object({callbackURL:_.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:_.string().optional(),errorCallbackURL:_.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:_.enum(le,{description:"OAuth2 provider to use"}),disableRedirect:_.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:_.optional(_.object({token:_.string({description:"ID token from the provider"}),nonce:_.string({description:"Nonce used to generate the token"}).optional(),accessToken:_.string({description:"Access token from the provider"}).optional(),refreshToken:_.string({description:"Refresh token from the provider"}).optional(),expiresAt:_.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let r=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!r)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new k("NOT_FOUND",{message:f.PROVIDER_NOT_FOUND});if(e.body.idToken){if(!r.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new k("NOT_FOUND",{message:f.ID_TOKEN_NOT_SUPPORTED});let{token:i,nonce:s}=e.body.idToken;if(!await r.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new k("UNAUTHORIZED",{message:f.INVALID_TOKEN});let d=await r.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 k("UNAUTHORIZED",{message:f.FAILED_TO_GET_USER_INFO});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new k("UNAUTHORIZED",{message:f.USER_EMAIL_NOT_FOUND});let c=await ue(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:r.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new k("UNAUTHORIZED",{message:c.error});return await S(e,c.data),e.json({session:c.data.session,user:c.data.user,url:void 0,redirect:!1})}let{codeVerifier:t,state:o}=await ce(e),n=await r.createAuthorizationURL({state:o,codeVerifier:t,redirectURI:`${e.context.baseURL}/callback/${r.id}`});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),Sr=u("/sign-in/email",{method:"POST",body:_.object({email:_.string({description:"Email of the user"}),password:_.string({description:"Password of the user"}),callbackURL:_.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:_.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new k("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:r,password:t}=e.body;if(!_.string().email().safeParse(r).success)throw new k("BAD_REQUEST",{message:f.INVALID_EMAIL});let n=await e.context.internalAdapter.findUserByEmail(r,{includeAccounts:!0});if(!n)throw await e.context.password.hash(t),e.context.logger.error("User not found",{email:r}),new k("UNAUTHORIZED",{message:f.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:r}),new k("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:r}),new k("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:s,password:t}))throw e.context.logger.error("Invalid password"),new k("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new k("UNAUTHORIZED",{message:f.EMAIL_NOT_VERIFIED});let c=await W(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:r}),new k("FORBIDDEN",{message:f.EMAIL_NOT_VERIFIED})}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 k("UNAUTHORIZED",{message:f.FAILED_TO_CREATE_SESSION});return await S(e,{session:d,user:n.user},e.body.rememberMe===!1),e.json({user:{id:n.user.id,email:n.user.email,name:n.user.name,image:n.user.image,emailVerified:n.user.emailVerified,createdAt:n.user.createdAt,updatedAt:n.user.updatedAt},redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as oe}from"zod";var pe=oe.object({code:oe.string().optional(),error:oe.string().optional(),error_description:oe.string().optional(),state:oe.string().optional()}),vr=u("/callback/:id",{method:["GET","POST"],body:pe.optional(),query:pe.optional(),metadata:X},async e=>{let r;try{if(e.method==="GET")r=pe.parse(e.query);else if(e.method==="POST")r=pe.parse(e.body);else throw new Error("Unsupported method")}catch(D){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",D),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:t,error:o,state:n,error_description:i}=r;if(!n)throw e.context.logger.error("State not found",o),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!t)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}&error_description=${i}`);let s=e.context.socialProviders.find(D=>D.id===e.params.id);if(!s)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:a,callbackURL:d,link:c,errorURL:l,newUserURL:m}=await Ne(e),h;try{h=await s.validateAuthorizationCode({code:t,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${s.id}`})}catch(D){throw e.context.logger.error("",D),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let y=await s.getUserInfo(h).then(D=>D?.user);function I(D){let V=l||d||`${e.context.baseURL}/error`;throw V.includes("?")?V=`${V}&error=${D}`:V=`${V}?error=${D}`,e.redirect(V)}if(!y)return e.context.logger.error("Unable to get user info"),I("unable_to_get_user_info");if(!y.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),I("email_not_found");if(!d)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(c){if(c.email!==y.email.toLowerCase())return I("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:c.userId,providerId:s.id,accountId:y.id}))return I("unable_to_link_account");let V;try{V=d.toString()}catch{V=d}throw e.redirect(V)}let N=await ue(e,{userInfo:{...y,email:y.email,name:y.name||y.email},account:{providerId:s.id,accountId:y.id,...h,scope:h.scopes?.join(",")},callbackURL:d});if(N.error)return e.context.logger.error(N.error.split(" ").join("_")),I(N.error.split(" ").join("_"));let{session:_e,user:fe}=N.data;await S(e,{session:_e,user:fe});let ge;try{ge=(N.isRegister&&m||d).toString()}catch{ge=N.isRegister&&m||d}throw e.redirect(ge)});import"zod";import{APIError as Vr}from"better-call";var kr=u("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let r=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!r)throw $(e),new Vr("BAD_REQUEST",{message:f.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(r),$(e),e.json({success:!0})});import{z as C}from"zod";import{APIError as ne}from"better-call";function Je(e,r,t){let o=r?new URL(r,e.baseURL):new URL(`${e.baseURL}/error`);return t&&Object.entries(t).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function Fr(e,r,t){let o=new URL(r,e.baseURL);return t&&Object.entries(t).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var zr=u("/forget-password",{method:"POST",body:C.object({email:C.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:C.string({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new ne("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:r,redirectTo:t}=e.body,o=await e.context.internalAdapter.findUserByEmail(r,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:r}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=q(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=H(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:i});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${t}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:a,token:s},e.request),e.json({status:!0})}),Nr=u("/reset-password/:token",{method:"GET",query:C.object({callbackURL:C.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:r}=e.params,{callbackURL:t}=e.query;if(!r||!t)throw e.redirect(Je(e.context,t,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${r}`);throw!o||o.expiresAt<new Date?e.redirect(Je(e.context,t,{error:"INVALID_TOKEN"})):e.redirect(Fr(e.context,t,{token:r}))}),Lr=u("/reset-password",{query:C.optional(C.object({token:C.string().optional(),currentURL:C.string().optional()})),method:"POST",body:C.object({newPassword:C.string({description:"The new password to set"}),token:C.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let r=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!r)throw new ne("BAD_REQUEST",{message:f.INVALID_TOKEN});let{newPassword:t}=e.body,o=e.context.password?.config.minPasswordLength,n=e.context.password?.config.maxPasswordLength;if(t.length<o)throw new ne("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});if(t.length>n)throw new ne("BAD_REQUEST",{message:f.PASSWORD_TOO_LONG});let i=`reset-password:${r}`,s=await e.context.internalAdapter.findVerificationValue(i);if(!s||s.expiresAt<new Date)throw new ne("BAD_REQUEST",{message:f.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(s.id);let a=s.value,d=await e.context.password.hash(t);return(await e.context.internalAdapter.findAccounts(a)).find(m=>m.providerId==="credential")?(await e.context.internalAdapter.updatePassword(a,d),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:a,providerId:"credential",password:d,accountId:a}),e.json({status:!0}))});import{z as L}from"zod";import{APIError as U}from"better-call";import{xchacha20poly1305 as sd}from"@noble/ciphers/chacha";import{bytesToHex as dd,hexToBytes as cd,utf8ToBytes as ld}from"@noble/ciphers/utils";import{managedNonce as pd}from"@noble/ciphers/webcrypto";import{sha256 as fd}from"oslo/crypto";import hd from"uncrypto";import{decodeHex as Qa,encodeHex as Ya}from"oslo/encoding";import{scryptAsync as Xa}from"@noble/hashes/scrypt";import{getRandomValues as td}from"uncrypto";import Xe from"uncrypto";function qr(e){return e.toString(2).padStart(8,"0")}function $r(e){return[...e].map(r=>qr(r)).join("")}function et(e){return parseInt($r(e),2)}function Hr(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let r=(e-1).toString(2).length,t=r%8,o=new Uint8Array(Math.ceil(r/8));Xe.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1);let n=et(o);for(;n>=e;)Xe.getRandomValues(o),t!==0&&(o[0]&=(1<<t)-1),n=et(o);return n}function tt(e,r){let t="";for(let o=0;o<e;o++)t+=r[Hr(r.length)];return t}function rt(...e){let r=new Set(e),t="";for(let o of r)o==="a-z"?t+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?t+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?t+="0123456789":t+=o;return t}var Pr=u("/change-password",{method:"POST",body:L.object({newPassword:L.string({description:"The new password to set"}),currentPassword:L.string({description:"The current password"}),revokeOtherSessions:L.boolean({description:"Revoke all other sessions"}).optional()}),use:[x],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:r,currentPassword:t,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(r.length<i)throw e.context.logger.error("Password is too short"),new U("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});let s=e.context.password.config.maxPasswordLength;if(r.length>s)throw e.context.logger.error("Password is too long"),new U("BAD_REQUEST",{message:f.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 U("BAD_REQUEST",{message:f.CREDENTIAL_ACCOUNT_NOT_FOUND});let c=await e.context.password.hash(r);if(!await e.context.password.verify({hash:d.password,password:t}))throw new U("BAD_REQUEST",{message:f.INVALID_PASSWORD});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let m=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!m)throw new U("INTERNAL_SERVER_ERROR",{message:f.FAILED_TO_GET_SESSION});await S(e,{session:m,user:n.user})}return e.json(n.user)}),Dr=u("/set-password",{method:"POST",body:L.object({newPassword:L.string()}),metadata:{SERVER_ONLY:!0},use:[x]},async e=>{let{newPassword:r}=e.body,t=e.context.session,o=e.context.password.config.minPasswordLength;if(r.length<o)throw e.context.logger.error("Password is too short"),new U("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});let n=e.context.password.config.maxPasswordLength;if(r.length>n)throw e.context.logger.error("Password is too long"),new U("BAD_REQUEST",{message:f.PASSWORD_TOO_LONG});let s=(await e.context.internalAdapter.findAccounts(t.user.id)).find(d=>d.providerId==="credential"&&d.password),a=await e.context.password.hash(r);if(!s)return await e.context.internalAdapter.linkAccount({userId:t.user.id,providerId:"credential",accountId:t.user.id,password:a}),e.json(t.user);throw new U("BAD_REQUEST",{message:"user already has a password"})}),xr=u("/delete-user",{method:"POST",use:[Ye],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options",{session:e.context.session}),new U("NOT_FOUND");let r=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=tt(32,rt("a-z","A-Z","0-9"));await e.context.internalAdapter.createVerificationValue({value:r.user.id,identifier:`delete-account-${n}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let i=`${e.context.baseURL}/delete-user/callback?token=${n}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:r.user,url:i,token:n},e.request),e.json({success:!0,message:"Verification email sent"})}let t=e.context.options.user.deleteUser?.beforeDelete;t&&await t(r.user,e.request),await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),await e.context.internalAdapter.deleteAccounts(r.user.id),$(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(r.user,e.request),e.json({success:!0,message:"User deleted"})}),Cr=u("/delete-user/callback",{method:"GET",query:L.object({token:L.string()})},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new U("NOT_FOUND");let r=await v(e);if(!r)throw new U("NOT_FOUND",{message:f.FAILED_TO_GET_USER_INFO});let t=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!t||t.expiresAt<new Date)throw t&&await e.context.internalAdapter.deleteVerificationValue(t.id),new U("NOT_FOUND",{message:f.INVALID_TOKEN});if(t.value!==r.user.id)throw new U("NOT_FOUND",{message:f.INVALID_TOKEN});let o=e.context.options.user.deleteUser?.beforeDelete;o&&await o(r.user,e.request),await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),await e.context.internalAdapter.deleteAccounts(r.user.id),await e.context.internalAdapter.deleteVerificationValue(t.id),$(e);let n=e.context.options.user.deleteUser?.afterDelete;return n&&await n(r.user,e.request),e.json({success:!0,message:"User deleted"})}),jr=u("/change-email",{method:"POST",query:L.object({currentURL:L.string().optional()}).optional(),body:L.object({newEmail:L.string({description:"The new email to set"}).email(),callbackURL:L.string({description:"The URL to redirect to after email verification"}).optional()}),use:[x],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new U("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 U("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 U("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 U("BAD_REQUEST",{message:"Verification email isn't enabled"});let t=await W(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:t},e.request),e.json({user:null,status:!0})});import{z as ie}from"zod";import{APIError as ot}from"better-call";var Br=u("/list-accounts",{method:"GET",use:[x],metadata:{openapi:{description:"List all accounts linked to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},provider:{type:"string"}}}}}}}}}}},async e=>{let r=e.context.session,t=await e.context.internalAdapter.findAccounts(r.user.id);return e.json(t.map(o=>({id:o.id,provider:o.providerId})))}),Mr=u("/link-social",{method:"POST",requireHeaders:!0,query:ie.object({currentURL:ie.string().optional()}).optional(),body:ie.object({callbackURL:ie.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:ie.enum(le,{description:"The OAuth2 provider to use"})}),use:[x],metadata:{openapi:{description:"Link a social account to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}},required:["url","redirect"]}}}}}}}},async e=>{let r=e.context.session;if((await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId===e.body.provider))throw new ot("BAD_REQUEST",{message:f.SOCIAL_ACCOUNT_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 ot("NOT_FOUND",{message:f.PROVIDER_NOT_FOUND});let i=await ce(e,{userId:r.user.id,email:r.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 nt=(e,r)=>{let t={};for(let[o,n]of Object.entries(e))t[o]=i=>n({...i,context:{...r,...i.context}}),t[o].path=n.path,t[o].method=n.method,t[o].options=n.options,t[o].headers=n.headers;return t};function me(e){let r=e;return{newRole(t){return Gr(t)}}}function Gr(e){return{statements:e,authorize(r,t){for(let[o,n]of Object.entries(r)){let i=e[o];return i?(t==="OR"?n.some(a=>i.includes(a)):n.every(a=>i.includes(a)))?{success:!0}:{success:!1,error:`Unauthorized to access resource "${o}"`}:{success:!1,error:`You are not allowed to access resource: ${o}`}}return{success:!1,error:"Not authorized"}}}}var Zr={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},Ie=me(Zr),Wr=Ie.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),Qr=Ie.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),Yr=Ie.newRole({organization:[],member:[],invitation:[]}),it={admin:Wr,owner:Qr,member:Yr};var Kr={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},Jr=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,st={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},Xr=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function eo(e){return e instanceof Date&&!isNaN(e.getTime())}function to(e){let r=Xr.exec(e);if(!r)return null;let[,t,o,n,i,s,a,d,c,l,m]=r,h=new Date(Date.UTC(parseInt(t,10),parseInt(o,10)-1,parseInt(n,10),parseInt(i,10),parseInt(s,10),parseInt(a,10),d?parseInt(d.padEnd(3,"0"),10):0));if(c){let y=(parseInt(l,10)*60+parseInt(m,10))*(c==="+"?-1:1);h.setUTCMinutes(h.getUTCMinutes()+y)}return eo(h)?h:null}function ro(e,r={}){let{strict:t=!1,warnings:o=!1,reviver:n,parseDates:i=!0}=r;if(typeof e!="string")return e;let s=e.trim();if(s[0]==='"'&&s.endsWith('"')&&!s.slice(1,-1).includes('"'))return s.slice(1,-1);let a=s.toLowerCase();if(a.length<=9&&a in st)return st[a];if(!Jr.test(s)){if(t)throw new SyntaxError("[better-json] Invalid JSON");return e}if(Object.entries(Kr).some(([c,l])=>{let m=l.test(s);return m&&o&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${c} pattern`),m})&&t)throw new Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(s,(l,m)=>{if(l==="__proto__"||l==="constructor"&&m&&typeof m=="object"&&"prototype"in m){o&&console.warn(`[better-json] Dropping "${l}" key to prevent prototype pollution`);return}if(i&&typeof m=="string"){let h=to(m);if(h)return h}return n?n(l,m):m})}catch(c){if(t)throw c;return e}}function oo(e,r={strict:!0}){return ro(e,r)}var at=oo;var E=(e,r)=>{let t=e.adapter;return{findOrganizationBySlug:async o=>await t.findOne({model:"organization",where:[{field:"slug",value:o}]}),createOrganization:async o=>{let n=await t.create({model:"organization",data:{...o.organization,metadata:o.organization.metadata?JSON.stringify(o.organization.metadata):void 0}}),i=await t.create({model:"member",data:{organizationId:n.id,userId:o.user.id,createdAt:new Date,role:r?.creatorRole||"owner"}});return{...n,metadata:n.metadata?JSON.parse(n.metadata):void 0,members:[{...i,user:{id:o.user.id,name:o.user.name,email:o.user.email,image:o.user.image}}]}},findMemberByEmail:async o=>{let n=await t.findOne({model:"user",where:[{field:"email",value:o.email}]});if(!n)return null;let i=await t.findOne({model:"member",where:[{field:"organizationId",value:o.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 o=>{let[n,i]=await Promise.all([await t.findOne({model:"member",where:[{field:"userId",value:o.userId},{field:"organizationId",value:o.organizationId}]}),await t.findOne({model:"user",where:[{field:"id",value:o.userId}]})]);return!i||!n?null:{...n,user:{id:i.id,name:i.name,email:i.email,image:i.image}}},findMemberById:async o=>{let n=await t.findOne({model:"member",where:[{field:"id",value:o}]});if(!n)return null;let i=await t.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 o=>await t.create({model:"member",data:o}),updateMember:async(o,n)=>await t.update({model:"member",where:[{field:"id",value:o}],update:{role:n}}),deleteMember:async o=>await t.delete({model:"member",where:[{field:"id",value:o}]}),updateOrganization:async(o,n)=>{let i=await t.update({model:"organization",where:[{field:"id",value:o}],update:{...n,metadata:typeof n.metadata=="object"?JSON.stringify(n.metadata):n.metadata}});return i?{...i,metadata:i.metadata?at(i.metadata):void 0}:null},deleteOrganization:async o=>(await t.delete({model:"member",where:[{field:"organizationId",value:o}]}),await t.delete({model:"invitation",where:[{field:"organizationId",value:o}]}),await t.delete({model:"organization",where:[{field:"id",value:o}]}),o),setActiveOrganization:async(o,n)=>await e.internalAdapter.updateSession(o,{activeOrganizationId:n}),findOrganizationById:async o=>await t.findOne({model:"organization",where:[{field:"id",value:o}]}),findFullOrganization:async({organizationId:o,isSlug:n})=>{let i=await t.findOne({model:"organization",where:[{field:n?"slug":"id",value:o}]});if(!i)return null;let[s,a]=await Promise.all([t.findMany({model:"invitation",where:[{field:"organizationId",value:i.id}]}),t.findMany({model:"member",where:[{field:"organizationId",value:i.id}]})]);if(!i)return null;let d=a.map(h=>h.userId),c=await t.findMany({model:"user",where:[{field:"id",value:d,operator:"in"}]}),l=new Map(c.map(h=>[h.id,h])),m=a.map(h=>{let y=l.get(h.userId);if(!y)throw new F("Unexpected error: User not found for member");return{...h,user:{id:y.id,name:y.name,email:y.email,image:y.image}}});return{...i,invitations:s,members:m}},listOrganizations:async o=>{let n=await t.findMany({model:"member",where:[{field:"userId",value:o}]});if(!n||n.length===0)return[];let i=n.map(a=>a.organizationId);return await t.findMany({model:"organization",where:[{field:"id",value:i,operator:"in"}]})},createInvitation:async({invitation:o,user:n})=>{let s=q(r?.invitationExpiresIn||1728e5);return await t.create({model:"invitation",data:{email:o.email,role:o.role,organizationId:o.organizationId,status:"pending",expiresAt:s,inviterId:n.id}})},findInvitationById:async o=>await t.findOne({model:"invitation",where:[{field:"id",value:o}]}),findPendingInvitation:async o=>(await t.findMany({model:"invitation",where:[{field:"email",value:o.email},{field:"organizationId",value:o.organizationId},{field:"status",value:"pending"}]})).filter(i=>new Date(i.expiresAt)>new Date),updateInvitation:async o=>await t.update({model:"invitation",where:[{field:"id",value:o.invitationId}],update:{status:o.status}})}};import"better-call";var T=Y(async e=>({})),z=Y({use:[x]},async e=>({session:e.context.session}));import{z as P}from"zod";import{z as A}from"zod";var dt=A.string(),no=A.enum(["pending","accepted","rejected","canceled"]).default("pending"),Ic=A.object({id:A.string().default(H),name:A.string(),slug:A.string(),logo:A.string().nullish(),metadata:A.record(A.string()).or(A.string().transform(e=>JSON.parse(e))).nullish(),createdAt:A.date()}),_c=A.object({id:A.string().default(H),organizationId:A.string(),userId:A.string(),role:dt,createdAt:A.date()}),Ec=A.object({id:A.string().default(H),organizationId:A.string(),email:A.string(),role:dt,status:no,inviterId:A.string(),expiresAt:A.date()});import{APIError as R}from"better-call";var p={YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization"};var ct=e=>u("/organization/invite-member",{method:"POST",use:[T,z],body:P.object({email:P.string({description:"The email address of the user to invite"}),role:P.string({description:"The role to assign to the user"}),organizationId:P.string({description:"The organization ID to invite the user to"}).optional(),resend:P.boolean({description:"Resend the invitation email, if the user is already invited"}).optional()}),metadata:{openapi:{description:"Invite a user to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt"]}}}}}}}},async r=>{if(!r.context.orgOptions.sendInvitationEmail)throw r.context.logger.warn("Invitation email is not enabled. Pass `sendInvitationEmail` to the plugin options to enable it."),new R("BAD_REQUEST",{message:"Invitation email is not enabled"});let t=r.context.session,o=r.body.organizationId||t.session.activeOrganizationId;if(!o)throw new R("BAD_REQUEST",{message:p.ORGANIZATION_NOT_FOUND});let n=E(r.context,r.context.orgOptions),i=await n.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!i)throw new R("BAD_REQUEST",{message:p.MEMBER_NOT_FOUND});let s=r.context.roles[i.role];if(!s)throw new R("BAD_REQUEST",{message:p.ROLE_NOT_FOUND});if(s.authorize({invitation:["create"]}).error)throw new R("FORBIDDEN",{message:p.YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION});if(await n.findMemberByEmail({email:r.body.email,organizationId:o}))throw new R("BAD_REQUEST",{message:p.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION});if((await n.findPendingInvitation({email:r.body.email,organizationId:o})).length&&!r.body.resend)throw new R("BAD_REQUEST",{message:p.USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION});let l=await n.createInvitation({invitation:{role:r.body.role,email:r.body.email,organizationId:o},user:t.user}),m=await n.findOrganizationById(o);if(!m)throw new R("BAD_REQUEST",{message:p.ORGANIZATION_NOT_FOUND});return await r.context.orgOptions.sendInvitationEmail?.({id:l.id,role:l.role,email:l.email,organization:m,inviter:{...i,user:t.user}},r.request),r.json(l)}),lt=u("/organization/accept-invitation",{method:"POST",body:P.object({invitationId:P.string({description:"The ID of the invitation to accept"})}),use:[T,z],metadata:{openapi:{description:"Accept an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"},member:{type:"object"}}}}}}}}}},async e=>{let r=e.context.session,t=E(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new R("BAD_REQUEST",{message:p.INVITATION_NOT_FOUND});if(o.email!==r.user.email)throw new R("FORBIDDEN",{message:p.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let n=await t.updateInvitation({invitationId:e.body.invitationId,status:"accepted"}),i=await t.createMember({organizationId:o.organizationId,userId:r.user.id,role:o.role,createdAt:new Date});return await t.setActiveOrganization(r.session.token,o.organizationId),n?e.json({invitation:n,member:i}):e.json(null,{status:400,body:{message:p.INVITATION_NOT_FOUND}})}),ut=u("/organization/reject-invitation",{method:"POST",body:P.object({invitationId:P.string({description:"The ID of the invitation to reject"})}),use:[T,z],metadata:{openapi:{description:"Reject an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"},member:{type:"null"}}}}}}}}}},async e=>{let r=e.context.session,t=E(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o||o.expiresAt<new Date||o.status!=="pending")throw new R("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==r.user.email)throw new R("FORBIDDEN",{message:p.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let n=await t.updateInvitation({invitationId:e.body.invitationId,status:"rejected"});return e.json({invitation:n,member:null})}),pt=u("/organization/cancel-invitation",{method:"POST",body:P.object({invitationId:P.string({description:"The ID of the invitation to cancel"})}),use:[T,z],openapi:{description:"Cancel an invitation to an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{invitation:{type:"object"}}}}}}}}},async e=>{let r=e.context.session,t=E(e.context,e.context.orgOptions),o=await t.findInvitationById(e.body.invitationId);if(!o)throw new R("BAD_REQUEST",{message:p.INVITATION_NOT_FOUND});let n=await t.findMemberByOrgId({userId:r.user.id,organizationId:o.organizationId});if(!n)throw new R("BAD_REQUEST",{message:p.MEMBER_NOT_FOUND});if(e.context.roles[n.role].authorize({invitation:["cancel"]}).error)throw new R("FORBIDDEN",{message:p.YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION});let s=await t.updateInvitation({invitationId:e.body.invitationId,status:"canceled"});return e.json(s)}),mt=u("/organization/get-invitation",{method:"GET",use:[T],requireHeaders:!0,query:P.object({id:P.string({description:"The ID of the invitation to get"})}),metadata:{openapi:{description:"Get an invitation by ID",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},email:{type:"string"},role:{type:"string"},organizationId:{type:"string"},inviterId:{type:"string"},status:{type:"string"},expiresAt:{type:"string"},organizationName:{type:"string"},organizationSlug:{type:"string"},inviterEmail:{type:"string"}},required:["id","email","role","organizationId","inviterId","status","expiresAt","organizationName","organizationSlug","inviterEmail"]}}}}}}}},async e=>{let r=await v(e);if(!r)throw new R("UNAUTHORIZED",{message:"Not authenticated"});let t=E(e.context,e.context.orgOptions),o=await t.findInvitationById(e.query.id);if(!o||o.status!=="pending"||o.expiresAt<new Date)throw new R("BAD_REQUEST",{message:"Invitation not found!"});if(o.email!==r.user.email)throw new R("FORBIDDEN",{message:p.YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION});let n=await t.findOrganizationById(o.organizationId);if(!n)throw new R("BAD_REQUEST",{message:p.ORGANIZATION_NOT_FOUND});let i=await t.findMemberByOrgId({userId:o.inviterId,organizationId:o.organizationId});if(!i)throw new R("BAD_REQUEST",{message:p.INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION});return e.json({...o,organizationName:n.name,organizationSlug:n.slug,inviterEmail:i.user.email})});import{z as M}from"zod";import{APIError as J}from"better-call";var ft=()=>u("/organization/add-member",{method:"POST",body:M.object({userId:M.string(),role:M.string(),organizationId:M.string().optional()}),use:[T],metadata:{SERVER_ONLY:!0}},async e=>{let r=e.body.userId?await v(e).catch(a=>null):null,t=e.body.organizationId||r?.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:p.NO_ACTIVE_ORGANIZATION}});let o=E(e.context,e.context.orgOptions),n=await e.context.internalAdapter.findUserById(e.body.userId);if(!n)throw new J("BAD_REQUEST",{message:f.USER_NOT_FOUND});if(await o.findMemberByEmail({email:n.email,organizationId:t}))throw new J("BAD_REQUEST",{message:p.USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION});let s=await o.createMember({id:H(),organizationId:t,userId:n.id,role:e.body.role,createdAt:new Date});return e.json(s)}),gt=u("/organization/remove-member",{method:"POST",body:M.object({memberIdOrEmail:M.string({description:"The ID or email of the member to remove"}),organizationId:M.string({description:"The ID of the organization to remove the member from. If not provided, the active organization will be used"}).optional()}),use:[T,z],metadata:{openapi:{description:"Remove a member from an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{member:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}},required:["member"]}}}}}}}},async e=>{let r=e.context.session,t=e.body.organizationId||r.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:p.NO_ACTIVE_ORGANIZATION}});let o=E(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:r.user.id,organizationId:t});if(!n)throw new J("BAD_REQUEST",{message:p.MEMBER_NOT_FOUND});let i=e.context.roles[n.role];if(!i)throw new J("BAD_REQUEST",{message:p.ROLE_NOT_FOUND});let s=r.user.email===e.body.memberIdOrEmail||n.id===e.body.memberIdOrEmail;if(s&&n.role===(e.context.orgOptions?.creatorRole||"owner"))throw new J("BAD_REQUEST",{message:p.YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER});if(!(s||i.authorize({member:["delete"]}).success))throw new J("UNAUTHORIZED",{message:p.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER});let c=null;if(e.body.memberIdOrEmail.includes("@")?c=await o.findMemberByEmail({email:e.body.memberIdOrEmail,organizationId:t}):c=await o.findMemberById(e.body.memberIdOrEmail),c?.organizationId!==t)throw new J("BAD_REQUEST",{message:p.MEMBER_NOT_FOUND});return await o.deleteMember(c.id),r.user.id===c.userId&&r.session.activeOrganizationId===c.organizationId&&await o.setActiveOrganization(r.session.token,null),e.json({member:c})}),ht=e=>u("/organization/update-member-role",{method:"POST",body:M.object({role:M.string(),memberId:M.string(),organizationId:M.string().optional()}),use:[T,z],metadata:{openapi:{description:"Update the role of a member in an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{member:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}},required:["member"]}}}}}}}},async r=>{let t=r.context.session,o=r.body.organizationId||t.session.activeOrganizationId;if(!o)return r.json(null,{status:400,body:{message:p.NO_ACTIVE_ORGANIZATION}});let n=E(r.context,r.context.orgOptions),i=await n.findMemberByOrgId({userId:t.user.id,organizationId:o});if(!i)return r.json(null,{status:400,body:{message:p.MEMBER_NOT_FOUND}});let s=r.context.roles[i.role];if(!s)return r.json(null,{status:400,body:{message:p.ROLE_NOT_FOUND}});if(s.authorize({member:["update"]}).error||r.body.role==="owner"&&i.role!=="owner")return r.json(null,{body:{message:"You are not allowed to update this member"},status:403});let d=await n.updateMember(r.body.memberId,r.body.role);return d?r.json(d):r.json(null,{status:400,body:{message:p.MEMBER_NOT_FOUND}})}),yt=u("/organization/get-active-member",{method:"GET",use:[T,z],metadata:{openapi:{description:"Get the active member in the organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string"},userId:{type:"string"},organizationId:{type:"string"},role:{type:"string"}},required:["id","userId","organizationId","role"]}}}}}}}},async e=>{let r=e.context.session,t=r.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:p.NO_ACTIVE_ORGANIZATION}});let n=await E(e.context,e.context.orgOptions).findMemberByOrgId({userId:r.user.id,organizationId:t});return n?e.json(n):e.json(null,{status:400,body:{message:p.MEMBER_NOT_FOUND}})});import{z as w}from"zod";import{APIError as Q}from"better-call";var wt=u("/organization/create",{method:"POST",body:w.object({name:w.string({description:"The name of the organization"}),slug:w.string({description:"The slug of the organization"}),userId:w.string({description:"The user id of the organization creator. If not provided, the current user will be used. Should only be used by admins or when called by the server."}).optional(),logo:w.string({description:"The logo of the organization"}).optional(),metadata:w.record(w.string(),w.any(),{description:"The metadata of the organization"}).optional()}),use:[T],metadata:{openapi:{description:"Create an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization that was created",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let r=await v(e);if(!r&&(e.request||e.headers))throw new Q("UNAUTHORIZED");let t=r?.user||null;if(!t){if(!e.body.userId)throw new Q("UNAUTHORIZED");t=await e.context.internalAdapter.findUserById(e.body.userId)}if(!t)return e.json(null,{status:401});let o=e.context.orgOptions;if(!(typeof o?.allowUserToCreateOrganization=="function"?await o.allowUserToCreateOrganization(t):o?.allowUserToCreateOrganization===void 0?!0:o.allowUserToCreateOrganization))throw new Q("FORBIDDEN",{message:p.YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION});let i=E(e.context,o),s=await i.listOrganizations(t.id);if(typeof o.organizationLimit=="number"?s.length>=o.organizationLimit:typeof o.organizationLimit=="function"?await o.organizationLimit(t):!1)throw new Q("FORBIDDEN",{message:p.YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS});if(await i.findOrganizationBySlug(e.body.slug))throw new Q("BAD_REQUEST",{message:p.ORGANIZATION_ALREADY_EXISTS});let c=await i.createOrganization({organization:{id:H(),slug:e.body.slug,name:e.body.name,logo:e.body.logo,createdAt:new Date,metadata:e.body.metadata},user:t});return e.context.session&&await i.setActiveOrganization(e.context.session.session.token,c.id),e.json(c)}),bt=u("/organization/update",{method:"POST",body:w.object({data:w.object({name:w.string({description:"The name of the organization"}).optional(),slug:w.string({description:"The slug of the organization"}).optional(),logo:w.string({description:"The logo of the organization"}).optional(),metadata:w.record(w.string(),w.any(),{description:"The metadata of the organization"}).optional()}).partial(),organizationId:w.string().optional()}),requireHeaders:!0,use:[T],metadata:{openapi:{description:"Update an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The updated organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let r=await e.context.getSession(e);if(!r)throw new Q("UNAUTHORIZED",{message:"User not found"});let t=e.body.organizationId||r.session.activeOrganizationId;if(!t)return e.json(null,{status:400,body:{message:p.ORGANIZATION_NOT_FOUND}});let o=E(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:r.user.id,organizationId:t});if(!n)return e.json(null,{status:400,body:{message:p.USER_IS_NOT_A_MEMBER_OF_THE_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:p.YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION},status:403});let a=await o.updateOrganization(t,e.body.data);return e.json(a)}),Ot=u("/organization/delete",{method:"POST",body:w.object({organizationId:w.string({description:"The organization id to delete"})}),requireHeaders:!0,use:[T],metadata:{openapi:{description:"Delete an organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string",description:"The organization id that was deleted"}}}}}}}},async e=>{let r=await e.context.getSession(e);if(!r)return e.json(null,{status:401});let t=e.body.organizationId;if(!t)return e.json(null,{status:400,body:{message:p.ORGANIZATION_NOT_FOUND}});let o=E(e.context,e.context.orgOptions),n=await o.findMemberByOrgId({userId:r.user.id,organizationId:t});if(!n)return e.json(null,{status:400,body:{message:p.USER_IS_NOT_A_MEMBER_OF_THE_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 Q("FORBIDDEN",{message:p.YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION});return t===r.session.activeOrganizationId&&await o.setActiveOrganization(r.session.token,null),await o.deleteOrganization(t),e.json(t)}),At=u("/organization/get-full-organization",{method:"GET",query:w.optional(w.object({organizationId:w.string({description:"The organization id to get"}).optional(),organizationSlug:w.string({description:"The organization slug to get"}).optional()})),requireHeaders:!0,use:[T,z],metadata:{openapi:{description:"Get the full organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let r=e.context.session,t=e.query?.organizationSlug||e.query?.organizationId||r.session.activeOrganizationId;if(!t)return e.json(null,{status:200});let n=await E(e.context,e.context.orgOptions).findFullOrganization({organizationId:t,isSlug:!!e.query?.organizationSlug});if(!n)throw new Q("BAD_REQUEST",{message:p.ORGANIZATION_NOT_FOUND});return e.json(n)}),It=u("/organization/set-active",{method:"POST",body:w.object({organizationId:w.string({description:"The organization id to set as active. It can be null to unset the active organization"}).nullable().optional(),organizationSlug:w.string({description:"The organization slug to set as active. It can be null to unset the active organization if organizationId is not provided"}).optional()}),use:[z,T],metadata:{openapi:{description:"Set the active organization",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",description:"The organization",$ref:"#/components/schemas/Organization"}}}}}}}},async e=>{let r=E(e.context,e.context.orgOptions),t=e.context.session,o=e.body.organizationSlug||e.body.organizationId;if(o===null){if(!t.session.activeOrganizationId)return e.json(null);let d=await r.setActiveOrganization(t.session.token,null);return await S(e,{session:d,user:t.user}),e.json(null)}if(!o){let a=t.session.activeOrganizationId;if(!a)return e.json(null);o=a}let n=await r.findFullOrganization({organizationId:o,isSlug:!!e.body.organizationSlug});if(!n?.members.find(a=>a.userId===t.user.id))throw await r.setActiveOrganization(t.session.token,null),new Q("FORBIDDEN",{message:p.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION});let s=await r.setActiveOrganization(t.session.token,o);return await S(e,{session:s,user:t.user}),e.json(n)}),_t=u("/organization/list",{method:"GET",use:[T,z],metadata:{openapi:{description:"List all organizations",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Organization"}}}}}}}}},async e=>{let t=await E(e.context,e.context.orgOptions).listOrganizations(e.context.session.user.id);return e.json(t)});var io=me({name:["action"]}),gl=io.newRole({name:["action"]}),hl=e=>{let r={createOrganization:wt,updateOrganization:bt,deleteOrganization:Ot,setActiveOrganization:It,getFullOrganization:At,listOrganizations:_t,createInvitation:ct(e),cancelInvitation:pt,acceptInvitation:lt,getInvitation:mt,rejectInvitation:ut,addMember:ft(),removeMember:gt,updateMemberRole:ht(e),getActiveMember:yt},t={...it,...e?.roles};return{id:"organization",endpoints:{...nt(r,{orgOptions:e||{},roles:t,getSession:async n=>await v(n)}),hasPermission:u("/organization/has-permission",{method:"POST",requireHeaders:!0,body:ee.object({organizationId:ee.string().optional(),permission:ee.record(ee.string(),ee.array(ee.string()))}),use:[z],metadata:{openapi:{description:"Check if the user has permission",requestBody:{content:{"application/json":{schema:{type:"object",properties:{permission:{type:"object",description:"The permission to check"}},required:["permission"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},success:{type:"boolean"}},required:["success"]}}}}}}}},async n=>{let i=n.body.organizationId||n.context.session.session.activeOrganizationId;if(!i)throw new Et("BAD_REQUEST",{message:p.NO_ACTIVE_ORGANIZATION});let a=await E(n.context).findMemberByOrgId({userId:n.context.session.user.id,organizationId:i});if(!a)throw new Et("UNAUTHORIZED",{message:p.USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION});let c=t[a.role].authorize(n.body.permission);return c.error?n.json({error:c.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:{modelName:e?.schema?.organization?.modelName,fields:{name:{type:"string",required:!0,fieldName:e?.schema?.organization?.fields?.name},slug:{type:"string",unique:!0,fieldName:e?.schema?.organization?.fields?.slug},logo:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.logo},createdAt:{type:"date",required:!0,fieldName:e?.schema?.organization?.fields?.createdAt},metadata:{type:"string",required:!1,fieldName:e?.schema?.organization?.fields?.metadata}}},member:{modelName:e?.schema?.member?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.member?.fields?.organizationId},userId:{type:"string",required:!0,fieldName:e?.schema?.member?.fields?.userId,references:{model:"user",field:"id"}},role:{type:"string",required:!0,defaultValue:"member",fieldName:e?.schema?.member?.fields?.role},createdAt:{type:"date",required:!0,fieldName:e?.schema?.member?.fields?.createdAt}}},invitation:{modelName:e?.schema?.invitation?.modelName,fields:{organizationId:{type:"string",required:!0,references:{model:"organization",field:"id"},fieldName:e?.schema?.invitation?.fields?.organizationId},email:{type:"string",required:!0,fieldName:e?.schema?.invitation?.fields?.email},role:{type:"string",required:!1,fieldName:e?.schema?.invitation?.fields?.role},status:{type:"string",required:!0,defaultValue:"pending",fieldName:e?.schema?.invitation?.fields?.status},expiresAt:{type:"date",required:!0,fieldName:e?.schema?.invitation?.fields?.expiresAt},inviterId:{type:"string",references:{model:"user",field:"id"},fieldName:e?.schema?.invitation?.fields?.inviterId,required:!0}}}},$Infer:{Organization:{},Invitation:{},Member:{},ActiveOrganization:{}},$ERROR_CODES:p}};export{hl as organization};
|