@better-auth/core 1.5.0-beta.2 → 1.5.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
 
2
- > @better-auth/core@1.5.0-beta.2 build /home/runner/work/better-auth/better-auth/packages/core
2
+ > @better-auth/core@1.5.0-beta.4 build /home/runner/work/better-auth/better-auth/packages/core
3
3
  > tsdown
4
4
 
5
5
  ℹ tsdown v0.17.2 powered by rolldown v1.0.0-beta.53
@@ -16,28 +16,28 @@
16
16
  ℹ dist/oauth2/index.mjs  0.75 kB │ gzip: 0.28 kB
17
17
  ℹ dist/context/index.mjs  0.70 kB │ gzip: 0.24 kB
18
18
  ℹ dist/env/index.mjs  0.44 kB │ gzip: 0.25 kB
19
- ℹ dist/utils/index.mjs  0.24 kB │ gzip: 0.17 kB
19
+ ℹ dist/utils/index.mjs  0.26 kB │ gzip: 0.18 kB
20
20
  ℹ dist/error/index.mjs  0.22 kB │ gzip: 0.16 kB
21
21
  ℹ dist/index.mjs  0.01 kB │ gzip: 0.03 kB
22
22
  ℹ dist/oauth2-BjWM15hm.mjs  12.82 kB │ gzip: 3.16 kB
23
23
  ℹ dist/env-DbssmzoK.mjs  7.67 kB │ gzip: 2.54 kB
24
24
  ℹ dist/get-tables-CMc_Emww.mjs  6.76 kB │ gzip: 1.30 kB
25
- ℹ dist/context-DblZrIwO.mjs  3.89 kB │ gzip: 1.00 kB
26
- ℹ dist/error-C7mY-p0f.mjs  3.19 kB │ gzip: 1.30 kB
27
- ℹ dist/utils-s65Fz0OM.mjs  1.22 kB │ gzip: 0.61 kB
25
+ ℹ dist/context-BBNwughv.mjs  4.87 kB │ gzip: 1.40 kB
26
+ ℹ dist/error-GNtLPYaS.mjs  3.19 kB │ gzip: 1.30 kB
27
+ ℹ dist/utils-puAL36Bz.mjs  1.58 kB │ gzip: 0.76 kB
28
28
  ℹ dist/error/index.d.mts  6.11 kB │ gzip: 1.50 kB
29
- ℹ dist/social-providers/index.d.mts  3.88 kB │ gzip: 1.19 kB
29
+ ℹ dist/social-providers/index.d.mts  3.89 kB │ gzip: 1.20 kB
30
30
  ℹ dist/context/index.d.mts  3.02 kB │ gzip: 0.96 kB
31
+ ℹ dist/utils/index.d.mts  1.55 kB │ gzip: 0.70 kB
31
32
  ℹ dist/db/adapter/index.d.mts  1.34 kB │ gzip: 0.43 kB
32
- ℹ dist/utils/index.d.mts  1.24 kB │ gzip: 0.56 kB
33
- ℹ dist/index.d.mts  0.92 kB │ gzip: 0.35 kB
33
+ ℹ dist/index.d.mts  1.09 kB │ gzip: 0.39 kB
34
34
  ℹ dist/oauth2/index.d.mts  0.88 kB │ gzip: 0.32 kB
35
35
  ℹ dist/db/index.d.mts  0.81 kB │ gzip: 0.34 kB
36
36
  ℹ dist/env/index.d.mts  0.59 kB │ gzip: 0.30 kB
37
37
  ℹ dist/api/index.d.mts  0.26 kB │ gzip: 0.14 kB
38
38
  ℹ dist/async_hooks/index.d.mts  0.24 kB │ gzip: 0.16 kB
39
39
  ℹ dist/async_hooks/pure.index.d.mts  0.22 kB │ gzip: 0.16 kB
40
- ℹ dist/index-BpRqx5_q.d.mts 221.64 kB │ gzip: 35.40 kB
40
+ ℹ dist/index-B5x_W0dM.d.mts 228.92 kB │ gzip: 36.28 kB
41
41
  ℹ dist/index-BRBu0-5h.d.mts  3.31 kB │ gzip: 1.11 kB
42
- ℹ 32 files, total: 406.80 kB
43
- ✔ Build complete in 4834ms
42
+ ℹ 32 files, total: 415.92 kB
43
+ ✔ Build complete in 5286ms
package/LICENSE.md CHANGED
@@ -1,17 +1,20 @@
1
1
  The MIT License (MIT)
2
2
  Copyright (c) 2024 - present, Bereket Engida
3
3
 
4
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software
5
- and associated documentation files (the "Software"), to deal in the Software without restriction,
6
- including without limitation the rights to use, copy, modify, merge, publish, distribute,
7
- sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
8
- is furnished to do so, subject to the following conditions:
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
5
+ this software and associated documentation files (the Software), to deal in
6
+ the Software without restriction, including without limitation the rights to
7
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
8
+ the Software, and to permit persons to whom the Software is furnished to do so,
9
+ subject to the following conditions:
9
10
 
10
- The above copyright notice and this permission notice shall be included in all copies or
11
- substantial portions of the Software.
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
12
13
 
13
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
14
- BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
15
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16
- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14
+ THE SOFTWARE IS PROVIDED AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
16
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20
+ DEALINGS IN THE SOFTWARE.
@@ -1,2 +1,2 @@
1
- import { a as optionsMiddleware, i as createAuthMiddleware, n as AuthMiddleware, r as createAuthEndpoint, t as AuthEndpoint } from "../index-BpRqx5_q.mjs";
1
+ import { a as optionsMiddleware, i as createAuthMiddleware, n as AuthMiddleware, r as createAuthEndpoint, t as AuthEndpoint } from "../index-B5x_W0dM.mjs";
2
2
  export { AuthEndpoint, AuthMiddleware, createAuthEndpoint, createAuthMiddleware, optionsMiddleware };
@@ -1,4 +1,4 @@
1
- import { f as runWithEndpointContext } from "../context-DblZrIwO.mjs";
1
+ import { f as runWithEndpointContext } from "../context-BBNwughv.mjs";
2
2
  import { createEndpoint, createMiddleware } from "better-call";
3
3
 
4
4
  //#region src/api/index.ts
@@ -1,4 +1,4 @@
1
- import { Yn as DBAdapter, er as DBTransactionAdapter, f as AuthContext } from "../index-BpRqx5_q.mjs";
1
+ import { Qn as DBAdapter, f as AuthContext, rr as DBTransactionAdapter } from "../index-B5x_W0dM.mjs";
2
2
  import { AsyncLocalStorage } from "@better-auth/core/async_hooks";
3
3
  import { EndpointContext, InputContext } from "better-call";
4
4
 
@@ -1,3 +1,3 @@
1
- import { a as defineRequestState, c as hasRequestState, d as getCurrentAuthContextAsyncLocalStorage, f as runWithEndpointContext, i as runWithTransaction, l as runWithRequestState, n as getCurrentDBAdapterAsyncLocalStorage, o as getCurrentRequestState, r as runWithAdapter, s as getRequestStateAsyncLocalStorage, t as getCurrentAdapter, u as getCurrentAuthContext } from "../context-DblZrIwO.mjs";
1
+ import { a as defineRequestState, c as hasRequestState, d as getCurrentAuthContextAsyncLocalStorage, f as runWithEndpointContext, i as runWithTransaction, l as runWithRequestState, n as getCurrentDBAdapterAsyncLocalStorage, o as getCurrentRequestState, r as runWithAdapter, s as getRequestStateAsyncLocalStorage, t as getCurrentAdapter, u as getCurrentAuthContext } from "../context-BBNwughv.mjs";
2
2
 
3
3
  export { defineRequestState, getCurrentAdapter, getCurrentAuthContext, getCurrentAuthContextAsyncLocalStorage, getCurrentDBAdapterAsyncLocalStorage, getCurrentRequestState, getRequestStateAsyncLocalStorage, hasRequestState, runWithAdapter, runWithEndpointContext, runWithRequestState, runWithTransaction };
@@ -110,5 +110,24 @@ const runWithTransaction = async (adapter, fn) => {
110
110
  });
111
111
  };
112
112
 
113
+ //#endregion
114
+ //#region src/context/index.ts
115
+ const glo = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {};
116
+ const importIdentifier = "__ $BETTER_AUTH$ __";
117
+ if (glo[importIdentifier] === true)
118
+ /**
119
+ * Dear reader of this message. Please take this seriously.
120
+ *
121
+ * If you see this message, make sure that you only import one version of Better Auth. In many cases,
122
+ * your package manager installs two versions of Better Auth that are used by different packages within your project.
123
+ *
124
+ * This often leads to issues that are hard to debug. We often need to ensure async local storage instance,
125
+ * If you imported different versions of Better Auth, it is impossible for us to
126
+ * do status synchronization per request anymore - which might break the states.
127
+ *
128
+ */
129
+ console.error("Better Auth was already imported. This breaks async local storage instance and will lead to issues!");
130
+ glo[importIdentifier] = true;
131
+
113
132
  //#endregion
