@better-auth/core 1.3.27 → 1.3.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/.turbo/turbo-build.log +54 -4
  2. package/build.config.ts +6 -0
  3. package/dist/db/adapter/index.d.cts +13 -23
  4. package/dist/db/adapter/index.d.mts +13 -23
  5. package/dist/db/adapter/index.d.ts +13 -23
  6. package/dist/db/index.cjs +16 -0
  7. package/dist/db/index.d.cts +6 -83
  8. package/dist/db/index.d.mts +6 -83
  9. package/dist/db/index.d.ts +6 -83
  10. package/dist/db/index.mjs +16 -1
  11. package/dist/env/index.cjs +312 -0
  12. package/dist/env/index.d.cts +36 -0
  13. package/dist/env/index.d.mts +36 -0
  14. package/dist/env/index.d.ts +36 -0
  15. package/dist/env/index.mjs +297 -0
  16. package/dist/error/index.cjs +44 -0
  17. package/dist/error/index.d.cts +33 -0
  18. package/dist/error/index.d.mts +33 -0
  19. package/dist/error/index.d.ts +33 -0
  20. package/dist/error/index.mjs +41 -0
  21. package/dist/index.d.cts +156 -101
  22. package/dist/index.d.mts +156 -101
  23. package/dist/index.d.ts +156 -101
  24. package/dist/middleware/index.cjs +25 -0
  25. package/dist/middleware/index.d.cts +13 -0
  26. package/dist/middleware/index.d.mts +13 -0
  27. package/dist/middleware/index.d.ts +13 -0
  28. package/dist/middleware/index.mjs +21 -0
  29. package/dist/oauth2/index.cjs +368 -0
  30. package/dist/oauth2/index.d.cts +100 -0
  31. package/dist/oauth2/index.d.mts +100 -0
  32. package/dist/oauth2/index.d.ts +100 -0
  33. package/dist/oauth2/index.mjs +357 -0
  34. package/dist/shared/core.Bl6TpxyD.d.mts +181 -0
  35. package/dist/shared/core.Bqe5IGAi.d.ts +13 -0
  36. package/dist/shared/core.Bshk2o_x.d.ts +1721 -0
  37. package/dist/shared/core.BwoNUcJQ.d.cts +53 -0
  38. package/dist/shared/core.BwoNUcJQ.d.mts +53 -0
  39. package/dist/shared/core.BwoNUcJQ.d.ts +53 -0
  40. package/dist/shared/core.C6_2xGyf.d.mts +1721 -0
  41. package/dist/shared/{core.CnvFgghY.d.cts → core.CajxAutx.d.cts} +27 -1
  42. package/dist/shared/{core.CnvFgghY.d.mts → core.CajxAutx.d.mts} +27 -1
  43. package/dist/shared/{core.CnvFgghY.d.ts → core.CajxAutx.d.ts} +27 -1
  44. package/dist/shared/core.CfqdiZTu.d.cts +1721 -0
  45. package/dist/shared/core.DkdZ1o38.d.ts +181 -0
  46. package/dist/shared/core.Dl-70uns.d.cts +84 -0
  47. package/dist/shared/core.Dl-70uns.d.mts +84 -0
  48. package/dist/shared/core.Dl-70uns.d.ts +84 -0
  49. package/dist/shared/core.DyEdx0m7.d.cts +181 -0
  50. package/dist/shared/core.E9DfzGLz.d.mts +13 -0
  51. package/dist/shared/core.HqYn20Fi.d.cts +13 -0
  52. package/dist/social-providers/index.cjs +2793 -0
  53. package/dist/social-providers/index.d.cts +3903 -0
  54. package/dist/social-providers/index.d.mts +3903 -0
  55. package/dist/social-providers/index.d.ts +3903 -0
  56. package/dist/social-providers/index.mjs +2743 -0
  57. package/dist/utils/index.cjs +7 -0
  58. package/dist/utils/index.d.cts +10 -0
  59. package/dist/utils/index.d.mts +10 -0
  60. package/dist/utils/index.d.ts +10 -0
  61. package/dist/utils/index.mjs +5 -0
  62. package/package.json +98 -2
  63. package/src/db/adapter/index.ts +424 -0
  64. package/src/db/index.ts +2 -0
  65. package/src/db/schema/rate-limit.ts +21 -0
  66. package/src/db/type.ts +28 -0
  67. package/src/env/color-depth.ts +172 -0
  68. package/src/env/env-impl.ts +124 -0
  69. package/src/env/index.ts +23 -0
  70. package/src/env/logger.test.ts +33 -0
  71. package/src/env/logger.ts +145 -0
  72. package/src/error/codes.ts +31 -0
  73. package/src/error/index.ts +11 -0
  74. package/src/index.ts +0 -2
  75. package/src/middleware/index.ts +33 -0
  76. package/src/oauth2/client-credentials-token.ts +102 -0
  77. package/src/oauth2/create-authorization-url.ts +85 -0
  78. package/src/oauth2/index.ts +22 -0
  79. package/src/oauth2/oauth-provider.ts +194 -0
  80. package/src/oauth2/refresh-access-token.ts +124 -0
  81. package/src/oauth2/utils.ts +36 -0
  82. package/src/oauth2/validate-authorization-code.ts +156 -0
  83. package/src/social-providers/apple.ts +213 -0
  84. package/src/social-providers/atlassian.ts +130 -0
  85. package/src/social-providers/cognito.ts +269 -0
  86. package/src/social-providers/discord.ts +172 -0
  87. package/src/social-providers/dropbox.ts +112 -0
  88. package/src/social-providers/facebook.ts +204 -0
  89. package/src/social-providers/figma.ts +115 -0
  90. package/src/social-providers/github.ts +154 -0
  91. package/src/social-providers/gitlab.ts +152 -0
  92. package/src/social-providers/google.ts +171 -0
  93. package/src/social-providers/huggingface.ts +116 -0
  94. package/src/social-providers/index.ts +118 -0
  95. package/src/social-providers/kakao.ts +178 -0
  96. package/src/social-providers/kick.ts +95 -0
  97. package/src/social-providers/line.ts +169 -0
  98. package/src/social-providers/linear.ts +120 -0
  99. package/src/social-providers/linkedin.ts +110 -0
  100. package/src/social-providers/microsoft-entra-id.ts +243 -0
  101. package/src/social-providers/naver.ts +112 -0
  102. package/src/social-providers/notion.ts +106 -0
  103. package/src/social-providers/paypal.ts +261 -0
  104. package/src/social-providers/reddit.ts +122 -0
  105. package/src/social-providers/roblox.ts +110 -0
  106. package/src/social-providers/salesforce.ts +157 -0
  107. package/src/social-providers/slack.ts +114 -0
  108. package/src/social-providers/spotify.ts +93 -0
  109. package/src/social-providers/tiktok.ts +211 -0
  110. package/src/social-providers/twitch.ts +111 -0
  111. package/src/social-providers/twitter.ts +194 -0
  112. package/src/social-providers/vk.ts +128 -0
  113. package/src/social-providers/zoom.ts +218 -0
  114. package/src/types/context.ts +334 -0
  115. package/src/types/cookie.ts +7 -0
  116. package/src/types/index.ts +19 -1
  117. package/src/types/init-options.ts +1048 -2
  118. package/src/types/plugin-client.ts +69 -0
  119. package/src/types/plugin.ts +134 -0
  120. package/src/utils/error-codes.ts +51 -0
  121. package/src/utils/index.ts +1 -0
