better-auth 1.1.8 → 1.1.9-beta.1
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.
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var Ae=Object.defineProperty;var jt=Object.getOwnPropertyDescriptor;var Vt=Object.getOwnPropertyNames;var Nt=Object.prototype.hasOwnProperty;var $t=(e,t)=>{for(var
|
|
2
|
-
`,`Current list of trustedOrigins: ${l}`),new ke.APIError("FORBIDDEN",{message:`Invalid ${S}`})};f&&!e.context.options.advanced?.disableCSRFCheck&&y(i,"origin"),n&&y(n,"callbackURL"),s&&y(s,"redirectURL"),c&&y(c,"currentURL"),a&&y(a,"errorCallbackURL"),d&&y(s,"newUserCallbackURL")}),re=e=>te(async t=>{let{context:
|
|
3
|
-
`,`Current list of trustedOrigins: ${i}`),new ke.APIError("FORBIDDEN",{message:`Invalid ${a}`})})(o,"callbackURL")});var P=require("better-call"),k=require("zod");var x=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var Be=require("@better-auth/utils/base64");var Me=require("@better-auth/utils/hmac");async function _e(e,t){if(e.context.options.session?.cookieCache?.enabled){let o=Be.base64Url.encode(JSON.stringify({session:t,expiresAt:x(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await(0,Me.createHMAC)("SHA-256","base64urlnopad").sign(e.context.secret,JSON.stringify(t))}),{padding:!1});if(o.length>4093)throw new W("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,o,e.context.authCookies.sessionData.options)}}async function v(e,t,r,o){let i=e.context.authCookies.sessionToken.options,n=r?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),await _e(e,t),e.context.setNewSession(t),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.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})}var Wt=Object.defineProperty,Qt=Object.defineProperties,Zt=Object.getOwnPropertyDescriptors,qe=Object.getOwnPropertySymbols,Jt=Object.prototype.hasOwnProperty,Kt=Object.prototype.propertyIsEnumerable,ze=(e,t,r)=>t in e?Wt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Y=(e,t)=>{for(var r in t||(t={}))Jt.call(t,r)&&ze(e,r,t[r]);if(qe)for(var r of qe(t))Kt.call(t,r)&&ze(e,r,t[r]);return e},X=(e,t)=>Qt(e,Zt(t)),Yt=class extends Error{constructor(e,t,r){super(t||e.toString(),{cause:r}),this.status=e,this.statusText=t,this.error=r}},Xt=async(e,t)=>{var r,o,i,n,s,c;let a=t||{},d={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:a,hooks:d};for(let l of t?.plugins||[]){if(l.init){let f=await((r=l.init)==null?void 0:r.call(l,e.toString(),t));a=f.options||a,e=f.url}d.onRequest.push((o=l.hooks)==null?void 0:o.onRequest),d.onResponse.push((i=l.hooks)==null?void 0:i.onResponse),d.onSuccess.push((n=l.hooks)==null?void 0:n.onSuccess),d.onError.push((s=l.hooks)==null?void 0:s.onError),d.onRetry.push((c=l.hooks)==null?void 0:c.onRetry)}return{url:e,options:a,hooks:d}},Fe=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},er=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function tr(e){if(typeof e=="number")return new Fe({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new Fe(e);case"exponential":return new er(e);default:throw new Error("Invalid retry strategy")}}var rr=e=>{let t={},r=o=>typeof o=="function"?o():o;if(e?.auth){if(e.auth.type==="Bearer"){let o=r(e.auth.token);if(!o)return t;t.authorization=`Bearer ${o}`}else if(e.auth.type==="Basic"){let o=r(e.auth.username),i=r(e.auth.password);if(!o||!i)return t;t.authorization=`Basic ${btoa(`${o}:${i}`)}`}else if(e.auth.type==="Custom"){let o=r(e.auth.value);if(!o)return t;t.authorization=`${r(e.auth.prefix)} ${o}`}}return t},We=["get","post","put","patch","delete"];var or=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function ir(e){let t=e.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!t)return"json";let o=t.split(";").shift()||"";return or.test(o)?"json":r.has(o)||o.startsWith("text/")?"text":"blob"}function nr(e){try{return JSON.parse(e),!0}catch{return!1}}function Qe(e){if(e===void 0)return!1;let t=typeof e;return t==="string"||t==="number"||t==="boolean"||t===null?!0:t!=="object"?!1:Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name==="Object"||typeof e.toJSON=="function"}function He(e){try{return JSON.parse(e)}catch{return e}}function Ge(e){return typeof e=="function"}function sr(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<"u"&&Ge(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&Ge(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}function ar(e){let t=new Headers(e?.headers),r=rr(e);for(let[o,i]of Object.entries(r||{}))t.set(o,i);if(!t.has("content-type")){let o=dr(e?.body);o&&t.set("content-type",o)}return t}function dr(e){return Qe(e)?"application/json":null}function cr(e){if(!e?.body)return null;let t=new Headers(e?.headers);return Qe(e.body)&&!t.has("content-type")?JSON.stringify(e.body):e.body}function lr(e,t){var r;if(t?.method)return t.method.toUpperCase();if(e.startsWith("@")){let o=(r=e.split("@")[1])==null?void 0:r.split("/")[0];return We.includes(o)?o.toUpperCase():t?.body?"POST":"GET"}return t?.body?"POST":"GET"}function ur(e,t){let r;return!e?.signal&&e?.timeout&&(r=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}function pr(e,t){let{baseURL:r,params:o,query:i}=t||{query:{},params:{},baseURL:""},n=e.startsWith("http")?e.split("/").slice(0,3).join("/"):r;if(!n)throw new TypeError(`Invalid URL ${e}. Are you passing in a relative URL but not setting the baseURL?`);if(e.startsWith("@")){let f=e.toString().split("@")[1].split("/")[0];We.includes(f)&&(e=e.replace(`@${f}/`,"/"))}n.endsWith("/")||(n+="/");let[s,c]=e.replace(n,"").split("?"),a=new URLSearchParams(c);for(let[f,p]of Object.entries(i||{}))a.set(f,String(p));if(o)if(Array.isArray(o)){let f=s.split("/").filter(p=>p.startsWith(":"));for(let[p,y]of f.entries()){let b=o[p];s=s.replace(y,b)}}else for(let[f,p]of Object.entries(o))s=s.replace(`:${f}`,String(p));s=s.split("/").map(encodeURIComponent).join("/"),s.startsWith("/")&&(s=s.slice(1));let d=a.size>0?`?${a}`.replace(/\+/g,"%20"):"";return new URL(`${s}${d}`,n)}var w=async(e,t)=>{var r,o,i,n,s,c,a,d;let{hooks:l,url:f,options:p}=await Xt(e,t),y=sr(p),b=new AbortController,S=(r=p.signal)!=null?r:b.signal,pe=pr(f,p),de=cr(p),ce=ar(p),L=lr(f,p),h=X(Y({},p),{url:pe,headers:ce,body:de,method:L,signal:S});for(let C of l.onRequest)if(C){let I=await C(h);I instanceof Object&&(h=I)}("pipeTo"in h&&typeof h.pipeTo=="function"||typeof((o=t?.body)==null?void 0:o.pipe)=="function")&&("duplex"in h||(h.duplex="half"));let{clearTimeout:xe}=ur(p,b),R=await y(h.url,h);xe();let De={response:R,request:h};for(let C of l.onResponse)if(C){let I=await C(X(Y({},De),{response:(i=t?.hookOptions)!=null&&i.cloneResponse?R.clone():R}));I instanceof Response?R=I:I instanceof Object&&(R=I.response)}if(R.ok){if(!(h.method!=="HEAD"))return{data:"",error:null};let I=ir(R),F={data:"",response:R,request:h};if(I==="json"||I==="text"){let H=await R.text(),Ct=await((n=h.jsonParser)!=null?n:He)(H);F.data=Ct}else F.data=await R[I]();h?.output&&h.output&&!h.disableValidation&&(F.data=h.output.parse(F.data));for(let H of l.onSuccess)H&&await H(X(Y({},F),{response:(s=t?.hookOptions)!=null&&s.cloneResponse?R.clone():R}));return t?.throw?F.data:{data:F.data,error:null}}let xt=(c=t?.jsonParser)!=null?c:He,Ce=await R.text(),be=nr(Ce)?await xt(Ce):{},Dt={response:R,request:h,error:X(Y({},be),{status:R.status,statusText:R.statusText})};for(let C of l.onError)C&&await C(X(Y({},Dt),{response:(a=t?.hookOptions)!=null&&a.cloneResponse?R.clone():R}));if(t?.retry){let C=tr(t.retry),I=(d=t.retryAttempt)!=null?d:0;if(await C.shouldAttemptRetry(I,R)){for(let H of l.onRetry)H&&await H(De);let F=C.getDelay(I);return await new Promise(H=>setTimeout(H,F)),await w(e,X(Y({},t),{retryAttempt:I+1}))}}if(t?.throw)throw new Yt(R.status,R.statusText,be);return{data:null,error:X(Y({},be),{status:R.status,statusText:R.statusText})}};var rt=require("better-call"),Q=require("jose");var Ze=require("@better-auth/utils/hash"),Je=require("@better-auth/utils/base64");async function Ke(e){let t=await(0,Ze.createHash)("SHA-256").digest(e);return Je.base64Url.encode(new Uint8Array(t),{padding:!1})}function ge(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?x(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function E({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:s,redirectURI:c,duration:a}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),i){let l=await Ke(i);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((f,p)=>(f[p]=null,f),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return a&&d.searchParams.set("duration",a),d}var mr=require("jose");async function A({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i,authentication:n}){let s=new URLSearchParams,c={"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),t&&s.set("code_verifier",t),s.set("redirect_uri",r),n==="basic"){let f=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${f}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await w(i,{method:"POST",body:s,headers:c});if(d)throw d;return ge(a)}var M=require("zod"),Se=require("better-call");var br=require("@better-auth/utils/hash"),Ar=require("@noble/ciphers/chacha"),Oe=require("@noble/ciphers/utils"),Rr=require("@noble/ciphers/webcrypto");var gr=require("@better-auth/utils/hash");var Ye=require("jose");async function Xe(e,t,r=3600){return await new Ye.SignJWT(e).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(t))}var hr=require("@noble/hashes/scrypt"),wr=require("uncrypto"),yr=require("@better-auth/utils/hex");var et=require("@better-auth/utils/random"),B=(0,et.createRandomStringGenerator)("a-z","0-9","A-Z","-_");async function he(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?$e(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new Se.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=B(128),i=B(32),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,newUserURL:e.body?.newUserCallbackURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:s});if(!c)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 Se.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function tt(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=M.z.object({callbackURL:M.z.string(),codeVerifier:M.z.string(),errorURL:M.z.string().optional(),newUserURL:M.z.string().optional(),expiresAt:M.z.number(),link:M.z.object({email:M.z.string(),userId:M.z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var ot=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=o||["email","name"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${e.redirectURI||i}&scope=${n.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>A({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let i=(0,Q.decodeProtectedHeader)(r),{kid:n,alg:s}=i;if(!n||!s)return!1;let c=await Er(n),{payload:a}=await(0,Q.jwtVerify)(r,c,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.appBundleIdentifier||e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=(0,Q.decodeJwt)(r.idToken);if(!o)return null;let i=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:i,emailVerified:!1,email:o.email,...n},data:o}}}},Er=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await w(`${t}${r}`);if(!o?.keys)throw new rt.APIError("BAD_REQUEST",{message:"Keys not found"});let i=o.keys.find(n=>n.kid===e);if(!i)throw new Error(`JWK with kid ${e} not found`);return await(0,Q.importJWK)(i,i.alg)};var it=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await w("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...i},data:r}}});var nt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await E({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await w("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...i},data:r}}});var st=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),E({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>A({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await w("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1,{data:s}=await w("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});s&&(o.email=(s.find(a=>a.primary)??s[0])?.email,n=s.find(a=>a.email===o.email)?.verified??!1);let c=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n,...c},data:o}}}};var at=require("jose");var ve=["info","success","warn","error","debug"];function Tr(e,t){return ve.indexOf(t)<=ve.indexOf(e)}var q={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",fg:{black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},bg:{black:"\x1B[40m",red:"\x1B[41m",green:"\x1B[42m",yellow:"\x1B[43m",blue:"\x1B[44m",magenta:"\x1B[45m",cyan:"\x1B[46m",white:"\x1B[47m"}},Ur={info:q.fg.blue,success:q.fg.green,warn:q.fg.yellow,error:q.fg.red,debug:q.fg.magenta},kr=(e,t)=>{let r=new Date().toISOString();return`${q.dim}${r}${q.reset} ${Ur[e]}${e.toUpperCase()}${q.reset} ${q.bright}[Better Auth]:${q.reset} ${t}`},_r=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(i,n,s=[])=>{if(!t||!Tr(r,i))return;let c=kr(i,n);if(!e||typeof e.log!="function"){i==="error"?console.error(c,...s):i==="warn"?console.warn(c,...s):console.log(c,...s);return}e.log(i==="success"?"info":i,c,...s)};return Object.fromEntries(ve.map(i=>[i,(...[n,...s])=>o(i,n,s)]))},V=_r();var dt=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw V.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new W("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new W("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await E({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),e.display&&s.searchParams.set("display",e.display),e.hd&&s.searchParams.set("hd",e.hd),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>A({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:i}=await w(o);return i?i.aud===e.clientId&&i.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,at.decodeJwt)(t.idToken),o=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...o},data:r}}});var ct=require("jose"),lt=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),E({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return A({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);if(!i.idToken)return null;let n=(0,ct.decodeJwt)(i.idToken),s=e.profilePhotoSize||48;await w(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let l=await a.response.clone().arrayBuffer(),f=Buffer.from(l).toString("base64");n.picture=`data:image/jpeg;base64, ${f}`}catch(d){V.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0,...c},data:n}}}};var ut=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),E({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>A({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await w("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...i},data:r}}});var oe={isAction:!1};var pt=require("@better-auth/utils/random"),mt=e=>(0,pt.createRandomStringGenerator)("a-z","A-Z","0-9")(e||32);var ft=require("jose"),gt=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),E({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return V.error("No idToken found in token"),null;let o=(0,ft.decodeJwt)(r),i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...i},data:o}}});var ht=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),E({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>A({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await w("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.data.id,name:r.data.name,email:r.data.username||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1,...i},data:r}}});var wt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await E({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await A({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await w("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...n},data:o}}}};var yt=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await E({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await A({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await w("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(n)return null;let s=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture,...s},data:i}}}};var Pe=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Or=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:Pe(`${t}/oauth/authorize`),tokenEndpoint:Pe(`${t}/oauth/token`),userinfoEndpoint:Pe(`${t}/api/v4/user`)}},bt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Or(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let l=c||["read_user"];return e.scope&&l.push(...e.scope),await E({id:i,options:e,authorizationEndpoint:t,scopes:l,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>A({code:s,redirectURI:e.redirectURI||c,options:e,codeVerifier:a,tokenEndpoint:r}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:c,error:a}=await w(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(a||c.state!=="active"||c.locked)return null;let d=await e.mapProfileToUser?.(c);return{user:{id:c.id.toString(),name:c.name??c.username,email:c.email,image:c.avatar_url,emailVerified:!0,...d},data:c}}}};var At=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identity"];return e.scope&&i.push(...e.scope),E({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:i,state:t,redirectURI:o,duration:e.duration})},validateAuthorizationCode:async({code:t,redirectURI:r})=>{let o=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:e.redirectURI||r}),i={"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:n,error:s}=await w("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:i,body:o.toString()});if(s)throw s;return ge(n)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await w("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.oauth_client_id,emailVerified:r.has_verified_email,image:r.icon_img?.split("?")[0],...i},data:r}}});var Rt=require("zod"),Sr={apple:ot,discord:it,facebook:nt,github:st,microsoft:lt,google:dt,spotify:ut,twitch:gt,twitter:ht,dropbox:wt,linkedin:yt,gitlab:bt,reddit:At},Ie=Object.keys(Sr),Et=Rt.z.enum(Ie,{description:"OAuth2 provider to use"});var j=require("zod");var ie=require("better-call");var z=require("better-call");var Z=require("zod");function Tt(e){try{return JSON.parse(e)}catch{return null}}var u={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",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action.",FAILED_TO_UNLINK_LAST_ACCOUNT:"You can't unlink your last account",ACCOUNT_NOT_FOUND:"Account not found"};var Ut=require("@better-auth/utils/hmac"),kt=require("@better-auth/utils/base64"),_t=require("@better-auth/utils/binary"),Ot=()=>m("/get-session",{method:"GET",query:Z.z.optional(Z.z.object({disableCookieCache:Z.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(Z.z.string().transform(e=>e==="true")).optional(),disableRefresh:Z.z.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?Tt(_t.binary.decode(kt.base64.decode(r))):null;if(o&&!await(0,Ut.createHMAC)("SHA-256","base64urlnopad").verify(e.context.secret,JSON.stringify(o.session),o.signature))return $(e),e.json(null);let i=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 p=e.context.authCookies.sessionData.name;e.setCookie(p,"",{maxAge:0})}else return e.json(l)}let n=await e.context.internalAdapter.findSession(t);if(e.context.session=n,!n||n.session.expiresAt<new Date)return $(e),n&&await e.context.internalAdapter.deleteSession(n.session.token),e.json(null);if(i||e.query?.disableRefresh)return e.json(n);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let l=await e.context.internalAdapter.updateSession(n.session.token,{expiresAt:x(e.context.sessionConfig.expiresIn,"sec")});if(!l)return $(e),e.json(null,{status:401});let f=(l.expiresAt.valueOf()-Date.now())/1e3;return await v(e,{session:l,user:n.user},!1,{maxAge:f}),e.json({session:l,user:n.user})}return await _e(e,n),e.json(n)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new z.APIError("INTERNAL_SERVER_ERROR",{message:u.FAILED_TO_GET_SESSION})}}),ee=async(e,t)=>{if(e.context.session)return e.context.session;let r=await Ot()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},N=te(async e=>{let t=await ee(e);if(!t?.session)throw new z.APIError("UNAUTHORIZED");return{session:t}}),St=te(async e=>{let t=await ee(e);if(!t?.session)throw new z.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.updatedAt?.valueOf()||t.session.createdAt.valueOf();if(!(Date.now()-o<r*1e3))throw new z.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}});var vr=m("/revoke-session",{method:"POST",body:Z.z.object({token:Z.z.string({description:"The token to revoke"})}),use:[N],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let t=e.body.token,r=await e.context.internalAdapter.findSession(t);if(!r)throw new z.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new z.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new z.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Pr=m("/revoke-sessions",{method:"POST",use:[N],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new z.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Ir=m("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[N],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw new z.APIError("UNAUTHORIZED");let i=(await e.context.internalAdapter.listSessions(t.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.token!==e.context.session.session.token);return await Promise.all(i.map(n=>e.context.internalAdapter.deleteSession(n.token))),e.json({status:!0})});var vt=require("jose");async function G(e,t,r){return await Xe({email:t.toLowerCase(),updateTo:r},e)}async function Lr(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new ie.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await G(e.context.secret,t.email),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:r},e.request)}var xr=m("/send-verification-email",{method:"POST",query:j.z.object({currentURL:j.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:j.z.object({email:j.z.string({description:"The email to send the verification email to"}).email(),callbackURL:j.z.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new ie.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new ie.APIError("BAD_REQUEST",{message:u.USER_NOT_FOUND});return await Lr(e,r.user),e.json({status:!0})}),Dr=m("/verify-email",{method:"GET",query:j.z.object({token:j.z.string({description:"The token to verify the email"}),callbackURL:j.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[re(e=>e.query.callbackURL)],metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(c){throw e.query.callbackURL?e.query.callbackURL.includes("?")?e.redirect(`${e.query.callbackURL}&error=${c}`):e.redirect(`${e.query.callbackURL}?error=${c}`):new ie.APIError("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await(0,vt.jwtVerify)(r,new TextEncoder().encode(e.context.secret),{algorithms:["HS256"]})}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let n=j.z.object({email:j.z.string().email(),updateTo:j.z.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(n.email);if(!s)return t("user_not_found");if(n.updateTo){let c=await ee(e);if(!c){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(c.user.email!==n.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo,emailVerified:!1}),d=await G(e.context.secret,n.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${d}`,token:d},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:{id:a.id,email:a.email,name:a.name,image:a.image,emailVerified:a.emailVerified,createdAt:a.createdAt,updatedAt:a.updatedAt}})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification){let c=await ee(e);if(!c||c.user.email!==n.email){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new ie.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await v(e,{session:a,user:s.user})}}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});async function we(e,{userInfo:t,account:r,callbackURL:o}){let i=await e.context.internalAdapter.findOAuthUser(t.email.toLowerCase(),r.accountId,r.providerId).catch(a=>{throw V.error(`Better auth was unable to query your database.
|
|
4
|
-
Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=i?.user,s=!n;if(i){let a=i.accounts.find(d=>d.providerId===r.providerId);if(a){let d=Object.fromEntries(Object.entries({accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([l,f])=>f!==void 0));Object.keys(d).length>0&&await e.context.internalAdapter.updateAccount(a.id,d)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Te&&V.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),userId:i.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope})}catch(f){return V.error("Unable to link account",f),{error:"unable to link account",data:null}}}}else try{if(n=await e.context.internalAdapter.createOAuthUser({...t,email:t.email.toLowerCase(),id:void 0},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:t.id.toString()}).then(a=>a?.user),!t.emailVerified&&n&&e.context.options.emailVerification?.sendOnSignUp){let a=await G(e.context.secret,n.email),d=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:n,url:d,token:a},e.request)}}catch(a){return a instanceof U.APIError?{error:a.message,data:null,isRegister:!1}:{error:"unable to create user",data:null,isRegister:!1}}if(!n)return{error:"unable to create user",data:null,isRegister:!1};let c=await e.context.internalAdapter.createSession(n.id,e.request);return c?{data:{session:c,user:n},error:null,isRegister:s}:{error:"unable to create session",data:null,isRegister:!1}}var Cr=m("/sign-in/social",{method:"POST",query:k.z.object({currentURL:k.z.string().optional()}).optional(),body:k.z.object({callbackURL:k.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:k.z.string().optional(),errorCallbackURL:k.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:Et,disableRedirect:k.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:k.z.optional(k.z.object({token:k.z.string({description:"ID token from the provider"}),nonce:k.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:k.z.string({description:"Access token from the provider"}).optional(),refreshToken:k.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:k.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new P.APIError("NOT_FOUND",{message:u.PROVIDER_NOT_FOUND});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new P.APIError("NOT_FOUND",{message:u.ID_TOKEN_NOT_SUPPORTED});let{token:n,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(n,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new P.APIError("UNAUTHORIZED",{message:u.INVALID_TOKEN});let a=await t.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new P.APIError("UNAUTHORIZED",{message:u.FAILED_TO_GET_USER_INFO});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new P.APIError("UNAUTHORIZED",{message:u.USER_EMAIL_NOT_FOUND});let d=await we(e,{userInfo:{email:a.user.email,id:a.user.id,name:a.user.name||"",image:a.user.image,emailVerified:a.user.emailVerified||!1},account:{providerId:t.id,accountId:a.user.id,accessToken:e.body.idToken.accessToken}});if(d.error)throw new P.APIError("UNAUTHORIZED",{message:d.error});return await v(e,d.data),e.json({redirect:!1,token:d.data.session.token,url:void 0,user:{id:d.data.user.id,email:d.data.user.email,name:d.data.user.name,image:d.data.user.image,emailVerified:d.data.user.emailVerified,createdAt:d.data.user.createdAt,updatedAt:d.data.user.updatedAt}})}let{codeVerifier:r,state:o}=await he(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!e.body.disableRedirect})}),jr=m("/sign-in/email",{method:"POST",body:k.z.object({email:k.z.string({description:"Email of the user"}),password:k.z.string({description:"Password of the user"}),callbackURL:k.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:k.z.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new P.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!k.z.string().email().safeParse(t).success)throw new P.APIError("BAD_REQUEST",{message:u.INVALID_EMAIL});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:u.INVALID_EMAIL_OR_PASSWORD});let n=i.accounts.find(d=>d.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:u.INVALID_EMAIL_OR_PASSWORD});let s=n?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:u.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new P.APIError("UNAUTHORIZED",{message:u.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new P.APIError("UNAUTHORIZED",{message:u.EMAIL_NOT_VERIFIED});let d=await G(e.context.secret,i.user.email),l=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:i.user,url:l,token:d},e.request),new P.APIError("FORBIDDEN",{message:u.EMAIL_NOT_VERIFIED})}let a=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new P.APIError("UNAUTHORIZED",{message:u.FAILED_TO_CREATE_SESSION});return await v(e,{session:a,user:i.user},e.body.rememberMe===!1),e.json({redirect:!!e.body.callbackURL,token:a.token,url:e.body.callbackURL,user:{id:i.user.id,email:i.user.email,name:i.user.name,image:i.user.image,emailVerified:i.user.emailVerified,createdAt:i.user.createdAt,updatedAt:i.user.updatedAt}})});var ne=require("zod");var ye=ne.z.object({code:ne.z.string().optional(),error:ne.z.string().optional(),error_description:ne.z.string().optional(),state:ne.z.string().optional()}),Vr=m("/callback/:id",{method:["GET","POST"],body:ye.optional(),query:ye.optional(),metadata:oe},async e=>{let t;try{if(e.method==="GET")t=ye.parse(e.query);else if(e.method==="POST")t=ye.parse(e.body);else throw new Error("Unsupported method")}catch(L){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",L),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:i,error_description:n}=t;if(!i)throw e.context.logger.error("State not found",o),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}&error_description=${n}`);let s=e.context.socialProviders.find(L=>L.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:c,callbackURL:a,link:d,errorURL:l,newUserURL:f}=await tt(e),p;try{p=await s.validateAuthorizationCode({code:r,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${s.id}`})}catch(L){throw e.context.logger.error("",L),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let y=await s.getUserInfo(p).then(L=>L?.user);function b(L){let h=l||a||`${e.context.baseURL}/error`;throw h.includes("?")?h=`${h}&error=${L}`:h=`${h}?error=${L}`,e.redirect(h)}if(!y)return e.context.logger.error("Unable to get user info"),b("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."),b("email_not_found");if(!a)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(d){if(d.email!==y.email.toLowerCase())return b("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:s.id,accountId:y.id}))return b("unable_to_link_account");let h;try{h=a.toString()}catch{h=a}throw e.redirect(h)}let S=await we(e,{userInfo:{...y,email:y.email,name:y.name||y.email},account:{providerId:s.id,accountId:y.id,...p,scope:p.scopes?.join(",")},callbackURL:a});if(S.error)return e.context.logger.error(S.error.split(" ").join("_")),b(S.error.split(" ").join("_"));let{session:pe,user:de}=S.data;await v(e,{session:pe,user:de});let ce;try{ce=(S.isRegister&&f||a).toString()}catch{ce=S.isRegister&&f||a}throw e.redirect(ce)});var As=require("zod");var Pt=require("better-call");var Nr=m("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw $(e),new Pt.APIError("BAD_REQUEST",{message:u.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(t),$(e),e.json({success:!0})});var D=require("zod");var se=require("better-call");function It(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}function $r(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}var Br=m("/forget-password",{method:"POST",body:D.z.object({email:D.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:D.z.string({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new se.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let i=60*60*1,n=x(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||i,"sec"),s=mt(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:n});let c=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:c,token:s},e.request),e.json({status:!0})}),Mr=m("/reset-password/:token",{method:"GET",query:D.z.object({callbackURL:D.z.string({description:"The URL to redirect the user to reset their password"})}),use:[re(e=>e.query.callbackURL)],metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(It(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(It(e.context,r,{error:"INVALID_TOKEN"})):e.redirect($r(e.context,r,{token:t}))}),qr=m("/reset-password",{query:D.z.optional(D.z.object({token:D.z.string().optional(),currentURL:D.z.string().optional()})),method:"POST",body:D.z.object({newPassword:D.z.string({description:"The new password to set"}),token:D.z.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new se.APIError("BAD_REQUEST",{message:u.INVALID_TOKEN});let{newPassword:r}=e.body,o=e.context.password?.config.minPasswordLength,i=e.context.password?.config.maxPasswordLength;if(r.length<o)throw new se.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_SHORT});if(r.length>i)throw new se.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_LONG});let n=`reset-password:${t}`,s=await e.context.internalAdapter.findVerificationValue(n);if(!s||s.expiresAt<new Date)throw new se.APIError("BAD_REQUEST",{message:u.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(s.id);let c=s.value,a=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(c)).find(f=>f.providerId==="credential")?(await e.context.internalAdapter.updatePassword(c,a),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:c,providerId:"credential",password:a,accountId:c}),e.json({status:!0}))});var O=require("zod");var _=require("better-call");var g=require("zod"),zr=require("better-call"),Ls=g.z.object({id:g.z.string(),providerId:g.z.string(),accountId:g.z.string(),userId:g.z.string(),accessToken:g.z.string().nullish(),refreshToken:g.z.string().nullish(),idToken:g.z.string().nullish(),accessTokenExpiresAt:g.z.date().nullish(),refreshTokenExpiresAt:g.z.date().nullish(),scope:g.z.string().nullish(),password:g.z.string().nullish(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date)}),xs=g.z.object({id:g.z.string(),email:g.z.string().transform(e=>e.toLowerCase()),emailVerified:g.z.boolean().default(!1),name:g.z.string(),image:g.z.string().nullish(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date)}),Ds=g.z.object({id:g.z.string(),userId:g.z.string(),expiresAt:g.z.date(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date),token:g.z.string(),ipAddress:g.z.string().nullish(),userAgent:g.z.string().nullish()}),Cs=g.z.object({id:g.z.string(),value:g.z.string(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date),expiresAt:g.z.date(),identifier:g.z.string()});var Hr=m("/change-password",{method:"POST",body:O.z.object({newPassword:O.z.string({description:"The new password to set"}),currentPassword:O.z.string({description:"The current password"}),revokeOtherSessions:O.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[N],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new _.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_SHORT});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new _.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_LONG});let a=(await e.context.internalAdapter.findAccounts(i.user.id)).find(p=>p.providerId==="credential"&&p.password);if(!a||!a.password)throw new _.APIError("BAD_REQUEST",{message:u.CREDENTIAL_ACCOUNT_NOT_FOUND});let d=await e.context.password.hash(t);if(!await e.context.password.verify({hash:a.password,password:r}))throw new _.APIError("BAD_REQUEST",{message:u.INVALID_PASSWORD});await e.context.internalAdapter.updateAccount(a.id,{password:d});let f=null;if(o){await e.context.internalAdapter.deleteSessions(i.user.id);let p=await e.context.internalAdapter.createSession(i.user.id,e.headers);if(!p)throw new _.APIError("INTERNAL_SERVER_ERROR",{message:u.FAILED_TO_GET_SESSION});await v(e,{session:p,user:i.user}),f=p.token}return e.json({token:f,user:{id:i.user.id,email:i.user.email,name:i.user.name,image:i.user.image,emailVerified:i.user.emailVerified,createdAt:i.user.createdAt,updatedAt:i.user.updatedAt}})}),Gr=m("/set-password",{method:"POST",body:O.z.object({newPassword:O.z.string()}),metadata:{SERVER_ONLY:!0},use:[N]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new _.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_SHORT});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new _.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_LONG});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password),c=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:c}),e.json({status:!0});throw new _.APIError("BAD_REQUEST",{message:"user already has a password"})}),Wr=m("/delete-user",{method:"POST",use:[N],body:O.z.object({callbackURL:O.z.string().optional(),password:O.z.string().optional(),token:O.z.string().optional()}),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 _.APIError("NOT_FOUND");let t=e.context.session;if(e.body.password){let n=(await e.context.internalAdapter.findAccounts(t.user.id)).find(c=>c.providerId==="credential"&&c.password);if(!n||!n.password)throw new _.APIError("BAD_REQUEST",{message:u.CREDENTIAL_ACCOUNT_NOT_FOUND});if(!await e.context.password.verify({hash:n.password,password:e.body.password}))throw new _.APIError("BAD_REQUEST",{message:u.INVALID_PASSWORD})}else if(e.context.options.session?.freshAge){let i=t.session.createdAt.getTime(),n=e.context.options.session.freshAge;if(Date.now()-i>n)throw new _.APIError("BAD_REQUEST",{message:u.SESSION_EXPIRED})}if(e.body.token)return await Lt({...e,query:{token:e.body.token}}),e.json({success:!0,message:"User deleted"});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let i=B(32,"0-9","a-z");await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${i}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let n=`${e.context.baseURL}/delete-user/callback?token=${i}&callbackURL=${e.body.callbackURL||"/"}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:n,token:i},e.request),e.json({success:!0,message:"Verification email sent"})}let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),$(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})}),Lt=m("/delete-user/callback",{method:"GET",query:O.z.object({token:O.z.string(),callbackURL:O.z.string().optional()}),use:[re(e=>e.query.callbackURL)]},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new _.APIError("NOT_FOUND");let t=await ee(e);if(!t)throw new _.APIError("NOT_FOUND",{message:u.FAILED_TO_GET_USER_INFO});let r=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!r||r.expiresAt<new Date)throw r&&await e.context.internalAdapter.deleteVerificationValue(r.id),new _.APIError("NOT_FOUND",{message:u.INVALID_TOKEN});if(r.value!==t.user.id)throw new _.APIError("NOT_FOUND",{message:u.INVALID_TOKEN});let o=e.context.options.user.deleteUser?.beforeDelete;o&&await o(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),await e.context.internalAdapter.deleteVerificationValue(r.id),$(e);let i=e.context.options.user.deleteUser?.afterDelete;if(i&&await i(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||"/");return e.json({success:!0,message:"User deleted"})}),Qr=m("/change-email",{method:"POST",query:O.z.object({currentURL:O.z.string().optional()}).optional(),body:O.z.object({newEmail:O.z.string({description:"The new email to set"}).email(),callbackURL:O.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[N],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 _.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new _.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new _.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let i=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new _.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await G(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),e.json({status:!0})});var Zr=(e="Unknown")=>`<!DOCTYPE html>
|
|
1
|
+
"use strict";var Ae=Object.defineProperty;var jt=Object.getOwnPropertyDescriptor;var Vt=Object.getOwnPropertyNames;var Nt=Object.prototype.hasOwnProperty;var $t=(e,t)=>{for(var o in t)Ae(e,o,{get:t[o],enumerable:!0})},Bt=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Vt(t))!Nt.call(e,i)&&i!==o&&Ae(e,i,{get:()=>t[i],enumerable:!(r=jt(t,i))||r.enumerable});return e};var Mt=e=>Bt(Ae({},"__esModule",{value:!0}),e);var io={};$t(io,{emailOTP:()=>oo});module.exports=Mt(io);var T=require("zod");var ae=require("better-call");var ke=require("better-call");var K=require("better-call"),je=(0,K.createMiddleware)(async()=>({})),te=(0,K.createMiddlewareCreator)({use:[je,(0,K.createMiddleware)(async()=>({}))]}),m=(0,K.createEndpointCreator)({use:[je]});function Re(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function qt(e){let t="";for(let o=0;o<e.length;o++)t+=Re(e[o]);return t}function Ve(e,t=!0){if(Array.isArray(e))return`(?:${e.map(l=>`^${Ve(l,t)}$`).join("|")})`;let o="",r="",i=".";t===!0?(o="/",r="[/\\\\]",i="[^/\\\\]"):t&&(o=t,r=qt(o),r.length>1?(r=`(?:${r})`,i=`((?!${r}).)`):i=`[^${r}]`);let n=t?`${r}+?`:"",s=t?`${r}*?`:"",c=t?e.split(o):[e],a="";for(let d=0;d<c.length;d++){let l=c[d],f=c[d+1],p="";if(!(!l&&d>0)){if(t&&(d===c.length-1?p=s:f!=="**"?p=n:p=""),t&&l==="**"){p&&(a+=d===0?"":p,a+=`(?:${i}*?${p})*?`);continue}for(let y=0;y<l.length;y++){let b=l[y];b==="\\"?y<l.length-1&&(a+=Re(l[y+1]),y++):b==="?"?a+=i:b==="*"?a+=`${i}*?`:a+=Re(b)}a+=p}}return a}function zt(e,t){if(typeof t!="string")throw new TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function me(e,t){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 t=="string"||typeof t=="boolean")&&(t={separator:t}),arguments.length===2&&!(typeof t>"u"||typeof t=="object"&&t!==null&&!Array.isArray(t)))throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if(t=t||{},t.separator==="\\")throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let o=Ve(e,t.separator),r=new RegExp(`^${o}$`,t.flags),i=zt.bind(null,r);return i.options=t,i.pattern=e,i.regexp=r,i}var fe=Object.create(null),le=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?fe:globalThis),Ne=new Proxy(fe,{get(e,t){return le()[t]??fe[t]},has(e,t){let o=le();return t in o||t in fe},set(e,t,o){let r=le(!0);return r[t]=o,!0},deleteProperty(e,t){if(!t)return!1;let o=le(!0);return delete o[t],!0},ownKeys(){let e=le(!0);return Object.keys(e)}});function Ft(e){return e?e!=="false":!1}var Ee=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Te=Ee==="dev"||Ee==="development",Ht=Ee==="test"||Ft(Ne.TEST);var W=class extends Error{constructor(t,o){super(t),this.name="BetterAuthError",this.message=t,this.cause=o,this.stack=""}};function $e(e){try{return new URL(e).origin}catch{return null}}function Ue(e){return e.includes("://")?new URL(e).host:e}var Gt=te(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:o,context:r}=e,i=e.headers?.get("origin")||e.headers?.get("referer")||"",n=t?.callbackURL||o?.callbackURL,s=t?.redirectTo,c=o?.currentURL,a=t?.errorCallbackURL,d=t?.newUserCallbackURL,l=r.trustedOrigins,f=e.headers?.has("cookie"),p=(b,S)=>b.startsWith("/")?!1:S.includes("*")?me(S)(Ue(b)):b.startsWith(S),y=(b,S)=>{if(!b)return;if(!l.some(de=>p(b,de)||b?.startsWith("/")&&S!=="origin"&&!b.includes(":")))throw e.context.logger.error(`Invalid ${S}: ${b}`),e.context.logger.info(`If it's a valid URL, please add ${b} to trustedOrigins in your auth config
|
|
2
|
+
`,`Current list of trustedOrigins: ${l}`),new ke.APIError("FORBIDDEN",{message:`Invalid ${S}`})};f&&!e.context.options.advanced?.disableCSRFCheck&&y(i,"origin"),n&&y(n,"callbackURL"),s&&y(s,"redirectURL"),c&&y(c,"currentURL"),a&&y(a,"errorCallbackURL"),d&&y(s,"newUserCallbackURL")}),re=e=>te(async t=>{let{context:o}=t,r=e(t),i=o.trustedOrigins,n=(c,a)=>c.startsWith("/")?!1:a.includes("*")?me(a)(Ue(c)):c.startsWith(a);r&&((c,a)=>{if(!c)return;if(!i.some(l=>n(c,l)||c?.startsWith("/")&&a!=="origin"&&!c.includes(":")))throw t.context.logger.error(`Invalid ${a}: ${c}`),t.context.logger.info(`If it's a valid URL, please add ${c} to trustedOrigins in your auth config
|
|
3
|
+
`,`Current list of trustedOrigins: ${i}`),new ke.APIError("FORBIDDEN",{message:`Invalid ${a}`})})(r,"callbackURL")});var P=require("better-call"),k=require("zod");var x=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var Be=require("@better-auth/utils/base64");var Me=require("@better-auth/utils/hmac");async function _e(e,t){if(e.context.options.session?.cookieCache?.enabled){let r=Be.base64Url.encode(JSON.stringify({session:t,expiresAt:x(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await(0,Me.createHMAC)("SHA-256","base64urlnopad").sign(e.context.secret,JSON.stringify(t))}),{padding:!1});if(r.length>4093)throw new W("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,r,e.context.authCookies.sessionData.options)}}async function v(e,t,o,r){let i=e.context.authCookies.sessionToken.options,n=o?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:n,...r}),o&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),await _e(e,t),e.context.setNewSession(t),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.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})}var Wt=Object.defineProperty,Qt=Object.defineProperties,Zt=Object.getOwnPropertyDescriptors,qe=Object.getOwnPropertySymbols,Jt=Object.prototype.hasOwnProperty,Kt=Object.prototype.propertyIsEnumerable,ze=(e,t,o)=>t in e?Wt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,Y=(e,t)=>{for(var o in t||(t={}))Jt.call(t,o)&&ze(e,o,t[o]);if(qe)for(var o of qe(t))Kt.call(t,o)&&ze(e,o,t[o]);return e},X=(e,t)=>Qt(e,Zt(t)),Yt=class extends Error{constructor(e,t,o){super(t||e.toString(),{cause:o}),this.status=e,this.statusText=t,this.error=o}},Xt=async(e,t)=>{var o,r,i,n,s,c;let a=t||{},d={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:a,hooks:d};for(let l of t?.plugins||[]){if(l.init){let f=await((o=l.init)==null?void 0:o.call(l,e.toString(),t));a=f.options||a,e=f.url}d.onRequest.push((r=l.hooks)==null?void 0:r.onRequest),d.onResponse.push((i=l.hooks)==null?void 0:i.onResponse),d.onSuccess.push((n=l.hooks)==null?void 0:n.onSuccess),d.onError.push((s=l.hooks)==null?void 0:s.onError),d.onRetry.push((c=l.hooks)==null?void 0:c.onRetry)}return{url:e,options:a,hooks:d}},Fe=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},er=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function tr(e){if(typeof e=="number")return new Fe({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new Fe(e);case"exponential":return new er(e);default:throw new Error("Invalid retry strategy")}}var rr=e=>{let t={},o=r=>typeof r=="function"?r():r;if(e?.auth){if(e.auth.type==="Bearer"){let r=o(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type==="Basic"){let r=o(e.auth.username),i=o(e.auth.password);if(!r||!i)return t;t.authorization=`Basic ${btoa(`${r}:${i}`)}`}else if(e.auth.type==="Custom"){let r=o(e.auth.value);if(!r)return t;t.authorization=`${o(e.auth.prefix)} ${r}`}}return t},We=["get","post","put","patch","delete"];var or=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function ir(e){let t=e.headers.get("content-type"),o=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!t)return"json";let r=t.split(";").shift()||"";return or.test(r)?"json":o.has(r)||r.startsWith("text/")?"text":"blob"}function nr(e){try{return JSON.parse(e),!0}catch{return!1}}function Qe(e){if(e===void 0)return!1;let t=typeof e;return t==="string"||t==="number"||t==="boolean"||t===null?!0:t!=="object"?!1:Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name==="Object"||typeof e.toJSON=="function"}function He(e){try{return JSON.parse(e)}catch{return e}}function Ge(e){return typeof e=="function"}function sr(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<"u"&&Ge(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&Ge(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}function ar(e){let t=new Headers(e?.headers),o=rr(e);for(let[r,i]of Object.entries(o||{}))t.set(r,i);if(!t.has("content-type")){let r=dr(e?.body);r&&t.set("content-type",r)}return t}function dr(e){return Qe(e)?"application/json":null}function cr(e){if(!e?.body)return null;let t=new Headers(e?.headers);return Qe(e.body)&&!t.has("content-type")?JSON.stringify(e.body):e.body}function lr(e,t){var o;if(t?.method)return t.method.toUpperCase();if(e.startsWith("@")){let r=(o=e.split("@")[1])==null?void 0:o.split("/")[0];return We.includes(r)?r.toUpperCase():t?.body?"POST":"GET"}return t?.body?"POST":"GET"}function ur(e,t){let o;return!e?.signal&&e?.timeout&&(o=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:o,clearTimeout:()=>{o&&clearTimeout(o)}}}function pr(e,t){let{baseURL:o,params:r,query:i}=t||{query:{},params:{},baseURL:""},n=e.startsWith("http")?e.split("/").slice(0,3).join("/"):o;if(!n)throw new TypeError(`Invalid URL ${e}. Are you passing in a relative URL but not setting the baseURL?`);if(e.startsWith("@")){let f=e.toString().split("@")[1].split("/")[0];We.includes(f)&&(e=e.replace(`@${f}/`,"/"))}n.endsWith("/")||(n+="/");let[s,c]=e.replace(n,"").split("?"),a=new URLSearchParams(c);for(let[f,p]of Object.entries(i||{}))a.set(f,String(p));if(r)if(Array.isArray(r)){let f=s.split("/").filter(p=>p.startsWith(":"));for(let[p,y]of f.entries()){let b=r[p];s=s.replace(y,b)}}else for(let[f,p]of Object.entries(r))s=s.replace(`:${f}`,String(p));s=s.split("/").map(encodeURIComponent).join("/"),s.startsWith("/")&&(s=s.slice(1));let d=a.size>0?`?${a}`.replace(/\+/g,"%20"):"";return new URL(`${s}${d}`,n)}var w=async(e,t)=>{var o,r,i,n,s,c,a,d;let{hooks:l,url:f,options:p}=await Xt(e,t),y=sr(p),b=new AbortController,S=(o=p.signal)!=null?o:b.signal,pe=pr(f,p),de=cr(p),ce=ar(p),L=lr(f,p),h=X(Y({},p),{url:pe,headers:ce,body:de,method:L,signal:S});for(let C of l.onRequest)if(C){let I=await C(h);I instanceof Object&&(h=I)}("pipeTo"in h&&typeof h.pipeTo=="function"||typeof((r=t?.body)==null?void 0:r.pipe)=="function")&&("duplex"in h||(h.duplex="half"));let{clearTimeout:xe}=ur(p,b),R=await y(h.url,h);xe();let De={response:R,request:h};for(let C of l.onResponse)if(C){let I=await C(X(Y({},De),{response:(i=t?.hookOptions)!=null&&i.cloneResponse?R.clone():R}));I instanceof Response?R=I:I instanceof Object&&(R=I.response)}if(R.ok){if(!(h.method!=="HEAD"))return{data:"",error:null};let I=ir(R),F={data:"",response:R,request:h};if(I==="json"||I==="text"){let H=await R.text(),Ct=await((n=h.jsonParser)!=null?n:He)(H);F.data=Ct}else F.data=await R[I]();h?.output&&h.output&&!h.disableValidation&&(F.data=h.output.parse(F.data));for(let H of l.onSuccess)H&&await H(X(Y({},F),{response:(s=t?.hookOptions)!=null&&s.cloneResponse?R.clone():R}));return t?.throw?F.data:{data:F.data,error:null}}let xt=(c=t?.jsonParser)!=null?c:He,Ce=await R.text(),be=nr(Ce)?await xt(Ce):{},Dt={response:R,request:h,error:X(Y({},be),{status:R.status,statusText:R.statusText})};for(let C of l.onError)C&&await C(X(Y({},Dt),{response:(a=t?.hookOptions)!=null&&a.cloneResponse?R.clone():R}));if(t?.retry){let C=tr(t.retry),I=(d=t.retryAttempt)!=null?d:0;if(await C.shouldAttemptRetry(I,R)){for(let H of l.onRetry)H&&await H(De);let F=C.getDelay(I);return await new Promise(H=>setTimeout(H,F)),await w(e,X(Y({},t),{retryAttempt:I+1}))}}if(t?.throw)throw new Yt(R.status,R.statusText,be);return{data:null,error:X(Y({},be),{status:R.status,statusText:R.statusText})}};var rt=require("better-call"),Q=require("jose");var Ze=require("@better-auth/utils/hash"),Je=require("@better-auth/utils/base64");async function Ke(e){let t=await(0,Ze.createHash)("SHA-256").digest(e);return Je.base64Url.encode(new Uint8Array(t),{padding:!1})}function ge(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?x(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function E({id:e,options:t,authorizationEndpoint:o,state:r,codeVerifier:i,scopes:n,claims:s,redirectURI:c,duration:a}){let d=new URL(o);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",r),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),i){let l=await Ke(i);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((f,p)=>(f[p]=null,f),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return a&&d.searchParams.set("duration",a),d}var mr=require("jose");async function A({code:e,codeVerifier:t,redirectURI:o,options:r,tokenEndpoint:i,authentication:n}){let s=new URLSearchParams,c={"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),t&&s.set("code_verifier",t),s.set("redirect_uri",o),n==="basic"){let f=btoa(`${r.clientId}:${r.clientSecret}`);c.authorization=`Basic ${f}`}else s.set("client_id",r.clientId),s.set("client_secret",r.clientSecret);let{data:a,error:d}=await w(i,{method:"POST",body:s,headers:c});if(d)throw d;return ge(a)}var M=require("zod"),Se=require("better-call");var br=require("@better-auth/utils/hash"),Ar=require("@noble/ciphers/chacha"),Oe=require("@noble/ciphers/utils"),Rr=require("@noble/ciphers/webcrypto");var gr=require("@better-auth/utils/hash");var Ye=require("jose");async function Xe(e,t,o=3600){return await new Ye.SignJWT(e).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+o).sign(new TextEncoder().encode(t))}var hr=require("@noble/hashes/scrypt"),wr=require("uncrypto"),yr=require("@better-auth/utils/hex");var et=require("@better-auth/utils/random"),B=(0,et.createRandomStringGenerator)("a-z","0-9","A-Z","-_");async function he(e,t){let o=e.body?.callbackURL||(e.query?.currentURL?$e(e.query?.currentURL):"")||e.context.options.baseURL;if(!o)throw new Se.APIError("BAD_REQUEST",{message:"callbackURL is required"});let r=B(128),i=B(32),n=JSON.stringify({callbackURL:o,codeVerifier:r,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,newUserURL:e.body?.newUserCallbackURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:s});if(!c)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 Se.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:r}}async function tt(e){let t=e.query.state||e.body.state,o=await e.context.internalAdapter.findVerificationValue(t);if(!o)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let r=M.z.object({callbackURL:M.z.string(),codeVerifier:M.z.string(),errorURL:M.z.string().optional(),newUserURL:M.z.string().optional(),expiresAt:M.z.number(),link:M.z.object({email:M.z.string(),userId:M.z.string()}).optional()}).parse(JSON.parse(o.value));if(r.errorURL||(r.errorURL=`${e.context.baseURL}/error`),r.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(o.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(o.id),r}var ot=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:o,scopes:r,redirectURI:i}){let n=r||["email","name"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${e.redirectURI||i}&scope=${n.join(" ")}&state=${o}&response_mode=form_post`)},validateAuthorizationCode:async({code:o,codeVerifier:r,redirectURI:i})=>A({code:o,codeVerifier:r,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async verifyIdToken(o,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(o,r);let i=(0,Q.decodeProtectedHeader)(o),{kid:n,alg:s}=i;if(!n||!s)return!1;let c=await Er(n),{payload:a}=await(0,Q.jwtVerify)(o,c,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.appBundleIdentifier||e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),r&&a.nonce!==r?!1:!!a},async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);if(!o.idToken)return null;let r=(0,Q.decodeJwt)(o.idToken);if(!r)return null;let i=r.user?`${r.user.name.firstName} ${r.user.name.lastName}`:r.email,n=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:i,emailVerified:!1,email:r.email,...n},data:r}}}},Er=async e=>{let t="https://appleid.apple.com",o="/auth/keys",{data:r}=await w(`${t}${o}`);if(!r?.keys)throw new rt.APIError("BAD_REQUEST",{message:"Keys not found"});let i=r.keys.find(n=>n.kid===e);if(!i)throw new Error(`JWK with kid ${e} not found`);return await(0,Q.importJWK)(i,i.alg)};var it=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:o,redirectURI:r}){let i=o||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||r)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:o})=>A({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:r}=await w("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(r)return null;if(o.avatar===null){let n=o.discriminator==="0"?Number(BigInt(o.id)>>BigInt(22))%6:parseInt(o.discriminator)%5;o.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=o.avatar.startsWith("a_")?"gif":"png";o.image_url=`https://cdn.discordapp.com/avatars/${o.id}/${o.avatar}.${n}`}let i=await e.mapProfileToUser?.(o);return{user:{id:o.id,name:o.display_name||o.username||"",email:o.email,emailVerified:o.verified,image:o.image_url,...i},data:o}}});var nt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:o,redirectURI:r}){let i=o||["email","public_profile"];return e.scope&&i.push(...e.scope),await E({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:r})},validateAuthorizationCode:async({code:t,redirectURI:o})=>A({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:r}=await w("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(r)return null;let i=await e.mapProfileToUser?.(o);return{user:{id:o.id,name:o.name,email:o.email,image:o.picture.data.url,emailVerified:o.email_verified,...i},data:o}}});var st=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:o,scopes:r,codeVerifier:i,redirectURI:n}){let s=r||["user:email"];return e.scope&&s.push(...e.scope),E({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:r})=>A({code:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t}),async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);let{data:r,error:i}=await w("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${o.accessToken}`}});if(i)return null;let n=!1,{data:s}=await w("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${o.accessToken}`,"User-Agent":"better-auth"}});s&&(r.email=(s.find(a=>a.primary)??s[0])?.email,n=s.find(a=>a.email===r.email)?.verified??!1);let c=await e.mapProfileToUser?.(r);return{user:{id:r.id.toString(),name:r.name||r.login,email:r.email,image:r.avatar_url,emailVerified:n,...c},data:r}}}};var at=require("jose");var ve=["info","success","warn","error","debug"];function Tr(e,t){return ve.indexOf(t)<=ve.indexOf(e)}var q={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",fg:{black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},bg:{black:"\x1B[40m",red:"\x1B[41m",green:"\x1B[42m",yellow:"\x1B[43m",blue:"\x1B[44m",magenta:"\x1B[45m",cyan:"\x1B[46m",white:"\x1B[47m"}},Ur={info:q.fg.blue,success:q.fg.green,warn:q.fg.yellow,error:q.fg.red,debug:q.fg.magenta},kr=(e,t)=>{let o=new Date().toISOString();return`${q.dim}${o}${q.reset} ${Ur[e]}${e.toUpperCase()}${q.reset} ${q.bright}[Better Auth]:${q.reset} ${t}`},_r=e=>{let t=e?.disabled!==!0,o=e?.level??"error",r=(i,n,s=[])=>{if(!t||!Tr(o,i))return;let c=kr(i,n);if(!e||typeof e.log!="function"){i==="error"?console.error(c,...s):i==="warn"?console.warn(c,...s):console.log(c,...s);return}e.log(i==="success"?"info":i,c,...s)};return Object.fromEntries(ve.map(i=>[i,(...[n,...s])=>r(i,n,s)]))},V=_r();var dt=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:o,codeVerifier:r,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw V.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new W("CLIENT_ID_AND_SECRET_REQUIRED");if(!r)throw new W("codeVerifier is required for Google");let n=o||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await E({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:r,redirectURI:i});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),e.display&&s.searchParams.set("display",e.display),e.hd&&s.searchParams.set("hd",e.hd),s},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:r})=>A({code:t,codeVerifier:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,o);let r=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:i}=await w(r);return i?i.aud===e.clientId&&i.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let o=(0,at.decodeJwt)(t.idToken),r=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.name,email:o.email,image:o.picture,emailVerified:o.email_verified,...r},data:o}}});var ct=require("jose"),lt=e=>{let t=e.tenantId||"common",o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),E({id:"microsoft",options:e,authorizationEndpoint:o,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return A({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:r})},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);if(!i.idToken)return null;let n=(0,ct.decodeJwt)(i.idToken),s=e.profilePhotoSize||48;await w(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let l=await a.response.clone().arrayBuffer(),f=Buffer.from(l).toString("base64");n.picture=`data:image/jpeg;base64, ${f}`}catch(d){V.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0,...c},data:n}}}};var ut=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:o,codeVerifier:r,redirectURI:i}){let n=o||["user-read-email"];return e.scope&&n.push(...e.scope),E({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:r,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:r})=>A({code:t,codeVerifier:o,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:r}=await w("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(o);return{user:{id:o.id,name:o.display_name,email:o.email,image:o.images[0]?.url,emailVerified:!1,...i},data:o}}});var oe={isAction:!1};var pt=require("@better-auth/utils/random"),mt=e=>(0,pt.createRandomStringGenerator)("a-z","A-Z","0-9")(e||32);var ft=require("jose"),gt=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:o,redirectURI:r}){let i=o||["user:read:email","openid"];return e.scope&&i.push(...e.scope),E({id:"twitch",redirectURI:r,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:o})=>A({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let o=t.idToken;if(!o)return V.error("No idToken found in token"),null;let r=(0,ft.decodeJwt)(o),i=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.preferred_username,email:r.email,image:r.picture,emailVerified:!1,...i},data:r}}});var ht=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let o=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&o.push(...e.scope),E({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:o,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:r})=>A({code:t,codeVerifier:o,authentication:"basic",redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:r}=await w("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(o);return{user:{id:o.data.id,name:o.data.name,email:o.data.username||null,image:o.data.profile_image_url,emailVerified:o.data.verified||!1,...i},data:o}}});var wt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:o,scopes:r,codeVerifier:i,redirectURI:n})=>{let s=r||["account_info.read"];return e.scope&&s.push(...e.scope),await E({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:o,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:o,codeVerifier:r,redirectURI:i})=>await A({code:o,codeVerifier:r,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(o){if(e.getUserInfo)return e.getUserInfo(o);let{data:r,error:i}=await w("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${o.accessToken}`}});if(i)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.account_id,name:r.name?.display_name,email:r.email,emailVerified:r.email_verified||!1,image:r.profile_photo_url,...n},data:r}}}};var yt=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",o="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:r,scopes:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await E({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:r,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:i})=>await A({code:r,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:o}),async getUserInfo(r){let{data:i,error:n}=await w("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});if(n)return null;let s=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture,...s},data:i}}}};var Pe=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Or=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:Pe(`${t}/oauth/authorize`),tokenEndpoint:Pe(`${t}/oauth/token`),userinfoEndpoint:Pe(`${t}/api/v4/user`)}},bt=e=>{let{authorizationEndpoint:t,tokenEndpoint:o,userinfoEndpoint:r}=Or(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let l=c||["read_user"];return e.scope&&l.push(...e.scope),await E({id:i,options:e,authorizationEndpoint:t,scopes:l,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>A({code:s,redirectURI:e.redirectURI||c,options:e,codeVerifier:a,tokenEndpoint:o}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:c,error:a}=await w(r,{headers:{authorization:`Bearer ${s.accessToken}`}});if(a||c.state!=="active"||c.locked)return null;let d=await e.mapProfileToUser?.(c);return{user:{id:c.id.toString(),name:c.name??c.username,email:c.email,image:c.avatar_url,emailVerified:!0,...d},data:c}}}};var At=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:o,redirectURI:r}){let i=o||["identity"];return e.scope&&i.push(...e.scope),E({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:i,state:t,redirectURI:r,duration:e.duration})},validateAuthorizationCode:async({code:t,redirectURI:o})=>{let r=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:e.redirectURI||o}),i={"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:n,error:s}=await w("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:i,body:r.toString()});if(s)throw s;return ge(n)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:o,error:r}=await w("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(r)return null;let i=await e.mapProfileToUser?.(o);return{user:{id:o.id,name:o.name,email:o.oauth_client_id,emailVerified:o.has_verified_email,image:o.icon_img?.split("?")[0],...i},data:o}}});var Rt=require("zod"),Sr={apple:ot,discord:it,facebook:nt,github:st,microsoft:lt,google:dt,spotify:ut,twitch:gt,twitter:ht,dropbox:wt,linkedin:yt,gitlab:bt,reddit:At},Ie=Object.keys(Sr),Et=Rt.z.enum(Ie,{description:"OAuth2 provider to use"});var j=require("zod");var ie=require("better-call");var z=require("better-call");var Z=require("zod");function Tt(e){try{return JSON.parse(e)}catch{return null}}var u={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",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action.",FAILED_TO_UNLINK_LAST_ACCOUNT:"You can't unlink your last account",ACCOUNT_NOT_FOUND:"Account not found"};var Ut=require("@better-auth/utils/hmac"),kt=require("@better-auth/utils/base64"),_t=require("@better-auth/utils/binary"),Ot=()=>m("/get-session",{method:"GET",query:Z.z.optional(Z.z.object({disableCookieCache:Z.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(Z.z.string().transform(e=>e==="true")).optional(),disableRefresh:Z.z.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let o=e.getCookie(e.context.authCookies.sessionData.name),r=o?Tt(_t.binary.decode(kt.base64.decode(o))):null;if(r&&!await(0,Ut.createHMAC)("SHA-256","base64urlnopad").verify(e.context.secret,JSON.stringify(r.session),r.signature))return $(e),e.json(null);let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(r?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let l=r.session;if(r.expiresAt<Date.now()||l.session.expiresAt<new Date){let p=e.context.authCookies.sessionData.name;e.setCookie(p,"",{maxAge:0})}else return e.json(l)}let n=await e.context.internalAdapter.findSession(t);if(e.context.session=n,!n||n.session.expiresAt<new Date)return $(e),n&&await e.context.internalAdapter.deleteSession(n.session.token),e.json(null);if(i||e.query?.disableRefresh)return e.json(n);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let l=await e.context.internalAdapter.updateSession(n.session.token,{expiresAt:x(e.context.sessionConfig.expiresIn,"sec")});if(!l)return $(e),e.json(null,{status:401});let f=(l.expiresAt.valueOf()-Date.now())/1e3;return await v(e,{session:l,user:n.user},!1,{maxAge:f}),e.json({session:l,user:n.user})}return await _e(e,n),e.json(n)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new z.APIError("INTERNAL_SERVER_ERROR",{message:u.FAILED_TO_GET_SESSION})}}),ee=async(e,t)=>{if(e.context.session)return e.context.session;let o=await Ot()({...e,_flag:"json",headers:e.headers,query:t}).catch(r=>null);return e.context.session=o,o},N=te(async e=>{let t=await ee(e);if(!t?.session)throw new z.APIError("UNAUTHORIZED");return{session:t}}),St=te(async e=>{let t=await ee(e);if(!t?.session)throw new z.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let o=e.context.sessionConfig.freshAge,r=t.session.updatedAt?.valueOf()||t.session.createdAt.valueOf();if(!(Date.now()-r<o*1e3))throw new z.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}});var vr=m("/revoke-session",{method:"POST",body:Z.z.object({token:Z.z.string({description:"The token to revoke"})}),use:[N],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let t=e.body.token,o=await e.context.internalAdapter.findSession(t);if(!o)throw new z.APIError("BAD_REQUEST",{message:"Session not found"});if(o.session.userId!==e.context.session.user.id)throw new z.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(r){throw e.context.logger.error(r&&typeof r=="object"&&"name"in r?r.name:"",r),new z.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Pr=m("/revoke-sessions",{method:"POST",use:[N],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new z.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Ir=m("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[N],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw new z.APIError("UNAUTHORIZED");let i=(await e.context.internalAdapter.listSessions(t.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.token!==e.context.session.session.token);return await Promise.all(i.map(n=>e.context.internalAdapter.deleteSession(n.token))),e.json({status:!0})});var vt=require("jose");async function G(e,t,o){return await Xe({email:t.toLowerCase(),updateTo:o},e)}async function Lr(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new ie.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let o=await G(e.context.secret,t.email),r=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:r,token:o},e.request)}var xr=m("/send-verification-email",{method:"POST",query:j.z.object({currentURL:j.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:j.z.object({email:j.z.string({description:"The email to send the verification email to"}).email(),callbackURL:j.z.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new ie.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,o=await e.context.internalAdapter.findUserByEmail(t);if(!o)throw new ie.APIError("BAD_REQUEST",{message:u.USER_NOT_FOUND});return await Lr(e,o.user),e.json({status:!0})}),Dr=m("/verify-email",{method:"GET",query:j.z.object({token:j.z.string({description:"The token to verify the email"}),callbackURL:j.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[re(e=>e.query.callbackURL)],metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(c){throw e.query.callbackURL?e.query.callbackURL.includes("?")?e.redirect(`${e.query.callbackURL}&error=${c}`):e.redirect(`${e.query.callbackURL}?error=${c}`):new ie.APIError("UNAUTHORIZED",{message:c})}let{token:o}=e.query,r;try{r=await(0,vt.jwtVerify)(o,new TextEncoder().encode(e.context.secret),{algorithms:["HS256"]})}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let n=j.z.object({email:j.z.string().email(),updateTo:j.z.string().optional()}).parse(r.payload),s=await e.context.internalAdapter.findUserByEmail(n.email);if(!s)return t("user_not_found");if(n.updateTo){let c=await ee(e);if(!c){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(c.user.email!==n.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo,emailVerified:!1}),d=await G(e.context.secret,n.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${d}`,token:d},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:{id:a.id,email:a.email,name:a.name,image:a.image,emailVerified:a.emailVerified,createdAt:a.createdAt,updatedAt:a.updatedAt}})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification){let c=await ee(e);if(!c||c.user.email!==n.email){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new ie.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await v(e,{session:a,user:s.user})}}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});async function we(e,{userInfo:t,account:o,callbackURL:r}){let i=await e.context.internalAdapter.findOAuthUser(t.email.toLowerCase(),o.accountId,o.providerId).catch(a=>{throw V.error(`Better auth was unable to query your database.
|
|
4
|
+
Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=i?.user,s=!n;if(i){let a=i.accounts.find(d=>d.providerId===o.providerId);if(a){let d=Object.fromEntries(Object.entries({accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt}).filter(([l,f])=>f!==void 0));Object.keys(d).length>0&&await e.context.internalAdapter.updateAccount(a.id,d)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(o.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Te&&V.warn(`User already exist but account isn't linked to ${o.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:o.providerId,accountId:t.id.toString(),userId:i.user.id,accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt,scope:o.scope})}catch(f){return V.error("Unable to link account",f),{error:"unable to link account",data:null}}}}else try{if(n=await e.context.internalAdapter.createOAuthUser({...t,email:t.email.toLowerCase(),id:void 0},{accessToken:o.accessToken,idToken:o.idToken,refreshToken:o.refreshToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt,scope:o.scope,providerId:o.providerId,accountId:t.id.toString()}).then(a=>a?.user),!t.emailVerified&&n&&e.context.options.emailVerification?.sendOnSignUp){let a=await G(e.context.secret,n.email),d=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${r}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:n,url:d,token:a},e.request)}}catch(a){return a instanceof U.APIError?{error:a.message,data:null,isRegister:!1}:{error:"unable to create user",data:null,isRegister:!1}}if(!n)return{error:"unable to create user",data:null,isRegister:!1};let c=await e.context.internalAdapter.createSession(n.id,e.request);return c?{data:{session:c,user:n},error:null,isRegister:s}:{error:"unable to create session",data:null,isRegister:!1}}var Cr=m("/sign-in/social",{method:"POST",query:k.z.object({currentURL:k.z.string().optional()}).optional(),body:k.z.object({callbackURL:k.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:k.z.string().optional(),errorCallbackURL:k.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:Et,disableRedirect:k.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:k.z.optional(k.z.object({token:k.z.string({description:"ID token from the provider"}),nonce:k.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:k.z.string({description:"Access token from the provider"}).optional(),refreshToken:k.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:k.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new P.APIError("NOT_FOUND",{message:u.PROVIDER_NOT_FOUND});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new P.APIError("NOT_FOUND",{message:u.ID_TOKEN_NOT_SUPPORTED});let{token:n,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(n,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new P.APIError("UNAUTHORIZED",{message:u.INVALID_TOKEN});let a=await t.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new P.APIError("UNAUTHORIZED",{message:u.FAILED_TO_GET_USER_INFO});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new P.APIError("UNAUTHORIZED",{message:u.USER_EMAIL_NOT_FOUND});let d=await we(e,{userInfo:{email:a.user.email,id:a.user.id,name:a.user.name||"",image:a.user.image,emailVerified:a.user.emailVerified||!1},account:{providerId:t.id,accountId:a.user.id,accessToken:e.body.idToken.accessToken}});if(d.error)throw new P.APIError("UNAUTHORIZED",{message:d.error});return await v(e,d.data),e.json({redirect:!1,token:d.data.session.token,url:void 0,user:{id:d.data.user.id,email:d.data.user.email,name:d.data.user.name,image:d.data.user.image,emailVerified:d.data.user.emailVerified,createdAt:d.data.user.createdAt,updatedAt:d.data.user.updatedAt}})}let{codeVerifier:o,state:r}=await he(e),i=await t.createAuthorizationURL({state:r,codeVerifier:o,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!e.body.disableRedirect})}),jr=m("/sign-in/email",{method:"POST",body:k.z.object({email:k.z.string({description:"Email of the user"}),password:k.z.string({description:"Password of the user"}),callbackURL:k.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:k.z.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new P.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:o}=e.body;if(!k.z.string().email().safeParse(t).success)throw new P.APIError("BAD_REQUEST",{message:u.INVALID_EMAIL});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(o),e.context.logger.error("User not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:u.INVALID_EMAIL_OR_PASSWORD});let n=i.accounts.find(d=>d.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:u.INVALID_EMAIL_OR_PASSWORD});let s=n?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:u.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:s,password:o}))throw e.context.logger.error("Invalid password"),new P.APIError("UNAUTHORIZED",{message:u.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new P.APIError("UNAUTHORIZED",{message:u.EMAIL_NOT_VERIFIED});let d=await G(e.context.secret,i.user.email),l=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:i.user,url:l,token:d},e.request),new P.APIError("FORBIDDEN",{message:u.EMAIL_NOT_VERIFIED})}let a=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new P.APIError("UNAUTHORIZED",{message:u.FAILED_TO_CREATE_SESSION});return await v(e,{session:a,user:i.user},e.body.rememberMe===!1),e.json({redirect:!!e.body.callbackURL,token:a.token,url:e.body.callbackURL,user:{id:i.user.id,email:i.user.email,name:i.user.name,image:i.user.image,emailVerified:i.user.emailVerified,createdAt:i.user.createdAt,updatedAt:i.user.updatedAt}})});var ne=require("zod");var ye=ne.z.object({code:ne.z.string().optional(),error:ne.z.string().optional(),error_description:ne.z.string().optional(),state:ne.z.string().optional()}),Vr=m("/callback/:id",{method:["GET","POST"],body:ye.optional(),query:ye.optional(),metadata:oe},async e=>{let t;try{if(e.method==="GET")t=ye.parse(e.query);else if(e.method==="POST")t=ye.parse(e.body);else throw new Error("Unsupported method")}catch(L){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",L),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:o,error:r,state:i,error_description:n}=t;if(!i)throw e.context.logger.error("State not found",r),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!o)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${r||"no_code"}&error_description=${n}`);let s=e.context.socialProviders.find(L=>L.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:c,callbackURL:a,link:d,errorURL:l,newUserURL:f}=await tt(e),p;try{p=await s.validateAuthorizationCode({code:o,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${s.id}`})}catch(L){throw e.context.logger.error("",L),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let y=await s.getUserInfo(p).then(L=>L?.user);function b(L){let h=l||a||`${e.context.baseURL}/error`;throw h.includes("?")?h=`${h}&error=${L}`:h=`${h}?error=${L}`,e.redirect(h)}if(!y)return e.context.logger.error("Unable to get user info"),b("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."),b("email_not_found");if(!a)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(d){if(d.email!==y.email.toLowerCase())return b("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:s.id,accountId:y.id}))return b("unable_to_link_account");let h;try{h=a.toString()}catch{h=a}throw e.redirect(h)}let S=await we(e,{userInfo:{...y,email:y.email,name:y.name||y.email},account:{providerId:s.id,accountId:y.id,...p,scope:p.scopes?.join(",")},callbackURL:a});if(S.error)return e.context.logger.error(S.error.split(" ").join("_")),b(S.error.split(" ").join("_"));let{session:pe,user:de}=S.data;await v(e,{session:pe,user:de});let ce;try{ce=(S.isRegister&&f||a).toString()}catch{ce=S.isRegister&&f||a}throw e.redirect(ce)});var As=require("zod");var Pt=require("better-call");var Nr=m("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw $(e),new Pt.APIError("BAD_REQUEST",{message:u.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(t),$(e),e.json({success:!0})});var D=require("zod");var se=require("better-call");function It(e,t,o){let r=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return o&&Object.entries(o).forEach(([i,n])=>r.searchParams.set(i,n)),r.href}function $r(e,t,o){let r=new URL(t,e.baseURL);return o&&Object.entries(o).forEach(([i,n])=>r.searchParams.set(i,n)),r.href}var Br=m("/forget-password",{method:"POST",body:D.z.object({email:D.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:D.z.string({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new se.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:o}=e.body,r=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!r)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let i=60*60*1,n=x(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||i,"sec"),s=mt(24);await e.context.internalAdapter.createVerificationValue({value:r.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:n});let c=`${e.context.baseURL}/reset-password/${s}?callbackURL=${o}`;return await e.context.options.emailAndPassword.sendResetPassword({user:r.user,url:c,token:s},e.request),e.json({status:!0})}),Mr=m("/reset-password/:token",{method:"GET",query:D.z.object({callbackURL:D.z.string({description:"The URL to redirect the user to reset their password"})}),use:[re(e=>e.query.callbackURL)],metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:o}=e.query;if(!t||!o)throw e.redirect(It(e.context,o,{error:"INVALID_TOKEN"}));let r=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!r||r.expiresAt<new Date?e.redirect(It(e.context,o,{error:"INVALID_TOKEN"})):e.redirect($r(e.context,o,{token:t}))}),qr=m("/reset-password",{query:D.z.optional(D.z.object({token:D.z.string().optional(),currentURL:D.z.string().optional()})),method:"POST",body:D.z.object({newPassword:D.z.string({description:"The new password to set"}),token:D.z.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new se.APIError("BAD_REQUEST",{message:u.INVALID_TOKEN});let{newPassword:o}=e.body,r=e.context.password?.config.minPasswordLength,i=e.context.password?.config.maxPasswordLength;if(o.length<r)throw new se.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_SHORT});if(o.length>i)throw new se.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_LONG});let n=`reset-password:${t}`,s=await e.context.internalAdapter.findVerificationValue(n);if(!s||s.expiresAt<new Date)throw new se.APIError("BAD_REQUEST",{message:u.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(s.id);let c=s.value,a=await e.context.password.hash(o);return(await e.context.internalAdapter.findAccounts(c)).find(f=>f.providerId==="credential")?(await e.context.internalAdapter.updatePassword(c,a),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:c,providerId:"credential",password:a,accountId:c}),e.json({status:!0}))});var O=require("zod");var _=require("better-call");var g=require("zod"),zr=require("better-call"),Ls=g.z.object({id:g.z.string(),providerId:g.z.string(),accountId:g.z.string(),userId:g.z.string(),accessToken:g.z.string().nullish(),refreshToken:g.z.string().nullish(),idToken:g.z.string().nullish(),accessTokenExpiresAt:g.z.date().nullish(),refreshTokenExpiresAt:g.z.date().nullish(),scope:g.z.string().nullish(),password:g.z.string().nullish(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date)}),xs=g.z.object({id:g.z.string(),email:g.z.string().transform(e=>e.toLowerCase()),emailVerified:g.z.boolean().default(!1),name:g.z.string(),image:g.z.string().nullish(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date)}),Ds=g.z.object({id:g.z.string(),userId:g.z.string(),expiresAt:g.z.date(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date),token:g.z.string(),ipAddress:g.z.string().nullish(),userAgent:g.z.string().nullish()}),Cs=g.z.object({id:g.z.string(),value:g.z.string(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date),expiresAt:g.z.date(),identifier:g.z.string()});var Hr=m("/change-password",{method:"POST",body:O.z.object({newPassword:O.z.string({description:"The new password to set"}),currentPassword:O.z.string({description:"The current password"}),revokeOtherSessions:O.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[N],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:o,revokeOtherSessions:r}=e.body,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new _.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_SHORT});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new _.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_LONG});let a=(await e.context.internalAdapter.findAccounts(i.user.id)).find(p=>p.providerId==="credential"&&p.password);if(!a||!a.password)throw new _.APIError("BAD_REQUEST",{message:u.CREDENTIAL_ACCOUNT_NOT_FOUND});let d=await e.context.password.hash(t);if(!await e.context.password.verify({hash:a.password,password:o}))throw new _.APIError("BAD_REQUEST",{message:u.INVALID_PASSWORD});await e.context.internalAdapter.updateAccount(a.id,{password:d});let f=null;if(r){await e.context.internalAdapter.deleteSessions(i.user.id);let p=await e.context.internalAdapter.createSession(i.user.id,e.headers);if(!p)throw new _.APIError("INTERNAL_SERVER_ERROR",{message:u.FAILED_TO_GET_SESSION});await v(e,{session:p,user:i.user}),f=p.token}return e.json({token:f,user:{id:i.user.id,email:i.user.email,name:i.user.name,image:i.user.image,emailVerified:i.user.emailVerified,createdAt:i.user.createdAt,updatedAt:i.user.updatedAt}})}),Gr=m("/set-password",{method:"POST",body:O.z.object({newPassword:O.z.string()}),metadata:{SERVER_ONLY:!0},use:[N]},async e=>{let{newPassword:t}=e.body,o=e.context.session,r=e.context.password.config.minPasswordLength;if(t.length<r)throw e.context.logger.error("Password is too short"),new _.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_SHORT});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new _.APIError("BAD_REQUEST",{message:u.PASSWORD_TOO_LONG});let s=(await e.context.internalAdapter.findAccounts(o.user.id)).find(a=>a.providerId==="credential"&&a.password),c=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:o.user.id,providerId:"credential",accountId:o.user.id,password:c}),e.json({status:!0});throw new _.APIError("BAD_REQUEST",{message:"user already has a password"})}),Wr=m("/delete-user",{method:"POST",use:[N],body:O.z.object({callbackURL:O.z.string().optional(),password:O.z.string().optional(),token:O.z.string().optional()}),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 _.APIError("NOT_FOUND");let t=e.context.session;if(e.body.password){let n=(await e.context.internalAdapter.findAccounts(t.user.id)).find(c=>c.providerId==="credential"&&c.password);if(!n||!n.password)throw new _.APIError("BAD_REQUEST",{message:u.CREDENTIAL_ACCOUNT_NOT_FOUND});if(!await e.context.password.verify({hash:n.password,password:e.body.password}))throw new _.APIError("BAD_REQUEST",{message:u.INVALID_PASSWORD})}else if(e.context.options.session?.freshAge){let i=t.session.createdAt.getTime(),n=e.context.options.session.freshAge;if(Date.now()-i>n)throw new _.APIError("BAD_REQUEST",{message:u.SESSION_EXPIRED})}if(e.body.token)return await Lt({...e,query:{token:e.body.token}}),e.json({success:!0,message:"User deleted"});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let i=B(32,"0-9","a-z");await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${i}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let n=`${e.context.baseURL}/delete-user/callback?token=${i}&callbackURL=${e.body.callbackURL||"/"}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:n,token:i},e.request),e.json({success:!0,message:"Verification email sent"})}let o=e.context.options.user.deleteUser?.beforeDelete;o&&await o(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),$(e);let r=e.context.options.user.deleteUser?.afterDelete;return r&&await r(t.user,e.request),e.json({success:!0,message:"User deleted"})}),Lt=m("/delete-user/callback",{method:"GET",query:O.z.object({token:O.z.string(),callbackURL:O.z.string().optional()}),use:[re(e=>e.query.callbackURL)]},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new _.APIError("NOT_FOUND");let t=await ee(e);if(!t)throw new _.APIError("NOT_FOUND",{message:u.FAILED_TO_GET_USER_INFO});let o=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!o||o.expiresAt<new Date)throw o&&await e.context.internalAdapter.deleteVerificationValue(o.id),new _.APIError("NOT_FOUND",{message:u.INVALID_TOKEN});if(o.value!==t.user.id)throw new _.APIError("NOT_FOUND",{message:u.INVALID_TOKEN});let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),await e.context.internalAdapter.deleteVerificationValue(o.id),$(e);let i=e.context.options.user.deleteUser?.afterDelete;if(i&&await i(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||"/");return e.json({success:!0,message:"User deleted"})}),Qr=m("/change-email",{method:"POST",query:O.z.object({currentURL:O.z.string().optional()}).optional(),body:O.z.object({newEmail:O.z.string({description:"The new email to set"}).email(),callbackURL:O.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[N],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 _.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new _.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new _.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let i=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new _.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let o=await G(e.context.secret,e.context.session.user.email,e.body.newEmail),r=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:r,token:o},e.request),e.json({status:!0})});var Zr=(e="Unknown")=>`<!DOCTYPE html>
|
|
5
5
|
<html lang="en">
|
|
6
6
|
<head>
|
|
7
7
|
<meta charset="UTF-8">
|
|
@@ -81,4 +81,4 @@ Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
|
|
|
81
81
|
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
82
82
|
</div>
|
|
83
83
|
</body>
|
|
84
|
-
</html>`,Jr=m("/error",{method:"GET",metadata:{...oe,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string"}}}}}}}},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Zr(t),{headers:{"Content-Type":"text/html"}})});var Kr=m("/ok",{method:"GET",metadata:{...oe,openapi:{description:"Check if the API is working",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean"}}}}}}}}}},async e=>e.json({ok:!0}));var Yr=require("zod");var Xr=require("better-call");var J=require("zod");var ue=require("better-call");var eo=m("/list-accounts",{method:"GET",use:[N],metadata:{openapi:{description:"List all accounts linked to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},provider:{type:"string"}}}}}}}}}}},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(o=>({id:o.id,provider:o.providerId,createdAt:o.createdAt,updatedAt:o.updatedAt,accountId:o.accountId,scopes:o.scope?.split(",")||[]})))}),to=m("/link-social",{method:"POST",requireHeaders:!0,query:J.z.object({currentURL:J.z.string().optional()}).optional(),body:J.z.object({callbackURL:J.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:J.z.enum(Ie,{description:"The OAuth2 provider to use"})}),use:[N],metadata:{openapi:{description:"Link a social account to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}},required:["url","redirect"]}}}}}}}},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(c=>c.providerId===e.body.provider))throw new ue.APIError("BAD_REQUEST",{message:u.SOCIAL_ACCOUNT_ALREADY_LINKED});let i=e.context.socialProviders.find(c=>c.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new ue.APIError("NOT_FOUND",{message:u.PROVIDER_NOT_FOUND});let n=await he(e,{userId:t.user.id,email:t.user.email}),s=await i.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:s.toString(),redirect:!0})}),ro=m("/unlink-account",{method:"POST",body:J.z.object({providerId:J.z.string()}),use:[St]},async e=>{let t=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(t.length===1)throw new ue.APIError("BAD_REQUEST",{message:u.FAILED_TO_UNLINK_LAST_ACCOUNT});if(!t.find(o=>o.providerId===e.body.providerId))throw new ue.APIError("BAD_REQUEST",{message:u.ACCOUNT_NOT_FOUND});return await e.context.internalAdapter.deleteAccount(e.body.providerId,e.context.session.user.id),e.json({status:!0})});var Ga=require("defu"),U=require("better-call");var Le=["email-verification","sign-in","forget-password"],oo=e=>{let t={expiresIn:300,otpLength:6,...e},r={OTP_EXPIRED:"otp expired",INVALID_OTP:"invalid otp",INVALID_EMAIL:"invalid email",USER_NOT_FOUND:"user not found"};return{id:"email-otp",endpoints:{sendVerificationOTP:m("/email-otp/send-verification-otp",{method:"POST",body:T.z.object({email:T.z.string({description:"Email address to send the OTP"}),type:T.z.enum(Le,{description:"Type of the OTP"})}),metadata:{openapi:{description:"Send verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{if(!e?.sendVerificationOTP)throw o.context.logger.error("send email verification is not implemented"),new U.APIError("BAD_REQUEST",{message:"send email verification is not implemented"});let i=o.body.email;if(!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(i))throw new U.APIError("BAD_REQUEST",{message:r.INVALID_EMAIL});if((o.body.type==="forget-password"||t.disableSignUp)&&!await o.context.internalAdapter.findUserByEmail(i))return o.json({success:!0});let s=B(t.otpLength,"0-9");return await o.context.internalAdapter.createVerificationValue({value:s,identifier:`${o.body.type}-otp-${i}`,expiresAt:x(t.expiresIn,"sec")}).catch(async c=>{await o.context.internalAdapter.deleteVerificationByIdentifier(`${o.body.type}-otp-${i}`),await o.context.internalAdapter.createVerificationValue({value:s,identifier:`${o.body.type}-otp-${i}`,expiresAt:x(t.expiresIn,"sec")})}),await e.sendVerificationOTP({email:i,otp:s,type:o.body.type},o.request),o.json({success:!0})}),createVerificationOTP:m("/email-otp/create-verification-otp",{method:"POST",body:T.z.object({email:T.z.string({description:"Email address to send the OTP"}),type:T.z.enum(Le,{description:"Type of the OTP"})}),metadata:{SERVER_ONLY:!0,openapi:{description:"Create verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string"}}}}}}}},async o=>{let i=o.body.email,n=B(t.otpLength,"0-9");return await o.context.internalAdapter.createVerificationValue({value:n,identifier:`${o.body.type}-otp-${i}`,expiresAt:x(t.expiresIn,"sec")}),n}),getVerificationOTP:m("/email-otp/get-verification-otp",{method:"GET",query:T.z.object({email:T.z.string({description:"Email address to get the OTP"}),type:T.z.enum(Le)}),metadata:{SERVER_ONLY:!0,openapi:{description:"Get verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{otp:{type:"string"}}}}}}}}}},async o=>{let i=o.query.email,n=await o.context.internalAdapter.findVerificationValue(`${o.query.type}-otp-${i}`);return!n||n.expiresAt<new Date?o.json({otp:null}):o.json({otp:n.value})}),verifyEmailOTP:m("/email-otp/verify-email",{method:"POST",body:T.z.object({email:T.z.string({description:"Email address to verify"}),otp:T.z.string({description:"OTP to verify"})}),metadata:{openapi:{description:"Verify email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async o=>{let i=o.body.email;if(!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(i))throw new U.APIError("BAD_REQUEST",{message:r.INVALID_EMAIL});let s=await o.context.internalAdapter.findVerificationValue(`email-verification-otp-${i}`);if(!s)throw new U.APIError("BAD_REQUEST",{message:r.INVALID_OTP});if(s.expiresAt<new Date)throw await o.context.internalAdapter.deleteVerificationValue(s.id),new U.APIError("BAD_REQUEST",{message:r.OTP_EXPIRED});let c=o.body.otp;if(s.value!==c)throw new U.APIError("BAD_REQUEST",{message:r.INVALID_OTP});await o.context.internalAdapter.deleteVerificationValue(s.id);let a=await o.context.internalAdapter.findUserByEmail(i);if(!a)throw new U.APIError("BAD_REQUEST",{message:r.USER_NOT_FOUND});let d=await o.context.internalAdapter.updateUser(a.user.id,{email:i,emailVerified:!0});if(o.context.options.emailVerification?.autoSignInAfterVerification){let l=await o.context.internalAdapter.createSession(d.id,o.request);return await v(o,{session:l,user:d}),o.json({status:!0,token:l.token,user:{id:d.id,email:d.email,emailVerified:d.emailVerified,name:d.name,image:d.image,createdAt:d.createdAt,updatedAt:d.updatedAt}})}return o.json({status:!0,token:null,user:{id:d.id,email:d.email,emailVerified:d.emailVerified,name:d.name,image:d.image,createdAt:d.createdAt,updatedAt:d.updatedAt}})}),signInEmailOTP:m("/sign-in/email-otp",{method:"POST",body:T.z.object({email:T.z.string({description:"Email address to sign in"}),otp:T.z.string({description:"OTP sent to the email"})}),metadata:{openapi:{description:"Sign in with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async o=>{let i=o.body.email,n=await o.context.internalAdapter.findVerificationValue(`sign-in-otp-${i}`);if(!n)throw new U.APIError("BAD_REQUEST",{message:r.INVALID_OTP});if(n.expiresAt<new Date)throw await o.context.internalAdapter.deleteVerificationValue(n.id),new U.APIError("BAD_REQUEST",{message:r.OTP_EXPIRED});let s=o.body.otp;if(n.value!==s)throw new U.APIError("BAD_REQUEST",{message:r.INVALID_OTP});await o.context.internalAdapter.deleteVerificationValue(n.id);let c=await o.context.internalAdapter.findUserByEmail(i);if(!c){if(t.disableSignUp)throw new U.APIError("BAD_REQUEST",{message:r.USER_NOT_FOUND});let d=await o.context.internalAdapter.createUser({email:i,emailVerified:!0,name:i}),l=await o.context.internalAdapter.createSession(d.id,o.request);return await v(o,{session:l,user:d}),o.json({token:l.token,user:{id:d.id,email:d.email,emailVerified:d.emailVerified,name:d.name,image:d.image,createdAt:d.createdAt,updatedAt:d.updatedAt}})}c.user.emailVerified||await o.context.internalAdapter.updateUser(c.user.id,{emailVerified:!0});let a=await o.context.internalAdapter.createSession(c.user.id,o.request);return await v(o,{session:a,user:c.user}),o.json({token:a.token,user:{id:c.user.id,email:c.user.email,emailVerified:c.user.emailVerified,name:c.user.name,image:c.user.image,createdAt:c.user.createdAt,updatedAt:c.user.updatedAt}})}),forgetPasswordEmailOTP:m("/forget-password/email-otp",{method:"POST",body:T.z.object({email:T.z.string({description:"Email address to send the OTP"})}),metadata:{openapi:{description:"Forget password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{let i=o.body.email;if(!await o.context.internalAdapter.findUserByEmail(i))throw new U.APIError("BAD_REQUEST",{message:r.USER_NOT_FOUND});let s=B(t.otpLength,"0-9");return await o.context.internalAdapter.createVerificationValue({value:s,identifier:`forget-password-otp-${i}`,expiresAt:x(t.expiresIn,"sec")}),await e.sendVerificationOTP({email:i,otp:s,type:"forget-password"},o.request),o.json({success:!0})}),resetPasswordEmailOTP:m("/email-otp/reset-password",{method:"POST",body:T.z.object({email:T.z.string({description:"Email address to reset the password"}),otp:T.z.string({description:"OTP sent to the email"}),password:T.z.string({description:"New password"})}),metadata:{openapi:{description:"Reset password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async o=>{let i=o.body.email,n=await o.context.internalAdapter.findUserByEmail(i,{includeAccounts:!0});if(!n)throw new U.APIError("BAD_REQUEST",{message:r.USER_NOT_FOUND});let s=await o.context.internalAdapter.findVerificationValue(`forget-password-otp-${i}`);if(!s)throw new U.APIError("BAD_REQUEST",{message:r.INVALID_OTP});if(s.expiresAt<new Date)throw await o.context.internalAdapter.deleteVerificationValue(s.id),new U.APIError("BAD_REQUEST",{message:r.OTP_EXPIRED});let c=o.body.otp;if(s.value!==c)throw new U.APIError("BAD_REQUEST",{message:r.INVALID_OTP});await o.context.internalAdapter.deleteVerificationValue(s.id);let a=await o.context.password.hash(o.body.password);return n.accounts.find(l=>l.providerId==="credential")?await o.context.internalAdapter.updatePassword(n.user.id,a):await o.context.internalAdapter.createAccount({userId:n.user.id,providerId:"credential",accountId:n.user.id,password:a}),o.json({success:!0})})},hooks:{after:[{matcher(o){return!!(o.path?.startsWith("/sign-up")&&t.sendVerificationOnSignUp)},async handler(o){let i=o.context.returned;if(i instanceof U.APIError)return;let n=i&&"email"in i?i.email:i instanceof Response&&i.status===200?o.body.email:null;if(n){let s=B(t.otpLength,"0-9");await o.context.internalAdapter.createVerificationValue({value:s,identifier:`email-verification-otp-${n}`,expiresAt:x(t.expiresIn,"sec")}),await e.sendVerificationOTP({email:n,otp:s,type:"email-verification"},o.request)}}}]},$ERROR_CODES:r}};0&&(module.exports={emailOTP});
|
|
84
|
+
</html>`,Jr=m("/error",{method:"GET",metadata:{...oe,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string"}}}}}}}},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Zr(t),{headers:{"Content-Type":"text/html"}})});var Kr=m("/ok",{method:"GET",metadata:{...oe,openapi:{description:"Check if the API is working",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean"}}}}}}}}}},async e=>e.json({ok:!0}));var Yr=require("zod");var Xr=require("better-call");var J=require("zod");var ue=require("better-call");var eo=m("/list-accounts",{method:"GET",use:[N],metadata:{openapi:{description:"List all accounts linked to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},provider:{type:"string"}}}}}}}}}}},async e=>{let t=e.context.session,o=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(o.map(r=>({id:r.id,provider:r.providerId,createdAt:r.createdAt,updatedAt:r.updatedAt,accountId:r.accountId,scopes:r.scope?.split(",")||[]})))}),to=m("/link-social",{method:"POST",requireHeaders:!0,query:J.z.object({currentURL:J.z.string().optional()}).optional(),body:J.z.object({callbackURL:J.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:J.z.enum(Ie,{description:"The OAuth2 provider to use"})}),use:[N],metadata:{openapi:{description:"Link a social account to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}},required:["url","redirect"]}}}}}}}},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(c=>c.providerId===e.body.provider))throw new ue.APIError("BAD_REQUEST",{message:u.SOCIAL_ACCOUNT_ALREADY_LINKED});let i=e.context.socialProviders.find(c=>c.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new ue.APIError("NOT_FOUND",{message:u.PROVIDER_NOT_FOUND});let n=await he(e,{userId:t.user.id,email:t.user.email}),s=await i.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:s.toString(),redirect:!0})}),ro=m("/unlink-account",{method:"POST",body:J.z.object({providerId:J.z.string()}),use:[St]},async e=>{let t=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(t.length===1)throw new ue.APIError("BAD_REQUEST",{message:u.FAILED_TO_UNLINK_LAST_ACCOUNT});if(!t.find(r=>r.providerId===e.body.providerId))throw new ue.APIError("BAD_REQUEST",{message:u.ACCOUNT_NOT_FOUND});return await e.context.internalAdapter.deleteAccount(e.body.providerId,e.context.session.user.id),e.json({status:!0})});var Ga=require("defu"),U=require("better-call");var Le=["email-verification","sign-in","forget-password"],oo=e=>{let t={expiresIn:300,otpLength:6,...e},o={OTP_EXPIRED:"otp expired",INVALID_OTP:"invalid otp",INVALID_EMAIL:"invalid email",USER_NOT_FOUND:"user not found"};return{id:"email-otp",endpoints:{sendVerificationOTP:m("/email-otp/send-verification-otp",{method:"POST",body:T.z.object({email:T.z.string({description:"Email address to send the OTP"}),type:T.z.enum(Le,{description:"Type of the OTP"})}),metadata:{openapi:{description:"Send verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async r=>{if(!e?.sendVerificationOTP)throw r.context.logger.error("send email verification is not implemented"),new U.APIError("BAD_REQUEST",{message:"send email verification is not implemented"});let i=r.body.email;if(!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(i))throw new U.APIError("BAD_REQUEST",{message:o.INVALID_EMAIL});if((r.body.type==="forget-password"||t.disableSignUp)&&!await r.context.internalAdapter.findUserByEmail(i))return r.json({success:!0});let s=B(t.otpLength,"0-9");return await r.context.internalAdapter.createVerificationValue({value:s,identifier:`${r.body.type}-otp-${i}`,expiresAt:x(t.expiresIn,"sec")}).catch(async c=>{await r.context.internalAdapter.deleteVerificationByIdentifier(`${r.body.type}-otp-${i}`),await r.context.internalAdapter.createVerificationValue({value:s,identifier:`${r.body.type}-otp-${i}`,expiresAt:x(t.expiresIn,"sec")})}),await e.sendVerificationOTP({email:i,otp:s,type:r.body.type},r.request),r.json({success:!0})}),createVerificationOTP:m("/email-otp/create-verification-otp",{method:"POST",body:T.z.object({email:T.z.string({description:"Email address to send the OTP"}),type:T.z.enum(Le,{description:"Type of the OTP"})}),metadata:{SERVER_ONLY:!0,openapi:{description:"Create verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string"}}}}}}}},async r=>{let i=r.body.email,n=B(t.otpLength,"0-9");return await r.context.internalAdapter.createVerificationValue({value:n,identifier:`${r.body.type}-otp-${i}`,expiresAt:x(t.expiresIn,"sec")}),n}),getVerificationOTP:m("/email-otp/get-verification-otp",{method:"GET",query:T.z.object({email:T.z.string({description:"Email address to get the OTP"}),type:T.z.enum(Le)}),metadata:{SERVER_ONLY:!0,openapi:{description:"Get verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{otp:{type:"string"}}}}}}}}}},async r=>{let i=r.query.email,n=await r.context.internalAdapter.findVerificationValue(`${r.query.type}-otp-${i}`);return!n||n.expiresAt<new Date?r.json({otp:null}):r.json({otp:n.value})}),verifyEmailOTP:m("/email-otp/verify-email",{method:"POST",body:T.z.object({email:T.z.string({description:"Email address to verify"}),otp:T.z.string({description:"OTP to verify"})}),metadata:{openapi:{description:"Verify email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async r=>{let i=r.body.email;if(!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(i))throw new U.APIError("BAD_REQUEST",{message:o.INVALID_EMAIL});let s=await r.context.internalAdapter.findVerificationValue(`email-verification-otp-${i}`);if(!s)throw new U.APIError("BAD_REQUEST",{message:o.INVALID_OTP});if(s.expiresAt<new Date)throw await r.context.internalAdapter.deleteVerificationValue(s.id),new U.APIError("BAD_REQUEST",{message:o.OTP_EXPIRED});let c=r.body.otp;if(s.value!==c)throw new U.APIError("BAD_REQUEST",{message:o.INVALID_OTP});await r.context.internalAdapter.deleteVerificationValue(s.id);let a=await r.context.internalAdapter.findUserByEmail(i);if(!a)throw new U.APIError("BAD_REQUEST",{message:o.USER_NOT_FOUND});let d=await r.context.internalAdapter.updateUser(a.user.id,{email:i,emailVerified:!0});if(r.context.options.emailVerification?.autoSignInAfterVerification){let l=await r.context.internalAdapter.createSession(d.id,r.request);return await v(r,{session:l,user:d}),r.json({status:!0,token:l.token,user:{id:d.id,email:d.email,emailVerified:d.emailVerified,name:d.name,image:d.image,createdAt:d.createdAt,updatedAt:d.updatedAt}})}return r.json({status:!0,token:null,user:{id:d.id,email:d.email,emailVerified:d.emailVerified,name:d.name,image:d.image,createdAt:d.createdAt,updatedAt:d.updatedAt}})}),signInEmailOTP:m("/sign-in/email-otp",{method:"POST",body:T.z.object({email:T.z.string({description:"Email address to sign in"}),otp:T.z.string({description:"OTP sent to the email"})}),metadata:{openapi:{description:"Sign in with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async r=>{let i=r.body.email,n=await r.context.internalAdapter.findVerificationValue(`sign-in-otp-${i}`);if(!n)throw new U.APIError("BAD_REQUEST",{message:o.INVALID_OTP});if(n.expiresAt<new Date)throw await r.context.internalAdapter.deleteVerificationValue(n.id),new U.APIError("BAD_REQUEST",{message:o.OTP_EXPIRED});let s=r.body.otp;if(n.value!==s)throw new U.APIError("BAD_REQUEST",{message:o.INVALID_OTP});await r.context.internalAdapter.deleteVerificationValue(n.id);let c=await r.context.internalAdapter.findUserByEmail(i);if(!c){if(t.disableSignUp)throw new U.APIError("BAD_REQUEST",{message:o.USER_NOT_FOUND});let d=await r.context.internalAdapter.createUser({email:i,emailVerified:!0,name:i}),l=await r.context.internalAdapter.createSession(d.id,r.request);return await v(r,{session:l,user:d}),r.json({token:l.token,user:{id:d.id,email:d.email,emailVerified:d.emailVerified,name:d.name,image:d.image,createdAt:d.createdAt,updatedAt:d.updatedAt}})}c.user.emailVerified||await r.context.internalAdapter.updateUser(c.user.id,{emailVerified:!0});let a=await r.context.internalAdapter.createSession(c.user.id,r.request);return await v(r,{session:a,user:c.user}),r.json({token:a.token,user:{id:c.user.id,email:c.user.email,emailVerified:c.user.emailVerified,name:c.user.name,image:c.user.image,createdAt:c.user.createdAt,updatedAt:c.user.updatedAt}})}),forgetPasswordEmailOTP:m("/forget-password/email-otp",{method:"POST",body:T.z.object({email:T.z.string({description:"Email address to send the OTP"})}),metadata:{openapi:{description:"Forget password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async r=>{let i=r.body.email;if(!await r.context.internalAdapter.findUserByEmail(i))throw new U.APIError("BAD_REQUEST",{message:o.USER_NOT_FOUND});let s=B(t.otpLength,"0-9");return await r.context.internalAdapter.createVerificationValue({value:s,identifier:`forget-password-otp-${i}`,expiresAt:x(t.expiresIn,"sec")}),await e.sendVerificationOTP({email:i,otp:s,type:"forget-password"},r.request),r.json({success:!0})}),resetPasswordEmailOTP:m("/email-otp/reset-password",{method:"POST",body:T.z.object({email:T.z.string({description:"Email address to reset the password"}),otp:T.z.string({description:"OTP sent to the email"}),password:T.z.string({description:"New password"})}),metadata:{openapi:{description:"Reset password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async r=>{let i=r.body.email,n=await r.context.internalAdapter.findUserByEmail(i,{includeAccounts:!0});if(!n)throw new U.APIError("BAD_REQUEST",{message:o.USER_NOT_FOUND});let s=await r.context.internalAdapter.findVerificationValue(`forget-password-otp-${i}`);if(!s)throw new U.APIError("BAD_REQUEST",{message:o.INVALID_OTP});if(s.expiresAt<new Date)throw await r.context.internalAdapter.deleteVerificationValue(s.id),new U.APIError("BAD_REQUEST",{message:o.OTP_EXPIRED});let c=r.body.otp;if(s.value!==c)throw new U.APIError("BAD_REQUEST",{message:o.INVALID_OTP});await r.context.internalAdapter.deleteVerificationValue(s.id);let a=await r.context.password.hash(r.body.password);return n.accounts.find(l=>l.providerId==="credential")?await r.context.internalAdapter.updatePassword(n.user.id,a):await r.context.internalAdapter.createAccount({userId:n.user.id,providerId:"credential",accountId:n.user.id,password:a}),r.json({success:!0})})},hooks:{after:[{matcher(r){return!!(r.path?.startsWith("/sign-up")&&t.sendVerificationOnSignUp)},async handler(r){let i=r.context.returned;if(i instanceof U.APIError)return;let n=i&&"email"in i?i.email:i instanceof Response&&i.status===200?r.body.email:null;if(n){let s=B(t.otpLength,"0-9");await r.context.internalAdapter.createVerificationValue({value:s,identifier:`email-verification-otp-${n}`,expiresAt:x(t.expiresIn,"sec")}),await e.sendVerificationOTP({email:n,otp:s,type:"email-verification"},r.request)}}}]},$ERROR_CODES:o,rateLimit:[{pathMatcher(r){return r==="/email-otp/send-verification-otp"},window:60,max:3},{pathMatcher(r){return r==="/email-otp/verify-email"},window:60,max:3},{pathMatcher(r){return r==="/sign-in/email-otp"},window:60,max:3}]}};0&&(module.exports={emailOTP});
|
|
@@ -646,6 +646,19 @@ declare const emailOTP: (options: EmailOTPOptions) => {
|
|
|
646
646
|
readonly INVALID_EMAIL: "invalid email";
|
|
647
647
|
readonly USER_NOT_FOUND: "user not found";
|
|
648
648
|
};
|
|
649
|
+
rateLimit: ({
|
|
650
|
+
pathMatcher(path: string): path is "/email-otp/send-verification-otp";
|
|
651
|
+
window: number;
|
|
652
|
+
max: number;
|
|
653
|
+
} | {
|
|
654
|
+
pathMatcher(path: string): path is "/email-otp/verify-email";
|
|
655
|
+
window: number;
|
|
656
|
+
max: number;
|
|
657
|
+
} | {
|
|
658
|
+
pathMatcher(path: string): path is "/sign-in/email-otp";
|
|
659
|
+
window: number;
|
|
660
|
+
max: number;
|
|
661
|
+
})[];
|
|
649
662
|
};
|
|
650
663
|
|
|
651
664
|
export { emailOTP };
|
|
@@ -646,6 +646,19 @@ declare const emailOTP: (options: EmailOTPOptions) => {
|
|
|
646
646
|
readonly INVALID_EMAIL: "invalid email";
|
|
647
647
|
readonly USER_NOT_FOUND: "user not found";
|
|
648
648
|
};
|
|
649
|
+
rateLimit: ({
|
|
650
|
+
pathMatcher(path: string): path is "/email-otp/send-verification-otp";
|
|
651
|
+
window: number;
|
|
652
|
+
max: number;
|
|
653
|
+
} | {
|
|
654
|
+
pathMatcher(path: string): path is "/email-otp/verify-email";
|
|
655
|
+
window: number;
|
|
656
|
+
max: number;
|
|
657
|
+
} | {
|
|
658
|
+
pathMatcher(path: string): path is "/sign-in/email-otp";
|
|
659
|
+
window: number;
|
|
660
|
+
max: number;
|
|
661
|
+
})[];
|
|
649
662
|
};
|
|
650
663
|
|
|
651
664
|
export { emailOTP };
|
|
@@ -81,4 +81,4 @@ Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
|
|
|
81
81
|
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
82
82
|
</div>
|
|
83
83
|
</body>
|
|
84
|
-
</html>`,Vr=m("/error",{method:"GET",metadata:{...te,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string"}}}}}}}},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(jr(t),{headers:{"Content-Type":"text/html"}})});var Nr=m("/ok",{method:"GET",metadata:{...te,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 Ma}from"zod";import{APIError as Qa}from"better-call";import{z as Y}from"zod";import{APIError as ge}from"better-call";var $r=m("/list-accounts",{method:"GET",use:[V],metadata:{openapi:{description:"List all accounts linked to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},provider:{type:"string"}}}}}}}}}}},async e=>{let t=e.context.session,o=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(o.map(r=>({id:r.id,provider:r.providerId,createdAt:r.createdAt,updatedAt:r.updatedAt,accountId:r.accountId,scopes:r.scope?.split(",")||[]})))}),Br=m("/link-social",{method:"POST",requireHeaders:!0,query:Y.object({currentURL:Y.string().optional()}).optional(),body:Y.object({callbackURL:Y.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:Y.enum(Ue,{description:"The OAuth2 provider to use"})}),use:[V],metadata:{openapi:{description:"Link a social account to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}},required:["url","redirect"]}}}}}}}},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(c=>c.providerId===e.body.provider))throw new ge("BAD_REQUEST",{message:u.SOCIAL_ACCOUNT_ALREADY_LINKED});let i=e.context.socialProviders.find(c=>c.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new ge("NOT_FOUND",{message:u.PROVIDER_NOT_FOUND});let n=await pe(e,{userId:t.user.id,email:t.user.email}),s=await i.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:s.toString(),redirect:!0})}),Mr=m("/unlink-account",{method:"POST",body:Y.object({providerId:Y.string()}),use:[ct]},async e=>{let t=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(t.length===1)throw new ge("BAD_REQUEST",{message:u.FAILED_TO_UNLINK_LAST_ACCOUNT});if(!t.find(r=>r.providerId===e.body.providerId))throw new ge("BAD_REQUEST",{message:u.ACCOUNT_NOT_FOUND});return await e.context.internalAdapter.deleteAccount(e.body.providerId,e.context.session.user.id),e.json({status:!0})});import"defu";import{APIError as U}from"better-call";var ke=["email-verification","sign-in","forget-password"],tc=e=>{let t={expiresIn:300,otpLength:6,...e},o={OTP_EXPIRED:"otp expired",INVALID_OTP:"invalid otp",INVALID_EMAIL:"invalid email",USER_NOT_FOUND:"user not found"};return{id:"email-otp",endpoints:{sendVerificationOTP:m("/email-otp/send-verification-otp",{method:"POST",body:T.object({email:T.string({description:"Email address to send the OTP"}),type:T.enum(ke,{description:"Type of the OTP"})}),metadata:{openapi:{description:"Send verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async r=>{if(!e?.sendVerificationOTP)throw r.context.logger.error("send email verification is not implemented"),new U("BAD_REQUEST",{message:"send email verification is not implemented"});let i=r.body.email;if(!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(i))throw new U("BAD_REQUEST",{message:o.INVALID_EMAIL});if((r.body.type==="forget-password"||t.disableSignUp)&&!await r.context.internalAdapter.findUserByEmail(i))return r.json({success:!0});let s=B(t.otpLength,"0-9");return await r.context.internalAdapter.createVerificationValue({value:s,identifier:`${r.body.type}-otp-${i}`,expiresAt:x(t.expiresIn,"sec")}).catch(async c=>{await r.context.internalAdapter.deleteVerificationByIdentifier(`${r.body.type}-otp-${i}`),await r.context.internalAdapter.createVerificationValue({value:s,identifier:`${r.body.type}-otp-${i}`,expiresAt:x(t.expiresIn,"sec")})}),await e.sendVerificationOTP({email:i,otp:s,type:r.body.type},r.request),r.json({success:!0})}),createVerificationOTP:m("/email-otp/create-verification-otp",{method:"POST",body:T.object({email:T.string({description:"Email address to send the OTP"}),type:T.enum(ke,{description:"Type of the OTP"})}),metadata:{SERVER_ONLY:!0,openapi:{description:"Create verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string"}}}}}}}},async r=>{let i=r.body.email,n=B(t.otpLength,"0-9");return await r.context.internalAdapter.createVerificationValue({value:n,identifier:`${r.body.type}-otp-${i}`,expiresAt:x(t.expiresIn,"sec")}),n}),getVerificationOTP:m("/email-otp/get-verification-otp",{method:"GET",query:T.object({email:T.string({description:"Email address to get the OTP"}),type:T.enum(ke)}),metadata:{SERVER_ONLY:!0,openapi:{description:"Get verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{otp:{type:"string"}}}}}}}}}},async r=>{let i=r.query.email,n=await r.context.internalAdapter.findVerificationValue(`${r.query.type}-otp-${i}`);return!n||n.expiresAt<new Date?r.json({otp:null}):r.json({otp:n.value})}),verifyEmailOTP:m("/email-otp/verify-email",{method:"POST",body:T.object({email:T.string({description:"Email address to verify"}),otp:T.string({description:"OTP to verify"})}),metadata:{openapi:{description:"Verify email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async r=>{let i=r.body.email;if(!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(i))throw new U("BAD_REQUEST",{message:o.INVALID_EMAIL});let s=await r.context.internalAdapter.findVerificationValue(`email-verification-otp-${i}`);if(!s)throw new U("BAD_REQUEST",{message:o.INVALID_OTP});if(s.expiresAt<new Date)throw await r.context.internalAdapter.deleteVerificationValue(s.id),new U("BAD_REQUEST",{message:o.OTP_EXPIRED});let c=r.body.otp;if(s.value!==c)throw new U("BAD_REQUEST",{message:o.INVALID_OTP});await r.context.internalAdapter.deleteVerificationValue(s.id);let a=await r.context.internalAdapter.findUserByEmail(i);if(!a)throw new U("BAD_REQUEST",{message:o.USER_NOT_FOUND});let d=await r.context.internalAdapter.updateUser(a.user.id,{email:i,emailVerified:!0});if(r.context.options.emailVerification?.autoSignInAfterVerification){let l=await r.context.internalAdapter.createSession(d.id,r.request);return await v(r,{session:l,user:d}),r.json({status:!0,token:l.token,user:{id:d.id,email:d.email,emailVerified:d.emailVerified,name:d.name,image:d.image,createdAt:d.createdAt,updatedAt:d.updatedAt}})}return r.json({status:!0,token:null,user:{id:d.id,email:d.email,emailVerified:d.emailVerified,name:d.name,image:d.image,createdAt:d.createdAt,updatedAt:d.updatedAt}})}),signInEmailOTP:m("/sign-in/email-otp",{method:"POST",body:T.object({email:T.string({description:"Email address to sign in"}),otp:T.string({description:"OTP sent to the email"})}),metadata:{openapi:{description:"Sign in with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async r=>{let i=r.body.email,n=await r.context.internalAdapter.findVerificationValue(`sign-in-otp-${i}`);if(!n)throw new U("BAD_REQUEST",{message:o.INVALID_OTP});if(n.expiresAt<new Date)throw await r.context.internalAdapter.deleteVerificationValue(n.id),new U("BAD_REQUEST",{message:o.OTP_EXPIRED});let s=r.body.otp;if(n.value!==s)throw new U("BAD_REQUEST",{message:o.INVALID_OTP});await r.context.internalAdapter.deleteVerificationValue(n.id);let c=await r.context.internalAdapter.findUserByEmail(i);if(!c){if(t.disableSignUp)throw new U("BAD_REQUEST",{message:o.USER_NOT_FOUND});let d=await r.context.internalAdapter.createUser({email:i,emailVerified:!0,name:i}),l=await r.context.internalAdapter.createSession(d.id,r.request);return await v(r,{session:l,user:d}),r.json({token:l.token,user:{id:d.id,email:d.email,emailVerified:d.emailVerified,name:d.name,image:d.image,createdAt:d.createdAt,updatedAt:d.updatedAt}})}c.user.emailVerified||await r.context.internalAdapter.updateUser(c.user.id,{emailVerified:!0});let a=await r.context.internalAdapter.createSession(c.user.id,r.request);return await v(r,{session:a,user:c.user}),r.json({token:a.token,user:{id:c.user.id,email:c.user.email,emailVerified:c.user.emailVerified,name:c.user.name,image:c.user.image,createdAt:c.user.createdAt,updatedAt:c.user.updatedAt}})}),forgetPasswordEmailOTP:m("/forget-password/email-otp",{method:"POST",body:T.object({email:T.string({description:"Email address to send the OTP"})}),metadata:{openapi:{description:"Forget password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async r=>{let i=r.body.email;if(!await r.context.internalAdapter.findUserByEmail(i))throw new U("BAD_REQUEST",{message:o.USER_NOT_FOUND});let s=B(t.otpLength,"0-9");return await r.context.internalAdapter.createVerificationValue({value:s,identifier:`forget-password-otp-${i}`,expiresAt:x(t.expiresIn,"sec")}),await e.sendVerificationOTP({email:i,otp:s,type:"forget-password"},r.request),r.json({success:!0})}),resetPasswordEmailOTP:m("/email-otp/reset-password",{method:"POST",body:T.object({email:T.string({description:"Email address to reset the password"}),otp:T.string({description:"OTP sent to the email"}),password:T.string({description:"New password"})}),metadata:{openapi:{description:"Reset password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async r=>{let i=r.body.email,n=await r.context.internalAdapter.findUserByEmail(i,{includeAccounts:!0});if(!n)throw new U("BAD_REQUEST",{message:o.USER_NOT_FOUND});let s=await r.context.internalAdapter.findVerificationValue(`forget-password-otp-${i}`);if(!s)throw new U("BAD_REQUEST",{message:o.INVALID_OTP});if(s.expiresAt<new Date)throw await r.context.internalAdapter.deleteVerificationValue(s.id),new U("BAD_REQUEST",{message:o.OTP_EXPIRED});let c=r.body.otp;if(s.value!==c)throw new U("BAD_REQUEST",{message:o.INVALID_OTP});await r.context.internalAdapter.deleteVerificationValue(s.id);let a=await r.context.password.hash(r.body.password);return n.accounts.find(l=>l.providerId==="credential")?await r.context.internalAdapter.updatePassword(n.user.id,a):await r.context.internalAdapter.createAccount({userId:n.user.id,providerId:"credential",accountId:n.user.id,password:a}),r.json({success:!0})})},hooks:{after:[{matcher(r){return!!(r.path?.startsWith("/sign-up")&&t.sendVerificationOnSignUp)},async handler(r){let i=r.context.returned;if(i instanceof U)return;let n=i&&"email"in i?i.email:i instanceof Response&&i.status===200?r.body.email:null;if(n){let s=B(t.otpLength,"0-9");await r.context.internalAdapter.createVerificationValue({value:s,identifier:`email-verification-otp-${n}`,expiresAt:x(t.expiresIn,"sec")}),await e.sendVerificationOTP({email:n,otp:s,type:"email-verification"},r.request)}}}]},$ERROR_CODES:o}};export{tc as emailOTP};
|
|
84
|
+
</html>`,Vr=m("/error",{method:"GET",metadata:{...te,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string"}}}}}}}},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(jr(t),{headers:{"Content-Type":"text/html"}})});var Nr=m("/ok",{method:"GET",metadata:{...te,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 Ma}from"zod";import{APIError as Qa}from"better-call";import{z as Y}from"zod";import{APIError as ge}from"better-call";var $r=m("/list-accounts",{method:"GET",use:[V],metadata:{openapi:{description:"List all accounts linked to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},provider:{type:"string"}}}}}}}}}}},async e=>{let t=e.context.session,o=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(o.map(r=>({id:r.id,provider:r.providerId,createdAt:r.createdAt,updatedAt:r.updatedAt,accountId:r.accountId,scopes:r.scope?.split(",")||[]})))}),Br=m("/link-social",{method:"POST",requireHeaders:!0,query:Y.object({currentURL:Y.string().optional()}).optional(),body:Y.object({callbackURL:Y.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:Y.enum(Ue,{description:"The OAuth2 provider to use"})}),use:[V],metadata:{openapi:{description:"Link a social account to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}},required:["url","redirect"]}}}}}}}},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(c=>c.providerId===e.body.provider))throw new ge("BAD_REQUEST",{message:u.SOCIAL_ACCOUNT_ALREADY_LINKED});let i=e.context.socialProviders.find(c=>c.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new ge("NOT_FOUND",{message:u.PROVIDER_NOT_FOUND});let n=await pe(e,{userId:t.user.id,email:t.user.email}),s=await i.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:s.toString(),redirect:!0})}),Mr=m("/unlink-account",{method:"POST",body:Y.object({providerId:Y.string()}),use:[ct]},async e=>{let t=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(t.length===1)throw new ge("BAD_REQUEST",{message:u.FAILED_TO_UNLINK_LAST_ACCOUNT});if(!t.find(r=>r.providerId===e.body.providerId))throw new ge("BAD_REQUEST",{message:u.ACCOUNT_NOT_FOUND});return await e.context.internalAdapter.deleteAccount(e.body.providerId,e.context.session.user.id),e.json({status:!0})});import"defu";import{APIError as U}from"better-call";var ke=["email-verification","sign-in","forget-password"],tc=e=>{let t={expiresIn:300,otpLength:6,...e},o={OTP_EXPIRED:"otp expired",INVALID_OTP:"invalid otp",INVALID_EMAIL:"invalid email",USER_NOT_FOUND:"user not found"};return{id:"email-otp",endpoints:{sendVerificationOTP:m("/email-otp/send-verification-otp",{method:"POST",body:T.object({email:T.string({description:"Email address to send the OTP"}),type:T.enum(ke,{description:"Type of the OTP"})}),metadata:{openapi:{description:"Send verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async r=>{if(!e?.sendVerificationOTP)throw r.context.logger.error("send email verification is not implemented"),new U("BAD_REQUEST",{message:"send email verification is not implemented"});let i=r.body.email;if(!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(i))throw new U("BAD_REQUEST",{message:o.INVALID_EMAIL});if((r.body.type==="forget-password"||t.disableSignUp)&&!await r.context.internalAdapter.findUserByEmail(i))return r.json({success:!0});let s=B(t.otpLength,"0-9");return await r.context.internalAdapter.createVerificationValue({value:s,identifier:`${r.body.type}-otp-${i}`,expiresAt:x(t.expiresIn,"sec")}).catch(async c=>{await r.context.internalAdapter.deleteVerificationByIdentifier(`${r.body.type}-otp-${i}`),await r.context.internalAdapter.createVerificationValue({value:s,identifier:`${r.body.type}-otp-${i}`,expiresAt:x(t.expiresIn,"sec")})}),await e.sendVerificationOTP({email:i,otp:s,type:r.body.type},r.request),r.json({success:!0})}),createVerificationOTP:m("/email-otp/create-verification-otp",{method:"POST",body:T.object({email:T.string({description:"Email address to send the OTP"}),type:T.enum(ke,{description:"Type of the OTP"})}),metadata:{SERVER_ONLY:!0,openapi:{description:"Create verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"string"}}}}}}}},async r=>{let i=r.body.email,n=B(t.otpLength,"0-9");return await r.context.internalAdapter.createVerificationValue({value:n,identifier:`${r.body.type}-otp-${i}`,expiresAt:x(t.expiresIn,"sec")}),n}),getVerificationOTP:m("/email-otp/get-verification-otp",{method:"GET",query:T.object({email:T.string({description:"Email address to get the OTP"}),type:T.enum(ke)}),metadata:{SERVER_ONLY:!0,openapi:{description:"Get verification OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{otp:{type:"string"}}}}}}}}}},async r=>{let i=r.query.email,n=await r.context.internalAdapter.findVerificationValue(`${r.query.type}-otp-${i}`);return!n||n.expiresAt<new Date?r.json({otp:null}):r.json({otp:n.value})}),verifyEmailOTP:m("/email-otp/verify-email",{method:"POST",body:T.object({email:T.string({description:"Email address to verify"}),otp:T.string({description:"OTP to verify"})}),metadata:{openapi:{description:"Verify email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async r=>{let i=r.body.email;if(!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(i))throw new U("BAD_REQUEST",{message:o.INVALID_EMAIL});let s=await r.context.internalAdapter.findVerificationValue(`email-verification-otp-${i}`);if(!s)throw new U("BAD_REQUEST",{message:o.INVALID_OTP});if(s.expiresAt<new Date)throw await r.context.internalAdapter.deleteVerificationValue(s.id),new U("BAD_REQUEST",{message:o.OTP_EXPIRED});let c=r.body.otp;if(s.value!==c)throw new U("BAD_REQUEST",{message:o.INVALID_OTP});await r.context.internalAdapter.deleteVerificationValue(s.id);let a=await r.context.internalAdapter.findUserByEmail(i);if(!a)throw new U("BAD_REQUEST",{message:o.USER_NOT_FOUND});let d=await r.context.internalAdapter.updateUser(a.user.id,{email:i,emailVerified:!0});if(r.context.options.emailVerification?.autoSignInAfterVerification){let l=await r.context.internalAdapter.createSession(d.id,r.request);return await v(r,{session:l,user:d}),r.json({status:!0,token:l.token,user:{id:d.id,email:d.email,emailVerified:d.emailVerified,name:d.name,image:d.image,createdAt:d.createdAt,updatedAt:d.updatedAt}})}return r.json({status:!0,token:null,user:{id:d.id,email:d.email,emailVerified:d.emailVerified,name:d.name,image:d.image,createdAt:d.createdAt,updatedAt:d.updatedAt}})}),signInEmailOTP:m("/sign-in/email-otp",{method:"POST",body:T.object({email:T.string({description:"Email address to sign in"}),otp:T.string({description:"OTP sent to the email"})}),metadata:{openapi:{description:"Sign in with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}}}}}}},async r=>{let i=r.body.email,n=await r.context.internalAdapter.findVerificationValue(`sign-in-otp-${i}`);if(!n)throw new U("BAD_REQUEST",{message:o.INVALID_OTP});if(n.expiresAt<new Date)throw await r.context.internalAdapter.deleteVerificationValue(n.id),new U("BAD_REQUEST",{message:o.OTP_EXPIRED});let s=r.body.otp;if(n.value!==s)throw new U("BAD_REQUEST",{message:o.INVALID_OTP});await r.context.internalAdapter.deleteVerificationValue(n.id);let c=await r.context.internalAdapter.findUserByEmail(i);if(!c){if(t.disableSignUp)throw new U("BAD_REQUEST",{message:o.USER_NOT_FOUND});let d=await r.context.internalAdapter.createUser({email:i,emailVerified:!0,name:i}),l=await r.context.internalAdapter.createSession(d.id,r.request);return await v(r,{session:l,user:d}),r.json({token:l.token,user:{id:d.id,email:d.email,emailVerified:d.emailVerified,name:d.name,image:d.image,createdAt:d.createdAt,updatedAt:d.updatedAt}})}c.user.emailVerified||await r.context.internalAdapter.updateUser(c.user.id,{emailVerified:!0});let a=await r.context.internalAdapter.createSession(c.user.id,r.request);return await v(r,{session:a,user:c.user}),r.json({token:a.token,user:{id:c.user.id,email:c.user.email,emailVerified:c.user.emailVerified,name:c.user.name,image:c.user.image,createdAt:c.user.createdAt,updatedAt:c.user.updatedAt}})}),forgetPasswordEmailOTP:m("/forget-password/email-otp",{method:"POST",body:T.object({email:T.string({description:"Email address to send the OTP"})}),metadata:{openapi:{description:"Forget password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async r=>{let i=r.body.email;if(!await r.context.internalAdapter.findUserByEmail(i))throw new U("BAD_REQUEST",{message:o.USER_NOT_FOUND});let s=B(t.otpLength,"0-9");return await r.context.internalAdapter.createVerificationValue({value:s,identifier:`forget-password-otp-${i}`,expiresAt:x(t.expiresIn,"sec")}),await e.sendVerificationOTP({email:i,otp:s,type:"forget-password"},r.request),r.json({success:!0})}),resetPasswordEmailOTP:m("/email-otp/reset-password",{method:"POST",body:T.object({email:T.string({description:"Email address to reset the password"}),otp:T.string({description:"OTP sent to the email"}),password:T.string({description:"New password"})}),metadata:{openapi:{description:"Reset password with email OTP",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async r=>{let i=r.body.email,n=await r.context.internalAdapter.findUserByEmail(i,{includeAccounts:!0});if(!n)throw new U("BAD_REQUEST",{message:o.USER_NOT_FOUND});let s=await r.context.internalAdapter.findVerificationValue(`forget-password-otp-${i}`);if(!s)throw new U("BAD_REQUEST",{message:o.INVALID_OTP});if(s.expiresAt<new Date)throw await r.context.internalAdapter.deleteVerificationValue(s.id),new U("BAD_REQUEST",{message:o.OTP_EXPIRED});let c=r.body.otp;if(s.value!==c)throw new U("BAD_REQUEST",{message:o.INVALID_OTP});await r.context.internalAdapter.deleteVerificationValue(s.id);let a=await r.context.password.hash(r.body.password);return n.accounts.find(l=>l.providerId==="credential")?await r.context.internalAdapter.updatePassword(n.user.id,a):await r.context.internalAdapter.createAccount({userId:n.user.id,providerId:"credential",accountId:n.user.id,password:a}),r.json({success:!0})})},hooks:{after:[{matcher(r){return!!(r.path?.startsWith("/sign-up")&&t.sendVerificationOnSignUp)},async handler(r){let i=r.context.returned;if(i instanceof U)return;let n=i&&"email"in i?i.email:i instanceof Response&&i.status===200?r.body.email:null;if(n){let s=B(t.otpLength,"0-9");await r.context.internalAdapter.createVerificationValue({value:s,identifier:`email-verification-otp-${n}`,expiresAt:x(t.expiresIn,"sec")}),await e.sendVerificationOTP({email:n,otp:s,type:"email-verification"},r.request)}}}]},$ERROR_CODES:o,rateLimit:[{pathMatcher(r){return r==="/email-otp/send-verification-otp"},window:60,max:3},{pathMatcher(r){return r==="/email-otp/verify-email"},window:60,max:3},{pathMatcher(r){return r==="/sign-in/email-otp"},window:60,max:3}]}};export{tc as emailOTP};
|