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