@better-auth/core 1.3.27 → 1.3.29

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.
Files changed (121) hide show
  1. package/.turbo/turbo-build.log +54 -4
  2. package/build.config.ts +6 -0
  3. package/dist/db/adapter/index.d.cts +13 -23
  4. package/dist/db/adapter/index.d.mts +13 -23
  5. package/dist/db/adapter/index.d.ts +13 -23
  6. package/dist/db/index.cjs +16 -0
  7. package/dist/db/index.d.cts +6 -83
  8. package/dist/db/index.d.mts +6 -83
  9. package/dist/db/index.d.ts +6 -83
  10. package/dist/db/index.mjs +16 -1
  11. package/dist/env/index.cjs +312 -0
  12. package/dist/env/index.d.cts +36 -0
  13. package/dist/env/index.d.mts +36 -0
  14. package/dist/env/index.d.ts +36 -0
  15. package/dist/env/index.mjs +297 -0
  16. package/dist/error/index.cjs +44 -0
  17. package/dist/error/index.d.cts +33 -0
  18. package/dist/error/index.d.mts +33 -0
  19. package/dist/error/index.d.ts +33 -0
  20. package/dist/error/index.mjs +41 -0
  21. package/dist/index.d.cts +156 -101
  22. package/dist/index.d.mts +156 -101
  23. package/dist/index.d.ts +156 -101
  24. package/dist/middleware/index.cjs +25 -0
  25. package/dist/middleware/index.d.cts +13 -0
  26. package/dist/middleware/index.d.mts +13 -0
  27. package/dist/middleware/index.d.ts +13 -0
  28. package/dist/middleware/index.mjs +21 -0
  29. package/dist/oauth2/index.cjs +368 -0
  30. package/dist/oauth2/index.d.cts +100 -0
  31. package/dist/oauth2/index.d.mts +100 -0
  32. package/dist/oauth2/index.d.ts +100 -0
  33. package/dist/oauth2/index.mjs +357 -0
  34. package/dist/shared/core.Bl6TpxyD.d.mts +181 -0
  35. package/dist/shared/core.Bqe5IGAi.d.ts +13 -0
  36. package/dist/shared/core.Bshk2o_x.d.ts +1721 -0
  37. package/dist/shared/core.BwoNUcJQ.d.cts +53 -0
  38. package/dist/shared/core.BwoNUcJQ.d.mts +53 -0
  39. package/dist/shared/core.BwoNUcJQ.d.ts +53 -0
  40. package/dist/shared/core.C6_2xGyf.d.mts +1721 -0
  41. package/dist/shared/{core.CnvFgghY.d.cts → core.CajxAutx.d.cts} +27 -1
  42. package/dist/shared/{core.CnvFgghY.d.mts → core.CajxAutx.d.mts} +27 -1
  43. package/dist/shared/{core.CnvFgghY.d.ts → core.CajxAutx.d.ts} +27 -1
  44. package/dist/shared/core.CfqdiZTu.d.cts +1721 -0
  45. package/dist/shared/core.DkdZ1o38.d.ts +181 -0
  46. package/dist/shared/core.Dl-70uns.d.cts +84 -0
  47. package/dist/shared/core.Dl-70uns.d.mts +84 -0
  48. package/dist/shared/core.Dl-70uns.d.ts +84 -0
  49. package/dist/shared/core.DyEdx0m7.d.cts +181 -0
  50. package/dist/shared/core.E9DfzGLz.d.mts +13 -0
  51. package/dist/shared/core.HqYn20Fi.d.cts +13 -0
  52. package/dist/social-providers/index.cjs +2793 -0
  53. package/dist/social-providers/index.d.cts +3903 -0
  54. package/dist/social-providers/index.d.mts +3903 -0
  55. package/dist/social-providers/index.d.ts +3903 -0
  56. package/dist/social-providers/index.mjs +2743 -0
  57. package/dist/utils/index.cjs +7 -0
  58. package/dist/utils/index.d.cts +10 -0
  59. package/dist/utils/index.d.mts +10 -0
  60. package/dist/utils/index.d.ts +10 -0
  61. package/dist/utils/index.mjs +5 -0
  62. package/package.json +98 -2
  63. package/src/db/adapter/index.ts +424 -0
  64. package/src/db/index.ts +2 -0
  65. package/src/db/schema/rate-limit.ts +21 -0
  66. package/src/db/type.ts +28 -0
  67. package/src/env/color-depth.ts +172 -0
  68. package/src/env/env-impl.ts +124 -0
  69. package/src/env/index.ts +23 -0
  70. package/src/env/logger.test.ts +33 -0
  71. package/src/env/logger.ts +145 -0
  72. package/src/error/codes.ts +31 -0
  73. package/src/error/index.ts +11 -0
  74. package/src/index.ts +0 -2
  75. package/src/middleware/index.ts +33 -0
  76. package/src/oauth2/client-credentials-token.ts +102 -0
  77. package/src/oauth2/create-authorization-url.ts +85 -0
  78. package/src/oauth2/index.ts +22 -0
  79. package/src/oauth2/oauth-provider.ts +194 -0
  80. package/src/oauth2/refresh-access-token.ts +124 -0
  81. package/src/oauth2/utils.ts +36 -0
  82. package/src/oauth2/validate-authorization-code.ts +156 -0
  83. package/src/social-providers/apple.ts +213 -0
  84. package/src/social-providers/atlassian.ts +130 -0
  85. package/src/social-providers/cognito.ts +269 -0
  86. package/src/social-providers/discord.ts +172 -0
  87. package/src/social-providers/dropbox.ts +112 -0
  88. package/src/social-providers/facebook.ts +204 -0
  89. package/src/social-providers/figma.ts +115 -0
  90. package/src/social-providers/github.ts +154 -0
  91. package/src/social-providers/gitlab.ts +152 -0
  92. package/src/social-providers/google.ts +171 -0
  93. package/src/social-providers/huggingface.ts +116 -0
  94. package/src/social-providers/index.ts +118 -0
  95. package/src/social-providers/kakao.ts +178 -0
  96. package/src/social-providers/kick.ts +95 -0
  97. package/src/social-providers/line.ts +169 -0
  98. package/src/social-providers/linear.ts +120 -0
  99. package/src/social-providers/linkedin.ts +110 -0
  100. package/src/social-providers/microsoft-entra-id.ts +243 -0
  101. package/src/social-providers/naver.ts +112 -0
  102. package/src/social-providers/notion.ts +106 -0
  103. package/src/social-providers/paypal.ts +261 -0
  104. package/src/social-providers/reddit.ts +122 -0
  105. package/src/social-providers/roblox.ts +110 -0
  106. package/src/social-providers/salesforce.ts +157 -0
  107. package/src/social-providers/slack.ts +114 -0
  108. package/src/social-providers/spotify.ts +93 -0
  109. package/src/social-providers/tiktok.ts +211 -0
  110. package/src/social-providers/twitch.ts +111 -0
  111. package/src/social-providers/twitter.ts +194 -0
  112. package/src/social-providers/vk.ts +128 -0
  113. package/src/social-providers/zoom.ts +218 -0
  114. package/src/types/context.ts +334 -0
  115. package/src/types/cookie.ts +7 -0
  116. package/src/types/index.ts +19 -1
  117. package/src/types/init-options.ts +1048 -2
  118. package/src/types/plugin-client.ts +69 -0
  119. package/src/types/plugin.ts +134 -0
  120. package/src/utils/error-codes.ts +51 -0
  121. package/src/utils/index.ts +1 -0
