better-auth 1.1.9-beta.1 → 1.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/drizzle.d.cts +1 -1
- package/dist/adapters/drizzle.d.ts +1 -1
- package/dist/adapters/kysely.d.cts +1 -1
- package/dist/adapters/kysely.d.ts +1 -1
- package/dist/adapters/memory.d.cts +1 -1
- package/dist/adapters/memory.d.ts +1 -1
- package/dist/adapters/mongodb.d.cts +1 -1
- package/dist/adapters/mongodb.d.ts +1 -1
- package/dist/adapters/prisma.d.cts +1 -1
- package/dist/adapters/prisma.d.ts +1 -1
- package/dist/api.cjs +5 -5
- package/dist/api.d.cts +1 -1
- package/dist/api.d.ts +1 -1
- package/dist/api.js +4 -4
- package/dist/{auth-B4Vamjan.d.cts → auth-BhctcQB2.d.cts} +21 -5
- package/dist/{auth-BckaOBu3.d.ts → auth-DZm_Ea50.d.ts} +21 -5
- package/dist/client/plugins.d.cts +2 -2
- package/dist/client/plugins.d.ts +2 -2
- package/dist/client.d.cts +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/cookies.d.cts +1 -1
- package/dist/cookies.d.ts +1 -1
- package/dist/db.d.cts +2 -2
- package/dist/db.d.ts +2 -2
- package/dist/{index-BvDQgCpd.d.ts → index-CbuGdEs3.d.ts} +10 -10
- package/dist/{index-C5lXQ_E3.d.cts → index-Crajs-hk.d.cts} +10 -10
- package/dist/index.cjs +4 -4
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +4 -4
- package/dist/next-js.d.cts +1 -1
- package/dist/next-js.d.ts +1 -1
- package/dist/node.d.cts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/oauth2.d.cts +2 -2
- package/dist/oauth2.d.ts +2 -2
- package/dist/plugin/custom-session.cjs +4 -4
- package/dist/plugin/custom-session.d.cts +1 -1
- package/dist/plugin/custom-session.d.ts +1 -1
- package/dist/plugin/custom-session.js +5 -5
- package/dist/plugins/admin.cjs +4 -4
- package/dist/plugins/admin.d.cts +1 -1
- package/dist/plugins/admin.d.ts +1 -1
- package/dist/plugins/admin.js +4 -4
- package/dist/plugins/anonymous.cjs +5 -5
- package/dist/plugins/anonymous.d.cts +1 -1
- package/dist/plugins/anonymous.d.ts +1 -1
- package/dist/plugins/anonymous.js +5 -5
- package/dist/plugins/bearer.cjs +4 -4
- package/dist/plugins/bearer.d.cts +1 -1
- package/dist/plugins/bearer.d.ts +1 -1
- package/dist/plugins/bearer.js +5 -5
- package/dist/plugins/email-otp.cjs +4 -4
- package/dist/plugins/email-otp.d.cts +13 -13
- package/dist/plugins/email-otp.d.ts +13 -13
- package/dist/plugins/email-otp.js +4 -4
- package/dist/plugins/generic-oauth.cjs +5 -5
- package/dist/plugins/generic-oauth.d.cts +6 -1
- package/dist/plugins/generic-oauth.d.ts +6 -1
- package/dist/plugins/generic-oauth.js +5 -5
- package/dist/plugins/jwt.cjs +4 -4
- package/dist/plugins/jwt.d.cts +1 -1
- package/dist/plugins/jwt.d.ts +1 -1
- package/dist/plugins/jwt.js +4 -4
- package/dist/plugins/magic-link.cjs +4 -4
- package/dist/plugins/magic-link.js +5 -5
- package/dist/plugins/multi-session.cjs +4 -4
- package/dist/plugins/multi-session.d.cts +1 -1
- package/dist/plugins/multi-session.d.ts +1 -1
- package/dist/plugins/multi-session.js +5 -5
- package/dist/plugins/oidc-provider.cjs +5 -5
- package/dist/plugins/oidc-provider.d.cts +1 -1
- package/dist/plugins/oidc-provider.d.ts +1 -1
- package/dist/plugins/oidc-provider.js +5 -5
- package/dist/plugins/one-tap.cjs +4 -4
- package/dist/plugins/one-tap.js +5 -5
- package/dist/plugins/open-api.cjs +7 -7
- package/dist/plugins/open-api.d.cts +29 -1
- package/dist/plugins/open-api.d.ts +29 -1
- package/dist/plugins/open-api.js +6 -6
- package/dist/plugins/organization.cjs +4 -4
- package/dist/plugins/organization.d.cts +2 -2
- package/dist/plugins/organization.d.ts +2 -2
- package/dist/plugins/organization.js +4 -4
- package/dist/plugins/passkey.cjs +5 -5
- package/dist/plugins/passkey.d.cts +1 -1
- package/dist/plugins/passkey.d.ts +1 -1
- package/dist/plugins/passkey.js +5 -5
- package/dist/plugins/phone-number.cjs +4 -4
- package/dist/plugins/phone-number.d.cts +1 -1
- package/dist/plugins/phone-number.d.ts +1 -1
- package/dist/plugins/phone-number.js +4 -4
- package/dist/plugins/sso.cjs +4 -4
- package/dist/plugins/sso.d.cts +1 -1
- package/dist/plugins/sso.d.ts +1 -1
- package/dist/plugins/sso.js +4 -4
- package/dist/plugins/two-factor.cjs +5 -5
- package/dist/plugins/two-factor.d.cts +1 -1
- package/dist/plugins/two-factor.d.ts +1 -1
- package/dist/plugins/two-factor.js +5 -5
- package/dist/plugins/username.cjs +4 -4
- package/dist/plugins/username.d.cts +1 -1
- package/dist/plugins/username.d.ts +1 -1
- package/dist/plugins/username.js +5 -5
- package/dist/plugins.cjs +8 -8
- package/dist/plugins.d.cts +4 -4
- package/dist/plugins.d.ts +4 -4
- package/dist/plugins.js +8 -8
- package/dist/react.d.cts +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/solid-start.d.cts +1 -1
- package/dist/solid-start.d.ts +1 -1
- package/dist/solid.d.cts +1 -1
- package/dist/solid.d.ts +1 -1
- package/dist/{state-DIITe_Bt.d.cts → state-CKau6ADC.d.cts} +1 -1
- package/dist/{state-P3iuPFFi.d.ts → state-CMAzXY7z.d.ts} +1 -1
- package/dist/svelte-kit.d.cts +1 -1
- package/dist/svelte-kit.d.ts +1 -1
- package/dist/svelte.d.cts +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/types.d.cts +2 -2
- package/dist/types.d.ts +2 -2
- package/dist/vue.d.cts +1 -1
- package/dist/vue.d.ts +1 -1
- package/package.json +1 -1
package/dist/api.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{APIError as
|
|
1
|
+
import{APIError as Z,createRouter as io,getCookie as so,getSignedCookie as ao,setCookie as co,setSignedCookie as lo}from"better-call";import{APIError as $e}from"better-call";import{createEndpointCreator as Gt,createMiddleware as Ie,createMiddlewareCreator as Wt}from"better-call";var Pe=Ie(async()=>({})),re=Wt({use:[Pe,Ie(async()=>({}))]}),A=Gt({use:[Pe]});function ke(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 r=0;r<e.length;r++)t+=ke(e[r]);return t}function De(e,t=!0){if(Array.isArray(e))return`(?:${e.map(u=>`^${De(u,t)}$`).join("|")})`;let r="",o="",n=".";t===!0?(r="/",o="[/\\\\]",n="[^/\\\\]"):t&&(r=t,o=Qt(r),o.length>1?(o=`(?:${o})`,n=`((?!${o}).)`):n=`[^${o}]`);let i=t?`${o}+?`:"",s=t?`${o}*?`:"",c=t?e.split(r):[e],a="";for(let d=0;d<c.length;d++){let u=c[d],h=c[d+1],p="";if(!(!u&&d>0)){if(t&&(d===c.length-1?p=s:h!=="**"?p=i:p=""),t&&u==="**"){p&&(a+=d===0?"":p,a+=`(?:${n}*?${p})*?`);continue}for(let l=0;l<u.length;l++){let y=u[l];y==="\\"?l<u.length-1&&(a+=ke(u[l+1]),l++):y==="?"?a+=n:y==="*"?a+=`${n}*?`:a+=ke(y)}a+=p}}return a}function Jt(e,t){if(typeof t!="string")throw new TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function se(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 r=De(e,t.separator),o=new RegExp(`^${r}$`,t.flags),n=Jt.bind(null,o);return n.options=t,n.pattern=e,n.regexp=o,n}var me=Object.create(null),ae=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?me:globalThis),Ce=new Proxy(me,{get(e,t){return ae()[t]??me[t]},has(e,t){let r=ae();return t in r||t in me},set(e,t,r){let o=ae(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=ae(!0);return delete r[t],!0},ownKeys(){let e=ae(!0);return Object.keys(e)}});function Zt(e){return e?e!=="false":!1}var Ee=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var fe=Ee==="dev"||Ee==="development",je=Ee==="test"||Zt(Ce.TEST);var Q=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function Ne(e){try{return new URL(e).origin}catch{return null}}function Ue(e){return e.includes("://")?new URL(e).host:e}var Ve=re(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=t?.callbackURL||r?.callbackURL,s=t?.redirectTo,c=r?.currentURL,a=t?.errorCallbackURL,d=t?.newUserCallbackURL,u=o.trustedOrigins,h=e.headers?.has("cookie"),p=(y,E)=>y.startsWith("/")?!1:E.includes("*")?se(E)(Ue(y)):y.startsWith(E),l=(y,E)=>{if(!y)return;if(!u.some(V=>p(y,V)||y?.startsWith("/")&&E!=="origin"&&!y.includes(":")))throw e.context.logger.error(`Invalid ${E}: ${y}`),e.context.logger.info(`If it's a valid URL, please add ${y} to trustedOrigins in your auth config
|
|
2
2
|
`,`Current list of trustedOrigins: ${u}`),new $e("FORBIDDEN",{message:`Invalid ${E}`})};h&&!e.context.options.advanced?.disableCSRFCheck&&l(n,"origin"),i&&l(i,"callbackURL"),s&&l(s,"redirectURL"),c&&l(c,"currentURL"),a&&l(a,"errorCallbackURL"),d&&l(s,"newUserCallbackURL")}),oe=e=>re(async t=>{let{context:r}=t,o=e(t),n=r.trustedOrigins,i=(c,a)=>c.startsWith("/")?!1:a.includes("*")?se(a)(Ue(c)):c.startsWith(a);o&&((c,a)=>{if(!c)return;if(!n.some(u=>i(c,u)||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: ${n}`),new $e("FORBIDDEN",{message:`Invalid ${a}`})})(o,"callbackURL")});import{APIError as x}from"better-call";import{z as v}from"zod";var Z=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{base64Url as Kt}from"@better-auth/utils/base64";import{createHMAC as Yt}from"@better-auth/utils/hmac";async function _e(e,t){if(e.context.options.session?.cookieCache?.enabled){let o=Kt.encode(JSON.stringify({session:t,expiresAt:Z(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await Yt("SHA-256","base64urlnopad").sign(e.context.secret,JSON.stringify(t))}),{padding:!1});if(o.length>4093)throw new Q("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 P(e,t,r,o){let n=e.context.authCookies.sessionToken.options,i=r?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...n,maxAge:i,...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 V(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 Xt=Object.defineProperty,er=Object.defineProperties,tr=Object.getOwnPropertyDescriptors,Ve=Object.getOwnPropertySymbols,rr=Object.prototype.hasOwnProperty,or=Object.prototype.propertyIsEnumerable,Me=(e,t,r)=>t in e?Xt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,K=(e,t)=>{for(var r in t||(t={}))rr.call(t,r)&&Me(e,r,t[r]);if(Ve)for(var r of Ve(t))or.call(t,r)&&Me(e,r,t[r]);return e},Y=(e,t)=>er(e,tr(t)),nr=class extends Error{constructor(e,t,r){super(t||e.toString(),{cause:r}),this.status=e,this.statusText=t,this.error=r}},ir=async(e,t)=>{var r,o,n,i,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 u of t?.plugins||[]){if(u.init){let h=await((r=u.init)==null?void 0:r.call(u,e.toString(),t));a=h.options||a,e=h.url}d.onRequest.push((o=u.hooks)==null?void 0:o.onRequest),d.onResponse.push((n=u.hooks)==null?void 0:n.onResponse),d.onSuccess.push((i=u.hooks)==null?void 0:i.onSuccess),d.onError.push((s=u.hooks)==null?void 0:s.onError),d.onRetry.push((c=u.hooks)==null?void 0:c.onRetry)}return{url:e,options:a,hooks:d}},qe=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}},sr=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 ar(e){if(typeof e=="number")return new qe({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new qe(e);case"exponential":return new sr(e);default:throw new Error("Invalid retry strategy")}}var cr=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),n=r(e.auth.password);if(!o||!n)return t;t.authorization=`Basic ${btoa(`${o}:${n}`)}`}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},He=["get","post","put","patch","delete"];var dr=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function lr(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 dr.test(o)?"json":r.has(o)||o.startsWith("text/")?"text":"blob"}function ur(e){try{return JSON.parse(e),!0}catch{return!1}}function Ge(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 ze(e){try{return JSON.parse(e)}catch{return e}}function Fe(e){return typeof e=="function"}function pr(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<"u"&&Fe(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&Fe(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}function mr(e){let t=new Headers(e?.headers),r=cr(e);for(let[o,n]of Object.entries(r||{}))t.set(o,n);if(!t.has("content-type")){let o=fr(e?.body);o&&t.set("content-type",o)}return t}function fr(e){return Ge(e)?"application/json":null}function gr(e){if(!e?.body)return null;let t=new Headers(e?.headers);return Ge(e.body)&&!t.has("content-type")?JSON.stringify(e.body):e.body}function hr(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 He.includes(o)?o.toUpperCase():t?.body?"POST":"GET"}return t?.body?"POST":"GET"}function wr(e,t){let r;return!e?.signal&&e?.timeout&&(r=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}function yr(e,t){let{baseURL:r,params:o,query:n}=t||{query:{},params:{},baseURL:""},i=e.startsWith("http")?e.split("/").slice(0,3).join("/"):r;if(!i)throw new TypeError(`Invalid URL ${e}. Are you passing in a relative URL but not setting the baseURL?`);if(e.startsWith("@")){let h=e.toString().split("@")[1].split("/")[0];He.includes(h)&&(e=e.replace(`@${h}/`,"/"))}i.endsWith("/")||(i+="/");let[s,c]=e.replace(i,"").split("?"),a=new URLSearchParams(c);for(let[h,p]of Object.entries(n||{}))a.set(h,String(p));if(o)if(Array.isArray(o)){let h=s.split("/").filter(p=>p.startsWith(":"));for(let[p,l]of h.entries()){let y=o[p];s=s.replace(l,y)}}else for(let[h,p]of Object.entries(o))s=s.replace(`:${h}`,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}`,i)}var R=async(e,t)=>{var r,o,n,i,s,c,a,d;let{hooks:u,url:h,options:p}=await ir(e,t),l=pr(p),y=new AbortController,E=(r=p.signal)!=null?r:y.signal,S=yr(h,p),B=gr(p),I=mr(p),m=hr(h,p),g=Y(K({},p),{url:S,headers:I,body:B,method:m,signal:E});for(let C of u.onRequest)if(C){let L=await C(g);L instanceof Object&&(g=L)}("pipeTo"in g&&typeof g.pipeTo=="function"||typeof((o=t?.body)==null?void 0:o.pipe)=="function")&&("duplex"in g||(g.duplex="half"));let{clearTimeout:O}=wr(p,y),w=await l(g.url,g);O();let pe={response:w,request:g};for(let C of u.onResponse)if(C){let L=await C(Y(K({},pe),{response:(n=t?.hookOptions)!=null&&n.cloneResponse?w.clone():w}));L instanceof Response?w=L:L instanceof Object&&(w=L.response)}if(w.ok){if(!(g.method!=="HEAD"))return{data:"",error:null};let L=lr(w),z={data:"",response:w,request:g};if(L==="json"||L==="text"){let F=await w.text(),Ht=await((i=g.jsonParser)!=null?i:ze)(F);z.data=Ht}else z.data=await w[L]();g?.output&&g.output&&!g.disableValidation&&(z.data=g.output.parse(z.data));for(let F of u.onSuccess)F&&await F(Y(K({},z),{response:(s=t?.hookOptions)!=null&&s.cloneResponse?w.clone():w}));return t?.throw?z.data:{data:z.data,error:null}}let zt=(c=t?.jsonParser)!=null?c:ze,xe=await w.text(),Re=ur(xe)?await zt(xe):{},Ft={response:w,request:g,error:Y(K({},Re),{status:w.status,statusText:w.statusText})};for(let C of u.onError)C&&await C(Y(K({},Ft),{response:(a=t?.hookOptions)!=null&&a.cloneResponse?w.clone():w}));if(t?.retry){let C=ar(t.retry),L=(d=t.retryAttempt)!=null?d:0;if(await C.shouldAttemptRetry(L,w)){for(let F of u.onRetry)F&&await F(pe);let z=C.getDelay(L);return await new Promise(F=>setTimeout(F,z)),await R(e,Y(K({},t),{retryAttempt:L+1}))}}if(t?.throw)throw new nr(w.status,w.statusText,Re);return{data:null,error:Y(K({},Re),{status:w.status,statusText:w.statusText})}};import{APIError as Ur}from"better-call";import{decodeJwt as _r,decodeProtectedHeader as Tr,importJWK as vr,jwtVerify as Or}from"jose";import{createHash as br}from"@better-auth/utils/hash";import{base64Url as Ar}from"@better-auth/utils/base64";async function We(e){let t=await br("SHA-256").digest(e);return Ar.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?Z(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function U({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,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",i.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),n){let u=await We(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",u)}if(s){let u=s.reduce((h,p)=>(h[p]=null,h),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return a&&d.searchParams.set("duration",a),d}import{jwtVerify as Xo}from"jose";async function k({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n,authentication:i}){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),i==="basic"){let h=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${h}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await R(n,{method:"POST",body:s,headers:c});if(d)throw d;return ge(a)}import{z as H}from"zod";import{APIError as Ze}from"better-call";import{createHash as An}from"@better-auth/utils/hash";import{xchacha20poly1305 as kn}from"@noble/ciphers/chacha";import{bytesToHex as Un,hexToBytes as _n,utf8ToBytes as Tn}from"@noble/ciphers/utils";import{managedNonce as On}from"@noble/ciphers/webcrypto";import{createHash as nn}from"@better-auth/utils/hash";import{SignJWT as kr}from"jose";async function Qe(e,t,r=3600){return await new kr(e).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(t))}import{scryptAsync as un}from"@noble/hashes/scrypt";import{getRandomValues as mn}from"uncrypto";import{hex as gn}from"@better-auth/utils/hex";import{createRandomStringGenerator as Er}from"@better-auth/utils/random";var ce=Er("a-z","0-9","A-Z","-_");async function he(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Ne(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new Ze("BAD_REQUEST",{message:"callbackURL is required"});let o=ce(128),n=ce(32),i=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:i,identifier:n,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 Ze("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function Je(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=H.object({callbackURL:H.string(),codeVerifier:H.string(),errorURL:H.string().optional(),newUserURL:H.string().optional(),expiresAt:H.number(),link:H.object({email:H.string(),userId:H.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 Ke=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${e.redirectURI||n}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>k({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let n=Tr(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let c=await Sr(i),{payload:a}=await Or(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=_r(r.idToken);if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email,...i},data:o}}}},Sr=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await R(`${t}${r}`);if(!o?.keys)throw new Ur("BAD_REQUEST",{message:"Keys not found"});let n=o.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await vr(n,n.alg)};var Ye=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>k({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 R("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}let n=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,...n},data:r}}});var Xe=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await U({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>k({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 R("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...n},data:r}}});var et=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),U({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>k({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await R("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1,{data:s}=await R("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,i=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:i,...c},data:o}}}};import{decodeJwt as Dr}from"jose";var Te=["info","success","warn","error","debug"];function Lr(e,t){return Te.indexOf(t)<=Te.indexOf(e)}var M={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"}},xr={info:M.fg.blue,success:M.fg.green,warn:M.fg.yellow,error:M.fg.red,debug:M.fg.magenta},Pr=(e,t)=>{let r=new Date().toISOString();return`${M.dim}${r}${M.reset} ${xr[e]}${e.toUpperCase()}${M.reset} ${M.bright}[Better Auth]:${M.reset} ${t}`},Ir=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,s=[])=>{if(!t||!Lr(r,n))return;let c=Pr(n,i);if(!e||typeof e.log!="function"){n==="error"?console.error(c,...s):n==="warn"?console.warn(c,...s):console.log(c,...s);return}e.log(n==="success"?"info":n,c,...s)};return Object.fromEntries(Te.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},j=Ir();var tt=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw j.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new Q("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new Q("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await U({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});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})=>k({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:n}=await R(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=Dr(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}}});import{decodeJwt as Cr}from"jose";var rt=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(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),U({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return k({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=Cr(n.idToken),s=e.profilePhotoSize||48;await R(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let u=await a.response.clone().arrayBuffer(),h=Buffer.from(u).toString("base64");i.picture=`data:image/jpeg;base64, ${h}`}catch(d){j.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0,...c},data:i}}}};var ot=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),U({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>k({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 R("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...n},data:r}}});var ne={isAction:!1};import{createRandomStringGenerator as jr}from"@better-auth/utils/random";var nt=e=>jr("a-z","A-Z","0-9")(e||32);import{decodeJwt as Nr}from"jose";var it=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),U({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>k({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 j.error("No idToken found in token"),null;let o=Nr(r),n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...n},data:o}}});var st=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),U({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})=>k({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 R("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=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,...n},data:r}}});var at=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await U({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await k({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await R("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...i},data:o}}}};var ct=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:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await U({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await k({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await R("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(i)return null;let s=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture,...s},data:n}}}};var ve=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),$r=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ve(`${t}/oauth/authorize`),tokenEndpoint:ve(`${t}/oauth/token`),userinfoEndpoint:ve(`${t}/api/v4/user`)}},dt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=$r(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let u=c||["read_user"];return e.scope&&u.push(...e.scope),await U({id:n,options:e,authorizationEndpoint:t,scopes:u,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>k({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 R(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 lt=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identity"];return e.scope&&n.push(...e.scope),U({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:n,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}),n={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`},{data:i,error:s}=await R("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:n,body:o.toString()});if(s)throw s;return ge(i)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await R("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let n=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],...n},data:r}}});import{z as Br}from"zod";var Vr={apple:Ke,discord:Ye,facebook:Xe,github:et,microsoft:rt,google:tt,spotify:ot,twitch:it,twitter:st,dropbox:at,linkedin:ct,gitlab:dt,reddit:lt},Oe=Object.keys(Vr),ut=Br.enum(Oe,{description:"OAuth2 provider to use"});import{z as $}from"zod";import{APIError as de}from"better-call";import{APIError as G}from"better-call";import{z as X}from"zod";function pt(e){try{return JSON.parse(e)}catch{return null}}var f={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",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"};import{createHMAC as Mr}from"@better-auth/utils/hmac";import{base64 as qr}from"@better-auth/utils/base64";import{binary as zr}from"@better-auth/utils/binary";var Se=()=>A("/get-session",{method:"GET",query:X.optional(X.object({disableCookieCache:X.boolean({description:"Disable cookie cache and fetch session from database"}).or(X.string().transform(e=>e==="true")).optional(),disableRefresh:X.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?pt(zr.decode(qr.decode(r))):null;if(o&&!await Mr("SHA-256","base64urlnopad").verify(e.context.secret,JSON.stringify(o.session),o.signature))return V(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let u=o.session;if(o.expiresAt<Date.now()||u.session.expiresAt<new Date){let p=e.context.authCookies.sessionData.name;e.setCookie(p,"",{maxAge:0})}else return e.json(u)}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return V(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n||e.query?.disableRefresh)return e.json(i);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let u=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:Z(e.context.sessionConfig.expiresIn,"sec")});if(!u)return V(e),e.json(null,{status:401});let h=(u.expiresAt.valueOf()-Date.now())/1e3;return await P(e,{session:u,user:i.user},!1,{maxAge:h}),e.json({session:u,user:i.user})}return await _e(e,i),e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new G("INTERNAL_SERVER_ERROR",{message:f.FAILED_TO_GET_SESSION})}}),ee=async(e,t)=>{if(e.context.session)return e.context.session;let r=await Se()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},D=re(async e=>{let t=await ee(e);if(!t?.session)throw new G("UNAUTHORIZED");return{session:t}}),mt=re(async e=>{let t=await ee(e);if(!t?.session)throw new G("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 G("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),ft=()=>A("/list-sessions",{method:"GET",use:[D],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),gt=A("/revoke-session",{method:"POST",body:X.object({token:X.string({description:"The token to revoke"})}),use:[D],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 G("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new G("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 G("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ht=A("/revoke-sessions",{method:"POST",use:[D],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 G("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),wt=A("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[D],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 G("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});import{jwtVerify as Fr}from"jose";async function q(e,t,r){return await Qe({email:t.toLowerCase(),updateTo:r},e)}async function Hr(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new de("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await q(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 yt=A("/send-verification-email",{method:"POST",query:$.object({currentURL:$.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:$.object({email:$.string({description:"The email to send the verification email to"}).email(),callbackURL:$.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 de("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new de("BAD_REQUEST",{message:f.USER_NOT_FOUND});return await Hr(e,r.user),e.json({status:!0})}),bt=A("/verify-email",{method:"GET",query:$.object({token:$.string({description:"The token to verify the email"}),callbackURL:$.string({description:"The URL to redirect to after email verification"}).optional()}),use:[oe(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 de("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await Fr(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 i=$.object({email:$.string().email(),updateTo:$.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(i.email);if(!s)return t("user_not_found");if(i.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!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),d=await q(e.context.secret,i.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(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification){let c=await ee(e);if(!c||c.user.email!==i.email){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new de("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await P(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 n=await e.context.internalAdapter.findOAuthUser(t.email.toLowerCase(),r.accountId,r.providerId).catch(a=>{throw j.error(`Better auth was unable to query your database.
|
|
4
|
-
Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user,s=!i;if(n){let a=n.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(([u,h])=>h!==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 fe&&j.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:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope})}catch(h){return j.error("Unable to link account",h),{error:"unable to link account",data:null}}}}else try{if(i=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&&i&&e.context.options.emailVerification?.sendOnSignUp){let a=await q(e.context.secret,i.email),d=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:d,token:a},e.request)}}catch(a){return a instanceof At?{error:a.message,data:null,isRegister:!1}:{error:"unable to create user",data:null,isRegister:!1}}if(!i)return{error:"unable to create user",data:null,isRegister:!1};let c=await e.context.internalAdapter.createSession(i.id,e.request);return c?{data:{session:c,user:i},error:null,isRegister:s}:{error:"unable to create session",data:null,isRegister:!1}}var Rt=A("/sign-in/social",{method:"POST",query:v.object({currentURL:v.string().optional()}).optional(),body:v.object({callbackURL:v.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:v.string().optional(),errorCallbackURL:v.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:ut,disableRedirect:v.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:v.optional(v.object({token:v.string({description:"ID token from the provider"}),nonce:v.string({description:"Nonce used to generate the token"}).optional(),accessToken:v.string({description:"Access token from the provider"}).optional(),refreshToken:v.string({description:"Refresh token from the provider"}).optional(),expiresAt:v.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(i=>i.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 x("NOT_FOUND",{message:f.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 x("NOT_FOUND",{message:f.ID_TOKEN_NOT_SUPPORTED});let{token:i,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new x("UNAUTHORIZED",{message:f.INVALID_TOKEN});let a=await t.getUserInfo({idToken:i,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 x("UNAUTHORIZED",{message:f.FAILED_TO_GET_USER_INFO});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new x("UNAUTHORIZED",{message:f.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 x("UNAUTHORIZED",{message:d.error});return await P(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),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),kt=A("/sign-in/email",{method:"POST",body:v.object({email:v.string({description:"Email of the user"}),password:v.string({description:"Password of the user"}),callbackURL:v.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:v.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 x("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!v.string().email().safeParse(t).success)throw new x("BAD_REQUEST",{message:f.INVALID_EMAIL});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new x("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});let i=n.accounts.find(d=>d.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new x("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new x("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new x("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new x("UNAUTHORIZED",{message:f.EMAIL_NOT_VERIFIED});let d=await q(e.context.secret,n.user.email),u=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:u,token:d},e.request),new x("FORBIDDEN",{message:f.EMAIL_NOT_VERIFIED})}let a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new x("UNAUTHORIZED",{message:f.FAILED_TO_CREATE_SESSION});return await P(e,{session:a,user:n.user},e.body.rememberMe===!1),e.json({redirect:!!e.body.callbackURL,token:a.token,url:e.body.callbackURL,user:{id:n.user.id,email:n.user.email,name:n.user.name,image:n.user.image,emailVerified:n.user.emailVerified,createdAt:n.user.createdAt,updatedAt:n.user.updatedAt}})});import{z as le}from"zod";var ye=le.object({code:le.string().optional(),error:le.string().optional(),error_description:le.string().optional(),state:le.string().optional()}),Et=A("/callback/:id",{method:["GET","POST"],body:ye.optional(),query:ye.optional(),metadata:ne},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(m){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",m),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n,error_description:i}=t;if(!n)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=${i}`);let s=e.context.socialProviders.find(m=>m.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:u,newUserURL:h}=await Je(e),p;try{p=await s.validateAuthorizationCode({code:r,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${s.id}`})}catch(m){throw e.context.logger.error("",m),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let l=await s.getUserInfo(p).then(m=>m?.user);function y(m){let g=u||a||`${e.context.baseURL}/error`;throw g.includes("?")?g=`${g}&error=${m}`:g=`${g}?error=${m}`,e.redirect(g)}if(!l)return e.context.logger.error("Unable to get user info"),y("unable_to_get_user_info");if(!l.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),y("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!==l.email.toLowerCase())return y("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:s.id,accountId:l.id}))return y("unable_to_link_account");let g;try{g=a.toString()}catch{g=a}throw e.redirect(g)}let E=await we(e,{userInfo:{...l,email:l.email,name:l.name||l.email},account:{providerId:s.id,accountId:l.id,...p,scope:p.scopes?.join(",")},callbackURL:a});if(E.error)return e.context.logger.error(E.error.split(" ").join("_")),y(E.error.split(" ").join("_"));let{session:S,user:B}=E.data;await P(e,{session:S,user:B});let I;try{I=(E.isRegister&&h||a).toString()}catch{I=E.isRegister&&h||a}throw e.redirect(I)});import"zod";import{APIError as Gr}from"better-call";var Ut=A("/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 V(e),new Gr("BAD_REQUEST",{message:f.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(t),V(e),e.json({success:!0})});import{z as N}from"zod";import{APIError as ue}from"better-call";function _t(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function Wr(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var Tt=A("/forget-password",{method:"POST",body:N.object({email:N.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:N.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 ue("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 n=60*60*1,i=Z(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=nt(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:i});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})}),vt=A("/reset-password/:token",{method:"GET",query:N.object({callbackURL:N.string({description:"The URL to redirect the user to reset their password"})}),use:[oe(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(_t(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(_t(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Wr(e.context,r,{token:t}))}),Ot=A("/reset-password",{query:N.optional(N.object({token:N.string().optional(),currentURL:N.string().optional()})),method:"POST",body:N.object({newPassword:N.string({description:"The new password to set"}),token:N.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 ue("BAD_REQUEST",{message:f.INVALID_TOKEN});let{newPassword:r}=e.body,o=e.context.password?.config.minPasswordLength,n=e.context.password?.config.maxPasswordLength;if(r.length<o)throw new ue("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});if(r.length>n)throw new ue("BAD_REQUEST",{message:f.PASSWORD_TOO_LONG});let i=`reset-password:${t}`,s=await e.context.internalAdapter.findVerificationValue(i);if(!s||s.expiresAt<new Date)throw new ue("BAD_REQUEST",{message:f.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(h=>h.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}))});import{z as _}from"zod";import{APIError as T}from"better-call";import{z as b}from"zod";import{APIError as Qr}from"better-call";var Ca=b.object({id:b.string(),providerId:b.string(),accountId:b.string(),userId:b.string(),accessToken:b.string().nullish(),refreshToken:b.string().nullish(),idToken:b.string().nullish(),accessTokenExpiresAt:b.date().nullish(),refreshTokenExpiresAt:b.date().nullish(),scope:b.string().nullish(),password:b.string().nullish(),createdAt:b.date().default(()=>new Date),updatedAt:b.date().default(()=>new Date)}),ja=b.object({id:b.string(),email:b.string().transform(e=>e.toLowerCase()),emailVerified:b.boolean().default(!1),name:b.string(),image:b.string().nullish(),createdAt:b.date().default(()=>new Date),updatedAt:b.date().default(()=>new Date)}),Na=b.object({id:b.string(),userId:b.string(),expiresAt:b.date(),createdAt:b.date().default(()=>new Date),updatedAt:b.date().default(()=>new Date),token:b.string(),ipAddress:b.string().nullish(),userAgent:b.string().nullish()}),$a=b.object({id:b.string(),value:b.string(),createdAt:b.date().default(()=>new Date),updatedAt:b.date().default(()=>new Date),expiresAt:b.date(),identifier:b.string()});function Zr(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function Jr(e,t){let r=t.action||"create",o=t.fields,n={};for(let i in o){if(i in e){if(o[i].input===!1){if(o[i].defaultValue){n[i]=o[i].defaultValue;continue}continue}if(o[i].validator?.input&&e[i]!==void 0){n[i]=o[i].validator.input.parse(e[i]);continue}if(o[i].transform?.input&&e[i]!==void 0){n[i]=o[i].transform?.input(e[i]);continue}n[i]=e[i];continue}if(o[i].defaultValue&&r==="create"){n[i]=o[i].defaultValue;continue}if(o[i].required&&r==="create")throw new Qr("BAD_REQUEST",{message:`${i} is required`})}return n}function be(e,t,r){let o=Zr(e,"user");return Jr(t||{},{fields:o,action:r})}var St=()=>A("/update-user",{method:"POST",body:_.record(_.string(),_.any()),use:[D],metadata:{openapi:{description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"}}}}}}}}}},async e=>{let t=e.body;if(t.email)throw new T("BAD_REQUEST",{message:f.EMAIL_CAN_NOT_BE_UPDATED});let{name:r,image:o,...n}=t,i=e.context.session;if(o===void 0&&r===void 0&&Object.keys(n).length===0)return e.json({status:!0});let s=be(e.context.options,n,"update"),c=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await P(e,{session:i.session,user:c}),e.json({status:!0})}),Lt=A("/change-password",{method:"POST",body:_.object({newPassword:_.string({description:"The new password to set"}),currentPassword:_.string({description:"The current password"}),revokeOtherSessions:_.boolean({description:"Revoke all other sessions"}).optional()}),use:[D],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,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new T("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new T("BAD_REQUEST",{message:f.PASSWORD_TOO_LONG});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(p=>p.providerId==="credential"&&p.password);if(!a||!a.password)throw new T("BAD_REQUEST",{message:f.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 T("BAD_REQUEST",{message:f.INVALID_PASSWORD});await e.context.internalAdapter.updateAccount(a.id,{password:d});let h=null;if(o){await e.context.internalAdapter.deleteSessions(n.user.id);let p=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!p)throw new T("INTERNAL_SERVER_ERROR",{message:f.FAILED_TO_GET_SESSION});await P(e,{session:p,user:n.user}),h=p.token}return e.json({token:h,user:{id:n.user.id,email:n.user.email,name:n.user.name,image:n.user.image,emailVerified:n.user.emailVerified,createdAt:n.user.createdAt,updatedAt:n.user.updatedAt}})}),xt=A("/set-password",{method:"POST",body:_.object({newPassword:_.string()}),metadata:{SERVER_ONLY:!0},use:[D]},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 T("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new T("BAD_REQUEST",{message:f.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 T("BAD_REQUEST",{message:"user already has a password"})}),Pt=A("/delete-user",{method:"POST",use:[D],body:_.object({callbackURL:_.string().optional(),password:_.string().optional(),token:_.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 T("NOT_FOUND");let t=e.context.session;if(e.body.password){let i=(await e.context.internalAdapter.findAccounts(t.user.id)).find(c=>c.providerId==="credential"&&c.password);if(!i||!i.password)throw new T("BAD_REQUEST",{message:f.CREDENTIAL_ACCOUNT_NOT_FOUND});if(!await e.context.password.verify({hash:i.password,password:e.body.password}))throw new T("BAD_REQUEST",{message:f.INVALID_PASSWORD})}else if(e.context.options.session?.freshAge){let n=t.session.createdAt.getTime(),i=e.context.options.session.freshAge;if(Date.now()-n>i)throw new T("BAD_REQUEST",{message:f.SESSION_EXPIRED})}if(e.body.token)return await Le({...e,query:{token:e.body.token}}),e.json({success:!0,message:"User deleted"});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=ce(32,"0-9","a-z");await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${n}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let i=`${e.context.baseURL}/delete-user/callback?token=${n}&callbackURL=${e.body.callbackURL||"/"}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:i,token:n},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),V(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})}),Le=A("/delete-user/callback",{method:"GET",query:_.object({token:_.string(),callbackURL:_.string().optional()}),use:[oe(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 T("NOT_FOUND");let t=await ee(e);if(!t)throw new T("NOT_FOUND",{message:f.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 T("NOT_FOUND",{message:f.INVALID_TOKEN});if(r.value!==t.user.id)throw new T("NOT_FOUND",{message:f.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),V(e);let n=e.context.options.user.deleteUser?.afterDelete;if(n&&await n(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||"/");return e.json({success:!0,message:"User deleted"})}),It=A("/change-email",{method:"POST",query:_.object({currentURL:_.string().optional()}).optional(),body:_.object({newEmail:_.string({description:"The new email to set"}).email(),callbackURL:_.string({description:"The URL to redirect to after email verification"}).optional()}),use:[D],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 T("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 T("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 T("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new T("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await q(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 Kr=(e="Unknown")=>`<!DOCTYPE html>
|
|
3
|
+
`,`Current list of trustedOrigins: ${n}`),new $e("FORBIDDEN",{message:`Invalid ${a}`})})(o,"callbackURL")});import{APIError as L}from"better-call";import{z as v}from"zod";var J=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{base64Url as Kt}from"@better-auth/utils/base64";import{createHMAC as Yt}from"@better-auth/utils/hmac";async function _e(e,t){if(e.context.options.session?.cookieCache?.enabled){let o=Kt.encode(JSON.stringify({session:t,expiresAt:J(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await Yt("SHA-256","base64urlnopad").sign(e.context.secret,JSON.stringify(t))}),{padding:!1});if(o.length>4093)throw new Q("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 I(e,t,r,o){let n=e.context.authCookies.sessionToken.options,i=r?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...n,maxAge:i,...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 B(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 Xt=Object.defineProperty,er=Object.defineProperties,tr=Object.getOwnPropertyDescriptors,Be=Object.getOwnPropertySymbols,rr=Object.prototype.hasOwnProperty,or=Object.prototype.propertyIsEnumerable,Me=(e,t,r)=>t in e?Xt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,K=(e,t)=>{for(var r in t||(t={}))rr.call(t,r)&&Me(e,r,t[r]);if(Be)for(var r of Be(t))or.call(t,r)&&Me(e,r,t[r]);return e},Y=(e,t)=>er(e,tr(t)),nr=class extends Error{constructor(e,t,r){super(t||e.toString(),{cause:r}),this.status=e,this.statusText=t,this.error=r}},ir=async(e,t)=>{var r,o,n,i,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 u of t?.plugins||[]){if(u.init){let h=await((r=u.init)==null?void 0:r.call(u,e.toString(),t));a=h.options||a,e=h.url}d.onRequest.push((o=u.hooks)==null?void 0:o.onRequest),d.onResponse.push((n=u.hooks)==null?void 0:n.onResponse),d.onSuccess.push((i=u.hooks)==null?void 0:i.onSuccess),d.onError.push((s=u.hooks)==null?void 0:s.onError),d.onRetry.push((c=u.hooks)==null?void 0:c.onRetry)}return{url:e,options:a,hooks:d}},qe=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}},sr=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 ar(e){if(typeof e=="number")return new qe({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new qe(e);case"exponential":return new sr(e);default:throw new Error("Invalid retry strategy")}}var cr=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),n=r(e.auth.password);if(!o||!n)return t;t.authorization=`Basic ${btoa(`${o}:${n}`)}`}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},He=["get","post","put","patch","delete"];var dr=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function lr(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 dr.test(o)?"json":r.has(o)||o.startsWith("text/")?"text":"blob"}function ur(e){try{return JSON.parse(e),!0}catch{return!1}}function Ge(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 ze(e){try{return JSON.parse(e)}catch{return e}}function Fe(e){return typeof e=="function"}function pr(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<"u"&&Fe(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&Fe(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}function mr(e){let t=new Headers(e?.headers),r=cr(e);for(let[o,n]of Object.entries(r||{}))t.set(o,n);if(!t.has("content-type")){let o=fr(e?.body);o&&t.set("content-type",o)}return t}function fr(e){return Ge(e)?"application/json":null}function gr(e){if(!e?.body)return null;let t=new Headers(e?.headers);return Ge(e.body)&&!t.has("content-type")?JSON.stringify(e.body):e.body}function hr(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 He.includes(o)?o.toUpperCase():t?.body?"POST":"GET"}return t?.body?"POST":"GET"}function wr(e,t){let r;return!e?.signal&&e?.timeout&&(r=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}function yr(e,t){let{baseURL:r,params:o,query:n}=t||{query:{},params:{},baseURL:""},i=e.startsWith("http")?e.split("/").slice(0,3).join("/"):r;if(!i)throw new TypeError(`Invalid URL ${e}. Are you passing in a relative URL but not setting the baseURL?`);if(e.startsWith("@")){let h=e.toString().split("@")[1].split("/")[0];He.includes(h)&&(e=e.replace(`@${h}/`,"/"))}i.endsWith("/")||(i+="/");let[s,c]=e.replace(i,"").split("?"),a=new URLSearchParams(c);for(let[h,p]of Object.entries(n||{}))a.set(h,String(p));if(o)if(Array.isArray(o)){let h=s.split("/").filter(p=>p.startsWith(":"));for(let[p,l]of h.entries()){let y=o[p];s=s.replace(l,y)}}else for(let[h,p]of Object.entries(o))s=s.replace(`:${h}`,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}`,i)}var R=async(e,t)=>{var r,o,n,i,s,c,a,d;let{hooks:u,url:h,options:p}=await ir(e,t),l=pr(p),y=new AbortController,E=(r=p.signal)!=null?r:y.signal,S=yr(h,p),V=gr(p),P=mr(p),m=hr(h,p),g=Y(K({},p),{url:S,headers:P,body:V,method:m,signal:E});for(let C of u.onRequest)if(C){let x=await C(g);x instanceof Object&&(g=x)}("pipeTo"in g&&typeof g.pipeTo=="function"||typeof((o=t?.body)==null?void 0:o.pipe)=="function")&&("duplex"in g||(g.duplex="half"));let{clearTimeout:O}=wr(p,y),w=await l(g.url,g);O();let pe={response:w,request:g};for(let C of u.onResponse)if(C){let x=await C(Y(K({},pe),{response:(n=t?.hookOptions)!=null&&n.cloneResponse?w.clone():w}));x instanceof Response?w=x:x instanceof Object&&(w=x.response)}if(w.ok){if(!(g.method!=="HEAD"))return{data:"",error:null};let x=lr(w),z={data:"",response:w,request:g};if(x==="json"||x==="text"){let F=await w.text(),Ht=await((i=g.jsonParser)!=null?i:ze)(F);z.data=Ht}else z.data=await w[x]();g?.output&&g.output&&!g.disableValidation&&(z.data=g.output.parse(z.data));for(let F of u.onSuccess)F&&await F(Y(K({},z),{response:(s=t?.hookOptions)!=null&&s.cloneResponse?w.clone():w}));return t?.throw?z.data:{data:z.data,error:null}}let zt=(c=t?.jsonParser)!=null?c:ze,Le=await w.text(),Re=ur(Le)?await zt(Le):{},Ft={response:w,request:g,error:Y(K({},Re),{status:w.status,statusText:w.statusText})};for(let C of u.onError)C&&await C(Y(K({},Ft),{response:(a=t?.hookOptions)!=null&&a.cloneResponse?w.clone():w}));if(t?.retry){let C=ar(t.retry),x=(d=t.retryAttempt)!=null?d:0;if(await C.shouldAttemptRetry(x,w)){for(let F of u.onRetry)F&&await F(pe);let z=C.getDelay(x);return await new Promise(F=>setTimeout(F,z)),await R(e,Y(K({},t),{retryAttempt:x+1}))}}if(t?.throw)throw new nr(w.status,w.statusText,Re);return{data:null,error:Y(K({},Re),{status:w.status,statusText:w.statusText})}};import{APIError as Ur}from"better-call";import{decodeJwt as _r,decodeProtectedHeader as Tr,importJWK as vr,jwtVerify as Or}from"jose";import{createHash as br}from"@better-auth/utils/hash";import{base64Url as Ar}from"@better-auth/utils/base64";async function We(e){let t=await br("SHA-256").digest(e);return Ar.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?J(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function U({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,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",i.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),n){let u=await We(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",u)}if(s){let u=s.reduce((h,p)=>(h[p]=null,h),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return a&&d.searchParams.set("duration",a),d}import{jwtVerify as en}from"jose";async function k({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n,authentication:i}){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),i==="basic"){let h=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${h}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await R(n,{method:"POST",body:s,headers:c});if(d)throw d;return ge(a)}import{z as H}from"zod";import{APIError as Je}from"better-call";import{createHash as Rn}from"@better-auth/utils/hash";import{xchacha20poly1305 as En}from"@noble/ciphers/chacha";import{bytesToHex as _n,hexToBytes as Tn,utf8ToBytes as vn}from"@noble/ciphers/utils";import{managedNonce as Sn}from"@noble/ciphers/webcrypto";import{createHash as sn}from"@better-auth/utils/hash";import{SignJWT as kr}from"jose";async function Qe(e,t,r=3600){return await new kr(e).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(t))}import{scryptAsync as pn}from"@noble/hashes/scrypt";import{getRandomValues as fn}from"uncrypto";import{hex as hn}from"@better-auth/utils/hex";import{createRandomStringGenerator as Er}from"@better-auth/utils/random";var ce=Er("a-z","0-9","A-Z","-_");async function he(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Ne(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new Je("BAD_REQUEST",{message:"callbackURL is required"});let o=ce(128),n=ce(32),i=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:i,identifier:n,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 Je("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function Ze(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=H.object({callbackURL:H.string(),codeVerifier:H.string(),errorURL:H.string().optional(),newUserURL:H.string().optional(),expiresAt:H.number(),link:H.object({email:H.string(),userId:H.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 Ke=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${e.redirectURI||n}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>k({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let n=Tr(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let c=await Sr(i),{payload:a}=await Or(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=_r(r.idToken);if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email,...i},data:o}}}},Sr=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await R(`${t}${r}`);if(!o?.keys)throw new Ur("BAD_REQUEST",{message:"Keys not found"});let n=o.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await vr(n,n.alg)};var Ye=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>k({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 R("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}let n=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,...n},data:r}}});var Xe=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await U({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>k({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 R("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...n},data:r}}});var et=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),U({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>k({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await R("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1,{data:s}=await R("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,i=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:i,...c},data:o}}}};import{decodeJwt as Dr}from"jose";var Te=["info","success","warn","error","debug"];function xr(e,t){return Te.indexOf(t)<=Te.indexOf(e)}var M={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"}},Lr={info:M.fg.blue,success:M.fg.green,warn:M.fg.yellow,error:M.fg.red,debug:M.fg.magenta},Ir=(e,t)=>{let r=new Date().toISOString();return`${M.dim}${r}${M.reset} ${Lr[e]}${e.toUpperCase()}${M.reset} ${M.bright}[Better Auth]:${M.reset} ${t}`},Pr=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,s=[])=>{if(!t||!xr(r,n))return;let c=Ir(n,i);if(!e||typeof e.log!="function"){n==="error"?console.error(c,...s):n==="warn"?console.warn(c,...s):console.log(c,...s);return}e.log(n==="success"?"info":n,c,...s)};return Object.fromEntries(Te.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},j=Pr();var tt=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw j.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new Q("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new Q("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await U({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});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})=>k({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:n}=await R(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=Dr(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}}});import{decodeJwt as Cr}from"jose";var rt=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(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),U({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return k({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=Cr(n.idToken),s=e.profilePhotoSize||48;await R(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let u=await a.response.clone().arrayBuffer(),h=Buffer.from(u).toString("base64");i.picture=`data:image/jpeg;base64, ${h}`}catch(d){j.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0,...c},data:i}}}};var ot=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),U({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>k({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 R("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...n},data:r}}});var ne={isAction:!1};import{createRandomStringGenerator as jr}from"@better-auth/utils/random";var nt=e=>jr("a-z","A-Z","0-9")(e||32);import{decodeJwt as Nr}from"jose";var it=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),U({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>k({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 j.error("No idToken found in token"),null;let o=Nr(r),n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...n},data:o}}});var st=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),U({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})=>k({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 R("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=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,...n},data:r}}});var at=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await U({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await k({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await R("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...i},data:o}}}};var ct=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:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await U({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await k({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await R("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(i)return null;let s=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture,...s},data:n}}}};var ve=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),$r=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ve(`${t}/oauth/authorize`),tokenEndpoint:ve(`${t}/oauth/token`),userinfoEndpoint:ve(`${t}/api/v4/user`)}},dt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=$r(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let u=c||["read_user"];return e.scope&&u.push(...e.scope),await U({id:n,options:e,authorizationEndpoint:t,scopes:u,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>k({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 R(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 lt=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identity"];return e.scope&&n.push(...e.scope),U({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:n,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}),n={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`},{data:i,error:s}=await R("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:n,body:o.toString()});if(s)throw s;return ge(i)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await R("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let n=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],...n},data:r}}});import{z as Vr}from"zod";var Br={apple:Ke,discord:Ye,facebook:Xe,github:et,microsoft:rt,google:tt,spotify:ot,twitch:it,twitter:st,dropbox:at,linkedin:ct,gitlab:dt,reddit:lt},Oe=Object.keys(Br),ut=Vr.enum(Oe,{description:"OAuth2 provider to use"});import{z as $}from"zod";import{APIError as de}from"better-call";import{APIError as G}from"better-call";import{z as X}from"zod";function pt(e){try{return JSON.parse(e)}catch{return null}}var f={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",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"};import{createHMAC as Mr}from"@better-auth/utils/hmac";import{base64 as qr}from"@better-auth/utils/base64";import{binary as zr}from"@better-auth/utils/binary";var Se=()=>A("/get-session",{method:"GET",query:X.optional(X.object({disableCookieCache:X.boolean({description:"Disable cookie cache and fetch session from database"}).or(X.string().transform(e=>e==="true")).optional(),disableRefresh:X.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?pt(zr.decode(qr.decode(r))):null;if(o&&!await Mr("SHA-256","base64urlnopad").verify(e.context.secret,JSON.stringify(o.session),o.signature))return B(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let u=o.session;if(o.expiresAt<Date.now()||u.session.expiresAt<new Date){let p=e.context.authCookies.sessionData.name;e.setCookie(p,"",{maxAge:0})}else return e.json(u)}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return B(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n||e.query?.disableRefresh)return e.json(i);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let u=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:J(e.context.sessionConfig.expiresIn,"sec")});if(!u)return B(e),e.json(null,{status:401});let h=(u.expiresAt.valueOf()-Date.now())/1e3;return await I(e,{session:u,user:i.user},!1,{maxAge:h}),e.json({session:u,user:i.user})}return await _e(e,i),e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new G("INTERNAL_SERVER_ERROR",{message:f.FAILED_TO_GET_SESSION})}}),ee=async(e,t)=>{if(e.context.session)return e.context.session;let r=await Se()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},D=re(async e=>{let t=await ee(e);if(!t?.session)throw new G("UNAUTHORIZED");return{session:t}}),mt=re(async e=>{let t=await ee(e);if(!t?.session)throw new G("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 G("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),ft=()=>A("/list-sessions",{method:"GET",use:[D],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),gt=A("/revoke-session",{method:"POST",body:X.object({token:X.string({description:"The token to revoke"})}),use:[D],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 G("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new G("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 G("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ht=A("/revoke-sessions",{method:"POST",use:[D],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 G("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),wt=A("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[D],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 G("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});import{jwtVerify as Fr}from"jose";import{JWTExpired as Hr}from"jose/errors";async function q(e,t,r,o=3600){return await Qe({email:t.toLowerCase(),updateTo:r},e,o)}async function Gr(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new de("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await q(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),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 yt=A("/send-verification-email",{method:"POST",query:$.object({currentURL:$.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:$.object({email:$.string({description:"The email to send the verification email to"}).email(),callbackURL:$.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 de("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new de("BAD_REQUEST",{message:f.USER_NOT_FOUND});return await Gr(e,r.user),e.json({status:!0})}),bt=A("/verify-email",{method:"GET",query:$.object({token:$.string({description:"The token to verify the email"}),callbackURL:$.string({description:"The URL to redirect to after email verification"}).optional()}),use:[oe(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 de("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await Fr(r,new TextEncoder().encode(e.context.secret),{algorithms:["HS256"]})}catch(c){return c instanceof Hr?t("token_expired"):t("invalid_token")}let i=$.object({email:$.string().email(),updateTo:$.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(i.email);if(!s)return t("user_not_found");if(i.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!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),d=await q(e.context.secret,i.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(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification){let c=await ee(e);if(!c||c.user.email!==i.email){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new de("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await I(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 n=await e.context.internalAdapter.findOAuthUser(t.email.toLowerCase(),r.accountId,r.providerId).catch(a=>{throw j.error(`Better auth was unable to query your database.
|
|
4
|
+
Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user,s=!i;if(n){let a=n.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(([u,h])=>h!==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 fe&&j.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:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope})}catch(h){return j.error("Unable to link account",h),{error:"unable to link account",data:null}}}}else try{if(i=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&&i&&e.context.options.emailVerification?.sendOnSignUp){let a=await q(e.context.secret,i.email,void 0,e.context.options.emailVerification?.expiresIn),d=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:d,token:a},e.request)}}catch(a){return a instanceof At?{error:a.message,data:null,isRegister:!1}:{error:"unable to create user",data:null,isRegister:!1}}if(!i)return{error:"unable to create user",data:null,isRegister:!1};let c=await e.context.internalAdapter.createSession(i.id,e.request);return c?{data:{session:c,user:i},error:null,isRegister:s}:{error:"unable to create session",data:null,isRegister:!1}}var Rt=A("/sign-in/social",{method:"POST",query:v.object({currentURL:v.string().optional()}).optional(),body:v.object({callbackURL:v.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:v.string().optional(),errorCallbackURL:v.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:ut,disableRedirect:v.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:v.optional(v.object({token:v.string({description:"ID token from the provider"}),nonce:v.string({description:"Nonce used to generate the token"}).optional(),accessToken:v.string({description:"Access token from the provider"}).optional(),refreshToken:v.string({description:"Refresh token from the provider"}).optional(),expiresAt:v.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(i=>i.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 L("NOT_FOUND",{message:f.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 L("NOT_FOUND",{message:f.ID_TOKEN_NOT_SUPPORTED});let{token:i,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new L("UNAUTHORIZED",{message:f.INVALID_TOKEN});let a=await t.getUserInfo({idToken:i,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 L("UNAUTHORIZED",{message:f.FAILED_TO_GET_USER_INFO});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new L("UNAUTHORIZED",{message:f.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 L("UNAUTHORIZED",{message:d.error});return await I(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),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),kt=A("/sign-in/email",{method:"POST",body:v.object({email:v.string({description:"Email of the user"}),password:v.string({description:"Password of the user"}),callbackURL:v.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:v.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 L("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!v.string().email().safeParse(t).success)throw new L("BAD_REQUEST",{message:f.INVALID_EMAIL});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new L("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});let i=n.accounts.find(d=>d.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new L("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new L("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new L("UNAUTHORIZED",{message:f.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new L("UNAUTHORIZED",{message:f.EMAIL_NOT_VERIFIED});let d=await q(e.context.secret,n.user.email,void 0,e.context.options.emailVerification?.expiresIn),u=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:u,token:d},e.request),new L("FORBIDDEN",{message:f.EMAIL_NOT_VERIFIED})}let a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new L("UNAUTHORIZED",{message:f.FAILED_TO_CREATE_SESSION});return await I(e,{session:a,user:n.user},e.body.rememberMe===!1),e.json({redirect:!!e.body.callbackURL,token:a.token,url:e.body.callbackURL,user:{id:n.user.id,email:n.user.email,name:n.user.name,image:n.user.image,emailVerified:n.user.emailVerified,createdAt:n.user.createdAt,updatedAt:n.user.updatedAt}})});import{z as le}from"zod";var ye=le.object({code:le.string().optional(),error:le.string().optional(),error_description:le.string().optional(),state:le.string().optional()}),Et=A("/callback/:id",{method:["GET","POST"],body:ye.optional(),query:ye.optional(),metadata:ne},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(m){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",m),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n,error_description:i}=t;if(!n)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=${i}`);let s=e.context.socialProviders.find(m=>m.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:u,newUserURL:h}=await Ze(e),p;try{p=await s.validateAuthorizationCode({code:r,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${s.id}`})}catch(m){throw e.context.logger.error("",m),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let l=await s.getUserInfo(p).then(m=>m?.user);function y(m){let g=u||a||`${e.context.baseURL}/error`;throw g.includes("?")?g=`${g}&error=${m}`:g=`${g}?error=${m}`,e.redirect(g)}if(!l)return e.context.logger.error("Unable to get user info"),y("unable_to_get_user_info");if(!l.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),y("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!==l.email.toLowerCase())return y("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:s.id,accountId:l.id}))return y("unable_to_link_account");let g;try{g=a.toString()}catch{g=a}throw e.redirect(g)}let E=await we(e,{userInfo:{...l,email:l.email,name:l.name||l.email},account:{providerId:s.id,accountId:l.id,...p,scope:p.scopes?.join(",")},callbackURL:a});if(E.error)return e.context.logger.error(E.error.split(" ").join("_")),y(E.error.split(" ").join("_"));let{session:S,user:V}=E.data;await I(e,{session:S,user:V});let P;try{P=(E.isRegister&&h||a).toString()}catch{P=E.isRegister&&h||a}throw e.redirect(P)});import"zod";import{APIError as Wr}from"better-call";var Ut=A("/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 B(e),new Wr("BAD_REQUEST",{message:f.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(t),B(e),e.json({success:!0})});import{z as N}from"zod";import{APIError as ue}from"better-call";function _t(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function Qr(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var Tt=A("/forget-password",{method:"POST",body:N.object({email:N.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:N.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 ue("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 n=60*60*1,i=J(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=nt(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:i});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})}),vt=A("/reset-password/:token",{method:"GET",query:N.object({callbackURL:N.string({description:"The URL to redirect the user to reset their password"})}),use:[oe(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(_t(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(_t(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Qr(e.context,r,{token:t}))}),Ot=A("/reset-password",{query:N.optional(N.object({token:N.string().optional(),currentURL:N.string().optional()})),method:"POST",body:N.object({newPassword:N.string({description:"The new password to set"}),token:N.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 ue("BAD_REQUEST",{message:f.INVALID_TOKEN});let{newPassword:r}=e.body,o=e.context.password?.config.minPasswordLength,n=e.context.password?.config.maxPasswordLength;if(r.length<o)throw new ue("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});if(r.length>n)throw new ue("BAD_REQUEST",{message:f.PASSWORD_TOO_LONG});let i=`reset-password:${t}`,s=await e.context.internalAdapter.findVerificationValue(i);if(!s||s.expiresAt<new Date)throw new ue("BAD_REQUEST",{message:f.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(h=>h.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}))});import{z as _}from"zod";import{APIError as T}from"better-call";import{z as b}from"zod";import{APIError as Jr}from"better-call";var Na=b.object({id:b.string(),providerId:b.string(),accountId:b.string(),userId:b.string(),accessToken:b.string().nullish(),refreshToken:b.string().nullish(),idToken:b.string().nullish(),accessTokenExpiresAt:b.date().nullish(),refreshTokenExpiresAt:b.date().nullish(),scope:b.string().nullish(),password:b.string().nullish(),createdAt:b.date().default(()=>new Date),updatedAt:b.date().default(()=>new Date)}),$a=b.object({id:b.string(),email:b.string().transform(e=>e.toLowerCase()),emailVerified:b.boolean().default(!1),name:b.string(),image:b.string().nullish(),createdAt:b.date().default(()=>new Date),updatedAt:b.date().default(()=>new Date)}),Va=b.object({id:b.string(),userId:b.string(),expiresAt:b.date(),createdAt:b.date().default(()=>new Date),updatedAt:b.date().default(()=>new Date),token:b.string(),ipAddress:b.string().nullish(),userAgent:b.string().nullish()}),Ba=b.object({id:b.string(),value:b.string(),createdAt:b.date().default(()=>new Date),updatedAt:b.date().default(()=>new Date),expiresAt:b.date(),identifier:b.string()});function Zr(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function Kr(e,t){let r=t.action||"create",o=t.fields,n={};for(let i in o){if(i in e){if(o[i].input===!1){if(o[i].defaultValue){n[i]=o[i].defaultValue;continue}continue}if(o[i].validator?.input&&e[i]!==void 0){n[i]=o[i].validator.input.parse(e[i]);continue}if(o[i].transform?.input&&e[i]!==void 0){n[i]=o[i].transform?.input(e[i]);continue}n[i]=e[i];continue}if(o[i].defaultValue&&r==="create"){n[i]=o[i].defaultValue;continue}if(o[i].required&&r==="create")throw new Jr("BAD_REQUEST",{message:`${i} is required`})}return n}function be(e,t,r){let o=Zr(e,"user");return Kr(t||{},{fields:o,action:r})}var St=()=>A("/update-user",{method:"POST",body:_.record(_.string(),_.any()),use:[D],metadata:{openapi:{description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"}}}}}}}}}},async e=>{let t=e.body;if(t.email)throw new T("BAD_REQUEST",{message:f.EMAIL_CAN_NOT_BE_UPDATED});let{name:r,image:o,...n}=t,i=e.context.session;if(o===void 0&&r===void 0&&Object.keys(n).length===0)return e.json({status:!0});let s=be(e.context.options,n,"update"),c=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await I(e,{session:i.session,user:c}),e.json({status:!0})}),xt=A("/change-password",{method:"POST",body:_.object({newPassword:_.string({description:"The new password to set"}),currentPassword:_.string({description:"The current password"}),revokeOtherSessions:_.boolean({description:"Revoke all other sessions"}).optional()}),use:[D],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,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new T("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new T("BAD_REQUEST",{message:f.PASSWORD_TOO_LONG});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(p=>p.providerId==="credential"&&p.password);if(!a||!a.password)throw new T("BAD_REQUEST",{message:f.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 T("BAD_REQUEST",{message:f.INVALID_PASSWORD});await e.context.internalAdapter.updateAccount(a.id,{password:d});let h=null;if(o){await e.context.internalAdapter.deleteSessions(n.user.id);let p=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!p)throw new T("INTERNAL_SERVER_ERROR",{message:f.FAILED_TO_GET_SESSION});await I(e,{session:p,user:n.user}),h=p.token}return e.json({token:h,user:{id:n.user.id,email:n.user.email,name:n.user.name,image:n.user.image,emailVerified:n.user.emailVerified,createdAt:n.user.createdAt,updatedAt:n.user.updatedAt}})}),Lt=A("/set-password",{method:"POST",body:_.object({newPassword:_.string()}),metadata:{SERVER_ONLY:!0},use:[D]},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 T("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new T("BAD_REQUEST",{message:f.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 T("BAD_REQUEST",{message:"user already has a password"})}),It=A("/delete-user",{method:"POST",use:[D],body:_.object({callbackURL:_.string().optional(),password:_.string().optional(),token:_.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 T("NOT_FOUND");let t=e.context.session;if(e.body.password){let i=(await e.context.internalAdapter.findAccounts(t.user.id)).find(c=>c.providerId==="credential"&&c.password);if(!i||!i.password)throw new T("BAD_REQUEST",{message:f.CREDENTIAL_ACCOUNT_NOT_FOUND});if(!await e.context.password.verify({hash:i.password,password:e.body.password}))throw new T("BAD_REQUEST",{message:f.INVALID_PASSWORD})}else if(e.context.options.session?.freshAge){let n=t.session.createdAt.getTime(),i=e.context.options.session.freshAge;if(Date.now()-n>i)throw new T("BAD_REQUEST",{message:f.SESSION_EXPIRED})}if(e.body.token)return await xe({...e,query:{token:e.body.token}}),e.json({success:!0,message:"User deleted"});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=ce(32,"0-9","a-z");await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${n}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let i=`${e.context.baseURL}/delete-user/callback?token=${n}&callbackURL=${e.body.callbackURL||"/"}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:i,token:n},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),B(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})}),xe=A("/delete-user/callback",{method:"GET",query:_.object({token:_.string(),callbackURL:_.string().optional()}),use:[oe(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 T("NOT_FOUND");let t=await ee(e);if(!t)throw new T("NOT_FOUND",{message:f.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 T("NOT_FOUND",{message:f.INVALID_TOKEN});if(r.value!==t.user.id)throw new T("NOT_FOUND",{message:f.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),B(e);let n=e.context.options.user.deleteUser?.afterDelete;if(n&&await n(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||"/");return e.json({success:!0,message:"User deleted"})}),Pt=A("/change-email",{method:"POST",query:_.object({currentURL:_.string().optional()}).optional(),body:_.object({newEmail:_.string({description:"The new email to set"}).email(),callbackURL:_.string({description:"The URL to redirect to after email verification"}).optional()}),use:[D],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 T("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 T("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 T("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new T("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await q(e.context.secret,e.context.session.user.email,e.body.newEmail,e.context.options.emailVerification?.expiresIn),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 Yr=(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>`,Dt=A("/error",{method:"GET",metadata:{...ne,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(Kr(t),{headers:{"Content-Type":"text/html"}})});var Ct=A("/ok",{method:"GET",metadata:{...ne,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 ie}from"zod";import{APIError as W}from"better-call";var jt=()=>A("/sign-up/email",{method:"POST",query:ie.object({currentURL:ie.string().optional()}).optional(),body:ie.record(ie.string(),ie.any()),metadata:{openapi:{description:"Sign up a user using email and password",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},email:{type:"string",description:"The email of the user"},password:{type:"string",description:"The password of the user"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["name","email","password"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"The id of the user"},email:{type:"string",description:"The email of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"},emailVerified:{type:"boolean",description:"If the email is verified"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new W("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:n,image:i,callbackURL:s,...c}=t;if(!ie.string().email().safeParse(o).success)throw new W("BAD_REQUEST",{message:f.INVALID_EMAIL});let d=e.context.password.config.minPasswordLength;if(n.length<d)throw e.context.logger.error("Password is too short"),new W("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});let u=e.context.password.config.maxPasswordLength;if(n.length>u)throw e.context.logger.error("Password is too long"),new W("BAD_REQUEST",{message:f.PASSWORD_TOO_LONG});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new W("UNPROCESSABLE_ENTITY",{message:f.USER_ALREADY_EXISTS});let p=be(e.context.options,c),l;try{if(l=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...p,emailVerified:!1}),!l)throw new W("BAD_REQUEST",{message:f.FAILED_TO_CREATE_USER})}catch(S){throw fe&&e.context.logger.error("Failed to create user",S),new W("UNPROCESSABLE_ENTITY",{message:f.FAILED_TO_CREATE_USER,details:S})}if(!l)throw new W("UNPROCESSABLE_ENTITY",{message:f.FAILED_TO_CREATE_USER});let y=await e.context.password.hash(n);if(await e.context.internalAdapter.linkAccount({userId:l.id,providerId:"credential",accountId:l.id,password:y}),e.context.options.emailVerification?.sendOnSignUp||e.context.options.emailAndPassword.requireEmailVerification){let S=await q(e.context.secret,l.email),B=`${e.context.baseURL}/verify-email?token=${S}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:l,url:B,token:S},e.request)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({token:null,user:{id:l.id,email:l.email,name:l.name,image:l.image,emailVerified:l.emailVerified,createdAt:l.createdAt,updatedAt:l.updatedAt}});let E=await e.context.internalAdapter.createSession(l.id,e.request);if(!E)throw new W("BAD_REQUEST",{message:f.FAILED_TO_CREATE_SESSION});return await P(e,{session:E,user:l}),e.json({token:E.token,user:{id:l.id,email:l.email,name:l.name,image:l.image,emailVerified:l.emailVerified,createdAt:l.createdAt,updatedAt:l.updatedAt}})});import{z as te}from"zod";import{APIError as Ae}from"better-call";var Nt=A("/list-accounts",{method:"GET",use:[D],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(",")||[]})))}),$t=A("/link-social",{method:"POST",requireHeaders:!0,query:te.object({currentURL:te.string().optional()}).optional(),body:te.object({callbackURL:te.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:te.enum(Oe,{description:"The OAuth2 provider to use"})}),use:[D],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 Ae("BAD_REQUEST",{message:f.SOCIAL_ACCOUNT_ALREADY_LINKED});let n=e.context.socialProviders.find(c=>c.id===e.body.provider);if(!n)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Ae("NOT_FOUND",{message:f.PROVIDER_NOT_FOUND});let i=await he(e,{userId:t.user.id,email:t.user.email}),s=await n.createAuthorizationURL({state:i.state,codeVerifier:i.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${n.id}`});return e.json({url:s.toString(),redirect:!0})}),Bt=A("/unlink-account",{method:"POST",body:te.object({providerId:te.string()}),use:[mt]},async e=>{let t=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(t.length===1)throw new Ae("BAD_REQUEST",{message:f.FAILED_TO_UNLINK_LAST_ACCOUNT});if(!t.find(o=>o.providerId===e.body.providerId))throw new Ae("BAD_REQUEST",{message:f.ACCOUNT_NOT_FOUND});return await e.context.internalAdapter.deleteAccount(e.body.providerId,e.context.session.user.id),e.json({status:!0})});function Vt(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let r="127.0.0.1";if(je)return r;let n=t.advanced?.ipAddress?.ipAddressHeaders||["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],i=e instanceof Request?e.headers:e;for(let s of n){let c=i.get(s);if(typeof c=="string"){let a=c.split(",")[0].trim();if(a)return a}}return null}function Yr(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function Xr(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":e.toString()}})}function eo(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function to(e,t){let r="rateLimit",o=e.adapter;return{get:async n=>(await o.findMany({model:r,where:[{field:"key",value:n}]}))[0],set:async(n,i,s)=>{try{s?await o.updateMany({model:t??"rateLimit",where:[{field:"key",value:n}],update:{count:i.count,lastRequest:i.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:n,count:i.count,lastRequest:i.lastRequest}})}catch(c){e.logger.error("Error setting rate limit",c)}}}}var Mt=new Map;function ro(e){return e.options.rateLimit?.customStorage?e.options.rateLimit.customStorage:e.rateLimit.storage==="secondary-storage"?{get:async r=>{let o=await e.options.secondaryStorage?.get(r);return o?JSON.parse(o):void 0},set:async(r,o)=>{await e.options.secondaryStorage?.set?.(r,JSON.stringify(o))}}:e.rateLimit.storage==="memory"?{async get(r){return Mt.get(r)},async set(r,o,n){Mt.set(r,o)}}:to(e,e.rateLimit.modelName)}async function qt(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,"").split("?")[0],n=t.rateLimit.window,i=t.rateLimit.max,s=Vt(e,t.options)+o,a=oo().find(p=>p.pathMatcher(o));a&&(n=a.window,i=a.max);for(let p of t.options.plugins||[])if(p.rateLimit){let l=p.rateLimit.find(y=>y.pathMatcher(o));if(l){n=l.window,i=l.max;break}}if(t.rateLimit.customRules){let p=Object.keys(t.rateLimit.customRules).find(l=>l.includes("*")?se(l)(o):l===o);if(p){let l=t.rateLimit.customRules[p],y=typeof l=="function"?await l(e):l;y&&(n=y.window,i=y.max)}}let d=ro(t),u=await d.get(s),h=Date.now();if(!u)await d.set(s,{key:s,count:1,lastRequest:h});else{let p=h-u.lastRequest;if(Yr(i,n,u)){let l=eo(u.lastRequest,n);return Xr(l)}else p>n*1e3?await d.set(s,{...u,count:1,lastRequest:h},!0):await d.set(s,{...u,count:u.count+1,lastRequest:h},!0)}}function oo(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")||t.startsWith("/change-password")||t.startsWith("/change-email")},window:10,max:3}]}import"defu";import{APIError as At}from"better-call";function lo(e,t){let r=t.plugins?.reduce((c,a)=>({...c,...a.endpoints}),{}),o=t.plugins?.map(c=>c.middlewares?.map(a=>{let d=async u=>a.middleware({...u,context:{...e,...u.context}});return d.path=a.path,d.options=a.middleware.options,d.headers=a.middleware.headers,{path:a.path,middleware:d}})).filter(c=>c!==void 0).flat()||[],i={...{signInSocial:Rt,callbackOAuth:Et,getSession:Se(),signOut:Ut,signUpEmail:jt(),signInEmail:kt,forgetPassword:Tt,resetPassword:Ot,verifyEmail:bt,sendVerificationEmail:yt,changeEmail:It,changePassword:Lt,setPassword:xt,updateUser:St(),deleteUser:Pt,forgetPasswordCallback:vt,listSessions:ft(),revokeSession:gt,revokeSessions:ht,revokeOtherSessions:wt,linkSocialAccount:$t,listUserAccounts:Nt,deleteUserCallback:Le,unlinkAccount:Bt},...r,ok:Ct,error:Dt},s={};for(let[c,a]of Object.entries(i))s[c]=async(d={})=>{a.headers=new Headers;let u={setHeader(m,g){a.headers.set(m,g)},setCookie(m,g,O){ao(a.headers,m,g,O)},getCookie(m,g){let w=d.headers?.get("cookie");return io(w||"",m,g)},getSignedCookie(m,g,O){let w=d.headers;return w?so(w,g,m,O):null},async setSignedCookie(m,g,O,w){await co(a.headers,m,g,O,w)},redirect(m){return a.headers.set("Location",m),new J("FOUND")},responseHeader:a.headers},h=await e,p=null,l={...u,...d,path:a.path,context:{...h,...d.context,session:null,setNewSession:function(m){this.newSession=m,p=m}}},y=t.plugins||[],E=y.map(m=>{if(m.hooks?.before)return m.hooks.before}).filter(m=>m!==void 0).flat(),S=y.map(m=>{if(m.hooks?.after)return m.hooks.after}).filter(m=>m!==void 0).flat();t.hooks?.before&&E.push({matcher:()=>!0,handler:t.hooks.before}),t.hooks?.after&&S.push({matcher:()=>!0,handler:t.hooks.after});for(let m of E){if(!m.matcher(l))continue;let g=await m.handler(l);if(g&&"context"in g){l={...l,...g.context};continue}if(g)return g}let B;try{B=await a(l),p&&(l.context.newSession=p)}catch(m){if(p&&(l.context.newSession=p),m instanceof J){if(!S?.length)throw m.headers=a.headers,m;l.context.returned=m,l.context.returned.headers=a.headers;for(let g of S||[])if(g.matcher(l))try{let w=await g.handler(l);w&&"response"in w&&(l.context.returned=w.response)}catch(w){if(w instanceof J){l.context.returned=w;continue}throw w}if(l.context.returned instanceof J)throw l.context.returned.headers=a.headers,l.context.returned;return l.context.returned}throw m}l.context.returned=B,l.responseHeader=a.headers;for(let m of S)if(m.matcher(l))try{let O=await m.handler(l);if(O)if("responseHeader"in O){let w=O.responseHeader;l.responseHeader=w}else l.context.returned=O}catch(O){if(O instanceof J){l.context.returned=O;continue}throw O}let I=l.context.returned;if(I instanceof Response&&a.headers.forEach((m,g)=>{g==="set-cookie"?I.headers.append(g,m):I.headers.set(g,m)}),I instanceof J)throw I.headers=a.headers,I;return I},s[c].path=a.path,s[c].method=a.method,s[c].options=a.options,s[c].headers=a.headers;return{api:s,middlewares:o}}var Xc=(e,t)=>{let{api:r,middlewares:o}=lo(e,t),n=new URL(e.baseURL).pathname;return no(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:Be},...o],async onRequest(i){for(let s of e.options.plugins||[])if(s.onRequest){let c=await s.onRequest(i,e);if(c&&"response"in c)return c.response}return qt(i,e)},async onResponse(i){for(let s of e.options.plugins||[])if(s.onResponse){let c=await s.onResponse(i,e);if(c)return c.response}return i},onError(i){if(i instanceof J&&i.status==="FOUND")return;if(t.onAPIError?.throw)throw i;if(t.onAPIError?.onError){t.onAPIError.onError(i,e);return}let s=t.logger?.level,c=s==="error"||s==="warn"||s==="debug"?j:void 0;if(t.logger?.disabled!==!0){if(i&&typeof i=="object"&&"message"in i&&typeof i.message=="string"&&(i.message.includes("no column")||i.message.includes("column")||i.message.includes("relation")||i.message.includes("table")||i.message.includes("does not exist"))){e.logger?.error(i.message);return}i instanceof J?(i.status==="INTERNAL_SERVER_ERROR"&&e.logger.error(i.status,i),c?.error(i.message)):e.logger?.error(i&&typeof i=="object"&&"name"in i?i.name:"",i)}}})};export{At as APIError,Et as callbackOAuth,It as changeEmail,Lt as changePassword,A as createAuthEndpoint,re as createAuthMiddleware,q as createEmailVerificationToken,Pt as deleteUser,Le as deleteUserCallback,Dt as error,Tt as forgetPassword,vt as forgetPasswordCallback,mt as freshSessionMiddleware,lo as getEndpoints,Se as getSession,ee as getSessionFromCtx,$t as linkSocialAccount,ft as listSessions,Nt as listUserAccounts,Ct as ok,Ie as optionsMiddleware,oe as originCheck,Be as originCheckMiddleware,Ot as resetPassword,wt as revokeOtherSessions,gt as revokeSession,ht as revokeSessions,Xc as router,yt as sendVerificationEmail,Hr as sendVerificationEmailFn,D as sessionMiddleware,xt as setPassword,kt as signInEmail,Rt as signInSocial,Ut as signOut,jt as signUpEmail,Bt as unlinkAccount,St as updateUser,bt as verifyEmail};
|
|
84
|
+
</html>`,Dt=A("/error",{method:"GET",metadata:{...ne,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(Yr(t),{headers:{"Content-Type":"text/html"}})});var Ct=A("/ok",{method:"GET",metadata:{...ne,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 ie}from"zod";import{APIError as W}from"better-call";var jt=()=>A("/sign-up/email",{method:"POST",query:ie.object({currentURL:ie.string().optional()}).optional(),body:ie.record(ie.string(),ie.any()),metadata:{openapi:{description:"Sign up a user using email and password",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},email:{type:"string",description:"The email of the user"},password:{type:"string",description:"The password of the user"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["name","email","password"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"The id of the user"},email:{type:"string",description:"The email of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"},emailVerified:{type:"boolean",description:"If the email is verified"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new W("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:n,image:i,callbackURL:s,...c}=t;if(!ie.string().email().safeParse(o).success)throw new W("BAD_REQUEST",{message:f.INVALID_EMAIL});let d=e.context.password.config.minPasswordLength;if(n.length<d)throw e.context.logger.error("Password is too short"),new W("BAD_REQUEST",{message:f.PASSWORD_TOO_SHORT});let u=e.context.password.config.maxPasswordLength;if(n.length>u)throw e.context.logger.error("Password is too long"),new W("BAD_REQUEST",{message:f.PASSWORD_TOO_LONG});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new W("UNPROCESSABLE_ENTITY",{message:f.USER_ALREADY_EXISTS});let p=be(e.context.options,c),l;try{if(l=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...p,emailVerified:!1}),!l)throw new W("BAD_REQUEST",{message:f.FAILED_TO_CREATE_USER})}catch(S){throw fe&&e.context.logger.error("Failed to create user",S),new W("UNPROCESSABLE_ENTITY",{message:f.FAILED_TO_CREATE_USER,details:S})}if(!l)throw new W("UNPROCESSABLE_ENTITY",{message:f.FAILED_TO_CREATE_USER});let y=await e.context.password.hash(n);if(await e.context.internalAdapter.linkAccount({userId:l.id,providerId:"credential",accountId:l.id,password:y}),e.context.options.emailVerification?.sendOnSignUp||e.context.options.emailAndPassword.requireEmailVerification){let S=await q(e.context.secret,l.email,void 0,e.context.options.emailVerification?.expiresIn),V=`${e.context.baseURL}/verify-email?token=${S}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:l,url:V,token:S},e.request)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({token:null,user:{id:l.id,email:l.email,name:l.name,image:l.image,emailVerified:l.emailVerified,createdAt:l.createdAt,updatedAt:l.updatedAt}});let E=await e.context.internalAdapter.createSession(l.id,e.request);if(!E)throw new W("BAD_REQUEST",{message:f.FAILED_TO_CREATE_SESSION});return await I(e,{session:E,user:l}),e.json({token:E.token,user:{id:l.id,email:l.email,name:l.name,image:l.image,emailVerified:l.emailVerified,createdAt:l.createdAt,updatedAt:l.updatedAt}})});import{z as te}from"zod";import{APIError as Ae}from"better-call";var Nt=A("/list-accounts",{method:"GET",use:[D],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(",")||[]})))}),$t=A("/link-social",{method:"POST",requireHeaders:!0,query:te.object({currentURL:te.string().optional()}).optional(),body:te.object({callbackURL:te.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:te.enum(Oe,{description:"The OAuth2 provider to use"})}),use:[D],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 Ae("BAD_REQUEST",{message:f.SOCIAL_ACCOUNT_ALREADY_LINKED});let n=e.context.socialProviders.find(c=>c.id===e.body.provider);if(!n)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Ae("NOT_FOUND",{message:f.PROVIDER_NOT_FOUND});let i=await he(e,{userId:t.user.id,email:t.user.email}),s=await n.createAuthorizationURL({state:i.state,codeVerifier:i.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${n.id}`});return e.json({url:s.toString(),redirect:!0})}),Vt=A("/unlink-account",{method:"POST",body:te.object({providerId:te.string()}),use:[mt]},async e=>{let t=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(t.length===1)throw new Ae("BAD_REQUEST",{message:f.FAILED_TO_UNLINK_LAST_ACCOUNT});if(!t.find(o=>o.providerId===e.body.providerId))throw new Ae("BAD_REQUEST",{message:f.ACCOUNT_NOT_FOUND});return await e.context.internalAdapter.deleteAccount(e.body.providerId,e.context.session.user.id),e.json({status:!0})});function Bt(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let r="127.0.0.1";if(je)return r;let n=t.advanced?.ipAddress?.ipAddressHeaders||["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],i=e instanceof Request?e.headers:e;for(let s of n){let c=i.get(s);if(typeof c=="string"){let a=c.split(",")[0].trim();if(a)return a}}return null}function Xr(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function eo(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":e.toString()}})}function to(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function ro(e,t){let r="rateLimit",o=e.adapter;return{get:async n=>(await o.findMany({model:r,where:[{field:"key",value:n}]}))[0],set:async(n,i,s)=>{try{s?await o.updateMany({model:t??"rateLimit",where:[{field:"key",value:n}],update:{count:i.count,lastRequest:i.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:n,count:i.count,lastRequest:i.lastRequest}})}catch(c){e.logger.error("Error setting rate limit",c)}}}}var Mt=new Map;function oo(e){return e.options.rateLimit?.customStorage?e.options.rateLimit.customStorage:e.rateLimit.storage==="secondary-storage"?{get:async r=>{let o=await e.options.secondaryStorage?.get(r);return o?JSON.parse(o):void 0},set:async(r,o)=>{await e.options.secondaryStorage?.set?.(r,JSON.stringify(o))}}:e.rateLimit.storage==="memory"?{async get(r){return Mt.get(r)},async set(r,o,n){Mt.set(r,o)}}:ro(e,e.rateLimit.modelName)}async function qt(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,"").split("?")[0],n=t.rateLimit.window,i=t.rateLimit.max,s=Bt(e,t.options)+o,a=no().find(p=>p.pathMatcher(o));a&&(n=a.window,i=a.max);for(let p of t.options.plugins||[])if(p.rateLimit){let l=p.rateLimit.find(y=>y.pathMatcher(o));if(l){n=l.window,i=l.max;break}}if(t.rateLimit.customRules){let p=Object.keys(t.rateLimit.customRules).find(l=>l.includes("*")?se(l)(o):l===o);if(p){let l=t.rateLimit.customRules[p],y=typeof l=="function"?await l(e):l;y&&(n=y.window,i=y.max)}}let d=oo(t),u=await d.get(s),h=Date.now();if(!u)await d.set(s,{key:s,count:1,lastRequest:h});else{let p=h-u.lastRequest;if(Xr(i,n,u)){let l=to(u.lastRequest,n);return eo(l)}else p>n*1e3?await d.set(s,{...u,count:1,lastRequest:h},!0):await d.set(s,{...u,count:u.count+1,lastRequest:h},!0)}}function no(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")||t.startsWith("/change-password")||t.startsWith("/change-email")},window:10,max:3}]}import"defu";import{APIError as At}from"better-call";function uo(e,t){let r=t.plugins?.reduce((c,a)=>({...c,...a.endpoints}),{}),o=t.plugins?.map(c=>c.middlewares?.map(a=>{let d=async u=>a.middleware({...u,context:{...e,...u.context}});return d.path=a.path,d.options=a.middleware.options,d.headers=a.middleware.headers,{path:a.path,middleware:d}})).filter(c=>c!==void 0).flat()||[],i={...{signInSocial:Rt,callbackOAuth:Et,getSession:Se(),signOut:Ut,signUpEmail:jt(),signInEmail:kt,forgetPassword:Tt,resetPassword:Ot,verifyEmail:bt,sendVerificationEmail:yt,changeEmail:Pt,changePassword:xt,setPassword:Lt,updateUser:St(),deleteUser:It,forgetPasswordCallback:vt,listSessions:ft(),revokeSession:gt,revokeSessions:ht,revokeOtherSessions:wt,linkSocialAccount:$t,listUserAccounts:Nt,deleteUserCallback:xe,unlinkAccount:Vt},...r,ok:Ct,error:Dt},s={};for(let[c,a]of Object.entries(i))s[c]=async(d={})=>{a.headers=new Headers;let u={setHeader(m,g){a.headers.set(m,g)},setCookie(m,g,O){co(a.headers,m,g,O)},getCookie(m,g){let w=d.headers?.get("cookie");return so(w||"",m,g)},getSignedCookie(m,g,O){let w=d.headers;return w?ao(w,g,m,O):null},async setSignedCookie(m,g,O,w){await lo(a.headers,m,g,O,w)},redirect(m){return a.headers.set("Location",m),new Z("FOUND")},responseHeader:a.headers},h=await e,p=null,l={...u,...d,path:a.path,context:{...h,...d.context,session:null,setNewSession:function(m){this.newSession=m,p=m}}},y=t.plugins||[],E=y.map(m=>{if(m.hooks?.before)return m.hooks.before}).filter(m=>m!==void 0).flat(),S=y.map(m=>{if(m.hooks?.after)return m.hooks.after}).filter(m=>m!==void 0).flat();t.hooks?.before&&E.push({matcher:()=>!0,handler:t.hooks.before}),t.hooks?.after&&S.push({matcher:()=>!0,handler:t.hooks.after});for(let m of E){if(!m.matcher(l))continue;let g=await m.handler(l);if(g&&"context"in g){l={...l,...g.context};continue}if(g)return g}let V;try{V=await a(l),p&&(l.context.newSession=p)}catch(m){if(p&&(l.context.newSession=p),m instanceof Z){if(!S?.length)throw m.headers=a.headers,m;l.context.returned=m,l.context.returned.headers=a.headers;for(let g of S||[])if(g.matcher(l))try{let w=await g.handler(l);w&&"response"in w&&(l.context.returned=w.response)}catch(w){if(w instanceof Z){l.context.returned=w;continue}throw w}if(l.context.returned instanceof Z)throw l.context.returned.headers=a.headers,l.context.returned;return l.context.returned}throw m}l.context.returned=V,l.responseHeader=a.headers;for(let m of S)if(m.matcher(l))try{let O=await m.handler(l);if(O)if("responseHeader"in O){let w=O.responseHeader;l.responseHeader=w}else l.context.returned=O}catch(O){if(O instanceof Z){l.context.returned=O;continue}throw O}let P=l.context.returned;if(P instanceof Response&&a.headers.forEach((m,g)=>{g==="set-cookie"?P.headers.append(g,m):P.headers.set(g,m)}),P instanceof Z)throw P.headers=a.headers,P;return P},s[c].path=a.path,s[c].method=a.method,s[c].options=a.options,s[c].headers=a.headers;return{api:s,middlewares:o}}var td=(e,t)=>{let{api:r,middlewares:o}=uo(e,t),n=new URL(e.baseURL).pathname;return io(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:Ve},...o],async onRequest(i){for(let s of e.options.plugins||[])if(s.onRequest){let c=await s.onRequest(i,e);if(c&&"response"in c)return c.response}return qt(i,e)},async onResponse(i){for(let s of e.options.plugins||[])if(s.onResponse){let c=await s.onResponse(i,e);if(c)return c.response}return i},onError(i){if(i instanceof Z&&i.status==="FOUND")return;if(t.onAPIError?.throw)throw i;if(t.onAPIError?.onError){t.onAPIError.onError(i,e);return}let s=t.logger?.level,c=s==="error"||s==="warn"||s==="debug"?j:void 0;if(t.logger?.disabled!==!0){if(i&&typeof i=="object"&&"message"in i&&typeof i.message=="string"&&(i.message.includes("no column")||i.message.includes("column")||i.message.includes("relation")||i.message.includes("table")||i.message.includes("does not exist"))){e.logger?.error(i.message);return}i instanceof Z?(i.status==="INTERNAL_SERVER_ERROR"&&e.logger.error(i.status,i),c?.error(i.message)):e.logger?.error(i&&typeof i=="object"&&"name"in i?i.name:"",i)}}})};export{At as APIError,Et as callbackOAuth,Pt as changeEmail,xt as changePassword,A as createAuthEndpoint,re as createAuthMiddleware,q as createEmailVerificationToken,It as deleteUser,xe as deleteUserCallback,Dt as error,Tt as forgetPassword,vt as forgetPasswordCallback,mt as freshSessionMiddleware,uo as getEndpoints,Se as getSession,ee as getSessionFromCtx,$t as linkSocialAccount,ft as listSessions,Nt as listUserAccounts,Ct as ok,Pe as optionsMiddleware,oe as originCheck,Ve as originCheckMiddleware,Ot as resetPassword,wt as revokeOtherSessions,gt as revokeSession,ht as revokeSessions,td as router,yt as sendVerificationEmail,Gr as sendVerificationEmailFn,D as sessionMiddleware,Lt as setPassword,kt as signInEmail,Rt as signInSocial,Ut as signOut,jt as signUpEmail,Vt as unlinkAccount,St as updateUser,bt as verifyEmail};
|
|
@@ -591,15 +591,15 @@ declare const verificationSchema: z.ZodObject<{
|
|
|
591
591
|
expiresAt: z.ZodDate;
|
|
592
592
|
identifier: z.ZodString;
|
|
593
593
|
}, "strip", z.ZodTypeAny, {
|
|
594
|
-
id: string;
|
|
595
594
|
value: string;
|
|
595
|
+
id: string;
|
|
596
596
|
createdAt: Date;
|
|
597
597
|
updatedAt: Date;
|
|
598
598
|
expiresAt: Date;
|
|
599
599
|
identifier: string;
|
|
600
600
|
}, {
|
|
601
|
-
id: string;
|
|
602
601
|
value: string;
|
|
602
|
+
id: string;
|
|
603
603
|
expiresAt: Date;
|
|
604
604
|
identifier: string;
|
|
605
605
|
createdAt?: Date | undefined;
|
|
@@ -771,6 +771,12 @@ type BetterAuthOptions = {
|
|
|
771
771
|
* Auto signin the user after they verify their email
|
|
772
772
|
*/
|
|
773
773
|
autoSignInAfterVerification?: boolean;
|
|
774
|
+
/**
|
|
775
|
+
* Number of seconds the verification token is
|
|
776
|
+
* valid for.
|
|
777
|
+
* @default 3600 seconds (1 hour)
|
|
778
|
+
*/
|
|
779
|
+
expiresIn?: number;
|
|
774
780
|
};
|
|
775
781
|
/**
|
|
776
782
|
* Email and password authentication
|
|
@@ -1370,6 +1376,12 @@ type BetterAuthOptions = {
|
|
|
1370
1376
|
*/
|
|
1371
1377
|
after?: HookAfterHandler;
|
|
1372
1378
|
};
|
|
1379
|
+
/**
|
|
1380
|
+
* Disabled paths
|
|
1381
|
+
*
|
|
1382
|
+
* Paths you want to disable.
|
|
1383
|
+
*/
|
|
1384
|
+
disabledPaths?: string[];
|
|
1373
1385
|
};
|
|
1374
1386
|
|
|
1375
1387
|
type HookEndpointContext<C extends Record<string, any> = {}> = ContextTools & {
|
|
@@ -1616,16 +1628,16 @@ declare const createInternalAdapter: (adapter: Adapter, ctx: {
|
|
|
1616
1628
|
}[]>;
|
|
1617
1629
|
updateAccount: (accountId: string, data: Partial<Account>) => Promise<any>;
|
|
1618
1630
|
createVerificationValue: (data: Omit<Verification, "createdAt" | "id" | "updatedAt"> & Partial<Verification>) => Promise<{
|
|
1619
|
-
id: string;
|
|
1620
1631
|
value: string;
|
|
1632
|
+
id: string;
|
|
1621
1633
|
createdAt: Date;
|
|
1622
1634
|
updatedAt: Date;
|
|
1623
1635
|
expiresAt: Date;
|
|
1624
1636
|
identifier: string;
|
|
1625
1637
|
}>;
|
|
1626
1638
|
findVerificationValue: (identifier: string) => Promise<{
|
|
1627
|
-
id: string;
|
|
1628
1639
|
value: string;
|
|
1640
|
+
id: string;
|
|
1629
1641
|
createdAt: Date;
|
|
1630
1642
|
updatedAt: Date;
|
|
1631
1643
|
expiresAt: Date;
|
|
@@ -3325,7 +3337,11 @@ declare function createEmailVerificationToken(secret: string, email: string,
|
|
|
3325
3337
|
/**
|
|
3326
3338
|
* The email to update from
|
|
3327
3339
|
*/
|
|
3328
|
-
updateTo?: string
|
|
3340
|
+
updateTo?: string,
|
|
3341
|
+
/**
|
|
3342
|
+
* The time in seconds for the token to expire
|
|
3343
|
+
*/
|
|
3344
|
+
expiresIn?: number): Promise<string>;
|
|
3329
3345
|
/**
|
|
3330
3346
|
* A function to send a verification email to the user
|
|
3331
3347
|
*/
|
|
@@ -591,15 +591,15 @@ declare const verificationSchema: z.ZodObject<{
|
|
|
591
591
|
expiresAt: z.ZodDate;
|
|
592
592
|
identifier: z.ZodString;
|
|
593
593
|
}, "strip", z.ZodTypeAny, {
|
|
594
|
-
id: string;
|
|
595
594
|
value: string;
|
|
595
|
+
id: string;
|
|
596
596
|
createdAt: Date;
|
|
597
597
|
updatedAt: Date;
|
|
598
598
|
expiresAt: Date;
|
|
599
599
|
identifier: string;
|
|
600
600
|
}, {
|
|
601
|
-
id: string;
|
|
602
601
|
value: string;
|
|
602
|
+
id: string;
|
|
603
603
|
expiresAt: Date;
|
|
604
604
|
identifier: string;
|
|
605
605
|
createdAt?: Date | undefined;
|
|
@@ -771,6 +771,12 @@ type BetterAuthOptions = {
|
|
|
771
771
|
* Auto signin the user after they verify their email
|
|
772
772
|
*/
|
|
773
773
|
autoSignInAfterVerification?: boolean;
|
|
774
|
+
/**
|
|
775
|
+
* Number of seconds the verification token is
|
|
776
|
+
* valid for.
|
|
777
|
+
* @default 3600 seconds (1 hour)
|
|
778
|
+
*/
|
|
779
|
+
expiresIn?: number;
|
|
774
780
|
};
|
|
775
781
|
/**
|
|
776
782
|
* Email and password authentication
|
|
@@ -1370,6 +1376,12 @@ type BetterAuthOptions = {
|
|
|
1370
1376
|
*/
|
|
1371
1377
|
after?: HookAfterHandler;
|
|
1372
1378
|
};
|
|
1379
|
+
/**
|
|
1380
|
+
* Disabled paths
|
|
1381
|
+
*
|
|
1382
|
+
* Paths you want to disable.
|
|
1383
|
+
*/
|
|
1384
|
+
disabledPaths?: string[];
|
|
1373
1385
|
};
|
|
1374
1386
|
|
|
1375
1387
|
type HookEndpointContext<C extends Record<string, any> = {}> = ContextTools & {
|
|
@@ -1616,16 +1628,16 @@ declare const createInternalAdapter: (adapter: Adapter, ctx: {
|
|
|
1616
1628
|
}[]>;
|
|
1617
1629
|
updateAccount: (accountId: string, data: Partial<Account>) => Promise<any>;
|
|
1618
1630
|
createVerificationValue: (data: Omit<Verification, "createdAt" | "id" | "updatedAt"> & Partial<Verification>) => Promise<{
|
|
1619
|
-
id: string;
|
|
1620
1631
|
value: string;
|
|
1632
|
+
id: string;
|
|
1621
1633
|
createdAt: Date;
|
|
1622
1634
|
updatedAt: Date;
|
|
1623
1635
|
expiresAt: Date;
|
|
1624
1636
|
identifier: string;
|
|
1625
1637
|
}>;
|
|
1626
1638
|
findVerificationValue: (identifier: string) => Promise<{
|
|
1627
|
-
id: string;
|
|
1628
1639
|
value: string;
|
|
1640
|
+
id: string;
|
|
1629
1641
|
createdAt: Date;
|
|
1630
1642
|
updatedAt: Date;
|
|
1631
1643
|
expiresAt: Date;
|
|
@@ -3325,7 +3337,11 @@ declare function createEmailVerificationToken(secret: string, email: string,
|
|
|
3325
3337
|
/**
|
|
3326
3338
|
* The email to update from
|
|
3327
3339
|
*/
|
|
3328
|
-
updateTo?: string
|
|
3340
|
+
updateTo?: string,
|
|
3341
|
+
/**
|
|
3342
|
+
* The time in seconds for the token to expire
|
|
3343
|
+
*/
|
|
3344
|
+
expiresIn?: number): Promise<string>;
|
|
3329
3345
|
/**
|
|
3330
3346
|
* A function to send a verification email to the user
|
|
3331
3347
|
*/
|