@better-auth/core 1.7.0-beta.3 → 1.7.0-beta.5

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 (188) hide show
  1. package/dist/api/index.d.mts +3 -3
  2. package/dist/context/global.mjs +1 -1
  3. package/dist/db/adapter/factory.mjs +62 -0
  4. package/dist/db/adapter/index.d.mts +35 -1
  5. package/dist/db/adapter/types.d.mts +1 -1
  6. package/dist/db/get-tables.mjs +3 -3
  7. package/dist/db/schema/account.d.mts +1 -1
  8. package/dist/db/schema/account.mjs +1 -1
  9. package/dist/db/type.d.mts +12 -0
  10. package/dist/env/env-impl.mjs +1 -1
  11. package/dist/error/codes.d.mts +6 -0
  12. package/dist/error/codes.mjs +6 -0
  13. package/dist/index.d.mts +2 -2
  14. package/dist/instrumentation/tracer.mjs +1 -1
  15. package/dist/oauth2/authorization-params.d.mts +12 -0
  16. package/dist/oauth2/authorization-params.mjs +12 -0
  17. package/dist/oauth2/basic-credentials.d.mts +30 -0
  18. package/dist/oauth2/basic-credentials.mjs +64 -0
  19. package/dist/oauth2/client-assertion.d.mts +38 -22
  20. package/dist/oauth2/client-assertion.mjs +63 -28
  21. package/dist/oauth2/client-credentials-token.d.mts +19 -40
  22. package/dist/oauth2/client-credentials-token.mjs +18 -29
  23. package/dist/oauth2/create-authorization-url.d.mts +13 -2
  24. package/dist/oauth2/create-authorization-url.mjs +28 -7
  25. package/dist/oauth2/index.d.mts +13 -8
  26. package/dist/oauth2/index.mjs +11 -7
  27. package/dist/oauth2/oauth-provider.d.mts +149 -11
  28. package/dist/oauth2/refresh-access-token.d.mts +20 -40
  29. package/dist/oauth2/refresh-access-token.mjs +20 -33
  30. package/dist/oauth2/scopes.d.mts +76 -0
  31. package/dist/oauth2/scopes.mjs +96 -0
  32. package/dist/oauth2/token-endpoint-auth.d.mts +17 -0
  33. package/dist/oauth2/token-endpoint-auth.mjs +89 -0
  34. package/dist/oauth2/utils.d.mts +9 -1
  35. package/dist/oauth2/utils.mjs +14 -2
  36. package/dist/oauth2/validate-authorization-code.d.mts +17 -52
  37. package/dist/oauth2/validate-authorization-code.mjs +17 -30
  38. package/dist/oauth2/verify-id-token.d.mts +26 -0
  39. package/dist/oauth2/verify-id-token.mjs +62 -0
  40. package/dist/oauth2/verify.d.mts +14 -0
  41. package/dist/oauth2/verify.mjs +38 -12
  42. package/dist/social-providers/apple.d.mts +18 -20
  43. package/dist/social-providers/apple.mjs +15 -28
  44. package/dist/social-providers/atlassian.d.mts +8 -2
  45. package/dist/social-providers/atlassian.mjs +9 -6
  46. package/dist/social-providers/cognito.d.mts +29 -3
  47. package/dist/social-providers/cognito.mjs +30 -34
  48. package/dist/social-providers/discord.d.mts +8 -2
  49. package/dist/social-providers/discord.mjs +20 -6
  50. package/dist/social-providers/dropbox.d.mts +8 -2
  51. package/dist/social-providers/dropbox.mjs +10 -9
  52. package/dist/social-providers/facebook.d.mts +24 -3
  53. package/dist/social-providers/facebook.mjs +51 -24
  54. package/dist/social-providers/figma.d.mts +8 -2
  55. package/dist/social-providers/figma.mjs +8 -7
  56. package/dist/social-providers/github.d.mts +8 -2
  57. package/dist/social-providers/github.mjs +9 -8
  58. package/dist/social-providers/gitlab.d.mts +8 -2
  59. package/dist/social-providers/gitlab.mjs +8 -7
  60. package/dist/social-providers/google.d.mts +32 -4
  61. package/dist/social-providers/google.mjs +26 -29
  62. package/dist/social-providers/huggingface.d.mts +8 -2
  63. package/dist/social-providers/huggingface.mjs +11 -10
  64. package/dist/social-providers/index.d.mts +322 -75
  65. package/dist/social-providers/kakao.d.mts +8 -2
  66. package/dist/social-providers/kakao.mjs +11 -10
  67. package/dist/social-providers/kick.d.mts +8 -2
  68. package/dist/social-providers/kick.mjs +7 -6
  69. package/dist/social-providers/line.d.mts +11 -3
  70. package/dist/social-providers/line.mjs +14 -15
  71. package/dist/social-providers/linear.d.mts +8 -2
  72. package/dist/social-providers/linear.mjs +7 -6
  73. package/dist/social-providers/linkedin.d.mts +8 -2
  74. package/dist/social-providers/linkedin.mjs +12 -11
  75. package/dist/social-providers/microsoft-entra-id.d.mts +33 -7
  76. package/dist/social-providers/microsoft-entra-id.mjs +28 -38
  77. package/dist/social-providers/naver.d.mts +8 -2
  78. package/dist/social-providers/naver.mjs +7 -6
  79. package/dist/social-providers/notion.d.mts +8 -2
  80. package/dist/social-providers/notion.mjs +9 -6
  81. package/dist/social-providers/paybin.d.mts +8 -2
  82. package/dist/social-providers/paybin.mjs +12 -11
  83. package/dist/social-providers/paypal.d.mts +8 -3
  84. package/dist/social-providers/paypal.mjs +10 -14
  85. package/dist/social-providers/polar.d.mts +8 -2
  86. package/dist/social-providers/polar.mjs +11 -10
  87. package/dist/social-providers/railway.d.mts +8 -2
  88. package/dist/social-providers/railway.mjs +11 -10
  89. package/dist/social-providers/reddit.d.mts +8 -2
  90. package/dist/social-providers/reddit.mjs +11 -9
  91. package/dist/social-providers/roblox.d.mts +8 -2
  92. package/dist/social-providers/roblox.mjs +15 -5
  93. package/dist/social-providers/salesforce.d.mts +8 -2
  94. package/dist/social-providers/salesforce.mjs +11 -10
  95. package/dist/social-providers/slack.d.mts +8 -2
  96. package/dist/social-providers/slack.mjs +18 -15
  97. package/dist/social-providers/spotify.d.mts +8 -2
  98. package/dist/social-providers/spotify.mjs +7 -6
  99. package/dist/social-providers/tiktok.d.mts +8 -2
  100. package/dist/social-providers/tiktok.mjs +21 -5
  101. package/dist/social-providers/twitch.d.mts +8 -2
  102. package/dist/social-providers/twitch.mjs +7 -6
  103. package/dist/social-providers/twitter.d.mts +7 -2
  104. package/dist/social-providers/twitter.mjs +11 -10
  105. package/dist/social-providers/vercel.d.mts +8 -2
  106. package/dist/social-providers/vercel.mjs +7 -9
  107. package/dist/social-providers/vk.d.mts +8 -2
  108. package/dist/social-providers/vk.mjs +7 -6
  109. package/dist/social-providers/wechat.d.mts +8 -2
  110. package/dist/social-providers/wechat.mjs +16 -6
  111. package/dist/social-providers/zoom.d.mts +10 -3
  112. package/dist/social-providers/zoom.mjs +14 -15
  113. package/dist/types/context.d.mts +33 -11
  114. package/dist/types/index.d.mts +1 -1
  115. package/dist/types/init-options.d.mts +121 -6
  116. package/dist/utils/ip.d.mts +5 -4
  117. package/dist/utils/ip.mjs +3 -3
  118. package/dist/utils/redirect-uri.d.mts +20 -0
  119. package/dist/utils/redirect-uri.mjs +48 -0
  120. package/dist/utils/string.d.mts +5 -1
  121. package/dist/utils/string.mjs +20 -1
  122. package/dist/utils/url.d.mts +18 -1
  123. package/dist/utils/url.mjs +30 -1
  124. package/package.json +13 -12
  125. package/src/db/adapter/factory.ts +126 -0
  126. package/src/db/adapter/index.ts +32 -0
  127. package/src/db/adapter/types.ts +1 -0
  128. package/src/db/get-tables.ts +8 -3
  129. package/src/db/schema/account.ts +14 -2
  130. package/src/db/type.ts +12 -0
  131. package/src/env/env-impl.ts +1 -2
  132. package/src/error/codes.ts +6 -0
  133. package/src/oauth2/authorization-params.ts +28 -0
  134. package/src/oauth2/basic-credentials.ts +87 -0
  135. package/src/oauth2/client-assertion.ts +131 -58
  136. package/src/oauth2/client-credentials-token.ts +48 -72
  137. package/src/oauth2/create-authorization-url.ts +30 -8
  138. package/src/oauth2/index.ts +42 -10
  139. package/src/oauth2/oauth-provider.ts +161 -12
  140. package/src/oauth2/refresh-access-token.ts +52 -78
  141. package/src/oauth2/scopes.ts +118 -0
  142. package/src/oauth2/token-endpoint-auth.ts +221 -0
  143. package/src/oauth2/utils.ts +21 -5
  144. package/src/oauth2/validate-authorization-code.ts +55 -85
  145. package/src/oauth2/verify-id-token.ts +111 -0
  146. package/src/oauth2/verify.ts +82 -15
  147. package/src/social-providers/apple.ts +32 -45
  148. package/src/social-providers/atlassian.ts +20 -9
  149. package/src/social-providers/cognito.ts +51 -48
  150. package/src/social-providers/discord.ts +37 -22
  151. package/src/social-providers/dropbox.ts +20 -12
  152. package/src/social-providers/facebook.ts +108 -57
  153. package/src/social-providers/figma.ts +21 -10
  154. package/src/social-providers/github.ts +16 -10
  155. package/src/social-providers/gitlab.ts +16 -8
  156. package/src/social-providers/google.ts +67 -46
  157. package/src/social-providers/huggingface.ts +20 -9
  158. package/src/social-providers/kakao.ts +18 -9
  159. package/src/social-providers/kick.ts +20 -8
  160. package/src/social-providers/line.ts +39 -37
  161. package/src/social-providers/linear.ts +20 -7
  162. package/src/social-providers/linkedin.ts +16 -10
  163. package/src/social-providers/microsoft-entra-id.ts +66 -64
  164. package/src/social-providers/naver.ts +14 -7
  165. package/src/social-providers/notion.ts +20 -7
  166. package/src/social-providers/paybin.ts +16 -11
  167. package/src/social-providers/paypal.ts +12 -25
  168. package/src/social-providers/polar.ts +20 -9
  169. package/src/social-providers/railway.ts +20 -9
  170. package/src/social-providers/reddit.ts +22 -10
  171. package/src/social-providers/roblox.ts +31 -15
  172. package/src/social-providers/salesforce.ts +21 -10
  173. package/src/social-providers/slack.ts +31 -16
  174. package/src/social-providers/spotify.ts +20 -7
  175. package/src/social-providers/tiktok.ts +32 -13
  176. package/src/social-providers/twitch.ts +14 -9
  177. package/src/social-providers/twitter.ts +18 -8
  178. package/src/social-providers/vercel.ts +24 -11
  179. package/src/social-providers/vk.ts +20 -7
  180. package/src/social-providers/wechat.ts +28 -8
  181. package/src/social-providers/zoom.ts +28 -19
  182. package/src/types/context.ts +33 -12
  183. package/src/types/index.ts +7 -0
  184. package/src/types/init-options.ts +148 -5
  185. package/src/utils/ip.ts +12 -13
  186. package/src/utils/redirect-uri.ts +54 -0
  187. package/src/utils/string.ts +37 -0
  188. package/src/utils/url.ts +28 -0
