@depup/better-auth__core 1.6.23-depup.2

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 (310) hide show
  1. package/LICENSE.md +20 -0
  2. package/README.md +32 -0
  3. package/changes.json +14 -0
  4. package/dist/api/index.d.mts +281 -0
  5. package/dist/api/index.mjs +92 -0
  6. package/dist/async_hooks/index.d.mts +6 -0
  7. package/dist/async_hooks/index.mjs +20 -0
  8. package/dist/async_hooks/pure.index.d.mts +6 -0
  9. package/dist/async_hooks/pure.index.mjs +33 -0
  10. package/dist/context/endpoint-context.d.mts +18 -0
  11. package/dist/context/endpoint-context.mjs +29 -0
  12. package/dist/context/global.d.mts +6 -0
  13. package/dist/context/global.mjs +36 -0
  14. package/dist/context/index.d.mts +5 -0
  15. package/dist/context/index.mjs +5 -0
  16. package/dist/context/request-state.d.mts +27 -0
  17. package/dist/context/request-state.mjs +47 -0
  18. package/dist/context/transaction.d.mts +27 -0
  19. package/dist/context/transaction.mjs +96 -0
  20. package/dist/db/adapter/factory.d.mts +17 -0
  21. package/dist/db/adapter/factory.mjs +905 -0
  22. package/dist/db/adapter/get-default-field-name.d.mts +18 -0
  23. package/dist/db/adapter/get-default-field-name.mjs +36 -0
  24. package/dist/db/adapter/get-default-model-name.d.mts +12 -0
  25. package/dist/db/adapter/get-default-model-name.mjs +30 -0
  26. package/dist/db/adapter/get-field-attributes.d.mts +26 -0
  27. package/dist/db/adapter/get-field-attributes.mjs +37 -0
  28. package/dist/db/adapter/get-field-name.d.mts +18 -0
  29. package/dist/db/adapter/get-field-name.mjs +31 -0
  30. package/dist/db/adapter/get-id-field.d.mts +36 -0
  31. package/dist/db/adapter/get-id-field.mjs +64 -0
  32. package/dist/db/adapter/get-model-name.d.mts +12 -0
  33. package/dist/db/adapter/get-model-name.mjs +21 -0
  34. package/dist/db/adapter/index.d.mts +615 -0
  35. package/dist/db/adapter/index.mjs +24 -0
  36. package/dist/db/adapter/types.d.mts +105 -0
  37. package/dist/db/adapter/utils.d.mts +7 -0
  38. package/dist/db/adapter/utils.mjs +37 -0
  39. package/dist/db/get-tables.d.mts +6 -0
  40. package/dist/db/get-tables.mjs +266 -0
  41. package/dist/db/index.d.mts +10 -0
  42. package/dist/db/index.mjs +8 -0
  43. package/dist/db/plugin.d.mts +12 -0
  44. package/dist/db/schema/account.d.mts +28 -0
  45. package/dist/db/schema/account.mjs +17 -0
  46. package/dist/db/schema/rate-limit.d.mts +18 -0
  47. package/dist/db/schema/rate-limit.mjs +9 -0
  48. package/dist/db/schema/session.d.mts +23 -0
  49. package/dist/db/schema/session.mjs +12 -0
  50. package/dist/db/schema/shared.d.mts +10 -0
  51. package/dist/db/schema/shared.mjs +9 -0
  52. package/dist/db/schema/user.d.mts +22 -0
  53. package/dist/db/schema/user.mjs +11 -0
  54. package/dist/db/schema/verification.d.mts +21 -0
  55. package/dist/db/schema/verification.mjs +10 -0
  56. package/dist/db/type.d.mts +194 -0
  57. package/dist/env/color-depth.d.mts +4 -0
  58. package/dist/env/color-depth.mjs +86 -0
  59. package/dist/env/env-impl.d.mts +32 -0
  60. package/dist/env/env-impl.mjs +81 -0
  61. package/dist/env/index.d.mts +4 -0
  62. package/dist/env/index.mjs +4 -0
  63. package/dist/env/logger.d.mts +48 -0
  64. package/dist/env/logger.mjs +79 -0
  65. package/dist/error/codes.d.mts +69 -0
  66. package/dist/error/codes.mjs +55 -0
  67. package/dist/error/index.d.mts +26 -0
  68. package/dist/error/index.mjs +27 -0
  69. package/dist/index.d.mts +9 -0
  70. package/dist/index.mjs +1 -0
  71. package/dist/instrumentation/api.mjs +12 -0
  72. package/dist/instrumentation/attributes.d.mts +11 -0
  73. package/dist/instrumentation/attributes.mjs +10 -0
  74. package/dist/instrumentation/index.d.mts +3 -0
  75. package/dist/instrumentation/index.mjs +3 -0
  76. package/dist/instrumentation/noop.mjs +42 -0
  77. package/dist/instrumentation/pure.index.d.mts +7 -0
  78. package/dist/instrumentation/pure.index.mjs +7 -0
  79. package/dist/instrumentation/tracer.d.mts +13 -0
  80. package/dist/instrumentation/tracer.mjs +53 -0
  81. package/dist/oauth2/client-credentials-token.d.mts +56 -0
  82. package/dist/oauth2/client-credentials-token.mjs +64 -0
  83. package/dist/oauth2/create-authorization-url.d.mts +44 -0
  84. package/dist/oauth2/create-authorization-url.mjs +41 -0
  85. package/dist/oauth2/index.d.mts +8 -0
  86. package/dist/oauth2/index.mjs +7 -0
  87. package/dist/oauth2/oauth-provider.d.mts +192 -0
  88. package/dist/oauth2/refresh-access-token.d.mts +54 -0
  89. package/dist/oauth2/refresh-access-token.mjs +73 -0
  90. package/dist/oauth2/reject-redirects.mjs +60 -0
  91. package/dist/oauth2/utils.d.mts +24 -0
  92. package/dist/oauth2/utils.mjs +48 -0
  93. package/dist/oauth2/validate-authorization-code.d.mts +85 -0
  94. package/dist/oauth2/validate-authorization-code.mjs +86 -0
  95. package/dist/oauth2/verify.d.mts +65 -0
  96. package/dist/oauth2/verify.mjs +202 -0
  97. package/dist/social-providers/apple.d.mts +133 -0
  98. package/dist/social-providers/apple.mjs +117 -0
  99. package/dist/social-providers/atlassian.d.mts +70 -0
  100. package/dist/social-providers/atlassian.mjs +80 -0
  101. package/dist/social-providers/cognito.d.mts +85 -0
  102. package/dist/social-providers/cognito.mjs +162 -0
  103. package/dist/social-providers/discord.d.mts +124 -0
  104. package/dist/social-providers/discord.mjs +62 -0
  105. package/dist/social-providers/dropbox.d.mts +69 -0
  106. package/dist/social-providers/dropbox.mjs +72 -0
  107. package/dist/social-providers/facebook.d.mts +79 -0
  108. package/dist/social-providers/facebook.mjs +157 -0
  109. package/dist/social-providers/figma.d.mts +61 -0
  110. package/dist/social-providers/figma.mjs +83 -0
  111. package/dist/social-providers/github.d.mts +102 -0
  112. package/dist/social-providers/github.mjs +92 -0
  113. package/dist/social-providers/gitlab.d.mts +123 -0
  114. package/dist/social-providers/gitlab.mjs +79 -0
  115. package/dist/social-providers/google.d.mts +123 -0
  116. package/dist/social-providers/google.mjs +137 -0
  117. package/dist/social-providers/huggingface.d.mts +83 -0
  118. package/dist/social-providers/huggingface.mjs +73 -0
  119. package/dist/social-providers/index.d.mts +1834 -0
  120. package/dist/social-providers/index.mjs +78 -0
  121. package/dist/social-providers/kakao.d.mts +161 -0
  122. package/dist/social-providers/kakao.mjs +70 -0
  123. package/dist/social-providers/kick.d.mts +73 -0
  124. package/dist/social-providers/kick.mjs +68 -0
  125. package/dist/social-providers/line.d.mts +105 -0
  126. package/dist/social-providers/line.mjs +110 -0
  127. package/dist/social-providers/linear.d.mts +68 -0
  128. package/dist/social-providers/linear.mjs +85 -0
  129. package/dist/social-providers/linkedin.d.mts +67 -0
  130. package/dist/social-providers/linkedin.mjs +73 -0
  131. package/dist/social-providers/microsoft-entra-id.d.mts +174 -0
  132. package/dist/social-providers/microsoft-entra-id.mjs +152 -0
  133. package/dist/social-providers/naver.d.mts +92 -0
  134. package/dist/social-providers/naver.mjs +65 -0
  135. package/dist/social-providers/notion.d.mts +64 -0
  136. package/dist/social-providers/notion.mjs +72 -0
  137. package/dist/social-providers/paybin.d.mts +71 -0
  138. package/dist/social-providers/paybin.mjs +81 -0
  139. package/dist/social-providers/paypal.d.mts +131 -0
  140. package/dist/social-providers/paypal.mjs +188 -0
  141. package/dist/social-providers/polar.d.mts +74 -0
  142. package/dist/social-providers/polar.mjs +71 -0
  143. package/dist/social-providers/railway.d.mts +65 -0
  144. package/dist/social-providers/railway.mjs +74 -0
  145. package/dist/social-providers/reddit.d.mts +62 -0
  146. package/dist/social-providers/reddit.mjs +81 -0
  147. package/dist/social-providers/roblox.d.mts +70 -0
  148. package/dist/social-providers/roblox.mjs +57 -0
  149. package/dist/social-providers/salesforce.d.mts +79 -0
  150. package/dist/social-providers/salesforce.mjs +87 -0
  151. package/dist/social-providers/slack.d.mts +83 -0
  152. package/dist/social-providers/slack.mjs +66 -0
  153. package/dist/social-providers/spotify.d.mts +63 -0
  154. package/dist/social-providers/spotify.mjs +69 -0
  155. package/dist/social-providers/tiktok.d.mts +168 -0
  156. package/dist/social-providers/tiktok.mjs +60 -0
  157. package/dist/social-providers/twitch.d.mts +79 -0
  158. package/dist/social-providers/twitch.mjs +75 -0
  159. package/dist/social-providers/twitter.d.mts +126 -0
  160. package/dist/social-providers/twitter.mjs +85 -0
  161. package/dist/social-providers/vercel.d.mts +62 -0
  162. package/dist/social-providers/vercel.mjs +58 -0
  163. package/dist/social-providers/vk.d.mts +70 -0
  164. package/dist/social-providers/vk.mjs +81 -0
  165. package/dist/social-providers/wechat.d.mts +113 -0
  166. package/dist/social-providers/wechat.mjs +81 -0
  167. package/dist/social-providers/zoom.d.mts +163 -0
  168. package/dist/social-providers/zoom.mjs +69 -0
  169. package/dist/types/context.d.mts +319 -0
  170. package/dist/types/cookie.d.mts +15 -0
  171. package/dist/types/helper.d.mts +10 -0
  172. package/dist/types/index.d.mts +9 -0
  173. package/dist/types/init-options.d.mts +1430 -0
  174. package/dist/types/plugin-client.d.mts +123 -0
  175. package/dist/types/plugin.d.mts +124 -0
  176. package/dist/types/secret.d.mts +11 -0
  177. package/dist/utils/async.d.mts +22 -0
  178. package/dist/utils/async.mjs +32 -0
  179. package/dist/utils/db.d.mts +9 -0
  180. package/dist/utils/db.mjs +15 -0
  181. package/dist/utils/deprecate.d.mts +9 -0
  182. package/dist/utils/deprecate.mjs +16 -0
  183. package/dist/utils/error-codes.d.mts +13 -0
  184. package/dist/utils/error-codes.mjs +10 -0
  185. package/dist/utils/fetch-metadata.d.mts +4 -0
  186. package/dist/utils/fetch-metadata.mjs +6 -0
  187. package/dist/utils/host.d.mts +147 -0
  188. package/dist/utils/host.mjs +295 -0
  189. package/dist/utils/id.d.mts +4 -0
  190. package/dist/utils/id.mjs +7 -0
  191. package/dist/utils/ip.d.mts +77 -0
  192. package/dist/utils/ip.mjs +230 -0
  193. package/dist/utils/is-api-error.d.mts +6 -0
  194. package/dist/utils/is-api-error.mjs +8 -0
  195. package/dist/utils/json.d.mts +4 -0
  196. package/dist/utils/json.mjs +41 -0
  197. package/dist/utils/redirect-uri.d.mts +20 -0
  198. package/dist/utils/redirect-uri.mjs +48 -0
  199. package/dist/utils/string.d.mts +8 -0
  200. package/dist/utils/string.mjs +25 -0
  201. package/dist/utils/url.d.mts +37 -0
  202. package/dist/utils/url.mjs +61 -0
  203. package/package.json +216 -0
  204. package/src/api/index.ts +185 -0
  205. package/src/async_hooks/index.ts +40 -0
  206. package/src/async_hooks/pure.index.ts +46 -0
  207. package/src/context/endpoint-context.ts +50 -0
  208. package/src/context/global.ts +57 -0
  209. package/src/context/index.ts +23 -0
  210. package/src/context/request-state.ts +91 -0
  211. package/src/context/transaction.ts +169 -0
  212. package/src/db/adapter/factory.ts +1740 -0
  213. package/src/db/adapter/get-default-field-name.ts +59 -0
  214. package/src/db/adapter/get-default-model-name.ts +51 -0
  215. package/src/db/adapter/get-field-attributes.ts +62 -0
  216. package/src/db/adapter/get-field-name.ts +43 -0
  217. package/src/db/adapter/get-id-field.ts +150 -0
  218. package/src/db/adapter/get-model-name.ts +36 -0
  219. package/src/db/adapter/index.ts +656 -0
  220. package/src/db/adapter/types.ts +134 -0
  221. package/src/db/adapter/utils.ts +61 -0
  222. package/src/db/get-tables.ts +304 -0
  223. package/src/db/index.ts +43 -0
  224. package/src/db/plugin.ts +11 -0
  225. package/src/db/schema/account.ts +47 -0
  226. package/src/db/schema/rate-limit.ts +36 -0
  227. package/src/db/schema/session.ts +29 -0
  228. package/src/db/schema/shared.ts +7 -0
  229. package/src/db/schema/user.ts +31 -0
  230. package/src/db/schema/verification.ts +28 -0
  231. package/src/db/type.ts +360 -0
  232. package/src/env/color-depth.ts +172 -0
  233. package/src/env/env-impl.ts +123 -0
  234. package/src/env/index.ts +23 -0
  235. package/src/env/logger.ts +145 -0
  236. package/src/error/codes.ts +72 -0
  237. package/src/error/index.ts +44 -0
  238. package/src/index.ts +1 -0
  239. package/src/instrumentation/api.ts +17 -0
  240. package/src/instrumentation/attributes.ts +22 -0
  241. package/src/instrumentation/index.ts +2 -0
  242. package/src/instrumentation/noop.ts +74 -0
  243. package/src/instrumentation/pure.index.ts +31 -0
  244. package/src/instrumentation/tracer.ts +95 -0
  245. package/src/oauth2/client-credentials-token.ts +126 -0
  246. package/src/oauth2/create-authorization-url.ts +89 -0
  247. package/src/oauth2/index.ts +34 -0
  248. package/src/oauth2/oauth-provider.ts +222 -0
  249. package/src/oauth2/refresh-access-token.ts +157 -0
  250. package/src/oauth2/reject-redirects.ts +70 -0
  251. package/src/oauth2/utils.ts +70 -0
  252. package/src/oauth2/validate-authorization-code.ts +190 -0
  253. package/src/oauth2/verify.ts +408 -0
  254. package/src/social-providers/apple.ts +249 -0
  255. package/src/social-providers/atlassian.ts +133 -0
  256. package/src/social-providers/cognito.ts +281 -0
  257. package/src/social-providers/discord.ts +170 -0
  258. package/src/social-providers/dropbox.ts +112 -0
  259. package/src/social-providers/facebook.ts +288 -0
  260. package/src/social-providers/figma.ts +118 -0
  261. package/src/social-providers/github.ts +184 -0
  262. package/src/social-providers/gitlab.ts +155 -0
  263. package/src/social-providers/google.ts +263 -0
  264. package/src/social-providers/huggingface.ts +119 -0
  265. package/src/social-providers/index.ts +132 -0
  266. package/src/social-providers/kakao.ts +179 -0
  267. package/src/social-providers/kick.ts +109 -0
  268. package/src/social-providers/line.ts +169 -0
  269. package/src/social-providers/linear.ts +121 -0
  270. package/src/social-providers/linkedin.ts +110 -0
  271. package/src/social-providers/microsoft-entra-id.ts +391 -0
  272. package/src/social-providers/naver.ts +113 -0
  273. package/src/social-providers/notion.ts +108 -0
  274. package/src/social-providers/paybin.ts +118 -0
  275. package/src/social-providers/paypal.ts +371 -0
  276. package/src/social-providers/polar.ts +111 -0
  277. package/src/social-providers/railway.ts +100 -0
  278. package/src/social-providers/reddit.ts +126 -0
  279. package/src/social-providers/roblox.ts +112 -0
  280. package/src/social-providers/salesforce.ts +159 -0
  281. package/src/social-providers/slack.ts +112 -0
  282. package/src/social-providers/spotify.ts +94 -0
  283. package/src/social-providers/tiktok.ts +211 -0
  284. package/src/social-providers/twitch.ts +112 -0
  285. package/src/social-providers/twitter.ts +199 -0
  286. package/src/social-providers/vercel.ts +87 -0
  287. package/src/social-providers/vk.ts +125 -0
  288. package/src/social-providers/wechat.ts +220 -0
  289. package/src/social-providers/zoom.ts +230 -0
  290. package/src/types/context.ts +460 -0
  291. package/src/types/cookie.ts +10 -0
  292. package/src/types/helper.ts +27 -0
  293. package/src/types/index.ts +40 -0
  294. package/src/types/init-options.ts +1679 -0
  295. package/src/types/plugin-client.ts +143 -0
  296. package/src/types/plugin.ts +163 -0
  297. package/src/types/secret.ts +8 -0
  298. package/src/utils/async.ts +53 -0
  299. package/src/utils/db.ts +20 -0
  300. package/src/utils/deprecate.ts +21 -0
  301. package/src/utils/error-codes.ts +68 -0
  302. package/src/utils/fetch-metadata.ts +3 -0
  303. package/src/utils/host.ts +416 -0
  304. package/src/utils/id.ts +5 -0
  305. package/src/utils/ip.ts +395 -0
  306. package/src/utils/is-api-error.ts +10 -0
  307. package/src/utils/json.ts +56 -0
  308. package/src/utils/redirect-uri.ts +54 -0
  309. package/src/utils/string.ts +40 -0
  310. package/src/utils/url.ts +77 -0
