@better-auth/core 1.4.0-beta.7 → 1.4.0-beta.8

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 (39) hide show
  1. package/.turbo/turbo-build.log +12 -4
  2. package/build.config.ts +2 -0
  3. package/dist/db/index.cjs +16 -0
  4. package/dist/db/index.d.cts +14 -3
  5. package/dist/db/index.d.mts +14 -3
  6. package/dist/db/index.d.ts +14 -3
  7. package/dist/db/index.mjs +16 -1
  8. package/dist/env/index.cjs +315 -0
  9. package/dist/env/index.d.cts +85 -0
  10. package/dist/env/index.d.mts +85 -0
  11. package/dist/env/index.d.ts +85 -0
  12. package/dist/env/index.mjs +300 -0
  13. package/dist/index.d.cts +2 -2
  14. package/dist/index.d.mts +2 -2
  15. package/dist/index.d.ts +2 -2
  16. package/dist/oauth2/index.cjs +368 -0
  17. package/dist/oauth2/index.d.cts +277 -0
  18. package/dist/oauth2/index.d.mts +277 -0
  19. package/dist/oauth2/index.d.ts +277 -0
  20. package/dist/oauth2/index.mjs +357 -0
  21. package/dist/shared/{core.CnvFgghY.d.cts → core.DeNN5HMO.d.cts} +27 -1
  22. package/dist/shared/{core.CnvFgghY.d.mts → core.DeNN5HMO.d.mts} +27 -1
  23. package/dist/shared/{core.CnvFgghY.d.ts → core.DeNN5HMO.d.ts} +27 -1
  24. package/package.json +29 -1
  25. package/src/db/index.ts +2 -0
  26. package/src/db/schema/rate-limit.ts +21 -0
  27. package/src/db/type.ts +28 -0
  28. package/src/env/color-depth.ts +171 -0
  29. package/src/env/env-impl.ts +123 -0
  30. package/src/env/index.ts +23 -0
  31. package/src/env/logger.test.ts +33 -0
  32. package/src/env/logger.ts +145 -0
  33. package/src/oauth2/client-credentials-token.ts +102 -0
  34. package/src/oauth2/create-authorization-url.ts +85 -0
  35. package/src/oauth2/index.ts +22 -0
  36. package/src/oauth2/oauth-provider.ts +194 -0
  37. package/src/oauth2/refresh-access-token.ts +124 -0
  38. package/src/oauth2/utils.ts +36 -0
  39. package/src/oauth2/validate-authorization-code.ts +156 -0
