@better-auth/core 1.4.0-beta.9 → 1.4.0

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 (151) hide show
  1. package/.turbo/turbo-build.log +41 -76
  2. package/dist/api/index.d.mts +3 -0
  3. package/dist/api/index.mjs +26 -0
  4. package/dist/async_hooks/index.d.mts +2 -10
  5. package/dist/async_hooks/index.mjs +2 -24
  6. package/dist/async_hooks-BfRfbd1J.mjs +18 -0
  7. package/dist/context/index.d.mts +54 -0
  8. package/dist/context/index.mjs +4 -0
  9. package/dist/context-DgQ9XGBl.mjs +114 -0
  10. package/dist/db/adapter/index.d.mts +3 -14
  11. package/dist/db/adapter/index.mjs +1 -1
  12. package/dist/db/index.d.mts +3 -39
  13. package/dist/db/index.mjs +46 -55
  14. package/dist/env/index.d.mts +2 -36
  15. package/dist/env/index.mjs +2 -299
  16. package/dist/env-DwlNAN_D.mjs +245 -0
  17. package/dist/error/index.d.mts +31 -29
  18. package/dist/error/index.mjs +3 -40
  19. package/dist/error-BhAKg8LX.mjs +45 -0
  20. package/dist/index-CdubV7uy.d.mts +82 -0
  21. package/dist/index-CkAWdKH8.d.mts +7352 -0
  22. package/dist/index-DgwIISs7.d.mts +7 -0
  23. package/dist/index.d.mts +3 -180
  24. package/dist/index.mjs +1 -1
  25. package/dist/oauth2/index.d.mts +3 -99
  26. package/dist/oauth2/index.mjs +2 -356
  27. package/dist/oauth2-DmgZmPEg.mjs +236 -0
  28. package/dist/social-providers/index.d.mts +3 -3903
  29. package/dist/social-providers/index.mjs +2434 -2654
  30. package/dist/utils/index.d.mts +5 -6
  31. package/dist/utils/index.mjs +2 -4
  32. package/dist/utils-C5EN75oV.mjs +7 -0
  33. package/package.json +70 -111
  34. package/src/api/index.ts +53 -0
  35. package/src/async_hooks/index.ts +1 -9
  36. package/src/context/endpoint-context.ts +49 -0
  37. package/src/context/index.ts +21 -0
  38. package/src/context/request-state.test.ts +94 -0
  39. package/src/context/request-state.ts +90 -0
  40. package/src/context/transaction.ts +73 -0
  41. package/src/db/adapter/index.ts +215 -129
  42. package/src/db/index.ts +12 -13
  43. package/src/db/plugin.ts +3 -3
  44. package/src/db/type.ts +54 -42
  45. package/src/env/color-depth.ts +5 -4
  46. package/src/env/env-impl.ts +2 -1
  47. package/src/env/index.ts +9 -9
  48. package/src/env/logger.test.ts +3 -2
  49. package/src/env/logger.ts +11 -9
  50. package/src/error/codes.ts +1 -1
  51. package/src/error/index.ts +1 -1
  52. package/src/oauth2/client-credentials-token.ts +9 -9
  53. package/src/oauth2/create-authorization-url.ts +12 -12
  54. package/src/oauth2/index.ts +10 -11
  55. package/src/oauth2/oauth-provider.ts +96 -74
  56. package/src/oauth2/refresh-access-token.ts +12 -12
  57. package/src/oauth2/utils.ts +2 -0
  58. package/src/oauth2/validate-authorization-code.ts +13 -15
  59. package/src/social-providers/apple.ts +8 -8
  60. package/src/social-providers/atlassian.ts +21 -19
  61. package/src/social-providers/cognito.ts +15 -15
  62. package/src/social-providers/discord.ts +8 -11
  63. package/src/social-providers/dropbox.ts +5 -5
  64. package/src/social-providers/facebook.ts +12 -10
  65. package/src/social-providers/figma.ts +6 -6
  66. package/src/social-providers/github.ts +4 -4
  67. package/src/social-providers/gitlab.ts +13 -10
  68. package/src/social-providers/google.ts +13 -13
  69. package/src/social-providers/huggingface.ts +27 -25
  70. package/src/social-providers/index.ts +30 -24
  71. package/src/social-providers/kakao.ts +41 -41
  72. package/src/social-providers/kick.ts +7 -9
  73. package/src/social-providers/line.ts +12 -12
  74. package/src/social-providers/linear.ts +9 -8
  75. package/src/social-providers/linkedin.ts +5 -5
  76. package/src/social-providers/microsoft-entra-id.ts +31 -15
  77. package/src/social-providers/naver.ts +5 -5
  78. package/src/social-providers/notion.ts +11 -9
  79. package/src/social-providers/paybin.ts +122 -0
  80. package/src/social-providers/paypal.ts +31 -29
  81. package/src/social-providers/polar.ts +110 -0
  82. package/src/social-providers/reddit.ts +6 -6
  83. package/src/social-providers/roblox.ts +15 -14
  84. package/src/social-providers/salesforce.ts +20 -18
  85. package/src/social-providers/slack.ts +4 -7
  86. package/src/social-providers/spotify.ts +5 -5
  87. package/src/social-providers/tiktok.ts +32 -33
  88. package/src/social-providers/twitch.ts +8 -8
  89. package/src/social-providers/twitter.ts +49 -45
  90. package/src/social-providers/vk.ts +14 -17
  91. package/src/social-providers/zoom.ts +29 -14
  92. package/src/types/context.ts +67 -67
  93. package/src/types/cookie.ts +1 -0
  94. package/src/types/index.ts +13 -11
  95. package/src/types/init-options.ts +1134 -911
  96. package/src/types/plugin-client.ts +61 -13
  97. package/src/types/plugin.ts +81 -57
  98. package/tsconfig.json +2 -5
  99. package/{build.config.ts → tsdown.config.ts} +8 -11
  100. package/vitest.config.ts +3 -0
  101. package/dist/async_hooks/index.cjs +0 -27
  102. package/dist/async_hooks/index.d.cts +0 -10
  103. package/dist/async_hooks/index.d.ts +0 -10
  104. package/dist/db/adapter/index.cjs +0 -2
  105. package/dist/db/adapter/index.d.cts +0 -14
  106. package/dist/db/adapter/index.d.ts +0 -14
  107. package/dist/db/index.cjs +0 -91
  108. package/dist/db/index.d.cts +0 -39
  109. package/dist/db/index.d.ts +0 -39
  110. package/dist/env/index.cjs +0 -315
  111. package/dist/env/index.d.cts +0 -36
  112. package/dist/env/index.d.ts +0 -36
  113. package/dist/error/index.cjs +0 -44
  114. package/dist/error/index.d.cts +0 -33
  115. package/dist/error/index.d.ts +0 -33
  116. package/dist/index.cjs +0 -2
  117. package/dist/index.d.cts +0 -180
  118. package/dist/index.d.ts +0 -180
  119. package/dist/middleware/index.cjs +0 -25
  120. package/dist/middleware/index.d.cts +0 -14
  121. package/dist/middleware/index.d.mts +0 -14
  122. package/dist/middleware/index.d.ts +0 -14
  123. package/dist/middleware/index.mjs +0 -21
  124. package/dist/oauth2/index.cjs +0 -368
  125. package/dist/oauth2/index.d.cts +0 -99
  126. package/dist/oauth2/index.d.ts +0 -99
  127. package/dist/shared/core.2rWMW9q9.d.ts +0 -13
  128. package/dist/shared/core.40VTWh-p.d.cts +0 -217
  129. package/dist/shared/core.BfcVdsSf.d.cts +0 -181
  130. package/dist/shared/core.Bisb2Bdk.d.mts +0 -181
  131. package/dist/shared/core.BwoNUcJQ.d.cts +0 -53
  132. package/dist/shared/core.BwoNUcJQ.d.mts +0 -53
  133. package/dist/shared/core.BwoNUcJQ.d.ts +0 -53
  134. package/dist/shared/core.CErFRCOZ.d.mts +0 -1684
  135. package/dist/shared/core.CGN6D-Mh.d.ts +0 -181
  136. package/dist/shared/core.CPuIItYE.d.ts +0 -217
  137. package/dist/shared/core.CftpHMDz.d.cts +0 -13
  138. package/dist/shared/core.Db7zJyxf.d.ts +0 -1684
  139. package/dist/shared/core.DqaxObkf.d.cts +0 -1684
  140. package/dist/shared/core.MjcDoj7R.d.cts +0 -5
  141. package/dist/shared/core.MjcDoj7R.d.mts +0 -5
  142. package/dist/shared/core.MjcDoj7R.d.ts +0 -5
  143. package/dist/shared/core.g2ZbxAEV.d.mts +0 -217
  144. package/dist/shared/core.g9ACQ8v2.d.mts +0 -13
  145. package/dist/social-providers/index.cjs +0 -2793
  146. package/dist/social-providers/index.d.cts +0 -3903
  147. package/dist/social-providers/index.d.ts +0 -3903
  148. package/dist/utils/index.cjs +0 -7
  149. package/dist/utils/index.d.cts +0 -10
  150. package/dist/utils/index.d.ts +0 -10
  151. package/src/middleware/index.ts +0 -33