@@ -2,7 +2,7 @@ import { BetterAuthDBSchema, ModelNames, SecondaryStorage } from "../db/type.mjs
2
2
  import { DBAdapter } from "../db/adapter/index.mjs";
3
3
  import { createLogger } from "../env/logger.mjs";
4
4
  import { AuthContext } from "../types/context.mjs";
5
- import { OAuthProvider } from "../oauth2/oauth-provider.mjs";
5
+ import { UpstreamProvider } from "../oauth2/oauth-provider.mjs";
6
6
  import * as better_call0 from "better-call";
7
7
  import { EndpointContext, EndpointOptions, StrictEndpoint } from "better-call";
8
8
  import * as _better_auth_core0 from "@better-auth/core";
@@ -87,7 +87,7 @@ declare const createAuthMiddleware: {
87
87
  image?: string | null | undefined;
88
88
  } & Record<string, any>;
89
89
  } | null) => void;
90
- socialProviders: OAuthProvider[];
90
+ socialProviders: UpstreamProvider[];
91
91
  authCookies: _better_auth_core0.BetterAuthCookies;
92
92
  logger: ReturnType<typeof createLogger>;
93
93
  rateLimit: {
@@ -216,7 +216,7 @@ declare const createAuthMiddleware: {
216
216
  image?: string | null | undefined;
217
217
  } & Record<string, any>;
218
218
  } | null) => void;