@@ -0,0 +1,85 @@
1
+ import type { ProviderOptions } from "./index";
2
+ import { generateCodeChallenge } from "./utils";
3
+
4
+ export async function createAuthorizationURL({
5
+ id,
6
+ options,
7
+ authorizationEndpoint,
8
+ state,
9
+ codeVerifier,
10
+ scopes,
11
+ claims,
12
+ redirectURI,
13
+ duration,
14
+ prompt,
15
+ accessType,
16
+ responseType,
17
+ display,
18
+ loginHint,
19
+ hd,
20
+ responseMode,
21
+ additionalParams,
22
+ scopeJoiner,
23
+ }: {
24
+ id: string;
25
+ options: ProviderOptions;
26
+ redirectURI: string;
27
+ authorizationEndpoint: string;
28
+ state: string;
29
+ codeVerifier?: string;
30
+ scopes: string[];
31
+ claims?: string[];
32
+ duration?: string;
33
+ prompt?: string;
34
+ accessType?: string;
35
+ responseType?: string;
36
+ display?: string;
37
+ loginHint?: string;
38
+ hd?: string;
39
+ responseMode?: string;
40
+ additionalParams?: Record<string, string>;
41
+ scopeJoiner?: string;
42
+ }) {
43
+ const url = new URL(authorizationEndpoint);
44
+ url.searchParams.set("response_type", responseType || "code");
45
+ const primaryClientId = Array.isArray(options.clientId)
46
+ ? options.clientId[0]
47
+ : options.clientId;
48
+ url.searchParams.set("client_id", primaryClientId);
49
+ url.searchParams.set("state", state);
50
+ url.searchParams.set("scope", scopes.join(scopeJoiner || " "));
51
+ url.searchParams.set("redirect_uri", options.redirectURI || redirectURI);
52
+ duration && url.searchParams.set("duration", duration);
53
+ display && url.searchParams.set("display", display);
54
+ loginHint && url.searchParams.set("login_hint", loginHint);
55
+ prompt && url.searchParams.set("prompt", prompt);
56
+ hd && url.searchParams.set("hd", hd);
57
+ accessType && url.searchParams.set("access_type", accessType);
58
+ responseMode && url.searchParams.set("response_mode", responseMode);
59
+ if (codeVerifier) {
60
+ const codeChallenge = await generateCodeChallenge(codeVerifier);
61
+ url.searchParams.set("code_challenge_method", "S256");
62
+ url.searchParams.set("code_challenge", codeChallenge);
63
+ }
64
+ if (claims) {
65
+ const claimsObj = claims.reduce(
66
+ (acc, claim) => {
67
+ acc[claim] = null;
68
+ return acc;
69
+ },
70
+ {} as Record<string, null>,
71
+ );
72
+ url.searchParams.set(
73
+ "claims",
74
+ JSON.stringify({
75
+ id_token: { email: null, email_verified: null, ...claimsObj },
76
+ }),
77
+ );
78
+ }
79
+ if (additionalParams) {
80
+ Object.entries(additionalParams).forEach(([key, value]) => {
81
+ url.searchParams.set(key, value);
82
+ });
83
+ }
84
+ return url;
85
+ }
@@ -0,0 +1,22 @@
1
+ export type {
2
+ OAuth2Tokens,
3
+ OAuthProvider,
4
+ OAuth2UserInfo,
5
+ ProviderOptions,
6
+ } from "./oauth-provider";
7
+
8
+ export { generateCodeChallenge, getOAuth2Tokens } from "./utils";
9
+ export { createAuthorizationURL } from "./create-authorization-url";
10
+ export {
11
+ createAuthorizationCodeRequest,
12
+ validateAuthorizationCode,
13
+ validateToken,
14
+ } from "./validate-authorization-code";
15
+ export {
16
+ createRefreshAccessTokenRequest,
17
+ refreshAccessToken,
18
+ } from "./refresh-access-token";
19
+ export {
20
+ clientCredentialsToken,
21
+ createClientCredentialsTokenRequest,
22
+ } from "./client-credentials-token";
@@ -0,0 +1,194 @@
1
+ import type { LiteralString } from "../types";
2
+
3
+ export interface OAuth2Tokens {
4
+ tokenType?: string;
5
+ accessToken?: string;
6
+ refreshToken?: string;
7
+ accessTokenExpiresAt?: Date;
8
+ refreshTokenExpiresAt?: Date;
9
+ scopes?: string[];
10
+ idToken?: string;
11
+ }
12
+
13
+ export type OAuth2UserInfo = {
14
+ id: string | number;
15
+ name?: string;
16
+ email?: string | null;
17
+ image?: string;
18
+ emailVerified: boolean;
19
+ };
20
+
21
+ export interface OAuthProvider<
22
+ T extends Record<string, any> = Record<string, any>,
23
+ O extends Record<string, any> = Partial<ProviderOptions>,
24
+ > {
25
+ id: LiteralString;
26
+ createAuthorizationURL: (data: {
27
+ state: string;
28
+ codeVerifier: string;
29
+ scopes?: string[];
30
+ redirectURI: string;
31
+ display?: string;
32
+ loginHint?: string;
33
+ }) => Promise<URL> | URL;
34
+ name: string;
35
+ validateAuthorizationCode: (data: {
36
+ code: string;
37
+ redirectURI: string;
38
+ codeVerifier?: string;
39
+ deviceId?: string;
40
+ }) => Promise<OAuth2Tokens>;
41
+ getUserInfo: (
42
+ token: OAuth2Tokens & {
43
+ /**
44
+ * The user object from the provider
45
+ * This is only available for some providers like Apple
46
+ */
47
+ user?: {
48
+ name?: {
49
+ firstName?: string;
50
+ lastName?: string;
51
+ };
52
+ email?: string;
53
+ };
54
+ },
55
+ ) => Promise<{
56
+ user: OAuth2UserInfo;
57
+ data: T;
58
+ } | null>;
59
+ /**
60
+ * Custom function to refresh a token
61
+ */
62
+ refreshAccessToken?: (refreshToken: string) => Promise<OAuth2Tokens>;
63
+ revokeToken?: (token: string) => Promise<void>;
64
+ /**
65
+ * Verify the id token
66
+ * @param token - The id token
67
+ * @param nonce - The nonce
68
+ * @returns True if the id token is valid, false otherwise
69
+ */
70
+ verifyIdToken?: (token: string, nonce?: string) => Promise<boolean>;
71
+ /**
72
+ * Disable implicit sign up for new users. When set to true for the provider,
73
+ * sign-in need to be called with with requestSignUp as true to create new users.
74
+ */
75
+ disableImplicitSignUp?: boolean;
76
+ /**
77
+ * Disable sign up for new users.
78
+ */
79
+ disableSignUp?: boolean;
80
+ /**
81
+ * Options for the provider
82
+ */
83
+ options?: O;
84
+ }
85
+
86
+ export type ProviderOptions<Profile extends Record<string, any> = any> = {
87
+ /**
88
+ * The client ID of your application.
89
+ *
90
+ * This is usually a string but can be any type depending on the provider.
91
+ */
92
+ clientId?: unknown;
93
+ /**
94
+ * The client secret of your application
95
+ */
96
+ clientSecret?: string;
97
+ /**
98
+ * The scopes you want to request from the provider
99
+ */
100
+ scope?: string[];
101
+ /**
102
+ * Remove default scopes of the provider
103
+ */
104
+ disableDefaultScope?: boolean;
105
+ /**
106
+ * The redirect URL for your application. This is where the provider will
107
+ * redirect the user after the sign in process. Make sure this URL is
108
+ * whitelisted in the provider's dashboard.
109
+ */
110
+ redirectURI?: string;
111
+ /**
112
+ * The client key of your application
113
+ * Tiktok Social Provider uses this field instead of clientId
114
+ */
115
+ clientKey?: string;
116
+ /**
117
+ * Disable provider from allowing users to sign in
118
+ * with this provider with an id token sent from the
119
+ * client.
120
+ */
121
+ disableIdTokenSignIn?: boolean;
122
+ /**
123
+ * verifyIdToken function to verify the id token
124
+ */
125
+ verifyIdToken?: (token: string, nonce?: string) => Promise<boolean>;
126
+ /**
127
+ * Custom function to get user info from the provider
128
+ */
129
+ getUserInfo?: (token: OAuth2Tokens) => Promise<{
130
+ user: {
131
+ id: string;
132
+ name?: string;
133
+ email?: string | null;
134
+ image?: string;
135
+ emailVerified: boolean;
136
+ [key: string]: any;
137
+ };
138
+ data: any;
139
+ }>;
140
+ /**
141
+ * Custom function to refresh a token
142
+ */
143
+ refreshAccessToken?: (refreshToken: string) => Promise<OAuth2Tokens>;
144
+ /**
145
+ * Custom function to map the provider profile to a
146
+ * user.
147
+ */
148
+ mapProfileToUser?: (profile: Profile) =>
149
+ | {
150
+ id?: string;
151
+ name?: string;
152
+ email?: string | null;
153
+ image?: string;
154
+ emailVerified?: boolean;
155
+ [key: string]: any;
156
+ }
157
+ | Promise<{
158
+ id?: string;
159
+ name?: string;
160
+ email?: string | null;
161
+ image?: string;
162
+ emailVerified?: boolean;
163
+ [key: string]: any;
164
+ }>;
165
+ /**
166
+ * Disable implicit sign up for new users. When set to true for the provider,
167
+ * sign-in need to be called with with requestSignUp as true to create new users.
168
+ */
169
+ disableImplicitSignUp?: boolean;
170
+ /**
171
+ * Disable sign up for new users.
172
+ */
173
+ disableSignUp?: boolean;
174
+ /**
175
+ * The prompt to use for the authorization code request
176
+ */
177
+ prompt?:
178
+ | "select_account"
179
+ | "consent"
180
+ | "login"
181
+ | "none"
182
+ | "select_account consent";
183
+ /**
184
+ * The response mode to use for the authorization code request
185
+ */
186
+ responseMode?: "query" | "form_post";
187
+ /**
188
+ * If enabled, the user info will be overridden with the provider user info
189
+ * This is useful if you want to use the provider user info to update the user info
190
+ *
191
+ * @default false
192
+ */
193
+ overrideUserInfoOnSignIn?: boolean;
194
+ };
@@ -0,0 +1,124 @@
1
+ import { betterFetch } from "@better-fetch/fetch";
2
+ import type { OAuth2Tokens, ProviderOptions } from "./oauth-provider";
3
+ import { base64 } from "@better-auth/utils/base64";
4
+
5
+ export function createRefreshAccessTokenRequest({
6
+ refreshToken,
7
+ options,
8
+ authentication,
9
+ extraParams,
10
+ resource,
11
+ }: {
12
+ refreshToken: string;
13
+ options: Partial<ProviderOptions>;
14
+ authentication?: "basic" | "post";
15
+ extraParams?: Record<string, string>;
16
+ resource?: string | string[];
17
+ }) {
18
+ const body = new URLSearchParams();
19
+ const headers: Record<string, any> = {
20
+ "content-type": "application/x-www-form-urlencoded",
21
+ accept: "application/json",
22
+ };
23
+
24
+ body.set("grant_type", "refresh_token");
25
+ body.set("refresh_token", refreshToken);
26
+ // Use standard Base64 encoding for HTTP Basic Auth (OAuth2 spec, RFC 7617)
27
+ // Fixes compatibility with providers like Notion, Twitter, etc.
28
+ if (authentication === "basic") {
29
+ const primaryClientId = Array.isArray(options.clientId)
30
+ ? options.clientId[0]
31
+ : options.clientId;
32
+ if (primaryClientId) {
33
+ headers["authorization"] =
34
+ "Basic " +
35
+ base64.encode(`${primaryClientId}:${options.clientSecret ?? ""}`);
36
+ } else {
37
+ headers["authorization"] =
38
+ "Basic " + base64.encode(`:${options.clientSecret ?? ""}`);
39
+ }
40
+ } else {
41
+ const primaryClientId = Array.isArray(options.clientId)
42
+ ? options.clientId[0]
43
+ : options.clientId;
44
+ body.set("client_id", primaryClientId);
45
+ if (options.clientSecret) {
46
+ body.set("client_secret", options.clientSecret);
47
+ }
48
+ }
49
+
50
+ if (resource) {
51
+ if (typeof resource === "string") {
52
+ body.append("resource", resource);
53
+ } else {
54
+ for (const _resource of resource) {
55
+ body.append("resource", _resource);
56
+ }
57
+ }
58
+ }
59
+ if (extraParams) {
60
+ for (const [key, value] of Object.entries(extraParams)) {
61
+ body.set(key, value);
62
+ }
63
+ }
64
+
65
+ return {
66
+ body,
67
+ headers,
68
+ };
69
+ }
70
+
71
+ export async function refreshAccessToken({
72
+ refreshToken,
73
+ options,
74
+ tokenEndpoint,
75
+ authentication,
76
+ extraParams,
77
+ }: {
78
+ refreshToken: string;
79
+ options: Partial<ProviderOptions>;
80
+ tokenEndpoint: string;
81
+ authentication?: "basic" | "post";
82
+ extraParams?: Record<string, string>;
83
+ /** @deprecated always "refresh_token" */
84
+ grantType?: string;
85
+ }): Promise<OAuth2Tokens> {
86
+ const { body, headers } = createRefreshAccessTokenRequest({
87
+ refreshToken,
88
+ options,
89
+ authentication,
90
+ extraParams,
91
+ });
92
+
93
+ const { data, error } = await betterFetch<{
94
+ access_token: string;
95
+ refresh_token?: string;
96
+ expires_in?: number;
97
+ token_type?: string;
98
+ scope?: string;
99
+ id_token?: string;
100
+ }>(tokenEndpoint, {
101
+ method: "POST",
102
+ body,
103
+ headers,
104
+ });
105
+ if (error) {
106
+ throw error;
107
+ }
108
+ const tokens: OAuth2Tokens = {
109
+ accessToken: data.access_token,
110
+ refreshToken: data.refresh_token,
111
+ tokenType: data.token_type,
112
+ scopes: data.scope?.split(" "),
113
+ idToken: data.id_token,
114
+ };
115
+
116
+ if (data.expires_in) {
117
+ const now = new Date();
118
+ tokens.accessTokenExpiresAt = new Date(
119
+ now.getTime() + data.expires_in * 1000,
120
+ );
121
+ }
122
+
123
+ return tokens;
124
+ }
@@ -0,0 +1,36 @@
1
+ import { base64Url } from "@better-auth/utils/base64";
2
+ import type { OAuth2Tokens } from "./oauth-provider";
3
+
4
+ export function getOAuth2Tokens(data: Record<string, any>): OAuth2Tokens {
5
+ const getDate = (seconds: number) => {
6
+ const now = new Date();
7
+ return new Date(now.getTime() + seconds * 1000);
8
+ };
9
+
10
+ return {
11
+ tokenType: data.token_type,
12
+ accessToken: data.access_token,
13
+ refreshToken: data.refresh_token,
14
+ accessTokenExpiresAt: data.expires_in
15
+ ? getDate(data.expires_in)
16
+ : undefined,
17
+ refreshTokenExpiresAt: data.refresh_token_expires_in
18
+ ? getDate(data.refresh_token_expires_in)
19
+ : undefined,
20
+ scopes: data?.scope
21
+ ? typeof data.scope === "string"
22
+ ? data.scope.split(" ")
23
+ : data.scope
24
+ : [],
25
+ idToken: data.id_token,
26
+ };
27
+ }
28
+
29
+ export async function generateCodeChallenge(codeVerifier: string) {
30
+ const encoder = new TextEncoder();
31
+ const data = encoder.encode(codeVerifier);
32
+ const hash = await crypto.subtle.digest("SHA-256", data);
33
+ return base64Url.encode(new Uint8Array(hash), {
34
+ padding: false,
35
+ });
36
+ }
@@ -0,0 +1,156 @@
1
+ import { betterFetch } from "@better-fetch/fetch";
2
+ import { jwtVerify } from "jose";
3
+ import type { ProviderOptions } from "./index";
4
+ import { getOAuth2Tokens } from "./index";
5
+ import { base64 } from "@better-auth/utils/base64";
6
+
7
+ export function createAuthorizationCodeRequest({
8
+ code,
9
+ codeVerifier,
10
+ redirectURI,
11
+ options,
12
+ authentication,
13
+ deviceId,
14
+ headers,
15
+ additionalParams = {},
16
+ resource,
17
+ }: {
18
+ code: string;
19
+ redirectURI: string;
20
+ options: Partial<ProviderOptions>;
21
+ codeVerifier?: string;
22
+ deviceId?: string;
23
+ authentication?: "basic" | "post";
24
+ headers?: Record<string, string>;
25
+ additionalParams?: Record<string, string>;
26
+ resource?: string | string[];
27
+ }) {
28
+ const body = new URLSearchParams();
29
+ const requestHeaders: Record<string, any> = {
30
+ "content-type": "application/x-www-form-urlencoded",
31
+ accept: "application/json",
32
+ "user-agent": "better-auth",
33
+ ...headers,
34
+ };
35
+ body.set("grant_type", "authorization_code");
36
+ body.set("code", code);
37
+ codeVerifier && body.set("code_verifier", codeVerifier);
38
+ options.clientKey && body.set("client_key", options.clientKey);
39
+ deviceId && body.set("device_id", deviceId);
40
+ body.set("redirect_uri", options.redirectURI || redirectURI);
41
+ if (resource) {
42
+ if (typeof resource === "string") {
43
+ body.append("resource", resource);
44
+ } else {
45
+ for (const _resource of resource) {
46
+ body.append("resource", _resource);
47
+ }
48
+ }
49
+ }
50
+ // Use standard Base64 encoding for HTTP Basic Auth (OAuth2 spec, RFC 7617)
51
+ // Fixes compatibility with providers like Notion, Twitter, etc.
52
+ if (authentication === "basic") {
53
+ const primaryClientId = Array.isArray(options.clientId)
54
+ ? options.clientId[0]
55
+ : options.clientId;
56
+ const encodedCredentials = base64.encode(
57
+ `${primaryClientId}:${options.clientSecret ?? ""}`,
58
+ );
59
+ requestHeaders["authorization"] = `Basic ${encodedCredentials}`;
60
+ } else {
61
+ const primaryClientId = Array.isArray(options.clientId)
62
+ ? options.clientId[0]
63
+ : options.clientId;
64
+ body.set("client_id", primaryClientId);
65
+ if (options.clientSecret) {
66
+ body.set("client_secret", options.clientSecret);
67
+ }
68
+ }
69
+
70
+ for (const [key, value] of Object.entries(additionalParams)) {
71
+ if (!body.has(key)) body.append(key, value);
72
+ }
73
+
74
+ return {
75
+ body,
76
+ headers: requestHeaders,
77
+ };
78
+ }
79
+
80
+ export async function validateAuthorizationCode({
81
+ code,
82
+ codeVerifier,
83
+ redirectURI,
84
+ options,
85
+ tokenEndpoint,
86
+ authentication,
87
+ deviceId,
88
+ headers,
89
+ additionalParams = {},
90
+ resource,
91
+ }: {
92
+ code: string;
93
+ redirectURI: string;
94
+ options: Partial<ProviderOptions>;
95
+ codeVerifier?: string;
96
+ deviceId?: string;
97
+ tokenEndpoint: string;
98
+ authentication?: "basic" | "post";
99
+ headers?: Record<string, string>;
100
+ additionalParams?: Record<string, string>;
101
+ resource?: string | string[];
102
+ }) {
103
+ const { body, headers: requestHeaders } = createAuthorizationCodeRequest({
104
+ code,
105
+ codeVerifier,
106
+ redirectURI,
107
+ options,
108
+ authentication,
109
+ deviceId,
110
+ headers,
111
+ additionalParams,
112
+ resource,
113
+ });
114
+
115
+ const { data, error } = await betterFetch<object>(tokenEndpoint, {
116
+ method: "POST",
117
+ body: body,
118
+ headers: requestHeaders,
119
+ });
120
+
121
+ if (error) {
122
+ throw error;
123
+ }
124
+ const tokens = getOAuth2Tokens(data);
125
+ return tokens;
126
+ }
127
+
128
+ export async function validateToken(token: string, jwksEndpoint: string) {
129
+ const { data, error } = await betterFetch<{
130
+ keys: {
131
+ kid: string;
132
+ kty: string;
133
+ use: string;
134
+ n: string;
135
+ e: string;
136
+ x5c: string[];
137
+ }[];
138
+ }>(jwksEndpoint, {
139
+ method: "GET",
140
+ headers: {
141
+ accept: "application/json",
142
+ "user-agent": "better-auth",
143
+ },
144
+ });
145
+ if (error) {
146
+ throw error;
147
+ }
148
+ const keys = data["keys"];
149
+ const header = JSON.parse(atob(token.split(".")[0]!));
150
+ const key = keys.find((key) => key.kid === header.kid);
151
+ if (!key) {
152
+ throw new Error("Key not found");
153
+ }
154
+ const verified = await jwtVerify(token, key);
155
+ return verified;
156
+ }