better-auth 1.0.8-beta.2 → 1.0.8-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.cjs +1 -1
- package/dist/api.js +1 -1
- package/dist/client/plugins.d.cts +2 -2
- package/dist/client/plugins.d.ts +2 -2
- package/dist/cookies.cjs +1 -1
- package/dist/cookies.js +1 -1
- package/dist/{index-DZWZjuQQ.d.ts → index-BqsItHPw.d.ts} +12 -0
- package/dist/{index-Cl_Lo39o.d.cts → index-COXQdrg3.d.cts} +12 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/next-js.cjs +1 -1
- package/dist/next-js.js +1 -1
- package/dist/plugins.cjs +3 -3
- package/dist/plugins.d.cts +1 -1
- package/dist/plugins.d.ts +1 -1
- package/dist/plugins.js +5 -5
- package/package.json +1 -1
package/dist/api.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use strict";var le=Object.defineProperty;var Ft=Object.getOwnPropertyDescriptor;var Ht=Object.getOwnPropertyNames;var Mt=Object.prototype.hasOwnProperty;var Gt=(e,t)=>{for(var r in t)le(e,r,{get:t[r],enumerable:!0})},Qt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ht(t))!Mt.call(e,n)&&n!==r&&le(e,n,{get:()=>t[n],enumerable:!(o=Ft(t,n))||o.enumerable});return e};var Zt=e=>Qt(le({},"__esModule",{value:!0}),e);var hr={};Gt(hr,{APIError:()=>Nt.APIError,callbackOAuth:()=>_e,changeEmail:()=>Be,changePassword:()=>Ce,createAuthEndpoint:()=>g,createAuthMiddleware:()=>M,createEmailVerificationToken:()=>j,deleteUser:()=>De,error:()=>Ve,forgetPassword:()=>Pe,forgetPasswordCallback:()=>Ie,freshSessionMiddleware:()=>be,getEndpoints:()=>qt,getSession:()=>ne,getSessionFromCtx:()=>q,linkSocialAccount:()=>Fe,listSessions:()=>ke,listUserAccounts:()=>Ne,ok:()=>ze,optionsMiddleware:()=>ue,originCheckMiddleware:()=>me,resetPassword:()=>Le,revokeOtherSessions:()=>Re,revokeSession:()=>Ae,revokeSessions:()=>Ue,router:()=>gr,sendVerificationEmail:()=>ve,sendVerificationEmailFn:()=>Ct,sessionMiddleware:()=>S,setPassword:()=>je,signInEmail:()=>xe,signInSocial:()=>Te,signOut:()=>Se,signUpEmail:()=>$e,updateUser:()=>Oe,verifyEmail:()=>Ee});module.exports=Zt(hr);var R=require("better-call");var He=require("better-call");var N=require("better-call"),ue=(0,N.createMiddleware)(async()=>({})),M=(0,N.createMiddlewareCreator)({use:[ue,(0,N.createMiddleware)(async()=>({}))]}),g=(0,N.createEndpointCreator)({use:[ue]});var me=M(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=o.trustedOrigins,d=e.headers?.has("cookie"),l=(p,w)=>w.includes("*")?new RegExp("^"+w.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(p):p.startsWith(w),m=(p,w)=>{if(!p)return;if(!a.some(I=>l(p,I)||p?.startsWith("/")&&w!=="origin"&&!p.includes(":")))throw e.context.logger.error(`Invalid ${w}: ${p}`),e.context.logger.info(`If it's a valid URL, please add ${p} to trustedOrigins in your auth config
|
|
2
|
-
`,`Current list of trustedOrigins: ${a}`),new He.APIError("FORBIDDEN",{message:`Invalid ${w}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&m(n,"origin"),i&&m(i,"callbackURL"),s&&m(s,"redirectURL"),c&&m(c,"currentURL")});var E=require("better-call"),A=require("zod");var Yt=require("oslo"),Ze=require("oslo/encoding");var X=require("oslo/crypto");async function Jt({value:e,secret:t}){return new X.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function Wt({value:e,signature:t,secret:r}){return new X.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var ee={sign:Jt,verify:Wt};var F=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};var $=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var te=Object.create(null),Y=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?te:globalThis),Me=new Proxy(te,{get(e,t){return Y()[t]??te[t]},has(e,t){let r=Y();return t in r||t in te},set(e,t,r){let o=Y(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=Y(!0);return delete r[t],!0},ownKeys(){let e=Y(!0);return Object.keys(e)}});function Kt(e){return e?e!=="false":!1}var fe=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Ge=fe==="dev"||fe==="development",Qe=fe==="test"||Kt(Me.TEST);async function T(e,t,r,o){let n=e.context.authCookies.sessionToken.options,i=r?void 0:e.context.sessionConfig.expiresIn,s=await q(e).catch(()=>null);s&&s.session.userId===t.session.userId&&s.session.token!==t.session.token&&await e.context.internalAdapter.deleteSession(s.session.token),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),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Ze.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:$(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await ee.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function 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 rt=require("@better-fetch/fetch"),ot=require("better-call"),G=require("jose"),it=require("oslo/jwt");var Je=require("oslo/crypto"),We=require("oslo/encoding");async function Ke(e){let t=await(0,Je.sha256)(new TextEncoder().encode(e));return We.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Ye(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?$(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}){let a=new URL(r);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",t.clientId),a.searchParams.set("state",o),a.searchParams.set("scope",i.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||c),n){let d=await Ke(n);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",d)}if(s){let d=s.reduce((l,m)=>(l[m]=null,l),{});a.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...d}}))}return a}var Xe=require("@better-fetch/fetch");async function b({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 m=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${m}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await(0,Xe.betterFetch)(n,{method:"POST",body:s,headers:c});if(d)throw d;return Ye(a)}var re=require("oslo/oauth2"),z=require("zod"),ge=require("better-call");function et(e){try{return new URL(e).origin}catch{return null}}async function oe(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?et(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ge.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,re.generateCodeVerifier)(),n=(0,re.generateState)(),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,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 ge.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function tt(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=z.z.object({callbackURL:z.z.string(),codeVerifier:z.z.string(),errorURL:z.z.string().optional(),expiresAt:z.z.number(),link:z.z.object({email:z.z.string(),userId:z.z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var nt=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=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>b({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=(0,G.decodeProtectedHeader)(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let c=await Xt(i),{payload:a}=await(0,G.jwtVerify)(r,c,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=(0,it.parseJWT)(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email;return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email},data:o}}}},Xt=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,rt.betterFetch)(`${t}${r}`);if(!o?.keys)throw new ot.APIError("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(0,G.importJWK)(n,n.alg)};var st=require("@better-fetch/fetch");var at=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}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({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(0,st.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var ct=require("@better-fetch/fetch");var dt=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})=>b({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(0,ct.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});var he=require("@better-fetch/fetch");var pt=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})=>b({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(0,he.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:c}=await(0,he.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});c||(o.email=(s.find(a=>a.primary)??s[0])?.email,i=s.find(a=>a.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};var ut=require("oslo/jwt");var lt=require("consola"),we=["info","success","warn","error","debug"];function er(e,t){return we.indexOf(t)<=we.indexOf(e)}var tr=(0,lt.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),rr=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,s=[])=>{if(!(!t||!er(r,n))){if(!e||typeof e.log!="function"){tr[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(we.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},_=rr();var mt=require("@better-fetch/fetch"),ft=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw _.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new F("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new F("codeVerifier is required for Google");let i=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),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({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(0,mt.betterFetch)(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=(0,ut.parseJWT)(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});var gt=require("@better-fetch/fetch"),ht=require("oslo/jwt");var wt=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 b({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=(0,ht.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,gt.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let d=await c.response.clone().arrayBuffer(),l=Buffer.from(d).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(a){_.error(a&&typeof a=="object"&&"name"in a?a.name:"",a)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};var yt=require("@better-fetch/fetch");var bt=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})=>b({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(0,yt.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});var Q={isAction:!1};var kt=require("nanoid"),At=e=>(0,kt.nanoid)(e);var Ut=require("oslo/jwt");var Rt=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})=>b({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 _.error("No idToken found in token"),null;let o=(0,Ut.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var vt=require("@better-fetch/fetch");var Et=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})=>b({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(0,vt.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var Tt=require("@better-fetch/fetch");var xt=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 b({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(0,Tt.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};var _t=require("@better-fetch/fetch");var St=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 b({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await(0,_t.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};var Pt=require("@better-fetch/fetch");var ye=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),or=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ye(`${t}/oauth/authorize`),tokenEndpoint:ye(`${t}/oauth/token`),userinfoEndpoint:ye(`${t}/api/v4/user`)}},It=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=or(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let l=c||["read_user"];return e.scope&&l.push(...e.scope),await U({id:n,options:e,authorizationEndpoint:t,scopes:l,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>b({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(0,Pt.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return a||c.state!=="active"||c.locked?null:{user:{id:c.id.toString(),name:c.name??c.username,email:c.email,image:c.avatar_url,emailVerified:!0},data:c}}}};var ir={apple:nt,discord:at,facebook:dt,github:pt,microsoft:wt,google:ft,spotify:bt,twitch:Rt,twitter:Et,dropbox:xt,linkedin:St,gitlab:It},ie=Object.keys(ir);var Ot=require("oslo"),se=require("oslo/jwt"),L=require("zod");var J=require("better-call");var C=require("better-call");var Z=require("zod");function Lt(e){try{return JSON.parse(e)}catch{return null}}var ne=()=>g("/get-session",{method:"GET",query:Z.z.optional(Z.z.object({disableCookieCache:Z.z.boolean({description:"Disable cookie cache and fetch session from database"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?Lt(Buffer.from(r,"base64").toString()):null;if(o&&!await ee.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))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 l=o.session;if(o.expiresAt<Date.now()||l.session.expiresAt<new Date){let p=e.context.authCookies.sessionData.name;e.setCookie(p,"",{maxAge:0})}else return e.json(l)}let 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)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 l=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:$(e.context.sessionConfig.expiresIn,"sec")});if(!l)return V(e),e.json(null,{status:401});let m=(l.expiresAt.valueOf()-Date.now())/1e3;return await T(e,{session:l,user:i.user},!1,{maxAge:m}),e.json({session:l,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new C.APIError("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),q=async e=>{if(e.context.session)return e.context.session;let t=await ne()({...e,_flag:"json",headers:e.headers});return e.context.session=t,t},S=M(async e=>{let t=await q(e);if(!t?.session)throw new C.APIError("UNAUTHORIZED");return{session:t}}),be=M(async e=>{let t=await q(e);if(!t?.session)throw new C.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),n=Date.now();if(!(o+r*1e3>n))throw new C.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),ke=()=>g("/list-sessions",{method:"GET",use:[S],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)}),Ae=g("/revoke-session",{method:"POST",body:Z.z.object({token:Z.z.string({description:"The token to revoke"})}),use:[S],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 C.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new C.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new C.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Ue=g("/revoke-sessions",{method:"POST",use:[S],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 C.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Re=g("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[S],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 C.APIError("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})});async function j(e,t,r){return await(0,se.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Ot.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Ct(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(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 ve=g("/send-verification-email",{method:"POST",query:L.z.object({currentURL:L.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:L.z.object({email:L.z.string({description:"The email to send the verification email to"}).email(),callbackURL:L.z.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new J.APIError("BAD_REQUEST",{message:"User not found"});return await Ct(e,r.user),e.json({status:!0})}),Ee=g("/verify-email",{method:"GET",query:L.z.object({token:L.z.string({description:"The token to verify the email"}),callbackURL:L.z.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(c){throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=${c}`):new J.APIError("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await(0,se.validateJWT)("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let i=L.z.object({email:L.z.string().email(),updateTo:L.z.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 q(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});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${r}`,token:r},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await q(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new J.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await T(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function ae(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(c=>{throw _.error(`Better auth was unable to query your database.
|
|
2
|
+
`,`Current list of trustedOrigins: ${a}`),new He.APIError("FORBIDDEN",{message:`Invalid ${w}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&m(n,"origin"),i&&m(i,"callbackURL"),s&&m(s,"redirectURL"),c&&m(c,"currentURL")});var E=require("better-call"),A=require("zod");var Yt=require("oslo"),Ze=require("oslo/encoding");var X=require("oslo/crypto");async function Jt({value:e,secret:t}){return new X.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function Wt({value:e,signature:t,secret:r}){return new X.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var ee={sign:Jt,verify:Wt};var F=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};var $=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var te=Object.create(null),Y=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?te:globalThis),Me=new Proxy(te,{get(e,t){return Y()[t]??te[t]},has(e,t){let r=Y();return t in r||t in te},set(e,t,r){let o=Y(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=Y(!0);return delete r[t],!0},ownKeys(){let e=Y(!0);return Object.keys(e)}});function Kt(e){return e?e!=="false":!1}var fe=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Ge=fe==="dev"||fe==="development",Qe=fe==="test"||Kt(Me.TEST);async function T(e,t,r,o){let n=e.context.authCookies.sessionToken.options,i=r?void 0:e.context.sessionConfig.expiresIn,s=await q(e).catch(()=>null);s&&s.session.userId===t.session.userId&&s.session.token!==t.session.token&&await e.context.internalAdapter.deleteSession(s.session.token),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),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Ze.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:$(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await ee.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),new Date(t.session.expiresAt).getTime()-Date.now())}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 rt=require("@better-fetch/fetch"),ot=require("better-call"),G=require("jose"),it=require("oslo/jwt");var Je=require("oslo/crypto"),We=require("oslo/encoding");async function Ke(e){let t=await(0,Je.sha256)(new TextEncoder().encode(e));return We.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Ye(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?$(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}){let a=new URL(r);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",t.clientId),a.searchParams.set("state",o),a.searchParams.set("scope",i.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||c),n){let d=await Ke(n);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",d)}if(s){let d=s.reduce((l,m)=>(l[m]=null,l),{});a.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...d}}))}return a}var Xe=require("@better-fetch/fetch");async function b({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 m=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${m}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await(0,Xe.betterFetch)(n,{method:"POST",body:s,headers:c});if(d)throw d;return Ye(a)}var re=require("oslo/oauth2"),z=require("zod"),ge=require("better-call");function et(e){try{return new URL(e).origin}catch{return null}}async function oe(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?et(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ge.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,re.generateCodeVerifier)(),n=(0,re.generateState)(),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,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 ge.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function tt(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=z.z.object({callbackURL:z.z.string(),codeVerifier:z.z.string(),errorURL:z.z.string().optional(),expiresAt:z.z.number(),link:z.z.object({email:z.z.string(),userId:z.z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var nt=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=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>b({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=(0,G.decodeProtectedHeader)(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let c=await Xt(i),{payload:a}=await(0,G.jwtVerify)(r,c,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=(0,it.parseJWT)(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email;return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email},data:o}}}},Xt=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,rt.betterFetch)(`${t}${r}`);if(!o?.keys)throw new ot.APIError("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(0,G.importJWK)(n,n.alg)};var st=require("@better-fetch/fetch");var at=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}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({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(0,st.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var ct=require("@better-fetch/fetch");var dt=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})=>b({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(0,ct.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});var he=require("@better-fetch/fetch");var pt=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})=>b({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(0,he.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:c}=await(0,he.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});c||(o.email=(s.find(a=>a.primary)??s[0])?.email,i=s.find(a=>a.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};var ut=require("oslo/jwt");var lt=require("consola"),we=["info","success","warn","error","debug"];function er(e,t){return we.indexOf(t)<=we.indexOf(e)}var tr=(0,lt.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),rr=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,s=[])=>{if(!(!t||!er(r,n))){if(!e||typeof e.log!="function"){tr[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(we.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},_=rr();var mt=require("@better-fetch/fetch"),ft=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw _.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new F("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new F("codeVerifier is required for Google");let i=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),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({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(0,mt.betterFetch)(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=(0,ut.parseJWT)(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});var gt=require("@better-fetch/fetch"),ht=require("oslo/jwt");var wt=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 b({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=(0,ht.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,gt.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let d=await c.response.clone().arrayBuffer(),l=Buffer.from(d).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(a){_.error(a&&typeof a=="object"&&"name"in a?a.name:"",a)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};var yt=require("@better-fetch/fetch");var bt=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})=>b({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(0,yt.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});var Q={isAction:!1};var kt=require("nanoid"),At=e=>(0,kt.nanoid)(e);var Ut=require("oslo/jwt");var Rt=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})=>b({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 _.error("No idToken found in token"),null;let o=(0,Ut.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var vt=require("@better-fetch/fetch");var Et=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})=>b({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(0,vt.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var Tt=require("@better-fetch/fetch");var xt=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 b({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(0,Tt.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};var _t=require("@better-fetch/fetch");var St=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 b({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await(0,_t.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};var Pt=require("@better-fetch/fetch");var ye=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),or=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ye(`${t}/oauth/authorize`),tokenEndpoint:ye(`${t}/oauth/token`),userinfoEndpoint:ye(`${t}/api/v4/user`)}},It=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=or(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let l=c||["read_user"];return e.scope&&l.push(...e.scope),await U({id:n,options:e,authorizationEndpoint:t,scopes:l,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>b({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(0,Pt.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return a||c.state!=="active"||c.locked?null:{user:{id:c.id.toString(),name:c.name??c.username,email:c.email,image:c.avatar_url,emailVerified:!0},data:c}}}};var ir={apple:nt,discord:at,facebook:dt,github:pt,microsoft:wt,google:ft,spotify:bt,twitch:Rt,twitter:Et,dropbox:xt,linkedin:St,gitlab:It},ie=Object.keys(ir);var Ot=require("oslo"),se=require("oslo/jwt"),L=require("zod");var J=require("better-call");var C=require("better-call");var Z=require("zod");function Lt(e){try{return JSON.parse(e)}catch{return null}}var ne=()=>g("/get-session",{method:"GET",query:Z.z.optional(Z.z.object({disableCookieCache:Z.z.boolean({description:"Disable cookie cache and fetch session from database"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?Lt(Buffer.from(r,"base64").toString()):null;if(o&&!await ee.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))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 l=o.session;if(o.expiresAt<Date.now()||l.session.expiresAt<new Date){let p=e.context.authCookies.sessionData.name;e.setCookie(p,"",{maxAge:0})}else return e.json(l)}let 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)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 l=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:$(e.context.sessionConfig.expiresIn,"sec")});if(!l)return V(e),e.json(null,{status:401});let m=(l.expiresAt.valueOf()-Date.now())/1e3;return await T(e,{session:l,user:i.user},!1,{maxAge:m}),e.json({session:l,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new C.APIError("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),q=async e=>{if(e.context.session)return e.context.session;let t=await ne()({...e,_flag:"json",headers:e.headers});return e.context.session=t,t},S=M(async e=>{let t=await q(e);if(!t?.session)throw new C.APIError("UNAUTHORIZED");return{session:t}}),be=M(async e=>{let t=await q(e);if(!t?.session)throw new C.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),n=Date.now();if(!(o+r*1e3>n))throw new C.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),ke=()=>g("/list-sessions",{method:"GET",use:[S],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)}),Ae=g("/revoke-session",{method:"POST",body:Z.z.object({token:Z.z.string({description:"The token to revoke"})}),use:[S],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 C.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new C.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new C.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Ue=g("/revoke-sessions",{method:"POST",use:[S],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 C.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Re=g("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[S],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 C.APIError("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})});async function j(e,t,r){return await(0,se.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Ot.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Ct(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(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 ve=g("/send-verification-email",{method:"POST",query:L.z.object({currentURL:L.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:L.z.object({email:L.z.string({description:"The email to send the verification email to"}).email(),callbackURL:L.z.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new J.APIError("BAD_REQUEST",{message:"User not found"});return await Ct(e,r.user),e.json({status:!0})}),Ee=g("/verify-email",{method:"GET",query:L.z.object({token:L.z.string({description:"The token to verify the email"}),callbackURL:L.z.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(c){throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=${c}`):new J.APIError("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await(0,se.validateJWT)("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let i=L.z.object({email:L.z.string().email(),updateTo:L.z.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 q(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});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${r}`,token:r},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await q(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new J.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await T(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function ae(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(c=>{throw _.error(`Better auth was unable to query your database.
|
|
3
3
|
Error: `,c),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user;if(n){let c=n.accounts.find(a=>a.providerId===r.providerId);if(c){let a=Object.fromEntries(Object.entries({accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([d,l])=>l!==void 0));Object.keys(a).length>0&&await e.context.internalAdapter.updateAccount(c.id,a)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Ge&&_.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(l){return _.error("Unable to link account",l),{error:"unable to link account",data:null}}}}else try{let c=t.emailVerified||!1;if(i=await e.context.internalAdapter.createOAuthUser({...t,id:void 0,emailVerified:c,email:t.email.toLowerCase()},{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),!c&&i&&e.context.options.emailVerification?.sendOnSignUp){let a=await j(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(c){return _.error("Unable to create user",c),{error:"unable to create user",data:null}}if(!i)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(i.id,e.request);return s?{data:{session:s,user:i},error:null}:{error:"unable to create session",data:null}}var Te=g("/sign-in/social",{method:"POST",query:A.z.object({currentURL:A.z.string().optional()}).optional(),body:A.z.object({callbackURL:A.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),errorCallbackURL:A.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:A.z.enum(ie,{description:"OAuth2 provider to use"}),disableRedirect:A.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:A.z.optional(A.z.object({token:A.z.string({description:"ID token from the provider"}),nonce:A.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:A.z.string({description:"Access token from the provider"}).optional(),refreshToken:A.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:A.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(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 E.APIError("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new E.APIError("NOT_FOUND",{message:"Provider does not support id token verification"});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 E.APIError("UNAUTHORIZED",{message:"Invalid id 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 E.APIError("UNAUTHORIZED",{message:"Failed to get user info"});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new E.APIError("UNAUTHORIZED",{message:"User email not found"});let d=await ae(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 E.APIError("UNAUTHORIZED",{message:d.error});return await T(e,d.data),e.json({session:d.data.session,user:d.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:r,state:o}=await oe(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})}),xe=g("/sign-in/email",{method:"POST",body:A.z.object({email:A.z.string({description:"Email of the user"}),password:A.z.string({description:"Password of the user"}),callbackURL:A.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:A.z.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new E.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!A.z.string().email().safeParse(t).success)throw new E.APIError("BAD_REQUEST",{message:"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 E.APIError("UNAUTHORIZED",{message:"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 E.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new E.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new E.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new E.APIError("UNAUTHORIZED",{message:"Email is not verified."});let d=await j(e.context.secret,n.user.email),l=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:l,token:d},e.request),e.context.logger.error("Email not verified",{email:t}),new E.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}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 E.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await T(e,{session:a,user:n.user},e.body.rememberMe===!1),e.json({user:n.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var W=require("zod");var ce=W.z.object({code:W.z.string().optional(),error:W.z.string().optional(),errorMessage:W.z.string().optional(),state:W.z.string().optional()}),_e=g("/callback/:id",{method:["GET","POST"],body:ce.optional(),query:ce.optional(),metadata:Q},async e=>{let t;try{if(e.method==="GET")t=ce.parse(e.query);else if(e.method==="POST")t=ce.parse(e.body);else throw new Error("Unsupported method")}catch(f){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",f),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n}=t;if(!n)throw e.context.logger.error("State not found"),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}`);let i=e.context.socialProviders.find(f=>f.id===e.params.id);if(!i)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:s,callbackURL:c,link:a,errorURL:d}=await tt(e),l;try{l=await i.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${i.id}`})}catch(f){throw e.context.logger.error("",f),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let m=await i.getUserInfo(l).then(f=>f?.user);function p(f){let y=d||c||`${e.context.baseURL}/error`;throw y.includes("?")?y=`${y}&error=${f}`:y=`${y}?error=${f}`,e.redirect(y)}if(!m)return e.context.logger.error("Unable to get user info"),p("unable_to_get_user_info");if(!m.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),p("email_not_found");if(!c)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(a){if(a.email!==m.email.toLowerCase())return p("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:a.userId,providerId:i.id,accountId:m.id}))return p("unable_to_link_account");let y;try{y=new URL(c).toString()}catch{y=c}throw e.redirect(y)}let w=await ae(e,{userInfo:{id:m.id,email:m.email,name:m.name||"",image:m.image,emailVerified:m.emailVerified||!1},account:{providerId:i.id,accountId:m.id,...l,scope:l.scopes?.join(",")},callbackURL:c});if(w.error)return e.context.logger.error(w.error.split(" ").join("_")),p(w.error.split(" ").join("_"));let{session:O,user:I}=w.data;await T(e,{session:O,user:I});let h;try{h=new URL(c).toString()}catch{h=c}throw e.redirect(h)});var zi=require("zod");var jt=require("better-call"),Se=g("/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 jt.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),V(e),e.json({success:!0})});var P=require("zod");var de=require("better-call");function Dt(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 nr(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 Pe=g("/forget-password",{method:"POST",body:P.z.object({email:P.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:P.z.string({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new de.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=$(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=At(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})}),Ie=g("/reset-password/:token",{method:"GET",query:P.z.object({callbackURL:P.z.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(Dt(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Dt(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(nr(e.context,r,{token:t}))}),Le=g("/reset-password",{query:P.z.optional(P.z.object({token:P.z.string().optional(),currentURL:P.z.string().optional()})),method:"POST",body:P.z.object({newPassword:P.z.string({description:"The new password to set"}),token:P.z.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new de.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new de.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(i)).find(d=>d.providerId==="credential")?(await e.context.internalAdapter.updatePassword(i,s),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:i}),e.json({status:!0}))});var v=require("zod");var x=require("better-call");var u=require("zod"),Bt=require("better-call"),Zi=u.z.object({id:u.z.string(),providerId:u.z.string(),accountId:u.z.string(),userId:u.z.string(),accessToken:u.z.string().nullish(),refreshToken:u.z.string().nullish(),idToken:u.z.string().nullish(),accessTokenExpiresAt:u.z.date().nullish(),refreshTokenExpiresAt:u.z.date().nullish(),scope:u.z.string().nullish(),password:u.z.string().nullish(),createdAt:u.z.date().default(()=>new Date),updatedAt:u.z.date().default(()=>new Date)}),Ji=u.z.object({id:u.z.string(),email:u.z.string().transform(e=>e.toLowerCase()),emailVerified:u.z.boolean().default(!1),name:u.z.string(),image:u.z.string().nullish(),createdAt:u.z.date().default(()=>new Date),updatedAt:u.z.date().default(()=>new Date)}),Wi=u.z.object({id:u.z.string(),userId:u.z.string(),expiresAt:u.z.date(),createdAt:u.z.date().default(()=>new Date),updatedAt:u.z.date().default(()=>new Date),token:u.z.string(),ipAddress:u.z.string().nullish(),userAgent:u.z.string().nullish()}),Ki=u.z.object({id:u.z.string(),value:u.z.string(),createdAt:u.z.date().default(()=>new Date),updatedAt:u.z.date().default(()=>new Date),expiresAt:u.z.date(),identifier:u.z.string()});function sr(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 ar(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}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 Bt.APIError("BAD_REQUEST",{message:`${i} is required`})}return n}function pe(e,t,r){let o=sr(e,"user");return ar(t||{},{fields:o,action:r})}var Oe=()=>g("/update-user",{method:"POST",body:v.z.record(v.z.string(),v.z.any()),use:[S],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 x.APIError("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...n}=t,i=e.context.session;if(!o&&!r&&Object.keys(n).length===0)return e.json({user:i.user});let s=pe(e.context.options,n,"update"),c=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await T(e,{session:i.session,user:c}),e.json({user:c})}),Ce=g("/change-password",{method:"POST",body:v.z.object({newPassword:v.z.string({description:"The new password to set"}),currentPassword:v.z.string({description:"The current password"}),revokeOtherSessions:v.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[S],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 x.APIError("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new x.APIError("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(m=>m.providerId==="credential"&&m.password);if(!a||!a.password)throw new x.APIError("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify({hash:a.password,password:r}))throw new x.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(a.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let m=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!m)throw new x.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await T(e,{session:m,user:n.user})}return e.json(n.user)}),je=g("/set-password",{method:"POST",body:v.z.object({newPassword:v.z.string()}),metadata:{SERVER_ONLY:!0},use:[S]},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 x.APIError("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new x.APIError("BAD_REQUEST",{message:"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(r.user);throw new x.APIError("BAD_REQUEST",{message:"user already has a password"})}),De=g("/delete-user",{method:"POST",body:v.z.object({password:v.z.string({description:"The password of the user"})}),use:[be],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{let t=e.context.session;return await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),V(e),e.json(null)}),Be=g("/change-email",{method:"POST",query:v.z.object({currentURL:v.z.string().optional()}).optional(),body:v.z.object({newEmail:v.z.string({description:"The new email to set"}).email(),callbackURL:v.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[S],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 x.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new x.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new x.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new x.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(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({user:null,status:!0})});var cr=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|
package/dist/api.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import{APIError as N,createRouter as lr,getCookie as ur,getSignedCookie as mr,setCookie as fr,setSignedCookie as gr}from"better-call";import{APIError as mt}from"better-call";import{createEndpointCreator as lt,createMiddleware as de,createMiddlewareCreator as ut}from"better-call";var pe=de(async()=>({})),M=ut({use:[pe,de(async()=>({}))]}),h=lt({use:[pe]});var le=M(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=o.trustedOrigins,d=e.headers?.has("cookie"),l=(p,w)=>w.includes("*")?new RegExp("^"+w.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(p):p.startsWith(w),m=(p,w)=>{if(!p)return;if(!a.some(_=>l(p,_)||p?.startsWith("/")&&w!=="origin"&&!p.includes(":")))throw e.context.logger.error(`Invalid ${w}: ${p}`),e.context.logger.info(`If it's a valid URL, please add ${p} to trustedOrigins in your auth config
|
|
2
|
-
`,`Current list of trustedOrigins: ${a}`),new mt("FORBIDDEN",{message:`Invalid ${w}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&m(n,"origin"),i&&m(i,"callbackURL"),s&&m(s,"redirectURL"),c&&m(c,"currentURL")});import{APIError as v}from"better-call";import{z as U}from"zod";import{TimeSpan as Cr}from"oslo";import{base64url as wt}from"oslo/encoding";import{HMAC as ue,sha256 as Er}from"oslo/crypto";async function ft({value:e,secret:t}){return new ue("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function gt({value:e,signature:t,secret:r}){return new ue("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var K={sign:ft,verify:gt};var $=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};var V=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var Y=Object.create(null),G=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Y:globalThis),me=new Proxy(Y,{get(e,t){return G()[t]??Y[t]},has(e,t){let r=G();return t in r||t in Y},set(e,t,r){let o=G(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=G(!0);return delete r[t],!0},ownKeys(){let e=G(!0);return Object.keys(e)}});function ht(e){return e?e!=="false":!1}var ie=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var fe=ie==="dev"||ie==="development",ge=ie==="test"||ht(me.TEST);async function E(e,t,r,o){let n=e.context.authCookies.sessionToken.options,i=r?void 0:e.context.sessionConfig.expiresIn,s=await q(e).catch(()=>null);s&&s.session.userId===t.session.userId&&s.session.token!==t.session.token&&await e.context.internalAdapter.deleteSession(s.session.token),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),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(wt.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:V(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await K.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function C(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}import{betterFetch as Rt}from"@better-fetch/fetch";import{APIError as vt}from"better-call";import{decodeProtectedHeader as Et,importJWK as Tt,jwtVerify as xt}from"jose";import{parseJWT as _t}from"oslo/jwt";import{sha256 as yt}from"oslo/crypto";import{base64url as bt}from"oslo/encoding";async function he(e){let t=await yt(new TextEncoder().encode(e));return bt.encode(new Uint8Array(t),{includePadding:!1})}function we(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?V(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,redirectURI:c}){let a=new URL(r);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",t.clientId),a.searchParams.set("state",o),a.searchParams.set("scope",i.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||c),n){let d=await he(n);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",d)}if(s){let d=s.reduce((l,m)=>(l[m]=null,l),{});a.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...d}}))}return a}import{betterFetch as kt}from"@better-fetch/fetch";async function b({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 m=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${m}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await kt(n,{method:"POST",body:s,headers:c});if(d)throw d;return we(a)}import{generateCodeVerifier as At,generateState as Ut}from"oslo/oauth2";import{z}from"zod";import{APIError as be}from"better-call";function ye(e){try{return new URL(e).origin}catch{return null}}async function X(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?ye(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new be("BAD_REQUEST",{message:"callbackURL is required"});let o=At(),n=Ut(),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,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 be("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function ke(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=z.object({callbackURL:z.string(),codeVerifier:z.string(),errorURL:z.string().optional(),expiresAt:z.number(),link:z.object({email:z.string(),userId:z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var Ae=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=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>b({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=Et(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let c=await St(i),{payload:a}=await xt(r,c,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=_t(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email;return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email},data:o}}}},St=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await Rt(`${t}${r}`);if(!o?.keys)throw new vt("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 Tt(n,n.alg)};import{betterFetch as Pt}from"@better-fetch/fetch";var Ue=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}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({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 Pt("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});import{betterFetch as It}from"@better-fetch/fetch";var Re=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 A({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})=>b({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 It("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});import{betterFetch as ve}from"@better-fetch/fetch";var Ee=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),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>b({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 ve("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:c}=await ve("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});c||(o.email=(s.find(a=>a.primary)??s[0])?.email,i=s.find(a=>a.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};import{parseJWT as Dt}from"oslo/jwt";import{createConsola as Lt}from"consola";var ne=["info","success","warn","error","debug"];function Ot(e,t){return ne.indexOf(t)<=ne.indexOf(e)}var Ct=Lt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),jt=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,s=[])=>{if(!(!t||!Ot(r,n))){if(!e||typeof e.log!="function"){Ct[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(ne.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},T=jt();import{betterFetch as Bt}from"@better-fetch/fetch";var Te=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw T.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new $("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new $("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await A({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),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({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 Bt(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=Dt(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});import{betterFetch as Vt}from"@better-fetch/fetch";import{parseJWT as zt}from"oslo/jwt";var xe=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),A({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 b({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=zt(n.idToken)?.payload,s=e.profilePhotoSize||48;return await Vt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let d=await c.response.clone().arrayBuffer(),l=Buffer.from(d).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(a){T.error(a&&typeof a=="object"&&"name"in a?a.name:"",a)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as $t}from"@better-fetch/fetch";var _e=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),A({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})=>b({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 $t("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});var F={isAction:!1};import{nanoid as qt}from"nanoid";var Se=e=>qt(e);import{parseJWT as Nt}from"oslo/jwt";var Pe=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),A({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})=>b({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 T.error("No idToken found in token"),null;let o=Nt(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as Ft}from"@better-fetch/fetch";var Ie=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),A({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})=>b({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 Ft("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});import{betterFetch as Ht}from"@better-fetch/fetch";var Le=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 A({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 b({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 Ht("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};import{betterFetch as Mt}from"@better-fetch/fetch";var Oe=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 A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await b({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await Mt("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};import{betterFetch as Gt}from"@better-fetch/fetch";var se=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Qt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:se(`${t}/oauth/authorize`),tokenEndpoint:se(`${t}/oauth/token`),userinfoEndpoint:se(`${t}/api/v4/user`)}},Ce=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Qt(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let l=c||["read_user"];return e.scope&&l.push(...e.scope),await A({id:n,options:e,authorizationEndpoint:t,scopes:l,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>b({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 Gt(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return a||c.state!=="active"||c.locked?null:{user:{id:c.id.toString(),name:c.name??c.username,email:c.email,image:c.avatar_url,emailVerified:!0},data:c}}}};var Zt={apple:Ae,discord:Ue,facebook:Re,github:Ee,microsoft:xe,google:Te,spotify:_e,twitch:Pe,twitter:Ie,dropbox:Le,linkedin:Oe,gitlab:Ce},ee=Object.keys(Zt);import{TimeSpan as Jt}from"oslo";import{createJWT as Wt,validateJWT as Kt}from"oslo/jwt";import{z as I}from"zod";import{APIError as Z}from"better-call";import{APIError as j}from"better-call";import{z as Q}from"zod";function je(e){try{return JSON.parse(e)}catch{return null}}var ae=()=>h("/get-session",{method:"GET",query:Q.optional(Q.object({disableCookieCache:Q.boolean({description:"Disable cookie cache and fetch session from database"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?je(Buffer.from(r,"base64").toString()):null;if(o&&!await K.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return C(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let l=o.session;if(o.expiresAt<Date.now()||l.session.expiresAt<new Date){let p=e.context.authCookies.sessionData.name;e.setCookie(p,"",{maxAge:0})}else return e.json(l)}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return C(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n)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 l=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:V(e.context.sessionConfig.expiresIn,"sec")});if(!l)return C(e),e.json(null,{status:401});let m=(l.expiresAt.valueOf()-Date.now())/1e3;return await E(e,{session:l,user:i.user},!1,{maxAge:m}),e.json({session:l,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new j("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),q=async e=>{if(e.context.session)return e.context.session;let t=await ae()({...e,_flag:"json",headers:e.headers});return e.context.session=t,t},S=M(async e=>{let t=await q(e);if(!t?.session)throw new j("UNAUTHORIZED");return{session:t}}),De=M(async e=>{let t=await q(e);if(!t?.session)throw new j("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),n=Date.now();if(!(o+r*1e3>n))throw new j("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),Be=()=>h("/list-sessions",{method:"GET",use:[S],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)}),Ve=h("/revoke-session",{method:"POST",body:Q.object({token:Q.string({description:"The token to revoke"})}),use:[S],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 j("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new j("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 j("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ze=h("/revoke-sessions",{method:"POST",use:[S],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 j("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),$e=h("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[S],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 j("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})});async function D(e,t,r){return await Wt("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Jt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Yt(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Z("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await D(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 qe=h("/send-verification-email",{method:"POST",query:I.object({currentURL:I.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:I.object({email:I.string({description:"The email to send the verification email to"}).email(),callbackURL:I.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 Z("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new Z("BAD_REQUEST",{message:"User not found"});return await Yt(e,r.user),e.json({status:!0})}),Ne=h("/verify-email",{method:"GET",query:I.object({token:I.string({description:"The token to verify the email"}),callbackURL:I.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(c){throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=${c}`):new Z("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await Kt("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let i=I.object({email:I.string().email(),updateTo:I.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 q(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});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${r}`,token:r},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await q(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new Z("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await E(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function te(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(c=>{throw T.error(`Better auth was unable to query your database.
|
|
2
|
+
`,`Current list of trustedOrigins: ${a}`),new mt("FORBIDDEN",{message:`Invalid ${w}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&m(n,"origin"),i&&m(i,"callbackURL"),s&&m(s,"redirectURL"),c&&m(c,"currentURL")});import{APIError as v}from"better-call";import{z as U}from"zod";import{TimeSpan as Cr}from"oslo";import{base64url as wt}from"oslo/encoding";import{HMAC as ue,sha256 as Er}from"oslo/crypto";async function ft({value:e,secret:t}){return new ue("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function gt({value:e,signature:t,secret:r}){return new ue("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var K={sign:ft,verify:gt};var $=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};var V=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var Y=Object.create(null),G=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?Y:globalThis),me=new Proxy(Y,{get(e,t){return G()[t]??Y[t]},has(e,t){let r=G();return t in r||t in Y},set(e,t,r){let o=G(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=G(!0);return delete r[t],!0},ownKeys(){let e=G(!0);return Object.keys(e)}});function ht(e){return e?e!=="false":!1}var ie=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var fe=ie==="dev"||ie==="development",ge=ie==="test"||ht(me.TEST);async function E(e,t,r,o){let n=e.context.authCookies.sessionToken.options,i=r?void 0:e.context.sessionConfig.expiresIn,s=await q(e).catch(()=>null);s&&s.session.userId===t.session.userId&&s.session.token!==t.session.token&&await e.context.internalAdapter.deleteSession(s.session.token),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),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(wt.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:V(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await K.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),new Date(t.session.expiresAt).getTime()-Date.now())}function C(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}import{betterFetch as Rt}from"@better-fetch/fetch";import{APIError as vt}from"better-call";import{decodeProtectedHeader as Et,importJWK as Tt,jwtVerify as xt}from"jose";import{parseJWT as _t}from"oslo/jwt";import{sha256 as yt}from"oslo/crypto";import{base64url as bt}from"oslo/encoding";async function he(e){let t=await yt(new TextEncoder().encode(e));return bt.encode(new Uint8Array(t),{includePadding:!1})}function we(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?V(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,redirectURI:c}){let a=new URL(r);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",t.clientId),a.searchParams.set("state",o),a.searchParams.set("scope",i.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||c),n){let d=await he(n);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",d)}if(s){let d=s.reduce((l,m)=>(l[m]=null,l),{});a.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...d}}))}return a}import{betterFetch as kt}from"@better-fetch/fetch";async function b({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 m=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${m}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await kt(n,{method:"POST",body:s,headers:c});if(d)throw d;return we(a)}import{generateCodeVerifier as At,generateState as Ut}from"oslo/oauth2";import{z}from"zod";import{APIError as be}from"better-call";function ye(e){try{return new URL(e).origin}catch{return null}}async function X(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?ye(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new be("BAD_REQUEST",{message:"callbackURL is required"});let o=At(),n=Ut(),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,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 be("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function ke(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=z.object({callbackURL:z.string(),codeVerifier:z.string(),errorURL:z.string().optional(),expiresAt:z.number(),link:z.object({email:z.string(),userId:z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var Ae=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=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>b({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=Et(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let c=await St(i),{payload:a}=await xt(r,c,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=_t(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email;return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email},data:o}}}},St=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await Rt(`${t}${r}`);if(!o?.keys)throw new vt("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 Tt(n,n.alg)};import{betterFetch as Pt}from"@better-fetch/fetch";var Ue=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}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({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 Pt("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});import{betterFetch as It}from"@better-fetch/fetch";var Re=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 A({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})=>b({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 It("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});import{betterFetch as ve}from"@better-fetch/fetch";var Ee=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),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>b({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 ve("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:c}=await ve("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});c||(o.email=(s.find(a=>a.primary)??s[0])?.email,i=s.find(a=>a.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};import{parseJWT as Dt}from"oslo/jwt";import{createConsola as Lt}from"consola";var ne=["info","success","warn","error","debug"];function Ot(e,t){return ne.indexOf(t)<=ne.indexOf(e)}var Ct=Lt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),jt=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,s=[])=>{if(!(!t||!Ot(r,n))){if(!e||typeof e.log!="function"){Ct[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(ne.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},T=jt();import{betterFetch as Bt}from"@better-fetch/fetch";var Te=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw T.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new $("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new $("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await A({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),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({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 Bt(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=Dt(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});import{betterFetch as Vt}from"@better-fetch/fetch";import{parseJWT as zt}from"oslo/jwt";var xe=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),A({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 b({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=zt(n.idToken)?.payload,s=e.profilePhotoSize||48;return await Vt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let d=await c.response.clone().arrayBuffer(),l=Buffer.from(d).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(a){T.error(a&&typeof a=="object"&&"name"in a?a.name:"",a)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as $t}from"@better-fetch/fetch";var _e=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),A({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})=>b({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 $t("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});var F={isAction:!1};import{nanoid as qt}from"nanoid";var Se=e=>qt(e);import{parseJWT as Nt}from"oslo/jwt";var Pe=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),A({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})=>b({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 T.error("No idToken found in token"),null;let o=Nt(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as Ft}from"@better-fetch/fetch";var Ie=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),A({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})=>b({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 Ft("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});import{betterFetch as Ht}from"@better-fetch/fetch";var Le=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 A({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 b({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 Ht("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};import{betterFetch as Mt}from"@better-fetch/fetch";var Oe=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 A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await b({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await Mt("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};import{betterFetch as Gt}from"@better-fetch/fetch";var se=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Qt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:se(`${t}/oauth/authorize`),tokenEndpoint:se(`${t}/oauth/token`),userinfoEndpoint:se(`${t}/api/v4/user`)}},Ce=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Qt(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let l=c||["read_user"];return e.scope&&l.push(...e.scope),await A({id:n,options:e,authorizationEndpoint:t,scopes:l,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>b({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 Gt(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return a||c.state!=="active"||c.locked?null:{user:{id:c.id.toString(),name:c.name??c.username,email:c.email,image:c.avatar_url,emailVerified:!0},data:c}}}};var Zt={apple:Ae,discord:Ue,facebook:Re,github:Ee,microsoft:xe,google:Te,spotify:_e,twitch:Pe,twitter:Ie,dropbox:Le,linkedin:Oe,gitlab:Ce},ee=Object.keys(Zt);import{TimeSpan as Jt}from"oslo";import{createJWT as Wt,validateJWT as Kt}from"oslo/jwt";import{z as I}from"zod";import{APIError as Z}from"better-call";import{APIError as j}from"better-call";import{z as Q}from"zod";function je(e){try{return JSON.parse(e)}catch{return null}}var ae=()=>h("/get-session",{method:"GET",query:Q.optional(Q.object({disableCookieCache:Q.boolean({description:"Disable cookie cache and fetch session from database"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?je(Buffer.from(r,"base64").toString()):null;if(o&&!await K.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return C(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let l=o.session;if(o.expiresAt<Date.now()||l.session.expiresAt<new Date){let p=e.context.authCookies.sessionData.name;e.setCookie(p,"",{maxAge:0})}else return e.json(l)}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return C(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n)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 l=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:V(e.context.sessionConfig.expiresIn,"sec")});if(!l)return C(e),e.json(null,{status:401});let m=(l.expiresAt.valueOf()-Date.now())/1e3;return await E(e,{session:l,user:i.user},!1,{maxAge:m}),e.json({session:l,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new j("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),q=async e=>{if(e.context.session)return e.context.session;let t=await ae()({...e,_flag:"json",headers:e.headers});return e.context.session=t,t},S=M(async e=>{let t=await q(e);if(!t?.session)throw new j("UNAUTHORIZED");return{session:t}}),De=M(async e=>{let t=await q(e);if(!t?.session)throw new j("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),n=Date.now();if(!(o+r*1e3>n))throw new j("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),Be=()=>h("/list-sessions",{method:"GET",use:[S],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)}),Ve=h("/revoke-session",{method:"POST",body:Q.object({token:Q.string({description:"The token to revoke"})}),use:[S],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 j("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new j("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 j("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ze=h("/revoke-sessions",{method:"POST",use:[S],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 j("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),$e=h("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[S],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 j("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})});async function D(e,t,r){return await Wt("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Jt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Yt(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new Z("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await D(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 qe=h("/send-verification-email",{method:"POST",query:I.object({currentURL:I.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:I.object({email:I.string({description:"The email to send the verification email to"}).email(),callbackURL:I.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 Z("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new Z("BAD_REQUEST",{message:"User not found"});return await Yt(e,r.user),e.json({status:!0})}),Ne=h("/verify-email",{method:"GET",query:I.object({token:I.string({description:"The token to verify the email"}),callbackURL:I.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(c){throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=${c}`):new Z("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await Kt("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let i=I.object({email:I.string().email(),updateTo:I.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 q(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});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${r}`,token:r},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await q(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new Z("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await E(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function te(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(c=>{throw T.error(`Better auth was unable to query your database.
|
|
3
3
|
Error: `,c),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user;if(n){let c=n.accounts.find(a=>a.providerId===r.providerId);if(c){let a=Object.fromEntries(Object.entries({accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([d,l])=>l!==void 0));Object.keys(a).length>0&&await e.context.internalAdapter.updateAccount(c.id,a)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return fe&&T.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(l){return T.error("Unable to link account",l),{error:"unable to link account",data:null}}}}else try{let c=t.emailVerified||!1;if(i=await e.context.internalAdapter.createOAuthUser({...t,id:void 0,emailVerified:c,email:t.email.toLowerCase()},{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),!c&&i&&e.context.options.emailVerification?.sendOnSignUp){let a=await D(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(c){return T.error("Unable to create user",c),{error:"unable to create user",data:null}}if(!i)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(i.id,e.request);return s?{data:{session:s,user:i},error:null}:{error:"unable to create session",data:null}}var Fe=h("/sign-in/social",{method:"POST",query:U.object({currentURL:U.string().optional()}).optional(),body:U.object({callbackURL:U.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),errorCallbackURL:U.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:U.enum(ee,{description:"OAuth2 provider to use"}),disableRedirect:U.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:U.optional(U.object({token:U.string({description:"ID token from the provider"}),nonce:U.string({description:"Nonce used to generate the token"}).optional(),accessToken:U.string({description:"Access token from the provider"}).optional(),refreshToken:U.string({description:"Refresh token from the provider"}).optional(),expiresAt:U.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 v("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new v("NOT_FOUND",{message:"Provider does not support id token verification"});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 v("UNAUTHORIZED",{message:"Invalid id 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 v("UNAUTHORIZED",{message:"Failed to get user info"});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new v("UNAUTHORIZED",{message:"User email not found"});let d=await te(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 v("UNAUTHORIZED",{message:d.error});return await E(e,d.data),e.json({session:d.data.session,user:d.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:r,state:o}=await X(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})}),He=h("/sign-in/email",{method:"POST",body:U.object({email:U.string({description:"Email of the user"}),password:U.string({description:"Password of the user"}),callbackURL:U.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:U.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new v("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!U.string().email().safeParse(t).success)throw new v("BAD_REQUEST",{message:"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 v("UNAUTHORIZED",{message:"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 v("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new v("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new v("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new v("UNAUTHORIZED",{message:"Email is not verified."});let d=await D(e.context.secret,n.user.email),l=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:l,token:d},e.request),e.context.logger.error("Email not verified",{email:t}),new v("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}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 v("UNAUTHORIZED",{message:"Failed to create session"});return await E(e,{session:a,user:n.user},e.body.rememberMe===!1),e.json({user:n.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as J}from"zod";var re=J.object({code:J.string().optional(),error:J.string().optional(),errorMessage:J.string().optional(),state:J.string().optional()}),Me=h("/callback/:id",{method:["GET","POST"],body:re.optional(),query:re.optional(),metadata:F},async e=>{let t;try{if(e.method==="GET")t=re.parse(e.query);else if(e.method==="POST")t=re.parse(e.body);else throw new Error("Unsupported method")}catch(f){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",f),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n}=t;if(!n)throw e.context.logger.error("State not found"),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}`);let i=e.context.socialProviders.find(f=>f.id===e.params.id);if(!i)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:s,callbackURL:c,link:a,errorURL:d}=await ke(e),l;try{l=await i.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${i.id}`})}catch(f){throw e.context.logger.error("",f),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let m=await i.getUserInfo(l).then(f=>f?.user);function p(f){let y=d||c||`${e.context.baseURL}/error`;throw y.includes("?")?y=`${y}&error=${f}`:y=`${y}?error=${f}`,e.redirect(y)}if(!m)return e.context.logger.error("Unable to get user info"),p("unable_to_get_user_info");if(!m.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),p("email_not_found");if(!c)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(a){if(a.email!==m.email.toLowerCase())return p("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:a.userId,providerId:i.id,accountId:m.id}))return p("unable_to_link_account");let y;try{y=new URL(c).toString()}catch{y=c}throw e.redirect(y)}let w=await te(e,{userInfo:{id:m.id,email:m.email,name:m.name||"",image:m.image,emailVerified:m.emailVerified||!1},account:{providerId:i.id,accountId:m.id,...l,scope:l.scopes?.join(",")},callbackURL:c});if(w.error)return e.context.logger.error(w.error.split(" ").join("_")),p(w.error.split(" ").join("_"));let{session:L,user:_}=w.data;await E(e,{session:L,user:_});let g;try{g=new URL(c).toString()}catch{g=c}throw e.redirect(g)});import"zod";import{APIError as Xt}from"better-call";var Ge=h("/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 C(e),new Xt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),C(e),e.json({success:!0})});import{z as P}from"zod";import{APIError as ce}from"better-call";function Qe(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 er(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 Ze=h("/forget-password",{method:"POST",body:P.object({email:P.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:P.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 ce("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=V(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=Se(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})}),Je=h("/reset-password/:token",{method:"GET",query:P.object({callbackURL:P.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(Qe(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Qe(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(er(e.context,r,{token:t}))}),We=h("/reset-password",{query:P.optional(P.object({token:P.string().optional(),currentURL:P.string().optional()})),method:"POST",body:P.object({newPassword:P.string({description:"The new password to set"}),token:P.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 ce("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new ce("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(i)).find(d=>d.providerId==="credential")?(await e.context.internalAdapter.updatePassword(i,s),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:i}),e.json({status:!0}))});import{z as R}from"zod";import{APIError as x}from"better-call";import{z as u}from"zod";import{APIError as tr}from"better-call";var $n=u.object({id:u.string(),providerId:u.string(),accountId:u.string(),userId:u.string(),accessToken:u.string().nullish(),refreshToken:u.string().nullish(),idToken:u.string().nullish(),accessTokenExpiresAt:u.date().nullish(),refreshTokenExpiresAt:u.date().nullish(),scope:u.string().nullish(),password:u.string().nullish(),createdAt:u.date().default(()=>new Date),updatedAt:u.date().default(()=>new Date)}),qn=u.object({id:u.string(),email:u.string().transform(e=>e.toLowerCase()),emailVerified:u.boolean().default(!1),name:u.string(),image:u.string().nullish(),createdAt:u.date().default(()=>new Date),updatedAt:u.date().default(()=>new Date)}),Nn=u.object({id:u.string(),userId:u.string(),expiresAt:u.date(),createdAt:u.date().default(()=>new Date),updatedAt:u.date().default(()=>new Date),token:u.string(),ipAddress:u.string().nullish(),userAgent:u.string().nullish()}),Fn=u.object({id:u.string(),value:u.string(),createdAt:u.date().default(()=>new Date),updatedAt:u.date().default(()=>new Date),expiresAt:u.date(),identifier:u.string()});function rr(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 or(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}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 tr("BAD_REQUEST",{message:`${i} is required`})}return n}function oe(e,t,r){let o=rr(e,"user");return or(t||{},{fields:o,action:r})}var Ke=()=>h("/update-user",{method:"POST",body:R.record(R.string(),R.any()),use:[S],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 x("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...n}=t,i=e.context.session;if(!o&&!r&&Object.keys(n).length===0)return e.json({user:i.user});let s=oe(e.context.options,n,"update"),c=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await E(e,{session:i.session,user:c}),e.json({user:c})}),Ye=h("/change-password",{method:"POST",body:R.object({newPassword:R.string({description:"The new password to set"}),currentPassword:R.string({description:"The current password"}),revokeOtherSessions:R.boolean({description:"Revoke all other sessions"}).optional()}),use:[S],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 x("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new x("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(m=>m.providerId==="credential"&&m.password);if(!a||!a.password)throw new x("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify({hash:a.password,password:r}))throw new x("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(a.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let m=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!m)throw new x("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await E(e,{session:m,user:n.user})}return e.json(n.user)}),Xe=h("/set-password",{method:"POST",body:R.object({newPassword:R.string()}),metadata:{SERVER_ONLY:!0},use:[S]},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 x("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new x("BAD_REQUEST",{message:"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(r.user);throw new x("BAD_REQUEST",{message:"user already has a password"})}),et=h("/delete-user",{method:"POST",body:R.object({password:R.string({description:"The password of the user"})}),use:[De],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{let t=e.context.session;return await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),C(e),e.json(null)}),tt=h("/change-email",{method:"POST",query:R.object({currentURL:R.string().optional()}).optional(),body:R.object({newEmail:R.string({description:"The new email to set"}).email(),callbackURL:R.string({description:"The URL to redirect to after email verification"}).optional()}),use:[S],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 x("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 x("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 x("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new x("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await D(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({user:null,status:!0})});var ir=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|
|
@@ -2,8 +2,8 @@ import * as nanostores from 'nanostores';
|
|
|
2
2
|
import { AccessControl, StatementsPrimitive, Role } from '../plugins/access.cjs';
|
|
3
3
|
import * as _better_fetch_fetch from '@better-fetch/fetch';
|
|
4
4
|
import { BetterFetchOption } from '@better-fetch/fetch';
|
|
5
|
-
import { o as organization, q as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, f as anonymous, i as admin, j as genericOAuth, k as jwt, l as multiSession, n as emailOTP } from '../index-
|
|
6
|
-
export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-
|
|
5
|
+
import { o as organization, q as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, f as anonymous, i as admin, j as genericOAuth, k as jwt, l as multiSession, n as emailOTP } from '../index-COXQdrg3.cjs';
|
|
6
|
+
export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-COXQdrg3.cjs';
|
|
7
7
|
import { P as Prettify } from '../helper-DxMBi7M2.cjs';
|
|
8
8
|
import { F as FieldAttribute, B as BetterAuthOptions, j as BetterAuthPlugin } from '../auth-DuzXr0Ie.cjs';
|
|
9
9
|
import { Store } from '../types.cjs';
|
package/dist/client/plugins.d.ts
CHANGED
|
@@ -2,8 +2,8 @@ import * as nanostores from 'nanostores';
|
|
|
2
2
|
import { AccessControl, StatementsPrimitive, Role } from '../plugins/access.js';
|
|
3
3
|
import * as _better_fetch_fetch from '@better-fetch/fetch';
|
|
4
4
|
import { BetterFetchOption } from '@better-fetch/fetch';
|
|
5
|
-
import { o as organization, q as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, f as anonymous, i as admin, j as genericOAuth, k as jwt, l as multiSession, n as emailOTP } from '../index-
|
|
6
|
-
export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-
|
|
5
|
+
import { o as organization, q as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, f as anonymous, i as admin, j as genericOAuth, k as jwt, l as multiSession, n as emailOTP } from '../index-BqsItHPw.js';
|
|
6
|
+
export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-BqsItHPw.js';
|
|
7
7
|
import { P as Prettify } from '../helper-DxMBi7M2.js';
|
|
8
8
|
import { F as FieldAttribute, B as BetterAuthOptions, j as BetterAuthPlugin } from '../auth-pJaOH2YO.js';
|
|
9
9
|
import { Store } from '../types.js';
|
package/dist/cookies.cjs
CHANGED
|
@@ -80,4 +80,4 @@ Error: `,c),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
|
|
|
80
80
|
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
81
81
|
</div>
|
|
82
82
|
</body>
|
|
83
|
-
</html>`,Qt=m("/error",{method:"GET",metadata:{...$,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(Gt(t),{headers:{"Content-Type":"text/html"}})});var Zt=m("/ok",{method:"GET",metadata:{...$,openapi:{description:"Check if the API is working",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean"}}}}}}}}}},async e=>e.json({ok:!0}));var Jt=require("zod");var Wt=require("better-call");var H=require("zod");var le=require("better-call");var Kt=m("/list-accounts",{method:"GET",use:[I],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})))}),Yt=m("/link-social",{method:"POST",requireHeaders:!0,query:H.z.object({currentURL:H.z.string().optional()}).optional(),body:H.z.object({callbackURL:H.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:H.z.enum(ee,{description:"The OAuth2 provider to use"})}),use:[I],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 le.APIError("BAD_REQUEST",{message:"Social Account is already linked."});let i=e.context.socialProviders.find(c=>c.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new le.APIError("NOT_FOUND",{message:"Provider not found"});let n=await X(e,{userId:t.user.id,email:t.user.email}),s=await i.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:s.toString(),redirect:!0})});var Xt=require("better-call");function er(e){let t=new Map;return e.split(", ").forEach(o=>{let i=o.split(";").map(u=>u.trim()),[n,...s]=i,[c,...a]=n.split("="),d=a.join("=");if(!c||d===void 0){console.warn(`Malformed cookie: ${o}`);return}let p={value:d};s.forEach(u=>{let[w,...k]=u.split("="),y=k.join("="),V=w.trim().toLowerCase();switch(V){case"max-age":p["max-age"]=y?parseInt(y.trim(),10):void 0;break;case"expires":p.expires=y?new Date(y.trim()):void 0;break;case"domain":p.domain=y?y.trim():void 0;break;case"path":p.path=y?y.trim():void 0;break;case"secure":p.secure=!0;break;case"httponly":p.httponly=!0;break;case"samesite":p.samesite=y?y.trim().toLowerCase():void 0;break;default:p[V]=y?y.trim():!0;break}}),t.set(c,p)}),t}function ct(e){let r=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:e.baseURL!==void 0?!!e.baseURL.startsWith("https://"):me)?"__Secure-":"",o=!!e.advanced?.crossSubDomainCookies?.enabled,i=o?e.advanced?.crossSubDomainCookies?.domain||(e.baseURL?new URL(e.baseURL).hostname:void 0):void 0;if(o&&!i)throw new O("baseURL is required when crossSubdomainCookies are enabled");function n(s,c={}){let a=e.advanced?.cookiePrefix||"better-auth",d=e.advanced?.cookies?.[s]?.name||`${a}.${s}`,p=e.advanced?.cookies?.[s]?.attributes;return{name:`${r}${d}`,attributes:{secure:!!r,sameSite:"lax",path:"/",httpOnly:!0,...o?{domain:i}:{},...e.advanced?.defaultCookieAttributes,...c,...p}}}return n}function tr(e){let t=ct(e),r=e.session?.expiresIn||new st.TimeSpan(7,"d").seconds(),o=t("session_token",{maxAge:r}),i=t("session_data",{maxAge:e.session?.cookieCache?.maxAge||60*5}),n=t("dont_remember");return{sessionToken:{name:o.name,options:o.attributes},sessionData:{name:i.name,options:i.attributes},dontRememberToken:{name:n.name,options:n.attributes}}}async function U(e,t,r,o){let i=e.context.authCookies.sessionToken.options,n=r?void 0:e.context.sessionConfig.expiresIn,s=await B(e).catch(()=>null);s&&s.session.userId===t.session.userId&&s.session.token!==t.session.token&&await e.context.internalAdapter.deleteSession(s.session.token),await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(at.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:C(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await J.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function P(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}function rr(e){let t=e.split("; "),r=new Map;return t.forEach(o=>{let[i,n]=o.split("=");r.set(i,n)}),r}0&&(module.exports={createCookieGetter,deleteSessionCookie,getCookies,parseCookies,parseSetCookieHeader,setSessionCookie});
|
|
83
|
+
</html>`,Qt=m("/error",{method:"GET",metadata:{...$,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(Gt(t),{headers:{"Content-Type":"text/html"}})});var Zt=m("/ok",{method:"GET",metadata:{...$,openapi:{description:"Check if the API is working",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean"}}}}}}}}}},async e=>e.json({ok:!0}));var Jt=require("zod");var Wt=require("better-call");var H=require("zod");var le=require("better-call");var Kt=m("/list-accounts",{method:"GET",use:[I],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})))}),Yt=m("/link-social",{method:"POST",requireHeaders:!0,query:H.z.object({currentURL:H.z.string().optional()}).optional(),body:H.z.object({callbackURL:H.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:H.z.enum(ee,{description:"The OAuth2 provider to use"})}),use:[I],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 le.APIError("BAD_REQUEST",{message:"Social Account is already linked."});let i=e.context.socialProviders.find(c=>c.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new le.APIError("NOT_FOUND",{message:"Provider not found"});let n=await X(e,{userId:t.user.id,email:t.user.email}),s=await i.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:s.toString(),redirect:!0})});var Xt=require("better-call");function er(e){let t=new Map;return e.split(", ").forEach(o=>{let i=o.split(";").map(u=>u.trim()),[n,...s]=i,[c,...a]=n.split("="),d=a.join("=");if(!c||d===void 0){console.warn(`Malformed cookie: ${o}`);return}let p={value:d};s.forEach(u=>{let[w,...k]=u.split("="),y=k.join("="),V=w.trim().toLowerCase();switch(V){case"max-age":p["max-age"]=y?parseInt(y.trim(),10):void 0;break;case"expires":p.expires=y?new Date(y.trim()):void 0;break;case"domain":p.domain=y?y.trim():void 0;break;case"path":p.path=y?y.trim():void 0;break;case"secure":p.secure=!0;break;case"httponly":p.httponly=!0;break;case"samesite":p.samesite=y?y.trim().toLowerCase():void 0;break;default:p[V]=y?y.trim():!0;break}}),t.set(c,p)}),t}function ct(e){let r=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:e.baseURL!==void 0?!!e.baseURL.startsWith("https://"):me)?"__Secure-":"",o=!!e.advanced?.crossSubDomainCookies?.enabled,i=o?e.advanced?.crossSubDomainCookies?.domain||(e.baseURL?new URL(e.baseURL).hostname:void 0):void 0;if(o&&!i)throw new O("baseURL is required when crossSubdomainCookies are enabled");function n(s,c={}){let a=e.advanced?.cookiePrefix||"better-auth",d=e.advanced?.cookies?.[s]?.name||`${a}.${s}`,p=e.advanced?.cookies?.[s]?.attributes;return{name:`${r}${d}`,attributes:{secure:!!r,sameSite:"lax",path:"/",httpOnly:!0,...o?{domain:i}:{},...e.advanced?.defaultCookieAttributes,...c,...p}}}return n}function tr(e){let t=ct(e),r=e.session?.expiresIn||new st.TimeSpan(7,"d").seconds(),o=t("session_token",{maxAge:r}),i=t("session_data",{maxAge:e.session?.cookieCache?.maxAge||60*5}),n=t("dont_remember");return{sessionToken:{name:o.name,options:o.attributes},sessionData:{name:i.name,options:i.attributes},dontRememberToken:{name:n.name,options:n.attributes}}}async function U(e,t,r,o){let i=e.context.authCookies.sessionToken.options,n=r?void 0:e.context.sessionConfig.expiresIn,s=await B(e).catch(()=>null);s&&s.session.userId===t.session.userId&&s.session.token!==t.session.token&&await e.context.internalAdapter.deleteSession(s.session.token),await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(at.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:C(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await J.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),new Date(t.session.expiresAt).getTime()-Date.now())}function P(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}function rr(e){let t=e.split("; "),r=new Map;return t.forEach(o=>{let[i,n]=o.split("=");r.set(i,n)}),r}0&&(module.exports={createCookieGetter,deleteSessionCookie,getCookies,parseCookies,parseSetCookieHeader,setSessionCookie});
|
package/dist/cookies.js
CHANGED
|
@@ -80,4 +80,4 @@ Error: `,c),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
|
|
|
80
80
|
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
81
81
|
</div>
|
|
82
82
|
</body>
|
|
83
|
-
</html>`,qt=m("/error",{method:"GET",metadata:{...V,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($t(t),{headers:{"Content-Type":"text/html"}})});var Nt=m("/ok",{method:"GET",metadata:{...V,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 Pn}from"zod";import{APIError as Bn}from"better-call";import{z as H}from"zod";import{APIError as Ie}from"better-call";var Ft=m("/list-accounts",{method:"GET",use:[S],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})))}),Ht=m("/link-social",{method:"POST",requireHeaders:!0,query:H.object({currentURL:H.string().optional()}).optional(),body:H.object({callbackURL:H.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:H.enum(J,{description:"The OAuth2 provider to use"})}),use:[S],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 Ie("BAD_REQUEST",{message:"Social Account is already linked."});let i=e.context.socialProviders.find(c=>c.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Ie("NOT_FOUND",{message:"Provider not found"});let n=await Z(e,{userId:t.user.id,email:t.user.email}),s=await i.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:s.toString(),redirect:!0})});import{APIError as js}from"better-call";function Ds(e){let t=new Map;return e.split(", ").forEach(o=>{let i=o.split(";").map(u=>u.trim()),[n,...s]=i,[c,...a]=n.split("="),d=a.join("=");if(!c||d===void 0){console.warn(`Malformed cookie: ${o}`);return}let p={value:d};s.forEach(u=>{let[w,...k]=u.split("="),y=k.join("="),B=w.trim().toLowerCase();switch(B){case"max-age":p["max-age"]=y?parseInt(y.trim(),10):void 0;break;case"expires":p.expires=y?new Date(y.trim()):void 0;break;case"domain":p.domain=y?y.trim():void 0;break;case"path":p.path=y?y.trim():void 0;break;case"secure":p.secure=!0;break;case"httponly":p.httponly=!0;break;case"samesite":p.samesite=y?y.trim().toLowerCase():void 0;break;default:p[B]=y?y.trim():!0;break}}),t.set(c,p)}),t}function Qt(e){let r=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:e.baseURL!==void 0?!!e.baseURL.startsWith("https://"):ie)?"__Secure-":"",o=!!e.advanced?.crossSubDomainCookies?.enabled,i=o?e.advanced?.crossSubDomainCookies?.domain||(e.baseURL?new URL(e.baseURL).hostname:void 0):void 0;if(o&&!i)throw new L("baseURL is required when crossSubdomainCookies are enabled");function n(s,c={}){let a=e.advanced?.cookiePrefix||"better-auth",d=e.advanced?.cookies?.[s]?.name||`${a}.${s}`,p=e.advanced?.cookies?.[s]?.attributes;return{name:`${r}${d}`,attributes:{secure:!!r,sameSite:"lax",path:"/",httpOnly:!0,...o?{domain:i}:{},...e.advanced?.defaultCookieAttributes,...c,...p}}}return n}function Ms(e){let t=Qt(e),r=e.session?.expiresIn||new Mt(7,"d").seconds(),o=t("session_token",{maxAge:r}),i=t("session_data",{maxAge:e.session?.cookieCache?.maxAge||60*5}),n=t("dont_remember");return{sessionToken:{name:o.name,options:o.attributes},sessionData:{name:i.name,options:i.attributes},dontRememberToken:{name:n.name,options:n.attributes}}}async function v(e,t,r,o){let i=e.context.authCookies.sessionToken.options,n=r?void 0:e.context.sessionConfig.expiresIn,s=await D(e).catch(()=>null);s&&s.session.userId===t.session.userId&&s.session.token!==t.session.token&&await e.context.internalAdapter.deleteSession(s.session.token),await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Gt.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:O(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await M.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function I(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}function Gs(e){let t=e.split("; "),r=new Map;return t.forEach(o=>{let[i,n]=o.split("=");r.set(i,n)}),r}export{Qt as createCookieGetter,I as deleteSessionCookie,Ms as getCookies,Gs as parseCookies,Ds as parseSetCookieHeader,v as setSessionCookie};
|
|
83
|
+
</html>`,qt=m("/error",{method:"GET",metadata:{...V,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($t(t),{headers:{"Content-Type":"text/html"}})});var Nt=m("/ok",{method:"GET",metadata:{...V,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 Pn}from"zod";import{APIError as Bn}from"better-call";import{z as H}from"zod";import{APIError as Ie}from"better-call";var Ft=m("/list-accounts",{method:"GET",use:[S],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})))}),Ht=m("/link-social",{method:"POST",requireHeaders:!0,query:H.object({currentURL:H.string().optional()}).optional(),body:H.object({callbackURL:H.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:H.enum(J,{description:"The OAuth2 provider to use"})}),use:[S],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 Ie("BAD_REQUEST",{message:"Social Account is already linked."});let i=e.context.socialProviders.find(c=>c.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Ie("NOT_FOUND",{message:"Provider not found"});let n=await Z(e,{userId:t.user.id,email:t.user.email}),s=await i.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:s.toString(),redirect:!0})});import{APIError as js}from"better-call";function Ds(e){let t=new Map;return e.split(", ").forEach(o=>{let i=o.split(";").map(u=>u.trim()),[n,...s]=i,[c,...a]=n.split("="),d=a.join("=");if(!c||d===void 0){console.warn(`Malformed cookie: ${o}`);return}let p={value:d};s.forEach(u=>{let[w,...k]=u.split("="),y=k.join("="),B=w.trim().toLowerCase();switch(B){case"max-age":p["max-age"]=y?parseInt(y.trim(),10):void 0;break;case"expires":p.expires=y?new Date(y.trim()):void 0;break;case"domain":p.domain=y?y.trim():void 0;break;case"path":p.path=y?y.trim():void 0;break;case"secure":p.secure=!0;break;case"httponly":p.httponly=!0;break;case"samesite":p.samesite=y?y.trim().toLowerCase():void 0;break;default:p[B]=y?y.trim():!0;break}}),t.set(c,p)}),t}function Qt(e){let r=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:e.baseURL!==void 0?!!e.baseURL.startsWith("https://"):ie)?"__Secure-":"",o=!!e.advanced?.crossSubDomainCookies?.enabled,i=o?e.advanced?.crossSubDomainCookies?.domain||(e.baseURL?new URL(e.baseURL).hostname:void 0):void 0;if(o&&!i)throw new L("baseURL is required when crossSubdomainCookies are enabled");function n(s,c={}){let a=e.advanced?.cookiePrefix||"better-auth",d=e.advanced?.cookies?.[s]?.name||`${a}.${s}`,p=e.advanced?.cookies?.[s]?.attributes;return{name:`${r}${d}`,attributes:{secure:!!r,sameSite:"lax",path:"/",httpOnly:!0,...o?{domain:i}:{},...e.advanced?.defaultCookieAttributes,...c,...p}}}return n}function Ms(e){let t=Qt(e),r=e.session?.expiresIn||new Mt(7,"d").seconds(),o=t("session_token",{maxAge:r}),i=t("session_data",{maxAge:e.session?.cookieCache?.maxAge||60*5}),n=t("dont_remember");return{sessionToken:{name:o.name,options:o.attributes},sessionData:{name:i.name,options:i.attributes},dontRememberToken:{name:n.name,options:n.attributes}}}async function v(e,t,r,o){let i=e.context.authCookies.sessionToken.options,n=r?void 0:e.context.sessionConfig.expiresIn,s=await D(e).catch(()=>null);s&&s.session.userId===t.session.userId&&s.session.token!==t.session.token&&await e.context.internalAdapter.deleteSession(s.session.token),await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Gt.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:O(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await M.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),new Date(t.session.expiresAt).getTime()-Date.now())}function I(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}function Gs(e){let t=e.split("; "),r=new Map;return t.forEach(o=>{let[i,n]=o.split("=");r.set(i,n)}),r}export{Qt as createCookieGetter,I as deleteSessionCookie,Ms as getCookies,Gs as parseCookies,Ds as parseSetCookieHeader,v as setSessionCookie};
|