@@ -0,0 +1,7 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+
3
+ //#region src/async_hooks/index.d.ts
4
+
5
+ declare function getAsyncLocalStorage(): Promise<typeof AsyncLocalStorage>;
6
+ //#endregion
7
+ export { getAsyncLocalStorage as n, AsyncLocalStorage as t };
package/dist/index.d.mts CHANGED
@@ -1,180 +1,3 @@
1
- import { L as LiteralString } from './shared/core.MjcDoj7R.mjs';
2
- export { a as LiteralUnion } from './shared/core.MjcDoj7R.mjs';
3
- import { A as AuthContext, B as BetterAuthOptions, a as AuthMiddleware } from './shared/core.CErFRCOZ.mjs';
4
- export { b as BetterAuthAdvancedOptions, d as BetterAuthCookies, c as BetterAuthRateLimitOptions, G as GenerateIdFn, e as GenericEndpointContext, I as InternalAdapter } from './shared/core.CErFRCOZ.mjs';
5
- import { Migration } from 'kysely';
6
- import { Endpoint, Middleware, EndpointContext, InputContext } from 'better-call';
7
- import { B as BetterAuthPluginDBSchema } from './shared/core.g9ACQ8v2.mjs';
8
- import { BetterFetch, BetterFetchOption, BetterFetchPlugin } from '@better-fetch/fetch';
9
- import { WritableAtom, Atom } from 'nanostores';
10
- import 'better-sqlite3';
11
- import './shared/core.g2ZbxAEV.mjs';
12
- import 'zod';
13
- import 'bun:sqlite';
14
- import 'node:sqlite';
15
- import './social-providers/index.mjs';
16
- import '@better-auth/core/oauth2';
17
- import './shared/core.Bisb2Bdk.mjs';
18
- import './shared/core.BwoNUcJQ.mjs';
19
- import '@better-auth/core';
20
-
21
- type Awaitable<T> = T | Promise<T>;
22
- type DeepPartial<T> = T extends Function ? T : T extends object ? {
23
- [K in keyof T]?: DeepPartial<T[K]>;
24
- } : T;
25
- type HookEndpointContext = EndpointContext<string, any> & Omit<InputContext<string, any>, "method"> & {
26
- context: AuthContext & {
27
- returned?: unknown;
28
- responseHeaders?: Headers;
29
- };
30
- headers?: Headers;
31
- };
32
- type BetterAuthPlugin = {
33
- id: LiteralString;
34
- /**
35
- * The init function is called when the plugin is initialized.
36
- * You can return a new context or modify the existing context.
37
- */
38
- init?: (ctx: AuthContext) => Awaitable<{
39
- context?: DeepPartial<Omit<AuthContext, "options">>;
40
- options?: Partial<BetterAuthOptions>;
41
- }> | void | Promise<void>;
42
- endpoints?: {
43
- [key: string]: Endpoint;
44
- };
45
- middlewares?: {
46
- path: string;
47
- middleware: Middleware;
48
- }[];
49
- onRequest?: (request: Request, ctx: AuthContext) => Promise<{
50
- response: Response;
51
- } | {
52
- request: Request;
53
- } | void>;
54
- onResponse?: (response: Response, ctx: AuthContext) => Promise<{
55
- response: Response;
56
- } | void>;
57
- hooks?: {
58
- before?: {
59
- matcher: (context: HookEndpointContext) => boolean;
60
- handler: AuthMiddleware;
61
- }[];
62
- after?: {
63
- matcher: (context: HookEndpointContext) => boolean;
64
- handler: AuthMiddleware;
65
- }[];
66
- };
67
- /**
68
- * Schema the plugin needs
69
- *
70
- * This will also be used to migrate the database. If the fields are dynamic from the plugins
71
- * configuration each time the configuration is changed a new migration will be created.
72
- *
73
- * NOTE: If you want to create migrations manually using
74
- * migrations option or any other way you
75
- * can disable migration per table basis.
76
- *
77
- * @example
78
- * ```ts
79
- * schema: {
80
- * user: {
81
- * fields: {
82
- * email: {
83
- * type: "string",
84
- * },
85
- * emailVerified: {
86
- * type: "boolean",
87
- * defaultValue: false,
88
- * },
89
- * },
90
- * }
91
- * } as AuthPluginSchema
92
- * ```
93
- */
94
- schema?: BetterAuthPluginDBSchema;
95
- /**
96
- * The migrations of the plugin. If you define schema that will automatically create
97
- * migrations for you.
98
- *
99
- * ⚠️ Only uses this if you dont't want to use the schema option and you disabled migrations for
100
- * the tables.
101
- */
102
- migrations?: Record<string, Migration>;
103
- /**
104
- * The options of the plugin
105
- */
106
- options?: Record<string, any> | undefined;
107
- /**
108
- * types to be inferred
109
- */
110
- $Infer?: Record<string, any>;
111
- /**
112
- * The rate limit rules to apply to specific paths.
113
- */
114
- rateLimit?: {
115
- window: number;
116
- max: number;
117
- pathMatcher: (path: string) => boolean;
118
- }[];
119
- /**
120
- * The error codes returned by the plugin
121
- */
122
- $ERROR_CODES?: Record<string, string>;
123
- };
124
-
125
- interface ClientStore {
126
- notify: (signal: string) => void;
127
- listen: (signal: string, listener: () => void) => void;
128
- atoms: Record<string, WritableAtom<any>>;
129
- }
130
- type ClientAtomListener = {
131
- matcher: (path: string) => boolean;
132
- signal: "$sessionSignal" | Omit<string, "$sessionSignal">;
133
- };
134
- interface BetterAuthClientOptions {
135
- fetchOptions?: BetterFetchOption;
136
- plugins?: BetterAuthClientPlugin[];
137
- baseURL?: string;
138
- basePath?: string;
139
- disableDefaultFetchPlugins?: boolean;
140
- $InferAuth?: BetterAuthOptions;
141
- }
142
- interface BetterAuthClientPlugin {
143
- id: LiteralString;
144
- /**
145
- * only used for type inference. don't pass the
146
- * actual plugin
147
- */
148
- $InferServerPlugin?: BetterAuthPlugin;
149
- /**
150
- * Custom actions
151
- */
152
- getActions?: ($fetch: BetterFetch, $store: ClientStore,
153
- /**
154
- * better-auth client options
155
- */
156
- options: BetterAuthClientOptions | undefined) => Record<string, any>;
157
- /**
158
- * State atoms that'll be resolved by each framework
159
- * auth store.
160
- */
161
- getAtoms?: ($fetch: BetterFetch) => Record<string, Atom<any>>;
162
- /**
163
- * specify path methods for server plugin inferred
164
- * endpoints to force a specific method.
165
- */
166
- pathMethods?: Record<string, "POST" | "GET">;
167
- /**
168
- * Better fetch plugins
169
- */
170
- fetchPlugins?: BetterFetchPlugin[];
171
- /**
172
- * a list of recaller based on a matcher function.
173
- * The signal name needs to match a signal in this
174
- * plugin or any plugin the user might have added.
175
- */
176
- atomListeners?: ClientAtomListener[];
177
- }
178
-
179
- export { AuthContext, BetterAuthOptions, LiteralString };
180
- export type { BetterAuthClientOptions, BetterAuthClientPlugin, BetterAuthPlugin, ClientAtomListener, ClientStore };
1
+ import { Dn as BetterAuthCookies, En as LiteralUnion, Tn as LiteralString, _ as BetterAuthRateLimitOptions, b as HookEndpointContext, c as BetterAuthClientPlugin, d as ClientStore, f as AuthContext, g as BetterAuthOptions, h as BetterAuthAdvancedOptions, l as ClientAtomListener, m as InternalAdapter, o as StandardSchemaV1, p as GenericEndpointContext, s as BetterAuthClientOptions, u as ClientFetchOption, v as GenerateIdFn, y as BetterAuthPlugin } from "./index-CkAWdKH8.mjs";
2
+ import "./index-CdubV7uy.mjs";
3
+ export { AuthContext, BetterAuthAdvancedOptions, BetterAuthClientOptions, BetterAuthClientPlugin, BetterAuthCookies, BetterAuthOptions, BetterAuthPlugin, BetterAuthRateLimitOptions, ClientAtomListener, ClientFetchOption, ClientStore, GenerateIdFn, GenericEndpointContext, HookEndpointContext, InternalAdapter, LiteralString, LiteralUnion, StandardSchemaV1 };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
-
1
+ export { };
@@ -1,99 +1,3 @@
1
- import { O as OAuth2Tokens, P as ProviderOptions } from '../shared/core.Bisb2Bdk.mjs';
2
- export { b as OAuth2UserInfo, a as OAuthProvider } from '../shared/core.Bisb2Bdk.mjs';
3
- import * as jose from 'jose';
4
- import '../shared/core.MjcDoj7R.mjs';
5
-
6
- declare function getOAuth2Tokens(data: Record<string, any>): OAuth2Tokens;
7
- declare function generateCodeChallenge(codeVerifier: string): Promise<string>;
8
-
9
- declare function createAuthorizationURL({ id, options, authorizationEndpoint, state, codeVerifier, scopes, claims, redirectURI, duration, prompt, accessType, responseType, display, loginHint, hd, responseMode, additionalParams, scopeJoiner, }: {
10
- id: string;
11
- options: ProviderOptions;
12
- redirectURI: string;
13
- authorizationEndpoint: string;
14
- state: string;
15
- codeVerifier?: string;
16
- scopes: string[];
17
- claims?: string[];
18
- duration?: string;
19
- prompt?: string;
20
- accessType?: string;
21
- responseType?: string;
22
- display?: string;
23
- loginHint?: string;
24
- hd?: string;
25
- responseMode?: string;
26
- additionalParams?: Record<string, string>;
27
- scopeJoiner?: string;
28
- }): Promise<URL>;
29
-
30
- declare function createAuthorizationCodeRequest({ code, codeVerifier, redirectURI, options, authentication, deviceId, headers, additionalParams, resource, }: {
31
- code: string;
32
- redirectURI: string;
33
- options: Partial<ProviderOptions>;
34
- codeVerifier?: string;
35
- deviceId?: string;
36
- authentication?: "basic" | "post";
37
- headers?: Record<string, string>;
38
- additionalParams?: Record<string, string>;
39
- resource?: string | string[];
40
- }): {
41
- body: URLSearchParams;
42
- headers: Record<string, any>;
43
- };
44
- declare function validateAuthorizationCode({ code, codeVerifier, redirectURI, options, tokenEndpoint, authentication, deviceId, headers, additionalParams, resource, }: {
45
- code: string;
46
- redirectURI: string;
47
- options: Partial<ProviderOptions>;
48
- codeVerifier?: string;
49
- deviceId?: string;
50
- tokenEndpoint: string;
51
- authentication?: "basic" | "post";
52
- headers?: Record<string, string>;
53
- additionalParams?: Record<string, string>;
54
- resource?: string | string[];
55
- }): Promise<OAuth2Tokens>;
56
- declare function validateToken(token: string, jwksEndpoint: string): Promise<jose.JWTVerifyResult<jose.JWTPayload>>;
57
-
58
- declare function createRefreshAccessTokenRequest({ refreshToken, options, authentication, extraParams, resource, }: {
59
- refreshToken: string;
60
- options: Partial<ProviderOptions>;
61
- authentication?: "basic" | "post";
62
- extraParams?: Record<string, string>;
63
- resource?: string | string[];
64
- }): {
65
- body: URLSearchParams;
66
- headers: Record<string, any>;
67
- };
68
- declare function refreshAccessToken({ refreshToken, options, tokenEndpoint, authentication, extraParams, }: {
69
- refreshToken: string;
70
- options: Partial<ProviderOptions>;
71
- tokenEndpoint: string;
72
- authentication?: "basic" | "post";
73
- extraParams?: Record<string, string>;
74
- /** @deprecated always "refresh_token" */
75
- grantType?: string;
76
- }): Promise<OAuth2Tokens>;
77
-
78
- declare function createClientCredentialsTokenRequest({ options, scope, authentication, resource, }: {
79
- options: ProviderOptions & {
80
- clientSecret: string;
81
- };
82
- scope?: string;
83
- authentication?: "basic" | "post";
84
- resource?: string | string[];
85
- }): {
86
- body: URLSearchParams;
87
- headers: Record<string, any>;
88
- };
89
- declare function clientCredentialsToken({ options, tokenEndpoint, scope, authentication, resource, }: {
90
- options: ProviderOptions & {
91
- clientSecret: string;
92
- };
93
- tokenEndpoint: string;
94
- scope: string;
95
- authentication?: "basic" | "post";
96
- resource?: string | string[];
97
- }): Promise<OAuth2Tokens>;
98
-
99
- export { OAuth2Tokens, ProviderOptions, clientCredentialsToken, createAuthorizationCodeRequest, createAuthorizationURL, createClientCredentialsTokenRequest, createRefreshAccessTokenRequest, generateCodeChallenge, getOAuth2Tokens, refreshAccessToken, validateAuthorizationCode, validateToken };
1
+ import { An as validateToken, Bn as OAuthProvider, Fn as createAuthorizationURL, In as clientCredentialsToken, Ln as createClientCredentialsTokenRequest, Mn as getOAuth2Tokens, Nn as createRefreshAccessTokenRequest, On as createAuthorizationCodeRequest, Pn as refreshAccessToken, Rn as OAuth2Tokens, Vn as ProviderOptions, jn as generateCodeChallenge, kn as validateAuthorizationCode, zn as OAuth2UserInfo } from "../index-CkAWdKH8.mjs";
2
+ import "../index-CdubV7uy.mjs";
3
+ export { OAuth2Tokens, OAuth2UserInfo, OAuthProvider, ProviderOptions, clientCredentialsToken, createAuthorizationCodeRequest, createAuthorizationURL, createClientCredentialsTokenRequest, createRefreshAccessTokenRequest, generateCodeChallenge, getOAuth2Tokens, refreshAccessToken, validateAuthorizationCode, validateToken };
@@ -1,357 +1,3 @@
1
- import { base64Url, base64 } from '@better-auth/utils/base64';
2
- import { betterFetch } from '@better-fetch/fetch';
3
- import { jwtVerify } from 'jose';
1
+ import { a as refreshAccessToken, c as getOAuth2Tokens, i as createRefreshAccessTokenRequest, l as clientCredentialsToken, n as validateAuthorizationCode, o as createAuthorizationURL, r as validateToken, s as generateCodeChallenge, t as createAuthorizationCodeRequest, u as createClientCredentialsTokenRequest } from "../oauth2-DmgZmPEg.mjs";
4
2
 