@@ -0,0 +1,171 @@
1
+ // Source code copied & modified from node internals: https://github.com/nodejs/node/blob/5b32bb1573dace2dd058c05ac4fab1e4e446c775/lib/internal/tty.js#L123
2
+ import { env, getEnvVar } from "./env-impl";
3
+
4
+ const COLORS_2 = 1;
5
+ const COLORS_16 = 4;
6
+ const COLORS_256 = 8;
7
+ const COLORS_16m = 24;
8
+
9
+ const TERM_ENVS: Record<string, number> = {
10
+ eterm: COLORS_16,
11
+ cons25: COLORS_16,
12
+ console: COLORS_16,
13
+ cygwin: COLORS_16,
14
+ dtterm: COLORS_16,
15
+ gnome: COLORS_16,
16
+ hurd: COLORS_16,
17
+ jfbterm: COLORS_16,
18
+ konsole: COLORS_16,
19
+ kterm: COLORS_16,
20
+ mlterm: COLORS_16,
21
+ mosh: COLORS_16m,
22
+ putty: COLORS_16,
23
+ st: COLORS_16,
24
+ // http://lists.schmorp.de/pipermail/rxvt-unicode/2016q2/002261.html
25
+ "rxvt-unicode-24bit": COLORS_16m,
26
+ // https://bugs.launchpad.net/terminator/+bug/1030562
27
+ terminator: COLORS_16m,
28
+ "xterm-kitty": COLORS_16m,
29
+ };
30
+
31
+ const CI_ENVS_MAP = new Map(
32
+ Object.entries({
33
+ APPVEYOR: COLORS_256,
34
+ BUILDKITE: COLORS_256,
35
+ CIRCLECI: COLORS_16m,
36
+ DRONE: COLORS_256,
37
+ GITEA_ACTIONS: COLORS_16m,
38
+ GITHUB_ACTIONS: COLORS_16m,
39
+ GITLAB_CI: COLORS_256,
40
+ TRAVIS: COLORS_256,
41
+ }),
42
+ );
43
+
44
+ const TERM_ENVS_REG_EXP = [
45
+ /ansi/,
46
+ /color/,
47
+ /linux/,
48
+ /direct/,
49
+ /^con[0-9]*x[0-9]/,
50
+ /^rxvt/,
51
+ /^screen/,
52
+ /^xterm/,
53
+ /^vt100/,
54
+ /^vt220/,
55
+ ];
56
+
57
+ // The `getColorDepth` API got inspired by multiple sources such as
58
+ // https://github.com/chalk/supports-color,
59
+ // https://github.com/isaacs/color-support.
60
+ export function getColorDepth(): number {
61
+ // Use level 0-3 to support the same levels as `chalk` does. This is done for
62
+ // consistency throughout the ecosystem.
63
+ if (getEnvVar("FORCE_COLOR") !== undefined) {
64
+ switch (getEnvVar("FORCE_COLOR")) {
65
+ case "":
66
+ case "1":
67
+ case "true":
68
+ return COLORS_16;
69
+ case "2":
70
+ return COLORS_256;
71
+ case "3":
72
+ return COLORS_16m;
73
+ default:
74
+ return COLORS_2;
75
+ }
76
+ }
77
+
78
+ if (
79
+ (getEnvVar("NODE_DISABLE_COLORS") !== undefined &&
80
+ getEnvVar("NODE_DISABLE_COLORS") !== "") ||
81
+ // See https://no-color.org/
82
+ (getEnvVar("NO_COLOR") !== undefined && getEnvVar("NO_COLOR") !== "") ||
83
+ // The "dumb" special terminal, as defined by terminfo, doesn't support
84
+ // ANSI color control codes.
85
+ // See https://invisible-island.net/ncurses/terminfo.ti.html#toc-_Specials
86
+ getEnvVar("TERM") === "dumb"
87
+ ) {
88
+ return COLORS_2;
89
+ }
90
+
91
+ if (typeof process !== "undefined" && process.platform === "win32") {
92
+ // Windows 10 build 14931 (from 2016) has true color support
93
+ return COLORS_16m;
94
+ }
95
+
96
+ if (getEnvVar("TMUX")) {
97
+ return COLORS_16m;
98
+ }
99
+
100
+ // Azure DevOps
101
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
102
+ return COLORS_16;
103
+ }
104
+
105
+ if ("CI" in env) {
106
+ for (const { 0: envName, 1: colors } of CI_ENVS_MAP) {
107
+ if (envName in env) {
108
+ return colors;
109
+ }
110
+ }
111
+ if (getEnvVar("CI_NAME") === "codeship") {
112
+ return COLORS_256;
113
+ }
114
+ return COLORS_2;
115
+ }
116
+
117
+ if ("TEAMCITY_VERSION" in env) {
118
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(
119
+ getEnvVar("TEAMCITY_VERSION"),
120
+ ) !== null
121
+ ? COLORS_16
122
+ : COLORS_2;
123
+ }
124
+
125
+ switch (getEnvVar("TERM_PROGRAM")) {
126
+ case "iTerm.app":
127
+ if (
128
+ !getEnvVar("TERM_PROGRAM_VERSION") ||
129
+ /^[0-2]\./.exec(getEnvVar("TERM_PROGRAM_VERSION")) !== null
130
+ ) {
131
+ return COLORS_256;
132
+ }
133
+ return COLORS_16m;
134
+ case "HyperTerm":
135
+ case "MacTerm":
136
+ return COLORS_16m;
137
+ case "Apple_Terminal":
138
+ return COLORS_256;
139
+ }
140
+
141
+ if (
142
+ getEnvVar("COLORTERM") === "truecolor" ||
143
+ getEnvVar("COLORTERM") === "24bit"
144
+ ) {
145
+ return COLORS_16m;
146
+ }
147
+
148
+ if (getEnvVar("TERM")) {
149
+ if (/truecolor/.exec(getEnvVar("TERM")) !== null) {
150
+ return COLORS_16m;
151
+ }
152
+
153
+ if (/^xterm-256/.exec(getEnvVar("TERM")) !== null) {
154
+ return COLORS_256;
155
+ }
156
+
157
+ const termEnv = getEnvVar("TERM").toLowerCase();
158
+
159
+ if (TERM_ENVS[termEnv]) {
160
+ return TERM_ENVS[termEnv];
161
+ }
162
+ if (TERM_ENVS_REG_EXP.some((term) => term.exec(termEnv) !== null)) {
163
+ return COLORS_16;
164
+ }
165
+ }
166
+ // Move 16 color COLORTERM below 16m and 256
167
+ if (getEnvVar("COLORTERM")) {
168
+ return COLORS_16;
169
+ }
170
+ return COLORS_2;
171
+ }
@@ -0,0 +1,123 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="bun" />
3
+ //https://github.com/unjs/std-env/blob/main/src/env.ts
4
+
5
+ const _envShim = Object.create(null);
6
+
7
+ export type EnvObject = Record<string, string | undefined>;
8
+
9
+ const _getEnv = (useShim?: boolean) =>
10
+ globalThis.process?.env ||
11
+ //@ts-expect-error
12
+ globalThis.Deno?.env.toObject() ||
13
+ //@ts-expect-error
14
+ globalThis.__env__ ||
15
+ (useShim ? _envShim : globalThis);
16
+
17
+ export const env = new Proxy<EnvObject>(_envShim, {
18
+ get(_, prop) {
19
+ const env = _getEnv();
20
+ return env[prop as any] ?? _envShim[prop];
21
+ },
22
+ has(_, prop) {
23
+ const env = _getEnv();
24
+ return prop in env || prop in _envShim;
25
+ },
26
+ set(_, prop, value) {
27
+ const env = _getEnv(true);
28
+ env[prop as any] = value;
29
+ return true;
30
+ },
31
+ deleteProperty(_, prop) {
32
+ if (!prop) {
33
+ return false;
34
+ }
35
+ const env = _getEnv(true);
36
+ delete env[prop as any];
37
+ return true;
38
+ },
39
+ ownKeys() {
40
+ const env = _getEnv(true);
41
+ return Object.keys(env);
42
+ },
43
+ });
44
+
45
+ function toBoolean(val: boolean | string | undefined) {
46
+ return val ? val !== "false" : false;
47
+ }
48
+
49
+ export const nodeENV =
50
+ (typeof process !== "undefined" && process.env && process.env.NODE_ENV) || "";
51
+
52
+ /** Detect if `NODE_ENV` environment variable is `production` */
53
+ export const isProduction = nodeENV === "production";
54
+
55
+ /** Detect if `NODE_ENV` environment variable is `dev` or `development` */
56
+ export const isDevelopment = nodeENV === "dev" || nodeENV === "development";
57
+
58
+ /** Detect if `NODE_ENV` environment variable is `test` */
59
+ export const isTest = () => nodeENV === "test" || toBoolean(env.TEST);
60
+
61
+ /**
62
+ * Get environment variable with fallback
63
+ */
64
+ export function getEnvVar<Fallback extends string>(
65
+ key: string,
66
+ fallback?: Fallback,
67
+ ): Fallback extends string ? string : string | undefined {
68
+ if (typeof process !== "undefined" && process.env) {
69
+ return process.env[key] ?? (fallback as any);
70
+ }
71
+
72
+ // @ts-expect-error deno
73
+ if (typeof Deno !== "undefined") {
74
+ // @ts-expect-error deno
75
+ return Deno.env.get(key) ?? (fallback as string);
76
+ }
77
+
78
+ // Handle Bun
79
+ if (typeof Bun !== "undefined") {
80
+ return Bun.env[key] ?? (fallback as string);
81
+ }
82
+
83
+ return fallback as any;
84
+ }
85
+
86
+ /**
87
+ * Get boolean environment variable
88
+ */
89
+ export function getBooleanEnvVar(key: string, fallback = true): boolean {
90
+ const value = getEnvVar(key);
91
+ if (!value) return fallback;
92
+ return value !== "0" && value.toLowerCase() !== "false" && value !== "";
93
+ }
94
+
95
+ /**
96
+ * Common environment variables used in Better Auth
97
+ */
98
+ export const ENV = Object.freeze({
99
+ get BETTER_AUTH_SECRET() {
100
+ return getEnvVar("BETTER_AUTH_SECRET");
101
+ },
102
+ get AUTH_SECRET() {
103
+ return getEnvVar("AUTH_SECRET");
104
+ },
105
+ get BETTER_AUTH_TELEMETRY() {
106
+ return getEnvVar("BETTER_AUTH_TELEMETRY");
107
+ },
108
+ get BETTER_AUTH_TELEMETRY_ID() {
109
+ return getEnvVar("BETTER_AUTH_TELEMETRY_ID");
110
+ },
111
+ get NODE_ENV() {
112
+ return getEnvVar("NODE_ENV", "development");
113
+ },
114
+ get PACKAGE_VERSION() {
115
+ return getEnvVar("PACKAGE_VERSION", "0.0.0");
116
+ },
117
+ get BETTER_AUTH_TELEMETRY_ENDPOINT() {
118
+ return getEnvVar(
119
+ "BETTER_AUTH_TELEMETRY_ENDPOINT",
120
+ "https://telemetry.better-auth.com/v1/track",
121
+ );
122
+ },
123
+ });
@@ -0,0 +1,23 @@
1
+ export {
2
+ ENV,
3
+ getEnvVar,
4
+ env,
5
+ nodeENV,
6
+ isTest,
7
+ getBooleanEnvVar,
8
+ isDevelopment,
9
+ type EnvObject,
10
+ isProduction,
11
+ } from "./env-impl";
12
+ export { getColorDepth } from "./color-depth";
13
+ export {
14
+ logger,
15
+ createLogger,
16
+ levels,
17
+ type Logger,
18
+ type LogLevel,
19
+ type LogHandlerParams,
20
+ type InternalLogger,
21
+ shouldPublishLog,
22
+ TTY_COLORS,
23
+ } from "./logger";
@@ -0,0 +1,33 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { shouldPublishLog, type LogLevel } from "./logger";
3
+
4
+ describe("shouldPublishLog", () => {
5
+ const testCases: {
6
+ currentLogLevel: LogLevel;
7
+ logLevel: LogLevel;
8
+ expected: boolean;
9
+ }[] = [
10
+ { currentLogLevel: "info", logLevel: "info", expected: true },
11
+ { currentLogLevel: "info", logLevel: "warn", expected: false },
12
+ { currentLogLevel: "info", logLevel: "error", expected: false },
13
+ { currentLogLevel: "info", logLevel: "debug", expected: false },
14
+ { currentLogLevel: "warn", logLevel: "info", expected: true },
15
+ { currentLogLevel: "warn", logLevel: "warn", expected: true },
16
+ { currentLogLevel: "warn", logLevel: "error", expected: false },
17
+ { currentLogLevel: "warn", logLevel: "debug", expected: false },
18
+ { currentLogLevel: "error", logLevel: "info", expected: true },
19
+ { currentLogLevel: "error", logLevel: "warn", expected: true },
20
+ { currentLogLevel: "error", logLevel: "error", expected: true },
21
+ { currentLogLevel: "error", logLevel: "debug", expected: false },
22
+ { currentLogLevel: "debug", logLevel: "info", expected: true },
23
+ { currentLogLevel: "debug", logLevel: "warn", expected: true },
24
+ { currentLogLevel: "debug", logLevel: "error", expected: true },
25
+ { currentLogLevel: "debug", logLevel: "debug", expected: true },
26
+ ];
27
+
28
+ testCases.forEach(({ currentLogLevel, logLevel, expected }) => {
29
+ it(`should return "${expected}" when currentLogLevel is "${currentLogLevel}" and logLevel is "${logLevel}"`, () => {
30
+ expect(shouldPublishLog(currentLogLevel, logLevel)).toBe(expected);
31
+ });
32
+ });
33
+ });
@@ -0,0 +1,145 @@
1
+ import { getColorDepth } from "./color-depth";
2
+
3
+ export const TTY_COLORS = {
4
+ reset: "\x1b[0m",
5
+ bright: "\x1b[1m",
6
+ dim: "\x1b[2m",
7
+ undim: "\x1b[22m",
8
+ underscore: "\x1b[4m",
9
+ blink: "\x1b[5m",
10
+ reverse: "\x1b[7m",
11
+ hidden: "\x1b[8m",
12
+ fg: {
13
+ black: "\x1b[30m",
14
+ red: "\x1b[31m",
15
+ green: "\x1b[32m",
16
+ yellow: "\x1b[33m",
17
+ blue: "\x1b[34m",
18
+ magenta: "\x1b[35m",
19
+ cyan: "\x1b[36m",
20
+ white: "\x1b[37m",
21
+ },
22
+ bg: {
23
+ black: "\x1b[40m",
24
+ red: "\x1b[41m",
25
+ green: "\x1b[42m",
26
+ yellow: "\x1b[43m",
27
+ blue: "\x1b[44m",
28
+ magenta: "\x1b[45m",
29
+ cyan: "\x1b[46m",
30
+ white: "\x1b[47m",
31
+ },
32
+ } as const;
33
+
34
+ export type LogLevel = "info" | "success" | "warn" | "error" | "debug";
35
+
36
+ export const levels = ["info", "success", "warn", "error", "debug"] as const;
37
+
38
+ export function shouldPublishLog(
39
+ currentLogLevel: LogLevel,
40
+ logLevel: LogLevel,
41
+ ): boolean {
42
+ return levels.indexOf(logLevel) <= levels.indexOf(currentLogLevel);
43
+ }
44
+
45
+ export interface Logger {
46
+ disabled?: boolean;
47
+ disableColors?: boolean;
48
+ level?: Exclude<LogLevel, "success">;
49
+ log?: (
50
+ level: Exclude<LogLevel, "success">,
51
+ message: string,
52
+ ...args: any[]
53
+ ) => void;
54
+ }
55
+
56
+ export type LogHandlerParams = Parameters<NonNullable<Logger["log"]>> extends [
57
+ LogLevel,
58
+ ...infer Rest,
59
+ ]
60
+ ? Rest
61
+ : never;
62
+
63
+ const levelColors: Record<LogLevel, string> = {
64
+ info: TTY_COLORS.fg.blue,
65
+ success: TTY_COLORS.fg.green,
66
+ warn: TTY_COLORS.fg.yellow,
67
+ error: TTY_COLORS.fg.red,
68
+ debug: TTY_COLORS.fg.magenta,
69
+ };
70
+
71
+ const formatMessage = (
72
+ level: LogLevel,
73
+ message: string,
74
+ colorsEnabled: boolean,
75
+ ): string => {
76
+ const timestamp = new Date().toISOString();
77
+
78
+ if (colorsEnabled) {
79
+ return `${TTY_COLORS.dim}${timestamp}${TTY_COLORS.reset} ${
80
+ levelColors[level]
81
+ }${level.toUpperCase()}${TTY_COLORS.reset} ${TTY_COLORS.bright}[Better Auth]:${
82
+ TTY_COLORS.reset
83
+ } ${message}`;
84
+ }
85
+
86
+ return `${timestamp} ${level.toUpperCase()} [Better Auth]: ${message}`;
87
+ };
88
+
89
+ export type InternalLogger = {
90
+ [K in LogLevel]: (...params: LogHandlerParams) => void;
91
+ } & {
92
+ get level(): LogLevel;
93
+ };
94
+
95
+ export const createLogger = (options?: Logger): InternalLogger => {
96
+ const enabled = options?.disabled !== true;
97
+ const logLevel = options?.level ?? "error";
98
+
99
+ const isDisableColorsSpecified = options?.disableColors !== undefined;
100
+ const colorsEnabled = isDisableColorsSpecified
101
+ ? !options.disableColors
102
+ : getColorDepth() !== 1;
103
+
104
+ const LogFunc = (
105
+ level: LogLevel,
106
+ message: string,
107
+ args: any[] = [],
108
+ ): void => {
109
+ if (!enabled || !shouldPublishLog(logLevel, level)) {
110
+ return;
111
+ }
112
+
113
+ const formattedMessage = formatMessage(level, message, colorsEnabled);
114
+
115
+ if (!options || typeof options.log !== "function") {
116
+ if (level === "error") {
117
+ console.error(formattedMessage, ...args);
118
+ } else if (level === "warn") {
119
+ console.warn(formattedMessage, ...args);
120
+ } else {
121
+ console.log(formattedMessage, ...args);
122
+ }
123
+ return;
124
+ }
125
+
126
+ options.log(level === "success" ? "info" : level, message, ...args);
127
+ };
128
+
129
+ const logger = Object.fromEntries(
130
+ levels.map((level) => [
131
+ level,
132
+ (...[message, ...args]: LogHandlerParams) =>
133
+ LogFunc(level, message, args),
134
+ ]),
135
+ ) as Record<LogLevel, (...params: LogHandlerParams) => void>;
136
+
137
+ return {
138
+ ...logger,
139
+ get level() {
140
+ return logLevel;
141
+ },
142
+ };
143
+ };
144
+
145
+ export const logger = createLogger();
@@ -0,0 +1,102 @@
1
+ import { betterFetch } from "@better-fetch/fetch";
2
+ import { base64Url } from "@better-auth/utils/base64";
3
+ import type { OAuth2Tokens, ProviderOptions } from "./oauth-provider";
4
+
5
+ export function createClientCredentialsTokenRequest({
6
+ options,
7
+ scope,
8
+ authentication,
9
+ resource,
10
+ }: {
11
+ options: ProviderOptions & { clientSecret: string };
12
+ scope?: string;
13
+ authentication?: "basic" | "post";
14
+ resource?: string | string[];
15
+ }) {
16
+ const body = new URLSearchParams();
17
+ const headers: Record<string, any> = {
18
+ "content-type": "application/x-www-form-urlencoded",
19
+ accept: "application/json",
20
+ };
21
+
22
+ body.set("grant_type", "client_credentials");
23
+ scope && body.set("scope", scope);
24
+ if (resource) {
25
+ if (typeof resource === "string") {
26
+ body.append("resource", resource);
27
+ } else {
28
+ for (const _resource of resource) {
29
+ body.append("resource", _resource);
30
+ }
31
+ }
32
+ }
33
+ if (authentication === "basic") {
34
+ const primaryClientId = Array.isArray(options.clientId)
35
+ ? options.clientId[0]
36
+ : options.clientId;
37
+ const encodedCredentials = base64Url.encode(
38
+ `${primaryClientId}:${options.clientSecret}`,
39
+ );
40
+ headers["authorization"] = `Basic ${encodedCredentials}`;
41
+ } else {
42
+ const primaryClientId = Array.isArray(options.clientId)
43
+ ? options.clientId[0]
44
+ : options.clientId;
45
+ body.set("client_id", primaryClientId);
46
+ body.set("client_secret", options.clientSecret);
47
+ }
48
+
49
+ return {
50
+ body,
51
+ headers,
52
+ };
53
+ }
54
+
55
+ export async function clientCredentialsToken({
56
+ options,
57
+ tokenEndpoint,
58
+ scope,
59
+ authentication,
60
+ resource,
61
+ }: {
62
+ options: ProviderOptions & { clientSecret: string };
63
+ tokenEndpoint: string;
64
+ scope: string;
65
+ authentication?: "basic" | "post";
66
+ resource?: string | string[];
67
+ }): Promise<OAuth2Tokens> {
68
+ const { body, headers } = createClientCredentialsTokenRequest({
69
+ options,
70
+ scope,
71
+ authentication,
72
+ resource,
73
+ });
74
+
75
+ const { data, error } = await betterFetch<{
76
+ access_token: string;
77
+ expires_in?: number;
78
+ token_type?: string;
79
+ scope?: string;
80
+ }>(tokenEndpoint, {
81
+ method: "POST",
82
+ body,
83
+ headers,
84
+ });
85
+ if (error) {
86
+ throw error;
87
+ }
88
+ const tokens: OAuth2Tokens = {
89
+ accessToken: data.access_token,
90
+ tokenType: data.token_type,
91
+ scopes: data.scope?.split(" "),
92
+ };
93
+
94
+ if (data.expires_in) {
95
+ const now = new Date();
96
+ tokens.accessTokenExpiresAt = new Date(
97
+ now.getTime() + data.expires_in * 1000,
98
+ );
99
+ }
100
+
101
+ return tokens;
102
+ }
@@ -0,0 +1,85 @@
1
+ import type { ProviderOptions } from "./index";
2
+ import { generateCodeChallenge } from "./utils";
3
+
4
+ export async function createAuthorizationURL({
5
+ id,
6
+ options,
7
+ authorizationEndpoint,
8
+ state,
9
+ codeVerifier,
10
+ scopes,
11
+ claims,
12
+ redirectURI,
13
+ duration,
14
+ prompt,
15
+ accessType,
16
+ responseType,
17
+ display,
18
+ loginHint,
19
+ hd,
20
+ responseMode,
21
+ additionalParams,
22
+ scopeJoiner,
23
+ }: {
24
+ id: string;
25
+ options: ProviderOptions;
26
+ redirectURI: string;
27
+ authorizationEndpoint: string;
28
+ state: string;
29
+ codeVerifier?: string;
30
+ scopes: string[];
31
+ claims?: string[];
32
+ duration?: string;
33
+ prompt?: string;
34
+ accessType?: string;
35
+ responseType?: string;
36
+ display?: string;
37
+ loginHint?: string;
38
+ hd?: string;
39
+ responseMode?: string;
40
+ additionalParams?: Record<string, string>;
41
+ scopeJoiner?: string;
42
+ }) {
43
+ const url = new URL(authorizationEndpoint);
44
+ url.searchParams.set("response_type", responseType || "code");
45
+ const primaryClientId = Array.isArray(options.clientId)
46
+ ? options.clientId[0]
47
+ : options.clientId;
48
+ url.searchParams.set("client_id", primaryClientId);
49
+ url.searchParams.set("state", state);
50
+ url.searchParams.set("scope", scopes.join(scopeJoiner || " "));
51
+ url.searchParams.set("redirect_uri", options.redirectURI || redirectURI);
52
+ duration && url.searchParams.set("duration", duration);
53
+ display && url.searchParams.set("display", display);
54
+ loginHint && url.searchParams.set("login_hint", loginHint);
55
+ prompt && url.searchParams.set("prompt", prompt);
56
+ hd && url.searchParams.set("hd", hd);
57
+ accessType && url.searchParams.set("access_type", accessType);
58
+ responseMode && url.searchParams.set("response_mode", responseMode);
59
+ if (codeVerifier) {
60
+ const codeChallenge = await generateCodeChallenge(codeVerifier);
61
+ url.searchParams.set("code_challenge_method", "S256");
62
+ url.searchParams.set("code_challenge", codeChallenge);
63
+ }
64
+ if (claims) {
65
+ const claimsObj = claims.reduce(
66
+ (acc, claim) => {
67
+ acc[claim] = null;
68
+ return acc;
69
+ },
70
+ {} as Record<string, null>,
71
+ );
72
+ url.searchParams.set(
73
+ "claims",
74
+ JSON.stringify({
75
+ id_token: { email: null, email_verified: null, ...claimsObj },
76
+ }),
77
+ );
78
+ }
79
+ if (additionalParams) {
80
+ Object.entries(additionalParams).forEach(([key, value]) => {
81
+ url.searchParams.set(key, value);
82
+ });
83
+ }
84
+ return url;
85
+ }
@@ -0,0 +1,22 @@
1
+ export type {
2
+ OAuth2Tokens,
3
+ OAuthProvider,
4
+ OAuth2UserInfo,
5
+ ProviderOptions,
6
+ } from "./oauth-provider";
7
+
8
+ export { generateCodeChallenge, getOAuth2Tokens } from "./utils";
9
+ export { createAuthorizationURL } from "./create-authorization-url";
10
+ export {
11
+ createAuthorizationCodeRequest,
12
+ validateAuthorizationCode,
13
+ validateToken,
14
+ } from "./validate-authorization-code";
15
+ export {
16
+ createRefreshAccessTokenRequest,
17
+ refreshAccessToken,
18
+ } from "./refresh-access-token";
19
+ export {
20
+ clientCredentialsToken,
21
+ createClientCredentialsTokenRequest,
22
+ } from "./client-credentials-token";