better-auth 1.0.11-beta.7 → 1.0.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/drizzle.d.cts +3 -3
- package/dist/adapters/drizzle.d.ts +3 -3
- package/dist/adapters/kysely.d.cts +3 -3
- package/dist/adapters/kysely.d.ts +3 -3
- package/dist/adapters/memory.d.cts +3 -3
- package/dist/adapters/memory.d.ts +3 -3
- package/dist/adapters/mongodb.d.cts +3 -3
- package/dist/adapters/mongodb.d.ts +3 -3
- package/dist/adapters/prisma.d.cts +3 -3
- package/dist/adapters/prisma.d.ts +3 -3
- package/dist/api.cjs +4 -4
- package/dist/api.d.cts +3 -3
- package/dist/api.d.ts +3 -3
- package/dist/api.js +4 -4
- package/dist/{auth-DhlXAvql.d.cts → auth-BXGk5qca.d.cts} +362 -208
- package/dist/{auth-KXS9j15R.d.ts → auth-CkPAOFDT.d.ts} +362 -208
- package/dist/client/plugins.cjs +1 -1
- package/dist/client/plugins.d.cts +5 -5
- package/dist/client/plugins.d.ts +5 -5
- package/dist/client/plugins.js +1 -1
- package/dist/client.cjs +1 -1
- package/dist/client.d.cts +6 -5
- package/dist/client.d.ts +6 -5
- package/dist/client.js +1 -1
- package/dist/cookies.cjs +4 -4
- package/dist/cookies.d.cts +3 -3
- package/dist/cookies.d.ts +3 -3
- package/dist/cookies.js +4 -4
- package/dist/db.d.cts +4 -4
- package/dist/db.d.ts +4 -4
- package/dist/{helper-D7-GCsit.d.cts → helper-CbDsvI53.d.cts} +1 -1
- package/dist/{helper-D7-GCsit.d.ts → helper-CbDsvI53.d.ts} +1 -1
- package/dist/{index-CzNk4Pfg.d.ts → index-D-YV5Zje.d.ts} +85 -24
- package/dist/{index-D8gQ5szs.d.ts → index-DF4xhhKM.d.ts} +1 -1
- package/dist/{index-BpO3bVrq.d.cts → index-DK8lgTJU.d.cts} +85 -24
- package/dist/{index-BCG0sjEj.d.cts → index-DPqpIwKX.d.cts} +1 -1
- package/dist/index.cjs +4 -4
- package/dist/index.d.cts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +4 -4
- package/dist/next-js.cjs +4 -4
- package/dist/next-js.d.cts +3 -3
- package/dist/next-js.d.ts +3 -3
- package/dist/next-js.js +4 -4
- package/dist/node.d.cts +3 -3
- package/dist/node.d.ts +3 -3
- package/dist/oauth2.d.cts +5 -5
- package/dist/oauth2.d.ts +5 -5
- package/dist/plugins/access.d.cts +1 -1
- package/dist/plugins/access.d.ts +1 -1
- package/dist/plugins.cjs +7 -7
- package/dist/plugins.d.cts +33 -5
- package/dist/plugins.d.ts +33 -5
- package/dist/plugins.js +7 -7
- package/dist/react.cjs +1 -1
- package/dist/react.d.cts +6 -5
- package/dist/react.d.ts +6 -5
- package/dist/react.js +1 -1
- package/dist/social.d.cts +2 -2
- package/dist/social.d.ts +2 -2
- package/dist/solid-start.d.cts +3 -3
- package/dist/solid-start.d.ts +3 -3
- package/dist/solid.cjs +1 -1
- package/dist/solid.d.cts +7 -6
- package/dist/solid.d.ts +7 -6
- package/dist/solid.js +1 -1
- package/dist/{state-DssXDG0e.d.ts → state-6dYBsmUy.d.ts} +1 -1
- package/dist/{state-fGFZRhVK.d.cts → state-BCXtPaPO.d.cts} +1 -1
- package/dist/svelte-kit.d.cts +3 -3
- package/dist/svelte-kit.d.ts +3 -3
- package/dist/svelte.cjs +1 -1
- package/dist/svelte.d.cts +6 -5
- package/dist/svelte.d.ts +6 -5
- package/dist/svelte.js +1 -1
- package/dist/types.d.cts +7 -6
- package/dist/types.d.ts +7 -6
- package/dist/vue.cjs +1 -1
- package/dist/vue.d.cts +6 -5
- package/dist/vue.d.ts +6 -5
- package/dist/vue.js +1 -1
- package/package.json +23 -23
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { B as BetterAuthOptions, W as Where } from '../auth-
|
|
1
|
+
import { B as BetterAuthOptions, W as Where } from '../auth-BXGk5qca.cjs';
|
|
2
2
|
import 'kysely';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'better-call';
|
|
5
|
-
import '../helper-
|
|
6
|
-
import '../index-
|
|
5
|
+
import '../helper-CbDsvI53.cjs';
|
|
6
|
+
import '../index-DPqpIwKX.cjs';
|
|
7
7
|
import 'jose';
|
|
8
8
|
import 'better-sqlite3';
|
|
9
9
|
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { B as BetterAuthOptions, W as Where } from '../auth-
|
|
1
|
+
import { B as BetterAuthOptions, W as Where } from '../auth-CkPAOFDT.js';
|
|
2
2
|
import 'kysely';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'better-call';
|
|
5
|
-
import '../helper-
|
|
6
|
-
import '../index-
|
|
5
|
+
import '../helper-CbDsvI53.js';
|
|
6
|
+
import '../index-DF4xhhKM.js';
|
|
7
7
|
import 'jose';
|
|
8
8
|
import 'better-sqlite3';
|
|
9
9
|
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { Kysely } from 'kysely';
|
|
2
|
-
import { B as BetterAuthOptions, K as KyselyDatabaseType, W as Where } from '../auth-
|
|
2
|
+
import { B as BetterAuthOptions, K as KyselyDatabaseType, W as Where } from '../auth-BXGk5qca.cjs';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'better-call';
|
|
5
|
-
import '../helper-
|
|
6
|
-
import '../index-
|
|
5
|
+
import '../helper-CbDsvI53.cjs';
|
|
6
|
+
import '../index-DPqpIwKX.cjs';
|
|
7
7
|
import 'jose';
|
|
8
8
|
import 'better-sqlite3';
|
|
9
9
|
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { Kysely } from 'kysely';
|
|
2
|
-
import { B as BetterAuthOptions, K as KyselyDatabaseType, W as Where } from '../auth-
|
|
2
|
+
import { B as BetterAuthOptions, K as KyselyDatabaseType, W as Where } from '../auth-CkPAOFDT.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'better-call';
|
|
5
|
-
import '../helper-
|
|
6
|
-
import '../index-
|
|
5
|
+
import '../helper-CbDsvI53.js';
|
|
6
|
+
import '../index-DF4xhhKM.js';
|
|
7
7
|
import 'jose';
|
|
8
8
|
import 'better-sqlite3';
|
|
9
9
|
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { B as BetterAuthOptions, W as Where } from '../auth-
|
|
1
|
+
import { B as BetterAuthOptions, W as Where } from '../auth-BXGk5qca.cjs';
|
|
2
2
|
import 'kysely';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'better-call';
|
|
5
|
-
import '../helper-
|
|
6
|
-
import '../index-
|
|
5
|
+
import '../helper-CbDsvI53.cjs';
|
|
6
|
+
import '../index-DPqpIwKX.cjs';
|
|
7
7
|
import 'jose';
|
|
8
8
|
import 'better-sqlite3';
|
|
9
9
|
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { B as BetterAuthOptions, W as Where } from '../auth-
|
|
1
|
+
import { B as BetterAuthOptions, W as Where } from '../auth-CkPAOFDT.js';
|
|
2
2
|
import 'kysely';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'better-call';
|
|
5
|
-
import '../helper-
|
|
6
|
-
import '../index-
|
|
5
|
+
import '../helper-CbDsvI53.js';
|
|
6
|
+
import '../index-DF4xhhKM.js';
|
|
7
7
|
import 'jose';
|
|
8
8
|
import 'better-sqlite3';
|
|
9
9
|
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { Db } from 'mongodb';
|
|
2
|
-
import { B as BetterAuthOptions, W as Where } from '../auth-
|
|
2
|
+
import { B as BetterAuthOptions, W as Where } from '../auth-BXGk5qca.cjs';
|
|
3
3
|
import 'kysely';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import 'better-call';
|
|
6
|
-
import '../helper-
|
|
7
|
-
import '../index-
|
|
6
|
+
import '../helper-CbDsvI53.cjs';
|
|
7
|
+
import '../index-DPqpIwKX.cjs';
|
|
8
8
|
import 'jose';
|
|
9
9
|
import 'better-sqlite3';
|
|
10
10
|
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { Db } from 'mongodb';
|
|
2
|
-
import { B as BetterAuthOptions, W as Where } from '../auth-
|
|
2
|
+
import { B as BetterAuthOptions, W as Where } from '../auth-CkPAOFDT.js';
|
|
3
3
|
import 'kysely';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import 'better-call';
|
|
6
|
-
import '../helper-
|
|
7
|
-
import '../index-
|
|
6
|
+
import '../helper-CbDsvI53.js';
|
|
7
|
+
import '../index-DF4xhhKM.js';
|
|
8
8
|
import 'jose';
|
|
9
9
|
import 'better-sqlite3';
|
|
10
10
|
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { B as BetterAuthOptions, W as Where } from '../auth-
|
|
1
|
+
import { B as BetterAuthOptions, W as Where } from '../auth-BXGk5qca.cjs';
|
|
2
2
|
import 'kysely';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'better-call';
|
|
5
|
-
import '../helper-
|
|
6
|
-
import '../index-
|
|
5
|
+
import '../helper-CbDsvI53.cjs';
|
|
6
|
+
import '../index-DPqpIwKX.cjs';
|
|
7
7
|
import 'jose';
|
|
8
8
|
import 'better-sqlite3';
|
|
9
9
|
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { B as BetterAuthOptions, W as Where } from '../auth-
|
|
1
|
+
import { B as BetterAuthOptions, W as Where } from '../auth-CkPAOFDT.js';
|
|
2
2
|
import 'kysely';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'better-call';
|
|
5
|
-
import '../helper-
|
|
6
|
-
import '../index-
|
|
5
|
+
import '../helper-CbDsvI53.js';
|
|
6
|
+
import '../index-DF4xhhKM.js';
|
|
7
7
|
import 'jose';
|
|
8
8
|
import 'better-sqlite3';
|
|
9
9
|
|
package/dist/api.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`,`Current list of trustedOrigins: ${a}`),new ot.APIError("FORBIDDEN",{message:`Invalid ${p}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&m(n,"origin"),i&&m(i,"callbackURL"),s&&m(s,"redirectURL"),c&&m(c,"currentURL")});var x=require("better-call"),A=require("zod");var gr=require("oslo"),nt=require("oslo/encoding");var re=require("oslo/crypto");async function mr({value:e,secret:t}){return new re.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function fr({value:e,signature:t,secret:r}){return new re.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var oe={sign:mr,verify:fr};var z=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));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),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(nt.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:z(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await oe.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3))}function C(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}var ut=require("@better-fetch/fetch"),pt=require("better-call"),Z=require("jose"),mt=require("oslo/jwt");var it=require("oslo/crypto"),st=require("oslo/encoding");async function at(e){let t=await(0,it.sha256)(new TextEncoder().encode(e));return st.base64url.encode(new Uint8Array(t),{includePadding:!1})}function ct(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?z(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function U({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,redirectURI:c}){let a=new URL(r);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",t.clientId),a.searchParams.set("state",o),a.searchParams.set("scope",i.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||c),n){let d=await at(n);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",d)}if(s){let d=s.reduce((u,m)=>(u[m]=null,u),{});a.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...d}}))}return a}var dt=require("@better-fetch/fetch");async function b({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n,authentication:i}){let s=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),i==="basic"){let m=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${m}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await(0,dt.betterFetch)(n,{method:"POST",body:s,headers:c});if(d)throw d;return ct(a)}var ne=require("oslo/oauth2"),$=require("zod"),we=require("better-call");async function ie(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?tt(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new we.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,ne.generateCodeVerifier)(),n=(0,ne.generateState)(),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:s});if(!c)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new we.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function lt(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=$.z.object({callbackURL:$.z.string(),codeVerifier:$.z.string(),errorURL:$.z.string().optional(),expiresAt:$.z.number(),link:$.z.object({email:$.z.string(),userId:$.z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var ft=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let n=(0,Z.decodeProtectedHeader)(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let c=await hr(i),{payload:a}=await(0,Z.jwtVerify)(r,c,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=(0,mt.parseJWT)(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email,...i},data:o}}}},hr=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,ut.betterFetch)(`${t}${r}`);if(!o?.keys)throw new pt.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,Z.importJWK)(n,n.alg)};var gt=require("@better-fetch/fetch");var ht=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})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,gt.betterFetch)("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 wt=require("@better-fetch/fetch");var yt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await U({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,wt.betterFetch)("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 ye=require("@better-fetch/fetch");var bt=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),U({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>b({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await(0,ye.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:c,error:a}=await(0,ye.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(c.find(d=>d.primary)??c[0])?.email,i=c.find(d=>d.email===o.email)?.verified??!1)}let s=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i,...s},data:o}}}};var At=require("oslo/jwt");var kt=require("consola"),be=["info","success","warn","error","debug"];function wr(e,t){return be.indexOf(t)<=be.indexOf(e)}var yr=(0,kt.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),br=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,s=[])=>{if(!(!t||!wr(r,n))){if(!e||typeof e.log!="function"){yr[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(be.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},L=br();var Ut=require("@better-fetch/fetch"),Rt=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw L.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new F("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new F("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await U({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:n}=await(0,Ut.betterFetch)(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,At.parseJWT)(t.idToken)?.payload,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 vt=require("@better-fetch/fetch"),Et=require("oslo/jwt");var Tt=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),U({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return b({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=(0,Et.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;await(0,vt.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let u=await a.response.clone().arrayBuffer(),m=Buffer.from(u).toString("base64");i.picture=`data:image/jpeg;base64, ${m}`}catch(d){L.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 xt=require("@better-fetch/fetch");var Pt=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),U({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,xt.betterFetch)("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 Q={isAction:!1};var _t=require("nanoid"),St=e=>(0,_t.nanoid)(e);var It=require("oslo/jwt");var Lt=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),U({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return L.error("No idToken found in token"),null;let o=(0,It.parseJWT)(r)?.payload,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...n},data:o}}});var Ot=require("@better-fetch/fetch");var Ct=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),U({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,Ot.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 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 Dt=require("@better-fetch/fetch");var jt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await U({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await b({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await(0,Dt.betterFetch)("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 Bt=require("@better-fetch/fetch");var Vt=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await U({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await b({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await(0,Bt.betterFetch)("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 $t=require("@better-fetch/fetch");var ke=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),kr=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ke(`${t}/oauth/authorize`),tokenEndpoint:ke(`${t}/oauth/token`),userinfoEndpoint:ke(`${t}/api/v4/user`)}},zt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=kr(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let u=c||["read_user"];return e.scope&&u.push(...e.scope),await U({id:n,options:e,authorizationEndpoint:t,scopes:u,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>b({code:s,redirectURI:e.redirectURI||c,options:e,codeVerifier:a,tokenEndpoint:r}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:c,error:a}=await(0,$t.betterFetch)(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 Ar={apple:ft,discord:ht,facebook:yt,github:bt,microsoft:Tt,google:Rt,spotify:Pt,twitch:Lt,twitter:Ct,dropbox:jt,linkedin:Vt,gitlab:zt},se=Object.keys(Ar);var qt=require("oslo"),ce=require("oslo/jwt"),O=require("zod");var J=require("better-call");var D=require("better-call");var N=require("zod");function Nt(e){try{return JSON.parse(e)}catch{return null}}var ae=()=>g("/get-session",{method:"GET",query:N.z.optional(N.z.object({disableCookieCache:N.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(N.z.string().transform(e=>e==="true")).optional(),disableRefresh:N.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?Nt(Buffer.from(r,"base64").toString()):null;if(o&&!await oe.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return C(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let u=o.session;if(o.expiresAt<Date.now()||u.session.expiresAt<new Date){let l=e.context.authCookies.sessionData.name;e.setCookie(l,"",{maxAge:0})}else return e.json(u)}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return C(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n||e.query?.disableRefresh)return e.json(i);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let u=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:z(e.context.sessionConfig.expiresIn,"sec")});if(!u)return C(e),e.json(null,{status:401});let m=(u.expiresAt.valueOf()-Date.now())/1e3;return await P(e,{session:u,user:i.user},!1,{maxAge:m}),e.json({session:u,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new D.APIError("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),q=async(e,t)=>{if(e.context.session)return e.context.session;let r=await ae()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},_=G(async e=>{let t=await q(e);if(!t?.session)throw new D.APIError("UNAUTHORIZED");return{session:t}}),Ae=G(async e=>{let t=await q(e);if(!t?.session)throw new D.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),n=Date.now();if(!(o+r*1e3>n))throw new D.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),Ue=()=>g("/list-sessions",{method:"GET",use:[_],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Re=g("/revoke-session",{method:"POST",body:N.z.object({token:N.z.string({description:"The token to revoke"})}),use:[_],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 D.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new D.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 D.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ve=g("/revoke-sessions",{method:"POST",use:[_],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 D.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Ee=g("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[_],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 D.APIError("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});async function j(e,t,r){return await(0,ce.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new qt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Mt(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(e.context.secret,t.email),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:r},e.request)}var Te=g("/send-verification-email",{method:"POST",query:O.z.object({currentURL:O.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:O.z.object({email:O.z.string({description:"The email to send the verification email to"}).email(),callbackURL:O.z.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new J.APIError("BAD_REQUEST",{message:"User not found"});return await Mt(e,r.user),e.json({status:!0})}),xe=g("/verify-email",{method:"GET",query:O.z.object({token:O.z.string({description:"The token to verify the email"}),callbackURL:O.z.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(c){throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=${c}`):new J.APIError("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await(0,ce.validateJWT)("HS256",Buffer.from(e.context.secret),r)}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let i=O.z.object({email:O.z.string().email(),updateTo:O.z.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(i.email);if(!s)return t("user_not_found");if(i.updateTo){let c=await q(e);if(!c){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(c.user.email!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${r}`,token:r},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await q(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new J.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await P(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function de(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(c=>{throw L.error(`Better auth was unable to query your database.
|
|
3
|
-
Error: `,c),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user;if(n){let c=n.accounts.find(a=>a.providerId===r.providerId);if(c){let a=Object.fromEntries(Object.entries({accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([d,u])=>u!==void 0));Object.keys(a).length>0&&await e.context.internalAdapter.updateAccount(c.id,a)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Xe&&L.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(u){return L.error("Unable to link account",u),{error:"unable to link account",data:null}}i=await e.context.internalAdapter.updateUser(n.user.id,{...t,updatedAt:new Date})}}else 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(c=>c?.user),!t.emailVerified&&i&&e.context.options.emailVerification?.sendOnSignUp){let c=await j(e.context.secret,i.email),a=`${e.context.baseURL}/verify-email?token=${c}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:a,token:c},e.request)}if(!i)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(i.id,e.request);return s?{data:{session:s,user:i},error:null}:{error:"unable to create session",data:null}}var Pe=g("/sign-in/social",{method:"POST",query:A.z.object({currentURL:A.z.string().optional()}).optional(),body:A.z.object({callbackURL:A.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),errorCallbackURL:A.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:A.z.enum(se,{description:"OAuth2 provider to use"}),disableRedirect:A.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:A.z.optional(A.z.object({token:A.z.string({description:"ID token from the provider"}),nonce:A.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:A.z.string({description:"Access token from the provider"}).optional(),refreshToken:A.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:A.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new x.APIError("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new x.APIError("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:i,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new x.APIError("UNAUTHORIZED",{message:"Invalid id token"});let a=await t.getUserInfo({idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new x.APIError("UNAUTHORIZED",{message:"Failed to get user info"});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new x.APIError("UNAUTHORIZED",{message:"User email not found"});let d=await de(e,{userInfo:{email:a.user.email,id:a.user.id,name:a.user.name||"",image:a.user.image,emailVerified:a.user.emailVerified||!1},account:{providerId:t.id,accountId:a.user.id,accessToken:e.body.idToken.accessToken}});if(d.error)throw new x.APIError("UNAUTHORIZED",{message:d.error});return await P(e,d.data),e.json({session:d.data.session,user:d.data.user,url:void 0,redirect:!1})}let{codeVerifier:r,state:o}=await ie(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})}),_e=g("/sign-in/email",{method:"POST",body:A.z.object({email:A.z.string({description:"Email of the user"}),password:A.z.string({description:"Password of the user"}),callbackURL:A.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:A.z.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new x.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 x.APIError("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new x.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(d=>d.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new x.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new x.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new x.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new x.APIError("UNAUTHORIZED",{message:"Email is not verified."});let d=await j(e.context.secret,n.user.email),u=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:u,token:d},e.request),e.context.logger.error("Email not verified",{email:t}),new x.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new x.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await P(e,{session:a,user:n.user},e.body.rememberMe===!1),e.json({user:n.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var W=require("zod");var le=W.z.object({code:W.z.string().optional(),error:W.z.string().optional(),errorMessage:W.z.string().optional(),state:W.z.string().optional()}),Se=g("/callback/:id",{method:["GET","POST"],body:le.optional(),query:le.optional(),metadata:Q},async e=>{let t;try{if(e.method==="GET")t=le.parse(e.query);else if(e.method==="POST")t=le.parse(e.body);else throw new Error("Unsupported method")}catch(h){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",h),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n}=t;if(!n)throw e.context.logger.error("State not found"),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}`);let i=e.context.socialProviders.find(h=>h.id===e.params.id);if(!i)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:s,callbackURL:c,link:a,errorURL:d}=await lt(e),u;try{u=await i.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${i.id}`})}catch(h){throw e.context.logger.error("",h),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let m=await i.getUserInfo(u).then(h=>h?.user);function l(h){let y=d||c||`${e.context.baseURL}/error`;throw y.includes("?")?y=`${y}&error=${h}`:y=`${y}?error=${h}`,e.redirect(y)}if(!m)return e.context.logger.error("Unable to get user info"),l("unable_to_get_user_info");if(!m.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),l("email_not_found");if(!c)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(a){if(a.email!==m.email.toLowerCase())return l("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:a.userId,providerId:i.id,accountId:m.id}))return l("unable_to_link_account");let y;try{y=new URL(c).toString()}catch{y=c}throw e.redirect(y)}let p=await de(e,{userInfo:{...m,email:m.email,name:m.name||m.email},account:{providerId:i.id,accountId:m.id,...u,scope:u.scopes?.join(",")},callbackURL:c});if(p.error)return e.context.logger.error(p.error.split(" ").join("_")),l(p.error.split(" ").join("_"));let{session:R,user:I}=p.data;await P(e,{session:R,user:I});let w;try{w=new URL(c).toString()}catch{w=c}throw e.redirect(w)});var gi=require("zod");var Ft=require("better-call"),Ie=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 C(e),new Ft.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),C(e),e.json({success:!0})});var S=require("zod");var ue=require("better-call");function Ht(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 Ur(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 Le=g("/forget-password",{method:"POST",body:S.z.object({email:S.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:S.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 ue.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=z(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=St(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})}),Oe=g("/reset-password/:token",{method:"GET",query:S.z.object({callbackURL:S.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(Ht(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Ht(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Ur(e.context,r,{token:t}))}),Ce=g("/reset-password",{query:S.z.optional(S.z.object({token:S.z.string().optional(),currentURL:S.z.string().optional()})),method:"POST",body:S.z.object({newPassword:S.z.string({description:"The new password to set"}),token:S.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 ue.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new ue.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(i)).find(d=>d.providerId==="credential")?(await e.context.internalAdapter.updatePassword(i,s),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:i}),e.json({status:!0}))});var T=require("zod");var v=require("better-call");var f=require("zod"),Gt=require("better-call"),vi=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)}),Ei=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)}),Ti=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()}),xi=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()});function Rr(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function vr(e,t){let r=t.action||"create",o=t.fields,n={};for(let i in o){if(i in e){if(o[i].input===!1){if(o[i].defaultValue){n[i]=o[i].defaultValue;continue}continue}if(o[i].validator?.input&&e[i]!==void 0){n[i]=o[i].validator.input.parse(e[i]);continue}n[i]=e[i];continue}if(o[i].defaultValue&&r==="create"){n[i]=o[i].defaultValue;continue}if(o[i].required&&r==="create")throw new Gt.APIError("BAD_REQUEST",{message:`${i} is required`})}return n}function pe(e,t,r){let o=Rr(e,"user");return vr(t||{},{fields:o,action:r})}var Sr=require("@noble/ciphers/chacha"),je=require("@noble/ciphers/utils"),Ir=require("@noble/ciphers/webcrypto"),Lr=require("oslo/crypto"),Or=We(require("uncrypto"),1);var Zt=require("oslo/encoding");var Er=require("@noble/hashes/scrypt"),Tr=require("uncrypto");var De=We(require("uncrypto"),1);function xr(e){return e.toString(2).padStart(8,"0")}function Pr(e){return[...e].map(t=>xr(t)).join("")}function Qt(e){return parseInt(Pr(e),2)}function _r(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,o=new Uint8Array(Math.ceil(t/8));De.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=Qt(o);for(;n>=e;)De.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=Qt(o);return n}function Jt(e,t){let r="";for(let o=0;o<e;o++)r+=t[_r(t.length)];return r}function Wt(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}var Be=()=>g("/update-user",{method:"POST",body:T.z.record(T.z.string(),T.z.any()),use:[_],metadata:{openapi:{description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"}}}}}}}}}},async e=>{let t=e.body;if(t.email)throw new v.APIError("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...n}=t,i=e.context.session;if(o===void 0&&!r&&Object.keys(n).length===0)return e.json({user:i.user});let s=pe(e.context.options,n,"update"),c=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await P(e,{session:i.session,user:c}),e.json({user:c})}),Ve=g("/change-password",{method:"POST",body:T.z.object({newPassword:T.z.string({description:"The new password to set"}),currentPassword:T.z.string({description:"The current password"}),revokeOtherSessions:T.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[_],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 v.APIError("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new v.APIError("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(m=>m.providerId==="credential"&&m.password);if(!a||!a.password)throw new v.APIError("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify({hash:a.password,password:r}))throw new v.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(a.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let m=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!m)throw new v.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await P(e,{session:m,user:n.user})}return e.json(n.user)}),$e=g("/set-password",{method:"POST",body:T.z.object({newPassword:T.z.string()}),metadata:{SERVER_ONLY:!0},use:[_]},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 v.APIError("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new v.APIError("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password),c=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:c}),e.json(r.user);throw new v.APIError("BAD_REQUEST",{message:"user already has a password"})}),ze=g("/delete-user",{method:"POST",use:[Ae],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 v.APIError("NOT_FOUND");let t=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=Jt(32,Wt("a-z","A-Z","0-9"));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}`;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),C(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})}),Ne=g("/delete-user/callback",{method:"GET",query:T.z.object({token:T.z.string()})},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new v.APIError("NOT_FOUND");let t=await q(e);if(!t)throw new v.APIError("NOT_FOUND",{message:"No session found"});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 v.APIError("NOT_FOUND",{message:"Invalid token"});if(r.value!==t.user.id)throw new v.APIError("NOT_FOUND",{message:"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),C(e);let n=e.context.options.user.deleteUser?.afterDelete;return n&&await n(t.user,e.request),e.json({success:!0,message:"User deleted"})}),qe=g("/change-email",{method:"POST",query:T.z.object({currentURL:T.z.string().optional()}).optional(),body:T.z.object({newEmail:T.z.string({description:"The new email to set"}).email(),callbackURL:T.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[_],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 v.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 v.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 v.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new v.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),e.json({user:null,status:!0})});var Cr=(e="Unknown")=>`<!DOCTYPE html>
|
|
1
|
+
"use strict";var ir=Object.create;var te=Object.defineProperty;var sr=Object.getOwnPropertyDescriptor;var ar=Object.getOwnPropertyNames;var cr=Object.getPrototypeOf,dr=Object.prototype.hasOwnProperty;var lr=(e,t)=>{for(var r in t)te(e,r,{get:t[r],enumerable:!0})},Ye=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ar(t))!dr.call(e,n)&&n!==r&&te(e,n,{get:()=>t[n],enumerable:!(o=sr(t,n))||o.enumerable});return e};var ge=(e,t,r)=>(r=e!=null?ir(cr(e)):{},Ye(t||!e||!e.__esModule?te(r,"default",{value:e,enumerable:!0}):r,e)),ur=e=>Ye(te({},"__esModule",{value:!0}),e);var Hr={};lr(Hr,{APIError:()=>nr.APIError,callbackOAuth:()=>Pe,changeEmail:()=>He,changePassword:()=>ze,createAuthEndpoint:()=>w,createAuthMiddleware:()=>Z,createEmailVerificationToken:()=>j,deleteUser:()=>Fe,deleteUserCallback:()=>Me,error:()=>Ge,forgetPassword:()=>Ce,forgetPasswordCallback:()=>Ne,freshSessionMiddleware:()=>Ue,getEndpoints:()=>or,getSession:()=>de,getSessionFromCtx:()=>M,linkSocialAccount:()=>Je,listSessions:()=>_e,listUserAccounts:()=>Ke,ok:()=>We,optionsMiddleware:()=>he,originCheckMiddleware:()=>be,resetPassword:()=>je,revokeOtherSessions:()=>Oe,revokeSession:()=>Te,revokeSessions:()=>Se,router:()=>Mr,sendVerificationEmail:()=>ve,sendVerificationEmailFn:()=>Ht,sessionMiddleware:()=>x,setPassword:()=>qe,signInEmail:()=>Le,signInSocial:()=>xe,signOut:()=>De,signUpEmail:()=>Ze,updateUser:()=>$e,verifyEmail:()=>Ie});module.exports=ur(Hr);var T=require("better-call");var it=require("better-call");var H=require("better-call"),he=(0,H.createMiddleware)(async()=>({})),Z=(0,H.createMiddlewareCreator)({use:[he,(0,H.createMiddleware)(async()=>({}))]}),w=(0,H.createEndpointCreator)({use:[he]});function we(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function pr(e){let t="";for(let r=0;r<e.length;r++)t+=we(e[r]);return t}function Xe(e,t=!0){if(Array.isArray(e))return`(?:${e.map(u=>`^${Xe(u,t)}$`).join("|")})`;let r="",o="",n=".";t===!0?(r="/",o="[/\\\\]",n="[^/\\\\]"):t&&(r=t,o=pr(r),o.length>1?(o=`(?:${o})`,n=`((?!${o}).)`):n=`[^${o}]`);let i=t?`${o}+?`:"",s=t?`${o}*?`:"",a=t?e.split(r):[e],c="";for(let l=0;l<a.length;l++){let u=a[l],g=a[l+1],m="";if(!(!u&&l>0)){if(t&&(l===a.length-1?m=s:g!=="**"?m=i:m=""),t&&u==="**"){m&&(c+=l===0?"":m,c+=`(?:${n}*?${m})*?`);continue}for(let d=0;d<u.length;d++){let _=u[d];_==="\\"?d<u.length-1&&(c+=we(u[d+1]),d++):_==="?"?c+=n:_==="*"?c+=`${n}*?`:c+=we(_)}c+=m}}return c}function mr(e,t){if(typeof t!="string")throw new TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function re(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=Xe(e,t.separator),o=new RegExp(`^${r}$`,t.flags),n=mr.bind(null,o);return n.options=t,n.pattern=e,n.regexp=o,n}var oe=Object.create(null),ee=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?oe:globalThis),et=new Proxy(oe,{get(e,t){return ee()[t]??oe[t]},has(e,t){let r=ee();return t in r||t in oe},set(e,t,r){let o=ee(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=ee(!0);return delete r[t],!0},ownKeys(){let e=ee(!0);return Object.keys(e)}});function fr(e){return e?e!=="false":!1}var ye=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var tt=ye==="dev"||ye==="development",rt=ye==="test"||fr(et.TEST);var G=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function ot(e){try{return new URL(e).origin}catch{return null}}function nt(e){return e.includes("://")?new URL(e).host:e}var be=Z(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,a=r?.currentURL,c=o.trustedOrigins,l=e.headers?.has("cookie"),u=(m,d)=>m.startsWith("/")?!1:d.includes("*")?re(d)(nt(m)):m.startsWith(d),g=(m,d)=>{if(!m)return;if(!c.some(B=>u(m,B)||m?.startsWith("/")&&d!=="origin"&&!m.includes(":")))throw e.context.logger.error(`Invalid ${d}: ${m}`),e.context.logger.info(`If it's a valid URL, please add ${m} to trustedOrigins in your auth config
|
|
2
|
+
`,`Current list of trustedOrigins: ${c}`),new it.APIError("FORBIDDEN",{message:`Invalid ${d}`})};l&&!e.context.options.advanced?.disableCSRFCheck&&g(n,"origin"),i&&g(i,"callbackURL"),s&&g(s,"redirectURL"),a&&g(a,"currentURL")});var O=require("better-call"),A=require("zod");var yr=require("oslo"),st=require("oslo/encoding");var ne=require("oslo/crypto");async function hr({value:e,secret:t}){return new ne.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function wr({value:e,signature:t,secret:r}){return new ne.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var ie={sign:hr,verify:wr};var q=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function I(e,t,r,o){let n=e.context.authCookies.sessionToken.options,i=r?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...n,maxAge:i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(st.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:q(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await ie.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),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 C(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}var mt=require("@better-fetch/fetch"),ft=require("better-call"),Q=require("jose"),gt=require("oslo/jwt");var at=require("oslo/crypto"),ct=require("oslo/encoding");async function dt(e){let t=await(0,at.sha256)(new TextEncoder().encode(e));return ct.base64url.encode(new Uint8Array(t),{includePadding:!1})}function lt(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?q(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function E({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,redirectURI: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",i.join(" ")),c.searchParams.set("redirect_uri",t.redirectURI||a),n){let l=await dt(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((u,g)=>(u[g]=null,u),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return c}var ut=require("@better-fetch/fetch");async function b({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n,authentication:i}){let s=new URLSearchParams,a={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),i==="basic"){let g=btoa(`${o.clientId}:${o.clientSecret}`);a.authorization=`Basic ${g}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:c,error:l}=await(0,ut.betterFetch)(n,{method:"POST",body:s,headers:a});if(l)throw l;return lt(c)}var se=require("oslo/oauth2"),z=require("zod"),Ae=require("better-call");async function ae(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?ot(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new Ae.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,se.generateCodeVerifier)(),n=(0,se.generateState)(),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:s});if(!a)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new Ae.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function pt(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=z.z.object({callbackURL:z.z.string(),codeVerifier:z.z.string(),errorURL:z.z.string().optional(),expiresAt:z.z.number(),link:z.z.object({email:z.z.string(),userId:z.z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var ht=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let n=(0,Q.decodeProtectedHeader)(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let a=await br(i),{payload:c}=await(0,Q.jwtVerify)(r,a,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(l=>{c[l]!==void 0&&(c[l]=!!c[l])}),o&&c.nonce!==o?!1:!!c},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=(0,gt.parseJWT)(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email,...i},data:o}}}},br=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,mt.betterFetch)(`${t}${r}`);if(!o?.keys)throw new ft.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,Q.importJWK)(n,n.alg)};var wt=require("@better-fetch/fetch");var yt=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})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,wt.betterFetch)("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 bt=require("@better-fetch/fetch");var At=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})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,bt.betterFetch)("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 ke=require("@better-fetch/fetch");var kt=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})=>b({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await(0,ke.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:a,error:c}=await(0,ke.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});c||(o.email=(a.find(l=>l.primary)??a[0])?.email,i=a.find(l=>l.email===o.email)?.verified??!1)}let s=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i,...s},data:o}}}};var Rt=require("oslo/jwt");var Et=require("consola"),Ee=["info","success","warn","error","debug"];function Ar(e,t){return Ee.indexOf(t)<=Ee.indexOf(e)}var kr=(0,Et.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Er=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,s=[])=>{if(!(!t||!Ar(r,n))){if(!e||typeof e.log!="function"){kr[n]("",i,...s);return}e.log(n==="success"?"info":n,i,s)}};return Object.fromEntries(Ee.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},P=Er();var Ut=require("@better-fetch/fetch"),_t=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw P.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new G("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new G("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})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:n}=await(0,Ut.betterFetch)(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,Rt.parseJWT)(t.idToken)?.payload,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 Tt=require("@better-fetch/fetch"),St=require("oslo/jwt");var Ot=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 b({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=(0,St.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;await(0,Tt.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let u=await c.response.clone().arrayBuffer(),g=Buffer.from(u).toString("base64");i.picture=`data:image/jpeg;base64, ${g}`}catch(l){P.error(l&&typeof l=="object"&&"name"in l?l.name:"",l)}}});let a=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0,...a},data:i}}}};var vt=require("@better-fetch/fetch");var It=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})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,vt.betterFetch)("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 K={isAction:!1};var xt=require("nanoid"),Lt=e=>(0,xt.nanoid)(e);var Pt=require("oslo/jwt");var Dt=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})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return P.error("No idToken found in token"),null;let o=(0,Pt.parseJWT)(r)?.payload,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...n},data:o}}});var Ct=require("@better-fetch/fetch");var Nt=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})=>b({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,Ct.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 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 jt=require("@better-fetch/fetch");var Vt=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 b({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await(0,jt.betterFetch)("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 Bt=require("@better-fetch/fetch");var $t=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 b({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await(0,Bt.betterFetch)("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 zt=require("@better-fetch/fetch");var Re=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Rr=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:Re(`${t}/oauth/authorize`),tokenEndpoint:Re(`${t}/oauth/token`),userinfoEndpoint:Re(`${t}/api/v4/user`)}},qt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Rr(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:c,redirectURI:l})=>{let u=a||["read_user"];return e.scope&&u.push(...e.scope),await E({id:n,options:e,authorizationEndpoint:t,scopes:u,state:s,redirectURI:l,codeVerifier:c})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:c})=>b({code:s,redirectURI:e.redirectURI||a,options:e,codeVerifier:c,tokenEndpoint:r}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:a,error:c}=await(0,zt.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(c||a.state!=="active"||a.locked)return null;let l=await e.mapProfileToUser?.(a);return{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0,...l},data:a}}}};var Ur={apple:ht,discord:yt,facebook:At,github:kt,microsoft:Ot,google:_t,spotify:It,twitch:Dt,twitter:Nt,dropbox:Vt,linkedin:$t,gitlab:qt},ce=Object.keys(Ur);var Mt=require("oslo"),le=require("oslo/jwt"),D=require("zod");var J=require("better-call");var N=require("better-call");var F=require("zod");function Ft(e){try{return JSON.parse(e)}catch{return null}}var p={USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found"};var de=()=>w("/get-session",{method:"GET",query:F.z.optional(F.z.object({disableCookieCache:F.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(F.z.string().transform(e=>e==="true")).optional(),disableRefresh:F.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?Ft(Buffer.from(r,"base64").toString()):null;if(o&&!await ie.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return C(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let u=o.session;if(o.expiresAt<Date.now()||u.session.expiresAt<new Date){let m=e.context.authCookies.sessionData.name;e.setCookie(m,"",{maxAge:0})}else return e.json(u)}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return C(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n||e.query?.disableRefresh)return e.json(i);let s=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+a*1e3<=Date.now()){let u=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:q(e.context.sessionConfig.expiresIn,"sec")});if(!u)return C(e),e.json(null,{status:401});let g=(u.expiresAt.valueOf()-Date.now())/1e3;return await I(e,{session:u,user:i.user},!1,{maxAge:g}),e.json({session:u,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new N.APIError("INTERNAL_SERVER_ERROR",{message:p.FAILED_TO_GET_SESSION})}}),M=async(e,t)=>{if(e.context.session)return e.context.session;let r=await de()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},x=Z(async e=>{let t=await M(e);if(!t?.session)throw new N.APIError("UNAUTHORIZED");return{session:t}}),Ue=Z(async e=>{let t=await M(e);if(!t?.session)throw new N.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.createdAt.valueOf(),n=Date.now();if(!(o+r*1e3>n))throw new N.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),_e=()=>w("/list-sessions",{method:"GET",use:[x],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Te=w("/revoke-session",{method:"POST",body:F.z.object({token:F.z.string({description:"The token to revoke"})}),use:[x],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let t=e.body.token,r=await e.context.internalAdapter.findSession(t);if(!r)throw new N.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new N.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 N.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Se=w("/revoke-sessions",{method:"POST",use:[x],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new N.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Oe=w("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[x],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw new N.APIError("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});async function j(e,t,r){return await(0,le.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Mt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}async function Ht(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(e.context.secret,t.email),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:r},e.request)}var ve=w("/send-verification-email",{method:"POST",query:D.z.object({currentURL:D.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:D.z.object({email:D.z.string({description:"The email to send the verification email to"}).email(),callbackURL:D.z.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new J.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new J.APIError("BAD_REQUEST",{message:p.USER_NOT_FOUND});return await Ht(e,r.user),e.json({status:!0})}),Ie=w("/verify-email",{method:"GET",query:D.z.object({token:D.z.string({description:"The token to verify the email"}),callbackURL:D.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(a){throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=${a}`):new J.APIError("UNAUTHORIZED",{message:a})}let{token:r}=e.query,o;try{o=await(0,le.validateJWT)("HS256",Buffer.from(e.context.secret),r)}catch(a){return e.context.logger.error("Failed to verify email",a),t("invalid_token")}let i=D.z.object({email:D.z.string().email(),updateTo:D.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 a=await M(e);if(!a){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(a.user.email!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let c=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:c,url:`${e.context.baseURL}/verify-email?token=${r}`,token:r},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:c,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await M(e)){let c=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!c)throw new J.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await I(e,{session:c,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function ue(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw P.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;if(n){let a=n.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(([l,u])=>u!==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 tt&&P.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(u){return P.error("Unable to link account",u),{error:"unable to link account",data:null}}i=await e.context.internalAdapter.updateUser(n.user.id,{...t,updatedAt:new Date})}}else 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 j(e.context.secret,i.email),c=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:c,token:a},e.request)}if(!i)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(i.id,e.request);return s?{data:{session:s,user:i},error:null}:{error:"unable to create session",data:null}}var xe=w("/sign-in/social",{method:"POST",query:A.z.object({currentURL:A.z.string().optional()}).optional(),body:A.z.object({callbackURL:A.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),errorCallbackURL:A.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:A.z.enum(ce,{description:"OAuth2 provider to use"}),disableRedirect:A.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:A.z.optional(A.z.object({token:A.z.string({description:"ID token from the provider"}),nonce:A.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:A.z.string({description:"Access token from the provider"}).optional(),refreshToken:A.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:A.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new O.APIError("NOT_FOUND",{message:p.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:p.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:p.INVALID_TOKEN});let c=await t.getUserInfo({idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!c||!c?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new O.APIError("UNAUTHORIZED",{message:p.FAILED_TO_GET_USER_INFO});if(!c.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new O.APIError("UNAUTHORIZED",{message:p.USER_EMAIL_NOT_FOUND});let l=await ue(e,{userInfo:{email:c.user.email,id:c.user.id,name:c.user.name||"",image:c.user.image,emailVerified:c.user.emailVerified||!1},account:{providerId:t.id,accountId:c.user.id,accessToken:e.body.idToken.accessToken}});if(l.error)throw new O.APIError("UNAUTHORIZED",{message:l.error});return await I(e,l.data),e.json({session:l.data.session,user:l.data.user,url:void 0,redirect:!1})}let{codeVerifier:r,state:o}=await ae(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})}),Le=w("/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 O.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 O.APIError("BAD_REQUEST",{message:p.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:p.INVALID_EMAIL_OR_PASSWORD});let i=n.accounts.find(l=>l.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new O.APIError("UNAUTHORIZED",{message:p.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:p.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:p.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:p.EMAIL_NOT_VERIFIED});let l=await j(e.context.secret,n.user.email),u=`${e.context.baseURL}/verify-email?token=${l}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:u,token:l},e.request),e.context.logger.error("Email not verified",{email:t}),new O.APIError("FORBIDDEN",{message:p.EMAIL_NOT_VERIFIED})}let c=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!c)throw e.context.logger.error("Failed to create session"),new O.APIError("UNAUTHORIZED",{message:p.FAILED_TO_CREATE_SESSION});return await I(e,{session:c,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 Y=require("zod");var pe=Y.z.object({code:Y.z.string().optional(),error:Y.z.string().optional(),errorMessage:Y.z.string().optional(),state:Y.z.string().optional()}),Pe=w("/callback/:id",{method:["GET","POST"],body:pe.optional(),query:pe.optional(),metadata:K},async e=>{let t;try{if(e.method==="GET")t=pe.parse(e.query);else if(e.method==="POST")t=pe.parse(e.body);else throw new Error("Unsupported method")}catch(f){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",f),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n}=t;if(!n)throw e.context.logger.error("State not found"),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}`);let i=e.context.socialProviders.find(f=>f.id===e.params.id);if(!i)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:s,callbackURL:a,link:c,errorURL:l}=await pt(e),u;try{u=await i.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${i.id}`})}catch(f){throw e.context.logger.error("",f),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let g=await i.getUserInfo(u).then(f=>f?.user);function m(f){let y=l||a||`${e.context.baseURL}/error`;throw y.includes("?")?y=`${y}&error=${f}`:y=`${y}?error=${f}`,e.redirect(y)}if(!g)return e.context.logger.error("Unable to get user info"),m("unable_to_get_user_info");if(!g.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),m("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!==g.email.toLowerCase())return m("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:c.userId,providerId:i.id,accountId:g.id}))return m("unable_to_link_account");let y;try{y=new URL(a).toString()}catch{y=a}throw e.redirect(y)}let d=await ue(e,{userInfo:{...g,email:g.email,name:g.name||g.email},account:{providerId:i.id,accountId:g.id,...u,scope:u.scopes?.join(",")},callbackURL:a});if(d.error)return e.context.logger.error(d.error.split(" ").join("_")),m(d.error.split(" ").join("_"));let{session:_,user:B}=d.data;await I(e,{session:_,user:B});let v;try{v=new URL(a).toString()}catch{v=a}throw e.redirect(v)});var Ei=require("zod");var Gt=require("better-call");var De=w("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw C(e),new Gt.APIError("BAD_REQUEST",{message:p.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(t),C(e),e.json({success:!0})});var L=require("zod");var me=require("better-call");function Wt(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 _r(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 Ce=w("/forget-password",{method:"POST",body:L.z.object({email:L.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:L.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 me.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=q(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=Lt(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:i});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:a,token:s},e.request),e.json({status:!0})}),Ne=w("/reset-password/:token",{method:"GET",query:L.z.object({callbackURL:L.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(Wt(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Wt(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(_r(e.context,r,{token:t}))}),je=w("/reset-password",{query:L.z.optional(L.z.object({token:L.z.string().optional(),currentURL:L.z.string().optional()})),method:"POST",body:L.z.object({newPassword:L.z.string({description:"The new password to set"}),token:L.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 me.APIError("BAD_REQUEST",{message:p.INVALID_TOKEN});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new me.APIError("BAD_REQUEST",{message:p.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(i)).find(l=>l.providerId==="credential")?(await e.context.internalAdapter.updatePassword(i,s),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:i}),e.json({status:!0}))});var S=require("zod");var U=require("better-call");var h=require("zod"),Zt=require("better-call"),Pi=h.z.object({id:h.z.string(),providerId:h.z.string(),accountId:h.z.string(),userId:h.z.string(),accessToken:h.z.string().nullish(),refreshToken:h.z.string().nullish(),idToken:h.z.string().nullish(),accessTokenExpiresAt:h.z.date().nullish(),refreshTokenExpiresAt:h.z.date().nullish(),scope:h.z.string().nullish(),password:h.z.string().nullish(),createdAt:h.z.date().default(()=>new Date),updatedAt:h.z.date().default(()=>new Date)}),Di=h.z.object({id:h.z.string(),email:h.z.string().transform(e=>e.toLowerCase()),emailVerified:h.z.boolean().default(!1),name:h.z.string(),image:h.z.string().nullish(),createdAt:h.z.date().default(()=>new Date),updatedAt:h.z.date().default(()=>new Date)}),Ci=h.z.object({id:h.z.string(),userId:h.z.string(),expiresAt:h.z.date(),createdAt:h.z.date().default(()=>new Date),updatedAt:h.z.date().default(()=>new Date),token:h.z.string(),ipAddress:h.z.string().nullish(),userAgent:h.z.string().nullish()}),Ni=h.z.object({id:h.z.string(),value:h.z.string(),createdAt:h.z.date().default(()=>new Date),updatedAt:h.z.date().default(()=>new Date),expiresAt:h.z.date(),identifier:h.z.string()});function Tr(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function Sr(e,t){let r=t.action||"create",o=t.fields,n={};for(let i in o){if(i in e){if(o[i].input===!1){if(o[i].defaultValue){n[i]=o[i].defaultValue;continue}continue}if(o[i].validator?.input&&e[i]!==void 0){n[i]=o[i].validator.input.parse(e[i]);continue}n[i]=e[i];continue}if(o[i].defaultValue&&r==="create"){n[i]=o[i].defaultValue;continue}if(o[i].required&&r==="create")throw new Zt.APIError("BAD_REQUEST",{message:`${i} is required`})}return n}function fe(e,t,r){let o=Tr(e,"user");return Sr(t||{},{fields:o,action:r})}var Pr=require("@noble/ciphers/chacha"),Be=require("@noble/ciphers/utils"),Dr=require("@noble/ciphers/webcrypto"),Cr=require("oslo/crypto"),Nr=ge(require("uncrypto"),1);var Qt=require("oslo/encoding");var Or=require("@noble/hashes/scrypt"),vr=require("uncrypto");var Ve=ge(require("uncrypto"),1);function Ir(e){return e.toString(2).padStart(8,"0")}function xr(e){return[...e].map(t=>Ir(t)).join("")}function Kt(e){return parseInt(xr(e),2)}function Lr(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,o=new Uint8Array(Math.ceil(t/8));Ve.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=Kt(o);for(;n>=e;)Ve.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=Kt(o);return n}function Jt(e,t){let r="";for(let o=0;o<e;o++)r+=t[Lr(t.length)];return r}function Yt(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}var $e=()=>w("/update-user",{method:"POST",body:S.z.record(S.z.string(),S.z.any()),use:[x],metadata:{openapi:{description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"}}}}}}}}}},async e=>{let t=e.body;if(t.email)throw new U.APIError("BAD_REQUEST",{message:p.EMAIL_CAN_NOT_BE_UPDATED});let{name:r,image:o,...n}=t,i=e.context.session;if(o===void 0&&!r&&Object.keys(n).length===0)return e.json({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});let s=fe(e.context.options,n,"update"),a=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await I(e,{session:i.session,user:a}),e.json({id:a.id,email:a.email,name:a.name,image:a.image,emailVerified:a.emailVerified,createdAt:a.createdAt,updatedAt:a.updatedAt})}),ze=w("/change-password",{method:"POST",body:S.z.object({newPassword:S.z.string({description:"The new password to set"}),currentPassword:S.z.string({description:"The current password"}),revokeOtherSessions:S.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[x],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword: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 U.APIError("BAD_REQUEST",{message:p.PASSWORD_TOO_SHORT});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new U.APIError("BAD_REQUEST",{message:p.PASSWORD_TOO_LONG});let c=(await e.context.internalAdapter.findAccounts(n.user.id)).find(g=>g.providerId==="credential"&&g.password);if(!c||!c.password)throw new U.APIError("BAD_REQUEST",{message:p.CREDENTIAL_ACCOUNT_NOT_FOUND});let l=await e.context.password.hash(t);if(!await e.context.password.verify({hash:c.password,password:r}))throw new U.APIError("BAD_REQUEST",{message:p.INVALID_PASSWORD});if(await e.context.internalAdapter.updateAccount(c.id,{password:l}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let g=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!g)throw new U.APIError("INTERNAL_SERVER_ERROR",{message:p.FAILED_TO_GET_SESSION});await I(e,{session:g,user:n.user})}return e.json(n.user)}),qe=w("/set-password",{method:"POST",body:S.z.object({newPassword:S.z.string()}),metadata:{SERVER_ONLY:!0},use:[x]},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 U.APIError("BAD_REQUEST",{message:p.PASSWORD_TOO_SHORT});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new U.APIError("BAD_REQUEST",{message:p.PASSWORD_TOO_LONG});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(c=>c.providerId==="credential"&&c.password),a=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:a}),e.json(r.user);throw new U.APIError("BAD_REQUEST",{message:"user already has a password"})}),Fe=w("/delete-user",{method:"POST",use:[Ue],metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options",{session:e.context.session}),new U.APIError("NOT_FOUND");let t=e.context.session;if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=Jt(32,Yt("a-z","A-Z","0-9"));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}`;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),C(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})}),Me=w("/delete-user/callback",{method:"GET",query:S.z.object({token:S.z.string()})},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new U.APIError("NOT_FOUND");let t=await M(e);if(!t)throw new U.APIError("NOT_FOUND",{message:p.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 U.APIError("NOT_FOUND",{message:p.INVALID_TOKEN});if(r.value!==t.user.id)throw new U.APIError("NOT_FOUND",{message:p.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),C(e);let n=e.context.options.user.deleteUser?.afterDelete;return n&&await n(t.user,e.request),e.json({success:!0,message:"User deleted"})}),He=w("/change-email",{method:"POST",query:S.z.object({currentURL:S.z.string().optional()}).optional(),body:S.z.object({newEmail:S.z.string({description:"The new email to set"}).email(),callbackURL:S.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[x],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new U.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 U.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 U.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new U.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),e.json({user:null,status:!0})});var jr=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|
|
6
6
|
<meta charset="UTF-8">
|
|
@@ -80,4 +80,4 @@ Error: `,c),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
|
|
|
80
80
|
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
81
81
|
</div>
|
|
82
82
|
</body>
|
|
83
|
-
</html>`,Me=g("/error",{method:"GET",metadata:{...Q,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(Cr(t),{headers:{"Content-Type":"text/html"}})});var Fe=g("/ok",{method:"GET",metadata:{...Q,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 H=require("zod");var B=require("better-call");var He=()=>g("/sign-up/email",{method:"POST",query:H.z.object({currentURL:H.z.string().optional()}).optional(),body:H.z.record(H.z.string(),H.z.any()),metadata:{openapi:{description:"Sign up a user using email and password",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},email:{type:"string",description:"The email of the user"},password:{type:"string",description:"The password of the user"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["name","email","password"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},session:{type:"object"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new B.APIError("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:n,image:i,callbackURL:s,...c}=t;if(!H.z.string().email().safeParse(o).success)throw new B.APIError("BAD_REQUEST",{message:"Invalid email"});if(typeof n!="string")throw new B.APIError("BAD_REQUEST",{message:"Password must be a string"});let d=e.context.password.config.minPasswordLength;if(n.length<d)throw e.context.logger.error("Password is too short"),new B.APIError("BAD_REQUEST",{message:"Password is too short"});let u=e.context.password.config.maxPasswordLength;if(n.length>u)throw e.context.logger.error("Password is too long"),new B.APIError("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new B.APIError("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let l=pe(e.context.options,c),p=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...l,emailVerified:!1});if(!p)throw new B.APIError("BAD_REQUEST",{message:"Failed to create user"});if(!p)throw new B.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let R=await e.context.password.hash(n);if(await e.context.internalAdapter.linkAccount({userId:p.id,providerId:"credential",accountId:p.id,password:R}),e.context.options.emailVerification?.sendOnSignUp){let w=await j(e.context.secret,p.email),h=`${e.context.baseURL}/verify-email?token=${w}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:p,url:h,token:w},e.request)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:p,session:null});let I=await e.context.internalAdapter.createSession(p.id,e.request);if(!I)throw new B.APIError("BAD_REQUEST",{message:"Failed to create session"});return await P(e,{session:I,user:p}),e.json({user:p,session:I})});var K=require("zod");var Ge=require("better-call");var Ze=g("/list-accounts",{method:"GET",use:[_],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})))}),Qe=g("/link-social",{method:"POST",requireHeaders:!0,query:K.z.object({currentURL:K.z.string().optional()}).optional(),body:K.z.object({callbackURL:K.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:K.z.enum(se,{description:"The OAuth2 provider to use"})}),use:[_],metadata:{openapi:{description:"Link a social account to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}},required:["url","redirect"]}}}}}}}},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(c=>c.providerId===e.body.provider))throw new Ge.APIError("BAD_REQUEST",{message:"Social Account is 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 Ge.APIError("NOT_FOUND",{message:"Provider not found"});let i=await ie(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})});function Kt(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let r="127.0.0.1";if(et)return r;let n=t.advanced?.ipAddress?.ipAddressHeaders||["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],i=e instanceof Request?e.headers:e;for(let s of n){let c=i.get(s);if(typeof c=="string"){let a=c.split(",")[0].trim();if(a)return a}}return null}function Dr(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function jr(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":e.toString()}})}function Br(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function Vr(e,t){let r="rateLimit",o=e.adapter;return{get:async n=>(await o.findMany({model:r,where:[{field:"key",value:n}]}))[0],set:async(n,i,s)=>{try{s?await o.updateMany({model:t??"rateLimit",where:[{field:"key",value:n}],update:{count:i.count,lastRequest:i.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:n,count:i.count,lastRequest:i.lastRequest}})}catch(c){e.logger.error("Error setting rate limit",c)}}}}var Yt=new Map;function $r(e){return e.options.rateLimit?.customStorage?e.options.rateLimit.customStorage:e.rateLimit.storage==="secondary-storage"?{get:async r=>{let o=await e.options.secondaryStorage?.get(r);return o?JSON.parse(o):void 0},set:async(r,o)=>{await e.options.secondaryStorage?.set?.(r,JSON.stringify(o))}}:e.rateLimit.storage==="memory"?{async get(r){return Yt.get(r)},async set(r,o,n){Yt.set(r,o)}}:Vr(e,e.rateLimit.modelName)}async function Xt(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,"").split("?")[0],n=t.rateLimit.window,i=t.rateLimit.max,s=Kt(e,t.options)+o,a=zr().find(l=>l.pathMatcher(o));a&&(n=a.window,i=a.max);for(let l of t.options.plugins||[])if(l.rateLimit){let p=l.rateLimit.find(R=>R.pathMatcher(o));if(p){n=p.window,i=p.max;break}}if(t.rateLimit.customRules){let l=Object.keys(t.rateLimit.customRules).find(p=>p.includes("*")?ee(p)(o):p===o);if(l){let p=t.rateLimit.customRules[l],R=typeof p=="function"?await p(e):p;R&&(n=R.window,i=R.max)}}let d=$r(t),u=await d.get(s),m=Date.now();if(!u)await d.set(s,{key:s,count:1,lastRequest:m});else{let l=m-u.lastRequest;if(Dr(i,n,u)){let p=Br(u.lastRequest,n);return jr(p)}else l>n*1e3?await d.set(s,{...u,count:1,lastRequest:m},!0):await d.set(s,{...u,count:u.count+1,lastRequest:m},!0)}}function zr(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")||t.startsWith("/change-password")||t.startsWith("/change-email")},window:10,max:3}]}var tr=require("better-call");function er(e,t){let r=t.plugins?.reduce((c,a)=>({...c,...a.endpoints}),{}),o=t.plugins?.map(c=>c.middlewares?.map(a=>{let d=async u=>a.middleware({...u,context:{...e,...u.context}});return d.path=a.path,d.options=a.middleware.options,d.headers=a.middleware.headers,{path:a.path,middleware:d}})).filter(c=>c!==void 0).flat()||[],i={...{signInSocial:Pe,callbackOAuth:Se,getSession:ae(),signOut:Ie,signUpEmail:He(),signInEmail:_e,forgetPassword:Le,resetPassword:Ce,verifyEmail:xe,sendVerificationEmail:Te,changeEmail:qe,changePassword:Ve,setPassword:$e,updateUser:Be(),deleteUser:ze,forgetPasswordCallback:Oe,listSessions:Ue(),revokeSession:Re,revokeSessions:ve,revokeOtherSessions:Ee,linkSocialAccount:Qe,listUserAccounts:Ze,deleteUserCallback:Ne},...r,ok:Fe,error:Me},s={};for(let[c,a]of Object.entries(i))s[c]=async(d={})=>{a.headers=new Headers;let u={setHeader(w,h){a.headers.set(w,h)},setCookie(w,h,y){(0,E.setCookie)(a.headers,w,h,y)},getCookie(w,h){let k=d.headers?.get("cookie");return(0,E.getCookie)(k||"",w,h)},getSignedCookie(w,h,y){let k=d.headers;return k?(0,E.getSignedCookie)(k,h,w,y):null},async setSignedCookie(w,h,y,k){await(0,E.setSignedCookie)(a.headers,w,h,y,k)},redirect(w){return a.headers.set("Location",w),new E.APIError("FOUND")},responseHeader:a.headers},m=await e,l={...u,...d,path:a.path,context:{...m,...d.context,endpoint:a}};m.session=null;let p=t.plugins||[];for(let w of p){let h=w.hooks?.before??[];for(let y of h){if(!y.matcher(l))continue;let k=await y.handler(l);if(k&&"context"in k){l={...l,...k.context};continue}if(k)return k}}let R;try{R=await a(l)}catch(w){if(w instanceof E.APIError){let h=t.plugins?.map(y=>{if(y.hooks?.after)return y.hooks.after}).filter(y=>y!==void 0).flat();if(!h?.length)throw w.headers=a.headers,w;l.context.returned=w,l.context.returned.headers=a.headers;for(let y of h||[])if(y.matcher(l))try{let V=await y.handler(l);V&&"response"in V&&(l.context.returned=V.response)}catch(V){if(V instanceof E.APIError){l.context.returned=V;continue}throw V}if(l.context.returned instanceof E.APIError)throw l.context.returned.headers=a.headers,l.context.returned;return l.context.returned}throw w}l.context.returned=R,l.responseHeader=a.headers;for(let w of t.plugins||[])if(w.hooks?.after){for(let h of w.hooks.after)if(h.matcher(l))try{let k=await h.handler(l);k&&(l.context.returned=k)}catch(k){if(k instanceof E.APIError){l.context.returned=k;continue}throw k}}let I=l.context.returned;return I instanceof Response&&a.headers.forEach((w,h)=>{h==="set-cookie"?I.headers.append(h,w):I.headers.set(h,w)}),I},s[c].path=a.path,s[c].method=a.method,s[c].options=a.options,s[c].headers=a.headers;return{api:s,middlewares:o}}var Nr=(e,t)=>{let{api:r,middlewares:o}=er(e,t),n=new URL(e.baseURL).pathname;return(0,E.createRouter)(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:he},...o],async onRequest(i){for(let s of e.options.plugins||[])if(s.onRequest){let c=await s.onRequest(i,e);if(c&&"response"in c)return c.response}return Xt(i,e)},async onResponse(i){for(let s of e.options.plugins||[])if(s.onResponse){let c=await s.onResponse(i,e);if(c)return c.response}return i},onError(i){if(i instanceof E.APIError&&i.status==="FOUND")return;if(t.onAPIError?.throw)throw i;if(t.onAPIError?.onError){t.onAPIError.onError(i,e);return}let s=t.logger?.level,c=s==="error"||s==="warn"||s==="debug"?L:void 0;if(t.logger?.disabled!==!0){if(i&&typeof i=="object"&&"message"in i&&typeof i.message=="string"&&(i.message.includes("no column")||i.message.includes("column")||i.message.includes("relation")||i.message.includes("table")||i.message.includes("does not exist"))){e.logger?.error(i.message),e.logger?.error("If you are seeing this error, it is likely that you need to run the migrations for the database or you need to update your database schema. If you recently updated the package, make sure to run the migrations.");return}i instanceof E.APIError?(i.status==="INTERNAL_SERVER_ERROR"&&e.logger.error(i.status,i),c?.error(i.message)):e.logger?.error(i&&typeof i=="object"&&"name"in i?i.name:"",i)}}})};0&&(module.exports={APIError,callbackOAuth,changeEmail,changePassword,createAuthEndpoint,createAuthMiddleware,createEmailVerificationToken,deleteUser,deleteUserCallback,error,forgetPassword,forgetPasswordCallback,freshSessionMiddleware,getEndpoints,getSession,getSessionFromCtx,linkSocialAccount,listSessions,listUserAccounts,ok,optionsMiddleware,originCheckMiddleware,resetPassword,revokeOtherSessions,revokeSession,revokeSessions,router,sendVerificationEmail,sendVerificationEmailFn,sessionMiddleware,setPassword,signInEmail,signInSocial,signOut,signUpEmail,updateUser,verifyEmail});
|
|
83
|
+
</html>`,Ge=w("/error",{method:"GET",metadata:{...K,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string"}}}}}}}},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(jr(t),{headers:{"Content-Type":"text/html"}})});var We=w("/ok",{method:"GET",metadata:{...K,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 W=require("zod");var V=require("better-call");var Ze=()=>w("/sign-up/email",{method:"POST",query:W.z.object({currentURL:W.z.string().optional()}).optional(),body:W.z.record(W.z.string(),W.z.any()),metadata:{openapi:{description:"Sign up a user using email and password",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},email:{type:"string",description:"The email of the user"},password:{type:"string",description:"The password of the user"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["name","email","password"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"The id of the user"},email:{type:"string",description:"The email of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"},emailVerified:{type:"boolean",description:"If the email is verified"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new V.APIError("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:n,image:i,callbackURL:s,...a}=t;if(!W.z.string().email().safeParse(o).success)throw new V.APIError("BAD_REQUEST",{message:p.INVALID_EMAIL});let l=e.context.password.config.minPasswordLength;if(n.length<l)throw e.context.logger.error("Password is too short"),new V.APIError("BAD_REQUEST",{message:p.PASSWORD_TOO_SHORT});let u=e.context.password.config.maxPasswordLength;if(n.length>u)throw e.context.logger.error("Password is too long"),new V.APIError("BAD_REQUEST",{message:p.PASSWORD_TOO_LONG});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new V.APIError("UNPROCESSABLE_ENTITY",{message:p.USER_ALREADY_EXISTS});let m=fe(e.context.options,a),d;try{if(d=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...m,emailVerified:!1}),!d)throw new V.APIError("BAD_REQUEST",{message:p.FAILED_TO_CREATE_USER})}catch(v){throw e.context.logger.error("Failed to create user",v),new V.APIError("UNPROCESSABLE_ENTITY",{message:p.FAILED_TO_CREATE_USER,details:v})}if(!d)throw new V.APIError("UNPROCESSABLE_ENTITY",{message:p.FAILED_TO_CREATE_USER});let _=await e.context.password.hash(n);if(await e.context.internalAdapter.linkAccount({userId:d.id,providerId:"credential",accountId:d.id,password:_}),e.context.options.emailVerification?.sendOnSignUp){let v=await j(e.context.secret,d.email),f=`${e.context.baseURL}/verify-email?token=${v}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:d,url:f,token:v},e.request)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({id:d.id,email:d.email,name:d.name,image:d.image,emailVerified:d.emailVerified});let B=await e.context.internalAdapter.createSession(d.id,e.request);if(!B)throw new V.APIError("BAD_REQUEST",{message:p.FAILED_TO_CREATE_SESSION});return await I(e,{session:B,user:d}),e.json({id:d.id,email:d.email,name:d.name,image:d.image,emailVerified:d.emailVerified,createdAt:d.createdAt,updatedAt:d.updatedAt})});var X=require("zod");var Qe=require("better-call");var Ke=w("/list-accounts",{method:"GET",use:[x],metadata:{openapi:{description:"List all accounts linked to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},provider:{type:"string"}}}}}}}}}}},async e=>{let 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})))}),Je=w("/link-social",{method:"POST",requireHeaders:!0,query:X.z.object({currentURL:X.z.string().optional()}).optional(),body:X.z.object({callbackURL:X.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:X.z.enum(ce,{description:"The OAuth2 provider to use"})}),use:[x],metadata:{openapi:{description:"Link a social account to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}},required:["url","redirect"]}}}}}}}},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(a=>a.providerId===e.body.provider))throw new Qe.APIError("BAD_REQUEST",{message:p.SOCIAL_ACCOUNT_ALREADY_LINKED});let n=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!n)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Qe.APIError("NOT_FOUND",{message:p.PROVIDER_NOT_FOUND});let i=await ae(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})});function Xt(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let r="127.0.0.1";if(rt)return r;let n=t.advanced?.ipAddress?.ipAddressHeaders||["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],i=e instanceof Request?e.headers:e;for(let s of n){let a=i.get(s);if(typeof a=="string"){let c=a.split(",")[0].trim();if(c)return c}}return null}function Vr(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function Br(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":e.toString()}})}function $r(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function zr(e,t){let r="rateLimit",o=e.adapter;return{get:async n=>(await o.findMany({model:r,where:[{field:"key",value:n}]}))[0],set:async(n,i,s)=>{try{s?await o.updateMany({model:t??"rateLimit",where:[{field:"key",value:n}],update:{count:i.count,lastRequest:i.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:n,count:i.count,lastRequest:i.lastRequest}})}catch(a){e.logger.error("Error setting rate limit",a)}}}}var er=new Map;function qr(e){return e.options.rateLimit?.customStorage?e.options.rateLimit.customStorage:e.rateLimit.storage==="secondary-storage"?{get:async r=>{let o=await e.options.secondaryStorage?.get(r);return o?JSON.parse(o):void 0},set:async(r,o)=>{await e.options.secondaryStorage?.set?.(r,JSON.stringify(o))}}:e.rateLimit.storage==="memory"?{async get(r){return er.get(r)},async set(r,o,n){er.set(r,o)}}:zr(e,e.rateLimit.modelName)}async function tr(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,"").split("?")[0],n=t.rateLimit.window,i=t.rateLimit.max,s=Xt(e,t.options)+o,c=Fr().find(m=>m.pathMatcher(o));c&&(n=c.window,i=c.max);for(let m of t.options.plugins||[])if(m.rateLimit){let d=m.rateLimit.find(_=>_.pathMatcher(o));if(d){n=d.window,i=d.max;break}}if(t.rateLimit.customRules){let m=Object.keys(t.rateLimit.customRules).find(d=>d.includes("*")?re(d)(o):d===o);if(m){let d=t.rateLimit.customRules[m],_=typeof d=="function"?await d(e):d;_&&(n=_.window,i=_.max)}}let l=qr(t),u=await l.get(s),g=Date.now();if(!u)await l.set(s,{key:s,count:1,lastRequest:g});else{let m=g-u.lastRequest;if(Vr(i,n,u)){let d=$r(u.lastRequest,n);return Br(d)}else m>n*1e3?await l.set(s,{...u,count:1,lastRequest:g},!0):await l.set(s,{...u,count:u.count+1,lastRequest:g},!0)}}function Fr(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")||t.startsWith("/change-password")||t.startsWith("/change-email")},window:10,max:3}]}var rr=ge(require("defu"),1);var nr=require("better-call");function or(e,t){let r=t.plugins?.reduce((a,c)=>({...a,...c.endpoints}),{}),o=t.plugins?.map(a=>a.middlewares?.map(c=>{let l=async u=>c.middleware({...u,context:{...e,...u.context}});return l.path=c.path,l.options=c.middleware.options,l.headers=c.middleware.headers,{path:c.path,middleware:l}})).filter(a=>a!==void 0).flat()||[],i={...{signInSocial:xe,callbackOAuth:Pe,getSession:de(),signOut:De,signUpEmail:Ze(),signInEmail:Le,forgetPassword:Ce,resetPassword:je,verifyEmail:Ie,sendVerificationEmail:ve,changeEmail:He,changePassword:ze,setPassword:qe,updateUser:$e(),deleteUser:Fe,forgetPasswordCallback:Ne,listSessions:_e(),revokeSession:Te,revokeSessions:Se,revokeOtherSessions:Oe,linkSocialAccount:Je,listUserAccounts:Ke,deleteUserCallback:Me},...r,ok:We,error:Ge},s={};for(let[a,c]of Object.entries(i))s[a]=async(l={})=>{c.headers=new Headers;let u={setHeader(f,y){c.headers.set(f,y)},setCookie(f,y,R){(0,T.setCookie)(c.headers,f,y,R)},getCookie(f,y){let k=l.headers?.get("cookie");return(0,T.getCookie)(k||"",f,y)},getSignedCookie(f,y,R){let k=l.headers;return k?(0,T.getSignedCookie)(k,y,f,R):null},async setSignedCookie(f,y,R,k){await(0,T.setSignedCookie)(c.headers,f,y,R,k)},redirect(f){return c.headers.set("Location",f),new T.APIError("FOUND")},responseHeader:c.headers},g=await e,m=null,d={...u,...l,path:c.path,context:{...g,...l.context,session:null,setNewSession:function(f){m=f}}},_=t.plugins||[];for(let f of _){let y=f.hooks?.before??[];for(let R of y){if(!R.matcher(d))continue;let k=await R.handler(d);if(k&&"context"in k){d=(0,rr.default)(d,k.context);continue}if(k)return k}}let B;try{B=await c(d),m&&(d.context.newSession=m)}catch(f){if(f instanceof T.APIError){let y=t.plugins?.map(R=>{if(R.hooks?.after)return R.hooks.after}).filter(R=>R!==void 0).flat();if(!y?.length)throw f.headers=c.headers,f;d.context.returned=f,d.context.returned.headers=c.headers;for(let R of y||[])if(R.matcher(d))try{let $=await R.handler(d);$&&"response"in $&&(d.context.returned=$.response)}catch($){if($ instanceof T.APIError){d.context.returned=$;continue}throw $}if(d.context.returned instanceof T.APIError)throw d.context.returned.headers=c.headers,d.context.returned;return d.context.returned}throw f}d.context.returned=B,d.responseHeader=c.headers;for(let f of t.plugins||[])if(f.hooks?.after){for(let y of f.hooks.after)if(y.matcher(d))try{let k=await y.handler(d);k&&(d.context.returned=k)}catch(k){if(k instanceof T.APIError){d.context.returned=k;continue}throw k}}let v=d.context.returned;return v instanceof Response&&c.headers.forEach((f,y)=>{y==="set-cookie"?v.headers.append(y,f):v.headers.set(y,f)}),v},s[a].path=c.path,s[a].method=c.method,s[a].options=c.options,s[a].headers=c.headers;return{api:s,middlewares:o}}var Mr=(e,t)=>{let{api:r,middlewares:o}=or(e,t),n=new URL(e.baseURL).pathname;return(0,T.createRouter)(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:be},...o],async onRequest(i){for(let s of e.options.plugins||[])if(s.onRequest){let a=await s.onRequest(i,e);if(a&&"response"in a)return a.response}return tr(i,e)},async onResponse(i){for(let s of e.options.plugins||[])if(s.onResponse){let a=await s.onResponse(i,e);if(a)return a.response}return i},onError(i){if(i instanceof T.APIError&&i.status==="FOUND")return;if(t.onAPIError?.throw)throw i;if(t.onAPIError?.onError){t.onAPIError.onError(i,e);return}let s=t.logger?.level,a=s==="error"||s==="warn"||s==="debug"?P:void 0;if(t.logger?.disabled!==!0){if(i&&typeof i=="object"&&"message"in i&&typeof i.message=="string"&&(i.message.includes("no column")||i.message.includes("column")||i.message.includes("relation")||i.message.includes("table")||i.message.includes("does not exist"))){e.logger?.error(i.message),e.logger?.error("If you are seeing this error, it is likely that you need to run the migrations for the database or you need to update your database schema. If you recently updated the package, make sure to run the migrations.");return}i instanceof T.APIError?(i.status==="INTERNAL_SERVER_ERROR"&&e.logger.error(i.status,i),a?.error(i.message)):e.logger?.error(i&&typeof i=="object"&&"name"in i?i.name:"",i)}}})};0&&(module.exports={APIError,callbackOAuth,changeEmail,changePassword,createAuthEndpoint,createAuthMiddleware,createEmailVerificationToken,deleteUser,deleteUserCallback,error,forgetPassword,forgetPasswordCallback,freshSessionMiddleware,getEndpoints,getSession,getSessionFromCtx,linkSocialAccount,listSessions,listUserAccounts,ok,optionsMiddleware,originCheckMiddleware,resetPassword,revokeOtherSessions,revokeSession,revokeSessions,router,sendVerificationEmail,sendVerificationEmailFn,sessionMiddleware,setPassword,signInEmail,signInSocial,signOut,signUpEmail,updateUser,verifyEmail});
|
package/dist/api.d.cts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export {
|
|
2
|
-
import './helper-
|
|
1
|
+
export { a7 as AuthEndpoint, a8 as AuthMiddleware, ad as callbackOAuth, az as changeEmail, av as changePassword, a6 as createAuthEndpoint, a5 as createAuthMiddleware, aq as createEmailVerificationToken, ax as deleteUser, ay as deleteUserCallback, aA as error, an as forgetPassword, ao as forgetPasswordCallback, ah as freshSessionMiddleware, a9 as getEndpoints, ae as getSession, af as getSessionFromCtx, aE as linkSocialAccount, ai as listSessions, aD as listUserAccounts, aB as ok, a4 as optionsMiddleware, aF as originCheckMiddleware, ap as resetPassword, al as revokeOtherSessions, aj as revokeSession, ak as revokeSessions, aa as router, as as sendVerificationEmail, ar as sendVerificationEmailFn, ag as sessionMiddleware, aw as setPassword, ac as signInEmail, ab as signInSocial, am as signOut, aC as signUpEmail, au as updateUser, at as verifyEmail } from './auth-BXGk5qca.cjs';
|
|
2
|
+
import './helper-CbDsvI53.cjs';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import 'kysely';
|
|
6
|
-
import './index-
|
|
6
|
+
import './index-DPqpIwKX.cjs';
|
|
7
7
|
import 'jose';
|
|
8
8
|
import 'better-sqlite3';
|
package/dist/api.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export {
|
|
2
|
-
import './helper-
|
|
1
|
+
export { a7 as AuthEndpoint, a8 as AuthMiddleware, ad as callbackOAuth, az as changeEmail, av as changePassword, a6 as createAuthEndpoint, a5 as createAuthMiddleware, aq as createEmailVerificationToken, ax as deleteUser, ay as deleteUserCallback, aA as error, an as forgetPassword, ao as forgetPasswordCallback, ah as freshSessionMiddleware, a9 as getEndpoints, ae as getSession, af as getSessionFromCtx, aE as linkSocialAccount, ai as listSessions, aD as listUserAccounts, aB as ok, a4 as optionsMiddleware, aF as originCheckMiddleware, ap as resetPassword, al as revokeOtherSessions, aj as revokeSession, ak as revokeSessions, aa as router, as as sendVerificationEmail, ar as sendVerificationEmailFn, ag as sessionMiddleware, aw as setPassword, ac as signInEmail, ab as signInSocial, am as signOut, aC as signUpEmail, au as updateUser, at as verifyEmail } from './auth-CkPAOFDT.js';
|
|
2
|
+
import './helper-CbDsvI53.js';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import 'kysely';
|
|
6
|
-
import './index-
|
|
6
|
+
import './index-DF4xhhKM.js';
|
|
7
7
|
import 'jose';
|
|
8
8
|
import 'better-sqlite3';
|