better-auth 0.5.4-beta.4 → 0.5.4-beta.6
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/access.d.cts +4 -0
- package/dist/adapters/drizzle.d.cts +36 -0
- package/dist/adapters/kysely.d.cts +43 -0
- package/dist/adapters/mongodb.d.cts +63 -0
- package/dist/adapters/prisma.d.cts +25 -0
- package/dist/api.cjs +4 -4
- package/dist/api.cjs.map +1 -1
- package/dist/api.d.cts +10 -0
- package/dist/api.js +4 -4
- package/dist/api.js.map +1 -1
- package/dist/auth-Bi4S5duG.d.cts +6387 -0
- package/dist/client/plugins.d.cts +280 -0
- package/dist/client.d.cts +276 -0
- package/dist/client.d.ts +36 -3
- package/dist/cookies.d.cts +10 -0
- package/dist/crypto.d.cts +30 -0
- package/dist/db.d.cts +54 -0
- package/dist/helper-DPDj8Nix.d.cts +21 -0
- package/dist/hide-metadata-DEHJp1rk.d.cts +5 -0
- package/dist/index-7DC3O4KM.d.cts +6298 -0
- package/dist/index-BkNFhk9A.d.cts +24 -0
- package/dist/index.cjs +4 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +28 -0
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/next-js.d.cts +35 -0
- package/dist/node.d.cts +17 -0
- package/dist/oauth2.cjs +1 -1
- package/dist/oauth2.cjs.map +1 -1
- package/dist/oauth2.d.cts +31 -0
- package/dist/oauth2.d.ts +1 -7
- package/dist/oauth2.js +1 -1
- package/dist/oauth2.js.map +1 -1
- package/dist/plugins.cjs +5 -5
- package/dist/plugins.cjs.map +1 -1
- package/dist/plugins.d.cts +182 -0
- package/dist/plugins.js +5 -5
- package/dist/plugins.js.map +1 -1
- package/dist/react.d.cts +296 -0
- package/dist/react.d.ts +36 -3
- package/dist/schema-Dkt0LqYs.d.cts +105 -0
- package/dist/social.cjs +2 -2
- package/dist/social.cjs.map +1 -1
- package/dist/social.d.cts +959 -0
- package/dist/social.d.ts +1 -0
- package/dist/social.js +2 -2
- package/dist/social.js.map +1 -1
- package/dist/solid-start.d.cts +21 -0
- package/dist/solid.d.cts +277 -0
- package/dist/solid.d.ts +36 -3
- package/dist/state-BUSdcdLW.d.cts +17 -0
- package/dist/statement-Da_cxgTI.d.cts +81 -0
- package/dist/svelte-kit.d.cts +25 -0
- package/dist/svelte.d.cts +276 -0
- package/dist/svelte.d.ts +36 -3
- package/dist/types-BVIhbXRu.d.cts +55 -0
- package/dist/types.d.cts +138 -0
- package/dist/vue.d.cts +327 -0
- package/dist/vue.d.ts +36 -3
- package/package.json +1 -1
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { A as AccessControl, a as AuthortizeResponse, P as ParsingError, R as Role, S as StatementsPrimitive, b as SubArray, c as Subset, d as adminAc, e as createAccessControl, f as defaultAc, g as defaultRoles, h as defaultStatements, m as memberAc, o as ownerAc } from './statement-Da_cxgTI.cjs';
|
|
2
|
+
export { p as permissionFromString } from './index-BkNFhk9A.cjs';
|
|
3
|
+
import './helper-DPDj8Nix.cjs';
|
|
4
|
+
import 'zod';
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { A as Adapter } from '../auth-Bi4S5duG.cjs';
|
|
2
|
+
import 'zod';
|
|
3
|
+
import 'kysely';
|
|
4
|
+
import '../schema-Dkt0LqYs.cjs';
|
|
5
|
+
import 'better-call';
|
|
6
|
+
import '../types-BVIhbXRu.cjs';
|
|
7
|
+
import '../helper-DPDj8Nix.cjs';
|
|
8
|
+
import '../social.cjs';
|
|
9
|
+
import 'better-sqlite3';
|
|
10
|
+
import 'mysql2';
|
|
11
|
+
|
|
12
|
+
interface DrizzleAdapterOptions {
|
|
13
|
+
schema?: Record<string, any>;
|
|
14
|
+
provider: "pg" | "mysql" | "sqlite";
|
|
15
|
+
/**
|
|
16
|
+
* If the table names in the schema are plural
|
|
17
|
+
* set this to true. For example, if the schema
|
|
18
|
+
* has an object with a key "users" instead of "user"
|
|
19
|
+
*/
|
|
20
|
+
usePlural?: boolean;
|
|
21
|
+
/**
|
|
22
|
+
* Custom generateId function.
|
|
23
|
+
*
|
|
24
|
+
* If not provided, nanoid will be used.
|
|
25
|
+
* If set to false, the database's auto generated id will be used.
|
|
26
|
+
*
|
|
27
|
+
* @default nanoid
|
|
28
|
+
*/
|
|
29
|
+
generateId?: ((size?: number) => string) | false;
|
|
30
|
+
}
|
|
31
|
+
interface DB {
|
|
32
|
+
[key: string]: any;
|
|
33
|
+
}
|
|
34
|
+
declare const drizzleAdapter: (db: DB, options: DrizzleAdapterOptions) => Adapter;
|
|
35
|
+
|
|
36
|
+
export { type DrizzleAdapterOptions, drizzleAdapter };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { Kysely } from 'kysely';
|
|
2
|
+
import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-Bi4S5duG.cjs';
|
|
3
|
+
import 'zod';
|
|
4
|
+
import '../schema-Dkt0LqYs.cjs';
|
|
5
|
+
import 'better-call';
|
|
6
|
+
import '../types-BVIhbXRu.cjs';
|
|
7
|
+
import '../helper-DPDj8Nix.cjs';
|
|
8
|
+
import '../social.cjs';
|
|
9
|
+
import 'better-sqlite3';
|
|
10
|
+
import 'mysql2';
|
|
11
|
+
|
|
12
|
+
declare const createKyselyAdapter: (config: BetterAuthOptions) => Promise<{
|
|
13
|
+
kysely: Kysely<any>;
|
|
14
|
+
databaseType: KyselyDatabaseType;
|
|
15
|
+
} | {
|
|
16
|
+
kysely: Kysely<unknown> | null;
|
|
17
|
+
databaseType: KyselyDatabaseType | null;
|
|
18
|
+
}>;
|
|
19
|
+
|
|
20
|
+
interface KyselyAdapterConfig {
|
|
21
|
+
/**
|
|
22
|
+
* Transform dates and booleans for sqlite.
|
|
23
|
+
*/
|
|
24
|
+
transform?: {
|
|
25
|
+
schema: {
|
|
26
|
+
[table: string]: Record<string, FieldAttribute>;
|
|
27
|
+
};
|
|
28
|
+
boolean: boolean;
|
|
29
|
+
date: boolean;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Custom generateId function.
|
|
33
|
+
*
|
|
34
|
+
* If not provided, nanoid will be used.
|
|
35
|
+
* If set to false, the database's auto generated id will be used.
|
|
36
|
+
*
|
|
37
|
+
* @default nanoid
|
|
38
|
+
*/
|
|
39
|
+
generateId?: ((size?: number) => string) | false;
|
|
40
|
+
}
|
|
41
|
+
declare const kyselyAdapter: (db: Kysely<any>, config?: KyselyAdapterConfig) => Adapter;
|
|
42
|
+
|
|
43
|
+
export { type KyselyAdapterConfig, KyselyDatabaseType, createKyselyAdapter, kyselyAdapter };
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { Db } from 'mongodb';
|
|
2
|
+
import { W as Where } from '../auth-Bi4S5duG.cjs';
|
|
3
|
+
import 'zod';
|
|
4
|
+
import 'kysely';
|
|
5
|
+
import '../schema-Dkt0LqYs.cjs';
|
|
6
|
+
import 'better-call';
|
|
7
|
+
import '../types-BVIhbXRu.cjs';
|
|
8
|
+
import '../helper-DPDj8Nix.cjs';
|
|
9
|
+
import '../social.cjs';
|
|
10
|
+
import 'better-sqlite3';
|
|
11
|
+
import 'mysql2';
|
|
12
|
+
|
|
13
|
+
declare const mongodbAdapter: (mongo: Db, opts?: {
|
|
14
|
+
usePlural?: boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Custom generateId function.
|
|
17
|
+
*
|
|
18
|
+
* If not provided, nanoid will be used.
|
|
19
|
+
* If set to false, the database's auto generated id will be used.
|
|
20
|
+
*
|
|
21
|
+
* @default nanoid
|
|
22
|
+
*/
|
|
23
|
+
generateId?: ((size?: number) => string) | false;
|
|
24
|
+
}) => {
|
|
25
|
+
id: string;
|
|
26
|
+
create<T extends {
|
|
27
|
+
id?: string;
|
|
28
|
+
} & Record<string, any>, R = T>(data: {
|
|
29
|
+
model: string;
|
|
30
|
+
data: T;
|
|
31
|
+
select?: string[];
|
|
32
|
+
}): Promise<any>;
|
|
33
|
+
findOne<T>(data: {
|
|
34
|
+
model: string;
|
|
35
|
+
where: Where[];
|
|
36
|
+
select?: string[];
|
|
37
|
+
}): Promise<any>;
|
|
38
|
+
findMany<T>(data: {
|
|
39
|
+
model: string;
|
|
40
|
+
where?: Where[];
|
|
41
|
+
limit?: number;
|
|
42
|
+
sortBy?: {
|
|
43
|
+
field: string;
|
|
44
|
+
direction: "asc" | "desc";
|
|
45
|
+
};
|
|
46
|
+
offset?: number;
|
|
47
|
+
}): Promise<any[]>;
|
|
48
|
+
update<T>(data: {
|
|
49
|
+
model: string;
|
|
50
|
+
where: Where[];
|
|
51
|
+
update: Record<string, any>;
|
|
52
|
+
}): Promise<any>;
|
|
53
|
+
delete<T>(data: {
|
|
54
|
+
model: string;
|
|
55
|
+
where: Where[];
|
|
56
|
+
}): Promise<void>;
|
|
57
|
+
deleteMany(data: {
|
|
58
|
+
model: string;
|
|
59
|
+
where: Where[];
|
|
60
|
+
}): Promise<void>;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
export { mongodbAdapter };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { A as Adapter } from '../auth-Bi4S5duG.cjs';
|
|
2
|
+
import 'zod';
|
|
3
|
+
import 'kysely';
|
|
4
|
+
import '../schema-Dkt0LqYs.cjs';
|
|
5
|
+
import 'better-call';
|
|
6
|
+
import '../types-BVIhbXRu.cjs';
|
|
7
|
+
import '../helper-DPDj8Nix.cjs';
|
|
8
|
+
import '../social.cjs';
|
|
9
|
+
import 'better-sqlite3';
|
|
10
|
+
import 'mysql2';
|
|
11
|
+
|
|
12
|
+
declare const prismaAdapter: (prisma: any, options: {
|
|
13
|
+
provider: "sqlite" | "cockroachdb" | "mysql" | "postgresql" | "sqlserver" | "mongodb";
|
|
14
|
+
/**
|
|
15
|
+
* Custom generateId function.
|
|
16
|
+
*
|
|
17
|
+
* If not provided, nanoid will be used.
|
|
18
|
+
* If set to false, the database's auto generated id will be used.
|
|
19
|
+
*
|
|
20
|
+
* @default nanoid
|
|
21
|
+
*/
|
|
22
|
+
generateId?: ((size?: number) => string) | false;
|
|
23
|
+
}) => Adapter;
|
|
24
|
+
|
|
25
|
+
export { prismaAdapter };
|
package/dist/api.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}}),w=er();var E=z(async e=>{let{body:t,query:r,headers:o,context:n}=e,i=t?.callbackURL||r?.callbackURL||r?.redirectTo||t?.redirectTo,s=r?.currentURL||o?.get("referer")||n.baseURL,a=n.trustedOrigins,c=(d,l)=>{if(d?.startsWith("http")&&!a.some(g=>d.startsWith(g)))throw w.error(`Invalid ${l}`,{[l]:d,trustedOrigins:a}),new Qe.APIError("FORBIDDEN",{message:`Invalid ${l}`})};c(i,"callbackURL"),c(s,"currentURL")});var Xe=require("oslo/jwt");var Ge=require("oslo/crypto"),We=require("oslo/encoding");async function Je(e){let t=await(0,Ge.sha256)(new TextEncoder().encode(e));return We.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Ke(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_at?new Date((Date.now()+e.expires_in)*1e3):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function b({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,disablePkce:a,redirectURI:c}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",i.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),!a&&n){let l=await Je(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((h,g)=>(h[g]=null,h),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return d}var Ye=require("@better-fetch/fetch");async function y({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:s,error:a}=await(0,Ye.betterFetch)(n,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(a)throw a;return Ke(s)}function Y(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var et=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=e.scope||o||["email","name","openid"];return 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}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>y({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=(0,Xe.parseJWT)(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};var tt=require("@better-fetch/fetch");var rt=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,tt.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var ot=require("@better-fetch/fetch");var nt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["email","public_profile"];return await b({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})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await(0,ot.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});var pe=require("@better-fetch/fetch");var it=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let s=e.scope||o||["user:email"];return b({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,pe.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:a}=await(0,pe.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(c=>c.primary)??s[0])?.email,i=s.find(c=>c.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};var st=require("oslo/jwt");var at=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw w.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new N("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new N("codeVerifier is required for Google");let i=e.scope||r||["email","profile"];return b({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=(0,st.parseJWT)(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});var dt=require("@better-fetch/fetch"),ct=require("oslo/jwt");var lt=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=e.scope||n.scopes||["openid","profile","email","User.Read"];return b({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 y({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=(0,ct.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,dt.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 d=await a.response.clone().arrayBuffer(),l=Buffer.from(d).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(c){w.error(c)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};var ut=require("@better-fetch/fetch");var pt=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=e.scope||r||["user-read-email"];return b({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})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,ut.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});var vo=require("@better-fetch/fetch");var C={isAction:!1};var mt=require("nanoid"),ft=e=>(0,mt.nanoid)(e);var gt=require("oslo/jwt");var ht=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return b({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})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return w.error("No idToken found in token"),null;let o=(0,gt.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var wt=require("@better-fetch/fetch");var yt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return b({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,wt.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var bt=require("@better-fetch/fetch");var At=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=e.scope||o||["account_info.read"];return await b({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 y({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,bt.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};var kt=require("@better-fetch/fetch");var Rt=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=e.scope||n||["profile","email","openid"];return await b({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await y({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await(0,kt.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};var tr={apple:et,discord:rt,facebook:nt,github:it,microsoft:lt,google:at,spotify:pt,twitch:ht,twitter:yt,dropbox:At,linkedin:Rt},Ut=Object.keys(tr);var Et=require("oslo"),re=require("oslo/jwt"),T=require("zod");var V=require("better-call");var M=require("better-call");var X=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var me=require("zod"),ee=()=>m("/get-session",{method:"GET",requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return Z(e),r&&await e.context.internalAdapter.deleteSession(r.session.id),e.json(null,{status:401});if(await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(r);let n=e.context.sessionConfig.expiresIn,i=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+i*1e3<=Date.now()){let c=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:X(e.context.sessionConfig.expiresIn,"sec")});if(!c)return Z(e),e.json(null,{status:401});let d=(c.expiresAt.valueOf()-Date.now())/1e3;return await S(e,c.id,!1,{maxAge:d}),e.json({session:c,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),te=async e=>await ee()({...e,_flag:"json",headers:e.headers}),O=z(async e=>{let t=await te(e);if(!t?.session)throw new M.APIError("UNAUTHORIZED");return{session:t}}),fe=()=>m("/user/list-sessions",{method:"GET",use:[O],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),ge=m("/user/revoke-session",{method:"POST",body:me.z.object({id:me.z.string()}),use:[O],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new M.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new M.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new M.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),he=m("/user/revoke-sessions",{method:"POST",use:[O],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new M.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function L(e,t,r){return await(0,re.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Et.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var we=m("/send-verification-email",{method:"POST",query:T.z.object({currentURL:T.z.string().optional()}).optional(),body:T.z.object({email:T.z.string().email(),callbackURL:T.z.string().optional()}),use:[E]},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new V.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 V.APIError("BAD_REQUEST",{message:"User not found"});let o=await L(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,n,o),e.json({status:!0})}),ye=m("/verify-email",{method:"GET",query:T.z.object({token:T.z.string(),callbackURL:T.z.string().optional()}),use:[E]},async e=>{let{token:t}=e.query,r;try{r=await(0,re.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new V.APIError("BAD_REQUEST",{message:"Invalid token"})}let n=T.z.object({email:T.z.string().email(),updateTo:T.z.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new V.APIError("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await te(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new V.APIError("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new V.APIError("UNAUTHORIZED",{message:"Invalid session"});let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(a,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var be=m("/sign-in/social",{method:"POST",requireHeaders:!0,query:v.z.object({currentURL:v.z.string().optional()}).optional(),body:v.z.object({callbackURL:v.z.string().optional(),provider:v.z.enum(Ut)}),use:[E]},async e=>{let t=e.context.socialProviders.find(c=>c.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new P.APIError("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,n=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,i=await Fe(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,i.hash,e.context.secret,r.state.options);let s=(0,xt.generateCodeVerifier)();await e.setSignedCookie(r.pkCodeVerifier.name,s,e.context.secret,r.pkCodeVerifier.options);let a=await t.createAuthorizationURL({state:i.raw,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:a.toString(),state:i,codeVerifier:s,redirect:!0})}),Ae=m("/sign-in/email",{method:"POST",body:v.z.object({email:v.z.string(),password:v.z.string(),callbackURL:v.z.string().optional(),dontRememberMe:v.z.boolean().default(!1).optional()}),use:[E]},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new P.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!v.z.string().email().safeParse(t).success)throw new P.APIError("BAD_REQUEST",{message:"Invalid email"});if(!v.z.string().email().safeParse(t).success)throw new P.APIError("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=i.accounts.find(l=>l.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let a=s?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new P.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw w.error("Email verification is required but no email verification handler is provided"),new P.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let l=await L(e.context.secret,i.user.email),h=`${e.context.options.baseURL}/verify-email?token=${l}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,h,l),e.context.logger.error("Email not verified",{email:t}),new P.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new P.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await S(e,d.id,e.body.dontRememberMe),e.json({user:i.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Q=require("zod");var f=require("zod"),En=f.z.object({id:f.z.string(),providerId:f.z.string(),accountId:f.z.string(),userId:f.z.string(),accessToken:f.z.string().nullable().optional(),refreshToken:f.z.string().nullable().optional(),idToken:f.z.string().nullable().optional(),expiresAt:f.z.date().nullable().optional(),password:f.z.string().optional().nullable()}),vt=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().optional(),createdAt:f.z.date().default(new Date),updatedAt:f.z.date().default(new Date)}),xn=f.z.object({id:f.z.string(),userId:f.z.string(),expiresAt:f.z.date(),ipAddress:f.z.string().optional(),userAgent:f.z.string().optional()}),vn=f.z.object({id:f.z.string(),value:f.z.string(),expiresAt:f.z.date(),identifier:f.z.string()});function Tt(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 Pt(e,t){let r=t.fields,o={};for(let n in r){if(n in e){if(r[n].input===!1){if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}continue}o[n]=e[n];continue}if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}}return o}function _t(e,t){let r=Tt(e,"user");return Pt(t||{},{fields:r})}function St(e,t){let r=Tt(e,"user");return Pt(t||{},{fields:r})}var ke=m("/callback/:id",{method:"GET",query:Q.z.object({state:Q.z.string(),code:Q.z.string().optional(),error:Q.z.string().optional()}),metadata:C},async e=>{if(e.query.error||!e.query.code){let U=ue(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${U}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(u=>u.id===e.params.id);if(!t)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 r=ue(e.query.state);if(!r.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:n}}=r,i=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!i)throw w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await Ne(e.query.state,i))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let a=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),c;try{c=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(u){throw e.context.logger.error(u),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let d=await t.getUserInfo(c).then(u=>u?.user),l=ft(),h=vt.safeParse({...d,id:l});if(!d||h.success===!1)throw w.error("Unable to get user info",h.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);function g(u){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${u}`)}let p=await e.context.internalAdapter.findUserByEmail(d.email,{includeAccounts:!0}).catch(u=>{throw w.error(`Better auth was unable to query your database.
|
|
3
|
-
Error: `,u),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),
|
|
1
|
+
"use strict";var zt=Object.create;var J=Object.defineProperty;var $t=Object.getOwnPropertyDescriptor;var Vt=Object.getOwnPropertyNames;var jt=Object.getPrototypeOf,qt=Object.prototype.hasOwnProperty;var Nt=(e,t)=>{for(var r in t)J(e,r,{get:t[r],enumerable:!0})},Ce=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Vt(t))!qt.call(e,n)&&n!==r&&J(e,n,{get:()=>t[n],enumerable:!(o=$t(t,n))||o.enumerable});return e};var Be=(e,t,r)=>(r=e!=null?zt(jt(e)):{},Ce(t||!e||!e.__esModule?J(r,"default",{value:e,enumerable:!0}):r,e)),Mt=e=>Ce(J({},"__esModule",{value:!0}),e);var cr={};Nt(cr,{APIError:()=>Dt.APIError,callbackOAuth:()=>ke,changeEmail:()=>_e,changePassword:()=>Te,createAuthEndpoint:()=>m,createAuthMiddleware:()=>z,createEmailVerificationToken:()=>L,csrfMiddleware:()=>de,deleteUser:()=>Pe,error:()=>Oe,forgetPassword:()=>Re,forgetPasswordCallback:()=>Ue,getCSRFToken:()=>Se,getEndpoints:()=>Bt,getSession:()=>X,getSessionFromCtx:()=>ee,listSessions:()=>me,ok:()=>Le,optionsMiddleware:()=>se,resetPassword:()=>Ee,revokeSession:()=>fe,revokeSessions:()=>ge,router:()=>dr,sendVerificationEmail:()=>he,sessionMiddleware:()=>O,setPassword:()=>ve,signInEmail:()=>be,signInOAuth:()=>ye,signOut:()=>Ae,signUpEmail:()=>Ie,updateUser:()=>xe,verifyEmail:()=>we});module.exports=Mt(cr);var q=require("better-call");var Y=require("better-call"),ae=require("zod");var Wt=require("@noble/ciphers/chacha"),ie=require("@noble/ciphers/utils"),Jt=require("@noble/ciphers/webcrypto"),Kt=require("oslo/crypto"),ne=Be(require("uncrypto"),1);function re(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let n=0;for(let i=0;i<r.length;i++)n|=r[i]^o[i];return n===0}var De=require("oslo/encoding");var Ft=require("@noble/hashes/scrypt"),Ht=require("uncrypto");var oe=Be(require("uncrypto"),1);function Zt(e){return e.toString(2).padStart(8,"0")}function Qt(e){return[...e].map(t=>Zt(t)).join("")}function ze(e){return parseInt(Qt(e),2)}function Gt(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));oe.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=ze(o);for(;n>=e;)oe.default.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=ze(o);return n}function $e(e,t){let r="";for(let o=0;o<e;o++)r+=t[Gt(t.length)];return r}function Ve(...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}async function K(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},n=await ne.default.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),i=await ne.default.subtle.sign(o.name,n,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(i)))}var D=require("better-call"),se=(0,D.createMiddleware)(async()=>({})),z=(0,D.createMiddlewareCreator)({use:[se,(0,D.createMiddleware)(async()=>({}))]}),m=(0,D.createEndpointCreator)({use:[se]});var de=z({body:ae.z.object({csrfToken:ae.z.string().optional()}).optional()},async e=>{if(e.request?.method!=="POST"||e.context.options.advanced?.disableCSRFCheck)return;let t=e.headers?.get("origin")||"";if(t){let d=new URL(t).origin;if(e.context.trustedOrigins.includes(d))return}let r=e.body?.csrfToken;if(!r)throw new Y.APIError("UNAUTHORIZED",{message:"CSRF Token is required"});let o=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[n,i]=o?.split("!")||[null,null];if(!r||!n||!i||n!==r)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new Y.APIError("UNAUTHORIZED",{message:"Invalid CSRF Token"});let s=await K(e.context.secret,n);if(i!==s)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new Y.APIError("UNAUTHORIZED",{message:"Invalid CSRF Token"})});var P=require("better-call"),Et=require("oslo/oauth2"),T=require("zod");var Ne=require("oslo/oauth2"),Z=require("zod");var ce=require("oslo/crypto");async function je(e){let t=await(0,ce.sha256)(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function qe(e,t){let r=await(0,ce.sha256)(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return re(r,o)}var Pr=require("better-call");async function Me(e){let t=(0,Ne.generateState)(),r=JSON.stringify({code:t,callbackURL:e}),o=await je(r);return{raw:r,hash:o}}function le(e){return Z.z.object({code:Z.z.string(),callbackURL:Z.z.string().optional(),currentURL:Z.z.string().optional()}).safeParse(JSON.parse(e))}var Yt=require("oslo");var N=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}};var Fe=require("std-env");async function S(e,t,r,o){let n=e.context.authCookies.sessionToken.options;n.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options)}function Q(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}var Ze=require("better-call");var He=require("consola"),$=(0,He.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Xt=e=>({log:(...t)=>{!e?.disabled&&$.log("",...t)},error:(...t)=>{!e?.disabled&&$.error("",...t)},warn:(...t)=>{!e?.disabled&&$.warn("",...t)},info:(...t)=>{!e?.disabled&&$.info("",...t)},debug:(...t)=>{!e?.disabled&&$.debug("",...t)},box:(...t)=>{!e?.disabled&&$.box("",...t)},success:(...t)=>{!e?.disabled&&$.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
|
+
`)}}),w=Xt();var E=z(async e=>{let{body:t,query:r,headers:o,context:n}=e,i=t?.callbackURL||r?.callbackURL||r?.redirectTo||t?.redirectTo,s=r?.currentURL||o?.get("referer")||n.baseURL,d=n.trustedOrigins,a=(c,l)=>{if(c?.startsWith("http")&&!d.some(g=>c.startsWith(g)))throw w.error(`Invalid ${l}`,{[l]:c,trustedOrigins:d}),new Ze.APIError("FORBIDDEN",{message:`Invalid ${l}`})};a(i,"callbackURL"),a(s,"currentURL")});var Ye=require("oslo/jwt");var Qe=require("oslo/crypto"),Ge=require("oslo/encoding");var M=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function We(e){let t=await(0,Qe.sha256)(new TextEncoder().encode(e));return Ge.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Je(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?M(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function b({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,disablePkce:d,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),!d&&n){let l=await We(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((h,g)=>(h[g]=null,h),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return c}var Ke=require("@better-fetch/fetch");async function y({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:s,error:d}=await(0,Ke.betterFetch)(n,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(d)throw d;return Je(s)}var Xe=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","openid"];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}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>y({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=(0,Ye.parseJWT)(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};var et=require("@better-fetch/fetch");var tt=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,et.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var rt=require("@better-fetch/fetch");var ot=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 b({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})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await(0,rt.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});var ue=require("@better-fetch/fetch");var nt=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),b({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,ue.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:d}=await(0,ue.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});d||(o.email=(s.find(a=>a.primary)??s[0])?.email,i=s.find(a=>a.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};var it=require("oslo/jwt");var st=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw w.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new N("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new N("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await b({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),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=(0,it.parseJWT)(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});var at=require("@better-fetch/fetch"),dt=require("oslo/jwt");var ct=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),b({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 y({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=(0,dt.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,at.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(d){if(!(e.disableProfilePhoto||!d.response.ok))try{let c=await d.response.clone().arrayBuffer(),l=Buffer.from(c).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(a){w.error(a)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};var lt=require("@better-fetch/fetch");var ut=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),b({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})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,lt.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});var xo=require("@better-fetch/fetch");var C={isAction:!1};var pt=require("nanoid"),mt=e=>(0,pt.nanoid)(e);var ft=require("oslo/jwt");var gt=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),b({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})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return w.error("No idToken found in token"),null;let o=(0,ft.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var ht=require("@better-fetch/fetch");var wt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["account_info.read"];return e.scope&&r.push(...e.scope),b({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,ht.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var yt=require("@better-fetch/fetch");var bt=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 b({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 y({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,yt.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};var kt=require("@better-fetch/fetch");var At=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 b({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await y({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await(0,kt.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};var er={apple:Xe,discord:tt,facebook:ot,github:nt,microsoft:ct,google:st,spotify:ut,twitch:gt,twitter:wt,dropbox:bt,linkedin:At},Rt=Object.keys(er);var Ut=require("oslo"),te=require("oslo/jwt"),v=require("zod");var V=require("better-call");var F=require("better-call");var pe=require("zod"),X=()=>m("/get-session",{method:"GET",requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return Q(e),r&&await e.context.internalAdapter.deleteSession(r.session.id),e.json(null,{status:401});if(await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(r);let n=e.context.sessionConfig.expiresIn,i=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+i*1e3<=Date.now()){let a=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:M(e.context.sessionConfig.expiresIn,"sec")});if(!a)return Q(e),e.json(null,{status:401});let c=(a.expiresAt.valueOf()-Date.now())/1e3;return await S(e,a.id,!1,{maxAge:c}),e.json({session:a,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),ee=async e=>await X()({...e,_flag:"json",headers:e.headers}),O=z(async e=>{let t=await ee(e);if(!t?.session)throw new F.APIError("UNAUTHORIZED");return{session:t}}),me=()=>m("/user/list-sessions",{method:"GET",use:[O],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),fe=m("/user/revoke-session",{method:"POST",body:pe.z.object({id:pe.z.string()}),use:[O],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new F.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new F.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new F.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ge=m("/user/revoke-sessions",{method:"POST",use:[O],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new F.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function L(e,t,r){return await(0,te.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Ut.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var he=m("/send-verification-email",{method:"POST",query:v.z.object({currentURL:v.z.string().optional()}).optional(),body:v.z.object({email:v.z.string().email(),callbackURL:v.z.string().optional()}),use:[E]},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new V.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 V.APIError("BAD_REQUEST",{message:"User not found"});let o=await L(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,n,o),e.json({status:!0})}),we=m("/verify-email",{method:"GET",query:v.z.object({token:v.z.string(),callbackURL:v.z.string().optional()}),use:[E]},async e=>{let{token:t}=e.query,r;try{r=await(0,te.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new V.APIError("BAD_REQUEST",{message:"Invalid token"})}let n=v.z.object({email:v.z.string().email(),updateTo:v.z.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new V.APIError("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await ee(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new V.APIError("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new V.APIError("UNAUTHORIZED",{message:"Invalid session"});let d=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(d,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:d,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var ye=m("/sign-in/social",{method:"POST",requireHeaders:!0,query:T.z.object({currentURL:T.z.string().optional()}).optional(),body:T.z.object({callbackURL:T.z.string().optional(),provider:T.z.enum(Rt)}),use:[E]},async e=>{let t=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new P.APIError("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,n=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,i=await Me(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,i.hash,e.context.secret,r.state.options);let s=(0,Et.generateCodeVerifier)();await e.setSignedCookie(r.pkCodeVerifier.name,s,e.context.secret,r.pkCodeVerifier.options);let d=await t.createAuthorizationURL({state:i.raw,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:d.toString(),state:i,codeVerifier:s,redirect:!0})}),be=m("/sign-in/email",{method:"POST",body:T.z.object({email:T.z.string(),password:T.z.string(),callbackURL:T.z.string().optional(),dontRememberMe:T.z.boolean().default(!1).optional()}),use:[E]},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new P.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!T.z.string().email().safeParse(t).success)throw new P.APIError("BAD_REQUEST",{message:"Invalid email"});if(!T.z.string().email().safeParse(t).success)throw new P.APIError("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=i.accounts.find(l=>l.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let d=s?.password;if(!d)throw e.context.logger.error("Password not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(d,r))throw e.context.logger.error("Invalid password"),new P.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw w.error("Email verification is required but no email verification handler is provided"),new P.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let l=await L(e.context.secret,i.user.email),h=`${e.context.options.baseURL}/verify-email?token=${l}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,h,l),e.context.logger.error("Email not verified",{email:t}),new P.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let c=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.dontRememberMe);if(!c)throw e.context.logger.error("Failed to create session"),new P.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await S(e,c.id,e.body.dontRememberMe),e.json({user:i.user,session:c,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var G=require("zod");var f=require("zod"),Rn=f.z.object({id:f.z.string(),providerId:f.z.string(),accountId:f.z.string(),userId:f.z.string(),accessToken:f.z.string().nullable().optional(),refreshToken:f.z.string().nullable().optional(),idToken:f.z.string().nullable().optional(),expiresAt:f.z.date().nullable().optional(),password:f.z.string().optional().nullable()}),xt=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().optional(),createdAt:f.z.date().default(new Date),updatedAt:f.z.date().default(new Date)}),Un=f.z.object({id:f.z.string(),userId:f.z.string(),expiresAt:f.z.date(),ipAddress:f.z.string().optional(),userAgent:f.z.string().optional()}),En=f.z.object({id:f.z.string(),value:f.z.string(),expiresAt:f.z.date(),identifier:f.z.string()});function Tt(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 vt(e,t){let r=t.fields,o={};for(let n in r){if(n in e){if(r[n].input===!1){if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}continue}o[n]=e[n];continue}if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}}return o}function Pt(e,t){let r=Tt(e,"user");return vt(t||{},{fields:r})}function _t(e,t){let r=Tt(e,"user");return vt(t||{},{fields:r})}var ke=m("/callback/:id",{method:"GET",query:G.z.object({state:G.z.string(),code:G.z.string().optional(),error:G.z.string().optional()}),metadata:C},async e=>{if(e.query.error||!e.query.code){let U=le(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${U}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(u=>u.id===e.params.id);if(!t)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 r=le(e.query.state);if(!r.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:n}}=r,i=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!i)throw w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await qe(e.query.state,i))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let d=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),a;try{a=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:d,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(u){throw e.context.logger.error(u),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let c=await t.getUserInfo(a).then(u=>u?.user),l=mt(),h=xt.safeParse({...c,id:l});if(!c||h.success===!1)throw w.error("Unable to get user info",h.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);function g(u){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${u}`)}let p=await e.context.internalAdapter.findUserByEmail(c.email,{includeAccounts:!0}).catch(u=>{throw w.error(`Better auth was unable to query your database.
|
|
3
|
+
Error: `,u),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),A=p?.user.id;if(p){let u=p.accounts.find(U=>U.providerId===t.id);if(u)await e.context.internalAdapter.updateAccount(u.id,{accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt});else{(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!c.emailVerified||!e.context.options.account?.accountLinking?.enabled)&&g("account_not_linked");try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:c.id.toString(),id:`${t.id}:${c.id}`,userId:p.user.id,accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt})}catch(B){w.error("Unable to link account",B),g("unable_to_link_account")}}}else try{let u=c.emailVerified||!1,U=await e.context.internalAdapter.createOAuthUser({...h.data,emailVerified:u},{accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt,providerId:t.id,accountId:c.id.toString()});if(A=U?.user.id,!u&&U&&e.context.options.emailVerification?.sendOnSignUp){let H=await L(e.context.secret,c.email),B=`${e.context.baseURL}/verify-email?token=${H}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(U.user,B,H)}}catch(u){w.error("Unable to create user",u),g("unable_to_create_user")}A||g("unable_to_create_user");let x=await e.context.internalAdapter.createSession(A,e.request);throw x||g("unable_to_create_session"),await S(e,x.id),e.redirect(o)});var Dn=require("zod");var St=require("better-call");var Ae=m("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new St.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),Q(e),e.json({success:!0})});var _=require("zod");var W=require("better-call");var Re=m("/forget-password",{method:"POST",body:_.z.object({email:_.z.string().email(),redirectTo:_.z.string()}),use:[E]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new W.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n)),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let d=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,d),e.json({status:!0})}),Ue=m("/reset-password/:token",{method:"GET",query:_.z.object({callbackURL:_.z.string()}),use:[E]},async e=>{let{token:t}=e.params,r=e.query.callbackURL,o=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}${o.includes("?")?"&":"?"}token=${t}`)}),Ee=m("/reset-password",{query:_.z.optional(_.z.object({token:_.z.string().optional(),currentURL:_.z.string().optional()})),method:"POST",body:_.z.object({newPassword:_.z.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new W.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 W.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(i)).find(l=>l.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(i,s))throw new W.APIError("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});var k=require("zod");var R=require("better-call");var xe=()=>m("/user/update",{method:"POST",body:k.z.record(k.z.string(),k.z.any()),use:[O,E]},async e=>{let t=e.body;if(t.email)throw new R.APIError("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...n}=t,i=e.context.session;if(!o&&!r&&Object.keys(n).length===0)return e.json({user:i.user});let s=Pt(e.context.options,n),d=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return e.json({user:d})}),Te=m("/user/change-password",{method:"POST",body:k.z.object({newPassword:k.z.string(),currentPassword:k.z.string(),revokeOtherSessions:k.z.boolean().optional()}),use:[O]},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 R.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 R.APIError("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(h=>h.providerId==="credential"&&h.password);if(!a||!a.password)throw new R.APIError("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(a.password,r))throw new R.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(a.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let h=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!h)throw new R.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await S(e,h.id)}return e.json(n.user)}),ve=m("/user/set-password",{method:"POST",body:k.z.object({newPassword:k.z.string()}),use:[O]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new R.APIError("BAD_REQUEST",{message:"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 R.APIError("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password),d=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:d}),e.json(r.user);throw new R.APIError("BAD_REQUEST",{message:"user already has a password"})}),Pe=m("/user/delete",{method:"POST",body:k.z.object({password:k.z.string()}),use:[O]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(d=>d.providerId==="credential"&&d.password);if(!n||!n.password)throw new R.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new R.APIError("BAD_REQUEST",{message:"Incorrect password"});await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id);let s=e.context.authCookies.sessionToken;return e.setCookie(s.name,"",{maxAge:0}),e.json(null)}),_e=m("/user/change-email",{method:"POST",query:k.z.object({currentURL:k.z.string().optional()}).optional(),body:k.z.object({newEmail:k.z.string().email(),callbackURL:k.z.string().optional()}),use:[O,E]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new R.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new R.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new R.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let 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 R.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await L(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(e.context.session.user,e.body.newEmail,o,r),e.json({user:null,status:!0})});var Se=m("/csrf",{method:"GET",metadata:C},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t){let[i,s]=t.split("!")||[null,null];return e.json({csrfToken:i})}let r=$e(32,Ve("a-z","0-9","A-Z")),o=await K(e.context.secret,r),n=`${r}!${o}`;return await e.setSignedCookie(e.context.authCookies.csrfToken.name,n,e.context.secret,e.context.authCookies.csrfToken.options),e.json({csrfToken:r})});var tr=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|
|
6
6
|
<meta charset="UTF-8">
|
|
@@ -80,5 +80,5 @@ Error: `,u),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
|
|
|
80
80
|
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
81
81
|
</div>
|
|
82
82
|
</body>
|
|
83
|
-
</html>`,
|
|
83
|
+
</html>`,Oe=m("/error",{method:"GET",metadata:C},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(tr(t),{headers:{"Content-Type":"text/html"}})});var Le=m("/ok",{method:"GET",metadata:C},async e=>e.json({ok:!0}));var j=require("zod");var I=require("better-call");var Ie=()=>m("/sign-up/email",{method:"POST",query:j.z.object({currentURL:j.z.string().optional()}).optional(),body:j.z.record(j.z.string(),j.z.any()),use:[E]},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new I.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,...d}=t;if(!j.z.string().email().safeParse(o).success)throw new I.APIError("BAD_REQUEST",{message:"Invalid email"});let c=e.context.password.config.minPasswordLength;if(n.length<c)throw e.context.logger.error("Password is too short"),new I.APIError("BAD_REQUEST",{message:"Password is too short"});let l=e.context.password.config.maxPasswordLength;if(n.length>l)throw e.context.logger.error("Password is too long"),new I.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 I.APIError("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let g=_t(e.context.options,d),p;try{if(p=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...g,emailVerified:!1}),!p)throw new I.APIError("BAD_REQUEST",{message:"Failed to create user"})}catch(u){throw new I.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:u})}if(!p)throw new I.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let A=await e.context.password.hash(n);if(await e.context.internalAdapter.linkAccount({userId:p.id,providerId:"credential",accountId:p.id,password:A,expiresAt:M(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let u=await L(e.context.secret,p.email),U=`${e.context.baseURL}/verify-email?token=${u}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(p,U,u)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:p,session:null},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:p,session:null}});let x=await e.context.internalAdapter.createSession(p.id,e.request);if(!x)throw new I.APIError("BAD_REQUEST",{message:"Failed to create session"});return await S(e,x.id),e.json({user:p,session:x},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:p,session:x}})});var Ot=require("std-env");function Lt(e){let t="127.0.0.1";if(Ot.isTest)return t;let r=["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],o=e instanceof Request?e.headers:e;for(let n of r){let i=o.get(n);if(typeof i=="string"){let s=i.split(",")[0].trim();if(s)return s}}return null}function rr(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function or(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 nr(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function ir(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async n=>await o.findOne({model:r,where:[{field:"key",value:n}]}),set:async(n,i,s)=>{try{s?await o.update({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(d){w.error("Error setting rate limit",d)}}}}var It=new Map;function sr(e){return 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 It.get(r)},async set(r,o,n){It.set(r,o)}}:ir(e,e.rateLimit.tableName)}async function Ct(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),n=t.rateLimit.window,i=t.rateLimit.max,s=Lt(e)+o,a=ar().find(g=>g.pathMatcher(o));a&&(n=a.window,i=a.max);for(let g of t.options.plugins||[])if(g.rateLimit){let p=g.rateLimit.find(A=>A.pathMatcher(o));if(p){n=p.window,i=p.max;break}}if(t.rateLimit.customRules){let g=t.rateLimit.customRules[o];g&&(n=g.window,i=g.max)}let c=sr(t),l=await c.get(s),h=Date.now();if(!l)await c.set(s,{key:s,count:1,lastRequest:h});else{let g=h-l.lastRequest;if(rr(i,n,l)){let p=nr(l.lastRequest,n);return or(p)}else g>n*1e3?await c.set(s,{...l,count:1,lastRequest:h}):await c.set(s,{...l,count:l.count+1,lastRequest:h})}}function ar(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:3}]}var Dt=require("better-call");function Bt(e,t){let r=t.plugins?.reduce((d,a)=>({...d,...a.endpoints}),{}),o=t.plugins?.map(d=>d.middlewares?.map(a=>{let c=async l=>a.middleware({...l,context:{...e,...l.context}});return c.path=a.path,c.options=a.middleware.options,c.headers=a.middleware.headers,{path:a.path,middleware:c}})).filter(d=>d!==void 0).flat()||[],i={...{signInOAuth:ye,callbackOAuth:ke,getCSRFToken:Se,getSession:X(),signOut:Ae,signUpEmail:Ie(),signInEmail:be,forgetPassword:Re,resetPassword:Ee,verifyEmail:we,sendVerificationEmail:he,changeEmail:_e,changePassword:Te,setPassword:ve,updateUser:xe(),deleteUser:Pe,forgetPasswordCallback:Ue,listSessions:me(),revokeSession:fe,revokeSessions:ge},...r,ok:Le,error:Oe},s={};for(let[d,a]of Object.entries(i))s[d]=async(c={})=>{let l=await e;for(let p of t.plugins||[])if(p.hooks?.before){for(let A of p.hooks.before)if(A.matcher({...a,...c,context:l})){let u=await A.handler({...c,context:{...l,...c?.context}});u&&"context"in u&&(l={...l,...u.context})}}let h;try{h=await a({...c,context:{...l,...c.context}})}catch(p){if(p instanceof q.APIError){let A=t.plugins?.map(u=>{if(u.hooks?.after)return u.hooks.after}).filter(u=>u!==void 0).flat();if(!A?.length)throw p;let x=new Response(JSON.stringify(p.body),{status:q.statusCode[p.status],headers:p.headers});for(let u of A||[])if(u.matcher(c)){let H=Object.assign(c,{context:{...e,returned:x}}),B=await u.handler(H);B&&"response"in B&&(x=B.response)}return x}throw p}let g=h;for(let p of t.plugins||[])if(p.hooks?.after){for(let A of p.hooks.after)if(A.matcher(c)){let u=Object.assign(c,{context:{...e,returned:g}}),U=await A.handler(u);U&&"response"in U&&(g=U.response)}}return g},s[d].path=a.path,s[d].method=a.method,s[d].options=a.options,s[d].headers=a.headers;return{api:s,middlewares:o}}var dr=(e,t)=>{let{api:r,middlewares:o}=Bt(e,t),n=new URL(e.baseURL).pathname;return(0,q.createRouter)(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:de},...o],async onRequest(i){for(let s of e.options.plugins||[])if(s.onRequest){let d=await s.onRequest(i,e);if(d)return d}return Ct(i,e)},async onResponse(i){for(let s of e.options.plugins||[])if(s.onResponse){let d=await s.onResponse(i,e);if(d)return d.response}return i},onError(i){if(t.onAPIError?.throw)throw i;if(t.onAPIError?.onError){t.onAPIError.onError(i,e);return}let s=t.logger?.verboseLogging?w:void 0;t.logger?.disabled!==!0&&(i instanceof q.APIError?(i.status==="INTERNAL_SERVER_ERROR"&&w.error(i),s?.error(i.message)):w?.error(i))}})};0&&(module.exports={APIError,callbackOAuth,changeEmail,changePassword,createAuthEndpoint,createAuthMiddleware,createEmailVerificationToken,csrfMiddleware,deleteUser,error,forgetPassword,forgetPasswordCallback,getCSRFToken,getEndpoints,getSession,getSessionFromCtx,listSessions,ok,optionsMiddleware,resetPassword,revokeSession,revokeSessions,router,sendVerificationEmail,sessionMiddleware,setPassword,signInEmail,signInOAuth,signOut,signUpEmail,updateUser,verifyEmail});
|
|
84
84
|
//# sourceMappingURL=api.cjs.map
|