@better-auth/core 1.7.0-beta.4 → 1.7.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/dist/api/index.d.mts +47 -4
  2. package/dist/api/index.mjs +40 -1
  3. package/dist/context/global.mjs +1 -1
  4. package/dist/context/transaction.d.mts +7 -4
  5. package/dist/context/transaction.mjs +6 -3
  6. package/dist/db/adapter/factory.mjs +57 -31
  7. package/dist/db/adapter/index.d.mts +54 -10
  8. package/dist/db/adapter/types.d.mts +1 -1
  9. package/dist/db/get-tables.mjs +3 -3
  10. package/dist/db/schema/account.d.mts +1 -1
  11. package/dist/db/schema/account.mjs +1 -1
  12. package/dist/db/type.d.mts +12 -7
  13. package/dist/env/env-impl.mjs +1 -1
  14. package/dist/error/codes.d.mts +5 -0
  15. package/dist/error/codes.mjs +5 -0
  16. package/dist/index.d.mts +2 -2
  17. package/dist/instrumentation/tracer.mjs +1 -1
  18. package/dist/oauth2/create-authorization-url.d.mts +4 -1
  19. package/dist/oauth2/create-authorization-url.mjs +5 -2
  20. package/dist/oauth2/dpop.d.mts +142 -0
  21. package/dist/oauth2/dpop.mjs +246 -0
  22. package/dist/oauth2/index.d.mts +6 -3
  23. package/dist/oauth2/index.mjs +5 -2
  24. package/dist/oauth2/oauth-provider.d.mts +128 -9
  25. package/dist/oauth2/refresh-access-token.mjs +1 -1
  26. package/dist/oauth2/scopes.d.mts +76 -0
  27. package/dist/oauth2/scopes.mjs +96 -0
  28. package/dist/oauth2/utils.mjs +2 -1
  29. package/dist/oauth2/verify-id-token.d.mts +26 -0
  30. package/dist/oauth2/verify-id-token.mjs +62 -0
  31. package/dist/oauth2/verify.d.mts +88 -15
  32. package/dist/oauth2/verify.mjs +187 -19
  33. package/dist/social-providers/apple.d.mts +14 -2
  34. package/dist/social-providers/apple.mjs +12 -36
  35. package/dist/social-providers/atlassian.d.mts +5 -1
  36. package/dist/social-providers/atlassian.mjs +4 -4
  37. package/dist/social-providers/cognito.d.mts +13 -2
  38. package/dist/social-providers/cognito.mjs +24 -32
  39. package/dist/social-providers/discord.d.mts +5 -1
  40. package/dist/social-providers/discord.mjs +7 -6
  41. package/dist/social-providers/dropbox.d.mts +5 -1
  42. package/dist/social-providers/dropbox.mjs +5 -5
  43. package/dist/social-providers/facebook.d.mts +21 -2
  44. package/dist/social-providers/facebook.mjs +46 -22
  45. package/dist/social-providers/figma.d.mts +5 -1
  46. package/dist/social-providers/figma.mjs +5 -5
  47. package/dist/social-providers/github.d.mts +5 -1
  48. package/dist/social-providers/github.mjs +4 -4
  49. package/dist/social-providers/gitlab.d.mts +5 -1
  50. package/dist/social-providers/gitlab.mjs +6 -6
  51. package/dist/social-providers/google.d.mts +29 -3
  52. package/dist/social-providers/google.mjs +24 -30
  53. package/dist/social-providers/huggingface.d.mts +5 -1
  54. package/dist/social-providers/huggingface.mjs +8 -8
  55. package/dist/social-providers/index.d.mts +222 -42
  56. package/dist/social-providers/kakao.d.mts +5 -1
  57. package/dist/social-providers/kakao.mjs +8 -8
  58. package/dist/social-providers/kick.d.mts +5 -1
  59. package/dist/social-providers/kick.mjs +4 -4
  60. package/dist/social-providers/line.d.mts +8 -2
  61. package/dist/social-providers/line.mjs +12 -14
  62. package/dist/social-providers/linear.d.mts +5 -1
  63. package/dist/social-providers/linear.mjs +4 -4
  64. package/dist/social-providers/linkedin.d.mts +5 -1
  65. package/dist/social-providers/linkedin.mjs +10 -10
  66. package/dist/social-providers/microsoft-entra-id.d.mts +41 -6
  67. package/dist/social-providers/microsoft-entra-id.mjs +40 -36
  68. package/dist/social-providers/naver.d.mts +5 -1
  69. package/dist/social-providers/naver.mjs +4 -4
  70. package/dist/social-providers/notion.d.mts +5 -1
  71. package/dist/social-providers/notion.mjs +4 -4
  72. package/dist/social-providers/paybin.d.mts +5 -1
  73. package/dist/social-providers/paybin.mjs +10 -10
  74. package/dist/social-providers/paypal.d.mts +5 -2
  75. package/dist/social-providers/paypal.mjs +8 -13
  76. package/dist/social-providers/polar.d.mts +5 -1
  77. package/dist/social-providers/polar.mjs +8 -8
  78. package/dist/social-providers/railway.d.mts +5 -1
  79. package/dist/social-providers/railway.mjs +9 -9
  80. package/dist/social-providers/reddit.d.mts +5 -1
  81. package/dist/social-providers/reddit.mjs +9 -8
  82. package/dist/social-providers/roblox.d.mts +5 -1
  83. package/dist/social-providers/roblox.mjs +5 -5
  84. package/dist/social-providers/salesforce.d.mts +5 -1
  85. package/dist/social-providers/salesforce.mjs +8 -8
  86. package/dist/social-providers/slack.d.mts +5 -1
  87. package/dist/social-providers/slack.mjs +9 -9
  88. package/dist/social-providers/spotify.d.mts +5 -1
  89. package/dist/social-providers/spotify.mjs +5 -5
  90. package/dist/social-providers/tiktok.d.mts +5 -1
  91. package/dist/social-providers/tiktok.mjs +9 -5
  92. package/dist/social-providers/twitch.d.mts +5 -1
  93. package/dist/social-providers/twitch.mjs +4 -4
  94. package/dist/social-providers/twitter.d.mts +6 -4
  95. package/dist/social-providers/twitter.mjs +9 -9
  96. package/dist/social-providers/vercel.d.mts +5 -1
  97. package/dist/social-providers/vercel.mjs +4 -7
  98. package/dist/social-providers/vk.d.mts +5 -1
  99. package/dist/social-providers/vk.mjs +5 -5
  100. package/dist/social-providers/wechat.d.mts +5 -1
  101. package/dist/social-providers/wechat.mjs +10 -6
  102. package/dist/social-providers/zoom.d.mts +6 -1
  103. package/dist/social-providers/zoom.mjs +15 -9
  104. package/dist/types/context.d.mts +27 -8
  105. package/dist/types/index.d.mts +1 -1
  106. package/dist/types/init-options.d.mts +137 -6
  107. package/dist/types/plugin-client.d.mts +12 -2
  108. package/dist/utils/host.mjs +4 -0
  109. package/dist/utils/url.mjs +4 -3
  110. package/package.json +7 -7
  111. package/src/api/index.ts +82 -0
  112. package/src/context/transaction.ts +45 -12
  113. package/src/db/adapter/factory.ts +127 -64
  114. package/src/db/adapter/index.ts +54 -9
  115. package/src/db/adapter/types.ts +1 -0
  116. package/src/db/get-tables.ts +8 -3
  117. package/src/db/schema/account.ts +14 -2
  118. package/src/db/type.ts +12 -7
  119. package/src/env/env-impl.ts +1 -2
  120. package/src/error/codes.ts +5 -0
  121. package/src/oauth2/create-authorization-url.ts +2 -2
  122. package/src/oauth2/dpop.ts +568 -0
  123. package/src/oauth2/index.ts +61 -2
  124. package/src/oauth2/oauth-provider.ts +140 -10
  125. package/src/oauth2/refresh-access-token.ts +2 -2
  126. package/src/oauth2/scopes.ts +118 -0
  127. package/src/oauth2/utils.ts +2 -5
  128. package/src/oauth2/verify-id-token.ts +111 -0
  129. package/src/oauth2/verify.ts +372 -58
  130. package/src/social-providers/apple.ts +24 -61
  131. package/src/social-providers/atlassian.ts +12 -8
  132. package/src/social-providers/cognito.ts +25 -47
  133. package/src/social-providers/discord.ts +19 -8
  134. package/src/social-providers/dropbox.ts +13 -7
  135. package/src/social-providers/facebook.ts +97 -51
  136. package/src/social-providers/figma.ts +13 -9
  137. package/src/social-providers/github.ts +12 -8
  138. package/src/social-providers/gitlab.ts +14 -8
  139. package/src/social-providers/google.ts +66 -47
  140. package/src/social-providers/huggingface.ts +12 -8
  141. package/src/social-providers/kakao.ts +16 -8
  142. package/src/social-providers/kick.ts +12 -7
  143. package/src/social-providers/line.ts +37 -37
  144. package/src/social-providers/linear.ts +12 -6
  145. package/src/social-providers/linkedin.ts +14 -10
  146. package/src/social-providers/microsoft-entra-id.ts +103 -59
  147. package/src/social-providers/naver.ts +12 -6
  148. package/src/social-providers/notion.ts +12 -6
  149. package/src/social-providers/paybin.ts +14 -11
  150. package/src/social-providers/paypal.ts +6 -25
  151. package/src/social-providers/polar.ts +12 -8
  152. package/src/social-providers/railway.ts +13 -9
  153. package/src/social-providers/reddit.ts +25 -10
  154. package/src/social-providers/roblox.ts +18 -7
  155. package/src/social-providers/salesforce.ts +12 -8
  156. package/src/social-providers/slack.ts +18 -9
  157. package/src/social-providers/spotify.ts +13 -7
  158. package/src/social-providers/tiktok.ts +13 -7
  159. package/src/social-providers/twitch.ts +12 -8
  160. package/src/social-providers/twitter.ts +17 -8
  161. package/src/social-providers/vercel.ts +16 -10
  162. package/src/social-providers/vk.ts +13 -7
  163. package/src/social-providers/wechat.ts +28 -9
  164. package/src/social-providers/zoom.ts +19 -6
  165. package/src/types/context.ts +26 -8
  166. package/src/types/index.ts +7 -0
  167. package/src/types/init-options.ts +159 -8
  168. package/src/types/plugin-client.ts +16 -2
  169. package/src/utils/host.ts +15 -0
  170. package/src/utils/url.ts +10 -4