219
- socialProviders: OAuthProvider[];
219
+ socialProviders: UpstreamProvider[];
220
220
  authCookies: _better_auth_core0.BetterAuthCookies;
221
221
  logger: ReturnType<typeof createLogger>;
222
222
  rateLimit: {
@@ -2,7 +2,7 @@
2
2
  const symbol = Symbol.for("better-auth:global");
3
3
  let bind = null;
4
4
  const __context = {};
5
- const __betterAuthVersion = "1.7.0-beta.3";
5
+ const __betterAuthVersion = "1.7.0-beta.5";
6
6
  /**
7
7
  * We store context instance in the globalThis.
8
8
  *
@@ -57,6 +57,7 @@ const createAdapterFactory = ({ adapter: customAdapter, config: cfg }) => (optio
57
57
  else if (method === "findMany" && !config.debugLogs.findMany) return;
58
58
  else if (method === "delete" && !config.debugLogs.delete) return;
59
59
  else if (method === "deleteMany" && !config.debugLogs.deleteMany) return;
60
+ else if (method === "consumeOne" && !config.debugLogs.consumeOne) return;
60
61
  else if (method === "count" && !config.debugLogs.count) return;
61
62
  }
62
63
  logger.info(`[${config.adapterName}]`, ...args);
@@ -676,6 +677,67 @@ const createAdapterFactory = ({ adapter: customAdapter, config: cfg }) => (optio
676
677
  });
677
678
  return res;
678
679
  },
680
+ consumeOne: async ({ model: unsafeModel, where: unsafeWhere }) => {
681
+ transactionId++;
682
+ const thisTransactionId = transactionId;
683
+ const model = getModelName(unsafeModel);
684
+ const where = transformWhereClause({
685
+ model: unsafeModel,
686
+ where: unsafeWhere,
687
+ action: "consumeOne"
688
+ });
689
+ unsafeModel = getDefaultModelName(unsafeModel);
690
+ debugLog({ method: "consumeOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("consumeOne")} ${formatAction("ConsumeOne")}:`, {
691
+ model,
692
+ where
693
+ });
694
+ let res;
695
+ let resultNeedsOutputTransform = true;
696
+ if (adapterInstance.consumeOne) res = await withSpan(`db consumeOne ${model}`, {
697
+ [ATTR_DB_OPERATION_NAME]: "consumeOne",
698
+ [ATTR_DB_COLLECTION_NAME]: model
699
+ }, () => adapterInstance.consumeOne({
700
+ model,
701
+ where
702
+ }));
703
+ else {
704
+ res = await withSpan(`db consumeOne ${model}`, {
705
+ [ATTR_DB_OPERATION_NAME]: "consumeOne",
706
+ [ATTR_DB_COLLECTION_NAME]: model
707
+ }, () => adapter.transaction(async (trx) => {
708
+ const target = (await trx.findMany({
709
+ model: unsafeModel,
710
+ where: unsafeWhere,
711
+ limit: 1
712
+ }))[0];
713
+ if (!target) return null;
714
+ const deleted = await trx.deleteMany({
715
+ model: unsafeModel,
716
+ where: [...unsafeWhere, {
717
+ field: "id",
718
+ value: target.id,
719
+ operator: "eq",
720
+ connector: "AND",
721
+ mode: "sensitive"
722
+ }]
723
+ });
724
+ if (typeof deleted !== "number") throw new BetterAuthError(`Adapter "${config.adapterId}" returned a non-numeric value from deleteMany during the consumeOne fallback. Return the number of deleted rows, or implement a native consumeOne for atomic single-use consumption.`);
725
+ return Number.isFinite(deleted) && deleted > 0 ? target : null;
726
+ }));
727
+ resultNeedsOutputTransform = false;
728
+ }
729
+ debugLog({ method: "consumeOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("consumeOne")} ${formatAction("DB Result")}:`, {
730
+ model,
731
+ data: res
732
+ });
733
+ let transformed = res;
734
+ if (!config.disableTransformOutput && resultNeedsOutputTransform && res) transformed = await transformOutput(res, unsafeModel, void 0, void 0);
735
+ debugLog({ method: "consumeOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("consumeOne")} ${formatAction("Parsed Result")}:`, {
736
+ model,
737
+ data: transformed
738
+ });
739
+ return transformed;
740
+ },
679
741
  count: async ({ model: unsafeModel, where: unsafeWhere }) => {
680
742
  transactionId++;
681
743
  const thisTransactionId = transactionId;
@@ -22,6 +22,7 @@ type DBAdapterDebugLogOption = boolean | {
22
22
  findMany?: boolean | undefined;
23
23
  delete?: boolean | undefined;
24
24
  deleteMany?: boolean | undefined;
25
+ consumeOne?: boolean | undefined;
25
26
  count?: boolean | undefined;
26
27
  } | {
27
28
  /**
@@ -197,7 +198,7 @@ interface DBAdapterFactoryConfig<Options extends BetterAuthOptions = BetterAuthO
197
198
  /**
198
199
  * The action which was called from the adapter.
199
200
  */
200
- action: "create" | "update" | "findOne" | "findMany" | "updateMany" | "delete" | "deleteMany" | "count";
201
+ action: "create" | "update" | "findOne" | "findMany" | "updateMany" | "delete" | "deleteMany" | "consumeOne" | "count";
201
202
  /**
202
203
  * The model name.
203
204
  */
@@ -415,6 +416,26 @@ type DBAdapter<Options extends BetterAuthOptions = BetterAuthOptions> = {
415
416
  model: string;
416
417
  where: Where[];
417
418
  }) => Promise<number>;
