@hammadj/better-auth-core 1.5.0-beta.9
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.
- package/.turbo/turbo-build.log +266 -0
- package/.turbo/turbo-test.log +2 -0
- package/LICENSE.md +20 -0
- package/dist/api/index.d.mts +181 -0
- package/dist/api/index.mjs +34 -0
- package/dist/api/index.mjs.map +1 -0
- package/dist/async_hooks/index.d.mts +7 -0
- package/dist/async_hooks/index.mjs +22 -0
- package/dist/async_hooks/index.mjs.map +1 -0
- package/dist/async_hooks/pure.index.d.mts +7 -0
- package/dist/async_hooks/pure.index.mjs +35 -0
- package/dist/async_hooks/pure.index.mjs.map +1 -0
- package/dist/context/endpoint-context.d.mts +19 -0
- package/dist/context/endpoint-context.mjs +32 -0
- package/dist/context/endpoint-context.mjs.map +1 -0
- package/dist/context/global.d.mts +7 -0
- package/dist/context/global.mjs +38 -0
- package/dist/context/global.mjs.map +1 -0
- package/dist/context/index.d.mts +5 -0
- package/dist/context/index.mjs +6 -0
- package/dist/context/request-state.d.mts +26 -0
- package/dist/context/request-state.mjs +50 -0
- package/dist/context/request-state.mjs.map +1 -0
- package/dist/context/transaction.d.mts +25 -0
- package/dist/context/transaction.mjs +96 -0
- package/dist/context/transaction.mjs.map +1 -0
- package/dist/db/adapter/factory.d.mts +28 -0
- package/dist/db/adapter/factory.mjs +716 -0
- package/dist/db/adapter/factory.mjs.map +1 -0
- package/dist/db/adapter/get-default-field-name.d.mts +19 -0
- package/dist/db/adapter/get-default-field-name.mjs +39 -0
- package/dist/db/adapter/get-default-field-name.mjs.map +1 -0
- package/dist/db/adapter/get-default-model-name.d.mts +13 -0
- package/dist/db/adapter/get-default-model-name.mjs +33 -0
- package/dist/db/adapter/get-default-model-name.mjs.map +1 -0
- package/dist/db/adapter/get-field-attributes.d.mts +30 -0
- package/dist/db/adapter/get-field-attributes.mjs +40 -0
- package/dist/db/adapter/get-field-attributes.mjs.map +1 -0
- package/dist/db/adapter/get-field-name.d.mts +19 -0
- package/dist/db/adapter/get-field-name.mjs +34 -0
- package/dist/db/adapter/get-field-name.mjs.map +1 -0
- package/dist/db/adapter/get-id-field.d.mts +40 -0
- package/dist/db/adapter/get-id-field.mjs +68 -0
- package/dist/db/adapter/get-id-field.mjs.map +1 -0
- package/dist/db/adapter/get-model-name.d.mts +13 -0
- package/dist/db/adapter/get-model-name.mjs +24 -0
- package/dist/db/adapter/get-model-name.mjs.map +1 -0
- package/dist/db/adapter/index.d.mts +515 -0
- package/dist/db/adapter/index.mjs +10 -0
- package/dist/db/adapter/types.d.mts +140 -0
- package/dist/db/adapter/utils.d.mts +8 -0
- package/dist/db/adapter/utils.mjs +39 -0
- package/dist/db/adapter/utils.mjs.map +1 -0
- package/dist/db/get-tables.d.mts +9 -0
- package/dist/db/get-tables.mjs +267 -0
- package/dist/db/get-tables.mjs.map +1 -0
- package/dist/db/index.d.mts +10 -0
- package/dist/db/index.mjs +9 -0
- package/dist/db/plugin.d.mts +13 -0
- package/dist/db/schema/account.d.mts +27 -0
- package/dist/db/schema/account.mjs +20 -0
- package/dist/db/schema/account.mjs.map +1 -0
- package/dist/db/schema/rate-limit.d.mts +15 -0
- package/dist/db/schema/rate-limit.mjs +12 -0
- package/dist/db/schema/rate-limit.mjs.map +1 -0
- package/dist/db/schema/session.d.mts +22 -0
- package/dist/db/schema/session.mjs +15 -0
- package/dist/db/schema/session.mjs.map +1 -0
- package/dist/db/schema/shared.d.mts +11 -0
- package/dist/db/schema/shared.mjs +12 -0
- package/dist/db/schema/shared.mjs.map +1 -0
- package/dist/db/schema/user.d.mts +21 -0
- package/dist/db/schema/user.mjs +14 -0
- package/dist/db/schema/user.mjs.map +1 -0
- package/dist/db/schema/verification.d.mts +20 -0
- package/dist/db/schema/verification.mjs +13 -0
- package/dist/db/schema/verification.mjs.map +1 -0
- package/dist/db/type.d.mts +147 -0
- package/dist/env/color-depth.d.mts +5 -0
- package/dist/env/color-depth.mjs +89 -0
- package/dist/env/color-depth.mjs.map +1 -0
- package/dist/env/env-impl.d.mts +33 -0
- package/dist/env/env-impl.mjs +83 -0
- package/dist/env/env-impl.mjs.map +1 -0
- package/dist/env/index.d.mts +4 -0
- package/dist/env/index.mjs +5 -0
- package/dist/env/logger.d.mts +49 -0
- package/dist/env/logger.mjs +82 -0
- package/dist/env/logger.mjs.map +1 -0
- package/dist/error/codes.d.mts +199 -0
- package/dist/error/codes.mjs +57 -0
- package/dist/error/codes.mjs.map +1 -0
- package/dist/error/index.d.mts +20 -0
- package/dist/error/index.mjs +30 -0
- package/dist/error/index.mjs.map +1 -0
- package/dist/index.d.mts +8 -0
- package/dist/index.mjs +1 -0
- package/dist/oauth2/client-credentials-token.d.mts +37 -0
- package/dist/oauth2/client-credentials-token.mjs +55 -0
- package/dist/oauth2/client-credentials-token.mjs.map +1 -0
- package/dist/oauth2/create-authorization-url.d.mts +46 -0
- package/dist/oauth2/create-authorization-url.mjs +43 -0
- package/dist/oauth2/create-authorization-url.mjs.map +1 -0
- package/dist/oauth2/index.d.mts +8 -0
- package/dist/oauth2/index.mjs +8 -0
- package/dist/oauth2/oauth-provider.d.mts +195 -0
- package/dist/oauth2/refresh-access-token.d.mts +36 -0
- package/dist/oauth2/refresh-access-token.mjs +59 -0
- package/dist/oauth2/refresh-access-token.mjs.map +1 -0
- package/dist/oauth2/utils.d.mts +8 -0
- package/dist/oauth2/utils.mjs +28 -0
- package/dist/oauth2/utils.mjs.map +1 -0
- package/dist/oauth2/validate-authorization-code.d.mts +56 -0
- package/dist/oauth2/validate-authorization-code.mjs +72 -0
- package/dist/oauth2/validate-authorization-code.mjs.map +1 -0
- package/dist/oauth2/verify.d.mts +43 -0
- package/dist/oauth2/verify.mjs +96 -0
- package/dist/oauth2/verify.mjs.map +1 -0
- package/dist/social-providers/apple.d.mts +120 -0
- package/dist/social-providers/apple.mjs +105 -0
- package/dist/social-providers/apple.mjs.map +1 -0
- package/dist/social-providers/atlassian.d.mts +73 -0
- package/dist/social-providers/atlassian.mjs +84 -0
- package/dist/social-providers/atlassian.mjs.map +1 -0
- package/dist/social-providers/cognito.d.mts +88 -0
- package/dist/social-providers/cognito.mjs +166 -0
- package/dist/social-providers/cognito.mjs.map +1 -0
- package/dist/social-providers/discord.d.mts +127 -0
- package/dist/social-providers/discord.mjs +65 -0
- package/dist/social-providers/discord.mjs.map +1 -0
- package/dist/social-providers/dropbox.d.mts +72 -0
- package/dist/social-providers/dropbox.mjs +76 -0
- package/dist/social-providers/dropbox.mjs.map +1 -0
- package/dist/social-providers/facebook.d.mts +82 -0
- package/dist/social-providers/facebook.mjs +121 -0
- package/dist/social-providers/facebook.mjs.map +1 -0
- package/dist/social-providers/figma.d.mts +64 -0
- package/dist/social-providers/figma.mjs +87 -0
- package/dist/social-providers/figma.mjs.map +1 -0
- package/dist/social-providers/github.d.mts +105 -0
- package/dist/social-providers/github.mjs +97 -0
- package/dist/social-providers/github.mjs.map +1 -0
- package/dist/social-providers/gitlab.d.mts +126 -0
- package/dist/social-providers/gitlab.mjs +83 -0
- package/dist/social-providers/gitlab.mjs.map +1 -0
- package/dist/social-providers/google.d.mts +100 -0
- package/dist/social-providers/google.mjs +109 -0
- package/dist/social-providers/google.mjs.map +1 -0
- package/dist/social-providers/huggingface.d.mts +86 -0
- package/dist/social-providers/huggingface.mjs +76 -0
- package/dist/social-providers/huggingface.mjs.map +1 -0
- package/dist/social-providers/index.d.mts +1725 -0
- package/dist/social-providers/index.mjs +77 -0
- package/dist/social-providers/index.mjs.map +1 -0
- package/dist/social-providers/kakao.d.mts +164 -0
- package/dist/social-providers/kakao.mjs +73 -0
- package/dist/social-providers/kakao.mjs.map +1 -0
- package/dist/social-providers/kick.d.mts +76 -0
- package/dist/social-providers/kick.mjs +72 -0
- package/dist/social-providers/kick.mjs.map +1 -0
- package/dist/social-providers/line.d.mts +108 -0
- package/dist/social-providers/line.mjs +114 -0
- package/dist/social-providers/line.mjs.map +1 -0
- package/dist/social-providers/linear.d.mts +71 -0
- package/dist/social-providers/linear.mjs +89 -0
- package/dist/social-providers/linear.mjs.map +1 -0
- package/dist/social-providers/linkedin.d.mts +70 -0
- package/dist/social-providers/linkedin.mjs +77 -0
- package/dist/social-providers/linkedin.mjs.map +1 -0
- package/dist/social-providers/microsoft-entra-id.d.mts +175 -0
- package/dist/social-providers/microsoft-entra-id.mjs +107 -0
- package/dist/social-providers/microsoft-entra-id.mjs.map +1 -0
- package/dist/social-providers/naver.d.mts +95 -0
- package/dist/social-providers/naver.mjs +68 -0
- package/dist/social-providers/naver.mjs.map +1 -0
- package/dist/social-providers/notion.d.mts +67 -0
- package/dist/social-providers/notion.mjs +76 -0
- package/dist/social-providers/notion.mjs.map +1 -0
- package/dist/social-providers/paybin.d.mts +74 -0
- package/dist/social-providers/paybin.mjs +86 -0
- package/dist/social-providers/paybin.mjs.map +1 -0
- package/dist/social-providers/paypal.d.mts +132 -0
- package/dist/social-providers/paypal.mjs +145 -0
- package/dist/social-providers/paypal.mjs.map +1 -0
- package/dist/social-providers/polar.d.mts +77 -0
- package/dist/social-providers/polar.mjs +74 -0
- package/dist/social-providers/polar.mjs.map +1 -0
- package/dist/social-providers/reddit.d.mts +65 -0
- package/dist/social-providers/reddit.mjs +84 -0
- package/dist/social-providers/reddit.mjs.map +1 -0
- package/dist/social-providers/roblox.d.mts +73 -0
- package/dist/social-providers/roblox.mjs +60 -0
- package/dist/social-providers/roblox.mjs.map +1 -0
- package/dist/social-providers/salesforce.d.mts +82 -0
- package/dist/social-providers/salesforce.mjs +92 -0
- package/dist/social-providers/salesforce.mjs.map +1 -0
- package/dist/social-providers/slack.d.mts +86 -0
- package/dist/social-providers/slack.mjs +69 -0
- package/dist/social-providers/slack.mjs.map +1 -0
- package/dist/social-providers/spotify.d.mts +66 -0
- package/dist/social-providers/spotify.mjs +72 -0
- package/dist/social-providers/spotify.mjs.map +1 -0
- package/dist/social-providers/tiktok.d.mts +171 -0
- package/dist/social-providers/tiktok.mjs +63 -0
- package/dist/social-providers/tiktok.mjs.map +1 -0
- package/dist/social-providers/twitch.d.mts +82 -0
- package/dist/social-providers/twitch.mjs +79 -0
- package/dist/social-providers/twitch.mjs.map +1 -0
- package/dist/social-providers/twitter.d.mts +129 -0
- package/dist/social-providers/twitter.mjs +88 -0
- package/dist/social-providers/twitter.mjs.map +1 -0
- package/dist/social-providers/vercel.d.mts +65 -0
- package/dist/social-providers/vercel.mjs +62 -0
- package/dist/social-providers/vercel.mjs.map +1 -0
- package/dist/social-providers/vk.d.mts +73 -0
- package/dist/social-providers/vk.mjs +84 -0
- package/dist/social-providers/vk.mjs.map +1 -0
- package/dist/social-providers/zoom.d.mts +173 -0
- package/dist/social-providers/zoom.mjs +73 -0
- package/dist/social-providers/zoom.mjs.map +1 -0
- package/dist/types/context.d.mts +267 -0
- package/dist/types/cookie.d.mts +16 -0
- package/dist/types/helper.d.mts +10 -0
- package/dist/types/index.d.mts +8 -0
- package/dist/types/init-options.d.mts +1314 -0
- package/dist/types/plugin-client.d.mts +112 -0
- package/dist/types/plugin.d.mts +125 -0
- package/dist/utils/db.d.mts +12 -0
- package/dist/utils/db.mjs +17 -0
- package/dist/utils/db.mjs.map +1 -0
- package/dist/utils/deprecate.d.mts +10 -0
- package/dist/utils/deprecate.mjs +18 -0
- package/dist/utils/deprecate.mjs.map +1 -0
- package/dist/utils/error-codes.d.mts +13 -0
- package/dist/utils/error-codes.mjs +12 -0
- package/dist/utils/error-codes.mjs.map +1 -0
- package/dist/utils/id.d.mts +5 -0
- package/dist/utils/id.mjs +10 -0
- package/dist/utils/id.mjs.map +1 -0
- package/dist/utils/ip.d.mts +55 -0
- package/dist/utils/ip.mjs +119 -0
- package/dist/utils/ip.mjs.map +1 -0
- package/dist/utils/json.d.mts +5 -0
- package/dist/utils/json.mjs +26 -0
- package/dist/utils/json.mjs.map +1 -0
- package/dist/utils/string.d.mts +5 -0
- package/dist/utils/string.mjs +8 -0
- package/dist/utils/string.mjs.map +1 -0
- package/dist/utils/url.d.mts +21 -0
- package/dist/utils/url.mjs +33 -0
- package/dist/utils/url.mjs.map +1 -0
- package/package.json +147 -0
- package/src/api/index.ts +106 -0
- package/src/async_hooks/index.ts +40 -0
- package/src/async_hooks/pure.index.ts +46 -0
- package/src/context/endpoint-context.ts +50 -0
- package/src/context/global.ts +57 -0
- package/src/context/index.ts +23 -0
- package/src/context/request-state.test.ts +94 -0
- package/src/context/request-state.ts +91 -0
- package/src/context/transaction.ts +136 -0
- package/src/db/adapter/factory.ts +1362 -0
- package/src/db/adapter/get-default-field-name.ts +59 -0
- package/src/db/adapter/get-default-model-name.ts +51 -0
- package/src/db/adapter/get-field-attributes.ts +62 -0
- package/src/db/adapter/get-field-name.ts +43 -0
- package/src/db/adapter/get-id-field.ts +141 -0
- package/src/db/adapter/get-model-name.ts +36 -0
- package/src/db/adapter/index.ts +554 -0
- package/src/db/adapter/types.ts +171 -0
- package/src/db/adapter/utils.ts +61 -0
- package/src/db/get-tables.ts +296 -0
- package/src/db/index.ts +18 -0
- package/src/db/plugin.ts +11 -0
- package/src/db/schema/account.ts +34 -0
- package/src/db/schema/rate-limit.ts +21 -0
- package/src/db/schema/session.ts +17 -0
- package/src/db/schema/shared.ts +7 -0
- package/src/db/schema/user.ts +16 -0
- package/src/db/schema/verification.ts +15 -0
- package/src/db/test/get-tables.test.ts +116 -0
- package/src/db/type.ts +180 -0
- package/src/env/color-depth.ts +172 -0
- package/src/env/env-impl.ts +124 -0
- package/src/env/index.ts +23 -0
- package/src/env/logger.test.ts +34 -0
- package/src/env/logger.ts +145 -0
- package/src/error/codes.ts +58 -0
- package/src/error/index.ts +35 -0
- package/src/index.ts +1 -0
- package/src/oauth2/client-credentials-token.ts +102 -0
- package/src/oauth2/create-authorization-url.ts +87 -0
- package/src/oauth2/index.ts +26 -0
- package/src/oauth2/oauth-provider.ts +222 -0
- package/src/oauth2/refresh-access-token.ts +124 -0
- package/src/oauth2/utils.ts +38 -0
- package/src/oauth2/validate-authorization-code.ts +149 -0
- package/src/oauth2/validate-token.test.ts +174 -0
- package/src/oauth2/verify.ts +221 -0
- package/src/social-providers/apple.ts +223 -0
- package/src/social-providers/atlassian.ts +132 -0
- package/src/social-providers/cognito.ts +279 -0
- package/src/social-providers/discord.ts +169 -0
- package/src/social-providers/dropbox.ts +112 -0
- package/src/social-providers/facebook.ts +206 -0
- package/src/social-providers/figma.ts +117 -0
- package/src/social-providers/github.ts +184 -0
- package/src/social-providers/gitlab.ts +155 -0
- package/src/social-providers/google.ts +199 -0
- package/src/social-providers/huggingface.ts +118 -0
- package/src/social-providers/index.ts +127 -0
- package/src/social-providers/kakao.ts +178 -0
- package/src/social-providers/kick.ts +109 -0
- package/src/social-providers/line.ts +169 -0
- package/src/social-providers/linear.ts +121 -0
- package/src/social-providers/linkedin.ts +110 -0
- package/src/social-providers/microsoft-entra-id.ts +259 -0
- package/src/social-providers/naver.ts +112 -0
- package/src/social-providers/notion.ts +108 -0
- package/src/social-providers/paybin.ts +122 -0
- package/src/social-providers/paypal.ts +263 -0
- package/src/social-providers/polar.ts +110 -0
- package/src/social-providers/reddit.ts +122 -0
- package/src/social-providers/roblox.ts +111 -0
- package/src/social-providers/salesforce.ts +159 -0
- package/src/social-providers/slack.ts +111 -0
- package/src/social-providers/spotify.ts +93 -0
- package/src/social-providers/tiktok.ts +209 -0
- package/src/social-providers/twitch.ts +111 -0
- package/src/social-providers/twitter.ts +198 -0
- package/src/social-providers/vercel.ts +87 -0
- package/src/social-providers/vk.ts +124 -0
- package/src/social-providers/zoom.ts +238 -0
- package/src/types/context.ts +396 -0
- package/src/types/cookie.ts +10 -0
- package/src/types/helper.ts +26 -0
- package/src/types/index.ts +32 -0
- package/src/types/init-options.ts +1529 -0
- package/src/types/plugin-client.ts +127 -0
- package/src/types/plugin.ts +157 -0
- package/src/utils/db.ts +20 -0
- package/src/utils/deprecate.test.ts +72 -0
- package/src/utils/deprecate.ts +21 -0
- package/src/utils/error-codes.ts +65 -0
- package/src/utils/id.ts +5 -0
- package/src/utils/ip.test.ts +255 -0
- package/src/utils/ip.ts +211 -0
- package/src/utils/json.ts +25 -0
- package/src/utils/string.ts +3 -0
- package/src/utils/url.ts +43 -0
- package/tsconfig.json +7 -0
- package/tsdown.config.ts +35 -0
- package/vitest.config.ts +3 -0
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { Awaitable, LiteralString } from "../types/helper.mjs";
|
|
2
|
+
import "../types/index.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/oauth2/oauth-provider.d.ts
|
|
5
|
+
interface OAuth2Tokens {
|
|
6
|
+
tokenType?: string | undefined;
|
|
7
|
+
accessToken?: string | undefined;
|
|
8
|
+
refreshToken?: string | undefined;
|
|
9
|
+
accessTokenExpiresAt?: Date | undefined;
|
|
10
|
+
refreshTokenExpiresAt?: Date | undefined;
|
|
11
|
+
scopes?: string[] | undefined;
|
|
12
|
+
idToken?: string | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* Raw token response from the provider.
|
|
15
|
+
* Preserves provider-specific fields that are not part of the standard OAuth2 token response.
|
|
16
|
+
*/
|
|
17
|
+
raw?: Record<string, unknown> | undefined;
|
|
18
|
+
}
|
|
19
|
+
type OAuth2UserInfo = {
|
|
20
|
+
id: string | number;
|
|
21
|
+
name?: string | undefined;
|
|
22
|
+
email?: (string | null) | undefined;
|
|
23
|
+
image?: string | undefined;
|
|
24
|
+
emailVerified: boolean;
|
|
25
|
+
};
|
|
26
|
+
interface OAuthProvider<T extends Record<string, any> = Record<string, any>, O extends Record<string, any> = Partial<ProviderOptions>> {
|
|
27
|
+
id: LiteralString;
|
|
28
|
+
createAuthorizationURL: (data: {
|
|
29
|
+
state: string;
|
|
30
|
+
codeVerifier: string;
|
|
31
|
+
scopes?: string[] | undefined;
|
|
32
|
+
redirectURI: string;
|
|
33
|
+
display?: string | undefined;
|
|
34
|
+
loginHint?: string | undefined;
|
|
35
|
+
}) => Awaitable<URL>;
|
|
36
|
+
name: string;
|
|
37
|
+
validateAuthorizationCode: (data: {
|
|
38
|
+
code: string;
|
|
39
|
+
redirectURI: string;
|
|
40
|
+
codeVerifier?: string | undefined;
|
|
41
|
+
deviceId?: string | undefined;
|
|
42
|
+
}) => Promise<OAuth2Tokens | null>;
|
|
43
|
+
getUserInfo: (token: OAuth2Tokens & {
|
|
44
|
+
/**
|
|
45
|
+
* The user object from the provider
|
|
46
|
+
* This is only available for some providers like Apple
|
|
47
|
+
*/
|
|
48
|
+
user?: {
|
|
49
|
+
name?: {
|
|
50
|
+
firstName?: string;
|
|
51
|
+
lastName?: string;
|
|
52
|
+
};
|
|
53
|
+
email?: string;
|
|
54
|
+
} | undefined;
|
|
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>) | undefined;
|
|
63
|
+
revokeToken?: ((token: string) => Promise<void>) | undefined;
|
|
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>) | undefined;
|
|
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 | undefined;
|
|
76
|
+
/**
|
|
77
|
+
* Disable sign up for new users.
|
|
78
|
+
*/
|
|
79
|
+
disableSignUp?: boolean | undefined;
|
|
80
|
+
/**
|
|
81
|
+
* Options for the provider
|
|
82
|
+
*/
|
|
83
|
+
options?: O | undefined;
|
|
84
|
+
}
|
|
85
|
+
type ProviderOptions<Profile extends Record<string, any> = any> = {
|
|
86
|
+
/**
|
|
87
|
+
* The client ID of your application.
|
|
88
|
+
*
|
|
89
|
+
* This is usually a string but can be any type depending on the provider.
|
|
90
|
+
*/
|
|
91
|
+
clientId?: unknown | undefined;
|
|
92
|
+
/**
|
|
93
|
+
* The client secret of your application
|
|
94
|
+
*/
|
|
95
|
+
clientSecret?: string | undefined;
|
|
96
|
+
/**
|
|
97
|
+
* The scopes you want to request from the provider
|
|
98
|
+
*/
|
|
99
|
+
scope?: string[] | undefined;
|
|
100
|
+
/**
|
|
101
|
+
* Remove default scopes of the provider
|
|
102
|
+
*/
|
|
103
|
+
disableDefaultScope?: boolean | undefined;
|
|
104
|
+
/**
|
|
105
|
+
* The redirect URL for your application. This is where the provider will
|
|
106
|
+
* redirect the user after the sign in process. Make sure this URL is
|
|
107
|
+
* whitelisted in the provider's dashboard.
|
|
108
|
+
*/
|
|
109
|
+
redirectURI?: string | undefined;
|
|
110
|
+
/**
|
|
111
|
+
* Custom authorization endpoint URL.
|
|
112
|
+
* Use this to override the default authorization endpoint of the provider.
|
|
113
|
+
* Useful for testing with local OAuth servers or using sandbox environments.
|
|
114
|
+
*/
|
|
115
|
+
authorizationEndpoint?: string | undefined;
|
|
116
|
+
/**
|
|
117
|
+
* The client key of your application
|
|
118
|
+
* Tiktok Social Provider uses this field instead of clientId
|
|
119
|
+
*/
|
|
120
|
+
clientKey?: string | undefined;
|
|
121
|
+
/**
|
|
122
|
+
* Disable provider from allowing users to sign in
|
|
123
|
+
* with this provider with an id token sent from the
|
|
124
|
+
* client.
|
|
125
|
+
*/
|
|
126
|
+
disableIdTokenSignIn?: boolean | undefined;
|
|
127
|
+
/**
|
|
128
|
+
* verifyIdToken function to verify the id token
|
|
129
|
+
*/
|
|
130
|
+
verifyIdToken?: ((token: string, nonce?: string) => Promise<boolean>) | undefined;
|
|
131
|
+
/**
|
|
132
|
+
* Custom function to get user info from the provider
|
|
133
|
+
*/
|
|
134
|
+
getUserInfo?: ((token: OAuth2Tokens) => Promise<{
|
|
135
|
+
user: {
|
|
136
|
+
id: string;
|
|
137
|
+
name?: string;
|
|
138
|
+
email?: string | null;
|
|
139
|
+
image?: string;
|
|
140
|
+
emailVerified: boolean;
|
|
141
|
+
[key: string]: any;
|
|
142
|
+
};
|
|
143
|
+
data: any;
|
|
144
|
+
} | null>) | undefined;
|
|
145
|
+
/**
|
|
146
|
+
* Custom function to refresh a token
|
|
147
|
+
*/
|
|
148
|
+
refreshAccessToken?: ((refreshToken: string) => Promise<OAuth2Tokens>) | undefined;
|
|
149
|
+
/**
|
|
150
|
+
* Custom function to map the provider profile to a
|
|
151
|
+
* user.
|
|
152
|
+
*/
|
|
153
|
+
mapProfileToUser?: ((profile: Profile) => {
|
|
154
|
+
id?: string;
|
|
155
|
+
name?: string;
|
|
156
|
+
email?: string | null;
|
|
157
|
+
image?: string;
|
|
158
|
+
emailVerified?: boolean;
|
|
159
|
+
[key: string]: any;
|
|
160
|
+
} | Promise<{
|
|
161
|
+
id?: string;
|
|
162
|
+
name?: string;
|
|
163
|
+
email?: string | null;
|
|
164
|
+
image?: string;
|
|
165
|
+
emailVerified?: boolean;
|
|
166
|
+
[key: string]: any;
|
|
167
|
+
}>) | undefined;
|
|
168
|
+
/**
|
|
169
|
+
* Disable implicit sign up for new users. When set to true for the provider,
|
|
170
|
+
* sign-in need to be called with with requestSignUp as true to create new users.
|
|
171
|
+
*/
|
|
172
|
+
disableImplicitSignUp?: boolean | undefined;
|
|
173
|
+
/**
|
|
174
|
+
* Disable sign up for new users.
|
|
175
|
+
*/
|
|
176
|
+
disableSignUp?: boolean | undefined;
|
|
177
|
+
/**
|
|
178
|
+
* The prompt to use for the authorization code request
|
|
179
|
+
*/
|
|
180
|
+
prompt?: ("select_account" | "consent" | "login" | "none" | "select_account consent") | undefined;
|
|
181
|
+
/**
|
|
182
|
+
* The response mode to use for the authorization code request
|
|
183
|
+
*/
|
|
184
|
+
responseMode?: ("query" | "form_post") | undefined;
|
|
185
|
+
/**
|
|
186
|
+
* If enabled, the user info will be overridden with the provider user info
|
|
187
|
+
* This is useful if you want to use the provider user info to update the user info
|
|
188
|
+
*
|
|
189
|
+
* @default false
|
|
190
|
+
*/
|
|
191
|
+
overrideUserInfoOnSignIn?: boolean | undefined;
|
|
192
|
+
};
|
|
193
|
+
//#endregion
|
|
194
|
+
export { OAuth2Tokens, OAuth2UserInfo, OAuthProvider, ProviderOptions };
|
|
195
|
+
//# sourceMappingURL=oauth-provider.d.mts.map
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { OAuth2Tokens, ProviderOptions } from "./oauth-provider.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/oauth2/refresh-access-token.d.ts
|
|
4
|
+
declare function createRefreshAccessTokenRequest({
|
|
5
|
+
refreshToken,
|
|
6
|
+
options,
|
|
7
|
+
authentication,
|
|
8
|
+
extraParams,
|
|
9
|
+
resource
|
|
10
|
+
}: {
|
|
11
|
+
refreshToken: string;
|
|
12
|
+
options: Partial<ProviderOptions>;
|
|
13
|
+
authentication?: ("basic" | "post") | undefined;
|
|
14
|
+
extraParams?: Record<string, string> | undefined;
|
|
15
|
+
resource?: (string | string[]) | undefined;
|
|
16
|
+
}): {
|
|
17
|
+
body: URLSearchParams;
|
|
18
|
+
headers: Record<string, any>;
|
|
19
|
+
};
|
|
20
|
+
declare function refreshAccessToken({
|
|
21
|
+
refreshToken,
|
|
22
|
+
options,
|
|
23
|
+
tokenEndpoint,
|
|
24
|
+
authentication,
|
|
25
|
+
extraParams
|
|
26
|
+
}: {
|
|
27
|
+
refreshToken: string;
|
|
28
|
+
options: Partial<ProviderOptions>;
|
|
29
|
+
tokenEndpoint: string;
|
|
30
|
+
authentication?: ("basic" | "post") | undefined;
|
|
31
|
+
extraParams?: Record<string, string> | undefined; /** @deprecated always "refresh_token" */
|
|
32
|
+
grantType?: string | undefined;
|
|
33
|
+
}): Promise<OAuth2Tokens>;
|
|
34
|
+
//#endregion
|
|
35
|
+
export { createRefreshAccessTokenRequest, refreshAccessToken };
|
|
36
|
+
//# sourceMappingURL=refresh-access-token.d.mts.map
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { betterFetch } from "@better-fetch/fetch";
|
|
2
|
+
import { base64 } from "@better-auth/utils/base64";
|
|
3
|
+
|
|
4
|
+
//#region src/oauth2/refresh-access-token.ts
|
|
5
|
+
function createRefreshAccessTokenRequest({ refreshToken, options, authentication, extraParams, resource }) {
|
|
6
|
+
const body = new URLSearchParams();
|
|
7
|
+
const headers = {
|
|
8
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
9
|
+
accept: "application/json"
|
|
10
|
+
};
|
|
11
|
+
body.set("grant_type", "refresh_token");
|
|
12
|
+
body.set("refresh_token", refreshToken);
|
|
13
|
+
if (authentication === "basic") {
|
|
14
|
+
const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId;
|
|
15
|
+
if (primaryClientId) headers["authorization"] = "Basic " + base64.encode(`${primaryClientId}:${options.clientSecret ?? ""}`);
|
|
16
|
+
else headers["authorization"] = "Basic " + base64.encode(`:${options.clientSecret ?? ""}`);
|
|
17
|
+
} else {
|
|
18
|
+
const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId;
|
|
19
|
+
body.set("client_id", primaryClientId);
|
|
20
|
+
if (options.clientSecret) body.set("client_secret", options.clientSecret);
|
|
21
|
+
}
|
|
22
|
+
if (resource) if (typeof resource === "string") body.append("resource", resource);
|
|
23
|
+
else for (const _resource of resource) body.append("resource", _resource);
|
|
24
|
+
if (extraParams) for (const [key, value] of Object.entries(extraParams)) body.set(key, value);
|
|
25
|
+
return {
|
|
26
|
+
body,
|
|
27
|
+
headers
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
async function refreshAccessToken({ refreshToken, options, tokenEndpoint, authentication, extraParams }) {
|
|
31
|
+
const { body, headers } = createRefreshAccessTokenRequest({
|
|
32
|
+
refreshToken,
|
|
33
|
+
options,
|
|
34
|
+
authentication,
|
|
35
|
+
extraParams
|
|
36
|
+
});
|
|
37
|
+
const { data, error } = await betterFetch(tokenEndpoint, {
|
|
38
|
+
method: "POST",
|
|
39
|
+
body,
|
|
40
|
+
headers
|
|
41
|
+
});
|
|
42
|
+
if (error) throw error;
|
|
43
|
+
const tokens = {
|
|
44
|
+
accessToken: data.access_token,
|
|
45
|
+
refreshToken: data.refresh_token,
|
|
46
|
+
tokenType: data.token_type,
|
|
47
|
+
scopes: data.scope?.split(" "),
|
|
48
|
+
idToken: data.id_token
|
|
49
|
+
};
|
|
50
|
+
if (data.expires_in) {
|
|
51
|
+
const now = /* @__PURE__ */ new Date();
|
|
52
|
+
tokens.accessTokenExpiresAt = new Date(now.getTime() + data.expires_in * 1e3);
|
|
53
|
+
}
|
|
54
|
+
return tokens;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
//#endregion
|
|
58
|
+
export { createRefreshAccessTokenRequest, refreshAccessToken };
|
|
59
|
+
//# sourceMappingURL=refresh-access-token.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"refresh-access-token.mjs","names":[],"sources":["../../src/oauth2/refresh-access-token.ts"],"sourcesContent":["import { base64 } from \"@better-auth/utils/base64\";\nimport { betterFetch } from \"@better-fetch/fetch\";\nimport type { OAuth2Tokens, ProviderOptions } from \"./oauth-provider\";\n\nexport function createRefreshAccessTokenRequest({\n\trefreshToken,\n\toptions,\n\tauthentication,\n\textraParams,\n\tresource,\n}: {\n\trefreshToken: string;\n\toptions: Partial<ProviderOptions>;\n\tauthentication?: (\"basic\" | \"post\") | undefined;\n\textraParams?: Record<string, string> | undefined;\n\tresource?: (string | string[]) | undefined;\n}) {\n\tconst body = new URLSearchParams();\n\tconst headers: Record<string, any> = {\n\t\t\"content-type\": \"application/x-www-form-urlencoded\",\n\t\taccept: \"application/json\",\n\t};\n\n\tbody.set(\"grant_type\", \"refresh_token\");\n\tbody.set(\"refresh_token\", refreshToken);\n\t// Use standard Base64 encoding for HTTP Basic Auth (OAuth2 spec, RFC 7617)\n\t// Fixes compatibility with providers like Notion, Twitter, etc.\n\tif (authentication === \"basic\") {\n\t\tconst primaryClientId = Array.isArray(options.clientId)\n\t\t\t? options.clientId[0]\n\t\t\t: options.clientId;\n\t\tif (primaryClientId) {\n\t\t\theaders[\"authorization\"] =\n\t\t\t\t\"Basic \" +\n\t\t\t\tbase64.encode(`${primaryClientId}:${options.clientSecret ?? \"\"}`);\n\t\t} else {\n\t\t\theaders[\"authorization\"] =\n\t\t\t\t\"Basic \" + base64.encode(`:${options.clientSecret ?? \"\"}`);\n\t\t}\n\t} else {\n\t\tconst primaryClientId = Array.isArray(options.clientId)\n\t\t\t? options.clientId[0]\n\t\t\t: options.clientId;\n\t\tbody.set(\"client_id\", primaryClientId);\n\t\tif (options.clientSecret) {\n\t\t\tbody.set(\"client_secret\", options.clientSecret);\n\t\t}\n\t}\n\n\tif (resource) {\n\t\tif (typeof resource === \"string\") {\n\t\t\tbody.append(\"resource\", resource);\n\t\t} else {\n\t\t\tfor (const _resource of resource) {\n\t\t\t\tbody.append(\"resource\", _resource);\n\t\t\t}\n\t\t}\n\t}\n\tif (extraParams) {\n\t\tfor (const [key, value] of Object.entries(extraParams)) {\n\t\t\tbody.set(key, value);\n\t\t}\n\t}\n\n\treturn {\n\t\tbody,\n\t\theaders,\n\t};\n}\n\nexport async function refreshAccessToken({\n\trefreshToken,\n\toptions,\n\ttokenEndpoint,\n\tauthentication,\n\textraParams,\n}: {\n\trefreshToken: string;\n\toptions: Partial<ProviderOptions>;\n\ttokenEndpoint: string;\n\tauthentication?: (\"basic\" | \"post\") | undefined;\n\textraParams?: Record<string, string> | undefined;\n\t/** @deprecated always \"refresh_token\" */\n\tgrantType?: string | undefined;\n}): Promise<OAuth2Tokens> {\n\tconst { body, headers } = createRefreshAccessTokenRequest({\n\t\trefreshToken,\n\t\toptions,\n\t\tauthentication,\n\t\textraParams,\n\t});\n\n\tconst { data, error } = await betterFetch<{\n\t\taccess_token: string;\n\t\trefresh_token?: string | undefined;\n\t\texpires_in?: number | undefined;\n\t\ttoken_type?: string | undefined;\n\t\tscope?: string | undefined;\n\t\tid_token?: string | undefined;\n\t}>(tokenEndpoint, {\n\t\tmethod: \"POST\",\n\t\tbody,\n\t\theaders,\n\t});\n\tif (error) {\n\t\tthrow error;\n\t}\n\tconst tokens: OAuth2Tokens = {\n\t\taccessToken: data.access_token,\n\t\trefreshToken: data.refresh_token,\n\t\ttokenType: data.token_type,\n\t\tscopes: data.scope?.split(\" \"),\n\t\tidToken: data.id_token,\n\t};\n\n\tif (data.expires_in) {\n\t\tconst now = new Date();\n\t\ttokens.accessTokenExpiresAt = new Date(\n\t\t\tnow.getTime() + data.expires_in * 1000,\n\t\t);\n\t}\n\n\treturn tokens;\n}\n"],"mappings":";;;;AAIA,SAAgB,gCAAgC,EAC/C,cACA,SACA,gBACA,aACA,YAOE;CACF,MAAM,OAAO,IAAI,iBAAiB;CAClC,MAAM,UAA+B;EACpC,gBAAgB;EAChB,QAAQ;EACR;AAED,MAAK,IAAI,cAAc,gBAAgB;AACvC,MAAK,IAAI,iBAAiB,aAAa;AAGvC,KAAI,mBAAmB,SAAS;EAC/B,MAAM,kBAAkB,MAAM,QAAQ,QAAQ,SAAS,GACpD,QAAQ,SAAS,KACjB,QAAQ;AACX,MAAI,gBACH,SAAQ,mBACP,WACA,OAAO,OAAO,GAAG,gBAAgB,GAAG,QAAQ,gBAAgB,KAAK;MAElE,SAAQ,mBACP,WAAW,OAAO,OAAO,IAAI,QAAQ,gBAAgB,KAAK;QAEtD;EACN,MAAM,kBAAkB,MAAM,QAAQ,QAAQ,SAAS,GACpD,QAAQ,SAAS,KACjB,QAAQ;AACX,OAAK,IAAI,aAAa,gBAAgB;AACtC,MAAI,QAAQ,aACX,MAAK,IAAI,iBAAiB,QAAQ,aAAa;;AAIjD,KAAI,SACH,KAAI,OAAO,aAAa,SACvB,MAAK,OAAO,YAAY,SAAS;KAEjC,MAAK,MAAM,aAAa,SACvB,MAAK,OAAO,YAAY,UAAU;AAIrC,KAAI,YACH,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,YAAY,CACrD,MAAK,IAAI,KAAK,MAAM;AAItB,QAAO;EACN;EACA;EACA;;AAGF,eAAsB,mBAAmB,EACxC,cACA,SACA,eACA,gBACA,eASyB;CACzB,MAAM,EAAE,MAAM,YAAY,gCAAgC;EACzD;EACA;EACA;EACA;EACA,CAAC;CAEF,MAAM,EAAE,MAAM,UAAU,MAAM,YAO3B,eAAe;EACjB,QAAQ;EACR;EACA;EACA,CAAC;AACF,KAAI,MACH,OAAM;CAEP,MAAM,SAAuB;EAC5B,aAAa,KAAK;EAClB,cAAc,KAAK;EACnB,WAAW,KAAK;EAChB,QAAQ,KAAK,OAAO,MAAM,IAAI;EAC9B,SAAS,KAAK;EACd;AAED,KAAI,KAAK,YAAY;EACpB,MAAM,sBAAM,IAAI,MAAM;AACtB,SAAO,uBAAuB,IAAI,KACjC,IAAI,SAAS,GAAG,KAAK,aAAa,IAClC;;AAGF,QAAO"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { OAuth2Tokens } from "./oauth-provider.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/oauth2/utils.d.ts
|
|
4
|
+
declare function getOAuth2Tokens(data: Record<string, any>): OAuth2Tokens;
|
|
5
|
+
declare function generateCodeChallenge(codeVerifier: string): Promise<string>;
|
|
6
|
+
//#endregion
|
|
7
|
+
export { generateCodeChallenge, getOAuth2Tokens };
|
|
8
|
+
//# sourceMappingURL=utils.d.mts.map
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { base64Url } from "@better-auth/utils/base64";
|
|
2
|
+
|
|
3
|
+
//#region src/oauth2/utils.ts
|
|
4
|
+
function getOAuth2Tokens(data) {
|
|
5
|
+
const getDate = (seconds) => {
|
|
6
|
+
const now = /* @__PURE__ */ new Date();
|
|
7
|
+
return new Date(now.getTime() + seconds * 1e3);
|
|
8
|
+
};
|
|
9
|
+
return {
|
|
10
|
+
tokenType: data.token_type,
|
|
11
|
+
accessToken: data.access_token,
|
|
12
|
+
refreshToken: data.refresh_token,
|
|
13
|
+
accessTokenExpiresAt: data.expires_in ? getDate(data.expires_in) : void 0,
|
|
14
|
+
refreshTokenExpiresAt: data.refresh_token_expires_in ? getDate(data.refresh_token_expires_in) : void 0,
|
|
15
|
+
scopes: data?.scope ? typeof data.scope === "string" ? data.scope.split(" ") : data.scope : [],
|
|
16
|
+
idToken: data.id_token,
|
|
17
|
+
raw: data
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
async function generateCodeChallenge(codeVerifier) {
|
|
21
|
+
const data = new TextEncoder().encode(codeVerifier);
|
|
22
|
+
const hash = await crypto.subtle.digest("SHA-256", data);
|
|
23
|
+
return base64Url.encode(new Uint8Array(hash), { padding: false });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
//#endregion
|
|
27
|
+
export { generateCodeChallenge, getOAuth2Tokens };
|
|
28
|
+
//# sourceMappingURL=utils.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.mjs","names":[],"sources":["../../src/oauth2/utils.ts"],"sourcesContent":["import { base64Url } from \"@better-auth/utils/base64\";\nimport type { OAuth2Tokens } from \"./oauth-provider\";\n\nexport function getOAuth2Tokens(data: Record<string, any>): OAuth2Tokens {\n\tconst getDate = (seconds: number) => {\n\t\tconst now = new Date();\n\t\treturn new Date(now.getTime() + seconds * 1000);\n\t};\n\n\treturn {\n\t\ttokenType: data.token_type,\n\t\taccessToken: data.access_token,\n\t\trefreshToken: data.refresh_token,\n\t\taccessTokenExpiresAt: data.expires_in\n\t\t\t? getDate(data.expires_in)\n\t\t\t: undefined,\n\t\trefreshTokenExpiresAt: data.refresh_token_expires_in\n\t\t\t? getDate(data.refresh_token_expires_in)\n\t\t\t: undefined,\n\t\tscopes: data?.scope\n\t\t\t? typeof data.scope === \"string\"\n\t\t\t\t? data.scope.split(\" \")\n\t\t\t\t: data.scope\n\t\t\t: [],\n\t\tidToken: data.id_token,\n\t\t// Preserve the raw token response for provider-specific fields\n\t\traw: data,\n\t};\n}\n\nexport async function generateCodeChallenge(codeVerifier: string) {\n\tconst encoder = new TextEncoder();\n\tconst data = encoder.encode(codeVerifier);\n\tconst hash = await crypto.subtle.digest(\"SHA-256\", data);\n\treturn base64Url.encode(new Uint8Array(hash), {\n\t\tpadding: false,\n\t});\n}\n"],"mappings":";;;AAGA,SAAgB,gBAAgB,MAAyC;CACxE,MAAM,WAAW,YAAoB;EACpC,MAAM,sBAAM,IAAI,MAAM;AACtB,SAAO,IAAI,KAAK,IAAI,SAAS,GAAG,UAAU,IAAK;;AAGhD,QAAO;EACN,WAAW,KAAK;EAChB,aAAa,KAAK;EAClB,cAAc,KAAK;EACnB,sBAAsB,KAAK,aACxB,QAAQ,KAAK,WAAW,GACxB;EACH,uBAAuB,KAAK,2BACzB,QAAQ,KAAK,yBAAyB,GACtC;EACH,QAAQ,MAAM,QACX,OAAO,KAAK,UAAU,WACrB,KAAK,MAAM,MAAM,IAAI,GACrB,KAAK,QACN,EAAE;EACL,SAAS,KAAK;EAEd,KAAK;EACL;;AAGF,eAAsB,sBAAsB,cAAsB;CAEjE,MAAM,OADU,IAAI,aAAa,CACZ,OAAO,aAAa;CACzC,MAAM,OAAO,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK;AACxD,QAAO,UAAU,OAAO,IAAI,WAAW,KAAK,EAAE,EAC7C,SAAS,OACT,CAAC"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { OAuth2Tokens, ProviderOptions } from "./oauth-provider.mjs";
|
|
2
|
+
import "./index.mjs";
|
|
3
|
+
import * as jose0 from "jose";
|
|
4
|
+
|
|
5
|
+
//#region src/oauth2/validate-authorization-code.d.ts
|
|
6
|
+
declare function createAuthorizationCodeRequest({
|
|
7
|
+
code,
|
|
8
|
+
codeVerifier,
|
|
9
|
+
redirectURI,
|
|
10
|
+
options,
|
|
11
|
+
authentication,
|
|
12
|
+
deviceId,
|
|
13
|
+
headers,
|
|
14
|
+
additionalParams,
|
|
15
|
+
resource
|
|
16
|
+
}: {
|
|
17
|
+
code: string;
|
|
18
|
+
redirectURI: string;
|
|
19
|
+
options: Partial<ProviderOptions>;
|
|
20
|
+
codeVerifier?: string | undefined;
|
|
21
|
+
deviceId?: string | undefined;
|
|
22
|
+
authentication?: ("basic" | "post") | undefined;
|
|
23
|
+
headers?: Record<string, string> | undefined;
|
|
24
|
+
additionalParams?: Record<string, string> | undefined;
|
|
25
|
+
resource?: (string | string[]) | undefined;
|
|
26
|
+
}): {
|
|
27
|
+
body: URLSearchParams;
|
|
28
|
+
headers: Record<string, any>;
|
|
29
|
+
};
|
|
30
|
+
declare function validateAuthorizationCode({
|
|
31
|
+
code,
|
|
32
|
+
codeVerifier,
|
|
33
|
+
redirectURI,
|
|
34
|
+
options,
|
|
35
|
+
tokenEndpoint,
|
|
36
|
+
authentication,
|
|
37
|
+
deviceId,
|
|
38
|
+
headers,
|
|
39
|
+
additionalParams,
|
|
40
|
+
resource
|
|
41
|
+
}: {
|
|
42
|
+
code: string;
|
|
43
|
+
redirectURI: string;
|
|
44
|
+
options: Partial<ProviderOptions>;
|
|
45
|
+
codeVerifier?: string | undefined;
|
|
46
|
+
deviceId?: string | undefined;
|
|
47
|
+
tokenEndpoint: string;
|
|
48
|
+
authentication?: ("basic" | "post") | undefined;
|
|
49
|
+
headers?: Record<string, string> | undefined;
|
|
50
|
+
additionalParams?: Record<string, string> | undefined;
|
|
51
|
+
resource?: (string | string[]) | undefined;
|
|
52
|
+
}): Promise<OAuth2Tokens>;
|
|
53
|
+
declare function validateToken(token: string, jwksEndpoint: string): Promise<jose0.JWTVerifyResult<jose0.JWTPayload>>;
|
|
54
|
+
//#endregion
|
|
55
|
+
export { createAuthorizationCodeRequest, validateAuthorizationCode, validateToken };
|
|
56
|
+
//# sourceMappingURL=validate-authorization-code.d.mts.map
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { getOAuth2Tokens } from "./utils.mjs";
|
|
2
|
+
import "./index.mjs";
|
|
3
|
+
import { betterFetch } from "@better-fetch/fetch";
|
|
4
|
+
import { decodeProtectedHeader, importJWK, jwtVerify } from "jose";
|
|
5
|
+
import { base64 } from "@better-auth/utils/base64";
|
|
6
|
+
|
|
7
|
+
//#region src/oauth2/validate-authorization-code.ts
|
|
8
|
+
function createAuthorizationCodeRequest({ code, codeVerifier, redirectURI, options, authentication, deviceId, headers, additionalParams = {}, resource }) {
|
|
9
|
+
const body = new URLSearchParams();
|
|
10
|
+
const requestHeaders = {
|
|
11
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
12
|
+
accept: "application/json",
|
|
13
|
+
...headers
|
|
14
|
+
};
|
|
15
|
+
body.set("grant_type", "authorization_code");
|
|
16
|
+
body.set("code", code);
|
|
17
|
+
codeVerifier && body.set("code_verifier", codeVerifier);
|
|
18
|
+
options.clientKey && body.set("client_key", options.clientKey);
|
|
19
|
+
deviceId && body.set("device_id", deviceId);
|
|
20
|
+
body.set("redirect_uri", options.redirectURI || redirectURI);
|
|
21
|
+
if (resource) if (typeof resource === "string") body.append("resource", resource);
|
|
22
|
+
else for (const _resource of resource) body.append("resource", _resource);
|
|
23
|
+
if (authentication === "basic") {
|
|
24
|
+
const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId;
|
|
25
|
+
requestHeaders["authorization"] = `Basic ${base64.encode(`${primaryClientId}:${options.clientSecret ?? ""}`)}`;
|
|
26
|
+
} else {
|
|
27
|
+
const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId;
|
|
28
|
+
body.set("client_id", primaryClientId);
|
|
29
|
+
if (options.clientSecret) body.set("client_secret", options.clientSecret);
|
|
30
|
+
}
|
|
31
|
+
for (const [key, value] of Object.entries(additionalParams)) if (!body.has(key)) body.append(key, value);
|
|
32
|
+
return {
|
|
33
|
+
body,
|
|
34
|
+
headers: requestHeaders
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
async function validateAuthorizationCode({ code, codeVerifier, redirectURI, options, tokenEndpoint, authentication, deviceId, headers, additionalParams = {}, resource }) {
|
|
38
|
+
const { body, headers: requestHeaders } = createAuthorizationCodeRequest({
|
|
39
|
+
code,
|
|
40
|
+
codeVerifier,
|
|
41
|
+
redirectURI,
|
|
42
|
+
options,
|
|
43
|
+
authentication,
|
|
44
|
+
deviceId,
|
|
45
|
+
headers,
|
|
46
|
+
additionalParams,
|
|
47
|
+
resource
|
|
48
|
+
});
|
|
49
|
+
const { data, error } = await betterFetch(tokenEndpoint, {
|
|
50
|
+
method: "POST",
|
|
51
|
+
body,
|
|
52
|
+
headers: requestHeaders
|
|
53
|
+
});
|
|
54
|
+
if (error) throw error;
|
|
55
|
+
return getOAuth2Tokens(data);
|
|
56
|
+
}
|
|
57
|
+
async function validateToken(token, jwksEndpoint) {
|
|
58
|
+
const { data, error } = await betterFetch(jwksEndpoint, {
|
|
59
|
+
method: "GET",
|
|
60
|
+
headers: { accept: "application/json" }
|
|
61
|
+
});
|
|
62
|
+
if (error) throw error;
|
|
63
|
+
const keys = data["keys"];
|
|
64
|
+
const header = decodeProtectedHeader(token);
|
|
65
|
+
const key = keys.find((k) => k.kid === header.kid);
|
|
66
|
+
if (!key) throw new Error("Key not found");
|
|
67
|
+
return await jwtVerify(token, await importJWK(key, header.alg));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
//#endregion
|
|
71
|
+
export { createAuthorizationCodeRequest, validateAuthorizationCode, validateToken };
|
|
72
|
+
//# sourceMappingURL=validate-authorization-code.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validate-authorization-code.mjs","names":[],"sources":["../../src/oauth2/validate-authorization-code.ts"],"sourcesContent":["import { base64 } from \"@better-auth/utils/base64\";\nimport { betterFetch } from \"@better-fetch/fetch\";\nimport type { JWK } from \"jose\";\nimport { decodeProtectedHeader, importJWK, jwtVerify } from \"jose\";\nimport type { ProviderOptions } from \"./index\";\nimport { getOAuth2Tokens } from \"./index\";\n\nexport function createAuthorizationCodeRequest({\n\tcode,\n\tcodeVerifier,\n\tredirectURI,\n\toptions,\n\tauthentication,\n\tdeviceId,\n\theaders,\n\tadditionalParams = {},\n\tresource,\n}: {\n\tcode: string;\n\tredirectURI: string;\n\toptions: Partial<ProviderOptions>;\n\tcodeVerifier?: string | undefined;\n\tdeviceId?: string | undefined;\n\tauthentication?: (\"basic\" | \"post\") | undefined;\n\theaders?: Record<string, string> | undefined;\n\tadditionalParams?: Record<string, string> | undefined;\n\tresource?: (string | string[]) | undefined;\n}) {\n\tconst body = new URLSearchParams();\n\tconst requestHeaders: Record<string, any> = {\n\t\t\"content-type\": \"application/x-www-form-urlencoded\",\n\t\taccept: \"application/json\",\n\t\t...headers,\n\t};\n\tbody.set(\"grant_type\", \"authorization_code\");\n\tbody.set(\"code\", code);\n\tcodeVerifier && body.set(\"code_verifier\", codeVerifier);\n\toptions.clientKey && body.set(\"client_key\", options.clientKey);\n\tdeviceId && body.set(\"device_id\", deviceId);\n\tbody.set(\"redirect_uri\", options.redirectURI || redirectURI);\n\tif (resource) {\n\t\tif (typeof resource === \"string\") {\n\t\t\tbody.append(\"resource\", resource);\n\t\t} else {\n\t\t\tfor (const _resource of resource) {\n\t\t\t\tbody.append(\"resource\", _resource);\n\t\t\t}\n\t\t}\n\t}\n\t// Use standard Base64 encoding for HTTP Basic Auth (OAuth2 spec, RFC 7617)\n\t// Fixes compatibility with providers like Notion, Twitter, etc.\n\tif (authentication === \"basic\") {\n\t\tconst primaryClientId = Array.isArray(options.clientId)\n\t\t\t? options.clientId[0]\n\t\t\t: options.clientId;\n\t\tconst encodedCredentials = base64.encode(\n\t\t\t`${primaryClientId}:${options.clientSecret ?? \"\"}`,\n\t\t);\n\t\trequestHeaders[\"authorization\"] = `Basic ${encodedCredentials}`;\n\t} else {\n\t\tconst primaryClientId = Array.isArray(options.clientId)\n\t\t\t? options.clientId[0]\n\t\t\t: options.clientId;\n\t\tbody.set(\"client_id\", primaryClientId);\n\t\tif (options.clientSecret) {\n\t\t\tbody.set(\"client_secret\", options.clientSecret);\n\t\t}\n\t}\n\n\tfor (const [key, value] of Object.entries(additionalParams)) {\n\t\tif (!body.has(key)) body.append(key, value);\n\t}\n\n\treturn {\n\t\tbody,\n\t\theaders: requestHeaders,\n\t};\n}\n\nexport async function validateAuthorizationCode({\n\tcode,\n\tcodeVerifier,\n\tredirectURI,\n\toptions,\n\ttokenEndpoint,\n\tauthentication,\n\tdeviceId,\n\theaders,\n\tadditionalParams = {},\n\tresource,\n}: {\n\tcode: string;\n\tredirectURI: string;\n\toptions: Partial<ProviderOptions>;\n\tcodeVerifier?: string | undefined;\n\tdeviceId?: string | undefined;\n\ttokenEndpoint: string;\n\tauthentication?: (\"basic\" | \"post\") | undefined;\n\theaders?: Record<string, string> | undefined;\n\tadditionalParams?: Record<string, string> | undefined;\n\tresource?: (string | string[]) | undefined;\n}) {\n\tconst { body, headers: requestHeaders } = createAuthorizationCodeRequest({\n\t\tcode,\n\t\tcodeVerifier,\n\t\tredirectURI,\n\t\toptions,\n\t\tauthentication,\n\t\tdeviceId,\n\t\theaders,\n\t\tadditionalParams,\n\t\tresource,\n\t});\n\n\tconst { data, error } = await betterFetch<object>(tokenEndpoint, {\n\t\tmethod: \"POST\",\n\t\tbody: body,\n\t\theaders: requestHeaders,\n\t});\n\n\tif (error) {\n\t\tthrow error;\n\t}\n\tconst tokens = getOAuth2Tokens(data);\n\treturn tokens;\n}\n\nexport async function validateToken(token: string, jwksEndpoint: string) {\n\tconst { data, error } = await betterFetch<{\n\t\tkeys: JWK[];\n\t}>(jwksEndpoint, {\n\t\tmethod: \"GET\",\n\t\theaders: {\n\t\t\taccept: \"application/json\",\n\t\t},\n\t});\n\tif (error) {\n\t\tthrow error;\n\t}\n\tconst keys = data[\"keys\"];\n\tconst header = decodeProtectedHeader(token);\n\tconst key = keys.find((k) => k.kid === header.kid);\n\tif (!key) {\n\t\tthrow new Error(\"Key not found\");\n\t}\n\tconst cryptoKey = await importJWK(key, header.alg);\n\tconst verified = await jwtVerify(token, cryptoKey);\n\treturn verified;\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,+BAA+B,EAC9C,MACA,cACA,aACA,SACA,gBACA,UACA,SACA,mBAAmB,EAAE,EACrB,YAWE;CACF,MAAM,OAAO,IAAI,iBAAiB;CAClC,MAAM,iBAAsC;EAC3C,gBAAgB;EAChB,QAAQ;EACR,GAAG;EACH;AACD,MAAK,IAAI,cAAc,qBAAqB;AAC5C,MAAK,IAAI,QAAQ,KAAK;AACtB,iBAAgB,KAAK,IAAI,iBAAiB,aAAa;AACvD,SAAQ,aAAa,KAAK,IAAI,cAAc,QAAQ,UAAU;AAC9D,aAAY,KAAK,IAAI,aAAa,SAAS;AAC3C,MAAK,IAAI,gBAAgB,QAAQ,eAAe,YAAY;AAC5D,KAAI,SACH,KAAI,OAAO,aAAa,SACvB,MAAK,OAAO,YAAY,SAAS;KAEjC,MAAK,MAAM,aAAa,SACvB,MAAK,OAAO,YAAY,UAAU;AAMrC,KAAI,mBAAmB,SAAS;EAC/B,MAAM,kBAAkB,MAAM,QAAQ,QAAQ,SAAS,GACpD,QAAQ,SAAS,KACjB,QAAQ;AAIX,iBAAe,mBAAmB,SAHP,OAAO,OACjC,GAAG,gBAAgB,GAAG,QAAQ,gBAAgB,KAC9C;QAEK;EACN,MAAM,kBAAkB,MAAM,QAAQ,QAAQ,SAAS,GACpD,QAAQ,SAAS,KACjB,QAAQ;AACX,OAAK,IAAI,aAAa,gBAAgB;AACtC,MAAI,QAAQ,aACX,MAAK,IAAI,iBAAiB,QAAQ,aAAa;;AAIjD,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,iBAAiB,CAC1D,KAAI,CAAC,KAAK,IAAI,IAAI,CAAE,MAAK,OAAO,KAAK,MAAM;AAG5C,QAAO;EACN;EACA,SAAS;EACT;;AAGF,eAAsB,0BAA0B,EAC/C,MACA,cACA,aACA,SACA,eACA,gBACA,UACA,SACA,mBAAmB,EAAE,EACrB,YAYE;CACF,MAAM,EAAE,MAAM,SAAS,mBAAmB,+BAA+B;EACxE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,CAAC;CAEF,MAAM,EAAE,MAAM,UAAU,MAAM,YAAoB,eAAe;EAChE,QAAQ;EACF;EACN,SAAS;EACT,CAAC;AAEF,KAAI,MACH,OAAM;AAGP,QADe,gBAAgB,KAAK;;AAIrC,eAAsB,cAAc,OAAe,cAAsB;CACxE,MAAM,EAAE,MAAM,UAAU,MAAM,YAE3B,cAAc;EAChB,QAAQ;EACR,SAAS,EACR,QAAQ,oBACR;EACD,CAAC;AACF,KAAI,MACH,OAAM;CAEP,MAAM,OAAO,KAAK;CAClB,MAAM,SAAS,sBAAsB,MAAM;CAC3C,MAAM,MAAM,KAAK,MAAM,MAAM,EAAE,QAAQ,OAAO,IAAI;AAClD,KAAI,CAAC,IACJ,OAAM,IAAI,MAAM,gBAAgB;AAIjC,QADiB,MAAM,UAAU,OADf,MAAM,UAAU,KAAK,OAAO,IAAI,CACA"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { JSONWebKeySet, JWTPayload, JWTVerifyOptions } from "jose";
|
|
2
|
+
|
|
3
|
+
//#region src/oauth2/verify.d.ts
|
|
4
|
+
interface VerifyAccessTokenRemote {
|
|
5
|
+
/** Full url of the introspect endpoint. Should end with `/oauth2/introspect` */
|
|
6
|
+
introspectUrl: string;
|
|
7
|
+
/** Client Secret */
|
|
8
|
+
clientId: string;
|
|
9
|
+
/** Client Secret */
|
|
10
|
+
clientSecret: string;
|
|
11
|
+
/**
|
|
12
|
+
* Forces remote verification of a token.
|
|
13
|
+
* This ensures attached session (if applicable)
|
|
14
|
+
* is also still active.
|
|
15
|
+
*/
|
|
16
|
+
force?: boolean;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Performs local verification of an access token for your APIs.
|
|
20
|
+
*
|
|
21
|
+
* Can also be configured for remote verification.
|
|
22
|
+
*/
|
|
23
|
+
declare function verifyJwsAccessToken(token: string, opts: {
|
|
24
|
+
/** Jwks url or promise of a Jwks */jwksFetch: string | (() => Promise<JSONWebKeySet | undefined>); /** Verify options */
|
|
25
|
+
verifyOptions: JWTVerifyOptions & Required<Pick<JWTVerifyOptions, "audience" | "issuer">>;
|
|
26
|
+
}): Promise<JWTPayload>;
|
|
27
|
+
declare function getJwks(token: string, opts: {
|
|
28
|
+
/** Jwks url or promise of a Jwks */jwksFetch: string | (() => Promise<JSONWebKeySet | undefined>);
|
|
29
|
+
}): Promise<JSONWebKeySet>;
|
|
30
|
+
/**
|
|
31
|
+
* Performs local verification of an access token for your API.
|
|
32
|
+
*
|
|
33
|
+
* Can also be configured for remote verification.
|
|
34
|
+
*/
|
|
35
|
+
declare function verifyAccessToken(token: string, opts: {
|
|
36
|
+
/** Verify options */verifyOptions: JWTVerifyOptions & Required<Pick<JWTVerifyOptions, "audience" | "issuer">>; /** Scopes to additionally verify. Token must include all but not exact. */
|
|
37
|
+
scopes?: string[]; /** Required to verify access token locally */
|
|
38
|
+
jwksUrl?: string; /** If provided, can verify a token remotely */
|
|
39
|
+
remoteVerify?: VerifyAccessTokenRemote;
|
|
40
|
+
}): Promise<JWTPayload>;
|
|
41
|
+
//#endregion
|
|
42
|
+
export { getJwks, verifyAccessToken, verifyJwsAccessToken };
|
|
43
|
+
//# sourceMappingURL=verify.d.mts.map
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { logger } from "../env/logger.mjs";
|
|
2
|
+
import "../env/index.mjs";
|
|
3
|
+
import { APIError } from "better-call";
|
|
4
|
+
import { betterFetch } from "@better-fetch/fetch";
|
|
5
|
+
import { UnsecuredJWT, createLocalJWKSet, decodeProtectedHeader, jwtVerify } from "jose";
|
|
6
|
+
|
|
7
|
+
//#region src/oauth2/verify.ts
|
|
8
|
+
/** Last fetched jwks used locally in getJwks @internal */
|
|
9
|
+
let jwks;
|
|
10
|
+
/**
|
|
11
|
+
* Performs local verification of an access token for your APIs.
|
|
12
|
+
*
|
|
13
|
+
* Can also be configured for remote verification.
|
|
14
|
+
*/
|
|
15
|
+
async function verifyJwsAccessToken(token, opts) {
|
|
16
|
+
try {
|
|
17
|
+
const jwt = await jwtVerify(token, createLocalJWKSet(await getJwks(token, opts)), opts.verifyOptions);
|
|
18
|
+
if (jwt.payload.azp) jwt.payload.client_id = jwt.payload.azp;
|
|
19
|
+
return jwt.payload;
|
|
20
|
+
} catch (error) {
|
|
21
|
+
if (error instanceof Error) throw error;
|
|
22
|
+
throw new Error(error);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
async function getJwks(token, opts) {
|
|
26
|
+
let jwtHeaders;
|
|
27
|
+
try {
|
|
28
|
+
jwtHeaders = decodeProtectedHeader(token);
|
|
29
|
+
} catch (error) {
|
|
30
|
+
if (error instanceof Error) throw error;
|
|
31
|
+
throw new Error(error);
|
|
32
|
+
}
|
|
33
|
+
if (!jwtHeaders.kid) throw new Error("Missing jwt kid");
|
|
34
|
+
if (!jwks || !jwks.keys.find((jwk) => jwk.kid === jwtHeaders.kid)) {
|
|
35
|
+
jwks = typeof opts.jwksFetch === "string" ? await betterFetch(opts.jwksFetch, { headers: { Accept: "application/json" } }).then(async (res) => {
|
|
36
|
+
if (res.error) throw new Error(`Jwks failed: ${res.error.message ?? res.error.statusText}`);
|
|
37
|
+
return res.data;
|
|
38
|
+
}) : await opts.jwksFetch();
|
|
39
|
+
if (!jwks) throw new Error("No jwks found");
|
|
40
|
+
}
|
|
41
|
+
return jwks;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Performs local verification of an access token for your API.
|
|
45
|
+
*
|
|
46
|
+
* Can also be configured for remote verification.
|
|
47
|
+
*/
|
|
48
|
+
async function verifyAccessToken(token, opts) {
|
|
49
|
+
let payload;
|
|
50
|
+
if (opts.jwksUrl && !opts?.remoteVerify?.force) try {
|
|
51
|
+
payload = await verifyJwsAccessToken(token, {
|
|
52
|
+
jwksFetch: opts.jwksUrl,
|
|
53
|
+
verifyOptions: opts.verifyOptions
|
|
54
|
+
});
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (error instanceof Error) if (error.name === "TypeError" || error.name === "JWSInvalid") {} else if (error.name === "JWTExpired") throw new APIError("UNAUTHORIZED", { message: "token expired" });
|
|
57
|
+
else if (error.name === "JWTInvalid") throw new APIError("UNAUTHORIZED", { message: "token invalid" });
|
|
58
|
+
else throw error;
|
|
59
|
+
else throw new Error(error);
|
|
60
|
+
}
|
|
61
|
+
if (opts?.remoteVerify) {
|
|
62
|
+
const { data: introspect, error: introspectError } = await betterFetch(opts.remoteVerify.introspectUrl, {
|
|
63
|
+
method: "POST",
|
|
64
|
+
headers: {
|
|
65
|
+
Accept: "application/json",
|
|
66
|
+
"Content-Type": "application/x-www-form-urlencoded"
|
|
67
|
+
},
|
|
68
|
+
body: new URLSearchParams({
|
|
69
|
+
client_id: opts.remoteVerify.clientId,
|
|
70
|
+
client_secret: opts.remoteVerify.clientSecret,
|
|
71
|
+
token,
|
|
72
|
+
token_type_hint: "access_token"
|
|
73
|
+
}).toString()
|
|
74
|
+
});
|
|
75
|
+
if (introspectError) logger.error(`Introspection failed: ${introspectError.message ?? introspectError.statusText}`);
|
|
76
|
+
if (!introspect) throw new APIError("INTERNAL_SERVER_ERROR", { message: "introspection failed" });
|
|
77
|
+
if (!introspect.active) throw new APIError("UNAUTHORIZED", { message: "token inactive" });
|
|
78
|
+
try {
|
|
79
|
+
const unsecuredJwt = new UnsecuredJWT(introspect).encode();
|
|
80
|
+
const { audience: _audience, ...verifyOptions } = opts.verifyOptions;
|
|
81
|
+
payload = (introspect.aud ? UnsecuredJWT.decode(unsecuredJwt, opts.verifyOptions) : UnsecuredJWT.decode(unsecuredJwt, verifyOptions)).payload;
|
|
82
|
+
} catch (error) {
|
|
83
|
+
throw new Error(error);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (!payload) throw new APIError("UNAUTHORIZED", { message: `no token payload` });
|
|
87
|
+
if (opts.scopes) {
|
|
88
|
+
const validScopes = new Set(payload.scope?.split(" "));
|
|
89
|
+
for (const sc of opts.scopes) if (!validScopes.has(sc)) throw new APIError("FORBIDDEN", { message: `invalid scope ${sc}` });
|
|
90
|
+
}
|
|
91
|
+
return payload;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
//#endregion
|
|
95
|
+
export { getJwks, verifyAccessToken, verifyJwsAccessToken };
|
|
96
|
+
//# sourceMappingURL=verify.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"verify.mjs","names":[],"sources":["../../src/oauth2/verify.ts"],"sourcesContent":["import { betterFetch } from \"@better-fetch/fetch\";\nimport { APIError } from \"better-call\";\nimport type {\n\tJSONWebKeySet,\n\tJWTPayload,\n\tJWTVerifyOptions,\n\tProtectedHeaderParameters,\n} from \"jose\";\nimport {\n\tcreateLocalJWKSet,\n\tdecodeProtectedHeader,\n\tjwtVerify,\n\tUnsecuredJWT,\n} from \"jose\";\nimport { logger } from \"../env\";\n\n/** Last fetched jwks used locally in getJwks @internal */\nlet jwks: JSONWebKeySet | undefined;\n\nexport interface VerifyAccessTokenRemote {\n\t/** Full url of the introspect endpoint. Should end with `/oauth2/introspect` */\n\tintrospectUrl: string;\n\t/** Client Secret */\n\tclientId: string;\n\t/** Client Secret */\n\tclientSecret: string;\n\t/**\n\t * Forces remote verification of a token.\n\t * This ensures attached session (if applicable)\n\t * is also still active.\n\t */\n\tforce?: boolean;\n}\n\n/**\n * Performs local verification of an access token for your APIs.\n *\n * Can also be configured for remote verification.\n */\nexport async function verifyJwsAccessToken(\n\ttoken: string,\n\topts: {\n\t\t/** Jwks url or promise of a Jwks */\n\t\tjwksFetch: string | (() => Promise<JSONWebKeySet | undefined>);\n\t\t/** Verify options */\n\t\tverifyOptions: JWTVerifyOptions &\n\t\t\tRequired<Pick<JWTVerifyOptions, \"audience\" | \"issuer\">>;\n\t},\n) {\n\ttry {\n\t\tconst jwks = await getJwks(token, opts);\n\t\tconst jwt = await jwtVerify<JWTPayload>(\n\t\t\ttoken,\n\t\t\tcreateLocalJWKSet(jwks),\n\t\t\topts.verifyOptions,\n\t\t);\n\t\t// Return the JWT payload in introspection format\n\t\t// https://datatracker.ietf.org/doc/html/rfc7662#section-2.2\n\t\tif (jwt.payload.azp) {\n\t\t\tjwt.payload.client_id = jwt.payload.azp;\n\t\t}\n\t\treturn jwt.payload;\n\t} catch (error) {\n\t\tif (error instanceof Error) throw error;\n\t\tthrow new Error(error as unknown as string);\n\t}\n}\n\nexport async function getJwks(\n\ttoken: string,\n\topts: {\n\t\t/** Jwks url or promise of a Jwks */\n\t\tjwksFetch: string | (() => Promise<JSONWebKeySet | undefined>);\n\t},\n) {\n\t// Attempt to decode the token and find a matching kid in jwks\n\tlet jwtHeaders: ProtectedHeaderParameters | undefined;\n\ttry {\n\t\tjwtHeaders = decodeProtectedHeader(token);\n\t} catch (error) {\n\t\tif (error instanceof Error) throw error;\n\t\tthrow new Error(error as unknown as string);\n\t}\n\n\tif (!jwtHeaders.kid) throw new Error(\"Missing jwt kid\");\n\n\t// Fetch jwks if not set or has a different kid than the one stored\n\tif (!jwks || !jwks.keys.find((jwk) => jwk.kid === jwtHeaders.kid)) {\n\t\tjwks =\n\t\t\ttypeof opts.jwksFetch === \"string\"\n\t\t\t\t? await betterFetch<JSONWebKeySet>(opts.jwksFetch, {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\t\t},\n\t\t\t\t\t}).then(async (res) => {\n\t\t\t\t\t\tif (res.error)\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Jwks failed: ${res.error.message ?? res.error.statusText}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn res.data;\n\t\t\t\t\t})\n\t\t\t\t: await opts.jwksFetch();\n\t\tif (!jwks) throw new Error(\"No jwks found\");\n\t}\n\n\treturn jwks;\n}\n\n/**\n * Performs local verification of an access token for your API.\n *\n * Can also be configured for remote verification.\n */\nexport async function verifyAccessToken(\n\ttoken: string,\n\topts: {\n\t\t/** Verify options */\n\t\tverifyOptions: JWTVerifyOptions &\n\t\t\tRequired<Pick<JWTVerifyOptions, \"audience\" | \"issuer\">>;\n\t\t/** Scopes to additionally verify. Token must include all but not exact. */\n\t\tscopes?: string[];\n\t\t/** Required to verify access token locally */\n\t\tjwksUrl?: string;\n\t\t/** If provided, can verify a token remotely */\n\t\tremoteVerify?: VerifyAccessTokenRemote;\n\t},\n) {\n\tlet payload: JWTPayload | undefined;\n\t// Locally verify\n\tif (opts.jwksUrl && !opts?.remoteVerify?.force) {\n\t\ttry {\n\t\t\tpayload = await verifyJwsAccessToken(token, {\n\t\t\t\tjwksFetch: opts.jwksUrl,\n\t\t\t\tverifyOptions: opts.verifyOptions,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tif (error.name === \"TypeError\" || error.name === \"JWSInvalid\") {\n\t\t\t\t\t// likely an opaque token (continue)\n\t\t\t\t} else if (error.name === \"JWTExpired\") {\n\t\t\t\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\t\t\t\tmessage: \"token expired\",\n\t\t\t\t\t});\n\t\t\t\t} else if (error.name === \"JWTInvalid\") {\n\t\t\t\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\t\t\t\tmessage: \"token invalid\",\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new Error(error as unknown as string);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remote verify\n\tif (opts?.remoteVerify) {\n\t\tconst { data: introspect, error: introspectError } = await betterFetch<\n\t\t\tJWTPayload & {\n\t\t\t\tactive: boolean;\n\t\t\t}\n\t\t>(opts.remoteVerify.introspectUrl, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\t},\n\t\t\tbody: new URLSearchParams({\n\t\t\t\tclient_id: opts.remoteVerify.clientId,\n\t\t\t\tclient_secret: opts.remoteVerify.clientSecret,\n\t\t\t\ttoken,\n\t\t\t\ttoken_type_hint: \"access_token\",\n\t\t\t}).toString(),\n\t\t});\n\t\tif (introspectError)\n\t\t\tlogger.error(\n\t\t\t\t`Introspection failed: ${introspectError.message ?? introspectError.statusText}`,\n\t\t\t);\n\t\tif (!introspect)\n\t\t\tthrow new APIError(\"INTERNAL_SERVER_ERROR\", {\n\t\t\t\tmessage: \"introspection failed\",\n\t\t\t});\n\t\tif (!introspect.active)\n\t\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\t\tmessage: \"token inactive\",\n\t\t\t});\n\t\t// Verifies payload using verify options (token valid through introspect)\n\t\ttry {\n\t\t\tconst unsecuredJwt = new UnsecuredJWT(introspect).encode();\n\t\t\tconst { audience: _audience, ...verifyOptions } = opts.verifyOptions;\n\t\t\tconst verify = introspect.aud\n\t\t\t\t? UnsecuredJWT.decode(unsecuredJwt, opts.verifyOptions)\n\t\t\t\t: UnsecuredJWT.decode(unsecuredJwt, verifyOptions);\n\t\t\tpayload = verify.payload;\n\t\t} catch (error) {\n\t\t\tthrow new Error(error as unknown as string);\n\t\t}\n\t}\n\n\tif (!payload)\n\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\tmessage: `no token payload`,\n\t\t});\n\n\t// Check scopes if provided\n\tif (opts.scopes) {\n\t\tconst validScopes = new Set(\n\t\t\t(payload.scope as string | undefined)?.split(\" \"),\n\t\t);\n\t\tfor (const sc of opts.scopes) {\n\t\t\tif (!validScopes.has(sc)) {\n\t\t\t\tthrow new APIError(\"FORBIDDEN\", {\n\t\t\t\t\tmessage: `invalid scope ${sc}`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\treturn payload;\n}\n"],"mappings":";;;;;;;;AAiBA,IAAI;;;;;;AAsBJ,eAAsB,qBACrB,OACA,MAOC;AACD,KAAI;EAEH,MAAM,MAAM,MAAM,UACjB,OACA,kBAHY,MAAM,QAAQ,OAAO,KAAK,CAGf,EACvB,KAAK,cACL;AAGD,MAAI,IAAI,QAAQ,IACf,KAAI,QAAQ,YAAY,IAAI,QAAQ;AAErC,SAAO,IAAI;UACH,OAAO;AACf,MAAI,iBAAiB,MAAO,OAAM;AAClC,QAAM,IAAI,MAAM,MAA2B;;;AAI7C,eAAsB,QACrB,OACA,MAIC;CAED,IAAI;AACJ,KAAI;AACH,eAAa,sBAAsB,MAAM;UACjC,OAAO;AACf,MAAI,iBAAiB,MAAO,OAAM;AAClC,QAAM,IAAI,MAAM,MAA2B;;AAG5C,KAAI,CAAC,WAAW,IAAK,OAAM,IAAI,MAAM,kBAAkB;AAGvD,KAAI,CAAC,QAAQ,CAAC,KAAK,KAAK,MAAM,QAAQ,IAAI,QAAQ,WAAW,IAAI,EAAE;AAClE,SACC,OAAO,KAAK,cAAc,WACvB,MAAM,YAA2B,KAAK,WAAW,EACjD,SAAS,EACR,QAAQ,oBACR,EACD,CAAC,CAAC,KAAK,OAAO,QAAQ;AACtB,OAAI,IAAI,MACP,OAAM,IAAI,MACT,gBAAgB,IAAI,MAAM,WAAW,IAAI,MAAM,aAC/C;AACF,UAAO,IAAI;IACV,GACD,MAAM,KAAK,WAAW;AAC1B,MAAI,CAAC,KAAM,OAAM,IAAI,MAAM,gBAAgB;;AAG5C,QAAO;;;;;;;AAQR,eAAsB,kBACrB,OACA,MAWC;CACD,IAAI;AAEJ,KAAI,KAAK,WAAW,CAAC,MAAM,cAAc,MACxC,KAAI;AACH,YAAU,MAAM,qBAAqB,OAAO;GAC3C,WAAW,KAAK;GAChB,eAAe,KAAK;GACpB,CAAC;UACM,OAAO;AACf,MAAI,iBAAiB,MACpB,KAAI,MAAM,SAAS,eAAe,MAAM,SAAS,cAAc,YAEpD,MAAM,SAAS,aACzB,OAAM,IAAI,SAAS,gBAAgB,EAClC,SAAS,iBACT,CAAC;WACQ,MAAM,SAAS,aACzB,OAAM,IAAI,SAAS,gBAAgB,EAClC,SAAS,iBACT,CAAC;MAEF,OAAM;MAGP,OAAM,IAAI,MAAM,MAA2B;;AAM9C,KAAI,MAAM,cAAc;EACvB,MAAM,EAAE,MAAM,YAAY,OAAO,oBAAoB,MAAM,YAIzD,KAAK,aAAa,eAAe;GAClC,QAAQ;GACR,SAAS;IACR,QAAQ;IACR,gBAAgB;IAChB;GACD,MAAM,IAAI,gBAAgB;IACzB,WAAW,KAAK,aAAa;IAC7B,eAAe,KAAK,aAAa;IACjC;IACA,iBAAiB;IACjB,CAAC,CAAC,UAAU;GACb,CAAC;AACF,MAAI,gBACH,QAAO,MACN,yBAAyB,gBAAgB,WAAW,gBAAgB,aACpE;AACF,MAAI,CAAC,WACJ,OAAM,IAAI,SAAS,yBAAyB,EAC3C,SAAS,wBACT,CAAC;AACH,MAAI,CAAC,WAAW,OACf,OAAM,IAAI,SAAS,gBAAgB,EAClC,SAAS,kBACT,CAAC;AAEH,MAAI;GACH,MAAM,eAAe,IAAI,aAAa,WAAW,CAAC,QAAQ;GAC1D,MAAM,EAAE,UAAU,WAAW,GAAG,kBAAkB,KAAK;AAIvD,cAHe,WAAW,MACvB,aAAa,OAAO,cAAc,KAAK,cAAc,GACrD,aAAa,OAAO,cAAc,cAAc,EAClC;WACT,OAAO;AACf,SAAM,IAAI,MAAM,MAA2B;;;AAI7C,KAAI,CAAC,QACJ,OAAM,IAAI,SAAS,gBAAgB,EAClC,SAAS,oBACT,CAAC;AAGH,KAAI,KAAK,QAAQ;EAChB,MAAM,cAAc,IAAI,IACtB,QAAQ,OAA8B,MAAM,IAAI,CACjD;AACD,OAAK,MAAM,MAAM,KAAK,OACrB,KAAI,CAAC,YAAY,IAAI,GAAG,CACvB,OAAM,IAAI,SAAS,aAAa,EAC/B,SAAS,iBAAiB,MAC1B,CAAC;;AAKL,QAAO"}
|