@@ -0,0 +1,1721 @@
1
+ import { PostgresPool, MysqlPool, SqliteDatabase, Dialect, Kysely } from 'kysely';
2
+ import * as better_call from 'better-call';
3
+ import { CookieOptions, EndpointContext } from 'better-call';
4
+ import { D as DBFieldAttribute, B as BetterAuthDBSchema, a as LiteralUnion, M as Models, S as SecondaryStorage } from './core.CajxAutx.cjs';
5
+ import { S as Session, U as User, A as Account, V as Verification, R as RateLimit } from './core.Dl-70uns.cjs';
6
+ import { Database } from 'bun:sqlite';
7
+ import { DatabaseSync } from 'node:sqlite';
8
+ import { SocialProviders, SocialProviderList } from '../social-providers/index.cjs';
9
+ import { c as createLogger, L as Logger } from './core.BwoNUcJQ.cjs';
10
+ import { a as OAuthProvider } from './core.DyEdx0m7.cjs';
11
+ import { BetterAuthPlugin } from '@better-auth/core';
12
+
13
+ type DBAdapterDebugLogOption = boolean | {
14
+ /**
15
+ * Useful when you want to log only certain conditions.
16
+ */
17
+ logCondition?: (() => boolean) | undefined;
18
+ create?: boolean;
19
+ update?: boolean;
20
+ updateMany?: boolean;
21
+ findOne?: boolean;
22
+ findMany?: boolean;
23
+ delete?: boolean;
24
+ deleteMany?: boolean;
25
+ count?: boolean;
26
+ } | {
27
+ /**
28
+ * Only used for adapter tests to show debug logs if a test fails.
29
+ *
30
+ * @deprecated Not actually deprecated. Doing this for IDEs to show this option at the very bottom and stop end-users from using this.
31
+ */
32
+ isRunningAdapterTests: boolean;
33
+ };
34
+ type DBAdapterSchemaCreation = {
35
+ /**
36
+ * Code to be inserted into the file
37
+ */
38
+ code: string;
39
+ /**
40
+ * Path to the file, including the file name and extension.
41
+ * Relative paths are supported, with the current working directory of the developer's project as the base.
42
+ */
43
+ path: string;
44
+ /**
45
+ * Append the file if it already exists.
46
+ * Note: This will not apply if `overwrite` is set to true.
47
+ */
48
+ append?: boolean;
49
+ /**
50
+ * Overwrite the file if it already exists
51
+ */
52
+ overwrite?: boolean;
53
+ };
54
+ interface DBAdapterFactoryConfig<Options extends BetterAuthOptions = BetterAuthOptions> {
55
+ /**
56
+ * Use plural table names.
57
+ *
58
+ * All tables will be named with an `s` at the end.
59
+ *
60
+ * @default false
61
+ */
62
+ usePlural?: boolean;
63
+ /**
64
+ * Enable debug logs.
65
+ *
66
+ * @default false
67
+ */
68
+ debugLogs?: DBAdapterDebugLogOption;
69
+ /**
70
+ * Name of the adapter.
71
+ *
72
+ * This is used to identify the adapter in the debug logs.
73
+ *
74
+ * @default `adapterId`
75
+ */
76
+ adapterName?: string;
77
+ /**
78
+ * Adapter id
79
+ */
80
+ adapterId: string;
81
+ /**
82
+ * If the database supports numeric ids, set this to `true`.
83
+ *
84
+ * @default true
85
+ */
86
+ supportsNumericIds?: boolean;
87
+ /**
88
+ * If the database doesn't support JSON columns, set this to `false`.
89
+ *
90
+ * We will handle the translation between using `JSON` columns, and saving `string`s to the database.
91
+ *
92
+ * @default false
93
+ */
94
+ supportsJSON?: boolean;
95
+ /**
96
+ * If the database doesn't support dates, set this to `false`.
97
+ *
98
+ * We will handle the translation between using `Date` objects, and saving `string`s to the database.
99
+ *
100
+ * @default true
101
+ */
102
+ supportsDates?: boolean;
103
+ /**
104
+ * If the database doesn't support booleans, set this to `false`.
105
+ *
106
+ * We will handle the translation between using `boolean`s, and saving `0`s and `1`s to the database.
107
+ *
108
+ * @default true
109
+ */
110
+ supportsBooleans?: boolean;
111
+ /**
112
+ * Execute multiple operations in a transaction.
113
+ *
114
+ * If the database doesn't support transactions, set this to `false` and operations will be executed sequentially.
115
+ *
116
+ * @default false
117
+ */
118
+ transaction?: false | (<R>(callback: (trx: DBTransactionAdapter<Options>) => Promise<R>) => Promise<R>);
119
+ /**
120
+ * Disable id generation for the `create` method.
121
+ *
122
+ * This is useful for databases that don't support custom id values and would auto-generate them for you.
123
+ *
124
+ * @default false
125
+ */
126
+ disableIdGeneration?: boolean;
127
+ /**
128
+ * Map the keys of the input data.
129
+ *
130
+ * This is useful for databases that expect a different key name for a given situation.
131
+ *
132
+ * For example, MongoDB uses `_id` while in Better-Auth we use `id`.
133
+ *
134
+ *
135
+ * @example
136
+ * Each key represents the old key to replace.
137
+ * The value represents the new key
138
+ *
139
+ * This can be a partial object that only transforms some keys.
140
+ *
141
+ * ```ts
142
+ * mapKeysTransformInput: {
143
+ * id: "_id" // We want to replace `id` to `_id` to save into MongoDB
144
+ * }
145
+ * ```
146
+ */
147
+ mapKeysTransformInput?: Record<string, string>;
148
+ /**
149
+ * Map the keys of the output data.
150
+ *
151
+ * This is useful for databases that expect a different key name for a given situation.
152
+ *
153
+ * For example, MongoDB uses `_id` while in Better-Auth we use `id`.
154
+ *
155
+ * @example
156
+ * Each key represents the old key to replace.
157
+ * The value represents the new key
158
+ *
159
+ * This can be a partial object that only transforms some keys.
160
+ *
161
+ * ```ts
162
+ * mapKeysTransformOutput: {
163
+ * _id: "id" // In MongoDB, we save `id` as `_id`. So we want to replace `_id` with `id` when we get the data back.
164
+ * }
165
+ * ```
166
+ */
167
+ mapKeysTransformOutput?: Record<string, string>;
168
+ /**
169
+ * Custom transform input function.
170
+ *
171
+ * This function is used to transform the input data before it is saved to the database.
172
+ */
173
+ customTransformInput?: (props: {
174
+ data: any;
175
+ /**
176
+ * The fields of the model.
177
+ */
178
+ fieldAttributes: DBFieldAttribute;
179
+ /**
180
+ * The field to transform.
181
+ */
182
+ field: string;
183
+ /**
184
+ * The action which was called from the adapter.
185
+ */
186
+ action: "create" | "update";
187
+ /**
188
+ * The model name.
189
+ */
190
+ model: string;
191
+ /**
192
+ * The schema of the user's Better-Auth instance.
193
+ */
194
+ schema: BetterAuthDBSchema;
195
+ /**
196
+ * The options of the user's Better-Auth instance.
197
+ */
198
+ options: Options;
199
+ }) => any;
200
+ /**
201
+ * Custom transform output function.
202
+ *
203
+ * This function is used to transform the output data before it is returned to the user.
204
+ */
205
+ customTransformOutput?: (props: {
206
+ data: any;
207
+ /**
208
+ * The fields of the model.
209
+ */
210
+ fieldAttributes: DBFieldAttribute;
211
+ /**
212
+ * The field to transform.
213
+ */
214
+ field: string;
215
+ /**
216
+ * The fields to select.
217
+ */
218
+ select: string[];
219
+ /**
220
+ * The model name.
221
+ */
222
+ model: string;
223
+ /**
224
+ * The schema of the user's Better-Auth instance.
225
+ */
226
+ schema: BetterAuthDBSchema;
227
+ /**
228
+ * The options of the user's Better-Auth instance.
229
+ */
230
+ options: Options;
231
+ }) => any;
232
+ /**
233
+ * Custom ID generator function.
234
+ *
235
+ * By default, we can handle ID generation for you, however if the database your adapter is for only supports a specific custom id generation,
236
+ * then you can use this function to generate your own IDs.
237
+ *
238
+ *
239
+ * Notes:
240
+ * - If the user enabled `useNumberId`, then this option will be ignored. Unless this adapter config has `supportsNumericIds` set to `false`.
241
+ * - If `generateId` is `false` in the user's Better-Auth config, then this option will be ignored.
242
+ * - If `generateId` is a function, then it will override this option.
243
+ *
244
+ * @example
245
+ *
246
+ * ```ts
247
+ * customIdGenerator: ({ model }) => {
248
+ * return "my-super-unique-id";
249
+ * }
250
+ * ```
251
+ */
252
+ customIdGenerator?: (props: {
253
+ model: string;
254
+ }) => string;
255
+ /**
256
+ * Whether to disable the transform output.
257
+ * Do not use this option unless you know what you are doing.
258
+ * @default false
259
+ */
260
+ disableTransformOutput?: boolean;
261
+ /**
262
+ * Whether to disable the transform input.
263
+ * Do not use this option unless you know what you are doing.
264
+ * @default false
265
+ */
266
+ disableTransformInput?: boolean;
267
+ }
268
+ type Where = {
269
+ /**
270
+ * @default eq
271
+ */
272
+ operator?: "eq" | "ne" | "lt" | "lte" | "gt" | "gte" | "in" | "not_in" | "contains" | "starts_with" | "ends_with";
273
+ value: string | number | boolean | string[] | number[] | Date | null;
274
+ field: string;
275
+ /**
276
+ * @default AND
277
+ */
278
+ connector?: "AND" | "OR";
279
+ };
280
+ type DBTransactionAdapter<Options extends BetterAuthOptions = BetterAuthOptions> = Omit<DBAdapter<Options>, "transaction">;
281
+ type DBAdapter<Options extends BetterAuthOptions = BetterAuthOptions> = {
282
+ id: string;
283
+ create: <T extends Record<string, any>, R = T>(data: {
284
+ model: string;
285
+ data: Omit<T, "id">;
286
+ select?: string[];
287
+ /**
288
+ * By default, any `id` provided in `data` will be ignored.
289
+ *
290
+ * If you want to force the `id` to be the same as the `data.id`, set this to `true`.
291
+ */
292
+ forceAllowId?: boolean;
293
+ }) => Promise<R>;
294
+ findOne: <T>(data: {
295
+ model: string;
296
+ where: Where[];
297
+ select?: string[];
298
+ }) => Promise<T | null>;
299
+ findMany: <T>(data: {
300
+ model: string;
301
+ where?: Where[];
302
+ limit?: number;
303
+ sortBy?: {
304
+ field: string;
305
+ direction: "asc" | "desc";
306
+ };
307
+ offset?: number;
308
+ }) => Promise<T[]>;
309
+ count: (data: {
310
+ model: string;
311
+ where?: Where[];
312
+ }) => Promise<number>;
313
+ /**
314
+ * ⚠︎ Update may not return the updated data
315
+ * if multiple where clauses are provided
316
+ */
317
+ update: <T>(data: {
318
+ model: string;
319
+ where: Where[];
320
+ update: Record<string, any>;
321
+ }) => Promise<T | null>;
322
+ updateMany: (data: {
323
+ model: string;
324
+ where: Where[];
325
+ update: Record<string, any>;
326
+ }) => Promise<number>;
327
+ delete: <T>(data: {
328
+ model: string;
329
+ where: Where[];
330
+ }) => Promise<void>;
331
+ deleteMany: (data: {
332
+ model: string;
333
+ where: Where[];
334
+ }) => Promise<number>;
335
+ /**
336
+ * Execute multiple operations in a transaction.
337
+ * If the adapter doesn't support transactions, operations will be executed sequentially.
338
+ */
339
+ transaction: <R>(callback: (trx: DBTransactionAdapter<Options>) => Promise<R>) => Promise<R>;
340
+ /**
341
+ *
342
+ * @param options
343
+ * @param file - file path if provided by the user
344
+ */
345
+ createSchema?: (options: Options, file?: string) => Promise<DBAdapterSchemaCreation>;
346
+ options?: {
347
+ adapterConfig: DBAdapterFactoryConfig<Options>;
348
+ } & CustomAdapter["options"];
349
+ };
350
+ type CleanedWhere = Required<Where>;
351
+ interface CustomAdapter {
352
+ create: <T extends Record<string, any>>({ data, model, select, }: {
353
+ model: string;
354
+ data: T;
355
+ select?: string[];
356
+ }) => Promise<T>;
357
+ update: <T>(data: {
358
+ model: string;
359
+ where: CleanedWhere[];
360
+ update: T;
361
+ }) => Promise<T | null>;
362
+ updateMany: (data: {
363
+ model: string;
364
+ where: CleanedWhere[];
365
+ update: Record<string, any>;
366
+ }) => Promise<number>;
367
+ findOne: <T>({ model, where, select, }: {
368
+ model: string;
369
+ where: CleanedWhere[];
370
+ select?: string[];
371
+ }) => Promise<T | null>;
372
+ findMany: <T>({ model, where, limit, sortBy, offset, }: {
373
+ model: string;
374
+ where?: CleanedWhere[];
375
+ limit: number;
376
+ sortBy?: {
377
+ field: string;
378
+ direction: "asc" | "desc";
379
+ };
380
+ offset?: number;
381
+ }) => Promise<T[]>;
382
+ delete: ({ model, where, }: {
383
+ model: string;
384
+ where: CleanedWhere[];
385
+ }) => Promise<void>;
386
+ deleteMany: ({ model, where, }: {
387
+ model: string;
388
+ where: CleanedWhere[];
389
+ }) => Promise<number>;
390
+ count: ({ model, where, }: {
391
+ model: string;
392
+ where?: CleanedWhere[];
393
+ }) => Promise<number>;
394
+ createSchema?: (props: {
395
+ /**
396
+ * The file the user may have passed in to the `generate` command as the expected schema file output path.
397
+ */
398
+ file?: string;
399
+ /**
400
+ * The tables from the user's Better-Auth instance schema.
401
+ */
402
+ tables: BetterAuthDBSchema;
403
+ }) => Promise<DBAdapterSchemaCreation>;
404
+ /**
405
+ * Your adapter's options.
406
+ */
407
+ options?: Record<string, any> | undefined;
408
+ }
409
+ interface DBAdapterInstance<Options extends BetterAuthOptions = BetterAuthOptions> {
410
+ (options: BetterAuthOptions): DBAdapter<Options>;
411
+ }
412
+
413
+ type BetterAuthCookies = {
414
+ sessionToken: {
415
+ name: string;
416
+ options: CookieOptions;
417
+ };
418
+ sessionData: {
419
+ name: string;
420
+ options: CookieOptions;
421
+ };
422
+ dontRememberToken: {
423
+ name: string;
424
+ options: CookieOptions;
425
+ };
426
+ };
427
+
428
+ type GenericEndpointContext<Options extends BetterAuthOptions = BetterAuthOptions> = EndpointContext<string, any> & {
429
+ context: AuthContext<Options>;
430
+ };
431
+ interface InternalAdapter<Options extends BetterAuthOptions = BetterAuthOptions> {
432
+ createOAuthUser(user: Omit<User, "id" | "createdAt" | "updatedAt">, account: Omit<Account, "userId" | "id" | "createdAt" | "updatedAt"> & Partial<Account>, context?: GenericEndpointContext<Options>): Promise<{
433
+ user: User;
434
+ account: Account;
435
+ }>;
436
+ createUser<T extends Record<string, any>>(user: Omit<User, "id" | "createdAt" | "updatedAt" | "emailVerified"> & Partial<User> & Record<string, any>, context?: GenericEndpointContext<Options>, trxAdapter?: DBTransactionAdapter<Options>): Promise<T & User>;
437
+ createAccount<T extends Record<string, any>>(account: Omit<Account, "id" | "createdAt" | "updatedAt"> & Partial<Account> & T, context?: GenericEndpointContext<Options>, trxAdapter?: DBTransactionAdapter<Options>): Promise<T & Account>;
438
+ listSessions(userId: string, trxAdapter?: DBTransactionAdapter<Options>): Promise<Session[]>;
439
+ listUsers(limit?: number, offset?: number, sortBy?: {
440
+ field: string;
441
+ direction: "asc" | "desc";
442
+ }, where?: Where[], trxAdapter?: DBTransactionAdapter<Options>): Promise<User[]>;
443
+ countTotalUsers(where?: Where[], trxAdapter?: DBTransactionAdapter<Options>): Promise<number>;
444
+ deleteUser(userId: string, trxAdapter?: DBTransactionAdapter<Options>): Promise<void>;
445
+ createSession(userId: string, ctx: GenericEndpointContext<Options>, dontRememberMe?: boolean, override?: Partial<Session> & Record<string, any>, overrideAll?: boolean, trxAdapter?: DBTransactionAdapter<Options>): Promise<Session>;
446
+ findSession(token: string, trxAdapter?: DBTransactionAdapter<Options>): Promise<{
447
+ session: Session & Record<string, any>;
448
+ user: User & Record<string, any>;
449
+ } | null>;
450
+ findSessions(sessionTokens: string[], trxAdapter?: DBTransactionAdapter<Options>): Promise<{
451
+ session: Session;
452
+ user: User;
453
+ }[]>;
454
+ updateSession(sessionToken: string, session: Partial<Session> & Record<string, any>, context?: GenericEndpointContext<Options>, trxAdapter?: DBTransactionAdapter<Options>): Promise<Session | null>;
455
+ deleteSession(token: string, trxAdapter?: DBTransactionAdapter<Options>): Promise<void>;
456
+ deleteAccounts(userId: string, trxAdapter?: DBTransactionAdapter<Options>): Promise<void>;
457
+ deleteAccount(accountId: string, trxAdapter?: DBTransactionAdapter<Options>): Promise<void>;
458
+ deleteSessions(userIdOrSessionTokens: string | string[], trxAdapter?: DBTransactionAdapter<Options>): Promise<void>;
459
+ findOAuthUser(email: string, accountId: string, providerId: string, trxAdapter?: DBTransactionAdapter<Options>): Promise<{
460
+ user: User;
461
+ accounts: Account[];
462
+ } | null>;
463
+ findUserByEmail(email: string, options?: {
464
+ includeAccounts: boolean;
465
+ }, trxAdapter?: DBTransactionAdapter<Options>): Promise<{
466
+ user: User;
467
+ accounts: Account[];
468
+ } | null>;
469
+ findUserById(userId: string, trxAdapter?: DBTransactionAdapter<Options>): Promise<User | null>;
470
+ linkAccount(account: Omit<Account, "id" | "createdAt" | "updatedAt"> & Partial<Account>, context?: GenericEndpointContext<Options>, trxAdapter?: DBTransactionAdapter<Options>): Promise<Account>;
471
+ updateUser(userId: string, data: Partial<User> & Record<string, any>, context?: GenericEndpointContext<Options>, trxAdapter?: DBTransactionAdapter<Options>): Promise<any>;
472
+ updateUserByEmail(email: string, data: Partial<User & Record<string, any>>, context?: GenericEndpointContext<Options>, trxAdapter?: DBTransactionAdapter<Options>): Promise<User>;
473
+ updatePassword(userId: string, password: string, context?: GenericEndpointContext<Options>, trxAdapter?: DBTransactionAdapter<Options>): Promise<void>;
474
+ findAccounts(userId: string, trxAdapter?: DBTransactionAdapter<Options>): Promise<Account[]>;
475
+ findAccount(accountId: string, trxAdapter?: DBTransactionAdapter<Options>): Promise<Account | null>;
476
+ findAccountByProviderId(accountId: string, providerId: string, trxAdapter?: DBTransactionAdapter<Options>): Promise<Account | null>;
477
+ findAccountByUserId(userId: string, trxAdapter?: DBTransactionAdapter<Options>): Promise<Account[]>;
478
+ updateAccount(id: string, data: Partial<Account>, context?: GenericEndpointContext<Options>, trxAdapter?: DBTransactionAdapter<Options>): Promise<Account>;
479
+ createVerificationValue(data: Omit<Verification, "createdAt" | "id" | "updatedAt"> & Partial<Verification>, context?: GenericEndpointContext<Options>, trxAdapter?: DBTransactionAdapter<Options>): Promise<Verification>;
480
+ findVerificationValue(identifier: string, trxAdapter?: DBTransactionAdapter<Options>): Promise<Verification | null>;
481
+ deleteVerificationValue(id: string, trxAdapter?: DBTransactionAdapter<Options>): Promise<void>;
482
+ deleteVerificationByIdentifier(identifier: string, trxAdapter?: DBTransactionAdapter<Options>): Promise<void>;
483
+ updateVerificationValue(id: string, data: Partial<Verification>, context?: GenericEndpointContext<Options>, trxAdapter?: DBTransactionAdapter<Options>): Promise<Verification>;
484
+ }
485
+ type CreateCookieGetterFn = (cookieName: string, overrideAttributes?: Partial<CookieOptions>) => {
486
+ name: string;
487
+ attributes: CookieOptions;
488
+ };
489
+ type CheckPasswordFn<Options extends BetterAuthOptions = BetterAuthOptions> = (userId: string, ctx: GenericEndpointContext<Options>) => Promise<boolean>;
490
+ type AuthContext<Options extends BetterAuthOptions = BetterAuthOptions> = {
491
+ options: Options;
492
+ appName: string;
493
+ baseURL: string;
494
+ trustedOrigins: string[];
495
+ oauthConfig?: {
496
+ /**
497
+ * This is dangerous and should only be used in dev or staging environments.
498
+ */
499
+ skipStateCookieCheck?: boolean;
500
+ };
501
+ /**
502
+ * New session that will be set after the request
503
+ * meaning: there is a `set-cookie` header that will set
504
+ * the session cookie. This is the fetched session. And it's set
505
+ * by `setNewSession` method.
506
+ */
507
+ newSession: {
508
+ session: Session & Record<string, any>;
509
+ user: User & Record<string, any>;
510
+ } | null;
511
+ session: {
512
+ session: Session & Record<string, any>;
513
+ user: User & Record<string, any>;
514
+ } | null;
515
+ setNewSession: (session: {
516
+ session: Session & Record<string, any>;
517
+ user: User & Record<string, any>;
518
+ } | null) => void;
519
+ socialProviders: OAuthProvider[];
520
+ authCookies: BetterAuthCookies;
521
+ logger: ReturnType<typeof createLogger>;
522
+ rateLimit: {
523
+ enabled: boolean;
524
+ window: number;
525
+ max: number;
526
+ storage: "memory" | "database" | "secondary-storage";
527
+ } & BetterAuthRateLimitOptions;
528
+ adapter: DBAdapter<Options>;
529
+ internalAdapter: InternalAdapter<Options>;
530
+ createAuthCookie: CreateCookieGetterFn;
531
+ secret: string;
532
+ sessionConfig: {
533
+ updateAge: number;
534
+ expiresIn: number;
535
+ freshAge: number;
536
+ };
537
+ generateId: (options: {
538
+ model: LiteralUnion<Models, string>;
539
+ size?: number;
540
+ }) => string | false;
541
+ secondaryStorage: SecondaryStorage | undefined;
542
+ password: {
543
+ hash: (password: string) => Promise<string>;
544
+ verify: (data: {
545
+ password: string;
546
+ hash: string;
547
+ }) => Promise<boolean>;
548
+ config: {
549
+ minPasswordLength: number;
550
+ maxPasswordLength: number;
551
+ };
552
+ checkPassword: CheckPasswordFn<Options>;
553
+ };
554
+ tables: BetterAuthDBSchema;
555
+ runMigrations: () => Promise<void>;
556
+ publishTelemetry: (event: {
557
+ type: string;
558
+ anonymousId?: string;
559
+ payload: Record<string, any>;
560
+ }) => Promise<void>;
561
+ /**
562
+ * This skips the origin check for all requests.
563
+ *
564
+ * set to true by default for `test` environments and `false`
565
+ * for other environments.
566
+ *
567
+ * It's inferred from the `options.advanced?.disableCSRFCheck`
568
+ * option or `options.advanced?.disableOriginCheck` option.
569
+ *
570
+ * @default false
571
+ */
572
+ skipOriginCheck: boolean;
573
+ /**
574
+ * This skips the CSRF check for all requests.
575
+ *
576
+ * This is inferred from the `options.advanced?.
577
+ * disableCSRFCheck` option.
578
+ *
579
+ * @default false
580
+ */
581
+ skipCSRFCheck: boolean;
582
+ };
583
+
584
+ declare const optionsMiddleware: <InputCtx extends better_call.MiddlewareInputContext<better_call.MiddlewareOptions>>(inputContext: InputCtx) => Promise<AuthContext>;
585
+ declare const createAuthMiddleware: {
586
+ <Options extends better_call.MiddlewareOptions, R>(options: Options, handler: (ctx: better_call.MiddlewareContext<Options, AuthContext & {
587
+ returned?: unknown;
588
+ responseHeaders?: Headers;
589
+ }>) => Promise<R>): (inputContext: better_call.MiddlewareInputContext<Options>) => Promise<R>;
590
+ <Options extends better_call.MiddlewareOptions, R_1>(handler: (ctx: better_call.MiddlewareContext<Options, AuthContext & {
591
+ returned?: unknown;
592
+ responseHeaders?: Headers;
593
+ }>) => Promise<R_1>): (inputContext: better_call.MiddlewareInputContext<Options>) => Promise<R_1>;
594
+ };
595
+ declare const createAuthEndpoint: <Path extends string, Opts extends better_call.EndpointOptions, R>(path: Path, options: Opts, handler: (ctx: better_call.EndpointContext<Path, Opts, AuthContext>) => Promise<R>) => {
596
+ <AsResponse extends boolean = false, ReturnHeaders extends boolean = false>(...inputCtx: better_call.HasRequiredKeys<better_call.InputContext<Path, Opts & {
597
+ use: any[];
598
+ }>> extends true ? [better_call.InferBodyInput<Opts & {
599
+ use: any[];
600
+ }, (Opts & {
601
+ use: any[];
602
+ })["metadata"] extends {
603
+ $Infer: {
604
+ body: infer B;
605
+ };
606
+ } ? B : (Opts & {
607
+ use: any[];
608
+ })["body"] extends better_call.StandardSchemaV1<unknown, unknown> ? better_call.StandardSchemaV1.InferInput<(Opts & {
609
+ use: any[];
610
+ })["body"]> : undefined> & better_call.InferInputMethod<Opts & {
611
+ use: any[];
612
+ }, (Opts & {
613
+ use: any[];
614
+ })["method"] extends any[] ? (Opts & {
615
+ use: any[];
616
+ })["method"][number] : (Opts & {
617
+ use: any[];
618
+ })["method"] extends "*" ? better_call.HTTPMethod : (Opts & {
619
+ use: any[];
620
+ })["method"] | undefined> & better_call.InferQueryInput<Opts & {
621
+ use: any[];
622
+ }, (Opts & {
623
+ use: any[];
624
+ })["metadata"] extends {
625
+ $Infer: {
626
+ query: infer Query;
627
+ };
628
+ } ? Query : (Opts & {
629
+ use: any[];
630
+ })["query"] extends better_call.StandardSchemaV1<unknown, unknown> ? better_call.StandardSchemaV1.InferInput<(Opts & {
631
+ use: any[];
632
+ })["query"]> : Record<string, any> | undefined> & better_call.InferParamInput<Path> & better_call.InferRequestInput<Opts & {
633
+ use: any[];
634
+ }> & better_call.InferHeadersInput<Opts & {
635
+ use: any[];
636
+ }> & {
637
+ asResponse?: boolean;
638
+ returnHeaders?: boolean;
639
+ use?: better_call.Middleware[];
640
+ path?: string;
641
+ } & {
642
+ asResponse?: AsResponse | undefined;
643
+ returnHeaders?: ReturnHeaders | undefined;
644
+ }] : [((better_call.InferBodyInput<Opts & {
645
+ use: any[];
646
+ }, (Opts & {
647
+ use: any[];
648
+ })["metadata"] extends {
649
+ $Infer: {
650
+ body: infer B_1;
651
+ };
652
+ } ? B_1 : (Opts & {
653
+ use: any[];
654
+ })["body"] extends better_call.StandardSchemaV1<unknown, unknown> ? better_call.StandardSchemaV1.InferInput<(Opts & {
655
+ use: any[];
656
+ })["body"]> : undefined> & better_call.InferInputMethod<Opts & {
657
+ use: any[];
658
+ }, (Opts & {
659
+ use: any[];
660
+ })["method"] extends any[] ? (Opts & {
661
+ use: any[];
662
+ })["method"][number] : (Opts & {
663
+ use: any[];
664
+ })["method"] extends "*" ? better_call.HTTPMethod : (Opts & {
665
+ use: any[];
666
+ })["method"] | undefined> & better_call.InferQueryInput<Opts & {
667
+ use: any[];
668
+ }, (Opts & {
669
+ use: any[];
670
+ })["metadata"] extends {
671
+ $Infer: {
672
+ query: infer Query_1;
673
+ };
674
+ } ? Query_1 : (Opts & {
675
+ use: any[];
676
+ })["query"] extends better_call.StandardSchemaV1<unknown, unknown> ? better_call.StandardSchemaV1.InferInput<(Opts & {
677
+ use: any[];
678
+ })["query"]> : Record<string, any> | undefined> & better_call.InferParamInput<Path> & better_call.InferRequestInput<Opts & {
679
+ use: any[];
680
+ }> & better_call.InferHeadersInput<Opts & {
681
+ use: any[];
682
+ }> & {
683
+ asResponse?: boolean;
684
+ returnHeaders?: boolean;
685
+ use?: better_call.Middleware[];
686
+ path?: string;
687
+ } & {
688
+ asResponse?: AsResponse | undefined;
689
+ returnHeaders?: ReturnHeaders | undefined;
690
+ }) | undefined)?]): Promise<[AsResponse] extends [true] ? Response : [ReturnHeaders] extends [true] ? {
691
+ headers: Headers;
692
+ response: R;
693
+ } : R>;
694
+ options: Opts & {
695
+ use: any[];
696
+ };
697
+ path: Path;
698
+ };
699
+ type AuthEndpoint = ReturnType<typeof createAuthEndpoint>;
700
+ type AuthMiddleware = ReturnType<typeof createAuthMiddleware>;
701
+
702
+ type KyselyDatabaseType = "postgres" | "mysql" | "sqlite" | "mssql";
703
+ type OmitId<T extends {
704
+ id: unknown;
705
+ }> = Omit<T, "id">;
706
+ type GenerateIdFn = (options: {
707
+ model: LiteralUnion<Models, string>;
708
+ size?: number;
709
+ }) => string | false;
710
+ type BetterAuthRateLimitOptions = {
711
+ /**
712
+ * By default, rate limiting is only
713
+ * enabled on production.
714
+ */
715
+ enabled?: boolean;
716
+ /**
717
+ * Default window to use for rate limiting. The value
718
+ * should be in seconds.
719
+ *
720
+ * @default 10 seconds
721
+ */
722
+ window?: number;
723
+ /**
724
+ * The default maximum number of requests allowed within the window.
725
+ *
726
+ * @default 100 requests
727
+ */
728
+ max?: number;
729
+ /**
730
+ * Custom rate limit rules to apply to
731
+ * specific paths.
732
+ */
733
+ customRules?: {
734
+ [key: string]: {
735
+ /**
736
+ * The window to use for the custom rule.
737
+ */
738
+ window: number;
739
+ /**
740
+ * The maximum number of requests allowed within the window.
741
+ */
742
+ max: number;
743
+ } | false | ((request: Request) => {
744
+ window: number;
745
+ max: number;
746
+ } | false | Promise<{
747
+ window: number;
748
+ max: number;
749
+ } | false>);
750
+ };
751
+ /**
752
+ * Storage configuration
753
+ *
754
+ * By default, rate limiting is stored in memory. If you passed a
755
+ * secondary storage, rate limiting will be stored in the secondary
756
+ * storage.
757
+ *
758
+ * @default "memory"
759
+ */
760
+ storage?: "memory" | "database" | "secondary-storage";
761
+ /**
762
+ * If database is used as storage, the name of the table to
763
+ * use for rate limiting.
764
+ *
765
+ * @default "rateLimit"
766
+ */
767
+ modelName?: string;
768
+ /**
769
+ * Custom field names for the rate limit table
770
+ */
771
+ fields?: Record<keyof RateLimit, string>;
772
+ /**
773
+ * custom storage configuration.
774
+ *
775
+ * NOTE: If custom storage is used storage
776
+ * is ignored
777
+ */
778
+ customStorage?: {
779
+ get: (key: string) => Promise<RateLimit | undefined>;
780
+ set: (key: string, value: RateLimit) => Promise<void>;
781
+ };
782
+ };
783
+ type BetterAuthAdvancedOptions = {
784
+ /**
785
+ * Ip address configuration
786
+ */
787
+ ipAddress?: {
788
+ /**
789
+ * List of headers to use for ip address
790
+ *
791
+ * Ip address is used for rate limiting and session tracking
792
+ *
793
+ * @example ["x-client-ip", "x-forwarded-for", "cf-connecting-ip"]
794
+ *
795
+ * @default
796
+ * @link https://github.com/better-auth/better-auth/blob/main/packages/better-auth/src/utils/get-request-ip.ts#L8
797
+ */
798
+ ipAddressHeaders?: string[];
799
+ /**
800
+ * Disable ip tracking
801
+ *
802
+ * ⚠︎ This is a security risk and it may expose your application to abuse
803
+ */
804
+ disableIpTracking?: boolean;
805
+ };
806
+ /**
807
+ * Use secure cookies
808
+ *
809
+ * @default false
810
+ */
811
+ useSecureCookies?: boolean;
812
+ /**
813
+ * Disable trusted origins check
814
+ *
815
+ * ⚠︎ This is a security risk and it may expose your application to
816
+ * CSRF attacks
817
+ */
818
+ disableCSRFCheck?: boolean;
819
+ /**
820
+ * Disable origin check
821
+ *
822
+ * ⚠︎ This may allow requests from any origin to be processed by
823
+ * Better Auth. And could lead to security vulnerabilities.
824
+ */
825
+ disableOriginCheck?: boolean;
826
+ /**
827
+ * Configure cookies to be cross subdomains
828
+ */
829
+ crossSubDomainCookies?: {
830
+ /**
831
+ * Enable cross subdomain cookies
832
+ */
833
+ enabled: boolean;
834
+ /**
835
+ * Additional cookies to be shared across subdomains
836
+ */
837
+ additionalCookies?: string[];
838
+ /**
839
+ * The domain to use for the cookies
840
+ *
841
+ * By default, the domain will be the root
842
+ * domain from the base URL.
843
+ */
844
+ domain?: string;
845
+ };
846
+ cookies?: {
847
+ [key: string]: {
848
+ name?: string;
849
+ attributes?: CookieOptions;
850
+ };
851
+ };
852
+ defaultCookieAttributes?: CookieOptions;
853
+ /**
854
+ * Prefix for cookies. If a cookie name is provided
855
+ * in cookies config, this will be overridden.
856
+ *
857
+ * @default
858
+ * ```txt
859
+ * "appName" -> which defaults to "better-auth"
860
+ * ```
861
+ */
862
+ cookiePrefix?: string;
863
+ /**
864
+ * Database configuration.
865
+ */
866
+ database?: {
867
+ /**
868
+ * The default number of records to return from the database
869
+ * when using the `findMany` adapter method.
870
+ *
871
+ * @default 100
872
+ */
873
+ defaultFindManyLimit?: number;
874
+ /**
875
+ * If your database auto increments number ids, set this to `true`.
876
+ *
877
+ * Note: If enabled, we will not handle ID generation (including if you use `generateId`), and it would be expected that your database will provide the ID automatically.
878
+ *
879
+ * @default false
880
+ */
881
+ useNumberId?: boolean;
882
+ /**
883
+ * Custom generateId function.
884
+ *
885
+ * If not provided, random ids will be generated.
886
+ * If set to false, the database's auto generated id will be used.
887
+ */
888
+ generateId?: GenerateIdFn | false;
889
+ };
890
+ /**
891
+ * Custom generateId function.
892
+ *
893
+ * If not provided, random ids will be generated.
894
+ * If set to false, the database's auto generated id will be used.
895
+ *
896
+ * @deprecated Please use `database.generateId` instead. This will be potentially removed in future releases.
897
+ */
898
+ generateId?: GenerateIdFn | false;
899
+ };
900
+ type BetterAuthOptions = {
901
+ /**
902
+ * The name of the application
903
+ *
904
+ * process.env.APP_NAME
905
+ *
906
+ * @default "Better Auth"
907
+ */
908
+ appName?: string;
909
+ /**
910
+ * Base URL for the Better Auth. This is typically the
911
+ * root URL where your application server is hosted.
912
+ * If not explicitly set,
913
+ * the system will check the following environment variable:
914
+ *
915
+ * process.env.BETTER_AUTH_URL
916
+ */
917
+ baseURL?: string;
918
+ /**
919
+ * Base path for the Better Auth. This is typically
920
+ * the path where the
921
+ * Better Auth routes are mounted.
922
+ *
923
+ * @default "/api/auth"
924
+ */
925
+ basePath?: string;
926
+ /**
927
+ * The secret to use for encryption,
928
+ * signing and hashing.
929
+ *
930
+ * By default Better Auth will look for
931
+ * the following environment variables:
932
+ * process.env.BETTER_AUTH_SECRET,
933
+ * process.env.AUTH_SECRET
934
+ * If none of these environment
935
+ * variables are set,
936
+ * it will default to
937
+ * "better-auth-secret-123456789".
938
+ *
939
+ * on production if it's not set
940
+ * it will throw an error.
941
+ *
942
+ * you can generate a good secret
943
+ * using the following command:
944
+ * @example
945
+ * ```bash
946
+ * openssl rand -base64 32
947
+ * ```
948
+ */
949
+ secret?: string;
950
+ /**
951
+ * Database configuration
952
+ */
953
+ database?: PostgresPool | MysqlPool | SqliteDatabase | Dialect | DBAdapterInstance | Database | DatabaseSync | {
954
+ dialect: Dialect;
955
+ type: KyselyDatabaseType;
956
+ /**
957
+ * casing for table names
958
+ *
959
+ * @default "camel"
960
+ */
961
+ casing?: "snake" | "camel";
962
+ /**
963
+ * Enable debug logs for the adapter
964
+ *
965
+ * @default false
966
+ */
967
+ debugLogs?: DBAdapterDebugLogOption;
968
+ /**
969
+ * Whether to execute multiple operations in a transaction.
970
+ * If the database doesn't support transactions,
971
+ * set this to `false` and operations will be executed sequentially.
972
+ * @default true
973
+ */
974
+ transaction?: boolean;
975
+ } | {
976
+ /**
977
+ * Kysely instance
978
+ */
979
+ db: Kysely<any>;
980
+ /**
981
+ * Database type between postgres, mysql and sqlite
982
+ */
983
+ type: KyselyDatabaseType;
984
+ /**
985
+ * casing for table names
986
+ *
987
+ * @default "camel"
988
+ */
989
+ casing?: "snake" | "camel";
990
+ /**
991
+ * Enable debug logs for the adapter
992
+ *
993
+ * @default false
994
+ */
995
+ debugLogs?: DBAdapterDebugLogOption;
996
+ /**
997
+ * Whether to execute multiple operations in a transaction.
998
+ * If the database doesn't support transactions,
999
+ * set this to `false` and operations will be executed sequentially.
1000
+ * @default true
1001
+ */
1002
+ transaction?: boolean;
1003
+ };
1004
+ /**
1005
+ * Secondary storage configuration
1006
+ *
1007
+ * This is used to store session and rate limit data.
1008
+ */
1009
+ secondaryStorage?: SecondaryStorage;
1010
+ /**
1011
+ * Email verification configuration
1012
+ */
1013
+ emailVerification?: {
1014
+ /**
1015
+ * Send a verification email
1016
+ * @param data the data object
1017
+ * @param request the request object
1018
+ */
1019
+ sendVerificationEmail?: (
1020
+ /**
1021
+ * @param user the user to send the
1022
+ * verification email to
1023
+ * @param url the URL to send the verification email to
1024
+ * it contains the token as well
1025
+ * @param token the token to send the verification email to
1026
+ */
1027
+ data: {
1028
+ user: User;
1029
+ url: string;
1030
+ token: string;
1031
+ },
1032
+ /**
1033
+ * The request object
1034
+ */
1035
+ request?: Request) => Promise<void>;
1036
+ /**
1037
+ * Send a verification email automatically
1038
+ * after sign up
1039
+ *
1040
+ * @default false
1041
+ */
1042
+ sendOnSignUp?: boolean;
1043
+ /**
1044
+ * Send a verification email automatically
1045
+ * on sign in when the user's email is not verified
1046
+ *
1047
+ * @default false
1048
+ */
1049
+ sendOnSignIn?: boolean;
1050
+ /**
1051
+ * Auto signin the user after they verify their email
1052
+ */
1053
+ autoSignInAfterVerification?: boolean;
1054
+ /**
1055
+ * Number of seconds the verification token is
1056
+ * valid for.
1057
+ * @default 3600 seconds (1 hour)
1058
+ */
1059
+ expiresIn?: number;
1060
+ /**
1061
+ * A function that is called when a user verifies their email
1062
+ * @param user the user that verified their email
1063
+ * @param request the request object
1064
+ */
1065
+ onEmailVerification?: (user: User, request?: Request) => Promise<void>;
1066
+ /**
1067
+ * A function that is called when a user's email is updated to verified
1068
+ * @param user the user that verified their email
1069
+ * @param request the request object
1070
+ */
1071
+ afterEmailVerification?: (user: User, request?: Request) => Promise<void>;
1072
+ };
1073
+ /**
1074
+ * Email and password authentication
1075
+ */
1076
+ emailAndPassword?: {
1077
+ /**
1078
+ * Enable email and password authentication
1079
+ *
1080
+ * @default false
1081
+ */
1082
+ enabled: boolean;
1083
+ /**
1084
+ * Disable email and password sign up
1085
+ *
1086
+ * @default false
1087
+ */
1088
+ disableSignUp?: boolean;
1089
+ /**
1090
+ * Require email verification before a session
1091
+ * can be created for the user.
1092
+ *
1093
+ * if the user is not verified, the user will not be able to sign in
1094
+ * and on sign in attempts, the user will be prompted to verify their email.
1095
+ */
1096
+ requireEmailVerification?: boolean;
1097
+ /**
1098
+ * The maximum length of the password.
1099
+ *
1100
+ * @default 128
1101
+ */
1102
+ maxPasswordLength?: number;
1103
+ /**
1104
+ * The minimum length of the password.
1105
+ *
1106
+ * @default 8
1107
+ */
1108
+ minPasswordLength?: number;
1109
+ /**
1110
+ * send reset password
1111
+ */
1112
+ sendResetPassword?: (
1113
+ /**
1114
+ * @param user the user to send the
1115
+ * reset password email to
1116
+ * @param url the URL to send the reset password email to
1117
+ * @param token the token to send to the user (could be used instead of sending the url
1118
+ * if you need to redirect the user to custom route)
1119
+ */
1120
+ data: {
1121
+ user: User;
1122
+ url: string;
1123
+ token: string;
1124
+ },
1125
+ /**
1126
+ * The request object
1127
+ */
1128
+ request?: Request) => Promise<void>;
1129
+ /**
1130
+ * Number of seconds the reset password token is
1131
+ * valid for.
1132
+ * @default 1 hour (60 * 60)
1133
+ */
1134
+ resetPasswordTokenExpiresIn?: number;
1135
+ /**
1136
+ * A callback function that is triggered
1137
+ * when a user's password is changed successfully.
1138
+ */
1139
+ onPasswordReset?: (data: {
1140
+ user: User;
1141
+ }, request?: Request) => Promise<void>;
1142
+ /**
1143
+ * Password hashing and verification
1144
+ *
1145
+ * By default Scrypt is used for password hashing and
1146
+ * verification. You can provide your own hashing and
1147
+ * verification function. if you want to use a
1148
+ * different algorithm.
1149
+ */
1150
+ password?: {
1151
+ hash?: (password: string) => Promise<string>;
1152
+ verify?: (data: {
1153
+ hash: string;
1154
+ password: string;
1155
+ }) => Promise<boolean>;
1156
+ };
1157
+ /**
1158
+ * Automatically sign in the user after sign up
1159
+ *
1160
+ * @default true
1161
+ */
1162
+ autoSignIn?: boolean;
1163
+ /**
1164
+ * Whether to revoke all other sessions when resetting password
1165
+ * @default false
1166
+ */
1167
+ revokeSessionsOnPasswordReset?: boolean;
1168
+ };
1169
+ /**
1170
+ * list of social providers
1171
+ */
1172
+ socialProviders?: SocialProviders;
1173
+ /**
1174
+ * List of Better Auth plugins
1175
+ */
1176
+ plugins?: [] | BetterAuthPlugin[];
1177
+ /**
1178
+ * User configuration
1179
+ */
1180
+ user?: {
1181
+ /**
1182
+ * The model name for the user. Defaults to "user".
1183
+ */
1184
+ modelName?: string;
1185
+ /**
1186
+ * Map fields
1187
+ *
1188
+ * @example
1189
+ * ```ts
1190
+ * {
1191
+ * userId: "user_id"
1192
+ * }
1193
+ * ```
1194
+ */
1195
+ fields?: Partial<Record<keyof OmitId<User>, string>>;
1196
+ /**
1197
+ * Additional fields for the user
1198
+ */
1199
+ additionalFields?: {
1200
+ [key: string]: DBFieldAttribute;
1201
+ };
1202
+ /**
1203
+ * Changing email configuration
1204
+ */
1205
+ changeEmail?: {
1206
+ /**
1207
+ * Enable changing email
1208
+ * @default false
1209
+ */
1210
+ enabled: boolean;
1211
+ /**
1212
+ * Send a verification email when the user changes their email.
1213
+ * @param data the data object
1214
+ * @param request the request object
1215
+ */
1216
+ sendChangeEmailVerification?: (data: {
1217
+ user: User;
1218
+ newEmail: string;
1219
+ url: string;
1220
+ token: string;
1221
+ }, request?: Request) => Promise<void>;
1222
+ };
1223
+ /**
1224
+ * User deletion configuration
1225
+ */
1226
+ deleteUser?: {
1227
+ /**
1228
+ * Enable user deletion
1229
+ */
1230
+ enabled?: boolean;
1231
+ /**
1232
+ * Send a verification email when the user deletes their account.
1233
+ *
1234
+ * if this is not set, the user will be deleted immediately.
1235
+ * @param data the data object
1236
+ * @param request the request object
1237
+ */
1238
+ sendDeleteAccountVerification?: (data: {
1239
+ user: User;
1240
+ url: string;
1241
+ token: string;
1242
+ }, request?: Request) => Promise<void>;
1243
+ /**
1244
+ * A function that is called before a user is deleted.
1245
+ *
1246
+ * to interrupt with error you can throw `APIError`
1247
+ */
1248
+ beforeDelete?: (user: User, request?: Request) => Promise<void>;
1249
+ /**
1250
+ * A function that is called after a user is deleted.
1251
+ *
1252
+ * This is useful for cleaning up user data
1253
+ */
1254
+ afterDelete?: (user: User, request?: Request) => Promise<void>;
1255
+ /**
1256
+ * The expiration time for the delete token.
1257
+ *
1258
+ * @default 1 day (60 * 60 * 24) in seconds
1259
+ */
1260
+ deleteTokenExpiresIn?: number;
1261
+ };
1262
+ };
1263
+ session?: {
1264
+ /**
1265
+ * The model name for the session.
1266
+ *
1267
+ * @default "session"
1268
+ */
1269
+ modelName?: string;
1270
+ /**
1271
+ * Map fields
1272
+ *
1273
+ * @example
1274
+ * ```ts
1275
+ * {
1276
+ * userId: "user_id"
1277
+ * }
1278
+ */
1279
+ fields?: Partial<Record<keyof OmitId<Session>, string>>;
1280
+ /**
1281
+ * Expiration time for the session token. The value
1282
+ * should be in seconds.
1283
+ * @default 7 days (60 * 60 * 24 * 7)
1284
+ */
1285
+ expiresIn?: number;
1286
+ /**
1287
+ * How often the session should be refreshed. The value
1288
+ * should be in seconds.
1289
+ * If set 0 the session will be refreshed every time it is used.
1290
+ * @default 1 day (60 * 60 * 24)
1291
+ */
1292
+ updateAge?: number;
1293
+ /**
1294
+ * Disable session refresh so that the session is not updated
1295
+ * regardless of the `updateAge` option.
1296
+ *
1297
+ * @default false
1298
+ */
1299
+ disableSessionRefresh?: boolean;
1300
+ /**
1301
+ * Additional fields for the session
1302
+ */
1303
+ additionalFields?: {
1304
+ [key: string]: DBFieldAttribute;
1305
+ };
1306
+ /**
1307
+ * By default if secondary storage is provided
1308
+ * the session is stored in the secondary storage.
1309
+ *
1310
+ * Set this to true to store the session in the database
1311
+ * as well.
1312
+ *
1313
+ * Reads are always done from the secondary storage.
1314
+ *
1315
+ * @default false
1316
+ */
1317
+ storeSessionInDatabase?: boolean;
1318
+ /**
1319
+ * By default, sessions are deleted from the database when secondary storage
1320
+ * is provided when session is revoked.
1321
+ *
1322
+ * Set this to true to preserve session records in the database,
1323
+ * even if they are deleted from the secondary storage.
1324
+ *
1325
+ * @default false
1326
+ */
1327
+ preserveSessionInDatabase?: boolean;
1328
+ /**
1329
+ * Enable caching session in cookie
1330
+ */
1331
+ cookieCache?: {
1332
+ /**
1333
+ * max age of the cookie
1334
+ * @default 5 minutes (5 * 60)
1335
+ */
1336
+ maxAge?: number;
1337
+ /**
1338
+ * Enable caching session in cookie
1339
+ * @default false
1340
+ */
1341
+ enabled?: boolean;
1342
+ };
1343
+ /**
1344
+ * The age of the session to consider it fresh.
1345
+ *
1346
+ * This is used to check if the session is fresh
1347
+ * for sensitive operations. (e.g. deleting an account)
1348
+ *
1349
+ * If the session is not fresh, the user should be prompted
1350
+ * to sign in again.
1351
+ *
1352
+ * If set to 0, the session will be considered fresh every time. (⚠︎ not recommended)
1353
+ *
1354
+ * @default 1 day (60 * 60 * 24)
1355
+ */
1356
+ freshAge?: number;
1357
+ };
1358
+ account?: {
1359
+ /**
1360
+ * The model name for the account. Defaults to "account".
1361
+ */
1362
+ modelName?: string;
1363
+ /**
1364
+ * Map fields
1365
+ */
1366
+ fields?: Partial<Record<keyof OmitId<Account>, string>>;
1367
+ /**
1368
+ * Additional fields for the account
1369
+ */
1370
+ additionalFields?: {
1371
+ [key: string]: DBFieldAttribute;
1372
+ };
1373
+ /**
1374
+ * When enabled (true), the user account data (accessToken, idToken, refreshToken, etc.)
1375
+ * will be updated on sign in with the latest data from the provider.
1376
+ *
1377
+ * @default true
1378
+ */
1379
+ updateAccountOnSignIn?: boolean;
1380
+ /**
1381
+ * Configuration for account linking.
1382
+ */
1383
+ accountLinking?: {
1384
+ /**
1385
+ * Enable account linking
1386
+ *
1387
+ * @default true
1388
+ */
1389
+ enabled?: boolean;
1390
+ /**
1391
+ * List of trusted providers
1392
+ */
1393
+ trustedProviders?: Array<LiteralUnion<SocialProviderList[number] | "email-password", string>>;
1394
+ /**
1395
+ * If enabled (true), this will allow users to manually linking accounts with different email addresses than the main user.
1396
+ *
1397
+ * @default false
1398
+ *
1399
+ * ⚠️ Warning: enabling this might lead to account takeovers, so proceed with caution.
1400
+ */
1401
+ allowDifferentEmails?: boolean;
1402
+ /**
1403
+ * If enabled (true), this will allow users to unlink all accounts.
1404
+ *
1405
+ * @default false
1406
+ */
1407
+ allowUnlinkingAll?: boolean;
1408
+ /**
1409
+ * If enabled (true), this will update the user information based on the newly linked account
1410
+ *
1411
+ * @default false
1412
+ */
1413
+ updateUserInfoOnLink?: boolean;
1414
+ };
1415
+ /**
1416
+ * Encrypt OAuth tokens
1417
+ *
1418
+ * By default, OAuth tokens (access tokens, refresh tokens, ID tokens) are stored in plain text in the database.
1419
+ * This poses a security risk if your database is compromised, as attackers could gain access to user accounts
1420
+ * on external services.
1421
+ *
1422
+ * When enabled, tokens are encrypted using AES-256-GCM before storage, providing protection against:
1423
+ * - Database breaches and unauthorized access to raw token data
1424
+ * - Internal threats from database administrators or compromised credentials
1425
+ * - Token exposure in database backups and logs
1426
+ * @default false
1427
+ */
1428
+ encryptOAuthTokens?: boolean;
1429
+ };
1430
+ /**
1431
+ * Verification configuration
1432
+ */
1433
+ verification?: {
1434
+ /**
1435
+ * Change the modelName of the verification table
1436
+ */
1437
+ modelName?: string;
1438
+ /**
1439
+ * Map verification fields
1440
+ */
1441
+ fields?: Partial<Record<keyof OmitId<Verification>, string>>;
1442
+ /**
1443
+ * disable cleaning up expired values when a verification value is
1444
+ * fetched
1445
+ */
1446
+ disableCleanup?: boolean;
1447
+ };
1448
+ /**
1449
+ * List of trusted origins.
1450
+ */
1451
+ trustedOrigins?: string[] | ((request: Request) => string[] | Promise<string[]>);
1452
+ /**
1453
+ * Rate limiting configuration
1454
+ */
1455
+ rateLimit?: BetterAuthRateLimitOptions;
1456
+ /**
1457
+ * Advanced options
1458
+ */
1459
+ advanced?: BetterAuthAdvancedOptions & {
1460
+ /**
1461
+ * @deprecated Please use `database.generateId` instead.
1462
+ */
1463
+ generateId?: GenerateIdFn | false;
1464
+ };
1465
+ logger?: Logger;
1466
+ /**
1467
+ * allows you to define custom hooks that can be
1468
+ * executed during lifecycle of core database
1469
+ * operations.
1470
+ */
1471
+ databaseHooks?: {
1472
+ /**
1473
+ * User hooks
1474
+ */
1475
+ user?: {
1476
+ create?: {
1477
+ /**
1478
+ * Hook that is called before a user is created.
1479
+ * if the hook returns false, the user will not be created.
1480
+ * If the hook returns an object, it'll be used instead of the original data
1481
+ */
1482
+ before?: (user: User & Record<string, unknown>, context?: GenericEndpointContext) => Promise<boolean | void | {
1483
+ data: Partial<User> & Record<string, any>;
1484
+ }>;
1485
+ /**
1486
+ * Hook that is called after a user is created.
1487
+ */
1488
+ after?: (user: User & Record<string, unknown>, context?: GenericEndpointContext) => Promise<void>;
1489
+ };
1490
+ update?: {
1491
+ /**
1492
+ * Hook that is called before a user is updated.
1493
+ * if the hook returns false, the user will not be updated.
1494
+ * If the hook returns an object, it'll be used instead of the original data
1495
+ */
1496
+ before?: (user: Partial<User> & Record<string, unknown>, context?: GenericEndpointContext) => Promise<boolean | void | {
1497
+ data: Partial<User & Record<string, any>>;
1498
+ }>;
1499
+ /**
1500
+ * Hook that is called after a user is updated.
1501
+ */
1502
+ after?: (user: User & Record<string, unknown>, context?: GenericEndpointContext) => Promise<void>;
1503
+ };
1504
+ delete?: {
1505
+ /**
1506
+ * Hook that is called before a user is deleted.
1507
+ * if the hook returns false, the user will not be deleted.
1508
+ */
1509
+ before?: (user: User & Record<string, unknown>, context?: GenericEndpointContext) => Promise<boolean | void>;
1510
+ /**
1511
+ * Hook that is called after a user is deleted.
1512
+ */
1513
+ after?: (user: User & Record<string, unknown>, context?: GenericEndpointContext) => Promise<void>;
1514
+ };
1515
+ };
1516
+ /**
1517
+ * Session Hook
1518
+ */
1519
+ session?: {
1520
+ create?: {
1521
+ /**
1522
+ * Hook that is called before a session is created.
1523
+ * if the hook returns false, the session will not be created.
1524
+ * If the hook returns an object, it'll be used instead of the original data
1525
+ */
1526
+ before?: (session: Session & Record<string, unknown>, context?: GenericEndpointContext) => Promise<boolean | void | {
1527
+ data: Partial<Session> & Record<string, any>;
1528
+ }>;
1529
+ /**
1530
+ * Hook that is called after a session is created.
1531
+ */
1532
+ after?: (session: Session & Record<string, unknown>, context?: GenericEndpointContext) => Promise<void>;
1533
+ };
1534
+ /**
1535
+ * Update hook
1536
+ */
1537
+ update?: {
1538
+ /**
1539
+ * Hook that is called before a user is updated.
1540
+ * if the hook returns false, the session will not be updated.
1541
+ * If the hook returns an object, it'll be used instead of the original data
1542
+ */
1543
+ before?: (session: Partial<Session> & Record<string, unknown>, context?: GenericEndpointContext) => Promise<boolean | void | {
1544
+ data: Partial<Session & Record<string, any>>;
1545
+ }>;
1546
+ /**
1547
+ * Hook that is called after a session is updated.
1548
+ */
1549
+ after?: (session: Session & Record<string, unknown>, context?: GenericEndpointContext) => Promise<void>;
1550
+ };
1551
+ delete?: {
1552
+ /**
1553
+ * Hook that is called before a session is deleted.
1554
+ * if the hook returns false, the session will not be deleted.
1555
+ */
1556
+ before?: (session: Session & Record<string, unknown>, context?: GenericEndpointContext) => Promise<boolean | void>;
1557
+ /**
1558
+ * Hook that is called after a session is deleted.
1559
+ */
1560
+ after?: (session: Session & Record<string, unknown>, context?: GenericEndpointContext) => Promise<void>;
1561
+ };
1562
+ };
1563
+ /**
1564
+ * Account Hook
1565
+ */
1566
+ account?: {
1567
+ create?: {
1568
+ /**
1569
+ * Hook that is called before a account is created.
1570
+ * If the hook returns false, the account will not be created.
1571
+ * If the hook returns an object, it'll be used instead of the original data
1572
+ */
1573
+ before?: (account: Account, context?: GenericEndpointContext) => Promise<boolean | void | {
1574
+ data: Partial<Account> & Record<string, any>;
1575
+ }>;
1576
+ /**
1577
+ * Hook that is called after a account is created.
1578
+ */
1579
+ after?: (account: Account, context?: GenericEndpointContext) => Promise<void>;
1580
+ };
1581
+ /**
1582
+ * Update hook
1583
+ */
1584
+ update?: {
1585
+ /**
1586
+ * Hook that is called before a account is update.
1587
+ * If the hook returns false, the user will not be updated.
1588
+ * If the hook returns an object, it'll be used instead of the original data
1589
+ */
1590
+ before?: (account: Partial<Account> & Record<string, unknown>, context?: GenericEndpointContext) => Promise<boolean | void | {
1591
+ data: Partial<Account & Record<string, any>>;
1592
+ }>;
1593
+ /**
1594
+ * Hook that is called after a account is updated.
1595
+ */
1596
+ after?: (account: Account & Record<string, unknown>, context?: GenericEndpointContext) => Promise<void>;
1597
+ };
1598
+ delete?: {
1599
+ /**
1600
+ * Hook that is called before an account is deleted.
1601
+ * if the hook returns false, the account will not be deleted.
1602
+ */
1603
+ before?: (account: Account & Record<string, unknown>, context?: GenericEndpointContext) => Promise<boolean | void>;
1604
+ /**
1605
+ * Hook that is called after an account is deleted.
1606
+ */
1607
+ after?: (account: Account & Record<string, unknown>, context?: GenericEndpointContext) => Promise<void>;
1608
+ };
1609
+ };
1610
+ /**
1611
+ * Verification Hook
1612
+ */
1613
+ verification?: {
1614
+ create?: {
1615
+ /**
1616
+ * Hook that is called before a verification is created.
1617
+ * if the hook returns false, the verification will not be created.
1618
+ * If the hook returns an object, it'll be used instead of the original data
1619
+ */
1620
+ before?: (verification: Verification & Record<string, unknown>, context?: GenericEndpointContext) => Promise<boolean | void | {
1621
+ data: Partial<Verification> & Record<string, any>;
1622
+ }>;
1623
+ /**
1624
+ * Hook that is called after a verification is created.
1625
+ */
1626
+ after?: (verification: Verification & Record<string, unknown>, context?: GenericEndpointContext) => Promise<void>;
1627
+ };
1628
+ update?: {
1629
+ /**
1630
+ * Hook that is called before a verification is updated.
1631
+ * if the hook returns false, the verification will not be updated.
1632
+ * If the hook returns an object, it'll be used instead of the original data
1633
+ */
1634
+ before?: (verification: Partial<Verification> & Record<string, unknown>, context?: GenericEndpointContext) => Promise<boolean | void | {
1635
+ data: Partial<Verification & Record<string, any>>;
1636
+ }>;
1637
+ /**
1638
+ * Hook that is called after a verification is updated.
1639
+ */
1640
+ after?: (verification: Verification & Record<string, unknown>, context?: GenericEndpointContext) => Promise<void>;
1641
+ };
1642
+ delete?: {
1643
+ /**
1644
+ * Hook that is called before a verification is deleted.
1645
+ * if the hook returns false, the verification will not be deleted.
1646
+ */
1647
+ before?: (verification: Verification & Record<string, unknown>, context?: GenericEndpointContext) => Promise<boolean | void>;
1648
+ /**
1649
+ * Hook that is called after a verification is deleted.
1650
+ */
1651
+ after?: (verification: Verification & Record<string, unknown>, context?: GenericEndpointContext) => Promise<void>;
1652
+ };
1653
+ };
1654
+ };
1655
+ /**
1656
+ * API error handling
1657
+ */
1658
+ onAPIError?: {
1659
+ /**
1660
+ * Throw an error on API error
1661
+ *
1662
+ * @default false
1663
+ */
1664
+ throw?: boolean;
1665
+ /**
1666
+ * Custom error handler
1667
+ *
1668
+ * @param error
1669
+ * @param ctx - Auth context
1670
+ */
1671
+ onError?: (error: unknown, ctx: AuthContext) => void | Promise<void>;
1672
+ /**
1673
+ * The URL to redirect to on error
1674
+ *
1675
+ * When errorURL is provided, the error will be added to the URL as a query parameter
1676
+ * and the user will be redirected to the errorURL.
1677
+ *
1678
+ * @default - "/api/auth/error"
1679
+ */
1680
+ errorURL?: string;
1681
+ };
1682
+ /**
1683
+ * Hooks
1684
+ */
1685
+ hooks?: {
1686
+ /**
1687
+ * Before a request is processed
1688
+ */
1689
+ before?: AuthMiddleware;
1690
+ /**
1691
+ * After a request is processed
1692
+ */
1693
+ after?: AuthMiddleware;
1694
+ };
1695
+ /**
1696
+ * Disabled paths
1697
+ *
1698
+ * Paths you want to disable.
1699
+ */
1700
+ disabledPaths?: string[];
1701
+ /**
1702
+ * Telemetry configuration
1703
+ */
1704
+ telemetry?: {
1705
+ /**
1706
+ * Enable telemetry collection
1707
+ *
1708
+ * @default false
1709
+ */
1710
+ enabled?: boolean;
1711
+ /**
1712
+ * Enable debug mode
1713
+ *
1714
+ * @default false
1715
+ */
1716
+ debug?: boolean;
1717
+ };
1718
+ };
1719
+
1720
+ export { createAuthMiddleware as l, createAuthEndpoint as m, optionsMiddleware as o };
1721
+ export type { AuthContext as A, BetterAuthOptions as B, CleanedWhere as C, DBAdapterDebugLogOption as D, GenerateIdFn as G, InternalAdapter as I, Where as W, AuthMiddleware as a, BetterAuthAdvancedOptions as b, BetterAuthRateLimitOptions as c, BetterAuthCookies as d, GenericEndpointContext as e, DBAdapterSchemaCreation as f, DBAdapterFactoryConfig as g, DBTransactionAdapter as h, DBAdapter as i, CustomAdapter as j, DBAdapterInstance as k, AuthEndpoint as n };