419
+ /**
420
+ * Atomically consume a single row matching the where clause: delete it and
421
+ * return the deleted row, or return `null` if no row matched.
422
+ * Implementations MUST NOT delete any additional rows that also match a
423
+ * non-unique predicate.
424
+ *
425
+ * Under concurrent invocation against the same row, exactly one caller
426
+ * receives the row; subsequent racers receive `null`. This is the
427
+ * race-safe primitive for consuming single-use credentials
428
+ * (verification tokens, authorization codes, one-time tokens).
429
+ *
430
+ * Always defined on the factory-wrapped adapter. When the underlying
431
+ * `CustomAdapter` does not implement `consumeOne`, the factory provides
432
+ * a fallback that wraps `findMany + deleteMany` in `transaction(...)`
433
+ * and returns the row only when the delete reports an affected row.
434
+ */
435
+ consumeOne: <T>(data: {
436
+ model: string;
437
+ where: Where[];
438
+ }) => Promise<T | null>;
418
439
  /**
419
440
  * Execute multiple operations in a transaction.
420
441
  * If the adapter doesn't support transactions, operations will be executed sequentially.
@@ -496,6 +517,19 @@ interface CustomAdapter {
496
517
  model: string;
497
518
  where: CleanedWhere[];
498
519
  }) => Promise<number>;
520
+ /**
521
+ * Optional native atomic single-row consume. When omitted, the adapter
522
+ * factory falls back to `transaction(findMany + deleteMany)`.
523
+ * Implementing this method natively (e.g. `DELETE ... RETURNING *`,
524
+ * `findOneAndDelete`, `OUTPUT deleted.*`) gives one round trip and the
525
+ * strongest race-safety guarantee. Implementations must delete at most
526
+ * one matching row. TODO(consume-one-required): tighten to required in the
527
+ * next minor on `next`.
528
+ */
529
+ consumeOne?: <T>(data: {
530
+ model: string;
531
+ where: CleanedWhere[];
532
+ }) => Promise<T | null>;
499
533
  count: ({
500
534
  model,
501
535
  where
@@ -94,7 +94,7 @@ type AdapterFactoryCustomizeAdapterCreator = (config: {
94
94
  }: {
95
95
  where: W;
96
96
  model: string;
97
- action: "create" | "update" | "findOne" | "findMany" | "updateMany" | "delete" | "deleteMany" | "count";
97
+ action: "create" | "update" | "findOne" | "findMany" | "updateMany" | "delete" | "deleteMany" | "consumeOne" | "count";
98
98
  }) => W extends undefined ? undefined : CleanedWhere[];
99
99
  }) => CustomAdapter;