114
133
  export { defineRequestState as a, hasRequestState as c, getCurrentAuthContextAsyncLocalStorage as d, runWithEndpointContext as f, runWithTransaction as i, runWithRequestState as l, getCurrentDBAdapterAsyncLocalStorage as n, getCurrentRequestState as o, runWithAdapter as r, getRequestStateAsyncLocalStorage as s, getCurrentAdapter as t, getCurrentAuthContext as u };
@@ -1,2 +1,2 @@
1
- import { $n as DBAdapterSchemaCreation, Cr as initGetFieldName, Er as initGetDefaultFieldName, Jn as CustomAdapter, Qn as DBAdapterInstance, Sr as initGetIdField, Tr as initGetDefaultModelName, Xn as DBAdapterDebugLogOption, Yn as DBAdapter, Zn as DBAdapterFactoryConfig, ar as withApplyDefault, cr as createAdapterFactory, dr as AdapterFactoryCustomizeAdapterCreator, er as DBTransactionAdapter, fr as AdapterFactoryOptions, hr as CreateCustomAdapter, ir as deepmerge, lr as AdapterConfig, mr as CreateAdapterOptions, nr as JoinOption, or as AdapterFactory, pr as AdapterTestDebugLogs, qn as CleanedWhere, rr as Where, sr as createAdapter, tr as JoinConfig, ur as AdapterFactoryConfig, wr as initGetFieldAttributes, xr as initGetModelName } from "../../index-BpRqx5_q.mjs";
1
+ import { $n as DBAdapterDebugLogOption, Dr as initGetFieldAttributes, Er as initGetFieldName, Or as initGetDefaultModelName, Qn as DBAdapter, Tr as initGetIdField, Xn as CleanedWhere, Zn as CustomAdapter, _r as CreateAdapterOptions, ar as JoinOption, cr as withApplyDefault, dr as createAdapterFactory, er as DBAdapterFactoryConfig, fr as AdapterConfig, gr as AdapterTestDebugLogs, hr as AdapterFactoryOptions, ir as JoinConfig, kr as initGetDefaultFieldName, lr as AdapterFactory, mr as AdapterFactoryCustomizeAdapterCreator, nr as DBAdapterSchemaCreation, or as Where, pr as AdapterFactoryConfig, rr as DBTransactionAdapter, sr as deepmerge, tr as DBAdapterInstance, ur as createAdapter, vr as CreateCustomAdapter, wr as initGetModelName } from "../../index-B5x_W0dM.mjs";
2
2
  export { AdapterConfig, AdapterFactory, AdapterFactoryConfig, AdapterFactoryCustomizeAdapterCreator, AdapterFactoryOptions, AdapterTestDebugLogs, CleanedWhere, CreateAdapterOptions, CreateCustomAdapter, CustomAdapter, DBAdapter, DBAdapterDebugLogOption, DBAdapterFactoryConfig, DBAdapterInstance, DBAdapterSchemaCreation, DBTransactionAdapter, JoinConfig, JoinOption, Where, createAdapter, createAdapterFactory, deepmerge, initGetDefaultFieldName, initGetDefaultModelName, initGetFieldAttributes, initGetFieldName, initGetIdField, initGetModelName, withApplyDefault };
@@ -1,7 +1,7 @@
1
1
  import { t as getAuthTables } from "../../get-tables-CMc_Emww.mjs";
2
2
  import { i as logger, n as createLogger, o as getColorDepth, t as TTY_COLORS } from "../../env-DbssmzoK.mjs";
3
- import { n as safeJSONParse, r as generateId } from "../../utils-s65Fz0OM.mjs";
4
- import { n as BetterAuthError } from "../../error-C7mY-p0f.mjs";
3
+ import { n as safeJSONParse, r as generateId } from "../../utils-puAL36Bz.mjs";
4
+ import { n as BetterAuthError } from "../../error-GNtLPYaS.mjs";
5
5
 
6
6
  //#region src/db/adapter/get-default-model-name.ts