@@ -0,0 +1,1430 @@
1
+ import { DBFieldAttribute, ModelNames, SecondaryStorage } from "../db/type.mjs";
2
+ import { DBAdapterDebugLogOption, DBAdapterInstance } from "../db/adapter/index.mjs";
3
+ import { BaseRateLimit, RateLimit } from "../db/schema/rate-limit.mjs";
4
+ import { BaseSession, Session } from "../db/schema/session.mjs";
5
+ import { BaseUser, User } from "../db/schema/user.mjs";
6
+ import { BaseVerification, Verification } from "../db/schema/verification.mjs";
7
+ import { Logger } from "../env/logger.mjs";
8
+ import { SocialProviderList, SocialProviders } from "../social-providers/index.mjs";
9
+ import { Awaitable, LiteralString, LiteralUnion } from "./helper.mjs";
10
+ import { BetterAuthPlugin } from "./plugin.mjs";
11
+ import { Account, BaseAccount } from "../db/schema/account.mjs";
12
+ import { AuthContext, GenericEndpointContext } from "./context.mjs";
13
+ import { AuthMiddleware } from "../api/index.mjs";
14
+ import { CookieOptions } from "better-call";
15
+ import { Database } from "bun:sqlite";
16
+ import { DatabaseSync } from "node:sqlite";
17
+ import { D1Database } from "@cloudflare/workers-types";
18
+ import { Dialect, Kysely, MysqlPool, PostgresPool, SqliteDatabase } from "kysely";
19
+
20
+ //#region src/types/init-options.d.ts
21
+ type KyselyDatabaseType = "postgres" | "mysql" | "sqlite" | "mssql";
22
+ type Optional<T> = { [P in keyof T]?: T[P] | undefined };
23
+ type StoreIdentifierOption = "plain" | "hashed" | {
24
+ hash: (identifier: string) => Promise<string>;
25
+ };
26
+ type GenerateIdFn = (options: {
27
+ model: ModelNames;
28
+ size?: number | undefined;
29
+ }) => string | false;
30
+ /**
31
+ * Configuration for dynamic base URL resolution.
32
+ * Allows Better Auth to work with multiple domains (e.g., Vercel preview deployments).
33
+ */
34
+ type DynamicBaseURLConfig = {
35
+ /**
36
+ * List of allowed hostnames. Supports wildcard patterns.
37
+ *
38
+ * The derived host from the request will be validated against this list.
39
+ * Uses the same wildcard matching as `trustedOrigins`.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * allowedHosts: [
44
+ * "myapp.com", // Exact match
45
+ * "*.vercel.app", // Any Vercel preview
46
+ * "preview-*.myapp.com" // Pattern match
47
+ * ]
48
+ * ```
49
+ */
50
+ allowedHosts: string[];
51
+ /**
52
+ * Fallback URL to use if the derived host doesn't match any allowed host.
53
+ * If not set, Better Auth will throw an error when the host doesn't match.
54
+ *
55
+ * @example "https://myapp.com"
56
+ */
57
+ fallback?: string | undefined;
58
+ /**
59
+ * Protocol to use when constructing the URL.
60
+ * - `"https"`: Always use HTTPS (recommended for production)
61
+ * - `"http"`: Always use HTTP (for local development)
62
+ * - `"auto"`: Derive from `x-forwarded-proto` header or default to HTTPS
63
+ *
64
+ * @default "auto"
65
+ */
66
+ protocol?: "http" | "https" | "auto" | undefined;
67
+ };
68
+ /**
69
+ * Base URL configuration.
70
+ * Can be a static string or a dynamic config for multi-domain deployments.
71
+ */
72
+ type BaseURLConfig = string | DynamicBaseURLConfig;
73
+ interface BetterAuthRateLimitStorage {
74
+ get: (key: string) => Promise<RateLimit | null | undefined>;
75
+ set: (key: string, value: RateLimit, update?: boolean | undefined) => Promise<void>;
76
+ /**
77
+ * Atomically records one request against `key` within the `window`
78
+ * (in seconds) and reports whether it is allowed.
79
+ *
80
+ * When `allowed` is true the request was counted within the active window;
81
+ * when `allowed` is false the limit was already reached and `retryAfter` is
82
+ * the number of seconds until the window frees up. Whether the window slides
83
+ * or is fixed depends on the backing storage: the database backend resets
84
+ * once the window elapses, while secondary storage uses a fixed time-to-live
85
+ * set when the window first opens.
86
+ *
87
+ * Performing the check and the increment in a single step closes the
88
+ * concurrent-bypass gap of the separate `get`/`set` path: N simultaneous
89
+ * requests can no longer all pass a stale read before any increment lands.
90
+ *
91
+ * Optional for backwards compatibility. A storage without it falls back to
92
+ * the legacy non-atomic `get`/`set` path, which is best-effort under
93
+ * concurrency.
94
+ *
95
+ * TODO(rate-limit-consume-required): make this the sole required member on
96
+ * `next`, dropping `get`/`set` and the non-atomic fallback.
97
+ */
98
+ consume?: (key: string, rule: {
99
+ window: number;
100
+ max: number;
101
+ }) => Promise<{
102
+ allowed: boolean;
103
+ retryAfter: number | null;
104
+ }>;
105
+ }
106
+ type BetterAuthRateLimitRule = {
107
+ /**
108
+ * Default window to use for rate limiting. The value
109
+ * should be in seconds.
110
+ *
111
+ * @default 10 seconds
112
+ */
113
+ window: number;
114
+ /**
115
+ * The default maximum number of requests allowed within the window.
116
+ *
117
+ * @default 100 requests
118
+ */
119
+ max: number;
120
+ };
121
+ type BetterAuthDBOptions<ModelName extends string, Keys extends string = string> = {
122
+ /**
123
+ * The name of the model. Defaults to the model name.
124
+ */
125
+ modelName?: ModelName | LiteralString;
126
+ /**
127
+ * Map fields to database columns
128
+ */
129
+ fields?: Partial<Record<Exclude<Keys, "id">, string>>;
130
+ /**
131
+ * Additional fields for the model
132
+ */
133
+ additionalFields?: { [Key in Exclude<string, Keys | "id">]: DBFieldAttribute };
134
+ };
135
+ type BetterAuthRateLimitOptions = Optional<BetterAuthRateLimitRule> & Omit<BetterAuthDBOptions<"rateLimit", keyof BaseRateLimit>, "additionalFields"> & {
136
+ /**
137
+ * By default, rate limiting is only
138
+ * enabled on production.
139
+ */
140
+ enabled?: boolean | undefined;
141
+ /**
142
+ * Custom rate limit rules to apply to
143
+ * specific paths.
144
+ */
145
+ customRules?: {
146
+ [key: string]: BetterAuthRateLimitRule | false | ((request: Request, currentRule: BetterAuthRateLimitRule) => Awaitable<false | BetterAuthRateLimitRule>);
147
+ } | undefined;
148
+ /**
149
+ * Storage configuration
150
+ *
151
+ * By default, rate limiting is stored in memory. If you passed a
152
+ * secondary storage, rate limiting will be stored in the secondary
153
+ * storage.
154
+ *
155
+ * @default "memory"
156
+ */
157
+ storage?: ("memory" | "database" | "secondary-storage") | undefined;
158
+ /**
159
+ * custom storage configuration.
160
+ *
161
+ * NOTE: If custom storage is used storage
162
+ * is ignored
163
+ */
164
+ customStorage?: BetterAuthRateLimitStorage;
165
+ };
166
+ type BetterAuthAdvancedOptions = {
167
+ /**
168
+ * Ip address configuration
169
+ */
170
+ ipAddress?: {
171
+ /**
172
+ * List of headers to use for ip address
173
+ *
174
+ * Ip address is used for rate limiting and session tracking
175
+ *
176
+ * @example ["x-client-ip", "x-forwarded-for", "cf-connecting-ip"]
177
+ *
178
+ * @default
179
+ * @link https://github.com/better-auth/better-auth/blob/main/packages/core/src/utils/ip.ts
180
+ */
181
+ ipAddressHeaders?: string[];
182
+ /**
183
+ * Disable ip tracking
184
+ *
185
+ * ⚠︎ This is a security risk and it may expose your application to abuse
186
+ */
187
+ disableIpTracking?: boolean;
188
+ /**
189
+ * IPv6 prefix length used to collapse addresses before rate-limit keying.
190
+ * Any integer from 0 to 128 is accepted; common values are 32, 48, 56, 64, 128.
191
+ * Out-of-range values fall back to safe behavior (negative -> mask all, > 128 -> no mask).
192
+ *
193
+ * @default 64
194
+ */
195
+ ipv6Subnet?: number;
196
+ /**
197
+ * Trusted reverse-proxy IPs or CIDR ranges. When set, a forwarded IP
198
+ * chain is walked right to left, trusted hops are skipped, and the
199
+ * first untrusted address is the client IP. Unset trusts only
200
+ * single-value IP headers. Use the actual address or subnet of your
201
+ * proxies, not a broad private range that also covers clients.
202
+ *
203
+ * This only interprets the forwarded header chain and cannot verify
204
+ * the direct sender. It is safe only when your origin is reachable
205
+ * through these proxies and clients cannot set forwarded headers
206
+ * directly.
207
+ *
208
+ * @example ["192.0.2.10", "10.0.0.0/24"]
209
+ */
210
+ trustedProxies?: string[];
211
+ } | undefined;
212
+ /**
213
+ * Force cookies to always use the `Secure` attribute. By default,
214
+ * cookies are secure in production environments. Set this to `true`
215
+ * to enforce secure cookies in all environments.
216
+ *
217
+ * @default false
218
+ */
219
+ useSecureCookies?: boolean | undefined;
220
+ /**
221
+ * Disable all CSRF protection.
222
+ *
223
+ * When enabled, this disables:
224
+ * - Origin header validation when cookies are present
225
+ * - Fetch Metadata checks (Sec-Fetch-Site, Sec-Fetch-Mode, Sec-Fetch-Dest)
226
+ * - Cross-site navigation blocking for first-login scenarios
227
+ *
228
+ * ⚠︎ This is a security risk and it may expose your application to
229
+ * CSRF attacks
230
+ *
231
+ * @default false
232
+ */
233
+ disableCSRFCheck?: boolean | undefined;
234
+ /**
235
+ * Disable URL validation against trustedOrigins.
236
+ *
237
+ * When enabled, this disables validation of:
238
+ * - callbackURL
239
+ * - redirectTo
240
+ * - errorCallbackURL
241
+ * - newUserCallbackURL
242
+ *
243
+ * ⚠︎ This may allow open redirects and could lead to security
244
+ * vulnerabilities.
245
+ *
246
+ * @default false
247
+ */
248
+ disableOriginCheck?: boolean | undefined;
249
+ /**
250
+ * Configure cookies to be cross subdomains
251
+ */
252
+ crossSubDomainCookies?: {
253
+ /**
254
+ * Enable cross subdomain cookies
255
+ */
256
+ enabled: boolean;
257
+ /**
258
+ * Additional cookies to be shared across subdomains
259
+ */
260
+ additionalCookies?: string[];
261
+ /**
262
+ * The domain to use for the cookies
263
+ *
264
+ * By default, the domain will be the root
265
+ * domain from the base URL.
266
+ */
267
+ domain?: string;
268
+ } | undefined;
269
+ cookies?: {
270
+ [key: string]: {
271
+ name?: string;
272
+ attributes?: CookieOptions;
273
+ };
274
+ } | undefined;
275
+ defaultCookieAttributes?: CookieOptions | undefined;
276
+ /**
277
+ * Prefix for cookies. If a cookie name is provided
278
+ * in cookies config, this will be overridden.
279
+ *
280
+ * @default
281
+ * ```txt
282
+ * "appName" -> which defaults to "better-auth"
283
+ * ```
284
+ */
285
+ cookiePrefix?: string | undefined;
286
+ /**
287
+ * Database configuration.
288
+ */
289
+ database?: {
290
+ /**
291
+ * The default number of records to return from the database
292
+ * when using the `findMany` adapter method.
293
+ *
294
+ * @default 100
295
+ */
296
+ defaultFindManyLimit?: number;
297
+ /**
298
+ * Custom generateId function.
299
+ *
300
+ * If not provided, random ids will be generated.
301
+ * If set to false, the database's auto generated id
302
+ * will be used.
303
+ *
304
+ * If set to "serial", the database's auto generated
305
+ * id will be used.
306
+ *
307
+ * If set to "uuid", we generate a random UUID for
308
+ * the id. If postgres, we use the `gen_random_uuid()
309
+ * ` function. If mysql or mssql, we use the `uuid()`
310
+ * function.
311
+ */
312
+ generateId?: GenerateIdFn | false | "serial" | "uuid";
313
+ } | undefined;
314
+ /**
315
+ * Trusted proxy headers
316
+ *
317
+ * - `x-forwarded-host`
318
+ * - `x-forwarded-proto`
319
+ *
320
+ * If set to `true` and no `baseURL` option is provided, we will use the headers to infer the
321
+ * base URL.
322
+ *
323
+ * ⚠︎ This may expose your application to security vulnerabilities if not
324
+ * used correctly. Please use this with caution.
325
+ */
326
+ trustedProxyHeaders?: boolean | undefined;
327
+ /**
328
+ * Configure background task handling for deferred operations.
329
+ *
330
+ * Background tasks allow non-critical operations (like cleanup, analytics,
331
+ * or timing-attack mitigation) to run after the response is sent.
332
+ *
333
+ * Use `waitUntil` from `@vercel/functions` on Vercel,
334
+ * or `ctx.waitUntil` on Cloudflare Workers.
335
+ *
336
+ * @example
337
+ * // Vercel
338
+ * import { waitUntil } from "@vercel/functions";
339
+ * advanced: { backgroundTasks: { handler: waitUntil } }
340
+ *
341
+ * @example
342
+ * // Cloudflare Workers (with AsyncLocalStorage)
343
+ * advanced: {
344
+ * backgroundTasks: {
345
+ * handler: (p) => execCtxStorage.getStore()?.waitUntil(p)
346
+ * }
347
+ * }
348
+ */
349
+ backgroundTasks?: {
350
+ handler: (promise: Promise<unknown>) => void;
351
+ };
352
+ /**
353
+ * Skip trailing slashes in API routes.
354
+ *
355
+ * When enabled, requests with trailing slashes (e.g., `/api/auth/session/`)
356
+ * will be handled the same as requests without (e.g., `/api/auth/session`).
357
+ *
358
+ * @default false
359
+ */
360
+ skipTrailingSlashes?: boolean;
361
+ };
362
+ type BetterAuthOptions = {
363
+ /**
364
+ * The name of your application. Used as a display name in contexts
365
+ * where your app needs to be identified — for example, as the default
366
+ * issuer name in authenticator apps when users set up 2FA/TOTP.
367
+ *
368
+ * Can also be set via the `APP_NAME` environment variable.
369
+ *
370
+ * @default "Better Auth"
371
+ */
372
+ appName?: string | undefined;
373
+ /**
374
+ * Base URL for the Better Auth. This is typically the
375
+ * root URL where your application server is hosted.
376
+ *
377
+ * Can be configured as:
378
+ * - A static string: `"https://myapp.com"`
379
+ * - A dynamic config with allowed hosts for multi-domain deployments
380
+ *
381
+ * If not explicitly set, the system will check environment variables:
382
+ * `BETTER_AUTH_URL`, `NEXT_PUBLIC_BETTER_AUTH_URL`, etc.
383
+ *
384
+ * @example
385
+ * ```ts
386
+ * // Static URL
387
+ * baseURL: "https://myapp.com"
388
+ *
389
+ * // Dynamic with allowed hosts (for Vercel, multi-domain, etc.)
390
+ * baseURL: {
391
+ * allowedHosts: ["myapp.com", "*.vercel.app", "preview-*.myapp.com"],
392
+ * fallback: "https://myapp.com"
393
+ * }
394
+ * ```
395
+ */
396
+ baseURL?: BaseURLConfig | undefined;
397
+ /**
398
+ * Base path for the Better Auth. This is typically
399
+ * the path where the
400
+ * Better Auth routes are mounted.
401
+ *
402
+ * @default "/api/auth"
403
+ */
404
+ basePath?: string | undefined;
405
+ /**
406
+ * The secret to use for encryption,
407
+ * signing and hashing.
408
+ *
409
+ * By default Better Auth will look for
410
+ * the following environment variables:
411
+ * process.env.BETTER_AUTH_SECRET,
412
+ * process.env.AUTH_SECRET
413
+ * If none of these environment
414
+ * variables are set,
415
+ * it will default to
416
+ * "better-auth-secret-123456789".
417
+ *
418
+ * on production if it's not set
419
+ * it will throw an error.
420
+ *
421
+ * you can generate a good secret
422
+ * using the following command:
423
+ * @example
424
+ * ```bash
425
+ * openssl rand -base64 32
426
+ * ```
427
+ */
428
+ secret?: string | undefined;
429
+ /**
430
+ * Versioned secrets for non-destructive secret rotation.
431
+ * When set, encryption uses an envelope format with key IDs.
432
+ * First entry is the current key used for new encryption.
433
+ * Remaining entries are decryption-only (previous rotations).
434
+ *
435
+ * Can also be set via BETTER_AUTH_SECRETS env var:
436
+ * `BETTER_AUTH_SECRETS=2:base64secret,1:base64secret`
437
+ *
438
+ * When set, `secret` is only used as legacy fallback
439
+ * for decrypting bare-hex payloads that predate the envelope format.
440
+ */
441
+ secrets?: Array<{
442
+ version: number;
443
+ value: string;
444
+ }> | undefined;
445
+ /**
446
+ * Database configuration
447
+ */
448
+ database?: (PostgresPool | MysqlPool | SqliteDatabase | Dialect | DBAdapterInstance | Database | DatabaseSync | D1Database | {
449
+ dialect: Dialect;
450
+ type: KyselyDatabaseType;
451
+ /**
452
+ * casing for table names
453
+ *
454
+ * @default "camel"
455
+ */
456
+ casing?: "snake" | "camel";
457
+ /**
458
+ * Enable debug logs for the adapter
459
+ *
460
+ * @default false
461
+ */
462
+ debugLogs?: DBAdapterDebugLogOption;
463
+ /**
464
+ * Whether to execute multiple operations in a transaction.
465
+ * If the database doesn't support transactions,
466
+ * set this to `false` and operations will be executed sequentially.
467
+ *
468
+ * @default false
469
+ */
470
+ transaction?: boolean;
471
+ } | {
472
+ /**
473
+ * Kysely instance
474
+ */
475
+ db: Kysely<any>;
476
+ /**
477
+ * Database type between postgres, mysql and sqlite
478
+ */
479
+ type: KyselyDatabaseType;
480
+ /**
481
+ * casing for table names
482
+ *
483
+ * @default "camel"
484
+ */
485
+ casing?: "snake" | "camel";
486
+ /**
487
+ * Enable debug logs for the adapter
488
+ *
489
+ * @default false
490
+ */
491
+ debugLogs?: DBAdapterDebugLogOption;
492
+ /**
493
+ * Whether to execute multiple operations in a transaction.
494
+ * If the database doesn't support transactions,
495
+ * set this to `false` and operations will be executed sequentially.
496
+ *
497
+ * @default false
498
+ */
499
+ transaction?: boolean;
500
+ }) | undefined;
501
+ /**
502
+ * Secondary storage configuration
503
+ *
504
+ * This is used to store session and rate limit data.
505
+ */
506
+ secondaryStorage?: SecondaryStorage | undefined;
507
+ /**
508
+ * Email verification configuration
509
+ */
510
+ emailVerification?: {
511
+ /**
512
+ * Send a verification email
513
+ * @param data the data object
514
+ * @param request the request object
515
+ */
516
+ sendVerificationEmail?: (
517
+ /**
518
+ * @param user the user to send the
519
+ * verification email to
520
+ * @param url the URL to send the verification email to
521
+ * it contains the token as well
522
+ * @param token the token to send the verification email to
523
+ */
524
+ data: {
525
+ user: User;
526
+ url: string;
527
+ token: string;
528
+ },
529
+ /**
530
+ * The request object
531
+ */
532
+ request?: Request) => Promise<void>;
533
+ /**
534
+ * Send a verification email automatically after sign up.
535
+ *
536
+ * - `true`: Always send verification email on sign up
537
+ * - `false`: Never send verification email on sign up
538
+ * - `undefined`: Follows `requireEmailVerification` behavior
539
+ *
540
+ * @default undefined
541
+ */
542
+ sendOnSignUp?: boolean;
543
+ /**
544
+ * Send a verification email automatically
545
+ * on sign in when the user's email is not verified
546
+ *
547
+ * @default false
548
+ */
549
+ sendOnSignIn?: boolean;
550
+ /**
551
+ * Auto signin the user after they verify their email
552
+ */
553
+ autoSignInAfterVerification?: boolean;
554
+ /**
555
+ * Number of seconds the verification token is
556
+ * valid for.
557
+ * @default 3600 seconds (1 hour)
558
+ */
559
+ expiresIn?: number;
560
+ /**
561
+ * A function that is called before a user verifies their email
562
+ * @param user the user that verified their email
563
+ * @param request the request object
564
+ */
565
+ beforeEmailVerification?: (user: User, request?: Request) => Promise<void>;
566
+ /**
567
+ * A function that is called when a user's email is updated to verified
568
+ * @param user the user that verified their email
569
+ * @param request the request object
570
+ */
571
+ afterEmailVerification?: (user: User, request?: Request) => Promise<void>;
572
+ } | undefined;
573
+ /**
574
+ * Email and password authentication
575
+ */
576
+ emailAndPassword?: {
577
+ /**
578
+ * Enable email and password authentication
579
+ *
580
+ * @default false
581
+ */
582
+ enabled: boolean;
583
+ /**
584
+ * Disable email and password sign up
585
+ *
586
+ * @default false
587
+ */
588
+ disableSignUp?: boolean;
589
+ /**
590
+ * Require email verification before a session
591
+ * can be created for the user.
592
+ *
593
+ * if the user is not verified, the user will not be able to sign in
594
+ * and on sign in attempts, the user will be prompted to verify their email.
595
+ */
596
+ requireEmailVerification?: boolean;
597
+ /**
598
+ * The maximum length of the password.
599
+ *
600
+ * @default 128
601
+ */
602
+ maxPasswordLength?: number;
603
+ /**
604
+ * The minimum length of the password.
605
+ *
606
+ * @default 8
607
+ */
608
+ minPasswordLength?: number;
609
+ /**
610
+ * send reset password
611
+ */
612
+ sendResetPassword?: (
613
+ /**
614
+ * @param user the user to send the
615
+ * reset password email to
616
+ * @param url the URL to send the reset password email to
617
+ * @param token the token to send to the user (could be used instead of sending the url
618
+ * if you need to redirect the user to custom route)
619
+ */
620
+ data: {
621
+ user: User;
622
+ url: string;
623
+ token: string;
624
+ },
625
+ /**
626
+ * The request object
627
+ */
628
+ request?: Request) => Promise<void>;
629
+ /**
630
+ * Number of seconds the reset password token is
631
+ * valid for.
632
+ * @default 1 hour (60 * 60)
633
+ */
634
+ resetPasswordTokenExpiresIn?: number;
635
+ /**
636
+ * A callback function that is triggered
637
+ * when a user's password is changed successfully.
638
+ */
639
+ onPasswordReset?: (data: {
640
+ user: User;
641
+ }, request?: Request) => Promise<void>;
642
+ /**
643
+ * Password hashing and verification
644
+ *
645
+ * By default Scrypt is used for password hashing and
646
+ * verification. You can provide your own hashing and
647
+ * verification function. if you want to use a
648
+ * different algorithm.
649
+ */
650
+ password?: {
651
+ hash?: (password: string) => Promise<string>;
652
+ verify?: (data: {
653
+ hash: string;
654
+ password: string;
655
+ }) => Promise<boolean>;
656
+ };
657
+ /**
658
+ * Automatically sign in the user after sign up
659
+ *
660
+ * @default true
661
+ */
662
+ autoSignIn?: boolean;
663
+ /**
664
+ * Whether to revoke all other sessions when resetting password
665
+ * @default false
666
+ */
667
+ revokeSessionsOnPasswordReset?: boolean;
668
+ /**
669
+ * A callback function that is triggered when a user tries to sign up
670
+ * with an email that already exists. Useful for notifying the existing user
671
+ * that someone attempted to register with their email.
672
+ *
673
+ * This is only called when `requireEmailVerification: true` or `autoSignIn: false`.
674
+ */
675
+ onExistingUserSignUp?: (
676
+ /**
677
+ * @param user the existing user from the database
678
+ */
679
+ data: {
680
+ user: User;
681
+ }, request?: Request) => Promise<void>;
682
+ /**
683
+ * Build a custom synthetic user for email enumeration
684
+ * protection. When a sign-up attempt is made with an
685
+ * email that already exists, this function is called
686
+ * to build the fake user response.
687
+ *
688
+ * Use this when plugins add fields to the user table
689
+ * (e.g. admin plugin adds `role`, `banned`, etc.)
690
+ * to ensure the fake response is indistinguishable
691
+ * from a real sign-up.
692
+ *
693
+ * @example
694
+ * ```ts
695
+ * customSyntheticUser: ({ coreFields, additionalFields, id }) => ({
696
+ * ...coreFields,
697
+ * role: "user",
698
+ * banned: false,
699
+ * banReason: null,
700
+ * banExpires: null,
701
+ * ...additionalFields,
702
+ * id,
703
+ * })
704
+ * ```
705
+ */
706
+ customSyntheticUser?: (params: {
707
+ /** Core user fields: name, email, emailVerified, image, createdAt, updatedAt */coreFields: {
708
+ name: string;
709
+ email: string;
710
+ emailVerified: boolean;
711
+ image: string | null;
712
+ createdAt: Date;
713
+ updatedAt: Date;
714
+ }; /** Processed additional fields from options.user.additionalFields (with defaults applied) */
715
+ additionalFields: Record<string, unknown>; /** Generated user ID */
716
+ id: string;
717
+ }) => Record<string, unknown>;
718
+ } | undefined;
719
+ /**
720
+ * list of social providers
721
+ */
722
+ socialProviders?: SocialProviders | undefined;
723
+ /**
724
+ * List of Better Auth plugins
725
+ */
726
+ plugins?: ([] | BetterAuthPlugin[]) | undefined;
727
+ /**
728
+ * User configuration
729
+ */
730
+ user?: (BetterAuthDBOptions<"user", keyof BaseUser> & {
731
+ /**
732
+ * Changing email configuration
733
+ */
734
+ changeEmail?: {
735
+ /**
736
+ * Enable changing email
737
+ * @default false
738
+ */
739
+ enabled: boolean;
740
+ /**
741
+ * Send a confirmation email to the old email address when the user changes their email.
742
+ * @param data the data object
743
+ * @param request the request object
744
+ */
745
+ sendChangeEmailConfirmation?: (data: {
746
+ user: User;
747
+ newEmail: string;
748
+ url: string;
749
+ token: string;
750
+ }, request?: Request) => Promise<void>;
751
+ /**
752
+ * Update the email without verification if the user is not verified.
753
+ * @default false
754
+ */
755
+ updateEmailWithoutVerification?: boolean;
756
+ };
757
+ /**
758
+ * User deletion configuration
759
+ */
760
+ deleteUser?: {
761
+ /**
762
+ * Enable user deletion
763
+ */
764
+ enabled?: boolean;
765
+ /**
766
+ * Send a verification email when the user deletes their account.
767
+ *
768
+ * if this is not set, the user will be deleted immediately.
769
+ * @param data the data object
770
+ * @param request the request object
771
+ */
772
+ sendDeleteAccountVerification?: (data: {
773
+ user: User;
774
+ url: string;
775
+ token: string;
776
+ }, request?: Request) => Promise<void>;
777
+ /**
778
+ * A function that is called before a user is deleted.
779
+ *
780
+ * to interrupt with error you can throw `APIError`
781
+ */
782
+ beforeDelete?: (user: User, request?: Request) => Promise<void>;
783
+ /**
784
+ * A function that is called after a user is deleted.
785
+ *
786
+ * This is useful for cleaning up user data
787
+ */
788
+ afterDelete?: (user: User, request?: Request) => Promise<void>;
789
+ /**
790
+ * The expiration time for the delete token.
791
+ *
792
+ * @default 1 day (60 * 60 * 24) in seconds
793
+ */
794
+ deleteTokenExpiresIn?: number;
795
+ };
796
+ }) | undefined;
797
+ session?: (BetterAuthDBOptions<"session", keyof BaseSession> & {
798
+ /**
799
+ * Expiration time for the session token. The value
800
+ * should be in seconds.
801
+ * @default 7 days (60 * 60 * 24 * 7)
802
+ */
803
+ expiresIn?: number;
804
+ /**
805
+ * How often the session should be refreshed. The value
806
+ * should be in seconds.
807
+ * If set 0 the session will be refreshed every time it is used.
808
+ * @default 1 day (60 * 60 * 24)
809
+ */
810
+ updateAge?: number;
811
+ /**
812
+ * Disable session refresh so that the session is not updated
813
+ * regardless of the `updateAge` option.
814
+ *
815
+ * @default false
816
+ */
817
+ disableSessionRefresh?: boolean;
818
+ /**
819
+ * Defer session refresh writes to POST requests.
820
+ * When enabled, GET is read-only and POST performs refresh.
821
+ * Useful for read-replica database setups.
822
+ *
823
+ * @default false
824
+ */
825
+ deferSessionRefresh?: boolean;
826
+ /**
827
+ * By default if secondary storage is provided
828
+ * the session is stored in the secondary storage.
829
+ *
830
+ * Set this to true to store the session in the database
831
+ * as well.
832
+ *
833
+ * Reads are always done from the secondary storage.
834
+ *
835
+ * @default false
836
+ */
837
+ storeSessionInDatabase?: boolean;
838
+ /**
839
+ * By default, sessions are deleted from the database when secondary storage
840
+ * is provided when session is revoked.
841
+ *
842
+ * Set this to true to preserve session records in the database,
843
+ * even if they are deleted from the secondary storage.
844
+ *
845
+ * @default false
846
+ */
847
+ preserveSessionInDatabase?: boolean;
848
+ /**
849
+ * Enable caching session in cookie
850
+ */
851
+ cookieCache?: {
852
+ /**
853
+ * max age of the cookie
854
+ * @default 5 minutes (5 * 60)
855
+ */
856
+ maxAge?: number;
857
+ /**
858
+ * Enable caching session in cookie
859
+ * @default false
860
+ */
861
+ enabled?: boolean;
862
+ /**
863
+ * Strategy for encoding/decoding cookie cache
864
+ *
865
+ * - "compact": Uses base64url encoding with HMAC-SHA256 signature (compact format, no JWT spec overhead)
866
+ * - "jwt": Uses JWT with HMAC signature (no encryption, follows JWT spec)
867
+ * - "jwe": Uses JWE (JSON Web Encryption) with A256CBC-HS512 and HKDF key derivation for secure encrypted tokens
868
+ *
869
+ * @default "compact"
870
+ */
871
+ strategy?: "compact" | "jwt" | "jwe";
872
+ /**
873
+ * Controls stateless cookie cache refresh behavior.
874
+ *
875
+ * When enabled, the cookie cache will be automatically refreshed before expiry
876
+ * WITHOUT querying the database. This is essential for fully stateless or DB-less scenarios.
877
+ *
878
+ * - `false`: Disable automatic refresh. Cache is only invalidated when it reaches maxAge expiry.
879
+ * - `true`: Enable automatic refresh with default settings (refreshes when 80% of maxAge is reached).
880
+ * - `object`: Custom refresh configuration with either `updateAge` or `shouldRefresh` function
881
+ *
882
+ * Note: When the cache expires (reaches maxAge), it will attempt to fetch from database if available.
883
+ * The refreshCache option is specifically for refreshing BEFORE expiry in a stateless manner.
884
+ *
885
+ * @default false
886
+ */
887
+ refreshCache?: boolean | {
888
+ /**
889
+ * Time in seconds before expiry when the cache should be refreshed.
890
+ * For example, if maxAge is 300 (5 minutes) and updateAge is 60,
891
+ * the cache will be refreshed when it has 60 seconds left before expiry.
892
+ *
893
+ * @default 20% of maxAge
894
+ */
895
+ updateAge?: number;
896
+ };
897
+ /**
898
+ * Version of the cookie cache
899
+ *
900
+ * If a cookie cache version is changed, all existing cookie caches with the old version
901
+ * will be invalidated.
902
+ *
903
+ * It can be a string or a function that returns a string or a promise that returns a string.
904
+ * If it's a function, it will be called with the session and user data
905
+ *
906
+ * @default "1"
907
+ */
908
+ version?: string | ((session: Session & Record<string, any>, user: User & Record<string, any>) => string) | ((session: Session & Record<string, any>, user: User & Record<string, any>) => Promise<string>);
909
+ };
910
+ /**
911
+ * The age of the session to consider it fresh.
912
+ *
913
+ * This is used to check if the session is fresh
914
+ * for sensitive operations. (e.g. deleting an account)
915
+ *
916
+ * If the session is not fresh, the user should be prompted
917
+ * to sign in again.
918
+ *
919
+ * If set to 0, the session will be considered fresh every time. (⚠︎ not recommended)
920
+ *
921
+ * @default 1 day (60 * 60 * 24)
922
+ */
923
+ freshAge?: number;
924
+ }) | undefined;
925
+ account?: (BetterAuthDBOptions<"account", keyof BaseAccount> & {
926
+ /**
927
+ * When enabled (true), the user account data (accessToken, idToken, refreshToken, etc.)
928
+ * will be updated on sign in with the latest data from the provider.
929
+ *
930
+ * @default true
931
+ */
932
+ updateAccountOnSignIn?: boolean;
933
+ /**
934
+ * Configuration for account linking.
935
+ */
936
+ accountLinking?: {
937
+ /**
938
+ * Enable account linking
939
+ *
940
+ * @default true
941
+ */
942
+ enabled?: boolean;
943
+ /**
944
+ * Disable implicit account linking on sign-in.
945
+ *
946
+ * When enabled, accounts will not be automatically linked
947
+ * during OAuth sign-in, even if the email is verified or
948
+ * the provider is trusted. Users must explicitly link
949
+ * accounts using `linkSocial()` while authenticated.
950
+ *
951
+ * @default false
952
+ */
953
+ disableImplicitLinking?: boolean;
954
+ /**
955
+ * Require the existing local user row to have
956
+ * `emailVerified: true` before implicit account linking
957
+ * uses the IdP's `email_verified` claim as ownership
958
+ * proof. Defaults to `true` so an attacker who
959
+ * pre-registers an unverified account at a victim's
960
+ * email cannot have the victim's OAuth identity linked
961
+ * into the attacker-owned row on first sign-in. Set to
962
+ * `false` for backward compatibility on apps whose
963
+ * users sign up via OAuth without verifying their email
964
+ * locally; understand the takeover risk before doing
965
+ * so.
966
+ *
967
+ * @default true
968
+ *
969
+ * @deprecated The option will be removed on the next
970
+ * minor; the gate will become unconditional.
971
+ */
972
+ requireLocalEmailVerified?: boolean;
973
+ /**
974
+ * List of trusted providers. Can be a static array or a function
975
+ * that returns providers dynamically. The function is called
976
+ * during context init (with `request` undefined) and again
977
+ * on each request (with the incoming Request). It must be
978
+ * resilient to `request` being undefined.
979
+ *
980
+ * @example
981
+ * ```ts
982
+ * trustedProviders: ["google", "github"]
983
+ * ```
984
+ *
985
+ * @example
986
+ * ```ts
987
+ * trustedProviders: async (request) => {
988
+ * if (!request) return [];
989
+ * const providers = await getTrustedProvidersForTenant(request);
990
+ * return providers;
991
+ * }
992
+ * ```
993
+ */
994
+ trustedProviders?: Array<LiteralUnion<SocialProviderList[number] | "email-password", string>> | ((request?: Request | undefined) => Awaitable<Array<LiteralUnion<SocialProviderList[number] | "email-password", string>>>);
995
+ /**
996
+ * If enabled (true), this will allow users to manually linking accounts with different email addresses than the main user.
997
+ *
998
+ * @default false
999
+ *
1000
+ * ⚠️ Warning: enabling this might lead to account takeovers, so proceed with caution.
1001
+ */
1002
+ allowDifferentEmails?: boolean;
1003
+ /**
1004
+ * If enabled (true), this will allow users to unlink all accounts.
1005
+ *
1006
+ * @default false
1007
+ */
1008
+ allowUnlinkingAll?: boolean;
1009
+ /**
1010
+ * When enabled, linking an account copies the provider's profile onto
1011
+ * the local user, matching the fields persisted on sign-up (`name`,
1012
+ * `image`, and any `mapProfileToUser` fields). The local `email` and
1013
+ * `emailVerified` are never changed, so a link cannot rebind the
1014
+ * account's identity.
1015
+ *
1016
+ * @default false
1017
+ */
1018
+ updateUserInfoOnLink?: boolean;
1019
+ };
1020
+ /**
1021
+ * Encrypt OAuth tokens
1022
+ *
1023
+ * By default, OAuth tokens (access tokens, refresh tokens, ID tokens) are stored in plain text in the database.
1024
+ * This poses a security risk if your database is compromised, as attackers could gain access to user accounts
1025
+ * on external services.
1026
+ *
1027
+ * When enabled, tokens are encrypted using AES-256-GCM before storage, providing protection against:
1028
+ * - Database breaches and unauthorized access to raw token data
1029
+ * - Internal threats from database administrators or compromised credentials
1030
+ * - Token exposure in database backups and logs
1031
+ * @default false
1032
+ */
1033
+ encryptOAuthTokens?: boolean;
1034
+ /**
1035
+ * Skip state cookie check
1036
+ *
1037
+ * ⚠︎ this has security implications and should only be enabled if you know what you are doing.
1038
+ * @default false
1039
+ */
1040
+ skipStateCookieCheck?: boolean;
1041
+ /**
1042
+ * Strategy for storing OAuth state
1043
+ *
1044
+ * - "cookie": Store state in an encrypted cookie (stateless)
1045
+ * - "database": Store state in the database
1046
+ *
1047
+ * @default "database" when `database` or `secondaryStorage` is configured, "cookie" otherwise
1048
+ */
1049
+ storeStateStrategy?: "database" | "cookie";
1050
+ /**
1051
+ * Store provider account data after an OAuth flow in an encrypted
1052
+ * cookie. This includes OAuth token material such as access tokens,
1053
+ * refresh tokens, ID tokens, scopes, and token expiry.
1054
+ *
1055
+ * This is useful for database-less flows, but large provider tokens can
1056
+ * still hit browser or proxy cookie/header limits even though Better Auth
1057
+ * chunks oversized account cookies.
1058
+ *
1059
+ * @default false
1060
+ *
1061
+ * @note This is automatically set to true if you haven't passed a database
1062
+ */
1063
+ storeAccountCookie?: boolean;
1064
+ }) | undefined;
1065
+ verification?: (BetterAuthDBOptions<"verification", keyof BaseVerification> & {
1066
+ /**
1067
+ * disable cleaning up expired values when a verification value is
1068
+ * fetched
1069
+ */
1070
+ disableCleanup?: boolean;
1071
+ /**
1072
+ * How to store verification identifiers (tokens, OTPs, etc.)
1073
+ *
1074
+ * @example "hashed"
1075
+ *
1076
+ * @default "plain"
1077
+ */
1078
+ storeIdentifier?: StoreIdentifierOption | {
1079
+ default: StoreIdentifierOption;
1080
+ overrides?: Record<string, StoreIdentifierOption>;
1081
+ };
1082
+ /**
1083
+ * Store verification data in database even when secondary storage is configured.
1084
+ * @default false
1085
+ */
1086
+ storeInDatabase?: boolean;
1087
+ }) | undefined;
1088
+ /**
1089
+ * Additional trusted origins. By default, Better Auth trusts your
1090
+ * app's {@link baseURL}. Use this option to allow additional origins
1091
+ * (e.g. a separate frontend domain).
1092
+ *
1093
+ * Can be a static array, a function that returns origins dynamically,
1094
+ * or use wildcard patterns (e.g. `"https://*.example.com"`).
1095
+ *
1096
+ * @param request - The request object.
1097
+ * It'll be undefined if no request was
1098
+ * made. Like during a create context call
1099
+ * or `auth.api` call.
1100
+ *
1101
+ * Trusted origins will be dynamically
1102
+ * calculated based on the request.
1103
+ *
1104
+ * @example
1105
+ * ```ts
1106
+ * trustedOrigins: async (request) => {
1107
+ * return [
1108
+ * "https://better-auth.com",
1109
+ * "https://*.better-auth.com",
1110
+ * request.headers.get("x-custom-origin")
1111
+ * ];
1112
+ * }
1113
+ * ```
1114
+ * @returns An array of trusted origins.
1115
+ */
1116
+ trustedOrigins?: (string[] | ((request?: Request | undefined) => Awaitable<(string | undefined | null)[]>)) | undefined;
1117
+ /**
1118
+ * Rate limiting configuration
1119
+ */
1120
+ rateLimit?: BetterAuthRateLimitOptions | undefined;
1121
+ /**
1122
+ * Advanced options
1123
+ */
1124
+ advanced?: BetterAuthAdvancedOptions | undefined;
1125
+ logger?: Logger | undefined;
1126
+ /**
1127
+ * allows you to define custom hooks that can be
1128
+ * executed during lifecycle of core database
1129
+ * operations.
1130
+ */
1131
+ databaseHooks?: {
1132
+ /**
1133
+ * User hooks
1134
+ */
1135
+ user?: {
1136
+ create?: {
1137
+ /**
1138
+ * Hook that is called before a user is created.
1139
+ * if the hook returns false, the user will not be created.
1140
+ * If the hook returns an object, it'll be used instead of the original data
1141
+ */
1142
+ before?: (user: User & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<boolean | void | {
1143
+ data: Optional<User> & Record<string, any>;
1144
+ }>;
1145
+ /**
1146
+ * Hook that is called after a user is created.
1147
+ */
1148
+ after?: (user: User & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<void>;
1149
+ };
1150
+ update?: {
1151
+ /**
1152
+ * Hook that is called before a user is updated.
1153
+ * if the hook returns false, the user will not be updated.
1154
+ * If the hook returns an object, it'll be used instead of the original data
1155
+ */
1156
+ before?: (user: Partial<User> & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<boolean | void | {
1157
+ data: Optional<User & Record<string, any>>;
1158
+ }>;
1159
+ /**
1160
+ * Hook that is called after a user is updated.
1161
+ */
1162
+ after?: (user: User & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<void>;
1163
+ };
1164
+ delete?: {
1165
+ /**
1166
+ * Hook that is called before a user is deleted.
1167
+ * if the hook returns false, the user will not be deleted.
1168
+ */
1169
+ before?: (user: User & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<boolean | void>;
1170
+ /**
1171
+ * Hook that is called after a user is deleted.
1172
+ */
1173
+ after?: (user: User & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<void>;
1174
+ };
1175
+ };
1176
+ /**
1177
+ * Session Hook
1178
+ */
1179
+ session?: {
1180
+ create?: {
1181
+ /**
1182
+ * Hook that is called before a session is created.
1183
+ * if the hook returns false, the session will not be created.
1184
+ * If the hook returns an object, it'll be used instead of the original data
1185
+ */
1186
+ before?: (session: Session & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<boolean | void | {
1187
+ data: Optional<Session> & Record<string, any>;
1188
+ }>;
1189
+ /**
1190
+ * Hook that is called after a session is created.
1191
+ */
1192
+ after?: (session: Session & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<void>;
1193
+ };
1194
+ /**
1195
+ * Update hook
1196
+ */
1197
+ update?: {
1198
+ /**
1199
+ * Hook that is called before a user is updated.
1200
+ * if the hook returns false, the session will not be updated.
1201
+ * If the hook returns an object, it'll be used instead of the original data
1202
+ */
1203
+ before?: (session: Partial<Session> & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<boolean | void | {
1204
+ data: Optional<Session & Record<string, any>>;
1205
+ }>;
1206
+ /**
1207
+ * Hook that is called after a session is updated.
1208
+ */
1209
+ after?: (session: Session & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<void>;
1210
+ };
1211
+ delete?: {
1212
+ /**
1213
+ * Hook that is called before a session is deleted.
1214
+ * if the hook returns false, the session will not be deleted.
1215
+ */
1216
+ before?: (session: Session & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<boolean | void>;
1217
+ /**
1218
+ * Hook that is called after a session is deleted.
1219
+ */
1220
+ after?: (session: Session & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<void>;
1221
+ };
1222
+ };
1223
+ /**
1224
+ * Account Hook
1225
+ */
1226
+ account?: {
1227
+ create?: {
1228
+ /**
1229
+ * Hook that is called before a account is created.
1230
+ * If the hook returns false, the account will not be created.
1231
+ * If the hook returns an object, it'll be used instead of the original data
1232
+ */
1233
+ before?: (account: Account, context: GenericEndpointContext | null) => Promise<boolean | void | {
1234
+ data: Optional<Account> & Record<string, any>;
1235
+ }>;
1236
+ /**
1237
+ * Hook that is called after a account is created.
1238
+ */
1239
+ after?: (account: Account, context: GenericEndpointContext | null) => Promise<void>;
1240
+ };
1241
+ /**
1242
+ * Update hook
1243
+ */
1244
+ update?: {
1245
+ /**
1246
+ * Hook that is called before a account is update.
1247
+ * If the hook returns false, the user will not be updated.
1248
+ * If the hook returns an object, it'll be used instead of the original data
1249
+ */
1250
+ before?: (account: Partial<Account> & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<boolean | void | {
1251
+ data: Optional<Account & Record<string, any>>;
1252
+ }>;
1253
+ /**
1254
+ * Hook that is called after a account is updated.
1255
+ */
1256
+ after?: (account: Account & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<void>;
1257
+ };
1258
+ delete?: {
1259
+ /**
1260
+ * Hook that is called before an account is deleted.
1261
+ * if the hook returns false, the account will not be deleted.
1262
+ */
1263
+ before?: (account: Account & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<boolean | void>;
1264
+ /**
1265
+ * Hook that is called after an account is deleted.
1266
+ */
1267
+ after?: (account: Account & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<void>;
1268
+ };
1269
+ };
1270
+ /**
1271
+ * Verification Hook
1272
+ */
1273
+ verification?: {
1274
+ create?: {
1275
+ /**
1276
+ * Hook that is called before a verification is created.
1277
+ * if the hook returns false, the verification will not be created.
1278
+ * If the hook returns an object, it'll be used instead of the original data
1279
+ */
1280
+ before?: (verification: Verification & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<boolean | void | {
1281
+ data: Optional<Verification> & Record<string, any>;
1282
+ }>;
1283
+ /**
1284
+ * Hook that is called after a verification is created.
1285
+ */
1286
+ after?: (verification: Verification & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<void>;
1287
+ };
1288
+ update?: {
1289
+ /**
1290
+ * Hook that is called before a verification is updated.
1291
+ * if the hook returns false, the verification will not be updated.
1292
+ * If the hook returns an object, it'll be used instead of the original data
1293
+ */
1294
+ before?: (verification: Partial<Verification> & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<boolean | void | {
1295
+ data: Optional<Verification & Record<string, any>>;
1296
+ }>;
1297
+ /**
1298
+ * Hook that is called after a verification is updated.
1299
+ */
1300
+ after?: (verification: Verification & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<void>;
1301
+ };
1302
+ delete?: {
1303
+ /**
1304
+ * Hook that is called before a verification is deleted.
1305
+ * if the hook returns false, the verification will not be deleted.
1306
+ */
1307
+ before?: (verification: Verification & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<boolean | void>;
1308
+ /**
1309
+ * Hook that is called after a verification is deleted.
1310
+ */
1311
+ after?: (verification: Verification & Record<string, unknown>, context: GenericEndpointContext | null) => Promise<void>;
1312
+ };
1313
+ };
1314
+ } | undefined;
1315
+ /**
1316
+ * API error handling
1317
+ */
1318
+ onAPIError?: {
1319
+ /**
1320
+ * Throw an error on API error
1321
+ *
1322
+ * @default false
1323
+ */
1324
+ throw?: boolean;
1325
+ /**
1326
+ * Custom error handler
1327
+ *
1328
+ * @param error
1329
+ * @param ctx - Auth context
1330
+ */
1331
+ onError?: (error: unknown, ctx: AuthContext) => void | Promise<void>;
1332
+ /**
1333
+ * The URL to redirect to on error
1334
+ *
1335
+ * When errorURL is provided, the error will be added to the URL as a query parameter
1336
+ * and the user will be redirected to the errorURL.
1337
+ *
1338
+ * @default - "/api/auth/error"
1339
+ */
1340
+ errorURL?: string;
1341
+ /**
1342
+ * Configure the default error page provided by Better-Auth
1343
+ * Start your dev server and go to /api/auth/error to see the error page.
1344
+ */
1345
+ customizeDefaultErrorPage?: {
1346
+ colors?: {
1347
+ background?: string;
1348
+ foreground?: string;
1349
+ primary?: string;
1350
+ primaryForeground?: string;
1351
+ mutedForeground?: string;
1352
+ border?: string;
1353
+ destructive?: string;
1354
+ titleBorder?: string;
1355
+ titleColor?: string;
1356
+ gridColor?: string;
1357
+ cardBackground?: string;
1358
+ cornerBorder?: string;
1359
+ };
1360
+ size?: {
1361
+ radiusSm?: string;
1362
+ radiusMd?: string;
1363
+ radiusLg?: string;
1364
+ textSm?: string;
1365
+ text2xl?: string;
1366
+ text4xl?: string;
1367
+ text6xl?: string;
1368
+ };
1369
+ font?: {
1370
+ defaultFamily?: string;
1371
+ monoFamily?: string;
1372
+ };
1373
+ disableTitleBorder?: boolean;
1374
+ disableCornerDecorations?: boolean;
1375
+ disableBackgroundGrid?: boolean;
1376
+ };
1377
+ } | undefined;
1378
+ /**
1379
+ * Hooks
1380
+ */
1381
+ hooks?: {
1382
+ /**
1383
+ * Before a request is processed
1384
+ */
1385
+ before?: AuthMiddleware;
1386
+ /**
1387
+ * After a request is processed
1388
+ */
1389
+ after?: AuthMiddleware;
1390
+ } | undefined;
1391
+ /**
1392
+ * Disabled paths
1393
+ *
1394
+ * Paths you want to disable.
1395
+ */
1396
+ disabledPaths?: string[] | undefined;
1397
+ /**
1398
+ * Telemetry configuration
1399
+ */
1400
+ telemetry?: {
1401
+ /**
1402
+ * Enable telemetry collection
1403
+ *
1404
+ * @default false
1405
+ */
1406
+ enabled?: boolean;
1407
+ /**
1408
+ * Enable debug mode
1409
+ *
1410
+ * @default false
1411
+ */
1412
+ debug?: boolean;
1413
+ } | undefined;
1414
+ /**
1415
+ * Experimental features
1416
+ */
1417
+ experimental?: {
1418
+ /**
1419
+ * Enable experimental joins for your database adapter.
1420
+ *
1421
+ * Please read the adapter documentation for more information regarding joins before enabling this.
1422
+ * Not all adapters support joins.
1423
+ *
1424
+ * @default false
1425
+ */
1426
+ joins?: boolean;
1427
+ };
1428
+ };
1429
+ //#endregion
1430
+ export { BaseURLConfig, BetterAuthAdvancedOptions, BetterAuthDBOptions, BetterAuthOptions, BetterAuthRateLimitOptions, BetterAuthRateLimitRule, BetterAuthRateLimitStorage, DynamicBaseURLConfig, GenerateIdFn, StoreIdentifierOption };