100
100
  type AdapterTestDebugLogs = {
@@ -228,10 +228,10 @@ const getAuthTables = (options) => {
228
228
  returned: false,
229
229
  fieldName: options.account?.fields?.refreshTokenExpiresAt || "refreshTokenExpiresAt"
230
230
  },
231
- scope: {
232
- type: "string",
231
+ grantedScopes: {
232
+ type: "string[]",
233
233
  required: false,
234
- fieldName: options.account?.fields?.scope || "scope"
234
+ fieldName: options.account?.fields?.grantedScopes || "grantedScopes"
235
235
  },
236
236
  password: {
237
237
  type: "string",
@@ -16,7 +16,7 @@ declare const accountSchema: z.ZodObject<{
16
16
  idToken: z.ZodOptional<z.ZodNullable<z.ZodString>>;
17
17
  accessTokenExpiresAt: z.ZodOptional<z.ZodNullable<z.ZodDate>>;
18
18
  refreshTokenExpiresAt: z.ZodOptional<z.ZodNullable<z.ZodDate>>;
19
- scope: z.ZodOptional<z.ZodNullable<z.ZodString>>;
19
+ grantedScopes: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
20
20
  password: z.ZodOptional<z.ZodNullable<z.ZodString>>;
21
21
  }, z.core.$strip>;
22
22
  type BaseAccount = z.infer<typeof accountSchema>;
@@ -10,7 +10,7 @@ const accountSchema = coreSchema.extend({
10
10
  idToken: z.string().nullish(),
11
11
  accessTokenExpiresAt: z.date().nullish(),
12
12
  refreshTokenExpiresAt: z.date().nullish(),
13
- scope: z.string().nullish(),
13
+ grantedScopes: z.array(z.string()).nullish(),
14
14
  password: z.string().nullish()
15
15
  });
16
16
  //#endregion
@@ -141,6 +141,18 @@ interface SecondaryStorage {
141
141
  * @returns - Value of the key
142
142
  */
143
143
  get: (key: string) => Awaitable<unknown>;
144
+ /**
145
+ * Atomically get a value and delete it from storage.
146
+ *
147
+ * This is optional for backwards compatibility with existing secondary
148
+ * storage implementations. Single-use credential consumers use it when
149
+ * present to avoid a read-then-delete race.
150
+ *
151
+ * TODO(secondary-storage-atomic-consume): make this required in the next
152
+ * breaking release, or require database-backed verification storage for
153
+ * security-sensitive consume paths.
154
+ */
155
+ getAndDelete?: (key: string) => Awaitable<unknown>;
144
156
  set: (
145
157
  /**
146
158
  * Key to store
@@ -27,7 +27,7 @@ const env = new Proxy(_envShim, {
27
27
  function toBoolean(val) {
28
28
  return val ? val !== "false" : false;
29
29
  }
30
- const nodeENV = typeof process !== "undefined" && process.env && process.env.NODE_ENV || "";
30
+ const nodeENV = env.NODE_ENV ?? "";
31
31
  /** Detect if `NODE_ENV` environment variable is `production` */
32
32
  const isProduction = nodeENV === "production";
33
33
  /** Detect if `NODE_ENV` environment variable is `dev` or `development` */
@@ -29,6 +29,11 @@ declare const BASE_ERROR_CODES: {
29
29
  TOKEN_EXPIRED: RawError<"TOKEN_EXPIRED">;
30
30
  ID_TOKEN_NOT_SUPPORTED: RawError<"ID_TOKEN_NOT_SUPPORTED">;
31
31
  FAILED_TO_GET_USER_INFO: RawError<"FAILED_TO_GET_USER_INFO">;
32
+ PROVIDER_NOT_SUPPORTED: RawError<"PROVIDER_NOT_SUPPORTED">;
33
+ TOKEN_REFRESH_NOT_SUPPORTED: RawError<"TOKEN_REFRESH_NOT_SUPPORTED">;
34
+ REFRESH_TOKEN_NOT_FOUND: RawError<"REFRESH_TOKEN_NOT_FOUND">;
35
+ FAILED_TO_GET_ACCESS_TOKEN: RawError<"FAILED_TO_GET_ACCESS_TOKEN">;
36
+ FAILED_TO_REFRESH_ACCESS_TOKEN: RawError<"FAILED_TO_REFRESH_ACCESS_TOKEN">;
32
37
  USER_EMAIL_NOT_FOUND: RawError<"USER_EMAIL_NOT_FOUND">;
33
38
  EMAIL_NOT_VERIFIED: RawError<"EMAIL_NOT_VERIFIED">;
34
39
  PASSWORD_TOO_SHORT: RawError<"PASSWORD_TOO_SHORT">;
@@ -36,6 +41,7 @@ declare const BASE_ERROR_CODES: {
36
41
  USER_ALREADY_EXISTS: RawError<"USER_ALREADY_EXISTS">;
37
42
  USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: RawError<"USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL">;
38
43
  EMAIL_CAN_NOT_BE_UPDATED: RawError<"EMAIL_CAN_NOT_BE_UPDATED">;
44
+ CHANGE_EMAIL_DISABLED: RawError<"CHANGE_EMAIL_DISABLED">;
39
45
  CREDENTIAL_ACCOUNT_NOT_FOUND: RawError<"CREDENTIAL_ACCOUNT_NOT_FOUND">;
40
46
  ACCOUNT_NOT_FOUND: RawError<"ACCOUNT_NOT_FOUND">;
41
47
  SESSION_EXPIRED: RawError<"SESSION_EXPIRED">;
@@ -16,6 +16,11 @@ const BASE_ERROR_CODES = defineErrorCodes({
16
16
  TOKEN_EXPIRED: "Token expired",
17
17
  ID_TOKEN_NOT_SUPPORTED: "id_token not supported",
18
18
  FAILED_TO_GET_USER_INFO: "Failed to get user info",
19
+ PROVIDER_NOT_SUPPORTED: "Provider not supported",
20
+ TOKEN_REFRESH_NOT_SUPPORTED: "Token refresh not supported",
21
+ REFRESH_TOKEN_NOT_FOUND: "Refresh token not found",
22
+ FAILED_TO_GET_ACCESS_TOKEN: "Failed to get a valid access token",
23
+ FAILED_TO_REFRESH_ACCESS_TOKEN: "Failed to refresh access token",
19
24
  USER_EMAIL_NOT_FOUND: "User email not found",
20
25
  EMAIL_NOT_VERIFIED: "Email not verified",
21
26
  PASSWORD_TOO_SHORT: "Password too short",
@@ -23,6 +28,7 @@ const BASE_ERROR_CODES = defineErrorCodes({
23
28
  USER_ALREADY_EXISTS: "User already exists.",
24
29
  USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: "User already exists. Use another email.",
25
30
  EMAIL_CAN_NOT_BE_UPDATED: "Email can not be updated",
31
+ CHANGE_EMAIL_DISABLED: "Change email is disabled",
26
32
  CREDENTIAL_ACCOUNT_NOT_FOUND: "Credential account not found",
27
33
  SESSION_EXPIRED: "Session expired. Re-authenticate to perform this action.",
28
34
  FAILED_TO_UNLINK_LAST_ACCOUNT: "You can't unlink your last account",
package/dist/index.d.mts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { Awaitable, AwaitableFunction, LiteralString, LiteralUnion, Prettify, Primitive, UnionToIntersection } from "./types/helper.mjs";
2
2
  import { BetterAuthPlugin, BetterAuthPluginErrorCodePart, HookEndpointContext } from "./types/plugin.mjs";
3
- import { BaseURLConfig, BetterAuthAdvancedOptions, BetterAuthDBOptions, BetterAuthOptions, BetterAuthRateLimitOptions, BetterAuthRateLimitRule, BetterAuthRateLimitStorage, DynamicBaseURLConfig, GenerateIdFn, StoreIdentifierOption } from "./types/init-options.mjs";
3
+ import { BaseURLConfig, BetterAuthAdvancedOptions, BetterAuthDBOptions, BetterAuthOptions, BetterAuthRateLimitOptions, BetterAuthRateLimitRule, BetterAuthRateLimitStorage, DynamicBaseURLConfig, GenerateIdFn, StoreIdentifierOption, UserProvisioningSource, ValidateUserInfoAction, ValidateUserInfoMethod, ValidateUserInfoOAuthInfo, ValidateUserInfoResult, ValidateUserInfoSSOInfo, ValidateUserInfoSource } from "./types/init-options.mjs";
4
4
  import { BetterAuthCookie, BetterAuthCookies } from "./types/cookie.mjs";
5
5
  import { SecretConfig } from "./types/secret.mjs";
6
6
  import { AuthContext, BetterAuthPluginRegistry, BetterAuthPluginRegistryIdentifier, GenericEndpointContext, InfoContext, InternalAdapter, PluginContext } from "./types/context.mjs";
7
7
  import { BetterAuthClientOptions, BetterAuthClientPlugin, ClientAtomListener, ClientFetchOption, ClientStore } from "./types/plugin-client.mjs";
8
8
  import { StandardSchemaV1 } from "./types/index.mjs";
9
- export { AuthContext, Awaitable, AwaitableFunction, BaseURLConfig, BetterAuthAdvancedOptions, BetterAuthClientOptions, BetterAuthClientPlugin, BetterAuthCookie, BetterAuthCookies, BetterAuthDBOptions, BetterAuthOptions, BetterAuthPlugin, BetterAuthPluginErrorCodePart, BetterAuthPluginRegistry, BetterAuthPluginRegistryIdentifier, BetterAuthRateLimitOptions, BetterAuthRateLimitRule, BetterAuthRateLimitStorage, ClientAtomListener, ClientFetchOption, ClientStore, DynamicBaseURLConfig, GenerateIdFn, GenericEndpointContext, HookEndpointContext, InfoContext, InternalAdapter, LiteralString, LiteralUnion, PluginContext, Prettify, Primitive, SecretConfig, StandardSchemaV1, StoreIdentifierOption, UnionToIntersection };
9
+ export { AuthContext, Awaitable, AwaitableFunction, BaseURLConfig, BetterAuthAdvancedOptions, BetterAuthClientOptions, BetterAuthClientPlugin, BetterAuthCookie, BetterAuthCookies, BetterAuthDBOptions, BetterAuthOptions, BetterAuthPlugin, BetterAuthPluginErrorCodePart, BetterAuthPluginRegistry, BetterAuthPluginRegistryIdentifier, BetterAuthRateLimitOptions, BetterAuthRateLimitRule, BetterAuthRateLimitStorage, ClientAtomListener, ClientFetchOption, ClientStore, DynamicBaseURLConfig, GenerateIdFn, GenericEndpointContext, HookEndpointContext, InfoContext, InternalAdapter, LiteralString, LiteralUnion, PluginContext, Prettify, Primitive, SecretConfig, StandardSchemaV1, StoreIdentifierOption, UnionToIntersection, UserProvisioningSource, ValidateUserInfoAction, ValidateUserInfoMethod, ValidateUserInfoOAuthInfo, ValidateUserInfoResult, ValidateUserInfoSSOInfo, ValidateUserInfoSource };
@@ -2,7 +2,7 @@ import { ATTR_HTTP_RESPONSE_STATUS_CODE } from "./attributes.mjs";
2
2
  import { getOpenTelemetryAPI } from "./api.mjs";
3
3
  //#region src/instrumentation/tracer.ts
4
4
  const INSTRUMENTATION_SCOPE = "better-auth";
5
- const INSTRUMENTATION_VERSION = "1.7.0-beta.3";
5
+ const INSTRUMENTATION_VERSION = "1.7.0-beta.5";
6
6
  /**
7
7
  * Better-auth uses `throw ctx.redirect(url)` for flow control (e.g. OAuth
8
8
  * callbacks). These are APIErrors with 3xx status codes and should not be
@@ -0,0 +1,12 @@
1
+ import * as z from "zod";
2
+
3
+ //#region src/oauth2/authorization-params.d.ts
4
+ /**
5
+ * Zod schema for the `additionalParams` field on social sign-in and
6
+ * account-linking request bodies. Rejects any key reserved by the
7
+ * authorization-URL builder (see `RESERVED_AUTHORIZATION_PARAMS`), so
8
+ * a caller cannot overwrite `state`, PKCE, `redirect_uri`, etc.
9
+ */
10
+ declare const additionalAuthorizationParamsSchema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
11
+ //#endregion
12
+ export { additionalAuthorizationParamsSchema };
@@ -0,0 +1,12 @@
1
+ import { RESERVED_AUTHORIZATION_PARAMS, RESERVED_AUTHORIZATION_PARAMS_SET } from "./create-authorization-url.mjs";
2
+ import * as z from "zod";
3
+ //#region src/oauth2/authorization-params.ts
4
+ /**
5
+ * Zod schema for the `additionalParams` field on social sign-in and
6
+ * account-linking request bodies. Rejects any key reserved by the
7
+ * authorization-URL builder (see `RESERVED_AUTHORIZATION_PARAMS`), so
8
+ * a caller cannot overwrite `state`, PKCE, `redirect_uri`, etc.
9
+ */
10
+ const additionalAuthorizationParamsSchema = z.record(z.string(), z.string()).refine((value) => !Object.keys(value).some((key) => RESERVED_AUTHORIZATION_PARAMS_SET.has(key)), { message: `additionalParams cannot include reserved OAuth parameters: ${RESERVED_AUTHORIZATION_PARAMS.join(", ")}` }).meta({ description: "Extra query parameters to append to the provider authorization URL (e.g. Cognito identity_provider, Google hd)." }).optional();
11
+ //#endregion
12
+ export { additionalAuthorizationParamsSchema };
@@ -0,0 +1,30 @@
1
+ //#region src/oauth2/basic-credentials.d.ts
2
+ /**
3
+ * Encodes an OAuth client id and secret as an HTTP Basic credential string.
4
+ *
5
+ * Follows RFC 6749 §2.3.1: both values are `application/x-www-form-urlencoded`
6
+ * prior to base64 encoding. The returned string is the full value of the
7
+ * `Authorization` header, including the `Basic ` prefix.
8
+ */
9
+ declare function encodeBasicCredentials(clientId: string, clientSecret: string): string;
10
+ /**
11
+ * Decodes an `Authorization: Basic …` header value into its OAuth client id
12
+ * and secret.
13
+ *
14
+ * Scheme matching is case-insensitive and tolerates one or more spaces
15
+ * between the scheme and credentials per RFC 7235 §2.1. The base64 payload
16
+ * is split on the first `:` only, so secrets containing colons round-trip
17
+ * correctly. Each half is form-url-decoded per RFC 6749 §2.3.1, accepting
18
+ * both `+` and `%20` as space. Per the URL Living Standard, invalid
19
+ * percent-escapes pass through as-is; downstream client lookup will fail
20
+ * with `invalid_client` for malformed credentials.
21
+ *
22
+ * Throws when the header is not a Basic credential, when the base64 payload
23
+ * contains no `:`, or when either half is empty.
24
+ */
25
+ declare function decodeBasicCredentials(authorization: string): {
26
+ clientId: string;
27
+ clientSecret: string;
28
+ };
29
+ //#endregion
30
+ export { decodeBasicCredentials, encodeBasicCredentials };
@@ -0,0 +1,64 @@
1
+ import { base64 } from "@better-auth/utils/base64";
2
+ //#region src/oauth2/basic-credentials.ts
3
+ const BASIC_AUTHORIZATION_PATTERN = /^Basic +(.*)$/i;
4
+ /**
5
+ * Encodes a value using `application/x-www-form-urlencoded` per the URL
6
+ * Living Standard. Differs from `encodeURIComponent` in two ways: it escapes
7
+ * `!`, `'`, `(`, and `)`, and it represents space as `+` rather than `%20`.
8
+ * `*` is left unescaped, matching the URL Standard's percent-encode set.
9
+ */
10
+ function formUrlEncode(value) {
11
+ return new URLSearchParams({ v: value }).toString().slice(2);
12
+ }
13
+ /**
14
+ * Inverse of `formUrlEncode`: decodes a single `application/x-www-form-urlencoded`
15
+ * value, handling both `+` and `%20` as space.
16
+ */
17
+ function formUrlDecode(value) {
18
+ const decoded = new URLSearchParams(`v=${value}`).get("v");
19
+ if (decoded === null) throw new Error("form-url-encoded value could not be decoded");
20
+ return decoded;
21
+ }
22
+ /**
23
+ * Encodes an OAuth client id and secret as an HTTP Basic credential string.
24
+ *
25
+ * Follows RFC 6749 §2.3.1: both values are `application/x-www-form-urlencoded`
26
+ * prior to base64 encoding. The returned string is the full value of the
27
+ * `Authorization` header, including the `Basic ` prefix.
28
+ */
29
+ function encodeBasicCredentials(clientId, clientSecret) {
30
+ const payload = `${formUrlEncode(clientId)}:${formUrlEncode(clientSecret)}`;
31
+ return `Basic ${base64.encode(payload)}`;
32
+ }
33
+ /**
34
+ * Decodes an `Authorization: Basic …` header value into its OAuth client id
35
+ * and secret.
36
+ *
37
+ * Scheme matching is case-insensitive and tolerates one or more spaces
38
+ * between the scheme and credentials per RFC 7235 §2.1. The base64 payload
39
+ * is split on the first `:` only, so secrets containing colons round-trip
40
+ * correctly. Each half is form-url-decoded per RFC 6749 §2.3.1, accepting
41
+ * both `+` and `%20` as space. Per the URL Living Standard, invalid
42
+ * percent-escapes pass through as-is; downstream client lookup will fail
43
+ * with `invalid_client` for malformed credentials.
44
+ *
45
+ * Throws when the header is not a Basic credential, when the base64 payload
46
+ * contains no `:`, or when either half is empty.
47
+ */
48
+ function decodeBasicCredentials(authorization) {
49
+ const match = authorization.match(BASIC_AUTHORIZATION_PATTERN);
50
+ if (!match) throw new Error("Authorization header is not a Basic credential");
51
+ const encoded = match[1] ?? "";
52
+ const decoded = new TextDecoder().decode(base64.decode(encoded));
53
+ const separatorIndex = decoded.indexOf(":");
54
+ if (separatorIndex === -1) throw new Error("Basic credential is missing the client id/secret separator");
55
+ const rawClientId = decoded.slice(0, separatorIndex);
56
+ const rawClientSecret = decoded.slice(separatorIndex + 1);
57
+ if (!rawClientId || !rawClientSecret) throw new Error("Basic credential client id and secret must both be non-empty");
58
+ return {
59
+ clientId: formUrlDecode(rawClientId),
60
+ clientSecret: formUrlDecode(rawClientSecret)
61
+ };
62
+ }
63
+ //#endregion
64
+ export { decodeBasicCredentials, encodeBasicCredentials };
@@ -1,11 +1,17 @@
1
+ import { Awaitable } from "../types/helper.mjs";
1
2
  //#region src/oauth2/client-assertion.d.ts
2
3
  /** Asymmetric signing algorithms compatible with private_key_jwt (RFC 7523). */
3
- declare const ASSERTION_SIGNING_ALGORITHMS: readonly ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512", "EdDSA"];
4
- type AssertionSigningAlgorithm = (typeof ASSERTION_SIGNING_ALGORITHMS)[number];
4
+ declare const PRIVATE_KEY_JWT_SIGNING_ALGORITHMS: readonly ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512", "EdDSA"];
5
+ type PrivateKeyJwtSigningAlgorithm = (typeof PRIVATE_KEY_JWT_SIGNING_ALGORITHMS)[number];
5
6
  declare const CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
6
- interface ClientAssertionConfig {
7
- /** Pre-signed JWT assertion string. If provided, signing is skipped. */
8
- assertion?: string;
7
+ type ClientAssertionGrantType = "authorization_code" | "refresh_token" | "client_credentials";
8
+ interface ClientAssertionContext {
9
+ clientId: string;
10
+ tokenEndpoint: string;
11
+ grantType: ClientAssertionGrantType;
12
+ }
13
+ type ClientAssertionGetter = (context: ClientAssertionContext) => Awaitable<string>;
14
+ interface PrivateKeyJwtClientAssertionGetterOptions {
9
15
  /** Private key in JWK format for signing. */
10
16
  privateKeyJwk?: JsonWebKey;
11
17
  /** Private key in PKCS#8 PEM format for signing. */
@@ -13,19 +19,23 @@ interface ClientAssertionConfig {
13
19
  /** Key ID to include in the JWT header. */
14
20
  kid?: string;
15
21
  /** Asymmetric signing algorithm. Symmetric algorithms (HS256) and "none" are not allowed. @default "RS256" */
16
- algorithm?: AssertionSigningAlgorithm;
17
- /** Token endpoint URL (used as the JWT `aud` claim). */
18
- tokenEndpoint?: string;
22
+ algorithm?: PrivateKeyJwtSigningAlgorithm;
19
23
  /** Assertion lifetime in seconds. @default 120 */
20
24
  expiresIn?: number;
21
25
  }
22
26
  /**
23
27
  * Signs an RFC 7523 client assertion JWT for `private_key_jwt` authentication.
24
28
  *
25
- * The JWT contains: iss=clientId, sub=clientId, aud=tokenEndpoint,
26
- * exp=now+120s, jti=unique, iat=now.
29
+ * The JWT contains these claims:
30
+ *
31
+ * - iss=clientId
32
+ * - sub=clientId
33
+ * - aud=tokenEndpoint
34
+ * - exp=now + 120s
35
+ * - jti=unique
36
+ * - iat=now
27
37
  */
28
- declare function signClientAssertion({
38
+ declare function signPrivateKeyJwtClientAssertion({
29
39
  clientId,
30
40
  tokenEndpoint,
31
41
  privateKeyJwk,
@@ -39,21 +49,27 @@ declare function signClientAssertion({
39
49
  privateKeyJwk?: JsonWebKey;
40
50
  privateKeyPem?: string;
41
51
  kid?: string;
42
- algorithm?: AssertionSigningAlgorithm;
52
+ algorithm?: PrivateKeyJwtSigningAlgorithm;
43
53
  expiresIn?: number;
44
54
  }): Promise<string>;
45
55
  /**
46
- * Resolves a ClientAssertionConfig into `client_assertion` + `client_assertion_type`
47
- * params for injection into a token request body.
56
+ * Creates a client assertion getter for `private_key_jwt` authentication.
57
+ *
58
+ * Validates options eagerly (key material, supported algorithm, JWK alg
59
+ * agreement) so misconfiguration surfaces at construction rather than on the
60
+ * first token request. The returned function signs a fresh RFC 7523 JWT
61
+ * assertion for every token endpoint request.
48
62
  */
49
- declare function resolveAssertionParams({
50
- clientAssertion,
51
- clientId,
52
- tokenEndpoint
63
+ declare function createPrivateKeyJwtClientAssertionGetter(options: PrivateKeyJwtClientAssertionGetterOptions): ClientAssertionGetter;
64
+ /**
65
+ * Resolves a client assertion getter into `client_assertion` + `client_assertion_type` params for injection into a token request body.
66
+ */
67
+ declare function resolveClientAssertionParams({
68
+ getClientAssertion,
69
+ context
53
70
  }: {
54
- clientAssertion: ClientAssertionConfig;
55
- clientId: string;
56
- tokenEndpoint?: string;
71
+ getClientAssertion: ClientAssertionGetter;
72
+ context: ClientAssertionContext;
57
73
  }): Promise<Record<string, string>>;
58
74
  //#endregion
59
- export { ASSERTION_SIGNING_ALGORITHMS, AssertionSigningAlgorithm, CLIENT_ASSERTION_TYPE, ClientAssertionConfig, resolveAssertionParams, signClientAssertion };
75
+ export { CLIENT_ASSERTION_TYPE, ClientAssertionContext, ClientAssertionGetter, ClientAssertionGrantType, PRIVATE_KEY_JWT_SIGNING_ALGORITHMS, PrivateKeyJwtClientAssertionGetterOptions, PrivateKeyJwtSigningAlgorithm, createPrivateKeyJwtClientAssertionGetter, resolveClientAssertionParams, signPrivateKeyJwtClientAssertion };