5
- function getOAuth2Tokens(data) {
6
- const getDate = (seconds) => {
7
- const now = /* @__PURE__ */ new Date();
8
- return new Date(now.getTime() + seconds * 1e3);
9
- };
10
- return {
11
- tokenType: data.token_type,
12
- accessToken: data.access_token,
13
- refreshToken: data.refresh_token,
14
- accessTokenExpiresAt: data.expires_in ? getDate(data.expires_in) : void 0,
15
- refreshTokenExpiresAt: data.refresh_token_expires_in ? getDate(data.refresh_token_expires_in) : void 0,
16
- scopes: data?.scope ? typeof data.scope === "string" ? data.scope.split(" ") : data.scope : [],
17
- idToken: data.id_token
18
- };
19
- }
20
- async function generateCodeChallenge(codeVerifier) {
21
- const encoder = new TextEncoder();
22
- const data = encoder.encode(codeVerifier);
23
- const hash = await crypto.subtle.digest("SHA-256", data);
24
- return base64Url.encode(new Uint8Array(hash), {
25
- padding: false
26
- });
27
- }
28
-
29
- async function createAuthorizationURL({
30
- id,
31
- options,
32
- authorizationEndpoint,
33
- state,
34
- codeVerifier,
35
- scopes,
36
- claims,
37
- redirectURI,
38
- duration,
39
- prompt,
40
- accessType,
41
- responseType,
42
- display,
43
- loginHint,
44
- hd,
45
- responseMode,
46
- additionalParams,
47
- scopeJoiner
48
- }) {
49
- const url = new URL(authorizationEndpoint);
50
- url.searchParams.set("response_type", responseType || "code");
51
- const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId;
52
- url.searchParams.set("client_id", primaryClientId);
53
- url.searchParams.set("state", state);
54
- url.searchParams.set("scope", scopes.join(scopeJoiner || " "));
55
- url.searchParams.set("redirect_uri", options.redirectURI || redirectURI);
56
- duration && url.searchParams.set("duration", duration);
57
- display && url.searchParams.set("display", display);
58
- loginHint && url.searchParams.set("login_hint", loginHint);
59
- prompt && url.searchParams.set("prompt", prompt);
60
- hd && url.searchParams.set("hd", hd);
61
- accessType && url.searchParams.set("access_type", accessType);
62
- responseMode && url.searchParams.set("response_mode", responseMode);
63
- if (codeVerifier) {
64
- const codeChallenge = await generateCodeChallenge(codeVerifier);
65
- url.searchParams.set("code_challenge_method", "S256");
66
- url.searchParams.set("code_challenge", codeChallenge);
67
- }
68
- if (claims) {
69
- const claimsObj = claims.reduce(
70
- (acc, claim) => {
71
- acc[claim] = null;
72
- return acc;
73
- },
74
- {}
75
- );
76
- url.searchParams.set(
77
- "claims",
78
- JSON.stringify({
79
- id_token: { email: null, email_verified: null, ...claimsObj }
80
- })
81
- );
82
- }
83
- if (additionalParams) {
84
- Object.entries(additionalParams).forEach(([key, value]) => {
85
- url.searchParams.set(key, value);
86
- });
87
- }
88
- return url;
89
- }
90
-
91
- function createAuthorizationCodeRequest({
92
- code,
93
- codeVerifier,
94
- redirectURI,
95
- options,
96
- authentication,
97
- deviceId,
98
- headers,
99
- additionalParams = {},
100
- resource
101
- }) {
102
- const body = new URLSearchParams();
103
- const requestHeaders = {
104
- "content-type": "application/x-www-form-urlencoded",
105
- accept: "application/json",
106
- "user-agent": "better-auth",
107
- ...headers
108
- };
109
- body.set("grant_type", "authorization_code");
110
- body.set("code", code);
111
- codeVerifier && body.set("code_verifier", codeVerifier);
112
- options.clientKey && body.set("client_key", options.clientKey);
113
- deviceId && body.set("device_id", deviceId);
114
- body.set("redirect_uri", options.redirectURI || redirectURI);
115
- if (resource) {
116
- if (typeof resource === "string") {
117
- body.append("resource", resource);
118
- } else {
119
- for (const _resource of resource) {
120
- body.append("resource", _resource);
121
- }
122
- }
123
- }
124
- if (authentication === "basic") {
125
- const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId;
126
- const encodedCredentials = base64.encode(
127
- `${primaryClientId}:${options.clientSecret ?? ""}`
128
- );
129
- requestHeaders["authorization"] = `Basic ${encodedCredentials}`;
130
- } else {
131
- const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId;
132
- body.set("client_id", primaryClientId);
133
- if (options.clientSecret) {
134
- body.set("client_secret", options.clientSecret);
135
- }
136
- }
137
- for (const [key, value] of Object.entries(additionalParams)) {
138
- if (!body.has(key)) body.append(key, value);
139
- }
140
- return {
141
- body,
142
- headers: requestHeaders
143
- };
144
- }
145
- async function validateAuthorizationCode({
146
- code,
147
- codeVerifier,
148
- redirectURI,
149
- options,
150
- tokenEndpoint,
151
- authentication,
152
- deviceId,
153
- headers,
154
- additionalParams = {},
155
- resource
156
- }) {
157
- const { body, headers: requestHeaders } = createAuthorizationCodeRequest({
158
- code,
159
- codeVerifier,
160
- redirectURI,
161
- options,
162
- authentication,
163
- deviceId,
164
- headers,
165
- additionalParams,
166
- resource
167
- });
168
- const { data, error } = await betterFetch(tokenEndpoint, {
169
- method: "POST",
170
- body,
171
- headers: requestHeaders
172
- });
173
- if (error) {
174
- throw error;
175
- }
176
- const tokens = getOAuth2Tokens(data);
177
- return tokens;
178
- }
179
- async function validateToken(token, jwksEndpoint) {
180
- const { data, error } = await betterFetch(jwksEndpoint, {
181
- method: "GET",
182
- headers: {
183
- accept: "application/json",
184
- "user-agent": "better-auth"
185
- }
186
- });
187
- if (error) {
188
- throw error;
189
- }
190
- const keys = data["keys"];
191
- const header = JSON.parse(atob(token.split(".")[0]));
192
- const key = keys.find((key2) => key2.kid === header.kid);
193
- if (!key) {
194
- throw new Error("Key not found");
195
- }
196
- const verified = await jwtVerify(token, key);
197
- return verified;
198
- }
199
-
200
- function createRefreshAccessTokenRequest({
201
- refreshToken,
202
- options,
203
- authentication,
204
- extraParams,
205
- resource
206
- }) {
207
- const body = new URLSearchParams();
208
- const headers = {
209
- "content-type": "application/x-www-form-urlencoded",
210
- accept: "application/json"
211
- };
212
- body.set("grant_type", "refresh_token");
213
- body.set("refresh_token", refreshToken);
214
- if (authentication === "basic") {
215
- const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId;
216
- if (primaryClientId) {
217
- headers["authorization"] = "Basic " + base64.encode(`${primaryClientId}:${options.clientSecret ?? ""}`);
218
- } else {
219
- headers["authorization"] = "Basic " + base64.encode(`:${options.clientSecret ?? ""}`);
220
- }
221
- } else {
222
- const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId;
223
- body.set("client_id", primaryClientId);
224
- if (options.clientSecret) {
225
- body.set("client_secret", options.clientSecret);
226
- }
227
- }
228
- if (resource) {
229
- if (typeof resource === "string") {
230
- body.append("resource", resource);
231
- } else {
232
- for (const _resource of resource) {
233
- body.append("resource", _resource);
234
- }
235
- }
236
- }
237
- if (extraParams) {
238
- for (const [key, value] of Object.entries(extraParams)) {
239
- body.set(key, value);
240
- }
241
- }
242
- return {
243
- body,
244
- headers
245
- };
246
- }
247
- async function refreshAccessToken({
248
- refreshToken,
249
- options,
250
- tokenEndpoint,
251
- authentication,
252
- extraParams
253
- }) {
254
- const { body, headers } = createRefreshAccessTokenRequest({
255
- refreshToken,
256
- options,
257
- authentication,
258
- extraParams
259
- });
260
- const { data, error } = await betterFetch(tokenEndpoint, {
261
- method: "POST",
262
- body,
263
- headers
264
- });
265
- if (error) {
266
- throw error;
267
- }
268
- const tokens = {
269
- accessToken: data.access_token,
270
- refreshToken: data.refresh_token,
271
- tokenType: data.token_type,
272
- scopes: data.scope?.split(" "),
273
- idToken: data.id_token
274
- };
275
- if (data.expires_in) {
276
- const now = /* @__PURE__ */ new Date();
277
- tokens.accessTokenExpiresAt = new Date(
278
- now.getTime() + data.expires_in * 1e3
279
- );
280
- }
281
- return tokens;
282
- }
283
-
284
- function createClientCredentialsTokenRequest({
285
- options,
286
- scope,
287
- authentication,
288
- resource
289
- }) {
290
- const body = new URLSearchParams();
291
- const headers = {
292
- "content-type": "application/x-www-form-urlencoded",
293
- accept: "application/json"
294
- };
295
- body.set("grant_type", "client_credentials");
296
- scope && body.set("scope", scope);
297
- if (resource) {
298
- if (typeof resource === "string") {
299
- body.append("resource", resource);
300
- } else {
301
- for (const _resource of resource) {
302
- body.append("resource", _resource);
303
- }
304
- }
305
- }
306
- if (authentication === "basic") {
307
- const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId;
308
- const encodedCredentials = base64Url.encode(
309
- `${primaryClientId}:${options.clientSecret}`
310
- );
311
- headers["authorization"] = `Basic ${encodedCredentials}`;
312
- } else {
313
- const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId;
314
- body.set("client_id", primaryClientId);
315
- body.set("client_secret", options.clientSecret);
316
- }
317
- return {
318
- body,
319
- headers
320
- };
321
- }
322
- async function clientCredentialsToken({
323
- options,
324
- tokenEndpoint,
325
- scope,
326
- authentication,
327
- resource
328
- }) {
329
- const { body, headers } = createClientCredentialsTokenRequest({
330
- options,
331
- scope,
332
- authentication,
333
- resource
334
- });
335
- const { data, error } = await betterFetch(tokenEndpoint, {
336
- method: "POST",
337
- body,
338
- headers
339
- });
340
- if (error) {
341
- throw error;
342
- }
343
- const tokens = {
344
- accessToken: data.access_token,
345
- tokenType: data.token_type,
346
- scopes: data.scope?.split(" ")
347
- };
348
- if (data.expires_in) {
349
- const now = /* @__PURE__ */ new Date();
350
- tokens.accessTokenExpiresAt = new Date(
351
- now.getTime() + data.expires_in * 1e3
352
- );
353
- }
354
- return tokens;
355
- }
356
-
357
- export { clientCredentialsToken, createAuthorizationCodeRequest, createAuthorizationURL, createClientCredentialsTokenRequest, createRefreshAccessTokenRequest, generateCodeChallenge, getOAuth2Tokens, refreshAccessToken, validateAuthorizationCode, validateToken };
3
+ export { clientCredentialsToken, createAuthorizationCodeRequest, createAuthorizationURL, createClientCredentialsTokenRequest, createRefreshAccessTokenRequest, generateCodeChallenge, getOAuth2Tokens, refreshAccessToken, validateAuthorizationCode, validateToken };