@@ -1,27 +1,27 @@
1
+ import { resolveRequestedScopes } from "../oauth2/scopes.mjs";
1
2
  import { createAuthorizationURL } from "../oauth2/create-authorization-url.mjs";
2
3
  import { refreshAccessToken } from "../oauth2/refresh-access-token.mjs";
3
4
  import { validateAuthorizationCode } from "../oauth2/validate-authorization-code.mjs";
4
5
  import { betterFetch } from "@better-fetch/fetch";
5
6
  //#region src/social-providers/twitter.ts
7
+ const TWITTER_DEFAULT_SCOPES = [
8
+ "users.read",
9
+ "tweet.read",
10
+ "offline.access",
11
+ "users.email"
12
+ ];
6
13
  const twitter = (options) => {
7
14
  const tokenEndpoint = "https://api.x.com/2/oauth2/token";
8
15
  return {
9
16
  id: "twitter",
10
17
  name: "Twitter",
18
+ callbackPath: "/callback/twitter",
11
19
  createAuthorizationURL(data) {
12
- const _scopes = options.disableDefaultScope ? [] : [
13
- "users.read",
14
- "tweet.read",
15
- "offline.access",
16
- "users.email"
17
- ];
18
- if (options.scope) _scopes.push(...options.scope);
19
- if (data.scopes) _scopes.push(...data.scopes);
20
20
  return createAuthorizationURL({
21
21
  id: "twitter",
22
22
  options,
23
23
  authorizationEndpoint: "https://x.com/i/oauth2/authorize",
24
- scopes: _scopes,
24
+ scopes: resolveRequestedScopes(options, TWITTER_DEFAULT_SCOPES, data.scopes),
25
25
  state: data.state,
26
26
  codeVerifier: data.codeVerifier,
27
27
  redirectURI: data.redirectURI,
@@ -14,6 +14,7 @@ interface VercelOptions extends ProviderOptions<VercelProfile> {
14
14
  declare const vercel: (options: VercelOptions) => {
15
15
  id: "vercel";
16
16
  name: string;
17
+ callbackPath: string;
17
18
  createAuthorizationURL({
18
19
  state,
19
20
  scopes,
@@ -28,7 +29,10 @@ declare const vercel: (options: VercelOptions) => {
28
29
  display?: string | undefined;
29
30
  loginHint?: string | undefined;
30
31
  additionalParams?: Record<string, string> | undefined;
31
- }): Promise<URL>;
32
+ }): Promise<{
33
+ url: URL;
34
+ requestedScopes: string[];
35
+ }>;
32
36
  validateAuthorizationCode: ({
33
37
  code,
34
38
  codeVerifier,
@@ -1,25 +1,22 @@
1
1
  import { BetterAuthError } from "../error/index.mjs";
2
+ import { resolveRequestedScopes } from "../oauth2/scopes.mjs";
2
3
  import { createAuthorizationURL } from "../oauth2/create-authorization-url.mjs";
3
4
  import { validateAuthorizationCode } from "../oauth2/validate-authorization-code.mjs";
4
5
  import { betterFetch } from "@better-fetch/fetch";
5
6
  //#region src/social-providers/vercel.ts
7
+ const VERCEL_DEFAULT_SCOPES = [];
6
8
  const vercel = (options) => {
7
9
  return {
8
10
  id: "vercel",
9
11
  name: "Vercel",
12
+ callbackPath: "/callback/vercel",
10
13
  createAuthorizationURL({ state, scopes, codeVerifier, redirectURI, additionalParams }) {
11
14
  if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Vercel");
12
- let _scopes = void 0;
13
- if (options.scope !== void 0 || scopes !== void 0) {
14
- _scopes = [];
15
- if (options.scope) _scopes.push(...options.scope);
16
- if (scopes) _scopes.push(...scopes);
17
- }
18
15
  return createAuthorizationURL({
19
16
  id: "vercel",
20
17
  options,
21
18
  authorizationEndpoint: "https://vercel.com/oauth/authorize",
22
- scopes: _scopes,
19
+ scopes: resolveRequestedScopes(options, VERCEL_DEFAULT_SCOPES, scopes),
23
20
  state,
24
21
  codeVerifier,
25
22
  redirectURI,
@@ -20,6 +20,7 @@ interface VkOption extends ProviderOptions {
20
20
  declare const vk: (options: VkOption) => {
21
21
  id: "vk";
22
22
  name: string;
23
+ callbackPath: string;
23
24
  createAuthorizationURL({
24
25
  state,
25
26
  scopes,
@@ -34,7 +35,10 @@ declare const vk: (options: VkOption) => {
34
35
  display?: string | undefined;
35
36
  loginHint?: string | undefined;
36
37
  additionalParams?: Record<string, string> | undefined;
37
- }): Promise<URL>;
38
+ }): Promise<{
39
+ url: URL;
40
+ requestedScopes: string[];
41
+ }>;
38
42
  validateAuthorizationCode: ({
39
43
  code,
40
44
  codeVerifier,
@@ -1,22 +1,22 @@
1
+ import { resolveRequestedScopes } from "../oauth2/scopes.mjs";
1
2
  import { createAuthorizationURL } from "../oauth2/create-authorization-url.mjs";
2
3
  import { refreshAccessToken } from "../oauth2/refresh-access-token.mjs";
3
4
  import { validateAuthorizationCode } from "../oauth2/validate-authorization-code.mjs";
4
5
  import { betterFetch } from "@better-fetch/fetch";
5
6
  //#region src/social-providers/vk.ts
7
+ const VK_DEFAULT_SCOPES = ["email", "phone"];
6
8
  const vk = (options) => {
7
9
  const tokenEndpoint = "https://id.vk.com/oauth2/auth";
8
10
  return {
9
11
  id: "vk",
10
12
  name: "VK",
11
- async createAuthorizationURL({ state, scopes, codeVerifier, redirectURI, additionalParams }) {
12
- const _scopes = options.disableDefaultScope ? [] : ["email", "phone"];
13
- if (options.scope) _scopes.push(...options.scope);
14
- if (scopes) _scopes.push(...scopes);
13
+ callbackPath: "/callback/vk",
14
+ createAuthorizationURL({ state, scopes, codeVerifier, redirectURI, additionalParams }) {
15
15
  return createAuthorizationURL({
16
16
  id: "vk",
17
17
  options,
18
18
  authorizationEndpoint: "https://id.vk.com/authorize",
19
- scopes: _scopes,
19
+ scopes: resolveRequestedScopes(options, VK_DEFAULT_SCOPES, scopes),
20
20
  state,
21
21
  redirectURI,
22
22
  codeVerifier,
@@ -53,6 +53,7 @@ interface WeChatOptions extends ProviderOptions<WeChatProfile> {
53
53
  declare const wechat: (options: WeChatOptions) => {
54
54
  id: "wechat";
55
55
  name: string;
56
+ callbackPath: string;
56
57
  createAuthorizationURL({
57
58
  state,
58
59
  scopes,
@@ -66,7 +67,10 @@ declare const wechat: (options: WeChatOptions) => {
66
67
  display?: string | undefined;
67
68
  loginHint?: string | undefined;
68
69
  additionalParams?: Record<string, string> | undefined;
69
- }): URL;
70
+ }): {
71
+ url: URL;
72
+ requestedScopes: string[];
73
+ };
70
74
  validateAuthorizationCode: ({
71
75
  code
72
76
  }: {
@@ -1,16 +1,17 @@
1
+ import { resolveRequestedScopes } from "../oauth2/scopes.mjs";
1
2
  import { RESERVED_AUTHORIZATION_PARAMS_SET } from "../oauth2/create-authorization-url.mjs";
2
3
  import { betterFetch } from "@better-fetch/fetch";
3
4
  //#region src/social-providers/wechat.ts
5
+ const WECHAT_DEFAULT_SCOPES = ["snsapi_login"];
4
6
  const wechat = (options) => {
5
7
  return {
6
8
  id: "wechat",
7
9
  name: "WeChat",
10
+ callbackPath: "/callback/wechat",
8
11
  createAuthorizationURL({ state, scopes, redirectURI, additionalParams }) {
9
- const _scopes = options.disableDefaultScope ? [] : ["snsapi_login"];
10
- options.scope && _scopes.push(...options.scope);
11
- scopes && _scopes.push(...scopes);
12
+ const requestedScopes = resolveRequestedScopes(options, WECHAT_DEFAULT_SCOPES, scopes);
12
13
  const url = new URL("https://open.weixin.qq.com/connect/qrconnect");
13
- url.searchParams.set("scope", _scopes.join(","));
14
+ url.searchParams.set("scope", requestedScopes.join(","));
14
15
  url.searchParams.set("response_type", "code");
15
16
  url.searchParams.set("appid", options.clientId);
16
17
  url.searchParams.set("redirect_uri", options.redirectURI || redirectURI);
@@ -22,7 +23,10 @@ const wechat = (options) => {
22
23
  url.searchParams.set(key, value);
23
24
  }
24
25
  url.hash = "wechat_redirect";
25
- return url;
26
+ return {
27
+ url,
28
+ requestedScopes
29
+ };
26
30
  },
27
31
  validateAuthorizationCode: async ({ code }) => {
28
32
  const { data: tokenData, error } = await betterFetch("https://api.weixin.qq.com/sns/oauth2/access_token?" + new URLSearchParams({
@@ -72,7 +76,7 @@ const wechat = (options) => {
72
76
  user: {
73
77
  id: profile.unionid || profile.openid || openid,
74
78
  name: profile.nickname,
75
- email: profile.email || null,
79
+ email: profile.email || `${profile.unionid || profile.openid || openid}@wechat.invalid`,
76
80
  image: profile.headimgurl,
77
81
  emailVerified: false,
78
82
  ...userMap
@@ -116,8 +116,10 @@ interface ZoomOptions extends ProviderOptions<ZoomProfile> {
116
116
  declare const zoom: (userOptions: ZoomOptions) => {
117
117
  id: "zoom";
118
118
  name: string;
119
+ callbackPath: string;
119
120
  createAuthorizationURL: ({
120
121
  state,
122
+ scopes,
121
123
  redirectURI,
122
124
  codeVerifier,
123
125
  additionalParams
@@ -129,7 +131,10 @@ declare const zoom: (userOptions: ZoomOptions) => {
129
131
  display?: string | undefined;
130
132
  loginHint?: string | undefined;
131
133
  additionalParams?: Record<string, string> | undefined;
132
- }) => Promise<URL>;
134
+ }) => Promise<{
135
+ url: URL;
136
+ requestedScopes: string[];
137
+ }>;
133
138
  validateAuthorizationCode: ({
134
139
  code,
135
140
  redirectURI,
@@ -1,8 +1,10 @@
1
+ import { resolveRequestedScopes } from "../oauth2/scopes.mjs";
1
2
  import { createAuthorizationURL } from "../oauth2/create-authorization-url.mjs";
2
3
  import { refreshAccessToken } from "../oauth2/refresh-access-token.mjs";
3
4
  import { validateAuthorizationCode } from "../oauth2/validate-authorization-code.mjs";
4
5
  import { betterFetch } from "@better-fetch/fetch";
5
6
  //#region src/social-providers/zoom.ts
7
+ const ZOOM_DEFAULT_SCOPES = [];
6
8
  const zoom = (userOptions) => {
7
9
  const options = {
8
10
  pkce: true,
@@ -11,15 +13,19 @@ const zoom = (userOptions) => {
11
13
  return {
12
14
  id: "zoom",
13
15
  name: "Zoom",
14
- createAuthorizationURL: async ({ state, redirectURI, codeVerifier, additionalParams }) => createAuthorizationURL({
15
- id: "zoom",
16
- options,
17
- authorizationEndpoint: "https://zoom.us/oauth/authorize",
18
- state,
19
- redirectURI,
20
- codeVerifier: options.pkce ? codeVerifier : void 0,
21
- additionalParams
22
- }),
16
+ callbackPath: "/callback/zoom",
17
+ createAuthorizationURL: ({ state, scopes, redirectURI, codeVerifier, additionalParams }) => {
18
+ return createAuthorizationURL({
19
+ id: "zoom",
20
+ options,
21
+ authorizationEndpoint: "https://zoom.us/oauth/authorize",
22
+ scopes: resolveRequestedScopes(options, ZOOM_DEFAULT_SCOPES, scopes),
23
+ state,
24
+ redirectURI,
25
+ codeVerifier: options.pkce ? codeVerifier : void 0,
26
+ additionalParams
27
+ });
28
+ },
23
29
  validateAuthorizationCode: async ({ code, redirectURI, codeVerifier }) => {
24
30
  return validateAuthorizationCode({
25
31
  code,
@@ -6,11 +6,11 @@ import { Verification } from "../db/schema/verification.mjs";
6
6
  import { createLogger } from "../env/logger.mjs";
7
7
  import { Awaitable, LiteralString } from "./helper.mjs";
8
8
  import { BetterAuthPlugin } from "./plugin.mjs";
9
- import { BetterAuthOptions, BetterAuthRateLimitOptions } from "./init-options.mjs";
9
+ import { BetterAuthOptions, BetterAuthRateLimitOptions, UserProvisioningSource } from "./init-options.mjs";
10
10
  import { Account } from "../db/schema/account.mjs";
11
11
  import { BetterAuthCookie, BetterAuthCookies } from "./cookie.mjs";
12
12
  import { SecretConfig } from "./secret.mjs";
13
- import { OAuthProvider } from "../oauth2/oauth-provider.mjs";
13
+ import { UpstreamProvider } from "../oauth2/oauth-provider.mjs";
14
14
  import { CookieOptions, EndpointContext } from "better-call";
15
15
 
16
16
  //#region src/types/context.d.ts
@@ -54,11 +54,13 @@ type GenericEndpointContext<Options extends BetterAuthOptions = BetterAuthOption
54
54
  context: AuthContext<Options>;
55
55
  };
56
56
  interface InternalAdapter<_Options extends BetterAuthOptions = BetterAuthOptions> {
57
- createOAuthUser(user: Omit<User, "id" | "createdAt" | "updatedAt">, account: Omit<Account, "userId" | "id" | "createdAt" | "updatedAt"> & Partial<Account>): Promise<{
58
- user: User;
59
- account: Account;
60
- }>;
61
- createUser<T extends Record<string, any>>(user: Omit<User, "id" | "createdAt" | "updatedAt" | "emailVerified"> & Partial<User> & Record<string, any>): Promise<T & User>;
57
+ createUser<T extends Record<string, any>>(user: Omit<User, "id" | "createdAt" | "updatedAt" | "emailVerified"> & Partial<User> & Record<string, any>,
58
+ /**
59
+ * Provisioning source. The creation seam adds `action: "create-user"` and
60
+ * runs the `user.validateUserInfo` gate.
61
+ */
62
+
63
+ source: UserProvisioningSource): Promise<T & User>;
62
64
  createAccount<T extends Record<string, any>>(account: Omit<Account, "id" | "createdAt" | "updatedAt"> & Partial<Account> & T): Promise<T & Account>;
63
65
  listSessions(userId: string, options?: {
64
66
  onlyActiveSessions?: boolean | undefined;
@@ -134,6 +136,23 @@ interface InternalAdapter<_Options extends BetterAuthOptions = BetterAuthOptions
134
136
  * pair at single-use credential consumption sites.
135
137
  */
136
138
  consumeVerificationValue(identifier: string): Promise<Verification | null>;
139
+ /**
140
+ * First-writer-wins create keyed by a deterministic primary key derived from
141
+ * `identifier`. Returns `true` when this caller created the row and `false`
142
+ * when a row for the same identifier already existed.
143
+ *
144
+ * The dual of `consumeVerificationValue`: reserve races to create a marker
145
+ * exactly once, where consume races to delete one exactly once. Use it for
146
+ * replay tombstones (a SAML assertion id, a JWT `jti`) where the first caller
147
+ * wins. The database path is atomic via the primary key. Secondary-storage-only
148
+ * verification is not supported for reservation and runtime implementations
149
+ * should fail closed unless verification is backed by the database.
150
+ */
151
+ reserveVerificationValue(data: {
152
+ identifier: string;
153
+ value: string;
154
+ expiresAt: Date;
155
+ }): Promise<boolean>;
137
156
  updateVerificationByIdentifier(identifier: string, data: Partial<Verification>): Promise<Verification>;
138
157
  refreshUserSessions(user: User): Promise<void>;
139
158
  }
@@ -213,7 +232,7 @@ type AuthContext<Options extends BetterAuthOptions = BetterAuthOptions> = Plugin
213
232
  session: Session & Record<string, any>;
214
233
  user: User & Record<string, any>;
215
234
  } | null) => void;
216
- socialProviders: OAuthProvider[];
235
+ socialProviders: UpstreamProvider[];
217
236
  authCookies: BetterAuthCookies;
218
237
  logger: ReturnType<typeof createLogger>;
219
238
  rateLimit: {
@@ -1,6 +1,6 @@
1
1
  import { Awaitable, AwaitableFunction, LiteralString, LiteralUnion, Prettify, Primitive, UnionToIntersection } from "./helper.mjs";
2
2
  import { BetterAuthPlugin, BetterAuthPluginErrorCodePart, HookEndpointContext } from "./plugin.mjs";
3
- import { BaseURLConfig, BetterAuthAdvancedOptions, BetterAuthDBOptions, BetterAuthOptions, BetterAuthRateLimitOptions, BetterAuthRateLimitRule, BetterAuthRateLimitStorage, DynamicBaseURLConfig, GenerateIdFn, StoreIdentifierOption } from "./init-options.mjs";
3
+ import { BaseURLConfig, BetterAuthAdvancedOptions, BetterAuthDBOptions, BetterAuthOptions, BetterAuthRateLimitOptions, BetterAuthRateLimitRule, BetterAuthRateLimitStorage, DynamicBaseURLConfig, GenerateIdFn, StoreIdentifierOption, UserProvisioningSource, ValidateUserInfoAction, ValidateUserInfoMethod, ValidateUserInfoOAuthInfo, ValidateUserInfoResult, ValidateUserInfoSSOInfo, ValidateUserInfoSource } from "./init-options.mjs";
4
4
  import { BetterAuthCookie, BetterAuthCookies } from "./cookie.mjs";
5
5
  import { SecretConfig } from "./secret.mjs";
6
6
  import { AuthContext, BetterAuthPluginRegistry, BetterAuthPluginRegistryIdentifier, GenericEndpointContext, InfoContext, InternalAdapter, PluginContext } from "./context.mjs";
@@ -1,6 +1,6 @@
1
1
  import { DBFieldAttribute, ModelNames, SecondaryStorage } from "../db/type.mjs";
2
2
  import { DBAdapterDebugLogOption, DBAdapterInstance } from "../db/adapter/index.mjs";
3
- import { BaseRateLimit, RateLimit } from "../db/schema/rate-limit.mjs";
3
+ import { BaseRateLimit } from "../db/schema/rate-limit.mjs";
4
4
  import { BaseSession, Session } from "../db/schema/session.mjs";
5
5
  import { BaseUser, User } from "../db/schema/user.mjs";
6
6
  import { BaseVerification, Verification } from "../db/schema/verification.mjs";
@@ -27,6 +27,73 @@ type GenerateIdFn = (options: {
27
27
  model: ModelNames;
28
28
  size?: number | undefined;
29
29
  }) => string | false;
30
+ /**
31
+ * What Better Auth is about to do with an incoming identity when
32
+ * {@link BetterAuthOptions.user}'s `validateUserInfo` runs.
33
+ *
34
+ * - `create-user`: a brand-new user record is about to be created.
35
+ * - `link-account`: a new provider account is about to be linked to an
36
+ * already-existing user.
37
+ * - `sign-in`: an existing OAuth or SSO user is signing in again. This is the
38
+ * one case where the provider can assert *changed* data, so the hook receives
39
+ * the fresh provider email and profile (not the stored row), letting a domain
40
+ * or org policy reject a user whose provider identity moved out of bounds.
41
+ *
42
+ * Non-provider returning sign-ins are not re-validated: they carry only the
43
+ * stored row, which has not changed since `create-user` gated it. Use the admin
44
+ * plugin's ban controls or a `databaseHooks.session.create.before` hook to
45
+ * block those.
46
+ */
47
+ type ValidateUserInfoAction = "create-user" | "link-account" | "sign-in";
48
+ /**
49
+ * The authentication method that produced the incoming user info. The named
50
+ * methods cover Better Auth's built-ins; the open `string` keeps it extensible
51
+ * for plugins (for example `"scim"`).
52
+ */
53
+ type ValidateUserInfoMethod = "oauth" | "sso-oidc" | "sso-saml" | "email-password" | "magic-link" | "email-otp" | "anonymous" | "siwe" | "phone-number" | "admin" | (string & {});
54
+ /** OAuth-specific provisioning context; present only when `method` is `"oauth"`. */
55
+ type ValidateUserInfoOAuthInfo = {
56
+ /** The social or generic OAuth provider id (e.g. `"google"`). */providerId: string; /** The raw provider profile (userinfo or id-token claims), unmapped. */
57
+ profile?: Record<string, unknown> | undefined;
58
+ };
59
+ /** SSO-specific provisioning context; present for OIDC and SAML SSO methods. */
60
+ type ValidateUserInfoSSOInfo = {
61
+ /** The configured SSO provider id. */providerId: string; /** The raw OIDC claims or SAML assertion attributes, unmapped. */
62
+ profile?: Record<string, unknown> | undefined;
63
+ };
64
+ /** Provisioning origin passed to `createUser`; the creation seam adds `action: "create-user"` to build {@link ValidateUserInfoSource}. */
65
+ type UserProvisioningSource = {
66
+ method: ValidateUserInfoMethod; /** Provider id and raw profile; present iff `method` is `"oauth"`. */
67
+ oauth?: ValidateUserInfoOAuthInfo | undefined; /** Provider id and raw profile; present iff `method` is `"sso-oidc"` or `"sso-saml"`. */
68
+ sso?: ValidateUserInfoSSOInfo | undefined;
69
+ };
70
+ /**
71
+ * The context passed to `validateUserInfo`: the lifecycle
72
+ * {@link ValidateUserInfoAction}, the {@link ValidateUserInfoMethod}, and (for
73
+ * OAuth/SSO provider methods) protocol-specific provider metadata.
74
+ *
75
+ * ```ts
76
+ * // Scope to one OAuth provider:
77
+ * if (source.oauth?.providerId !== "google") return;
78
+ * // Branch on the method:
79
+ * if (source.method === "anonymous") return { error: "no_anonymous" };
80
+ * // Inspect SSO claims:
81
+ * if (source.method === "sso-saml" && source.sso?.profile?.department !== "eng") {
82
+ * return { error: "invalid_department" };
83
+ * }
84
+ * ```
85
+ */
86
+ type ValidateUserInfoSource = UserProvisioningSource & {
87
+ action: ValidateUserInfoAction;
88
+ };
89
+ type ValidateUserInfoResult = {
90
+ /** A short, machine-readable rejection code, surfaced to the client. */error: string;
91
+ /**
92
+ * A human-readable reason, surfaced to the client. Do not put sensitive
93
+ * details here.
94
+ */
95
+ errorDescription?: string | undefined;
96
+ };
30
97
  /**
31
98
  * Configuration for dynamic base URL resolution.
32
99
  * Allows Better Auth to work with multiple domains (e.g., Vercel preview deployments).
@@ -71,8 +138,30 @@ type DynamicBaseURLConfig = {
71
138
  */
72
139
  type BaseURLConfig = string | DynamicBaseURLConfig;
73
140
  interface BetterAuthRateLimitStorage {
74
- get: (key: string) => Promise<RateLimit | null | undefined>;
75
- set: (key: string, value: RateLimit, update?: boolean | undefined) => Promise<void>;
141
+ /**
142
+ * Atomically records one request against `key` within the rolling `window`
143
+ * (in seconds) and reports whether it is allowed.
144
+ *
145
+ * When `allowed` is true the count was incremented within the active window,
146
+ * or the window had elapsed and was reset to start at 1. When `allowed` is
147
+ * false the limit was already reached and `retryAfter` is the number of
148
+ * seconds until the window frees up.
149
+ *
150
+ * Performing the check and the increment in a single step closes the
151
+ * concurrent-bypass gap of the separate `get`/`set` path: N simultaneous
152
+ * requests can no longer all pass a stale read before any increment lands.
153
+ *
154
+ * Custom storages must implement this operation directly. Better Auth no
155
+ * longer accepts separate `get`/`set` rate-limit storage because that shape
156
+ * cannot enforce a distributed limit under concurrent requests.
157
+ */
158
+ consume: (key: string, rule: {
159
+ window: number;
160
+ max: number;
161
+ }) => Promise<{
162
+ allowed: boolean;
163
+ retryAfter: number | null;
164
+ }>;
76
165
  }
77
166
  type BetterAuthRateLimitRule = {
78
167
  /**
@@ -684,6 +773,30 @@ type BetterAuthOptions = {
684
773
  * User configuration
685
774
  */
686
775
  user?: (BetterAuthDBOptions<"user", keyof BaseUser> & {
776
+ /**
777
+ * Gate which identities Better Auth admits. Called just before
778
+ * `create-user`, `link-account`, and (for OAuth) `sign-in`, across
779
+ * every authentication method, including stateless setups with no
780
+ * persistent database. On `sign-in` the hook receives the *fresh*
781
+ * provider email and profile, so a domain policy can reject a user
782
+ * whose provider identity moved out of bounds.
783
+ *
784
+ * Non-provider returning sign-ins are not re-validated; use the admin
785
+ * plugin's ban controls or a `databaseHooks.session.create.before`
786
+ * hook for those.
787
+ *
788
+ * Return nothing to allow; return `{ error }` to reject. Browser flows
789
+ * redirect to the configured error URL; programmatic flows surface a
790
+ * `403`.
791
+ *
792
+ * TODO: rename to `validateUser` (and the `ValidateUserInfo*` types).
793
+ * "UserInfo" is the OIDC term and misleads for the email/password,
794
+ * SIWE, phone, and admin methods.
795
+ */
796
+ validateUserInfo?: (data: {
797
+ user: Partial<User> & Record<string, unknown>;
798
+ source: ValidateUserInfoSource;
799
+ }, context: GenericEndpointContext) => Awaitable<void | ValidateUserInfoResult>;
687
800
  /**
688
801
  * Changing email configuration
689
802
  */
@@ -825,6 +938,20 @@ type BetterAuthOptions = {
825
938
  * @default "compact"
826
939
  */
827
940
  strategy?: "compact" | "jwt" | "jwe";
941
+ /**
942
+ * JWT-specific configuration for `strategy: "jwt"`.
943
+ */
944
+ jwt?: {
945
+ /**
946
+ * Which signing key is used for cookie-cache JWTs.
947
+ *
948
+ * - `"secret"`: uses the Better Auth secret with HS256.
949
+ * - `"jwt-plugin"`: uses the installed `jwt()` plugin's asymmetric signing keys.
950
+ *
951
+ * @default "secret"
952
+ */
953
+ signingKey?: "secret" | "jwt-plugin";
954
+ };
828
955
  /**
829
956
  * Controls stateless cookie cache refresh behavior.
830
957
  *
@@ -1004,9 +1131,13 @@ type BetterAuthOptions = {
1004
1131
  */
1005
1132
  storeStateStrategy?: "database" | "cookie";
1006
1133
  /**
1007
- * Store account data after oauth flow on a cookie
1134
+ * Store provider account data after an OAuth flow in an encrypted
1135
+ * cookie. This includes OAuth token material such as access tokens,
1136
+ * refresh tokens, ID tokens, scopes, and token expiry.
1008
1137
  *
1009
- * This is useful for database-less flow
1138
+ * This is useful for database-less flows, but large provider tokens can
1139
+ * still hit browser or proxy cookie/header limits even though Better Auth
1140
+ * chunks oversized account cookies.
1010
1141
  *
1011
1142
  * @default false
1012
1143
  *
@@ -1379,4 +1510,4 @@ type BetterAuthOptions = {
1379
1510
  };
1380
1511
  };
1381
1512
  //#endregion
1382
- export { BaseURLConfig, BetterAuthAdvancedOptions, BetterAuthDBOptions, BetterAuthOptions, BetterAuthRateLimitOptions, BetterAuthRateLimitRule, BetterAuthRateLimitStorage, DynamicBaseURLConfig, GenerateIdFn, StoreIdentifierOption };
1513
+ export { BaseURLConfig, BetterAuthAdvancedOptions, BetterAuthDBOptions, BetterAuthOptions, BetterAuthRateLimitOptions, BetterAuthRateLimitRule, BetterAuthRateLimitStorage, DynamicBaseURLConfig, GenerateIdFn, StoreIdentifierOption, UserProvisioningSource, ValidateUserInfoAction, ValidateUserInfoMethod, ValidateUserInfoOAuthInfo, ValidateUserInfoResult, ValidateUserInfoSSOInfo, ValidateUserInfoSource };
@@ -1,10 +1,20 @@
1
1
  import { LiteralString } from "./helper.mjs";
2
- import { BetterAuthPlugin } from "./plugin.mjs";
3
2
  import { BetterAuthOptions } from "./init-options.mjs";
4
3
  import { BetterFetch, BetterFetchOption, BetterFetchPlugin } from "@better-fetch/fetch";
5
4
  import { Atom, WritableAtom } from "nanostores";
6
5
 
7
6
  //#region src/types/plugin-client.d.ts
7
+ type InferableServerPlugin = {
8
+ id?: LiteralString | undefined;
9
+ endpoints?: Record<string, unknown> | undefined;
10
+ schema?: Record<string, {
11
+ fields: Record<string, unknown>;
12
+ }> | undefined;
13
+ $ERROR_CODES?: Record<string, {
14
+ readonly code: string;
15
+ message: string;
16
+ }> | undefined;
17
+ };
8
18
  interface ClientStore {
9
19
  notify: (signal: string) => void;
10
20
  listen: (signal: string, listener: () => void) => void;
@@ -71,7 +81,7 @@ interface BetterAuthClientPlugin {
71
81
  * only used for type inference. don't pass the
72
82
  * actual plugin
73
83
  */
74
- $InferServerPlugin?: BetterAuthPlugin | undefined;
84
+ $InferServerPlugin?: InferableServerPlugin | undefined;
75
85
  /**
76
86
  * Custom actions
77
87
  */
@@ -126,6 +126,7 @@ function classifyIPv6(expanded) {
126
126
  if (firstByte === 254 && (secondByte & 192) === 128) return "linkLocal";
127
127
  if ((firstByte & 254) === 252) return "private";
128
128
  if (expanded.startsWith("2001:0db8:")) return "documentation";
129
+ if (expanded.startsWith("2001:0002:0000:")) return "benchmarking";
129
130
  if (expanded.startsWith("2002:")) {
130
131
  const embedded = extractEmbeddedIPv4(expanded, 1);
131
132
  if (embedded && classifyIPv4(embedded) !== "public") return "reserved";
@@ -136,12 +137,15 @@ function classifyIPv6(expanded) {
136
137
  if (embedded && classifyIPv4(embedded) !== "public") return "reserved";
137
138
  return "reserved";
138
139
  }
140
+ if (expanded.startsWith("0064:ff9b:0001:")) return "reserved";
139
141
  if (expanded.startsWith("2001:0000:")) {
140
142
  const embedded = extractEmbeddedIPv4(expanded, 6, { xor: true });
141
143
  if (embedded && classifyIPv4(embedded) !== "public") return "reserved";
142
144
  return "reserved";
143
145
  }
144
146
  if (expanded.startsWith("0100:0000:0000:0000:")) return "reserved";
147
+ if (expanded.startsWith("3fff:0")) return "documentation";
148
+ if (expanded.startsWith("5f00:")) return "reserved";
145
149
  return "public";
146
150
  }
147
151
  /**
@@ -22,9 +22,10 @@ function normalizePathname(requestUrl, basePath) {
22
22
  } catch {
23
23
  return "/";
24
24
  }
25
- if (basePath === "/" || basePath === "") return pathname;
26
- if (pathname === basePath) return "/";
27
- if (pathname.startsWith(basePath + "/")) return pathname.slice(basePath.length).replace(/\/+$/, "") || "/";
25
+ const normalizedBasePath = basePath.replace(/\/+$/, "");
26
+ if (normalizedBasePath === "") return pathname;
27
+ if (pathname === normalizedBasePath) return "/";
28
+ if (pathname.startsWith(normalizedBasePath + "/")) return pathname.slice(normalizedBasePath.length).replace(/\/+$/, "") || "/";
28
29
  return pathname;
29
30
  }
30
31
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@better-auth/core",
3
- "version": "1.7.0-beta.4",
3
+ "version": "1.7.0-beta.6",
4
4
  "description": "The most comprehensive authentication framework for TypeScript.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -152,12 +152,12 @@
152
152
  "zod": "^4.3.6"
153
153
  },
154
154
  "devDependencies": {
155
- "@better-auth/utils": "0.4.1",
156
- "@better-fetch/fetch": "1.1.21",
155
+ "@better-auth/utils": "0.4.2",
156
+ "@better-fetch/fetch": "1.3.1",
157
157
  "@opentelemetry/api": "^1.9.0",
158
158
  "@opentelemetry/sdk-trace-base": "^1.30.0",
159
159
  "@opentelemetry/sdk-trace-node": "^1.30.0",
160
- "better-call": "1.3.5",
160
+ "better-call": "1.3.6",
161
161
  "@cloudflare/workers-types": "^4.20250121.0",
162
162
  "jose": "^6.1.3",
163
163
  "kysely": "^0.28.17 || ^0.29.0",
@@ -165,10 +165,10 @@
165
165
  "tsdown": "0.21.1"
166
166
  },
167
167
  "peerDependencies": {
168
- "@better-auth/utils": "0.4.1",
169
- "@better-fetch/fetch": "1.1.21",
168
+ "@better-auth/utils": "0.4.2",
169
+ "@better-fetch/fetch": "1.3.1",
170
170
  "@opentelemetry/api": "^1.9.0",
171
- "better-call": "1.3.5",
171
+ "better-call": "1.3.6",
172
172
  "@cloudflare/workers-types": ">=4",
173
173
  "jose": "^6.1.0",
174
174
  "kysely": "^0.28.5 || ^0.29.0",