7
7
  const initGetDefaultModelName = ({ usePlural, schema }) => {
@@ -1,2 +1,2 @@
1
- import { Ar as userSchema, Br as BaseModelNames, Dr as Verification, Fr as rateLimitSchema, Gr as DBPrimitive, Hr as DBFieldAttribute, Ir as Account, Kr as ModelNames, Lr as accountSchema, Mr as Session, Nr as sessionSchema, Or as verificationSchema, Pr as RateLimit, Rr as BetterAuthPluginDBSchema, Ur as DBFieldAttributeConfig, Vr as BetterAuthDBSchema, Wr as DBFieldType, jr as coreSchema, kr as User, qr as SecondaryStorage, zr as getAuthTables } from "../index-BpRqx5_q.mjs";
1
+ import { Ar as Verification, Br as accountSchema, Fr as Session, Gr as DBFieldAttribute, Hr as getAuthTables, Ir as sessionSchema, Jr as DBPrimitive, Kr as DBFieldAttributeConfig, Lr as RateLimit, Mr as User, Nr as userSchema, Pr as coreSchema, Rr as rateLimitSchema, Ur as BaseModelNames, Vr as BetterAuthPluginDBSchema, Wr as BetterAuthDBSchema, Xr as SecondaryStorage, Yr as ModelNames, jr as verificationSchema, qr as DBFieldType, zr as Account } from "../index-B5x_W0dM.mjs";
2
2
  export { Account, BaseModelNames, BetterAuthDBSchema, BetterAuthPluginDBSchema, DBFieldAttribute, DBFieldAttributeConfig, DBFieldType, DBPrimitive, ModelNames, RateLimit, SecondaryStorage, Session, User, Verification, accountSchema, coreSchema, getAuthTables, rateLimitSchema, sessionSchema, userSchema, verificationSchema };
@@ -1,5 +1,5 @@
1
1
  import "../env-DbssmzoK.mjs";
2
- import "../utils-s65Fz0OM.mjs";
3
- import { n as BetterAuthError, r as BASE_ERROR_CODES, t as APIError } from "../error-C7mY-p0f.mjs";
2
+ import "../utils-puAL36Bz.mjs";
3
+ import { n as BetterAuthError, r as BASE_ERROR_CODES, t as APIError } from "../error-GNtLPYaS.mjs";
4
4
 
5
5
  export { APIError, BASE_ERROR_CODES, BetterAuthError };
@@ -1,4 +1,4 @@
1
- import { i as defineErrorCodes } from "./utils-s65Fz0OM.mjs";
1
+ import { i as defineErrorCodes } from "./utils-puAL36Bz.mjs";
2
2
  import { APIError } from "better-call/error";
3
3
 
4
4
  //#region src/error/codes.ts
@@ -6415,17 +6415,32 @@ type BetterAuthAdvancedOptions = {
6415
6415
  */
6416
6416
  useSecureCookies?: boolean | undefined;
6417
6417
  /**
6418
- * Disable trusted origins check
6418
+ * Disable all CSRF protection.
6419
+ *
6420
+ * When enabled, this disables:
6421
+ * - Origin header validation when cookies are present
6422
+ * - Fetch Metadata checks (Sec-Fetch-Site, Sec-Fetch-Mode, Sec-Fetch-Dest)
6423
+ * - Cross-site navigation blocking for first-login scenarios
6419
6424
  *
6420
6425
  * ⚠︎ This is a security risk and it may expose your application to
6421
6426
  * CSRF attacks
6427
+ *
6428
+ * @default false
6422
6429
  */
6423
6430
  disableCSRFCheck?: boolean | undefined;
6424
6431
  /**
6425
- * Disable origin check
6432
+ * Disable URL validation against trustedOrigins.
6433
+ *
6434
+ * When enabled, this disables validation of:
6435
+ * - callbackURL
6436
+ * - redirectTo
6437
+ * - errorCallbackURL
6438
+ * - newUserCallbackURL
6426
6439
  *
6427
- * ⚠︎ This may allow requests from any origin to be processed by
6428
- * Better Auth. And could lead to security vulnerabilities.
6440
+ * ⚠︎ This may allow open redirects and could lead to security
6441
+ * vulnerabilities.
6442
+ *
6443
+ * @default false
6429
6444
  */
6430
6445
  disableOriginCheck?: boolean | undefined;
6431
6446
  /**
@@ -6709,8 +6724,15 @@ type BetterAuthOptions = {
6709
6724
  * A function that is called when a user verifies their email
6710
6725
  * @param user the user that verified their email
6711
6726
  * @param request the request object
6727
+ * @deprecated Use `beforeEmailVerification` or `afterEmailVerification` instead. This will be removed in 1.5
6712
6728
  */
6713
6729
  onEmailVerification?: (user: User, request?: Request) => Promise<void>;
6730
+ /**
6731
+ * A function that is called before a user verifies their email
6732
+ * @param user the user that verified their email
6733
+ * @param request the request object
6734
+ */
6735
+ beforeEmailVerification?: (user: User, request?: Request) => Promise<void>;
6714
6736
  /**
6715
6737
  * A function that is called when a user's email is updated to verified
6716
6738
  * @param user the user that verified their email
@@ -7199,8 +7221,20 @@ type BetterAuthOptions = {
7199
7221
  *
7200
7222
  * Trusted origins will be dynamically
7201
7223
  * calculated based on the request.
7224
+ *
7225
+ * @example
7226
+ * ```ts
7227
+ * trustedOrigins: async (request) => {
7228
+ * return [
7229
+ * "https://better-auth.com",
7230
+ * "https://*.better-auth.com",
7231
+ * request.headers.get("x-custom-origin")
7232
+ * ];
7233
+ * }
7234
+ * ```
7235
+ * @returns An array of trusted origins.
7202
7236
  */
7203
- trustedOrigins?: (string[] | ((request?: Request | undefined) => Awaitable<string[]>)) | undefined;
7237
+ trustedOrigins?: (string[] | ((request?: Request | undefined) => Awaitable<(string | undefined | null)[]>)) | undefined;
7204
7238
  /**
7205
7239
  * Rate limiting configuration
7206
7240
  */
@@ -7515,6 +7549,22 @@ type BetterAuthOptions = {
7515
7549
  };
7516
7550
  //#endregion
7517
7551
  //#region src/types/context.d.ts
7552
+ /**
7553
+ * Mutators are defined in each plugin
7554
+ *
7555
+ * @example
7556
+ * ```ts
7557
+ * declare module "@better-auth/core" {
7558
+ * interface BetterAuthPluginRegistry<Auth, Context> {
7559
+ * 'jwt': {
7560
+ * creator: typeof jwt
7561
+ * }
7562
+ * }
7563
+ * }
7564
+ * ```
7565
+ */
7566
+ interface BetterAuthPluginRegistry<Auth, Context> {}
7567
+ type BetterAuthPluginRegistryIdentifier = keyof BetterAuthPluginRegistry<unknown, unknown>;
7518
7568
  type GenericEndpointContext<Options extends BetterAuthOptions = BetterAuthOptions> = EndpointContext<string, any> & {
7519
7569
  context: AuthContext<Options>;
7520
7570
  };
@@ -7577,7 +7627,24 @@ type CreateCookieGetterFn = (cookieName: string, overrideAttributes?: Partial<Co
7577
7627
  attributes: CookieOptions;
7578
7628
  };
7579
7629
  type CheckPasswordFn<Options extends BetterAuthOptions = BetterAuthOptions> = (userId: string, ctx: GenericEndpointContext<Options>) => Promise<boolean>;
7580
- type AuthContext<Options extends BetterAuthOptions = BetterAuthOptions> = {
7630
+ type PluginContext = {
7631
+ getPlugin: <ID extends BetterAuthPluginRegistryIdentifier | LiteralString>(pluginId: ID) => (ID extends BetterAuthPluginRegistryIdentifier ? ReturnType<BetterAuthPluginRegistry<unknown, unknown>[ID]["creator"]> : BetterAuthPlugin) | null;
7632
+ /**
7633
+ * Checks if a plugin is enabled by its ID.
7634
+ *
7635
+ * @param pluginId - The ID of the plugin to check
7636
+ * @returns `true` if the plugin is enabled, `false` otherwise
7637
+ *
7638
+ * @example
7639
+ * ```ts
7640
+ * if (ctx.context.hasPlugin("organization")) {
7641
+ * // organization plugin is enabled
7642
+ * }
7643
+ * ```
7644
+ */
7645
+ hasPlugin: <ID extends BetterAuthPluginRegistryIdentifier | LiteralString>(pluginId: ID) => boolean;
7646
+ };
7647
+ type AuthContext<Options extends BetterAuthOptions = BetterAuthOptions> = PluginContext & {
7581
7648
  options: Options;
7582
7649
  appName: string;
7583
7650
  baseURL: string;
@@ -7815,13 +7882,167 @@ interface BetterAuthClientPlugin {
7815
7882
  //#region src/api/index.d.ts
7816
7883
  declare const optionsMiddleware: <InputCtx extends better_call0.MiddlewareInputContext<better_call0.MiddlewareOptions>>(inputContext: InputCtx) => Promise<AuthContext>;
7817
7884
  declare const createAuthMiddleware: {
7818
- <Options extends better_call0.MiddlewareOptions, R>(options: Options, handler: (ctx: better_call0.MiddlewareContext<Options, AuthContext & {
7885
+ <Options extends better_call0.MiddlewareOptions, R>(options: Options, handler: (ctx: better_call0.MiddlewareContext<Options, {
7819
7886
  returned?: unknown | undefined;
7820
7887
  responseHeaders?: Headers | undefined;
7888
+ } & PluginContext & {
7889
+ options: BetterAuthOptions;
7890
+ appName: string;
7891
+ baseURL: string;
7892
+ trustedOrigins: string[];
7893
+ isTrustedOrigin: (url: string, settings?: {
7894
+ allowRelativePaths: boolean;
7895
+ }) => boolean;
7896
+ oauthConfig: {
7897
+ skipStateCookieCheck?: boolean | undefined;
7898
+ storeStateStrategy: "database" | "cookie";
7899
+ };
7900
+ newSession: {
7901
+ session: Session & Record<string, any>;
7902
+ user: User & Record<string, any>;
7903
+ } | null;
7904
+ session: {
7905
+ session: Session & Record<string, any>;
7906
+ user: User & Record<string, any>;
7907
+ } | null;
7908
+ setNewSession: (session: {
7909
+ session: Session & Record<string, any>;
7910
+ user: User & Record<string, any>;
7911
+ } | null) => void;
7912
+ socialProviders: OAuthProvider[];
7913
+ authCookies: BetterAuthCookies;
7914
+ logger: ReturnType<typeof createLogger>;
7915
+ rateLimit: {
7916
+ enabled: boolean;
7917
+ window: number;
7918
+ max: number;
7919
+ storage: "memory" | "database" | "secondary-storage";
7920
+ } & BetterAuthRateLimitOptions;
7921
+ adapter: DBAdapter<BetterAuthOptions>;
7922
+ internalAdapter: InternalAdapter<BetterAuthOptions>;
7923
+ createAuthCookie: (cookieName: string, overrideAttributes?: Partial<better_call0.CookieOptions> | undefined) => {
7924
+ name: string;
7925
+ attributes: better_call0.CookieOptions;
7926
+ };
7927
+ secret: string;
7928
+ sessionConfig: {
7929
+ updateAge: number;
7930
+ expiresIn: number;
7931
+ freshAge: number;
7932
+ cookieRefreshCache: false | {
7933
+ enabled: true;
7934
+ updateAge: number;
7935
+ };
7936
+ };
7937
+ generateId: (options: {
7938
+ model: ModelNames;
7939
+ size?: number | undefined;
7940
+ }) => string | false;
7941
+ secondaryStorage: SecondaryStorage | undefined;
7942
+ password: {
7943
+ hash: (password: string) => Promise<string>;
7944
+ verify: (data: {
7945
+ password: string;
7946
+ hash: string;
7947
+ }) => Promise<boolean>;
7948
+ config: {
7949
+ minPasswordLength: number;
7950
+ maxPasswordLength: number;
7951
+ };
7952
+ checkPassword: (userId: string, ctx: GenericEndpointContext<BetterAuthOptions>) => Promise<boolean>;
7953
+ };
7954
+ tables: BetterAuthDBSchema;
7955
+ runMigrations: () => Promise<void>;
7956
+ publishTelemetry: (event: {
7957
+ type: string;
7958
+ anonymousId?: string | undefined;
7959
+ payload: Record<string, any>;
7960
+ }) => Promise<void>;
7961
+ skipOriginCheck: boolean;
7962
+ skipCSRFCheck: boolean;
7963
+ runInBackground: (promise: Promise<void>) => void;
7964
+ runInBackgroundOrAwait: (promise: Promise<unknown> | Promise<void> | void | unknown) => Promise<unknown>;
7821
7965
  }>) => Promise<R>): (inputContext: better_call0.MiddlewareInputContext<Options>) => Promise<R>;
7822
- <Options extends better_call0.MiddlewareOptions, R_1>(handler: (ctx: better_call0.MiddlewareContext<Options, AuthContext & {
7966
+ <Options extends better_call0.MiddlewareOptions, R_1>(handler: (ctx: better_call0.MiddlewareContext<Options, {
7823
7967
  returned?: unknown | undefined;
7824
7968
  responseHeaders?: Headers | undefined;
7969
+ } & PluginContext & {
7970
+ options: BetterAuthOptions;
7971
+ appName: string;
7972
+ baseURL: string;
7973
+ trustedOrigins: string[];
7974
+ isTrustedOrigin: (url: string, settings?: {
7975
+ allowRelativePaths: boolean;
7976
+ }) => boolean;
7977
+ oauthConfig: {
7978
+ skipStateCookieCheck?: boolean | undefined;
7979
+ storeStateStrategy: "database" | "cookie";
7980
+ };
7981
+ newSession: {
7982
+ session: Session & Record<string, any>;
7983
+ user: User & Record<string, any>;
7984
+ } | null;
7985
+ session: {
7986
+ session: Session & Record<string, any>;
7987
+ user: User & Record<string, any>;
7988
+ } | null;
7989
+ setNewSession: (session: {
7990
+ session: Session & Record<string, any>;
7991
+ user: User & Record<string, any>;
7992
+ } | null) => void;
7993
+ socialProviders: OAuthProvider[];
7994
+ authCookies: BetterAuthCookies;
7995
+ logger: ReturnType<typeof createLogger>;
7996
+ rateLimit: {
7997
+ enabled: boolean;
7998
+ window: number;
7999
+ max: number;
8000
+ storage: "memory" | "database" | "secondary-storage";
8001
+ } & BetterAuthRateLimitOptions;
8002
+ adapter: DBAdapter<BetterAuthOptions>;
8003
+ internalAdapter: InternalAdapter<BetterAuthOptions>;
8004
+ createAuthCookie: (cookieName: string, overrideAttributes?: Partial<better_call0.CookieOptions> | undefined) => {
8005
+ name: string;
8006
+ attributes: better_call0.CookieOptions;
8007
+ };
8008
+ secret: string;
8009
+ sessionConfig: {
8010
+ updateAge: number;
8011
+ expiresIn: number;
8012
+ freshAge: number;
8013
+ cookieRefreshCache: false | {
8014
+ enabled: true;
8015
+ updateAge: number;
8016
+ };
8017
+ };
8018
+ generateId: (options: {
8019
+ model: ModelNames;
8020
+ size?: number | undefined;
8021
+ }) => string | false;
8022
+ secondaryStorage: SecondaryStorage | undefined;
8023
+ password: {
8024
+ hash: (password: string) => Promise<string>;
8025
+ verify: (data: {
8026
+ password: string;
8027
+ hash: string;
8028
+ }) => Promise<boolean>;
8029
+ config: {
8030
+ minPasswordLength: number;
8031
+ maxPasswordLength: number;
8032
+ };
8033
+ checkPassword: (userId: string, ctx: GenericEndpointContext<BetterAuthOptions>) => Promise<boolean>;
8034
+ };
8035
+ tables: BetterAuthDBSchema;
8036
+ runMigrations: () => Promise<void>;
8037
+ publishTelemetry: (event: {
8038
+ type: string;
8039
+ anonymousId?: string | undefined;
8040
+ payload: Record<string, any>;
8041
+ }) => Promise<void>;
8042
+ skipOriginCheck: boolean;
8043
+ skipCSRFCheck: boolean;
8044
+ runInBackground: (promise: Promise<void>) => void;
8045
+ runInBackgroundOrAwait: (promise: Promise<unknown> | Promise<void> | void | unknown) => Promise<unknown>;
7825
8046
  }>) => Promise<R_1>): (inputContext: better_call0.MiddlewareInputContext<Options>) => Promise<R_1>;
7826
8047
  };
7827
8048
  type EndpointHandler<Path extends string, Options extends EndpointOptions, R> = (context: EndpointContext<Path, Options, AuthContext>) => Promise<R>;
@@ -7830,4 +8051,4 @@ declare function createAuthEndpoint<Path extends string, Options extends Endpoin
7830
8051
  type AuthEndpoint<Path extends string, Opts extends EndpointOptions, R> = ReturnType<typeof createAuthEndpoint<Path, Opts, R>>;
7831
8052
  type AuthMiddleware = ReturnType<typeof createAuthMiddleware>;
7832
8053
  //#endregion
7833
- export { AccountStatus as $, DBAdapterSchemaCreation as $n, GoogleProfile as $t, PolarOptions as A, getJwks as An, userSchema as Ar, linear as At, LineIdTokenPayload as B, createAuthorizationURL as Bn, BaseModelNames as Br, TwitchOptions as Bt, SocialProviderListEnum as C, atlassian as Cn, initGetFieldName as Cr, gitlab as Ct, VercelOptions as D, apple as Dn, Verification as Dr, LinearOptions as Dt, socialProviders as E, AppleProfile as En, initGetDefaultFieldName as Er, linkedin as Et, PayPalTokenResponse as F, validateToken as Fn, rateLimitSchema as Fr, DropboxProfile as Ft, NaverProfile as G, OAuthProvider as Gn, DBPrimitive as Gr, spotify as Gt, LineUserInfo as H, createClientCredentialsTokenRequest as Hn, DBFieldAttribute as Hr, twitch as Ht, paypal as I, generateCodeChallenge as In, Account as Ir, dropbox as It, KakaoProfile as J, CustomAdapter as Jn, slack as Jt, naver as K, ProviderOptions as Kn, ModelNames as Kr, SlackOptions as Kt, PaybinOptions as L, getOAuth2Tokens as Ln, accountSchema as Lr, TwitterOption as Lt, polar as M, verifyJwsAccessToken as Mn, Session as Mr, KickProfile as Mt, PayPalOptions as N, createAuthorizationCodeRequest as Nn, sessionSchema as Nr, kick as Nt, VercelProfile as O, getApplePublicKey as On, verificationSchema as Or, LinearProfile as Ot, PayPalProfile as P, validateAuthorizationCode as Pn, RateLimit as Pr, DropboxOptions as Pt, notion as Q, DBAdapterInstance as Qn, GoogleOptions as Qt, PaybinProfile as R, createRefreshAccessTokenRequest as Rn, BetterAuthPluginDBSchema as Rr, TwitterProfile as Rt, SocialProviderList as S, AtlassianProfile as Sn, initGetIdField as Sr, GitlabProfile as St, socialProviderList as T, AppleOptions as Tn, initGetDefaultModelName as Tr, LinkedInProfile as Tt, line as U, OAuth2Tokens as Un, DBFieldAttributeConfig as Ur, SpotifyOptions as Ut, LineOptions as V, clientCredentialsToken as Vn, BetterAuthDBSchema as Vr, TwitchProfile as Vt, NaverOptions as W, OAuth2UserInfo as Wn, DBFieldType as Wr, SpotifyProfile as Wt, NotionOptions as X, DBAdapterDebugLogOption as Xn, HuggingFaceProfile as Xt, kakao as Y, DBAdapter as Yn, HuggingFaceOptions as Yt, NotionProfile as Z, DBAdapterFactoryConfig as Zn, huggingface as Zt, BetterAuthRateLimitOptions as _, CognitoOptions as _n, LiteralString as _r, reddit as _t, optionsMiddleware as a, GithubOptions as an, withApplyDefault as ar, zoom as at, HookEndpointContext as b, getCognitoPublicKey as bn, Primitive as br, tiktok as bt, BetterAuthClientPlugin as c, FigmaOptions as cn, createAdapterFactory as cr, vk as ct, ClientStore as d, FacebookOptions as dn, AdapterFactoryCustomizeAdapterCreator as dr, salesforce as dt, getGooglePublicKey as en, DBTransactionAdapter as er, LoginType as et, AuthContext as f, FacebookProfile as fn, AdapterFactoryOptions as fr, RobloxOptions as ft, BetterAuthOptions as g, discord as gn, Awaitable as gr, RedditProfile as gt, BetterAuthAdvancedOptions as h, DiscordProfile as hn, CreateCustomAdapter as hr, RedditOptions as ht, createAuthMiddleware as i, microsoft as in, deepmerge as ir, ZoomProfile as it, PolarProfile as j, verifyAccessToken as jn, coreSchema as jr, KickOptions as jt, vercel as k, BetterAuthCookies as kn, User as kr, LinearUser as kt, ClientAtomListener as l, FigmaProfile as ln, AdapterConfig as lr, SalesforceOptions as lt, InternalAdapter as m, DiscordOptions as mn, CreateAdapterOptions as mr, roblox as mt, AuthMiddleware as n, MicrosoftEntraIDProfile as nn, JoinOption as nr, PronounOption as nt, StandardSchemaV1$1 as o, GithubProfile as on, AdapterFactory as or, VkOption as ot, GenericEndpointContext as p, facebook as pn, AdapterTestDebugLogs as pr, RobloxProfile as pt, KakaoOptions as q, CleanedWhere as qn, SecondaryStorage as qr, SlackProfile as qt, createAuthEndpoint as r, MicrosoftOptions as rn, Where as rr, ZoomOptions as rt, BetterAuthClientOptions as s, github as sn, createAdapter as sr, VkProfile as st, AuthEndpoint as t, google as tn, JoinConfig as tr, PhoneNumber as tt, ClientFetchOption as u, figma as un, AdapterFactoryConfig as ur, SalesforceProfile as ut, GenerateIdFn as v, CognitoProfile as vn, LiteralUnion as vr, TiktokOptions as vt, SocialProviders as w, AppleNonConformUser as wn, initGetFieldAttributes as wr, LinkedInOptions as wt, SocialProvider as x, AtlassianOptions as xn, initGetModelName as xr, GitlabOptions as xt, BetterAuthPlugin as y, cognito as yn, Prettify as yr, TiktokProfile as yt, paybin as z, refreshAccessToken as zn, getAuthTables as zr, twitter as zt };
8054
+ export { NotionOptions as $, DBAdapterDebugLogOption as $n, HuggingFaceProfile as $t, VercelOptions as A, apple as An, Verification as Ar, LinearOptions as At, PaybinOptions as B, getOAuth2Tokens as Bn, accountSchema as Br, TwitterOption as Bt, HookEndpointContext as C, getCognitoPublicKey as Cn, Primitive as Cr, tiktok as Ct, SocialProviders as D, AppleNonConformUser as Dn, initGetFieldAttributes as Dr, LinkedInOptions as Dt, SocialProviderListEnum as E, atlassian as En, initGetFieldName as Er, gitlab as Et, polar as F, verifyJwsAccessToken as Fn, Session as Fr, KickProfile as Ft, LineUserInfo as G, createClientCredentialsTokenRequest as Gn, DBFieldAttribute as Gr, twitch as Gt, paybin as H, refreshAccessToken as Hn, getAuthTables as Hr, twitter as Ht, PayPalOptions as I, createAuthorizationCodeRequest as In, sessionSchema as Ir, kick as It, NaverProfile as J, OAuthProvider as Jn, DBPrimitive as Jr, spotify as Jt, line as K, OAuth2Tokens as Kn, DBFieldAttributeConfig as Kr, SpotifyOptions as Kt, PayPalProfile as L, validateAuthorizationCode as Ln, RateLimit as Lr, DropboxOptions as Lt, vercel as M, BetterAuthCookies as Mn, User as Mr, LinearUser as Mt, PolarOptions as N, getJwks as Nn, userSchema as Nr, linear as Nt, socialProviderList as O, AppleOptions as On, initGetDefaultModelName as Or, LinkedInProfile as Ot, PolarProfile as P, verifyAccessToken as Pn, coreSchema as Pr, KickOptions as Pt, kakao as Q, DBAdapter as Qn, HuggingFaceOptions as Qt, PayPalTokenResponse as R, validateToken as Rn, rateLimitSchema as Rr, DropboxProfile as Rt, BetterAuthPlugin as S, cognito as Sn, Prettify as Sr, TiktokProfile as St, SocialProviderList as T, AtlassianProfile as Tn, initGetIdField as Tr, GitlabProfile as Tt, LineIdTokenPayload as U, createAuthorizationURL as Un, BaseModelNames as Ur, TwitchOptions as Ut, PaybinProfile as V, createRefreshAccessTokenRequest as Vn, BetterAuthPluginDBSchema as Vr, TwitterProfile as Vt, LineOptions as W, clientCredentialsToken as Wn, BetterAuthDBSchema as Wr, TwitchProfile as Wt, KakaoOptions as X, CleanedWhere as Xn, SecondaryStorage as Xr, SlackProfile as Xt, naver as Y, ProviderOptions as Yn, ModelNames as Yr, SlackOptions as Yt, KakaoProfile as Z, CustomAdapter as Zn, slack as Zt, PluginContext as _, DiscordOptions as _n, CreateAdapterOptions as _r, roblox as _t, optionsMiddleware as a, MicrosoftEntraIDProfile as an, JoinOption as ar, PronounOption as at, BetterAuthRateLimitOptions as b, CognitoOptions as bn, LiteralString as br, reddit as bt, BetterAuthClientPlugin as c, GithubOptions as cn, withApplyDefault as cr, zoom as ct, ClientStore as d, FigmaOptions as dn, createAdapterFactory as dr, vk as dt, huggingface as en, DBAdapterFactoryConfig as er, NotionProfile as et, AuthContext as f, FigmaProfile as fn, AdapterConfig as fr, SalesforceOptions as ft, InternalAdapter as g, facebook as gn, AdapterTestDebugLogs as gr, RobloxProfile as gt, GenericEndpointContext as h, FacebookProfile as hn, AdapterFactoryOptions as hr, RobloxOptions as ht, createAuthMiddleware as i, google as in, JoinConfig as ir, PhoneNumber as it, VercelProfile as j, getApplePublicKey as jn, verificationSchema as jr, LinearProfile as jt, socialProviders as k, AppleProfile as kn, initGetDefaultFieldName as kr, linkedin as kt, ClientAtomListener as l, GithubProfile as ln, AdapterFactory as lr, VkOption as lt, BetterAuthPluginRegistryIdentifier as m, FacebookOptions as mn, AdapterFactoryCustomizeAdapterCreator as mr, salesforce as mt, AuthMiddleware as n, GoogleProfile as nn, DBAdapterSchemaCreation as nr, AccountStatus as nt, StandardSchemaV1$1 as o, MicrosoftOptions as on, Where as or, ZoomOptions as ot, BetterAuthPluginRegistry as p, figma as pn, AdapterFactoryConfig as pr, SalesforceProfile as pt, NaverOptions as q, OAuth2UserInfo as qn, DBFieldType as qr, SpotifyProfile as qt, createAuthEndpoint as r, getGooglePublicKey as rn, DBTransactionAdapter as rr, LoginType as rt, BetterAuthClientOptions as s, microsoft as sn, deepmerge as sr, ZoomProfile as st, AuthEndpoint as t, GoogleOptions as tn, DBAdapterInstance as tr, notion as tt, ClientFetchOption as u, github as un, createAdapter as ur, VkProfile as ut, BetterAuthAdvancedOptions as v, DiscordProfile as vn, CreateCustomAdapter as vr, RedditOptions as vt, SocialProvider as w, AtlassianOptions as wn, initGetModelName as wr, GitlabOptions as wt, GenerateIdFn as x, CognitoProfile as xn, LiteralUnion as xr, TiktokOptions as xt, BetterAuthOptions as y, discord as yn, Awaitable as yr, RedditProfile as yt, paypal as z, generateCodeChallenge as zn, Account as zr, dropbox as zt };
package/dist/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { _ as BetterAuthRateLimitOptions, _r as LiteralString, b as HookEndpointContext, br as Primitive, c as BetterAuthClientPlugin, d as ClientStore, f as AuthContext, g as BetterAuthOptions, gr as Awaitable, h as BetterAuthAdvancedOptions, kn as BetterAuthCookies, l as ClientAtomListener, m as InternalAdapter, o as StandardSchemaV1, p as GenericEndpointContext, s as BetterAuthClientOptions, u as ClientFetchOption, v as GenerateIdFn, vr as LiteralUnion, y as BetterAuthPlugin, yr as Prettify } from "./index-BpRqx5_q.mjs";
2
- export { AuthContext, Awaitable, BetterAuthAdvancedOptions, BetterAuthClientOptions, BetterAuthClientPlugin, BetterAuthCookies, BetterAuthOptions, BetterAuthPlugin, BetterAuthRateLimitOptions, ClientAtomListener, ClientFetchOption, ClientStore, GenerateIdFn, GenericEndpointContext, HookEndpointContext, InternalAdapter, LiteralString, LiteralUnion, Prettify, Primitive, StandardSchemaV1 };
1
+ import { C as HookEndpointContext, Cr as Primitive, Mn as BetterAuthCookies, S as BetterAuthPlugin, Sr as Prettify, _ as PluginContext, b as BetterAuthRateLimitOptions, br as LiteralString, c as BetterAuthClientPlugin, d as ClientStore, f as AuthContext, g as InternalAdapter, h as GenericEndpointContext, l as ClientAtomListener, m as BetterAuthPluginRegistryIdentifier, o as StandardSchemaV1, p as BetterAuthPluginRegistry, s as BetterAuthClientOptions, u as ClientFetchOption, v as BetterAuthAdvancedOptions, x as GenerateIdFn, xr as LiteralUnion, y as BetterAuthOptions, yr as Awaitable } from "./index-B5x_W0dM.mjs";
2
+ export { AuthContext, Awaitable, BetterAuthAdvancedOptions, BetterAuthClientOptions, BetterAuthClientPlugin, BetterAuthCookies, BetterAuthOptions, BetterAuthPlugin, BetterAuthPluginRegistry, BetterAuthPluginRegistryIdentifier, BetterAuthRateLimitOptions, ClientAtomListener, ClientFetchOption, ClientStore, GenerateIdFn, GenericEndpointContext, HookEndpointContext, InternalAdapter, LiteralString, LiteralUnion, PluginContext, Prettify, Primitive, StandardSchemaV1 };
@@ -1,2 +1,2 @@
1
- import { An as getJwks, Bn as createAuthorizationURL, Fn as validateToken, Gn as OAuthProvider, Hn as createClientCredentialsTokenRequest, In as generateCodeChallenge, Kn as ProviderOptions, Ln as getOAuth2Tokens, Mn as verifyJwsAccessToken, Nn as createAuthorizationCodeRequest, Pn as validateAuthorizationCode, Rn as createRefreshAccessTokenRequest, Un as OAuth2Tokens, Vn as clientCredentialsToken, Wn as OAuth2UserInfo, jn as verifyAccessToken, zn as refreshAccessToken } from "../index-BpRqx5_q.mjs";
1
+ import { Bn as getOAuth2Tokens, Fn as verifyJwsAccessToken, Gn as createClientCredentialsTokenRequest, Hn as refreshAccessToken, In as createAuthorizationCodeRequest, Jn as OAuthProvider, Kn as OAuth2Tokens, Ln as validateAuthorizationCode, Nn as getJwks, Pn as verifyAccessToken, Rn as validateToken, Un as createAuthorizationURL, Vn as createRefreshAccessTokenRequest, Wn as clientCredentialsToken, Yn as ProviderOptions, qn as OAuth2UserInfo, zn as generateCodeChallenge } from "../index-B5x_W0dM.mjs";
2
2
  export { OAuth2Tokens, OAuth2UserInfo, OAuthProvider, ProviderOptions, clientCredentialsToken, createAuthorizationCodeRequest, createAuthorizationURL, createClientCredentialsTokenRequest, createRefreshAccessTokenRequest, generateCodeChallenge, getJwks, getOAuth2Tokens, refreshAccessToken, validateAuthorizationCode, validateToken, verifyAccessToken, verifyJwsAccessToken };
@@ -1,2 +1,2 @@
1
- import { $ as AccountStatus, $t as GoogleProfile, A as PolarOptions, At as linear, B as LineIdTokenPayload, Bt as TwitchOptions, C as SocialProviderListEnum, Cn as atlassian, Ct as gitlab, D as VercelOptions, Dn as apple, Dt as LinearOptions, E as socialProviders, En as AppleProfile, Et as linkedin, F as PayPalTokenResponse, Ft as DropboxProfile, G as NaverProfile, Gt as spotify, H as LineUserInfo, Ht as twitch, I as paypal, It as dropbox, J as KakaoProfile, Jt as slack, K as naver, Kt as SlackOptions, L as PaybinOptions, Lt as TwitterOption, M as polar, Mt as KickProfile, N as PayPalOptions, Nt as kick, O as VercelProfile, On as getApplePublicKey, Ot as LinearProfile, P as PayPalProfile, Pt as DropboxOptions, Q as notion, Qt as GoogleOptions, R as PaybinProfile, Rt as TwitterProfile, S as SocialProviderList, Sn as AtlassianProfile, St as GitlabProfile, T as socialProviderList, Tn as AppleOptions, Tt as LinkedInProfile, U as line, Ut as SpotifyOptions, V as LineOptions, Vt as TwitchProfile, W as NaverOptions, Wt as SpotifyProfile, X as NotionOptions, Xt as HuggingFaceProfile, Y as kakao, Yt as HuggingFaceOptions, Z as NotionProfile, Zt as huggingface, _n as CognitoOptions, _t as reddit, an as GithubOptions, at as zoom, bn as getCognitoPublicKey, bt as tiktok, cn as FigmaOptions, ct as vk, dn as FacebookOptions, dt as salesforce, en as getGooglePublicKey, et as LoginType, fn as FacebookProfile, ft as RobloxOptions, gn as discord, gt as RedditProfile, hn as DiscordProfile, ht as RedditOptions, in as microsoft, it as ZoomProfile, j as PolarProfile, jt as KickOptions, k as vercel, kt as LinearUser, ln as FigmaProfile, lt as SalesforceOptions, mn as DiscordOptions, mt as roblox, nn as MicrosoftEntraIDProfile, nt as PronounOption, on as GithubProfile, ot as VkOption, pn as facebook, pt as RobloxProfile, q as KakaoOptions, qt as SlackProfile, rn as MicrosoftOptions, rt as ZoomOptions, sn as github, st as VkProfile, tn as google, tt as PhoneNumber, un as figma, ut as SalesforceProfile, vn as CognitoProfile, vt as TiktokOptions, w as SocialProviders, wn as AppleNonConformUser, wt as LinkedInOptions, x as SocialProvider, xn as AtlassianOptions, xt as GitlabOptions, yn as cognito, yt as TiktokProfile, z as paybin, zt as twitter } from "../index-BpRqx5_q.mjs";
1
+ import { $ as NotionOptions, $t as HuggingFaceProfile, A as VercelOptions, An as apple, At as LinearOptions, B as PaybinOptions, Bt as TwitterOption, Cn as getCognitoPublicKey, Ct as tiktok, D as SocialProviders, Dn as AppleNonConformUser, Dt as LinkedInOptions, E as SocialProviderListEnum, En as atlassian, Et as gitlab, F as polar, Ft as KickProfile, G as LineUserInfo, Gt as twitch, H as paybin, Ht as twitter, I as PayPalOptions, It as kick, J as NaverProfile, Jt as spotify, K as line, Kt as SpotifyOptions, L as PayPalProfile, Lt as DropboxOptions, M as vercel, Mt as LinearUser, N as PolarOptions, Nt as linear, O as socialProviderList, On as AppleOptions, Ot as LinkedInProfile, P as PolarProfile, Pt as KickOptions, Q as kakao, Qt as HuggingFaceOptions, R as PayPalTokenResponse, Rt as DropboxProfile, Sn as cognito, St as TiktokProfile, T as SocialProviderList, Tn as AtlassianProfile, Tt as GitlabProfile, U as LineIdTokenPayload, Ut as TwitchOptions, V as PaybinProfile, Vt as TwitterProfile, W as LineOptions, Wt as TwitchProfile, X as KakaoOptions, Xt as SlackProfile, Y as naver, Yt as SlackOptions, Z as KakaoProfile, Zt as slack, _n as DiscordOptions, _t as roblox, an as MicrosoftEntraIDProfile, at as PronounOption, bn as CognitoOptions, bt as reddit, cn as GithubOptions, ct as zoom, dn as FigmaOptions, dt as vk, en as huggingface, et as NotionProfile, fn as FigmaProfile, ft as SalesforceOptions, gn as facebook, gt as RobloxProfile, hn as FacebookProfile, ht as RobloxOptions, in as google, it as PhoneNumber, j as VercelProfile, jn as getApplePublicKey, jt as LinearProfile, k as socialProviders, kn as AppleProfile, kt as linkedin, ln as GithubProfile, lt as VkOption, mn as FacebookOptions, mt as salesforce, nn as GoogleProfile, nt as AccountStatus, on as MicrosoftOptions, ot as ZoomOptions, pn as figma, pt as SalesforceProfile, q as NaverOptions, qt as SpotifyProfile, rn as getGooglePublicKey, rt as LoginType, sn as microsoft, st as ZoomProfile, tn as GoogleOptions, tt as notion, un as github, ut as VkProfile, vn as DiscordProfile, vt as RedditOptions, w as SocialProvider, wn as AtlassianOptions, wt as GitlabOptions, xn as CognitoProfile, xt as TiktokOptions, yn as discord, yt as RedditProfile, z as paypal, zt as dropbox } from "../index-B5x_W0dM.mjs";
2
2
  export { AccountStatus, AppleNonConformUser, AppleOptions, AppleProfile, AtlassianOptions, AtlassianProfile, CognitoOptions, CognitoProfile, DiscordOptions, DiscordProfile, DropboxOptions, DropboxProfile, FacebookOptions, FacebookProfile, FigmaOptions, FigmaProfile, GithubOptions, GithubProfile, GitlabOptions, GitlabProfile, GoogleOptions, GoogleProfile, HuggingFaceOptions, HuggingFaceProfile, KakaoOptions, KakaoProfile, KickOptions, KickProfile, LineIdTokenPayload, LineOptions, LineUserInfo, LinearOptions, LinearProfile, LinearUser, LinkedInOptions, LinkedInProfile, LoginType, MicrosoftEntraIDProfile, MicrosoftOptions, NaverOptions, NaverProfile, NotionOptions, NotionProfile, PayPalOptions, PayPalProfile, PayPalTokenResponse, PaybinOptions, PaybinProfile, PhoneNumber, PolarOptions, PolarProfile, PronounOption, RedditOptions, RedditProfile, RobloxOptions, RobloxProfile, SalesforceOptions, SalesforceProfile, SlackOptions, SlackProfile, SocialProvider, SocialProviderList, SocialProviderListEnum, SocialProviders, SpotifyOptions, SpotifyProfile, TiktokOptions, TiktokProfile, TwitchOptions, TwitchProfile, TwitterOption, TwitterProfile, VercelOptions, VercelProfile, VkOption, VkProfile, ZoomOptions, ZoomProfile, apple, atlassian, cognito, discord, dropbox, facebook, figma, getApplePublicKey, getCognitoPublicKey, getGooglePublicKey, github, gitlab, google, huggingface, kakao, kick, line, linear, linkedin, microsoft, naver, notion, paybin, paypal, polar, reddit, roblox, salesforce, slack, socialProviderList, socialProviders, spotify, tiktok, twitch, twitter, vercel, vk, zoom };
@@ -1,6 +1,6 @@
1
1
  import { i as logger } from "../env-DbssmzoK.mjs";
2
- import "../utils-s65Fz0OM.mjs";
3
- import { n as BetterAuthError, t as APIError } from "../error-C7mY-p0f.mjs";
2
+ import "../utils-puAL36Bz.mjs";
3
+ import { n as BetterAuthError, t as APIError } from "../error-GNtLPYaS.mjs";
4
4
  import { a as validateAuthorizationCode, c as refreshAccessToken, d as getOAuth2Tokens, l as createAuthorizationURL, u as generateCodeChallenge } from "../oauth2-BjWM15hm.mjs";
5
5
  import * as z from "zod";
6
6
  import { base64 } from "@better-auth/utils/base64";
@@ -1,3 +1,12 @@
1
+ import { t as InternalLogger } from "../index-BRBu0-5h.mjs";
2
+
3
+ //#region src/utils/deprecate.d.ts
4
+
5
+ /**
6
+ * Wraps a function to log a deprecation warning at once.
7
+ */
8
+ declare function deprecate<T extends (...args: any[]) => any>(fn: T, message: string, logger?: InternalLogger): T;
9
+ //#endregion
1
10
  //#region src/utils/error-codes.d.ts
2
11
  type UpperLetter = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z";
3
12
  type SpecialCharacter = "_";
@@ -18,4 +27,4 @@ declare function safeJSONParse<T>(data: unknown): T | null;
18
27
  //#region src/utils/string.d.ts
19
28
  declare function capitalizeFirstLetter(str: string): string;
20
29
  //#endregion
21
- export { capitalizeFirstLetter, defineErrorCodes, generateId, safeJSONParse };
30
+ export { capitalizeFirstLetter, defineErrorCodes, deprecate, generateId, safeJSONParse };
@@ -1,4 +1,4 @@
1
1
  import "../env-DbssmzoK.mjs";
2
- import { i as defineErrorCodes, n as safeJSONParse, r as generateId, t as capitalizeFirstLetter } from "../utils-s65Fz0OM.mjs";
2
+ import { a as deprecate, i as defineErrorCodes, n as safeJSONParse, r as generateId, t as capitalizeFirstLetter } from "../utils-puAL36Bz.mjs";
3
3
 
4
- export { capitalizeFirstLetter, defineErrorCodes, generateId, safeJSONParse };
4
+ export { capitalizeFirstLetter, defineErrorCodes, deprecate, generateId, safeJSONParse };
@@ -1,6 +1,22 @@
1
1
  import { i as logger } from "./env-DbssmzoK.mjs";
2
2
  import { createRandomStringGenerator } from "@better-auth/utils/random";
3
3
 
4
+ //#region src/utils/deprecate.ts
5
+ /**
6
+ * Wraps a function to log a deprecation warning at once.
7
+ */
8
+ function deprecate(fn, message, logger$1) {
9
+ let warned = false;
10
+ return function(...args) {
11
+ if (!warned) {
12
+ (logger$1?.warn ?? console.warn)(`[Deprecation] ${message}`);
13
+ warned = true;
14
+ }
15
+ return fn.apply(this, args);
16
+ };
17
+ }
18
+
19
+ //#endregion
4
20
  //#region src/utils/error-codes.ts
5
21
  function defineErrorCodes(codes) {
6
22
  return Object.fromEntries(Object.entries(codes).map(([key, value]) => [key, {
@@ -44,4 +60,4 @@ function capitalizeFirstLetter(str) {
44
60
  }
45
61
 
46
62
  //#endregion
47
- export { defineErrorCodes as i, safeJSONParse as n, generateId as r, capitalizeFirstLetter as t };
63
+ export { deprecate as a, defineErrorCodes as i, safeJSONParse as n, generateId as r, capitalizeFirstLetter as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@better-auth/core",
3
- "version": "1.5.0-beta.2",
3
+ "version": "1.5.0-beta.4",
4
4
  "description": "The most comprehensive authentication framework for TypeScript.",
5
5
  "type": "module",
6
6
  "repository": {
@@ -114,7 +114,7 @@
114
114
  "devDependencies": {
115
115
  "@better-auth/utils": "0.3.0",
116
116
  "@better-fetch/fetch": "1.1.21",
117
- "better-call": "1.1.7",
117
+ "better-call": "1.1.8",
118
118
  "jose": "^6.1.0",
119
119
  "kysely": "^0.28.5",
120
120
  "nanostores": "^1.0.1",
@@ -127,7 +127,7 @@
127
127
  "peerDependencies": {
128
128
  "@better-auth/utils": "0.3.0",
129
129
  "@better-fetch/fetch": "1.1.21",
130
- "better-call": "1.1.7",
130
+ "better-call": "1.1.8",
131
131
  "jose": "^6.1.0",
132
132
  "kysely": "^0.28.5",
133
133
  "nanostores": "^1.0.1"
@@ -139,6 +139,6 @@
139
139
  "lint:types": "attw --profile esm-only --pack .",
140
140
  "typecheck": "tsc --project tsconfig.json",
141
141
  "test": "vitest",
142
- "coverage": "vitest run --coverage"
142
+ "coverage": "vitest run --coverage --coverage.provider=istanbul"
143
143
  }
144
144
  }
@@ -19,3 +19,32 @@ export {
19
19
  runWithAdapter,
20
20
  runWithTransaction,
21
21
  } from "./transaction";
22
+
23
+ const glo: any =
24
+ typeof globalThis !== "undefined"
25
+ ? globalThis
26
+ : typeof window !== "undefined"
27
+ ? window
28
+ : typeof global !== "undefined"
29
+ ? global
30
+ : {};
31
+
32
+ const importIdentifier = "__ $BETTER_AUTH$ __";
33
+
34
+ if (glo[importIdentifier] === true) {
35
+ /**
36
+ * Dear reader of this message. Please take this seriously.
37
+ *
38
+ * If you see this message, make sure that you only import one version of Better Auth. In many cases,
39
+ * your package manager installs two versions of Better Auth that are used by different packages within your project.
40
+ *
41
+ * This often leads to issues that are hard to debug. We often need to ensure async local storage instance,
42
+ * If you imported different versions of Better Auth, it is impossible for us to
43
+ * do status synchronization per request anymore - which might break the states.
44
+ *
45
+ */
46
+ console.error(
47
+ "Better Auth was already imported. This breaks async local storage instance and will lead to issues!",
48
+ );
49
+ }
50
+ glo[importIdentifier] = true;
@@ -12,10 +12,33 @@ import type { DBAdapter, Where } from "../db/adapter";
12
12
  import type { createLogger } from "../env";
13
13
  import type { OAuthProvider } from "../oauth2";
14
14
  import type { BetterAuthCookies } from "./cookie";
15
+ import type { LiteralString } from "./helper";
15
16
  import type {
16
17
  BetterAuthOptions,
17
18
  BetterAuthRateLimitOptions,
18
19
  } from "./init-options";
20
+ import type { BetterAuthPlugin } from "./plugin";
21
+
22
+ /**
23
+ * Mutators are defined in each plugin
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * declare module "@better-auth/core" {
28
+ * interface BetterAuthPluginRegistry<Auth, Context> {
29
+ * 'jwt': {
30
+ * creator: typeof jwt
31
+ * }
32
+ * }
33
+ * }
34
+ * ```
35
+ */
36
+ // biome-ignore lint/correctness/noUnusedVariables: Auth and Context is used in the declaration merging
37
+ export interface BetterAuthPluginRegistry<Auth, Context> {}
38
+ export type BetterAuthPluginRegistryIdentifier = keyof BetterAuthPluginRegistry<
39
+ unknown,
40
+ unknown
41
+ >;
19
42
 
20
43
  export type GenericEndpointContext<
21
44
  Options extends BetterAuthOptions = BetterAuthOptions,
@@ -159,8 +182,34 @@ type CheckPasswordFn<Options extends BetterAuthOptions = BetterAuthOptions> = (
159
182
  ctx: GenericEndpointContext<Options>,
160
183
  ) => Promise<boolean>;
161
184
 
185
+ export type PluginContext = {
186
+ getPlugin: <ID extends BetterAuthPluginRegistryIdentifier | LiteralString>(
187
+ pluginId: ID,
188
+ ) =>
189
+ | (ID extends BetterAuthPluginRegistryIdentifier
190
+ ? ReturnType<BetterAuthPluginRegistry<unknown, unknown>[ID]["creator"]>
191
+ : BetterAuthPlugin)
192
+ | null;
193
+ /**
194
+ * Checks if a plugin is enabled by its ID.
195
+ *
196
+ * @param pluginId - The ID of the plugin to check
197
+ * @returns `true` if the plugin is enabled, `false` otherwise
198
+ *
199
+ * @example
200
+ * ```ts
201
+ * if (ctx.context.hasPlugin("organization")) {
202
+ * // organization plugin is enabled
203
+ * }
204
+ * ```
205
+ */
206
+ hasPlugin: <ID extends BetterAuthPluginRegistryIdentifier | LiteralString>(
207
+ pluginId: ID,
208
+ ) => boolean;
209
+ };
210
+
162
211
  export type AuthContext<Options extends BetterAuthOptions = BetterAuthOptions> =
163
- {
212
+ PluginContext & {
164
213
  options: Options;
165
214
  appName: string;
166
215
  baseURL: string;
@@ -1,8 +1,11 @@
1
1
  export type { StandardSchemaV1 } from "@standard-schema/spec";
2
2
  export type {
3
3
  AuthContext,
4
+ BetterAuthPluginRegistry,
5
+ BetterAuthPluginRegistryIdentifier,
4
6
  GenericEndpointContext,
5
7
  InternalAdapter,
8
+ PluginContext,
6
9
  } from "./context";
7
10
  export type { BetterAuthCookies } from "./cookie";
8
11
  export type * from "./helper";
@@ -151,17 +151,32 @@ export type BetterAuthAdvancedOptions = {
151
151
  */
152
152
  useSecureCookies?: boolean | undefined;
153
153
  /**
154
- * Disable trusted origins check
154
+ * Disable all CSRF protection.
155
+ *
156
+ * When enabled, this disables:
157
+ * - Origin header validation when cookies are present
158
+ * - Fetch Metadata checks (Sec-Fetch-Site, Sec-Fetch-Mode, Sec-Fetch-Dest)
159
+ * - Cross-site navigation blocking for first-login scenarios
155
160
  *
156
161
  * ⚠︎ This is a security risk and it may expose your application to
157
162
  * CSRF attacks
163
+ *
164
+ * @default false
158
165
  */
159
166
  disableCSRFCheck?: boolean | undefined;
160
167
  /**
161
- * Disable origin check
168
+ * Disable URL validation against trustedOrigins.
169
+ *
170
+ * When enabled, this disables validation of:
171
+ * - callbackURL
172
+ * - redirectTo
173
+ * - errorCallbackURL
174
+ * - newUserCallbackURL
175
+ *
176
+ * ⚠︎ This may allow open redirects and could lead to security
177
+ * vulnerabilities.
162
178
  *
163
- * ⚠︎ This may allow requests from any origin to be processed by
164
- * Better Auth. And could lead to security vulnerabilities.
179
+ * @default false
165
180
  */
166
181
  disableOriginCheck?: boolean | undefined;
167
182
  /**
@@ -478,8 +493,18 @@ export type BetterAuthOptions = {
478
493
  * A function that is called when a user verifies their email
479
494
  * @param user the user that verified their email
480
495
  * @param request the request object
496
+ * @deprecated Use `beforeEmailVerification` or `afterEmailVerification` instead. This will be removed in 1.5
481
497
  */
482
498
  onEmailVerification?: (user: User, request?: Request) => Promise<void>;
499
+ /**
500
+ * A function that is called before a user verifies their email
501
+ * @param user the user that verified their email
502
+ * @param request the request object
503
+ */
504
+ beforeEmailVerification?: (
505
+ user: User,
506
+ request?: Request,
507
+ ) => Promise<void>;
483
508
  /**
484
509
  * A function that is called when a user's email is updated to verified
485
510
  * @param user the user that verified their email
@@ -1002,9 +1027,26 @@ export type BetterAuthOptions = {
1002
1027
  *
1003
1028
  * Trusted origins will be dynamically
1004
1029
  * calculated based on the request.
1030
+ *
1031
+ * @example
1032
+ * ```ts
1033
+ * trustedOrigins: async (request) => {
1034
+ * return [
1035
+ * "https://better-auth.com",
1036
+ * "https://*.better-auth.com",
1037
+ * request.headers.get("x-custom-origin")
1038
+ * ];
1039
+ * }
1040
+ * ```
1041
+ * @returns An array of trusted origins.
1005
1042
  */
1006
1043
  trustedOrigins?:
1007
- | (string[] | ((request?: Request | undefined) => Awaitable<string[]>))
1044
+ | (
1045
+ | string[]
1046
+ | ((
1047
+ request?: Request | undefined,
1048
+ ) => Awaitable<(string | undefined | null)[]>)
1049
+ )
1008
1050
  | undefined;
1009
1051
  /**
1010
1052
  * Rate limiting configuration
@@ -0,0 +1,72 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { deprecate } from "./deprecate";
3
+
4
+ describe("deprecate", () => {
5
+ it("should warn once when called multiple times", () => {
6
+ const warn = vi.fn();
7
+ const logger = { warn } as any;
8
+ const fn = vi.fn();
9
+ const deprecatedFn = deprecate(fn, "test message", logger);
10
+
11
+ deprecatedFn();
12
+ deprecatedFn();
13
+ deprecatedFn();
14
+
15
+ expect(warn).toHaveBeenCalledTimes(1);
16
+ expect(warn).toHaveBeenCalledWith("[Deprecation] test message");
17
+ expect(fn).toHaveBeenCalledTimes(3);
18
+ });
19
+
20
+ it("should use provided logger if available", () => {
21
+ const warn = vi.fn();
22
+ const logger = { warn } as any;
23
+ const fn = vi.fn();
24
+ const deprecatedFn = deprecate(fn, "test message", logger);
25
+
26
+ deprecatedFn();
27
+
28
+ expect(warn).toHaveBeenCalledWith("[Deprecation] test message");
29
+ });
30
+
31
+ it("should fall back to console.warn if no logger provided", () => {
32
+ const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => {});
33
+ const fn = vi.fn();
34
+ const deprecatedFn = deprecate(fn, "test message");
35
+
36
+ deprecatedFn();
37
+
38
+ expect(consoleWarn).toHaveBeenCalledWith("[Deprecation] test message");
39
+ consoleWarn.mockRestore();
40
+ });
41
+
42
+ it("should pass arguments and return value correctly", () => {
43
+ const fn = vi.fn((a: number, b: number) => a + b);
44
+ const deprecatedFn = deprecate(fn, "test message", {
45
+ warn: vi.fn(),
46
+ } as any);
47
+
48
+ const result = deprecatedFn(1, 2);
49
+
50
+ expect(result).toBe(3);
51
+ expect(fn).toHaveBeenCalledWith(1, 2);
52
+ });
53
+
54
+ it("should preserve this context", () => {
55
+ class TestClass {
56
+ value = 10;
57
+ method(a: number) {
58
+ return this.value + a;
59
+ }
60
+ }
61
+
62
+ const instance = new TestClass();
63
+ const originalMethod = instance.method;
64
+ instance.method = deprecate(originalMethod, "test message", {
65
+ warn: vi.fn(),
66
+ } as any);
67
+
68
+ const result = instance.method(5);
69
+
70
+ expect(result).toBe(15);
71
+ });
72
+ });
@@ -0,0 +1,21 @@
1
+ import type { InternalLogger } from "../env";
2
+
3
+ /**
4
+ * Wraps a function to log a deprecation warning at once.
5
+ */
6
+ export function deprecate<T extends (...args: any[]) => any>(
7
+ fn: T,
8
+ message: string,
9
+ logger?: InternalLogger,
10
+ ): T {
11
+ let warned = false;
12
+
13
+ return function (this: any, ...args: Parameters<T>): ReturnType<T> {
14
+ if (!warned) {
15
+ const warn = logger?.warn ?? console.warn;
16
+ warn(`[Deprecation] ${message}`);
17
+ warned = true;
18
+ }
19
+ return fn.apply(this, args);
20
+ } as T;
21
+ }
@@ -1,3 +1,4 @@
1
+ export { deprecate } from "./deprecate";
1
2
  export { defineErrorCodes } from "./error-codes";
2
3
  export { generateId } from "./id";
3
4
  export { safeJSONParse } from "./json";